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
+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()),