forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package pipeline
|
||||
|
||||
import "context"
|
||||
|
||||
// Retention owns replay fencing and deletion acknowledgements.
|
||||
type Retention interface {
|
||||
// ExpireStaging claims at most 100 old terminal source keys.
|
||||
ExpireStaging(context.Context) ([]string, error)
|
||||
// StagingRemoved acknowledges idempotent source removal.
|
||||
StagingRemoved(context.Context, string) error
|
||||
}
|
||||
|
||||
// Remover deletes only a server-claimed immutable key.
|
||||
type Remover interface {
|
||||
// Remove is safe to repeat after an uncertain acknowledgement.
|
||||
Remove(context.Context, string) error
|
||||
}
|
||||
|
||||
// Cleanup removes expired staging only after the database has excluded replay.
|
||||
func Cleanup(ctx context.Context, store Retention, objects Remover) (int, error) {
|
||||
keys, err := store.ExpireStaging(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
removed := 0
|
||||
for _, key := range keys {
|
||||
if err := objects.Remove(ctx, key); err != nil {
|
||||
return removed, err
|
||||
}
|
||||
if err := store.StagingRemoved(ctx, key); err != nil {
|
||||
return removed, err
|
||||
}
|
||||
removed++
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type cleanupFixture struct {
|
||||
claimErr error
|
||||
removeErr error
|
||||
confirmErr error
|
||||
}
|
||||
|
||||
// ExpireStaging supplies one safely claimed source key.
|
||||
func (f cleanupFixture) ExpireStaging(context.Context) ([]string, error) {
|
||||
return []string{"staging/claimed"}, f.claimErr
|
||||
}
|
||||
|
||||
// Remove injects an independent deletion acknowledgement outcome.
|
||||
func (f cleanupFixture) Remove(context.Context, string) error {
|
||||
return f.removeErr
|
||||
}
|
||||
|
||||
// StagingRemoved injects acknowledgement persistence failure.
|
||||
func (f cleanupFixture) StagingRemoved(context.Context, string) error {
|
||||
return f.confirmErr
|
||||
}
|
||||
|
||||
// TestCleanupBoundaries verifies deletion is counted only after both acknowledgements.
|
||||
func TestCleanupBoundaries(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
fixture cleanupFixture
|
||||
want int
|
||||
failed bool
|
||||
}{
|
||||
{"claim failed", cleanupFixture{claimErr: errInjected}, 0, true},
|
||||
{"delete failed", cleanupFixture{removeErr: errInjected}, 0, true},
|
||||
{"confirm failed", cleanupFixture{confirmErr: errInjected}, 0, true},
|
||||
{"completed", cleanupFixture{}, 1, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
count, err := Cleanup(t.Context(), tc.fixture, tc.fixture)
|
||||
if count != tc.want || (err != nil) != tc.failed {
|
||||
t.Fatalf("cleanup: %d %v", count, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/observation"
|
||||
)
|
||||
|
||||
// Observer preserves job causality and records bounded processing measurements.
|
||||
type Observer interface {
|
||||
observation.Tracer
|
||||
// Extract restores a durable parent context.
|
||||
Extract(context.Context, string, string) context.Context
|
||||
// Inject serializes the producer's W3C carrier.
|
||||
Inject(context.Context) (string, string)
|
||||
// JobStarted increments current worker occupancy.
|
||||
JobStarted()
|
||||
// JobFinished records a real attempt's outcome and duration.
|
||||
JobFinished(context.Context, time.Duration, error)
|
||||
// Ready records latency from durable acceptance to confirmed publication.
|
||||
Ready(context.Context, time.Time)
|
||||
}
|
||||
|
||||
// WithObserver binds optional telemetry at the composition root.
|
||||
func (w *Worker) WithObserver(observer Observer) *Worker {
|
||||
w.observer = observer
|
||||
return w
|
||||
}
|
||||
|
||||
// publish traces one durable handoff and propagates the producer context to its consumer.
|
||||
func (w *Worker) publish(ctx context.Context, job Job) error {
|
||||
if w.observer == nil {
|
||||
return w.queue.Publish(ctx, job)
|
||||
}
|
||||
ctx = w.observer.Extract(ctx, job.Traceparent, job.Tracestate)
|
||||
ctx, end := w.observer.Start(ctx, "attachment.publish", "producer")
|
||||
job.Traceparent, job.Tracestate = w.observer.Inject(ctx)
|
||||
err := w.queue.Publish(ctx, job)
|
||||
end(err)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type observerFixture struct {
|
||||
extracted string
|
||||
injected bool
|
||||
started int
|
||||
finished int
|
||||
ready int
|
||||
spans int
|
||||
}
|
||||
|
||||
// Start counts actual operation scopes without imposing an SDK on pipeline tests.
|
||||
func (o *observerFixture) Start(ctx context.Context, _ string, _ string) (context.Context, func(error)) {
|
||||
o.spans++
|
||||
return ctx, func(error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Extract captures only the intended durable carrier.
|
||||
func (o *observerFixture) Extract(ctx context.Context, parent, _ string) context.Context {
|
||||
o.extracted = parent
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Inject models the producer's outgoing parent context.
|
||||
func (o *observerFixture) Inject(context.Context) (string, string) {
|
||||
o.injected = true
|
||||
return "producer-parent", "state"
|
||||
}
|
||||
|
||||
// JobStarted records one claimed attempt.
|
||||
func (o *observerFixture) JobStarted() {
|
||||
o.started++
|
||||
}
|
||||
|
||||
// JobFinished releases one claimed attempt after its actual result.
|
||||
func (o *observerFixture) JobFinished(context.Context, time.Duration, error) {
|
||||
o.finished++
|
||||
}
|
||||
|
||||
// Ready counts only confirmed durable results.
|
||||
func (o *observerFixture) Ready(context.Context, time.Time) {
|
||||
o.ready++
|
||||
}
|
||||
|
||||
// TestObservedDispatchPropagatesProducer verifies producer spans surround the real queue call.
|
||||
func TestObservedDispatchPropagatesProducer(t *testing.T) {
|
||||
worker, _, _ := fixtureWorker(t)
|
||||
observer := &observerFixture{}
|
||||
worker.WithObserver(observer)
|
||||
if err := worker.Dispatch(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !observer.injected || observer.spans != 1 {
|
||||
t.Fatal("producer handoff not observed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestObservedAttemptMeasuresDurableCompletion ensures metrics do not count only notification receipt.
|
||||
func TestObservedAttemptMeasuresDurableCompletion(t *testing.T) {
|
||||
worker, _, delivery := fixtureWorker(t)
|
||||
delivery.Job.Traceparent = "accepted-parent"
|
||||
observer := &observerFixture{}
|
||||
worker.WithObserver(observer)
|
||||
if err := worker.Handle(t.Context(), delivery); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if observer.extracted != "accepted-parent" || observer.started != 1 || observer.finished != 1 || observer.ready != 1 {
|
||||
t.Fatal("incorrect attempt observation")
|
||||
}
|
||||
}
|
||||
|
||||
// TestObservedFailedCommitDoesNotCountReady protects the end-to-end success histogram from failed publication.
|
||||
func TestObservedFailedCommitDoesNotCountReady(t *testing.T) {
|
||||
worker, fixture, delivery := fixtureWorker(t)
|
||||
fixture.completeErr = errors.New("uncertain commit")
|
||||
observer := &observerFixture{}
|
||||
worker.WithObserver(observer)
|
||||
if err := worker.Handle(t.Context(), delivery); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if observer.ready != 0 || observer.finished != 1 {
|
||||
t.Fatal("uncertain result counted ready")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Package pipeline coordinates durable jobs through consumer-owned interfaces.
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// Job is the versioned broker envelope; storage paths never enter the broker.
|
||||
type Job struct {
|
||||
// SchemaVersion fixes the wire schema.
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
// ID remains stable across retries.
|
||||
ID uuid.UUID `json:"job_id"`
|
||||
// Type identifies the processing operation.
|
||||
Type string `json:"type"`
|
||||
// AttachmentID identifies trusted metadata.
|
||||
AttachmentID uuid.UUID `json:"attachment_id"`
|
||||
// Version fences superseded pipelines.
|
||||
Version int `json:"pipeline_version"`
|
||||
// Attempt is a managed processing attempt, starting at one.
|
||||
Attempt int `json:"attempt"`
|
||||
// CreatedAt records durable intent.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Traceparent propagates a W3C parent when telemetry is enabled.
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
// Tracestate carries optional vendor state.
|
||||
Tracestate string `json:"tracestate,omitempty"`
|
||||
}
|
||||
|
||||
// Lease carries a fenced claim and trusted storage metadata.
|
||||
type Lease struct {
|
||||
// Job is the current durable attempt.
|
||||
Job Job
|
||||
// Token prevents a late attempt from publishing.
|
||||
Token uuid.UUID
|
||||
// Attachment describes the original.
|
||||
Attachment dto.Attachment
|
||||
// StagingKey is read only from the database.
|
||||
StagingKey string
|
||||
}
|
||||
|
||||
// Delivery pairs the broker receipt with its envelope.
|
||||
type Delivery struct {
|
||||
// Receipt is used only for acknowledgement.
|
||||
Receipt string
|
||||
// Job is the validated notification.
|
||||
Job Job
|
||||
}
|
||||
|
||||
// Store owns atomic job and metadata transitions.
|
||||
type Store interface {
|
||||
// Due returns bounded durable intents requiring publication.
|
||||
Due(context.Context, int) ([]Job, error)
|
||||
// Published records a successful broker confirmation.
|
||||
Published(context.Context, Job) error
|
||||
// Claim obtains a lease or returns nil for an ineligible notification.
|
||||
Claim(context.Context, Job, time.Duration, int) (*Lease, error)
|
||||
// Complete atomically publishes the current fenced result.
|
||||
Complete(context.Context, Lease, string, []dto.Variant) (bool, error)
|
||||
// Fail persists retry scheduling or a safe terminal failure.
|
||||
Fail(context.Context, Lease, string, time.Duration, int) error
|
||||
}
|
||||
|
||||
// Queue transports durable notifications with explicit acknowledgements.
|
||||
type Queue interface {
|
||||
// Publish confirms acceptance by the persistent broker.
|
||||
Publish(context.Context, Job) error
|
||||
// Receive reads one notification, including abandoned deliveries.
|
||||
Receive(context.Context) (*Delivery, error)
|
||||
// Ack releases a delivery after its durable transition.
|
||||
Ack(context.Context, string) error
|
||||
}
|
||||
|
||||
// Objects accesses private bytes; all keys come from trusted code.
|
||||
type Objects interface {
|
||||
// Get opens an object owned by the job.
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
// Put persists an immutable attempt output.
|
||||
Put(context.Context, string, string, io.Reader, int64) error
|
||||
}
|
||||
|
||||
// Output pairs public metadata with generated encoded bytes.
|
||||
type Output struct {
|
||||
// Metadata describes this variant.
|
||||
Metadata dto.Variant
|
||||
// Bytes contains a bounded encoded image.
|
||||
Bytes []byte
|
||||
}
|
||||
|
||||
// Processor converts one validated source within the supplied deadline.
|
||||
type Processor interface {
|
||||
// Process returns all variants required before ready.
|
||||
Process(context.Context, []byte) ([]Output, error)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// ErrInvalidImage identifies a permanent decode/checksum failure.
|
||||
var ErrInvalidImage = errors.New("invalid image")
|
||||
|
||||
const sourceLimit = 10 * 1024 * 1024
|
||||
const maxAttempts = 5
|
||||
const claimDuration = 2 * time.Minute
|
||||
const processingTimeout = 45 * time.Second
|
||||
const outboxBatch = 100
|
||||
|
||||
// Worker processes one job at a time, independently of API admission.
|
||||
type Worker struct {
|
||||
observer Observer
|
||||
store Store
|
||||
queue Queue
|
||||
objects Objects
|
||||
processor Processor
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// New validates all side-effect boundaries at composition time.
|
||||
func New(store Store, queue Queue, objects Objects, processor Processor, log *zap.Logger) (*Worker, error) {
|
||||
if store == nil || queue == nil || objects == nil || processor == nil || log == nil {
|
||||
return nil, fmt.Errorf("worker dependencies are required")
|
||||
}
|
||||
return &Worker{store: store, queue: queue, objects: objects, processor: processor, log: log}, nil
|
||||
}
|
||||
|
||||
// Dispatch republishes durable intents whose notification or consumer was lost.
|
||||
func (w *Worker) Dispatch(ctx context.Context) error {
|
||||
jobs, err := w.store.Due(ctx, outboxBatch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, job := range jobs {
|
||||
if err := w.publish(ctx, job); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.store.Published(ctx, job); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Run owns a bounded serial processing loop and observes cancellation between operations.
|
||||
func (w *Worker) Run(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
if err := w.Dispatch(ctx); err != nil {
|
||||
w.log.Warn("job dispatch unavailable")
|
||||
}
|
||||
delivery, err := w.queue.Receive(ctx)
|
||||
if err != nil {
|
||||
w.log.Warn("job broker unavailable")
|
||||
wait(ctx, time.Second)
|
||||
continue
|
||||
}
|
||||
if delivery == nil {
|
||||
continue
|
||||
}
|
||||
if err := w.Handle(ctx, *delivery); err != nil {
|
||||
w.log.Warn("job transition unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle acknowledges only a durable completion, retry, terminal result or fenced no-op.
|
||||
func (w *Worker) Handle(ctx context.Context, delivery Delivery) (result error) {
|
||||
var processingError error
|
||||
if w.observer != nil {
|
||||
ctx = w.observer.Extract(ctx, delivery.Job.Traceparent, delivery.Job.Tracestate)
|
||||
var finish func(error)
|
||||
ctx, finish = w.observer.Start(ctx, "attachment.process", "consumer")
|
||||
defer func() { finish(errors.Join(result, processingError)) }()
|
||||
}
|
||||
lease, err := w.store.Claim(ctx, delivery.Job, claimDuration, maxAttempts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lease == nil {
|
||||
return w.queue.Ack(ctx, delivery.Receipt)
|
||||
}
|
||||
started := time.Now()
|
||||
if w.observer != nil {
|
||||
w.observer.JobStarted()
|
||||
}
|
||||
operation, cancel := context.WithTimeout(ctx, processingTimeout)
|
||||
err = w.process(operation, *lease)
|
||||
processingError = err
|
||||
if w.observer != nil {
|
||||
w.observer.JobFinished(ctx, time.Since(started), err)
|
||||
}
|
||||
cancel()
|
||||
if err != nil {
|
||||
code := "processing_failed"
|
||||
if errors.Is(err, ErrInvalidImage) {
|
||||
code = "invalid_image"
|
||||
}
|
||||
delay := time.Duration(1<<min(lease.Job.Attempt, maxAttempts))*time.Second + time.Duration(rand.IntN(1000))*time.Millisecond
|
||||
if failErr := w.store.Fail(ctx, *lease, code, delay, maxAttempts); failErr != nil {
|
||||
return failErr
|
||||
}
|
||||
}
|
||||
return w.queue.Ack(ctx, delivery.Receipt)
|
||||
}
|
||||
|
||||
// process writes attempt-isolated objects before atomically publishing their metadata.
|
||||
func (w *Worker) process(ctx context.Context, lease Lease) error {
|
||||
reader, err := w.objects.Get(ctx, lease.StagingKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
source, readErr := io.ReadAll(io.LimitReader(reader, sourceLimit+1))
|
||||
closeErr := reader.Close()
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
sum := sha256.Sum256(source)
|
||||
if len(source) > sourceLimit || int64(len(source)) != lease.Attachment.SizeBytes || hex.EncodeToString(sum[:]) != lease.Attachment.SHA256 {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
outputs, err := w.processor.Process(ctx, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prefix := fmt.Sprintf("results/%s/v%d/%s/", lease.Job.AttachmentID, lease.Job.Version, lease.Token)
|
||||
original := prefix + "original"
|
||||
if err := w.objects.Put(ctx, original, lease.Attachment.ContentType, bytes.NewReader(source), int64(len(source))); err != nil {
|
||||
return err
|
||||
}
|
||||
variants := make([]dto.Variant, 0, len(outputs))
|
||||
for _, output := range outputs {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
output.Metadata.ObjectKey = prefix + output.Metadata.Name
|
||||
if err := w.objects.Put(ctx, output.Metadata.ObjectKey, output.Metadata.ContentType, bytes.NewReader(output.Bytes), int64(len(output.Bytes))); err != nil {
|
||||
return err
|
||||
}
|
||||
variants = append(variants, output.Metadata)
|
||||
}
|
||||
published, err := w.store.Complete(ctx, lease, original, variants)
|
||||
if err == nil && published && w.observer != nil {
|
||||
w.observer.Ready(ctx, lease.Job.CreatedAt)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// wait backs off broker failures without delaying shutdown.
|
||||
func wait(ctx context.Context, duration time.Duration) {
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
var errInjected = errors.New("errInjected dependency failure")
|
||||
|
||||
type workerFixture struct {
|
||||
lease *Lease
|
||||
source []byte
|
||||
outputs []Output
|
||||
dueErr error
|
||||
publishErr error
|
||||
confirmErr error
|
||||
claimErr error
|
||||
getErr error
|
||||
readErr error
|
||||
closeErr error
|
||||
processErr error
|
||||
completeErr error
|
||||
failErr error
|
||||
ackErr error
|
||||
putAt int
|
||||
puts int
|
||||
code string
|
||||
delay time.Duration
|
||||
acked int
|
||||
completed int
|
||||
received bool
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// fixtureWorker provides independent dependencies for one delivery invariant.
|
||||
func fixtureWorker(t *testing.T) (*Worker, *workerFixture, Delivery) {
|
||||
t.Helper()
|
||||
source := []byte("bounded synthetic original")
|
||||
sum := sha256.Sum256(source)
|
||||
job := Job{ID: uuid.New(), AttachmentID: uuid.New(), Version: 1, Attempt: 1}
|
||||
f := &workerFixture{source: source, lease: &Lease{Job: job, Token: uuid.New(), Attachment: dto.Attachment{SHA256: hex.EncodeToString(sum[:]), SizeBytes: int64(len(source)), ContentType: "image/png"}, StagingKey: "staging/test"}, outputs: []Output{{Metadata: dto.Variant{Name: "thumbnail", ContentType: "image/jpeg"}, Bytes: []byte("variant")}}}
|
||||
worker, err := New(f, f, f, f, zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return worker, f, Delivery{Job: job, Receipt: "receipt"}
|
||||
}
|
||||
|
||||
// Due supplies one durable fixture intent or a database failure.
|
||||
func (f *workerFixture) Due(context.Context, int) ([]Job, error) {
|
||||
return []Job{f.lease.Job}, f.dueErr
|
||||
}
|
||||
|
||||
// Published models acknowledgement persistence after broker acceptance.
|
||||
func (f *workerFixture) Published(context.Context, Job) error {
|
||||
return f.confirmErr
|
||||
}
|
||||
|
||||
// Claim supplies a fenced claim or the configured database outcome.
|
||||
func (f *workerFixture) Claim(context.Context, Job, time.Duration, int) (*Lease, error) {
|
||||
return f.lease, f.claimErr
|
||||
}
|
||||
|
||||
// Complete records publication attempts without implementing a second SQL model.
|
||||
func (f *workerFixture) Complete(context.Context, Lease, string, []dto.Variant) (bool, error) {
|
||||
f.completed++
|
||||
return f.completeErr == nil, f.completeErr
|
||||
}
|
||||
|
||||
// Fail captures safe failure classification and bounded retry scheduling.
|
||||
func (f *workerFixture) Fail(_ context.Context, _ Lease, code string, delay time.Duration, _ int) error {
|
||||
f.code = code
|
||||
f.delay = delay
|
||||
return f.failErr
|
||||
}
|
||||
|
||||
// Publish supplies one broker acceptance outcome.
|
||||
func (f *workerFixture) Publish(context.Context, Job) error {
|
||||
return f.publishErr
|
||||
}
|
||||
|
||||
// Receive delivers once and cancels the fixture loop on its second read.
|
||||
func (f *workerFixture) Receive(context.Context) (*Delivery, error) {
|
||||
if f.received {
|
||||
f.cancel()
|
||||
return nil, errInjected
|
||||
}
|
||||
f.received = true
|
||||
return &Delivery{Job: f.lease.Job, Receipt: "receipt"}, nil
|
||||
}
|
||||
|
||||
// Ack records whether the coordinator released the delivery.
|
||||
func (f *workerFixture) Ack(context.Context, string) error {
|
||||
f.acked++
|
||||
return f.ackErr
|
||||
}
|
||||
|
||||
// Get supplies a bounded reader with independent read and close failures.
|
||||
func (f *workerFixture) Get(context.Context, string) (io.ReadCloser, error) {
|
||||
return &faultReader{Reader: bytes.NewReader(f.source), readErr: f.readErr, closeErr: f.closeErr}, f.getErr
|
||||
}
|
||||
|
||||
// Put injects a failure at a configured original or variant write.
|
||||
func (f *workerFixture) Put(context.Context, string, string, io.Reader, int64) error {
|
||||
f.puts++
|
||||
if f.putAt == f.puts {
|
||||
return errInjected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process supplies one independent transformation outcome.
|
||||
func (f *workerFixture) Process(context.Context, []byte) ([]Output, error) {
|
||||
return f.outputs, f.processErr
|
||||
}
|
||||
|
||||
type faultReader struct {
|
||||
*bytes.Reader
|
||||
readErr error
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// Read injects a transport read failure before consuming source bytes.
|
||||
func (r *faultReader) Read(p []byte) (int, error) {
|
||||
if r.readErr != nil {
|
||||
return 0, r.readErr
|
||||
}
|
||||
return r.Reader.Read(p)
|
||||
}
|
||||
|
||||
// Close exposes an independently failed stream finalization.
|
||||
func (r *faultReader) Close() error {
|
||||
return r.closeErr
|
||||
}
|
||||
|
||||
// TestHandlePublishesBeforeAck verifies all output writes precede the durable completion.
|
||||
func TestHandlePublishesBeforeAck(t *testing.T) {
|
||||
worker, f, delivery := fixtureWorker(t)
|
||||
if err := worker.Handle(t.Context(), delivery); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.puts != 2 || f.completed != 1 || f.acked != 1 || f.code != "" {
|
||||
t.Fatal("incomplete publication acknowledged")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandlePersistsRetryBeforeAck checks all transient I/O windows converge to durable retry.
|
||||
func TestHandlePersistsRetryBeforeAck(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
setup func(*workerFixture)
|
||||
code string
|
||||
}{
|
||||
{"read source", func(f *workerFixture) { f.getErr = errInjected }, "processing_failed"},
|
||||
{"read bytes", func(f *workerFixture) { f.readErr = errInjected }, "processing_failed"},
|
||||
{"close source", func(f *workerFixture) { f.closeErr = errInjected }, "processing_failed"},
|
||||
{"decode", func(f *workerFixture) { f.processErr = ErrInvalidImage }, "invalid_image"},
|
||||
{"checksum", func(f *workerFixture) { f.source = []byte("tampered") }, "invalid_image"},
|
||||
{"original write", func(f *workerFixture) { f.putAt = 1 }, "processing_failed"},
|
||||
{"variant write", func(f *workerFixture) { f.putAt = 2 }, "processing_failed"},
|
||||
{"result commit", func(f *workerFixture) { f.completeErr = errInjected }, "processing_failed"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
worker, f, delivery := fixtureWorker(t)
|
||||
tc.setup(f)
|
||||
if err := worker.Handle(t.Context(), delivery); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.code != tc.code || f.acked != 1 || f.delay < 2*time.Second || f.delay >= 3*time.Second {
|
||||
t.Fatal("unsafe failure transition")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleLeavesUncommittedFailurePending prevents acknowledgement when retry persistence fails.
|
||||
func TestHandleLeavesUncommittedFailurePending(t *testing.T) {
|
||||
worker, f, delivery := fixtureWorker(t)
|
||||
f.getErr = errInjected
|
||||
f.failErr = errInjected
|
||||
if err := worker.Handle(t.Context(), delivery); !errors.Is(err, errInjected) || f.acked != 0 {
|
||||
t.Fatal("uncommitted retry acknowledged")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleUnavailableClaimLeavesPending preserves delivery when the source of truth is unavailable.
|
||||
func TestHandleUnavailableClaimLeavesPending(t *testing.T) {
|
||||
worker, f, delivery := fixtureWorker(t)
|
||||
f.claimErr = errInjected
|
||||
if err := worker.Handle(t.Context(), delivery); !errors.Is(err, errInjected) || f.acked != 0 {
|
||||
t.Fatal("failed claim acknowledged")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDuplicateAcknowledgesWithoutEffects verifies fenced no-ops never touch S3.
|
||||
func TestHandleDuplicateAcknowledgesWithoutEffects(t *testing.T) {
|
||||
worker, f, delivery := fixtureWorker(t)
|
||||
f.lease = nil
|
||||
if err := worker.Handle(t.Context(), delivery); err != nil || f.acked != 1 || f.puts != 0 {
|
||||
t.Fatal("duplicate caused effects")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchFailureBoundaries checks uncertainty leaves durable outbox intent for another pass.
|
||||
func TestDispatchFailureBoundaries(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
setup func(*workerFixture)
|
||||
}{
|
||||
{"database read", func(f *workerFixture) { f.dueErr = errInjected }},
|
||||
{"broker publish", func(f *workerFixture) { f.publishErr = errInjected }},
|
||||
{"confirmation commit", func(f *workerFixture) { f.confirmErr = errInjected }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
worker, f, _ := fixtureWorker(t)
|
||||
tc.setup(f)
|
||||
if err := worker.Dispatch(t.Context()); !errors.Is(err, errInjected) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkerLoopStops verifies the loop releases ownership on cancellation.
|
||||
func TestWorkerLoopStops(t *testing.T) {
|
||||
worker, f, _ := fixtureWorker(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
f.cancel = cancel
|
||||
f.failErr = errInjected
|
||||
f.getErr = errInjected
|
||||
worker.Run(ctx)
|
||||
if ctx.Err() == nil {
|
||||
t.Fatal("worker did not stop")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkerRejectsMissingDependencies keeps invalid composition from starting a background loop.
|
||||
func TestWorkerRejectsMissingDependencies(t *testing.T) {
|
||||
if _, err := New(nil, nil, nil, nil, nil); err == nil {
|
||||
t.Fatal("missing dependencies accepted")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user