forked from mtusi2026/mtusi2026lab5
fix: enforce pipeline lifecycle limits
This commit is contained in:
@@ -27,6 +27,7 @@ import (
|
||||
type Repository interface {
|
||||
AttachmentJob(context.Context, string) (model.AttachmentJob, error)
|
||||
ClaimAttachmentJob(context.Context, string, string, int, int, string, time.Duration) (model.AttachmentJobLease, error)
|
||||
RenewAttachmentJobLease(context.Context, model.AttachmentJobLease, time.Duration) (bool, error)
|
||||
CompleteAttachmentJob(context.Context, model.AttachmentJobLease, []model.Variant) (model.JobMutationResult, error)
|
||||
RetryAttachmentJob(context.Context, model.AttachmentJobLease, string, time.Time) (model.JobMutationResult, error)
|
||||
FailAttachmentJob(context.Context, model.AttachmentJobLease, string) (model.JobMutationResult, error)
|
||||
@@ -59,6 +60,7 @@ type Config struct {
|
||||
WorkerID string
|
||||
Concurrency int
|
||||
LeaseDuration time.Duration
|
||||
HeartbeatInterval time.Duration
|
||||
ProcessingTimeout time.Duration
|
||||
ReclaimInterval time.Duration
|
||||
MaxAttempts int
|
||||
@@ -119,6 +121,7 @@ func New(
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
if config.WorkerID == "" || config.Concurrency < 1 || config.LeaseDuration <= 0 ||
|
||||
config.HeartbeatInterval <= 0 || config.HeartbeatInterval >= config.LeaseDuration ||
|
||||
config.ProcessingTimeout <= 0 || config.ProcessingTimeout >= config.LeaseDuration ||
|
||||
config.ReclaimInterval <= 0 || config.MaxAttempts < 1 || config.RetryBase <= 0 ||
|
||||
config.RetryMax < config.RetryBase || config.MaxBytes < 1 || config.MaxPixels < 1 || config.MemoryBytes < 1 {
|
||||
@@ -218,9 +221,17 @@ func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Deliv
|
||||
return ErrInjectedFailure
|
||||
}
|
||||
|
||||
processingCtx, cancel := context.WithTimeout(ctx, w.config.ProcessingTimeout)
|
||||
processingCtx, cancelProcessing := context.WithTimeout(ctx, w.config.ProcessingTimeout)
|
||||
heartbeatCtx, cancelHeartbeat := context.WithCancel(ctx)
|
||||
heartbeatDone := make(chan error, 1)
|
||||
go func() { heartbeatDone <- w.maintainLease(heartbeatCtx, cancelProcessing, lease) }()
|
||||
variants, err := w.process(processingCtx, lease)
|
||||
cancel()
|
||||
cancelProcessing()
|
||||
cancelHeartbeat()
|
||||
heartbeatErr := <-heartbeatDone
|
||||
if heartbeatErr != nil {
|
||||
return heartbeatErr
|
||||
}
|
||||
if err != nil {
|
||||
result, err = w.resolveProcessingFailure(ctx, delivery, lease, err)
|
||||
return err
|
||||
@@ -252,6 +263,34 @@ func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Deliv
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) maintainLease(
|
||||
ctx context.Context,
|
||||
cancelProcessing context.CancelFunc,
|
||||
lease model.AttachmentJobLease,
|
||||
) error {
|
||||
ticker := time.NewTicker(w.config.HeartbeatInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
renewed, err := w.repository.RenewAttachmentJobLease(ctx, lease, w.config.LeaseDuration)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
cancelProcessing()
|
||||
return fmt.Errorf("renew attachment job lease: %w", err)
|
||||
}
|
||||
if !renewed {
|
||||
cancelProcessing()
|
||||
return model.ErrStaleLease
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) resolveClaim(
|
||||
ctx context.Context,
|
||||
delivery redisstream.Delivery,
|
||||
@@ -295,15 +334,18 @@ func (w *Worker) process(ctx context.Context, lease model.AttachmentJobLease) ([
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = body.Close() }()
|
||||
data, err := io.ReadAll(io.LimitReader(body, w.config.MaxBytes+1))
|
||||
data, err := io.ReadAll(io.LimitReader(contextReader{ctx: ctx, reader: body}, w.config.MaxBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > w.config.MaxBytes {
|
||||
return nil, transform.ErrPayloadTooLarge
|
||||
}
|
||||
imageConfig, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
imageConfig, _, err := image.DecodeConfig(contextReader{ctx: ctx, reader: bytes.NewReader(data)})
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, transform.ErrInvalidImage
|
||||
}
|
||||
weight, err := transform.EstimateMemoryWeight(int64(len(data)), imageConfig.Width, imageConfig.Height)
|
||||
@@ -346,6 +388,20 @@ func (w *Worker) process(ctx context.Context, lease model.AttachmentJobLease) ([
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r contextReader) Read(buffer []byte) (int, error) {
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return 0, r.ctx.Err()
|
||||
default:
|
||||
return r.reader.Read(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
var errWorkerCapacity = errors.New("image exceeds worker memory budget")
|
||||
|
||||
func variantObjectKey(attachmentID string, pipelineVersion int, name string, value transform.Variant) string {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
|
||||
)
|
||||
|
||||
@@ -46,11 +49,61 @@ func TestProcessingErrorClassification(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeaseHeartbeatRenewsUntilCanceled(t *testing.T) {
|
||||
var renewals atomic.Int32
|
||||
repository := &repositoryStub{renew: func(context.Context, model.AttachmentJobLease, time.Duration) (bool, error) {
|
||||
renewals.Add(1)
|
||||
return true, nil
|
||||
}}
|
||||
config := validConfig()
|
||||
config.HeartbeatInterval = 5 * time.Millisecond
|
||||
worker := &Worker{repository: repository, config: config}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- worker.maintainLease(ctx, cancel, testLease()) }()
|
||||
require.Eventually(t, func() bool { return renewals.Load() >= 2 }, time.Second, time.Millisecond)
|
||||
cancel()
|
||||
require.NoError(t, <-done)
|
||||
}
|
||||
|
||||
func TestLeaseHeartbeatCancelsProcessingWhenLeaseIsLost(t *testing.T) {
|
||||
repository := &repositoryStub{renew: func(context.Context, model.AttachmentJobLease, time.Duration) (bool, error) {
|
||||
return false, nil
|
||||
}}
|
||||
config := validConfig()
|
||||
config.HeartbeatInterval = time.Millisecond
|
||||
worker := &Worker{repository: repository, config: config}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
err := worker.maintainLease(ctx, cancel, testLease())
|
||||
require.ErrorIs(t, err, model.ErrStaleLease)
|
||||
require.ErrorIs(t, ctx.Err(), context.Canceled)
|
||||
}
|
||||
|
||||
type repositoryStub struct {
|
||||
Repository
|
||||
renew func(context.Context, model.AttachmentJobLease, time.Duration) (bool, error)
|
||||
}
|
||||
|
||||
func (s *repositoryStub) RenewAttachmentJobLease(
|
||||
ctx context.Context,
|
||||
lease model.AttachmentJobLease,
|
||||
duration time.Duration,
|
||||
) (bool, error) {
|
||||
return s.renew(ctx, lease, duration)
|
||||
}
|
||||
|
||||
func testLease() model.AttachmentJobLease {
|
||||
return model.AttachmentJobLease{Job: model.AttachmentJob{
|
||||
ID: "11111111-1111-4111-8111-111111111111", LeaseToken: "lease-token", LeaseOwner: "worker-1",
|
||||
}}
|
||||
}
|
||||
|
||||
func validConfig() Config {
|
||||
return Config{
|
||||
WorkerID: "worker-1", Concurrency: 2, LeaseDuration: 30 * time.Second,
|
||||
ProcessingTimeout: 20 * time.Second, ReclaimInterval: 5 * time.Second,
|
||||
MaxAttempts: 5, RetryBase: time.Second, RetryMax: 30 * time.Second,
|
||||
HeartbeatInterval: 5 * time.Second, ProcessingTimeout: 20 * time.Second,
|
||||
ReclaimInterval: 5 * time.Second,
|
||||
MaxAttempts: 5, RetryBase: time.Second, RetryMax: 30 * time.Second,
|
||||
MaxBytes: 10 * 1024 * 1024, MaxPixels: 40_000_000, MemoryBytes: 704 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user