Подключите RabbitMQ и отдельный обработчик заданий

This commit is contained in:
2026-11-18 15:33:33 +03:00
parent 752f29573b
commit 2dc566e6ec
19 changed files with 818 additions and 14 deletions
+115
View File
@@ -0,0 +1,115 @@
// Package broker owns the AMQP connection for one publisher or consumer.
package broker
import (
"context"
"errors"
"net"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const queue = "attachment.jobs"
type link struct {
conn *amqp.Connection
channel *amqp.Channel
}
func open(ctx context.Context, url string) (*link, error) {
conn, err := amqp.DialConfig(url, amqp.Config{Heartbeat: 5 * time.Second, Dial: func(network, addr string) (net.Conn, error) {
d := net.Dialer{Timeout: 3 * time.Second}
c, err := d.DialContext(ctx, network, addr)
if err == nil {
err = c.SetDeadline(time.Now().Add(5 * time.Second))
}
return c, err
}})
// Parse errors can contain the complete connection URL.
if err != nil {
return nil, errors.New("RabbitMQ connection unavailable")
}
l := &link{conn: conn}
l.channel, err = conn.Channel()
if err == nil {
// PostgreSQL limits processing attempts. A broker redelivery can occur
// before PostgreSQL is reachable and must leave the job recoverable.
_, err = l.channel.QueueDeclare(queue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum", "x-delivery-limit": int32(-1),
})
}
if err != nil {
l.Close()
return nil, err
}
return l, nil
}
func (l *link) Close() { _ = l.conn.CloseDeadline(time.Now().Add(time.Second)) }
type Publisher struct {
*link
returned <-chan amqp.Return
}
func NewPublisher(ctx context.Context, url string) (*Publisher, error) {
l, err := open(ctx, url)
if err != nil {
return nil, err
}
if err = l.channel.Confirm(false); err != nil {
l.Close()
return nil, err
}
return &Publisher{l, l.channel.NotifyReturn(make(chan amqp.Return, 1))}, nil
}
// Publish has one in-flight confirm on its channel. An ambiguous result means
// the caller discards this publisher and leaves the outbox row pending.
func (p *Publisher) Publish(ctx context.Context, body []byte) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
stop := context.AfterFunc(ctx, p.Close)
defer stop()
confirmation, err := p.channel.PublishWithDeferredConfirmWithContext(ctx, "", queue, true, false, amqp.Publishing{ContentType: "application/json", DeliveryMode: amqp.Persistent, Body: body})
if err != nil {
return err
}
ok, err := confirmation.WaitContext(ctx)
if err != nil {
return err
}
if !ok {
return errors.New("broker did not confirm publication")
}
// RabbitMQ sends basic.return before the associated publisher confirm.
select {
case <-p.returned:
return errors.New("broker returned publication")
default:
return nil
}
}
type Consumer struct {
*link
Deliveries <-chan amqp.Delivery
}
func NewConsumer(ctx context.Context, url string) (*Consumer, error) {
l, err := open(ctx, url)
if err != nil {
return nil, err
}
if err = l.channel.Qos(1, 0, false); err != nil {
l.Close()
return nil, err
}
d, err := l.channel.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
if err != nil {
l.Close()
return nil, err
}
return &Consumer{l, d}, nil
}
+56
View File
@@ -0,0 +1,56 @@
package broker
import (
"context"
"testing"
"time"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestConfirmAndRedeliverUnacked(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
defer cancel()
c, err := testcontainers.Run(ctx, "rabbitmq:4.1.4-alpine", testcontainers.WithEnv(map[string]string{"RABBITMQ_DEFAULT_USER": "lab", "RABBITMQ_DEFAULT_PASS": "test-only"}), testcontainers.WithExposedPorts("5672/tcp"), testcontainers.WithWaitStrategy(wait.ForLog("Server startup complete")))
if err != nil {
t.Fatal(err)
}
testcontainers.CleanupContainer(t, c)
endpoint, err := c.PortEndpoint(ctx, "5672/tcp", "")
if err != nil {
t.Fatal(err)
}
url := "amqp://lab:test-only@" + endpoint + "/"
pub, err := NewPublisher(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pub.Close()
if err = pub.Publish(ctx, []byte("work")); err != nil {
t.Fatal(err)
}
// Broker redeliveries while PostgreSQL is unreachable do not consume
// the application budget. Exercise more than the quorum queue default.
for attempt := 0; attempt <= 22; attempt++ {
consumer, err := NewConsumer(ctx, url)
if err != nil {
t.Fatal(err)
}
select {
case msg := <-consumer.Deliveries:
if string(msg.Body) != "work" || msg.Redelivered != (attempt > 0) {
t.Fatalf("unexpected delivery on attempt %d", attempt)
}
if attempt == 22 {
if err := msg.Ack(false); err != nil {
t.Fatal(err)
}
}
case <-time.After(5 * time.Second):
consumer.Close()
t.Fatalf("confirmed job missing on delivery %d", attempt+1)
}
consumer.Close()
}
}
+41
View File
@@ -0,0 +1,41 @@
package config
import (
"fmt"
"strconv"
"time"
)
type Jobs struct {
URL string
Concurrency, MaxAttempts int
Timeout time.Duration
}
func LoadJobs(lookup Lookup) (Jobs, error) {
url, err := secret(lookup, "BROKER_URL_FILE")
if err != nil {
return Jobs{}, err
}
c := Jobs{URL: url, Concurrency: 2, MaxAttempts: 5}
seconds := 60
for _, p := range []struct {
key string
value *int
max int
}{
{"WORKER_CONCURRENCY", &c.Concurrency, 2},
{"JOB_MAX_ATTEMPTS", &c.MaxAttempts, 100},
{"JOB_TIMEOUT_SECONDS", &seconds, 3600},
} {
if s, ok := lookup(p.key); ok {
n, err := strconv.Atoi(s)
if err != nil || n < 1 || n > p.max {
return Jobs{}, fmt.Errorf("%s must be between 1 and %d", p.key, p.max)
}
*p.value = n
}
}
c.Timeout = time.Duration(seconds) * time.Second
return c, nil
}
+28
View File
@@ -0,0 +1,28 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestLoadJobs(t *testing.T) {
path := filepath.Join(t.TempDir(), "url")
if err := os.WriteFile(path, []byte("amqp://worker:secret@broker:5672/\n"), 0600); err != nil {
t.Fatal(err)
}
values := map[string]string{"BROKER_URL_FILE": path}
lookup := func(k string) (string, bool) { v, ok := values[k]; return v, ok }
cfg, err := LoadJobs(lookup)
if err != nil || cfg.Timeout != 60*time.Second || cfg.MaxAttempts != 5 || cfg.Concurrency < 1 || cfg.URL != "amqp://worker:secret@broker:5672/" {
t.Fatalf("unexpected defaults or secret read, err=%v", err)
}
for _, key := range []string{"JOB_TIMEOUT_SECONDS", "WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS"} {
values[key] = "0"
if _, err := LoadJobs(lookup); err == nil {
t.Errorf("%s accepted zero", key)
}
delete(values, key)
}
}
+18
View File
@@ -0,0 +1,18 @@
package processing
import (
"context"
"fmt"
"path/filepath"
"messenger/internal/pipeline"
"messenger/internal/platform/faultbarrier"
)
// Only the explicit fault experiment enables these one-shot barriers.
func FileBarrier(dir string) func(context.Context, pipeline.Job, string) error {
return func(ctx context.Context, j pipeline.Job, phase string) error {
base := filepath.Join(dir, fmt.Sprintf("%s-v%d-%s", j.AttachmentID, j.PipelineVersion, phase))
return faultbarrier.Wait(ctx, base, "")
}
}
+70
View File
@@ -0,0 +1,70 @@
package processing
import (
"context"
"encoding/json"
"log/slog"
"time"
"messenger/internal/broker"
"messenger/internal/pipeline"
"messenger/internal/platform/config"
)
func retryPolicy(cfg config.Jobs) pipeline.RetryPolicy {
return pipeline.RetryPolicy{MaxAttempts: cfg.MaxAttempts, BaseDelay: time.Second, MaxDelay: time.Minute}
}
func pause(ctx context.Context, d time.Duration) {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}
func Dispatch(ctx context.Context, log *slog.Logger, store *pipeline.Store, cfg config.Jobs, barrier func(context.Context, pipeline.Job, string) error) {
var p *broker.Publisher
defer func() {
if p != nil {
p.Close()
}
}()
for ctx.Err() == nil {
_, err := store.RecoverOne(ctx, retryPolicy(cfg))
if err == nil && p == nil {
p, err = broker.NewPublisher(ctx, cfg.URL)
}
if err == nil {
var sent bool
sent, err = store.PublishOne(ctx, func(ctx context.Context, j pipeline.Job) error {
body, err := json.Marshal(j)
if err != nil {
return err
}
if err := p.Publish(ctx, body); err != nil {
return err
}
if barrier != nil {
return barrier(ctx, j, "published")
}
return nil
})
if err == nil {
if !sent {
pause(ctx, 250*time.Millisecond)
}
continue
}
}
if p != nil {
p.Close()
p = nil
}
if ctx.Err() == nil {
log.Warn("attachment dispatcher will retry", "error", err)
}
pause(ctx, time.Second)
}
}
+176
View File
@@ -0,0 +1,176 @@
package processing
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"io"
"log/slog"
"sync"
"time"
"messenger/internal/attachment"
"messenger/internal/broker"
"messenger/internal/imaging"
"messenger/internal/pipeline"
"messenger/internal/platform/config"
)
var errSourceMismatch = errors.New("original differs from accepted metadata")
type Worker struct {
Store *pipeline.Store
Blobs attachment.Blobs
Config config.Jobs
Log *slog.Logger
// An experiment may pause an individual attempt at an exact durability boundary.
Checkpoint func(context.Context, pipeline.Job, string) error
}
func (w *Worker) Run(ctx context.Context) {
var wg sync.WaitGroup
for range w.Config.Concurrency {
wg.Go(func() {
for ctx.Err() == nil {
err := w.consume(ctx)
if ctx.Err() == nil {
w.Log.Warn("consumer reconnecting", "error", err)
pause(ctx, time.Second)
}
}
})
}
wg.Wait()
}
func (w *Worker) consume(ctx context.Context) error {
c, err := broker.NewConsumer(ctx, w.Config.URL)
if err != nil {
return err
}
defer c.Close()
for d := range c.Deliveries {
var j pipeline.Job
dec := json.NewDecoder(bytes.NewReader(d.Body))
dec.DisallowUnknownFields()
if err := dec.Decode(&j); err != nil || !j.Valid() || dec.Decode(new(any)) != io.EOF {
w.Log.Warn("discarding invalid attachment envelope")
if err := d.Reject(false); err != nil {
return err
}
continue
}
if err := w.process(ctx, j); err != nil {
return err
}
if err := d.Ack(false); err != nil {
return err
}
if err := w.checkpoint(ctx, j, "acked"); err != nil {
return err
}
}
return errors.New("broker delivery stream closed")
}
func (w *Worker) checkpoint(ctx context.Context, j pipeline.Job, phase string) error {
if w.Checkpoint != nil {
return w.Checkpoint(ctx, j, phase)
}
return nil
}
func (w *Worker) process(ctx context.Context, j pipeline.Job) error {
c, err := w.Store.Claim(ctx, j, w.Config.Timeout+5*time.Second)
if err != nil {
return err
}
if c == nil {
return w.checkpoint(ctx, j, "duplicate")
}
if err := w.checkpoint(ctx, j, "claimed"); err != nil {
return err
}
jobCtx, cancel := context.WithTimeout(ctx, w.Config.Timeout)
defer cancel()
variants, err := w.writeObjects(jobCtx, c)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
code := "processing_failed"
permanent := false
switch {
case errors.Is(err, imaging.ErrInvalidImage):
code, permanent = "invalid_image", true
case errors.Is(err, errSourceMismatch):
code, permanent = "source_mismatch", true
case errors.Is(err, attachment.ErrObjectMissing):
code = "source_missing"
}
w.Log.Warn("attachment attempt failed", "job_id", j.JobID, "attempt", j.Attempt, "error_code", code)
_, err = w.Store.Fail(ctx, c, code, permanent, retryPolicy(w.Config))
return err
}
if err := w.checkpoint(ctx, j, "objects"); err != nil {
return err
}
saved, err := w.Store.Complete(ctx, c, variants)
if err != nil || !saved {
return err
}
return w.checkpoint(ctx, j, "committed")
}
func readOriginal(ctx context.Context, blobs attachment.Blobs, c *pipeline.Claim) ([]byte, error) {
if c.SizeBytes < 1 || c.SizeBytes > 10<<20 {
return nil, errSourceMismatch
}
r, err := blobs.Open(ctx, c.SourceKey)
if err != nil {
return nil, err
}
data, err := io.ReadAll(io.LimitReader(r, c.SizeBytes+1))
closeErr := r.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
h := sha256.Sum256(data)
if int64(len(data)) != c.SizeBytes || !bytes.Equal(h[:], c.Hash) {
return nil, errSourceMismatch
}
return data, nil
}
func (w *Worker) writeObjects(ctx context.Context, c *pipeline.Claim) ([]pipeline.Variant, error) {
data, err := readOriginal(ctx, w.Blobs, c)
if err != nil {
return nil, err
}
encoded, err := imaging.Render(ctx, data, c.PipelineVersion)
if err != nil {
return nil, err
}
key := attachment.BlobKey(c.Hash)
if c.SourceKey != key {
if err := w.Blobs.Put(ctx, key, bytes.NewReader(data), c.SizeBytes, c.MIMEType); err != nil {
return nil, err
}
}
var variants []pipeline.Variant
for _, v := range encoded {
hash := sha256.Sum256(v.Data)
key := pipeline.VariantKey(c.AttachmentID, c.PipelineVersion, v.Name, hash[:])
n := int64(len(v.Data))
if err := w.Blobs.Put(ctx, key, bytes.NewReader(v.Data), n, v.MIMEType); err != nil {
return nil, err
}
variants = append(variants, pipeline.Variant{Name: v.Name, Key: key, MIMEType: v.MIMEType, Width: v.Width, Height: v.Height, SizeBytes: n, SHA256: hash[:]})
}
return variants, nil
}
+37
View File
@@ -0,0 +1,37 @@
package processing
import (
"context"
"crypto/sha256"
"errors"
"io"
"strings"
"testing"
"messenger/internal/attachment"
"messenger/internal/pipeline"
)
type stagedSource struct {
attachment.Blobs
body string
}
func (s stagedSource) Open(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader(s.body)), nil
}
func TestReadOriginalValidatesPersistedSizeAndDigest(t *testing.T) {
h := sha256.Sum256([]byte("accepted"))
c := &pipeline.Claim{SizeBytes: 8, Hash: h[:], SourceKey: "staging/test"}
for _, bad := range []string{"truncated", "altered!", "oversized bytes"} {
_, err := readOriginal(t.Context(), stagedSource{body: bad}, c)
if !errors.Is(err, errSourceMismatch) {
t.Fatalf("body %q: %v", bad, err)
}
}
got, err := readOriginal(t.Context(), stagedSource{body: "accepted"}, c)
if err != nil || string(got) != "accepted" {
t.Fatalf("valid original: %v", err)
}
}