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:
+100
-26
@@ -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
|
||||
|
||||
@@ -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")
|
||||
)
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
@@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user