Instrument durable messenger with OTel, provision Grafana and prove SLO incident detection

This commit is contained in:
2026-11-21 00:58:18 +03:00
parent 470d9d6f1e
commit bd2c7f7b37
89 changed files with 15839 additions and 25 deletions
+105
View File
@@ -0,0 +1,105 @@
package database
import (
"context"
"crypto/sha256"
"embed"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi/messenger/internal/telemetry"
"os"
"sort"
"strconv"
"time"
)
//go:embed migrations/*.sql
var migrations embed.FS
func Open(ctx context.Context, url string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("invalid database configuration")
}
cfg.MaxConns = 10
if v := os.Getenv("DB_POOL_MAX"); v != "" {
n, e := strconv.Atoi(v)
if e != nil || n < 1 || n > 64 {
return nil, fmt.Errorf("DB_POOL_MAX must be 1..64")
}
cfg.MaxConns = int32(n)
}
cfg.ConnConfig.Tracer = telemetry.DBTracer{}
cfg.MinConns = 0
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("cannot create database pool")
}
if err = pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("database unavailable")
}
return pool, nil
}
// All migrations and the version ledger commit together. An advisory lock also
// serializes bootstrap across API instances; edited applied migrations fail.
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026002)"); err != nil {
return err
}
if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
return err
}
entries, err := migrations.ReadDir("migrations")
if err != nil {
return err
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
for _, entry := range entries {
body, err := migrations.ReadFile("migrations/" + entry.Name())
if err != nil {
return err
}
checksum := fmt.Sprintf("%x", sha256.Sum256(body))
var stored string
rows, err := tx.Query(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name())
if err != nil {
return err
}
found := rows.Next()
if found {
err = rows.Scan(&stored)
}
if err == nil {
err = rows.Err()
}
rows.Close()
if err != nil {
return err
}
if found {
if stored != checksum {
return fmt.Errorf("applied migration changed: %s", entry.Name())
}
continue
}
if _, err = tx.Exec(ctx, string(body)); err != nil {
return err
}
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum); err != nil {
return err
}
}
return tx.Commit(ctx)
}
@@ -0,0 +1,36 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
last_message_at timestamptz NOT NULL DEFAULT '-infinity'
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id),
user_id uuid NOT NULL REFERENCES users(id),
PRIMARY KEY (chat_id, user_id)
);
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 REFERENCES chats(id),
sender_id uuid NOT NULL,
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
created_at timestamptz NOT NULL,
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
);
CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id);
CREATE INDEX chats_order_idx ON chats(created_at, id);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
user_id uuid NOT NULL REFERENCES users(id),
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
@@ -0,0 +1,10 @@
CREATE TABLE message_requests (
user_id uuid NOT NULL REFERENCES users(id),
chat_id uuid NOT NULL REFERENCES chats(id),
key text NOT NULL,
body_hash bytea NOT NULL,
response jsonb NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY(user_id,chat_id,key)
);
CREATE INDEX message_requests_expiry_idx ON message_requests(expires_at);
@@ -0,0 +1,29 @@
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CHECK(char_length(text) BETWEEN 0 AND 4000);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
owner_id uuid NOT NULL REFERENCES users(id),
filename text NOT NULL,
object_key text NOT NULL UNIQUE,
content_type text NOT NULL CHECK(content_type IN ('image/png','image/jpeg')),
size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL CHECK(sha256 ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages(id),
attachment_id uuid NOT NULL REFERENCES attachments(id),
position integer NOT NULL CHECK(position BETWEEN 0 AND 9),
PRIMARY KEY(message_id,attachment_id),
UNIQUE(message_id,position)
);
-- Durable upload journal is committed BEFORE PUT, so incomplete work remains
-- attributable after process termination. Final metadata + journal deletion
-- share one PG transaction, under the same per-key lock as the reconciler.
CREATE TABLE upload_intents (
object_key text PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
@@ -0,0 +1,30 @@
ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK(status IN ('queued','processing','ready','failed'));
ALTER TABLE attachments ADD COLUMN error_code text;
ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]';
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK(pipeline_version>0);
ALTER TABLE attachments ADD COLUMN staging_key text;
CREATE TABLE pipeline_jobs (
job_id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments(id),
pipeline_version integer NOT NULL CHECK(pipeline_version>0),
attempt integer NOT NULL DEFAULT 0,
lease_token uuid,
lease_until timestamptz,
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
finished_at timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
traceparent text NOT NULL DEFAULT '',
tracestate text NOT NULL DEFAULT '',
UNIQUE(attachment_id,pipeline_version)
);
CREATE INDEX pipeline_dispatch_idx ON pipeline_jobs(next_attempt_at) WHERE finished_at IS NULL;
CREATE TABLE pipeline_audit (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES pipeline_jobs(job_id),
event text NOT NULL,
attempt integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
-- This is the durable, queryable failed registry (DLQ equivalent).
CREATE VIEW failed_jobs AS SELECT j.job_id,j.attachment_id,j.pipeline_version,j.attempt,a.error_code,j.finished_at FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE a.status='failed';
@@ -0,0 +1,2 @@
ALTER TABLE pipeline_jobs ADD COLUMN ready_at timestamptz;
CREATE INDEX pipeline_jobs_created_idx ON pipeline_jobs(created_at);
+315
View File
@@ -0,0 +1,315 @@
package messenger
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"mtusi/messenger/internal/telemetry"
"net/http"
"net/url"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
const maxUpload = 10 << 20
const maxPixels = 40000000
type ObjectStore struct {
Client *minio.Client
Bucket string
}
func NewObjectStore(endpoint, bucket, access, secret string) (*ObjectStore, error) {
u, e := url.Parse(endpoint)
if e != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return nil, fmt.Errorf("invalid S3 endpoint")
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxConnsPerHost = 8
transport.ResponseHeaderTimeout = 5 * time.Second
client, e := minio.New(u.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https", Region: "us-east-1", Transport: telemetry.Transport(transport), MaxRetries: 1})
if e != nil {
return nil, fmt.Errorf("invalid S3 configuration")
}
return &ObjectStore{client, bucket}, nil
}
func (o *ObjectStore) Ready(ctx context.Context) bool {
ok, e := o.Client.BucketExists(ctx, o.Bucket)
return e == nil && ok
}
func (s *Server) SetObjectStore(o *ObjectStore) { s.objects = o; s.uploads = make(chan struct{}, 1) }
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"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
const attachmentColumns = `a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at,a.object_key,a.status,a.error_code,a.variants`
func scanAttachment(row scanner) (Attachment, string, error) {
a := Attachment{Status: "ready", Variants: []Variant{}}
var c, u time.Time
var key string
var variants []byte
e := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.Size, &a.SHA256, &c, &u, &key, &a.Status, &a.ErrorCode, &variants)
if e == nil {
e = json.Unmarshal(variants, &a.Variants)
}
a.CreatedAt = stamp(c)
a.UpdatedAt = stamp(u)
return a, key, e
}
func validFilename(name string) bool {
if !validText(name, 255) {
return false
}
for _, c := range name {
if c == '/' || c == '\\' || unicode.IsControl(c) {
return false
}
}
return true
}
// A temporary capped spool avoids holding a compressed file in RAM; it is
// removed on every exit. DecodeConfig bounds pixels before full validation.
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request, uid, cid string) {
q, e := url.ParseQuery(r.URL.RawQuery)
if e != nil || len(q["filename"]) != 1 || !validFilename(q.Get("filename")) {
bad(w)
return
}
contentType, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
if e != nil || (contentType != "image/png" && contentType != "image/jpeg") {
fail(w, 415, "unsupported_media_type", "Expected PNG or JPEG")
return
}
if r.ContentLength > maxUpload {
_, _ = io.Copy(io.Discard, io.LimitReader(r.Body, maxUpload+1))
fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB")
return
}
select {
case s.uploads <- struct{}{}:
defer func() { <-s.uploads }()
case <-r.Context().Done():
unavailable(w)
return
}
f, e := os.CreateTemp("", "messenger-upload-*")
if e != nil {
unavailable(w)
return
}
defer os.Remove(f.Name())
defer f.Close()
hash := sha256.New()
n, e := io.Copy(io.MultiWriter(f, hash), http.MaxBytesReader(w, r.Body, maxUpload))
if e != nil {
var over *http.MaxBytesError
if errors.As(e, &over) {
fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB")
} else {
bad(w)
}
return
}
_, _ = f.Seek(0, io.SeekStart)
config, format, e := image.DecodeConfig(f)
if e != nil || "image/"+format != contentType {
fail(w, 415, "unsupported_media_type", "Invalid image or MIME mismatch")
return
}
if config.Width < 1 || config.Height < 1 || int64(config.Width)*int64(config.Height) > maxPixels {
fail(w, 413, "payload_too_large", "Maximum image is 40 million pixels")
return
}
_, _ = f.Seek(0, io.SeekStart)
if !validateImage(f) {
fail(w, 415, "unsupported_media_type", "Invalid image")
return
}
_, _ = f.Seek(0, io.SeekStart)
id := uuid()
key := "staging/" + id
ctx := r.Context()
// Journal survives a crash between PUT and metadata COMMIT.
if _, e = s.db.Exec(ctx, "INSERT INTO upload_intents(object_key) VALUES($1)", key); e != nil {
unavailable(w)
return
}
tx, e := s.db.Begin(ctx)
if e != nil {
unavailable(w)
return
}
defer tx.Rollback(context.Background())
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", key); e != nil {
unavailable(w)
return
}
// Disable multipart: the bounded spool is <=10MiB, hence one atomic object PUT.
_, e = s.objects.Client.PutObject(ctx, s.objects.Bucket, key, f, n, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true})
if e != nil {
unavailable(w)
return
}
a, _, e := scanAttachment(tx.QueryRow(ctx, `INSERT INTO attachments AS a(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status,staging_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued',$9) RETURNING `+attachmentColumns, id, cid, uid, q.Get("filename"), "originals/"+id+"/v1/original", contentType, n, hex.EncodeToString(hash.Sum(nil)), key))
if e != nil {
unavailable(w)
return
}
// Admission and intent share a transaction; no unbounded accepted backlog.
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026005)"); e != nil {
unavailable(w)
return
}
var pending int
if e = tx.QueryRow(ctx, "SELECT count(*) FROM pipeline_jobs WHERE finished_at IS NULL").Scan(&pending); e != nil {
unavailable(w)
return
}
if pending >= 1000 {
w.Header().Set("Retry-After", "5")
fail(w, 429, "rate_limited", "Processing backlog is full")
return
}
parent, state := telemetry.Inject(ctx)
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version,traceparent,tracestate) VALUES($1,$2,1,$3,$4)`, uuid(), id, parent, state); e != nil {
unavailable(w)
return
}
if _, e = tx.Exec(ctx, "DELETE FROM upload_intents WHERE object_key=$1", key); e != nil {
unavailable(w)
return
}
if tx.Commit(ctx) != nil {
unavailable(w)
return
}
reply(w, 202, a)
}
func validateImage(r io.Reader) bool { _, _, e := image.Decode(r); return e == nil }
func (s *Server) serveAttachment(w http.ResponseWriter, r *http.Request, uid string, parts []string) {
if r.Method != "GET" || (len(parts) != 4 && len(parts) != 5) || (len(parts) == 5 && parts[4] != "content") {
missing(w)
return
}
id := strings.ToLower(parts[3])
if !uuidRE.MatchString(id) {
bad(w)
return
}
a, key, e := scanAttachment(s.db.QueryRow(r.Context(), `SELECT `+attachmentColumns+` FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2 WHERE a.id=$1`, id, uid))
if errors.Is(e, pgx.ErrNoRows) {
missing(w)
return
}
if e != nil {
unavailable(w)
return
}
if len(parts) == 4 {
reply(w, 200, a)
return
}
q, e := url.ParseQuery(r.URL.RawQuery)
if e != nil || len(q["variant"]) > 1 {
bad(w)
return
}
if a.Status != "ready" {
fail(w, 409, "conflict", "Attachment is not ready")
return
}
variant := q.Get("variant")
if variant != "" && variant != "original" {
found := false
for _, v := range a.Variants {
if v.Name == variant {
a.ContentType = v.ContentType
a.Size = v.Size
key = strings.TrimSuffix(key, "original") + variant
found = true
break
}
}
if !found {
missing(w)
return
}
}
object, e := s.objects.Client.GetObject(r.Context(), s.objects.Bucket, key, minio.GetObjectOptions{})
if e != nil {
unavailable(w)
return
}
defer object.Close()
info, e := object.Stat()
if e != nil || info.Size != a.Size {
unavailable(w)
return
}
w.Header().Set("Content-Type", a.ContentType)
w.Header().Set("Content-Length", fmt.Sprint(a.Size))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
w.WriteHeader(200)
_, _ = io.Copy(w, object)
}
// Normalize optional attachments before hashing; JSON key ordering is irrelevant.
func parseMessage(w http.ResponseWriter, r *http.Request) (string, []string, bool) {
var in struct {
Text *string `json:"text"`
Attachments []string `json:"attachment_ids"`
}
// strict decoder accepts an explicitly optional field (suffix '?').
if !decode(w, r, &in, "text", "attachment_ids?") {
return "", nil, false
}
if in.Text == nil || !utf8.ValidString(*in.Text) || utf8.RuneCountInString(*in.Text) > 4000 || len(in.Attachments) > 10 || (strings.TrimSpace(*in.Text) == "" && len(in.Attachments) == 0) {
bad(w)
return "", nil, false
}
seen := map[string]bool{}
for i, id := range in.Attachments {
id = strings.ToLower(id)
if !uuidRE.MatchString(id) || seen[id] {
bad(w)
return "", nil, false
}
seen[id] = true
in.Attachments[i] = id
}
if in.Attachments == nil {
in.Attachments = []string{}
}
return *in.Text, in.Attachments, true
}
+18
View File
@@ -0,0 +1,18 @@
//go:build linux
package messenger
import (
"os/exec"
"syscall"
)
func configureChild(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !linux
package messenger
import "os/exec"
func configureChild(cmd *exec.Cmd) {}
+163
View File
@@ -0,0 +1,163 @@
package messenger
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mtusi/messenger/internal/database"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
)
// Real PostgreSQL + HTTP + the race detector, in the optional Compose tests
// service. Local go test skips this test unless the DB secret path is supplied.
func TestDatabaseConcurrentHTTP(t *testing.T) {
path := os.Getenv("DATABASE_TEST_URL_FILE")
if path == "" {
t.Skip("run make test-race for real PostgreSQL HTTP integration")
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pool, err := database.Open(ctx, strings.TrimSpace(string(raw)))
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = database.Migrate(ctx, pool); err != nil {
t.Fatal(err)
}
api := New(pool, nil, make([]byte, 32), 3600, nil)
ts := httptest.NewServer(api)
defer ts.Close()
call := func(method, path, body, auth string, status int) map[string]any {
t.Helper()
r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
if err != nil {
t.Error(err)
return nil
}
if body != "" {
r.Header.Set("Content-Type", "application/json")
}
r.Header.Set("Authorization", auth)
if method == "POST" && strings.HasSuffix(path, "/messages") {
r.Header.Set("Idempotency-Key", uuid())
}
response, err := ts.Client().Do(r)
if err != nil {
t.Error(err)
return nil
}
defer response.Body.Close()
b, err := io.ReadAll(response.Body)
if err != nil {
t.Error(err)
return nil
}
if response.StatusCode != status {
t.Errorf("%s %s: want %d got %d", method, path, status, response.StatusCode)
return nil
}
var v map[string]any
if err = json.Unmarshal(b, &v); err != nil {
t.Error(err)
}
return v
}
username := "go_" + strings.ReplaceAll(uuid(), "-", "")[:20]
user := call("POST", "/api/v1/users", fmt.Sprintf(`{"username":%q,"display_name":"Race","password":"Synthetic-Go-Test-123"}`, username), "", 201)
if user == nil {
t.Fatal("create failed")
}
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":Synthetic-Go-Test-123"))
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
if session == nil {
t.Fatal("login failed")
}
bearer := "Bearer " + session["token"].(string)
chat := call("POST", "/api/v1/chats", fmt.Sprintf(`{"title":"Race","member_ids":[%q]}`, user["id"]), bearer, 201)
if chat == nil {
t.Fatal("chat failed")
}
messages := "/api/v1/chats/" + chat["id"].(string) + "/messages"
var wg sync.WaitGroup
for worker := 0; worker < 10; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
for j := 0; j < 10; j++ {
call("POST", messages, fmt.Sprintf(`{"text":"worker-%d-message-%d"}`, worker, j), bearer, 201)
}
}(worker)
}
wg.Wait()
page := call("GET", messages+"?limit=100", "", bearer, 200)
if page == nil {
t.Fatal("history failed")
}
items := page["items"].([]any)
if len(items) != 100 {
t.Fatalf("expected 100 messages, got %d", len(items))
}
seen := map[string]bool{}
for _, v := range items {
m := v.(map[string]any)
id := m["id"].(string)
if seen[id] {
t.Fatal("duplicate ID")
}
seen[id] = true
}
// Race a single key through the real server, then verify only one side effect.
var repeatWG sync.WaitGroup
ids := make(chan string, 12)
for i := 0; i < 12; i++ {
repeatWG.Add(1)
go func() {
defer repeatWG.Done()
req, _ := http.NewRequest("POST", ts.URL+messages, strings.NewReader(`{"text":"one key"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", bearer)
req.Header.Set("Idempotency-Key", "same-concurrent-key")
res, err := ts.Client().Do(req)
if err != nil {
t.Error(err)
return
}
defer res.Body.Close()
var m Message
if res.StatusCode != 201 || json.NewDecoder(res.Body).Decode(&m) != nil {
t.Error("repeat failed")
return
}
ids <- m.ID
}()
}
repeatWG.Wait()
close(ids)
var expected string
for id := range ids {
if expected == "" {
expected = id
}
if id != expected {
t.Error("idempotency duplicate")
}
}
var count int
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id=$1", chat["id"]).Scan(&count); err != nil || count != 101 {
t.Errorf("want 101 persisted messages, got %d: %v", count, err)
}
t.Log("100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled")
}
+137
View File
@@ -0,0 +1,137 @@
package messenger
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
"strings"
"time"
)
// Operator-only CLI. It exposes no unauthenticated HTTP mutation endpoint.
func (p *Pipeline) Replay(ctx context.Context, id string, newVersion bool) error {
if !uuidRE.MatchString(id) {
return fmt.Errorf("expected attachment UUID")
}
tx, e := p.DB.Begin(ctx)
if e != nil {
return e
}
defer tx.Rollback(context.Background())
var status, key, stage string
var version int
e = tx.QueryRow(ctx, `SELECT status,object_key,COALESCE(staging_key,''),pipeline_version FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&status, &key, &stage, &version)
if e != nil {
return e
}
if newVersion {
if status != "ready" && status != "queued" && status != "processing" {
return fmt.Errorf("replay failed before version upgrade")
}
if version >= 2 {
return fmt.Errorf("supported pipeline versions: 1 and 2")
}
version++
if status == "ready" {
stage = key
}
} else {
if status != "failed" {
return fmt.Errorf("only failed can be replayed")
}
}
if _, e = p.Objects.Client.StatObject(ctx, p.Objects.Bucket, stage, minio.StatObjectOptions{}); e != nil {
return fmt.Errorf("source unavailable; restore before replay")
}
var jobID string
if newVersion {
jobID = uuid()
if _, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp() WHERE attachment_id=$1 AND finished_at IS NULL", id); e != nil {
return e
}
_, e = tx.Exec(ctx, `INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version) VALUES($1,$2,$3)`, jobID, id, version)
} else {
e = tx.QueryRow(ctx, `UPDATE pipeline_jobs SET attempt=0,lease_token=NULL,lease_until=NULL,published_at=NULL,finished_at=NULL,next_attempt_at=clock_timestamp() WHERE attachment_id=$1 AND pipeline_version=$2 RETURNING job_id::text`, id, version).Scan(&jobID)
}
if e != nil {
return e
}
_, e = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,variants='[]',pipeline_version=$2,staging_key=$3,updated_at=clock_timestamp() WHERE id=$1`, id, version, stage)
if e != nil {
return e
}
event := "operator_replay"
if newVersion {
event = "operator_new_version"
}
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,$2,0)`, jobID, event); e != nil {
return e
}
return tx.Commit(ctx)
}
// Only staging is collected automatically. Live queued/processing work and final
// objects are always protected. Ready stage is redundant; failed source has 7d
// retention. Unattributed aborted uploads/intents have a conservative 24h grace.
func (p *Pipeline) Cleanup(ctx context.Context, apply bool) error {
for object := range p.Objects.Client.ListObjects(ctx, p.Objects.Bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) {
if object.Err != nil {
return object.Err
}
if time.Since(object.LastModified) < 24*time.Hour {
continue
}
tx, e := p.DB.Begin(ctx)
if e != nil {
return e
}
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", object.Key); e != nil {
tx.Rollback(ctx)
return e
}
var status string
var updated time.Time
e = tx.QueryRow(ctx, `SELECT status,updated_at FROM attachments WHERE staging_key=$1 FOR UPDATE`, object.Key).Scan(&status, &updated)
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
tx.Rollback(ctx)
return e
}
safe := errors.Is(e, pgx.ErrNoRows) || status == "ready" || (status == "failed" && time.Since(updated) > 7*24*time.Hour)
if safe {
p.Log.Info("staging_cleanup", "event", "staging_cleanup", "apply", apply, "status", status)
if apply {
if e = p.Objects.Client.RemoveObject(ctx, p.Objects.Bucket, object.Key, minio.RemoveObjectOptions{}); e != nil {
tx.Rollback(ctx)
return e
}
if _, e = tx.Exec(ctx, `DELETE FROM upload_intents WHERE object_key=$1`, object.Key); e != nil {
tx.Rollback(ctx)
return e
}
}
}
if e = tx.Commit(ctx); e != nil {
return e
}
}
return nil
}
func (p *Pipeline) RunHousekeeping(ctx context.Context) error {
for ctx.Err() == nil {
if e := p.Cleanup(ctx, true); e != nil {
p.Log.Warn("cleanup_retry", "event", "cleanup_retry")
}
if !wait(ctx, time.Hour) {
break
}
}
return nil
}
func ParseOperatorArgs(args []string) (string, bool, error) {
if len(args) != 1 || strings.TrimSpace(args[0]) == "" {
return "", false, fmt.Errorf("expected one attachment UUID")
}
return args[0], false, nil
}
+33
View File
@@ -0,0 +1,33 @@
package messenger
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"golang.org/x/crypto/argon2"
"strings"
)
// Fixed, bounded parameters: 64 MiB, 3 passes, 2 lanes, 16-byte salt,
// 32-byte result. The HTTP layer bounds simultaneous KDF work to 2 calls.
func hashPassword(password string) string {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
panic(err)
}
hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
return "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash)
}
func verifyPassword(password, encoded string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || strings.Join(parts[:4], "$") != "$argon2id$v=19$m=65536,t=3,p=2" {
return false
}
salt, e1 := base64.RawStdEncoding.DecodeString(parts[4])
want, e2 := base64.RawStdEncoding.DecodeString(parts[5])
if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 {
return false
}
got := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
return subtle.ConstantTimeCompare(got, want) == 1
}
+20
View File
@@ -0,0 +1,20 @@
package messenger
import (
"strings"
"testing"
)
func TestPasswordFullUnicodeRange(t *testing.T) {
password := strings.Repeat("🙂", 128) // 512 bytes: exceeds bcrypt's 72-byte limit.
hash := hashPassword(password)
if !verifyPassword(password, hash) || verifyPassword(password+"x", hash) {
t.Fatal("password mismatch")
}
if hash == hashPassword(password) {
t.Fatal("salt reused")
}
if verifyPassword(password, "$argon2id$v=19$m=999999999,t=3,p=2$abc$def") {
t.Fatal("unbounded parameters accepted")
}
}
+441
View File
@@ -0,0 +1,441 @@
package messenger
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"io"
"log/slog"
"math/rand/v2"
"mtusi/messenger/internal/telemetry"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
const stream = "attachment.jobs.v1"
const group = "image-workers"
const maxAttempts = 5
const leaseSeconds = 45
type Job struct {
SchemaVersion int `json:"schema_version"`
ID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
Version int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt string `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
type Pipeline struct {
DB *pgxpool.Pool
Broker *redis.Client
Objects *ObjectStore
Log *slog.Logger
}
func NewPipeline(db *pgxpool.Pool, broker *redis.Client, o *ObjectStore, log *slog.Logger) *Pipeline {
return &Pipeline{db, broker, o, log}
}
func wait(ctx context.Context, d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}
func (p *Pipeline) RunDispatcher(ctx context.Context) error {
for ctx.Err() == nil {
if e := p.dispatch(ctx); e != nil {
p.Log.Warn("outbox_retry", "event", "outbox_retry")
}
if !wait(ctx, 500*time.Millisecond) {
break
}
}
return nil
}
func (p *Pipeline) dispatch(ctx context.Context) error {
// Small per-row transaction + SKIP LOCKED allows multiple dispatchers. A crash
// after XADD before COMMIT gives a duplicate, never a missing durable intent.
for i := 0; i < 32; i++ {
tx, e := p.DB.Begin(ctx)
if e != nil {
return e
}
var j Job
var created time.Time
e = tx.QueryRow(ctx, `SELECT job_id::text,attachment_id::text,pipeline_version,attempt+1,created_at,traceparent,tracestate FROM pipeline_jobs WHERE finished_at IS NULL AND next_attempt_at<=clock_timestamp() AND (lease_until IS NULL OR lease_until<clock_timestamp()) AND (published_at IS NULL OR published_at<clock_timestamp()-interval '60 seconds') ORDER BY next_attempt_at FOR UPDATE SKIP LOCKED LIMIT 1`).Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &created, &j.Traceparent, &j.Tracestate)
if errors.Is(e, pgx.ErrNoRows) {
tx.Rollback(ctx)
return nil
}
if e != nil {
tx.Rollback(ctx)
return e
}
j.SchemaVersion = 1
j.Type = "attachment.process.v1"
j.CreatedAt = stamp(created)
publishCtx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.publish", trace.SpanKindProducer)
span.SetAttributes(attribute.String("messaging.system", "valkey"), attribute.String("messaging.destination.name", stream))
j.Traceparent, j.Tracestate = telemetry.Inject(publishCtx)
payload, _ := json.Marshal(j)
_, e = p.Broker.XAdd(publishCtx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"payload": string(payload)}}).Result()
telemetry.Failure(span, e)
span.End()
if e == nil {
_, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET published_at=clock_timestamp() WHERE job_id=$1", j.ID)
}
if e != nil {
tx.Rollback(ctx)
return e
}
if e = tx.Commit(ctx); e != nil {
return e
}
p.Log.InfoContext(publishCtx, "job_published", "event", "job_published", "job_id", j.ID, "pipeline_version", j.Version)
}
return nil
}
func (p *Pipeline) RunWorker(ctx context.Context, concurrency int) error {
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("WORKER_CONCURRENCY must be 1..4")
}
for ctx.Err() == nil {
e := p.Broker.XGroupCreateMkStream(ctx, stream, group, "0").Err()
if e == nil || strings.Contains(e.Error(), "BUSYGROUP") {
break
}
if !wait(ctx, time.Second) {
return nil
}
}
telemetry.WorkerCapacity(concurrency)
var wg sync.WaitGroup
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func() { defer wg.Done(); p.consume(ctx, uuid()) }()
}
wg.Wait()
return nil
}
func (p *Pipeline) consume(ctx context.Context, consumer string) {
cursor := "0-0"
for ctx.Err() == nil {
claimed, next, e := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: stream, Group: group, Consumer: consumer, MinIdle: time.Minute, Start: cursor, Count: 1}).Result()
cursor = next
if e == nil && len(claimed) > 0 {
p.handle(ctx, claimed[0])
continue
}
entries, e := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 1, Block: time.Second}).Result()
if e != nil {
if e != redis.Nil {
wait(ctx, time.Second)
}
continue
}
for _, entry := range entries {
for _, m := range entry.Messages {
p.handle(ctx, m)
}
}
}
}
func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) {
raw, _ := m.Values["payload"].(string)
var j Job
d := json.NewDecoder(strings.NewReader(raw))
d.DisallowUnknownFields()
if len(raw) > 4096 || d.Decode(&j) != nil || j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || !uuidRE.MatchString(j.ID) || !uuidRE.MatchString(j.AttachmentID) || j.Version < 1 || j.Attempt < 1 {
p.Log.Warn("invalid_job", "event", "invalid_job")
p.ack(ctx, m.ID)
return
}
// The authoritative attempt and storage locations come from PostgreSQL, never
// from untrusted broker payload fields. A terminal/stale delivery is a no-op.
ctx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.consume", trace.SpanKindConsumer)
defer span.End()
done, e := p.process(ctx, j)
telemetry.Failure(span, e)
if e != nil {
p.Log.WarnContext(ctx, "job_deferred", "event", "job_deferred", "job_id", j.ID)
}
if done {
p.ack(ctx, m.ID)
}
}
func (p *Pipeline) ack(ctx context.Context, id string) {
// Do not delete an entry unless ACK succeeded; the only consumer group is ours.
if p.Broker.XAck(ctx, stream, group, id).Err() == nil {
p.Broker.XDel(ctx, stream, id)
}
}
func (p *Pipeline) process(parent context.Context, j Job) (bool, error) {
ctx, cancel := context.WithTimeout(parent, 30*time.Second)
defer cancel()
tx, e := p.DB.Begin(ctx)
if e != nil {
return false, e
}
defer tx.Rollback(context.Background())
var status, key, sha, contentType string
var version, attempt int
var size int64
var lease *time.Time
e = tx.QueryRow(ctx, `SELECT a.status,a.pipeline_version,a.staging_key,a.sha256,a.content_type,a.size_bytes,j.attempt,j.lease_until FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.Version).Scan(&status, &version, &key, &sha, &contentType, &size, &attempt, &lease)
if errors.Is(e, pgx.ErrNoRows) {
return true, nil
}
if e != nil {
return false, e
}
if version != j.Version || status == "ready" || status == "failed" {
return true, nil
}
var now time.Time
if e = tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); e != nil {
return false, e
}
if lease != nil && lease.After(now) {
return true, nil
} // live attempt; DB recovery remains durable
if attempt >= maxAttempts {
_, e = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=$1;`, j.AttachmentID)
if e == nil {
_, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1", j.ID)
}
if e != nil {
return false, e
}
return true, tx.Commit(ctx)
}
token := uuid()
attempt++
if _, e = tx.Exec(ctx, `UPDATE pipeline_jobs SET attempt=$2,lease_token=$3,lease_until=clock_timestamp()+interval '45 seconds' WHERE job_id=$1`, j.ID, attempt, token); e != nil {
return false, e
}
if _, e = tx.Exec(ctx, `UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID); e != nil {
return false, e
}
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,'claimed',$2)`, j.ID, attempt); e != nil {
return false, e
}
if e = tx.Commit(ctx); e != nil {
return false, e
}
trace.SpanFromContext(ctx).SetAttributes(attribute.Int("job.attempt", attempt), attribute.Int("pipeline.version", j.Version))
attemptStart := time.Now()
outcome := "failure"
defer func() {
trace.SpanFromContext(ctx).SetAttributes(attribute.String("job.outcome", outcome))
telemetry.Job(ctx, outcome, time.Since(attemptStart).Seconds())
}()
p.Log.InfoContext(ctx, "job_started", "event", "job_started", "job_id", j.ID, "attempt", attempt, "pipeline_version", j.Version)
faultPoint("before_objects")
telemetry.Busy.Add(1)
variants, processErr := p.perform(ctx, j, key, sha, contentType, size)
telemetry.Busy.Add(-1)
telemetry.Failure(trace.SpanFromContext(ctx), processErr)
if processErr == nil {
faultPoint("after_objects")
}
// A short independent commit budget allows recording a timed-out attempt;
// a cancelled/killed process instead recovers via the persisted lease.
finish, stop := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
defer stop()
tx, e = p.DB.Begin(finish)
if e != nil {
return false, e
}
defer tx.Rollback(context.Background())
var currentToken *string
var currentVersion int
e = tx.QueryRow(finish, `SELECT j.lease_token::text,a.pipeline_version FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 FOR UPDATE OF j,a`, j.ID).Scan(&currentToken, &currentVersion)
if e != nil {
return false, e
}
if currentToken == nil || *currentToken != token || currentVersion != j.Version {
return true, nil
}
if processErr == nil {
encoded, _ := json.Marshal(variants)
_, e = tx.Exec(finish, `UPDATE attachments SET status='ready',error_code=NULL,variants=$2,object_key=$3,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, encoded, resultPrefix(j)+"original")
if e == nil {
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),ready_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID)
}
} else {
permanent := errors.Is(processErr, errInvalidImage)
if permanent || attempt >= maxAttempts {
code := "retry_exhausted"
if permanent {
code = "invalid_image"
}
_, e = tx.Exec(finish, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, code)
if e == nil {
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID)
}
} else {
_, e = tx.Exec(finish, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID)
delay := time.Duration(1<<attempt)*time.Second + time.Duration(rand.IntN(1000))*time.Millisecond
if e == nil {
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET lease_until=NULL,published_at=NULL,next_attempt_at=clock_timestamp()+$2::interval WHERE job_id=$1`, j.ID, fmt.Sprintf("%f seconds", delay.Seconds()))
}
}
}
if e != nil {
return false, e
}
event := "ready"
if processErr != nil {
event = "processing_error"
}
if _, e = tx.Exec(finish, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,$2,$3)`, j.ID, event, attempt); e != nil {
return false, e
}
if e = tx.Commit(finish); e != nil {
return false, e
}
var since float64
if processErr == nil && p.DB.QueryRow(finish, "SELECT EXTRACT(EPOCH FROM ready_at-created_at)::float8 FROM pipeline_jobs WHERE job_id=$1", j.ID).Scan(&since) == nil {
telemetry.Ready(ctx, since)
}
p.Log.InfoContext(ctx, "job_completed", "event", "job_completed", "job_id", j.ID, "outcome", event, "attempt", attempt)
if processErr == nil {
outcome = "success"
faultPoint("after_commit")
// Committed ready points only at final objects. Cleanup failure is retried
// by the housekeeping pass; staging is never deleted before ready COMMIT.
if strings.HasPrefix(key, "staging/") {
_ = p.Objects.Client.RemoveObject(finish, p.Objects.Bucket, key, minio.RemoveObjectOptions{})
}
}
return true, nil
}
var ErrInvalidImage = errors.New("invalid_image")
var errInvalidImage = ErrInvalidImage
func resultPrefix(j Job) string {
return "originals/" + j.AttachmentID + "/v" + strconv.Itoa(j.Version) + "/"
}
func (p *Pipeline) perform(ctx context.Context, j Job, key, sha, contentType string, size int64) ([]Variant, error) {
dir, e := os.MkdirTemp("", "messenger-job-*")
if e != nil {
return nil, e
}
defer os.RemoveAll(dir)
object, e := p.Objects.Client.GetObject(ctx, p.Objects.Bucket, key, minio.GetObjectOptions{})
if e != nil {
return nil, e
}
defer object.Close()
f, e := os.Create(filepath.Join(dir, "input"))
if e != nil {
return nil, e
}
h := sha256.New()
n, e := io.Copy(io.MultiWriter(f, h), io.LimitReader(object, maxUpload+1))
f.Close()
if e != nil {
return nil, e
}
if n != size || hex.EncodeToString(h.Sum(nil)) != sha {
return nil, errInvalidImage
}
executable, e := os.Executable()
if e != nil {
return nil, e
}
transformCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
cmd := exec.CommandContext(transformCtx, executable, "transform", filepath.Join(dir, "input"), dir, strconv.Itoa(j.Version))
// Descendant cwebp inherits the process group; negative-PGID kill prevents
// an orphan encoder outliving the transform deadline (Linux container only).
configureChild(cmd)
transformCtx, transformSpan := telemetry.Start(transformCtx, "image.transform", trace.SpanKindInternal)
_ = transformCtx
e = cmd.Run()
telemetry.Failure(transformSpan, e)
transformSpan.End()
if e != nil {
return nil, classifyTransformFailure(transformCtx.Err(), e)
}
raw, e := os.ReadFile(filepath.Join(dir, "variants.json"))
if e != nil {
return nil, e
}
var variants []Variant
if e = json.Unmarshal(raw, &variants); e != nil {
return nil, e
}
input, e := os.Open(filepath.Join(dir, "input"))
if e != nil {
return nil, e
}
defer input.Close()
faultPoint("before_write")
if _, e = p.Objects.Client.PutObject(ctx, p.Objects.Bucket, resultPrefix(j)+"original", input, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true}); e != nil {
return nil, e
}
for i, v := range variants {
b, e := os.ReadFile(filepath.Join(dir, v.Name))
if e != nil {
return nil, e
}
digest := sha256.Sum256(b)
variants[i].SHA256 = hex.EncodeToString(digest[:])
variants[i].Size = int64(len(b))
_, e = p.Objects.Client.PutObject(ctx, p.Objects.Bucket, resultPrefix(j)+v.Name, bytes.NewReader(b), int64(len(b)), minio.PutObjectOptions{ContentType: v.ContentType, DisableMultipart: true})
if e != nil {
return nil, e
}
}
return variants, nil
}
// Opt-in local fault injection is absent from the normal Compose environment.
// A marker allows tests to observe the real boundary before killing the worker.
func faultPoint(point string) {
if os.Getenv("LAB_FAULT_POINT") == point {
_ = os.WriteFile("/tmp/fault-reached", []byte(point), 0600)
for {
if _, e := os.Stat("/tmp/fault-release"); e == nil {
return
}
time.Sleep(100 * time.Millisecond)
}
}
}
// A killed/crashed encoder is not evidence of an invalid source image.
func classifyTransformFailure(deadline, errorResult error) error {
if deadline != nil {
return deadline
}
var exited *exec.ExitError
if errors.As(errorResult, &exited) && exited.ExitCode() == 65 {
return ErrInvalidImage
}
return fmt.Errorf("transform temporarily unavailable")
}
+101
View File
@@ -0,0 +1,101 @@
package messenger
import (
"encoding/binary"
"github.com/disintegration/imaging"
"image"
"io"
"os"
)
// imaging handles JPEG APP1 orientation. PNG stores the same TIFF data in eXIf.
// Read only inside the already capped upload, with bounds checks on every IFD.
func pngOrientation(path string) int {
f, e := os.Open(path)
if e != nil {
return 1
}
defer f.Close()
if _, e = f.Seek(8, io.SeekStart); e != nil {
return 1
}
for {
var h [8]byte
if _, e = io.ReadFull(f, h[:]); e != nil {
return 1
}
n := binary.BigEndian.Uint32(h[:4])
if n > maxUpload {
return 1
}
if string(h[4:]) == "eXIf" {
b := make([]byte, n)
if _, e = io.ReadFull(f, b); e != nil {
return 1
}
return tiffOrientation(b)
}
if string(h[4:]) == "IEND" {
return 1
}
if _, e = f.Seek(int64(n)+4, io.SeekCurrent); e != nil {
return 1
}
}
}
func tiffOrientation(b []byte) int {
if len(b) < 8 {
return 1
}
var order binary.ByteOrder
switch string(b[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(b[2:4]) != 42 {
return 1
}
offset := uint64(order.Uint32(b[4:8]))
if offset+2 > uint64(len(b)) {
return 1
}
count := int(order.Uint16(b[offset : offset+2]))
for i := 0; i < count; i++ {
pos := offset + 2 + uint64(i)*12
if pos+12 > uint64(len(b)) {
return 1
}
entry := b[pos : pos+12]
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
v := int(order.Uint16(entry[8:10]))
if v >= 1 && v <= 8 {
return v
}
return 1
}
}
return 1
}
func orientPNG(img image.Image, orientation int) image.Image {
switch orientation {
case 2:
return imaging.FlipH(img)
case 3:
return imaging.Rotate180(img)
case 4:
return imaging.FlipV(img)
case 5:
return imaging.Transpose(img)
case 6:
return imaging.Rotate270(img)
case 7:
return imaging.Transverse(img)
case 8:
return imaging.Rotate90(img)
}
return img
}
+828
View File
@@ -0,0 +1,828 @@
// Package messenger implements the lab6 contract. PostgreSQL is authoritative.
package messenger
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"io"
"log/slog"
"mime"
"mtusi/messenger/internal/telemetry"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
type Message struct {
AttachmentIDs []string `json:"attachment_ids"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
type Page[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func uuid() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
panic(err)
}
b[6] = (b[6] & 15) | 64
b[8] = (b[8] & 63) | 128
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func validText(v string, max int) bool {
return utf8.ValidString(v) && strings.TrimSpace(v) != "" && utf8.RuneCountInString(v) <= max
}
func reply(w http.ResponseWriter, status int, v any) {
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func fail(w http.ResponseWriter, status int, code, msg string) {
reply(w, status, map[string]any{"error": map[string]string{"code": code, "message": msg, "request_id": w.Header().Get("X-Request-Id")}})
}
func bad(w http.ResponseWriter) { fail(w, 400, "invalid_request", "Invalid request") }
func missing(w http.ResponseWriter) { fail(w, 404, "not_found", "Object not found") }
// Decode exact object keys (encoding/json structs alone accept case variants).
// Reject null, duplicate keys, trailing documents and invalid UTF-8 as well.
func decode(w http.ResponseWriter, r *http.Request, dst any, fields ...string) bool {
media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || media != "application/json" {
fail(w, 415, "unsupported_media_type", "Expected application/json")
return false
}
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
if _, ok := err.(*http.MaxBytesError); ok {
fail(w, 413, "payload_too_large", "Body exceeds 1 MiB")
} else {
bad(w)
}
return false
}
if !utf8.Valid(b) {
bad(w)
return false
}
d := json.NewDecoder(bytes.NewReader(b))
token, err := d.Token()
if err != nil || token != json.Delim('{') {
bad(w)
return false
}
allowed := map[string]bool{}
for _, f := range fields {
allowed[strings.TrimSuffix(f, "?")] = true
}
seen := map[string]bool{}
for d.More() {
t, e := d.Token()
k, ok := t.(string)
if e != nil || !ok || !allowed[k] || seen[k] {
bad(w)
return false
}
seen[k] = true
var raw json.RawMessage
if d.Decode(&raw) != nil || bytes.Equal(raw, []byte("null")) {
bad(w)
return false
}
}
if _, err = d.Token(); err != nil {
bad(w)
return false
}
if _, err = d.Token(); err != io.EOF {
bad(w)
return false
}
for _, f := range fields {
if !strings.HasSuffix(f, "?") && !seen[f] {
bad(w)
return false
}
}
if json.Unmarshal(b, dst) != nil {
bad(w)
return false
}
return true
}
type cursor struct {
Scope string `json:"scope"`
Time string `json:"time"`
ID string `json:"id"`
}
func (s *Server) encodeCursor(c cursor) *string {
b, _ := json.Marshal(c)
mac := hmac.New(sha256.New, s.secret)
mac.Write(b)
v := base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
return &v
}
func (s *Server) pagination(w http.ResponseWriter, r *http.Request, scope string) (int, cursor, bool) {
var c cursor
limit := 50
// ParseQuery explicitly reports malformed escaping, unlike URL.Query.
values, e := url.ParseQuery(r.URL.RawQuery)
if e != nil {
bad(w)
return 0, c, false
}
if v, ok := values["limit"]; ok {
if len(v) != 1 || v[0] == "" || strings.Trim(v[0], "0123456789") != "" {
bad(w)
return 0, c, false
}
limit, e = strconv.Atoi(v[0])
if e != nil || limit < 1 || limit > 100 {
bad(w)
return 0, c, false
}
}
if v, ok := values["cursor"]; ok {
if len(v) != 1 || len(v[0]) > 2048 {
bad(w)
return 0, c, false
}
parts := strings.Split(v[0], ".")
if len(parts) != 2 {
bad(w)
return 0, c, false
}
b, e1 := base64.RawURLEncoding.DecodeString(parts[0])
sig, e2 := base64.RawURLEncoding.DecodeString(parts[1])
mac := hmac.New(sha256.New, s.secret)
mac.Write(b)
if e1 != nil || e2 != nil || !hmac.Equal(sig, mac.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope || !uuidRE.MatchString(c.ID) {
bad(w)
return 0, c, false
}
}
if c.ID != "" {
if _, err := time.Parse(time.RFC3339Nano, c.Time); err != nil {
bad(w)
return 0, c, false
}
}
return limit, c, true
}
type Server struct {
db *pgxpool.Pool
cache *redis.Client
secret []byte
ttl int
log *slog.Logger
stopping atomic.Bool
kdf chan struct{}
objects *ObjectStore
uploads chan struct{}
instance string
dummyHash string
}
func New(db *pgxpool.Pool, cache *redis.Client, secret []byte, ttl int, logger *slog.Logger) *Server {
hostname, _ := os.Hostname()
return &Server{instance: hostname, db: db, cache: cache, secret: secret, ttl: ttl, log: logger, kdf: make(chan struct{}, 2), dummyHash: hashPassword("dummy-not-a-real-password")}
}
func (s *Server) Stop() { s.stopping.Store(true) }
func (s *Server) acquireKDF(ctx context.Context, w http.ResponseWriter) bool {
select {
case s.kdf <- struct{}{}:
return true
case <-ctx.Done():
unavailable(w)
return false
}
}
func unavailable(w http.ResponseWriter) {
fail(w, 503, "unavailable", "Dependency temporarily unavailable")
}
func unauthorized(w http.ResponseWriter, scheme string) {
challenge := scheme + ` realm="messenger"`
if scheme == "Basic" {
challenge += `, charset="UTF-8"`
}
w.Header().Set("WWW-Authenticate", challenge)
fail(w, 401, "unauthorized", "Invalid or missing credentials")
}
func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") }
const userColumns = "id::text, username, display_name, created_at"
type scanner interface{ Scan(...any) error }
func scanUser(row scanner) (User, error) {
var u User
var t time.Time
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &t)
u.CreatedAt = stamp(t)
return u, err
}
func scanMessage(row scanner) (Message, error) {
var m Message
var t time.Time
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t)
m.CreatedAt = stamp(t)
m.AttachmentIDs = []string{}
return m, err
}
func (s *Server) profile(ctx context.Context, uid string) (User, error) {
// Valkey caches ONLY immutable User JSON. Session validity is always read
// from PostgreSQL first; cache loss never permits anonymous access.
key := "profile:v1:" + uid
if s.cache != nil {
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
raw, err := s.cache.Get(c, key).Bytes()
cancel()
var u User
if err == nil && json.Unmarshal(raw, &u) == nil && u.ID == uid {
return u, nil
}
}
u, err := scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id=$1", uid))
if err != nil {
return u, err
}
if s.cache != nil {
raw, _ := json.Marshal(u)
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
_ = s.cache.Set(c, key, raw, 300*time.Second).Err()
cancel()
}
return u, nil
}
func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (User, []byte, bool) {
parts := strings.Fields(r.Header.Get("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
unauthorized(w, "Bearer")
return User{}, nil, false
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil || len(raw) != 32 {
unauthorized(w, "Bearer")
return User{}, nil, false
}
digest := sha256.Sum256([]byte(parts[1]))
var uid string
err = s.db.QueryRow(r.Context(), "SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()", digest[:]).Scan(&uid)
if errors.Is(err, pgx.ErrNoRows) {
unauthorized(w, "Bearer")
return User{}, nil, false
}
if err != nil {
unavailable(w)
return User{}, nil, false
}
u, err := s.profile(r.Context(), uid)
if err != nil {
unavailable(w)
return User{}, nil, false
}
return u, digest[:], true
}
type recorder struct {
http.ResponseWriter
status int
}
func (w *recorder) WriteHeader(status int) { w.status = status; w.ResponseWriter.WriteHeader(status) }
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ctxSpan, span := telemetry.Start(telemetry.Incoming(r), "http.request", trace.SpanKindServer)
r = r.WithContext(ctxSpan)
defer span.End()
out := &recorder{w, 200}
w = out
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Request-Id", uuid())
w.Header().Set("X-Instance-Id", s.instance)
budget := 3 * time.Second
if strings.Contains(r.URL.Path, "attachments") {
budget = 30 * time.Second
}
ctx, cancel := context.WithTimeout(r.Context(), budget)
defer cancel()
r = r.WithContext(ctx)
if span.SpanContext().IsValid() {
w.Header().Set("X-Trace-Id", telemetry.TraceID(ctx))
}
route := routeTemplate(r.URL.Path)
defer func() {
if recover() != nil {
fail(w, 500, "internal_error", "Internal server error")
}
span.SetName(r.Method + " " + route)
span.SetAttributes(attribute.String("http.request.method", r.Method), attribute.String("http.route", route), attribute.Int("http.response.status_code", out.status))
if out.status >= 500 {
span.SetStatus(codes.Error, "HTTP 5xx")
}
telemetry.HTTP(ctx, r.Method, route, out.status, time.Since(start).Seconds())
if s.log != nil {
s.log.InfoContext(ctx, "request", "method", r.Method, "route", route, "status", out.status, "duration_us", time.Since(start).Microseconds(), "request_id", w.Header().Get("X-Request-Id"))
}
}()
if r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") {
if r.URL.Path == "/health/ready" && (s.stopping.Load() || s.db.Ping(ctx) != nil || (s.objects != nil && !s.objects.Ready(ctx))) {
unavailable(w)
} else {
reply(w, 200, map[string]string{"status": "ok"})
}
return
}
if s.stopping.Load() {
unavailable(w)
return
}
if r.Method == "POST" && r.URL.Path == "/api/v1/users" {
s.createUser(w, r)
return
}
if r.Method == "POST" && r.URL.Path == "/api/v1/auth/sessions" {
s.login(w, r)
return
}
user, digest, ok := s.authenticate(w, r)
if !ok {
return
}
if r.Method == "DELETE" && r.URL.Path == "/api/v1/auth/sessions/current" {
tag, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest)
if err != nil {
unavailable(w)
} else if tag.RowsAffected() == 0 {
unauthorized(w, "Bearer")
} else {
w.WriteHeader(204)
}
return
}
if r.Method == "GET" && r.URL.Path == "/api/v1/users/me" {
reply(w, 200, user)
return
}
if r.URL.Path == "/api/v1/chats" {
switch r.Method {
case "POST":
s.createChat(w, r, user.ID)
case "GET":
s.listChats(w, r, user.ID)
default:
missing(w)
}
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && s.objects != nil {
s.serveAttachment(w, r, user.ID, parts)
return
}
if len(parts) < 4 || len(parts) > 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "chats" {
missing(w)
return
}
cid := strings.ToLower(parts[3])
if !uuidRE.MatchString(cid) {
bad(w)
return
}
chat, err := s.getChat(ctx, cid, user.ID)
if errors.Is(err, pgx.ErrNoRows) {
missing(w)
return
}
if err != nil {
unavailable(w)
return
}
if len(parts) == 4 && r.Method == "GET" {
reply(w, 200, chat)
return
}
if len(parts) == 5 && parts[4] == "attachments" && r.Method == "POST" && s.objects != nil {
s.uploadAttachment(w, r, user.ID, cid)
return
}
if len(parts) == 5 && parts[4] == "messages" {
switch r.Method {
case "POST":
s.createMessage(w, r, user.ID, cid)
case "GET":
s.listMessages(w, r, cid)
default:
missing(w)
}
return
}
missing(w)
}
func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
var input struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if !decode(w, r, &input, "username", "display_name", "password") {
return
}
if !usernameRE.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validText(input.Password, 128) || utf8.RuneCountInString(input.Password) < 12 {
bad(w)
return
}
if !s.acquireKDF(r.Context(), w) {
return
}
hash := hashPassword(input.Password)
<-s.kdf
u, err := scanUser(s.db.QueryRow(r.Context(), "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING "+userColumns, uuid(), input.Username, input.DisplayName, hash))
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
fail(w, 409, "conflict", "Username already exists")
return
}
if err != nil {
unavailable(w)
return
}
reply(w, 201, u)
}
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1))
if err != nil || len(body) != 0 {
bad(w)
return
}
username, password, ok := r.BasicAuth()
if !ok || !usernameRE.MatchString(username) || !validText(password, 128) || utf8.RuneCountInString(password) < 12 {
unauthorized(w, "Basic")
return
}
var u User
var hash string
var t time.Time
err = s.db.QueryRow(r.Context(), "SELECT "+userColumns+", password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, &u.DisplayName, &t, &hash)
absent := errors.Is(err, pgx.ErrNoRows)
if err != nil && !absent {
unavailable(w)
return
}
if absent {
hash = s.dummyHash
}
if !s.acquireKDF(r.Context(), w) {
return
}
valid := verifyPassword(password, hash)
<-s.kdf
if !valid || absent {
unauthorized(w, "Basic")
return
}
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
panic(err)
}
token := base64.RawURLEncoding.EncodeToString(raw)
digest := sha256.Sum256([]byte(token))
var expires time.Time
err = s.db.QueryRow(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,clock_timestamp()+make_interval(secs=>$3)) RETURNING expires_at", digest[:], u.ID, s.ttl).Scan(&expires)
if err != nil {
unavailable(w)
return
}
u.CreatedAt = stamp(t)
reply(w, 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": stamp(expires), "user": u})
}
func (s *Server) createChat(w http.ResponseWriter, r *http.Request, uid string) {
var input struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if !decode(w, r, &input, "title", "member_ids") {
return
}
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
bad(w)
return
}
seen := map[string]bool{}
for i, id := range input.MemberIDs {
id = strings.ToLower(id)
if !uuidRE.MatchString(id) || seen[id] {
bad(w)
return
}
seen[id] = true
input.MemberIDs[i] = id
}
if !seen[uid] {
bad(w)
return
}
tx, err := s.db.Begin(r.Context())
if err != nil {
unavailable(w)
return
}
defer tx.Rollback(context.Background())
chat := Chat{ID: uuid(), Title: input.Title, MemberIDs: input.MemberIDs}
var t time.Time
err = tx.QueryRow(r.Context(), "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", chat.ID, chat.Title).Scan(&t)
if err != nil {
unavailable(w)
return
}
for _, id := range input.MemberIDs {
_, err = tx.Exec(r.Context(), "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id)
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == "23503" {
bad(w)
return
}
if err != nil {
unavailable(w)
return
}
}
if tx.Commit(r.Context()) != nil {
unavailable(w)
return
}
chat.CreatedAt = stamp(t)
reply(w, 201, chat)
}
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)`
func scanChat(row scanner) (Chat, error) {
var c Chat
var t time.Time
err := row.Scan(&c.ID, &c.Title, &t, &c.MemberIDs)
c.CreatedAt = stamp(t)
return c, err
}
func (s *Server) getChat(ctx context.Context, cid, uid string) (Chat, error) {
return scanChat(s.db.QueryRow(ctx, "SELECT "+chatColumns+" FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$2 WHERE c.id=$1", cid, uid))
}
var idempotencyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (s *Server) createMessage(w http.ResponseWriter, r *http.Request, uid, cid string) {
text, attachments, ok := parseMessage(w, r)
if !ok {
return
}
input := struct {
Text string `json:"text"`
Attachments []string `json:"attachment_ids"`
}{text, attachments}
keys := r.Header.Values("Idempotency-Key")
if len(keys) != 1 || !idempotencyRE.MatchString(keys[0]) {
bad(w)
return
}
body, _ := json.Marshal(input)
digest := sha256.Sum256(body)
ctx := r.Context()
tx, err := s.db.Begin(ctx)
if err != nil {
unavailable(w)
return
}
defer tx.Rollback(context.Background())
// Serialize only the same scope/key, across processes. Hash collisions only
// serialize unrelated requests; the full unique key still decides identity.
_, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", uid+":"+cid+":"+keys[0])
if err != nil {
unavailable(w)
return
}
var previous, saved []byte
err = tx.QueryRow(ctx, "SELECT body_hash,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()", uid, cid, keys[0]).Scan(&previous, &saved)
if err == nil {
if !bytes.Equal(previous, digest[:]) {
fail(w, 409, "conflict", "Key already used with another message")
return
}
if tx.Commit(ctx) != nil {
unavailable(w)
return
}
w.WriteHeader(201)
_, _ = w.Write(saved)
return
}
if !errors.Is(err, pgx.ErrNoRows) {
unavailable(w)
return
}
// A row lock prevents cleanup of an attachment while a message links it.
for _, id := range attachments {
var found, status string
err = tx.QueryRow(ctx, "SELECT id::text,status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE", id, cid).Scan(&found, &status)
if errors.Is(err, pgx.ErrNoRows) {
missing(w)
return
}
if err != nil {
unavailable(w)
return
}
if status == "failed" {
fail(w, 409, "conflict", "Attachment processing failed")
return
}
}
var t time.Time
err = tx.QueryRow(ctx, "UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') WHERE id=$1 RETURNING last_message_at", cid).Scan(&t)
if err != nil {
unavailable(w)
return
}
m, err := scanMessage(tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5) RETURNING id::text,chat_id::text,sender_id::text,text,created_at", uuid(), cid, uid, input.Text, t))
if err != nil {
unavailable(w)
return
}
m.AttachmentIDs = attachments
for i, id := range attachments {
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", m.ID, id, i); err != nil {
unavailable(w)
return
}
}
response, _ := json.Marshal(m)
_, err = tx.Exec(ctx, `INSERT INTO message_requests(user_id,chat_id,key,body_hash,response,expires_at) VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body_hash=EXCLUDED.body_hash,response=EXCLUDED.response,expires_at=EXCLUDED.expires_at`, uid, cid, keys[0], digest[:], response)
if err != nil || tx.Commit(ctx) != nil {
unavailable(w)
return
}
reply(w, 201, m)
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, cid string) {
scope := "messages:" + cid
limit, c, ok := s.pagination(w, r, scope)
if !ok {
return
}
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1`
args := []any{cid}
if c.ID != "" {
query += ` AND (created_at,id)>($2::timestamptz,$3::uuid)`
args = append(args, c.Time, c.ID)
}
query += fmt.Sprintf(" ORDER BY messages.created_at,messages.id LIMIT $%d", len(args)+1)
args = append(args, limit+1)
rows, err := s.db.Query(r.Context(), query, args...)
if err != nil {
unavailable(w)
return
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var m Message
var created time.Time
err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs)
m.CreatedAt = stamp(created)
if err != nil {
unavailable(w)
return
}
items = append(items, m)
}
if rows.Err() != nil {
unavailable(w)
return
}
var next *string
if len(items) > limit {
items = items[:limit]
last := items[limit-1]
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
}
reply(w, 200, Page[Message]{items, next})
}
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, uid string) {
scope := "chats:" + uid
limit, c, ok := s.pagination(w, r, scope)
if !ok {
return
}
query := "SELECT " + chatColumns + " FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$1"
args := []any{uid}
if c.ID != "" {
query += " WHERE (c.created_at,c.id)>($2::timestamptz,$3::uuid)"
args = append(args, c.Time, c.ID)
}
query += fmt.Sprintf(" ORDER BY c.created_at,c.id LIMIT $%d", len(args)+1)
args = append(args, limit+1)
rows, err := s.db.Query(r.Context(), query, args...)
if err != nil {
unavailable(w)
return
}
defer rows.Close()
items := []Chat{}
for rows.Next() {
chat, err := scanChat(rows)
if err != nil {
unavailable(w)
return
}
items = append(items, chat)
}
if rows.Err() != nil {
unavailable(w)
return
}
var next *string
if len(items) > limit {
items = items[:limit]
last := items[limit-1]
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
}
reply(w, 200, Page[Chat]{items, next})
}
// Classify before authentication/SQL so failures retain the endpoint template.
func routeTemplate(path string) string {
switch path {
case "/health/live", "/health/ready":
return path
}
if !strings.HasPrefix(path, "/api/v1/") {
return "unknown"
}
tail := strings.TrimPrefix(path, "/api/v1")
switch tail {
case "/users", "/users/me", "/auth/sessions", "/auth/sessions/current", "/chats":
return tail
}
p := strings.Split(strings.TrimPrefix(tail, "/"), "/")
if len(p) == 2 && p[0] == "chats" {
return "/chats/{id}"
}
if len(p) == 3 && p[0] == "chats" {
switch p[2] {
case "messages":
return "/chats/{id}/messages"
case "attachments":
return "/chats/{id}/attachments"
}
}
if len(p) == 2 && p[0] == "attachments" {
return "/attachments/{id}"
}
if len(p) == 3 && p[0] == "attachments" && p[2] == "content" {
return "/attachments/{id}/content"
}
return "unknown"
}
+104
View File
@@ -0,0 +1,104 @@
package messenger
import (
"encoding/json"
"fmt"
"github.com/disintegration/imaging"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"math"
"os"
"os/exec"
"path/filepath"
)
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
Size int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
func fitDimensions(w, h, max int) (int, int) {
scale := math.Min(1, math.Min(float64(max)/float64(w), float64(max)/float64(h)))
return int(math.Max(1, math.Floor(float64(w)*scale))), int(math.Max(1, math.Floor(float64(h)*scale)))
}
// Runs in a disposable child process, killed by the parent's 20s deadline.
// The only paths are server-generated temp paths. No client arguments/shell.
func Transform(input, dir string, versions ...int) error {
version := 1
if len(versions) > 0 {
version = versions[0]
}
if version < 1 || version > 2 {
return fmt.Errorf("unknown pipeline version")
}
quality, webpQuality := 85, "80"
if version == 2 {
quality, webpQuality = 90, "82"
}
f, e := os.Open(input)
if e != nil {
return e
}
c, format, e := image.DecodeConfig(f)
f.Close()
if e != nil || c.Width < 1 || c.Height < 1 || int64(c.Width)*int64(c.Height) > maxPixels {
return ErrInvalidImage
}
img, e := imaging.Open(input, imaging.AutoOrientation(true))
if e != nil {
return ErrInvalidImage
}
var oriented image.Image = img
if format == "png" {
oriented = orientPNG(img, pngOrientation(input))
}
bounds := oriented.Bounds()
white := image.NewNRGBA(bounds)
draw.Draw(white, bounds, &image.Uniform{C: color.White}, image.Point{}, draw.Src)
draw.Draw(white, bounds, oriented, bounds.Min, draw.Over)
w, h := fitDimensions(bounds.Dx(), bounds.Dy(), 256)
thumbnail := imaging.Resize(white, w, h, imaging.Lanczos)
crop := imaging.Fill(white, 128, 128, imaging.Center, imaging.Lanczos)
for name, result := range map[string]image.Image{"thumbnail": thumbnail, "crop": crop} {
f, e := os.Create(filepath.Join(dir, name))
if e != nil {
return e
}
e = jpeg.Encode(f, result, &jpeg.Options{Quality: quality})
ce := f.Close()
if e != nil {
return e
}
if ce != nil {
return ce
}
}
ow, oh := fitDimensions(bounds.Dx(), bounds.Dy(), 1280)
optimized := imaging.Resize(white, ow, oh, imaging.Lanczos)
p := filepath.Join(dir, "optimized.png")
f, e = os.Create(p)
if e != nil {
return e
}
e = png.Encode(f, optimized)
f.Close()
if e != nil {
return e
}
// Decoding/re-encoding removes EXIF and other source metadata. WebP quality 80.
cmd := exec.Command("cwebp", "-quiet", "-q", webpQuality, "-m", "4", "-metadata", "none", p, "-o", filepath.Join(dir, "optimized"))
if e = cmd.Run(); e != nil {
return fmt.Errorf("webp_encode")
}
result := []Variant{{Name: "thumbnail", ContentType: "image/jpeg", Width: w, Height: h}, {Name: "crop", ContentType: "image/jpeg", Width: 128, Height: 128}, {Name: "optimized", ContentType: "image/webp", Width: ow, Height: oh}}
b, _ := json.Marshal(result)
return os.WriteFile(filepath.Join(dir, "variants.json"), b, 0600)
}
@@ -0,0 +1,23 @@
package messenger
import (
"context"
"errors"
"os/exec"
"testing"
)
func TestTransformFailureClassification(t *testing.T) {
for _, c := range []struct {
command string
invalid bool
}{{"exit 65", true}, {"exit 2", false}, {"kill -KILL $$", false}} {
e := exec.Command("sh", "-c", c.command).Run()
if errors.Is(classifyTransformFailure(nil, e), ErrInvalidImage) != c.invalid {
t.Fatalf("misclassified encoder termination %q", c.command)
}
}
if !errors.Is(classifyTransformFailure(context.DeadlineExceeded, nil), context.DeadlineExceeded) {
t.Fatal("deadline lost")
}
}
+118
View File
@@ -0,0 +1,118 @@
package messenger
import (
"bytes"
"encoding/binary"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestFitFloorNoUpscale(t *testing.T) {
for _, v := range [][5]int{{320, 200, 256, 256, 160}, {3, 2, 256, 3, 2}, {301, 200, 256, 256, 170}, {1, 40000, 256, 1, 256}} {
w, h := fitDimensions(v[0], v[1], v[2])
if w != v[3] || h != v[4] {
t.Fatalf("fit %v got %dx%d", v, w, h)
}
}
}
func TestTransformAlphaAndEXIF(t *testing.T) {
if _, e := exec.LookPath("cwebp"); e != nil {
t.Skip("cwebp provided by Docker test target")
}
dir := t.TempDir()
input := filepath.Join(dir, "input.png")
f, _ := os.Create(input)
png.Encode(f, image.NewNRGBA(image.Rect(0, 0, 320, 200)))
f.Close()
if e := Transform(input, dir); e != nil {
t.Fatal(e)
}
b, _ := os.ReadFile(filepath.Join(dir, "thumbnail"))
img, e := jpeg.Decode(bytes.NewReader(b))
if e != nil {
t.Fatal(e)
}
r, g, bl, _ := img.At(20, 20).RGBA()
if r < 65000 || g < 65000 || bl < 65000 {
t.Fatal("alpha not composited white")
}
if img.Bounds().Dx() != 256 || img.Bounds().Dy() != 160 {
t.Fatal(img.Bounds())
}
source := image.NewNRGBA(image.Rect(0, 0, 320, 200))
source.Set(0, 0, color.White)
var jpg bytes.Buffer
jpeg.Encode(&jpg, source, nil)
// APP1 Exif, little endian TIFF, orientation=6 (90 degrees clockwise).
exif := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
var oriented bytes.Buffer
oriented.Write(jpg.Bytes()[:2])
oriented.Write([]byte{255, 225})
binary.Write(&oriented, binary.BigEndian, uint16(len(exif)+2))
oriented.Write(exif)
oriented.Write(jpg.Bytes()[2:])
os.WriteFile(input, oriented.Bytes(), 0600)
if e = Transform(input, dir); e != nil {
t.Fatal(e)
}
b, _ = os.ReadFile(filepath.Join(dir, "thumbnail"))
img, e = jpeg.Decode(bytes.NewReader(b))
if e != nil {
t.Fatal(e)
}
if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 {
t.Fatalf("EXIF ignored: %v", img.Bounds())
}
}
func TestPNGEXIFAndMalformedIFD(t *testing.T) {
tiff := []byte{'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
if tiffOrientation(tiff) != 6 {
t.Fatal("TIFF orientation")
}
for i := 0; i < len(tiff); i++ {
_ = tiffOrientation(tiff[:i])
}
bad := append([]byte{}, tiff...)
for i := 4; i < 8; i++ {
bad[i] = 255
}
if tiffOrientation(bad) != 1 {
t.Fatal("bad IFD offset")
}
var raw bytes.Buffer
png.Encode(&raw, image.NewNRGBA(image.Rect(0, 0, 320, 200)))
var chunk bytes.Buffer
binary.Write(&chunk, binary.BigEndian, uint32(len(tiff)))
chunk.WriteString("eXIf")
chunk.Write(tiff)
binary.Write(&chunk, binary.BigEndian, crc32.ChecksumIEEE(chunk.Bytes()[4:]))
data := append(append(append([]byte{}, raw.Bytes()[:33]...), chunk.Bytes()...), raw.Bytes()[33:]...)
dir := t.TempDir()
input := filepath.Join(dir, "input.png")
os.WriteFile(input, data, 0600)
if pngOrientation(input) != 6 {
t.Fatal("PNG eXIf orientation")
}
if _, e := exec.LookPath("cwebp"); e != nil {
return
}
if e := Transform(input, dir); e != nil {
t.Fatal(e)
}
b, _ := os.ReadFile(filepath.Join(dir, "thumbnail"))
img, e := jpeg.Decode(bytes.NewReader(b))
if e != nil {
t.Fatal(e)
}
if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 {
t.Fatal("PNG orientation not applied", img.Bounds())
}
}
+40
View File
@@ -0,0 +1,40 @@
package telemetry
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel/trace"
"strings"
)
type DBTracer struct{}
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
fields := strings.Fields(d.SQL)
op := "query"
if len(fields) > 0 {
switch strings.ToUpper(fields[0]) {
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
op = strings.ToUpper(fields[0])
}
}
ctx, _ = Start(ctx, "db."+op, trace.SpanKindClient)
return ctx
}
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
s := trace.SpanFromContext(ctx)
Failure(s, d.Err)
s.End()
}
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
PendingAcquires.Add(1)
ctx, _ = Start(ctx, "db.pool.acquire", trace.SpanKindInternal)
return ctx
}
func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, d pgxpool.TraceAcquireEndData) {
PendingAcquires.Add(-1)
s := trace.SpanFromContext(ctx)
Failure(s, d.Err)
s.End()
}
+24
View File
@@ -0,0 +1,24 @@
package telemetry
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"net/http"
)
func Incoming(r *http.Request) context.Context {
return otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
}
type transport struct{ next http.RoundTripper }
func Transport(next http.RoundTripper) http.RoundTripper { return &transport{next} }
func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
ctx, s := Start(r.Context(), "s3.request", trace.SpanKindClient)
defer s.End()
response, e := t.next.RoundTrip(r.Clone(ctx))
Failure(s, e)
return response, e
}
+242
View File
@@ -0,0 +1,242 @@
// Package telemetry owns bounded, best-effort OTLP exporters. It never affects
// business readiness and never exports URLs, SQL text, credentials or payloads.
package telemetry
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/contrib/bridges/otelslog"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.32.0"
"go.opentelemetry.io/otel/trace"
"log/slog"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
)
var HTTPCount metric.Int64Counter
var HTTPDuration, JobDuration, ReadyDuration metric.Float64Histogram
var Jobs metric.Int64Counter
var PendingAcquires atomic.Int64
var Busy atomic.Int64
var capacity atomic.Int64
var tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL))
func Init(ctx context.Context, service string) (*slog.Logger, func(), error) {
instance, _ := os.Hostname()
attrs := []attribute.KeyValue{attribute.String("service.name", service), attribute.String("service.version", "6.1.0"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab")}
res := resource.NewWithAttributes(semconv.SchemaURL, attrs...)
otel.SetTextMapPropagator(propagation.TraceContext{})
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
return slog.New(&contextHandler{next: slog.NewJSONHandler(os.Stdout, nil), service: service}), func() {}, nil
}
te, e := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(time.Second))
if e != nil {
return nil, nil, e
}
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))), sdktrace.WithBatcher(te, sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(time.Second)))
otel.SetTracerProvider(tp)
tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL))
me, e := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(time.Second))
if e != nil {
return nil, nil, e
}
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(me, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(time.Second))), sdkmetric.WithView(sdkmetric.NewView(sdkmetric.Instrument{Kind: sdkmetric.InstrumentKindHistogram}, sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120}}})))
otel.SetMeterProvider(mp)
le, e := otlploghttp.New(ctx, otlploghttp.WithTimeout(time.Second))
if e != nil {
return nil, nil, e
}
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(le, sdklog.WithMaxQueueSize(1024), sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(time.Second))))
log := slog.New(&contextHandler{next: &tee{a: slog.NewJSONHandler(os.Stdout, nil), b: otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp))}, service: service})
m := otel.Meter("messenger")
HTTPCount, _ = m.Int64Counter("http.server.requests")
HTTPDuration, _ = m.Float64Histogram("http.server.duration", metric.WithUnit("s"))
Jobs, _ = m.Int64Counter("messenger.jobs")
JobDuration, _ = m.Float64Histogram("messenger.job.duration", metric.WithUnit("s"))
ReadyDuration, _ = m.Float64Histogram("messenger.attachment.ready.duration", metric.WithUnit("s"))
shutdown := func() {
c, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
_ = tp.Shutdown(c)
_ = mp.Shutdown(c)
_ = lp.Shutdown(c)
}
return log, shutdown, nil
}
func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) {
return tracer.Start(ctx, name, trace.WithSpanKind(kind))
}
func Failure(span trace.Span, e error) {
if e != nil {
span.SetStatus(codes.Error, "dependency operation failed")
}
}
func Inject(ctx context.Context) (string, string) {
c := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, c)
return c.Get("traceparent"), c.Get("tracestate")
}
func Extract(ctx context.Context, parent, state string) context.Context {
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
}
func TraceID(ctx context.Context) string { return trace.SpanContextFromContext(ctx).TraceID().String() }
func HTTP(ctx context.Context, method, route string, status int, seconds float64) {
switch method {
case "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS":
default:
method = "_OTHER"
}
if HTTPCount == nil {
return
}
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", fmt.Sprintf("%dxx", status/100)))
HTTPCount.Add(ctx, 1, attrs)
HTTPDuration.Record(ctx, seconds, attrs)
}
func Job(ctx context.Context, outcome string, seconds float64) {
if Jobs == nil {
return
}
attrs := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
Jobs.Add(ctx, 1, attrs)
JobDuration.Record(ctx, seconds, attrs)
}
func Ready(ctx context.Context, seconds float64) {
if ReadyDuration != nil {
ReadyDuration.Record(ctx, seconds)
}
}
func WorkerCapacity(n int) { capacity.Store(int64(n)) }
func Observe(pool *pgxpool.Pool, worker bool) {
m := otel.Meter("messenger")
used, _ := m.Int64ObservableGauge("messenger.db.pool.used")
limit, _ := m.Int64ObservableGauge("messenger.db.pool.limit")
waiting, _ := m.Int64ObservableGauge("messenger.db.pool.waiting")
waits, _ := m.Int64ObservableCounter("messenger.db.pool.waits")
depth, _ := m.Int64ObservableGauge("messenger.queue.depth")
age, _ := m.Float64ObservableGauge("messenger.queue.oldest.age", metric.WithUnit("s"))
busy, _ := m.Int64ObservableGauge("messenger.worker.busy")
cap, _ := m.Int64ObservableGauge("messenger.worker.capacity")
sliTotal, _ := m.Int64ObservableCounter("messenger.attachment.sli.total")
sliBad, _ := m.Int64ObservableCounter("messenger.attachment.sli.bad")
containerRSS, _ := m.Int64ObservableGauge("container.memory.usage", metric.WithUnit("By"))
containerCPU, _ := m.Float64ObservableCounter("container.cpu.time", metric.WithUnit("s"))
rss, _ := m.Int64ObservableGauge("process.memory.usage", metric.WithUnit("By"))
cpu, _ := m.Float64ObservableCounter("process.cpu.time", metric.WithUnit("s"))
_, _ = m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
stat := pool.Stat()
o.ObserveInt64(used, int64(stat.AcquiredConns()))
o.ObserveInt64(limit, int64(stat.MaxConns()))
o.ObserveInt64(waits, stat.EmptyAcquireCount())
o.ObserveInt64(waiting, PendingAcquires.Load())
o.ObserveInt64(busy, Busy.Load())
o.ObserveInt64(cap, capacity.Load())
mem, cputime := processUsage()
o.ObserveInt64(rss, mem)
o.ObserveFloat64(cpu, cputime)
if raw, e := os.ReadFile("/sys/fs/cgroup/memory.current"); e == nil {
if bytes, e := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64); e == nil {
o.ObserveInt64(containerRSS, bytes)
}
}
if raw, e := os.ReadFile("/sys/fs/cgroup/cpu.stat"); e == nil {
for _, line := range strings.Split(string(raw), "\n") {
fields := strings.Fields(line)
if len(fields) == 2 && fields[0] == "usage_usec" {
if us, e := strconv.ParseFloat(fields[1], 64); e == nil {
o.ObserveFloat64(containerCPU, us/1e6)
}
}
}
}
if worker {
// One bounded query on the worker only avoids duplicating global queue
// gauges per API. A DB failure omits the observation, never invents zero.
query, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
var n int64
var oldest float64
e := pool.QueryRow(query, `SELECT count(*),COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(created_at)),0)::float8 FROM pipeline_jobs WHERE finished_at IS NULL`).Scan(&n, &oldest)
if e == nil {
o.ObserveInt64(depth, n)
o.ObserveFloat64(age, oldest)
}
var matured, bad int64
e = pool.QueryRow(query, `SELECT count(*),count(*) FILTER (WHERE ready_at IS NULL OR ready_at>created_at+interval '5 seconds') FROM pipeline_jobs WHERE created_at<=clock_timestamp()-interval '5 seconds'`).Scan(&matured, &bad)
if e == nil {
o.ObserveInt64(sliTotal, matured)
o.ObserveInt64(sliBad, bad)
}
}
return nil
}, used, limit, waits, waiting, depth, age, busy, cap, rss, cpu, sliTotal, sliBad, containerRSS, containerCPU)
}
func processUsage() (int64, float64) {
raw, e := os.ReadFile("/proc/self/stat")
if e != nil {
return 0, 0
}
end := strings.LastIndex(string(raw), ")")
if end < 0 {
return 0, 0
}
fields := strings.Fields(string(raw)[end+1:])
if len(fields) < 22 {
return 0, 0
}
u, _ := strconv.ParseFloat(fields[11], 64)
s, _ := strconv.ParseFloat(fields[12], 64)
pages, _ := strconv.ParseInt(fields[21], 10, 64)
return pages * int64(os.Getpagesize()), (u + s) / 100
}
type contextHandler struct {
next slog.Handler
service string
}
func (h *contextHandler) Enabled(ctx context.Context, l slog.Level) bool {
return h.next.Enabled(ctx, l)
}
func (h *contextHandler) Handle(ctx context.Context, r slog.Record) error {
r.AddAttrs(slog.String("service.name", h.service), slog.String("event", r.Message))
sc := trace.SpanContextFromContext(ctx)
if sc.IsValid() {
r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()))
}
return h.next.Handle(ctx, r)
}
func (h *contextHandler) WithAttrs(a []slog.Attr) slog.Handler {
return &contextHandler{next: h.next.WithAttrs(a), service: h.service}
}
func (h *contextHandler) WithGroup(g string) slog.Handler {
return &contextHandler{next: h.next.WithGroup(g), service: h.service}
}
type tee struct{ a, b slog.Handler }
func (h *tee) Enabled(ctx context.Context, l slog.Level) bool {
return h.a.Enabled(ctx, l) || h.b.Enabled(ctx, l)
}
func (h *tee) Handle(ctx context.Context, r slog.Record) error {
_ = h.a.Handle(ctx, r.Clone())
return h.b.Handle(ctx, r)
}
func (h *tee) WithAttrs(a []slog.Attr) slog.Handler { return &tee{h.a.WithAttrs(a), h.b.WithAttrs(a)} }
func (h *tee) WithGroup(g string) slog.Handler { return &tee{h.a.WithGroup(g), h.b.WithGroup(g)} }