Реализована лабораторная 6 на оценку 4

This commit is contained in:
MacBook
2026-11-16 15:16:54 +03:00
parent 470d9d6f1e
commit 4262a16ada
64 changed files with 8467 additions and 43 deletions
+64
View File
@@ -0,0 +1,64 @@
package database
import (
"context"
"embed"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/*.sql
var migrations embed.FS
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(202602)`); err != nil {
return err
}
if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
return err
}
entries, err := fs.ReadDir(migrations, "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 {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
part := strings.SplitN(entry.Name(), "_", 2)[0]
version, parseErr := strconv.Atoi(part)
if parseErr != nil {
return fmt.Errorf("invalid migration name %s", entry.Name())
}
var applied bool
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)`, version).Scan(&applied); err != nil {
return err
}
if applied {
continue
}
sqlBytes, readErr := migrations.ReadFile("migrations/" + entry.Name())
if readErr != nil {
return readErr
}
if _, err = tx.Exec(ctx, string(sqlBytes)); err != nil {
return fmt.Errorf("migration %s: %w", entry.Name(), err)
}
if _, err = tx.Exec(ctx, `INSERT INTO schema_migrations(version) VALUES($1)`, version); err != nil {
return err
}
}
return tx.Commit(ctx)
}
@@ -0,0 +1,31 @@
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(btrim(display_name)) > 0 AND char_length(display_name) <= 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(btrim(title)) > 0 AND char_length(title) <= 100),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL CHECK (char_length(btrim(text)) > 0 AND char_length(text) <= 4000),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
@@ -0,0 +1,13 @@
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
idempotency_key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid REFERENCES messages(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, method, path, idempotency_key)
);
CREATE INDEX message_idempotency_created_at_idx
ON message_idempotency (created_at);
@@ -0,0 +1,30 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
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}$'),
status text NOT NULL DEFAULT 'ready' CHECK (status='ready'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachments_chat_idx ON attachments(chat_id,created_at,id);
-- Durable intent is committed BEFORE any S3 PUT. A crashed upload remains
-- visible to the cleanup process even if its ready metadata never committed.
CREATE TABLE attachment_uploads (
id uuid PRIMARY KEY,
object_key text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachment_uploads_created_idx ON attachment_uploads(created_at);
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text)<=4000);
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
ALTER TABLE messages ADD CONSTRAINT messages_body_check
CHECK (char_length(btrim(text))>0 OR cardinality(attachment_ids)>0);
ALTER TABLE messages ADD CONSTRAINT messages_attachments_limit CHECK (cardinality(attachment_ids)<=10);
@@ -0,0 +1,37 @@
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued';
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check 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 '[]';
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version=1),
staging_key text NOT NULL UNIQUE,
state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','processing','ready','failed')),
attempts integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL DEFAULT 5 CHECK (max_attempts BETWEEN 1 AND 20),
next_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_until timestamptz,
lease_token uuid,
error_code text,
staging_deleted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachment_jobs_due_idx ON attachment_jobs(state,next_at);
-- Same transaction as attachment + job; repeated publication is intentional.
CREATE TABLE attachment_outbox (
job_id uuid PRIMARY KEY REFERENCES attachment_jobs(id) ON DELETE CASCADE,
published_at timestamptz,
publications integer NOT NULL DEFAULT 0
);
CREATE TABLE attachment_replays (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
previous_error text NOT NULL,
replayed_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
-- Internal CLI-only, one-shot crash injection. No HTTP endpoint exposes it.
CREATE TABLE pipeline_faults (point text PRIMARY KEY, armed boolean NOT NULL DEFAULT true, hit_at timestamptz);
@@ -0,0 +1,4 @@
-- Persist causal context in the same transaction as durable acceptance/outbox.
ALTER TABLE attachment_jobs ADD COLUMN traceparent text NOT NULL DEFAULT '';
ALTER TABLE attachment_jobs ADD COLUMN tracestate text NOT NULL DEFAULT '';
ALTER TABLE attachment_jobs ADD COLUMN request_id text NOT NULL DEFAULT '';
+263
View File
@@ -0,0 +1,263 @@
package messenger
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"mtusi-messenger/internal/telemetry"
)
const MaxUploadBytes int64 = 10 * 1024 * 1024
const MaxImagePixels int64 = 40000000
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 []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func tooLarge() *apiError {
return &apiError{status: 413, code: "payload_too_large", message: "Превышен лимит изображения"}
}
func invalidImage() *apiError {
return &apiError{status: 415, code: "unsupported_media_type", message: "Требуется корректный PNG или JPEG"}
}
func rollbackUpload(tx pgx.Tx) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_ = tx.Rollback(ctx)
}
func validFilename(s string) bool {
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > 255 {
return false
}
for _, c := range s {
if c == '/' || c == '\\' || unicode.IsControl(c) {
return false
}
}
return true
}
func (a *API) isMember(r *http.Request, uid, chatID string) *apiError {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
var member bool
if err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil {
return unavailable()
}
if !member {
return missing()
}
return nil
}
func (a *API) uploadAttachment(r *http.Request, uid, chatID string) (response, *apiError) {
if e := a.isMember(r, uid, chatID); e != nil {
return response{}, e
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil || len(query) != 1 || len(query["filename"]) != 1 || !validFilename(query.Get("filename")) {
return response{}, bad("Неверное имя файла")
}
kind, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || (kind != "image/png" && kind != "image/jpeg") {
return response{}, invalidImage()
}
if r.ContentLength > MaxUploadBytes {
return response{}, tooLarge()
}
ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second)
defer cancel()
// One decoder/temporary original per replica bounds RAM and tmpfs usage.
select {
case a.uploadSlots <- struct{}{}:
defer func() { <-a.uploadSlots }()
case <-ctx.Done():
return response{}, unavailable()
}
file, err := os.CreateTemp("", "upload-*")
if err != nil {
return response{}, unavailable()
}
defer os.Remove(file.Name())
defer file.Close()
hash := sha256.New()
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(r.Body, MaxUploadBytes+1), make([]byte, 32*1024))
if size > MaxUploadBytes {
return response{}, tooLarge()
}
if err != nil {
return response{}, bad("Загрузка прервана")
}
if size == 0 {
return response{}, invalidImage()
}
file.Seek(0, io.SeekStart)
config, format, err := image.DecodeConfig(file)
if err != nil || (format != "png" && format != "jpeg") || "image/"+format != kind {
return response{}, invalidImage()
}
if config.Width < 1 || config.Height < 1 || int64(config.Width) > MaxImagePixels/int64(config.Height) {
return response{}, tooLarge()
}
file.Seek(0, io.SeekStart)
// Decode after the dimension guard to reject corrupt payloads, not just
// apparently valid headers. The decoded bitmap is never persisted.
if e := validateImage(file); e != nil {
return response{}, e
}
file.Seek(0, io.SeekStart)
id := newID()
key := "staging/" + id
dbctx, dbcancel := a.dbContext(ctx)
_, err = a.db.Exec(dbctx, `INSERT INTO attachment_uploads(id,object_key) VALUES($1,$2)`, id, key)
dbcancel()
if err != nil {
return response{}, unavailable()
}
tx, err := a.db.Begin(ctx)
if err != nil {
return response{}, unavailable()
}
defer rollbackUpload(tx)
// Cleanup and upload use the same lock. Cleanup cannot delete an object
// while its upload/metadata transaction is in progress.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,4))`, key); err != nil {
return response{}, unavailable()
}
var pending bool
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachment_uploads WHERE id=$1)`, id).Scan(&pending); err != nil || !pending {
return response{}, unavailable()
}
putctx, putcancel := context.WithTimeout(ctx, 20*time.Second)
err = a.objects.Put(putctx, key, file, size, kind)
putcancel()
if err != nil {
return response{}, unavailable()
}
att := Attachment{ID: id, ChatID: chatID, OwnerID: uid, Filename: query.Get("filename"), ContentType: kind, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "queued", Variants: []any{}}
var created, updated time.Time
if err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued') RETURNING created_at,updated_at`, id, chatID, uid, att.Filename, key, kind, size, att.SHA256).Scan(&created, &updated); err != nil {
return response{}, unavailable()
}
if _, err = tx.Exec(ctx, `DELETE FROM attachment_uploads WHERE id=$1`, id); err != nil {
return response{}, unavailable()
}
maxAttempts := 5
if raw := os.Getenv("JOB_MAX_ATTEMPTS"); raw != "" {
n, parseErr := strconv.Atoi(raw)
if parseErr != nil || n < 1 || n > 20 {
return response{}, unavailable()
}
maxAttempts = n
}
parent, state := telemetry.Inject(ctx)
if _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key,max_attempts,traceparent,tracestate,request_id) VALUES($1,$2,$3,$4,$5,$6,$7)`, id, id, key, maxAttempts, parent, state, telemetry.RequestID(ctx)); err != nil {
return response{}, unavailable()
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id) VALUES($1)`, id); err != nil {
return response{}, unavailable()
}
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
att.CreatedAt = formatTime(created)
att.UpdatedAt = formatTime(updated)
return response{status: 202, body: att}, nil
}
func validateImage(r io.Reader) *apiError {
_, _, err := image.Decode(r)
if err != nil {
return invalidImage()
}
return nil
}
func (a *API) getAttachment(r *http.Request, uid, id string, content bool) (response, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return response{}, bad("Неверные параметры вложения")
}
if (!content && len(query) > 0) || (content && (len(query) > 1 || (len(query) > 0 && len(query["variant"]) != 1))) {
return response{}, bad("Неверные параметры вложения")
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
att := Attachment{Variants: []any{}}
var key string
var variantsJSON []byte
var created, updated time.Time
err = a.db.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.created_at,a.updated_at,a.variants,a.error_code FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=$2 WHERE a.id=$1`, id, uid).Scan(&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &key, &att.ContentType, &att.SizeBytes, &att.SHA256, &att.Status, &created, &updated, &variantsJSON, &att.ErrorCode)
if errors.Is(err, pgx.ErrNoRows) {
return response{}, missing()
}
if err != nil {
return response{}, unavailable()
}
_ = json.Unmarshal(variantsJSON, &att.Variants)
att.CreatedAt = formatTime(created)
att.UpdatedAt = formatTime(updated)
if !content {
return response{status: 200, body: att}, nil
}
if att.Status != "ready" {
return response{}, &apiError{status: 409, code: "conflict", message: "Вложение не готово"}
}
if variant, ok := query["variant"]; ok && variant[0] != "original" {
found := false
for _, item := range att.Variants {
v, ok := item.(map[string]any)
if ok && v["name"] == variant[0] {
key = "variants/" + id + "/v1/" + variant[0]
att.ContentType = v["content_type"].(string)
att.SizeBytes = int64(v["size_bytes"].(float64))
att.Filename = variant[0] + map[bool]string{true: ".webp", false: ".jpg"}[variant[0] == "optimized"]
found = true
break
}
}
if !found {
return response{}, missing()
}
}
downloadCtx, downloadCancel := context.WithTimeout(r.Context(), 45*time.Second)
object, err := a.objects.Get(downloadCtx, key)
if err != nil {
downloadCancel()
return response{}, unavailable()
}
return response{status: 200, content: object, contentType: att.ContentType, length: att.SizeBytes, filename: att.Filename, cancel: downloadCancel}, nil
}
+118
View File
@@ -0,0 +1,118 @@
package messenger
import (
"context"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"mtusi-messenger/internal/objectstore"
)
type CleanupResult struct {
RemovedObjects int `json:"removed_objects"`
RemovedIntents int64 `json:"removed_intents"`
KeptReady int `json:"kept_ready"`
SkippedRecent int `json:"skipped_recent"`
SkippedBusy int `json:"skipped_busy"`
}
// Cleanup removes abandoned uploads. Accepted pipeline jobs protect staging.
func Cleanup(ctx context.Context, db *pgxpool.Pool, store *objectstore.Store, grace time.Duration) (CleanupResult, error) {
result := CleanupResult{}
cutoff := time.Now().Add(-grace)
clean := func(key string) error {
if !strings.HasPrefix(key, "originals/") && !strings.HasPrefix(key, "staging/") {
return nil
}
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer rollbackUpload(tx)
var locked bool
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,4))`, key).Scan(&locked); err != nil {
return err
}
if !locked {
result.SkippedBusy++
return nil
}
var ready, recent bool
if err = tx.QueryRow(ctx, `SELECT (EXISTS(SELECT 1 FROM attachments WHERE object_key=$1) OR EXISTS(SELECT 1 FROM attachment_jobs WHERE staging_key=$1)),EXISTS(SELECT 1 FROM attachment_uploads WHERE object_key=$1 AND created_at>$2)`, key, cutoff).Scan(&ready, &recent); err != nil {
return err
}
if ready {
result.KeptReady++
return nil
}
if recent {
result.SkippedRecent++
return nil
}
info, err := store.Client.StatObject(ctx, store.Bucket, key, minio.StatObjectOptions{})
exists := err == nil
if err != nil && minio.ToErrorResponse(err).Code != "NoSuchKey" {
return err
}
if exists && info.LastModified.After(cutoff) {
result.SkippedRecent++
return nil
}
if exists {
if err = store.Delete(ctx, key); err != nil {
return err
}
}
command, err := tx.Exec(ctx, `DELETE FROM attachment_uploads WHERE object_key=$1`, key)
if err != nil {
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
result.RemovedIntents += command.RowsAffected()
if exists {
result.RemovedObjects++
}
return nil
}
rows, err := db.Query(ctx, `SELECT object_key FROM attachment_uploads WHERE created_at<$1 ORDER BY created_at LIMIT 1000`, cutoff)
if err != nil {
return result, err
}
keys := []string{}
for rows.Next() {
var key string
if err = rows.Scan(&key); err != nil {
rows.Close()
return result, err
}
keys = append(keys, key)
}
err = rows.Err()
rows.Close()
if err != nil {
return result, err
}
for _, key := range keys {
if err = clean(key); err != nil {
return result, err
}
}
listctx, cancel := context.WithCancel(ctx)
defer cancel()
for object := range store.Client.ListObjects(listctx, store.Bucket, minio.ListObjectsOptions{Recursive: true}) {
if object.Err != nil {
return result, fmt.Errorf("S3 cleanup listing: %w", object.Err)
}
if object.LastModified.Before(cutoff) {
if err = clean(object.Key); err != nil {
return result, err
}
}
}
return result, nil
}
+44
View File
@@ -0,0 +1,44 @@
package messenger
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/scrypt"
)
const scryptN, scryptR, scryptP = 32768, 8, 1
func hashPassword(password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash, err := scrypt.Key([]byte(password), salt, scryptN, scryptR, scryptP, 32)
if err != nil {
return "", err
}
b64 := base64.RawStdEncoding
return fmt.Sprintf("scrypt$%d$%d$%d$%s$%s", scryptN, scryptR, scryptP, b64.EncodeToString(salt), b64.EncodeToString(hash)), nil
}
func verifyPassword(encoded, password string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "scrypt" {
return false
}
n, e1 := strconv.Atoi(parts[1])
r, e2 := strconv.Atoi(parts[2])
p, e3 := strconv.Atoi(parts[3])
salt, e4 := base64.RawStdEncoding.DecodeString(parts[4])
expected, e5 := base64.RawStdEncoding.DecodeString(parts[5])
if e1 != nil || e2 != nil || e3 != nil || e4 != nil || e5 != nil || len(expected) != 32 {
return false
}
actual, err := scrypt.Key([]byte(password), salt, n, r, p, len(expected))
return err == nil && subtle.ConstantTimeCompare(actual, expected) == 1
}
+33
View File
@@ -0,0 +1,33 @@
package messenger
import (
"strings"
"testing"
)
func TestPasswordHash(t *testing.T) {
const password = "long-test-password"
first, err := hashPassword(password)
if err != nil {
t.Fatal(err)
}
second, err := hashPassword(password)
if err != nil {
t.Fatal(err)
}
if first == password || strings.Contains(first, password) {
t.Fatal("hash contains the original password")
}
if first == second {
t.Fatal("independent hashes must use different salts")
}
if !verifyPassword(first, password) {
t.Fatal("correct password was rejected")
}
if verifyPassword(first, "wrong-test-password") {
t.Fatal("wrong password was accepted")
}
if verifyPassword("damaged-hash", password) {
t.Fatal("malformed hash was accepted")
}
}
+776
View File
@@ -0,0 +1,776 @@
package messenger
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"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"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"mtusi-messenger/internal/objectstore"
"mtusi-messenger/internal/telemetry"
)
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 {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User User `json:"user"`
}
type API struct {
objects *objectstore.Store
uploadSlots chan struct{}
db *pgxpool.Pool
sessions *redis.Client
ttl time.Duration
idempotencyTTL time.Duration
dbTimeout time.Duration
instanceID string
logger *log.Logger
}
func NewHandler(db *pgxpool.Pool, sessions *redis.Client, objects *objectstore.Store, ttl, idempotencyTTL, dbTimeout time.Duration, instanceID string, logger *log.Logger) http.Handler {
return &API{db: db, sessions: sessions, objects: objects, uploadSlots: make(chan struct{}, 1), ttl: ttl, idempotencyTTL: idempotencyTTL, dbTimeout: dbTimeout, instanceID: instanceID, logger: logger}
}
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}$`)
var idempotencyKeyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type apiError struct {
status int
code, message, challenge string
}
type response struct {
status int
body any
noBody bool
content io.ReadCloser
contentType string
length int64
filename string
cancel context.CancelFunc
}
func bad(msg string) *apiError { return &apiError{status: 400, code: "invalid_request", message: msg} }
func missing() *apiError {
return &apiError{status: 404, code: "not_found", message: "Объект не найден"}
}
func unavailable() *apiError {
return &apiError{status: 503, code: "unavailable", message: "Сервис временно недоступен"}
}
func unauthorized(scheme string) *apiError {
challenge := `Bearer realm="messenger"`
if scheme == "Basic" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
return &apiError{status: 401, code: "unauthorized", message: "Неверные учётные данные", challenge: challenge}
}
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := newID()
route, method := telemetry.Route(r.URL.Path), telemetry.Method(r.Method)
parent := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := telemetry.Span(parent, method+" "+route, trace.SpanKindServer, attribute.String("http.route", route), attribute.String("http.request.method", method), attribute.String("request.id", id))
ctx = telemetry.WithRequestID(ctx, id)
r = r.WithContext(ctx)
w.Header().Set("X-Trace-Id", span.SpanContext().TraceID().String())
w.Header().Set("X-Request-Id", id)
w.Header().Set("X-Instance-Id", a.instanceID)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
start, status := time.Now(), 500
defer func() {
if x := recover(); x != nil {
status = 500
telemetry.Event(ctx, "http.panic", nil)
writeError(w, id, &apiError{status: 500, code: "internal_error", message: "Внутренняя ошибка"})
}
span.SetAttributes(attribute.Int("http.response.status_code", status))
if status >= 500 {
span.SetStatus(codes.Error, "HTTP server error")
}
telemetry.HTTP(ctx, method, route, status, time.Since(start))
telemetry.Event(ctx, "http.request", map[string]any{"method": method, "route": route, "status": status, "duration_ms": time.Since(start).Milliseconds()})
span.End()
}()
res, apiErr := a.route(r)
if apiErr != nil {
status = apiErr.status
writeError(w, id, apiErr)
return
}
status = res.status
if res.content != nil {
if res.cancel != nil {
defer res.cancel()
}
defer res.content.Close()
w.Header().Set("Content-Type", res.contentType)
w.Header().Set("Content-Length", strconv.FormatInt(res.length, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": res.filename}))
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
if _, err := io.Copy(w, res.content); err != nil {
telemetry.Event(ctx, "http.download_interrupted", nil)
}
return
}
w.WriteHeader(status)
if !res.noBody {
_ = json.NewEncoder(w).Encode(res.body)
}
}
func writeError(w http.ResponseWriter, requestID string, e *apiError) {
if e.challenge != "" {
w.Header().Set("WWW-Authenticate", e.challenge)
}
w.WriteHeader(e.status)
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": e.code, "message": e.message, "request_id": requestID}})
}
func decode(r *http.Request, dst any) *apiError {
if strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("Content-Type"), ";")[0])) != "application/json" {
return &apiError{status: 415, code: "unsupported_media_type", message: "Требуется application/json"}
}
if r.ContentLength > 1<<20 {
return &apiError{status: 413, code: "payload_too_large", message: "Слишком большой запрос"}
}
data, err := io.ReadAll(io.LimitReader(r.Body, (1<<20)+1))
if err != nil {
return bad("Не удалось прочитать JSON")
}
if len(data) > 1<<20 {
return &apiError{status: 413, code: "payload_too_large", message: "Слишком большой запрос"}
}
if !utf8.Valid(data) {
return bad("JSON должен быть в UTF-8")
}
var fields map[string]json.RawMessage
if json.Unmarshal(data, &fields) == nil {
for _, value := range fields {
if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
return bad("Поля запроса не должны быть null")
}
}
}
d := json.NewDecoder(bytes.NewReader(data))
d.DisallowUnknownFields()
if err = d.Decode(dst); err != nil {
return bad("Неверный JSON или поля")
}
var rest any
if !errors.Is(d.Decode(&rest), io.EOF) {
return bad("Ожидался один JSON-объект")
}
return nil
}
func validText(s string, max int) bool {
return utf8.ValidString(s) && strings.TrimSpace(s) != "" && utf8.RuneCountInString(s) <= max
}
func validPassword(s string) bool {
n := utf8.RuneCountInString(s)
return utf8.ValidString(s) && n >= 12 && n <= 128
}
func formatTime(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) }
func newID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func newToken() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
func tokenKey(token string) string {
sum := sha256.Sum256([]byte(token))
return "session:" + hex.EncodeToString(sum[:])
}
func cursorFor(resource string, created time.Time, id string) string {
b, _ := json.Marshal([]string{resource, formatTime(created), id})
return base64.RawURLEncoding.EncodeToString(b)
}
func parsePage(r *http.Request, resource string) (int, *time.Time, string, *apiError) {
q, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, "", bad("Неверные параметры страницы")
}
for k, v := range q {
if (k != "limit" && k != "cursor") || len(v) != 1 {
return 0, nil, "", bad("Неверные параметры страницы")
}
}
limit := 50
if raw := q.Get("limit"); raw != "" {
n, e := strconv.Atoi(raw)
if e != nil || n < 1 || n > 100 {
return 0, nil, "", bad("limit должен быть от 1 до 100")
}
limit = n
} else if _, ok := q["limit"]; ok {
return 0, nil, "", bad("Пустой limit")
}
if _, ok := q["cursor"]; !ok {
return limit, nil, "", nil
}
raw := q.Get("cursor")
if raw == "" || len(raw) > 1024 {
return 0, nil, "", bad("Неверный cursor")
}
b, e := base64.RawURLEncoding.DecodeString(raw)
if e != nil {
return 0, nil, "", bad("Неверный cursor")
}
var p []string
if json.Unmarshal(b, &p) != nil || len(p) != 3 || p[0] != resource || !uuidRE.MatchString(p[2]) {
return 0, nil, "", bad("Неверный cursor")
}
t, e := time.Parse(time.RFC3339Nano, p[1])
if e != nil {
return 0, nil, "", bad("Неверный cursor")
}
return limit, &t, p[2], nil
}
func (a *API) dbContext(parent context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, a.dbTimeout)
}
func (a *API) authenticate(r *http.Request) (string, string, *apiError) {
h := r.Header.Get("Authorization")
if !strings.HasPrefix(h, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(h, "Bearer ")) == "" {
return "", "", unauthorized("Bearer")
}
token := strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
ctx, cancel := context.WithTimeout(r.Context(), a.dbTimeout)
defer cancel()
uid, err := a.sessions.Get(ctx, tokenKey(token)).Result()
if errors.Is(err, redis.Nil) {
return "", "", unauthorized("Bearer")
}
if err != nil {
a.logger.Printf("session store unavailable: %v", err)
return "", "", unavailable()
}
if !uuidRE.MatchString(uid) {
return "", "", unauthorized("Bearer")
}
return uid, token, nil
}
func scanUser(row pgx.Row) (User, string, error) {
var u User
var created time.Time
var password string
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &created, &password)
u.CreatedAt = formatTime(created)
return u, password, err
}
func (a *API) route(r *http.Request) (response, *apiError) {
p := r.URL.Path
if r.Method == "GET" && p == "/health/live" {
return response{status: 200, body: map[string]string{"status": "ok"}}, nil
}
if r.Method == "GET" && p == "/health/ready" {
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
dbctx, dbspan := telemetry.Span(ctx, "db.readiness", trace.SpanKindClient, attribute.String("db.system.name", "postgresql"))
dbErr := a.db.Ping(dbctx)
telemetry.Result(dbspan, dbErr)
if dbErr != nil || a.sessions.Ping(ctx).Err() != nil || a.objects.Ready(ctx) != nil {
return response{}, unavailable()
}
return response{status: 200, body: map[string]string{"status": "ok"}}, nil
}
if r.Method == "POST" && p == "/api/v1/users" {
return a.createUser(r)
}
if r.Method == "POST" && p == "/api/v1/auth/sessions" {
return a.createSession(r)
}
if !strings.HasPrefix(p, "/api/v1/") {
return response{}, missing()
}
uid, token, authErr := a.authenticate(r)
if authErr != nil {
return response{}, authErr
}
if r.Method == "DELETE" && p == "/api/v1/auth/sessions/current" {
ctx, cancel := context.WithTimeout(r.Context(), a.dbTimeout)
defer cancel()
if err := a.sessions.Del(ctx, tokenKey(token)).Err(); err != nil {
return response{}, unavailable()
}
return response{status: 204, noBody: true}, nil
}
if r.Method == "GET" && p == "/api/v1/users/me" {
return a.currentUser(r, uid)
}
if strings.HasPrefix(p, "/api/v1/attachments/") {
parts := strings.Split(strings.TrimPrefix(p, "/api/v1/attachments/"), "/")
if !uuidRE.MatchString(parts[0]) {
return response{}, bad("Неверный attachment_id")
}
if r.Method == "GET" && (len(parts) == 1 || (len(parts) == 2 && parts[1] == "content")) {
return a.getAttachment(r, uid, parts[0], len(parts) == 2)
}
return response{}, missing()
}
if p == "/api/v1/chats" {
if r.Method == "POST" {
return a.createChat(r, uid)
}
if r.Method == "GET" {
return a.listChats(r, uid)
}
}
if !strings.HasPrefix(p, "/api/v1/chats/") {
return response{}, missing()
}
parts := strings.Split(strings.TrimPrefix(p, "/api/v1/chats/"), "/")
if len(parts) < 1 || !uuidRE.MatchString(parts[0]) {
return response{}, bad("Неверный chat_id")
}
chatID := parts[0]
if len(parts) == 2 && parts[1] == "attachments" && r.Method == "POST" {
return a.uploadAttachment(r, uid, chatID)
}
if len(parts) == 1 && r.Method == "GET" {
return a.getChat(r, uid, chatID)
}
if len(parts) == 2 && parts[1] == "messages" {
if r.Method == "POST" {
return a.createMessage(r, uid, chatID)
}
if r.Method == "GET" {
return a.listMessages(r, uid, chatID)
}
}
return response{}, missing()
}
func (a *API) createUser(r *http.Request) (response, *apiError) {
var in struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if e := decode(r, &in); e != nil {
return response{}, e
}
if !usernameRE.MatchString(in.Username) || !validText(in.DisplayName, 100) || !validPassword(in.Password) {
return response{}, bad("Неверные данные пользователя")
}
passwordHash, err := hashPassword(in.Password)
if err != nil {
return response{}, &apiError{status: 500, code: "internal_error", message: "Внутренняя ошибка"}
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
var u User
var created time.Time
err = a.db.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING id::text,username,display_name,created_at`, newID(), in.Username, in.DisplayName, passwordHash).Scan(&u.ID, &u.Username, &u.DisplayName, &created)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return response{}, &apiError{status: 409, code: "conflict", message: "Имя пользователя занято"}
}
return response{}, unavailable()
}
u.CreatedAt = formatTime(created)
return response{status: 201, body: u}, nil
}
func (a *API) createSession(r *http.Request) (response, *apiError) {
if r.ContentLength > 0 {
return response{}, bad("Тело запроса не допускается")
}
h := r.Header.Get("Authorization")
if !strings.HasPrefix(h, "Basic ") {
return response{}, unauthorized("Basic")
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(strings.TrimPrefix(h, "Basic ")))
if err != nil {
return response{}, unauthorized("Basic")
}
parts := strings.SplitN(string(raw), ":", 2)
if len(parts) != 2 || !usernameRE.MatchString(parts[0]) {
return response{}, unauthorized("Basic")
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
u, passwordHash, err := scanUser(a.db.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1`, parts[0]))
if errors.Is(err, pgx.ErrNoRows) {
return response{}, unauthorized("Basic")
}
if err != nil {
return response{}, unavailable()
}
if !verifyPassword(passwordHash, parts[1]) {
return response{}, unauthorized("Basic")
}
token := newToken()
expires := time.Now().UTC().Add(a.ttl)
if err = a.sessions.Set(ctx, tokenKey(token), u.ID, a.ttl).Err(); err != nil {
return response{}, unavailable()
}
return response{status: 201, body: Session{Token: token, TokenType: "Bearer", ExpiresAt: formatTime(expires), User: u}}, nil
}
func (a *API) currentUser(r *http.Request, uid string) (response, *apiError) {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
u, _, err := scanUser(a.db.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE id=$1`, uid))
if errors.Is(err, pgx.ErrNoRows) {
return response{}, unauthorized("Bearer")
}
if err != nil {
return response{}, unavailable()
}
return response{status: 200, body: u}, nil
}
func (a *API) createChat(r *http.Request, uid string) (response, *apiError) {
var in struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if e := decode(r, &in); e != nil {
return response{}, e
}
if !validText(in.Title, 100) || len(in.MemberIDs) < 1 || len(in.MemberIDs) > 100 {
return response{}, bad("Неверные данные чата")
}
seen := map[string]bool{}
for _, id := range in.MemberIDs {
if !uuidRE.MatchString(id) || seen[id] {
return response{}, bad("Неверные участники чата")
}
seen[id] = true
}
if !seen[uid] {
return response{}, bad("Создатель должен быть участником")
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
tx, err := a.db.Begin(ctx)
if err != nil {
return response{}, unavailable()
}
defer tx.Rollback(ctx)
c := Chat{ID: newID(), Title: in.Title, MemberIDs: append([]string{}, in.MemberIDs...)}
var created time.Time
if err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, c.ID, c.Title).Scan(&created); err != nil {
return response{}, unavailable()
}
for _, id := range c.MemberIDs {
if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, c.ID, id); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
return response{}, bad("Неверные участники чата")
}
return response{}, unavailable()
}
}
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
c.CreatedAt = formatTime(created)
return response{status: 201, body: c}, nil
}
func scanChat(row pgx.Row) (Chat, time.Time, error) {
var c Chat
var t time.Time
err := row.Scan(&c.ID, &c.Title, &c.MemberIDs, &t)
c.CreatedAt = formatTime(t)
return c, t, err
}
func chatSelect() string {
return `SELECT c.id::text,c.title,ARRAY(SELECT cm2.user_id::text FROM chat_members cm2 WHERE cm2.chat_id=c.id ORDER BY cm2.user_id),c.created_at FROM chats c`
}
func (a *API) getChat(r *http.Request, uid, chatID string) (response, *apiError) {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
c, _, err := scanChat(a.db.QueryRow(ctx, chatSelect()+` WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members cm WHERE cm.chat_id=c.id AND cm.user_id=$2)`, chatID, uid))
if errors.Is(err, pgx.ErrNoRows) {
return response{}, missing()
}
if err != nil {
return response{}, unavailable()
}
return response{status: 200, body: c}, nil
}
func (a *API) listChats(r *http.Request, uid string) (response, *apiError) {
limit, afterTime, afterID, e := parsePage(r, "chats:"+uid)
if e != nil {
return response{}, e
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
if afterTime != nil {
var ok bool
err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND c.id=$2 AND c.created_at=$3)`, uid, afterID, *afterTime).Scan(&ok)
if err != nil {
return response{}, unavailable()
}
if !ok {
return response{}, bad("Неверный cursor")
}
}
var rows pgx.Rows
var err error
base := chatSelect() + ` JOIN chat_members mine ON mine.chat_id=c.id WHERE mine.user_id=$1`
if afterTime == nil {
rows, err = a.db.Query(ctx, base+` ORDER BY c.created_at,c.id LIMIT $2`, uid, limit+1)
} else {
rows, err = a.db.Query(ctx, base+` AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, uid, *afterTime, afterID, limit+1)
}
if err != nil {
return response{}, unavailable()
}
defer rows.Close()
items := make([]Chat, 0, limit+1)
times := make([]time.Time, 0, limit+1)
for rows.Next() {
c, t, scanErr := scanChat(rows)
if scanErr != nil {
return response{}, unavailable()
}
items = append(items, c)
times = append(times, t)
}
if rows.Err() != nil {
return response{}, unavailable()
}
var next any
if len(items) > limit {
last := items[limit-1]
next = cursorFor("chats:"+uid, times[limit-1], last.ID)
items = items[:limit]
}
return response{status: 200, body: map[string]any{"items": items, "next_cursor": next}}, nil
}
func (a *API) createMessage(r *http.Request, uid, chatID string) (response, *apiError) {
key := r.Header.Get("Idempotency-Key")
if !idempotencyKeyRE.MatchString(key) {
return response{}, bad("Требуется корректный Idempotency-Key")
}
var in struct {
Text *string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
if e := decode(r, &in); e != nil {
return response{}, e
}
if in.Text == nil {
return response{}, bad("Требуется поле text")
}
text := *in.Text
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 || len(in.AttachmentIDs) > 10 || (strings.TrimSpace(text) == "" && len(in.AttachmentIDs) == 0) {
return response{}, bad("Текст сообщения должен содержать от 1 до 4000 символов")
}
if in.AttachmentIDs == nil {
in.AttachmentIDs = []string{}
}
seen := map[string]bool{}
for i, id := range in.AttachmentIDs {
id = strings.ToLower(id)
if !uuidRE.MatchString(id) || seen[id] {
return response{}, bad("Неверные attachment_ids")
}
seen[id] = true
in.AttachmentIDs[i] = id
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
tx, err := a.db.Begin(ctx)
if err != nil {
return response{}, unavailable()
}
defer tx.Rollback(ctx)
var member bool
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil {
return response{}, unavailable()
}
if !member {
return response{}, missing()
}
requestHash := sha256.Sum256([]byte(text))
if len(in.AttachmentIDs) > 0 {
canonical, _ := json.Marshal(in)
requestHash = sha256.Sum256(canonical)
}
if _, err = tx.Exec(ctx, `DELETE FROM message_idempotency WHERE user_id=$1 AND method=$2 AND path=$3 AND idempotency_key=$4 AND created_at < clock_timestamp() - ($5 * interval '1 second')`, uid, r.Method, r.URL.Path, key, int64(a.idempotencyTTL/time.Second)); err != nil {
return response{}, unavailable()
}
result, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,path,idempotency_key,request_hash) VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`, uid, r.Method, r.URL.Path, key, requestHash[:])
if err != nil {
return response{}, unavailable()
}
inserted := result.RowsAffected() == 1
if !inserted {
var storedHash []byte
var messageID string
if err = tx.QueryRow(ctx, `SELECT request_hash,message_id::text FROM message_idempotency WHERE user_id=$1 AND method=$2 AND path=$3 AND idempotency_key=$4 FOR UPDATE`, uid, r.Method, r.URL.Path, key).Scan(&storedHash, &messageID); err != nil {
return response{}, unavailable()
}
if !bytes.Equal(storedHash, requestHash[:]) {
return response{}, &apiError{status: 409, code: "conflict", message: "Idempotency-Key уже использован с другим запросом"}
}
var m Message
var created time.Time
if err = tx.QueryRow(ctx, `SELECT id::text,chat_id::text,sender_id::text,text,created_at,attachment_ids::text[] FROM messages WHERE id=$1`, messageID).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs); err != nil {
return response{}, unavailable()
}
m.CreatedAt = formatTime(created)
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
return response{status: 201, body: m}, nil
}
for _, id := range in.AttachmentIDs {
var state string
err = tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1 AND chat_id=$2`, id, chatID).Scan(&state)
if errors.Is(err, pgx.ErrNoRows) {
return response{}, missing()
}
if err != nil {
return response{}, unavailable()
}
if state == "failed" {
return response{}, &apiError{status: 409, code: "conflict", message: "Вложение не готово"}
}
}
m := Message{ID: newID(), ChatID: chatID, SenderID: uid, Text: text, AttachmentIDs: in.AttachmentIDs}
var created time.Time
if err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids) VALUES($1,$2,$3,$4,$5) RETURNING created_at`, m.ID, m.ChatID, m.SenderID, m.Text, m.AttachmentIDs).Scan(&created); err != nil {
return response{}, unavailable()
}
if _, err = tx.Exec(ctx, `UPDATE message_idempotency SET message_id=$1 WHERE user_id=$2 AND method=$3 AND path=$4 AND idempotency_key=$5`, m.ID, uid, r.Method, r.URL.Path, key); err != nil {
return response{}, unavailable()
}
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
m.CreatedAt = formatTime(created)
return response{status: 201, body: m}, nil
}
func (a *API) listMessages(r *http.Request, uid, chatID string) (response, *apiError) {
limit, afterTime, afterID, e := parsePage(r, "messages:"+chatID)
if e != nil {
return response{}, e
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
var member bool
if err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil {
return response{}, unavailable()
}
if !member {
return response{}, missing()
}
if afterTime != nil {
var ok bool
err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE chat_id=$1 AND id=$2 AND created_at=$3)`, chatID, afterID, *afterTime).Scan(&ok)
if err != nil {
return response{}, unavailable()
}
if !ok {
return response{}, bad("Неверный cursor")
}
}
var rows pgx.Rows
var err error
base := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,attachment_ids::text[] FROM messages WHERE chat_id=$1`
if afterTime == nil {
rows, err = a.db.Query(ctx, base+` ORDER BY created_at,id LIMIT $2`, chatID, limit+1)
} else {
rows, err = a.db.Query(ctx, base+` AND (created_at,id)>($2,$3) ORDER BY created_at,id LIMIT $4`, chatID, *afterTime, afterID, limit+1)
}
if err != nil {
return response{}, unavailable()
}
defer rows.Close()
items := make([]Message, 0, limit+1)
times := make([]time.Time, 0, limit+1)
for rows.Next() {
var m Message
var t time.Time
if rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t, &m.AttachmentIDs) != nil {
return response{}, unavailable()
}
m.CreatedAt = formatTime(t)
items = append(items, m)
times = append(times, t)
}
if rows.Err() != nil {
return response{}, unavailable()
}
var next any
if len(items) > limit {
last := items[limit-1]
next = cursorFor("messages:"+chatID, times[limit-1], last.ID)
items = items[:limit]
}
return response{status: 200, body: map[string]any{"items": items, "next_cursor": next}}, nil
}
+40
View File
@@ -0,0 +1,40 @@
package objectstore
import (
"context"
"encoding/json"
"net/url"
madmin "github.com/minio/madmin-go/v3"
)
// Bootstrap receives root credentials only in the one-shot s3-init process.
// The API and cleaner receive a separate user limited to this bucket/prefix.
func Bootstrap(ctx context.Context, endpoint, bucket, rootAccess, rootSecret, apiAccess, apiSecret string) error {
u, err := url.Parse(endpoint)
if err != nil {
return err
}
admin, err := madmin.New(u.Host, rootAccess, rootSecret, u.Scheme == "https")
if err != nil {
return err
}
if err = admin.AddUser(ctx, apiAccess, apiSecret); err != nil {
return err
}
policy := map[string]any{
"Version": "2012-10-17",
"Statement": []any{
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + bucket}},
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + bucket + "/originals/*", "arn:aws:s3:::" + bucket + "/staging/*", "arn:aws:s3:::" + bucket + "/variants/*"}},
},
}
encoded, err := json.Marshal(policy)
if err != nil {
return err
}
if err = admin.AddCannedPolicy(ctx, "messenger-api", encoded); err != nil {
return err
}
return admin.SetPolicy(ctx, "messenger-api", apiAccess, false)
}
+108
View File
@@ -0,0 +1,108 @@
package objectstore
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"mtusi-messenger/internal/telemetry"
)
type Store struct {
Client *minio.Client
Bucket string
endpoint string
}
func New(endpoint, region, bucket, access, secret string) (*Store, error) {
u, err := url.Parse(endpoint)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.Path != "" {
return nil, fmt.Errorf("invalid S3 endpoint")
}
transport := &http.Transport{
DialContext: (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
MaxIdleConns: 16, MaxIdleConnsPerHost: 8, MaxConnsPerHost: 8,
ResponseHeaderTimeout: 10 * time.Second, IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
}
client, err := minio.New(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https",
Region: region, Transport: transport, MaxRetries: 1,
})
if err != nil {
return nil, err
}
return &Store{Client: client, Bucket: bucket, endpoint: endpoint}, nil
}
func (s *Store) Ready(ctx context.Context) (err error) {
ctx, span := telemetry.Span(ctx, "s3.bucket.exists", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
ok, err := s.Client.BucketExists(ctx, s.Bucket)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("S3 bucket missing")
}
return nil
}
func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64, kind string) (err error) {
ctx, span := telemetry.Span(ctx, "s3.put", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
_, err = s.Client.PutObject(ctx, s.Bucket, key, r, size, minio.PutObjectOptions{
ContentType: kind, DisableMultipart: true,
})
return err
}
func (s *Store) Get(ctx context.Context, key string) (object *minio.Object, err error) {
ctx, span := telemetry.Span(ctx, "s3.get", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
object, err = s.Client.GetObject(ctx, s.Bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
if _, err = object.Stat(); err != nil {
object.Close()
return nil, err
}
return object, nil
}
func (s *Store) Delete(ctx context.Context, key string) (err error) {
ctx, span := telemetry.Span(ctx, "s3.delete", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
return s.Client.RemoveObject(ctx, s.Bucket, key, minio.RemoveObjectOptions{})
}
// Audit performs an actual unauthenticated GET and an out-of-scope operation
// with API credentials. Neither check prints credentials or object URLs.
func (s *Store) Audit(ctx context.Context, key string) error {
req, err := http.NewRequestWithContext(ctx, "GET", s.endpoint+"/"+s.Bucket+"/"+key, nil)
if err != nil {
return err
}
response, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
return err
}
response.Body.Close()
if response.StatusCode != 403 {
return fmt.Errorf("anonymous GET returned %d", response.StatusCode)
}
err = s.Client.MakeBucket(ctx, "forbidden-audit-bucket", minio.MakeBucketOptions{})
if minio.ToErrorResponse(err).Code != "AccessDenied" {
return fmt.Errorf("API credentials are not restricted: %v", err)
}
return nil
}
+549
View File
@@ -0,0 +1,549 @@
// Package pipeline implements durable intent, at-least-once delivery and fenced effects.
package pipeline
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"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"
"mtusi-messenger/internal/objectstore"
"mtusi-messenger/internal/telemetry"
)
const Stream = "attachment.jobs.v1"
const Group = "image-workers"
type Pipeline struct {
DB *pgxpool.Pool
Broker *redis.Client
Objects *objectstore.Store
Timeout time.Duration
Retention time.Duration
Logger *log.Logger
}
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"`
Created string `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
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"`
SHA string `json:"sha256"`
}
func (p *Pipeline) Checkpoint(ctx context.Context, point string) {
var armed bool
err := p.DB.QueryRow(ctx, `UPDATE pipeline_faults SET armed=false,hit_at=clock_timestamp() WHERE point=$1 AND armed RETURNING true`, point).Scan(&armed)
if err == nil && armed {
p.Logger.Printf("injected crash: %s", point)
os.Exit(86)
}
}
func pause(ctx context.Context, d time.Duration) {
select {
case <-ctx.Done():
case <-time.After(d):
}
}
// Dispatch re-publishes unfinished intents if a broker confirmation/connection is lost.
// Publication is deliberately outside the PostgreSQL transaction; duplicates are safe.
func (p *Pipeline) Dispatch(ctx context.Context) {
for ctx.Err() == nil {
if err := p.dispatchOnce(ctx); err != nil {
p.Logger.Print("dispatcher unavailable; intent retained")
}
sweepctx, cancelSweep := context.WithTimeout(ctx, 5*time.Second)
if err := p.Sweep(sweepctx); err != nil {
p.Logger.Print("staging sweep deferred")
}
cancelSweep()
pause(ctx, time.Second)
}
}
func (p *Pipeline) dispatchOnce(ctx context.Context) error {
rows, err := p.DB.Query(ctx, `SELECT j.id::text,j.attachment_id::text,j.pipeline_version,j.attempts+1,j.created_at,j.traceparent,j.tracestate
FROM attachment_jobs j JOIN attachment_outbox o ON o.job_id=j.id
WHERE ((j.state='queued' AND j.next_at<=clock_timestamp()) OR (j.state='processing' AND j.lease_until<clock_timestamp()))
AND (o.published_at IS NULL OR o.published_at<clock_timestamp()-interval '5 seconds') ORDER BY j.created_at LIMIT 50`)
if err != nil {
return err
}
jobs := []Job{}
for rows.Next() {
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
var created time.Time
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &created, &j.Traceparent, &j.Tracestate); err != nil {
rows.Close()
return err
}
j.Created = created.UTC().Format(time.RFC3339Nano)
jobs = append(jobs, j)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, j := range jobs {
p.Checkpoint(ctx, "dispatcher_before_publish")
parent := telemetry.Extract(ctx, j.Traceparent, j.Tracestate)
pubctx, pubspan := telemetry.Span(parent, "attachment.publish", trace.SpanKindProducer, attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.Int("job.attempt", j.Attempt))
j.Traceparent, j.Tracestate = telemetry.Inject(pubctx)
b, _ := json.Marshal(j)
err = p.Broker.XAdd(pubctx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"job": string(b)}}).Err()
telemetry.Event(pubctx, "job.published", map[string]any{"job_id": j.ID, "attempt": j.Attempt, "success": err == nil})
telemetry.Result(pubspan, err)
if err != nil {
return err
}
p.Checkpoint(ctx, "dispatcher_after_publish")
if _, err = p.DB.Exec(ctx, `UPDATE attachment_outbox SET published_at=clock_timestamp(),publications=publications+1 WHERE job_id=$1`, j.ID); err != nil {
return err
}
}
return nil
}
func (p *Pipeline) ack(ctx context.Context, id string) {
// Stream belongs to one group. Delete only after acknowledged; PG remains recovery authority.
if p.Broker.XAck(ctx, Stream, Group, id).Err() == nil {
_ = p.Broker.XDel(ctx, Stream, id).Err()
}
}
func (p *Pipeline) Worker(ctx context.Context, concurrency int) error {
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("WORKER_CONCURRENCY must be 1..4")
}
// One message at a time per consumer: prefetch=1.
done := make(chan struct{}, concurrency)
for i := 0; i < concurrency; i++ {
go func() { defer func() { done <- struct{}{} }(); p.consume(ctx, uuid.NewString()) }()
}
for i := 0; i < concurrency; i++ {
<-done
}
return nil
}
func (p *Pipeline) consume(ctx context.Context, consumer string) {
reclaimIdle := p.Timeout + 10*time.Second
for ctx.Err() == nil {
_ = p.Broker.XGroupCreateMkStream(ctx, Stream, Group, "0").Err()
pending, _, err := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: reclaimIdle, Start: "0-0", Count: 1}).Result()
if err == nil && len(pending) > 0 {
p.handle(ctx, pending[0])
continue
}
messages, err := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: 1, Block: time.Second}).Result()
if err != nil {
pause(ctx, 200*time.Millisecond)
continue
}
for _, stream := range messages {
for _, m := range stream.Messages {
p.handle(ctx, m)
}
}
}
}
func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) {
raw, ok := m.Values["job"].(string)
var j Job
if !ok || json.Unmarshal([]byte(raw), &j) != nil || j.SchemaVersion != 1 || j.Version != 1 || j.Type != "attachment.process.v1" || uuid.Validate(j.ID) != nil || uuid.Validate(j.AttachmentID) != nil {
// Malformed envelopes go to a diagnostic dead-letter stream, never interpreted as storage paths.
if p.Broker.XAdd(ctx, &redis.XAddArgs{Stream: "attachment.invalid.dlq", Values: map[string]any{"stream_id": m.ID, "error_code": "invalid_envelope"}}).Err() == nil {
p.ack(ctx, m.ID)
}
return
}
ctx = telemetry.Extract(ctx, j.Traceparent, j.Tracestate)
ctx, consumer := telemetry.Span(ctx, "attachment.consume", trace.SpanKindConsumer, attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.String("job.id", j.ID))
began := time.Now()
attempted := false
outcome := "abandoned"
defer func() {
consumer.SetAttributes(attribute.String("job.outcome", outcome))
if outcome == "retry" || outcome == "failed" || outcome == "abandoned" {
consumer.SetStatus(codes.Error, outcome)
}
if attempted {
telemetry.Busy.Add(-1)
telemetry.Job(ctx, outcome, time.Since(began))
}
telemetry.Event(ctx, "job.completed", map[string]any{"job_id": j.ID, "outcome": outcome, "duration_ms": time.Since(began).Milliseconds()})
consumer.End()
}()
jobctx, cancel := context.WithTimeout(ctx, p.Timeout)
defer cancel()
conn, err := p.DB.Acquire(jobctx)
if err != nil {
return
}
defer conn.Release()
var locked bool
if err = conn.QueryRow(jobctx, `SELECT pg_try_advisory_lock(hashtextextended($1,5))`, j.ID).Scan(&locked); err != nil || !locked {
return
}
defer func() {
unlockctx, done := context.WithTimeout(context.Background(), 3*time.Second)
defer done()
_, e := conn.Exec(unlockctx, `SELECT pg_advisory_unlock(hashtextextended($1,5))`, j.ID)
if e != nil {
_ = conn.Conn().Close(unlockctx)
}
}()
tx, err := conn.Begin(jobctx)
if err != nil {
return
}
defer tx.Rollback(context.Background())
var state, staging, attachment, requestID string
var accepted time.Time
var attempt, maxAttempts int
var due bool
err = tx.QueryRow(jobctx, `SELECT state,staging_key,attachment_id::text,attempts,max_attempts,
(state='queued' AND next_at<=clock_timestamp()) OR (state='processing' AND lease_until<clock_timestamp())
,created_at,request_id FROM attachment_jobs WHERE id=$1 FOR UPDATE`, j.ID).Scan(&state, &staging, &attachment, &attempt, &maxAttempts, &due, &accepted, &requestID)
if errors.Is(err, pgx.ErrNoRows) {
p.ack(ctx, m.ID)
return
}
if err != nil {
return
}
if attachment != j.AttachmentID {
return
}
ctx = telemetry.WithRequestID(ctx, requestID)
jobctx = telemetry.WithRequestID(jobctx, requestID)
if state == "ready" || state == "failed" {
outcome = "duplicate"
_ = tx.Rollback(jobctx)
p.ack(ctx, m.ID)
return
}
if !due {
outcome = "deferred"
_ = tx.Rollback(jobctx)
p.ack(ctx, m.ID)
return
}
if attempt >= maxAttempts {
if p.failTx(jobctx, tx, j.ID, attachment, "retry_exhausted") == nil && tx.Commit(jobctx) == nil {
p.ack(ctx, m.ID)
}
return
}
token := uuid.NewString()
consumer.SetAttributes(attribute.Int("job.attempt", attempt+1))
attempt++
_, err = tx.Exec(jobctx, `UPDATE attachment_jobs SET state='processing',attempts=$2,lease_token=$3,lease_until=clock_timestamp()+($4*interval '1 second'),updated_at=clock_timestamp() WHERE id=$1`, j.ID, attempt, token, int(p.Timeout/time.Second)+5)
if err != nil {
return
}
if _, err = tx.Exec(jobctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1`, attachment); err != nil {
return
}
if tx.Commit(jobctx) != nil {
return
}
attempted = true
telemetry.Busy.Add(1)
telemetry.Event(jobctx, "job.started", map[string]any{"job_id": j.ID, "attempt": attempt})
p.Checkpoint(jobctx, "worker_after_claim")
variants, code := p.process(jobctx, attachment, staging)
p.Checkpoint(jobctx, "worker_after_objects")
// A fresh transaction completes after job timeout/cancel; token fences stale attempts.
finishctx, finishcancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer finishcancel()
finish, err := conn.Begin(finishctx)
if err != nil {
return
}
defer finish.Rollback(context.Background())
var current string
if err = finish.QueryRow(finishctx, `SELECT lease_token::text FROM attachment_jobs WHERE id=$1 AND state='processing' FOR UPDATE`, j.ID).Scan(&current); err != nil || current != token {
return
}
if code == "" {
outcome = "success"
encoded, _ := json.Marshal(variants)
_, err = finish.Exec(finishctx, `UPDATE attachments SET status='ready',object_key=$2,variants=$3,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, attachment, "originals/"+attachment, encoded)
if err == nil {
_, err = finish.Exec(finishctx, `UPDATE attachment_jobs SET state='ready',lease_until=NULL,lease_token=NULL,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.ID)
}
} else if code == "invalid_image" || attempt >= maxAttempts {
outcome = "failed"
if code != "invalid_image" {
code = "retry_exhausted"
}
err = p.failTx(finishctx, finish, j.ID, attachment, code)
} else {
outcome = "retry"
delay := RetryDelay(attempt)
_, err = finish.Exec(finishctx, `UPDATE attachment_jobs SET state='queued',error_code=$2,next_at=clock_timestamp()+($3*interval '1 millisecond'),lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.ID, code, delay.Milliseconds())
if err == nil {
_, err = finish.Exec(finishctx, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, attachment)
}
}
if err != nil || finish.Commit(finishctx) != nil {
outcome = "abandoned"
return
}
if outcome == "success" {
telemetry.Ready(ctx, time.Since(accepted))
}
p.Checkpoint(finishctx, "worker_before_ack")
p.ack(finishctx, m.ID)
}
func RetryDelay(attempt int) time.Duration {
if attempt > 6 {
attempt = 6
}
base := time.Second * time.Duration(1<<uint(attempt-1))
return base + time.Duration(rand.Int64N(int64(base/2)+1))
}
func (p *Pipeline) failTx(ctx context.Context, tx pgx.Tx, id, attachment, code string) error {
_, err := tx.Exec(ctx, `UPDATE attachment_jobs SET state='failed',error_code=$2,lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, id, code)
if err == nil {
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, attachment, code)
}
return err
}
func (p *Pipeline) process(ctx context.Context, id, key string) ([]Variant, string) {
dir, err := os.MkdirTemp("", "job-*")
if err != nil {
return nil, "storage_unavailable"
}
defer os.RemoveAll(dir)
object, err := p.Objects.Get(ctx, key)
if err != nil {
return nil, "storage_unavailable"
}
file, err := os.Create(filepath.Join(dir, "source"))
if err != nil {
object.Close()
return nil, "storage_unavailable"
}
hash := sha256.New()
n, copyErr := io.Copy(io.MultiWriter(file, hash), io.LimitReader(object, 10485761))
object.Close()
file.Close()
if copyErr != nil {
return nil, "storage_unavailable"
}
if n > 10485760 {
return nil, "invalid_image"
}
var expected string
if p.DB.QueryRow(ctx, `SELECT sha256 FROM attachments WHERE id=$1`, id).Scan(&expected) != nil {
return nil, "storage_unavailable"
}
if hex.EncodeToString(hash.Sum(nil)) != expected {
return nil, "invalid_image"
}
cmd := exec.CommandContext(ctx, "python3", "/opt/process_image.py", filepath.Join(dir, "source"), dir)
_, imagespan := telemetry.Span(ctx, "image.process", trace.SpanKindInternal)
output, err := cmd.Output()
telemetry.Result(imagespan, err)
if err != nil {
if ctx.Err() != nil {
return nil, "processing_timeout"
}
var exit *exec.ExitError
if errors.As(err, &exit) && exit.ExitCode() == 2 {
return nil, "invalid_image"
}
return nil, "processing_failed"
}
variants := []Variant{}
if json.Unmarshal(output, &variants) != nil || len(variants) != 3 {
return nil, "processing_failed"
}
var kind string
if p.DB.QueryRow(ctx, `SELECT content_type FROM attachments WHERE id=$1`, id).Scan(&kind) != nil {
return nil, "storage_unavailable"
}
source, err := os.Open(filepath.Join(dir, "source"))
if err != nil {
return nil, "storage_unavailable"
}
err = p.Objects.Put(ctx, "originals/"+id, source, n, kind)
source.Close()
if err != nil {
return nil, "storage_unavailable"
}
for _, v := range variants {
f, err := os.Open(filepath.Join(dir, v.Name))
if err != nil {
return nil, "processing_failed"
}
err = p.Objects.Put(ctx, "variants/"+id+"/v1/"+v.Name, f, v.Size, v.ContentType)
f.Close()
if err != nil {
return nil, "storage_unavailable"
}
}
return variants, ""
}
// Failed registry is PostgreSQL; explicit replay is audited and refuses successful jobs.
func (p *Pipeline) Replay(ctx context.Context, id string) error {
if uuid.Validate(id) != nil {
return fmt.Errorf("invalid job id")
}
conn, err := p.DB.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
tx, err := conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var attachment, state, code string
var retained bool
err = tx.QueryRow(ctx, `SELECT attachment_id::text,state,COALESCE(error_code,''),staging_deleted_at IS NULL FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id).Scan(&attachment, &state, &code, &retained)
if err != nil {
return err
}
if state != "failed" || !retained {
return fmt.Errorf("only failed jobs with retained staging can be replayed")
}
var key string
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachment_jobs WHERE id=$1`, id).Scan(&key); err != nil {
return err
}
object, err := p.Objects.Get(ctx, key)
if err != nil {
return fmt.Errorf("staging unavailable")
}
object.Close()
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(job_id,previous_error) VALUES($1,$2)`, id, code); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='queued',attempts=0,error_code=NULL,next_at=clock_timestamp(),lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, attachment); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL WHERE job_id=$1`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
func (p *Pipeline) Sweep(ctx context.Context) error {
rows, err := p.DB.Query(ctx, `SELECT id::text,staging_key FROM attachment_jobs WHERE staging_deleted_at IS NULL AND (state='ready' OR (state='failed' AND updated_at<clock_timestamp()-($1*interval '1 second'))) LIMIT 20`, int64(p.Retention/time.Second))
if err != nil {
return err
}
type item struct{ id, key string }
items := []item{}
for rows.Next() {
var i item
if err = rows.Scan(&i.id, &i.key); err != nil {
rows.Close()
return err
}
items = append(items, i)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, i := range items {
tx, err := p.DB.Begin(ctx)
if err != nil {
return err
}
// Replay and retention serialize on this row. Never delete a newly queued job.
var allowed bool
err = tx.QueryRow(ctx, `SELECT state='ready' OR (state='failed' AND updated_at<clock_timestamp()-($2*interval '1 second')) FROM attachment_jobs WHERE id=$1 FOR UPDATE`, i.id, int64(p.Retention/time.Second)).Scan(&allowed)
if err != nil || !allowed {
_ = tx.Rollback(ctx)
continue
}
err = p.Objects.Delete(ctx, i.key)
if err == nil {
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET staging_deleted_at=clock_timestamp() WHERE id=$1`, i.id)
}
if err != nil {
_ = tx.Rollback(ctx)
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
}
return nil
}
// Operator commands are available only through docker exec, not through HTTP.
func (p *Pipeline) Command(ctx context.Context, args []string) error {
if len(args) == 2 && args[0] == "replay" {
return p.Replay(ctx, args[1])
}
if len(args) == 1 && args[0] == "failed-jobs" {
rows, err := p.DB.Query(ctx, `SELECT id::text,error_code,attempts FROM attachment_jobs WHERE state='failed' ORDER BY created_at`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id, code string
var attempts int
if err = rows.Scan(&id, &code, &attempts); err != nil {
return err
}
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"job_id": id, "error_code": code, "attempts": attempts})
}
return rows.Err()
}
if len(args) == 3 && args[0] == "fault" && (args[1] == "arm" || args[1] == "clear") {
allowed := map[string]bool{"dispatcher_before_publish": true, "dispatcher_after_publish": true, "worker_after_claim": true, "worker_after_objects": true, "worker_before_ack": true}
if !allowed[args[2]] {
return fmt.Errorf("unknown fault point")
}
if args[1] == "clear" {
_, err := p.DB.Exec(ctx, `DELETE FROM pipeline_faults WHERE point=$1`, args[2])
return err
}
_, err := p.DB.Exec(ctx, `INSERT INTO pipeline_faults(point) VALUES($1) ON CONFLICT(point) DO UPDATE SET armed=true,hit_at=NULL`, args[2])
return err
}
return fmt.Errorf("unknown pipeline command: %s", strconv.Itoa(len(args)))
}
+22
View File
@@ -0,0 +1,22 @@
package pipeline
import (
"testing"
"time"
)
func TestRetryDelayBounds(t *testing.T) {
for attempt := 1; attempt <= 20; attempt++ {
bounded := attempt
if bounded > 6 {
bounded = 6
}
base := time.Second * time.Duration(1<<uint(bounded-1))
for i := 0; i < 100; i++ {
got := RetryDelay(attempt)
if got < base || got > base+base/2 {
t.Fatalf("attempt %d: delay %s outside [%s,%s]", attempt, got, base, base+base/2)
}
}
}
}
+74
View File
@@ -0,0 +1,74 @@
package telemetry
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"net"
"strings"
)
// Queries are named by operation only. SQL text/args never enter telemetry.
type DBTracer struct{}
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
if !trace.SpanContextFromContext(ctx).IsValid() {
return ctx
}
op := "OTHER"
f := strings.Fields(d.SQL)
if len(f) > 0 {
switch strings.ToUpper(f[0]) {
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "CREATE", "ALTER":
op = strings.ToUpper(f[0])
}
}
c, _ := Span(ctx, "db."+strings.ToLower(op), trace.SpanKindClient, attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op))
return c
}
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
if trace.SpanContextFromContext(ctx).IsValid() {
Result(trace.SpanFromContext(ctx), d.Err)
}
}
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
Waiting.Add(1)
if trace.SpanContextFromContext(ctx).IsValid() {
c, _ := Span(ctx, "db.pool.acquire", trace.SpanKindClient, attribute.String("db.system.name", "postgresql"))
return c
}
return ctx
}
func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
Waiting.Add(-1)
if trace.SpanContextFromContext(ctx).IsValid() {
Result(trace.SpanFromContext(ctx), data.Err)
}
}
type RedisHook struct{}
func (RedisHook) DialHook(next redis.DialHook) redis.DialHook {
return func(ctx context.Context, network, addr string) (net.Conn, error) { return next(ctx, network, addr) }
}
func (RedisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if !trace.SpanContextFromContext(ctx).IsValid() {
return next(ctx, cmd)
}
c, s := Span(ctx, "redis."+cmd.Name(), trace.SpanKindClient, attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", cmd.Name()))
err := next(c, cmd)
if err == redis.Nil {
s.End()
} else {
Result(s, err)
}
return err
}
}
func (RedisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return next
}
+93
View File
@@ -0,0 +1,93 @@
package telemetry
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"os"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
func Monitor(pool *pgxpool.Pool, role string, capacity int) error {
m := otel.Meter(Scope)
names := []string{"messenger_db_pool_used", "messenger_db_pool_idle", "messenger_db_pool_waiting", "messenger_db_pool_capacity", "messenger_worker_busy", "messenger_worker_capacity", "messenger_queue_depth", "messenger_queue_oldest_age_seconds", "messenger_db_available", "messenger_process_memory_bytes", "messenger_container_memory_bytes", "messenger_container_memory_limit_bytes", "messenger_telemetry_export_errors", "messenger_process_last_observed_seconds"}
gauges := map[string]metric.Int64ObservableGauge{}
for _, n := range names {
g, err := m.Int64ObservableGauge(n)
if err != nil {
return err
}
gauges[n] = g
}
containerCPU, _ := m.Float64ObservableCounter("messenger_container_cpu", metric.WithUnit("s"))
cpu, _ := m.Float64ObservableCounter("messenger_process_cpu", metric.WithUnit("s"))
acquired, _ := m.Int64ObservableCounter("messenger_db_pool_acquire_wait")
duration, _ := m.Float64ObservableCounter("messenger_db_pool_acquire_wait_duration", metric.WithUnit("s"))
instruments := []metric.Observable{cpu, containerCPU, acquired, duration}
for _, g := range gauges {
instruments = append(instruments, g)
}
_, err := m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
stat := pool.Stat()
observeTime := time.Now().Unix()
observe := func(n string, value int64) { o.ObserveInt64(gauges[n], value) }
observe("messenger_db_pool_used", int64(stat.AcquiredConns()))
observe("messenger_db_pool_idle", int64(stat.IdleConns()))
observe("messenger_db_pool_waiting", Waiting.Load())
observe("messenger_db_pool_capacity", int64(stat.MaxConns()))
o.ObserveInt64(acquired, stat.EmptyAcquireCount())
o.ObserveFloat64(duration, stat.EmptyAcquireWaitTime().Seconds())
observe("messenger_telemetry_export_errors", ExportErrors.Load())
observe("messenger_process_last_observed_seconds", observeTime)
if role == "worker" {
observe("messenger_worker_busy", Busy.Load())
observe("messenger_worker_capacity", int64(capacity))
}
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
observe("messenger_process_memory_bytes", int64(mem.Sys))
for file, name := range map[string]string{"memory.current": "messenger_container_memory_bytes", "memory.max": "messenger_container_memory_limit_bytes"} {
if b, e := os.ReadFile("/sys/fs/cgroup/" + file); e == nil {
if n, e := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); e == nil {
observe(name, n)
}
}
}
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 n, e := strconv.ParseFloat(fields[1], 64); e == nil {
o.ObserveFloat64(containerCPU, n/1e6)
}
}
}
}
var usage syscall.Rusage
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
o.ObserveFloat64(cpu, float64(usage.Utime.Sec+usage.Stime.Sec)+float64(usage.Utime.Usec+usage.Stime.Usec)/1e6)
}
if role == "dispatcher" {
c, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
var depth, age int64
e := pool.QueryRow(c, `SELECT count(*),COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(created_at))::bigint,0) FROM attachment_jobs WHERE state='queued'`).Scan(&depth, &age)
if e == nil {
o.ObserveInt64(gauges["messenger_queue_depth"], depth, metric.WithAttributes(attribute.String("queue", "attachment.jobs.v1")))
o.ObserveInt64(gauges["messenger_queue_oldest_age_seconds"], age, metric.WithAttributes(attribute.String("queue", "attachment.jobs.v1")))
observe("messenger_db_available", 1)
} else {
observe("messenger_db_available", 0)
}
}
return nil
}, instruments...)
return err
}
+205
View File
@@ -0,0 +1,205 @@
// Package telemetry exports bounded, asynchronous OTLP signals without business payloads.
package telemetry
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"sync/atomic"
"time"
"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"
otellog "go.opentelemetry.io/otel/log"
logglobal "go.opentelemetry.io/otel/log/global"
"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"
"go.opentelemetry.io/otel/trace"
)
const Scope = "mtusi-messenger/telemetry-v1"
var Service = "messenger-api"
var Busy atomic.Int64
var Waiting atomic.Int64
var ExportErrors atomic.Int64
var signals *Signals
type Signals struct {
Requests metric.Int64Counter
HTTPDuration metric.Float64Histogram
Jobs metric.Int64Counter
JobDuration metric.Float64Histogram
ReadyDuration metric.Float64Histogram
}
func Start(ctx context.Context, service, instance string) (func(context.Context) error, error) {
Service = service
otel.SetTextMapPropagator(propagation.TraceContext{})
attrs := []attribute.KeyValue{attribute.String("service.name", service), attribute.String("service.version", "lab6-v1"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab")}
res := resource.NewWithAttributes("https://opentelemetry.io/schemas/1.37.0", attrs...)
traceExp, err := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(2*time.Second), otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
if err != nil {
return nil, err
}
metricExp, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(2*time.Second), otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
if err != nil {
return nil, err
}
logExp, err := otlploghttp.New(ctx, otlploghttp.WithTimeout(2*time.Second), otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithBatcher(traceExp, sdktrace.WithMaxQueueSize(256), sdktrace.WithMaxExportBatchSize(64), sdktrace.WithBatchTimeout(500*time.Millisecond), sdktrace.WithExportTimeout(2*time.Second)))
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(2*time.Second))))
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp, sdklog.WithMaxQueueSize(256), sdklog.WithExportMaxBatchSize(64), sdklog.WithExportInterval(500*time.Millisecond), sdklog.WithExportTimeout(2*time.Second))))
otel.SetTracerProvider(tp)
otel.SetMeterProvider(mp)
logglobal.SetLoggerProvider(lp)
// No exporter/network details, payloads or credentials are logged on errors.
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { ExportErrors.Add(1) }))
meter := otel.Meter(Scope)
s := &Signals{}
s.Requests, err = meter.Int64Counter("messenger_http_requests")
if err != nil {
return nil, err
}
buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120}
s.HTTPDuration, _ = meter.Float64Histogram("messenger_http_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
s.Jobs, _ = meter.Int64Counter("messenger_jobs_processed")
s.JobDuration, _ = meter.Float64Histogram("messenger_job_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
s.ReadyDuration, _ = meter.Float64Histogram("messenger_time_to_ready", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.1, .5, 1, 5, 10, 30, 60, 120, 300, 900, 3600, 86400))
signals = s
return func(c context.Context) error {
// Shared deadline bounds shutdown across all signals.
a := tp.Shutdown(c)
b := mp.Shutdown(c)
d := lp.Shutdown(c)
if a != nil || b != nil || d != nil {
return fmt.Errorf("telemetry shutdown incomplete")
}
return nil
}, nil
}
func Span(ctx context.Context, name string, kind trace.SpanKind, attrs ...attribute.KeyValue) (context.Context, trace.Span) {
return otel.Tracer(Scope).Start(ctx, name, trace.WithSpanKind(kind), trace.WithAttributes(attrs...))
}
func Result(span trace.Span, err error) {
if err != nil {
span.SetStatus(codes.Error, "dependency unavailable")
span.SetAttributes(attribute.Bool("error", true))
}
span.End()
}
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})
}
type requestKey struct{}
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestKey{}, id)
}
func RequestID(ctx context.Context) string { v, _ := ctx.Value(requestKey{}).(string); return v }
func Event(ctx context.Context, event string, fields map[string]any) {
sc := trace.SpanContextFromContext(ctx)
body := map[string]any{"timestamp": time.Now().UTC().Format(time.RFC3339Nano), "severity": "INFO", "service.name": Service, "event": event}
if sc.IsValid() {
body["trace_id"] = sc.TraceID().String()
body["span_id"] = sc.SpanID().String()
}
if id, ok := ctx.Value(requestKey{}).(string); ok {
body["request_id"] = id
}
for k, v := range fields {
body[k] = v
}
severity := otellog.SeverityInfo
if status, ok := fields["status"].(int); ok && status >= 500 {
severity = otellog.SeverityError
}
if outcome, ok := fields["outcome"].(string); ok && (outcome == "failed" || outcome == "retry" || outcome == "abandoned") {
severity = otellog.SeverityError
}
if severity == otellog.SeverityError {
body["severity"] = "ERROR"
}
encoded, _ := json.Marshal(body)
_, _ = os.Stdout.Write(append(encoded, '\n'))
var record otellog.Record
record.SetTimestamp(time.Now())
record.SetSeverity(severity)
record.SetSeverityText(body["severity"].(string))
record.SetBody(otellog.StringValue(string(encoded)))
record.AddAttributes(otellog.String("event", event))
logglobal.GetLoggerProvider().Logger(Scope).Emit(ctx, record)
}
func HTTP(ctx context.Context, method, route string, status int, elapsed time.Duration) {
if signals == nil {
return
}
a := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", fmt.Sprintf("%dxx", status/100)))
signals.Requests.Add(ctx, 1, a)
signals.HTTPDuration.Record(ctx, elapsed.Seconds(), a)
}
func Job(ctx context.Context, outcome string, d time.Duration) {
if signals == nil {
return
}
a := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
signals.Jobs.Add(ctx, 1, a)
signals.JobDuration.Record(ctx, d.Seconds(), a)
}
func Ready(ctx context.Context, d time.Duration) {
if signals != nil {
signals.ReadyDuration.Record(ctx, d.Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process.v1")))
}
}
func Method(s string) string {
switch s {
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
return s
}
return "OTHER"
}
func Route(path string) string {
switch path {
case "/health/live", "/health/ready", "/api/v1/users", "/api/v1/users/me", "/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
return path
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" {
if parts[2] == "chats" {
if len(parts) == 4 {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 5 && (parts[4] == "messages" || parts[4] == "attachments") {
return "/api/v1/chats/{chat_id}/" + parts[4]
}
}
if parts[2] == "attachments" {
if len(parts) == 4 {
return "/api/v1/attachments/{attachment_id}"
}
if len(parts) == 5 && parts[4] == "content" {
return "/api/v1/attachments/{attachment_id}/content"
}
}
}
return "/unmatched"
}
+28
View File
@@ -0,0 +1,28 @@
package telemetry
import (
"strings"
"testing"
)
func TestRouteLabelsNeverContainResourceIDs(t *testing.T) {
ids := []string{"11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"}
for _, id := range ids {
cases := map[string]string{
"/api/v1/chats/" + id: "/api/v1/chats/{chat_id}",
"/api/v1/chats/" + id + "/messages": "/api/v1/chats/{chat_id}/messages",
"/api/v1/chats/" + id + "/attachments": "/api/v1/chats/{chat_id}/attachments",
"/api/v1/attachments/" + id + "/content": "/api/v1/attachments/{attachment_id}/content",
"/arbitrary/" + id: "/unmatched",
}
for input, want := range cases {
got := Route(input)
if got != want || strings.Contains(got, id) {
t.Fatalf("unsafe route label %q for %q", got, input)
}
}
}
if Method("CUSTOM-USER-METHOD") != "OTHER" {
t.Fatal("unbounded method label")
}
}