lab5: исправления по ревью
Concurrent complete no longer deletes the shared verified source; admission is atomic and covers pending presign rows; relay reconciles queued jobs lost to dead-lettering; failed staging is protected until failed_retention; timestamps normalized to UTC; reprocess prefers the durable original and keeps job->attachment lock order; heartbeat errors no longer burn attempts; confirm timeout enforced; pinned images and sanitized health responses.
This commit is contained in:
@@ -64,6 +64,8 @@ func scanAttachmentRow(row rowScanner) (domain.Attachment, error) {
|
||||
}
|
||||
|
||||
attachment.Status = domain.AttachmentStatus(status)
|
||||
attachment.CreatedAt = toUTCTime(attachment.CreatedAt)
|
||||
attachment.UpdatedAt = toUTCTime(attachment.UpdatedAt)
|
||||
if errCode.Valid {
|
||||
code := errCode.String
|
||||
attachment.ErrorCode = &code
|
||||
@@ -112,6 +114,9 @@ func scanJobRow(row rowScanner) (domain.Job, error) {
|
||||
}
|
||||
|
||||
job.Status = domain.JobStatus(status)
|
||||
job.AvailableAt = toUTCTime(job.AvailableAt)
|
||||
job.CreatedAt = toUTCTime(job.CreatedAt)
|
||||
job.UpdatedAt = toUTCTime(job.UpdatedAt)
|
||||
if owner.Valid {
|
||||
job.LeaseOwner = owner.String
|
||||
}
|
||||
@@ -330,12 +335,11 @@ func (r *PipelineRepository) Admission(
|
||||
|
||||
err = r.store.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
count(*) FILTER (WHERE a.owner_id = $1)::int,
|
||||
count(*) FILTER (WHERE owner_id = $1)::int,
|
||||
count(*)::int,
|
||||
COALESCE(sum(a.size_bytes), 0)::bigint
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status IN ('queued', 'processing')`, ownerID).Scan(
|
||||
COALESCE(sum(size_bytes), 0)::bigint
|
||||
FROM attachments
|
||||
WHERE status IN ('pending', 'queued', 'processing')`, ownerID).Scan(
|
||||
&userPending, &totalPending, &stagedBytes,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -394,10 +398,15 @@ func (r *PipelineRepository) CreateQueued(
|
||||
ctx context.Context,
|
||||
draft domain.AttachmentDraft,
|
||||
job domain.Job,
|
||||
limits domain.AdmissionLimits,
|
||||
) (domain.Attachment, error) {
|
||||
var created domain.Attachment
|
||||
|
||||
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
||||
if err := checkAdmissionTx(ctx, tx, draft.OwnerID, limits); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
row := tx.QueryRow(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
@@ -1307,6 +1316,15 @@ func (r *PipelineRepository) Reprocess(
|
||||
var created domain.Job
|
||||
|
||||
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
||||
// Keep the global lock order job -> attachment, as in CompleteJob.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
SELECT 1 FROM attachment_jobs
|
||||
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
|
||||
AND pipeline_version < $2
|
||||
FOR UPDATE`, attachmentID, targetVersion); err != nil {
|
||||
return fmt.Errorf("lock superseded jobs: %w", mapError(err))
|
||||
}
|
||||
|
||||
attachmentRow := tx.QueryRow(ctx, `
|
||||
SELECT `+attachmentReturning+`
|
||||
FROM attachments WHERE id = $1 FOR UPDATE`, attachmentID)
|
||||
@@ -1320,9 +1338,9 @@ func (r *PipelineRepository) Reprocess(
|
||||
return fmt.Errorf("%w: target pipeline version must be newer", domain.ErrConflict)
|
||||
}
|
||||
|
||||
sourceKey := attachment.StagingKey
|
||||
sourceKey := attachment.ObjectKey
|
||||
if sourceKey == "" {
|
||||
sourceKey = attachment.ObjectKey
|
||||
sourceKey = attachment.StagingKey
|
||||
}
|
||||
if sourceKey == "" {
|
||||
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
|
||||
@@ -1394,6 +1412,10 @@ func (r *PipelineRepository) ReplayJob(
|
||||
jobID uuid.UUID,
|
||||
extraAttempts int,
|
||||
) (domain.Job, error) {
|
||||
if extraAttempts < 1 {
|
||||
return domain.Job{}, fmt.Errorf("%w: replay attempts must be >= 1", domain.ErrValidation)
|
||||
}
|
||||
|
||||
var replayed domain.Job
|
||||
|
||||
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
||||
@@ -1629,7 +1651,7 @@ func (r *PipelineRepository) ListReferencedKeys(
|
||||
SELECT object_key AS key FROM attachment_variants
|
||||
UNION
|
||||
SELECT staging_key AS key FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing')
|
||||
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing', 'failed')
|
||||
) referenced
|
||||
WHERE key > $1
|
||||
ORDER BY key
|
||||
@@ -1776,30 +1798,89 @@ func (r *PipelineRepository) InsertRawOutbox(
|
||||
func (r *PipelineRepository) CreatePresign(
|
||||
ctx context.Context,
|
||||
draft domain.AttachmentDraft,
|
||||
limits domain.AdmissionLimits,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
var attachment domain.Attachment
|
||||
|
||||
row := r.store.pool.QueryRow(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, status, pipeline_version, staging_key
|
||||
err := r.withTx(ctx, func(tx pgx.Tx) error {
|
||||
if err := checkAdmissionTx(ctx, tx, draft.OwnerID, limits); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
row := tx.QueryRow(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, status, pipeline_version, staging_key
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
|
||||
RETURNING `+attachmentReturning,
|
||||
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
|
||||
draft.ContentType, draft.SizeBytes, draft.SHA256,
|
||||
draft.PipelineVersion, draft.StagingKey,
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
|
||||
RETURNING `+attachmentReturning,
|
||||
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
|
||||
draft.ContentType, draft.SizeBytes, draft.SHA256,
|
||||
draft.PipelineVersion, draft.StagingKey,
|
||||
)
|
||||
|
||||
attachment, err := scanAttachmentRow(row)
|
||||
created, err := scanAttachmentRow(row)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create presign attachment: %w", mapError(err))
|
||||
}
|
||||
|
||||
attachment = created
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("create presign attachment: %w", mapError(err))
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
const admissionLockKey int64 = 0x41444d31 // "ADM1"
|
||||
|
||||
// checkAdmissionTx serializes upload admission across API replicas with a
|
||||
// transaction-scoped advisory lock, then re-counts pending/queued/processing
|
||||
// rows. This closes the check-then-act window before the row is inserted.
|
||||
func checkAdmissionTx(ctx context.Context, tx pgx.Tx, ownerID uuid.UUID, limits domain.AdmissionLimits) error {
|
||||
if limits.PerUser == 0 && limits.Total == 0 && limits.Bytes == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, admissionLockKey); err != nil {
|
||||
return fmt.Errorf("lock admission: %w", mapError(err))
|
||||
}
|
||||
|
||||
var (
|
||||
total int
|
||||
bytes int64
|
||||
)
|
||||
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT count(*)::int, COALESCE(sum(size_bytes), 0)::bigint
|
||||
FROM attachments
|
||||
WHERE status IN ('pending', 'queued', 'processing')`).Scan(&total, &bytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("admission count: %w", mapError(err))
|
||||
}
|
||||
|
||||
perUser := 0
|
||||
if limits.PerUser > 0 {
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT count(*)::int FROM attachments
|
||||
WHERE status IN ('pending', 'queued', 'processing')
|
||||
AND owner_id = $1`, ownerID).Scan(&perUser); err != nil {
|
||||
return fmt.Errorf("admission per-user count: %w", mapError(err))
|
||||
}
|
||||
}
|
||||
|
||||
if (limits.PerUser > 0 && perUser >= limits.PerUser) ||
|
||||
(limits.Total > 0 && total >= limits.Total) ||
|
||||
(limits.Bytes > 0 && bytes >= limits.Bytes) {
|
||||
return fmt.Errorf("%w: admission limit reached", domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DuplicateJob publishes another copy of a specific job attempt. It is used by
|
||||
// the fault-injection evidence to simulate duplicate delivery of an old version.
|
||||
func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID) (domain.OutboxMessage, error) {
|
||||
@@ -1832,3 +1913,48 @@ func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID)
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// ReconcileQueuedJobs republishes jobs whose only broker delivery was lost
|
||||
// (dead-lettered, dropped, or a broker data loss). The worker CAS makes an
|
||||
// extra delivery a no-op. Only one unpublished outbox row is created per job.
|
||||
func (r *PipelineRepository) ReconcileQueuedJobs(
|
||||
ctx context.Context,
|
||||
olderThan time.Duration,
|
||||
limit int,
|
||||
) (int, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tag, err := r.store.pool.Exec(ctx, `
|
||||
WITH lost AS (
|
||||
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at
|
||||
FROM attachment_jobs j
|
||||
WHERE j.status = 'queued'
|
||||
AND j.available_at < now() - $1::interval
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM outbox_messages o
|
||||
WHERE o.job_id = j.job_id AND o.published_at IS NULL
|
||||
)
|
||||
ORDER BY j.available_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
INSERT INTO outbox_messages (job_id, attempt, kind, routing_key, payload, available_at)
|
||||
SELECT job_id, attempt, 'reconcile', $3,
|
||||
jsonb_build_object(
|
||||
'schema_version', 1,
|
||||
'job_id', job_id,
|
||||
'type', $3::text,
|
||||
'attachment_id', attachment_id,
|
||||
'pipeline_version', pipeline_version,
|
||||
'attempt', attempt,
|
||||
'created_at', created_at),
|
||||
now()
|
||||
FROM lost`,
|
||||
intervalString(olderThan), limit, defaultRoutingKey)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("reconcile queued jobs: %w", mapError(err))
|
||||
}
|
||||
|
||||
return int(tag.RowsAffected()), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user