Реализация на 5

This commit is contained in:
Grbisba
2026-11-13 12:48:18 +03:00
parent ce035c8528
commit 2198368a44
60 changed files with 3253 additions and 181 deletions
+10
View File
@@ -27,6 +27,7 @@ import (
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"gitea.privcloud.tech/mtusi2026/internal/service/user"
"github.com/google/uuid"
stdhttp "net/http"
@@ -56,6 +57,9 @@ func run() error {
if err != nil {
return err
}
if len(os.Args) > 1 && (os.Args[1] == "worker" || os.Args[1] == "dispatcher" || os.Args[1] == "jobs" || os.Args[1] == "outbox") {
return runPipeline(cfg, attachmentConfig, os.Args[1:])
}
if len(os.Args) > 1 && os.Args[1] == "storage" {
return runStorage(cfg, attachmentConfig, os.Args[2:])
}
@@ -91,6 +95,12 @@ func run() error {
chatSvc := chat.New(tm, chatsRepo, messageRepo, chatCache)
objectStore := objectstore.New(attachmentConfig)
attachmentSvc := attachment.New(&storage.AttachmentsRepo{Pool: pgx}, objectStore, attachmentConfig, chatSvc)
pipelineConfig, err := config.LoadPipeline()
if err != nil {
return err
}
outboxSvc := outbox.New(&storage.OutboxRepo{Pool: pgx}, tm, nil)
attachmentSvc.Configure(tm, outboxSvc, pipelineConfig)
httpRouter := router.New(
middleware.NewAuthMiddleware(authSvc),
+138
View File
@@ -0,0 +1,138 @@
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"gitea.privcloud.tech/mtusi2026/internal/adapter/broker"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
)
func runPipeline(cfg *config.Config, a *config.Attachment, args []string) error {
c, e := config.LoadPipeline()
if e != nil {
return e
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
pool := postgres.New(cfg.Postgres)
defer pool.Close()
tm := txmanager.New(pool)
repo := &storage.AttachmentsRepo{Pool: pool}
rabbit := &broker.Rabbit{URL: c.BrokerURL}
ob := outbox.New(&storage.OutboxRepo{Pool: pool}, tm, rabbit)
svc := attachment.New(repo, objectstore.New(a), a, nil)
svc.Configure(tm, ob, c)
ob.OnDead = svc.PublishFailed
if args[0] == "jobs" || args[0] == "outbox" {
if len(args) < 2 {
return errors.New("operator action required")
}
fs := flag.NewFlagSet(args[1], flag.ContinueOnError)
idText := fs.String("id", "", "job ID (attachment ID for reprocess)")
version := fs.Int("pipeline-version", 2, "new pipeline version")
if e = fs.Parse(args[2:]); e != nil {
return e
}
if args[1] == "list" {
jobs, e := repo.ListJobs(ctx)
if e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(jobs)
}
id, e := uuid.Parse(*idText)
if e != nil {
return e
}
switch args[1] {
case "redeliver":
if os.Getenv("LAB5_FAULTS") != "1" {
return errors.New("redeliver is restricted to the explicit fault profile")
}
var payload []byte
e = tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
j, e := repo.JobTx(ctx, tx, id)
if e != nil {
return e
}
payload, e = json.Marshal(j.Message)
return e
})
if e == nil {
e = rabbit.Publish(ctx, outbox.DeliveryMessage{ID: uuid.New(), AggregateID: id, Payload: payload})
}
case "replay":
e = svc.Replay(ctx, id)
case "reprocess":
e = svc.Reprocess(ctx, id, *version)
default:
return errors.New("unknown operator action")
}
if e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"accepted": true, "id": id})
}
if c.BrokerURL == "" {
return errors.New("BROKER_URL_FILE is required")
}
if args[0] == "worker" {
// Recovery continues while the consumer is disconnected or a delivery is paused.
recoveryDone := make(chan struct{})
defer func() { stop(); <-recoveryDone }()
go func() {
defer close(recoveryDone)
tick := time.NewTicker(time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if e := svc.Recover(ctx); e != nil {
slog.Warn("job_recovery_failed")
}
if e := svc.Cleanup(ctx); e != nil {
slog.Warn("source_cleanup_failed")
}
}
}
}()
for ctx.Err() == nil {
if e = rabbit.Consume(ctx, c.Concurrency, c.Prefetch, svc.Process); e != nil && ctx.Err() == nil {
slog.Warn("consumer_reconnecting")
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
return nil
}
for ctx.Err() == nil {
_, e = ob.ProcessOnce(ctx)
if e != nil {
slog.Warn("dispatcher_retry")
}
select {
case <-ctx.Done():
case <-time.After(100 * time.Millisecond):
}
}
return nil
}
+8
View File
@@ -20,7 +20,9 @@ import (
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
)
func runStorage(cfg *config.Config, c *config.Attachment, args []string) error {
@@ -93,6 +95,12 @@ func runStorage(cfg *config.Config, c *config.Attachment, args []string) error {
pool := postgres.New(cfg.Postgres)
defer pool.Close()
svc := attachment.New(&storage.AttachmentsRepo{Pool: pool}, store, c, nil)
jobs, e := config.LoadPipeline()
if e != nil {
return e
}
tm := txmanager.New(pool)
svc.Configure(tm, outbox.New(&storage.OutboxRepo{Pool: pool}, tm, nil), jobs)
switch args[0] {
case "reconcile":
fs := flag.NewFlagSet("reconcile", flag.ContinueOnError)
+1
View File
@@ -52,6 +52,7 @@ require (
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 // indirect
github.com/rabbitmq/amqp091-go v1.10.0 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
+2
View File
@@ -94,6 +94,8 @@ github.com/oapi-codegen/runtime v1.4.2/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/Ge
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 h1:gIZQQ2+wbsdQGWLPDSdJFptR25tBCjSC0KbSIQZ1rgE=
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
+170
View File
@@ -0,0 +1,170 @@
package broker
import (
"bytes"
"context"
"encoding/json"
"errors"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/fault"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
"io"
"log/slog"
"net"
"regexp"
"time"
)
const Queue = "attachments.v1"
var tracePattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
type Rabbit struct{ URL string }
func (r *Rabbit) connect(deadline time.Duration) (*amqp.Connection, *amqp.Channel, error) {
dial := amqp.DefaultDial(5 * time.Second)
if deadline > 0 {
dial = func(network, address string) (net.Conn, error) {
c, e := net.DialTimeout(network, address, 5*time.Second)
if e != nil {
return nil, e
}
if e = c.SetDeadline(time.Now().Add(deadline)); e != nil {
c.Close()
return nil, e
}
return c, nil
}
}
conn, e := amqp.DialConfig(r.URL, amqp.Config{Heartbeat: 10 * time.Second, Dial: dial})
if e != nil {
return nil, nil, errors.New("broker connection unavailable")
}
ch, e := conn.Channel()
if e != nil {
conn.Close()
return nil, nil, errors.New("broker channel unavailable")
}
_, e = ch.QueueDeclare(Queue+".invalid", true, false, false, false, nil)
if e == nil {
e = ch.ExchangeDeclare("attachments.invalid", "direct", true, false, false, false, nil)
}
if e == nil {
e = ch.QueueBind(Queue+".invalid", "invalid", "attachments.invalid", false, nil)
}
if e == nil {
_, e = ch.QueueDeclare(Queue, true, false, false, false, amqp.Table{"x-dead-letter-exchange": "attachments.invalid", "x-dead-letter-routing-key": "invalid"})
}
if e != nil {
ch.Close()
conn.Close()
return nil, nil, errors.New("broker topology unavailable")
}
return conn, ch, nil
}
func (r *Rabbit) Publish(ctx context.Context, m outbox.DeliveryMessage) error {
conn, ch, e := r.connect(20 * time.Second)
if e != nil {
return e
}
defer conn.Close()
defer ch.Close()
if e = ch.Confirm(false); e != nil {
return e
}
confirms := ch.NotifyPublish(make(chan amqp.Confirmation, 1))
returns := ch.NotifyReturn(make(chan amqp.Return, 1))
var job dto.JobMessage
if e = json.Unmarshal(m.Payload, &job); e != nil {
return e
}
fault.Hit(ctx, "before_publish", job.JobID)
if e = ch.PublishWithContext(ctx, "", Queue, true, false, amqp.Publishing{DeliveryMode: amqp.Persistent, ContentType: "application/json", MessageId: m.ID.String(), Body: m.Payload}); e != nil {
return errors.New("broker publish failed")
}
select {
case c, ok := <-confirms:
if !ok || !c.Ack {
return errors.New("broker did not confirm")
}
select {
case <-returns:
return errors.New("unroutable job")
default:
}
case <-time.After(15 * time.Second):
return errors.New("confirm timeout")
case <-ctx.Done():
return ctx.Err()
}
fault.Hit(ctx, "after_publish", job.JobID)
return nil
}
func (r *Rabbit) Consume(ctx context.Context, concurrency, prefetch int, process func(context.Context, dto.JobMessage) error) error {
conn, ch, e := r.connect(0)
if e != nil {
return e
}
defer conn.Close()
defer ch.Close()
if e = ch.Qos(prefetch, 0, false); e != nil {
return e
}
deliveries, e := ch.Consume(Queue, "worker-"+uuid.NewString(), false, false, false, false, nil)
if e != nil {
return e
}
done := make(chan struct{})
go func() {
select {
case <-ctx.Done():
conn.Close()
case <-done:
}
}()
defer close(done)
tasks := make(chan amqp.Delivery)
finished := make(chan struct{}, concurrency)
for range concurrency {
go func() {
defer func() { finished <- struct{}{} }()
for d := range tasks {
var m dto.JobMessage
dec := json.NewDecoder(bytes.NewReader(d.Body))
dec.DisallowUnknownFields()
e := dec.Decode(&m)
if e != nil || dec.Decode(new(any)) != io.EOF || m.SchemaVersion != 1 || m.Type != "attachment.process.v1" || m.JobID == uuid.Nil || m.AttachmentID == uuid.Nil || m.Attempt < 1 || m.PipelineVersion < 1 || m.CreatedAt.IsZero() || len(m.Tracestate) > 512 || (m.Traceparent != "" && !tracePattern.MatchString(m.Traceparent)) {
_ = d.Reject(false)
continue
}
if e = process(ctx, m); e != nil {
slog.Warn("job_not_acknowledged", "job_id", m.JobID, "reason", "processing_or_dependency_unavailable")
select {
case <-ctx.Done():
case <-time.After(200 * time.Millisecond):
}
_ = d.Nack(false, true)
continue
}
fault.Hit(ctx, "before_ack", m.JobID)
_ = d.Ack(false)
}
}()
}
for d := range deliveries {
select {
case tasks <- d:
case <-ctx.Done():
}
}
close(tasks)
for range concurrency {
<-finished
}
if ctx.Err() != nil {
return ctx.Err()
}
return errors.New("broker consumer disconnected")
}
@@ -1,12 +1,14 @@
package http
import (
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"io"
"mime"
"net/http"
"strconv"
"strings"
@@ -41,7 +43,20 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one filename"))
return
}
a, e := h.svc.Upload(w, r, user.UserID, id, values[0])
if !attachment.ValidFilename(values[0]) {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid filename"))
return
}
mt, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
if e != nil || (mt != "image/png" && mt != "image/jpeg") {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected PNG or JPEG"))
return
}
if r.ContentLength > h.svc.Config.MaxBytes {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodePayloadTooLarge, "upload too large"))
return
}
a, e := h.svc.Upload(r.Context(), dto.UploadAttachment{UserID: user.UserID, ChatID: id, Filename: values[0], ContentType: mt, Body: io.LimitReader(r.Body, h.svc.Config.MaxBytes+1)})
if e != nil {
if apperr.CodeFromError(e) == apperr.CodeTooManyRequests {
w.Header().Set("Retry-After", "1")
@@ -49,7 +64,7 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
framework.JSONError(r.Context(), w, e)
return
}
framework.JSONResponse(w, http.StatusCreated, a)
framework.JSONResponse(w, http.StatusAccepted, a)
}
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
user, e := framework.ParseToken(r, h.provider)
@@ -61,27 +76,32 @@ func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
if e != nil {
return
}
a, e := h.svc.Get(r.Context(), user.UserID, id)
if !strings.HasSuffix(r.URL.Path, "/content") {
a, e := h.svc.Get(r.Context(), user.UserID, id)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
framework.JSONResponse(w, 200, a.Public)
return
}
v := r.URL.Query().Get("variant")
if v == "" {
v = "original"
}
if v != "original" && v != "thumbnail" && v != "crop" && v != "optimized" {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid variant"))
return
}
obj, e := h.svc.Content(r.Context(), user.UserID, id, v)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
if !strings.HasSuffix(r.URL.Path, "/content") {
framework.JSONResponse(w, 200, a.Public)
return
}
if v := r.URL.Query().Get("variant"); v != "" && v != "original" {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid variant"))
return
}
obj, e := h.svc.Store.Get(r.Context(), a.Key)
if e != nil {
framework.JSONError(r.Context(), w, attachment.Unavailable())
return
}
defer obj.Body.Close()
w.Header().Set("Content-Type", string(a.Public.ContentType))
w.Header().Set("Content-Length", strconv.Itoa(a.Public.SizeBytes))
w.Header().Set("Content-Type", obj.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(obj.Size, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
// Once streaming has started a transport failure terminates the response; no JSON
// error can be appended to an image. Content-Length exposes incomplete downloads.
@@ -25,10 +25,15 @@ func (r *AttachmentsRepo) Page(ctx context.Context, after uuid.UUID) ([]*Attachm
}
func (r *AttachmentsRepo) Exists(ctx context.Context, c *pgxpool.Conn, key string) (bool, error) {
var found bool
e := c.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&found)
e := c.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachment_variants WHERE object_key=$1 UNION ALL SELECT 1 FROM attachments WHERE object_key=$1 OR staging_key=$1 OR variant_keys @> jsonb_build_object('thumbnail',$1::text) OR variant_keys @> jsonb_build_object('crop',$1::text) OR variant_keys @> jsonb_build_object('optimized',$1::text))", key).Scan(&found)
return found, e
}
func (r *AttachmentsRepo) MarkMissing(ctx context.Context, c *pgxpool.Conn, id uuid.UUID, missing bool) (bool, error) {
tag, e := c.Exec(ctx, "UPDATE attachments SET integrity_missing=$2,updated_at=clock_timestamp() WHERE id=$1 AND integrity_missing<>$2", id, missing)
return tag.RowsAffected() == 1, e
}
func (r *AttachmentsRepo) CheckConn(ctx context.Context, c *pgxpool.Conn) error {
_, e := c.Exec(ctx, "SELECT 1")
return e
}
@@ -8,40 +8,34 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type AttachmentRecord struct {
Public contracts.Attachment
Key string
Missing bool
}
type AttachmentRecord = dto.AttachmentRecord
type AttachmentsRepo struct{ Pool *pgxpool.Pool }
const AttachmentColumns = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,integrity_missing"
const AttachmentColumns = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,integrity_missing,status,error_code,pipeline_version,staging_key,variants,variant_keys"
func ScanAttachment(row pgx.Row) (*AttachmentRecord, error) {
a := new(AttachmentRecord)
p := &a.Public
if err := row.Scan(&p.Id, &p.ChatId, &p.OwnerId, &p.Filename, &p.ContentType, &p.SizeBytes, &p.Sha256, &p.CreatedAt, &p.UpdatedAt, &a.Key, &a.Missing); err != nil {
var variants, keys []byte
if err := row.Scan(&p.Id, &p.ChatId, &p.OwnerId, &p.Filename, &p.ContentType, &p.SizeBytes, &p.Sha256, &p.CreatedAt, &p.UpdatedAt, &a.Key, &a.Missing, &p.Status, &p.ErrorCode, &a.PipelineVersion, &a.StagingKey, &variants, &keys); err != nil {
return nil, apperr.WrapPostgres(err, "attachment unavailable")
}
p.Status = "ready"
p.Variants = []contracts.Variant{}
if err := json.Unmarshal(variants, &p.Variants); err != nil {
return nil, err
}
if err := json.Unmarshal(keys, &a.VariantKeys); err != nil {
return nil, err
}
return a, nil
}
func (r *AttachmentsRepo) Get(ctx context.Context, id uuid.UUID) (*AttachmentRecord, error) {
return ScanAttachment(r.Pool.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1", id))
}
func (r *AttachmentsRepo) Save(ctx context.Context, conn *pgxpool.Conn, a *AttachmentRecord) error {
p := a.Public
_, e := conn.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, p.Id, p.ChatId, p.OwnerId, p.Filename, p.ContentType, p.SizeBytes, p.Sha256, p.CreatedAt, p.UpdatedAt, a.Key)
if e != nil {
return apperr.WrapPostgres(e, "failed to save attachment")
}
return nil
}
// Session locks span S3 work and the database commit. A lost connection releases
// the lock; the mandatory grace period also exceeds the maximum upload lifetime.
@@ -58,7 +58,7 @@ func TestIdempotencyTransactionAndExpiry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err != nil {
if _, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, req); err != nil {
t.Fatal(err)
}
if err = tx.Rollback(ctx); err != nil {
@@ -75,7 +75,7 @@ func TestIdempotencyTransactionAndExpiry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
first, err := repo.CreateIdempotentTx(ctx, tx, req)
first, err := chatsvc.CreateIdempotentTx(ctx, tx, repo, req)
if err != nil {
t.Fatal(err)
}
@@ -91,7 +91,7 @@ func TestIdempotencyTransactionAndExpiry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
second, err := repo.CreateIdempotentTx(ctx, tx, req)
second, err := chatsvc.CreateIdempotentTx(ctx, tx, repo, req)
if err != nil {
t.Fatal(err)
}
@@ -115,7 +115,7 @@ func TestIdempotencyTransactionAndExpiry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err == nil {
if _, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, req); err == nil {
t.Fatal("expected injected failure")
}
if err = tx.Rollback(ctx); err != nil {
@@ -134,7 +134,7 @@ func TestIdempotencyTransactionAndExpiry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err != nil {
if _, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, req); err != nil {
t.Fatal("transient failure was cached", err)
}
if err = tx.Commit(ctx); err != nil {
@@ -257,7 +257,7 @@ func TestIdempotencyTransactionAndExpiry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
_, err = repo.CreateIdempotentTx(ctx, tx, dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: "link rollback", AttachmentIDs: []uuid.UUID{own, uuid.New()}})
_, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: "link rollback", AttachmentIDs: []uuid.UUID{own, uuid.New()}})
if err == nil {
t.Fatal("expected missing attachment FK failure")
}
@@ -0,0 +1,134 @@
package storage
import (
"context"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"time"
)
func (r *AttachmentsRepo) Ping(ctx context.Context) error { return r.Pool.Ping(ctx) }
func (r *AttachmentsRepo) GetTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.AttachmentRecord, error) {
return ScanAttachment(tx.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1 FOR UPDATE", id))
}
func (r *AttachmentsRepo) InsertTx(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
p := a.Public
_, e := tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,staging_key,status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$10,$11)`, p.Id, p.ChatId, p.OwnerId, p.Filename, p.ContentType, p.SizeBytes, p.Sha256, p.CreatedAt, p.UpdatedAt, a.StagingKey, p.Status)
return e
}
func (r *AttachmentsRepo) UpdateTx(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
variants, e := json.Marshal(a.Public.Variants)
if e != nil {
return e
}
keys, e := json.Marshal(a.VariantKeys)
if e != nil {
return e
}
_, e = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,pipeline_version=$4,staging_key=$5,object_key=$6,variants=$7,variant_keys=$8,updated_at=$9,integrity_missing=$10 WHERE id=$1`, a.Public.Id, a.Public.Status, a.Public.ErrorCode, a.PipelineVersion, a.StagingKey, a.Key, variants, keys, a.Public.UpdatedAt, a.Missing)
return e
}
const jobColumns = `id,attachment_id,pipeline_version,attempt,created_at,state,token,lease_until,next_attempt_at,attempt_limit,error_code,updated_at`
func scanJob(row pgx.Row) (*dto.AttachmentJob, error) {
j := new(dto.AttachmentJob)
m := &j.Message
err := row.Scan(&m.JobID, &m.AttachmentID, &m.PipelineVersion, &m.Attempt, &m.CreatedAt, &j.State, &j.Token, &j.LeaseUntil, &j.NextAttemptAt, &j.AttemptLimit, &j.ErrorCode, &j.UpdatedAt)
m.SchemaVersion = 1
m.Type = "attachment.process.v1"
return j, err
}
func (r *AttachmentsRepo) JobTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.AttachmentJob, error) {
return scanJob(tx.QueryRow(ctx, `SELECT `+jobColumns+` FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id))
}
func (r *AttachmentsRepo) InsertJobTx(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
m := j.Message
_, e := tx.Exec(ctx, `INSERT INTO attachment_jobs(`+jobColumns+`) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, m.JobID, m.AttachmentID, m.PipelineVersion, m.Attempt, m.CreatedAt, j.State, j.Token, j.LeaseUntil, j.NextAttemptAt, j.AttemptLimit, j.ErrorCode, j.UpdatedAt)
return e
}
func (r *AttachmentsRepo) SaveJobTx(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
_, e := tx.Exec(ctx, `UPDATE attachment_jobs SET attempt=$2,state=$3,token=$4,lease_until=$5,next_attempt_at=$6,attempt_limit=$7,error_code=$8,updated_at=$9 WHERE id=$1`, j.Message.JobID, j.Message.Attempt, j.State, j.Token, j.LeaseUntil, j.NextAttemptAt, j.AttemptLimit, j.ErrorCode, j.UpdatedAt)
return e
}
func (r *AttachmentsRepo) ExpiredJobs(ctx context.Context) ([]uuid.UUID, error) {
rows, e := r.Pool.Query(ctx, `SELECT id FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() ORDER BY lease_until LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if e = rows.Scan(&id); e != nil {
return nil, e
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *AttachmentsRepo) AuditTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, action string) error {
_, e := tx.Exec(ctx, `INSERT INTO job_audit(job_id,action) VALUES($1,$2)`, id, action)
return e
}
func (r *AttachmentsRepo) ListJobs(ctx context.Context) ([]dto.AttachmentJob, error) {
rows, e := r.Pool.Query(ctx, `SELECT `+jobColumns+` FROM attachment_jobs ORDER BY updated_at DESC LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
out := []dto.AttachmentJob{}
for rows.Next() {
j, e := scanJob(rows)
if e != nil {
return nil, e
}
out = append(out, *j)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) FailedOutbox(ctx context.Context) ([]uuid.UUID, error) {
rows, e := r.Pool.Query(ctx, `SELECT DISTINCT o.job_id FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.status='dead_letter' AND j.state='queued' AND (o.payload->>'attempt')::integer=j.attempt LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if e = rows.Scan(&id); e != nil {
return nil, e
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *AttachmentsRepo) RetiredSources(ctx context.Context, before time.Time) ([]*dto.AttachmentRecord, error) {
rows, e := r.Pool.Query(ctx, `SELECT `+AttachmentColumns+` FROM attachments WHERE staging_key<>'' AND (status='ready' OR (status='failed' AND updated_at<$1)) LIMIT 100`, before)
if e != nil {
return nil, e
}
defer rows.Close()
var out []*dto.AttachmentRecord
for rows.Next() {
a, e := ScanAttachment(rows)
if e != nil {
return nil, e
}
out = append(out, a)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) SaveVariantTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, version int, name, key, sha string, size int64) error {
_, e := tx.Exec(ctx, `INSERT INTO attachment_variants(attachment_id,pipeline_version,variant,object_key,sha256,size_bytes) VALUES($1,$2,$3,$4,$5,$6)`, id, version, name, key, sha, size)
return e
}
func (r *AttachmentsRepo) PublicationDeadTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, attempt int) (bool, error) {
var dead bool
e := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM outbox WHERE job_id=$1 AND status='dead_letter' AND (payload->>'attempt')::integer=$2)`, id, attempt).Scan(&dead)
return dead, e
}
@@ -1,10 +1,8 @@
package storage
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"time"
@@ -26,55 +24,49 @@ func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
return &MessagesRepo{pool: pool}
}
// CreateIdempotentTx serializes only requests sharing an idempotency scope.
// The transaction commits both the message and its replay record, or neither.
func (r *MessagesRepo) CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error) {
scope := req.SenderID.String() + ":POST:" + req.ChatID.String() + ":" + req.IdempotencyKey
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, scope); err != nil {
return nil, apperr.WrapPostgres(err, "failed to lock message key")
// LockKeyTx serializes persistence for one idempotency scope.
func (r *MessagesRepo) LockKeyTx(ctx context.Context, tx pgx.Tx, scope string) error {
_, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, scope)
if err != nil {
return apperr.WrapPostgres(err, "failed to lock message key")
}
hash := messageHash(req)
var hashVersion int
var storedHash []byte
var messageID uuid.UUID
err := tx.QueryRow(ctx, `SELECT request_hash, message_id, hash_version FROM message_idempotency
WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`,
req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&storedHash, &messageID, &hashVersion)
if err == nil {
if hashVersion == 1 && len(req.AttachmentIDs) == 0 {
hash = sha256.Sum256([]byte(req.Text))
} else if hashVersion != 2 {
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
}
if !bytes.Equal(hash[:], storedHash) {
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
}
return scanMessage(tx.QueryRow(ctx, `SELECT `+messageColumns+` FROM messages WHERE id=$1`, messageID))
return nil
}
func (r *MessagesRepo) ReplayTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.MessageReplay, error) {
v := new(dto.MessageReplay)
err := tx.QueryRow(ctx, `SELECT request_hash,message_id,hash_version FROM message_idempotency WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`, req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&v.Hash, &v.MessageID, &v.HashVersion)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to read message key")
}
message := dto.Message{ID: uuid.New(), ChatID: req.ChatID, SenderID: req.SenderID, Text: req.Text, AttachmentIDs: append([]uuid.UUID{}, req.AttachmentIDs...), CreatedAt: time.Now().UTC().Truncate(time.Microsecond)}
if _, err = tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`,
message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt); err != nil {
return v, nil
}
func (r *MessagesRepo) MessageTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.Message, error) {
return scanMessage(tx.QueryRow(ctx, `SELECT `+messageColumns+` FROM messages WHERE id=$1`, id))
}
func (r *MessagesRepo) InsertMessageTx(ctx context.Context, tx pgx.Tx, message dto.Message) error {
_, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`, message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
if err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == pgerrcode.ForeignKeyViolation {
return nil, apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
}
return nil, apperr.WrapPostgres(err, "failed to create message")
return apperr.WrapPostgres(err, "failed to create message")
}
for position, attachmentID := range req.AttachmentIDs {
if _, err = tx.Exec(ctx, `INSERT INTO message_attachments(message_id,chat_id,attachment_id,position) VALUES($1,$2,$3,$4)`, message.ID, message.ChatID, attachmentID, position); err != nil {
return nil, apperr.WrapPostgres(err, "failed to link attachment")
for position, id := range message.AttachmentIDs {
if _, err = tx.Exec(ctx, `INSERT INTO message_attachments(message_id,chat_id,attachment_id,position) VALUES($1,$2,$3,$4)`, message.ID, message.ChatID, id, position); err != nil {
return apperr.WrapPostgres(err, "failed to link attachment")
}
}
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at,hash_version)
VALUES($1,'POST',$2,$3,$4,$5,clock_timestamp()+interval '24 hours',2)
ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,
message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at,hash_version=EXCLUDED.hash_version`, req.SenderID, req.ChatID, req.IdempotencyKey, hash[:], message.ID); err != nil {
return nil, apperr.WrapPostgres(err, "failed to save message key")
return nil
}
func (r *MessagesRepo) SaveKeyTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage, hash []byte, messageID uuid.UUID, expires time.Time) error {
_, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at,hash_version) VALUES($1,'POST',$2,$3,$4,$5,$6,2) ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at,hash_version=EXCLUDED.hash_version`, req.SenderID, req.ChatID, req.IdempotencyKey, hash, messageID, expires)
if err != nil {
return apperr.WrapPostgres(err, "failed to save message key")
}
return &message, nil
return nil
}
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
@@ -120,20 +112,10 @@ func scanMessage(row pgx.Row) (*dto.Message, error) {
const messageColumns = `id, chat_id, sender_id, text, created_at,
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=messages.id ORDER BY position)`
func messageHash(req dto.CreateMessage) [32]byte {
// Field order and a non-nil list define the canonical v2 representation.
canonical := struct {
Text string `json:"text"`
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
}{req.Text, append([]uuid.UUID{}, req.AttachmentIDs...)}
encoded, _ := json.Marshal(canonical) // strings and UUIDs have no encoding failures.
return sha256.Sum256(encoded)
}
func (r *MessagesRepo) AttachmentsForMessageTx(ctx context.Context, tx pgx.Tx, ids []uuid.UUID) ([]dto.MessageAttachment, error) {
// Prevent a concurrent integrity update from invalidating the checked rows
// until the message and its links have committed together.
rows, err := tx.Query(ctx, `SELECT id, chat_id, integrity_missing FROM attachments WHERE id=ANY($1) ORDER BY id FOR SHARE`, ids)
rows, err := tx.Query(ctx, `SELECT id, chat_id, integrity_missing,status FROM attachments WHERE id=ANY($1) ORDER BY id FOR SHARE`, ids)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to read attachments")
}
@@ -141,7 +123,7 @@ func (r *MessagesRepo) AttachmentsForMessageTx(ctx context.Context, tx pgx.Tx, i
result := make([]dto.MessageAttachment, 0, len(ids))
for rows.Next() {
var a dto.MessageAttachment
if err := rows.Scan(&a.ID, &a.ChatID, &a.Missing); err != nil {
if err := rows.Scan(&a.ID, &a.ChatID, &a.Missing, &a.Status); err != nil {
return nil, apperr.WrapPostgres(err, "failed to read attachment")
}
result = append(result, a)
@@ -0,0 +1,52 @@
package storage
import (
"context"
"errors"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"time"
)
type OutboxRepo struct{ Pool *pgxpool.Pool }
func (r *OutboxRepo) CreateTx(ctx context.Context, tx pgx.Tx, q outbox.CreateMessageReq) (outbox.CreateMessageRes, error) {
_, e := tx.Exec(ctx, `INSERT INTO outbox(id,job_id,payload,status,max_attempts,token,next_attempt_at,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$7,$7)`, q.ID, q.AggregateID, q.Payload, q.Status, q.MaxAttempts, uuid.New(), q.CreatedAt)
return outbox.CreateMessageRes{ID: q.ID, CreatedAt: q.CreatedAt}, e
}
func scanOutbox(rows pgx.Rows) (out []outbox.AcquiredMessage, err error) {
defer rows.Close()
for rows.Next() {
var m outbox.AcquiredMessage
if err = rows.Scan(&m.ID, &m.AggregateID, &m.Payload, &m.Attempts, &m.MaxAttempts, &m.Token); err != nil {
return
}
out = append(out, m)
}
err = rows.Err()
return
}
func (r *OutboxRepo) AcquireManyForProcessing(ctx context.Context, q outbox.AcquireMessagesForProcessingReq) ([]outbox.AcquiredMessage, error) {
rows, e := r.Pool.Query(ctx, `WITH picked AS (SELECT id FROM outbox WHERE status IN ('pending','failed') AND next_attempt_at<=clock_timestamp() ORDER BY next_attempt_at,id LIMIT $1 FOR UPDATE SKIP LOCKED)
UPDATE outbox o SET status='processing',attempts=attempts+1,token=$2,locked_until=clock_timestamp()+$3::interval,updated_at=clock_timestamp() FROM picked p WHERE o.id=p.id RETURNING o.id,o.job_id,o.payload,o.attempts,o.max_attempts,o.token`, q.Limit, uuid.New(), q.LockDuration.String())
if e != nil {
return nil, e
}
return scanOutbox(rows)
}
func (r *OutboxRepo) Expired(ctx context.Context) ([]outbox.AcquiredMessage, error) {
rows, e := r.Pool.Query(ctx, `SELECT id,job_id,payload,attempts,max_attempts,token FROM outbox WHERE status='processing' AND locked_until<clock_timestamp() LIMIT 100`)
if e != nil {
return nil, e
}
return scanOutbox(rows)
}
func (r *OutboxRepo) Update(ctx context.Context, m outbox.AcquiredMessage, status outbox.Status, next time.Time, code string) error {
tag, e := r.Pool.Exec(ctx, `UPDATE outbox SET status=$3,next_attempt_at=$4,last_error=NULLIF($5,''),locked_until=NULL,updated_at=clock_timestamp() WHERE id=$1 AND token=$2 AND status='processing'`, m.ID, m.Token, status, next, code)
if e == nil && tag.RowsAffected() != 1 {
return errors.New("outbox lease lost")
}
return e
}
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Pipeline struct {
Concurrency, Prefetch, MaxAttempts int
Timeout, Lease, Retention time.Duration
BrokerURL string
}
func LoadPipeline() (*Pipeline, error) {
c := &Pipeline{Concurrency: 2, Prefetch: 2, MaxAttempts: 5, Timeout: 60 * time.Second, Lease: 90 * time.Second, Retention: 24 * time.Hour}
for k, p := range map[string]*int{"WORKER_CONCURRENCY": &c.Concurrency, "WORKER_PREFETCH": &c.Prefetch, "JOB_MAX_ATTEMPTS": &c.MaxAttempts} {
if v := os.Getenv(k); v != "" {
n, e := strconv.Atoi(v)
if e != nil || n < 1 || n > 64 {
return nil, fmt.Errorf("invalid %s", k)
}
*p = n
}
}
for k, p := range map[string]*time.Duration{"JOB_TIMEOUT": &c.Timeout, "JOB_LEASE": &c.Lease, "STAGING_RETENTION": &c.Retention} {
if v := os.Getenv(k); v != "" {
d, e := time.ParseDuration(v)
if e != nil || d <= 0 {
return nil, fmt.Errorf("invalid %s", k)
}
*p = d
}
}
if c.Lease <= c.Timeout || c.Prefetch > c.Concurrency {
return nil, fmt.Errorf("lease must exceed timeout; prefetch must not exceed concurrency")
}
if p := os.Getenv("BROKER_URL_FILE"); p != "" {
b, e := os.ReadFile(p)
if e != nil {
return nil, fmt.Errorf("read broker secret: %w", e)
}
c.BrokerURL = strings.TrimSpace(string(b))
}
return c, nil
}
+47
View File
@@ -1 +1,48 @@
package dto
import (
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"github.com/google/uuid"
"io"
"time"
)
type AttachmentRecord struct {
Public contracts.Attachment
Key string
StagingKey string
PipelineVersion int
VariantKeys map[string]string
Missing bool
}
type UploadAttachment struct {
UserID, ChatID uuid.UUID
Filename, ContentType string
Body io.Reader
}
type AttachmentContent struct {
Body io.ReadCloser
ContentType string
Size int64
}
type JobMessage struct {
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
SchemaVersion int `json:"schema_version"`
JobID uuid.UUID `json:"job_id"`
Type string `json:"type"`
AttachmentID uuid.UUID `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
}
type AttachmentJob struct {
Message JobMessage
State string
Token uuid.UUID
LeaseUntil *time.Time
NextAttemptAt time.Time
AttemptLimit int
ErrorCode *string
UpdatedAt time.Time
}
+7
View File
@@ -35,4 +35,11 @@ type MessageAttachment struct {
ID uuid.UUID
ChatID uuid.UUID
Missing bool
Status string
}
type MessageReplay struct {
Hash []byte
HashVersion int
MessageID uuid.UUID
}
+11 -5
View File
@@ -22,7 +22,10 @@ const (
// Defines values for AttachmentStatus.
const (
Ready AttachmentStatus = "ready"
Failed AttachmentStatus = "failed"
Processing AttachmentStatus = "processing"
Queued AttachmentStatus = "queued"
Ready AttachmentStatus = "ready"
)
// Defines values for ErrorErrorCode.
@@ -52,14 +55,17 @@ const (
// Defines values for VariantName.
const (
Crop VariantName = "crop"
Optimized VariantName = "optimized"
Thumbnail VariantName = "thumbnail"
VariantNameCrop VariantName = "crop"
VariantNameOptimized VariantName = "optimized"
VariantNameThumbnail VariantName = "thumbnail"
)
// Defines values for DownloadAttachmentParamsVariant.
const (
Original DownloadAttachmentParamsVariant = "original"
DownloadAttachmentParamsVariantCrop DownloadAttachmentParamsVariant = "crop"
DownloadAttachmentParamsVariantOptimized DownloadAttachmentParamsVariant = "optimized"
DownloadAttachmentParamsVariantOriginal DownloadAttachmentParamsVariant = "original"
DownloadAttachmentParamsVariantThumbnail DownloadAttachmentParamsVariant = "thumbnail"
)
// Attachment defines model for Attachment.
+64
View File
@@ -0,0 +1,64 @@
// Package fault implements explicit, file-controlled barriers for the isolated lab.
package fault
import (
"context"
"errors"
"github.com/google/uuid"
"os"
"path/filepath"
"strings"
"time"
)
func Hit(ctx context.Context, point string, id uuid.UUID) {
if os.Getenv("LAB5_FAULTS") != "1" {
return
}
p := filepath.Join("/faults", point+"."+id.String())
b, e := os.ReadFile(p)
if e != nil {
p = filepath.Join("/faults", point+".all")
b, e = os.ReadFile(p)
if e != nil {
return
}
}
hit, e := os.OpenFile(p+".hit", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)
if e != nil {
return
}
_, _ = hit.WriteString(id.String() + "\n")
_ = hit.Close()
switch strings.TrimSpace(string(b)) {
case "crash":
_ = os.Remove(p)
os.Exit(86)
case "pause":
for {
if _, e = os.Stat(p); os.IsNotExist(e) {
return
}
select {
case <-ctx.Done():
return
case <-time.After(50 * time.Millisecond):
}
}
}
}
func Error(point string, id uuid.UUID) error {
if os.Getenv("LAB5_FAULTS") != "1" {
return nil
}
b, e := os.ReadFile(filepath.Join("/faults", point+"."+id.String()))
if e != nil {
return nil
}
v := strings.TrimSpace(string(b))
if v == "temporary" || v == "permanent" {
return errors.New(v)
}
return nil
}
@@ -0,0 +1,83 @@
package imageprocessor
import (
"context"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"os"
"os/exec"
"path/filepath"
"time"
)
func run(ctx context.Context, args ...string) error {
cmd := exec.CommandContext(ctx, "magick", args...)
cmd.Env = append(os.Environ(), "MAGICK_MEMORY_LIMIT=256MiB", "MAGICK_MAP_LIMIT=0", "MAGICK_DISK_LIMIT=256MiB", "MAGICK_THREAD_LIMIT=1", "MAGICK_TIME_LIMIT=60")
cmd.WaitDelay = time.Second
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("image conversion failed: %w", err)
}
return nil
}
func Validate(ctx context.Context, path string) error {
return run(ctx, "-regard-warnings", path, "null:")
}
type Result struct {
Name, Path, MIME string
Width, Height int
}
func fit(w, h, limit int) (int, int) {
if w <= limit && h <= limit {
return w, h
}
if w >= h {
return limit, max(1, h*limit/w)
}
return max(1, w*limit/h), limit
}
func Process(ctx context.Context, source, dir string, version int) ([]Result, error) {
normalized := filepath.Join(dir, "normalized.png")
if e := run(ctx, source, "-auto-orient", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "png:"+normalized); e != nil {
return nil, e
}
f, e := os.Open(normalized)
if e != nil {
return nil, e
}
cfg, _, e := image.DecodeConfig(f)
f.Close()
if e != nil {
return nil, e
}
tw, th := fit(cfg.Width, cfg.Height, 256)
ow, oh := fit(cfg.Width, cfg.Height, 1280)
out := []Result{{"thumbnail", filepath.Join(dir, "thumbnail.jpg"), "image/jpeg", tw, th}, {"crop", filepath.Join(dir, "crop.jpg"), "image/jpeg", 128, 128}, {"optimized", filepath.Join(dir, "optimized.webp"), "image/webp", ow, oh}}
for _, v := range out {
args := []string{normalized}
if v.Name == "crop" {
side := min(cfg.Width, cfg.Height)
args = append(args, "-gravity", "center", "-crop", fmt.Sprintf("%dx%d+0+0", side, side), "+repage")
}
args = append(args, "-resize", fmt.Sprintf("%dx%d!", v.Width, v.Height), "-strip", "-quality")
quality := "85"
if v.Name == "optimized" && version == 1 {
quality = "80"
}
coder := "jpeg:"
if v.Name == "optimized" {
coder = "webp:"
}
args = append(args, quality, coder+v.Path)
if e = run(ctx, args...); e != nil {
return nil, e
}
}
return out, nil
}
+8
View File
@@ -67,3 +67,11 @@ func Missing(err error) bool {
var api smithy.APIError
return errors.As(err, &api) && (api.ErrorCode() == "NoSuchKey" || api.ErrorCode() == "NotFound" || api.ErrorCode() == "404")
}
func (s *Store) List(ctx context.Context, token string) (*s3.ListObjectsV2Output, error) {
q := &s3.ListObjectsV2Input{Bucket: &s.Bucket, MaxKeys: aws.Int32(100)}
if token != "" {
q.ContinuationToken = &token
}
return s.Client.ListObjectsV2(ctx, q)
}
@@ -0,0 +1,51 @@
package attachment
import (
"context"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"io"
"time"
)
type TransactionManager interface {
RunInTransaction(context.Context, *pgx.TxOptions, func(pgx.Tx) error) error
}
type Outbox interface {
CreateTx(context.Context, pgx.Tx, outbox.CreateMessageReq) (outbox.CreateMessageRes, error)
}
type ObjectStore interface {
Put(context.Context, string, string, io.Reader, int64) error
Get(context.Context, string) (*s3.GetObjectOutput, error)
Head(context.Context, string) (*s3.HeadObjectOutput, error)
Delete(context.Context, string) error
Ping(context.Context) error
List(context.Context, string) (*s3.ListObjectsV2Output, error)
}
type Repository interface {
SaveVariantTx(context.Context, pgx.Tx, uuid.UUID, int, string, string, string, int64) error
Ping(context.Context) error
Get(context.Context, uuid.UUID) (*dto.AttachmentRecord, error)
GetTx(context.Context, pgx.Tx, uuid.UUID) (*dto.AttachmentRecord, error)
InsertTx(context.Context, pgx.Tx, *dto.AttachmentRecord) error
UpdateTx(context.Context, pgx.Tx, *dto.AttachmentRecord) error
JobTx(context.Context, pgx.Tx, uuid.UUID) (*dto.AttachmentJob, error)
InsertJobTx(context.Context, pgx.Tx, *dto.AttachmentJob) error
SaveJobTx(context.Context, pgx.Tx, *dto.AttachmentJob) error
ExpiredJobs(context.Context) ([]uuid.UUID, error)
PublicationDeadTx(context.Context, pgx.Tx, uuid.UUID, int) (bool, error)
FailedOutbox(context.Context) ([]uuid.UUID, error)
ListJobs(context.Context) ([]dto.AttachmentJob, error)
RetiredSources(context.Context, time.Time) ([]*dto.AttachmentRecord, error)
AuditTx(context.Context, pgx.Tx, uuid.UUID, string) error
Lock(context.Context, string) (*pgxpool.Conn, func(), error)
Exists(context.Context, *pgxpool.Conn, string) (bool, error)
Page(context.Context, uuid.UUID) ([]*dto.AttachmentRecord, error)
MarkMissing(context.Context, *pgxpool.Conn, uuid.UUID, bool) (bool, error)
CheckConn(context.Context, *pgxpool.Conn) error
}
@@ -0,0 +1,486 @@
package attachment
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/fault"
"gitea.privcloud.tech/mtusi2026/internal/pkg/imageprocessor"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"io"
"os"
"path/filepath"
"strings"
"time"
)
var ErrBusy = errors.New("job lease held")
func validateImage(ctx context.Context, path string) error { return imageprocessor.Validate(ctx, path) }
func (s *Service) Fault(ctx context.Context, point string, id uuid.UUID) { fault.Hit(ctx, point, id) }
func (s *Service) newJob(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
now := time.Now().UTC()
j := &dto.AttachmentJob{Message: dto.JobMessage{SchemaVersion: 1, JobID: uuid.New(), Type: "attachment.process.v1", AttachmentID: a.Public.Id, PipelineVersion: a.PipelineVersion, Attempt: 1, CreatedAt: now}, State: "queued", Token: uuid.New(), NextAttemptAt: now, AttemptLimit: s.Jobs.MaxAttempts, UpdatedAt: now}
if e := s.Repo.InsertJobTx(ctx, tx, j); e != nil {
return e
}
return s.enqueue(ctx, tx, j)
}
func (s *Service) enqueue(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
b, e := json.Marshal(j.Message)
if e != nil {
return e
}
_, e = s.outbox.CreateTx(ctx, tx, outbox.CreateMessageReq{ID: uuid.New(), AggregateID: j.Message.JobID, Transport: outbox.TransportAMQP, Payload: b, CreatedAt: j.NextAttemptAt, MaxAttempts: s.Jobs.MaxAttempts})
return e
}
func (s *Service) Content(ctx context.Context, user, id uuid.UUID, variant string) (*dto.AttachmentContent, error) {
a, e := s.Get(ctx, user, id)
if e != nil {
return nil, e
}
if a.Public.Status != "ready" {
return nil, apperr.New(apperr.CodeConflict, "attachment not ready")
}
key, mime, size := a.Key, string(a.Public.ContentType), int64(a.Public.SizeBytes)
if variant != "original" {
key = a.VariantKeys[variant]
if key == "" {
return nil, apperr.New(apperr.CodeNotFound, "variant not found")
}
for _, v := range a.Public.Variants {
if string(v.Name) == variant {
mime = string(v.ContentType)
size = int64(v.SizeBytes)
}
}
}
obj, e := s.Store.Get(ctx, key)
if e != nil {
return nil, Unavailable()
}
return &dto.AttachmentContent{Body: obj.Body, ContentType: mime, Size: size}, nil
}
func (s *Service) Process(ctx context.Context, m dto.JobMessage) error {
var j *dto.AttachmentJob
var a *dto.AttachmentRecord
claimed := false
err := s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
var e error
j, e = s.Repo.JobTx(ctx, tx, m.JobID)
if errors.Is(e, pgx.ErrNoRows) {
return nil
}
if e != nil {
return e
}
// Broker data is a notification. Trusted metadata and attempt live in PostgreSQL.
if j.Message.AttachmentID != m.AttachmentID || j.Message.PipelineVersion != m.PipelineVersion || j.Message.Attempt != m.Attempt {
return nil
}
a, e = s.Repo.GetTx(ctx, tx, m.AttachmentID)
if e != nil {
return e
}
if a.PipelineVersion != m.PipelineVersion || j.State == "ready" || j.State == "failed" {
return nil
}
if j.State == "processing" {
return ErrBusy
}
if time.Now().Before(j.NextAttemptAt) {
return ErrBusy
}
j.State = "processing"
j.Token = uuid.New()
lease := time.Now().Add(s.Jobs.Lease)
j.LeaseUntil = &lease
j.UpdatedAt = time.Now().UTC()
a.Public.Status = "processing"
a.Public.UpdatedAt = j.UpdatedAt
if e = s.Repo.SaveJobTx(ctx, tx, j); e != nil {
return e
}
if e = s.Repo.UpdateTx(ctx, tx, a); e != nil {
return e
}
claimed = true
return nil
})
if err != nil || !claimed {
return err
}
s.Fault(ctx, "after_claim", m.JobID)
task, cancel := context.WithTimeout(ctx, s.Jobs.Timeout)
defer cancel()
result, e := s.effects(task, j, a)
if e != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return s.finish(ctx, j, nil, e)
}
s.Fault(ctx, "after_objects", m.JobID)
if err = s.finish(ctx, j, result, nil); err != nil {
return err
}
s.Fault(ctx, "after_result_commit", m.JobID)
return nil
}
type processed struct {
Key string
Variants []contracts.Variant
Keys map[string]string
}
type permanentError struct{ code string }
func (e permanentError) Error() string { return e.code }
func (s *Service) effects(ctx context.Context, j *dto.AttachmentJob, a *dto.AttachmentRecord) (*processed, error) {
dir, e := os.MkdirTemp("", "pipeline-*")
if e != nil {
return nil, e
}
defer os.RemoveAll(dir)
key := a.StagingKey
if key == "" {
key = a.Key
}
obj, e := s.Store.Get(ctx, key)
if e != nil {
if objectstore.Missing(e) {
return nil, permanentError{"source_missing"}
}
return nil, e
}
defer obj.Body.Close()
path := filepath.Join(dir, "source")
f, e := os.Create(path)
if e != nil {
return nil, e
}
hash := sha256.New()
n, e := io.Copy(io.MultiWriter(f, hash), io.LimitReader(obj.Body, s.Config.MaxBytes+1))
f.Close()
if e != nil {
return nil, e
}
if n != int64(a.Public.SizeBytes) || fmt.Sprintf("%x", hash.Sum(nil)) != a.Public.Sha256 {
return nil, permanentError{"source_corrupt"}
}
f, e = os.Open(path)
if e != nil {
return nil, e
}
e = s.Validate(ctx, f, string(a.Public.ContentType))
f.Close()
if e != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, permanentError{"invalid_image"}
}
s.Fault(ctx, "before_objects", j.Message.JobID)
if e := fault.Error("before_objects", j.Message.JobID); e != nil {
if e.Error() == "permanent" {
return nil, permanentError{"invalid_image"}
}
return nil, e
}
converted, e := imageprocessor.Process(ctx, path, dir, j.Message.PipelineVersion)
if e != nil {
return nil, e
}
prefix := fmt.Sprintf("results/%s/v%d/", a.Public.Id, j.Message.PipelineVersion)
result := &processed{Key: prefix + "original/" + a.Public.Sha256, Variants: []contracts.Variant{}, Keys: map[string]string{}}
f, e = os.Open(path)
if e != nil {
return nil, e
}
e = s.Store.Put(ctx, result.Key, string(a.Public.ContentType), f, n)
f.Close()
if e != nil {
return nil, e
}
s.Fault(ctx, "after_original_put", j.Message.JobID)
for _, v := range converted {
b, e := os.ReadFile(v.Path)
if e != nil {
return nil, e
}
sum := fmt.Sprintf("%x", sha256.Sum256(b))
key := prefix + v.Name + "/" + sum
if e = s.Store.Put(ctx, key, v.MIME, bytes.NewReader(b), int64(len(b))); e != nil {
return nil, e
}
result.Keys[v.Name] = key
result.Variants = append(result.Variants, contracts.Variant{Name: contracts.VariantName(v.Name), ContentType: contracts.VariantContentType(v.MIME), Width: v.Width, Height: v.Height, SizeBytes: len(b), Sha256: sum})
}
return result, nil
}
func (s *Service) finish(ctx context.Context, owned *dto.AttachmentJob, result *processed, cause error) error {
return s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
j, e := s.Repo.JobTx(ctx, tx, owned.Message.JobID)
if e != nil {
return e
}
a, e := s.Repo.GetTx(ctx, tx, j.Message.AttachmentID)
if e != nil {
return e
}
if j.Token != owned.Token || j.State != "processing" || j.LeaseUntil == nil || !j.LeaseUntil.After(time.Now()) || a.PipelineVersion != j.Message.PipelineVersion {
return nil
}
if cause != nil {
return s.retry(ctx, tx, j, a, cause)
}
if e = s.Repo.SaveVariantTx(ctx, tx, a.Public.Id, j.Message.PipelineVersion, "original", result.Key, a.Public.Sha256, int64(a.Public.SizeBytes)); e != nil {
return e
}
for _, v := range result.Variants {
if e = s.Repo.SaveVariantTx(ctx, tx, a.Public.Id, j.Message.PipelineVersion, string(v.Name), result.Keys[string(v.Name)], v.Sha256, int64(v.SizeBytes)); e != nil {
return e
}
}
j.State = "ready"
j.ErrorCode = nil
j.LeaseUntil = nil
j.UpdatedAt = time.Now().UTC()
a.Missing = false
a.Key = result.Key
a.VariantKeys = result.Keys
a.Public.Variants = result.Variants
a.Public.Status = "ready"
a.Public.ErrorCode = nil
a.Public.UpdatedAt = j.UpdatedAt
if e = s.Repo.SaveJobTx(ctx, tx, j); e != nil {
return e
}
return s.Repo.UpdateTx(ctx, tx, a)
})
}
func (s *Service) retry(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob, a *dto.AttachmentRecord, cause error) error {
code := "processing_failed"
var permanent permanentError
terminal := errors.As(cause, &permanent) || j.Message.Attempt >= j.AttemptLimit
if permanent.code != "" {
code = permanent.code
}
if terminal && permanent.code == "" {
code = "retry_exhausted"
}
j.LeaseUntil = nil
j.Token = uuid.New()
j.UpdatedAt = time.Now().UTC()
j.ErrorCode = &code
if terminal {
j.State = "failed"
a.Public.Status = "failed"
a.Public.ErrorCode = &code
} else {
j.State = "queued"
j.Message.Attempt++
j.NextAttemptAt = j.UpdatedAt.Add(outbox.Backoff(j.Message.Attempt - 1))
a.Public.Status = "queued"
a.Public.ErrorCode = nil
if e := s.enqueue(ctx, tx, j); e != nil {
return e
}
}
a.Public.UpdatedAt = j.UpdatedAt
if e := s.Repo.SaveJobTx(ctx, tx, j); e != nil {
return e
}
return s.Repo.UpdateTx(ctx, tx, a)
}
func (s *Service) Recover(ctx context.Context) error {
ids, e := s.Repo.ExpiredJobs(ctx)
if e != nil {
return e
}
for _, id := range ids {
e = s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
j, e := s.Repo.JobTx(ctx, tx, id)
if e != nil {
return e
}
if j.State != "processing" || j.LeaseUntil == nil || j.LeaseUntil.After(time.Now()) {
return nil
}
a, e := s.Repo.GetTx(ctx, tx, j.Message.AttachmentID)
if e != nil {
return e
}
if a.PipelineVersion != j.Message.PipelineVersion {
return nil
}
return s.retry(ctx, tx, j, a, errors.New("lease expired"))
})
if e != nil {
return e
}
}
dead, e := s.Repo.FailedOutbox(ctx)
if e != nil {
return e
}
for _, id := range dead {
if e = s.PublishFailed(ctx, id); e != nil {
return e
}
}
return nil
}
func (s *Service) PublishFailed(ctx context.Context, id uuid.UUID) error {
return s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
j, e := s.Repo.JobTx(ctx, tx, id)
if e != nil {
return e
}
if j.State != "queued" {
return nil
}
dead, e := s.Repo.PublicationDeadTx(ctx, tx, id, j.Message.Attempt)
if e != nil {
return e
}
if !dead {
return nil
}
a, e := s.Repo.GetTx(ctx, tx, j.Message.AttachmentID)
if e != nil {
return e
}
if a.PipelineVersion != j.Message.PipelineVersion {
return nil
}
code := "publish_failed"
j.State = "failed"
j.ErrorCode = &code
j.UpdatedAt = time.Now().UTC()
a.Public.Status = "failed"
a.Public.ErrorCode = &code
a.Public.UpdatedAt = j.UpdatedAt
if e = s.Repo.SaveJobTx(ctx, tx, j); e != nil {
return e
}
return s.Repo.UpdateTx(ctx, tx, a)
})
}
func (s *Service) Replay(ctx context.Context, id uuid.UUID) error {
return s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
j, e := s.Repo.JobTx(ctx, tx, id)
if e != nil {
return e
}
a, e := s.Repo.GetTx(ctx, tx, j.Message.AttachmentID)
if e != nil {
return e
}
if j.State != "failed" || a.PipelineVersion != j.Message.PipelineVersion {
return apperr.New(apperr.CodeConflict, "only current failed job can be replayed")
}
source := a.StagingKey
if source == "" {
return errors.New("source unavailable; restore original first")
}
if _, e = s.Store.Head(ctx, source); e != nil {
return errors.New("source unavailable")
}
j.State = "queued"
j.Message.Attempt++
j.AttemptLimit = j.Message.Attempt + s.Jobs.MaxAttempts - 1
j.NextAttemptAt = time.Now().UTC()
j.UpdatedAt = j.NextAttemptAt
j.Token = uuid.New()
j.ErrorCode = nil
j.LeaseUntil = nil
a.Public.Status = "queued"
a.Public.ErrorCode = nil
a.Public.UpdatedAt = j.UpdatedAt
if e = s.Repo.SaveJobTx(ctx, tx, j); e != nil {
return e
}
if e = s.Repo.UpdateTx(ctx, tx, a); e != nil {
return e
}
if e = s.Repo.AuditTx(ctx, tx, id, "replay"); e != nil {
return e
}
return s.enqueue(ctx, tx, j)
})
}
func (s *Service) Reprocess(ctx context.Context, id uuid.UUID, version int) error {
if version < 1 || version > 2 {
return errors.New("supported pipeline versions: 1, 2")
}
return s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
a, e := s.Repo.GetTx(ctx, tx, id)
if e != nil {
return e
}
if version <= a.PipelineVersion || a.Public.Status != "ready" {
return errors.New("requires ready attachment and newer version")
}
a.PipelineVersion = version
a.StagingKey = a.Key
a.Public.Status = "queued"
a.Public.Variants = []contracts.Variant{}
a.VariantKeys = map[string]string{}
a.Public.UpdatedAt = time.Now().UTC()
if e = s.Repo.UpdateTx(ctx, tx, a); e != nil {
return e
}
return s.newJob(ctx, tx, a)
})
}
func (s *Service) Cleanup(ctx context.Context) error {
records, e := s.Repo.RetiredSources(ctx, time.Now().Add(-s.Jobs.Retention))
if e != nil {
return e
}
for _, record := range records {
// Serialize deletion with operator Restore and the initial upload handoff.
_, unlock, lockErr := s.Repo.Lock(ctx, record.StagingKey)
if lockErr != nil {
return lockErr
}
e = s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
a, e := s.Repo.GetTx(ctx, tx, record.Public.Id)
if e != nil {
return e
}
if a.StagingKey == "" || a.StagingKey == a.Key && a.Public.Status == "ready" {
return nil
}
if a.Public.Status != "ready" && (a.Public.Status != "failed" || time.Since(a.Public.UpdatedAt) < s.Jobs.Retention) {
return nil
}
if !strings.HasPrefix(a.StagingKey, "results/") {
if e = s.Store.Delete(ctx, a.StagingKey); e != nil {
return e
}
}
a.StagingKey = ""
return s.Repo.UpdateTx(ctx, tx, a)
})
unlock()
if e != nil {
return e
}
}
return nil
}
func managedPipelineKey(key string) bool {
return strings.HasPrefix(key, "staging/") || strings.HasPrefix(key, "results/")
}
@@ -10,8 +10,9 @@ import (
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
)
@@ -38,17 +39,17 @@ func (s *Service) Reconcile(ctx context.Context, apply bool) (result ScanResult,
result.Apply = apply
result.GraceSeconds = s.Config.Grace.Seconds()
defer func() { result.DurationMS = time.Since(start).Milliseconds() }()
if err = s.Repo.Pool.Ping(ctx); err != nil {
if err = s.Repo.Ping(ctx); err != nil {
return
}
result.S3Requests++
if err = s.Store.Ping(ctx); err != nil {
return
}
pager := s3.NewListObjectsV2Paginator(s.Store.Client, &s3.ListObjectsV2Input{Bucket: &s.Store.Bucket, Prefix: aws.String(Prefix), MaxKeys: aws.Int32(100)})
for pager.HasMorePages() {
token := ""
for {
result.S3Requests++
page, e := pager.NextPage(ctx)
page, e := s.Store.List(ctx, token)
if e != nil {
return result, e
}
@@ -92,7 +93,7 @@ func (s *Service) Reconcile(ctx context.Context, apply bool) (result ScanResult,
return nil
}
result.DBChecks++
if _, e = conn.Exec(ctx, "SELECT 1"); e != nil {
if e = s.Repo.CheckConn(ctx, conn); e != nil {
return e
}
result.S3Requests++
@@ -106,7 +107,12 @@ func (s *Service) Reconcile(ctx context.Context, apply bool) (result ScanResult,
return result, e
}
}
if !aws.ToBool(page.IsTruncated) {
break
}
token = aws.ToString(page.NextContinuationToken)
}
after := uuid.Nil
for {
result.DBChecks++
@@ -120,6 +126,9 @@ func (s *Service) Reconcile(ctx context.Context, apply bool) (result ScanResult,
for _, a := range page {
result.Metadata++
after = a.Public.Id
if a.Public.Status != "ready" {
continue
}
result.LockAttempts++
conn, unlock, e := s.Repo.Lock(ctx, a.Key)
if e != nil {
@@ -201,5 +210,19 @@ func (s *Service) Restore(ctx context.Context, id uuid.UUID, path string) error
return fmt.Errorf("stored original verification failed")
}
_, e = s.Repo.MarkMissing(ctx, conn, id, false)
return e
if e != nil {
return e
}
return s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
current, e := s.Repo.GetTx(ctx, tx, id)
if e != nil {
return e
}
if current.Public.Status == "failed" {
current.StagingKey = current.Key
current.Public.UpdatedAt = time.Now().UTC()
return s.Repo.UpdateTx(ctx, tx, current)
}
return nil
})
}
+38 -35
View File
@@ -8,8 +8,7 @@ import (
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"os"
"strings"
"time"
@@ -18,28 +17,31 @@ import (
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"github.com/jackc/pgx/v5"
)
const Prefix = "originals/"
const StagingPrefix = "staging/"
type Membership interface {
GetForMember(context.Context, dto.ChatMember) (*dto.Chat, error)
}
type Service struct {
Repo *storage.AttachmentsRepo
Store *objectstore.Store
Repo Repository
Store ObjectStore
Config *config.Attachment
chats Membership
tm TransactionManager
outbox Outbox
Jobs *config.Pipeline
uploads, decoders chan struct{}
}
func New(repo *storage.AttachmentsRepo, store *objectstore.Store, c *config.Attachment, chats Membership) *Service {
func New(repo Repository, store ObjectStore, c *config.Attachment, chats Membership) *Service {
return &Service{Repo: repo, Store: store, Config: c, chats: chats, uploads: make(chan struct{}, c.Uploads), decoders: make(chan struct{}, c.Decoders)}
}
func ValidFilename(s string) bool {
@@ -53,21 +55,15 @@ func ValidFilename(s string) bool {
}
return true
}
func (s *Service) Upload(w http.ResponseWriter, r *http.Request, user, chat uuid.UUID, filename string) (*contracts.Attachment, error) {
ctx := r.Context()
if _, e := s.chats.GetForMember(ctx, dto.ChatMember{UserID: user, ChatID: chat}); e != nil {
func (s *Service) Configure(tm TransactionManager, outbox Outbox, jobs *config.Pipeline) {
s.tm = tm
s.outbox = outbox
s.Jobs = jobs
}
func (s *Service) Upload(ctx context.Context, req dto.UploadAttachment) (*contracts.Attachment, error) {
if _, e := s.chats.GetForMember(ctx, dto.ChatMember{UserID: req.UserID, ChatID: req.ChatID}); e != nil {
return nil, e
}
if !ValidFilename(filename) {
return nil, apperr.New(apperr.CodeBadRequest, "invalid filename")
}
mt, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
if e != nil || (mt != "image/png" && mt != "image/jpeg") {
return nil, apperr.New(apperr.CodeUnsupportedMediaType, "expected PNG or JPEG")
}
if r.ContentLength > s.Config.MaxBytes {
return nil, apperr.New(apperr.CodePayloadTooLarge, "upload too large")
}
select {
case s.uploads <- struct{}{}:
defer func() { <-s.uploads }()
@@ -80,23 +76,22 @@ func (s *Service) Upload(w http.ResponseWriter, r *http.Request, user, chat uuid
}
defer os.Remove(f.Name())
defer f.Close()
r.Body = http.MaxBytesReader(w, r.Body, s.Config.MaxBytes)
hash := sha256.New()
size, e := io.Copy(io.MultiWriter(f, hash), r.Body)
size, e := io.Copy(io.MultiWriter(f, hash), io.LimitReader(req.Body, s.Config.MaxBytes+1))
if e != nil {
if _, ok := e.(*http.MaxBytesError); ok {
return nil, apperr.New(apperr.CodePayloadTooLarge, "upload too large")
}
return nil, apperr.New(apperr.CodeBadRequest, "incomplete upload")
}
if e = s.Validate(ctx, f, mt); e != nil {
if size > s.Config.MaxBytes {
return nil, apperr.New(apperr.CodePayloadTooLarge, "upload too large")
}
if e = s.Validate(ctx, f, req.ContentType); e != nil {
return nil, e
}
now := time.Now().UTC().Truncate(time.Microsecond)
id := uuid.New()
key := Prefix + id.String()
a := &storage.AttachmentRecord{Key: key, Public: contracts.Attachment{Id: id, ChatId: chat, OwnerId: user, Filename: filename, ContentType: contracts.AttachmentContentType(mt), SizeBytes: int(size), Sha256: fmt.Sprintf("%x", hash.Sum(nil)), Status: "ready", Variants: []contracts.Variant{}, CreatedAt: now, UpdatedAt: now}}
conn, unlock, e := s.Repo.Lock(ctx, key)
key := StagingPrefix + id.String()
a := &dto.AttachmentRecord{Key: key, StagingKey: key, PipelineVersion: 1, VariantKeys: map[string]string{}, Public: contracts.Attachment{Id: id, ChatId: req.ChatID, OwnerId: req.UserID, Filename: req.Filename, ContentType: contracts.AttachmentContentType(req.ContentType), SizeBytes: int(size), Sha256: fmt.Sprintf("%x", hash.Sum(nil)), Status: "queued", Variants: []contracts.Variant{}, CreatedAt: now, UpdatedAt: now}}
_, unlock, e := s.Repo.Lock(ctx, key)
if e != nil {
return nil, e
}
@@ -104,14 +99,19 @@ func (s *Service) Upload(w http.ResponseWriter, r *http.Request, user, chat uuid
if _, e = f.Seek(0, 0); e != nil {
return nil, e
}
if e = s.Store.Put(ctx, key, mt, f, size); e != nil {
if e = s.Store.Put(ctx, key, req.ContentType, f, size); e != nil {
return nil, Unavailable()
}
// Never blindly compensate a failed/ambiguous COMMIT with DELETE: a committed
// row may already reference this key. Reconciliation decides after grace.
if e = s.Repo.Save(ctx, conn, a); e != nil {
s.Fault(ctx, "after_staging", id)
if e = s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
if e := s.Repo.InsertTx(ctx, tx, a); e != nil {
return e
}
return s.newJob(ctx, tx, a)
}); e != nil {
return nil, e
}
s.Fault(ctx, "after_upload_commit", id)
return &a.Public, nil
}
func (s *Service) Validate(ctx context.Context, f *os.File, mt string) error {
@@ -134,12 +134,12 @@ func (s *Service) Validate(ctx context.Context, f *os.File, mt string) error {
if _, e = f.Seek(0, 0); e != nil {
return e
}
if _, _, e = image.Decode(f); e != nil {
if e = validateImage(ctx, f.Name()); e != nil {
return apperr.New(apperr.CodeUnsupportedMediaType, "corrupt image")
}
return ctx.Err()
}
func (s *Service) Get(ctx context.Context, user, id uuid.UUID) (*storage.AttachmentRecord, error) {
func (s *Service) Get(ctx context.Context, user, id uuid.UUID) (*dto.AttachmentRecord, error) {
a, e := s.Repo.Get(ctx, id)
if e != nil {
return nil, e
@@ -154,6 +154,9 @@ func (s *Service) Get(ctx context.Context, user, id uuid.UUID) (*storage.Attachm
}
func Unavailable() error { return apperr.New(apperr.CodeUnavailable, "attachment storage unavailable") }
func ManagedKey(key string) bool {
if managedPipelineKey(key) {
return true
}
if !strings.HasPrefix(key, Prefix) {
return false
}
@@ -0,0 +1,54 @@
package chat
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"time"
)
// CreateIdempotentTx performs the message use case inside an existing transaction.
func CreateIdempotentTx(ctx context.Context, tx pgx.Tx, repo messagesRepo, req dto.CreateMessage) (*dto.Message, error) {
scope := req.SenderID.String() + ":POST:" + req.ChatID.String() + ":" + req.IdempotencyKey
if err := repo.LockKeyTx(ctx, tx, scope); err != nil {
return nil, err
}
canonical := struct {
Text string `json:"text"`
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
}{req.Text, append([]uuid.UUID{}, req.AttachmentIDs...)}
encoded, err := json.Marshal(canonical)
if err != nil {
return nil, err
}
hash := sha256.Sum256(encoded)
replay, err := repo.ReplayTx(ctx, tx, req)
if err != nil {
return nil, err
}
if replay != nil {
if replay.HashVersion == 1 && len(req.AttachmentIDs) == 0 {
hash = sha256.Sum256([]byte(req.Text))
} else if replay.HashVersion != 2 {
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
}
if !bytes.Equal(hash[:], replay.Hash) {
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
}
return repo.MessageTx(ctx, tx, replay.MessageID)
}
now := time.Now().UTC().Truncate(time.Microsecond)
message := dto.Message{ID: uuid.New(), ChatID: req.ChatID, SenderID: req.SenderID, Text: req.Text, AttachmentIDs: append([]uuid.UUID{}, req.AttachmentIDs...), CreatedAt: now}
if err = repo.InsertMessageTx(ctx, tx, message); err != nil {
return nil, err
}
if err = repo.SaveKeyTx(ctx, tx, req, hash[:], message.ID, now.Add(24*time.Hour)); err != nil {
return nil, err
}
return &message, nil
}
+6 -1
View File
@@ -2,6 +2,7 @@ package chat
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -17,7 +18,11 @@ type chatsRepo interface {
type messagesRepo interface {
AttachmentsForMessageTx(ctx context.Context, tx pgx.Tx, ids []uuid.UUID) ([]dto.MessageAttachment, error)
CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error)
LockKeyTx(context.Context, pgx.Tx, string) error
ReplayTx(context.Context, pgx.Tx, dto.CreateMessage) (*dto.MessageReplay, error)
MessageTx(context.Context, pgx.Tx, uuid.UUID) (*dto.Message, error)
InsertMessageTx(context.Context, pgx.Tx, dto.Message) error
SaveKeyTx(context.Context, pgx.Tx, dto.CreateMessage, []byte, uuid.UUID, time.Time) error
GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error)
ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error)
}
+4 -1
View File
@@ -190,6 +190,9 @@ func (c *Chat) CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.M
if attachment.ChatID != req.ChatID {
return apperr.New(apperr.CodeNotFound, "attachment not found")
}
if attachment.Status == "failed" {
return apperr.New(apperr.CodeConflict, "failed attachment")
}
if attachment.Missing {
return apperr.New(apperr.CodeUnavailable, "attachment storage unavailable")
}
@@ -197,7 +200,7 @@ func (c *Chat) CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.M
}
var err error
message, err = c.messagesRepo.CreateIdempotentTx(ctx, tx, req)
message, err = CreateIdempotentTx(ctx, tx, c.messagesRepo, req)
return err
})
return message, err
+12
View File
@@ -0,0 +1,12 @@
package outbox
import (
"context"
"github.com/jackc/pgx/v5"
)
type API interface {
CreateTx(context.Context, pgx.Tx, CreateMessageReq) (CreateMessageRes, error)
Create(context.Context, CreateMessageReq) (CreateMessageRes, error)
}
+115
View File
@@ -0,0 +1,115 @@
package outbox
import (
"time"
"github.com/google/uuid"
)
type CreateMessageReq struct {
ID uuid.UUID
CreatedAt time.Time
Transport Transport
AggregateType string
AggregateID uuid.UUID
MessageType string
IdempotencyKey *string
SchemaVersion int
CausationID *uuid.UUID
Metadata map[string]string
Payload []byte
MaxAttempts int
Status Status
}
type CreateMessageRes struct {
ID uuid.UUID
CreatedAt time.Time
}
type MarkPublishedMessageReq struct {
ID uuid.UUID
UpdatedAt time.Time
PublishedAt time.Time
}
type MarkFailedMessageReq struct {
ID uuid.UUID
UpdatedAt time.Time
NextAttemptAt time.Time
LastError string
}
type MarkDeadLetterMessageReq struct {
ID uuid.UUID
UpdatedAt time.Time
DeadLetterAt time.Time
LastError string
}
type AcquireMessagesForProcessingReq struct {
Limit uint
LockDuration time.Duration
}
type AcquiredMessage struct {
Token uuid.UUID
ID uuid.UUID
Transport Transport
AggregateType string
AggregateID uuid.UUID
MessageType string
SchemaVersion int
CorrelationID uuid.UUID
CausationID *uuid.UUID
Status Status
Metadata map[string]string
Payload []byte
Attempts int
MaxAttempts int
LastError *string
LockedAt *time.Time
LockedUntil *time.Time
NextAttemptAt *time.Time
PublishedAt *time.Time
DeadLetterAt *time.Time
CreatedAt time.Time
UpdatedAt *time.Time
}
type RecoverStuckMessagesAsFailedReq struct {
UpdatedAt time.Time
NextAttemptAt time.Time
LastError string
Limit uint
}
type RecoverStuckMessagesAsDeadLetterReq struct {
UpdatedAt time.Time
DeadLetterAt time.Time
LastError string
Limit uint
}
type DeliveryMessage struct {
ID uuid.UUID
Transport Transport
AggregateType string
AggregateID uuid.UUID
MessageType string
SchemaVersion int
CorrelationID uuid.UUID
CausationID *uuid.UUID
Payload []byte
Metadata map[string]string
}
type ProcessOnceResult struct {
RecoveredAsFailed int64
RecoveredAsDeadLetter int64
Acquired int
Published int
Failed int
DeadLettered int
}
+16
View File
@@ -0,0 +1,16 @@
package outbox
const (
StatusCreated Status = "created"
StatusPending Status = "pending"
StatusProcessing Status = "processing"
StatusPublished Status = "published"
StatusFailed Status = "failed"
StatusDeadLetter Status = "dead_letter"
)
type Status string
func (s Status) String() string {
return string(s)
}
+114
View File
@@ -0,0 +1,114 @@
// Adapted from mamont-optics/application/internal/service/outbox.
// Retains transactional creation, batch acquisition, bounded retries and lease recovery.
package outbox
import (
"context"
"encoding/json"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"math/rand/v2"
"time"
)
type Repository interface {
CreateTx(context.Context, pgx.Tx, CreateMessageReq) (CreateMessageRes, error)
AcquireManyForProcessing(context.Context, AcquireMessagesForProcessingReq) ([]AcquiredMessage, error)
Expired(context.Context) ([]AcquiredMessage, error)
Update(context.Context, AcquiredMessage, Status, time.Time, string) error
}
type TransportPublisher interface {
Publish(context.Context, DeliveryMessage) error
}
type TransactionManager interface {
RunInTransaction(context.Context, *pgx.TxOptions, func(pgx.Tx) error) error
}
type Svc struct {
repo Repository
tm TransactionManager
publisher TransportPublisher
OnDead func(context.Context, uuid.UUID) error
}
func New(repo Repository, tm TransactionManager, publisher TransportPublisher) *Svc {
return &Svc{repo: repo, tm: tm, publisher: publisher}
}
func (s *Svc) CreateTx(ctx context.Context, tx pgx.Tx, r CreateMessageReq) (CreateMessageRes, error) {
if r.ID == uuid.Nil {
r.ID = uuid.New()
}
if r.CreatedAt.IsZero() {
r.CreatedAt = time.Now().UTC()
}
if r.Status == "" {
r.Status = StatusPending
}
if r.MaxAttempts == 0 {
r.MaxAttempts = 5
}
return s.repo.CreateTx(ctx, tx, r)
}
func (s *Svc) Create(ctx context.Context, r CreateMessageReq) (res CreateMessageRes, err error) {
err = s.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error { var e error; res, e = s.CreateTx(ctx, tx, r); return e })
return
}
func Backoff(attempt int) time.Duration {
n := min(max(attempt-1, 0), 5)
cap := min(time.Second*time.Duration(1<<n), 30*time.Second)
return cap/2 + time.Duration(rand.Int64N(int64(cap/2)+1))
}
func (s *Svc) ProcessOnce(ctx context.Context) (result ProcessOnceResult, err error) {
expired, e := s.repo.Expired(ctx)
if e != nil {
return result, e
}
for _, m := range expired {
if e = s.fail(ctx, m, "publish_lease_expired"); e != nil {
return result, e
}
}
messages, e := s.repo.AcquireManyForProcessing(ctx, AcquireMessagesForProcessingReq{Limit: 1, LockDuration: 30 * time.Second})
if e != nil {
return result, e
}
for _, m := range messages {
result.Acquired++
// Publish payload is the job contract, never the outbox envelope.
if s.publisher == nil {
return result, errors.New("publisher unavailable")
}
e = s.publisher.Publish(ctx, DeliveryMessage{ID: m.ID, AggregateID: m.AggregateID, Payload: m.Payload})
if e != nil {
if e = s.fail(ctx, m, "publish_failed"); e != nil {
return result, e
}
result.Failed++
continue
}
if e = s.repo.Update(ctx, m, StatusPublished, time.Now().UTC(), ""); e != nil {
return result, e
}
result.Published++
}
return result, nil
}
func (s *Svc) fail(ctx context.Context, m AcquiredMessage, code string) error {
status := StatusFailed
if m.Attempts >= m.MaxAttempts {
status = StatusDeadLetter
}
if err := s.repo.Update(ctx, m, status, time.Now().UTC().Add(Backoff(m.Attempts)), code); err != nil {
return err
}
if status == StatusDeadLetter && s.OnDead != nil {
var j struct {
JobID uuid.UUID `json:"job_id"`
}
if err := json.Unmarshal(m.Payload, &j); err != nil {
return err
}
return s.OnDead(ctx, j.JobID)
}
return nil
}
@@ -0,0 +1,7 @@
package outbox
type Transport string
const TransportAMQP Transport = "amqp"
func (t Transport) String() string { return string(t) }
+41
View File
@@ -0,0 +1,41 @@
ALTER TABLE attachments
ADD COLUMN status text NOT NULL DEFAULT 'queued' CHECK(status IN ('queued','processing','ready','failed')),
ADD COLUMN error_code text,
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1,
ADD COLUMN staging_key text NOT NULL DEFAULT '',
ADD COLUMN variants jsonb NOT NULL DEFAULT '[]',
ADD COLUMN variant_keys jsonb NOT NULL DEFAULT '{}';
UPDATE attachments SET staging_key=object_key;
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id),
pipeline_version integer NOT NULL, attempt integer NOT NULL CHECK(attempt>0),
attempt_limit integer NOT NULL, state text NOT NULL,
token uuid NOT NULL, lease_until timestamptz, next_attempt_at timestamptz NOT NULL,
error_code text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,
UNIQUE(attachment_id,pipeline_version)
);
CREATE INDEX jobs_recovery ON attachment_jobs(state,lease_until);
CREATE TABLE outbox (
id uuid PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(id),
payload jsonb NOT NULL, status text NOT NULL,
attempts integer NOT NULL DEFAULT 0, max_attempts integer NOT NULL,
token uuid NOT NULL, locked_until timestamptz, next_attempt_at timestamptz NOT NULL,
last_error text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL
);
CREATE INDEX outbox_delivery ON outbox(status,next_attempt_at);
CREATE TABLE job_audit (
id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(id),
action text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
-- Existing lab4 originals become durable sources for the first asynchronous run.
INSERT INTO attachment_jobs
SELECT gen_random_uuid(),id,1,1,5,'queued',gen_random_uuid(),NULL,clock_timestamp(),NULL,created_at,clock_timestamp() FROM attachments;
INSERT INTO outbox
SELECT gen_random_uuid(),id,jsonb_build_object('schema_version',1,'job_id',id,'type','attachment.process.v1','attachment_id',attachment_id,'pipeline_version',1,'attempt',1,'created_at',created_at),
'pending',0,5,gen_random_uuid(),NULL,clock_timestamp(),NULL,clock_timestamp(),clock_timestamp() FROM attachment_jobs;
---- create above / drop below ----
DROP TABLE job_audit;
DROP TABLE outbox;
DROP TABLE attachment_jobs;
ALTER TABLE attachments DROP COLUMN status,DROP COLUMN error_code,DROP COLUMN pipeline_version,DROP COLUMN staging_key,DROP COLUMN variants,DROP COLUMN variant_keys;
@@ -0,0 +1,8 @@
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments(id), pipeline_version integer NOT NULL,
variant text NOT NULL CHECK(variant IN ('original','thumbnail','crop','optimized')),
object_key text NOT NULL UNIQUE, sha256 text NOT NULL, size_bytes bigint NOT NULL,
PRIMARY KEY(attachment_id,pipeline_version,variant)
);
---- create above / drop below ----
DROP TABLE attachment_variants;
+27 -5
View File
@@ -69,11 +69,12 @@ func TestAttachmentContractAndErrors(t *testing.T) {
Sha string `json:"sha256"`
Size int `json:"size_bytes"`
}
decodeOK(t, api.upload(t, chat, alice, "Файл.png", "image/png", data, false), 201, &att)
decodeOK(t, api.upload(t, chat, alice, "Файл.png", "image/png", data, false), 202, &att)
hash := sha256.Sum256(data)
if att.Sha != hex.EncodeToString(hash[:]) || att.Size != len(data) {
t.Fatal("original metadata mismatch")
}
waitAttachmentReady(t, api, alice, att.ID)
content := "/api/v1/attachments/" + att.ID + "/content"
got := api.request(t, "GET", content, bob, "")
if got.status != 200 || !bytes.Equal(got.body, data) {
@@ -115,7 +116,7 @@ func TestAttachmentContractAndErrors(t *testing.T) {
boundary = binary.BigEndian.AppendUint32(boundary, crc32.ChecksumIEEE(chunk))
boundary = append(boundary, data[len(data)-12:]...)
var boundaryAtt map[string]any
decodeOK(t, api.upload(t, chat, alice, "boundary.png", "image/png", boundary, false), 201, &boundaryAtt)
decodeOK(t, api.upload(t, chat, alice, "boundary.png", "image/png", boundary, false), 202, &boundaryAtt)
oversized := make([]byte, 10485761)
copy(oversized, data)
@@ -127,7 +128,7 @@ func TestAttachmentContractAndErrors(t *testing.T) {
t.Fatal(e)
}
var jpegAtt map[string]any
decodeOK(t, api.upload(t, chat, bob, "file.jpg", "image/jpeg", jpg.Bytes(), false), 201, &jpegAtt)
decodeOK(t, api.upload(t, chat, bob, "file.jpg", "image/jpeg", jpg.Bytes(), false), 202, &jpegAtt)
imageOnly := `{"text":"","attachment_ids":["` + att.ID + `"]}`
var message map[string]any
key := uuid.NewString()
@@ -145,7 +146,9 @@ func TestAttachmentContractAndErrors(t *testing.T) {
for _, body := range []string{`{"text":""}`, `{"text":" "}`, `{"attachment_ids":["` + att.ID + `"]}`, `{"text":"ok","attachment_ids":null}`, `{"text":"ok","attachment_ids":"bad"}`, `{"text":"ok","attachment_ids":["` + att.ID + `","` + att.ID + `"]}`} {
assertError(t, api.request(t, "POST", "/api/v1/chats/"+chat+"/messages", alice, body), 400, "invalid_request")
}
assertError(t, api.request(t, "GET", content+"?variant=thumbnail", bob, ""), 400, "invalid_request")
if got := api.request(t, "GET", content+"?variant=thumbnail", bob, ""); got.status != 200 {
t.Fatal("thumbnail unavailable")
}
}
func TestConcurrentAttachmentMessage(t *testing.T) {
api := newAPI(t)
@@ -154,7 +157,7 @@ func TestConcurrentAttachmentMessage(t *testing.T) {
var att struct {
ID string `json:"id"`
}
decodeOK(t, api.upload(t, chat, user, "sample.png", "image/png", fixturePNG(t), false), 201, &att)
decodeOK(t, api.upload(t, chat, user, "sample.png", "image/png", fixturePNG(t), false), 202, &att)
key := uuid.NewString()
body := `{"text":"","attachment_ids":["` + att.ID + `"]}`
type result struct {
@@ -202,3 +205,22 @@ func TestConcurrentAttachmentMessage(t *testing.T) {
t.Fatal("duplicate history")
}
}
func waitAttachmentReady(t *testing.T, api *apiClient, user, id string) {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
var att struct {
Status string `json:"status"`
}
decodeOK(t, api.request(t, "GET", "/api/v1/attachments/"+id, user, ""), 200, &att)
if att.Status == "ready" {
return
}
if att.Status == "failed" {
t.Fatal("attachment failed")
}
time.Sleep(100 * time.Millisecond)
}
t.Fatal("attachment readiness deadline")
}