Fixed
This commit is contained in:
@@ -0,0 +1,331 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/api"
|
||||
"mtusi-messenger/internal/auth"
|
||||
"mtusi-messenger/internal/cache"
|
||||
"mtusi-messenger/internal/db"
|
||||
"mtusi-messenger/internal/objstore"
|
||||
"mtusi-messenger/internal/reconcile"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getint(key string, def int) int {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n <= 0 {
|
||||
fmt.Fprintf(os.Stderr, "invalid %s\n", key)
|
||||
os.Exit(2)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func secret(key string) (string, error) {
|
||||
if path := os.Getenv(key + "_FILE"); path != "" {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s_FILE: %w", key, err)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s or %s_FILE is required", key, key)
|
||||
}
|
||||
|
||||
func main() {
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
if err := run(log); err != nil {
|
||||
log.Error("fatal", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func openDB(ctx context.Context) (*store.Store, func(), error) {
|
||||
dsn, err := secret("DATABASE_URL")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pool, err := db.Open(ctx, dsn, db.PoolOptions{MaxConns: int32(getint("DB_MAX_CONNS", 10))})
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("database config is invalid")
|
||||
}
|
||||
return store.New(pool), pool.Close, nil
|
||||
}
|
||||
|
||||
func getduration(key string, def time.Duration) time.Duration {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil || d <= 0 {
|
||||
fmt.Fprintf(os.Stderr, "invalid %s\n", key)
|
||||
os.Exit(2)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func openObjects() (*objstore.Store, error) { return openObjectsAs("S3") }
|
||||
|
||||
// openObjectsAs reads <prefix>_ACCESS_KEY_ID[_FILE] / <prefix>_SECRET_ACCESS_KEY[_FILE]:
|
||||
// S3 for the restricted API identity, S3_ADMIN only in the one-shot bootstrap.
|
||||
func openObjectsAs(prefix string) (*objstore.Store, error) {
|
||||
access, err := secret(prefix + "_ACCESS_KEY_ID")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
secretKey, err := secret(prefix + "_SECRET_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return objstore.New(objstore.Config{
|
||||
Endpoint: getenv("S3_ENDPOINT", "http://s3:9000"),
|
||||
Region: getenv("S3_REGION", "us-east-1"),
|
||||
Bucket: getenv("S3_BUCKET", "messenger-attachments"),
|
||||
AccessKey: access,
|
||||
SecretKey: secretKey,
|
||||
})
|
||||
}
|
||||
|
||||
// runReconcile: `server reconcile [--apply] [--grace 15m] [--every 10m]`.
|
||||
// Dry-run by default; prints one JSON report per pass.
|
||||
func runReconcile(ctx context.Context, log *slog.Logger, args []string) error {
|
||||
fs := flag.NewFlagSet("reconcile", flag.ContinueOnError)
|
||||
apply := fs.Bool("apply", false, "apply fixes (default: dry-run, report only)")
|
||||
grace := fs.Duration("grace", getduration("RECONCILE_GRACE", 15*time.Minute), "minimum age before an object/row is touched")
|
||||
every := fs.Duration("every", 0, "repeat interval; 0 runs once")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if *grace < time.Minute {
|
||||
return errors.New("grace below 1m is unsafe: it is shorter than an upload may take")
|
||||
}
|
||||
st, closeDB, err := openDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeDB()
|
||||
objects, err := openObjects()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rec := reconcile.New(st, objects, log)
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
for {
|
||||
pctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
|
||||
rep, err := rec.Run(pctx, reconcile.Options{Apply: *apply, Grace: *grace})
|
||||
cancel()
|
||||
if err != nil {
|
||||
if *every == 0 {
|
||||
return err
|
||||
}
|
||||
log.Warn("reconcile pass failed", "error", err.Error())
|
||||
} else {
|
||||
out, _ := json.Marshal(rep)
|
||||
fmt.Println(string(out))
|
||||
}
|
||||
if *every == 0 {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
case <-time.After(*every):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run(log *slog.Logger) error {
|
||||
ctx := context.Background()
|
||||
|
||||
if len(os.Args) > 1 && os.Args[1] == "migrate" {
|
||||
dsn, err := secret("DATABASE_URL")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := db.Open(ctx, dsn, db.PoolOptions{MaxConns: 2})
|
||||
if err != nil {
|
||||
return errors.New("database config is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
mctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
return db.Migrate(mctx, pool, log)
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "s3-init" {
|
||||
objects, err := openObjectsAs("S3_ADMIN")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var created bool
|
||||
for attempt := 1; ; attempt++ {
|
||||
bctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
created, err = objects.EnsureBucket(bctx, getenv("S3_REGION", "us-east-1"))
|
||||
cancel()
|
||||
if err == nil || attempt == 30 {
|
||||
break
|
||||
}
|
||||
log.Warn("s3 not ready, retrying", "attempt", attempt, "error", err.Error())
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("bucket ready", "bucket", objects.Bucket(), "created", created)
|
||||
return nil
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "reconcile" {
|
||||
return runReconcile(ctx, log, os.Args[2:])
|
||||
}
|
||||
|
||||
st, closeDB, err := openDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeDB()
|
||||
|
||||
ttl := time.Duration(getint("SESSION_TTL_SECONDS", 3600)) * time.Second
|
||||
cacheMaxTTL := time.Duration(getint("SESSION_CACHE_MAX_TTL_SECONDS", 60)) * time.Second
|
||||
|
||||
var sessCache auth.SessionCache
|
||||
switch mode := getenv("SESSION_STORE", "postgres"); mode {
|
||||
case "postgres":
|
||||
case "valkey", "redis":
|
||||
url, err := secret("CACHE_URL")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vk, err := cache.NewValkey(url)
|
||||
if err != nil {
|
||||
return errors.New("cache config is invalid")
|
||||
}
|
||||
defer vk.Close()
|
||||
sessCache = vk
|
||||
default:
|
||||
return fmt.Errorf("unknown SESSION_STORE %q (postgres|valkey|redis)", mode)
|
||||
}
|
||||
|
||||
hasher := auth.NewHasher(getint("PASSWORD_HASH_CONCURRENCY", 4))
|
||||
sessions := auth.NewSessions(st, sessCache, ttl, cacheMaxTTL, log)
|
||||
|
||||
instanceID := getenv("INSTANCE_ID", "")
|
||||
if instanceID == "" {
|
||||
h, err := os.Hostname()
|
||||
if err != nil || h == "" {
|
||||
return errors.New("cannot determine instance id; set INSTANCE_ID")
|
||||
}
|
||||
instanceID = h
|
||||
}
|
||||
idemTTL := time.Duration(getint("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second
|
||||
objects, err := openObjects()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
maxUpload := int64(getint("MAX_UPLOAD_BYTES", 10485760))
|
||||
if maxUpload > 10485760 {
|
||||
return errors.New("MAX_UPLOAD_BYTES above the 10 MiB contract limit")
|
||||
}
|
||||
drainDelay := time.Duration(getint("SHUTDOWN_DRAIN_MS", 3000)) * time.Millisecond
|
||||
|
||||
ready := &atomic.Bool{}
|
||||
ready.Store(true)
|
||||
|
||||
host := getenv("APP_HOST", "0.0.0.0")
|
||||
port := getenv("APP_PORT", "8080")
|
||||
addr := host + ":" + port
|
||||
srv := api.NewServer(st, objects, sessions, hasher, log, ready, api.Options{
|
||||
InstanceID: instanceID, IdempotencyTTL: idemTTL,
|
||||
MaxUploadBytes: maxUpload,
|
||||
MaxImagePixels: int64(getint("MAX_IMAGE_PIXELS", 40000000)),
|
||||
UploadConcurrency: int64(getint("UPLOAD_CONCURRENCY", 8)),
|
||||
DecodeBudgetBytes: int64(getint("DECODE_BUDGET_BYTES", 128<<20)),
|
||||
UploadTimeout: getduration("UPLOAD_TIMEOUT", 60*time.Second),
|
||||
S3Timeout: getduration("S3_TIMEOUT", 15*time.Second),
|
||||
})
|
||||
httpSrv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: srv.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 90 * time.Second,
|
||||
WriteTimeout: 90 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
bgCtx, stopBg := context.WithCancel(ctx)
|
||||
defer stopBg()
|
||||
go func() {
|
||||
t := time.NewTicker(10 * time.Minute)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-bgCtx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
c, cancel := context.WithTimeout(bgCtx, 10*time.Second)
|
||||
if n, err := st.PurgeSessions(c, 24*time.Hour); err == nil && n > 0 {
|
||||
log.Info("expired sessions purged", "count", n)
|
||||
}
|
||||
if n, err := st.PurgeIdempotency(c, idemTTL); err == nil && n > 0 {
|
||||
log.Info("expired idempotency keys purged", "count", n)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- httpSrv.ListenAndServe() }()
|
||||
log.Info("server started", "addr", addr, "pid", os.Getpid(), "instance_id", instanceID, "build", getenv("APP_BUILD", "dev"), "s3_bucket", objects.Bucket(),
|
||||
"session_store", getenv("SESSION_STORE", "postgres"), "session_ttl_s", int(ttl.Seconds()))
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
case sig := <-stop:
|
||||
log.Info("shutdown signal received", "signal", sig.String())
|
||||
ready.Store(false)
|
||||
time.Sleep(drainDelay)
|
||||
httpSrv.SetKeepAlivesEnabled(false)
|
||||
sctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := httpSrv.Shutdown(sctx); err != nil {
|
||||
log.Warn("graceful shutdown exceeded budget, closing", "error", err.Error())
|
||||
_ = httpSrv.Close()
|
||||
}
|
||||
log.Info("server stopped cleanly")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
module mtusi-messenger
|
||||
|
||||
go 1.23
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.2
|
||||
github.com/minio/minio-go/v7 v7.0.82
|
||||
github.com/redis/go-redis/v9 v9.7.0
|
||||
golang.org/x/crypto v0.31.0
|
||||
golang.org/x/sync v0.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
golang.org/x/net v0.30.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
)
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
|
||||
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.82 h1:tWfICLhmp2aFPXL8Tli0XDTHj2VB/fNf0PC1f/i1gRo=
|
||||
github.com/minio/minio-go/v7 v7.0.82/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
|
||||
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
|
||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,338 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/model"
|
||||
"mtusi-messenger/internal/objstore"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
mimePNG = "image/png"
|
||||
mimeJPEG = "image/jpeg"
|
||||
// An oversized body is read and discarded up to this many bytes so the client
|
||||
// receives 413 instead of a connection reset; beyond it the connection is closed.
|
||||
maxDrainBytes = 64 << 20
|
||||
)
|
||||
|
||||
func (s *Server) objectError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
s.log.Warn("object storage unavailable", "request_id", requestID(r), "error", err.Error())
|
||||
apperr.Write(w, requestID(r), apperr.Unavailable("attachment storage temporarily unavailable"))
|
||||
}
|
||||
|
||||
func validFilename(name string) bool {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || name == "." || name == ".." {
|
||||
return false
|
||||
}
|
||||
if n := runeLen(name); n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
for _, c := range name {
|
||||
switch {
|
||||
case c == '/', c == '\\', c == 0, unicode.IsControl(c):
|
||||
return false
|
||||
case c >= 0x202a && c <= 0x202e, c >= 0x2066 && c <= 0x2069: // bidi overrides hide the real extension
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sniffImage(data []byte) string {
|
||||
switch {
|
||||
case bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")):
|
||||
return mimePNG
|
||||
case bytes.HasPrefix(data, []byte{0xff, 0xd8, 0xff}):
|
||||
return mimeJPEG
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// decodeCost estimates bytes allocated by a full decode for the memory budget.
|
||||
func decodeCost(m color.Model, pixels int64) int64 {
|
||||
bpp := int64(4)
|
||||
switch m {
|
||||
case color.GrayModel, color.AlphaModel:
|
||||
bpp = 1
|
||||
case color.Gray16Model, color.Alpha16Model:
|
||||
bpp = 2
|
||||
case color.YCbCrModel:
|
||||
bpp = 3
|
||||
case color.RGBA64Model, color.NRGBA64Model:
|
||||
bpp = 8
|
||||
}
|
||||
if _, ok := m.(color.Palette); ok {
|
||||
bpp = 1
|
||||
}
|
||||
return pixels * bpp
|
||||
}
|
||||
|
||||
type imageInfo struct {
|
||||
contentType string
|
||||
width, height int
|
||||
}
|
||||
|
||||
// inspectImage checks the real format by magic bytes, compares it with the
|
||||
// declared Content-Type, enforces the pixel limit from the header only and then
|
||||
// fully decodes the image under a shared memory budget to reject corrupt data.
|
||||
func (s *Server) inspectImage(ctx context.Context, data []byte, declared string) (imageInfo, *apperr.AppError) {
|
||||
detected := sniffImage(data)
|
||||
if detected == "" {
|
||||
return imageInfo{}, apperr.UnsupportedMedia("content is not a PNG or JPEG image")
|
||||
}
|
||||
if detected != declared {
|
||||
return imageInfo{}, apperr.UnsupportedMedia("Content-Type does not match the image content")
|
||||
}
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return imageInfo{}, apperr.UnsupportedMedia("image header is invalid")
|
||||
}
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if pixels > s.maxPixels {
|
||||
return imageInfo{}, apperr.PayloadTooLarge("image exceeds " + strconv.FormatInt(s.maxPixels, 10) + " pixels")
|
||||
}
|
||||
cost := min(decodeCost(cfg.ColorModel, pixels), s.decodeBudget)
|
||||
if err := s.decodeSem.Acquire(ctx, cost); err != nil {
|
||||
return imageInfo{}, apperr.Unavailable("server is busy processing images, retry later")
|
||||
}
|
||||
if detected == mimePNG {
|
||||
_, err = png.Decode(bytes.NewReader(data))
|
||||
} else {
|
||||
_, err = jpeg.Decode(bytes.NewReader(data))
|
||||
}
|
||||
s.decodeSem.Release(cost)
|
||||
if err != nil {
|
||||
return imageInfo{}, apperr.UnsupportedMedia("image data is corrupted")
|
||||
}
|
||||
return imageInfo{contentType: detected, width: cfg.Width, height: cfg.Height}, nil
|
||||
}
|
||||
|
||||
func readBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, *apperr.AppError) {
|
||||
var buf bytes.Buffer
|
||||
if r.ContentLength > 0 {
|
||||
buf.Grow(int(r.ContentLength))
|
||||
}
|
||||
_, err := buf.ReadFrom(http.MaxBytesReader(w, r.Body, limit))
|
||||
var maxErr *http.MaxBytesError
|
||||
switch {
|
||||
case errors.As(err, &maxErr):
|
||||
return nil, apperr.PayloadTooLarge("attachment exceeds " + strconv.FormatInt(limit, 10) + " bytes")
|
||||
case err != nil:
|
||||
return nil, apperr.InvalidRequest("request body could not be read")
|
||||
case buf.Len() == 0:
|
||||
return nil, apperr.InvalidRequest("request body is empty")
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
body := r.Body
|
||||
defer func() { _, _ = io.CopyN(io.Discard, body, maxDrainBytes) }()
|
||||
|
||||
id := requestID(r)
|
||||
chatID, ok := s.chatAccess(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil || len(query["filename"]) != 1 {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("exactly one filename query parameter is required"))
|
||||
return
|
||||
}
|
||||
filename := query.Get("filename")
|
||||
if !validFilename(filename) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("filename must be 1..255 code points without path separators or control characters"))
|
||||
return
|
||||
}
|
||||
media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if media != mimePNG && media != mimeJPEG {
|
||||
apperr.Write(w, id, apperr.UnsupportedMedia("Content-Type must be image/png or image/jpeg"))
|
||||
return
|
||||
}
|
||||
if r.ContentLength > s.maxUpload {
|
||||
apperr.Write(w, id, apperr.PayloadTooLarge("attachment exceeds "+strconv.FormatInt(s.maxUpload, 10)+" bytes"))
|
||||
return
|
||||
}
|
||||
|
||||
// Each slot may hold up to maxUpload bytes in memory; waiting is bounded by the request timeout.
|
||||
if err := s.uploadSem.Acquire(r.Context(), 1); err != nil {
|
||||
apperr.Write(w, id, apperr.Unavailable("too many concurrent uploads, retry later"))
|
||||
return
|
||||
}
|
||||
defer s.uploadSem.Release(1)
|
||||
|
||||
data, aerr := readBody(w, r, s.maxUpload)
|
||||
if aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
info, aerr := s.inspectImage(r.Context(), data, media)
|
||||
if aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
attID := uuid.NewString()
|
||||
att := &model.Attachment{
|
||||
ID: attID, ChatID: chatID, OwnerID: currentUser(r).ID, Filename: filename,
|
||||
ContentType: info.contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]),
|
||||
Status: "ready", Variants: []model.Variant{},
|
||||
// The key is server-generated; filename never reaches S3.
|
||||
ObjectKey: "attachments/" + chatID + "/" + attID,
|
||||
}
|
||||
|
||||
// 1. intent row (pending) -> 2. S3 PUT -> 3. pending->ready. A crash between
|
||||
// the steps leaves a pending row and maybe an object; both are removed by the
|
||||
// reconciler after the grace period, never an untracked object.
|
||||
if err := s.store.InsertPendingAttachment(r.Context(), att, info.width, info.height); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
apperr.Write(w, id, apperr.NotFound("chat not found or not accessible"))
|
||||
return
|
||||
}
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
putCtx, cancel := context.WithTimeout(r.Context(), s.s3Timeout)
|
||||
err = s.objects.Put(putCtx, att.ObjectKey, data, att.ContentType)
|
||||
cancel()
|
||||
if err != nil {
|
||||
go s.compensateUpload(att, id)
|
||||
s.objectError(w, r, err)
|
||||
return
|
||||
}
|
||||
updated, err := s.store.MarkAttachmentReady(r.Context(), att.ID)
|
||||
if err != nil {
|
||||
go s.compensateUpload(att, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
apperr.Write(w, id, apperr.Unavailable("upload expired, retry"))
|
||||
return
|
||||
}
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
att.UpdatedAt = model.NewTime(updated)
|
||||
writeJSON(w, r, http.StatusCreated, att)
|
||||
}
|
||||
|
||||
// compensateUpload is best effort and starts from the row: the object is removed
|
||||
// only if this call deleted the still-pending row. If the row is already ready
|
||||
// (the UPDATE committed but its reply was lost) the object is kept. Anything left
|
||||
// behind (pending row while PostgreSQL is down, or an object whose removal
|
||||
// failed) is cleaned up by the reconciler after the grace period.
|
||||
func (s *Server) compensateUpload(att *model.Attachment, reqID string) {
|
||||
dctx, dcancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer dcancel()
|
||||
deleted, err := s.store.DeletePendingAttachment(dctx, att.ID)
|
||||
if err != nil || !deleted {
|
||||
if err != nil {
|
||||
s.log.Warn("upload compensation deferred to reconciler", "request_id", reqID,
|
||||
"attachment_id", att.ID, "stage", "delete_row")
|
||||
}
|
||||
return
|
||||
}
|
||||
octx, ocancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer ocancel()
|
||||
if err := s.objects.Remove(octx, att.ObjectKey); err != nil {
|
||||
s.log.Warn("upload compensation deferred to reconciler", "request_id", reqID,
|
||||
"attachment_id", att.ID, "stage", "remove_object")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) attachmentForRequest(w http.ResponseWriter, r *http.Request) (*model.Attachment, bool) {
|
||||
id := requestID(r)
|
||||
attID, err := parseUUID(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("attachment_id must be a UUID"))
|
||||
return nil, false
|
||||
}
|
||||
att, err := s.store.AttachmentForUser(r.Context(), attID, currentUser(r).ID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
apperr.Write(w, id, apperr.NotFound("attachment not found or not accessible"))
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return nil, false
|
||||
}
|
||||
return att, true
|
||||
}
|
||||
|
||||
func (s *Server) getAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
if att, ok := s.attachmentForRequest(w, r); ok {
|
||||
writeJSON(w, r, http.StatusOK, att)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) downloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
id := requestID(r)
|
||||
att, ok := s.attachmentForRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch v := r.URL.Query().Get("variant"); v {
|
||||
case "", "original":
|
||||
case "thumbnail", "crop", "optimized":
|
||||
apperr.Write(w, id, apperr.NotFound("variant not found"))
|
||||
return
|
||||
default:
|
||||
apperr.Write(w, id, apperr.InvalidRequest("unknown variant"))
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), s.s3Timeout)
|
||||
defer cancel()
|
||||
obj, size, err := s.objects.Get(ctx, att.ObjectKey)
|
||||
if objstore.IsNotFound(err) {
|
||||
s.log.Error("attachment object missing in S3", "request_id", id, "attachment_id", att.ID)
|
||||
apperr.Write(w, id, apperr.NotFound("attachment content is not available"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.objectError(w, r, err)
|
||||
return
|
||||
}
|
||||
defer obj.Close()
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", att.ContentType)
|
||||
h.Set("Content-Length", strconv.FormatInt(size, 10))
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Cache-Control", "private, no-store")
|
||||
h.Set("Content-Disposition", "inline; filename*=UTF-8''"+url.PathEscape(att.Filename))
|
||||
h.Set("ETag", `"`+att.SHA256+`"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, obj); err != nil {
|
||||
s.log.Warn("download interrupted", "request_id", id, "attachment_id", att.ID, "error", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/auth"
|
||||
"mtusi-messenger/internal/model"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) storeError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
id := requestID(r)
|
||||
if store.IsUnavailable(err) || errors.Is(err, auth.ErrCacheUnavailable) {
|
||||
s.log.Warn("dependency unavailable", "request_id", id, "error", err.Error())
|
||||
apperr.Write(w, id, apperr.Unavailable("storage temporarily unavailable"))
|
||||
return
|
||||
}
|
||||
s.log.Error("unexpected storage error", "request_id", id, "error", err.Error())
|
||||
apperr.Write(w, id, apperr.Internal("internal error"))
|
||||
}
|
||||
|
||||
func (s *Server) healthLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, r, http.StatusOK, model.Health{Status: "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) healthReady(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.ready.Load() {
|
||||
apperr.Write(w, requestID(r), apperr.Unavailable("service is shutting down"))
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
|
||||
defer cancel()
|
||||
if err := s.store.Ping(ctx); err != nil {
|
||||
apperr.Write(w, requestID(r), apperr.Unavailable("database is not reachable"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, model.Health{Status: "ok"})
|
||||
}
|
||||
|
||||
type createUserReq struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func validPassword(p string) bool {
|
||||
n := utf8.RuneCountInString(p)
|
||||
return utf8.ValidString(p) && n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
func (s *Server) usersRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
id := requestID(r)
|
||||
var req createUserReq
|
||||
if aerr := decodeJSON(w, r, &req); aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("username must match ^[a-z0-9_]{3,32}$"))
|
||||
return
|
||||
}
|
||||
if !validText(req.DisplayName, 100) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("display_name must be 1..100 non-space code points"))
|
||||
return
|
||||
}
|
||||
if !validPassword(req.Password) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("password must be 12..128 code points"))
|
||||
return
|
||||
}
|
||||
hash, err := s.hasher.Hash(r.Context(), req.Password)
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
u, err := s.store.CreateUser(r.Context(), req.Username, req.DisplayName, hash)
|
||||
if errors.Is(err, store.ErrUsernameTaken) {
|
||||
apperr.Write(w, id, apperr.Conflict("username is already taken"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, currentUser(r))
|
||||
}
|
||||
|
||||
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
|
||||
func unauthorizedBasic(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||
apperr.Write(w, requestID(r), apperr.Unauthorized("invalid username or password"))
|
||||
}
|
||||
|
||||
func parseBasic(r *http.Request) (string, string, bool) {
|
||||
scheme, value, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Basic") {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
user, pass, ok := strings.Cut(string(raw), ":")
|
||||
if !ok || !usernameRe.MatchString(user) || !validPassword(pass) {
|
||||
return "", "", false
|
||||
}
|
||||
return user, pass, true
|
||||
}
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
username, password, ok := parseBasic(r)
|
||||
if !ok {
|
||||
unauthorizedBasic(w, r)
|
||||
return
|
||||
}
|
||||
user, hash, err := s.store.Credentials(r.Context(), username)
|
||||
if err != nil && !errors.Is(err, store.ErrNotFound) {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
valid, err := s.hasher.Verify(r.Context(), password, hash)
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
if !valid {
|
||||
unauthorizedBasic(w, r)
|
||||
return
|
||||
}
|
||||
token, expires, err := s.sessions.Create(r.Context(), user)
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, model.Session{
|
||||
Token: token, TokenType: "Bearer", ExpiresAt: model.NewTime(expires), User: *user,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
err := s.sessions.Revoke(r.Context(), currentToken(r))
|
||||
if errors.Is(err, auth.ErrInvalidSession) {
|
||||
unauthorizedBearer(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Request-Id", requestID(r))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type createChatReq struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (s *Server) chatsRoute(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
s.createChat(w, r)
|
||||
case http.MethodGet:
|
||||
s.listChats(w, r)
|
||||
default:
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
var req createChatReq
|
||||
if aerr := decodeJSON(w, r, &req); aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
if !validText(req.Title, 100) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("title must be 1..100 non-space code points"))
|
||||
return
|
||||
}
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("member_ids must contain 1..100 items"))
|
||||
return
|
||||
}
|
||||
seen := make(map[string]bool, len(req.MemberIDs))
|
||||
for _, raw := range req.MemberIDs {
|
||||
uid, err := parseUUID(raw)
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("member_ids must be UUID strings"))
|
||||
return
|
||||
}
|
||||
if seen[uid] {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("duplicate member_id"))
|
||||
return
|
||||
}
|
||||
seen[uid] = true
|
||||
}
|
||||
caller := currentUser(r)
|
||||
if !seen[caller.ID] {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("creator must be included in member_ids"))
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := s.store.CreateChat(r.Context(), caller.ID, req.Title, req.MemberIDs)
|
||||
if errors.Is(err, store.ErrUnknownMember) {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("unknown member_id"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (s *Server) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
caller := currentUser(r)
|
||||
limit, cur, aerr := pagingParams(r, caller.ID)
|
||||
if aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
items, more, err := s.store.ListChats(r.Context(), caller.ID, limit, cur)
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
page := model.Page[*model.Chat]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := store.EncodeCursor(store.Cursor{Scope: caller.ID, TS: last.CreatedAt.Time, ID: last.ID})
|
||||
page.NextCursor = &encoded
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (s *Server) chatRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
methodNotAllowed(w, r)
|
||||
return
|
||||
}
|
||||
id := requestID(r)
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
chat, err := s.store.ChatForUser(r.Context(), chatID, currentUser(r).ID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
apperr.Write(w, id, apperr.NotFound("chat not found or not accessible"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
type createMessageReq struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (s *Server) messagesRoute(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
s.createMessage(w, r)
|
||||
case http.MethodGet:
|
||||
s.listMessages(w, r)
|
||||
default:
|
||||
methodNotAllowed(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) chatAccess(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
id := requestID(r)
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return "", false
|
||||
}
|
||||
ok, err := s.store.IsMember(r.Context(), chatID, currentUser(r).ID)
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return "", false
|
||||
}
|
||||
if !ok {
|
||||
apperr.Write(w, id, apperr.NotFound("chat not found or not accessible"))
|
||||
return "", false
|
||||
}
|
||||
return chatID, true
|
||||
}
|
||||
|
||||
func (s *Server) createMessage(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
chatID, err := parseUUID(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
apperr.Write(w, id, apperr.InvalidRequest("chat_id must be a UUID"))
|
||||
return
|
||||
}
|
||||
// Validation errors are reported only to members; outsiders always get 404.
|
||||
reject := func(aerr *apperr.AppError) {
|
||||
if _, ok := s.chatAccess(w, r); !ok {
|
||||
return
|
||||
}
|
||||
apperr.Write(w, id, aerr)
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyRe.MatchString(key) {
|
||||
reject(apperr.InvalidRequest("Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}"))
|
||||
return
|
||||
}
|
||||
var req createMessageReq
|
||||
if aerr := decodeJSON(w, r, &req); aerr != nil {
|
||||
reject(aerr)
|
||||
return
|
||||
}
|
||||
if req.AttachmentIDs == nil {
|
||||
req.AttachmentIDs = []string{}
|
||||
}
|
||||
if len(req.AttachmentIDs) > 10 {
|
||||
reject(apperr.InvalidRequest("attachment_ids must contain at most 10 items"))
|
||||
return
|
||||
}
|
||||
seen := make(map[string]bool, len(req.AttachmentIDs))
|
||||
for _, raw := range req.AttachmentIDs {
|
||||
aid, err := parseUUID(raw)
|
||||
if err != nil {
|
||||
reject(apperr.InvalidRequest("attachment_ids must be UUID strings"))
|
||||
return
|
||||
}
|
||||
if seen[aid] {
|
||||
reject(apperr.InvalidRequest("duplicate attachment_id"))
|
||||
return
|
||||
}
|
||||
seen[aid] = true
|
||||
}
|
||||
if len(req.AttachmentIDs) == 0 && !validText(req.Text, 4000) {
|
||||
reject(apperr.InvalidRequest("text must be 1..4000 non-space code points when there are no attachments"))
|
||||
return
|
||||
}
|
||||
if !utf8.ValidString(req.Text) || runeLen(req.Text) > 4000 {
|
||||
reject(apperr.InvalidRequest("text must be at most 4000 code points"))
|
||||
return
|
||||
}
|
||||
msg, replayed, err := s.store.AddMessage(r.Context(), chatID, currentUser(r).ID, req.Text, req.AttachmentIDs,
|
||||
key, messageFingerprint(req), s.idempotencyTTL)
|
||||
if errors.Is(err, store.ErrIdempotencyConflict) {
|
||||
apperr.Write(w, id, apperr.Conflict("Idempotency-Key was already used with a different request"))
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
apperr.Write(w, id, apperr.NotFound("chat not found or not accessible"))
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrAttachmentNotFound) {
|
||||
apperr.Write(w, id, apperr.NotFound("attachment not found in this chat"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
if replayed {
|
||||
w.Header().Set("Idempotent-Replayed", "true")
|
||||
}
|
||||
writeJSON(w, r, http.StatusCreated, msg)
|
||||
}
|
||||
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
chatID, ok := s.chatAccess(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cur, aerr := pagingParams(r, chatID)
|
||||
if aerr != nil {
|
||||
apperr.Write(w, id, aerr)
|
||||
return
|
||||
}
|
||||
items, more, err := s.store.ListMessages(r.Context(), chatID, limit, cur)
|
||||
if err != nil {
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
page := model.Page[*model.Message]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := store.EncodeCursor(store.Cursor{Scope: chatID, TS: last.CreatedAt.Time, ID: last.ID})
|
||||
page.NextCursor = &encoded
|
||||
}
|
||||
writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
apperr.Write(w, requestID(r), apperr.NotFound("route not found"))
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
const maxBodyBytes = 1 << 20
|
||||
|
||||
var (
|
||||
usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
)
|
||||
|
||||
func messageFingerprint(req createMessageReq) []byte {
|
||||
b, _ := json.Marshal(req)
|
||||
sum := sha256.Sum256(b)
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func parseUUID(s string) (string, error) {
|
||||
u, err := uuid.Parse(s)
|
||||
if err != nil || u.String() != s {
|
||||
return "", errors.New("invalid uuid")
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func runeLen(s string) int { return utf8.RuneCountInString(s) }
|
||||
|
||||
func validText(s string, max int) bool {
|
||||
n := runeLen(s)
|
||||
return n >= 1 && n <= max && strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) *apperr.AppError {
|
||||
media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if media != "application/json" {
|
||||
return apperr.UnsupportedMedia("Content-Type must be application/json")
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
return apperr.PayloadTooLarge("request body too large")
|
||||
}
|
||||
return apperr.InvalidRequest("malformed JSON body")
|
||||
}
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); err != io.EOF {
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
return apperr.PayloadTooLarge("request body too large")
|
||||
}
|
||||
return apperr.InvalidRequest("malformed JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pagingParams(r *http.Request, scope string) (int, *store.Cursor, *apperr.AppError) {
|
||||
limit := 50
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, apperr.InvalidRequest("limit must be an integer in 1..100")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cur *store.Cursor
|
||||
if v := r.URL.Query().Get("cursor"); v != "" {
|
||||
c, err := store.DecodeCursor(v)
|
||||
if err == nil {
|
||||
_, err = parseUUID(c.ID)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, apperr.InvalidRequest("invalid cursor")
|
||||
}
|
||||
if c.Scope != scope {
|
||||
return 0, nil, apperr.InvalidRequest("cursor does not belong to this resource")
|
||||
}
|
||||
cur = &c
|
||||
}
|
||||
return limit, cur, nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, r *http.Request, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", requestID(r))
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
|
||||
apperr.Write(w, requestID(r), apperr.New(http.StatusMethodNotAllowed, apperr.CodeInvalidRequest, "method not allowed"))
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/auth"
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
ctxRequestID ctxKey = iota
|
||||
ctxUser
|
||||
ctxToken
|
||||
)
|
||||
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxRequestID, id)))
|
||||
})
|
||||
}
|
||||
|
||||
func instanceIDMiddleware(instanceID string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
if id, ok := r.Context().Value(ctxRequestID).(string); ok && id != "" {
|
||||
return id
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func loggingMiddleware(log *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(sw, r)
|
||||
|
||||
log.Info("http",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"dur_ms", time.Since(start).Milliseconds(),
|
||||
"request_id", requestID(r),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
func recoverMiddleware(log *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
log.Error("panic recovered", "path", r.URL.Path, "request_id", requestID(r))
|
||||
apperr.Write(w, requestID(r), apperr.Internal("internal error"))
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Binary transfers get a longer budget than JSON requests.
|
||||
func timeoutMiddleware(d, binary time.Duration, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
limit := d
|
||||
if strings.Contains(r.URL.Path, "/attachments") {
|
||||
limit = binary
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), limit)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
func unauthorizedBearer(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||
apperr.Write(w, requestID(r), apperr.Unauthorized("valid Bearer session token is required"))
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) (string, bool) {
|
||||
scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" || len(token) > 256 {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func (s *Server) auth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
unauthorizedBearer(w, r)
|
||||
return
|
||||
}
|
||||
user, err := s.sessions.Resolve(r.Context(), token)
|
||||
if errors.Is(err, auth.ErrInvalidSession) {
|
||||
unauthorizedBearer(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
s.storeError(w, r, err)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ctxUser, user)
|
||||
ctx = context.WithValue(ctx, ctxToken, token)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func currentUser(r *http.Request) *model.User {
|
||||
return r.Context().Value(ctxUser).(*model.User)
|
||||
}
|
||||
|
||||
func currentToken(r *http.Request) string {
|
||||
return r.Context().Value(ctxToken).(string)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"mtusi-messenger/internal/auth"
|
||||
"mtusi-messenger/internal/objstore"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
store *store.Store
|
||||
objects *objstore.Store
|
||||
sessions *auth.Sessions
|
||||
hasher *auth.Hasher
|
||||
log *slog.Logger
|
||||
ready *atomic.Bool
|
||||
timeout time.Duration
|
||||
|
||||
instanceID string
|
||||
idempotencyTTL time.Duration
|
||||
|
||||
uploadTimeout time.Duration
|
||||
s3Timeout time.Duration
|
||||
maxUpload int64
|
||||
maxPixels int64
|
||||
decodeBudget int64
|
||||
uploadSem *semaphore.Weighted
|
||||
decodeSem *semaphore.Weighted
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
InstanceID string
|
||||
IdempotencyTTL time.Duration
|
||||
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
UploadConcurrency int64
|
||||
DecodeBudgetBytes int64
|
||||
UploadTimeout time.Duration
|
||||
S3Timeout time.Duration
|
||||
}
|
||||
|
||||
func NewServer(st *store.Store, objects *objstore.Store, sessions *auth.Sessions, hasher *auth.Hasher, log *slog.Logger, ready *atomic.Bool, opt Options) *Server {
|
||||
return &Server{store: st, objects: objects, sessions: sessions, hasher: hasher, log: log, ready: ready, timeout: 8 * time.Second,
|
||||
instanceID: opt.InstanceID, idempotencyTTL: opt.IdempotencyTTL,
|
||||
uploadTimeout: opt.UploadTimeout, s3Timeout: opt.S3Timeout,
|
||||
maxUpload: opt.MaxUploadBytes, maxPixels: opt.MaxImagePixels, decodeBudget: opt.DecodeBudgetBytes,
|
||||
uploadSem: semaphore.NewWeighted(opt.UploadConcurrency), decodeSem: semaphore.NewWeighted(opt.DecodeBudgetBytes)}
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/health/live", s.healthLive)
|
||||
mux.HandleFunc("/health/ready", s.healthReady)
|
||||
mux.HandleFunc("/api/v1/users", s.usersRoute)
|
||||
mux.HandleFunc("/api/v1/auth/sessions", s.createSession)
|
||||
mux.HandleFunc("/api/v1/auth/sessions/current", s.auth(s.revokeSession))
|
||||
mux.HandleFunc("/api/v1/users/me", s.auth(s.me))
|
||||
mux.HandleFunc("/api/v1/chats", s.auth(s.chatsRoute))
|
||||
mux.HandleFunc("/api/v1/chats/{chat_id}", s.auth(s.chatRoute))
|
||||
mux.HandleFunc("/api/v1/chats/{chat_id}/messages", s.auth(s.messagesRoute))
|
||||
mux.HandleFunc("/api/v1/chats/{chat_id}/attachments", s.auth(s.uploadAttachment))
|
||||
mux.HandleFunc("/api/v1/attachments/{attachment_id}", s.auth(s.getAttachment))
|
||||
mux.HandleFunc("/api/v1/attachments/{attachment_id}/content", s.auth(s.downloadAttachment))
|
||||
mux.HandleFunc("/", s.notFound)
|
||||
|
||||
var h http.Handler = mux
|
||||
h = timeoutMiddleware(s.timeout, s.uploadTimeout, h)
|
||||
h = recoverMiddleware(s.log, h)
|
||||
h = loggingMiddleware(s.log, h)
|
||||
h = requestIDMiddleware(h)
|
||||
h = instanceIDMiddleware(s.instanceID, h)
|
||||
return h
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Code string
|
||||
|
||||
const (
|
||||
CodeInvalidRequest Code = "invalid_request"
|
||||
CodeUnauthorized Code = "unauthorized"
|
||||
CodeNotFound Code = "not_found"
|
||||
CodeConflict Code = "conflict"
|
||||
CodePayloadTooLarge Code = "payload_too_large"
|
||||
CodeUnsupportedMedia Code = "unsupported_media_type"
|
||||
CodeRateLimited Code = "rate_limited"
|
||||
CodeUnavailable Code = "unavailable"
|
||||
CodeInternal Code = "internal_error"
|
||||
)
|
||||
|
||||
type Body struct {
|
||||
Code Code `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type Envelope struct {
|
||||
Error Body `json:"error"`
|
||||
}
|
||||
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code Code
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string { return e.Msg }
|
||||
|
||||
func New(status int, code Code, msg string) *AppError {
|
||||
return &AppError{Status: status, Code: code, Msg: msg}
|
||||
}
|
||||
|
||||
func InvalidRequest(msg string) *AppError { return New(http.StatusBadRequest, CodeInvalidRequest, msg) }
|
||||
func Unauthorized(msg string) *AppError { return New(http.StatusUnauthorized, CodeUnauthorized, msg) }
|
||||
func NotFound(msg string) *AppError { return New(http.StatusNotFound, CodeNotFound, msg) }
|
||||
func Conflict(msg string) *AppError { return New(http.StatusConflict, CodeConflict, msg) }
|
||||
func PayloadTooLarge(msg string) *AppError {
|
||||
return New(http.StatusRequestEntityTooLarge, CodePayloadTooLarge, msg)
|
||||
}
|
||||
func UnsupportedMedia(msg string) *AppError {
|
||||
return New(http.StatusUnsupportedMediaType, CodeUnsupportedMedia, msg)
|
||||
}
|
||||
func Unavailable(msg string) *AppError {
|
||||
return New(http.StatusServiceUnavailable, CodeUnavailable, msg)
|
||||
}
|
||||
func Internal(msg string) *AppError { return New(http.StatusInternalServerError, CodeInternal, msg) }
|
||||
|
||||
func Write(w http.ResponseWriter, requestID string, err *AppError) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(err.Status)
|
||||
_ = json.NewEncoder(w).Encode(Envelope{Error: Body{Code: err.Code, Message: err.Msg, RequestID: requestID}})
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemoryKiB = 19 * 1024
|
||||
argonTime = 2
|
||||
argonThreads = 1
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
var ErrBadHash = errors.New("malformed password hash")
|
||||
|
||||
type Hasher struct {
|
||||
slots chan struct{}
|
||||
dummy string
|
||||
}
|
||||
|
||||
func NewHasher(concurrency int) *Hasher {
|
||||
h := &Hasher{slots: make(chan struct{}, concurrency)}
|
||||
|
||||
salt := make([]byte, argonSaltLen)
|
||||
_, _ = rand.Read(salt)
|
||||
h.dummy = encode(salt, argon2.IDKey([]byte("dummy-password-x"), salt, argonTime, argonMemoryKiB, argonThreads, argonKeyLen))
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Hasher) acquire(ctx context.Context) error {
|
||||
select {
|
||||
case h.slots <- struct{}{}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hasher) release() { <-h.slots }
|
||||
|
||||
func encode(salt, key []byte) string {
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, argonMemoryKiB, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key))
|
||||
}
|
||||
|
||||
func (h *Hasher) Hash(ctx context.Context, password string) (string, error) {
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer h.release()
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encode(salt, argon2.IDKey([]byte(password), salt, argonTime, argonMemoryKiB, argonThreads, argonKeyLen)), nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(ctx context.Context, password, encoded string) (bool, error) {
|
||||
missing := encoded == ""
|
||||
if missing {
|
||||
encoded = h.dummy
|
||||
}
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, ErrBadHash
|
||||
}
|
||||
var version int
|
||||
var mem uint32
|
||||
var t uint32
|
||||
var p uint8
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return false, ErrBadHash
|
||||
}
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &t, &p); err != nil {
|
||||
return false, ErrBadHash
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, ErrBadHash
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, ErrBadHash
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, t, mem, p, uint32(len(want)))
|
||||
h.release()
|
||||
return subtle.ConstantTimeCompare(got, want) == 1 && !missing, nil
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidSession = errors.New("invalid session")
|
||||
ErrCacheUnavailable = errors.New("session cache unavailable")
|
||||
)
|
||||
|
||||
type SessionCache interface {
|
||||
Get(ctx context.Context, key string) (*CachedSession, error)
|
||||
Set(ctx context.Context, key string, s *CachedSession, ttl time.Duration) error
|
||||
Del(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type CachedSession struct {
|
||||
User model.User `json:"user"`
|
||||
ExpiresAt time.Time `json:"exp"`
|
||||
}
|
||||
|
||||
type Sessions struct {
|
||||
store *store.Store
|
||||
cache SessionCache
|
||||
ttl time.Duration
|
||||
cacheMaxTTL time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewSessions(st *store.Store, cache SessionCache, ttl, cacheMaxTTL time.Duration, log *slog.Logger) *Sessions {
|
||||
return &Sessions{store: st, cache: cache, ttl: ttl, cacheMaxTTL: cacheMaxTTL, log: log}
|
||||
}
|
||||
|
||||
func NewToken() (string, []byte, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
return token, HashToken(token), nil
|
||||
}
|
||||
|
||||
func HashToken(token string) []byte {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func cacheKey(hash []byte) string {
|
||||
return "sess:" + base64.RawURLEncoding.EncodeToString(hash)
|
||||
}
|
||||
|
||||
func (s *Sessions) Create(ctx context.Context, user *model.User) (string, time.Time, error) {
|
||||
token, hash, err := NewToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
expires, err := s.store.CreateSession(ctx, hash, user.ID, s.ttl)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
s.cacheSet(ctx, hash, user, expires)
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
func (s *Sessions) Resolve(ctx context.Context, token string) (*model.User, error) {
|
||||
hash := HashToken(token)
|
||||
if s.cache != nil {
|
||||
cs, err := s.cache.Get(ctx, cacheKey(hash))
|
||||
if err == nil && cs != nil {
|
||||
if time.Now().Before(cs.ExpiresAt) {
|
||||
u := cs.User
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
} else if err != nil {
|
||||
s.log.Debug("session cache get failed, falling back to postgres", "error", err.Error())
|
||||
}
|
||||
}
|
||||
user, expires, err := s.store.SessionUser(ctx, hash)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, ErrInvalidSession
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.cacheSet(ctx, hash, user, expires)
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Sessions) Revoke(ctx context.Context, token string) error {
|
||||
hash := HashToken(token)
|
||||
if s.cache != nil {
|
||||
if err := s.cache.Del(ctx, cacheKey(hash)); err != nil {
|
||||
return ErrCacheUnavailable
|
||||
}
|
||||
}
|
||||
err := s.store.RevokeSession(ctx, hash)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return ErrInvalidSession
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.cache != nil {
|
||||
if err := s.cache.Del(ctx, cacheKey(hash)); err != nil {
|
||||
|
||||
s.log.Warn("session cache delete after revoke failed", "error", err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Sessions) cacheSet(ctx context.Context, hash []byte, user *model.User, expires time.Time) {
|
||||
if s.cache == nil {
|
||||
return
|
||||
}
|
||||
ttl := time.Until(expires)
|
||||
if ttl > s.cacheMaxTTL {
|
||||
ttl = s.cacheMaxTTL
|
||||
}
|
||||
if ttl <= 0 {
|
||||
return
|
||||
}
|
||||
if err := s.cache.Set(ctx, cacheKey(hash), &CachedSession{User: *user, ExpiresAt: expires}, ttl); err != nil {
|
||||
s.log.Debug("session cache set failed", "error", err.Error())
|
||||
}
|
||||
}
|
||||
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/auth"
|
||||
)
|
||||
|
||||
var ErrOpen = errors.New("cache circuit open")
|
||||
|
||||
type Valkey struct {
|
||||
rdb *redis.Client
|
||||
openUntil atomic.Int64
|
||||
cooldown time.Duration
|
||||
}
|
||||
|
||||
func NewValkey(url string) (*Valkey, error) {
|
||||
opt, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opt.DialTimeout = 500 * time.Millisecond
|
||||
opt.ReadTimeout = 300 * time.Millisecond
|
||||
opt.WriteTimeout = 300 * time.Millisecond
|
||||
opt.PoolSize = 10
|
||||
opt.MaxRetries = 0
|
||||
return &Valkey{rdb: redis.NewClient(opt), cooldown: 2 * time.Second}, nil
|
||||
}
|
||||
|
||||
func (v *Valkey) Close() error { return v.rdb.Close() }
|
||||
|
||||
func (v *Valkey) Ping(ctx context.Context) error { return v.guard(v.rdb.Ping(ctx).Err()) }
|
||||
|
||||
func (v *Valkey) open() bool { return time.Now().UnixNano() < v.openUntil.Load() }
|
||||
|
||||
func (v *Valkey) guard(err error) error {
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
v.openUntil.Store(time.Now().Add(v.cooldown).UnixNano())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (v *Valkey) Get(ctx context.Context, key string) (*auth.CachedSession, error) {
|
||||
if v.open() {
|
||||
return nil, ErrOpen
|
||||
}
|
||||
raw, err := v.rdb.Get(ctx, key).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, nil
|
||||
}
|
||||
if err := v.guard(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cs auth.CachedSession
|
||||
if err := json.Unmarshal(raw, &cs); err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
func (v *Valkey) Set(ctx context.Context, key string, s *auth.CachedSession, ttl time.Duration) error {
|
||||
if v.open() {
|
||||
return ErrOpen
|
||||
}
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return v.guard(v.rdb.Set(ctx, key, raw, ttl).Err())
|
||||
}
|
||||
|
||||
func (v *Valkey) Del(ctx context.Context, key string) error {
|
||||
return v.guard(v.rdb.Del(ctx, key).Err())
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFS embed.FS
|
||||
|
||||
const advisoryLockID = 20260202
|
||||
|
||||
type migration struct {
|
||||
version int
|
||||
name string
|
||||
sql string
|
||||
}
|
||||
|
||||
func loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(migrationFS, "migrations")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []migration
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
prefix, _, ok := strings.Cut(name, "_")
|
||||
if !ok || !strings.HasSuffix(name, ".sql") {
|
||||
return nil, fmt.Errorf("bad migration file name %q", name)
|
||||
}
|
||||
v, err := strconv.Atoi(prefix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad migration version in %q", name)
|
||||
}
|
||||
body, err := migrationFS.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, migration{version: v, name: name, sql: string(body)})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].version < out[j].version })
|
||||
for i := 1; i < len(out); i++ {
|
||||
if out[i].version == out[i-1].version {
|
||||
return nil, fmt.Errorf("duplicate migration version %d", out[i].version)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool, log *slog.Logger) error {
|
||||
migs, err := loadMigrations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn, err := pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock($1)", advisoryLockID); err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Exec(context.Background(), "SELECT pg_advisory_unlock($1)", advisoryLockID)
|
||||
|
||||
if _, err := conn.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version integer PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now())`); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
applied := map[int]bool{}
|
||||
rows, err := conn.Query(ctx, "SELECT version FROM schema_migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for rows.Next() {
|
||||
var v int
|
||||
if err := rows.Scan(&v); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
applied[v] = true
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, m := range migs {
|
||||
if applied[m.version] {
|
||||
continue
|
||||
}
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, m.sql); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("migration %s: %w", m.name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "INSERT INTO schema_migrations (version, name) VALUES ($1, $2)", m.version, m.name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("migration applied", "version", m.version, "name", m.name)
|
||||
}
|
||||
log.Info("migrations up to date", "total", len(migs))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds', now()),
|
||||
CONSTRAINT users_username_key UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_by uuid NOT NULL REFERENCES users (id),
|
||||
created_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds', now()),
|
||||
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_position_key UNIQUE (chat_id, position)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds', now()),
|
||||
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
CONSTRAINT messages_sender_member_fk FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds', now()),
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz,
|
||||
CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32),
|
||||
CONSTRAINT sessions_expiry_after_create CHECK (expires_at > created_at)
|
||||
);
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expires_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
idem_key text NOT NULL,
|
||||
request_hash bytea NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE
|
||||
DEFERRABLE INITIALLY DEFERRED,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, chat_id, idem_key),
|
||||
CONSTRAINT message_idempotency_key_format CHECK (idem_key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
CONSTRAINT message_idempotency_hash_len CHECK (octet_length(request_hash) = 32)
|
||||
);
|
||||
CREATE INDEX message_idempotency_created_idx ON message_idempotency (created_at);
|
||||
@@ -0,0 +1,51 @@
|
||||
-- Lab4: attachment metadata lives here, bytes live in the private S3 bucket.
|
||||
-- Text may be empty when a message carries at least one attachment (checked by the API).
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000);
|
||||
|
||||
-- status: pending = intent row written before S3 PUT (not visible through the API);
|
||||
-- ready = object stored and metadata committed.
|
||||
-- missing_at is set by the reconciler when a ready row has no S3 object.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL,
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
width integer NOT NULL,
|
||||
height integer NOT NULL,
|
||||
object_key text NOT NULL,
|
||||
status text NOT NULL,
|
||||
missing_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds', now()),
|
||||
updated_at timestamptz NOT NULL DEFAULT date_trunc('milliseconds', now()),
|
||||
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
|
||||
CONSTRAINT attachments_chat_id_key UNIQUE (chat_id, id),
|
||||
CONSTRAINT attachments_owner_member_fk FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE,
|
||||
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT attachments_pixels CHECK (width > 0 AND height > 0 AND width::bigint * height <= 40000000),
|
||||
CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready'))
|
||||
);
|
||||
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
|
||||
|
||||
-- (chat_id, attachment_id) -> attachments (chat_id, id): the database itself refuses
|
||||
-- to link a file of another chat to a message.
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE
|
||||
DEFERRABLE INITIALLY DEFERRED,
|
||||
chat_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
position smallint NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position),
|
||||
CONSTRAINT message_attachments_position CHECK (position BETWEEN 0 AND 9),
|
||||
CONSTRAINT message_attachments_same_chat_fk FOREIGN KEY (chat_id, attachment_id)
|
||||
REFERENCES attachments (chat_id, id)
|
||||
);
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
@@ -0,0 +1,31 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type PoolOptions struct {
|
||||
MaxConns int32
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, url string, opt PoolOptions) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.MaxConns = opt.MaxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 15 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
rp := cfg.ConnConfig.RuntimeParams
|
||||
rp["application_name"] = "mtusi-messenger"
|
||||
rp["statement_timeout"] = "5000"
|
||||
rp["lock_timeout"] = "2000"
|
||||
rp["idle_in_transaction_session_timeout"] = "10000"
|
||||
return pgxpool.NewWithConfig(ctx, cfg)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Time struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func NewTime(t time.Time) Time { return Time{Time: t} }
|
||||
|
||||
func (t Time) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + t.UTC().Format("2006-01-02T15:04:05.000Z") + `"`), nil
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []Variant `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
UpdatedAt Time `json:"updated_at"`
|
||||
|
||||
ObjectKey string `json:"-"`
|
||||
Missing bool `json:"-"`
|
||||
}
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type Health struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package objstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
c *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
func New(cfg Config) (*Store, error) {
|
||||
u, err := url.Parse(cfg.Endpoint)
|
||||
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return nil, errors.New("S3_ENDPOINT must be http(s)://host:port")
|
||||
}
|
||||
if cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
|
||||
return nil, errors.New("S3 bucket and credentials are required")
|
||||
}
|
||||
// The SDK retries 10 times with backoff by default; a dead S3 must turn into a
|
||||
// fast 503 instead (the client may retry the upload itself).
|
||||
minio.MaxRetry = 1
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
c, err := minio.New(u.Host, &minio.Options{
|
||||
Transport: transport,
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: u.Scheme == "https",
|
||||
Region: cfg.Region,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{c: c, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Bucket() string { return s.bucket }
|
||||
|
||||
// Ping checks that the bucket is reachable with the configured credentials.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ok, err := s.c.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("bucket %q does not exist", s.bucket)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsureBucket creates the bucket if it is absent; safe to repeat.
|
||||
func (s *Store) EnsureBucket(ctx context.Context, region string) (bool, error) {
|
||||
ok, err := s.c.BucketExists(ctx, s.bucket)
|
||||
if err != nil || ok {
|
||||
return false, err
|
||||
}
|
||||
if err := s.c.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: region}); err != nil {
|
||||
if code := minio.ToErrorResponse(err).Code; code == "BucketAlreadyOwnedByYou" || code == "BucketAlreadyExists" {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) Put(ctx context.Context, key string, data []byte, contentType string) error {
|
||||
_, err := s.c.PutObject(ctx, s.bucket, key, bytes.NewReader(data), int64(len(data)),
|
||||
minio.PutObjectOptions{ContentType: contentType, SendContentMd5: true, DisableMultipart: true})
|
||||
return err
|
||||
}
|
||||
|
||||
// Get returns a stream of the object; Stat is called first so that a missing
|
||||
// object or an unavailable S3 is reported before any response byte is written.
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
|
||||
obj, err := s.c.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
info, err := obj.Stat()
|
||||
if err != nil {
|
||||
obj.Close()
|
||||
return nil, 0, err
|
||||
}
|
||||
return obj, info.Size, nil
|
||||
}
|
||||
|
||||
func (s *Store) Stat(ctx context.Context, key string) (Object, error) {
|
||||
info, err := s.c.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return Object{}, err
|
||||
}
|
||||
return Object{Key: info.Key, Size: info.Size, LastModified: info.LastModified}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Remove(ctx context.Context, key string) error {
|
||||
return s.c.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, prefix string, fn func(Object) error) error {
|
||||
for info := range s.c.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if info.Err != nil {
|
||||
return info.Err
|
||||
}
|
||||
if err := fn(Object{Key: info.Key, Size: info.Size, LastModified: info.LastModified}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func IsNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
// Package reconcile compares attachment metadata in PostgreSQL with objects in
|
||||
// the S3 bucket and repairs what can be repaired safely.
|
||||
//
|
||||
// Order matters: S3 is listed first, the database is read second. An upload
|
||||
// writes its pending row before the PUT, so an object seen in the listing
|
||||
// already has its row when the database is read. Every destructive decision is
|
||||
// re-checked against the source of truth right before it is applied.
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/objstore"
|
||||
"mtusi-messenger/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
Prefix = "attachments/"
|
||||
lockID = 20260404
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Apply bool
|
||||
Grace time.Duration
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
Kind string `json:"kind"`
|
||||
Key string `json:"key,omitempty"`
|
||||
ID string `json:"attachment_id,omitempty"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Mode string `json:"mode"`
|
||||
GraceSeconds int64 `json:"grace_seconds"`
|
||||
ObjectsScanned int `json:"objects_scanned"`
|
||||
RowsScanned int `json:"rows_scanned"`
|
||||
OrphanObjects int `json:"orphan_objects"`
|
||||
FreshSkipped int `json:"fresh_skipped"`
|
||||
StalePending int `json:"stale_pending"`
|
||||
MissingObjects int `json:"missing_objects"`
|
||||
SizeMismatch int `json:"size_mismatch"`
|
||||
Recovered int `json:"recovered"`
|
||||
Fixed int `json:"fixed"`
|
||||
Errors int `json:"errors"`
|
||||
ListMS int64 `json:"list_ms"`
|
||||
DBMS int64 `json:"db_ms"`
|
||||
TotalMS int64 `json:"total_ms"`
|
||||
Items []Item `json:"items"`
|
||||
Truncated bool `json:"items_truncated"`
|
||||
PerObjectUS float64 `json:"per_object_us"`
|
||||
}
|
||||
|
||||
var ErrLocked = errors.New("another reconciler run holds the lock")
|
||||
|
||||
type Reconciler struct {
|
||||
db *store.Store
|
||||
s3 *objstore.Store
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func New(db *store.Store, s3 *objstore.Store, log *slog.Logger) *Reconciler {
|
||||
return &Reconciler{db: db, s3: s3, log: log}
|
||||
}
|
||||
|
||||
func (r *Reconciler) note(rep *Report, it Item) {
|
||||
if len(rep.Items) < 200 {
|
||||
rep.Items = append(rep.Items, it)
|
||||
} else {
|
||||
rep.Truncated = true
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reconciler) Run(ctx context.Context, opt Options) (*Report, error) {
|
||||
if opt.Now == nil {
|
||||
opt.Now = time.Now
|
||||
}
|
||||
unlock, ok, err := r.db.TryLock(ctx, lockID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrLocked
|
||||
}
|
||||
defer unlock()
|
||||
|
||||
rep := &Report{Mode: "dry-run", GraceSeconds: int64(opt.Grace.Seconds()), Items: []Item{}}
|
||||
if opt.Apply {
|
||||
rep.Mode = "apply"
|
||||
}
|
||||
start := time.Now()
|
||||
cutoff := opt.Now().Add(-opt.Grace)
|
||||
|
||||
objects := make(map[string]objstore.Object)
|
||||
if err := r.s3.List(ctx, Prefix, func(o objstore.Object) error {
|
||||
objects[o.Key] = o
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rep.ObjectsScanned = len(objects)
|
||||
rep.ListMS = time.Since(start).Milliseconds()
|
||||
|
||||
dbStart := time.Now()
|
||||
known := make(map[string]bool, len(objects))
|
||||
var refs []store.AttachmentRef
|
||||
if err := r.db.EachAttachmentRef(ctx, func(a store.AttachmentRef) error {
|
||||
known[a.ObjectKey] = true
|
||||
rep.RowsScanned++
|
||||
obj, present := objects[a.ObjectKey]
|
||||
switch {
|
||||
case a.Status == "pending" && a.CreatedAt.Before(cutoff):
|
||||
refs = append(refs, a)
|
||||
case a.Status == "ready" && !present && !a.Missing && a.CreatedAt.Before(cutoff):
|
||||
refs = append(refs, a)
|
||||
case a.Status == "ready" && present && a.Missing:
|
||||
refs = append(refs, a)
|
||||
case a.Status == "ready" && present && obj.Size != a.SizeBytes:
|
||||
rep.SizeMismatch++
|
||||
r.note(rep, Item{Kind: "size_mismatch", Key: a.ObjectKey, ID: a.ID, Action: "report only"})
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rep.DBMS = time.Since(dbStart).Milliseconds()
|
||||
|
||||
for _, a := range refs {
|
||||
_, present := objects[a.ObjectKey]
|
||||
switch {
|
||||
case a.Status == "pending":
|
||||
r.stalePending(ctx, rep, a, opt.Apply)
|
||||
case !present:
|
||||
r.missing(ctx, rep, a, opt.Apply)
|
||||
default:
|
||||
r.recovered(ctx, rep, a, opt.Apply)
|
||||
}
|
||||
}
|
||||
|
||||
for key, o := range objects {
|
||||
if known[key] {
|
||||
continue
|
||||
}
|
||||
if !o.LastModified.Before(cutoff) {
|
||||
rep.FreshSkipped++
|
||||
r.note(rep, Item{Kind: "orphan_object", Key: key, Action: "skip: younger than grace"})
|
||||
continue
|
||||
}
|
||||
r.orphan(ctx, rep, key, opt.Apply)
|
||||
}
|
||||
|
||||
rep.TotalMS = time.Since(start).Milliseconds()
|
||||
if rep.ObjectsScanned > 0 {
|
||||
rep.PerObjectUS = float64(time.Since(start).Microseconds()) / float64(rep.ObjectsScanned)
|
||||
}
|
||||
return rep, nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) fail(rep *Report, it Item, err error) {
|
||||
rep.Errors++
|
||||
it.Action = "error: " + strings.SplitN(err.Error(), "\n", 2)[0]
|
||||
r.note(rep, it)
|
||||
}
|
||||
|
||||
// Stale pending row: the upload never reached "ready", so no message can
|
||||
// reference it. The row is deleted first (conditionally), then the object.
|
||||
func (r *Reconciler) stalePending(ctx context.Context, rep *Report, a store.AttachmentRef, apply bool) {
|
||||
rep.StalePending++
|
||||
it := Item{Kind: "stale_pending", Key: a.ObjectKey, ID: a.ID, Action: "would delete row and object"}
|
||||
if !apply {
|
||||
r.note(rep, it)
|
||||
return
|
||||
}
|
||||
deleted, err := r.db.DeletePendingAttachment(ctx, a.ID)
|
||||
if err != nil {
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
if !deleted {
|
||||
it.Action = "skip: row changed concurrently"
|
||||
r.note(rep, it)
|
||||
return
|
||||
}
|
||||
if err := r.s3.Remove(ctx, a.ObjectKey); err != nil {
|
||||
// The object becomes an orphan and is removed by the next run.
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
rep.Fixed++
|
||||
it.Action = "deleted row and object"
|
||||
r.note(rep, it)
|
||||
}
|
||||
|
||||
// Orphan object: no metadata row. The DB is re-checked right before deletion.
|
||||
func (r *Reconciler) orphan(ctx context.Context, rep *Report, key string, apply bool) {
|
||||
rep.OrphanObjects++
|
||||
it := Item{Kind: "orphan_object", Key: key, Action: "would delete object"}
|
||||
if !apply {
|
||||
r.note(rep, it)
|
||||
return
|
||||
}
|
||||
known, err := r.db.ObjectKeyKnown(ctx, key)
|
||||
if err != nil {
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
if known {
|
||||
it.Action = "skip: row appeared concurrently"
|
||||
r.note(rep, it)
|
||||
return
|
||||
}
|
||||
if err := r.s3.Remove(ctx, key); err != nil {
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
rep.Fixed++
|
||||
it.Action = "deleted object"
|
||||
r.note(rep, it)
|
||||
}
|
||||
|
||||
// Missing object of a ready row: bytes cannot be restored, metadata of a
|
||||
// possibly referenced attachment is never deleted. The row is marked so that
|
||||
// operators see it; StatObject confirms the absence first.
|
||||
func (r *Reconciler) missing(ctx context.Context, rep *Report, a store.AttachmentRef, apply bool) {
|
||||
_, err := r.s3.Stat(ctx, a.ObjectKey)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
it := Item{Kind: "missing_object", Key: a.ObjectKey, ID: a.ID, Action: "would mark missing (metadata kept)"}
|
||||
if !objstore.IsNotFound(err) {
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
rep.MissingObjects++
|
||||
if !apply {
|
||||
r.note(rep, it)
|
||||
return
|
||||
}
|
||||
if err := r.db.SetAttachmentMissing(ctx, a.ID, true); err != nil {
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
rep.Fixed++
|
||||
it.Action = "marked missing (metadata kept)"
|
||||
r.note(rep, it)
|
||||
}
|
||||
|
||||
func (r *Reconciler) recovered(ctx context.Context, rep *Report, a store.AttachmentRef, apply bool) {
|
||||
rep.Recovered++
|
||||
it := Item{Kind: "recovered_object", Key: a.ObjectKey, ID: a.ID, Action: "would clear missing mark"}
|
||||
if !apply {
|
||||
r.note(rep, it)
|
||||
return
|
||||
}
|
||||
if err := r.db.SetAttachmentMissing(ctx, a.ID, false); err != nil {
|
||||
r.fail(rep, it, err)
|
||||
return
|
||||
}
|
||||
rep.Fixed++
|
||||
it.Action = "cleared missing mark"
|
||||
r.note(rep, it)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
const attachmentColumns = `a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.object_key, a.missing_at IS NOT NULL, a.created_at, a.updated_at`
|
||||
|
||||
func scanAttachment(row pgx.Row) (*model.Attachment, error) {
|
||||
a := &model.Attachment{Status: "ready", Variants: []model.Variant{}}
|
||||
var created, updated time.Time
|
||||
err := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
|
||||
&a.ObjectKey, &a.Missing, &created, &updated)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.CreatedAt, a.UpdatedAt = utc(created), utc(updated)
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// InsertPendingAttachment records the intent before the S3 PUT. A pending row is
|
||||
// invisible to the API; if the upload never completes, the reconciler removes
|
||||
// the row and the object after the grace period.
|
||||
func (s *Store) InsertPendingAttachment(ctx context.Context, a *model.Attachment, width, height int) error {
|
||||
var created time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'pending')
|
||||
RETURNING created_at`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256,
|
||||
width, height, a.ObjectKey).Scan(&created)
|
||||
if pgCode(err) == "23503" {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.CreatedAt = utc(created)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkAttachmentReady succeeds only while the row is still pending: if the
|
||||
// reconciler already removed a stale intent, the upload must not report 201.
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, id string) (time.Time, error) {
|
||||
var updated time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
UPDATE attachments SET status = 'ready', updated_at = date_trunc('milliseconds', now())
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
RETURNING updated_at`, id).Scan(&updated)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return updated.UTC(), nil
|
||||
}
|
||||
|
||||
// DeletePendingAttachment removes an intent row that never became ready.
|
||||
func (s *Store) DeletePendingAttachment(ctx context.Context, id string) (bool, error) {
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
// AttachmentForUser returns a ready attachment only to a member of its chat.
|
||||
func (s *Store) AttachmentForUser(ctx context.Context, id, userID string) (*model.Attachment, error) {
|
||||
a, err := scanAttachment(s.pool.QueryRow(ctx, `
|
||||
SELECT `+attachmentColumns+`
|
||||
FROM attachments a
|
||||
WHERE a.id = $1 AND a.status = 'ready'
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2)`,
|
||||
id, userID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// AttachmentRef is the reconciler's view of one metadata row.
|
||||
type AttachmentRef struct {
|
||||
ID string
|
||||
ObjectKey string
|
||||
Status string
|
||||
SizeBytes int64
|
||||
Missing bool
|
||||
CreatedAt time.Time
|
||||
Referenced bool
|
||||
}
|
||||
|
||||
func (s *Store) EachAttachmentRef(ctx context.Context, fn func(AttachmentRef) error) error {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT a.id, a.object_key, a.status, a.size_bytes, a.missing_at IS NOT NULL, a.created_at,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
|
||||
FROM attachments a`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r AttachmentRef
|
||||
if err := rows.Scan(&r.ID, &r.ObjectKey, &r.Status, &r.SizeBytes, &r.Missing, &r.CreatedAt, &r.Referenced); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fn(r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ObjectKeyKnown(ctx context.Context, key string) (bool, error) {
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (s *Store) SetAttachmentMissing(ctx context.Context, id string, missing bool) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET missing_at = CASE WHEN $2 THEN COALESCE(missing_at, now()) END
|
||||
WHERE id = $1 AND status = 'ready'`, id, missing)
|
||||
return err
|
||||
}
|
||||
|
||||
// TryLock takes a session-level advisory lock on a dedicated connection so that
|
||||
// only one reconciler pass runs at a time. The returned func releases it.
|
||||
func (s *Store) TryLock(ctx context.Context, id int64) (func(), bool, error) {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
var ok bool
|
||||
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, id).Scan(&ok); err != nil || !ok {
|
||||
conn.Release()
|
||||
return nil, false, err
|
||||
}
|
||||
return func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, id)
|
||||
conn.Release()
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Cursor struct {
|
||||
Scope string `json:"s"`
|
||||
TS time.Time `json:"t"`
|
||||
ID string `json:"i"`
|
||||
}
|
||||
|
||||
func EncodeCursor(c Cursor) string {
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func DecodeCursor(s string) (Cursor, error) {
|
||||
var c Cursor
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return c, ErrInvalidCursor
|
||||
}
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
return c, ErrInvalidCursor
|
||||
}
|
||||
if c.Scope == "" || c.ID == "" || c.TS.IsZero() {
|
||||
return c, ErrInvalidCursor
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
ErrUnknownMember = errors.New("unknown member")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) }
|
||||
|
||||
func IsUnavailable(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || pgconn.Timeout(err) {
|
||||
return true
|
||||
}
|
||||
var connErr *pgconn.ConnectError
|
||||
if errors.As(err, &connErr) {
|
||||
return true
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return true
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
|
||||
switch {
|
||||
case pgErr.Code == "57P01", pgErr.Code == "57P03", pgErr.Code == "57014", pgErr.Code == "55P03",
|
||||
len(pgErr.Code) == 5 && pgErr.Code[:2] == "08":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return errors.Is(err, pgx.ErrTxClosed) || errors.Is(err, net.ErrClosed)
|
||||
}
|
||||
|
||||
func pgCode(err error) string {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func utc(t time.Time) model.Time { return model.NewTime(t.UTC()) }
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (*model.User, error) {
|
||||
u := &model.User{ID: uuid.NewString(), Username: username, DisplayName: displayName}
|
||||
var created time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4) RETURNING created_at`,
|
||||
u.ID, username, displayName, passwordHash).Scan(&created)
|
||||
if pgCode(err) == "23505" {
|
||||
return nil, ErrUsernameTaken
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.CreatedAt = utc(created)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Store) Credentials(ctx context.Context, username string) (*model.User, string, error) {
|
||||
u := &model.User{}
|
||||
var created time.Time
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1`,
|
||||
username).Scan(&u.ID, &u.Username, &u.DisplayName, &created, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
u.CreatedAt = utc(created)
|
||||
return u, hash, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateSession(ctx context.Context, tokenHash []byte, userID string, ttl time.Duration) (time.Time, error) {
|
||||
var expires time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, date_trunc('milliseconds', now()) + make_interval(secs => $3))
|
||||
RETURNING expires_at`,
|
||||
tokenHash, userID, ttl.Seconds()).Scan(&expires)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return expires.UTC(), nil
|
||||
}
|
||||
|
||||
func (s *Store) SessionUser(ctx context.Context, tokenHash []byte) (*model.User, time.Time, error) {
|
||||
u := &model.User{}
|
||||
var created, expires time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > now()`,
|
||||
tokenHash).Scan(&u.ID, &u.Username, &u.DisplayName, &created, &expires)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
u.CreatedAt = utc(created)
|
||||
return u, expires.UTC(), nil
|
||||
}
|
||||
|
||||
func (s *Store) RevokeSession(ctx context.Context, tokenHash []byte) error {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`UPDATE sessions SET revoked_at = now()
|
||||
WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > now()`, tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) PurgeSessions(ctx context.Context, olderThan time.Duration) (int64, error) {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM sessions
|
||||
WHERE expires_at < now() - make_interval(secs => $1)
|
||||
OR revoked_at < now() - make_interval(secs => $1)`, olderThan.Seconds())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, creatorID, title string, memberIDs []string) (*model.Chat, error) {
|
||||
c := &model.Chat{ID: uuid.NewString(), Title: title, MemberIDs: append([]string(nil), memberIDs...)}
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
var created time.Time
|
||||
if err := tx.QueryRow(ctx,
|
||||
`INSERT INTO chats (id, title, created_by) VALUES ($1, $2, $3) RETURNING created_at`,
|
||||
c.ID, title, creatorID).Scan(&created); err != nil {
|
||||
return err
|
||||
}
|
||||
c.CreatedAt = utc(created)
|
||||
_, err := tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT $1, m.user_id, m.ord - 1
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS m(user_id, ord)`,
|
||||
c.ID, memberIDs)
|
||||
return err
|
||||
})
|
||||
if pgCode(err) == "23503" {
|
||||
return nil, ErrUnknownMember
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (*model.Chat, error) {
|
||||
c := &model.Chat{}
|
||||
var created time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id::text ORDER BY m.position)
|
||||
FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members x WHERE x.chat_id = c.id AND x.user_id = $2)
|
||||
GROUP BY c.id`,
|
||||
chatID, userID).Scan(&c.ID, &c.Title, &created, &c.MemberIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.CreatedAt = utc(created)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cur *Cursor) ([]*model.Chat, bool, error) {
|
||||
var ts *time.Time
|
||||
var cid *string
|
||||
if cur != nil {
|
||||
ts, cid = &cur.TS, &cur.ID
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT c.id, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id::text ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id)
|
||||
FROM chat_members me JOIN chats c ON c.id = me.chat_id
|
||||
WHERE me.user_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`,
|
||||
userID, ts, cid, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]*model.Chat, 0, limit+1)
|
||||
for rows.Next() {
|
||||
c := &model.Chat{}
|
||||
var created time.Time
|
||||
if err := rows.Scan(&c.ID, &c.Title, &created, &c.MemberIDs); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
c.CreatedAt = utc(created)
|
||||
out = append(out, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
more := len(out) > limit
|
||||
if more {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
|
||||
var (
|
||||
ErrIdempotencyConflict = errors.New("idempotency key reused with different body")
|
||||
ErrAttachmentNotFound = errors.New("attachment not found in chat")
|
||||
)
|
||||
|
||||
// AddMessage inserts the message, its idempotency record and attachment links in
|
||||
// one statement. Attachments must be ready and belong to the same chat; the
|
||||
// composite FK on message_attachments enforces the chat boundary in the DB too.
|
||||
func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, key string, reqHash []byte, ttl time.Duration) (*model.Message, bool, error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
newID := uuid.NewString()
|
||||
var member, attachmentsOK bool
|
||||
var created *time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
WITH member AS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $1
|
||||
), att AS (
|
||||
SELECT count(*) = cardinality($8::uuid[]) AS ok
|
||||
FROM attachments
|
||||
WHERE chat_id = $2 AND id = ANY($8::uuid[]) AND status = 'ready'
|
||||
), k AS (
|
||||
INSERT INTO message_idempotency (user_id, chat_id, idem_key, request_hash, message_id)
|
||||
SELECT $1, $2, $3, $4, $5 FROM member, att WHERE att.ok
|
||||
ON CONFLICT (user_id, chat_id, idem_key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = now()
|
||||
WHERE message_idempotency.created_at < now() - make_interval(secs => $7)
|
||||
RETURNING message_id
|
||||
), m AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
SELECT $5, $2, $1, $6 FROM k
|
||||
RETURNING created_at
|
||||
), ma AS (
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
SELECT $5, $2, a.id, a.ord - 1
|
||||
FROM unnest($8::uuid[]) WITH ORDINALITY AS a(id, ord)
|
||||
WHERE EXISTS (SELECT 1 FROM m)
|
||||
)
|
||||
SELECT EXISTS (SELECT 1 FROM member), (SELECT ok FROM att), (SELECT created_at FROM m)`,
|
||||
senderID, chatID, key, reqHash, newID, text, ttl.Seconds(), attachmentIDs).Scan(&member, &attachmentsOK, &created)
|
||||
if pgCode(err) == "23503" {
|
||||
return nil, false, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !member {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
if !attachmentsOK {
|
||||
return nil, false, ErrAttachmentNotFound
|
||||
}
|
||||
if created != nil {
|
||||
return &model.Message{ID: newID, ChatID: chatID, SenderID: senderID, Text: text,
|
||||
CreatedAt: utc(*created), AttachmentIDs: attachmentIDs}, false, nil
|
||||
}
|
||||
var stored []byte
|
||||
var at time.Time
|
||||
m := &model.Message{ChatID: chatID}
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
SELECT i.request_hash, m.id, m.sender_id, m.text, m.created_at,
|
||||
`+attachmentIDsSQL+`
|
||||
FROM message_idempotency i JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1 AND i.chat_id = $2 AND i.idem_key = $3
|
||||
AND i.created_at >= now() - make_interval(secs => $4)`,
|
||||
senderID, chatID, key, ttl.Seconds()).Scan(&stored, &m.ID, &m.SenderID, &m.Text, &at, &m.AttachmentIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !bytes.Equal(stored, reqHash) {
|
||||
return nil, false, ErrIdempotencyConflict
|
||||
}
|
||||
m.CreatedAt = utc(at)
|
||||
return m, true, nil
|
||||
}
|
||||
return nil, false, errors.New("idempotency record kept changing")
|
||||
}
|
||||
|
||||
const attachmentIDsSQL = `COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
|
||||
FROM message_attachments ma WHERE ma.message_id = m.id), '{}')`
|
||||
|
||||
func (s *Store) PurgeIdempotency(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM message_idempotency WHERE created_at < now() - make_interval(secs => $1)`, ttl.Seconds())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, cur *Cursor) ([]*model.Message, bool, error) {
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if cur == nil {
|
||||
rows, err = s.pool.Query(ctx,
|
||||
`SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, `+attachmentIDsSQL+`
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id LIMIT $2`, chatID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx,
|
||||
`SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, `+attachmentIDsSQL+`
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3::uuid)
|
||||
ORDER BY m.created_at, m.id LIMIT $4`, chatID, cur.TS, cur.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]*model.Message, 0, limit+1)
|
||||
for rows.Next() {
|
||||
m := &model.Message{}
|
||||
var created time.Time
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
m.CreatedAt = utc(created)
|
||||
out = append(out, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
more := len(out) > limit
|
||||
if more {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
Reference in New Issue
Block a user