Реализация на 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
+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
}