ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/gen2brain/webp"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidSource = errors.New("invalid source image")
|
||||
ErrUnsupportedPipelineVersion = errors.New("unsupported pipeline version")
|
||||
)
|
||||
|
||||
type imageVariant struct {
|
||||
Name db.AttachmentVariantName
|
||||
Data []byte
|
||||
ContentType string
|
||||
Width, Height int
|
||||
}
|
||||
|
||||
func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) {
|
||||
if row.StagingKey == nil {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
source, err := w.s3.Get(ctx, *row.StagingKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer source.Body.Close()
|
||||
|
||||
tmp, err := os.CreateTemp("", "attachment-job-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
|
||||
hash := sha256.New()
|
||||
size, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(source.Body, int64(w.maxBytes)+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if size != int64(row.SizeBytes) ||
|
||||
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
select {
|
||||
case w.decodeSlot <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-w.decodeSlot
|
||||
return nil, err
|
||||
}
|
||||
|
||||
images, err := runImageProcess(ctx, tmp, w.maxPixels, row.PipelineVersion)
|
||||
<-w.decodeSlot
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := w.s3.Put(ctx, row.S3Key, tmp, size, string(row.ContentType)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
variants := make([]db.CreateAttachmentVariantParams, 0, len(images))
|
||||
for _, img := range images {
|
||||
key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.Name)
|
||||
if err := w.s3.Put(ctx, key, bytes.NewReader(img.Data), int64(len(img.Data)), img.ContentType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(img.Data)
|
||||
variants = append(variants, db.CreateAttachmentVariantParams{
|
||||
AttachmentID: row.ID,
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
Variant: img.Name,
|
||||
S3Key: key,
|
||||
ContentType: img.ContentType,
|
||||
SizeBytes: len(img.Data),
|
||||
Width: img.Width,
|
||||
Height: img.Height,
|
||||
Sha256: hex.EncodeToString(sum[:]),
|
||||
})
|
||||
}
|
||||
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
func imageVariants(r io.ReadSeeker, maxPixels, pipelineVersion int) ([]imageVariant, error) {
|
||||
quality := 80
|
||||
switch pipelineVersion {
|
||||
case 1:
|
||||
case 2:
|
||||
quality = 75
|
||||
default:
|
||||
return nil, ErrUnsupportedPipelineVersion
|
||||
}
|
||||
|
||||
cfg, format, err := image.DecodeConfig(r)
|
||||
if err != nil ||
|
||||
(format != "png" && format != "jpeg") ||
|
||||
cfg.Width <= 0 ||
|
||||
cfg.Height <= 0 ||
|
||||
cfg.Width > maxPixels/cfg.Height {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
variants := make([]imageVariant, 0, 3)
|
||||
for _, item := range []struct {
|
||||
name db.AttachmentVariantName
|
||||
image image.Image
|
||||
}{
|
||||
{db.AttachmentVariantNameThumbnail, fitImage(src, 256)},
|
||||
{db.AttachmentVariantNameCrop, imaging.Fill(src, 128, 128, imaging.Center, imaging.Lanczos)},
|
||||
{db.AttachmentVariantNameOptimized, fitImage(src, 1280)},
|
||||
} {
|
||||
var data []byte
|
||||
contentType := "image/jpeg"
|
||||
if item.name == db.AttachmentVariantNameOptimized {
|
||||
contentType = "image/webp"
|
||||
data, err = encodeWebP(item.image, quality)
|
||||
} else {
|
||||
data, err = encodeJPEG(item.image, 85)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
variants = append(variants, imageVariant{
|
||||
Name: item.name,
|
||||
ContentType: contentType,
|
||||
Data: data,
|
||||
Width: item.image.Bounds().Dx(),
|
||||
Height: item.image.Bounds().Dy(),
|
||||
})
|
||||
}
|
||||
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
func fitImage(src image.Image, maxSize int) image.Image {
|
||||
width, height := src.Bounds().Dx(), src.Bounds().Dy()
|
||||
if width > maxSize || height > maxSize {
|
||||
if width >= height {
|
||||
height = max(1, height*maxSize/width)
|
||||
width = maxSize
|
||||
} else {
|
||||
width = max(1, width*maxSize/height)
|
||||
height = maxSize
|
||||
}
|
||||
|
||||
return imaging.Resize(src, width, height, imaging.Lanczos)
|
||||
}
|
||||
|
||||
return src
|
||||
}
|
||||
|
||||
func encodeJPEG(src image.Image, quality int) ([]byte, error) {
|
||||
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Dx(), src.Bounds().Dy()))
|
||||
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
||||
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over)
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: quality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
func encodeWebP(src image.Image, quality int) ([]byte, error) {
|
||||
var out bytes.Buffer
|
||||
if err := webp.Encode(&out, src, webp.Options{Quality: quality, Method: 4}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func ProcessImage(maxPixels, pipelineVersion int) error {
|
||||
variants, err := imageVariants(os.Stdin, maxPixels, pipelineVersion)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return gob.NewEncoder(os.Stdout).Encode(variants)
|
||||
}
|
||||
|
||||
func runImageProcess(ctx context.Context, source *os.File, maxPixels, pipelineVersion int) ([]imageVariant, error) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, executable,
|
||||
"-process-image", strconv.Itoa(maxPixels),
|
||||
"-pipeline-version", strconv.Itoa(pipelineVersion),
|
||||
)
|
||||
cmd.Stdin = source
|
||||
data, err := cmd.Output()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var variants []imageVariant
|
||||
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&variants); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return variants, nil
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
"gavrilenko-sxdees/lab7/internal/model"
|
||||
s3store "gavrilenko-sxdees/lab7/internal/s3"
|
||||
"gavrilenko-sxdees/lab7/internal/telemetry"
|
||||
)
|
||||
|
||||
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)
|
||||
transformCtx, transformSpan := telemetry.Start(jobCtx, "image.transform", trace.SpanKindInternal)
|
||||
variants, processErr := w.process(transformCtx, row)
|
||||
telemetry.Failure(transformSpan, processErr)
|
||||
transformSpan.End()
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
telemetry.Ready(jobCtx, time.Since(job.CreatedAt).Seconds())
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
s3store "gavrilenko-sxdees/lab7/internal/s3"
|
||||
)
|
||||
|
||||
var (
|
||||
errAttachmentNotReplayable = errors.New("attachment is not replayable: expected failed with staging and no existing variants")
|
||||
errMissingPipelineJob = errors.New("attachment has no pipeline job")
|
||||
errReplayNotUpdated = errors.New("attachment replay did not update one row")
|
||||
)
|
||||
|
||||
type txBeginner interface {
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
func Replay(
|
||||
ctx context.Context,
|
||||
pool txBeginner,
|
||||
storage *s3store.Client,
|
||||
id uuid.UUID,
|
||||
operator, reason string,
|
||||
) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := db.New(tx)
|
||||
row, err := q.LockFailedAttachmentForReplay(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return errAttachmentNotReplayable
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if row.JobID == nil {
|
||||
return errMissingPipelineJob
|
||||
}
|
||||
|
||||
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
|
||||
return fmt.Errorf("verify replay source: %w", err)
|
||||
}
|
||||
|
||||
n, err := q.ReplayAttachmentJob(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return errReplayNotUpdated
|
||||
}
|
||||
|
||||
if err := q.CreateAttachmentReplay(ctx, db.CreateAttachmentReplayParams{
|
||||
AttachmentID: id,
|
||||
Attempt: row.Attempts + 1,
|
||||
PreviousErrorCode: row.ErrorCode,
|
||||
Operator: operator,
|
||||
Reason: reason,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: id,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now(),
|
||||
Traceparent: "",
|
||||
Tracestate: "",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
"gavrilenko-sxdees/lab7/internal/model"
|
||||
s3store "gavrilenko-sxdees/lab7/internal/s3"
|
||||
)
|
||||
|
||||
func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cause error) error {
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
row, err := q.LockAttachmentJob(ctx, db.LockAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
code := "processing_failed"
|
||||
permanent := errors.Is(cause, ErrInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound)
|
||||
if permanent {
|
||||
code = "invalid_source"
|
||||
} else if errors.Is(cause, context.DeadlineExceeded) {
|
||||
code = "job_timeout"
|
||||
}
|
||||
|
||||
var n int64
|
||||
if permanent || row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
|
||||
n, err = q.FailAttachmentJob(ctx, db.FailAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
ErrorCode: code,
|
||||
})
|
||||
} else {
|
||||
n, err = q.RetryAttachmentJob(ctx, db.RetryAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
ErrorCode: code,
|
||||
})
|
||||
if err == nil && n == 1 {
|
||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: row.ID,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
|
||||
Traceparent: "",
|
||||
Tracestate: "",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != 1 {
|
||||
return errLeaseExpired
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Warn(
|
||||
"attachment processing failed",
|
||||
"job_id",
|
||||
job.JobID,
|
||||
"attempt",
|
||||
job.Attempt,
|
||||
"error_code",
|
||||
code,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) recoverLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
recovered, err := w.recoverOne(ctx)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
w.log.Warn("recover attachment lease", "error", err)
|
||||
}
|
||||
|
||||
if (err != nil || !recovered) && !wait(ctx, time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) recoverOne(ctx context.Context) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
rows, err := q.LockExpiredAttachmentJobs(ctx, 1)
|
||||
if err != nil || len(rows) == 0 {
|
||||
return false, err
|
||||
}
|
||||
|
||||
row := rows[0]
|
||||
if row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
|
||||
_, err = q.FailExpiredAttachmentJob(ctx, row.ID)
|
||||
} else {
|
||||
_, err = q.RecoverExpiredAttachmentJob(ctx, row.ID)
|
||||
if err == nil {
|
||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: row.ID,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
|
||||
Traceparent: "",
|
||||
Tracestate: "",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
w.log.Info("attachment lease recovered", "attachment_id", row.ID, "attempt", row.Attempts)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func retryDelay(attempt int) time.Duration {
|
||||
ceiling := time.Second * time.Duration(1<<min(max(attempt, 1), 6))
|
||||
return ceiling/2 + time.Duration(rand.Int64N(int64(ceiling/2)))
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
s3store "gavrilenko-sxdees/lab7/internal/s3"
|
||||
)
|
||||
|
||||
var (
|
||||
errAttachmentNotUpgradeable = errors.New("attachment is not upgradeable: expected v1 queued or processing with staging")
|
||||
errUpgradeNotUpdated = errors.New("attachment upgrade did not update one row")
|
||||
)
|
||||
|
||||
func Upgrade(ctx context.Context, pool txBeginner, storage *s3store.Client, id uuid.UUID) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := db.New(tx)
|
||||
row, err := q.LockAttachmentForUpgrade(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return errAttachmentNotUpgradeable
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if row.JobID == nil {
|
||||
return errMissingPipelineJob
|
||||
}
|
||||
|
||||
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
n, err := q.UpgradeAttachmentPipeline(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return errUpgradeNotUpdated
|
||||
}
|
||||
|
||||
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: id,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now(),
|
||||
Traceparent: "",
|
||||
Tracestate: "",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/config"
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
"gavrilenko-sxdees/lab7/internal/model"
|
||||
"gavrilenko-sxdees/lab7/internal/rabbitmq"
|
||||
s3store "gavrilenko-sxdees/lab7/internal/s3"
|
||||
"gavrilenko-sxdees/lab7/internal/telemetry"
|
||||
)
|
||||
|
||||
type Worker struct {
|
||||
pool *pgxpool.Pool
|
||||
q *db.Queries
|
||||
s3 *s3store.Client
|
||||
brokerURL string
|
||||
cfg config.WorkerConfig
|
||||
maxBytes, maxPixels int
|
||||
decodeSlot chan struct{}
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func New(
|
||||
pool *pgxpool.Pool,
|
||||
s3 *s3store.Client,
|
||||
brokerURL string,
|
||||
cfg config.WorkerConfig,
|
||||
maxBytes, maxPixels int,
|
||||
log *slog.Logger,
|
||||
) *Worker {
|
||||
return &Worker{
|
||||
pool: pool,
|
||||
q: db.New(pool),
|
||||
s3: s3,
|
||||
brokerURL: brokerURL,
|
||||
cfg: cfg,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
decodeSlot: make(chan struct{}, 1),
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) Run(ctx context.Context) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
w.recoverLoop(ctx)
|
||||
}()
|
||||
|
||||
for range w.cfg.Concurrency {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
w.consumeLoop(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (w *Worker) consumeLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
client, err := rabbitmq.New(w.brokerURL)
|
||||
if err == nil {
|
||||
err = w.consume(ctx, client)
|
||||
_ = client.Close()
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
w.log.Warn("worker consumer reconnect", "error", err)
|
||||
if !wait(ctx, 2*time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) consume(ctx context.Context, client *rabbitmq.Client) error {
|
||||
stop := context.AfterFunc(ctx, func() {
|
||||
_ = client.Close()
|
||||
})
|
||||
defer stop()
|
||||
|
||||
deliveries, err := client.Consume(ctx, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case delivery, ok := <-deliveries:
|
||||
if !ok {
|
||||
return amqp.ErrClosed
|
||||
}
|
||||
|
||||
var job model.AttachmentJob
|
||||
if json.Unmarshal(delivery.Body, &job) != nil ||
|
||||
job.SchemaVersion != 1 ||
|
||||
job.Type != "attachment.process.v1" ||
|
||||
job.JobID == uuid.Nil ||
|
||||
job.AttachmentID == uuid.Nil ||
|
||||
(job.PipelineVersion != 1 && job.PipelineVersion != 2) ||
|
||||
job.Attempt < 1 ||
|
||||
job.CreatedAt.IsZero() {
|
||||
if err := delivery.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Warn("invalid attachment job rejected")
|
||||
continue
|
||||
}
|
||||
|
||||
parent, state := job.Traceparent, job.Tracestate
|
||||
if delivery.Headers != nil {
|
||||
if v, ok := delivery.Headers["traceparent"].(string); ok && v != "" {
|
||||
parent = v
|
||||
}
|
||||
if v, ok := delivery.Headers["tracestate"].(string); ok && v != "" {
|
||||
state = v
|
||||
}
|
||||
}
|
||||
jobCtx, span := telemetry.Start(
|
||||
telemetry.Extract(ctx, parent, state),
|
||||
"queue.consume",
|
||||
trace.SpanKindConsumer,
|
||||
)
|
||||
telemetry.IncBusy()
|
||||
started := time.Now()
|
||||
err := w.handle(jobCtx, job)
|
||||
telemetry.DecBusy()
|
||||
outcome := "success"
|
||||
if err != nil {
|
||||
outcome = "error"
|
||||
telemetry.Failure(span, err)
|
||||
}
|
||||
telemetry.Job(jobCtx, outcome, time.Since(started).Seconds())
|
||||
span.End()
|
||||
if err == nil {
|
||||
if err := delivery.Ack(false); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
w.log.Warn(
|
||||
"attachment job not acknowledged",
|
||||
"job_id",
|
||||
job.JobID,
|
||||
"attempt",
|
||||
job.Attempt,
|
||||
"error",
|
||||
err,
|
||||
)
|
||||
if !wait(ctx, time.Second) {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if err := delivery.Nack(false, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func wait(ctx context.Context, duration time.Duration) bool {
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user