Перенеси реализацию мессенджера из ЛР 6
Application / e2e (pull_request) Blocked by required conditions
Application / unit (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions

Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
This commit is contained in:
2026-11-30 10:54:41 +03:00
parent 20afc2c790
commit 8054913ef9
204 changed files with 23709 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
package attachment
import (
"time"
"github.com/google/uuid"
)
type FileStatus string
const (
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, UpdatedAt time.Time
ErrorCode *string
Variants []Variant
}
type UploadInput struct {
ChatID uuid.UUID
Filename string
MIMEType string
SizeBytes int64
}
type Variant struct {
Name string
ObjectKey string
MIMEType string
SizeBytes int64
Width, Height int
Hash []byte
}
+25
View File
@@ -0,0 +1,25 @@
package attachment
import (
"context"
"errors"
"io"
"time"
)
var ErrObjectMissing = errors.New("object missing")
type Object struct {
Key string
Size int64
Modified time.Time
}
type Blobs interface {
Put(ctx context.Context, key string, body io.Reader, size int64, mimeType string) error
Open(ctx context.Context, key string) (io.ReadCloser, error)
Stat(ctx context.Context, key string) (Object, error)
Copy(ctx context.Context, sourceKey, destinationKey string) error
Delete(ctx context.Context, key string) error
List(ctx context.Context, prefix, after string, limit int) ([]Object, error)
}
+168
View File
@@ -0,0 +1,168 @@
package attachment
import (
"encoding/hex"
"io"
"log/slog"
"mime"
"net/http"
"strconv"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Handler struct{ s *Service }
func NewHandler(s *Service) *Handler { return &Handler{s} }
func (h *Handler) Register(protected, binaryProtected gin.IRouter) {
binaryProtected.POST("/chats/:chat_id/attachments", httpx.WithUser(h.upload))
protected.GET("/attachments/:attachment_id", httpx.WithUser(h.metadata))
binaryProtected.GET("/attachments/:attachment_id/content", httpx.WithUser(h.content))
}
type Response struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []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"`
}
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(),
OwnerID: a.OwnerID.String(),
Filename: a.Filename,
ContentType: a.MIMEType,
SizeBytes: a.SizeBytes,
SHA256: hex.EncodeToString(a.FileHash),
Status: string(a.Status),
Variants: variants,
ErrorCode: a.ErrorCode,
CreatedAt: httpx.Timestamp(a.CreatedAt),
UpdatedAt: httpx.Timestamp(a.UpdatedAt),
}
}
func (h *Handler) upload(c *gin.Context, actor uuid.UUID) {
id, err := ident.Parse(c.Param("chat_id"))
if err != nil {
httpx.Error(c, apperr.Invalid("chat_id must be a UUID"))
return
}
names := c.Request.URL.Query()["filename"]
if len(names) != 1 {
httpx.Error(c, apperr.Invalid("one filename is required"))
return
}
if err := ValidateFilename(names[0]); err != nil {
httpx.Error(c, err)
return
}
media, params, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || len(params) > 0 {
httpx.Error(c, apperr.UnsupportedMedia("Content-Type must be image/png or image/jpeg"))
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.s.config.MaxBytes)
input := UploadInput{
ChatID: id,
Filename: names[0],
MIMEType: media,
SizeBytes: c.Request.ContentLength,
}
a, err := h.s.Upload(c.Request.Context(), actor, input, c.Request.Body)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusAccepted, toResponse(a))
}
func attachmentID(c *gin.Context) (uuid.UUID, error) {
id, err := ident.Parse(c.Param("attachment_id"))
if err != nil {
return uuid.Nil, apperr.Invalid("attachment_id must be a UUID")
}
return id, nil
}
func (h *Handler) metadata(c *gin.Context, actor uuid.UUID) {
id, err := attachmentID(c)
if err != nil {
httpx.Error(c, err)
return
}
a, err := h.s.Get(c.Request.Context(), actor, id)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, toResponse(a))
}
func (h *Handler) content(c *gin.Context, actor uuid.UUID) {
id, err := attachmentID(c)
if err != nil {
httpx.Error(c, err)
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, variant)
if err != nil {
httpx.Error(c, err)
return
}
defer func() {
if err := r.Close(); err != nil {
slog.Warn("download reader close failed", "request_id", httpx.RequestID(c), "error", err)
}
}()
c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Content-Type", a.MIMEType)
c.Header("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
c.Status(http.StatusOK)
if _, err := io.CopyN(c.Writer, r, a.SizeBytes); err != nil {
slog.Error("download interrupted", "request_id", httpx.RequestID(c), "error", err)
}
}
+23
View File
@@ -0,0 +1,23 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"github.com/jackc/pgx/v5"
)
// LockHash serializes CAS publication and collection until the transaction ends.
// A collision in the signed first eight digest bytes only adds serialization.
func LockHash(ctx context.Context, tx pgx.Tx, hash []byte) error {
if len(hash) != sha256.Size {
return errors.New("attachment: lock requires a SHA256 hash")
}
_, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, int64(binary.BigEndian.Uint64(hash[:8])))
return err
}
func BlobKey(hash []byte) string { return "blobs/" + hex.EncodeToString(hash) }
+610
View File
@@ -0,0 +1,610 @@
package attachment
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const (
reconcilePageSize = 500
reconcileOperationTimeout = 30 * time.Second
)
type Finding struct {
Kind string `json:"kind"`
Key string `json:"key"`
Action string `json:"action"`
Applied bool `json:"applied"`
}
// SQLQueries counts SQL statements, including transaction control and locks.
// S3Calls counts calls to the Blobs port, including each list page and deep GET.
type Stats struct {
ElapsedMS int64 `json:"elapsed_ms"`
SQLQueries int64 `json:"sql_queries"`
S3Calls int64 `json:"s3_calls"`
ScannedFiles int64 `json:"scanned_files"`
ScannedObjects int64 `json:"scanned_objects"`
Findings int64 `json:"findings"`
Repaired int64 `json:"repaired"`
}
type Reconciler struct {
db *pgxpool.Pool
blobs Blobs
grace time.Duration
retention time.Duration
}
type ReconcileOptions struct {
Apply bool
Deep bool
}
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")
}
if grace == 0 {
grace = time.Hour
}
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, retention: retention}, nil
}
// Run streams findings and keeps at most one page of metadata in memory.
// Dry runs only read storage. Each apply candidate is checked again under the
// publisher's transaction lock; no scan snapshot authorizes a later mutation.
func (r *Reconciler) Run(ctx context.Context, options ReconcileOptions, emit func(Finding)) (stats Stats, err error) {
started := time.Now()
defer func() { stats.ElapsedMS = time.Since(started).Milliseconds() }()
run := reconcileRun{
r: r,
ctx: ctx,
apply: options.Apply,
deep: options.Deep,
emit: emit,
stats: &stats,
cutoff: started.Add(-r.grace),
}
for _, prefix := range []string{"staging/", "variants/", "blobs/"} {
if err = run.objects(prefix); err != nil {
return stats, err
}
}
err = run.files()
return stats, err
}
type reconcileRun struct {
r *Reconciler
ctx context.Context
apply, deep bool
emit func(Finding)
stats *Stats
cutoff time.Time
}
func (s *reconcileRun) note(f *Finding) {
if f == nil {
return
}
s.stats.Findings++
if f.Applied {
s.stats.Repaired++
}
if s.emit != nil {
s.emit(*f)
}
}
func (s *reconcileRun) old(modified time.Time) bool {
// Unknown timestamps must never authorize collection.
return !modified.IsZero() && modified.Before(s.cutoff)
}
func (s *reconcileRun) objects(prefix string) error {
after := ""
for {
if err := s.ctx.Err(); err != nil {
return err
}
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
page, err := s.r.blobs.List(opCtx, prefix, after, reconcilePageSize)
cancel()
if err != nil {
return fmt.Errorf("reconcile list %s: %w", prefix, err)
}
if len(page) == 0 {
return nil
}
var known map[string]bool
if prefix == "blobs/" {
known, err = s.knownFiles(page)
} else {
known, err = s.knownJobObjects(s.ctx, s.r.db, prefix, page)
}
if err != nil {
return err
}
for _, obj := range page {
if obj.Key <= after {
return errors.New("reconcile: object page did not advance")
}
after = obj.Key
s.stats.ScannedObjects++
if !s.old(obj.Modified) || known[obj.Key] {
continue
}
var finding *Finding
if prefix == "blobs/" {
finding, err = s.orphan(obj)
} else {
finding, err = s.jobObject(prefix, obj)
}
if err != nil {
return fmt.Errorf("reconcile %s: %w", obj.Key, err)
}
s.note(finding)
}
}
}
func (s *reconcileRun) stat(key string) (Object, error) {
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
return s.r.blobs.Stat(opCtx, key)
}
func (s *reconcileRun) delete(key string) error {
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
err := s.r.blobs.Delete(opCtx, key)
if errors.Is(err, ErrObjectMissing) {
return nil
}
return err
}
func parseJobObject(prefix, key string) (uuid.UUID, int32, bool) {
parts := strings.Split(strings.TrimPrefix(key, prefix), "/")
id, err := uuid.Parse(parts[0])
if prefix == "staging/" {
return id, 0, err == nil
}
if len(parts) != 4 || err != nil {
return uuid.Nil, 0, false
}
version, err := strconv.ParseInt(parts[1], 10, 32)
return id, int32(version), err == nil && version > 0
}
type jobObjectReader interface {
Query(context.Context, string, ...any) (pgx.Rows, error)
}
// The same lookup filters an S3 page and rechecks a single candidate inside its deletion transaction.
func (s *reconcileRun) knownJobObjects(ctx context.Context, db jobObjectReader, prefix string, page []Object) (map[string]bool, error) {
var ids []uuid.UUID
var keys []string
var versions []int32
for _, obj := range page {
if !s.old(obj.Modified) {
continue
}
id, version, ok := parseJobObject(prefix, obj.Key)
if !ok {
continue
}
ids = append(ids, id)
keys = append(keys, obj.Key)
if prefix == "variants/" {
versions = append(versions, version)
}
}
if len(keys) == 0 {
return nil, nil
}
var query string
var args []any
if prefix == "variants/" {
query = `SELECT o.key FROM unnest($1::uuid[], $2::text[], $3::integer[]) AS o(id,key,version)
WHERE EXISTS (SELECT 1 FROM attachment_variants v
WHERE v.attachment_id=o.id AND v.pipeline_version=o.version AND v.object_key=o.key)
OR EXISTS (SELECT 1 FROM attachment_jobs j
WHERE j.attachment_id=o.id AND j.pipeline_version=o.version AND j.state IN ('queued','processing'))`
args = []any{ids, keys, versions}
} else {
query = `SELECT o.key FROM unnest($1::uuid[], $2::text[]) AS o(id,key)
WHERE EXISTS (SELECT 1 FROM attachment_jobs j WHERE j.attachment_id=o.id AND j.source_key=o.key AND
(j.state IN ('queued','processing') OR (j.state='failed' AND j.updated_at >= now()-$3::bigint*interval '1 second')))`
args = []any{ids, keys, int64(s.r.retention / time.Second)}
}
s.stats.SQLQueries++
rows, err := db.Query(ctx, query, args...)
if err != nil {
return nil, err
}
known := make(map[string]bool)
var key string
_, err = pgx.ForEachRow(rows, []any{&key}, func() error {
known[key] = true
return nil
})
return known, err
}
func (s *reconcileRun) jobObject(prefix string, obj Object) (*Finding, error) {
id, _, valid := parseJobObject(prefix, obj.Key)
kind := "stale_staging"
if prefix == "variants/" {
if !valid {
return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil
}
kind = "orphan_variant"
}
finding := &Finding{Kind: kind, Key: obj.Key, Action: "delete_object"}
if !s.apply {
return finding, 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 valid {
s.stats.SQLQueries++
if _, err := tx.Exec(opCtx, `SELECT id FROM attachments WHERE id=$1 FOR UPDATE`, id); err != nil {
return nil, err
}
}
known, err := s.knownJobObjects(opCtx, tx, prefix, []Object{obj})
if err != nil {
return nil, err
}
if known[obj.Key] {
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) {
hashes := make([][]byte, 0, len(page))
for _, obj := range page {
if !s.old(obj.Modified) {
continue
}
hash, err := hex.DecodeString(obj.Key[len("blobs/"):])
if err == nil && len(hash) == sha256.Size && BlobKey(hash) == obj.Key {
hashes = append(hashes, hash)
}
}
known := make(map[string]bool, len(hashes))
if len(hashes) == 0 {
return known, nil
}
s.stats.SQLQueries++
rows, err := s.r.db.Query(s.ctx, `
SELECT hash FROM files WHERE hash = ANY($1::bytea[])`, hashes)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var hash []byte
if err := rows.Scan(&hash); err != nil {
return nil, err
}
known[BlobKey(hash)] = true
}
return known, rows.Err()
}
func (s *reconcileRun) orphan(obj Object) (*Finding, error) {
hash, err := hex.DecodeString(obj.Key[len("blobs/"):])
if err != nil || len(hash) != sha256.Size || BlobKey(hash) != obj.Key {
return &Finding{Kind: "invalid_blob_key", Key: obj.Key, Action: "report"}, nil
}
f := &Finding{Kind: "orphan_blob", Key: obj.Key, Action: "delete_object"}
if !s.apply {
return f, nil
}
return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
op := *s
op.ctx = opCtx
var exists bool
s.stats.SQLQueries++
if err := tx.QueryRow(opCtx, `
SELECT EXISTS (SELECT 1 FROM files WHERE hash = $1)`, hash).Scan(&exists); err != nil {
return nil, err
}
if exists {
return nil, nil
}
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
}
f.Applied = true
return f, nil
})
}
// locked also covers hashes without a files row: a publisher and an orphan
// collector therefore cannot pass each other's existence check concurrently.
func (s *reconcileRun) locked(hash []byte, fn func(context.Context, pgx.Tx) (*Finding, error)) (*Finding, error) {
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
s.stats.SQLQueries++
tx, err := s.r.db.Begin(opCtx)
if err != nil {
return nil, err
}
committed := false
defer func() {
if !committed {
cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s.stats.SQLQueries++
_ = tx.Rollback(cleanup)
}
}()
// Pool defaults cover ordinary requests; object I/O can outlive those
// idle limits. The operation deadline bounds the entire locked candidate.
s.stats.SQLQueries++
if _, err = tx.Exec(opCtx, `SET LOCAL idle_in_transaction_session_timeout='35s'`); err != nil {
return nil, err
}
s.stats.SQLQueries++
if err = LockHash(opCtx, tx, hash); err != nil {
return nil, err
}
f, err := fn(opCtx, tx)
if err != nil {
return nil, err
}
s.stats.SQLQueries++
err = tx.Commit(opCtx)
committed = true // pgx closes the transaction even when COMMIT fails.
if err != nil {
return nil, err
}
return f, nil
}
type reconcileFile struct {
hash []byte
size int64
status FileStatus
created time.Time
referenced bool
}
func (s *reconcileRun) files() error {
after := []byte{}
for {
if err := s.ctx.Err(); err != nil {
return err
}
s.stats.SQLQueries++
rows, err := s.r.db.Query(s.ctx, `
SELECT f.hash, f.size_bytes, f.status, f.created_at,
EXISTS (SELECT 1 FROM attachments a WHERE a.file_hash = f.hash)
FROM files f
WHERE f.hash > $1
ORDER BY f.hash
LIMIT $2`, after, reconcilePageSize)
if err != nil {
return err
}
page := make([]reconcileFile, 0, reconcilePageSize)
for rows.Next() {
var f reconcileFile
if err = rows.Scan(&f.hash, &f.size, &f.status, &f.created, &f.referenced); err != nil {
rows.Close()
return err
}
page = append(page, f)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
if len(page) == 0 {
return nil
}
// Close the page's SQL rows before acquiring a transaction connection.
for _, f := range page {
after = f.hash
s.stats.ScannedFiles++
if !s.candidate(f) {
continue
}
finding, err := s.inspect(f)
if err == nil && s.apply && finding != nil && finding.Action != "report" {
finding, err = s.repairFile(f.hash)
}
if err != nil {
return fmt.Errorf("reconcile file %s: %w", BlobKey(f.hash), err)
}
s.note(finding)
}
}
}
func (s *reconcileRun) repairFile(hash []byte) (*Finding, error) {
return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
op := *s
op.ctx = opCtx
var current reconcileFile
s.stats.SQLQueries++
err := tx.QueryRow(opCtx, `
SELECT f.hash, f.size_bytes, f.status, f.created_at,
EXISTS (SELECT 1 FROM attachments a WHERE a.file_hash = f.hash)
FROM files f
WHERE f.hash = $1
FOR UPDATE OF f`, hash).
Scan(&current.hash, &current.size, &current.status, &current.created, &current.referenced)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
if !op.candidate(current) {
return nil, nil
}
finding, err := op.inspect(current)
if err != nil || finding == nil {
return finding, err
}
switch finding.Action {
case "delete_file":
// Delete bytes first. A failed SQL commit leaves an unreferenced
// missing row that the next pass can safely finish collecting.
if err := op.delete(finding.Key); err != nil {
return nil, err
}
s.stats.SQLQueries++
_, err = tx.Exec(opCtx, `DELETE FROM files WHERE hash = $1`, hash)
case "mark_failed":
s.stats.SQLQueries++
_, err = tx.Exec(opCtx, `UPDATE files SET status = $2 WHERE hash = $1`, hash, FileFailed)
default:
return finding, nil
}
if err != nil {
return nil, err
}
finding.Applied = true
return finding, nil
})
}
func (s *reconcileRun) candidate(f reconcileFile) bool {
if !s.old(f.created) {
return false
}
if !f.referenced {
return f.status == FilePending || f.status == FileReady
}
return f.status == FileReady || f.status == FileFailed
}
func (s *reconcileRun) inspect(f reconcileFile) (*Finding, error) {
key := BlobKey(f.hash)
if !f.referenced {
// A publication that rolled back can leave fresh bytes behind an old
// pending row. Both the metadata and the current object must be old.
obj, err := s.stat(key)
if err != nil && !errors.Is(err, ErrObjectMissing) {
return nil, err
}
if err == nil && !s.old(obj.Modified) {
return nil, nil
}
return &Finding{Kind: "unreferenced_" + string(f.status), Key: key, Action: "delete_file"}, nil
}
obj, err := s.stat(key)
if errors.Is(err, ErrObjectMissing) {
if f.status == FileFailed {
return nil, nil
}
return &Finding{Kind: "missing_blob", Key: key, Action: "mark_failed"}, nil
}
if err != nil {
return nil, err
}
if obj.Size != f.size {
return &Finding{Kind: "size_mismatch", Key: key, Action: "report"}, nil
}
if s.deep {
match, err := s.verify(f)
if err != nil {
return nil, err
}
if !match {
return &Finding{Kind: "hash_mismatch", Key: key, Action: "report"}, nil
}
}
// A failed file stays failed even when the key reappears. Recovery requires
// an explicit publisher; a shallow HEAD cannot prove content integrity.
if f.status == FileFailed {
return &Finding{Kind: "failed_present", Key: key, Action: "report"}, nil
}
return nil, nil
}
func (s *reconcileRun) verify(f reconcileFile) (bool, error) {
if f.size < 0 || f.size == math.MaxInt64 {
return false, errors.New("reconcile: invalid file size")
}
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
body, err := s.r.blobs.Open(opCtx, BlobKey(f.hash))
if err != nil {
return false, err
}
hash := sha256.New()
n, readErr := io.Copy(hash, io.LimitReader(body, f.size+1))
closeErr := body.Close()
if readErr != nil {
return false, readErr
}
if closeErr != nil {
return false, closeErr
}
return n == f.size && bytes.Equal(hash.Sum(nil), f.hash), nil
}
+844
View File
@@ -0,0 +1,844 @@
package attachment_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/attachment"
"messenger/internal/testenv"
)
func TestReconcileBlobKey(t *testing.T) {
hash, _ := hex.DecodeString("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
if got := attachment.BlobKey(hash); got != "blobs/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
t.Fatalf("blob key: %q", got)
}
}
// Only object storage is doubled: SQL, transactions, FKs and advisory locks are real.
type reconcileBlobs struct {
mu sync.Mutex
objects map[string]attachment.Object
bodies map[string][]byte
statErr, deleteErr, openErr error
listed func(string)
stating func(string)
opening func(string) io.ReadCloser
writes, readBytes int
limits []int
}
func newReconcileBlobs() *reconcileBlobs {
return &reconcileBlobs{objects: make(map[string]attachment.Object), bodies: make(map[string][]byte)}
}
func (b *reconcileBlobs) add(key string, body []byte, modified time.Time) {
b.mu.Lock()
defer b.mu.Unlock()
b.objects[key] = attachment.Object{Key: key, Size: int64(len(body)), Modified: modified}
b.bodies[key] = bytes.Clone(body)
}
func (b *reconcileBlobs) has(key string) bool {
b.mu.Lock()
defer b.mu.Unlock()
_, ok := b.objects[key]
return ok
}
func (b *reconcileBlobs) Put(_ context.Context, key string, r io.Reader, size int64, _ string) error {
body, err := io.ReadAll(io.LimitReader(r, size+1))
if err != nil {
return err
}
if int64(len(body)) != size {
return io.ErrUnexpectedEOF
}
b.add(key, body, time.Now())
b.mu.Lock()
b.writes++
b.mu.Unlock()
return nil
}
func (b *reconcileBlobs) Copy(_ context.Context, source, dest string) error {
b.mu.Lock()
body, ok := b.bodies[source]
b.mu.Unlock()
if !ok {
return attachment.ErrObjectMissing
}
b.add(dest, body, time.Now())
b.mu.Lock()
b.writes++
b.mu.Unlock()
return nil
}
func (b *reconcileBlobs) Open(_ context.Context, key string) (io.ReadCloser, error) {
if b.openErr != nil {
return nil, b.openErr
}
if b.opening != nil {
return b.opening(key), nil
}
b.mu.Lock()
defer b.mu.Unlock()
body, ok := b.bodies[key]
if !ok {
return nil, attachment.ErrObjectMissing
}
return io.NopCloser(bytes.NewReader(body)), nil
}
func (b *reconcileBlobs) Stat(_ context.Context, key string) (attachment.Object, error) {
if b.stating != nil {
b.stating(key)
}
b.mu.Lock()
defer b.mu.Unlock()
if b.statErr != nil {
return attachment.Object{}, b.statErr
}
obj, ok := b.objects[key]
if !ok {
return attachment.Object{}, fmt.Errorf("head: %w", attachment.ErrObjectMissing)
}
return obj, nil
}
func (b *reconcileBlobs) Delete(_ context.Context, key string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.deleteErr != nil {
return b.deleteErr
}
delete(b.objects, key)
delete(b.bodies, key)
b.writes++
return nil
}
func (b *reconcileBlobs) List(_ context.Context, prefix, after string, limit int) ([]attachment.Object, error) {
b.mu.Lock()
b.limits = append(b.limits, limit)
if limit < 1 || limit > 500 {
b.mu.Unlock()
return nil, errors.New("unbounded page")
}
var page []attachment.Object
for key, obj := range b.objects {
if strings.HasPrefix(key, prefix) && key > after {
page = append(page, obj)
}
}
sort.Slice(page, func(i, j int) bool { return page[i].Key < page[j].Key })
if len(page) > limit {
page = page[:limit]
}
b.mu.Unlock()
if b.listed != nil {
b.listed(prefix)
}
return page, nil
}
type reconcileFixture struct {
t *testing.T
db *pgxpool.Pool
b *reconcileBlobs
user, chat, message uuid.UUID
}
func reconcileSetup(t *testing.T, db *testenv.DB) *reconcileFixture {
t.Helper()
db.Reset(t)
f := &reconcileFixture{t: t, db: db.Pool, b: newReconcileBlobs(), user: uuid.New(), chat: uuid.New(), message: uuid.New()}
f.exec(`INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,'reconcile','Reconcile','unused',now())`, f.user)
f.exec(`INSERT INTO chats(id,title,created_at) VALUES($1,'reconcile',now())`, f.chat)
f.exec(`INSERT INTO messages(chat_id,id,sender_id,text,created_at) VALUES($1,$2,$3,'preserve',now())`, f.chat, f.message, f.user)
return f
}
func (f *reconcileFixture) exec(sql string, args ...any) {
f.t.Helper()
if _, err := f.db.Exec(context.Background(), sql, args...); err != nil {
f.t.Fatal(err)
}
}
func (f *reconcileFixture) file(body, status string, age time.Duration, referenced, present bool) []byte {
f.t.Helper()
hash := sha256.Sum256([]byte(body))
f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png',$3,$4)`, hash[:], len(body), status, time.Now().Add(-age))
if referenced {
id := uuid.New()
f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'image.png',$4,now())`, id, f.chat, f.user, hash[:])
f.exec(`INSERT INTO message_attachments(chat_id,message_id,attachment_id,ordinal)
VALUES($1,$2,$3,(SELECT count(*) FROM message_attachments WHERE chat_id=$1 AND message_id=$2))`, f.chat, f.message, id)
}
if present {
f.b.add(attachment.BlobKey(hash[:]), []byte(body), time.Now().Add(-age))
}
return hash[:]
}
func (f *reconcileFixture) status(hash []byte) string {
f.t.Helper()
var s string
err := f.db.QueryRow(context.Background(), `SELECT status FROM files WHERE hash=$1`, hash).Scan(&s)
if errors.Is(err, pgx.ErrNoRows) {
return ""
}
if err != nil {
f.t.Fatal(err)
}
return s
}
func (f *reconcileFixture) run(apply, deep bool) (attachment.Stats, []attachment.Finding, error) {
f.t.Helper()
r, err := attachment.NewReconciler(f.db, f.b, 0)
if err != nil {
f.t.Fatal(err)
}
var found []attachment.Finding
options := attachment.ReconcileOptions{Apply: apply, Deep: deep}
stats, err := r.Run(context.Background(), options, func(v attachment.Finding) { found = append(found, v) })
return stats, found, err
}
func TestReconciler(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
t.Run("healthy apply does not block publication", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("healthy", "ready", 2*time.Hour, true, true)
tx, err := db.Pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err := attachment.LockHash(ctx, tx, hash); err != nil {
t.Fatal(err)
}
r, err := attachment.NewReconciler(f.db, f.b, time.Hour)
if err != nil {
t.Fatal(err)
}
scanCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
stats, err := r.Run(scanCtx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil)
if err != nil || stats.Findings != 0 || stats.Repaired != 0 {
t.Fatalf("healthy inspection waited for publication: %+v %v", stats, err)
}
})
t.Run("constructor validates and defaults grace", func(t *testing.T) {
f := reconcileSetup(t, db)
for _, grace := range []time.Duration{-time.Second, time.Minute} {
if _, err := attachment.NewReconciler(f.db, f.b, grace); err == nil {
t.Fatalf("accepted grace %v", grace)
}
}
if _, err := attachment.NewReconciler(nil, f.b, 0); err == nil {
t.Fatal("accepted nil DB")
}
if _, err := attachment.NewReconciler(f.db, nil, 0); err == nil {
t.Fatal("accepted nil blobs")
}
if _, err := attachment.NewReconciler(f.db, f.b, 2*time.Minute); err != nil {
t.Fatal(err)
}
fresh := f.file("half hour", "ready", 30*time.Minute, false, true)
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || f.status(fresh) != "ready" {
t.Fatalf("default grace: %+v %v", stats, err)
}
})
t.Run("dry run then apply then repeat preserves fresh referenced and message links", func(t *testing.T) {
f := reconcileSetup(t, db)
old := 2 * time.Hour
pending := f.file("pending", "pending", old, false, true)
unused := f.file("unused", "ready", old, false, true)
used := f.file("used", "ready", old, true, true)
fresh := f.file("fresh", "pending", time.Minute, false, true)
missing := f.file("missing", "ready", old, true, false)
f.b.add("staging/old", []byte("old"), time.Now().Add(-old))
f.b.add("staging/fresh", []byte("new"), time.Now())
orphan := sha256.Sum256([]byte("orphan"))
orphanKey := attachment.BlobKey(orphan[:])
f.b.add(orphanKey, []byte("orphan"), time.Now().Add(-old))
stats, findings, err := f.run(false, false)
if err != nil || stats.Repaired != 0 || stats.Findings != 5 || len(findings) != 5 {
t.Fatalf("dry: %+v %v %+v", stats, err, findings)
}
if f.b.writes != 0 || f.status(pending) != "pending" || f.status(missing) != "ready" {
t.Fatal("dry run mutated storage")
}
for _, finding := range findings {
if finding.Applied {
t.Fatal("dry finding marked applied")
}
}
stats, findings, err = f.run(true, false)
if err != nil || stats.Repaired != 5 {
t.Fatalf("apply: %+v %v %+v", stats, err, findings)
}
if f.status(pending) != "" || f.status(unused) != "" || f.status(missing) != "failed" {
t.Fatal("metadata repair incorrect")
}
if f.b.has(orphanKey) || f.b.has("staging/old") || !f.b.has("staging/fresh") || !f.b.has(attachment.BlobKey(used)) || !f.b.has(attachment.BlobKey(fresh)) {
t.Fatal("incorrect object collection")
}
var links int
if err := f.db.QueryRow(ctx, `SELECT count(*) FROM message_attachments`).Scan(&links); err != nil || links != 2 {
t.Fatalf("message links lost: %d %v", links, err)
}
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 0 {
t.Fatalf("repeat: %+v %v", stats, err)
}
})
t.Run("outage is not missing and failed delete keeps row", func(t *testing.T) {
f := reconcileSetup(t, db)
used := f.file("used", "ready", 2*time.Hour, true, true)
outage := errors.New("injected S3 outage")
f.b.statErr = outage
stats, _, err := f.run(true, false)
if !errors.Is(err, outage) || stats.Repaired != 0 || f.status(used) != "ready" {
t.Fatalf("outage: %+v %v", stats, err)
}
f.b.statErr = nil
unused := f.file("unused", "pending", 2*time.Hour, false, true)
f.b.deleteErr = outage
_, _, err = f.run(true, false)
if !errors.Is(err, outage) || f.status(unused) != "pending" {
t.Fatalf("delete failure: %v", err)
}
})
t.Run("deep reports corruption and never revives failed without verification", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, true)
f.b.add(attachment.BlobKey(hash), []byte("evil"), time.Now().Add(-2*time.Hour))
stats, found, err := f.run(true, true)
if err != nil || stats.Findings != 1 || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "hash_mismatch" || f.status(hash) != "ready" || !f.b.has(attachment.BlobKey(hash)) {
t.Fatalf("deep: %+v %v %+v", stats, err, found)
}
f.exec(`UPDATE files SET status='failed' WHERE hash=$1`, hash)
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 0 || f.status(hash) != "failed" {
t.Fatal("shallow revived failed file")
}
stats, _, err = f.run(true, true)
if err != nil || stats.Repaired != 0 || f.status(hash) != "failed" {
t.Fatal("corrupt file revived")
}
})
t.Run("wrong size reports only and fresh missing stays ready", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("sized", "ready", 2*time.Hour, true, true)
f.b.add(attachment.BlobKey(hash), []byte("longer body"), time.Now().Add(-2*time.Hour))
fresh := f.file("new missing", "ready", time.Minute, true, false)
stats, found, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || stats.Findings != 1 || found[0].Kind != "size_mismatch" || f.status(fresh) != "ready" {
t.Fatalf("size/fresh: %+v %v %+v", stats, err, found)
}
})
t.Run("orphan rechecks current object age", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := sha256.Sum256([]byte("orphan"))
key := attachment.BlobKey(hash[:])
f.b.add(key, []byte("orphan"), time.Now().Add(-2*time.Hour))
f.b.listed = func(prefix string) {
if prefix == "blobs/" {
f.b.add(key, []byte("republished"), time.Now())
}
}
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || !f.b.has(key) {
t.Fatalf("fresh replacement deleted: %+v %v", stats, err)
}
})
t.Run("row rechecks references after taking lock", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("race refs", "ready", 2*time.Hour, false, true)
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err = attachment.LockHash(ctx, tx, hash); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
r, _ := attachment.NewReconciler(f.db, f.b, 0)
_, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
done <- err
}()
waitReconcileLock(t, ctx, f.db)
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'race.png',$4,now())`, uuid.New(), f.chat, f.user, hash)
if err != nil {
t.Fatal(err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
if err = <-done; err != nil {
t.Fatal(err)
}
if f.status(hash) != "ready" || !f.b.has(attachment.BlobKey(hash)) {
t.Fatal("new reference collected")
}
})
t.Run("concurrent upload lock prevents orphan collection", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := sha256.Sum256([]byte("publishing"))
key := attachment.BlobKey(hash[:])
f.b.add(key, []byte("publishing"), time.Now().Add(-2*time.Hour))
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err = attachment.LockHash(ctx, tx, hash[:]); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
r, _ := attachment.NewReconciler(f.db, f.b, 0)
_, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
done <- err
}()
waitReconcileLock(t, ctx, f.db)
if _, err = tx.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES($1,10,'image/png','ready')`, hash[:]); err != nil {
t.Fatal(err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
if err = <-done; err != nil {
t.Fatal(err)
}
if !f.b.has(key) || f.status(hash[:]) != "ready" {
t.Fatal("published blob collected")
}
})
t.Run("signed big endian lock key matches publisher", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := make([]byte, 32)
for i := 0; i < 8; i++ {
hash[i] = 255
}
hash[7] = 254
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err = attachment.LockHash(ctx, tx, hash); err != nil {
t.Fatal(err)
}
other, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer other.Rollback(ctx)
var acquired bool
if err = other.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(-2::bigint)`).Scan(&acquired); err != nil || acquired {
t.Fatalf("lock mismatch: %v %v", acquired, err)
}
})
t.Run("keyset pages tolerate deletes and report costs", func(t *testing.T) {
f := reconcileSetup(t, db)
for i := 0; i < 1003; i++ {
f.b.add(fmt.Sprintf("staging/%04d", i), []byte("x"), time.Now().Add(-2*time.Hour))
}
f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) SELECT decode(lpad(to_hex(i),64,'0'),'hex'),1,'image/png','pending',now()-interval '2 hour' FROM generate_series(1,1003) AS i`)
stats, _, err := f.run(true, false)
if err != nil || stats.ScannedFiles != 1003 || stats.ScannedObjects != 1003 || stats.Repaired != 2006 {
t.Fatalf("pages: %+v %v", stats, err)
}
var n int
if err := f.db.QueryRow(ctx, `SELECT count(*) FROM files`).Scan(&n); err != nil || n != 0 {
t.Fatalf("skipped rows: %d %v", n, err)
}
if len(f.b.limits) < 4 || stats.SQLQueries == 0 || stats.S3Calls == 0 {
t.Fatalf("missing paging/costs: %+v", stats)
}
raw, err := json.Marshal(stats)
if err != nil {
t.Fatal(err)
}
for _, key := range []string{"elapsed_ms", "sql_queries", "s3_calls", "scanned_files", "scanned_objects", "findings", "repaired"} {
if !bytes.Contains(raw, []byte(`"`+key+`":`)) {
t.Fatalf("missing JSON key %s: %s", key, raw)
}
}
})
t.Run("old blob existence checks are batched by page", func(t *testing.T) {
f := reconcileSetup(t, db)
f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) SELECT decode(lpad(to_hex(i),64,'0'),'hex'),1,'image/png','ready',now()-interval '2 hour' FROM generate_series(1,1003) AS i`)
f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) SELECT gen_random_uuid(),$1,$2,'batch.png',hash,now() FROM files`, f.chat, f.user)
for i := 1; i <= 1003; i++ {
f.b.add(fmt.Sprintf("blobs/%064x", i), []byte("x"), time.Now().Add(-2*time.Hour))
}
stats, _, err := f.run(false, false)
if err != nil || stats.SQLQueries > 8 || stats.SQLQueries == 0 || stats.ScannedFiles != 1003 || stats.Findings != 0 {
t.Fatalf("per-object SQL lookup: %+v %v", stats, err)
}
})
t.Run("published variants and active staging sources are checked by page", func(t *testing.T) {
f := reconcileSetup(t, db)
const count = 100
old := time.Now().Add(-2 * time.Hour)
digest := strings.Repeat("0", 64)
hash := f.file("shared original", "ready", 2*time.Hour, false, true)
ids := make([]uuid.UUID, count)
for i := range ids {
id := uuid.New()
ids[i] = id
f.b.add("staging/"+id.String(), []byte("x"), old)
for _, name := range []string{"thumbnail", "crop", "optimized"} {
key := fmt.Sprintf("variants/%s/1/%s/%s", id, name, digest)
f.b.add(key, []byte("x"), old)
}
}
f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at,target_version,published_version)
SELECT id,$2,$3,'batch.png',$4,now(),2,1 FROM unnest($1::uuid[]) id`, ids, f.chat, f.user, hash)
f.exec(`INSERT INTO attachment_jobs(attachment_id,pipeline_version,source_key,state)
SELECT id,1,'staging/'||id,'ready' FROM attachments UNION ALL
SELECT id,2,'staging/'||id,'queued' FROM attachments`)
f.exec(`INSERT INTO attachment_variants(attachment_id,pipeline_version,variant,object_key,mime_type,width,height,size_bytes,sha256)
SELECT id,1,name,'variants/'||id||'/1/'||name||'/'||$1,
CASE WHEN name='optimized' THEN 'image/webp' ELSE 'image/jpeg' END,1,1,1,decode($1,'hex')
FROM attachments CROSS JOIN unnest(ARRAY['thumbnail','crop','optimized']) name`, digest)
stats, _, err := f.run(true, false)
t.Logf("%d published variants and %d active staging sources: %+v", 3*count, count, stats)
if err != nil || stats.Findings != 0 || stats.ScannedObjects != 4*count+1 || stats.SQLQueries > 6 {
t.Fatalf("expected page-batched lookups to preserve all referenced objects: %+v, %v", stats, err)
}
})
t.Run("new job protects a variant after the page lookup", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("pending source", "pending", 2*time.Hour, true, false)
var id uuid.UUID
if err := f.db.QueryRow(ctx, `SELECT id FROM attachments WHERE file_hash=$1`, hash).Scan(&id); err != nil {
t.Fatal(err)
}
key := fmt.Sprintf("variants/%s/1/thumbnail/%064x", id, 0)
f.b.add(key, []byte("x"), time.Now().Add(-2*time.Hour))
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
keyHash := sha256.Sum256([]byte(key))
if err := attachment.LockHash(ctx, tx, keyHash[:]); err != nil {
t.Fatal(err)
}
r, err := attachment.NewReconciler(f.db, f.b, 0)
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
_, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
done <- err
}()
waitReconcileLock(t, ctx, f.db)
if _, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(attachment_id, source_key) VALUES ($1,$2)`, id, "staging/"+id.String()); err != nil {
t.Fatal(err)
}
if err := tx.Commit(ctx); err != nil {
t.Fatal(err)
}
if err := <-done; err != nil || !f.b.has(key) {
t.Fatalf("variant required by new job was lost: %v", err)
}
})
}
func waitReconcileLock(t *testing.T, ctx context.Context, db *pgxpool.Pool) {
t.Helper()
deadline := time.NewTimer(5 * time.Second)
defer deadline.Stop()
tick := time.NewTicker(10 * time.Millisecond)
defer tick.Stop()
for {
var waiting bool
if err := db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype='advisory' AND NOT granted)`).Scan(&waiting); err != nil {
t.Fatal(err)
}
if waiting {
return
}
select {
case <-deadline.C:
t.Fatal("reconciler did not wait on publisher advisory lock")
case <-tick.C:
}
}
}
type reconcileEndless struct {
read int64
closed bool
}
func (r *reconcileEndless) Read(p []byte) (int, error) {
for i := range p {
p[i] = 'x'
}
r.read += int64(len(p))
return len(p), nil
}
func (r *reconcileEndless) Close() error { r.closed = true; return nil }
func TestReconcilerFailureBoundaries(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
t.Run("slow object call survives pool idle transaction timeout", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("slow object", "pending", 2*time.Hour, false, true)
cfg := f.db.Config()
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "100ms"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
f.db = pool
f.b.stating = func(string) { time.Sleep(250 * time.Millisecond) }
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 1 || f.status(hash) != "" {
t.Fatalf("slow S3 transaction rolled back: %+v %v", stats, err)
}
})
t.Run("fresh object with old unused metadata is preserved", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("republished", "pending", 2*time.Hour, false, true)
f.b.add(attachment.BlobKey(hash), []byte("republished"), time.Now())
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || f.status(hash) != "pending" || !f.b.has(attachment.BlobKey(hash)) {
t.Fatalf("fresh blob lost: %+v %v", stats, err)
}
})
t.Run("deep read stops at size plus one and closes body", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, true)
body := &reconcileEndless{}
f.b.opening = func(string) io.ReadCloser { return body }
stats, found, err := f.run(true, true)
if err != nil || body.read != 5 || !body.closed || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "hash_mismatch" || f.status(hash) != "ready" {
t.Fatalf("unbounded deep read: read=%d closed=%v %+v %v", body.read, body.closed, stats, err)
}
})
t.Run("deep GET outage preserves referenced state", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, true)
outage := errors.New("injected GET outage")
f.b.openErr = outage
stats, _, err := f.run(true, true)
if !errors.Is(err, outage) || stats.Repaired != 0 || f.status(hash) != "ready" {
t.Fatalf("GET outage: %+v %v", stats, err)
}
})
t.Run("valid failed object remains stable even deep", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "failed", 2*time.Hour, true, true)
for _, deep := range []bool{false, true} {
stats, found, err := f.run(true, deep)
if err != nil || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "failed_present" || f.status(hash) != "failed" {
t.Fatalf("failed state unstable: %+v %v %+v", stats, err, found)
}
}
})
t.Run("dry run works with a read only PostgreSQL session", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("missing", "ready", 2*time.Hour, true, false)
cfg := f.db.Config()
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
readOnly, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer readOnly.Close()
r, err := attachment.NewReconciler(readOnly, f.b, 0)
if err != nil {
t.Fatal(err)
}
stats, err := r.Run(ctx, attachment.ReconcileOptions{Deep: true}, nil)
if err != nil || stats.Findings != 1 || stats.Repaired != 0 || f.status(hash) != "ready" {
t.Fatalf("read only dry run: %+v %v", stats, err)
}
})
t.Run("failed SQL commit after blob deletion is retryable", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("unused", "pending", 2*time.Hour, false, true)
f.exec(`CREATE FUNCTION reconcile_reject_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected commit failure'; END $$`)
f.exec(`CREATE CONSTRAINT TRIGGER reconcile_reject_delete AFTER DELETE ON files DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_reject_delete()`)
t.Cleanup(func() {
f.exec(`DROP TRIGGER IF EXISTS reconcile_reject_delete ON files`)
f.exec(`DROP FUNCTION IF EXISTS reconcile_reject_delete()`)
})
stats, _, err := f.run(true, false)
if err == nil || stats.Repaired != 0 || f.status(hash) != "pending" || f.b.has(attachment.BlobKey(hash)) {
t.Fatalf("failed commit: %+v %v", stats, err)
}
f.exec(`DROP TRIGGER reconcile_reject_delete ON files`)
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 1 || f.status(hash) != "" {
t.Fatalf("retry: %+v %v", stats, err)
}
})
}
func TestReconcilerS3(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
s3, err := testenv.StartS3(ctx)
if err != nil {
t.Fatal(err)
}
defer s3.Close()
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, false)
missing := f.file("missing", "ready", 2*time.Hour, true, false)
key := attachment.BlobKey(hash)
if err = s3.Store.Put(ctx, key, strings.NewReader("evil"), 4, "image/png"); err != nil {
t.Fatal(err)
}
if err = s3.Store.Put(ctx, "staging/fresh", strings.NewReader("x"), 1, "image/png"); err != nil {
t.Fatal(err)
}
r, err := attachment.NewReconciler(f.db, s3.Store, 0)
if err != nil {
t.Fatal(err)
}
// Exercise the command with file-based configuration and the real listing
// identity. Its default must remain read-only, including missing metadata.
secretDir := t.TempDir()
cliEnv := os.Environ()
for name, value := range map[string]string{
"DATABASE_URL_FILE": db.DSN,
"S3_ACCESS_KEY_ID_FILE": s3.AccessKey,
"S3_SECRET_ACCESS_KEY_FILE": s3.SecretKey,
} {
path := filepath.Join(secretDir, name)
if err := os.WriteFile(path, []byte(value), 0600); err != nil {
t.Fatal(err)
}
cliEnv = append(cliEnv, name+"="+path)
}
cliEnv = append(cliEnv, "S3_ENDPOINT="+s3.Endpoint, "S3_REGION="+s3.Region, "S3_BUCKET="+s3.Bucket)
cmd := exec.CommandContext(ctx, "go", "run", "../../cmd/reconcile", "--deep")
cmd.Env = cliEnv
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
t.Fatalf("CLI dry run: %v: %s", err, stderr.String())
}
decoder := json.NewDecoder(&stdout)
var cliStats attachment.Stats
for i := 0; i < 2; i++ {
var finding attachment.Finding
if err := decoder.Decode(&finding); err != nil || finding.Applied || finding.Kind == "" || finding.Key == "" || finding.Action == "" {
t.Fatalf("CLI finding: %+v %v", finding, err)
}
}
if err := decoder.Decode(&cliStats); err != nil || cliStats.Findings != 2 || cliStats.Repaired != 0 || f.status(missing) != "ready" {
t.Fatalf("CLI mutated by default: %+v %v", cliStats, err)
}
var found []attachment.Finding
stats, err := r.Run(ctx, attachment.ReconcileOptions{Deep: true}, func(v attachment.Finding) { found = append(found, v) })
if err != nil || stats.Repaired != 0 || stats.Findings != 2 || f.status(missing) != "ready" {
t.Fatalf("S3 dry: %+v %v %+v", stats, err, found)
}
stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil)
if err != nil || stats.Repaired != 1 || f.status(missing) != "failed" || f.status(hash) != "ready" {
t.Fatalf("S3 apply: %+v %v", stats, err)
}
if _, err = s3.Store.Stat(ctx, key); err != nil {
t.Fatal("referenced corrupt object deleted", err)
}
if _, err = s3.Store.Stat(ctx, "staging/fresh"); err != nil {
t.Fatal("fresh staging deleted", err)
}
stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil)
if err != nil || stats.Repaired != 0 {
t.Fatalf("S3 repeat: %+v %v", stats, err)
}
}
func TestReconcileLockRejectsMalformedHash(t *testing.T) {
if err := attachment.LockHash(context.Background(), nil, []byte("bad")); err == nil {
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)
}
}
+17
View File
@@ -0,0 +1,17 @@
package attachment
import (
"context"
"github.com/google/uuid"
)
type AttachmentRepository interface {
// 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 ChatMembership interface {
IsMember(ctx context.Context, chatID, actorID uuid.UUID) (bool, error)
}
+27
View File
@@ -0,0 +1,27 @@
package attachment_test
import (
"context"
"messenger/internal/testenv"
"testing"
)
func TestFilesSchemaRejectsMalformedHashes(t *testing.T) {
db, err := testenv.StartPostgres(context.Background())
if err != nil {
t.Fatal(err)
}
defer db.Close()
_, err = db.Pool.Exec(context.Background(), `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES (decode(repeat('ab',32),'hex'),12,'image/png','ready')`)
if err != nil {
t.Fatalf("valid content-addressed file: %v", err)
}
_, err = db.Pool.Exec(context.Background(), `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES ('bad',12,'image/png','ready')`)
if err == nil {
t.Fatal("accepted a malformed SHA256")
}
_, err = db.Pool.Exec(context.Background(), `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES (decode(repeat('ab',32),'hex'),12,'image/png','ready')`)
if err == nil {
t.Fatal("accepted duplicate content hash")
}
}
+245
View File
@@ -0,0 +1,245 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"log/slog"
"net/http"
"path/filepath"
"time"
"github.com/google/uuid"
"messenger/internal/imaging"
"messenger/internal/platform/apperr"
"messenger/internal/platform/faultbarrier"
"messenger/internal/platform/ident"
)
type Service struct {
attachments AttachmentRepository
chats ChatMembership
blobs Blobs
config Config
decode chan struct{}
}
type Config struct {
MaxBytes int64
MaxPixels int64
BarrierDir string
}
// A nil blobs dependency allows the text API to run without configured S3.
// Binary operations report unavailability in that mode.
func NewService(attachments AttachmentRepository, chats ChatMembership, blobs Blobs, cfg Config) *Service {
if cfg.MaxBytes == 0 {
cfg.MaxBytes = imaging.MaxUploadBytes
}
if cfg.MaxPixels == 0 {
cfg.MaxPixels = imaging.MaxImagePixels
}
return &Service{
attachments: attachments,
chats: chats,
blobs: blobs,
config: cfg,
decode: make(chan struct{}, 1),
}
}
func (s *Service) Upload(ctx context.Context, actor uuid.UUID, input UploadInput, body io.Reader) (Attachment, error) {
if err := ValidateFilename(input.Filename); err != nil {
return Attachment{}, err
}
if _, accepted := imageFormats[input.MIMEType]; !accepted {
return Attachment{}, apperr.UnsupportedMedia("only image/png and image/jpeg are accepted")
}
ok, err := s.chats.IsMember(ctx, input.ChatID, actor)
if err != nil {
return Attachment{}, err
}
if !ok {
return Attachment{}, apperr.NotFound("chat not found")
}
if input.SizeBytes > s.config.MaxBytes {
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
}
if input.SizeBytes <= 0 {
return Attachment{}, apperr.Invalid("a nonempty body with Content-Length is required")
}
if s.blobs == nil {
return Attachment{}, apperr.Unavailable("object storage is unavailable")
}
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.
if err := s.blobs.Delete(cleanup, stage); err != nil {
slog.Warn("staging cleanup deferred", "key", stage, "error", err)
}
}()
hash := sha256.New()
counter := &countReader{r: io.LimitReader(body, s.config.MaxBytes+1)}
err = s.blobs.Put(ctx, stage, io.TeeReader(counter, hash), input.SizeBytes, input.MIMEType)
if err != nil {
_, tooLarge := errors.AsType[*http.MaxBytesError](err)
if counter.n > s.config.MaxBytes || tooLarge {
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
}
if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) {
return Attachment{}, apperr.Invalid("incomplete upload")
}
return Attachment{}, unavailable(err)
}
var extra [1]byte
n, readErr := counter.Read(extra[:])
if counter.n > s.config.MaxBytes {
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
}
if counter.n != input.SizeBytes || n != 0 || !errors.Is(readErr, io.EOF) {
return Attachment{}, apperr.Invalid("body length does not match Content-Length")
}
// Full decoding is bounded by dimensions and one decoder per replica. Body
// transfer itself stays streaming and does not occupy the decoder slot.
select {
case s.decode <- struct{}{}:
case <-ctx.Done():
return Attachment{}, unavailable(ctx.Err())
}
err = s.validate(ctx, stage, input.MIMEType)
<-s.decode
if err != nil {
return Attachment{}, err
}
a := Attachment{
ID: id,
ChatID: input.ChatID,
OwnerID: actor,
Filename: input.Filename,
FileHash: hash.Sum(nil),
SizeBytes: input.SizeBytes,
MIMEType: input.MIMEType,
Status: FileQueued,
UpdatedAt: ident.TimeOf(id),
CreatedAt: ident.TimeOf(id),
}
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)
}
}
// 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)
}
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) {
r, err := s.blobs.Open(ctx, stage)
if err != nil {
return unavailable(err)
}
defer func() {
if closeErr := r.Close(); closeErr != nil && err == nil {
err = unavailable(closeErr)
}
}()
tracked := &storageReader{reader: r}
err = ValidateImage(tracked, mime, s.config.MaxPixels)
if tracked.err != nil {
return unavailable(tracked.err)
}
if ctx.Err() != nil {
return unavailable(ctx.Err())
}
return err
}
// Image sniffing can replace a reader failure with ErrFormat. Preserve the
// storage failure independently, while ordinary EOF still means malformed bytes.
type storageReader struct {
reader io.Reader
err error
}
func (r *storageReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if err != nil && !errors.Is(err, io.EOF) {
r.err = err
}
return n, err
}
func (s *Service) Get(ctx context.Context, actor, id uuid.UUID) (Attachment, error) {
return s.attachments.GetForMember(ctx, id, actor)
}
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, key)
if name != "original" && errors.Is(err, ErrObjectMissing) {
return Attachment{}, nil, apperr.NotFound("variant not found")
}
if err != nil {
return Attachment{}, nil, unavailable(err)
}
return a, r, nil
}
type countReader struct {
r io.Reader
n int64
}
func (c *countReader) Read(b []byte) (int, error) {
n, err := c.r.Read(b)
c.n += int64(n)
return n, err
}
func unavailable(err error) error {
return apperr.Wrap(apperr.KindUnavailable, "object storage is unavailable", err)
}
+181
View File
@@ -0,0 +1,181 @@
package attachment_test
import (
"bytes"
"context"
"errors"
"io"
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"messenger/internal/attachment"
"messenger/internal/attachment/store"
chatstore "messenger/internal/chat/store"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/testenv"
)
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()
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)
}
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():
}
})
}
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), f.b, attachment.Config{})
uploaded := make(chan error, 1)
go func() {
_, 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 key = <-entered:
case <-ctx.Done():
t.Fatal("upload never verified staging under lock")
}
r, err := attachment.NewReconciler(db.Pool, f.b, time.Hour)
if err != nil {
t.Fatal(err)
}
collect := make(chan error, 1)
go func() {
stats, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
if err == nil && stats.Repaired != 0 {
err = errors.New("removed concurrent upload")
}
collect <- err
}()
waitReconcileLock(t, ctx, db.Pool)
close(resume)
if err := <-uploaded; err != nil {
t.Fatal(err)
}
if err := <-collect; err != nil {
t.Fatal(err)
}
if !f.b.has(key) {
t.Fatal("accepted source lost")
}
}
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
}
return io.ErrUnexpectedEOF
}
func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
ctx := context.Background()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
actor, c1, c2 := ident.New(), ident.New(), ident.New()
_, err = db.Pool.Exec(ctx, `INSERT INTO users VALUES($1,'alice','Alice','hash',now());`, actor)
if err != nil {
t.Fatal(err)
}
for _, c := range []uuid.UUID{c1, c2} {
_, err = db.Pool.Exec(ctx, `INSERT INTO chats VALUES($1,'room',now())`, c)
if err != nil {
t.Fatal(err)
}
_, err = db.Pool.Exec(ctx, `INSERT INTO chat_members VALUES($1,$2)`, c, actor)
if err != nil {
t.Fatal(err)
}
}
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 {
t.Fatal(err)
}
var results [10]attachment.Attachment
var wg sync.WaitGroup
for i := range results {
wg.Go(func() {
c := c1
if i%2 == 1 {
c = c2
}
var e error
input := attachment.UploadInput{ChatID: c, Filename: "photo.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
results[i], e = s.Upload(ctx, actor, input, bytes.NewReader(data))
if e != nil {
t.Error(e)
}
})
}
wg.Wait()
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)
}
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")
}
if _, err := s.Get(ctx, ident.New(), results[0].ID); apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("outsider got %v", 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)
}
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)
}
_, 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)
}
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("accepted rejected job")
}
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)
}
}
+92
View File
@@ -0,0 +1,92 @@
package store
import (
"context"
"crypto/sha256"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/attachment"
"messenger/internal/platform/apperr"
"messenger/internal/platform/postgres"
"messenger/internal/platform/tracectx"
)
type Attachments struct{ pool *pgxpool.Pool }
var _ attachment.AttachmentRepository = (*Attachments)(nil)
func NewAttachments(pool *pgxpool.Pool) *Attachments { return &Attachments{pool: pool} }
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 {
// 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
}
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
}
if _, err := tx.Exec(ctx, `
INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at,accepted_at)
VALUES ($1,$2,$3,$4,$5,$6,clock_timestamp())`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.FileHash, a.CreatedAt); err != nil {
return err
}
parent, state := tracectx.Fields(ctx)
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(attachment_id,source_key,traceparent,tracestate,available_at)
VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),clock_timestamp())`, a.ID, stage, parent, state)
return err
}))
}
func (r *Attachments) GetForMember(ctx context.Context, id, actor uuid.UUID) (attachment.Attachment, error) {
var a attachment.Attachment
// 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 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)
}
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
}
+54
View File
@@ -0,0 +1,54 @@
package attachment
import (
"bytes"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"strings"
"unicode"
"unicode/utf8"
"messenger/internal/imaging"
"messenger/internal/platform/apperr"
)
var imageFormats = map[string]string{
"image/png": "png",
"image/jpeg": "jpeg",
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return apperr.Invalid("filename must contain 1-255 characters")
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return apperr.Invalid("filename contains a forbidden character")
}
}
return nil
}
// The small header is replayed into the decoder; pixels are allocated only
// after checking dimensions. The caller serializes decoding per replica.
func ValidateImage(r io.Reader, mime string, maxPixels int64) error {
limited := io.LimitReader(r, imaging.MaxUploadBytes+1)
var header bytes.Buffer
cfg, format, err := image.DecodeConfig(io.TeeReader(limited, &header))
if err != nil {
return apperr.Wrap(apperr.KindUnsupportedMedia, "invalid image", err)
}
if expectedFormat, accepted := imageFormats[mime]; !accepted || format != expectedFormat {
return apperr.UnsupportedMedia("image does not match Content-Type")
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > maxPixels/int64(cfg.Height) {
return apperr.PayloadTooLarge("image exceeds pixel limit")
}
_, _, err = image.Decode(io.MultiReader(bytes.NewReader(header.Bytes()), limited))
if err != nil {
return apperr.Wrap(apperr.KindUnsupportedMedia, "invalid image", err)
}
return nil
}
+145
View File
@@ -0,0 +1,145 @@
package attachment
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"os"
"strings"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
)
type chatMember struct {
chatID, userID uuid.UUID
}
func (m chatMember) IsMember(_ context.Context, chatID, userID uuid.UUID) (bool, error) {
return chatID == m.chatID && userID == m.userID, nil
}
func TestUploadWithoutStoragePreservesChatAccessCheck(t *testing.T) {
member := chatMember{chatID: uuid.New(), userID: uuid.New()}
s := NewService(nil, member, nil, Config{})
input := UploadInput{ChatID: member.chatID, Filename: "photo.png", MIMEType: "image/png", SizeBytes: 4}
for _, tc := range []struct {
name string
actor uuid.UUID
kind apperr.Kind
}{
{name: "member", actor: member.userID, kind: apperr.KindUnavailable},
{name: "outsider", actor: uuid.New(), kind: apperr.KindNotFound},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := s.Upload(context.Background(), tc.actor, input, strings.NewReader("data"))
if apperr.KindOf(err) != tc.kind {
t.Fatalf("got %v, want %v", err, tc.kind)
}
})
}
}
func TestValidateFilename(t *testing.T) {
for _, name := range []string{"", " ", "../a.png", `a\b.jpg`, "a\x00b", "a\nb", strings.Repeat("я", 256)} {
if err := ValidateFilename(name); apperr.KindOf(err) != apperr.KindInvalid {
t.Errorf("%q: %v", name, err)
}
}
if err := ValidateFilename("фото 👋.png"); err != nil {
t.Fatal(err)
}
}
type failingRead struct{ prefix []byte }
func (r *failingRead) Read(p []byte) (int, error) {
if len(r.prefix) > 0 {
n := copy(p, r.prefix)
r.prefix = r.prefix[n:]
return n, nil
}
return 0, errors.New("injected storage read outage")
}
type openedBlob struct {
Blobs
reader io.Reader
}
func (b openedBlob) Open(context.Context, string) (io.ReadCloser, error) {
if reader, ok := b.reader.(io.ReadCloser); ok {
return reader, nil
}
return io.NopCloser(b.reader), nil
}
type closeErrorBody struct{ io.Reader }
func (closeErrorBody) Close() error { return errors.New("injected close failure") }
func TestStagingCloseFailurePreventsPublication(t *testing.T) {
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
blobs := openedBlob{reader: closeErrorBody{Reader: bytes.NewReader(data)}}
s := NewService(nil, nil, blobs, Config{})
if err := s.validate(context.Background(), "staging/test", "image/png"); apperr.KindOf(err) != apperr.KindUnavailable {
t.Fatalf("close failure classified as %v", err)
}
}
func TestStagingReadOutageIsUnavailableBeforeAndAfterHeader(t *testing.T) {
var pngData bytes.Buffer
if err := png.Encode(&pngData, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
t.Fatal(err)
}
for _, prefix := range [][]byte{nil, pngData.Bytes()[:33]} {
s := NewService(nil, nil, openedBlob{reader: &failingRead{prefix: prefix}}, Config{})
err := s.validate(context.Background(), "staging/test", "image/png")
if apperr.KindOf(err) != apperr.KindUnavailable {
t.Fatalf("storage read error classified as %v: %v", apperr.KindOf(err), err)
}
}
}
func TestValidateImageRejectsCorruptionAndLimitsPixelsBeforeDecode(t *testing.T) {
im := image.NewNRGBA(image.Rect(0, 0, 3, 2))
im.Set(1, 1, color.NRGBA{R: 200, A: 255})
var b bytes.Buffer
if err := png.Encode(&b, im); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, mime string
data []byte
pixels int64
kind apperr.Kind
}{
{"valid", "image/png", b.Bytes(), 6, apperr.KindInternal},
{"spoof", "image/jpeg", b.Bytes(), 6, apperr.KindUnsupportedMedia},
{"truncated", "image/png", b.Bytes()[:len(b.Bytes())-20], 6, apperr.KindUnsupportedMedia},
{"pixels", "image/png", b.Bytes(), 5, apperr.KindPayloadTooLarge},
{"garbage", "image/png", []byte("not a picture"), 6, apperr.KindUnsupportedMedia},
} {
t.Run(tc.name, func(t *testing.T) {
err := ValidateImage(bytes.NewReader(tc.data), tc.mime, tc.pixels)
if tc.name == "valid" {
if err != nil {
t.Fatal(err)
}
return
}
if err == nil || apperr.KindOf(err) != tc.kind {
t.Fatalf("got %v, want kind %v", err, tc.kind)
}
})
}
}