Переведите приём и чтение вложений на асинхронный контракт

This commit is contained in:
2026-11-18 15:33:32 +03:00
parent efc56b1382
commit bf970227d6
19 changed files with 667 additions and 367 deletions
+23 -10
View File
@@ -9,19 +9,23 @@ import (
type FileStatus string
const (
FilePending FileStatus = "pending"
FileReady FileStatus = "ready"
FileFailed FileStatus = "failed"
FileQueued FileStatus = "queued"
FileProcessing FileStatus = "processing"
FilePending FileStatus = "pending"
FileReady FileStatus = "ready"
FileFailed FileStatus = "failed"
)
type Attachment struct {
ID, ChatID, OwnerID uuid.UUID
Filename string
FileHash []byte
SizeBytes int64
MIMEType string
Status FileStatus
CreatedAt time.Time
ID, ChatID, OwnerID uuid.UUID
Filename string
FileHash []byte
SizeBytes int64
MIMEType string
Status FileStatus
CreatedAt, UpdatedAt time.Time
ErrorCode *string
Variants []Variant
}
type UploadInput struct {
@@ -30,3 +34,12 @@ type UploadInput struct {
MIMEType string
SizeBytes int64
}
type Variant struct {
Name string
ObjectKey string
MIMEType string
SizeBytes int64
Width, Height int
Hash []byte
}
+43 -18
View File
@@ -26,22 +26,37 @@ func (h *Handler) Register(protected, binaryProtected gin.IRouter) {
}
type Response struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []VariantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type VariantResponse struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
// Lab4's shared response contract requires variants=[], even without processing.
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func toResponse(a Attachment) Response {
variants := make([]VariantResponse, 0, len(a.Variants))
for _, v := range a.Variants {
variants = append(variants, VariantResponse{
Name: v.Name, ContentType: v.MIMEType, SizeBytes: v.SizeBytes,
Width: v.Width, Height: v.Height, SHA256: hex.EncodeToString(v.Hash),
})
}
return Response{
ID: a.ID.String(),
ChatID: a.ChatID.String(),
@@ -51,9 +66,10 @@ func toResponse(a Attachment) Response {
SizeBytes: a.SizeBytes,
SHA256: hex.EncodeToString(a.FileHash),
Status: string(a.Status),
Variants: []any{},
Variants: variants,
ErrorCode: a.ErrorCode,
CreatedAt: httpx.Timestamp(a.CreatedAt),
UpdatedAt: httpx.Timestamp(a.CreatedAt),
UpdatedAt: httpx.Timestamp(a.UpdatedAt),
}
}
@@ -89,7 +105,7 @@ func (h *Handler) upload(c *gin.Context, actor uuid.UUID) {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusCreated, toResponse(a))
httpx.JSON(c, http.StatusAccepted, toResponse(a))
}
func attachmentID(c *gin.Context) (uuid.UUID, error) {
id, err := ident.Parse(c.Param("attachment_id"))
@@ -117,12 +133,21 @@ func (h *Handler) content(c *gin.Context, actor uuid.UUID) {
httpx.Error(c, err)
return
}
variant, present := c.GetQuery("variant")
if present && variant != "original" {
httpx.Error(c, apperr.Invalid("variant must be original"))
return
variant := "original"
if values, ok := c.Request.URL.Query()["variant"]; ok {
if len(values) != 1 {
httpx.Error(c, apperr.Invalid("one variant is required"))
return
}
variant = values[0]
switch variant {
case "original", "thumbnail", "crop", "optimized":
default:
httpx.Error(c, apperr.Invalid("unknown variant"))
return
}
}
a, r, err := h.s.Content(c.Request.Context(), actor, id)
a, r, err := h.s.Content(c.Request.Context(), actor, id, variant)
if err != nil {
httpx.Error(c, err)
return
+87 -26
View File
@@ -9,8 +9,11 @@ import (
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
@@ -40,9 +43,10 @@ type Stats struct {
}
type Reconciler struct {
db *pgxpool.Pool
blobs Blobs
grace time.Duration
db *pgxpool.Pool
blobs Blobs
grace time.Duration
retention time.Duration
}
type ReconcileOptions struct {
@@ -51,6 +55,13 @@ type ReconcileOptions struct {
}
func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconciler, error) {
return NewReconcilerWithRetention(db, blobs, grace, 24*time.Hour)
}
func NewReconcilerWithRetention(db *pgxpool.Pool, blobs Blobs, grace, retention time.Duration) (*Reconciler, error) {
if retention < time.Second {
return nil, errors.New("reconcile: staging retention must be at least one second")
}
if db == nil || blobs == nil {
return nil, errors.New("reconcile: database and blobs are required")
}
@@ -60,7 +71,7 @@ func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconci
if grace < 2*time.Minute {
return nil, errors.New("reconcile: grace must be at least two minutes")
}
return &Reconciler{db: db, blobs: blobs, grace: grace}, nil
return &Reconciler{db: db, blobs: blobs, grace: grace, retention: retention}, nil
}
// Run streams findings and keeps at most one page of metadata in memory.
@@ -78,7 +89,7 @@ func (r *Reconciler) Run(ctx context.Context, options ReconcileOptions, emit fun
stats: &stats,
cutoff: started.Add(-r.grace),
}
for _, prefix := range []string{"staging/", "blobs/"} {
for _, prefix := range []string{"staging/", "variants/", "blobs/"} {
if err = run.objects(prefix); err != nil {
return stats, err
}
@@ -147,10 +158,10 @@ func (s *reconcileRun) objects(prefix string) error {
continue
}
var finding *Finding
if prefix == "staging/" {
finding, err = s.staging(obj)
} else {
if prefix == "blobs/" {
finding, err = s.orphan(obj, known[obj.Key])
} else {
finding, err = s.jobObject(prefix, obj)
}
if err != nil {
return fmt.Errorf("reconcile %s: %w", obj.Key, err)
@@ -178,26 +189,76 @@ func (s *reconcileRun) delete(key string) error {
return err
}
func (s *reconcileRun) staging(obj Object) (*Finding, error) {
f := &Finding{Kind: "stale_staging", Key: obj.Key, Action: "delete_object"}
// Failed sources remain available for operator replay until the retention period after failure elapses.
// Staging shared by several pipeline versions is retained while any active job needs it.
func (s *reconcileRun) jobObject(prefix string, obj Object) (*Finding, error) {
parts := strings.Split(strings.TrimPrefix(obj.Key, prefix), "/")
id, idErr := uuid.Parse(parts[0])
kind := "stale_staging"
query := `SELECT EXISTS(SELECT 1 FROM attachment_jobs
WHERE attachment_id=$1 AND source_key=$2 AND
(state IN ('queued','processing') OR (state='failed' AND updated_at >= now()-$3::bigint*interval '1 second')))`
args := []any{id, obj.Key, int64(s.r.retention / time.Second)}
if prefix == "variants/" {
if len(parts) != 4 || idErr != nil {
return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil
}
version, err := strconv.Atoi(parts[1])
if err != nil || version < 1 || version > math.MaxInt32 {
return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil
}
kind = "orphan_variant"
query = `SELECT EXISTS(SELECT 1 FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$3 AND object_key=$2)
OR EXISTS(SELECT 1 FROM attachment_jobs WHERE attachment_id=$1 AND pipeline_version=$3 AND state IN ('queued','processing'))`
args[2] = version
}
finding := &Finding{Kind: kind, Key: obj.Key, Action: "delete_object"}
var keep bool
s.stats.SQLQueries++
if err := s.r.db.QueryRow(s.ctx, query, args...).Scan(&keep); err != nil {
return nil, err
}
if keep {
return nil, nil
}
if !s.apply {
return f, nil
return finding, nil
}
current, err := s.stat(obj.Key)
if errors.Is(err, ErrObjectMissing) {
return nil, nil
}
if err != nil {
return nil, err
}
if !s.old(current.Modified) {
return nil, nil
}
if err = s.delete(obj.Key); err != nil {
return nil, err
}
f.Applied = true
return f, nil
keyHash := sha256.Sum256([]byte(obj.Key))
return s.locked(keyHash[:], func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
// Intake locks the staging key before inserting an attachment. Replay,
// reprocess and completion lock the existing attachment before changing job state.
if idErr == nil {
s.stats.SQLQueries++
if _, err := tx.Exec(opCtx, `SELECT id FROM attachments WHERE id=$1 FOR UPDATE`, id); err != nil {
return nil, err
}
}
s.stats.SQLQueries++
if err := tx.QueryRow(opCtx, query, args...).Scan(&keep); err != nil {
return nil, err
}
if keep {
return nil, nil
}
op := *s
op.ctx = opCtx
current, err := op.stat(obj.Key)
if errors.Is(err, ErrObjectMissing) {
return nil, nil
}
if err != nil {
return nil, err
}
if !s.old(current.Modified) {
return nil, nil
}
if err := op.delete(obj.Key); err != nil {
return nil, err
}
finding.Applied = true
return finding, nil
})
}
func (s *reconcileRun) knownFiles(page []Object) (map[string]bool, error) {
+44
View File
@@ -729,3 +729,47 @@ func TestReconcileLockRejectsMalformedHash(t *testing.T) {
t.Fatal("malformed hash accepted")
}
}
func TestGCRespectsJobSourcesAndVersionedOutputs(t *testing.T) {
ctx := context.Background()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
f := reconcileSetup(t, db)
hash := f.file("job input", "pending", 48*time.Hour, true, false)
var id uuid.UUID
if err := db.Pool.QueryRow(ctx, `SELECT id FROM attachments WHERE file_hash=$1`, hash).Scan(&id); err != nil {
t.Fatal(err)
}
stage := "staging/" + id.String()
output := "variants/" + id.String() + "/1/thumbnail/" + strings.Repeat("0", 64)
old := time.Now().Add(-48 * time.Hour)
f.b.add(stage, []byte("job input"), old)
f.b.add(output, []byte("partial"), old)
f.exec(`INSERT INTO attachment_jobs(attachment_id,source_key) VALUES ($1,$2)`, id, stage)
for _, apply := range []bool{false, true} {
stats, _, err := f.run(apply, false)
if err != nil || stats.Findings != 0 || !f.b.has(stage) || !f.b.has(output) {
t.Fatalf("active job lost: %+v %v", stats, err)
}
}
f.exec(`UPDATE attachment_jobs SET state='failed', error_code='retry_exhausted',updated_at=now()`)
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 1 || !f.b.has(stage) || f.b.has(output) {
t.Fatalf("failed retention: %+v %v", stats, err)
}
f.exec(`UPDATE attachment_jobs SET updated_at=now()-interval '3 hours'`)
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 0 || !f.b.has(stage) {
t.Fatalf("default failed retention: %+v %v", stats, err)
}
r, err := attachment.NewReconcilerWithRetention(db.Pool, f.b, time.Hour, 2*time.Hour)
if err != nil {
t.Fatal(err)
}
stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
if err != nil || stats.Repaired != 1 || f.b.has(stage) {
t.Fatalf("expired source: %+v %v", stats, err)
}
}
+2 -8
View File
@@ -7,17 +7,11 @@ import (
)
type AttachmentRepository interface {
// WithPublication holds the file's hash lock through the callback and commit.
// Publication is valid only inside the callback. Any callback error rolls back.
WithPublication(ctx context.Context, attachment Attachment, fn func(Publication) error) error
// Enqueue checks the staging object under the collector's lock before committing its job.
Enqueue(ctx context.Context, attachment Attachment, stage string, checkStage func() error) error
GetForMember(ctx context.Context, attachmentID, actorID uuid.UUID) (Attachment, error)
}
type Publication interface {
FileReady() bool
SaveReady(ctx context.Context) error
}
type ChatMembership interface {
IsMember(ctx context.Context, chatID, actorID uuid.UUID) (bool, error)
}
+51 -37
View File
@@ -3,14 +3,17 @@ package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"log/slog"
"net/http"
"path/filepath"
"time"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/faultbarrier"
"messenger/internal/platform/ident"
)
@@ -23,8 +26,9 @@ type Service struct {
}
type Config struct {
MaxBytes int64
MaxPixels int64
MaxBytes int64
MaxPixels int64
BarrierDir string
}
// A nil blobs dependency allows the text API to run without configured S3.
@@ -70,7 +74,11 @@ func (s *Service) Upload(ctx context.Context, actor uuid.UUID, input UploadInput
}
id := ident.New()
stage := "staging/" + id.String()
discard := true
defer func() {
if !discard {
return
}
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// A failed cleanup leaves a staging object for the reconciler's grace-based collection.
@@ -119,37 +127,30 @@ func (s *Service) Upload(ctx context.Context, actor uuid.UUID, input UploadInput
FileHash: hash.Sum(nil),
SizeBytes: input.SizeBytes,
MIMEType: input.MIMEType,
Status: FileReady,
Status: FileQueued,
UpdatedAt: ident.TimeOf(id),
CreatedAt: ident.TimeOf(id),
}
if err := s.attachments.WithPublication(ctx, a, func(p Publication) error {
if err := s.publishBlob(ctx, a, stage, p.FileReady()); err != nil {
return err
if s.config.BarrierDir != "" {
base := filepath.Join(s.config.BarrierDir, hex.EncodeToString(a.FileHash)+"-staged")
if err := faultbarrier.Wait(ctx, base, a.ID.String()); err != nil {
return Attachment{}, unavailable(err)
}
return p.SaveReady(ctx)
}); err != nil {
return Attachment{}, err
}
return a, nil
}
func (s *Service) publishBlob(ctx context.Context, a Attachment, stagingKey string, fileReady bool) error {
blobKey := BlobKey(a.FileHash)
if fileReady {
obj, err := s.blobs.Stat(ctx, blobKey)
if err == nil && obj.Size == a.SizeBytes {
return nil
}
if err != nil && !errors.Is(err, ErrObjectMissing) {
// COMMIT can succeed even if its reply is lost. From this point only the
// collector, after consulting durable job state, may delete this source.
discard = false
err = s.attachments.Enqueue(ctx, a, stage, func() error {
obj, err := s.blobs.Stat(ctx, stage)
if err != nil {
return unavailable(err)
}
}
// The hash is known after streaming. Copy the validated staging object to
// its permanent CAS key while the repository's publication lock is held.
if err := s.blobs.Copy(ctx, stagingKey, blobKey); err != nil {
return unavailable(err)
}
return nil
if obj.Size != a.SizeBytes {
return unavailable(errors.New("staging size changed"))
}
return nil
})
return a, err
}
func (s *Service) validate(ctx context.Context, stage, mime string) (err error) {
@@ -189,25 +190,38 @@ func (r *storageReader) Read(p []byte) (int, error) {
}
func (s *Service) Get(ctx context.Context, actor, id uuid.UUID) (Attachment, error) {
a, err := s.attachments.GetForMember(ctx, id, actor)
if err != nil {
return Attachment{}, err
}
if a.Status != FileReady {
return Attachment{}, apperr.Conflict("attachment is not ready")
}
return a, nil
return s.attachments.GetForMember(ctx, id, actor)
}
func (s *Service) Content(ctx context.Context, actor, id uuid.UUID) (Attachment, io.ReadCloser, error) {
func (s *Service) Content(ctx context.Context, actor, id uuid.UUID, name string) (Attachment, io.ReadCloser, error) {
a, err := s.Get(ctx, actor, id)
if err != nil {
return Attachment{}, nil, err
}
if a.Status != FileReady {
return Attachment{}, nil, apperr.Conflict("attachment is not ready")
}
key := BlobKey(a.FileHash)
if name != "original" {
found := false
for _, v := range a.Variants {
if name == v.Name {
key, a.MIMEType, a.SizeBytes = v.ObjectKey, v.MIMEType, v.SizeBytes
found = true
break
}
}
if !found {
return Attachment{}, nil, apperr.NotFound("variant not found")
}
}
if s.blobs == nil {
return Attachment{}, nil, apperr.Unavailable("object storage is unavailable")
}
r, err := s.blobs.Open(ctx, BlobKey(a.FileHash))
r, err := s.blobs.Open(ctx, key)
if name != "original" && errors.Is(err, ErrObjectMissing) {
return Attachment{}, nil, apperr.NotFound("variant not found")
}
if err != nil {
return Attachment{}, nil, unavailable(err)
}
+64 -159
View File
@@ -3,7 +3,6 @@ package attachment_test
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"io"
"os"
@@ -20,159 +19,79 @@ import (
"messenger/internal/testenv"
)
type testBlobs struct {
mu sync.Mutex
data map[string][]byte
copies int
failCopy bool
}
type blockingPublication struct {
*testBlobs
entered, resume chan struct{}
}
func (b *blockingPublication) Copy(ctx context.Context, from, to string) error {
close(b.entered)
select {
case <-b.resume:
case <-ctx.Done():
return ctx.Err()
}
return b.testBlobs.Copy(ctx, from, to)
}
func (b *blockingPublication) Stat(ctx context.Context, key string) (attachment.Object, error) {
o, e := b.testBlobs.Stat(ctx, key)
o.Modified = time.Now().Add(-2 * time.Hour)
return o, e
}
func TestCollectorRechecksReferencesAfterConcurrentPublication(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
func TestCollectorRechecksStageAfterConcurrentEnqueue(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
actor, room := ident.New(), ident.New()
if _, err = db.Pool.Exec(ctx, `INSERT INTO users VALUES($1,'race_user','User','hash',now())`, actor); err != nil {
t.Fatal(err)
}
if _, err = db.Pool.Exec(ctx, `INSERT INTO chats VALUES($1,'race',now())`, room); err != nil {
t.Fatal(err)
}
if _, err = db.Pool.Exec(ctx, `INSERT INTO chat_members VALUES($1,$2)`, room, actor); err != nil {
t.Fatal(err)
}
f := reconcileSetup(t, db)
f.exec(`INSERT INTO chat_members VALUES ($1,$2)`, f.chat, f.user)
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
hash := sha256.Sum256(data)
if _, err = db.Pool.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png','pending',now()-interval '2 hours')`, hash[:], len(data)); err != nil {
t.Fatal(err)
entered := make(chan string, 1)
resume := make(chan struct{})
var once sync.Once
f.b.stating = func(key string) {
once.Do(func() {
f.b.add(key, data, time.Now().Add(-2*time.Hour))
entered <- key
select {
case <-resume:
case <-ctx.Done():
}
})
}
b := &blockingPublication{testBlobs: &testBlobs{data: map[string][]byte{}}, entered: make(chan struct{}), resume: make(chan struct{})}
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), b, attachment.Config{})
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), f.b, attachment.Config{})
uploaded := make(chan error, 1)
go func() {
input := attachment.UploadInput{ChatID: room, Filename: "race.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
_, e := s.Upload(ctx, actor, input, bytes.NewReader(data))
uploaded <- e
_, err := s.Upload(ctx, f.user, attachment.UploadInput{ChatID: f.chat, Filename: "photo.png", MIMEType: "image/png", SizeBytes: int64(len(data))}, bytes.NewReader(data))
uploaded <- err
}()
var key string
select {
case <-b.entered:
case key = <-entered:
case <-ctx.Done():
t.Fatal("publisher never reached copy")
t.Fatal("upload never verified staging under lock")
}
r, err := attachment.NewReconciler(db.Pool, b, time.Hour)
r, err := attachment.NewReconciler(db.Pool, f.b, time.Hour)
if err != nil {
t.Fatal(err)
}
collected := make(chan error, 1)
collect := make(chan error, 1)
go func() {
stats, e := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
if e == nil && stats.Repaired != 0 {
e = errors.New("collector removed a newly referenced file")
stats, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
if err == nil && stats.Repaired != 0 {
err = errors.New("removed concurrent upload")
}
collected <- e
collect <- err
}()
// Observe a real waiting advisory lock, rather than guessing which goroutine won.
deadline := time.Now().Add(3 * time.Second)
waiting := false
for time.Now().Before(deadline) {
var n int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND NOT granted`).Scan(&n); err != nil {
t.Fatal(err)
}
if n > 0 {
waiting = true
break
}
time.Sleep(5 * time.Millisecond)
}
close(b.resume)
if !waiting {
t.Fatal("collector did not serialize with the publisher")
}
waitReconcileLock(t, ctx, db.Pool)
close(resume)
if err := <-uploaded; err != nil {
t.Fatal(err)
}
if err := <-collected; err != nil {
if err := <-collect; err != nil {
t.Fatal(err)
}
if _, err := b.Stat(ctx, attachment.BlobKey(hash[:])); err != nil {
t.Fatal("collector deleted published data", err)
if !f.b.has(key) {
t.Fatal("accepted source lost")
}
}
func (b *testBlobs) Put(_ context.Context, k string, r io.Reader, n int64, m string) error {
data, err := io.ReadAll(r)
if err != nil {
type lostCommitReply struct {
attachment.AttachmentRepository
}
func (r lostCommitReply) Enqueue(ctx context.Context, a attachment.Attachment, stage string, check func() error) error {
if err := r.AttachmentRepository.Enqueue(ctx, a, stage, check); err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
b.data[k] = data
return nil
}
func (b *testBlobs) Open(_ context.Context, k string) (io.ReadCloser, error) {
b.mu.Lock()
defer b.mu.Unlock()
data, ok := b.data[k]
if !ok {
return nil, attachment.ErrObjectMissing
}
return io.NopCloser(bytes.NewReader(data)), nil
}
func (b *testBlobs) Stat(_ context.Context, k string) (attachment.Object, error) {
b.mu.Lock()
defer b.mu.Unlock()
data, ok := b.data[k]
if !ok {
return attachment.Object{}, attachment.ErrObjectMissing
}
return attachment.Object{Key: k, Size: int64(len(data)), Modified: time.Now()}, nil
}
func (b *testBlobs) Copy(_ context.Context, from, to string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.failCopy {
return errors.New("copy outage")
}
b.copies++
b.data[to] = bytes.Clone(b.data[from])
return nil
}
func (b *testBlobs) Delete(_ context.Context, k string) error {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.data, k)
return nil
}
func (b *testBlobs) List(context.Context, string, string, int) ([]attachment.Object, error) {
return nil, nil
return io.ErrUnexpectedEOF
}
func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
@@ -197,7 +116,7 @@ func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
t.Fatal(err)
}
}
b := &testBlobs{data: map[string][]byte{}}
b := newReconcileBlobs()
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), b, attachment.Config{})
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
@@ -220,13 +139,16 @@ func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
})
}
wg.Wait()
var files, atts int
err = db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments)`).Scan(&files, &atts)
if err != nil {
t.Fatal(err)
var files, atts, jobs int
err = db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments),
(SELECT count(*) FROM attachment_jobs WHERE state='queued' AND attempt=1 AND published_at IS NULL)`).Scan(&files, &atts, &jobs)
if err != nil || files != 1 || atts != 10 || jobs != 10 || len(b.objects) != 10 {
t.Fatalf("handoff: files=%d attachments=%d jobs=%d objects=%d err=%v", files, atts, jobs, len(b.objects), err)
}
if files != 1 || atts != 10 || b.copies != 1 || len(b.data) != 1 {
t.Fatalf("files=%d attachments=%d copies=%d objects=%d", files, atts, b.copies, len(b.data))
for _, a := range results {
if a.Status != attachment.FileQueued || !bytes.Equal(b.bodies["staging/"+a.ID.String()], data) {
t.Fatal("missing queued source", a.ID)
}
}
if results[0].ID == results[1].ID {
t.Fatal("deduplication merged chat ACL identity")
@@ -234,43 +156,26 @@ func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
if _, err := s.Get(ctx, ident.New(), results[0].ID); apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("outsider got %v", err)
}
// A removed blob is republished from the new upload, preserving old references.
b.mu.Lock()
clear(b.data)
b.mu.Unlock()
input := attachment.UploadInput{ChatID: c1, Filename: "again.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(data)); err != nil {
t.Fatal(err)
input := attachment.UploadInput{ChatID: c1, Filename: "lost.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
lost := attachment.NewService(lostCommitReply{store.NewAttachments(db.Pool)}, chatstore.NewChats(db.Pool), b, attachment.Config{})
if _, err := lost.Upload(ctx, actor, input, bytes.NewReader(data)); !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatal("lost commit reply:", err)
}
if b.copies != 2 {
t.Fatalf("missing ready blob was not restored: copies=%d", b.copies)
var source string
if err := db.Pool.QueryRow(ctx, `SELECT j.source_key FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.filename='lost.png'`).Scan(&source); err != nil || !bytes.Equal(b.bodies[source], data) {
t.Fatal("committed job lost source", err)
}
b.failCopy = true
other := bytes.Clone(data)
other = append(other, 0)
input.Filename, input.SizeBytes = "failed.png", int64(len(other))
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(other)); apperr.KindOf(err) != apperr.KindUnavailable {
t.Fatalf("copy outage: %v", err)
}
if len(b.data) != 1 {
t.Fatalf("failed publication left staging: %d objects", len(b.data))
}
b.failCopy = false
// S3 publication succeeds, then PostgreSQL refuses the logical attachment.
// Compensation may remove staging but must leave shared CAS data intact.
_, err = db.Pool.Exec(ctx, `CREATE FUNCTION reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected insert failure'; END $$;
CREATE TRIGGER reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION reject_attachment()`)
_, err = db.Pool.Exec(ctx, `CREATE FUNCTION reject_job() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected insert failure'; END $$;
CREATE TRIGGER reject_job BEFORE INSERT ON attachment_jobs FOR EACH ROW EXECUTE FUNCTION reject_job()`)
if err != nil {
t.Fatal(err)
}
input.Filename = "rollback.png"
other := append(bytes.Clone(data), 0)
input.Filename, input.SizeBytes = "rollback.png", int64(len(other))
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(other)); err == nil {
t.Fatal("publication survived rejected metadata")
t.Fatal("accepted rejected job")
}
if len(b.data) != 2 {
t.Fatalf("expected original and recoverable orphan, got %d objects", len(b.data))
}
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM files`).Scan(&files); err != nil || files != 1 {
t.Fatalf("failed DB insert committed file metadata: %d %v", files, err)
if err := db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments),(SELECT count(*) FROM attachment_jobs)`).Scan(&files, &atts, &jobs); err != nil || files != 1 || atts != 11 || jobs != 11 || len(b.objects) != 12 {
t.Fatalf("rollback: files=%d attachments=%d jobs=%d objects=%d err=%v", files, atts, jobs, len(b.objects), err)
}
}
+55 -57
View File
@@ -2,8 +2,7 @@ package store
import (
"context"
"errors"
"fmt"
"crypto/sha256"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -14,78 +13,77 @@ import (
"messenger/internal/platform/postgres"
)
type Attachments struct {
pool *pgxpool.Pool
}
type Attachments struct{ pool *pgxpool.Pool }
var _ attachment.AttachmentRepository = (*Attachments)(nil)
func NewAttachments(pool *pgxpool.Pool) *Attachments {
return &Attachments{pool: pool}
}
func NewAttachments(pool *pgxpool.Pool) *Attachments { return &Attachments{pool: pool} }
// Publication and garbage collection use the same hash lock. The transaction
// spans only publication, never client transfer or image decoding.
func (r *Attachments) WithPublication(ctx context.Context, a attachment.Attachment, fn func(attachment.Publication) error) error {
func (r *Attachments) Enqueue(ctx context.Context, a attachment.Attachment, stage string, checkStage func() error) error {
return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `SET LOCAL idle_in_transaction_session_timeout = '35s'`); err != nil {
// A request can pause after validation for longer than the GC grace.
// Verify the source after serializing with deletion of this exact key.
stageHash := sha256.Sum256([]byte(stage))
if err := attachment.LockHash(ctx, tx, stageHash[:]); err != nil {
return err
}
if err := checkStage(); err != nil {
return err
}
if err := attachment.LockHash(ctx, tx, a.FileHash); err != nil {
return err
}
var status attachment.FileStatus
err := tx.QueryRow(ctx, `SELECT status FROM files WHERE hash = $1 FOR UPDATE`, a.FileHash).Scan(&status)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
if _, err := tx.Exec(ctx, `
INSERT INTO files(hash,size_bytes,mime_type,status) VALUES ($1,$2,$3,'pending')
ON CONFLICT (hash) DO NOTHING`, a.FileHash, a.SizeBytes, a.MIMEType); err != nil {
return err
}
return fn(publication{tx: tx, attachment: a, ready: status == attachment.FileReady})
if _, err := tx.Exec(ctx, `
INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at)
VALUES ($1,$2,$3,$4,$5,$6)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.FileHash, a.CreatedAt); err != nil {
return err
}
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(attachment_id,source_key) VALUES ($1,$2)`, a.ID, stage)
return err
}))
}
type publication struct {
tx pgx.Tx
attachment attachment.Attachment
ready bool
}
func (p publication) FileReady() bool { return p.ready }
func (p publication) SaveReady(ctx context.Context) error {
a := p.attachment
_, err := p.tx.Exec(ctx, `
INSERT INTO files (hash, size_bytes, mime_type, status)
VALUES ($1, $2, $3, $4)
ON CONFLICT (hash) DO UPDATE
SET size_bytes = excluded.size_bytes,
mime_type = excluded.mime_type,
status = excluded.status`,
a.FileHash, a.SizeBytes, a.MIMEType, attachment.FileReady)
if err != nil {
return fmt.Errorf("publish file: %w", err)
}
_, err = p.tx.Exec(ctx, `
INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at)
VALUES ($1, $2, $3, $4, $5, $6)`,
a.ID, a.ChatID, a.OwnerID, a.Filename, a.FileHash, a.CreatedAt)
return err
}
func (r *Attachments) GetForMember(ctx context.Context, id, actor uuid.UUID) (attachment.Attachment, error) {
var a attachment.Attachment
err := r.pool.QueryRow(ctx, `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.file_hash,
f.size_bytes, f.mime_type, f.status, a.created_at
// A single statement returns one snapshot of the published version, even
// when a worker completes a newer version during a download.
rows, err := r.pool.Query(ctx, `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.file_hash, f.size_bytes, f.mime_type,
s.status, s.error_code, a.created_at, s.updated_at,
coalesce(v.variant,''),coalesce(v.object_key,''),coalesce(v.mime_type,''),
coalesce(v.size_bytes,0),coalesce(v.width,0),coalesce(v.height,0),v.sha256
FROM attachments a
JOIN files f ON f.hash = a.file_hash
WHERE a.id = $1 AND EXISTS (
SELECT 1 FROM chat_members m
WHERE m.chat_id = a.chat_id AND m.user_id = $2
)`, id, actor).
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.FileHash,
&a.SizeBytes, &a.MIMEType, &a.Status, &a.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return attachment.Attachment{}, apperr.NotFound("attachment not found")
JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2
JOIN files f ON f.hash=a.file_hash
JOIN attachment_states s ON s.id=a.id
LEFT JOIN attachment_variants v ON v.attachment_id=a.id AND v.pipeline_version=a.published_version AND s.status='ready'
WHERE a.id=$1 ORDER BY v.variant`, id, actor)
if err != nil {
return a, postgres.Classify(err)
}
return a, postgres.Classify(err)
defer rows.Close()
for rows.Next() {
var v attachment.Variant
err := rows.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.FileHash, &a.SizeBytes, &a.MIMEType,
&a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt,
&v.Name, &v.ObjectKey, &v.MIMEType, &v.SizeBytes, &v.Width, &v.Height, &v.Hash)
if err != nil {
return attachment.Attachment{}, postgres.Classify(err)
}
if v.Name != "" {
a.Variants = append(a.Variants, v)
}
}
if err := rows.Err(); err != nil {
return attachment.Attachment{}, postgres.Classify(err)
}
if a.ID == uuid.Nil {
return a, apperr.NotFound("attachment not found")
}
return a, nil
}