Files
mtusi2026lab5/internal/worker/job.go
T

220 lines
4.9 KiB
Go

package worker
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"time"
"github.com/jackc/pgx/v5"
"mtusi2026-messenger/internal/db"
"mtusi2026-messenger/internal/model"
s3store "mtusi2026-messenger/internal/s3"
)
var (
errLeaseExpired = errors.New("attachment lease expired")
errMissingThumbnail = errors.New("ready attachment has no thumbnail")
errAttemptProcessing = errors.New("attachment attempt is still processing")
errAttemptUnavailable = errors.New("attachment attempt is not yet available")
errEffectChecksumMismatch = errors.New("attachment effect checksum mismatch")
)
func (w *Worker) handle(ctx context.Context, job model.AttachmentJob) error {
jobCtx, cancel := context.WithTimeout(ctx, w.cfg.Timeout)
defer cancel()
row, err := w.q.ClaimAttachmentJob(jobCtx, db.ClaimAttachmentJobParams{
ID: job.AttachmentID,
JobID: job.JobID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
LeaseUntil: time.Now().Add(w.cfg.Timeout),
})
if errors.Is(err, pgx.ErrNoRows) {
return w.duplicate(jobCtx, job)
}
if err != nil {
return err
}
w.log.Info("attachment processing", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
variants, processErr := w.process(jobCtx, row)
if processErr != nil {
resultCtx, resultCancel := context.WithTimeout(ctx, 5*time.Second)
defer resultCancel()
return w.finishFailure(resultCtx, job, processErr)
}
tx, err := w.pool.Begin(jobCtx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := w.q.WithTx(tx)
_, err = q.LockAttachmentJob(jobCtx, db.LockAttachmentJobParams{
ID: job.AttachmentID,
JobID: job.JobID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
})
if err != nil {
return err
}
for _, variant := range variants {
if err := q.CreateAttachmentVariant(jobCtx, variant); err != nil {
return err
}
}
n, err := q.CompleteAttachmentJob(jobCtx, db.CompleteAttachmentJobParams{
ID: row.ID,
Attempt: job.Attempt,
})
if err != nil {
return err
}
if n != 1 {
return errLeaseExpired
}
if err := tx.Commit(jobCtx); err != nil {
return err
}
if row.StagingKey != nil {
err := w.deleteStagingObject(ctx, *row.StagingKey)
if err != nil && ctx.Err() == nil {
w.log.Warn("delete ready attachment staging", "attachment_id", row.ID, "error", err)
}
}
w.log.Info("attachment ready", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
return nil
}
func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error {
row, err := w.q.GetAttachmentByID(ctx, job.AttachmentID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if row.JobID == nil || *row.JobID != job.JobID || row.PipelineVersion != job.PipelineVersion {
return nil
}
if row.Status == db.AttachmentStatusFailed {
return nil
}
if row.Status == db.AttachmentStatusReady {
variants, err := w.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{
AttachmentID: row.ID,
PipelineVersion: row.PipelineVersion,
})
if err != nil {
return err
}
if err := verify(ctx, w.s3, row.S3Key, row.SizeBytes, row.Sha256); err != nil {
return err
}
hasThumbnail := false
for _, variant := range variants {
if err := verify(ctx, w.s3, variant.S3Key, variant.SizeBytes, variant.Sha256); err != nil {
return err
}
if variant.Variant == db.AttachmentVariantNameThumbnail {
hasThumbnail = true
}
}
if !hasThumbnail {
return errMissingThumbnail
}
return nil
}
if row.Status == db.AttachmentStatusProcessing && row.Attempts == job.Attempt {
return errAttemptProcessing
}
if row.Attempts >= job.Attempt {
return nil
}
return errAttemptUnavailable
}
func verify(ctx context.Context, storage *s3store.Client, key string, size int, checksum string) error {
object, err := storage.Get(ctx, key)
if err != nil {
return err
}
defer object.Body.Close()
hash := sha256.New()
n, err := io.Copy(hash, io.LimitReader(object.Body, int64(size)+1))
if err != nil {
return err
}
if n != int64(size) || hex.EncodeToString(hash.Sum(nil)) != checksum {
return errEffectChecksumMismatch
}
return nil
}
func (w *Worker) deleteStagingObject(ctx context.Context, key string) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
tx, err := w.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := w.q.WithTx(tx)
row, err := q.LockAttachmentByStagingKey(ctx, key)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if row.Status != db.AttachmentStatusReady {
return nil
}
if err := w.s3.Delete(ctx, key); err != nil {
return err
}
if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil {
return err
}
return tx.Commit(ctx)
}