829 lines
23 KiB
Go
829 lines
23 KiB
Go
// Package messenger implements the lab6 contract. PostgreSQL is authoritative.
|
|
package messenger
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/trace"
|
|
"io"
|
|
"log/slog"
|
|
"mime"
|
|
"mtusi/messenger/internal/telemetry"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type User struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
type Chat struct {
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
MemberIDs []string `json:"member_ids"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
type Message struct {
|
|
AttachmentIDs []string `json:"attachment_ids"`
|
|
ID string `json:"id"`
|
|
ChatID string `json:"chat_id"`
|
|
SenderID string `json:"sender_id"`
|
|
Text string `json:"text"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
type Page[T any] struct {
|
|
Items []T `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
|
|
func uuid() string {
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
panic(err)
|
|
}
|
|
b[6] = (b[6] & 15) | 64
|
|
b[8] = (b[8] & 63) | 128
|
|
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
|
|
}
|
|
|
|
var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
|
var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
|
|
func validText(v string, max int) bool {
|
|
return utf8.ValidString(v) && strings.TrimSpace(v) != "" && utf8.RuneCountInString(v) <= max
|
|
}
|
|
func reply(w http.ResponseWriter, status int, v any) {
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
func fail(w http.ResponseWriter, status int, code, msg string) {
|
|
reply(w, status, map[string]any{"error": map[string]string{"code": code, "message": msg, "request_id": w.Header().Get("X-Request-Id")}})
|
|
}
|
|
func bad(w http.ResponseWriter) { fail(w, 400, "invalid_request", "Invalid request") }
|
|
func missing(w http.ResponseWriter) { fail(w, 404, "not_found", "Object not found") }
|
|
|
|
// Decode exact object keys (encoding/json structs alone accept case variants).
|
|
// Reject null, duplicate keys, trailing documents and invalid UTF-8 as well.
|
|
func decode(w http.ResponseWriter, r *http.Request, dst any, fields ...string) bool {
|
|
media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
if err != nil || media != "application/json" {
|
|
fail(w, 415, "unsupported_media_type", "Expected application/json")
|
|
return false
|
|
}
|
|
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
|
if err != nil {
|
|
if _, ok := err.(*http.MaxBytesError); ok {
|
|
fail(w, 413, "payload_too_large", "Body exceeds 1 MiB")
|
|
} else {
|
|
bad(w)
|
|
}
|
|
return false
|
|
}
|
|
if !utf8.Valid(b) {
|
|
bad(w)
|
|
return false
|
|
}
|
|
d := json.NewDecoder(bytes.NewReader(b))
|
|
token, err := d.Token()
|
|
if err != nil || token != json.Delim('{') {
|
|
bad(w)
|
|
return false
|
|
}
|
|
allowed := map[string]bool{}
|
|
for _, f := range fields {
|
|
allowed[strings.TrimSuffix(f, "?")] = true
|
|
}
|
|
seen := map[string]bool{}
|
|
for d.More() {
|
|
t, e := d.Token()
|
|
k, ok := t.(string)
|
|
if e != nil || !ok || !allowed[k] || seen[k] {
|
|
bad(w)
|
|
return false
|
|
}
|
|
seen[k] = true
|
|
var raw json.RawMessage
|
|
if d.Decode(&raw) != nil || bytes.Equal(raw, []byte("null")) {
|
|
bad(w)
|
|
return false
|
|
}
|
|
}
|
|
if _, err = d.Token(); err != nil {
|
|
bad(w)
|
|
return false
|
|
}
|
|
if _, err = d.Token(); err != io.EOF {
|
|
bad(w)
|
|
return false
|
|
}
|
|
for _, f := range fields {
|
|
if !strings.HasSuffix(f, "?") && !seen[f] {
|
|
bad(w)
|
|
return false
|
|
}
|
|
}
|
|
if json.Unmarshal(b, dst) != nil {
|
|
bad(w)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
type cursor struct {
|
|
Scope string `json:"scope"`
|
|
Time string `json:"time"`
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
func (s *Server) encodeCursor(c cursor) *string {
|
|
b, _ := json.Marshal(c)
|
|
mac := hmac.New(sha256.New, s.secret)
|
|
mac.Write(b)
|
|
v := base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
|
return &v
|
|
}
|
|
func (s *Server) pagination(w http.ResponseWriter, r *http.Request, scope string) (int, cursor, bool) {
|
|
var c cursor
|
|
limit := 50
|
|
// ParseQuery explicitly reports malformed escaping, unlike URL.Query.
|
|
values, e := url.ParseQuery(r.URL.RawQuery)
|
|
if e != nil {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
if v, ok := values["limit"]; ok {
|
|
if len(v) != 1 || v[0] == "" || strings.Trim(v[0], "0123456789") != "" {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
limit, e = strconv.Atoi(v[0])
|
|
if e != nil || limit < 1 || limit > 100 {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
}
|
|
if v, ok := values["cursor"]; ok {
|
|
if len(v) != 1 || len(v[0]) > 2048 {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
parts := strings.Split(v[0], ".")
|
|
if len(parts) != 2 {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
b, e1 := base64.RawURLEncoding.DecodeString(parts[0])
|
|
sig, e2 := base64.RawURLEncoding.DecodeString(parts[1])
|
|
mac := hmac.New(sha256.New, s.secret)
|
|
mac.Write(b)
|
|
if e1 != nil || e2 != nil || !hmac.Equal(sig, mac.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope || !uuidRE.MatchString(c.ID) {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
}
|
|
if c.ID != "" {
|
|
if _, err := time.Parse(time.RFC3339Nano, c.Time); err != nil {
|
|
bad(w)
|
|
return 0, c, false
|
|
}
|
|
}
|
|
return limit, c, true
|
|
}
|
|
|
|
type Server struct {
|
|
db *pgxpool.Pool
|
|
cache *redis.Client
|
|
secret []byte
|
|
ttl int
|
|
log *slog.Logger
|
|
stopping atomic.Bool
|
|
kdf chan struct{}
|
|
objects *ObjectStore
|
|
uploads chan struct{}
|
|
instance string
|
|
dummyHash string
|
|
}
|
|
|
|
func New(db *pgxpool.Pool, cache *redis.Client, secret []byte, ttl int, logger *slog.Logger) *Server {
|
|
hostname, _ := os.Hostname()
|
|
return &Server{instance: hostname, db: db, cache: cache, secret: secret, ttl: ttl, log: logger, kdf: make(chan struct{}, 2), dummyHash: hashPassword("dummy-not-a-real-password")}
|
|
}
|
|
func (s *Server) Stop() { s.stopping.Store(true) }
|
|
func (s *Server) acquireKDF(ctx context.Context, w http.ResponseWriter) bool {
|
|
select {
|
|
case s.kdf <- struct{}{}:
|
|
return true
|
|
case <-ctx.Done():
|
|
unavailable(w)
|
|
return false
|
|
}
|
|
}
|
|
func unavailable(w http.ResponseWriter) {
|
|
fail(w, 503, "unavailable", "Dependency temporarily unavailable")
|
|
}
|
|
func unauthorized(w http.ResponseWriter, scheme string) {
|
|
challenge := scheme + ` realm="messenger"`
|
|
if scheme == "Basic" {
|
|
challenge += `, charset="UTF-8"`
|
|
}
|
|
w.Header().Set("WWW-Authenticate", challenge)
|
|
fail(w, 401, "unauthorized", "Invalid or missing credentials")
|
|
}
|
|
func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") }
|
|
|
|
const userColumns = "id::text, username, display_name, created_at"
|
|
|
|
type scanner interface{ Scan(...any) error }
|
|
|
|
func scanUser(row scanner) (User, error) {
|
|
var u User
|
|
var t time.Time
|
|
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &t)
|
|
u.CreatedAt = stamp(t)
|
|
return u, err
|
|
}
|
|
func scanMessage(row scanner) (Message, error) {
|
|
var m Message
|
|
var t time.Time
|
|
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t)
|
|
m.CreatedAt = stamp(t)
|
|
m.AttachmentIDs = []string{}
|
|
return m, err
|
|
}
|
|
|
|
func (s *Server) profile(ctx context.Context, uid string) (User, error) {
|
|
// Valkey caches ONLY immutable User JSON. Session validity is always read
|
|
// from PostgreSQL first; cache loss never permits anonymous access.
|
|
key := "profile:v1:" + uid
|
|
if s.cache != nil {
|
|
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
|
raw, err := s.cache.Get(c, key).Bytes()
|
|
cancel()
|
|
var u User
|
|
if err == nil && json.Unmarshal(raw, &u) == nil && u.ID == uid {
|
|
return u, nil
|
|
}
|
|
}
|
|
u, err := scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id=$1", uid))
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
if s.cache != nil {
|
|
raw, _ := json.Marshal(u)
|
|
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
|
_ = s.cache.Set(c, key, raw, 300*time.Second).Err()
|
|
cancel()
|
|
}
|
|
return u, nil
|
|
}
|
|
func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (User, []byte, bool) {
|
|
parts := strings.Fields(r.Header.Get("Authorization"))
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
|
unauthorized(w, "Bearer")
|
|
return User{}, nil, false
|
|
}
|
|
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil || len(raw) != 32 {
|
|
unauthorized(w, "Bearer")
|
|
return User{}, nil, false
|
|
}
|
|
digest := sha256.Sum256([]byte(parts[1]))
|
|
var uid string
|
|
err = s.db.QueryRow(r.Context(), "SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()", digest[:]).Scan(&uid)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
unauthorized(w, "Bearer")
|
|
return User{}, nil, false
|
|
}
|
|
if err != nil {
|
|
unavailable(w)
|
|
return User{}, nil, false
|
|
}
|
|
u, err := s.profile(r.Context(), uid)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return User{}, nil, false
|
|
}
|
|
return u, digest[:], true
|
|
}
|
|
|
|
type recorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (w *recorder) WriteHeader(status int) { w.status = status; w.ResponseWriter.WriteHeader(status) }
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
ctxSpan, span := telemetry.Start(telemetry.Incoming(r), "http.request", trace.SpanKindServer)
|
|
r = r.WithContext(ctxSpan)
|
|
defer span.End()
|
|
out := &recorder{w, 200}
|
|
w = out
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Header().Set("X-Request-Id", uuid())
|
|
w.Header().Set("X-Instance-Id", s.instance)
|
|
budget := 3 * time.Second
|
|
if strings.Contains(r.URL.Path, "attachments") {
|
|
budget = 30 * time.Second
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), budget)
|
|
defer cancel()
|
|
r = r.WithContext(ctx)
|
|
if span.SpanContext().IsValid() {
|
|
w.Header().Set("X-Trace-Id", telemetry.TraceID(ctx))
|
|
}
|
|
route := routeTemplate(r.URL.Path)
|
|
defer func() {
|
|
if recover() != nil {
|
|
fail(w, 500, "internal_error", "Internal server error")
|
|
}
|
|
span.SetName(r.Method + " " + route)
|
|
span.SetAttributes(attribute.String("http.request.method", r.Method), attribute.String("http.route", route), attribute.Int("http.response.status_code", out.status))
|
|
if out.status >= 500 {
|
|
span.SetStatus(codes.Error, "HTTP 5xx")
|
|
}
|
|
telemetry.HTTP(ctx, r.Method, route, out.status, time.Since(start).Seconds())
|
|
if s.log != nil {
|
|
s.log.InfoContext(ctx, "request", "method", r.Method, "route", route, "status", out.status, "duration_us", time.Since(start).Microseconds(), "request_id", w.Header().Get("X-Request-Id"))
|
|
}
|
|
}()
|
|
if r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") {
|
|
if r.URL.Path == "/health/ready" && (s.stopping.Load() || s.db.Ping(ctx) != nil || (s.objects != nil && !s.objects.Ready(ctx))) {
|
|
unavailable(w)
|
|
} else {
|
|
reply(w, 200, map[string]string{"status": "ok"})
|
|
}
|
|
return
|
|
}
|
|
if s.stopping.Load() {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
if r.Method == "POST" && r.URL.Path == "/api/v1/users" {
|
|
s.createUser(w, r)
|
|
return
|
|
}
|
|
if r.Method == "POST" && r.URL.Path == "/api/v1/auth/sessions" {
|
|
s.login(w, r)
|
|
return
|
|
}
|
|
user, digest, ok := s.authenticate(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if r.Method == "DELETE" && r.URL.Path == "/api/v1/auth/sessions/current" {
|
|
tag, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest)
|
|
if err != nil {
|
|
unavailable(w)
|
|
} else if tag.RowsAffected() == 0 {
|
|
unauthorized(w, "Bearer")
|
|
} else {
|
|
w.WriteHeader(204)
|
|
}
|
|
return
|
|
}
|
|
if r.Method == "GET" && r.URL.Path == "/api/v1/users/me" {
|
|
reply(w, 200, user)
|
|
return
|
|
}
|
|
if r.URL.Path == "/api/v1/chats" {
|
|
switch r.Method {
|
|
case "POST":
|
|
s.createChat(w, r, user.ID)
|
|
case "GET":
|
|
s.listChats(w, r, user.ID)
|
|
default:
|
|
missing(w)
|
|
}
|
|
return
|
|
}
|
|
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
|
|
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && s.objects != nil {
|
|
s.serveAttachment(w, r, user.ID, parts)
|
|
return
|
|
}
|
|
if len(parts) < 4 || len(parts) > 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "chats" {
|
|
missing(w)
|
|
return
|
|
}
|
|
cid := strings.ToLower(parts[3])
|
|
if !uuidRE.MatchString(cid) {
|
|
bad(w)
|
|
return
|
|
}
|
|
chat, err := s.getChat(ctx, cid, user.ID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
missing(w)
|
|
return
|
|
}
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
if len(parts) == 4 && r.Method == "GET" {
|
|
reply(w, 200, chat)
|
|
return
|
|
}
|
|
if len(parts) == 5 && parts[4] == "attachments" && r.Method == "POST" && s.objects != nil {
|
|
s.uploadAttachment(w, r, user.ID, cid)
|
|
return
|
|
}
|
|
if len(parts) == 5 && parts[4] == "messages" {
|
|
switch r.Method {
|
|
case "POST":
|
|
s.createMessage(w, r, user.ID, cid)
|
|
case "GET":
|
|
s.listMessages(w, r, cid)
|
|
default:
|
|
missing(w)
|
|
}
|
|
return
|
|
}
|
|
missing(w)
|
|
}
|
|
func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
|
|
var input struct {
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Password string `json:"password"`
|
|
}
|
|
if !decode(w, r, &input, "username", "display_name", "password") {
|
|
return
|
|
}
|
|
if !usernameRE.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validText(input.Password, 128) || utf8.RuneCountInString(input.Password) < 12 {
|
|
bad(w)
|
|
return
|
|
}
|
|
if !s.acquireKDF(r.Context(), w) {
|
|
return
|
|
}
|
|
hash := hashPassword(input.Password)
|
|
<-s.kdf
|
|
u, err := scanUser(s.db.QueryRow(r.Context(), "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING "+userColumns, uuid(), input.Username, input.DisplayName, hash))
|
|
var pgerr *pgconn.PgError
|
|
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
|
|
fail(w, 409, "conflict", "Username already exists")
|
|
return
|
|
}
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
reply(w, 201, u)
|
|
}
|
|
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1))
|
|
if err != nil || len(body) != 0 {
|
|
bad(w)
|
|
return
|
|
}
|
|
username, password, ok := r.BasicAuth()
|
|
if !ok || !usernameRE.MatchString(username) || !validText(password, 128) || utf8.RuneCountInString(password) < 12 {
|
|
unauthorized(w, "Basic")
|
|
return
|
|
}
|
|
var u User
|
|
var hash string
|
|
var t time.Time
|
|
err = s.db.QueryRow(r.Context(), "SELECT "+userColumns+", password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, &u.DisplayName, &t, &hash)
|
|
absent := errors.Is(err, pgx.ErrNoRows)
|
|
if err != nil && !absent {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
if absent {
|
|
hash = s.dummyHash
|
|
}
|
|
if !s.acquireKDF(r.Context(), w) {
|
|
return
|
|
}
|
|
valid := verifyPassword(password, hash)
|
|
<-s.kdf
|
|
if !valid || absent {
|
|
unauthorized(w, "Basic")
|
|
return
|
|
}
|
|
raw := make([]byte, 32)
|
|
if _, err = rand.Read(raw); err != nil {
|
|
panic(err)
|
|
}
|
|
token := base64.RawURLEncoding.EncodeToString(raw)
|
|
digest := sha256.Sum256([]byte(token))
|
|
var expires time.Time
|
|
err = s.db.QueryRow(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,clock_timestamp()+make_interval(secs=>$3)) RETURNING expires_at", digest[:], u.ID, s.ttl).Scan(&expires)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
u.CreatedAt = stamp(t)
|
|
reply(w, 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": stamp(expires), "user": u})
|
|
}
|
|
func (s *Server) createChat(w http.ResponseWriter, r *http.Request, uid string) {
|
|
var input struct {
|
|
Title string `json:"title"`
|
|
MemberIDs []string `json:"member_ids"`
|
|
}
|
|
if !decode(w, r, &input, "title", "member_ids") {
|
|
return
|
|
}
|
|
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
|
bad(w)
|
|
return
|
|
}
|
|
seen := map[string]bool{}
|
|
for i, id := range input.MemberIDs {
|
|
id = strings.ToLower(id)
|
|
if !uuidRE.MatchString(id) || seen[id] {
|
|
bad(w)
|
|
return
|
|
}
|
|
seen[id] = true
|
|
input.MemberIDs[i] = id
|
|
}
|
|
if !seen[uid] {
|
|
bad(w)
|
|
return
|
|
}
|
|
tx, err := s.db.Begin(r.Context())
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
chat := Chat{ID: uuid(), Title: input.Title, MemberIDs: input.MemberIDs}
|
|
var t time.Time
|
|
err = tx.QueryRow(r.Context(), "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", chat.ID, chat.Title).Scan(&t)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
for _, id := range input.MemberIDs {
|
|
_, err = tx.Exec(r.Context(), "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id)
|
|
var pgerr *pgconn.PgError
|
|
if errors.As(err, &pgerr) && pgerr.Code == "23503" {
|
|
bad(w)
|
|
return
|
|
}
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
}
|
|
if tx.Commit(r.Context()) != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
chat.CreatedAt = stamp(t)
|
|
reply(w, 201, chat)
|
|
}
|
|
|
|
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)`
|
|
|
|
func scanChat(row scanner) (Chat, error) {
|
|
var c Chat
|
|
var t time.Time
|
|
err := row.Scan(&c.ID, &c.Title, &t, &c.MemberIDs)
|
|
c.CreatedAt = stamp(t)
|
|
return c, err
|
|
}
|
|
func (s *Server) getChat(ctx context.Context, cid, uid string) (Chat, error) {
|
|
return scanChat(s.db.QueryRow(ctx, "SELECT "+chatColumns+" FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$2 WHERE c.id=$1", cid, uid))
|
|
}
|
|
|
|
var idempotencyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
|
|
|
func (s *Server) createMessage(w http.ResponseWriter, r *http.Request, uid, cid string) {
|
|
text, attachments, ok := parseMessage(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
input := struct {
|
|
Text string `json:"text"`
|
|
Attachments []string `json:"attachment_ids"`
|
|
}{text, attachments}
|
|
keys := r.Header.Values("Idempotency-Key")
|
|
if len(keys) != 1 || !idempotencyRE.MatchString(keys[0]) {
|
|
bad(w)
|
|
return
|
|
}
|
|
body, _ := json.Marshal(input)
|
|
digest := sha256.Sum256(body)
|
|
ctx := r.Context()
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
// Serialize only the same scope/key, across processes. Hash collisions only
|
|
// serialize unrelated requests; the full unique key still decides identity.
|
|
_, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", uid+":"+cid+":"+keys[0])
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
var previous, saved []byte
|
|
err = tx.QueryRow(ctx, "SELECT body_hash,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()", uid, cid, keys[0]).Scan(&previous, &saved)
|
|
if err == nil {
|
|
if !bytes.Equal(previous, digest[:]) {
|
|
fail(w, 409, "conflict", "Key already used with another message")
|
|
return
|
|
}
|
|
if tx.Commit(ctx) != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
w.WriteHeader(201)
|
|
_, _ = w.Write(saved)
|
|
return
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
// A row lock prevents cleanup of an attachment while a message links it.
|
|
for _, id := range attachments {
|
|
var found, status string
|
|
err = tx.QueryRow(ctx, "SELECT id::text,status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE", id, cid).Scan(&found, &status)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
missing(w)
|
|
return
|
|
}
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
if status == "failed" {
|
|
fail(w, 409, "conflict", "Attachment processing failed")
|
|
return
|
|
}
|
|
}
|
|
var t time.Time
|
|
err = tx.QueryRow(ctx, "UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') WHERE id=$1 RETURNING last_message_at", cid).Scan(&t)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
m, err := scanMessage(tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5) RETURNING id::text,chat_id::text,sender_id::text,text,created_at", uuid(), cid, uid, input.Text, t))
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
m.AttachmentIDs = attachments
|
|
for i, id := range attachments {
|
|
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", m.ID, id, i); err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
}
|
|
response, _ := json.Marshal(m)
|
|
_, err = tx.Exec(ctx, `INSERT INTO message_requests(user_id,chat_id,key,body_hash,response,expires_at) VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body_hash=EXCLUDED.body_hash,response=EXCLUDED.response,expires_at=EXCLUDED.expires_at`, uid, cid, keys[0], digest[:], response)
|
|
if err != nil || tx.Commit(ctx) != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
reply(w, 201, m)
|
|
}
|
|
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, cid string) {
|
|
scope := "messages:" + cid
|
|
limit, c, ok := s.pagination(w, r, scope)
|
|
if !ok {
|
|
return
|
|
}
|
|
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1`
|
|
args := []any{cid}
|
|
if c.ID != "" {
|
|
query += ` AND (created_at,id)>($2::timestamptz,$3::uuid)`
|
|
args = append(args, c.Time, c.ID)
|
|
}
|
|
query += fmt.Sprintf(" ORDER BY messages.created_at,messages.id LIMIT $%d", len(args)+1)
|
|
args = append(args, limit+1)
|
|
rows, err := s.db.Query(r.Context(), query, args...)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
items := []Message{}
|
|
for rows.Next() {
|
|
var m Message
|
|
var created time.Time
|
|
err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs)
|
|
m.CreatedAt = stamp(created)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
items = append(items, m)
|
|
}
|
|
if rows.Err() != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
var next *string
|
|
if len(items) > limit {
|
|
items = items[:limit]
|
|
last := items[limit-1]
|
|
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
|
|
}
|
|
reply(w, 200, Page[Message]{items, next})
|
|
}
|
|
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, uid string) {
|
|
scope := "chats:" + uid
|
|
limit, c, ok := s.pagination(w, r, scope)
|
|
if !ok {
|
|
return
|
|
}
|
|
query := "SELECT " + chatColumns + " FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$1"
|
|
args := []any{uid}
|
|
if c.ID != "" {
|
|
query += " WHERE (c.created_at,c.id)>($2::timestamptz,$3::uuid)"
|
|
args = append(args, c.Time, c.ID)
|
|
}
|
|
query += fmt.Sprintf(" ORDER BY c.created_at,c.id LIMIT $%d", len(args)+1)
|
|
args = append(args, limit+1)
|
|
rows, err := s.db.Query(r.Context(), query, args...)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
items := []Chat{}
|
|
for rows.Next() {
|
|
chat, err := scanChat(rows)
|
|
if err != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
items = append(items, chat)
|
|
}
|
|
if rows.Err() != nil {
|
|
unavailable(w)
|
|
return
|
|
}
|
|
var next *string
|
|
if len(items) > limit {
|
|
items = items[:limit]
|
|
last := items[limit-1]
|
|
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
|
|
}
|
|
reply(w, 200, Page[Chat]{items, next})
|
|
}
|
|
|
|
// Classify before authentication/SQL so failures retain the endpoint template.
|
|
func routeTemplate(path string) string {
|
|
switch path {
|
|
case "/health/live", "/health/ready":
|
|
return path
|
|
}
|
|
if !strings.HasPrefix(path, "/api/v1/") {
|
|
return "unknown"
|
|
}
|
|
tail := strings.TrimPrefix(path, "/api/v1")
|
|
switch tail {
|
|
case "/users", "/users/me", "/auth/sessions", "/auth/sessions/current", "/chats":
|
|
return tail
|
|
}
|
|
p := strings.Split(strings.TrimPrefix(tail, "/"), "/")
|
|
if len(p) == 2 && p[0] == "chats" {
|
|
return "/chats/{id}"
|
|
}
|
|
if len(p) == 3 && p[0] == "chats" {
|
|
switch p[2] {
|
|
case "messages":
|
|
return "/chats/{id}/messages"
|
|
case "attachments":
|
|
return "/chats/{id}/attachments"
|
|
}
|
|
}
|
|
if len(p) == 2 && p[0] == "attachments" {
|
|
return "/attachments/{id}"
|
|
}
|
|
if len(p) == 3 && p[0] == "attachments" && p[2] == "content" {
|
|
return "/attachments/{id}/content"
|
|
}
|
|
return "unknown"
|
|
}
|