lab6 done

This commit is contained in:
Khakimov Dmitrij
2026-11-18 21:37:25 +03:00
parent 470d9d6f1e
commit 4ab9b0ef9a
158 changed files with 21115 additions and 52 deletions
+158
View File
@@ -0,0 +1,158 @@
package attachment
import (
"context"
"encoding/json"
"fmt"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
"os"
"strconv"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type Options struct {
Concurrency, Prefetch, MaxOutstanding, MaxAttempts, PixelBudget int
Timeout, Lease time.Duration
}
func LoadOptions() (Options, error) {
o := Options{}
for _, v := range []struct {
name string
target *int
def, max int
}{
{"WORKER_CONCURRENCY", &o.Concurrency, 2, 8}, {"WORKER_PREFETCH", &o.Prefetch, 4, 32},
{"MAX_OUTSTANDING_JOBS", &o.MaxOutstanding, 200, 10000}, {"WORKER_MAX_ATTEMPTS", &o.MaxAttempts, 5, 20},
{"WORKER_PIXEL_BUDGET", &o.PixelBudget, 40000000, 80000000},
} {
n := v.def
if raw := os.Getenv(v.name); raw != "" {
var err error
n, err = strconv.Atoi(raw)
if err != nil {
return o, fmt.Errorf("invalid %s", v.name)
}
}
if n < 1 || n > v.max {
return o, fmt.Errorf("invalid %s", v.name)
}
*v.target = n
}
for _, v := range []struct {
name string
target *time.Duration
def int
}{{"WORKER_TIMEOUT_SECONDS", &o.Timeout, 25}, {"WORKER_LEASE_SECONDS", &o.Lease, 40}} {
n := v.def
if raw := os.Getenv(v.name); raw != "" {
var e error
n, e = strconv.Atoi(raw)
if e != nil {
return o, fmt.Errorf("invalid %s", v.name)
}
}
if n < 1 || n > 300 {
return o, fmt.Errorf("invalid %s", v.name)
}
*v.target = time.Duration(n) * time.Second
}
if o.Lease < o.Timeout+5*time.Second {
return o, fmt.Errorf("worker lease must exceed timeout by at least 5s")
}
if o.PixelBudget < int(MaxPixels) {
return o, fmt.Errorf("WORKER_PIXEL_BUDGET must allow one 40MP image")
}
return o, nil
}
func NewAsync(pool *pgxpool.Pool, store *Store, o Options) *Service {
s := New(pool, store)
s.Async = true
s.Options = o
return s
}
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body interface{ Read([]byte) (int, error) }) (Attachment, error) {
if !s.Async {
return s.uploadSync(ctx, chatID, userID, name, contentType, body)
}
if err := ValidateFilename(name); err != nil {
return Attachment{}, err
}
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
defer cancel()
select {
case s.slots <- struct{}{}:
defer func() { <-s.slots }()
case <-ctx.Done():
return Attachment{}, unavailable()
}
original, err := Spool(ctx, body, contentType)
if err != nil {
return Attachment{}, err
}
defer original.Close()
tx, err := s.Pool.Begin(ctx)
if err != nil {
return Attachment{}, unavailable()
}
defer tx.Rollback(context.Background())
// All API replicas serialize admission, including inserts before their COMMIT.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(578903551)`); err != nil {
return Attachment{}, unavailable()
}
var pending int
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')`).Scan(&pending); err != nil {
return Attachment{}, unavailable()
}
if pending >= s.Options.MaxOutstanding {
return Attachment{}, appError("rate_limited", "Очередь заполнена; повторите загрузку позднее")
}
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "queued", Variants: []any{}, PipelineVersion: 1}
stage := "staging/" + a.ID
a.Key = effectKey(a.ID, 1, "original")
// The stage lock protects even a slow PUT from the orphan cleaner.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, stage); err != nil {
return Attachment{}, unavailable()
}
if err = s.put(ctx, stage, original.File, original.Size, original.ContentType); err != nil {
return Attachment{}, unavailable()
}
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height,status,staging_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'queued',$11) RETURNING created_at,updated_at`, a.ID, chatID, userID, name, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height, stage).Scan(&a.CreatedAt, &a.UpdatedAt)
if err != nil {
return Attachment{}, unavailable()
}
job := uuid.NewString()
traceparent, tracestate := observability.Inject(ctx)
if _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,state,max_attempts,traceparent,tracestate) VALUES($1,$2,'queued',$3,$4,$5)`, job, a.ID, s.Options.MaxAttempts, traceparent, tracestate); err != nil {
return Attachment{}, unavailable()
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id) VALUES($1)`, job); err != nil {
return Attachment{}, unavailable()
}
if err = tx.Commit(ctx); err != nil {
return Attachment{}, unavailable()
}
return a, nil
}
func effectKey(id string, version int, name string) string {
return fmt.Sprintf("original/%s/v%d/%s", id, version, name)
}
func (s *Service) Variant(a Attachment, name string) (Attachment, error) {
if name == "original" {
return a, nil
}
for _, item := range a.Variants {
raw, _ := json.Marshal(item)
var v Variant
if json.Unmarshal(raw, &v) == nil && v.Name == name {
a.Key = effectKey(a.ID, a.PipelineVersion, name)
a.ContentType = v.ContentType
return a, nil
}
}
return Attachment{}, appError(domain.ErrorNotFound, "Вариант не найден")
}
+128
View File
@@ -0,0 +1,128 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"os"
"strings"
"unicode"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const MaxBytes int64 = 10 * 1024 * 1024
const MaxPixels int64 = 40_000_000
func appError(code domain.ErrorCode, message string) error {
return domain.NewApplicationError(code, message)
}
func unavailable() error {
return appError(domain.ErrorUnavailable, "Хранилище вложений недоступно")
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return appError(domain.ErrorInvalid, "Некорректный filename")
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return appError(domain.ErrorInvalid, "Недопустимые символы filename")
}
}
return nil
}
type Original struct {
File *os.File
Size int64
SHA256, ContentType string
Width, Height int
}
func (o *Original) Close() { name := o.File.Name(); o.File.Close(); os.Remove(name) }
// Spool bounds compressed bytes on disk before any decode. DecodeConfig checks the
// pixel budget before a full decode verifies CRCs/truncated scan data.
func Spool(ctx context.Context, body io.Reader, declared string) (*Original, error) {
media, _, err := mime.ParseMediaType(declared)
if err != nil || (media != "image/png" && media != "image/jpeg") {
return nil, appError("unsupported_media_type", "Допустимы PNG и JPEG")
}
f, err := os.CreateTemp("", "messenger-upload-*")
if err != nil {
return nil, unavailable()
}
o := &Original{File: f}
good := false
defer func() {
if !good {
o.Close()
}
}()
hash := sha256.New()
n, err := io.Copy(io.MultiWriter(f, hash), io.LimitReader(&contextReader{ctx: ctx, r: body}, MaxBytes+1))
if n > MaxBytes {
return nil, appError("payload_too_large", "Файл превышает 10 MiB")
}
if err != nil {
return nil, appError(domain.ErrorInvalid, "Загрузка прервана")
}
o.Size = n
o.SHA256 = hex.EncodeToString(hash.Sum(nil))
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
cfg, format, err := image.DecodeConfig(f)
if err != nil {
return nil, appError("unsupported_media_type", "Повреждённое изображение")
}
actual := "image/" + format
if actual != media {
return nil, appError("unsupported_media_type", "MIME не соответствует содержимому")
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
return nil, appError("payload_too_large", "Изображение превышает 40 миллионов пикселей")
}
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
decoded, format, err := image.Decode(f)
if err != nil || decoded == nil || "image/"+format != actual {
return nil, appError("unsupported_media_type", "Повреждённое изображение")
}
if decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
return nil, appError("unsupported_media_type", "Некорректные размеры изображения")
}
decoded = nil
if _, err = f.Seek(0, 0); err != nil {
return nil, unavailable()
}
o.ContentType = actual
o.Width = cfg.Width
o.Height = cfg.Height
good = true
return o, nil
}
type contextReader struct {
ctx context.Context
r io.Reader
}
func (r *contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
n, err := r.r.Read(p)
if errors.Is(err, context.Canceled) {
return n, err
}
return n, err
}
+139
View File
@@ -0,0 +1,139 @@
package attachment
import (
"bytes"
"context"
"encoding/binary"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"testing"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func pngFixture(t *testing.T) []byte {
t.Helper()
m := image.NewRGBA(image.Rect(0, 0, 10, 8))
m.Set(1, 1, color.RGBA{R: 255, A: 255})
var b bytes.Buffer
if err := png.Encode(&b, m); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func code(t *testing.T, err error, want domain.ErrorCode) {
t.Helper()
app, ok := domain.AsApplicationError(err)
if !ok || app.Code != want {
t.Fatalf("want %s, got %v", want, err)
}
}
func TestSpoolOriginalAndFullValidation(t *testing.T) {
original := pngFixture(t)
good, err := Spool(context.Background(), bytes.NewReader(original), "image/png")
if err != nil {
t.Fatal(err)
}
defer good.Close()
got, err := io.ReadAll(good.File)
if err != nil || !bytes.Equal(got, original) {
t.Fatal("original changed")
}
if good.Width != 10 || good.Height != 8 || good.Size != int64(len(original)) || len(good.SHA256) != 64 {
t.Fatalf("wrong metadata %+v", good)
}
_, err = Spool(context.Background(), bytes.NewReader(original), "image/jpeg")
code(t, err, "unsupported_media_type")
_, err = Spool(context.Background(), bytes.NewReader(original[:len(original)-12]), "image/png")
code(t, err, "unsupported_media_type")
corrupted := bytes.Clone(original)
corrupted[len(corrupted)-18] ^= 0x80
_, err = Spool(context.Background(), bytes.NewReader(corrupted), "image/png")
code(t, err, "unsupported_media_type")
var jpegBytes bytes.Buffer
if err = jpeg.Encode(&jpegBytes, image.NewRGBA(image.Rect(0, 0, 12, 9)), nil); err != nil {
t.Fatal(err)
}
jpegOriginal, err := Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()), "image/jpeg")
if err != nil {
t.Fatal(err)
}
jpegOriginal.Close()
_, err = Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()[:jpegBytes.Len()/2]), "image/jpeg")
code(t, err, "unsupported_media_type")
}
func TestSpoolLimitsBeforeDecode(t *testing.T) {
// Oversized compressed input is stopped after exactly MaxBytes+1 reads.
source := &countingReader{remaining: MaxBytes + 100_000}
_, err := Spool(context.Background(), source, "image/png")
code(t, err, "payload_too_large")
if source.read != MaxBytes+1 {
t.Fatalf("read %d bytes", source.read)
}
bomb := bytes.Clone(pngFixture(t))
binary.BigEndian.PutUint32(bomb[16:20], 40001)
binary.BigEndian.PutUint32(bomb[20:24], 1000)
binary.BigEndian.PutUint32(bomb[29:33], crc32.ChecksumIEEE(bomb[12:29]))
_, err = Spool(context.Background(), bytes.NewReader(bomb), "image/png")
code(t, err, "payload_too_large")
}
type countingReader struct{ remaining, read int64 }
func (c *countingReader) Read(p []byte) (int, error) {
if c.remaining == 0 {
return 0, io.EOF
}
n := min(int64(len(p)), c.remaining)
clear(p[:n])
c.remaining -= n
c.read += n
return int(n), nil
}
func TestFilenameAndCancelledUpload(t *testing.T) {
for _, name := range []string{"", "../x.png", "x\\photo.jpg", "a\x00b", "a\nb", "\t"} {
code(t, ValidateFilename(name), domain.ErrorInvalid)
}
for _, name := range []string{"фото.png", "image.jpg", ".."} {
if err := ValidateFilename(name); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := Spool(ctx, bytes.NewReader(pngFixture(t)), "image/png")
code(t, err, domain.ErrorInvalid)
}
func TestReconcileRejectsUnsafeGrace(t *testing.T) {
s := &Service{}
if _, err := s.Reconcile(context.Background(), true, 89*time.Second); err == nil {
t.Fatal("unsafe grace accepted")
}
if MinimumGrace <= UploadTimeout {
t.Fatal("grace does not cover in-flight PUT")
}
}
func TestValid16BitWidePNG(t *testing.T) {
// Exercise the same RGBA64 + scanline allocation path as an extreme-aspect
// 40M image, at 1/1000 of that pixel count to keep the unit suite small.
img := image.NewNRGBA64(image.Rect(0, 0, 40000, 1))
img.SetNRGBA64(1, 0, color.NRGBA64{R: 65535, G: 12345, B: 4, A: 32000})
var encoded bytes.Buffer
if err := png.Encode(&encoded, img); err != nil {
t.Fatal(err)
}
original, err := Spool(context.Background(), bytes.NewReader(encoded.Bytes()), "image/png")
if err != nil {
t.Fatal(err)
}
defer original.Close()
if original.Width != 40000 || original.Height != 1 {
t.Fatal("wide PNG dimensions changed")
}
}
+18
View File
@@ -0,0 +1,18 @@
package attachment
import (
"encoding/json"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
// MarshalJSON uses the API's fixed microsecond precision instead of time.Time's
// variable fractional precision, which Python 3.9 clients cannot always parse.
func (a Attachment) MarshalJSON() ([]byte, error) {
type fields Attachment
return json.Marshal(struct {
fields
CreatedAt dto.Timestamp `json:"created_at"`
UpdatedAt dto.Timestamp `json:"updated_at"`
}{fields: fields(a), CreatedAt: dto.Timestamp(a.CreatedAt), UpdatedAt: dto.Timestamp(a.UpdatedAt)})
}
+37
View File
@@ -0,0 +1,37 @@
package attachment
import (
"encoding/json"
"testing"
"time"
)
func TestAttachmentTimestampsUseFixedMicroseconds(t *testing.T) {
value := Attachment{ID: "attachment-id", CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC), UpdatedAt: time.Date(2026, 1, 2, 6, 4, 5, 0, time.FixedZone("MSK", 3*60*60)), Key: "original/private", Variants: []any{}}
encoded, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err = json.Unmarshal(encoded, &fields); err != nil {
t.Fatal(err)
}
if fields["created_at"] != "2026-01-02T03:04:05.123400Z" {
t.Fatalf("created_at=%v", fields["created_at"])
}
if fields["updated_at"] != "2026-01-02T03:04:05.000000Z" {
t.Fatalf("updated_at=%v", fields["updated_at"])
}
if fields["id"] != value.ID {
t.Fatal("serialization lost metadata")
}
if _, exposed := fields["Key"]; exposed {
t.Fatal("serialization exposed private object key")
}
if _, exposed := fields["key"]; exposed {
t.Fatal("serialization exposed private object key")
}
if fields["error_code"] != nil {
t.Fatal("ready error_code must be null")
}
}
+225
View File
@@ -0,0 +1,225 @@
package attachment
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
)
type Summary struct {
Apply bool `json:"apply"`
GraceSeconds float64 `json:"grace_seconds"`
ObjectsScanned int `json:"objects_scanned"`
MetadataScanned int `json:"metadata_scanned"`
BytesScanned int64 `json:"bytes_scanned"`
ListRequestsEstimate int `json:"list_requests_estimate"`
StatRequests int `json:"stat_requests"`
DBQueries int `json:"db_queries"`
Orphans int `json:"orphans"`
Missing int `json:"missing"`
FreshSkipped int `json:"fresh_skipped"`
LockedSkipped int `json:"locked_skipped"`
ReferencedMissing int `json:"referenced_missing"`
Deleted int `json:"deleted"`
MarkedFailed int `json:"marked_failed"`
DurationMS int64 `json:"duration_ms"`
Actions []Action `json:"actions"`
}
type Action struct {
Kind string `json:"kind"`
Key string `json:"key"`
Applied bool `json:"applied"`
}
// Reconcile scans a fixed cutoff and rechecks each candidate while holding the
// same transaction-scoped advisory lock as upload. Metadata, including message
// references, is never deleted. Missing originals become failed tombstones.
func (s *Service) Reconcile(ctx context.Context, apply bool, grace time.Duration) (result Summary, err error) {
started := time.Now()
result = Summary{Apply: apply, GraceSeconds: grace.Seconds(), Actions: []Action{}}
defer func() { result.DurationMS = time.Since(started).Milliseconds() }()
if grace < MinimumGrace {
return result, fmt.Errorf("grace must be at least %s (upload timeout %s)", MinimumGrace, UploadTimeout)
}
cutoff := started.Add(-grace)
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) {
if obj.Err != nil {
return result, fmt.Errorf("S3 listing failed")
}
result.ObjectsScanned++
result.BytesScanned += obj.Size
if result.ObjectsScanned%1000 == 1 {
result.ListRequestsEstimate++
}
if !obj.LastModified.Before(cutoff) {
result.FreshSkipped++
continue
}
err = s.reconcileObject(ctx, obj.Key, cutoff, apply, &result)
if err != nil {
return result, err
}
}
// Bounded keyset pages avoid retaining the entire bucket or a DB cursor while
// making per-object transactions. A later run picks up concurrent new rows.
last := "00000000-0000-0000-0000-000000000000"
for {
result.DBQueries++
rows, e := s.Pool.Query(ctx, `SELECT id::text,object_key,created_at,status FROM attachments WHERE id>$1 ORDER BY id LIMIT 100`, last)
if e != nil {
return result, fmt.Errorf("metadata scan failed")
}
type metadata struct {
id, key, status string
created time.Time
}
page := []metadata{}
for rows.Next() {
var m metadata
if e = rows.Scan(&m.id, &m.key, &m.created, &m.status); e != nil {
rows.Close()
return result, e
}
page = append(page, m)
}
e = rows.Err()
rows.Close()
if e != nil {
return result, e
}
if len(page) == 0 {
break
}
for _, m := range page {
last = m.id
result.MetadataScanned++
if m.status != "ready" {
continue
}
if !m.created.Before(cutoff) {
result.FreshSkipped++
continue
}
if e = s.reconcileMetadata(ctx, m.id, m.key, cutoff, apply, &result); e != nil {
return result, e
}
}
}
if ctx.Err() != nil {
return result, ctx.Err()
}
return result, nil
}
func (s *Service) locked(ctx context.Context, key string, r *Summary) (pgx.Tx, bool, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return nil, false, fmt.Errorf("DB unavailable")
}
var locked bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, key).Scan(&locked); err != nil {
tx.Rollback(context.Background())
return nil, false, fmt.Errorf("lock failed")
}
if !locked {
r.LockedSkipped++
tx.Rollback(context.Background())
return nil, false, nil
}
return tx, true, nil
}
func (s *Service) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var exists bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1 OR staging_key=$1 OR $1 LIKE 'original/'||id::text||'/v'||pipeline_version::text||'/%')`, key).Scan(&exists); err != nil {
return fmt.Errorf("metadata recheck failed")
}
if exists {
return nil
}
r.StatRequests++
obj, err := s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if IsMissing(err) {
return nil
}
if err != nil {
return fmt.Errorf("object recheck failed")
}
if !obj.LastModified.Before(cutoff) {
r.FreshSkipped++
return nil
}
r.Orphans++
if apply {
if err = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{}); err != nil {
return fmt.Errorf("orphan deletion failed")
}
r.Deleted++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "orphan", Key: key, Applied: apply})
}
return nil
}
func (s *Service) reconcileMetadata(ctx context.Context, id, key string, cutoff time.Time, apply bool, r *Summary) error {
tx, ok, err := s.locked(ctx, key, r)
if err != nil || !ok {
return err
}
defer tx.Rollback(context.Background())
var created time.Time
var status string
r.DBQueries++
err = tx.QueryRow(ctx, `SELECT created_at,status FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&created, &status)
if err == pgx.ErrNoRows {
return nil
}
if err != nil {
return fmt.Errorf("metadata recheck failed")
}
if status != "ready" || !created.Before(cutoff) {
return nil
}
r.StatRequests++
_, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
if err == nil {
return nil
}
if !IsMissing(err) {
return fmt.Errorf("object stat failed (no mutation)")
}
var referenced bool
r.DBQueries++
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE $1::uuid=ANY(attachment_ids))`, id).Scan(&referenced); err != nil {
return fmt.Errorf("reference check failed")
}
r.Missing++
if referenced {
r.ReferencedMissing++
}
if apply {
r.DBQueries++
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing',updated_at=clock_timestamp() WHERE id=$1 AND status='ready'`, id); err != nil {
return fmt.Errorf("mark missing failed")
}
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='failed',last_error='original_missing',fence=fence+1,updated_at=clock_timestamp() WHERE attachment_id=$1 AND state='ready'`, id); err != nil {
return fmt.Errorf("mark job missing failed")
}
if err = tx.Commit(ctx); err != nil {
return fmt.Errorf("commit missing failed")
}
r.MarkedFailed++
}
if len(r.Actions) < 100 {
r.Actions = append(r.Actions, Action{Kind: "missing", Key: key, Applied: apply})
}
return nil
}
+267
View File
@@ -0,0 +1,267 @@
package attachment
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"image"
"image/color"
"image/jpeg"
"image/png"
"math"
"os"
"os/exec"
"path/filepath"
"syscall"
)
var ErrInvalidImage = errors.New("invalid image")
type oriented struct {
image.Image
orientation int
}
func (o oriented) Bounds() image.Rectangle {
b := o.Image.Bounds()
w, h := b.Dx(), b.Dy()
if o.orientation >= 5 && o.orientation <= 8 {
w, h = h, w
}
return image.Rect(0, 0, w, h)
}
func (o oriented) At(x, y int) color.Color {
b := o.Image.Bounds()
w, h := b.Dx(), b.Dy()
sx, sy := x, y
switch o.orientation {
case 2:
sx = w - 1 - x
case 3:
sx, sy = w-1-x, h-1-y
case 4:
sy = h - 1 - y
case 5:
sx, sy = y, x
case 6:
sx, sy = y, h-1-x
case 7:
sx, sy = w-1-y, h-1-x
case 8:
sx, sy = w-1-y, x
}
r, g, blue, a := o.Image.At(b.Min.X+sx, b.Min.Y+sy).RGBA()
white := uint32(65535) - a
return color.RGBA{uint8((r + white) / 257), uint8((g + white) / 257), uint8((blue + white) / 257), 255}
}
// EXIF IFD0 orientation; bounded segment parsing does not follow client offsets outside APP1.
func tiffOrientation(t []byte) int {
if len(t) < 8 {
return 1
}
var order binary.ByteOrder
if string(t[:2]) == "II" {
order = binary.LittleEndian
} else if string(t[:2]) == "MM" {
order = binary.BigEndian
} else {
return 1
}
if order.Uint16(t[2:4]) != 42 {
return 1
}
offset := uint64(order.Uint32(t[4:8]))
if offset+2 > uint64(len(t)) {
return 1
}
count := uint64(order.Uint16(t[offset : offset+2]))
for k := uint64(0); k < count; k++ {
p := offset + 2 + k*12
if p+12 > uint64(len(t)) {
break
}
entry := t[p : p+12]
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
v := int(order.Uint16(entry[8:10]))
if v >= 1 && v <= 8 {
return v
}
}
}
return 1
}
func Orientation(data []byte) int {
if len(data) >= 8 && bytes.Equal(data[:8], []byte{137, 80, 78, 71, 13, 10, 26, 10}) {
for i := 8; i+12 <= len(data); {
n := uint64(binary.BigEndian.Uint32(data[i : i+4]))
if n > uint64(len(data)-i-12) {
return 1
}
end := i + 8 + int(n)
if string(data[i+4:i+8]) == "eXIf" {
return tiffOrientation(data[i+8 : end])
}
i = end + 4
}
return 1
}
if len(data) < 4 || data[0] != 255 || data[1] != 216 {
return 1
}
for i := 2; i+4 <= len(data); {
if data[i] != 255 {
return 1
}
for i+1 < len(data) && data[i+1] == 255 {
i++
}
if i+3 >= len(data) {
return 1
}
marker := data[i+1]
i += 2
if marker == 0xda || marker == 0xd9 {
return 1
}
if marker == 0x01 || marker >= 0xd0 && marker <= 0xd7 {
continue
}
n := int(binary.BigEndian.Uint16(data[i : i+2]))
if n < 2 || i+n > len(data) {
return 1
}
body := data[i+2 : i+n]
i += n
if marker == 0xe1 && len(body) >= 14 && bytes.Equal(body[:6], []byte("Exif\x00\x00")) {
return tiffOrientation(body[6:])
}
}
return 1
}
func fit(w, h, maxSide int) (int, int) {
if w <= maxSide && h <= maxSide {
return w, h
}
if w >= h {
return maxSide, max(1, int(int64(h)*int64(maxSide)/int64(w)))
}
return max(1, int(int64(w)*int64(maxSide)/int64(h))), maxSide
}
func resize(src image.Image, region image.Rectangle, w, h int) *image.RGBA {
out := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
fy := (float64(y)+.5)*float64(region.Dy())/float64(h) - .5
fy = math.Max(0, fy)
y0 := min(int(fy), region.Dy()-1)
y1 := min(y0+1, region.Dy()-1)
dy := fy - float64(y0)
for x := 0; x < w; x++ {
fx := (float64(x)+.5)*float64(region.Dx())/float64(w) - .5
fx = math.Max(0, fx)
x0 := min(int(fx), region.Dx()-1)
x1 := min(x0+1, region.Dx()-1)
dx := fx - float64(x0)
colors := [4]color.RGBA{color.RGBAModel.Convert(src.At(region.Min.X+x0, region.Min.Y+y0)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x1, region.Min.Y+y0)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x0, region.Min.Y+y1)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x1, region.Min.Y+y1)).(color.RGBA)}
blend := func(a, b, c, d uint8) uint8 {
return uint8(math.Round(float64(a)*(1-dx)*(1-dy) + float64(b)*dx*(1-dy) + float64(c)*(1-dx)*dy + float64(d)*dx*dy))
}
out.SetRGBA(x, y, color.RGBA{blend(colors[0].R, colors[1].R, colors[2].R, colors[3].R), blend(colors[0].G, colors[1].G, colors[2].G, colors[3].G), blend(colors[0].B, colors[1].B, colors[2].B, colors[3].B), 255})
}
}
return out
}
// Render runs only inside a deadline-killed child, never in the HTTP process.
func Render(ctx context.Context, source, dir, expectedSHA string) error {
raw, err := os.ReadFile(source)
if err != nil {
return err
}
sum := sha256.Sum256(raw)
if int64(len(raw)) > MaxBytes || hex.EncodeToString(sum[:]) != expectedSHA {
return ErrInvalidImage
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
if err != nil || cfg.Width < 1 || cfg.Height < 1 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
return ErrInvalidImage
}
if os.Getenv("PIPELINE_FAILPOINT") == "renderer_timeout" {
fifo := filepath.Join(dir, "blocked-input.png")
if err = syscall.Mkfifo(fifo, 0600); err != nil {
return err
}
return exec.CommandContext(ctx, "cwebp", "-quiet", fifo, "-o", filepath.Join(dir, "blocked.webp")).Run()
}
decoded, _, err := image.Decode(bytes.NewReader(raw))
if err != nil {
return ErrInvalidImage
}
src := oriented{decoded, Orientation(raw)}
bounds := src.Bounds()
tw, th := fit(bounds.Dx(), bounds.Dy(), 256)
ow, oh := fit(bounds.Dx(), bounds.Dy(), 1280)
variants := []Variant{}
for _, name := range []string{"thumbnail", "crop", "optimized"} {
w, h := tw, th
region := bounds
if name == "crop" {
w, h = 128, 128
side := min(bounds.Dx(), bounds.Dy())
left, top := (bounds.Dx()-side)/2, (bounds.Dy()-side)/2
region = image.Rect(left, top, left+side, top+side)
}
if name == "optimized" {
w, h = ow, oh
}
img := resize(src, region, w, h)
path := filepath.Join(dir, name)
if name == "optimized" {
input := filepath.Join(dir, "webp-input.png")
f, e := os.Create(input)
if e != nil {
return e
}
e = png.Encode(f, img)
f.Close()
if e != nil {
return e
}
command := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", "80", "-m", "4", "-metadata", "none", input, "-o", path)
if err = command.Run(); err != nil {
return err
}
} else {
f, e := os.Create(path)
if e != nil {
return e
}
e = jpeg.Encode(f, img, &jpeg.Options{Quality: 85})
f.Close()
if e != nil {
return e
}
}
data, e := os.ReadFile(path)
if e != nil {
return e
}
hash := sha256.Sum256(data)
mime := "image/jpeg"
if name == "optimized" {
mime = "image/webp"
}
variants = append(variants, Variant{Name: name, ContentType: mime, Width: w, Height: h, Size: int64(len(data)), SHA256: hex.EncodeToString(hash[:])})
}
data, err := json.Marshal(variants)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(dir, "manifest.json"), data, 0600)
}
+81
View File
@@ -0,0 +1,81 @@
package attachment
import (
"bytes"
"encoding/binary"
"image"
"image/color"
"testing"
)
func TestFitGeometry(t *testing.T) {
for _, c := range []struct{ w, h, limit, x, y int }{{320, 200, 256, 256, 160}, {513, 257, 256, 256, 128}, {257, 513, 256, 128, 256}, {12, 8, 256, 12, 8}, {1, 40000, 256, 1, 256}} {
w, h := fit(c.w, c.h, c.limit)
if w != c.x || h != c.y {
t.Fatalf("fit(%d,%d)=%d,%d", c.w, c.h, w, h)
}
}
}
func TestOrientationsAndAlpha(t *testing.T) {
img := image.NewNRGBA(image.Rect(0, 0, 3, 2))
for y := 0; y < 2; y++ {
for x := 0; x < 3; x++ {
img.SetNRGBA(x, y, color.NRGBA{R: uint8(1 + x + y*3), A: 255})
}
}
expected := [][]uint8{{1, 2, 3, 4, 5, 6}, {3, 2, 1, 6, 5, 4}, {6, 5, 4, 3, 2, 1}, {4, 5, 6, 1, 2, 3}, {1, 4, 2, 5, 3, 6}, {4, 1, 5, 2, 6, 3}, {6, 3, 5, 2, 4, 1}, {3, 6, 2, 5, 1, 4}}
for i, want := range expected {
src := oriented{img, i + 1}
got := []uint8{}
for y := 0; y < src.Bounds().Dy(); y++ {
for x := 0; x < src.Bounds().Dx(); x++ {
got = append(got, src.At(x, y).(color.RGBA).R)
}
}
if !bytes.Equal(got, want) {
t.Fatalf("orientation %d: %v want %v", i+1, got, want)
}
}
img.SetNRGBA(0, 0, color.NRGBA{R: 255, A: 128})
got := oriented{img, 1}.At(0, 0).(color.RGBA)
if got != (color.RGBA{255, 127, 127, 255}) {
t.Fatalf("white alpha: %v", got)
}
}
func TestEXIFOrientation(t *testing.T) {
for _, order := range []binary.ByteOrder{binary.LittleEndian, binary.BigEndian} {
for v := 1; v <= 8; v++ {
tiff := make([]byte, 26)
copy(tiff, "II")
if order == binary.BigEndian {
copy(tiff, "MM")
}
order.PutUint16(tiff[2:], 42)
order.PutUint32(tiff[4:], 8)
order.PutUint16(tiff[8:], 1)
order.PutUint16(tiff[10:], 0x112)
order.PutUint16(tiff[12:], 3)
order.PutUint32(tiff[14:], 1)
order.PutUint16(tiff[18:], uint16(v))
data := append([]byte{255, 216, 255, 225, 0, 34}, append([]byte("Exif\x00\x00"), tiff...)...)
if Orientation(data) != v {
t.Fatalf("EXIF value %d", v)
}
pngData := []byte{137, 80, 78, 71, 13, 10, 26, 10}
size := make([]byte, 4)
binary.BigEndian.PutUint32(size, uint32(len(tiff)))
pngData = append(pngData, size...)
pngData = append(pngData, []byte("eXIf")...)
pngData = append(pngData, tiff...)
pngData = append(pngData, 0, 0, 0, 0)
if Orientation(pngData) != v {
t.Fatalf("PNG EXIF value %d", v)
}
}
}
for _, b := range [][]byte{nil, {}, {255, 216, 255, 225, 255, 255}, {255, 216, 255, 255, 225, 0, 2}} {
if Orientation(b) != 1 {
t.Fatal("malformed EXIF should be ignored")
}
}
}
+45
View File
@@ -0,0 +1,45 @@
package attachment
import (
"context"
"crypto/tls"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
"net"
"net/http"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type Store struct {
Client *minio.Client
Bucket string
}
func NewStore(endpoint, bucket, access, secret string, secure bool) (*Store, error) {
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext, MaxIdleConns: 16, MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 5 * time.Second, TLSHandshakeTimeout: 5 * time.Second, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}}
c, err := minio.New(endpoint, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: secure, Region: "us-east-1", Transport: observability.Transport{Base: transport}, MaxRetries: 1})
if err != nil {
return nil, err
}
return &Store{Client: c, Bucket: bucket}, nil
}
func (s *Store) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
for item := range s.Client.ListObjects(ctx, s.Bucket, minio.ListObjectsOptions{Prefix: "original/", MaxKeys: 1, Recursive: true}) {
if item.Err != nil {
return unavailable()
}
return nil
}
if ctx.Err() != nil {
return unavailable()
}
return nil
}
func IsMissing(err error) bool {
code := minio.ToErrorResponse(err).Code
return code == "NoSuchKey" || code == "NoSuchObject"
}
+138
View File
@@ -0,0 +1,138 @@
package attachment
import (
"context"
"encoding/json"
"errors"
"io"
"log"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const UploadTimeout = 45 * time.Second
const MinimumGrace = 90 * time.Second
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Key string `json:"-"`
PipelineVersion int `json:"-"`
}
type Service struct {
Pool *pgxpool.Pool
Store *Store
slots chan struct{}
Async bool
Options Options
}
func New(pool *pgxpool.Pool, store *Store) *Service {
return &Service{Pool: pool, Store: store, slots: make(chan struct{}, 1)}
}
func (s *Service) Ready(ctx context.Context) error { return s.Store.Ready(ctx) }
func (s *Service) uploadSync(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
if err := ValidateFilename(name); err != nil {
return Attachment{}, err
}
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
defer cancel()
select {
case s.slots <- struct{}{}:
defer func() { <-s.slots }()
case <-ctx.Done():
return Attachment{}, unavailable()
}
original, err := Spool(ctx, body, contentType)
if err != nil {
return Attachment{}, err
}
defer original.Close()
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "ready", Variants: []any{}}
a.Key = "original/" + a.ID
tx, err := s.Pool.Begin(ctx)
if err != nil {
return Attachment{}, unavailable()
}
defer tx.Rollback(context.Background())
// Keep the object lock through PUT, metadata insert and COMMIT. A crash releases
// the lock; the grace protects a still-running client PUT at the S3 server.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, a.Key); err != nil {
return Attachment{}, unavailable()
}
_, err = s.Store.Client.PutObject(ctx, s.Store.Bucket, a.Key, original.File, a.Size, minio.PutObjectOptions{ContentType: a.ContentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": a.SHA256}})
if err != nil {
return Attachment{}, unavailable()
}
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING created_at`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height).Scan(&a.CreatedAt)
if err != nil {
log.Print("attachment metadata failed; orphan retained for grace-period reconciliation")
return Attachment{}, unavailable()
}
// Never DELETE on an ambiguous COMMIT failure: the DB may have committed. A
// later reconciler checks both stores under the same lock before any cleanup.
if err = tx.Commit(ctx); err != nil {
return Attachment{}, unavailable()
}
a.UpdatedAt = a.CreatedAt
return a, nil
}
func (s *Service) Get(ctx context.Context, id, userID string) (Attachment, error) {
parsed, err := uuid.Parse(id)
if err != nil {
return Attachment{}, appError(domain.ErrorInvalid, "Некорректный attachment_id")
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
a := Attachment{Variants: []any{}}
var variants []byte
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at,a.updated_at,a.variants,a.pipeline_version FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt, &variants, &a.PipelineVersion)
if errors.Is(err, pgx.ErrNoRows) {
return Attachment{}, appError(domain.ErrorNotFound, "Объект не найден")
}
if err != nil {
return Attachment{}, unavailable()
}
if err = json.Unmarshal(variants, &a.Variants); err != nil {
return Attachment{}, unavailable()
}
// The legacy fixture service preserves lab4 errors; production Async exposes all states.
if a.Status != "ready" && !s.Async {
return Attachment{}, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return a, nil
}
func (s *Service) Content(ctx context.Context, a Attachment) (*minio.Object, error) {
if a.Status != "ready" {
return nil, appError(domain.ErrorConflict, "Вложение не готово")
}
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, a.Key, minio.GetObjectOptions{})
if err != nil {
return nil, unavailable()
}
if _, err = obj.Stat(); err != nil {
obj.Close()
if IsMissing(err) {
return nil, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
}
return nil, unavailable()
}
return obj, nil
}
+658
View File
@@ -0,0 +1,658 @@
package attachment
import (
"context"
"encoding/json"
"errors"
"fmt"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"io"
"log"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
"github.com/redis/go-redis/v9"
"golang.org/x/sync/semaphore"
)
const Stream = "attachments:jobs:v1"
const Group = "image-workers-v1"
type JobMessage struct {
SchemaVersion int `json:"schema_version"`
JobID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
Width int `json:"width"`
Height int `json:"height"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
}
type claimed struct {
JobMessage
Fence int64
Stage, Original, MIME, SHA string
Width, Height int
Size int64
}
func (s *Service) put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
ctx, span := observability.Start(ctx, "s3 PUT", trace.SpanKindClient)
defer span.End()
_, err := s.Store.Client.PutObject(ctx, s.Store.Bucket, key, r, size, minio.PutObjectOptions{ContentType: mime, DisableMultipart: true})
observability.Result(span, err)
return err
}
func (s *Service) Publish(ctx context.Context, r *redis.Client) error {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
rows, err := tx.Query(ctx, `SELECT j.id::text,j.attachment_id::text,j.pipeline_version,j.attempts+1,j.created_at,j.traceparent,j.tracestate FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.published_at IS NULL AND o.available_at<=clock_timestamp() AND j.state='queued' ORDER BY o.available_at LIMIT 32 FOR UPDATE OF o SKIP LOCKED`)
if err != nil {
return err
}
messages := []JobMessage{}
for rows.Next() {
m := JobMessage{SchemaVersion: 1, Type: "attachment.process.v1"}
if err = rows.Scan(&m.JobID, &m.AttachmentID, &m.PipelineVersion, &m.Attempt, &m.CreatedAt, &m.Traceparent, &m.Tracestate); err != nil {
rows.Close()
return err
}
m.CreatedAt = m.CreatedAt.UTC()
messages = append(messages, m)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, m := range messages {
parent := observability.Extract(ctx, m.Traceparent, m.Tracestate)
publishCtx, span := observability.Start(parent, "attachments publish", trace.SpanKindProducer)
m.Traceparent, m.Tracestate = observability.Inject(publishCtx)
raw, _ := json.Marshal(m)
id, e := r.XAdd(publishCtx, &redis.XAddArgs{Stream: Stream, Values: map[string]interface{}{"job": string(raw)}}).Result()
observability.Result(span, e)
observability.Log(publishCtx, "job.published", map[string]any{"job_type": m.Type, "attempt": m.Attempt})
span.End()
if e != nil {
return e
}
if _, e = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=clock_timestamp(),stream_id=$2 WHERE job_id=$1`, m.JobID, id); e != nil {
return e
}
}
return tx.Commit(ctx)
}
func (s *Service) recover(ctx context.Context) error {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
rows, err := tx.Query(ctx, `SELECT id::text,attachment_id::text,attempts,max_attempts FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED`)
if err != nil {
return err
}
type lost struct {
id, att string
attempt, max int
}
all := []lost{}
for rows.Next() {
var l lost
if err = rows.Scan(&l.id, &l.att, &l.attempt, &l.max); err != nil {
rows.Close()
return err
}
all = append(all, l)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, l := range all {
state := "queued"
var code *string
if l.attempt >= l.max {
state = "failed"
v := "retry_exhausted"
code = &v
}
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state=$2,lease_until=NULL,available_at=clock_timestamp(),updated_at=clock_timestamp(),last_error='worker_lost' WHERE id=$1`, l.id, state); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=clock_timestamp() WHERE id=$1`, l.att, state, code); err != nil {
return err
}
if state == "queued" {
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=clock_timestamp() WHERE job_id=$1`, l.id); err != nil {
return err
}
}
}
return tx.Commit(ctx)
}
func (s *Service) claim(ctx context.Context, m JobMessage) (claimed, bool, error) {
j := claimed{JobMessage: m}
tx, err := s.Pool.Begin(ctx)
if err != nil {
return j, false, err
}
defer tx.Rollback(context.Background())
var state string
var attempts, max, version int
var available time.Time
err = tx.QueryRow(ctx, `SELECT state,attempts,max_attempts,available_at,pipeline_version FROM attachment_jobs WHERE id=$1 AND attachment_id=$2 FOR UPDATE`, m.JobID, m.AttachmentID).Scan(&state, &attempts, &max, &available, &version)
if errors.Is(err, pgx.ErrNoRows) {
return j, false, nil
}
if err != nil {
return j, false, err
}
if state == "ready" {
var key, mime string
var size int64
var raw []byte
if err = tx.QueryRow(ctx, `SELECT object_key,content_type,size_bytes,variants FROM attachments WHERE id=$1 AND status='ready' AND pipeline_version=$2`, m.AttachmentID, version).Scan(&key, &mime, &size, &raw); err != nil {
return j, false, err
}
var variants []Variant
if err = json.Unmarshal(raw, &variants); err != nil || len(variants) != 3 {
return j, false, fmt.Errorf("completed effect metadata incomplete")
}
objects := map[string]int64{key: size}
for _, v := range variants {
objects[effectKey(m.AttachmentID, version, v.Name)] = v.Size
}
for object, n := range objects {
info, e := s.Store.Client.StatObject(ctx, s.Store.Bucket, object, minio.StatObjectOptions{})
if e != nil {
return j, false, e
}
if info.Size != n {
return j, false, fmt.Errorf("completed effect size mismatch")
}
}
return j, false, nil
}
if state != "queued" || available.After(time.Now()) || m.Attempt != attempts+1 || version != m.PipelineVersion {
return j, false, nil
}
if attempts >= max {
return j, false, fmt.Errorf("attempt invariant violated")
}
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET state='processing',attempts=attempts+1,fence=fence+1,lease_until=clock_timestamp()+$2*interval '1 second',updated_at=clock_timestamp() WHERE id=$1 RETURNING fence`, m.JobID, s.Options.Lease.Seconds()).Scan(&j.Fence)
if err != nil {
return j, false, err
}
err = tx.QueryRow(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1 AND pipeline_version=$2 AND status IN ('queued','processing') RETURNING staging_key,object_key,content_type,size_bytes,sha256,width,height`, m.AttachmentID, version).Scan(&j.Stage, &j.Original, &j.MIME, &j.Size, &j.SHA, &j.Width, &j.Height)
if err != nil {
return j, false, err
}
return j, true, tx.Commit(ctx)
}
// finish publishes metadata only for the current, unexpired fencing token.
func (s *Service) finish(ctx context.Context, j claimed, variants []Variant, code string, permanent bool) (bool, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(context.Background())
var max int
err = tx.QueryRow(ctx, `SELECT max_attempts FROM attachment_jobs WHERE id=$1 AND fence=$2 AND state='processing' AND lease_until>clock_timestamp() AND pipeline_version=$3 FOR UPDATE`, j.JobID, j.Fence, j.PipelineVersion).Scan(&max)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
lastError := code
state := "ready"
var failure *string
available := time.Now()
if code != "" {
state = "queued"
if permanent || j.Attempt >= max {
state = "failed"
if !permanent {
code = "retry_exhausted"
}
failure = &code
}
delay := time.Duration(1<<min(j.Attempt, 5)) * time.Second
available = available.Add(delay + time.Duration(rand.IntN(500))*time.Millisecond)
}
raw := []byte("[]")
if state == "ready" {
raw, err = json.Marshal(variants)
if err != nil {
return false, err
}
}
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state=$2,lease_until=NULL,available_at=$3,last_error=NULLIF($4,''),updated_at=clock_timestamp() WHERE id=$1`, j.JobID, state, available, lastError); err != nil {
return false, err
}
tag, updateErr := tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,variants=$4,updated_at=clock_timestamp() WHERE id=$1 AND pipeline_version=$5 AND status='processing'`, j.AttachmentID, state, failure, raw, j.PipelineVersion)
if updateErr != nil {
return false, updateErr
}
if tag.RowsAffected() != 1 {
return false, fmt.Errorf("attachment version/state changed")
}
if state == "queued" {
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=$2 WHERE job_id=$1`, j.JobID, available); err != nil {
return false, err
}
}
return true, tx.Commit(ctx)
}
func (s *Service) render(ctx context.Context, j claimed) ([]Variant, string, bool) {
ctx, span := observability.Start(ctx, "s3 download and image render", trace.SpanKindInternal)
defer span.End()
if os.Getenv("PIPELINE_FAILPOINT") == "transient" {
return nil, "storage_unavailable", false
}
dir, err := os.MkdirTemp("", "pipeline-*")
if err != nil {
return nil, "processing_failed", false
}
defer os.RemoveAll(dir)
source := filepath.Join(dir, "source")
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, j.Stage, minio.GetObjectOptions{})
if err != nil {
return nil, "storage_unavailable", false
}
defer obj.Close()
f, err := os.Create(source)
if err != nil {
return nil, "processing_failed", false
}
n, err := io.Copy(f, io.LimitReader(&contextReader{ctx: ctx, r: obj}, MaxBytes+1))
f.Close()
if err != nil {
if IsMissing(err) {
return nil, "original_missing", true
}
return nil, "storage_unavailable", false
}
if n != j.Size {
return nil, "invalid_image", true
}
exe, err := os.Executable()
if err != nil {
return nil, "processing_failed", false
}
cmd := exec.CommandContext(ctx, exe, "render", source, dir, j.SHA)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process == nil {
return nil
}
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
cmd.WaitDelay = time.Second
cmd.Env = append(os.Environ(), "GOMEMLIMIT=384MiB")
if err = cmd.Run(); err != nil {
if ctx.Err() != nil {
return nil, "processing_timeout", false
}
if cmd.ProcessState != nil && cmd.ProcessState.ExitCode() == 2 {
return nil, "invalid_image", true
}
return nil, "processing_failed", false
}
raw, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
if err != nil {
return nil, "processing_failed", false
}
var variants []Variant
if json.Unmarshal(raw, &variants) != nil {
return nil, "processing_failed", false
}
f, err = os.Open(source)
if err != nil {
return nil, "processing_failed", false
}
err = s.put(ctx, j.Original, f, j.Size, j.MIME)
f.Close()
if err != nil {
return nil, "storage_unavailable", false
}
for _, v := range variants {
f, err = os.Open(filepath.Join(dir, v.Name))
if err != nil {
return nil, "processing_failed", false
}
err = s.put(ctx, effectKey(j.AttachmentID, j.PipelineVersion, v.Name), f, v.Size, v.ContentType)
f.Close()
if err != nil {
return nil, "storage_unavailable", false
}
}
if os.Getenv("PIPELINE_FAILPOINT") == "after_objects" {
log.Print("FAILPOINT after_objects reached")
os.Exit(86)
}
return variants, "", false
}
func (s *Service) RunWorker(ctx context.Context, r *redis.Client) error {
if err := r.XGroupCreateMkStream(ctx, Stream, Group, "0").Err(); err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
return err
}
consumer := uuid.NewString()
queue := make(chan redis.XMessage, s.Options.Prefetch)
pixels := semaphore.NewWeighted(int64(s.Options.PixelBudget))
var wg sync.WaitGroup
for i := 0; i < s.Options.Concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for msg := range queue {
var m JobMessage
decoder := json.NewDecoder(strings.NewReader(fmt.Sprint(msg.Values["job"])))
decoder.DisallowUnknownFields()
err := decoder.Decode(&m)
if err != nil || m.SchemaVersion != 1 || m.Type != "attachment.process.v1" || m.Attempt < 1 || m.PipelineVersion < 1 || m.CreatedAt.IsZero() || uuid.Validate(m.JobID) != nil || uuid.Validate(m.AttachmentID) != nil {
log.Print("invalid stream envelope ignored")
ack(ctx, r, msg.ID)
continue
}
s.processMessage(ctx, r, msg, m, pixels)
}
}()
}
lastCleanup := time.Now()
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
defer func() { close(queue); wg.Wait() }()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
}
op, cancel := context.WithTimeout(ctx, 5*time.Second)
if err := s.recover(op); err != nil {
log.Print("lease recovery will retry")
}
if os.Getenv("PIPELINE_PAUSE_PUBLISH") != "1" {
if err := s.Publish(op, r); err != nil {
log.Print("outbox publish will retry")
}
}
cancel()
// Claim PEL entries left by a dead consumer; PG leases remain the effect authority.
op, cancel = context.WithTimeout(ctx, 2*time.Second)
pending, _, _ := r.XAutoClaim(op, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: s.Options.Lease, Start: "0-0", Count: int64(s.Options.Prefetch)}).Result()
cancel()
for _, m := range pending {
select {
case queue <- m:
case <-ctx.Done():
return nil
}
}
// Never fetch beyond bounded prefetch capacity; no unbounded in-memory backlog.
room := cap(queue) - len(queue)
if room > 0 {
op, cancel = context.WithTimeout(ctx, time.Second)
streams, e := r.XReadGroup(op, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: int64(room), Block: 100 * time.Millisecond}).Result()
cancel()
if e == nil {
for _, stream := range streams {
for _, m := range stream.Messages {
select {
case queue <- m:
case <-ctx.Done():
return nil
}
}
}
}
}
if time.Since(lastCleanup) >= 5*time.Second {
lastCleanup = time.Now()
op, cancel = context.WithTimeout(ctx, 5*time.Second)
s.cleanStages(op)
cancel()
}
}
}
func ack(ctx context.Context, r *redis.Client, id string) {
if r.XAck(ctx, Stream, Group, id).Err() == nil {
r.XDel(ctx, Stream, id)
}
}
// Replay is an explicit operator action, serialized with admission and job claims.
// It preserves job/effect identity and refuses already successful work.
func (s *Service) Replay(ctx context.Context, id, operator, reason string) error {
if uuid.Validate(id) != nil || len(operator) < 1 || len(operator) > 100 || len(reason) < 1 || len(reason) > 300 {
return fmt.Errorf("job UUID, operator and reason are required")
}
tx, err := s.Pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(578903551)`); err != nil {
return err
}
var pending int
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')`).Scan(&pending); err != nil {
return err
}
if pending >= s.Options.MaxOutstanding {
return fmt.Errorf("admission limit reached")
}
var att, state, previous string
err = tx.QueryRow(ctx, `SELECT attachment_id::text,state,coalesce(last_error,'processing_failed') FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id).Scan(&att, &state, &previous)
if err != nil {
return err
}
if state != "failed" {
return fmt.Errorf("only failed jobs may be replayed")
}
var stage *string
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id=$1 FOR UPDATE`, att).Scan(&stage); err != nil {
return err
}
if stage == nil {
return fmt.Errorf("staging retention expired")
}
if _, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, *stage, minio.StatObjectOptions{}); err != nil {
return fmt.Errorf("staging unavailable")
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(job_id,operator,reason,previous_error) VALUES($1,$2,$3,$4)`, id, operator, reason, previous); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='queued',attempts=0,fence=fence+1,last_error=NULL,available_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, att); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=clock_timestamp() WHERE job_id=$1`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
// Keep failed stages for seven days for explicit replay; ready stages are garbage.
func (s *Service) cleanStages(ctx context.Context) {
rows, err := s.Pool.Query(ctx, `SELECT id::text FROM attachments WHERE (status='ready' AND staging_key IS NOT NULL) OR (status='failed' AND updated_at<clock_timestamp()-interval '7 days' AND storage_cleaned_at IS NULL) LIMIT 100`)
if err != nil {
return
}
ids := []string{}
for rows.Next() {
var id string
if rows.Scan(&id) == nil {
ids = append(ids, id)
}
}
rows.Close()
for _, id := range ids {
tx, e := s.Pool.Begin(ctx)
if e != nil {
return
}
var stage *string
var state, original string
var version int
e = tx.QueryRow(ctx, `SELECT staging_key,status,object_key,pipeline_version FROM attachments WHERE id=$1 AND ((status='ready' AND staging_key IS NOT NULL) OR (status='failed' AND updated_at<clock_timestamp()-interval '7 days' AND storage_cleaned_at IS NULL)) FOR UPDATE`, id).Scan(&stage, &state, &original, &version)
if e == nil && state == "failed" {
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
key := effectKey(id, version, name)
if name == "original" {
key = original
}
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{})
if e != nil {
break
}
}
}
if e == nil && stage != nil {
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, *stage, minio.RemoveObjectOptions{})
}
if e == nil {
if state == "failed" {
_, e = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL,variants='[]',storage_cleaned_at=clock_timestamp() WHERE id=$1`, id)
} else {
_, e = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1`, id)
}
}
if e == nil {
tx.Commit(ctx)
} else {
tx.Rollback(ctx)
}
}
// Unconfirmed stages (PUT succeeded, DB did not COMMIT) have a 90s grace and upload lock.
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) {
if obj.Err != nil {
return
}
if time.Since(obj.LastModified) < MinimumGrace {
continue
}
tx, e := s.Pool.Begin(ctx)
if e != nil {
return
}
var locked, exists bool
e = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, obj.Key).Scan(&locked)
if e == nil && locked {
e = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE staging_key=$1)`, obj.Key).Scan(&exists)
if e == nil && !exists {
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, obj.Key, minio.RemoveObjectOptions{})
}
}
tx.Rollback(ctx)
}
}
// RunPublisher drains durable DB intentions independently of worker availability.
func (s *Service) RunPublisher(ctx context.Context, r *redis.Client) {
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
if os.Getenv("PIPELINE_PAUSE_PUBLISH") == "1" {
continue
}
op, cancel := context.WithTimeout(ctx, 5*time.Second)
if err := s.Publish(op, r); err != nil {
log.Print("outbox publisher will retry")
}
cancel()
}
}
func (s *Service) processMessage(ctx context.Context, r *redis.Client, msg redis.XMessage, m JobMessage, pixels *semaphore.Weighted) {
ctx = observability.Extract(ctx, m.Traceparent, m.Tracestate)
ctx, span := observability.Start(ctx, "attachments process", trace.SpanKindConsumer)
defer span.End()
span.SetAttributes(attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.Int("job.attempt", m.Attempt))
start := time.Now()
observability.JobStart()
outcome := "claim_error"
defer func() {
observability.JobEnd(ctx, start, m.CreatedAt, outcome)
observability.Log(ctx, "job.completed", map[string]any{"job_type": m.Type, "attempt": m.Attempt, "outcome": outcome})
}()
op, cancel := context.WithTimeout(ctx, 5*time.Second)
j, ok, err := s.claim(op, m)
cancel()
if err != nil {
observability.Result(span, err)
return
}
if !ok {
outcome = "duplicate"
ack(ctx, r, msg.ID)
return
}
op, cancel = context.WithTimeout(ctx, s.Options.Timeout)
var variants []Variant
code := "processing_timeout"
permanent := false
if err = pixels.Acquire(op, int64(j.Width)*int64(j.Height)); err == nil {
variants, code, permanent = s.render(op, j)
pixels.Release(int64(j.Width) * int64(j.Height))
}
cancel()
finishCtx, finishCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
durable, e := s.finish(finishCtx, j, variants, code, permanent)
finishCancel()
if e != nil {
observability.Result(span, e)
outcome = "commit_error"
return
}
outcome = code
if code == "" {
outcome = "ready"
} else {
observability.Result(span, fmt.Errorf("processing failed"))
}
span.SetAttributes(attribute.String("job.outcome", outcome))
if durable {
if os.Getenv("PIPELINE_FAILPOINT") == "after_commit" && code == "" {
os.Exit(87)
}
ack(ctx, r, msg.ID)
}
}
@@ -0,0 +1,99 @@
package attachment
import (
"context"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"os"
"testing"
"time"
)
// The HTTP/S3 fault suite supplies real processing; this test isolates the DB fence.
func TestFenceIntegration(t *testing.T) {
if os.Getenv("INTEGRATION_TESTS") != "1" {
t.Skip("run make test-integration")
}
cfg, e := config.Load()
if e != nil {
t.Fatal(e)
}
pc, e := pgxpool.ParseConfig("sslmode=disable")
if e != nil {
t.Fatal(e)
}
pc.ConnConfig.Host = cfg.PostgresHost
pc.ConnConfig.Port = cfg.PostgresPort
pc.ConnConfig.User = cfg.PostgresUser
pc.ConnConfig.Password = cfg.PostgresPassword
pc.ConnConfig.Database = cfg.PostgresDatabase
pool, e := pgxpool.NewWithConfig(context.Background(), pc)
if e != nil {
t.Fatal(e)
}
defer pool.Close()
ctx := context.Background()
user, chat, att, id := uuid.NewString(), uuid.NewString(), uuid.NewString(), uuid.NewString()
defer func() {
pool.Exec(ctx, `DELETE FROM attachment_outbox WHERE job_id=$1`, id)
pool.Exec(ctx, `DELETE FROM attachment_jobs WHERE id=$1`, id)
pool.Exec(ctx, `DELETE FROM attachments WHERE id=$1`, att)
pool.Exec(ctx, `DELETE FROM chat_members WHERE chat_id=$1`, chat)
pool.Exec(ctx, `DELETE FROM chats WHERE id=$1`, chat)
pool.Exec(ctx, `DELETE FROM users WHERE id=$1`, user)
}()
if _, e = pool.Exec(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,'Fence','test')`, user, "fence_"+user[:8]); e != nil {
t.Fatal(e)
}
if _, e = pool.Exec(ctx, `INSERT INTO chats(id,title) VALUES($1,'Fence')`, chat); e != nil {
t.Fatal(e)
}
if _, e = pool.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id,ordinal) VALUES($1,$2,0)`, chat, user); e != nil {
t.Fatal(e)
}
if _, e = pool.Exec(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height,status,staging_key) VALUES($1,$2,$3,'x.png',$4,'image/png',1,repeat('a',64),1,1,'queued',$5)`, att, chat, user, effectKey(att, 1, "original"), "staging/"+att); e != nil {
t.Fatal(e)
}
if _, e = pool.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,state,max_attempts) VALUES($1,$2,'queued',5)`, id, att); e != nil {
t.Fatal(e)
}
options, _ := LoadOptions()
s := NewAsync(pool, nil, options)
message := JobMessage{SchemaVersion: 1, JobID: id, AttachmentID: att, PipelineVersion: 1, Attempt: 1, CreatedAt: time.Now()}
first, ok, e := s.claim(ctx, message)
if e != nil || !ok {
t.Fatalf("claim: %v %v", ok, e)
}
if _, ok, e = s.claim(ctx, message); e != nil || ok {
t.Fatalf("duplicate claimed active lease: %v %v", ok, e)
}
if _, e = pool.Exec(ctx, `UPDATE attachment_jobs SET lease_until=clock_timestamp()-interval '1 second' WHERE id=$1`, id); e != nil {
t.Fatal(e)
}
if durable, e := s.finish(ctx, first, []Variant{}, "", false); e != nil || durable {
t.Fatalf("expired fence published: %v %v", durable, e)
}
if e = s.recover(ctx); e != nil {
t.Fatal(e)
}
message.Attempt = 2
second, ok, e := s.claim(ctx, message)
if e != nil || !ok || second.Fence <= first.Fence {
t.Fatalf("reclaim: %+v %v %v", second, ok, e)
}
if durable, e := s.finish(ctx, first, []Variant{}, "", false); e != nil || durable {
t.Fatalf("stale fence published: %v %v", durable, e)
}
if _, e = pool.Exec(ctx, `UPDATE attachments SET pipeline_version=2 WHERE id=$1`, att); e != nil {
t.Fatal(e)
}
if durable, e := s.finish(ctx, second, []Variant{}, "", false); e == nil || durable {
t.Fatal("stale pipeline version accepted")
}
var state string
if e = pool.QueryRow(ctx, `SELECT state FROM attachment_jobs WHERE id=$1`, id).Scan(&state); e != nil || state != "processing" {
t.Fatalf("partial result committed: %s %v", state, e)
}
}