lab5: асинхронная очередь, worker и идемпотентный pipeline

API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
This commit is contained in:
Vladislav Kunetskiy
2026-10-30 22:36:52 +03:00
parent 6c5ba026f1
commit 4bdcac3dfa
95 changed files with 8466 additions and 764 deletions
+313
View File
@@ -0,0 +1,313 @@
// Package broker owns the RabbitMQ topology, confirmed publishing and the
// consumer loop. Business state never lives here: PostgreSQL is the source of
// truth for jobs and the outbox.
package broker
import (
"context"
"errors"
"fmt"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"mtusi-messenger/internal/domain"
)
type Config struct {
URL string
Exchange string
DLX string
Queue string
DLQ string
ConnectTimeout time.Duration
ConfirmTimeout time.Duration
Heartbeat time.Duration
Prefetch int
}
type Client struct {
cfg Config
conn *amqp.Connection
publisher *amqp.Channel
mu sync.Mutex
returns chan amqp.Return
closed chan *amqp.Error
}
// Dial connects, declares the durable topology idempotently and opens a
// confirm-mode publisher channel.
func Dial(cfg Config) (*Client, error) {
if cfg.URL == "" {
return nil, errors.New("broker url is empty")
}
conn, err := amqp.DialConfig(cfg.URL, amqp.Config{
Heartbeat: cfg.Heartbeat,
Dial: amqp.DefaultDial(cfg.ConnectTimeout),
Properties: amqp.Table{
"connection_name": "messenger-relay",
},
})
if err != nil {
return nil, fmt.Errorf("dial broker: %w", err)
}
channel, err := conn.Channel()
if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("open topology channel: %w", err)
}
if err := declareTopology(channel, cfg); err != nil {
_ = channel.Close()
_ = conn.Close()
return nil, err
}
if err := channel.Close(); err != nil {
_ = conn.Close()
return nil, fmt.Errorf("close topology channel: %w", err)
}
publisher, err := conn.Channel()
if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("open publisher channel: %w", err)
}
client := &Client{
cfg: cfg,
conn: conn,
publisher: publisher,
returns: make(chan amqp.Return, 16),
closed: conn.NotifyClose(make(chan *amqp.Error, 1)),
}
if err := publisher.Confirm(false); err != nil {
_ = client.Close()
return nil, fmt.Errorf("enable publisher confirms: %w", err)
}
publisher.NotifyReturn(client.returns)
return client, nil
}
func declareTopology(channel *amqp.Channel, cfg Config) error {
if err := channel.ExchangeDeclare(cfg.Exchange, "direct", true, false, false, false, nil); err != nil {
return fmt.Errorf("declare exchange: %w", err)
}
if err := channel.ExchangeDeclare(cfg.DLX, "direct", true, false, false, false, nil); err != nil {
return fmt.Errorf("declare dlx: %w", err)
}
queue, err := channel.QueueDeclare(cfg.Queue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-delivery-limit": int32(8),
"x-delayed-retry-type": "all",
"x-delayed-retry-min": int32(5000),
"x-delayed-retry-max": int32(60000),
"x-dead-letter-exchange": cfg.DLX,
"x-dead-letter-routing-key": cfg.DLQ,
"x-dead-letter-strategy": "at-least-once",
"x-overflow": "reject-publish",
"x-max-length": int32(100000),
"x-consumer-timeout": int32(300000),
})
if err != nil {
return fmt.Errorf("declare job queue: %w", err)
}
if queue.Name != cfg.Queue {
return fmt.Errorf("broker returned queue %q, want %q", queue.Name, cfg.Queue)
}
if err := channel.QueueBind(cfg.Queue, cfg.Queue, cfg.Exchange, false, nil); err != nil {
return fmt.Errorf("bind job queue: %w", err)
}
if _, err := channel.QueueDeclare(cfg.DLQ, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-max-length": int32(100000),
"x-overflow": "reject-publish",
"x-message-ttl": int32(7 * 24 * 60 * 60 * 1000),
}); err != nil {
return fmt.Errorf("declare dlq: %w", err)
}
if err := channel.QueueBind(cfg.DLQ, cfg.DLQ, cfg.DLX, false, nil); err != nil {
return fmt.Errorf("bind dlq: %w", err)
}
return nil
}
func (c *Client) Connected() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.conn != nil && !c.conn.IsClosed()
}
// PublishConfirmed returns only after the broker acknowledged the persistent
// message. A duplicate publication after a crash is normal and harmless.
func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error {
payload, err := message.MarshalPayload()
if err != nil {
return fmt.Errorf("marshal job message: %w", err)
}
confirmation, err := c.publisher.PublishWithDeferredConfirmWithContext(
ctx,
c.cfg.Exchange,
routingKey,
true,
false,
amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
MessageId: message.JobID.String(),
Type: message.Type,
Timestamp: message.CreatedAt,
Body: payload,
},
)
if err != nil {
return fmt.Errorf("publish job: %w", err)
}
confirmed, err := confirmation.WaitContext(ctx)
if err != nil {
return fmt.Errorf("await publisher confirm: %w", err)
}
if !confirmed {
return errors.New("broker nacked the job message")
}
// mandatory=true: an unroutable message is returned even though the
// confirm may still be positive. The topology is declared before publish,
// so this is a safety net rather than a normal path.
select {
case returned := <-c.returns:
if returned.MessageId == message.JobID.String() {
return fmt.Errorf("broker returned unroutable message: %s", returned.ReplyText)
}
default:
}
return nil
}
type Outcome int
const (
Ack Outcome = iota
Requeue
Drop
)
type Handler func(ctx context.Context, delivery amqp.Delivery) Outcome
// Consume blocks until the context is cancelled or the consumer channel fails.
// Each call uses its own channel so worker slots do not share prefetch state.
func (c *Client) Consume(ctx context.Context, handler Handler) error {
channel, err := c.conn.Channel()
if err != nil {
return fmt.Errorf("open consumer channel: %w", err)
}
defer channel.Close()
if err := channel.Qos(c.cfg.Prefetch, 0, false); err != nil {
return fmt.Errorf("set qos: %w", err)
}
consumerTag := fmt.Sprintf("messenger-%d", time.Now().UnixNano())
deliveries, err := channel.Consume(
c.cfg.Queue,
consumerTag,
false,
false,
false,
false,
nil,
)
if err != nil {
return fmt.Errorf("consume: %w", err)
}
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
_ = channel.Cancel(consumerTag, false)
case <-done:
}
}()
for delivery := range deliveries {
outcome := safeHandle(ctx, handler, delivery)
switch outcome {
case Ack:
_ = delivery.Ack(false)
case Requeue:
_ = delivery.Nack(false, true)
case Drop:
_ = delivery.Nack(false, false)
}
if ctx.Err() != nil {
// Let unacked deliveries return to the broker on channel close.
return nil
}
}
if ctx.Err() != nil {
return nil
}
return errors.New("consumer channel closed")
}
func safeHandle(ctx context.Context, handler Handler, delivery amqp.Delivery) (outcome Outcome) {
defer func() {
if recover() != nil {
outcome = Requeue
}
}()
return handler(ctx, delivery)
}
func (c *Client) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.publisher != nil {
_ = c.publisher.Close()
c.publisher = nil
}
if c.conn != nil {
err := c.conn.Close()
c.conn = nil
return err
}
return nil
}
+121
View File
@@ -37,6 +37,73 @@ type Config struct {
Session Session `mapstructure:"session"`
Idempotency Idempotency `mapstructure:"idempotency"`
S3 S3 `mapstructure:"s3"`
Broker Broker `mapstructure:"broker"`
Worker Worker `mapstructure:"worker"`
Relay Relay `mapstructure:"relay"`
Outbox Outbox `mapstructure:"outbox"`
Processing Processing `mapstructure:"processing"`
Staging Staging `mapstructure:"staging"`
Admission Admission `mapstructure:"admission"`
}
// Broker carries the AMQP transport settings. The API never publishes; relay
// and worker require a non-empty URL at startup.
type Broker struct {
URL string `mapstructure:"url"`
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"`
Heartbeat time.Duration `mapstructure:"heartbeat"`
Exchange string `mapstructure:"exchange" validate:"required"`
DLX string `mapstructure:"dlx" validate:"required"`
Queue string `mapstructure:"queue" validate:"required"`
DLQ string `mapstructure:"dlq" validate:"required"`
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"`
}
// Worker bounds the process that consumes jobs.
type Worker struct {
Concurrency int `mapstructure:"concurrency" validate:"required,gt=0,lte=32"`
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0,lte=100"`
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
HealthAddr string `mapstructure:"health_addr" validate:"required"`
}
// Relay bounds the outbox publisher and lease reaper.
type Relay struct {
HealthAddr string `mapstructure:"health_addr" validate:"required"`
}
// Outbox schedules publications and reclaims abandoned relay claims.
type Outbox struct {
PollInterval time.Duration `mapstructure:"poll_interval" validate:"required,gt=0"`
ClaimTTL time.Duration `mapstructure:"claim_ttl" validate:"required,gt=0"`
Batch int `mapstructure:"batch" validate:"required,gt=0,lte=1000"`
ReaperInterval time.Duration `mapstructure:"reaper_interval" validate:"required,gt=0"`
Retention time.Duration `mapstructure:"retention" validate:"required,gt=0"`
}
// Processing holds the shared job contract knobs read by API and worker.
type Processing struct {
PipelineVersion int `mapstructure:"pipeline_version" validate:"required,gte=1,lte=2"`
MaxAttempts int `mapstructure:"max_attempts" validate:"required,gte=1,lte=100"`
JobTimeout time.Duration `mapstructure:"job_timeout" validate:"required,gt=0"`
LeaseTTL time.Duration `mapstructure:"lease_ttl" validate:"required,gt=0"`
Heartbeat time.Duration `mapstructure:"heartbeat" validate:"required,gt=0"`
RetryBase time.Duration `mapstructure:"retry_base" validate:"required,gt=0"`
RetryCap time.Duration `mapstructure:"retry_cap" validate:"required,gt=0"`
}
// Staging controls cleanup of objects that are no longer the active source.
type Staging struct {
OrphanGrace time.Duration `mapstructure:"orphan_grace" validate:"required,gt=0"`
FailedRetention time.Duration `mapstructure:"failed_retention" validate:"required,gt=0"`
}
// Admission bounds accepted-but-unfinished work per user and globally.
type Admission struct {
MaxPendingPerUser int `mapstructure:"max_pending_per_user" validate:"required,gte=0"`
MaxPending int `mapstructure:"max_pending" validate:"required,gte=0"`
MaxStagedBytes int64 `mapstructure:"max_staged_bytes" validate:"required,gte=0"`
}
// S3 describes the object store and attachment limits. Access keys are checked
@@ -178,6 +245,38 @@ var defaults = map[string]any{
"cache.chat_list_ttl": "5m",
"cache.lock_ttl": "10s",
"cache.lock_wait_timeout": "2s",
"broker.url": "",
"broker.connect_timeout": "5s",
"broker.confirm_timeout": "5s",
"broker.heartbeat": "10s",
"broker.exchange": "attachments.jobs",
"broker.dlx": "attachments.dlx",
"broker.queue": "attachment.process.v1",
"broker.dlq": "attachment.process.dead",
"broker.prefetch": 1,
"worker.concurrency": 1,
"worker.prefetch": 1,
"worker.shutdown_timeout": "30s",
"worker.health_addr": ":8081",
"relay.health_addr": ":8082",
"outbox.poll_interval": "1s",
"outbox.claim_ttl": "30s",
"outbox.batch": 20,
"outbox.reaper_interval": "15s",
"outbox.retention": "168h",
"processing.pipeline_version": 1,
"processing.max_attempts": 5,
"processing.job_timeout": "120s",
"processing.lease_ttl": "180s",
"processing.heartbeat": "30s",
"processing.retry_base": "2s",
"processing.retry_cap": "60s",
"staging.orphan_grace": "1h",
"staging.failed_retention": "168h",
"admission.max_pending_per_user": 20,
"admission.max_pending": 200,
"admission.max_staged_bytes": 2147483648,
}
func Load() (Config, error) {
@@ -233,6 +332,28 @@ func (c Config) validateDependencies() error {
return errors.New("validate config: s3.sweep_grace must exceed s3.presign_ttl")
}
if c.Processing.LeaseTTL < 3*c.Processing.Heartbeat {
return errors.New("validate config: processing.lease_ttl must be at least 3x processing.heartbeat")
}
if c.Processing.JobTimeout >= c.Processing.LeaseTTL {
return errors.New("validate config: processing.job_timeout must be below processing.lease_ttl")
}
if c.Processing.RetryCap < c.Processing.RetryBase {
return errors.New("validate config: processing.retry_cap must be >= processing.retry_base")
}
if c.Staging.FailedRetention < c.Staging.OrphanGrace {
return errors.New("validate config: staging.failed_retention must be >= staging.orphan_grace")
}
if c.Broker.URL != "" {
if _, err := url.Parse(c.Broker.URL); err != nil {
return fmt.Errorf("validate config: broker.url: %w", err)
}
}
return nil
}
+100 -26
View File
@@ -6,53 +6,120 @@ import (
"github.com/google/uuid"
)
// AttachmentStatus is the lifecycle of an attachment. Only ready attachments
// are exposed to members; pending rows exist while the object is being written,
// failed rows are reserved for later labs.
// AttachmentStatus is the public lifecycle of an attachment. Pending is an
// internal presign state and is never exposed by the API.
type AttachmentStatus string
const (
AttachmentPending AttachmentStatus = "pending"
AttachmentReady AttachmentStatus = "ready"
AttachmentFailed AttachmentStatus = "failed"
AttachmentPending AttachmentStatus = "pending"
AttachmentQueued AttachmentStatus = "queued"
AttachmentProcessing AttachmentStatus = "processing"
AttachmentReady AttachmentStatus = "ready"
AttachmentFailed AttachmentStatus = "failed"
)
func (s AttachmentStatus) Valid() bool {
switch s {
case AttachmentPending, AttachmentReady, AttachmentFailed:
case AttachmentPending, AttachmentQueued, AttachmentProcessing, AttachmentReady, AttachmentFailed:
return true
default:
return false
}
}
// Attachment describes the original object. ObjectKey is internal: it never
// leaves the service and must not be mapped into an API response.
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
// Public reports whether the status is part of the API enum.
func (s AttachmentStatus) Public() bool {
switch s {
case AttachmentQueued, AttachmentProcessing, AttachmentReady, AttachmentFailed:
return true
default:
return false
}
}
// VariantName is the contract variant identifier.
type VariantName string
const (
VariantOriginal VariantName = "original"
VariantThumbnail VariantName = "thumbnail"
VariantCrop VariantName = "crop"
VariantOptimized VariantName = "optimized"
)
func (n VariantName) Valid() bool {
switch n {
case VariantThumbnail, VariantCrop, VariantOptimized:
return true
default:
return false
}
}
// ContentType returns the contract media type of the variant.
func (n VariantName) ContentType() string {
if n == VariantOptimized {
return "image/webp"
}
return "image/jpeg"
}
// ObjectName returns the object suffix for the variant.
func (n VariantName) ObjectName() string {
if n == VariantOptimized {
return string(n) + ".webp"
}
return string(n) + ".jpg"
}
// Variant is one derived image. ObjectKey is internal and never leaves the
// service.
type Variant struct {
Name VariantName
ContentType string
SizeBytes int64
Width int
Height int
SHA256 string
Status AttachmentStatus
ErrorCode *string
ObjectKey string
CreatedAt time.Time
UpdatedAt time.Time
}
// Attachment describes the original object and the current pipeline result.
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
SHA256 string
Status AttachmentStatus
ErrorCode *string
ObjectKey string
StagingKey string
PipelineVersion int
Variants []Variant
CreatedAt time.Time
UpdatedAt time.Time
ReadyAt *time.Time
FailedAt *time.Time
}
// AttachmentDraft is a fully validated attachment awaiting persistence.
type AttachmentDraft struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
SHA256 string
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
StagingKey string
Filename string
ContentType string
SizeBytes int64
SHA256 string
Status AttachmentStatus
PipelineVersion int
}
// AttachmentState is the minimal projection used while validating message
@@ -70,6 +137,13 @@ type AttachmentKey struct {
CreatedAt time.Time
}
// StaleStaging is one staging object whose owner row is already terminal.
type StaleStaging struct {
AttachmentID uuid.UUID
StagingKey string
Status AttachmentStatus
}
// PresignRequest is the validated client intent for a direct upload.
type PresignRequest struct {
ChatID uuid.UUID
+1
View File
@@ -15,4 +15,5 @@ var (
ErrTooLarge = errors.New("payload is too large")
ErrUnsupportedMedia = errors.New("unsupported media type")
ErrIncomplete = errors.New("object is not fully uploaded")
ErrRateLimited = errors.New("too many unfinished uploads")
)
+180
View File
@@ -0,0 +1,180 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
// JobType is the fixed contract type from contracts/jobs.schema.json.
const JobType = "attachment.process.v1"
// JobStatus is the durable state of one logical processing job. Superseded is
// internal: a newer pipeline version replaced the job before it completed.
type JobStatus string
const (
JobQueued JobStatus = "queued"
JobProcessing JobStatus = "processing"
JobReady JobStatus = "ready"
JobFailed JobStatus = "failed"
JobSuperseded JobStatus = "superseded"
)
func (s JobStatus) Valid() bool {
switch s {
case JobQueued, JobProcessing, JobReady, JobFailed, JobSuperseded:
return true
default:
return false
}
}
// Job is the durable processing intent. SourceKey is the trusted object the
// worker reads: staging for a fresh upload, the original object for reprocess.
type Job struct {
ID uuid.UUID
AttachmentID uuid.UUID
PipelineVersion int
SourceKey string
Attempt int
MaxAttempts int
Status JobStatus
AvailableAt time.Time
LeaseOwner string
LeaseExpiresAt *time.Time
LastErrorCode *string
ReplayCount int
CreatedAt time.Time
UpdatedAt time.Time
CompletedAt *time.Time
}
// OutboxMessage is one pending broker publication. Payload is the exact
// jobs.schema.json document; no binary data or credentials are stored.
type OutboxMessage struct {
ID int64
JobID uuid.UUID
Attempt int
Kind string
RoutingKey string
Payload []byte
AvailableAt time.Time
PublishedAt *time.Time
ClaimedBy string
ClaimedUntil *time.Time
PublishAttempts int
LastError *string
CreatedAt time.Time
}
// JobMessage is the broker carrier defined by contracts/jobs.schema.json.
type JobMessage struct {
SchemaVersion int `json:"schema_version"`
JobID uuid.UUID `json:"job_id"`
Type string `json:"type"`
AttachmentID uuid.UUID `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
// NewJobMessage builds the only message the application is allowed to publish.
func NewJobMessage(job Job) JobMessage {
return JobMessage{
SchemaVersion: 1,
JobID: job.ID,
Type: JobType,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
CreatedAt: job.CreatedAt.UTC(),
}
}
// Validate enforces the closed schema. The worker must never trust paths or
// storage metadata from this message.
func (m JobMessage) Validate() error {
if m.SchemaVersion != 1 {
return errors.New("unsupported schema_version")
}
if m.Type != JobType {
return fmt.Errorf("unsupported type %q", m.Type)
}
if m.JobID == uuid.Nil || m.AttachmentID == uuid.Nil {
return errors.New("job_id and attachment_id are required")
}
if m.PipelineVersion < 1 || m.Attempt < 1 {
return errors.New("pipeline_version and attempt must be >= 1")
}
if m.CreatedAt.IsZero() {
return errors.New("created_at is required")
}
return nil
}
func (m JobMessage) MarshalPayload() ([]byte, error) {
return json.Marshal(m)
}
func ParseJobMessage(payload []byte) (JobMessage, error) {
var message JobMessage
if err := json.Unmarshal(payload, &message); err != nil {
return JobMessage{}, fmt.Errorf("decode job message: %w", err)
}
if err := message.Validate(); err != nil {
return JobMessage{}, err
}
return message, nil
}
// ClaimOutcome explains why a delivery did or did not become the active
// processing attempt. The worker maps it to ack/nack without guessing.
type ClaimOutcome string
const (
ClaimAcquired ClaimOutcome = "acquired"
ClaimAlreadyReady ClaimOutcome = "already_ready"
ClaimAlreadyFailed ClaimOutcome = "already_failed"
ClaimSuperseded ClaimOutcome = "superseded"
ClaimStaleAttempt ClaimOutcome = "stale_attempt"
ClaimFutureAttempt ClaimOutcome = "future_attempt"
ClaimBusyLease ClaimOutcome = "busy_lease"
ClaimNotDue ClaimOutcome = "not_due"
ClaimVersionStale ClaimOutcome = "version_stale"
ClaimJobNotFound ClaimOutcome = "job_not_found"
ClaimSourceMissing ClaimOutcome = "source_missing"
ClaimPayloadInvalid ClaimOutcome = "payload_invalid"
)
type ClaimResult struct {
Outcome ClaimOutcome
Job Job
Attachment Attachment
}
// Job event names used by the operator audit trail.
const (
EventEnqueued = "enqueued"
EventClaimed = "claimed"
EventRetried = "retried"
EventReady = "ready"
EventFailed = "failed"
EventLeaseExpired = "lease_expired"
EventReplayed = "replayed"
EventReprocessed = "reprocessed"
EventSuperseded = "superseded"
)
+31
View File
@@ -0,0 +1,31 @@
package domain
import (
"strconv"
"github.com/google/uuid"
)
const (
StagingUploadPrefix = "staging/uploads/"
StagingVerifiedPrefix = "staging/verified/"
StagingPresignPrefix = "staging/presign/"
AttachmentsPrefix = "attachments/"
)
func StagingUploadKey(chatID, attachmentID uuid.UUID) string {
return StagingUploadPrefix + chatID.String() + "/" + attachmentID.String()
}
func StagingVerifiedKey(chatID, attachmentID uuid.UUID) string {
return StagingVerifiedPrefix + chatID.String() + "/" + attachmentID.String()
}
func OriginalObjectKey(chatID, attachmentID uuid.UUID) string {
return AttachmentsPrefix + chatID.String() + "/" + attachmentID.String() + "/original"
}
func VariantObjectKey(chatID, attachmentID uuid.UUID, pipelineVersion int, name VariantName) string {
return AttachmentsPrefix + chatID.String() + "/" + attachmentID.String() +
"/variants/v" + strconv.Itoa(pipelineVersion) + "/" + name.ObjectName()
}
+102
View File
@@ -0,0 +1,102 @@
// Package failpoint implements deterministic, environment-gated crash windows
// for the lab5 fault-injection evidence. Nothing fires unless FAULTS_ENABLED=1
// and the action matches both FAULT_<ACTION> and, for job-scoped faults,
// FAULT_TARGET_JOB. Production and CI leave the variables unset.
package failpoint
import (
"log/slog"
"os"
"path/filepath"
"time"
"github.com/google/uuid"
)
// Enabled reports whether fault injection is explicitly switched on.
func Enabled() bool {
return os.Getenv("FAULTS_ENABLED") == "1"
}
// Check exits the process if the action is armed for this job. It must be
// called at the exact window the evidence describes; a marker line is written
// before exit so the harness can prove the fault actually fired.
func Check(action string, jobID uuid.UUID) {
if !Enabled() {
return
}
if os.Getenv("FAULT_"+action) != "exit" {
return
}
target := os.Getenv("FAULT_TARGET_JOB")
if target != "" && target != jobID.String() {
return
}
// A one-shot marker survives the container restart performed by the
// restart policy. Without it a targeted crash failpoint would loop forever.
marker := filepath.Join(os.TempDir(), "messenger-failpoint-"+action+"-"+jobID.String())
if _, err := os.Stat(marker); err == nil {
return
}
_ = os.WriteFile(marker, []byte("fired\n"), 0o600)
slog.Default().Error("failpoint fired",
slog.String("action", action),
slog.String("job_id", jobID.String()),
slog.Int("exit_code", 70),
)
_ = os.Stdout.Sync()
_ = os.Stderr.Sync()
os.Exit(70)
}
// Mode returns the armed value for an action/job pair. Unlike Check it does not
// exit; the worker uses it to inject a permanent or transient processing error.
func Mode(action string, jobID uuid.UUID) string {
if !Enabled() {
return ""
}
target := os.Getenv("FAULT_TARGET_JOB")
if target != "" && target != jobID.String() {
return ""
}
return os.Getenv("FAULT_" + action)
}
// Sleep blocks for the configured duration when the action is armed for this
// job. It is used for hang/slow-worker scenarios where the heartbeat must keep
// running (the caller controls that separately).
func Sleep(action string, jobID uuid.UUID) {
if !Enabled() {
return
}
raw := os.Getenv("FAULT_" + action)
if raw == "" {
return
}
target := os.Getenv("FAULT_TARGET_JOB")
if target != "" && target != jobID.String() {
return
}
delay, err := time.ParseDuration(raw)
if err != nil {
return
}
slog.Default().Warn("failpoint sleeping",
slog.String("action", action),
slog.String("job_id", jobID.String()),
slog.Duration("duration", delay),
)
time.Sleep(delay)
}
+118
View File
@@ -0,0 +1,118 @@
package imageproc
import (
"encoding/binary"
"io"
)
const (
exifMaxBytes = 64 << 10
exifTagOrient = 0x0112
)
// readEXIFOrientation extracts only IFD0 Orientation from a JPEG APP1 segment.
// The parser is deliberately small and bounded: no TIFF offsets are trusted and
// the whole segment is capped at 64 KiB, so attacker-controlled EXIF cannot make
// the worker allocate unbounded memory.
func readEXIFOrientation(r io.Reader) int {
data, err := io.ReadAll(io.LimitReader(r, exifMaxBytes))
if err != nil || len(data) < 4 || data[0] != 0xff || data[1] != 0xd8 {
return 1
}
pos := 2
for pos+4 <= len(data) {
if data[pos] != 0xff {
return 1
}
marker := data[pos+1]
pos += 2
// Standalone markers without a length field.
if marker == 0xd8 || marker == 0xd9 || marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7) {
continue
}
if pos+2 > len(data) {
return 1
}
length := int(binary.BigEndian.Uint16(data[pos : pos+2]))
if length < 2 || pos+length > len(data) {
return 1
}
segment := data[pos+2 : pos+length]
pos += length
if marker != 0xe1 || len(segment) < 6 {
continue
}
if string(segment[:6]) != "Exif\x00\x00" {
continue
}
return parseTIFFOrientation(segment[6:])
}
return 1
}
func parseTIFFOrientation(tiff []byte) int {
if len(tiff) < 8 {
return 1
}
var order binary.ByteOrder
switch string(tiff[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(tiff[2:4]) != 42 {
return 1
}
ifdOffset := int(order.Uint32(tiff[4:8]))
if ifdOffset < 8 || ifdOffset+2 > len(tiff) {
return 1
}
count := int(order.Uint16(tiff[ifdOffset : ifdOffset+2]))
if count > 512 {
count = 512
}
entry := ifdOffset + 2
for range count {
if entry+12 > len(tiff) {
return 1
}
tag := order.Uint16(tiff[entry : entry+2])
typ := order.Uint16(tiff[entry+2 : entry+4])
n := order.Uint32(tiff[entry+4 : entry+8])
if tag == exifTagOrient && typ == 3 && n == 1 {
value := order.Uint16(tiff[entry+8 : entry+10])
if value >= 1 && value <= 8 {
return int(value)
}
return 1
}
entry += 12
}
return 1
}
+259
View File
@@ -0,0 +1,259 @@
// Package imageproc turns one decoded original into the contract variants.
// Output bytes are deterministic for a given pipeline version, source bytes and
// encoder versions; the worker uses that property for idempotent retries.
package imageproc
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"image"
"image/color"
"image/jpeg"
_ "image/png" // register the PNG decoder
"io"
"math"
"os"
"github.com/gen2brain/webp"
xdraw "golang.org/x/image/draw"
"mtusi-messenger/internal/domain"
)
const (
thumbnailMax = 256
cropSize = 128
optimizedMax = 1280
defaultMethod = 2
)
// Params are immutable per pipeline version. They are compiled into the binary
// so a retry can never silently produce different bytes than the first attempt.
type Params struct {
JPEGQuality int
WebPQuality int
WebPMethod int
}
// Pipeline returns the versioned encoder parameters. Only v1 and v2 are
// defined; the course baseline is v1.
func Pipeline(version int) (Params, bool) {
switch version {
case 1:
return Params{JPEGQuality: 85, WebPQuality: 80, WebPMethod: defaultMethod}, true
case 2:
return Params{JPEGQuality: 70, WebPQuality: 65, WebPMethod: 4}, true
default:
return Params{}, false
}
}
// Image is one encoded variant.
type Image struct {
Name domain.VariantName
ContentType string
Data []byte
SizeBytes int64
Width int
Height int
SHA256 string
}
// Load decodes a PNG/JPEG file, applies EXIF orientation and composites alpha
// on white. The returned image is always *image.RGBA, which bounds the variant
// encoders to 8-bit output.
func Load(path string, maxPixels int64) (image.Image, string, error) {
file, err := os.Open(path)
if err != nil {
return nil, "", fmt.Errorf("open source: %w", err)
}
defer file.Close()
cfg, format, err := image.DecodeConfig(file)
if err != nil {
return nil, "", fmt.Errorf("decode config: %w", err)
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return nil, "", fmt.Errorf("invalid dimensions %dx%d", cfg.Width, cfg.Height)
}
if maxPixels > 0 && int64(cfg.Width)*int64(cfg.Height) > maxPixels {
return nil, "", fmt.Errorf("image has %d pixels, limit %d", int64(cfg.Width)*int64(cfg.Height), maxPixels)
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return nil, "", fmt.Errorf("rewind source: %w", err)
}
decoded, _, err := image.Decode(file)
if err != nil {
return nil, "", fmt.Errorf("decode image: %w", err)
}
orientation := 1
if format == "jpeg" {
if _, err := file.Seek(0, io.SeekStart); err == nil {
orientation = readEXIFOrientation(file)
}
}
return toWhiteRGBA(decoded, orientation), format, nil
}
func toWhiteRGBA(src image.Image, orientation int) image.Image {
transformed := orient(src, orientation)
bounds := transformed.Bounds()
dst := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
xdraw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, xdraw.Src)
xdraw.Draw(dst, dst.Bounds(), transformed, bounds.Min, xdraw.Over)
return dst
}
// orient applies the eight EXIF orientation values. The result has the same
// bounds as the source except for 90-degree rotations.
func orient(src image.Image, orientation int) image.Image {
if orientation < 2 || orientation > 8 {
return src
}
b := src.Bounds()
w, h := b.Dx(), b.Dy()
width, height := w, h
if orientation >= 5 {
width, height = h, w
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
for y := range h {
for x := range w {
nx, ny := orientPoint(orientation, x, y, w, h)
dst.Set(nx, ny, src.At(b.Min.X+x, b.Min.Y+y))
}
}
return dst
}
func orientPoint(orientation, x, y, w, h int) (int, int) {
switch orientation {
case 2:
return w - 1 - x, y
case 3:
return w - 1 - x, h - 1 - y
case 4:
return x, h - 1 - y
case 5:
return y, x
case 6:
return h - 1 - y, x
case 7:
return h - 1 - y, w - 1 - x
case 8:
return y, w - 1 - x
default:
return x, y
}
}
// Thumbnail fits inside 256x256 without upscaling; dimensions are floored and
// never below 1 px.
func Thumbnail(src image.Image, params Params) (Image, error) {
return encodeJPEG(fit(src, thumbnailMax, thumbnailMax, false), domain.VariantThumbnail, params)
}
// Crop takes the centered square and scales it to 128x128. Upscaling small
// sources is allowed by the contract.
func Crop(src image.Image, params Params) (Image, error) {
b := src.Bounds()
side := b.Dx()
if b.Dy() < side {
side = b.Dy()
}
left := b.Min.X + (b.Dx()-side)/2
top := b.Min.Y + (b.Dy()-side)/2
square := image.NewRGBA(image.Rect(0, 0, side, side))
xdraw.Draw(square, square.Bounds(), src, image.Pt(left, top), xdraw.Src)
dst := image.NewRGBA(image.Rect(0, 0, cropSize, cropSize))
xdraw.CatmullRom.Scale(dst, dst.Bounds(), square, square.Bounds(), xdraw.Over, nil)
return encodeJPEG(dst, domain.VariantCrop, params)
}
// Optimized fits inside 1280x1280 without upscaling and encodes WebP. Metadata
// is stripped because the output is a fresh re-encode.
func Optimized(src image.Image, params Params) (Image, error) {
dst := fit(src, optimizedMax, optimizedMax, false)
var buf bytes.Buffer
if err := webp.Encode(&buf, dst, webp.Options{
Quality: params.WebPQuality,
Method: params.WebPMethod,
}); err != nil {
return Image{}, fmt.Errorf("encode webp: %w", err)
}
return newImage(domain.VariantOptimized, "image/webp", buf.Bytes(), dst.Bounds().Dx(), dst.Bounds().Dy()), nil
}
func encodeJPEG(dst image.Image, name domain.VariantName, params Params) (Image, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: params.JPEGQuality}); err != nil {
return Image{}, fmt.Errorf("encode jpeg: %w", err)
}
return newImage(name, "image/jpeg", buf.Bytes(), dst.Bounds().Dx(), dst.Bounds().Dy()), nil
}
func newImage(name domain.VariantName, contentType string, data []byte, width, height int) Image {
sum := sha256.Sum256(data)
return Image{
Name: name,
ContentType: contentType,
Data: data,
SizeBytes: int64(len(data)),
Width: width,
Height: height,
SHA256: hex.EncodeToString(sum[:]),
}
}
// fit scales src into maxWidth x maxHeight preserving aspect ratio, floors the
// dimensions, enforces at least 1 px and, unless allowUpscale is set, never
// enlarges the source.
func fit(src image.Image, maxWidth, maxHeight int, allowUpscale bool) *image.RGBA {
b := src.Bounds()
w, h := b.Dx(), b.Dy()
scale := math.Min(float64(maxWidth)/float64(w), float64(maxHeight)/float64(h))
if !allowUpscale && scale > 1 {
scale = 1
}
width := int(math.Floor(float64(w) * scale))
height := int(math.Floor(float64(h) * scale))
if width < 1 {
width = 1
}
if height < 1 {
height = 1
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, b, xdraw.Over, nil)
return dst
}
+222
View File
@@ -0,0 +1,222 @@
package imageproc_test
import (
"bytes"
"encoding/binary"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"testing"
"github.com/gen2brain/webp"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/imageproc"
)
func writePNG(t *testing.T, width, height int, alpha bool) string {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for x := range width {
for y := range height {
a := uint8(255)
if alpha && x < width/2 && y < height/2 {
a = 0
}
img.Set(x, y, color.NRGBA{R: 200, G: 40, B: 20, A: a})
}
}
var buf bytes.Buffer
require.NoError(t, png.Encode(&buf, img))
path := filepath.Join(t.TempDir(), "source.png")
require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600))
return path
}
func writeJPEG(t *testing.T, width, height, orientation int) string {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for x := range width {
for y := range height {
img.Set(x, y, color.RGBA{R: 200, G: 40, B: 20, A: 255})
}
}
var raw bytes.Buffer
require.NoError(t, jpeg.Encode(&raw, img, &jpeg.Options{Quality: 95}))
data := append([]byte(nil), raw.Bytes()...)
if orientation > 1 {
data = insertEXIFOrientation(t, data, uint16(orientation))
}
path := filepath.Join(t.TempDir(), "source.jpg")
require.NoError(t, os.WriteFile(path, data, 0o600))
return path
}
func insertEXIFOrientation(t *testing.T, jpegBytes []byte, orientation uint16) []byte {
t.Helper()
// TIFF: II, 42, IFD0 at offset 8, one entry (0x0112 SHORT 1 = orientation).
tiff := make([]byte, 8+2+12+4)
binary.LittleEndian.PutUint16(tiff[0:2], 0x4949)
binary.LittleEndian.PutUint16(tiff[2:4], 42)
binary.LittleEndian.PutUint32(tiff[4:8], 8)
binary.LittleEndian.PutUint16(tiff[8:10], 1)
binary.LittleEndian.PutUint16(tiff[10:12], 0x0112)
binary.LittleEndian.PutUint16(tiff[12:14], 3)
binary.LittleEndian.PutUint32(tiff[14:18], 1)
binary.LittleEndian.PutUint16(tiff[18:20], orientation)
payload := append([]byte("Exif\x00\x00"), tiff...)
segment := make([]byte, 4+len(payload))
segment[0] = 0xff
segment[1] = 0xe1
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
copy(segment[4:], payload)
// Insert immediately after SOI (before the first DQT/SOF).
out := append([]byte(nil), jpegBytes[:2]...)
out = append(out, segment...)
out = append(out, jpegBytes[2:]...)
return out
}
func decodeConfig(t *testing.T, data []byte) image.Config {
t.Helper()
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
require.NoError(t, err)
return cfg
}
func TestThumbnailContract(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
cases := []struct {
name string
width int
height int
expected [2]int
}{
{"320x200", 320, 200, [2]int{256, 160}},
{"no upscale 64x64", 64, 64, [2]int{64, 64}},
{"no upscale 64x40", 64, 40, [2]int{64, 40}},
{"floor 1000x10", 1000, 10, [2]int{256, 2}},
{"height limited", 100, 320, [2]int{80, 256}},
{"minimum 1x1", 1, 1, [2]int{1, 1}},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
img, _, err := imageproc.Load(writePNG(t, test.width, test.height, false), 40_000_000)
require.NoError(t, err)
thumb, err := imageproc.Thumbnail(img, params)
require.NoError(t, err)
cfg := decodeConfig(t, thumb.Data)
require.Equal(t, test.expected[0], cfg.Width)
require.Equal(t, test.expected[1], cfg.Height)
require.Equal(t, test.expected[0], thumb.Width)
require.Equal(t, test.expected[1], thumb.Height)
require.Equal(t, "image/jpeg", thumb.ContentType)
require.NotContains(t, string(thumb.Data), "Exif")
})
}
}
func TestCropAndOptimized(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
img, _, err := imageproc.Load(writePNG(t, 320, 200, false), 40_000_000)
require.NoError(t, err)
crop, err := imageproc.Crop(img, params)
require.NoError(t, err)
cfg := decodeConfig(t, crop.Data)
require.Equal(t, 128, cfg.Width)
require.Equal(t, 128, cfg.Height)
optimized, err := imageproc.Optimized(img, params)
require.NoError(t, err)
cfg = decodeConfig(t, optimized.Data)
require.Equal(t, 320, cfg.Width)
require.Equal(t, 200, cfg.Height)
require.Equal(t, "image/webp", optimized.ContentType)
decoded, err := webp.Decode(bytes.NewReader(optimized.Data))
require.NoError(t, err)
require.Equal(t, 320, decoded.Bounds().Dx())
require.Equal(t, 200, decoded.Bounds().Dy())
}
func TestEXIFOrientationChangesThumbnailDimensions(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
for _, orientation := range []int{6, 8} {
img, _, err := imageproc.Load(writeJPEG(t, 320, 200, orientation), 40_000_000)
require.NoError(t, err)
thumb, err := imageproc.Thumbnail(img, params)
require.NoError(t, err)
cfg := decodeConfig(t, thumb.Data)
require.Equal(t, 160, cfg.Width, "orientation %d", orientation)
require.Equal(t, 256, cfg.Height, "orientation %d", orientation)
}
}
func TestAlphaCompositedOnWhite(t *testing.T) {
params, ok := imageproc.Pipeline(1)
require.True(t, ok)
img, _, err := imageproc.Load(writePNG(t, 100, 100, true), 40_000_000)
require.NoError(t, err)
thumb, err := imageproc.Thumbnail(img, params)
require.NoError(t, err)
decoded, err := jpeg.Decode(bytes.NewReader(thumb.Data))
require.NoError(t, err)
r, g, b, _ := decoded.At(0, 0).RGBA()
require.Greater(t, r, uint32(0xf000), "transparent corner must be white")
require.Greater(t, g, uint32(0xf000), "transparent corner must be white")
require.Greater(t, b, uint32(0xf000), "transparent corner must be white")
}
func TestPipelineVersionsDiffer(t *testing.T) {
v1, ok := imageproc.Pipeline(1)
require.True(t, ok)
v2, ok := imageproc.Pipeline(2)
require.True(t, ok)
require.NotEqual(t, v1, v2)
_, ok = imageproc.Pipeline(3)
require.False(t, ok)
}
func TestVariantNames(t *testing.T) {
require.Equal(t, "image/jpeg", domain.VariantThumbnail.ContentType())
require.Equal(t, "image/jpeg", domain.VariantCrop.ContentType())
require.Equal(t, "image/webp", domain.VariantOptimized.ContentType())
require.Equal(t, "thumbnail.jpg", domain.VariantThumbnail.ObjectName())
require.Equal(t, "optimized.webp", domain.VariantOptimized.ObjectName())
}
+155
View File
@@ -0,0 +1,155 @@
// Package outbox publishes the durable job intents with publisher confirms and
// reclaims abandoned relay claims and expired worker leases.
package outbox
import (
"context"
"log/slog"
"time"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/failpoint"
)
type Repository interface {
ClaimOutbox(ctx context.Context, owner string, claimTTL time.Duration, limit int) ([]domain.OutboxMessage, error)
MarkPublished(ctx context.Context, ids []int64) error
ReleaseOutbox(ctx context.Context, id int64, reason string) error
ReapOutboxClaims(ctx context.Context) error
ReapExpiredLeases(ctx context.Context, limit int) (int, error)
PruneOutbox(ctx context.Context, retention time.Duration) error
OldestUnpublished(ctx context.Context) (time.Time, error)
}
type Publisher interface {
PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error
}
type Config struct {
Owner string
PollInterval time.Duration
ClaimTTL time.Duration
Batch int
ReaperInterval time.Duration
Retention time.Duration
}
type Relay struct {
repo Repository
publisher Publisher
config Config
log *slog.Logger
lastPublished time.Time
lastReap time.Time
}
func New(repo Repository, publisher Publisher, config Config, log *slog.Logger) *Relay {
if log == nil {
log = slog.Default()
}
return &Relay{repo: repo, publisher: publisher, config: config, log: log}
}
func (r *Relay) Run(ctx context.Context) {
poll := time.NewTicker(r.config.PollInterval)
defer poll.Stop()
reaper := time.NewTicker(r.config.ReaperInterval)
defer reaper.Stop()
for {
select {
case <-ctx.Done():
return
case <-poll.C:
if _, err := r.RunOnce(ctx); err != nil {
r.log.WarnContext(ctx, "outbox publish cycle failed", slog.Any("error", err))
}
case <-reaper.C:
r.reap(ctx)
}
}
}
// RunOnce claims due rows, publishes each with a broker confirm and marks only
// confirmed rows. A crash between confirm and mark causes a duplicate publish,
// which the worker tolerates by CAS.
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
messages, err := r.repo.ClaimOutbox(ctx, r.config.Owner, r.config.ClaimTTL, r.config.Batch)
if err != nil {
return 0, err
}
published := make([]int64, 0, len(messages))
for _, message := range messages {
job, err := domain.ParseJobMessage(message.Payload)
if err != nil {
// A malformed payload is an application bug, not a transient
// failure. Keep the row claim until it expires and log loudly; the
// operator can inspect the outbox.
r.log.ErrorContext(ctx, "outbox payload is invalid",
slog.Int64("outbox_id", message.ID),
slog.Any("error", err),
)
_ = r.repo.ReleaseOutbox(ctx, message.ID, "invalid payload")
continue
}
failpoint.Check("OUTBOX_AFTER_COMMIT", job.JobID)
if err := r.publisher.PublishConfirmed(ctx, message.RoutingKey, job); err != nil {
_ = r.repo.ReleaseOutbox(ctx, message.ID, err.Error())
continue
}
published = append(published, message.ID)
r.lastPublished = time.Now()
}
if err := r.repo.MarkPublished(ctx, published); err != nil {
return len(published), err
}
return len(published), nil
}
func (r *Relay) reap(ctx context.Context) {
if err := r.repo.ReapOutboxClaims(ctx); err != nil {
r.log.WarnContext(ctx, "outbox claim reaper failed", slog.Any("error", err))
}
reaped, err := r.repo.ReapExpiredLeases(ctx, 100)
if err != nil {
r.log.WarnContext(ctx, "lease reaper failed", slog.Any("error", err))
} else if reaped > 0 {
r.log.InfoContext(ctx, "expired job leases requeued", slog.Int("count", reaped))
}
if r.config.Retention > 0 {
if err := r.repo.PruneOutbox(ctx, r.config.Retention); err != nil {
r.log.WarnContext(ctx, "outbox retention failed", slog.Any("error", err))
}
}
r.lastReap = time.Now()
}
// Health returns the age of the oldest unpublished intent. A bounded age is a
// better relay readiness signal than "connected to broker".
func (r *Relay) Health(ctx context.Context) (oldest time.Duration, err error) {
oldestAt, err := r.repo.OldestUnpublished(ctx)
if err != nil {
return 0, err
}
if oldestAt.IsZero() {
return 0, nil
}
return time.Since(oldestAt), nil
}
@@ -22,6 +22,8 @@ type Object struct {
// because AWS SigV4 may need to rewind the payload; the proxy upload path always
// passes an *os.File.
type Store interface {
// Ping verifies that the bucket is reachable and the credentials are valid.
Ping(ctx context.Context) error
Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error
Open(ctx context.Context, key string) (io.ReadCloser, Object, error)
Head(ctx context.Context, key string) (Object, error)
+13
View File
@@ -91,6 +91,19 @@ func New(cfg Config) (*S3, error) {
return st, nil
}
func (s *S3) Ping(ctx context.Context) error {
// HeadBucket needs bucket-level permissions that the application identity
// intentionally does not have. A HeadObject on a sentinel staging key is
// enough to prove connectivity and the object-level credentials; a missing
// sentinel is the expected healthy result.
_, err := s.Head(ctx, "staging/.health/ping")
if err == nil || errors.Is(err, domain.ErrNotFound) {
return nil
}
return err
}
func (s *S3) Put(
ctx context.Context,
key string,
+366 -257
View File
@@ -7,7 +7,6 @@ package mocks
import (
"context"
"mtusi-messenger/internal/domain"
"time"
"github.com/google/uuid"
mock "github.com/stretchr/testify/mock"
@@ -49,12 +48,192 @@ func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
return &MockRepository_Expecter{mock: &_m.Mock}
}
// Create provides a mock function for the type MockRepository
func (_mock *MockRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
// Admission provides a mock function for the type MockRepository
func (_mock *MockRepository) Admission(ctx context.Context, ownerID uuid.UUID) (int, int, int64, error) {
ret := _mock.Called(ctx, ownerID)
if len(ret) == 0 {
panic("no return value specified for Admission")
}
var r0 int
var r1 int
var r2 int64
var r3 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int, int, int64, error)); ok {
return returnFunc(ctx, ownerID)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int); ok {
r0 = returnFunc(ctx, ownerID)
} else {
r0 = ret.Get(0).(int)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) int); ok {
r1 = returnFunc(ctx, ownerID)
} else {
r1 = ret.Get(1).(int)
}
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID) int64); ok {
r2 = returnFunc(ctx, ownerID)
} else {
r2 = ret.Get(2).(int64)
}
if returnFunc, ok := ret.Get(3).(func(context.Context, uuid.UUID) error); ok {
r3 = returnFunc(ctx, ownerID)
} else {
r3 = ret.Error(3)
}
return r0, r1, r2, r3
}
// MockRepository_Admission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Admission'
type MockRepository_Admission_Call struct {
*mock.Call
}
// Admission is a helper method to define mock.On call
// - ctx context.Context
// - ownerID uuid.UUID
func (_e *MockRepository_Expecter) Admission(ctx any, ownerID any) *MockRepository_Admission_Call {
return &MockRepository_Admission_Call{Call: _e.mock.On("Admission", ctx, ownerID)}
}
func (_c *MockRepository_Admission_Call) Run(run func(ctx context.Context, ownerID uuid.UUID)) *MockRepository_Admission_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Admission_Call) Return(userPending int, totalPending int, stagedBytes int64, err error) *MockRepository_Admission_Call {
_c.Call.Return(userPending, totalPending, stagedBytes, err)
return _c
}
func (_c *MockRepository_Admission_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID) (int, int, int64, error)) *MockRepository_Admission_Call {
_c.Call.Return(run)
return _c
}
// CompletePresign provides a mock function for the type MockRepository
func (_mock *MockRepository) CompletePresign(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID) (domain.Attachment, error) {
ret := _mock.Called(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
if len(ret) == 0 {
panic("no return value specified for CompletePresign")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) (domain.Attachment, error)); ok {
return returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) domain.Attachment); ok {
r0 = returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) error); ok {
r1 = returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_CompletePresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CompletePresign'
type MockRepository_CompletePresign_Call struct {
*mock.Call
}
// CompletePresign is a helper method to define mock.On call
// - ctx context.Context
// - ownerID uuid.UUID
// - attachmentID uuid.UUID
// - verifiedKey string
// - finalKey string
// - pipelineVersion int
// - maxAttempts int
// - jobID uuid.UUID
func (_e *MockRepository_Expecter) CompletePresign(ctx any, ownerID any, attachmentID any, verifiedKey any, finalKey any, pipelineVersion any, maxAttempts any, jobID any) *MockRepository_CompletePresign_Call {
return &MockRepository_CompletePresign_Call{Call: _e.mock.On("CompletePresign", ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)}
}
func (_c *MockRepository_CompletePresign_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID)) *MockRepository_CompletePresign_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 uuid.UUID
if args[2] != nil {
arg2 = args[2].(uuid.UUID)
}
var arg3 string
if args[3] != nil {
arg3 = args[3].(string)
}
var arg4 string
if args[4] != nil {
arg4 = args[4].(string)
}
var arg5 int
if args[5] != nil {
arg5 = args[5].(int)
}
var arg6 int
if args[6] != nil {
arg6 = args[6].(int)
}
var arg7 uuid.UUID
if args[7] != nil {
arg7 = args[7].(uuid.UUID)
}
run(
arg0,
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
)
})
return _c
}
func (_c *MockRepository_CompletePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CompletePresign_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_CompletePresign_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID) (domain.Attachment, error)) *MockRepository_CompletePresign_Call {
_c.Call.Return(run)
return _c
}
// CreatePresign provides a mock function for the type MockRepository
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft)
if len(ret) == 0 {
panic("no return value specified for Create")
panic("no return value specified for CreatePresign")
}
var r0 domain.Attachment
@@ -75,19 +254,19 @@ func (_mock *MockRepository) Create(ctx context.Context, draft domain.Attachment
return r0, r1
}
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
type MockRepository_Create_Call struct {
// MockRepository_CreatePresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePresign'
type MockRepository_CreatePresign_Call struct {
*mock.Call
}
// Create is a helper method to define mock.On call
// CreatePresign is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.AttachmentDraft
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft)}
}
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_Create_Call {
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_CreatePresign_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -105,12 +284,84 @@ func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft do
return _c
}
func (_c *MockRepository_Create_Call) Return(attachment domain.Attachment, err error) *MockRepository_Create_Call {
func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreatePresign_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_Create_Call {
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
_c.Call.Return(run)
return _c
}
// CreateQueued provides a mock function for the type MockRepository
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job)
if len(ret) == 0 {
panic("no return value specified for CreateQueued")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job) error); ok {
r1 = returnFunc(ctx, draft, job)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_CreateQueued_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateQueued'
type MockRepository_CreateQueued_Call struct {
*mock.Call
}
// CreateQueued is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.AttachmentDraft
// - job domain.Job
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job)}
}
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job)) *MockRepository_CreateQueued_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 domain.AttachmentDraft
if args[1] != nil {
arg1 = args[1].(domain.AttachmentDraft)
}
var arg2 domain.Job
if args[2] != nil {
arg2 = args[2].(domain.Job)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_CreateQueued_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreateQueued_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
_c.Call.Return(run)
return _c
}
@@ -316,6 +567,84 @@ func (_c *MockRepository_GetForOwner_Call) RunAndReturn(run func(ctx context.Con
return _c
}
// GetVariant provides a mock function for the type MockRepository
func (_mock *MockRepository) GetVariant(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName) (domain.Variant, error) {
ret := _mock.Called(ctx, attachmentID, pipelineVersion, name)
if len(ret) == 0 {
panic("no return value specified for GetVariant")
}
var r0 domain.Variant
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int, domain.VariantName) (domain.Variant, error)); ok {
return returnFunc(ctx, attachmentID, pipelineVersion, name)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int, domain.VariantName) domain.Variant); ok {
r0 = returnFunc(ctx, attachmentID, pipelineVersion, name)
} else {
r0 = ret.Get(0).(domain.Variant)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, int, domain.VariantName) error); ok {
r1 = returnFunc(ctx, attachmentID, pipelineVersion, name)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_GetVariant_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVariant'
type MockRepository_GetVariant_Call struct {
*mock.Call
}
// GetVariant is a helper method to define mock.On call
// - ctx context.Context
// - attachmentID uuid.UUID
// - pipelineVersion int
// - name domain.VariantName
func (_e *MockRepository_Expecter) GetVariant(ctx any, attachmentID any, pipelineVersion any, name any) *MockRepository_GetVariant_Call {
return &MockRepository_GetVariant_Call{Call: _e.mock.On("GetVariant", ctx, attachmentID, pipelineVersion, name)}
}
func (_c *MockRepository_GetVariant_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName)) *MockRepository_GetVariant_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 int
if args[2] != nil {
arg2 = args[2].(int)
}
var arg3 domain.VariantName
if args[3] != nil {
arg3 = args[3].(domain.VariantName)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockRepository_GetVariant_Call) Return(variant domain.Variant, err error) *MockRepository_GetVariant_Call {
_c.Call.Return(variant, err)
return _c
}
func (_c *MockRepository_GetVariant_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName) (domain.Variant, error)) *MockRepository_GetVariant_Call {
_c.Call.Return(run)
return _c
}
// IsChatMember provides a mock function for the type MockRepository
func (_mock *MockRepository) IsChatMember(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error) {
ret := _mock.Called(ctx, chatID, userID)
@@ -388,196 +717,48 @@ func (_c *MockRepository_IsChatMember_Call) RunAndReturn(run func(ctx context.Co
return _c
}
// ListKeys provides a mock function for the type MockRepository
func (_mock *MockRepository) ListKeys(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error) {
ret := _mock.Called(ctx, limit, offset)
// ListVariants provides a mock function for the type MockRepository
func (_mock *MockRepository) ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error) {
ret := _mock.Called(ctx, attachmentID, pipelineVersion)
if len(ret) == 0 {
panic("no return value specified for ListKeys")
panic("no return value specified for ListVariants")
}
var r0 []domain.AttachmentKey
var r0 []domain.Variant
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) ([]domain.AttachmentKey, error)); ok {
return returnFunc(ctx, limit, offset)
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int) ([]domain.Variant, error)); ok {
return returnFunc(ctx, attachmentID, pipelineVersion)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) []domain.AttachmentKey); ok {
r0 = returnFunc(ctx, limit, offset)
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int) []domain.Variant); ok {
r0 = returnFunc(ctx, attachmentID, pipelineVersion)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.AttachmentKey)
r0 = ret.Get(0).([]domain.Variant)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, int32, int32) error); ok {
r1 = returnFunc(ctx, limit, offset)
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, int) error); ok {
r1 = returnFunc(ctx, attachmentID, pipelineVersion)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_ListKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListKeys'
type MockRepository_ListKeys_Call struct {
// MockRepository_ListVariants_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVariants'
type MockRepository_ListVariants_Call struct {
*mock.Call
}
// ListKeys is a helper method to define mock.On call
// ListVariants is a helper method to define mock.On call
// - ctx context.Context
// - limit int32
// - offset int32
func (_e *MockRepository_Expecter) ListKeys(ctx any, limit any, offset any) *MockRepository_ListKeys_Call {
return &MockRepository_ListKeys_Call{Call: _e.mock.On("ListKeys", ctx, limit, offset)}
// - attachmentID uuid.UUID
// - pipelineVersion int
func (_e *MockRepository_Expecter) ListVariants(ctx any, attachmentID any, pipelineVersion any) *MockRepository_ListVariants_Call {
return &MockRepository_ListVariants_Call{Call: _e.mock.On("ListVariants", ctx, attachmentID, pipelineVersion)}
}
func (_c *MockRepository_ListKeys_Call) Run(run func(ctx context.Context, limit int32, offset int32)) *MockRepository_ListKeys_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 int32
if args[1] != nil {
arg1 = args[1].(int32)
}
var arg2 int32
if args[2] != nil {
arg2 = args[2].(int32)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_ListKeys_Call) Return(attachmentKeys []domain.AttachmentKey, err error) *MockRepository_ListKeys_Call {
_c.Call.Return(attachmentKeys, err)
return _c
}
func (_c *MockRepository_ListKeys_Call) RunAndReturn(run func(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error)) *MockRepository_ListKeys_Call {
_c.Call.Return(run)
return _c
}
// ListStalePending provides a mock function for the type MockRepository
func (_mock *MockRepository) ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error) {
ret := _mock.Called(ctx, createdBefore, limit)
if len(ret) == 0 {
panic("no return value specified for ListStalePending")
}
var r0 []domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) ([]domain.Attachment, error)); ok {
return returnFunc(ctx, createdBefore, limit)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) []domain.Attachment); ok {
r0 = returnFunc(ctx, createdBefore, limit)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.Attachment)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int32) error); ok {
r1 = returnFunc(ctx, createdBefore, limit)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_ListStalePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStalePending'
type MockRepository_ListStalePending_Call struct {
*mock.Call
}
// ListStalePending is a helper method to define mock.On call
// - ctx context.Context
// - createdBefore time.Time
// - limit int32
func (_e *MockRepository_Expecter) ListStalePending(ctx any, createdBefore any, limit any) *MockRepository_ListStalePending_Call {
return &MockRepository_ListStalePending_Call{Call: _e.mock.On("ListStalePending", ctx, createdBefore, limit)}
}
func (_c *MockRepository_ListStalePending_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int32)) *MockRepository_ListStalePending_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 time.Time
if args[1] != nil {
arg1 = args[1].(time.Time)
}
var arg2 int32
if args[2] != nil {
arg2 = args[2].(int32)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_ListStalePending_Call) Return(attachments []domain.Attachment, err error) *MockRepository_ListStalePending_Call {
_c.Call.Return(attachments, err)
return _c
}
func (_c *MockRepository_ListStalePending_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)) *MockRepository_ListStalePending_Call {
_c.Call.Return(run)
return _c
}
// ListStates provides a mock function for the type MockRepository
func (_mock *MockRepository) ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error) {
ret := _mock.Called(ctx, chatID, ids)
if len(ret) == 0 {
panic("no return value specified for ListStates")
}
var r0 []domain.AttachmentState
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) ([]domain.AttachmentState, error)); ok {
return returnFunc(ctx, chatID, ids)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) []domain.AttachmentState); ok {
r0 = returnFunc(ctx, chatID, ids)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.AttachmentState)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, []uuid.UUID) error); ok {
r1 = returnFunc(ctx, chatID, ids)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_ListStates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStates'
type MockRepository_ListStates_Call struct {
*mock.Call
}
// ListStates is a helper method to define mock.On call
// - ctx context.Context
// - chatID uuid.UUID
// - ids []uuid.UUID
func (_e *MockRepository_Expecter) ListStates(ctx any, chatID any, ids any) *MockRepository_ListStates_Call {
return &MockRepository_ListStates_Call{Call: _e.mock.On("ListStates", ctx, chatID, ids)}
}
func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID)) *MockRepository_ListStates_Call {
func (_c *MockRepository_ListVariants_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int)) *MockRepository_ListVariants_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -587,9 +768,9 @@ func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chat
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 []uuid.UUID
var arg2 int
if args[2] != nil {
arg2 = args[2].([]uuid.UUID)
arg2 = args[2].(int)
}
run(
arg0,
@@ -600,84 +781,12 @@ func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chat
return _c
}
func (_c *MockRepository_ListStates_Call) Return(attachmentStates []domain.AttachmentState, err error) *MockRepository_ListStates_Call {
_c.Call.Return(attachmentStates, err)
func (_c *MockRepository_ListVariants_Call) Return(variants []domain.Variant, err error) *MockRepository_ListVariants_Call {
_c.Call.Return(variants, err)
return _c
}
func (_c *MockRepository_ListStates_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)) *MockRepository_ListStates_Call {
_c.Call.Return(run)
return _c
}
// MarkReady provides a mock function for the type MockRepository
func (_mock *MockRepository) MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error) {
ret := _mock.Called(ctx, id, objectKey)
if len(ret) == 0 {
panic("no return value specified for MarkReady")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) (domain.Attachment, error)); ok {
return returnFunc(ctx, id, objectKey)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) domain.Attachment); ok {
r0 = returnFunc(ctx, id, objectKey)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, string) error); ok {
r1 = returnFunc(ctx, id, objectKey)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_MarkReady_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkReady'
type MockRepository_MarkReady_Call struct {
*mock.Call
}
// MarkReady is a helper method to define mock.On call
// - ctx context.Context
// - id uuid.UUID
// - objectKey string
func (_e *MockRepository_Expecter) MarkReady(ctx any, id any, objectKey any) *MockRepository_MarkReady_Call {
return &MockRepository_MarkReady_Call{Call: _e.mock.On("MarkReady", ctx, id, objectKey)}
}
func (_c *MockRepository_MarkReady_Call) Run(run func(ctx context.Context, id uuid.UUID, objectKey string)) *MockRepository_MarkReady_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 string
if args[2] != nil {
arg2 = args[2].(string)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_MarkReady_Call) Return(attachment domain.Attachment, err error) *MockRepository_MarkReady_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_MarkReady_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)) *MockRepository_MarkReady_Call {
func (_c *MockRepository_ListVariants_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)) *MockRepository_ListVariants_Call {
_c.Call.Return(run)
return _c
}
@@ -0,0 +1,398 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"mtusi-messenger/internal/domain"
"time"
"github.com/google/uuid"
mock "github.com/stretchr/testify/mock"
)
// NewMockSweepRepository creates a new instance of MockSweepRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockSweepRepository(t interface {
mock.TestingT
Cleanup(func())
}) *MockSweepRepository {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockSweepRepository{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockSweepRepository is an autogenerated mock type for the SweepRepository type
type MockSweepRepository struct {
mock.Mock
}
type MockSweepRepository_Expecter struct {
mock *mock.Mock
}
func (_m *MockSweepRepository) EXPECT() *MockSweepRepository_Expecter {
return &MockSweepRepository_Expecter{mock: &_m.Mock}
}
// DeletePending provides a mock function for the type MockSweepRepository
func (_mock *MockSweepRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
ret := _mock.Called(ctx, id)
if len(ret) == 0 {
panic("no return value specified for DeletePending")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) error); ok {
r0 = returnFunc(ctx, id)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockSweepRepository_DeletePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePending'
type MockSweepRepository_DeletePending_Call struct {
*mock.Call
}
// DeletePending is a helper method to define mock.On call
// - ctx context.Context
// - id uuid.UUID
func (_e *MockSweepRepository_Expecter) DeletePending(ctx any, id any) *MockSweepRepository_DeletePending_Call {
return &MockSweepRepository_DeletePending_Call{Call: _e.mock.On("DeletePending", ctx, id)}
}
func (_c *MockSweepRepository_DeletePending_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockSweepRepository_DeletePending_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockSweepRepository_DeletePending_Call) Return(err error) *MockSweepRepository_DeletePending_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockSweepRepository_DeletePending_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) error) *MockSweepRepository_DeletePending_Call {
_c.Call.Return(run)
return _c
}
// ListPendingPresign provides a mock function for the type MockSweepRepository
func (_mock *MockSweepRepository) ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error) {
ret := _mock.Called(ctx, createdBefore, limit)
if len(ret) == 0 {
panic("no return value specified for ListPendingPresign")
}
var r0 []domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) ([]domain.Attachment, error)); ok {
return returnFunc(ctx, createdBefore, limit)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) []domain.Attachment); ok {
r0 = returnFunc(ctx, createdBefore, limit)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.Attachment)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int) error); ok {
r1 = returnFunc(ctx, createdBefore, limit)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSweepRepository_ListPendingPresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPendingPresign'
type MockSweepRepository_ListPendingPresign_Call struct {
*mock.Call
}
// ListPendingPresign is a helper method to define mock.On call
// - ctx context.Context
// - createdBefore time.Time
// - limit int
func (_e *MockSweepRepository_Expecter) ListPendingPresign(ctx any, createdBefore any, limit any) *MockSweepRepository_ListPendingPresign_Call {
return &MockSweepRepository_ListPendingPresign_Call{Call: _e.mock.On("ListPendingPresign", ctx, createdBefore, limit)}
}
func (_c *MockSweepRepository_ListPendingPresign_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int)) *MockSweepRepository_ListPendingPresign_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 time.Time
if args[1] != nil {
arg1 = args[1].(time.Time)
}
var arg2 int
if args[2] != nil {
arg2 = args[2].(int)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockSweepRepository_ListPendingPresign_Call) Return(attachments []domain.Attachment, err error) *MockSweepRepository_ListPendingPresign_Call {
_c.Call.Return(attachments, err)
return _c
}
func (_c *MockSweepRepository_ListPendingPresign_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)) *MockSweepRepository_ListPendingPresign_Call {
_c.Call.Return(run)
return _c
}
// ListReferencedKeys provides a mock function for the type MockSweepRepository
func (_mock *MockSweepRepository) ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error) {
ret := _mock.Called(ctx, afterKey, limit)
if len(ret) == 0 {
panic("no return value specified for ListReferencedKeys")
}
var r0 []string
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, int) ([]string, error)); ok {
return returnFunc(ctx, afterKey, limit)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string, int) []string); ok {
r0 = returnFunc(ctx, afterKey, limit)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]string)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string, int) error); ok {
r1 = returnFunc(ctx, afterKey, limit)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSweepRepository_ListReferencedKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListReferencedKeys'
type MockSweepRepository_ListReferencedKeys_Call struct {
*mock.Call
}
// ListReferencedKeys is a helper method to define mock.On call
// - ctx context.Context
// - afterKey string
// - limit int
func (_e *MockSweepRepository_Expecter) ListReferencedKeys(ctx any, afterKey any, limit any) *MockSweepRepository_ListReferencedKeys_Call {
return &MockSweepRepository_ListReferencedKeys_Call{Call: _e.mock.On("ListReferencedKeys", ctx, afterKey, limit)}
}
func (_c *MockSweepRepository_ListReferencedKeys_Call) Run(run func(ctx context.Context, afterKey string, limit int)) *MockSweepRepository_ListReferencedKeys_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
var arg2 int
if args[2] != nil {
arg2 = args[2].(int)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockSweepRepository_ListReferencedKeys_Call) Return(strings []string, err error) *MockSweepRepository_ListReferencedKeys_Call {
_c.Call.Return(strings, err)
return _c
}
func (_c *MockSweepRepository_ListReferencedKeys_Call) RunAndReturn(run func(ctx context.Context, afterKey string, limit int) ([]string, error)) *MockSweepRepository_ListReferencedKeys_Call {
_c.Call.Return(run)
return _c
}
// ListStaleStaging provides a mock function for the type MockSweepRepository
func (_mock *MockSweepRepository) ListStaleStaging(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int) ([]domain.StaleStaging, error) {
ret := _mock.Called(ctx, readyBefore, failedBefore, limit)
if len(ret) == 0 {
panic("no return value specified for ListStaleStaging")
}
var r0 []domain.StaleStaging
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, int) ([]domain.StaleStaging, error)); ok {
return returnFunc(ctx, readyBefore, failedBefore, limit)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, int) []domain.StaleStaging); ok {
r0 = returnFunc(ctx, readyBefore, failedBefore, limit)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.StaleStaging)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, time.Time, int) error); ok {
r1 = returnFunc(ctx, readyBefore, failedBefore, limit)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSweepRepository_ListStaleStaging_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStaleStaging'
type MockSweepRepository_ListStaleStaging_Call struct {
*mock.Call
}
// ListStaleStaging is a helper method to define mock.On call
// - ctx context.Context
// - readyBefore time.Time
// - failedBefore time.Time
// - limit int
func (_e *MockSweepRepository_Expecter) ListStaleStaging(ctx any, readyBefore any, failedBefore any, limit any) *MockSweepRepository_ListStaleStaging_Call {
return &MockSweepRepository_ListStaleStaging_Call{Call: _e.mock.On("ListStaleStaging", ctx, readyBefore, failedBefore, limit)}
}
func (_c *MockSweepRepository_ListStaleStaging_Call) Run(run func(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int)) *MockSweepRepository_ListStaleStaging_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 time.Time
if args[1] != nil {
arg1 = args[1].(time.Time)
}
var arg2 time.Time
if args[2] != nil {
arg2 = args[2].(time.Time)
}
var arg3 int
if args[3] != nil {
arg3 = args[3].(int)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockSweepRepository_ListStaleStaging_Call) Return(staleStagings []domain.StaleStaging, err error) *MockSweepRepository_ListStaleStaging_Call {
_c.Call.Return(staleStagings, err)
return _c
}
func (_c *MockSweepRepository_ListStaleStaging_Call) RunAndReturn(run func(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)) *MockSweepRepository_ListStaleStaging_Call {
_c.Call.Return(run)
return _c
}
// MarkStagingDeleted provides a mock function for the type MockSweepRepository
func (_mock *MockSweepRepository) MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error {
ret := _mock.Called(ctx, attachmentID, stagingKey)
if len(ret) == 0 {
panic("no return value specified for MarkStagingDeleted")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) error); ok {
r0 = returnFunc(ctx, attachmentID, stagingKey)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockSweepRepository_MarkStagingDeleted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkStagingDeleted'
type MockSweepRepository_MarkStagingDeleted_Call struct {
*mock.Call
}
// MarkStagingDeleted is a helper method to define mock.On call
// - ctx context.Context
// - attachmentID uuid.UUID
// - stagingKey string
func (_e *MockSweepRepository_Expecter) MarkStagingDeleted(ctx any, attachmentID any, stagingKey any) *MockSweepRepository_MarkStagingDeleted_Call {
return &MockSweepRepository_MarkStagingDeleted_Call{Call: _e.mock.On("MarkStagingDeleted", ctx, attachmentID, stagingKey)}
}
func (_c *MockSweepRepository_MarkStagingDeleted_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, stagingKey string)) *MockSweepRepository_MarkStagingDeleted_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 string
if args[2] != nil {
arg2 = args[2].(string)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockSweepRepository_MarkStagingDeleted_Call) Return(err error) *MockSweepRepository_MarkStagingDeleted_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockSweepRepository_MarkStagingDeleted_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error) *MockSweepRepository_MarkStagingDeleted_Call {
_c.Call.Return(run)
return _c
}
+264 -96
View File
@@ -27,32 +27,55 @@ const (
contentTypePNG = "image/png"
contentTypeJPEG = "image/jpeg"
objectPrefixAttachments = "attachments/"
objectPrefixStaging = "staging/"
objectPrefixPresign = "staging/presign/"
objectPrefixAttachments = domain.AttachmentsPrefix
objectPrefixStaging = domain.StagingUploadPrefix
objectPrefixPresign = domain.StagingPresignPrefix
)
var sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
// Repository is the persistence port. It is consumer-side so the service can be
// tested without PostgreSQL.
// tested without PostgreSQL. Job/outbox writes are atomic with the attachment
// row inside CreateQueued/CompletePresign.
type Repository interface {
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)
DeletePending(ctx context.Context, id uuid.UUID) error
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)
ListKeys(ctx context.Context, limit, offset int32) ([]domain.AttachmentKey, error)
ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)
GetVariant(
ctx context.Context,
attachmentID uuid.UUID,
pipelineVersion int,
name domain.VariantName,
) (domain.Variant, error)
CreateQueued(
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
) (domain.Attachment, error)
CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
CompletePresign(
ctx context.Context,
ownerID, attachmentID uuid.UUID,
verifiedKey, finalKey string,
pipelineVersion, maxAttempts int,
jobID uuid.UUID,
) (domain.Attachment, error)
Admission(ctx context.Context, ownerID uuid.UUID) (userPending, totalPending int, stagedBytes int64, err error)
DeletePending(ctx context.Context, id uuid.UUID) error
}
// Config carries the attachment limits. They are validated by config.Load.
// Config carries attachment limits and the shared job contract knobs.
type Config struct {
MaxUploadBytes int64
MaxImagePixels int64
PresignTTL time.Duration
PipelineVersion int
MaxAttempts int
MaxPendingPerUser int
MaxPending int
MaxStagedBytes int64
}
type Service struct {
@@ -80,6 +103,8 @@ type UploadInput struct {
Body io.Reader
}
// Upload durably stages the original, records the job intent and returns the
// queued snapshot. It never waits for the broker or the worker.
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
if err := ValidateFilename(input.Filename); err != nil {
return domain.Attachment{}, err
@@ -94,6 +119,17 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
return domain.Attachment{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
}
userPending, totalPending, stagedBytes, err := s.repo.Admission(ctx, input.OwnerID)
if err != nil {
return domain.Attachment{}, unavailable("check admission", err)
}
if (s.config.MaxPendingPerUser > 0 && userPending >= s.config.MaxPendingPerUser) ||
(s.config.MaxPending > 0 && totalPending >= s.config.MaxPending) ||
(s.config.MaxStagedBytes > 0 && stagedBytes >= s.config.MaxStagedBytes) {
return domain.Attachment{}, fmt.Errorf("%w: too many unfinished uploads", domain.ErrRateLimited)
}
file, size, sum, err := s.spool(input.Body)
if err != nil {
return domain.Attachment{}, err
@@ -123,79 +159,153 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
return domain.Attachment{}, fmt.Errorf("generate attachment id: %w", err)
}
objectKey := objectPrefixAttachments + input.ChatID.String() + "/" + id.String()
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
OwnerID: input.OwnerID,
ObjectKey: objectKey,
Filename: input.Filename,
ContentType: info.ContentType,
SizeBytes: size,
SHA256: sum,
}); err != nil {
return domain.Attachment{}, err
jobID, err := uuid.NewV7()
if err != nil {
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
}
stagingKey := domain.StagingUploadKey(input.ChatID, id)
finalKey := domain.OriginalObjectKey(input.ChatID, id)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
}
if err := s.store.Put(ctx, objectKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
s.cleanupPending(ctx, id, "")
return domain.Attachment{}, unavailable("store attachment", err)
if err := s.store.Put(ctx, stagingKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("store staging object", err)
}
ready, err := s.repo.MarkReady(ctx, id, objectKey)
if err := s.verifyStaging(ctx, stagingKey, size, sum); err != nil {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, unavailable("verify staging object", err)
}
job := domain.Job{
ID: jobID,
AttachmentID: id,
PipelineVersion: s.config.PipelineVersion,
SourceKey: stagingKey,
Attempt: 1,
MaxAttempts: s.config.MaxAttempts,
CreatedAt: time.Now().UTC(),
}
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
OwnerID: input.OwnerID,
ObjectKey: finalKey,
StagingKey: stagingKey,
Filename: input.Filename,
ContentType: info.ContentType,
SizeBytes: size,
SHA256: sum,
Status: domain.AttachmentQueued,
PipelineVersion: s.config.PipelineVersion,
}, job)
if err != nil {
// The object and the pending row remain; the sweeper either finalises
// the row or removes both after the grace period. The client must not
// receive 201 until metadata is committed.
return domain.Attachment{}, unavailable("commit attachment", err)
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, unavailable("commit attachment intent", err)
}
return ready, nil
created.Variants = []domain.Variant{}
return created, nil
}
// Get returns metadata for any public status. Variants are exposed only for the
// currently published pipeline version and only when ready.
func (s *Service) Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
return domain.Attachment{}, err
}
// Contract 1.4.0 declares Attachment.status as the single value "ready".
// Pending/failed rows therefore cannot be represented in a 200 response;
// they are reported as 409 until lab5 extends the enum.
if attachment.Status != domain.AttachmentReady {
if !attachment.Status.Public() {
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
}
return attachment, nil
return s.withVariants(ctx, attachment)
}
// Open returns metadata and the original stream. Only ready attachments have
// bytes; pending/failed return 409 on the content endpoint.
func (s *Service) Open(
// OpenVariant returns metadata plus the selected content stream. Only a ready
// attachment has bytes.
func (s *Service) OpenVariant(
ctx context.Context,
callerID, id uuid.UUID,
) (domain.Attachment, io.ReadCloser, error) {
name domain.VariantName,
) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
return domain.Attachment{}, nil, err
return domain.Attachment{}, domain.Variant{}, nil, err
}
if !attachment.Status.Public() || attachment.Status != domain.AttachmentReady {
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
"%w: attachment is %s", domain.ErrConflict, attachment.Status,
)
}
if name == "" || name == domain.VariantOriginal {
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
return attachment, domain.Variant{
Name: domain.VariantOriginal,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
SHA256: attachment.SHA256,
ObjectKey: attachment.ObjectKey,
}, body, nil
}
if !name.Valid() {
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
"%w: variant %q", domain.ErrValidation, name,
)
}
variant, err := s.repo.GetVariant(ctx, attachment.ID, attachment.PipelineVersion, name)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
body, _, err := s.store.Open(ctx, variant.ObjectKey)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
return attachment, variant, body, nil
}
// Open is kept for the legacy service port used by tests.
func (s *Service) Open(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error) {
attachment, _, body, err := s.OpenVariant(ctx, callerID, id, domain.VariantOriginal)
return attachment, body, err
}
func (s *Service) withVariants(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error) {
attachment.Variants = []domain.Variant{}
if attachment.Status != domain.AttachmentReady {
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
return attachment, nil
}
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
variants, err := s.repo.ListVariants(ctx, attachment.ID, attachment.PipelineVersion)
if err != nil {
return domain.Attachment{}, nil, err
return domain.Attachment{}, err
}
return attachment, body, nil
if variants != nil {
attachment.Variants = variants
}
return attachment, nil
}
func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
@@ -235,15 +345,18 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
stagingKey := objectPrefixPresign + request.ChatID.String() + "/" + id.String()
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
ID: id,
ChatID: request.ChatID,
OwnerID: request.OwnerID,
ObjectKey: stagingKey,
Filename: request.Filename,
ContentType: request.ContentType,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
if _, err := s.repo.CreatePresign(ctx, domain.AttachmentDraft{
ID: id,
ChatID: request.ChatID,
OwnerID: request.OwnerID,
ObjectKey: stagingKey,
StagingKey: stagingKey,
Filename: request.Filename,
ContentType: request.ContentType,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
Status: domain.AttachmentPending,
PipelineVersion: s.config.PipelineVersion,
}); err != nil {
return domain.PresignResult{}, err
}
@@ -264,6 +377,10 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
}, nil
}
// Complete verifies the presigned object, copies the verified bytes to a
// server-owned staging key, and enqueues the same async pipeline as the proxy
// upload. The client's staging key remains writable until the verified copy is
// durable.
func (s *Service) Complete(
ctx context.Context,
ownerID, id uuid.UUID,
@@ -279,12 +396,12 @@ func (s *Service) Complete(
}
switch attachment.Status {
case domain.AttachmentReady:
case domain.AttachmentReady, domain.AttachmentQueued, domain.AttachmentProcessing:
if attachment.SHA256 != requestSHA {
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
}
return attachment, nil
return s.withVariants(ctx, attachment)
case domain.AttachmentFailed:
return domain.Attachment{}, fmt.Errorf("%w: attachment is failed", domain.ErrConflict)
case domain.AttachmentPending:
@@ -319,18 +436,31 @@ func (s *Service) Complete(
return domain.Attachment{}, err
}
hasher := sha256.New()
info, validateErr := imagecheck.Validate(io.TeeReader(body, hasher), s.config.MaxImagePixels)
closeErr := body.Close()
file, size, sum, err := s.spool(body)
_ = body.Close()
if validateErr != nil {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, mapImageError(validateErr)
if err != nil {
return domain.Attachment{}, err
}
if closeErr != nil {
return domain.Attachment{}, unavailable("read uploaded object", closeErr)
defer func() { _ = file.Close() }()
defer func() { _ = os.Remove(file.Name()) }()
if size != attachment.SizeBytes {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf("%w: uploaded object size changed", domain.ErrValidation)
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind uploaded object: %w", err)
}
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
if err != nil {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, mapImageError(err)
}
if info.ContentType != attachment.ContentType {
@@ -342,7 +472,6 @@ func (s *Service) Complete(
)
}
sum := hex.EncodeToString(hasher.Sum(nil))
if sum != attachment.SHA256 {
s.cleanupPending(ctx, id, attachment.ObjectKey)
@@ -350,43 +479,76 @@ func (s *Service) Complete(
}
if requestSHA != attachment.SHA256 {
// The object is valid; only the completion request is inconsistent.
// Keep the pending row and staging object so a retry can succeed.
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
}
finalKey := objectPrefixAttachments + attachment.ChatID.String() + "/" + id.String()
verifiedKey := domain.StagingVerifiedKey(attachment.ChatID, attachment.ID)
finalKey := domain.OriginalObjectKey(attachment.ChatID, attachment.ID)
if err := s.store.Copy(ctx, attachment.ObjectKey, finalKey, attachment.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("publish attachment", err)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind verified object: %w", err)
}
ready, err := s.repo.MarkReady(ctx, id, finalKey)
if err := s.store.Put(ctx, verifiedKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("store verified object", err)
}
if err := s.verifyStaging(ctx, verifiedKey, size, sum); err != nil {
s.deleteObject(ctx, id, verifiedKey)
return domain.Attachment{}, unavailable("verify staging object", err)
}
jobID, err := uuid.NewV7()
if err != nil {
// A concurrent completion may have won. Re-read instead of reporting a
// spurious failure.
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.Status == domain.AttachmentReady && current.SHA256 == requestSHA {
return current, nil
}
s.deleteObject(ctx, id, verifiedKey)
return domain.Attachment{}, unavailable("commit attachment", err)
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
}
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil {
// The final object is already committed; a stale staging object is an
// orphan and the sweeper removes it after the grace period.
s.log.WarnContext(ctx, "staging object cleanup failed",
queued, err := s.repo.CompletePresign(
ctx, ownerID, id, verifiedKey, finalKey,
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
)
if err != nil {
s.deleteObject(ctx, id, verifiedKey)
return domain.Attachment{}, unavailable("commit presigned attachment", err)
}
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "presign staging cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
return ready, nil
queued.Variants = []domain.Variant{}
return queued, nil
}
// verifyStaging checks the freshly written object; a mismatch is a broken
// staging handoff and must never become a 202.
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
head, err := s.store.Head(ctx, key)
if err != nil {
return fmt.Errorf("head staging object: %w", err)
}
if head.Size != size {
return fmt.Errorf("staging size %d, want %d", head.Size, size)
}
if sha := head.Metadata["sha256"]; sha != "" && sha != sum {
return errors.New("staging checksum metadata does not match")
}
return nil
}
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
file, err := os.CreateTemp("", "lab4-upload-*")
file, err := os.CreateTemp("", "lab5-upload-*")
if err != nil {
return nil, 0, "", fmt.Errorf("create upload spool: %w", err)
}
@@ -427,16 +589,22 @@ func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
}
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
if objectKey != "" {
if err := s.store.Delete(ctx, objectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "object cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
func (s *Service) deleteObject(ctx context.Context, id uuid.UUID, key string) {
if key == "" {
return
}
if err := s.store.Delete(ctx, key); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "object cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
}
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
s.deleteObject(ctx, id, objectKey)
if err := s.repo.DeletePending(ctx, id); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "pending attachment cleanup failed",
slog.String("attachment_id", id.String()),
+114 -49
View File
@@ -71,6 +71,8 @@ func (f *fakeStore) Open(_ context.Context, key string) (io.ReadCloser, objectst
return io.NopCloser(bytes.NewReader(object.data)), f.object(key, object), nil
}
func (f *fakeStore) Ping(context.Context) error { return nil }
func (f *fakeStore) Head(_ context.Context, key string) (objectstore.Object, error) {
object, ok := f.objects[key]
if !ok {
@@ -144,9 +146,11 @@ func pngBytes(t *testing.T, width, height int) []byte {
func serviceConfig() attachment.Config {
return attachment.Config{
MaxUploadBytes: 1 << 20,
MaxImagePixels: 1_000_000,
PresignTTL: 5 * time.Minute,
MaxUploadBytes: 1 << 20,
MaxImagePixels: 1_000_000,
PresignTTL: 5 * time.Minute,
PipelineVersion: 1,
MaxAttempts: 5,
}
}
@@ -162,7 +166,7 @@ func TestValidateFilename(t *testing.T) {
}
}
func TestUploadStoresOriginal(t *testing.T) {
func TestUploadStagesAndQueues(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
@@ -171,16 +175,25 @@ func TestUploadStoresOriginal(t *testing.T) {
ownerID := uuid.New()
content := pngBytes(t, 16, 16)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
repo.EXPECT().Create(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
repo.EXPECT().Admission(mock.Anything, ownerID).Return(0, 0, int64(0), nil).Once()
repo.EXPECT().CreateQueued(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
return draft.ChatID == chatID && draft.OwnerID == ownerID &&
draft.ContentType == "image/png" && draft.SizeBytes == int64(len(content)) &&
draft.SHA256 == hex.EncodeToString(sum[:]) && strings.HasPrefix(draft.ObjectKey, "attachments/")
})).Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
repo.EXPECT().MarkReady(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentReady, ContentType: "image/png", SizeBytes: int64(len(content))}, nil).
Once()
draft.SHA256 == digest && draft.Status == domain.AttachmentQueued &&
draft.PipelineVersion == 1 &&
strings.HasPrefix(draft.ObjectKey, "attachments/") &&
strings.HasPrefix(draft.StagingKey, "staging/uploads/")
}), mock.MatchedBy(func(job domain.Job) bool {
return job.PipelineVersion == 1 && job.Attempt == 1 &&
job.MaxAttempts == 5 && job.SourceKey != ""
})).Return(domain.Attachment{
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}, nil).Once()
result, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: chatID,
@@ -190,28 +203,28 @@ func TestUploadStoresOriginal(t *testing.T) {
Body: bytes.NewReader(content),
})
require.NoError(t, err)
require.Equal(t, domain.AttachmentReady, result.Status)
require.Equal(t, domain.AttachmentQueued, result.Status)
require.Len(t, store.objects, 1)
for key := range store.objects {
require.Contains(t, key, "staging/uploads/")
}
}
func TestUploadRejectsTooLargeBody(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
MaxUploadBytes: 8,
MaxImagePixels: 1_000_000,
PresignTTL: time.Minute,
MaxUploadBytes: 8, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
PipelineVersion: 1, MaxAttempts: 5,
}, slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(),
OwnerID: uuid.New(),
Filename: "photo.png",
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(bytes.Repeat([]byte("x"), 9)),
})
require.ErrorIs(t, err, domain.ErrTooLarge)
}
@@ -220,19 +233,63 @@ func TestUploadRejectsMIMEMismatch(t *testing.T) {
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(),
OwnerID: uuid.New(),
Filename: "photo.jpg",
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.jpg",
DeclaredContentType: "image/jpeg",
Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrUnsupportedMedia)
}
func TestGetRejectsNonReadyAttachment(t *testing.T) {
func TestUploadAdmissionRejectsFlood(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
MaxUploadBytes: 1 << 20, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
PipelineVersion: 1, MaxAttempts: 5, MaxPendingPerUser: 1,
}, slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(1, 1, int64(0), nil).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
}
func TestGetReturnsQueuedSnapshotWithoutVariants(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentQueued, PipelineVersion: 1}, nil).Once()
got, err := service.Get(t.Context(), uuid.New(), uuid.New())
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, got.Status)
require.Empty(t, got.Variants)
}
func TestGetReadyLoadsCurrentVariants(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
attachmentID := uuid.New()
variant := domain.Variant{Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 10, Width: 256, Height: 160, SHA256: strings.Repeat("a", 64)}
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, attachmentID).
Return(domain.Attachment{ID: attachmentID, Status: domain.AttachmentReady, PipelineVersion: 2}, nil).Once()
repo.EXPECT().ListVariants(mock.Anything, attachmentID, 2).Return([]domain.Variant{variant}, nil).Once()
got, err := service.Get(t.Context(), uuid.New(), attachmentID)
require.NoError(t, err)
require.Equal(t, []domain.Variant{variant}, got.Variants)
}
func TestGetRejectsInternalPending(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
@@ -243,7 +300,18 @@ func TestGetRejectsNonReadyAttachment(t *testing.T) {
require.ErrorIs(t, err, domain.ErrConflict)
}
func TestCompletePublishesPresignedObject(t *testing.T) {
func TestOpenVariantRejectsQueued(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentQueued}, nil).Once()
_, _, _, err := service.OpenVariant(t.Context(), uuid.New(), uuid.New(), domain.VariantOriginal)
require.ErrorIs(t, err, domain.ErrConflict)
}
func TestCompleteQueuesPresignedObject(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
@@ -257,29 +325,32 @@ func TestCompletePublishesPresignedObject(t *testing.T) {
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content,
contentType: "image/png",
metadata: map[string]string{"sha256": digest},
lastModified: time.Now().UTC(),
data: content, contentType: "image/png",
metadata: map[string]string{"sha256": digest}, lastModified: time.Now().UTC(),
}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().MarkReady(mock.Anything, id, mock.MatchedBy(func(key string) bool {
return strings.HasPrefix(key, "attachments/")
})).Return(domain.Attachment{
repo.EXPECT().CompletePresign(
mock.Anything, ownerID, id,
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "staging/verified/") }),
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "attachments/") }),
1, 5, mock.Anything,
).Return(domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest, Status: domain.AttachmentReady,
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}, nil).Once()
completed, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentReady, completed.Status)
require.Equal(t, domain.AttachmentQueued, completed.Status)
require.NotContains(t, store.objects, stagingKey)
require.Len(t, store.objects, 1)
}
@@ -297,16 +368,13 @@ func TestCompleteRejectsChecksumMismatch(t *testing.T) {
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content,
contentType: "image/png",
metadata: map[string]string{"sha256": digest},
}
store.objects[stagingKey] = storedObject{data: content, contentType: "image/png", metadata: map[string]string{"sha256": digest}}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
ContentType: "image/png", SizeBytes: int64(len(content)) + 1, SHA256: digest,
Status: domain.AttachmentPending,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)) + 1, SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
@@ -330,15 +398,12 @@ func TestCompleteKeepsObjectOnWrongRequestChecksum(t *testing.T) {
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content,
contentType: "image/png",
metadata: map[string]string{"sha256": digest},
}
store.objects[stagingKey] = storedObject{data: content, contentType: "image/png", metadata: map[string]string{"sha256": digest}}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
+78 -84
View File
@@ -4,9 +4,10 @@ import (
"context"
"errors"
"log/slog"
"strings"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/objectstore"
)
@@ -16,26 +17,38 @@ type LockStore interface {
AcquireSweepLock(ctx context.Context) (release func(), acquired bool, err error)
}
// SweepRepository is the storage port used by cleanup. It exposes only
// read/delete projections; object bytes still live in S3.
type SweepRepository interface {
ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)
DeletePending(ctx context.Context, id uuid.UUID) error
ListStaleStaging(ctx context.Context, readyBefore, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)
MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error
ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error)
}
type SweepStats struct {
Recovered int
RowsDeleted int
ObjectsDeleted int
StagingCleared int
}
type Sweeper struct {
repo Repository
store objectstore.Store
locker LockStore
grace time.Duration
interval time.Duration
log *slog.Logger
repo SweepRepository
store objectstore.Store
locker LockStore
grace time.Duration
orphanGrace time.Duration
failedRetain time.Duration
interval time.Duration
log *slog.Logger
}
func NewSweeper(
repo Repository,
repo SweepRepository,
store objectstore.Store,
locker LockStore,
grace, interval time.Duration,
grace, orphanGrace, failedRetain, interval time.Duration,
log *slog.Logger,
) *Sweeper {
if log == nil {
@@ -43,12 +56,14 @@ func NewSweeper(
}
return &Sweeper{
repo: repo,
store: store,
locker: locker,
grace: grace,
interval: interval,
log: log,
repo: repo,
store: store,
locker: locker,
grace: grace,
orphanGrace: orphanGrace,
failedRetain: failedRetain,
interval: interval,
log: log,
}
}
@@ -77,18 +92,18 @@ func (s *Sweeper) sweep(ctx context.Context) {
return
}
if stats.Recovered+stats.RowsDeleted+stats.ObjectsDeleted > 0 {
if stats.RowsDeleted+stats.ObjectsDeleted+stats.StagingCleared > 0 {
s.log.InfoContext(ctx, "attachment sweep finished",
slog.Int("recovered", stats.Recovered),
slog.Int("rows_deleted", stats.RowsDeleted),
slog.Int("objects_deleted", stats.ObjectsDeleted),
slog.Int("staging_cleared", stats.StagingCleared),
)
}
}
// SweepOnce reconciles PostgreSQL metadata with S3 objects. It never deletes a
// ready row or an object referenced by any row. Only objects older than the
// grace period are candidates, so an in-flight upload cannot be collected.
// SweepOnce applies explicit, status-aware retention rules. It never deletes
// staging of a queued/processing attachment and aborts object collection if any
// database page or S3 listing fails.
func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
release, acquired, err := s.locker.AcquireSweepLock(ctx)
if err != nil {
@@ -101,72 +116,20 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
defer release()
before := time.Now().UTC().Add(-s.grace)
now := time.Now().UTC()
var stats SweepStats
stale, err := s.repo.ListStalePending(ctx, before, 100)
// Abandoned presign rows: no completion ever arrived.
pending, err := s.repo.ListPendingPresign(ctx, now.Add(-s.grace), 100)
if err != nil {
return stats, err
}
for _, row := range stale {
if row.Status != domain.AttachmentPending {
continue
}
if strings.HasPrefix(row.ObjectKey, objectPrefixPresign) {
if s.deleteObject(ctx, row.ObjectKey) {
for _, row := range pending {
if row.StagingKey != "" {
if s.deleteObject(ctx, row.StagingKey) {
stats.ObjectsDeleted++
}
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
return stats, err
}
stats.RowsDeleted++
continue
}
// A proxy upload writes directly to its final key. If the process died
// between PutObject and MarkReady, the object is complete and can be
// recovered instead of discarded.
head, err := s.store.Head(ctx, row.ObjectKey)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
return stats, err
}
stats.RowsDeleted++
continue
}
s.log.WarnContext(ctx, "sweep head failed",
slog.String("attachment_id", row.ID.String()),
slog.Any("error", err),
)
continue
}
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err != nil {
// A transient database failure must not destroy a valid object.
// Leave both the row and the object for the next sweep.
s.log.WarnContext(ctx, "sweep recovery failed",
slog.String("attachment_id", row.ID.String()),
slog.Any("error", err),
)
continue
}
stats.Recovered++
continue
}
if s.deleteObject(ctx, row.ObjectKey) {
stats.ObjectsDeleted++
}
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
@@ -176,12 +139,40 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
stats.RowsDeleted++
}
// Ready/failed rows keep their staging key until the object is safely
// removed. Active queued/processing staging is never in this list.
stale, err := s.repo.ListStaleStaging(
ctx, now.Add(-s.orphanGrace), now.Add(-s.failedRetain), 100,
)
if err != nil {
return stats, err
}
for _, row := range stale {
if s.deleteObject(ctx, row.StagingKey) {
stats.ObjectsDeleted++
}
if err := s.repo.MarkStagingDeleted(ctx, row.AttachmentID, row.StagingKey); err != nil {
return stats, err
}
stats.StagingCleared++
}
referenced, err := s.referencedKeys(ctx)
if err != nil {
return stats, err
}
for _, prefix := range []string{objectPrefixAttachments, objectPrefixStaging} {
// Orphans: objects no row references. Final objects and variants use the
// normal grace; staging uses the longer orphan grace.
for _, prefix := range []string{domain.AttachmentsPrefix, "staging/"} {
before := now.Add(-s.grace)
if prefix == "staging/" {
before = now.Add(-s.orphanGrace)
}
objects, err := s.store.List(ctx, prefix)
if err != nil {
return stats, err
@@ -209,20 +200,23 @@ func (s *Sweeper) referencedKeys(ctx context.Context) (map[string]struct{}, erro
const pageSize = 1000
keys := make(map[string]struct{})
after := ""
for offset := int32(0); ; offset += pageSize {
rows, err := s.repo.ListKeys(ctx, pageSize, offset)
for {
rows, err := s.repo.ListReferencedKeys(ctx, after, pageSize)
if err != nil {
return nil, err
}
for _, row := range rows {
keys[row.ObjectKey] = struct{}{}
for _, key := range rows {
keys[key] = struct{}{}
}
if len(rows) < pageSize {
return keys, nil
}
after = rows[len(rows)-1]
}
}
+57 -70
View File
@@ -15,73 +15,71 @@ import (
"mtusi-messenger/internal/service/attachment/mocks"
)
func TestSweepReconcilesPendingAndOrphanObjects(t *testing.T) {
repo := mocks.NewMockRepository(t)
func TestSweepAppliesStatusAwareRetention(t *testing.T) {
repo := mocks.NewMockSweepRepository(t)
locker := mocks.NewMockLockStore(t)
store := newFakeStore()
stale := time.Now().UTC().Add(-time.Hour)
stale := time.Now().UTC().Add(-2 * time.Hour)
presign := domain.Attachment{
ID: uuid.New(), ObjectKey: "staging/presign/chat/" + uuid.NewString(),
Status: domain.AttachmentPending, CreatedAt: stale,
ID: uuid.New(), StagingKey: "staging/presign/chat/" + uuid.NewString(),
Status: domain.AttachmentPending,
}
proxyRecoverable := domain.Attachment{
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
Status: domain.AttachmentPending, CreatedAt: stale,
staleStaging := domain.StaleStaging{
AttachmentID: uuid.New(), StagingKey: "staging/uploads/chat/ready", Status: domain.AttachmentReady,
}
proxyMissing := domain.Attachment{
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
Status: domain.AttachmentPending, CreatedAt: stale,
}
readyKey := "attachments/chat/ready"
activeStaging := "staging/uploads/chat/active"
readyKey := "attachments/chat/ready/original"
variantKey := "attachments/chat/ready/variants/v1/thumbnail.jpg"
store.objects[presign.ObjectKey] = storedObject{data: []byte("x"), lastModified: stale}
store.objects[proxyRecoverable.ObjectKey] = storedObject{
data: []byte("abc"),
lastModified: stale,
metadata: map[string]string{"sha256": proxyRecoverable.SHA256},
for _, key := range []string{
presign.StagingKey, staleStaging.StagingKey, activeStaging, readyKey, variantKey,
"attachments/chat/orphan", "staging/orphan",
} {
store.objects[key] = storedObject{data: []byte("x"), lastModified: stale}
}
store.objects[readyKey] = storedObject{data: []byte("ready"), lastModified: stale}
store.objects["attachments/chat/orphan"] = storedObject{data: []byte("orphan"), lastModified: stale}
store.objects["staging/abandoned"] = storedObject{data: []byte("stale"), lastModified: stale}
store.objects["staging/fresh"] = storedObject{data: []byte("fresh"), lastModified: time.Now().UTC()}
store.objects["staging/fresh"] = storedObject{data: []byte("x"), lastModified: time.Now().UTC()}
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
Return([]domain.Attachment{presign, proxyRecoverable, proxyMissing}, nil).Once()
repo.EXPECT().ListPendingPresign(mock.Anything, mock.Anything, 100).
Return([]domain.Attachment{presign}, nil).Once()
repo.EXPECT().DeletePending(mock.Anything, presign.ID).Return(nil).Once()
repo.EXPECT().MarkReady(mock.Anything, proxyRecoverable.ID, proxyRecoverable.ObjectKey).
Return(domain.Attachment{ID: proxyRecoverable.ID, Status: domain.AttachmentReady}, nil).Once()
repo.EXPECT().DeletePending(mock.Anything, proxyMissing.ID).Return(nil).Once()
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
Return([]domain.AttachmentKey{
{ID: proxyRecoverable.ID, ObjectKey: proxyRecoverable.ObjectKey, Status: domain.AttachmentReady},
{ID: uuid.New(), ObjectKey: readyKey, Status: domain.AttachmentReady},
}, nil).Once()
locker.EXPECT().AcquireSweepLock(mock.Anything).
Return(func() {}, true, nil).Once()
repo.EXPECT().ListStaleStaging(mock.Anything, mock.Anything, mock.Anything, 100).
Return([]domain.StaleStaging{staleStaging}, nil).Once()
repo.EXPECT().MarkStagingDeleted(mock.Anything, staleStaging.AttachmentID, staleStaging.StagingKey).
Return(nil).Once()
repo.EXPECT().ListReferencedKeys(mock.Anything, "", 1000).
Return([]string{activeStaging, readyKey, variantKey}, nil).Once()
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
sweeper := attachment.NewSweeper(
repo, store, locker,
10*time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
)
stats, err := sweeper.SweepOnce(t.Context())
require.NoError(t, err)
require.Equal(t, 1, stats.Recovered)
require.Equal(t, 2, stats.RowsDeleted)
require.Equal(t, 3, stats.ObjectsDeleted)
require.Equal(t, 1, stats.RowsDeleted)
require.Equal(t, 1, stats.StagingCleared)
require.Equal(t, 4, stats.ObjectsDeleted)
require.NotContains(t, store.objects, presign.ObjectKey)
require.NotContains(t, store.objects, presign.StagingKey)
require.NotContains(t, store.objects, staleStaging.StagingKey)
require.NotContains(t, store.objects, "attachments/chat/orphan")
require.NotContains(t, store.objects, "staging/abandoned")
require.Contains(t, store.objects, proxyRecoverable.ObjectKey)
require.NotContains(t, store.objects, "staging/orphan")
require.Contains(t, store.objects, activeStaging)
require.Contains(t, store.objects, readyKey)
require.Contains(t, store.objects, variantKey)
require.Contains(t, store.objects, "staging/fresh")
}
func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
repo := mocks.NewMockRepository(t)
repo := mocks.NewMockSweepRepository(t)
locker := mocks.NewMockLockStore(t)
sweeper := attachment.NewSweeper(repo, newFakeStore(), locker, time.Minute, time.Hour, slog.Default())
sweeper := attachment.NewSweeper(
repo, newFakeStore(), locker,
time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
)
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(nil, false, nil).Once()
@@ -90,37 +88,26 @@ func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
require.Zero(t, stats)
}
func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) {
repo := mocks.NewMockRepository(t)
func TestSweepAbortsObjectCollectionWhenKeysCannotBeRead(t *testing.T) {
repo := mocks.NewMockSweepRepository(t)
locker := mocks.NewMockLockStore(t)
store := newFakeStore()
stale := time.Now().UTC().Add(-time.Hour)
row := domain.Attachment{
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
Status: domain.AttachmentPending, CreatedAt: stale,
}
orphan := "attachments/chat/orphan"
store.objects[orphan] = storedObject{data: []byte("x"), lastModified: time.Now().UTC().Add(-2 * time.Hour)}
store.objects[row.ObjectKey] = storedObject{
data: []byte("abc"),
lastModified: stale,
metadata: map[string]string{"sha256": row.SHA256},
}
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
Return([]domain.Attachment{row}, nil).Once()
repo.EXPECT().MarkReady(mock.Anything, row.ID, row.ObjectKey).
Return(domain.Attachment{}, context.DeadlineExceeded).Once()
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
Return([]domain.AttachmentKey{{ID: row.ID, ObjectKey: row.ObjectKey, Status: domain.AttachmentPending}}, nil).Once()
repo.EXPECT().ListPendingPresign(mock.Anything, mock.Anything, 100).Return(nil, nil).Once()
repo.EXPECT().ListStaleStaging(mock.Anything, mock.Anything, mock.Anything, 100).Return(nil, nil).Once()
repo.EXPECT().ListReferencedKeys(mock.Anything, "", 1000).
Return(nil, context.DeadlineExceeded).Once()
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
sweeper := attachment.NewSweeper(
repo, store, locker,
time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
)
stats, err := sweeper.SweepOnce(t.Context())
require.NoError(t, err)
require.Zero(t, stats.Recovered)
require.Zero(t, stats.RowsDeleted)
require.Contains(t, store.objects, row.ObjectKey)
_, err := sweeper.SweepOnce(t.Context())
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Contains(t, store.objects, orphan, "fail-closed: no deletion when the key set is unknown")
}
@@ -269,3 +269,75 @@ func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Con
_c.Call.Return(run)
return _c
}
// Replay provides a mock function for the type MockRepository
func (_mock *MockRepository) Replay(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error) {
ret := _mock.Called(ctx, draft)
if len(ret) == 0 {
panic("no return value specified for Replay")
}
var r0 domain.Message
var r1 bool
var r2 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, bool, error)); ok {
return returnFunc(ctx, draft)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) domain.Message); ok {
r0 = returnFunc(ctx, draft)
} else {
r0 = ret.Get(0).(domain.Message)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.MessageDraft) bool); ok {
r1 = returnFunc(ctx, draft)
} else {
r1 = ret.Get(1).(bool)
}
if returnFunc, ok := ret.Get(2).(func(context.Context, domain.MessageDraft) error); ok {
r2 = returnFunc(ctx, draft)
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// MockRepository_Replay_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Replay'
type MockRepository_Replay_Call struct {
*mock.Call
}
// Replay is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.MessageDraft
func (_e *MockRepository_Expecter) Replay(ctx any, draft any) *MockRepository_Replay_Call {
return &MockRepository_Replay_Call{Call: _e.mock.On("Replay", ctx, draft)}
}
func (_c *MockRepository_Replay_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockRepository_Replay_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 domain.MessageDraft
if args[1] != nil {
arg1 = args[1].(domain.MessageDraft)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Replay_Call) Return(message domain.Message, b bool, err error) *MockRepository_Replay_Call {
_c.Call.Return(message, b, err)
return _c
}
func (_c *MockRepository_Replay_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error)) *MockRepository_Replay_Call {
_c.Call.Return(run)
return _c
}
+18 -1
View File
@@ -11,6 +11,11 @@ import (
type Repository interface {
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
// Replay returns the stored message for a live Idempotency-Key. It must be
// checked before attachment-state validation: a message that was accepted
// while the attachment was queued keeps replaying as 201 even after the
// attachment later fails.
Replay(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error)
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
ListVisible(
ctx context.Context,
@@ -50,6 +55,15 @@ func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.M
return domain.Message{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
}
replayed, found, err := s.messages.Replay(ctx, draft)
if err != nil {
return domain.Message{}, fmt.Errorf("replay message: %w", err)
}
if found {
return replayed, nil
}
if len(draft.AttachmentIDs) > 0 {
if s.attachments == nil {
return domain.Message{}, fmt.Errorf("attachment checker is not configured: %w", domain.ErrUnavailable)
@@ -65,7 +79,10 @@ func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.M
}
for _, state := range states {
if state.Status != domain.AttachmentReady {
switch state.Status {
case domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentReady:
// Accepted work is linkable by contract.
default:
return domain.Message{}, fmt.Errorf(
"%w: attachment %s is %s",
domain.ErrConflict, state.ID, state.Status,
+37
View File
@@ -6,6 +6,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
@@ -38,6 +39,8 @@ func (s *ServiceSuite) SetupTest() {
s.caller = uuid.New()
s.chatID = uuid.New()
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
s.messages.EXPECT().Replay(mock.Anything, mock.Anything).
Return(domain.Message{}, false, nil).Maybe()
}
func (s *ServiceSuite) draft() domain.MessageDraft {
@@ -167,6 +170,40 @@ func (s *ServiceSuite) TestSendAcceptsReadyAttachment() {
s.Equal([]uuid.UUID{attachmentID}, got.AttachmentIDs)
}
func (s *ServiceSuite) TestSendReplaysBeforeAttachmentValidation() {
draft := s.draft()
draft.AttachmentIDs = []uuid.UUID{uuid.New()}
stored := domain.Message{
ID: uuid.New(), ChatID: draft.ChatID, SenderID: draft.SenderID,
Text: draft.Text, AttachmentIDs: draft.AttachmentIDs, CreatedAt: s.now,
}
// The stored key is authoritative even if the attachment has since failed;
// ListStates must not be consulted on a replay.
s.messages.ExpectedCalls = nil
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
s.messages.EXPECT().Replay(s.T().Context(), draft).Return(stored, true, nil).Once()
got, err := s.service.Send(s.T().Context(), draft)
s.Require().NoError(err)
s.Equal(stored, got)
}
func (s *ServiceSuite) TestSendRejectsFailedAttachment() {
attachmentID := uuid.New()
draft := s.draft()
draft.AttachmentIDs = []uuid.UUID{attachmentID}
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
s.attachments.EXPECT().
ListStates(s.T().Context(), draft.ChatID, []uuid.UUID{attachmentID}).
Return([]domain.AttachmentState{{ID: attachmentID, Status: domain.AttachmentFailed}}, nil).
Once()
_, err := s.service.Send(s.T().Context(), draft)
s.Require().ErrorIs(err, domain.ErrConflict)
}
func (s *ServiceSuite) TestSendAllowsAttachmentOnlyMessage() {
attachmentID := uuid.New()
draft := s.draft()
@@ -6,6 +6,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
@@ -48,7 +49,7 @@ func (r *AttachmentRepository) Create(ctx context.Context, draft domain.Attachme
return domain.Attachment{}, fmt.Errorf("create attachment: %w", mapError(err))
}
return mapAttachment(row), nil
return mapCreateAttachment(row), nil
}
func (r *AttachmentRepository) MarkReady(
@@ -67,7 +68,7 @@ func (r *AttachmentRepository) MarkReady(
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", mapError(err))
}
return mapAttachment(row), nil
return mapMarkReadyAttachment(row), nil
}
func (r *AttachmentRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
@@ -96,7 +97,7 @@ func (r *AttachmentRepository) GetForMember(
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
}
return mapAttachment(row), nil
return mapMemberAttachment(row), nil
}
func (r *AttachmentRepository) GetForOwner(
@@ -114,7 +115,7 @@ func (r *AttachmentRepository) GetForOwner(
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
}
return mapAttachment(row), nil
return mapOwnerAttachment(row), nil
}
func (r *AttachmentRepository) ListStates(
@@ -160,7 +161,12 @@ func (r *AttachmentRepository) ListStalePending(
return nil, fmt.Errorf("list stale attachments: %w", mapError(err))
}
return mapAll(rows, mapAttachment), nil
stale := make([]domain.Attachment, 0, len(rows))
for _, row := range rows {
stale = append(stale, mapStaleAttachment(row))
}
return stale, nil
}
func (r *AttachmentRepository) ListKeys(
@@ -191,23 +197,47 @@ func (r *AttachmentRepository) ListKeys(
return keys, nil
}
func mapAttachment(row sqlcgen.Attachment) domain.Attachment {
attachment := domain.Attachment{
ID: row.ID,
ChatID: row.ChatID,
OwnerID: row.OwnerID,
ObjectKey: row.ObjectKey,
Filename: row.Filename,
ContentType: row.ContentType,
SizeBytes: row.SizeBytes,
SHA256: row.Sha256,
Status: domain.AttachmentStatus(row.Status),
CreatedAt: toUTCTime(row.CreatedAt),
UpdatedAt: toUTCTime(row.UpdatedAt),
}
func mapCreateAttachment(row sqlcgen.CreateAttachmentRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
if row.ErrorCode.Valid {
code := row.ErrorCode.String
func mapMarkReadyAttachment(row sqlcgen.MarkAttachmentReadyRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapMemberAttachment(row sqlcgen.GetAttachmentForMemberRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapOwnerAttachment(row sqlcgen.GetAttachmentForOwnerRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapStaleAttachment(row sqlcgen.ListStalePendingAttachmentsRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func legacyAttachment(
id, chatID, ownerID uuid.UUID,
objectKey, filename, contentType string,
sizeBytes int64,
sha, status string,
errorCode pgtype.Text,
createdAt, updatedAt time.Time,
) domain.Attachment {
attachment := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: objectKey,
Filename: filename, ContentType: contentType, SizeBytes: sizeBytes,
SHA256: sha, Status: domain.AttachmentStatus(status),
PipelineVersion: 1, CreatedAt: createdAt, UpdatedAt: updatedAt,
}
if errorCode.Valid {
code := errorCode.String
attachment.ErrorCode = &code
}
@@ -10,6 +10,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
)
const attachToMessage = `-- name: AttachToMessage :exec
@@ -58,7 +59,22 @@ type CreateAttachmentParams struct {
Sha256 string
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
type CreateAttachmentRow struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (CreateAttachmentRow, error) {
row := q.db.QueryRow(ctx, createAttachment,
arg.ID,
arg.ChatID,
@@ -69,7 +85,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
arg.SizeBytes,
arg.Sha256,
)
var i Attachment
var i CreateAttachmentRow
err := row.Scan(
&i.ID,
&i.ChatID,
@@ -113,9 +129,24 @@ type GetAttachmentForMemberParams struct {
ID uuid.UUID
}
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (Attachment, error) {
type GetAttachmentForMemberRow struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (GetAttachmentForMemberRow, error) {
row := q.db.QueryRow(ctx, getAttachmentForMember, arg.UserID, arg.ID)
var i Attachment
var i GetAttachmentForMemberRow
err := row.Scan(
&i.ID,
&i.ChatID,
@@ -149,9 +180,24 @@ type GetAttachmentForOwnerParams struct {
OwnerID uuid.UUID
}
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (Attachment, error) {
type GetAttachmentForOwnerRow struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (GetAttachmentForOwnerRow, error) {
row := q.db.QueryRow(ctx, getAttachmentForOwner, arg.ID, arg.OwnerID)
var i Attachment
var i GetAttachmentForOwnerRow
err := row.Scan(
&i.ID,
&i.ChatID,
@@ -297,15 +343,30 @@ type ListStalePendingAttachmentsParams struct {
RowLimit int32
}
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]Attachment, error) {
type ListStalePendingAttachmentsRow struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]ListStalePendingAttachmentsRow, error) {
rows, err := q.db.Query(ctx, listStalePendingAttachments, arg.CreatedBefore, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Attachment{}
items := []ListStalePendingAttachmentsRow{}
for rows.Next() {
var i Attachment
var i ListStalePendingAttachmentsRow
if err := rows.Scan(
&i.ID,
&i.ChatID,
@@ -346,9 +407,24 @@ type MarkAttachmentReadyParams struct {
ID uuid.UUID
}
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (Attachment, error) {
type MarkAttachmentReadyRow struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (MarkAttachmentReadyRow, error) {
row := q.db.QueryRow(ctx, markAttachmentReady, arg.ObjectKey, arg.ID)
var i Attachment
var i MarkAttachmentReadyRow
err := row.Scan(
&i.ID,
&i.ChatID,
@@ -126,3 +126,32 @@ func (q *Queries) GetMessageIdempotency(ctx context.Context, arg GetMessageIdemp
err := row.Scan(&i.MessageID, &i.RequestHash)
return i, err
}
const lookupMessageIdempotency = `-- name: LookupMessageIdempotency :one
SELECT message_id, request_hash
FROM message_idempotency
WHERE actor_id = $1
AND chat_id = $2
AND key = $3
AND expires_at > now()
`
type LookupMessageIdempotencyParams struct {
ActorID uuid.UUID
ChatID uuid.UUID
Key string
}
type LookupMessageIdempotencyRow struct {
MessageID pgtype.UUID
RequestHash []byte
}
// Read-only replay lookup used before attachment-state validation. A live key
// returns the stored message; an expired key is ignored and may be claimed.
func (q *Queries) LookupMessageIdempotency(ctx context.Context, arg LookupMessageIdempotencyParams) (LookupMessageIdempotencyRow, error) {
row := q.db.QueryRow(ctx, lookupMessageIdempotency, arg.ActorID, arg.ChatID, arg.Key)
var i LookupMessageIdempotencyRow
err := row.Scan(&i.MessageID, &i.RequestHash)
return i, err
}
@@ -12,18 +12,62 @@ import (
)
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
ErrorCode pgtype.Text
CreatedAt time.Time
UpdatedAt time.Time
PipelineVersion int32
StagingKey pgtype.Text
ReadyAt pgtype.Timestamptz
FailedAt pgtype.Timestamptz
}
type AttachmentJob struct {
JobID uuid.UUID
AttachmentID uuid.UUID
PipelineVersion int32
SourceKey string
Attempt int32
MaxAttempts int32
Status string
AvailableAt time.Time
LeaseOwner pgtype.Text
LeaseExpiresAt pgtype.Timestamptz
LastErrorCode pgtype.Text
ReplayCount int32
CreatedAt time.Time
UpdatedAt time.Time
CompletedAt pgtype.Timestamptz
}
type AttachmentJobEvent struct {
ID int64
JobID uuid.UUID
Event string
Attempt pgtype.Int4
Detail []byte
CreatedAt time.Time
}
type AttachmentVariant struct {
AttachmentID uuid.UUID
PipelineVersion int32
Name string
ContentType string
SizeBytes int64
Width int32
Height int32
Sha256 string
ObjectKey string
CreatedAt time.Time
}
type Chat struct {
@@ -62,6 +106,22 @@ type MessageIdempotency struct {
ExpiresAt time.Time
}
type OutboxMessage struct {
ID int64
JobID uuid.UUID
Attempt int32
Kind string
RoutingKey string
Payload []byte
AvailableAt time.Time
PublishedAt pgtype.Timestamptz
ClaimedBy pgtype.Text
ClaimedUntil pgtype.Timestamptz
PublishAttempts int32
LastError pgtype.Text
CreatedAt time.Time
}
type Session struct {
TokenHash []byte
UserID uuid.UUID
@@ -56,6 +56,61 @@ func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraf
return created, nil
}
// Replay returns the stored message for a live Idempotency-Key without
// touching attachment state. The caller uses it before attachment validation so
// a replay stays 201 even if a linked attachment later failed.
func (r *MessageRepository) Replay(
ctx context.Context,
draft domain.MessageDraft,
) (domain.Message, bool, error) {
var (
replayed domain.Message
found bool
)
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
stored, err := queries.LookupMessageIdempotency(ctx, sqlcgen.LookupMessageIdempotencyParams{
ActorID: draft.SenderID,
ChatID: draft.ChatID,
Key: draft.Idempotency.Key,
})
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return mapError(err)
}
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
return domain.ErrIdempotency
}
if !stored.MessageID.Valid {
return errors.New("idempotency record without a message")
}
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
if err != nil {
return mapError(err)
}
replayed = mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
if err != nil {
return err
}
found = true
return nil
})
if err != nil {
return domain.Message{}, false, fmt.Errorf("replay idempotent message: %w", mapError(err))
}
return replayed, found, nil
}
// createIdempotent stores the message and its Idempotency-Key in one
// transaction: either both are committed or neither, so a replay never observes
// a claimed key whose message is missing. Claiming is a single statement, so
@@ -0,0 +1,150 @@
-- +goose Up
-- Lab5 async attachment pipeline: durable intent (jobs + transactional outbox),
-- per-version results (variants), and operator audit (events).
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
status IN ('pending', 'queued', 'processing', 'ready', 'failed')
) NOT VALID;
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_status_check;
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
(status IN ('ready', 'queued', 'processing') AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL) OR
status = 'pending'
) NOT VALID;
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_error_consistency;
ALTER TABLE attachments
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1
CHECK (pipeline_version >= 1),
ADD COLUMN staging_key text,
ADD COLUMN ready_at timestamptz,
ADD COLUMN failed_at timestamptz;
CREATE UNIQUE INDEX attachments_staging_key_key
ON attachments (staging_key)
WHERE staging_key IS NOT NULL;
CREATE INDEX attachments_pipeline_status_idx
ON attachments (status, pipeline_version);
-- One logical job per (attachment, pipeline version). job_id is stable across
-- redelivery; attempt is the managed attempt number (1-based).
CREATE TABLE attachment_jobs (
job_id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
source_key text NOT NULL,
attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1),
max_attempts integer NOT NULL CHECK (max_attempts BETWEEN 1 AND 100),
status text NOT NULL CHECK (
status IN ('queued', 'processing', 'ready', 'failed', 'superseded')
),
available_at timestamptz NOT NULL DEFAULT now(),
lease_owner text,
lease_expires_at timestamptz,
last_error_code text,
replay_count integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
CONSTRAINT attachment_jobs_attachment_version_key UNIQUE (attachment_id, pipeline_version),
CONSTRAINT attachment_jobs_lease_consistency CHECK (
(status = 'processing' AND lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL) OR
(status <> 'processing')
)
);
CREATE INDEX attachment_jobs_due_idx
ON attachment_jobs (status, available_at);
CREATE INDEX attachment_jobs_lease_idx
ON attachment_jobs (status, lease_expires_at);
-- Delivery ledger. available_at is the only retry scheduler; RabbitMQ is the
-- durable transport. No UNIQUE(job_id, attempt): a graceful shutdown may
-- re-publish the same attempt, and duplicates are harmless (worker CAS).
CREATE TABLE outbox_messages (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
attempt integer NOT NULL CHECK (attempt >= 1),
kind text NOT NULL DEFAULT 'publish',
routing_key text NOT NULL,
payload jsonb NOT NULL,
available_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
claimed_by text,
claimed_until timestamptz,
publish_attempts integer NOT NULL DEFAULT 0,
last_error text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX outbox_due_idx
ON outbox_messages (available_at, id)
WHERE published_at IS NULL;
CREATE INDEX outbox_claim_expiry_idx
ON outbox_messages (claimed_until)
WHERE published_at IS NULL AND claimed_by IS NOT NULL;
-- Effect key (attachment_id, pipeline_version, name). The primary key is the
-- idempotency boundary for redelivery and versioned pipelines.
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
content_type text NOT NULL CHECK (
content_type IN ('image/jpeg', 'image/png', 'image/webp')
),
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
object_key text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (attachment_id, pipeline_version, name)
);
CREATE TABLE attachment_job_events (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
event text NOT NULL,
attempt integer,
detail jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX attachment_job_events_job_idx
ON attachment_job_events (job_id, created_at);
-- +goose Down
DROP TABLE attachment_job_events;
DROP TABLE attachment_variants;
DROP TABLE outbox_messages;
DROP TABLE attachment_jobs;
DROP INDEX attachments_pipeline_status_idx;
DROP INDEX attachments_staging_key_key;
ALTER TABLE attachments
DROP COLUMN failed_at,
DROP COLUMN ready_at,
DROP COLUMN staging_key,
DROP COLUMN pipeline_version;
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
(status = 'ready' AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL) OR
status = 'pending'
);
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
status IN ('pending', 'ready', 'failed')
);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,135 @@
//go:build integration
package postgres_test
import (
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type PipelineSuite struct {
BaseSuite
}
func TestPipelineSuite(t *testing.T) {
suite.Run(t, new(PipelineSuite))
}
func (s *PipelineSuite) attachmentDraft(chat domain.Chat, owner domain.User, version int) (domain.AttachmentDraft, domain.Job) {
s.T().Helper()
id, err := uuid.NewV7()
s.Require().NoError(err)
jobID, err := uuid.NewV7()
s.Require().NoError(err)
draft := domain.AttachmentDraft{
ID: id,
ChatID: chat.ID,
OwnerID: owner.ID,
ObjectKey: domain.OriginalObjectKey(chat.ID, id),
StagingKey: domain.StagingUploadKey(chat.ID, id),
Filename: "photo.png",
ContentType: "image/png",
SizeBytes: 10,
SHA256: strings.Repeat("a", 64),
Status: domain.AttachmentQueued,
PipelineVersion: version,
}
job := domain.Job{
ID: jobID,
AttachmentID: id,
PipelineVersion: version,
SourceKey: draft.StagingKey,
Attempt: 1,
MaxAttempts: 5,
CreatedAt: time.Now().UTC(),
}
return draft, job
}
func (s *PipelineSuite) TestCreateClaimCompleteAndIdempotentRedelivery() {
alice := s.createUser("alice")
bob := s.createUser("bob")
chat := s.createChat(alice, bob)
draft, job := s.attachmentDraft(chat, alice, 1)
repo := s.store.Pipeline()
created, err := repo.CreateQueued(s.T().Context(), draft, job)
s.Require().NoError(err)
s.Equal(domain.AttachmentQueued, created.Status)
s.Equal(1, created.PipelineVersion)
message := domain.NewJobMessage(job)
claim, err := repo.ClaimJob(s.T().Context(), message, "lease-1", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
s.Equal(domain.AttachmentProcessing, claim.Attachment.Status)
duplicate, err := repo.ClaimJob(s.T().Context(), message, "lease-2", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimBusyLease, duplicate.Outcome)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
s.Require().NoError(err)
s.True(ok)
ready, err := repo.GetForMember(s.T().Context(), bob.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentReady, ready.Status)
stored, err := repo.ListVariants(s.T().Context(), draft.ID, 1)
s.Require().NoError(err)
s.Require().Len(stored, 1)
s.Equal(domain.VariantThumbnail, stored[0].Name)
// A redelivery after ready is a no-op, even with the same attempt.
again, err := repo.ClaimJob(s.T().Context(), message, "lease-3", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAlreadyReady, again.Outcome)
}
func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
alice := s.createUser("alice")
chat := s.createChat(alice)
draft, job := s.attachmentDraft(chat, alice, 1)
job.MaxAttempts = 1
repo := s.store.Pipeline()
_, err := repo.CreateQueued(s.T().Context(), draft, job)
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Millisecond)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
time.Sleep(10 * time.Millisecond)
reaped, err := repo.ReapExpiredLeases(s.T().Context(), 10)
s.Require().NoError(err)
s.Equal(1, reaped)
dead, err := repo.GetJob(s.T().Context(), job.ID)
s.Require().NoError(err)
s.Equal(domain.JobFailed, dead.Status)
s.NotNil(dead.LastErrorCode)
s.Equal("retry_exhausted", *dead.LastErrorCode)
}
@@ -38,3 +38,13 @@ WHERE actor_id = sqlc.arg(actor_id)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE id = sqlc.arg(id);
-- Read-only replay lookup used before attachment-state validation. A live key
-- returns the stored message; an expired key is ignored and may be claimed.
-- name: LookupMessageIdempotency :one
SELECT message_id, request_hash
FROM message_idempotency
WHERE actor_id = sqlc.arg(actor_id)
AND chat_id = sqlc.arg(chat_id)
AND key = sqlc.arg(key)
AND expires_at > now();
+4
View File
@@ -22,6 +22,7 @@ type Store struct {
messages *MessageRepository
sessions *SessionRepository
attachments *AttachmentRepository
pipeline *PipelineRepository
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
@@ -67,6 +68,7 @@ func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration)
store.messages = &MessageRepository{store: store}
store.sessions = &SessionRepository{store: store}
store.attachments = &AttachmentRepository{store: store}
store.pipeline = &PipelineRepository{store: store}
return store, nil
}
@@ -81,6 +83,8 @@ func (s *Store) Sessions() *SessionRepository { return s.sessions }
func (s *Store) Attachments() *AttachmentRepository { return s.attachments }
func (s *Store) Pipeline() *PipelineRepository { return s.pipeline }
func (s *Store) Ping(ctx context.Context) error {
if err := s.pool.Ping(ctx); err != nil {
return fmt.Errorf("ping database: %w", err)
+42 -6
View File
@@ -56,11 +56,14 @@ func (h *Handler) DownloadAttachment(
ctx context.Context,
params oas.DownloadAttachmentParams,
) (oas.DownloadAttachmentRes, error) {
if variant, ok := params.Variant.Get(); ok && variant != oas.DownloadAttachmentVariantOriginal {
return nil, fmt.Errorf("%w: variant %q is not available", domain.ErrNotFound, variant)
variant := domain.VariantOriginal
if requested, ok := params.Variant.Get(); ok {
variant = domain.VariantName(requested)
}
attachment, body, err := h.attachments.Open(ctx, caller(ctx), params.AttachmentID)
attachment, metadata, body, err := h.attachments.OpenVariant(
ctx, caller(ctx), params.AttachmentID, variant,
)
if err != nil {
return nil, err
}
@@ -73,7 +76,7 @@ func (h *Handler) DownloadAttachment(
requestID := oas.NewOptString(requestIDFromContext(ctx))
reader := closeOnEOF{ReadCloser: body}
switch attachment.ContentType {
switch metadata.ContentType {
case "image/png":
return &oas.DownloadAttachmentOKImagePNGHeaders{
XRequestID: requestID,
@@ -84,6 +87,11 @@ func (h *Handler) DownloadAttachment(
XRequestID: requestID,
Response: oas.DownloadAttachmentOKImageJpeg{Data: reader},
}, nil
case "image/webp":
return &oas.DownloadAttachmentOKImageWEBPHeaders{
XRequestID: requestID,
Response: oas.DownloadAttachmentOKImageWEBP{Data: reader},
}, nil
default:
_ = body.Close()
@@ -110,11 +118,11 @@ func attachmentResponse(attachment domain.Attachment) oas.Attachment {
Filename: attachment.Filename,
SizeBytes: int(attachment.SizeBytes),
SHA256: attachment.SHA256,
Status: oas.AttachmentStatusReady,
Variants: []oas.Variant{},
Status: attachmentStatus(attachment.Status),
ErrorCode: oas.NilString{Null: true},
CreatedAt: attachment.CreatedAt,
UpdatedAt: attachment.UpdatedAt,
Variants: make([]oas.Variant, 0, len(attachment.Variants)),
}
switch attachment.ContentType {
@@ -130,9 +138,37 @@ func attachmentResponse(attachment domain.Attachment) oas.Attachment {
response.ErrorCode = oas.NilString{Value: *attachment.ErrorCode}
}
for _, variant := range attachment.Variants {
response.Variants = append(response.Variants, oas.Variant{
Name: oas.VariantName(variant.Name),
ContentType: oas.VariantContentType(variant.ContentType),
SizeBytes: int(variant.SizeBytes),
Width: variant.Width,
Height: variant.Height,
SHA256: variant.SHA256,
})
}
return response
}
func attachmentStatus(status domain.AttachmentStatus) oas.AttachmentStatus {
switch status {
case domain.AttachmentQueued:
return oas.AttachmentStatusQueued
case domain.AttachmentProcessing:
return oas.AttachmentStatusProcessing
case domain.AttachmentReady:
return oas.AttachmentStatusReady
case domain.AttachmentFailed:
return oas.AttachmentStatusFailed
default:
// Pending is internal and never reaches the transport; map it to the
// closest public state rather than inventing a new enum value.
return oas.AttachmentStatusQueued
}
}
type closeOnEOF struct {
io.ReadCloser
}
+2
View File
@@ -60,6 +60,8 @@ func statusForDomainError(err error) int {
errors.Is(err, domain.ErrUnknownMember),
errors.Is(err, domain.ErrInvalidCursor):
return http.StatusBadRequest
case errors.Is(err, domain.ErrRateLimited):
return http.StatusTooManyRequests
case errors.Is(err, domain.ErrTooLarge):
return http.StatusRequestEntityTooLarge
case errors.Is(err, domain.ErrUnsupportedMedia):
+1 -1
View File
@@ -176,7 +176,7 @@ func (e *Extensions) complete(w http.ResponseWriter, r *http.Request, userID uui
return err
}
return writeJSON(w, http.StatusOK, attachmentResponse(attachment))
return writeJSON(w, http.StatusAccepted, attachmentResponse(attachment))
}
func decodeJSON(r *http.Request, target any) error {
+5 -1
View File
@@ -56,7 +56,11 @@ type SessionService interface {
type AttachmentService interface {
Upload(ctx context.Context, input attachmentService.UploadInput) (domain.Attachment, error)
Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error)
Open(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error)
OpenVariant(
ctx context.Context,
callerID, id uuid.UUID,
name domain.VariantName,
) (domain.Attachment, domain.Variant, io.ReadCloser, error)
Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error)
Complete(ctx context.Context, ownerID, id uuid.UUID, sha256 string) (domain.Attachment, error)
}
@@ -357,8 +357,14 @@ func (s *AttachmentStatus) Decode(d *jx.Decoder) error {
}
// Try to use constant string.
switch AttachmentStatus(v) {
case AttachmentStatusQueued:
*s = AttachmentStatusQueued
case AttachmentStatusProcessing:
*s = AttachmentStatusProcessing
case AttachmentStatusReady:
*s = AttachmentStatusReady
case AttachmentStatusFailed:
*s = AttachmentStatusFailed
default:
*s = AttachmentStatus(v)
}
@@ -4592,7 +4592,7 @@ func encodeUploadAttachmentResponse(response UploadAttachmentRes, w http.Respons
}
}
}
w.WriteHeader(201)
w.WriteHeader(202)
e := new(jx.Encoder)
response.Response.Encode(e)
@@ -230,21 +230,33 @@ func (*AttachmentHeaders) uploadAttachmentRes() {}
type AttachmentStatus string
const (
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusQueued AttachmentStatus = "queued"
AttachmentStatusProcessing AttachmentStatus = "processing"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
)
// AllValues returns all AttachmentStatus values.
func (AttachmentStatus) AllValues() []AttachmentStatus {
return []AttachmentStatus{
AttachmentStatusQueued,
AttachmentStatusProcessing,
AttachmentStatusReady,
AttachmentStatusFailed,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s AttachmentStatus) MarshalText() ([]byte, error) {
switch s {
case AttachmentStatusQueued:
return []byte(s), nil
case AttachmentStatusProcessing:
return []byte(s), nil
case AttachmentStatusReady:
return []byte(s), nil
case AttachmentStatusFailed:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
@@ -253,9 +265,18 @@ func (s AttachmentStatus) MarshalText() ([]byte, error) {
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *AttachmentStatus) UnmarshalText(data []byte) error {
switch AttachmentStatus(data) {
case AttachmentStatusQueued:
*s = AttachmentStatusQueued
return nil
case AttachmentStatusProcessing:
*s = AttachmentStatusProcessing
return nil
case AttachmentStatusReady:
*s = AttachmentStatusReady
return nil
case AttachmentStatusFailed:
*s = AttachmentStatusFailed
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
@@ -818,13 +839,19 @@ func (*DownloadAttachmentServiceUnavailable) downloadAttachmentRes() {}
type DownloadAttachmentVariant string
const (
DownloadAttachmentVariantOriginal DownloadAttachmentVariant = "original"
DownloadAttachmentVariantOriginal DownloadAttachmentVariant = "original"
DownloadAttachmentVariantThumbnail DownloadAttachmentVariant = "thumbnail"
DownloadAttachmentVariantCrop DownloadAttachmentVariant = "crop"
DownloadAttachmentVariantOptimized DownloadAttachmentVariant = "optimized"
)
// AllValues returns all DownloadAttachmentVariant values.
func (DownloadAttachmentVariant) AllValues() []DownloadAttachmentVariant {
return []DownloadAttachmentVariant{
DownloadAttachmentVariantOriginal,
DownloadAttachmentVariantThumbnail,
DownloadAttachmentVariantCrop,
DownloadAttachmentVariantOptimized,
}
}
@@ -833,6 +860,12 @@ func (s DownloadAttachmentVariant) MarshalText() ([]byte, error) {
switch s {
case DownloadAttachmentVariantOriginal:
return []byte(s), nil
case DownloadAttachmentVariantThumbnail:
return []byte(s), nil
case DownloadAttachmentVariantCrop:
return []byte(s), nil
case DownloadAttachmentVariantOptimized:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
@@ -844,6 +877,15 @@ func (s *DownloadAttachmentVariant) UnmarshalText(data []byte) error {
case DownloadAttachmentVariantOriginal:
*s = DownloadAttachmentVariantOriginal
return nil
case DownloadAttachmentVariantThumbnail:
*s = DownloadAttachmentVariantThumbnail
return nil
case DownloadAttachmentVariantCrop:
*s = DownloadAttachmentVariantCrop
return nil
case DownloadAttachmentVariantOptimized:
*s = DownloadAttachmentVariantOptimized
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
@@ -234,8 +234,14 @@ func (s *AttachmentHeaders) Validate() error {
func (s AttachmentStatus) Validate() error {
switch s {
case "queued":
return nil
case "processing":
return nil
case "ready":
return nil
case "failed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -1103,6 +1109,12 @@ func (s DownloadAttachmentVariant) Validate() error {
switch s {
case "original":
return nil
case "thumbnail":
return nil
case "crop":
return nil
case "optimized":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -200,54 +200,61 @@ func (_c *MockAttachmentService_Get_Call) RunAndReturn(run func(ctx context.Cont
return _c
}
// Open provides a mock function for the type MockAttachmentService
func (_mock *MockAttachmentService) Open(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error) {
ret := _mock.Called(ctx, callerID, id)
// OpenVariant provides a mock function for the type MockAttachmentService
func (_mock *MockAttachmentService) OpenVariant(ctx context.Context, callerID uuid.UUID, id uuid.UUID, name domain.VariantName) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
ret := _mock.Called(ctx, callerID, id, name)
if len(ret) == 0 {
panic("no return value specified for Open")
panic("no return value specified for OpenVariant")
}
var r0 domain.Attachment
var r1 io.ReadCloser
var r2 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, io.ReadCloser, error)); ok {
return returnFunc(ctx, callerID, id)
var r1 domain.Variant
var r2 io.ReadCloser
var r3 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) (domain.Attachment, domain.Variant, io.ReadCloser, error)); ok {
return returnFunc(ctx, callerID, id, name)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
r0 = returnFunc(ctx, callerID, id)
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) domain.Attachment); ok {
r0 = returnFunc(ctx, callerID, id, name)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) io.ReadCloser); ok {
r1 = returnFunc(ctx, callerID, id)
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) domain.Variant); ok {
r1 = returnFunc(ctx, callerID, id, name)
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).(io.ReadCloser)
r1 = ret.Get(1).(domain.Variant)
}
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) io.ReadCloser); ok {
r2 = returnFunc(ctx, callerID, id, name)
} else {
if ret.Get(2) != nil {
r2 = ret.Get(2).(io.ReadCloser)
}
}
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
r2 = returnFunc(ctx, callerID, id)
if returnFunc, ok := ret.Get(3).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) error); ok {
r3 = returnFunc(ctx, callerID, id, name)
} else {
r2 = ret.Error(2)
r3 = ret.Error(3)
}
return r0, r1, r2
return r0, r1, r2, r3
}
// MockAttachmentService_Open_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Open'
type MockAttachmentService_Open_Call struct {
// MockAttachmentService_OpenVariant_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OpenVariant'
type MockAttachmentService_OpenVariant_Call struct {
*mock.Call
}
// Open is a helper method to define mock.On call
// OpenVariant is a helper method to define mock.On call
// - ctx context.Context
// - callerID uuid.UUID
// - id uuid.UUID
func (_e *MockAttachmentService_Expecter) Open(ctx any, callerID any, id any) *MockAttachmentService_Open_Call {
return &MockAttachmentService_Open_Call{Call: _e.mock.On("Open", ctx, callerID, id)}
// - name domain.VariantName
func (_e *MockAttachmentService_Expecter) OpenVariant(ctx any, callerID any, id any, name any) *MockAttachmentService_OpenVariant_Call {
return &MockAttachmentService_OpenVariant_Call{Call: _e.mock.On("OpenVariant", ctx, callerID, id, name)}
}
func (_c *MockAttachmentService_Open_Call) Run(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID)) *MockAttachmentService_Open_Call {
func (_c *MockAttachmentService_OpenVariant_Call) Run(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID, name domain.VariantName)) *MockAttachmentService_OpenVariant_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -261,21 +268,26 @@ func (_c *MockAttachmentService_Open_Call) Run(run func(ctx context.Context, cal
if args[2] != nil {
arg2 = args[2].(uuid.UUID)
}
var arg3 domain.VariantName
if args[3] != nil {
arg3 = args[3].(domain.VariantName)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockAttachmentService_Open_Call) Return(attachment domain.Attachment, readCloser io.ReadCloser, err error) *MockAttachmentService_Open_Call {
_c.Call.Return(attachment, readCloser, err)
func (_c *MockAttachmentService_OpenVariant_Call) Return(attachment domain.Attachment, variant domain.Variant, readCloser io.ReadCloser, err error) *MockAttachmentService_OpenVariant_Call {
_c.Call.Return(attachment, variant, readCloser, err)
return _c
}
func (_c *MockAttachmentService_Open_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error)) *MockAttachmentService_Open_Call {
func (_c *MockAttachmentService_OpenVariant_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID, name domain.VariantName) (domain.Attachment, domain.Variant, io.ReadCloser, error)) *MockAttachmentService_OpenVariant_Call {
_c.Call.Return(run)
return _c
}
+561
View File
@@ -0,0 +1,561 @@
// Package worker consumes attachment jobs, enforces the lease, produces the
// contract variants and acknowledges only after the durable result is
// committed.
package worker
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"math/rand/v2"
"os"
"strings"
"sync"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
"mtusi-messenger/internal/broker"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/failpoint"
"mtusi-messenger/internal/imagecheck"
"mtusi-messenger/internal/imageproc"
"mtusi-messenger/internal/platform/objectstore"
)
type Repository interface {
ClaimJob(
ctx context.Context,
message domain.JobMessage,
leaseOwner string,
leaseTTL time.Duration,
) (domain.ClaimResult, error)
Heartbeat(ctx context.Context, jobID uuid.UUID, attempt int, leaseOwner string, leaseTTL time.Duration) (bool, error)
CompleteJob(ctx context.Context, jobID uuid.UUID, attempt int, leaseOwner string, variants []domain.Variant) (bool, error)
RetryJob(
ctx context.Context,
jobID uuid.UUID,
attempt int,
leaseOwner, errorCode string,
nextAvailable time.Time,
sameAttempt bool,
kind string,
) (failed bool, err error)
FailJob(ctx context.Context, jobID uuid.UUID, attempt int, leaseOwner, errorCode string) (bool, error)
MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error
}
type Store interface {
Open(ctx context.Context, key string) (io.ReadCloser, objectstore.Object, error)
Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error
Delete(ctx context.Context, key string) error
}
type Consumer interface {
Consume(ctx context.Context, handler broker.Handler) error
Connected() bool
}
type Config struct {
Concurrency int
LeaseTTL time.Duration
Heartbeat time.Duration
JobTimeout time.Duration
RetryBase time.Duration
RetryCap time.Duration
MaxUploadBytes int64
MaxImagePixels int64
Owner string
}
type Worker struct {
repo Repository
store Store
config Config
log *slog.Logger
consumer Consumer
mu sync.RWMutex
running bool
}
func New(repo Repository, store Store, config Config, log *slog.Logger) *Worker {
if log == nil {
log = slog.Default()
}
if config.Owner == "" {
config.Owner = "worker-" + uuid.NewString()
}
return &Worker{repo: repo, store: store, config: config, log: log}
}
// Run starts Concurrency consumer channels. It returns when the context is
// cancelled or one consumer fails; the caller recreates the broker connection.
func (w *Worker) Run(ctx context.Context, consumer Consumer) error {
w.consumer = consumer
w.setRunning(true)
defer w.setRunning(false)
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
var (
wg sync.WaitGroup
once sync.Once
firstErr error
)
for range w.config.Concurrency {
wg.Add(1)
go func() {
defer wg.Done()
if err := consumer.Consume(runCtx, w.handle); err != nil && runCtx.Err() == nil {
once.Do(func() {
firstErr = err
cancel()
})
}
}()
}
wg.Wait()
return firstErr
}
func (w *Worker) setRunning(value bool) {
w.mu.Lock()
defer w.mu.Unlock()
w.running = value
}
func (w *Worker) Ready() (consumerRunning, brokerConnected bool) {
w.mu.RLock()
running := w.running
w.mu.RUnlock()
if w.consumer == nil {
return running, false
}
return running, w.consumer.Connected()
}
func (w *Worker) handle(ctx context.Context, delivery amqp.Delivery) broker.Outcome {
message, err := domain.ParseJobMessage(delivery.Body)
if err != nil {
w.log.WarnContext(ctx, "invalid job payload moved to DLQ", slog.Any("error", err))
return broker.Drop
}
result, err := w.repo.ClaimJob(ctx, message, w.config.Owner, w.config.LeaseTTL)
if err != nil {
w.log.WarnContext(ctx, "claim job failed", slog.String("job_id", message.JobID.String()), slog.Any("error", err))
return broker.Requeue
}
switch result.Outcome {
case domain.ClaimAcquired:
w.log.InfoContext(ctx, "job claimed",
slog.String("job_id", message.JobID.String()),
slog.String("attachment_id", message.AttachmentID.String()),
slog.Int("attempt", message.Attempt),
slog.Int("pipeline_version", message.PipelineVersion),
)
case domain.ClaimAlreadyReady, domain.ClaimAlreadyFailed, domain.ClaimSuperseded,
domain.ClaimStaleAttempt, domain.ClaimFutureAttempt, domain.ClaimBusyLease,
domain.ClaimNotDue, domain.ClaimVersionStale, domain.ClaimJobNotFound:
w.log.DebugContext(ctx, "job delivery is a no-op",
slog.String("job_id", message.JobID.String()),
slog.String("outcome", string(result.Outcome)),
)
return broker.Ack
default:
return broker.Ack
}
return w.process(ctx, result)
}
func (w *Worker) process(
ctx context.Context,
result domain.ClaimResult,
) broker.Outcome {
job := result.Job
attachment := result.Attachment
failpoint.Check("WORKER_AFTER_CLAIM", job.ID)
switch failpoint.Mode("WORKER_FAIL", job.ID) {
case "permanent":
return w.fail(ctx, job, permanentError{code: "injected_failure", err: errors.New("injected permanent worker failure")})
case "transient":
return w.fail(ctx, job, errors.New("injected transient worker failure"))
}
jobCtx, cancel := context.WithTimeout(ctx, w.config.JobTimeout)
defer cancel()
leaseLost := false
heartbeatDone := make(chan struct{})
go func() {
defer close(heartbeatDone)
ticker := time.NewTicker(w.config.Heartbeat)
defer ticker.Stop()
for {
select {
case <-jobCtx.Done():
return
case <-ticker.C:
ok, err := w.repo.Heartbeat(jobCtx, job.ID, job.Attempt, w.config.Owner, w.config.LeaseTTL)
if err != nil || !ok {
leaseLost = true
cancel()
return
}
}
}
}()
// The hook runs after the heartbeat starts: it can be paused to test a
// genuinely stuck (not merely slow) worker without consuming every attempt.
failpoint.Sleep("WORKER_SLEEP_AFTER_CLAIM", job.ID)
watchdog := time.AfterFunc(w.config.JobTimeout+30*time.Second, func() {
w.log.ErrorContext(ctx, "worker job watchdog fired",
slog.String("job_id", job.ID.String()),
slog.String("attachment_id", job.AttachmentID.String()),
)
os.Exit(70)
})
defer watchdog.Stop()
err := w.runJob(jobCtx, job, attachment)
cancel()
<-heartbeatDone
if leaseLost {
w.log.WarnContext(ctx, "lease lost; reaper will requeue",
slog.String("job_id", job.ID.String()),
)
return broker.Ack
}
if err == nil {
failpoint.Check("WORKER_AFTER_COMMIT", job.ID)
return broker.Ack
}
return w.fail(ctx, job, err)
}
func (w *Worker) runJob(
ctx context.Context,
job domain.Job,
attachment domain.Attachment,
) error {
params, ok := imageproc.Pipeline(job.PipelineVersion)
if !ok {
return permanentError{code: "unsupported_pipeline", err: fmt.Errorf("pipeline %d", job.PipelineVersion)}
}
sourceKey := job.SourceKey
if sourceKey == "" {
sourceKey = attachment.StagingKey
}
if sourceKey == "" {
sourceKey = attachment.ObjectKey
}
file, size, sum, err := w.spoolSource(ctx, sourceKey)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
defer func() { _ = os.Remove(file.Name()) }()
if size != attachment.SizeBytes || sum != attachment.SHA256 {
return permanentError{code: "source_corrupt", err: errors.New("source bytes do not match metadata")}
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("rewind source: %w", err)
}
if _, err := imagecheck.Validate(file, w.config.MaxImagePixels); err != nil {
return permanentError{code: "invalid_image", err: err}
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("rewind source: %w", err)
}
img, _, err := imageproc.Load(file.Name(), w.config.MaxImagePixels)
if err != nil {
return permanentError{code: "invalid_image", err: err}
}
if sourceKey != attachment.ObjectKey {
if _, err := file.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("rewind original: %w", err)
}
if err := w.store.Put(
ctx, attachment.ObjectKey, file, size, attachment.ContentType,
map[string]string{"sha256": sum},
); err != nil {
return fmt.Errorf("publish original: %w", err)
}
}
variants := make([]domain.Variant, 0, 3)
generated := []func() (imageproc.Image, error){
func() (imageproc.Image, error) { return imageproc.Thumbnail(img, params) },
func() (imageproc.Image, error) { return imageproc.Crop(img, params) },
func() (imageproc.Image, error) { return imageproc.Optimized(img, params) },
}
for idx, generate := range generated {
variantImage, err := generate()
if err != nil {
return permanentError{code: "processing_failed", err: err}
}
key := domain.VariantObjectKey(attachment.ChatID, attachment.ID, job.PipelineVersion, variantImage.Name)
if err := w.store.Put(
ctx, key, bytes.NewReader(variantImage.Data), variantImage.SizeBytes,
variantImage.ContentType, map[string]string{"sha256": variantImage.SHA256},
); err != nil {
return fmt.Errorf("publish variant %s: %w", variantImage.Name, err)
}
if idx == 0 {
failpoint.Check("WORKER_AFTER_FIRST_VARIANT", job.ID)
}
variants = append(variants, domain.Variant{
Name: variantImage.Name,
ContentType: variantImage.ContentType,
SizeBytes: variantImage.SizeBytes,
Width: variantImage.Width,
Height: variantImage.Height,
SHA256: variantImage.SHA256,
ObjectKey: key,
})
}
failpoint.Check("WORKER_AFTER_PUT", job.ID)
completed, err := w.repo.CompleteJob(ctx, job.ID, job.Attempt, w.config.Owner, variants)
if err != nil {
return err
}
if !completed {
w.log.WarnContext(ctx, "completion CAS lost", slog.String("job_id", job.ID.String()))
return nil
}
w.log.InfoContext(ctx, "attachment ready",
slog.String("job_id", job.ID.String()),
slog.String("attachment_id", attachment.ID.String()),
slog.Int("pipeline_version", job.PipelineVersion),
)
if strings.HasPrefix(sourceKey, "staging/") && sourceKey != attachment.ObjectKey {
if err := w.store.Delete(ctx, sourceKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
w.log.WarnContext(ctx, "staging delete failed", slog.String("object_key", sourceKey), slog.Any("error", err))
return nil
}
if sourceKey == attachment.StagingKey {
if err := w.repo.MarkStagingDeleted(ctx, attachment.ID, sourceKey); err != nil {
w.log.WarnContext(ctx, "clear staging projection failed", slog.Any("error", err))
}
}
}
return nil
}
func (w *Worker) spoolSource(ctx context.Context, key string) (*os.File, int64, string, error) {
body, _, err := w.store.Open(ctx, key)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, 0, "", permanentError{code: "source_missing", err: err}
}
return nil, 0, "", fmt.Errorf("open source: %w", err)
}
defer body.Close()
file, err := os.CreateTemp("", "lab5-worker-*")
if err != nil {
return nil, 0, "", fmt.Errorf("create worker spool: %w", err)
}
cleanup := func() {
_ = file.Close()
_ = os.Remove(file.Name())
}
hasher := sha256.New()
limited := io.LimitReader(body, w.config.MaxUploadBytes+1)
buffer := make([]byte, 64<<10)
size, err := io.CopyBuffer(io.MultiWriter(file, hasher), limited, buffer)
if err != nil {
cleanup()
return nil, 0, "", fmt.Errorf("copy source: %w", err)
}
if size > w.config.MaxUploadBytes {
cleanup()
return nil, 0, "", permanentError{code: "source_too_large", err: fmt.Errorf("source exceeds %d bytes", w.config.MaxUploadBytes)}
}
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
}
func (w *Worker) fail(ctx context.Context, job domain.Job, err error) broker.Outcome {
if ctx.Err() != nil {
// Parent cancellation means graceful shutdown. Keep the attempt number:
// an operator restart must not consume the processing budget. The job
// context is already cancelled, so use a short detached context for the
// durable requeue.
retryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
failed, retryErr := w.repo.RetryJob(
retryCtx, job.ID, job.Attempt, w.config.Owner, "shutdown",
time.Now().Add(time.Second), true, "shutdown",
)
if retryErr != nil {
return broker.Requeue
}
_ = failed
return broker.Ack
}
code := "processing_failed"
permanent := false
var typed permanentError
if errors.As(err, &typed) {
code = typed.code
permanent = true
}
if errors.Is(err, domain.ErrValidation) || errors.Is(err, domain.ErrUnsupportedMedia) ||
errors.Is(err, domain.ErrTooLarge) || errors.Is(err, domain.ErrConflict) {
permanent = true
if code == "processing_failed" {
code = "invalid_image"
}
}
if errors.Is(err, context.DeadlineExceeded) {
code = "processing_timeout"
permanent = false
}
if permanent {
w.log.WarnContext(ctx, "job permanently failed",
slog.String("job_id", job.ID.String()),
slog.String("error_code", code),
slog.Any("error", err),
)
ok, failErr := w.repo.FailJob(ctx, job.ID, job.Attempt, w.config.Owner, code)
if failErr != nil {
return broker.Requeue
}
if !ok {
return broker.Ack
}
return broker.Drop
}
next := time.Now().Add(w.backoff(job.Attempt))
w.log.WarnContext(ctx, "job retry scheduled",
slog.String("job_id", job.ID.String()),
slog.String("error_code", code),
slog.Time("available_at", next),
slog.Any("error", err),
)
failed, retryErr := w.repo.RetryJob(
ctx, job.ID, job.Attempt, w.config.Owner, code, next, false, "retry",
)
if retryErr != nil {
return broker.Requeue
}
if failed {
return broker.Drop
}
return broker.Ack
}
func (w *Worker) backoff(attempt int) time.Duration {
if attempt < 1 {
attempt = 1
}
capDelay := w.config.RetryCap
base := w.config.RetryBase
for range attempt - 1 {
base *= 2
if base >= capDelay {
base = capDelay
break
}
}
if base <= 0 {
return time.Second
}
return time.Duration(rand.Int64N(int64(base))) + time.Millisecond
}
type permanentError struct {
code string
err error
}
func (e permanentError) Error() string { return e.code + ": " + e.err.Error() }
func (e permanentError) Unwrap() error { return e.err }