Files
mtusi2026lab5-fork/handlers.go
T

1093 lines
29 KiB
Go

package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
var instanceID = func() string {
h, err := os.Hostname()
if err != nil || h == "" {
return newUUID()
}
return h
}()
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type apiError struct {
Code string `json:"code"`
Message string `json:"message"`
ReqID string `json:"request_id"`
}
type errorBody struct {
Error apiError `json:"error"`
}
type App struct {
db *pgxpool.Pool
cache *Cache
log *slog.Logger
ready atomic.Bool
sessionTTL time.Duration
idempotencyTTL time.Duration
store *Store
limits limits
uploads chan struct{}
fault string
}
func NewApp(db *pgxpool.Pool, cache *Cache, log *slog.Logger, sessionTTL, idempotencyTTL time.Duration, store *Store, lim limits) *App {
a := &App{db: db, cache: cache, log: log, sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, store: store, limits: lim, uploads: make(chan struct{}, lim.uploadSlots), fault: os.Getenv("FAULT_POINT")}
a.ready.Store(true)
return a
}
func (a *App) SetReady(v bool) {
a.ready.Store(v)
}
func newUUID() string {
var b [16]byte
_, _ = rand.Read(b[:])
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
func nowUTC() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
}
func formatTime(t time.Time) string {
return t.UTC().Format("2006-01-02T15:04:05.000000Z")
}
func parseTime(s string) (time.Time, error) {
return time.Parse("2006-01-02T15:04:05.000000Z", s)
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
type ctxKey int
const reqIDKey ctxKey = 1
func (a *App) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
reqID := newUUID()
w.Header().Set("X-Request-Id", reqID)
w.Header().Set("X-Instance-Id", instanceID)
sw := &statusWriter{ResponseWriter: w, status: 200}
defer func() {
if rec := recover(); rec != nil {
a.writeErr(sw, reqID, 500, "internal_error", "internal error")
a.log.Error("panic", "request_id", reqID, "err", fmt.Sprint(rec))
}
a.log.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration_ms", time.Since(start).Milliseconds(),
"request_id", reqID,
)
}()
next.ServeHTTP(sw, r.WithContext(context.WithValue(r.Context(), reqIDKey, reqID)))
})
}
func reqIDFrom(r *http.Request) string {
if v, ok := r.Context().Value(reqIDKey).(string); ok {
return v
}
return ""
}
func (a *App) writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(v)
}
func (a *App) writeErr(w http.ResponseWriter, reqID string, status int, code, msg string) {
a.writeJSON(w, status, errorBody{Error: apiError{Code: code, Message: msg, ReqID: reqID}})
}
func (a *App) writeUnauthorized(w http.ResponseWriter, r *http.Request, realm string) {
reqID := reqIDFrom(r)
if realm == "Basic" {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
} else {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
}
a.writeErr(w, reqID, 401, "unauthorized", "unauthorized")
}
func (a *App) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", a.handleLive)
mux.HandleFunc("GET /health/ready", a.handleReady)
mux.HandleFunc("POST /api/v1/users", a.handleCreateUser)
mux.HandleFunc("GET /api/v1/users/me", a.handleMe)
mux.HandleFunc("POST /api/v1/chats", a.handleCreateChat)
mux.HandleFunc("GET /api/v1/chats", a.handleListChats)
mux.HandleFunc("GET /api/v1/chats/{chat_id}", a.handleGetChat)
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.handleCreateMessage)
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.handleListMessages)
mux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", a.handleUploadAttachment)
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}", a.handleGetAttachment)
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", a.handleDownloadAttachment)
mux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.handleRevokeSession)
return a.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, pattern := mux.Handler(r)
if pattern == "" {
a.writeErr(w, reqIDFrom(r), 404, "not_found", "not found")
return
}
mux.ServeHTTP(w, r)
}))
}
func (a *App) handleLive(w http.ResponseWriter, r *http.Request) {
a.writeJSON(w, 200, map[string]string{"status": "ok"})
}
func (a *App) handleReady(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
if !a.ready.Load() {
a.writeErr(w, reqID, 503, "unavailable", "shutting down")
return
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
if err := a.db.Ping(ctx); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.writeJSON(w, 200, map[string]string{"status": "ok"})
}
func (a *App) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
reqID := reqIDFrom(r)
ct := r.Header.Get("Content-Type")
media := strings.ToLower(strings.TrimSpace(strings.Split(ct, ";")[0]))
if media != "application/json" {
a.writeErr(w, reqID, 415, "unsupported_media_type", "Content-Type must be application/json")
return false
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
if _, ok := err.(*http.MaxBytesError); ok {
a.writeErr(w, reqID, 413, "payload_too_large", "body too large")
return false
}
a.writeErr(w, reqID, 400, "invalid_request", "invalid json")
return false
}
var extra json.RawMessage
if err := dec.Decode(&extra); err != io.EOF {
a.writeErr(w, reqID, 400, "invalid_request", "invalid json")
return false
}
return true
}
func isBlank(s string) bool {
return strings.TrimSpace(s) == ""
}
func isUUID(s string) bool {
if len(s) != 36 {
return false
}
for i, c := range s {
switch i {
case 8, 13, 18, 23:
if c != '-' {
return false
}
default:
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
return false
}
}
}
raw := strings.ReplaceAll(s, "-", "")
_, err := hex.DecodeString(raw)
return err == nil
}
func isPgCode(err error, code string) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == code
}
func userJSON(u *User) map[string]any {
return map[string]any{
"id": u.ID,
"username": u.Username,
"display_name": u.DisplayName,
"created_at": formatTime(u.CreatedAt),
}
}
func (a *App) getUserByID(ctx context.Context, id string) (*User, error) {
ctx, cancel := dbCtx(ctx)
defer cancel()
var u User
err := a.db.QueryRow(ctx, `
select id::text, username, display_name, password_hash, created_at
from users where id = $1::uuid`, id).Scan(
&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &u, nil
}
func (a *App) authUser(w http.ResponseWriter, r *http.Request) (*User, string) {
token, ok := parseBearer(r.Header.Get("Authorization"))
if !ok {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
}
hash, hashHex := tokenHash(token)
if cs, hit := a.cache.GetSession(r.Context(), hashHex); hit {
u, err := a.getUserByID(r.Context(), cs.UserID)
if err != nil {
a.writeErr(w, reqIDFrom(r), 503, "unavailable", "database unavailable")
return nil, ""
}
if u == nil {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
}
return u, hashHex
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
var userID string
var expiresAt time.Time
err := a.db.QueryRow(ctx, `
select user_id::text, expires_at from sessions
where token_hash = $1 and expires_at > now()`, hash).Scan(&userID, &expiresAt)
if errors.Is(err, pgx.ErrNoRows) {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
}
if err != nil {
a.writeErr(w, reqIDFrom(r), 503, "unavailable", "database unavailable")
return nil, ""
}
u, err := a.getUserByID(r.Context(), userID)
if err != nil {
a.writeErr(w, reqIDFrom(r), 503, "unavailable", "database unavailable")
return nil, ""
}
if u == nil {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
}
a.cache.SetSession(r.Context(), hashHex, userID, expiresAt)
return u, hashHex
}
func (a *App) handleCreateUser(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
var body struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
if !a.readJSON(w, r, &body) {
return
}
if body.Username == nil || body.DisplayName == nil || body.Password == nil {
a.writeErr(w, reqID, 400, "invalid_request", "username, display_name and password required")
return
}
username := *body.Username
display := *body.DisplayName
password := *body.Password
if !usernameRe.MatchString(username) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid username")
return
}
n := utf8.RuneCountInString(display)
if n < 1 || n > 100 || isBlank(display) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid display_name")
return
}
if !validPassword(password) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid password")
return
}
ph, err := hashPassword(password)
if err != nil {
a.writeErr(w, reqID, 500, "internal_error", "internal error")
return
}
id := newUUID()
createdAt := nowUTC()
ctx, cancel := dbCtx(r.Context())
defer cancel()
_, err = a.db.Exec(ctx, `
insert into users(id, username, display_name, password_hash, created_at)
values($1::uuid, $2, $3, $4, $5)`, id, username, display, ph, createdAt)
if isPgCode(err, "23505") {
a.writeErr(w, reqID, 409, "conflict", "username taken")
return
}
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.writeJSON(w, 201, map[string]any{
"id": id,
"username": username,
"display_name": display,
"created_at": formatTime(createdAt),
})
}
func (a *App) handleCreateSession(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
username, password, ok := parseBasic(r.Header.Get("Authorization"))
if !ok {
a.writeUnauthorized(w, r, "Basic")
return
}
if !usernameRe.MatchString(username) || !validPassword(password) {
a.writeUnauthorized(w, r, "Basic")
return
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
var u User
err := a.db.QueryRow(ctx, `
select id::text, username, display_name, password_hash, created_at
from users where username = $1`, username).Scan(
&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
a.writeUnauthorized(w, r, "Basic")
return
}
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
match, err := checkPassword(u.PasswordHash, password)
if err != nil || !match {
a.writeUnauthorized(w, r, "Basic")
return
}
token, hash, hashHex, err := newToken()
if err != nil {
a.writeErr(w, reqID, 500, "internal_error", "internal error")
return
}
createdAt := nowUTC()
expiresAt := createdAt.Add(a.sessionTTL)
_, err = a.db.Exec(ctx, `
insert into sessions(token_hash, user_id, created_at, expires_at)
values($1, $2::uuid, $3, $4)`, hash, u.ID, createdAt, expiresAt)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.cache.SetSession(r.Context(), hashHex, u.ID, expiresAt)
a.writeJSON(w, 201, map[string]any{
"token": token,
"token_type": "Bearer",
"expires_at": formatTime(expiresAt),
"user": userJSON(&u),
})
}
func (a *App) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
token, ok := parseBearer(r.Header.Get("Authorization"))
if !ok {
a.writeUnauthorized(w, r, "Bearer")
return
}
hash, hashHex := tokenHash(token)
ctx, cancel := dbCtx(r.Context())
defer cancel()
tag, err := a.db.Exec(ctx, `
delete from sessions where token_hash = $1 and expires_at > now()`, hash)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.cache.DelSession(r.Context(), hashHex)
if tag.RowsAffected() == 0 {
a.writeUnauthorized(w, r, "Bearer")
return
}
w.Header().Set("X-Request-Id", reqID)
w.WriteHeader(204)
}
func (a *App) handleMe(w http.ResponseWriter, r *http.Request) {
u, _ := a.authUser(w, r)
if u == nil {
return
}
a.writeJSON(w, 200, userJSON(u))
}
func (a *App) handleCreateChat(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
u, _ := a.authUser(w, r)
if u == nil {
return
}
var body struct {
Title *string `json:"title"`
MemberIDs *[]string `json:"member_ids"`
}
if !a.readJSON(w, r, &body) {
return
}
if body.Title == nil || body.MemberIDs == nil {
a.writeErr(w, reqID, 400, "invalid_request", "title and member_ids required")
return
}
title := *body.Title
n := utf8.RuneCountInString(title)
if n < 1 || n > 100 || isBlank(title) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid title")
return
}
members := *body.MemberIDs
if len(members) < 1 || len(members) > 100 {
a.writeErr(w, reqID, 400, "invalid_request", "invalid member_ids")
return
}
seen := make(map[string]struct{}, len(members))
hasCaller := false
for _, id := range members {
if !isUUID(id) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid member id")
return
}
if _, dup := seen[id]; dup {
a.writeErr(w, reqID, 400, "invalid_request", "duplicate member")
return
}
seen[id] = struct{}{}
if id == u.ID {
hasCaller = true
}
}
if !hasCaller {
a.writeErr(w, reqID, 400, "invalid_request", "caller must be member")
return
}
chatID := newUUID()
createdAt := nowUTC()
ctx, cancel := dbCtx(r.Context())
defer cancel()
tx, err := a.db.Begin(ctx)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, `insert into chats(id, title, created_at) values($1::uuid, $2, $3)`,
chatID, title, createdAt)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
for _, mid := range members {
_, err = tx.Exec(ctx, `insert into chat_members(chat_id, user_id) values($1::uuid, $2::uuid)`,
chatID, mid)
if isPgCode(err, "23503") {
a.writeErr(w, reqID, 400, "invalid_request", "unknown member")
return
}
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
}
if err := tx.Commit(ctx); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.writeJSON(w, 201, map[string]any{
"id": chatID,
"title": title,
"member_ids": members,
"created_at": formatTime(createdAt),
})
}
func encodeCursor(parts ...string) string {
return base64.RawURLEncoding.EncodeToString([]byte(strings.Join(parts, "|")))
}
func decodeCursor(s string) ([]string, error) {
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return nil, err
}
return strings.Split(string(b), "|"), nil
}
func parseLimit(r *http.Request) (int, error) {
q := r.URL.Query().Get("limit")
if q == "" {
return 50, nil
}
n, err := strconv.Atoi(q)
if err != nil || n < 1 || n > 100 {
return 0, fmt.Errorf("bad limit")
}
return n, nil
}
func (a *App) loadChatMembers(ctx context.Context, chatID string) ([]string, error) {
ctx, cancel := dbCtx(ctx)
defer cancel()
rows, err := a.db.Query(ctx, `
select user_id::text from chat_members where chat_id = $1::uuid order by user_id`, chatID)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (a *App) isMember(ctx context.Context, chatID, userID string) (bool, error) {
ctx, cancel := dbCtx(ctx)
defer cancel()
var ok bool
err := a.db.QueryRow(ctx, `
select exists(
select 1 from chat_members where chat_id = $1::uuid and user_id = $2::uuid
)`, chatID, userID).Scan(&ok)
return ok, err
}
func (a *App) handleListChats(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
u, _ := a.authUser(w, r)
if u == nil {
return
}
limit, err := parseLimit(r)
if err != nil {
a.writeErr(w, reqID, 400, "invalid_request", "invalid limit")
return
}
var afterTS *time.Time
var afterID string
if cur := r.URL.Query().Get("cursor"); cur != "" {
parts, err := decodeCursor(cur)
if err != nil || len(parts) != 3 {
a.writeErr(w, reqID, 400, "invalid_request", "invalid cursor")
return
}
if parts[0] != u.ID {
a.writeErr(w, reqID, 400, "invalid_request", "invalid cursor")
return
}
ts, err := parseTime(parts[1])
if err != nil || !isUUID(parts[2]) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid cursor")
return
}
afterTS = &ts
afterID = parts[2]
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
var rows pgx.Rows
if afterTS == nil {
rows, err = a.db.Query(ctx, `
select c.id::text, c.title, c.created_at
from chats c
join chat_members m on m.chat_id = c.id
where m.user_id = $1::uuid
order by c.created_at, c.id
limit $2`, u.ID, limit+1)
} else {
rows, err = a.db.Query(ctx, `
select c.id::text, c.title, c.created_at
from chats c
join chat_members m on m.chat_id = c.id
where m.user_id = $1::uuid
and (c.created_at, c.id) > ($2, $3::uuid)
order by c.created_at, c.id
limit $4`, u.ID, *afterTS, afterID, limit+1)
}
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
defer rows.Close()
type row struct {
id, title string
created time.Time
}
var list []row
for rows.Next() {
var x row
if err := rows.Scan(&x.id, &x.title, &x.created); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
list = append(list, x)
}
if err := rows.Err(); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
hasMore := len(list) > limit
if hasMore {
list = list[:limit]
}
out := make([]map[string]any, 0, len(list))
for _, c := range list {
members, err := a.loadChatMembers(r.Context(), c.id)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
out = append(out, map[string]any{
"id": c.id,
"title": c.title,
"member_ids": members,
"created_at": formatTime(c.created),
})
}
var next any = nil
if hasMore && len(list) > 0 {
last := list[len(list)-1]
next = encodeCursor(u.ID, formatTime(last.created), last.id)
}
a.writeJSON(w, 200, map[string]any{"items": out, "next_cursor": next})
}
func (a *App) handleGetChat(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
u, _ := a.authUser(w, r)
if u == nil {
return
}
chatID := r.PathValue("chat_id")
if !isUUID(chatID) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid chat_id")
return
}
ok, err := a.isMember(r.Context(), chatID, u.ID)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if !ok {
a.writeErr(w, reqID, 404, "not_found", "chat not found")
return
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
var title string
var createdAt time.Time
err = a.db.QueryRow(ctx, `select title, created_at from chats where id = $1::uuid`, chatID).
Scan(&title, &createdAt)
if errors.Is(err, pgx.ErrNoRows) {
a.writeErr(w, reqID, 404, "not_found", "chat not found")
return
}
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
members, err := a.loadChatMembers(r.Context(), chatID)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.writeJSON(w, 200, map[string]any{
"id": chatID,
"title": title,
"member_ids": members,
"created_at": formatTime(createdAt),
})
}
func (a *App) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
u, _ := a.authUser(w, r)
if u == nil {
return
}
chatID := r.PathValue("chat_id")
if !isUUID(chatID) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid chat_id")
return
}
key := r.Header.Get("Idempotency-Key")
if !idempotencyKeyRe.MatchString(key) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid Idempotency-Key")
return
}
ok, err := a.isMember(r.Context(), chatID, u.ID)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if !ok {
a.writeErr(w, reqID, 404, "not_found", "chat not found")
return
}
var body struct {
Text *string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
if !a.readJSON(w, r, &body) {
return
}
if body.Text == nil {
a.writeErr(w, reqID, 400, "invalid_request", "text required")
return
}
text := *body.Text
attachmentIDs := body.AttachmentIDs
if attachmentIDs == nil {
attachmentIDs = []string{}
}
if len(attachmentIDs) > 10 {
a.writeErr(w, reqID, 400, "invalid_request", "too many attachments")
return
}
seen := make(map[string]bool, len(attachmentIDs))
for _, id := range attachmentIDs {
if !isUUID(id) || seen[id] {
a.writeErr(w, reqID, 400, "invalid_request", "invalid attachment_ids")
return
}
seen[id] = true
}
n := utf8.RuneCountInString(text)
if n > 4000 || (len(attachmentIDs) == 0 && (n < 1 || isBlank(text))) || (n > 0 && isBlank(text)) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid text")
return
}
if len(attachmentIDs) > 0 {
var found, failed int
cctx, ccancel := dbCtx(r.Context())
err := a.db.QueryRow(cctx, `
select count(*), count(*) filter (where status = 'failed')
from attachments where id = any($1::uuid[]) and chat_id = $2::uuid`, attachmentIDs, chatID).Scan(&found, &failed)
ccancel()
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if found != len(attachmentIDs) {
a.writeErr(w, reqID, 404, "not_found", "attachment not found")
return
}
if failed > 0 {
a.writeErr(w, reqID, 409, "conflict", "attachment processing failed")
return
}
}
hashInput := text
if len(attachmentIDs) > 0 {
hashInput += "\x00" + strings.Join(attachmentIDs, ",")
}
sum := sha256.Sum256([]byte(hashInput))
bodyHash := hex.EncodeToString(sum[:])
path := r.URL.Path
ctx, cancel := dbCtx(r.Context())
defer cancel()
tx, err := a.db.Begin(ctx)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `
delete from idempotency_keys
where user_id=$1::uuid and method='POST' and path=$2 and key=$3
and created_at < $4`,
u.ID, path, key, time.Now().Add(-a.idempotencyTTL)); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
msgID := newUUID()
createdAt := nowUTC()
resp := map[string]any{
"id": msgID,
"chat_id": chatID,
"sender_id": u.ID,
"text": text,
"created_at": formatTime(createdAt),
"attachment_ids": attachmentIDs,
}
respJSON, _ := json.Marshal(resp)
tag, err := tx.Exec(ctx, `
insert into idempotency_keys(user_id, method, path, key, body_hash, response, created_at)
values($1::uuid, 'POST', $2, $3, $4, $5, $6)
on conflict do nothing`,
u.ID, path, key, bodyHash, respJSON, createdAt)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if tag.RowsAffected() == 0 {
var storedHash string
var stored []byte
err := tx.QueryRow(ctx, `
select body_hash, response from idempotency_keys
where user_id=$1::uuid and method='POST' and path=$2 and key=$3`,
u.ID, path, key).Scan(&storedHash, &stored)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if storedHash != bodyHash {
a.writeErr(w, reqID, 409, "conflict", "idempotency key reused with different body")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
_, _ = w.Write(append(stored, '\n'))
return
}
if _, err := tx.Exec(ctx, `
insert into messages(id, chat_id, sender_id, text, created_at)
values($1::uuid, $2::uuid, $3::uuid, $4, $5)`,
msgID, chatID, u.ID, text, createdAt); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if len(attachmentIDs) > 0 {
if _, err := tx.Exec(ctx, `
insert into message_attachments(message_id, attachment_id, position)
select $1::uuid, t.id, t.ord - 1
from unnest($2::uuid[]) with ordinality as t(id, ord)`,
msgID, attachmentIDs); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
}
if err := tx.Commit(ctx); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.writeJSON(w, 201, resp)
}
func (a *App) handleListMessages(w http.ResponseWriter, r *http.Request) {
reqID := reqIDFrom(r)
u, _ := a.authUser(w, r)
if u == nil {
return
}
chatID := r.PathValue("chat_id")
if !isUUID(chatID) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid chat_id")
return
}
ok, err := a.isMember(r.Context(), chatID, u.ID)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
if !ok {
a.writeErr(w, reqID, 404, "not_found", "chat not found")
return
}
limit, err := parseLimit(r)
if err != nil {
a.writeErr(w, reqID, 400, "invalid_request", "invalid limit")
return
}
var afterTS *time.Time
var afterID string
if cur := r.URL.Query().Get("cursor"); cur != "" {
parts, err := decodeCursor(cur)
if err != nil || len(parts) != 3 {
a.writeErr(w, reqID, 400, "invalid_request", "invalid cursor")
return
}
if parts[0] != chatID {
a.writeErr(w, reqID, 400, "invalid_request", "invalid cursor")
return
}
ts, err := parseTime(parts[1])
if err != nil || !isUUID(parts[2]) {
a.writeErr(w, reqID, 400, "invalid_request", "invalid cursor")
return
}
afterTS = &ts
afterID = parts[2]
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
var rows pgx.Rows
if afterTS == nil {
rows, err = a.db.Query(ctx, `
select id::text, chat_id::text, sender_id::text, text, created_at
from messages
where chat_id = $1::uuid
order by created_at, id
limit $2`, chatID, limit+1)
} else {
rows, err = a.db.Query(ctx, `
select id::text, chat_id::text, sender_id::text, text, created_at
from messages
where chat_id = $1::uuid
and (created_at, id) > ($2, $3::uuid)
order by created_at, id
limit $4`, chatID, *afterTS, afterID, limit+1)
}
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
defer rows.Close()
type row struct {
id, chatID, senderID, text string
created time.Time
}
var list []row
for rows.Next() {
var x row
if err := rows.Scan(&x.id, &x.chatID, &x.senderID, &x.text, &x.created); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
list = append(list, x)
}
if err := rows.Err(); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
hasMore := len(list) > limit
if hasMore {
list = list[:limit]
}
attachments := map[string][]string{}
if len(list) > 0 {
ids := make([]string, len(list))
for i, m := range list {
ids[i] = m.id
}
arows, err := a.db.Query(ctx, `
select message_id::text, attachment_id::text
from message_attachments
where message_id = any($1::uuid[])
order by message_id, position`, ids)
if err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
for arows.Next() {
var mid, aid string
if err := arows.Scan(&mid, &aid); err != nil {
arows.Close()
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
attachments[mid] = append(attachments[mid], aid)
}
arows.Close()
if err := arows.Err(); err != nil {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
}
out := make([]map[string]any, 0, len(list))
for _, m := range list {
ids := attachments[m.id]
if ids == nil {
ids = []string{}
}
out = append(out, map[string]any{
"id": m.id,
"chat_id": m.chatID,
"sender_id": m.senderID,
"text": m.text,
"created_at": formatTime(m.created),
"attachment_ids": ids,
})
}
var next any = nil
if hasMore && len(list) > 0 {
last := list[len(list)-1]
next = encodeCursor(chatID, formatTime(last.created), last.id)
}
a.writeJSON(w, 200, map[string]any{"items": out, "next_cursor": next})
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}