feat(outbox): relay committed outbox events to Kafka
This commit is contained in:
1 parent
78f1651f6b
commit
6c3b34f73e
42 files changed
+3731
-45
No files matched your search
@@ -0,0 +1,76 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// EnvelopeVersion identifies the layout of the record value. It changes only
|
||||
// when envelope fields change; the payload layout of each event type is
|
||||
// versioned separately by schema_version.
|
||||
const EnvelopeVersion = 1
|
||||
|
||||
// Record header names. Consumers can route and deduplicate on headers without
|
||||
// decoding the value.
|
||||
const (
|
||||
headerEventID = "event_id"
|
||||
headerEventType = "event_type"
|
||||
headerSchemaVersion = "schema_version"
|
||||
)
|
||||
|
||||
// recordKeySeparator joins the aggregate type and ID in the record key.
|
||||
// Aggregate types are snake_case, so the separator cannot occur in them.
|
||||
const recordKeySeparator = ":"
|
||||
|
||||
// envelope is the JSON record value. Field names are part of the published
|
||||
// contract; see the transactional outbox section of ARCHITECTURE.md.
|
||||
type envelope struct {
|
||||
EnvelopeVersion int `json:"envelope_version"`
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
EventType string `json:"event_type"`
|
||||
SchemaVersion int32 `json:"schema_version"`
|
||||
AggregateType string `json:"aggregate_type"`
|
||||
AggregateID uuid.UUID `json:"aggregate_id"`
|
||||
AggregateVersion int64 `json:"aggregate_version"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
}
|
||||
|
||||
// newRecord builds the Kafka record for event. The key is the aggregate type
|
||||
// and ID, so the default partitioner keeps all events of one aggregate in one
|
||||
// partition and their relative order.
|
||||
func newRecord(topic string, event outbound.OutboxEvent) (*kgo.Record, error) {
|
||||
value, err := json.Marshal(envelope{
|
||||
EnvelopeVersion: EnvelopeVersion,
|
||||
EventID: event.EventID,
|
||||
EventType: event.EventType,
|
||||
SchemaVersion: event.SchemaVersion,
|
||||
AggregateType: event.AggregateType,
|
||||
AggregateID: event.AggregateID,
|
||||
AggregateVersion: event.AggregateVersion,
|
||||
OccurredAt: event.OccurredAt.UTC(),
|
||||
Payload: event.Payload,
|
||||
})
|
||||
if err != nil {
|
||||
// json.Marshal reports only the invalid payload position, not its
|
||||
// content, but the cause is dropped to keep payload text out of logs.
|
||||
return nil, fmt.Errorf("kafka.newRecord - encode envelope of event %s: payload is not valid JSON", event.EventID)
|
||||
}
|
||||
return &kgo.Record{
|
||||
Topic: topic,
|
||||
Key: []byte(event.AggregateType + recordKeySeparator + event.AggregateID.String()),
|
||||
Value: value,
|
||||
Headers: []kgo.RecordHeader{
|
||||
{Key: headerEventID, Value: []byte(event.EventID.String())},
|
||||
{Key: headerEventType, Value: []byte(event.EventType)},
|
||||
{Key: headerSchemaVersion, Value: []byte(strconv.FormatInt(int64(event.SchemaVersion), 10))},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const testTopic = "lincodex.domain.events"
|
||||
|
||||
func testEvent() outbound.OutboxEvent {
|
||||
return outbound.OutboxEvent{
|
||||
EventID: uuid.MustParse("01920000-0000-7000-8000-000000000001"),
|
||||
EventType: "identity.user_registered",
|
||||
SchemaVersion: 2,
|
||||
AggregateType: "user",
|
||||
AggregateID: uuid.MustParse("6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a"),
|
||||
AggregateVersion: 7,
|
||||
// jsonb text output, as PostgreSQL returns it.
|
||||
Payload: json.RawMessage(`{"user_id": "6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a", "nested": {"n": 1}}`),
|
||||
OccurredAt: time.Date(2026, 10, 6, 12, 30, 0, 123456000, time.FixedZone("UTC+3", 3*60*60)),
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRecordEncodesTheEnvelope(t *testing.T) {
|
||||
record, err := newRecord(testTopic, testEvent())
|
||||
if err != nil {
|
||||
t.Fatalf("newRecord() error = %v", err)
|
||||
}
|
||||
if record.Topic != testTopic {
|
||||
t.Fatalf("topic = %q, want %q", record.Topic, testTopic)
|
||||
}
|
||||
if got, want := string(record.Key), "user:6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a"; got != want {
|
||||
t.Fatalf("key = %q, want %q", got, want)
|
||||
}
|
||||
want := `{"envelope_version":1,"event_id":"01920000-0000-7000-8000-000000000001",` +
|
||||
`"event_type":"identity.user_registered","schema_version":2,"aggregate_type":"user",` +
|
||||
`"aggregate_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","aggregate_version":7,` +
|
||||
`"occurred_at":"2026-10-06T09:30:00.123456Z",` +
|
||||
`"payload":{"user_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","nested":{"n":1}}}`
|
||||
if string(record.Value) != want {
|
||||
t.Fatalf("value =\n%s\nwant\n%s", record.Value, want)
|
||||
}
|
||||
headers := make(map[string]string, len(record.Headers))
|
||||
for _, header := range record.Headers {
|
||||
headers[header.Key] = string(header.Value)
|
||||
}
|
||||
wantHeaders := map[string]string{
|
||||
"event_id": "01920000-0000-7000-8000-000000000001",
|
||||
"event_type": "identity.user_registered",
|
||||
"schema_version": "2",
|
||||
}
|
||||
if len(headers) != len(wantHeaders) || len(record.Headers) != len(wantHeaders) {
|
||||
t.Fatalf("headers = %v, want %v", headers, wantHeaders)
|
||||
}
|
||||
for key, value := range wantHeaders {
|
||||
if headers[key] != value {
|
||||
t.Fatalf("header %s = %q, want %q", key, headers[key], value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRecordKeepsAggregatesOnSeparateKeys(t *testing.T) {
|
||||
first := testEvent()
|
||||
sameAggregate := testEvent()
|
||||
sameAggregate.EventID = uuid.New()
|
||||
sameAggregate.AggregateVersion++
|
||||
otherType := testEvent()
|
||||
otherType.AggregateType = "company"
|
||||
|
||||
keys := make([]string, 0, 3)
|
||||
for _, event := range []outbound.OutboxEvent{first, sameAggregate, otherType} {
|
||||
record, err := newRecord(testTopic, event)
|
||||
if err != nil {
|
||||
t.Fatalf("newRecord() error = %v", err)
|
||||
}
|
||||
keys = append(keys, string(record.Key))
|
||||
}
|
||||
if keys[0] != keys[1] {
|
||||
t.Fatalf("versions of one aggregate have keys %q and %q, want one key", keys[0], keys[1])
|
||||
}
|
||||
if keys[0] == keys[2] {
|
||||
t.Fatalf("aggregates of different types share key %q", keys[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRecordRejectsAnInvalidPayloadWithoutQuotingIt(t *testing.T) {
|
||||
event := testEvent()
|
||||
event.Payload = json.RawMessage(`{"token": "secret-value"`)
|
||||
_, err := newRecord(testTopic, event)
|
||||
if err == nil {
|
||||
t.Fatal("newRecord() accepted an invalid payload")
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-value") {
|
||||
t.Fatalf("newRecord() error quotes the payload: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), event.EventID.String()) {
|
||||
t.Fatalf("newRecord() error = %v, want the event ID", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kadm"
|
||||
"github.com/twmb/franz-go/pkg/kerr"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// maxRecordRetries bounds the client's own retries of one record within a
|
||||
// publish call. The relay retries unacknowledged events on later passes, so
|
||||
// the client does not need to retry indefinitely.
|
||||
const maxRecordRetries = 5
|
||||
|
||||
// errNotAcknowledged reports an event whose broker acknowledgement did not
|
||||
// arrive before the publish deadline. The broker may still have stored it.
|
||||
var errNotAcknowledged = errors.New("event not acknowledged before the publish deadline")
|
||||
|
||||
// minInsyncReplicasConfig is the topic setting that acks=all writes need from
|
||||
// the in-sync replicas.
|
||||
const minInsyncReplicasConfig = "min.insync.replicas"
|
||||
|
||||
// Publisher implements outbound.EventPublisher with a franz-go producer. All
|
||||
// events go to one topic; the record key keeps each aggregate's events in one
|
||||
// partition.
|
||||
type Publisher struct {
|
||||
client *kgo.Client
|
||||
admin *kadm.Client
|
||||
logger *slog.Logger
|
||||
topic string
|
||||
partitions int32
|
||||
replicationFactor int16
|
||||
minInsyncReplicas int16
|
||||
provisionTopics bool
|
||||
produceTimeout time.Duration
|
||||
// layoutReported keeps the warning about an existing topic with another
|
||||
// layout to one log line per process.
|
||||
layoutReported atomic.Bool
|
||||
}
|
||||
|
||||
var _ outbound.EventPublisher = (*Publisher)(nil)
|
||||
|
||||
// NewPublisher creates the producer without connecting; franz-go dials brokers
|
||||
// on first use, so an unavailable broker does not block startup. The returned
|
||||
// cleanup closes the client and fails records that are still buffered.
|
||||
func NewPublisher(settings config.Config, logger *slog.Logger) (*Publisher, func(), error) {
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(settings.KafkaBrokers...),
|
||||
// Idempotent writes stay enabled (the franz-go default), which needs
|
||||
// acks from all in-sync replicas.
|
||||
kgo.RequiredAcks(kgo.AllISRAcks()),
|
||||
// Without this option an idempotent record that is already in flight
|
||||
// cannot be failed until the broker answers, so a hung broker would
|
||||
// hold the relay transaction open indefinitely. Failing it keeps the
|
||||
// publish deadline; a retried event may then be stored twice, which
|
||||
// the at-least-once contract already allows.
|
||||
kgo.AllowIdempotentProduceCancellation(),
|
||||
kgo.RecordDeliveryTimeout(settings.RelayProduceTimeout),
|
||||
kgo.RecordRetries(maxRecordRetries),
|
||||
// Linger would delay every pass by its full value, because a pass
|
||||
// produces its whole batch at once and then only waits. Without it the
|
||||
// first record leaves at once and franz-go batches the records produced
|
||||
// while that request is in flight (up to five idempotent requests per
|
||||
// broker), so a pass needs a few requests at most.
|
||||
kgo.ProducerLinger(0),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("kafka.NewPublisher - create Kafka client: %w", err)
|
||||
}
|
||||
publisher := &Publisher{
|
||||
client: client,
|
||||
admin: kadm.NewClient(client),
|
||||
logger: logger,
|
||||
topic: settings.KafkaEventsTopic,
|
||||
partitions: settings.KafkaEventsTopicPartitions,
|
||||
replicationFactor: settings.KafkaEventsTopicReplicationFactor,
|
||||
minInsyncReplicas: settings.KafkaEventsTopicMinInsyncReplicas,
|
||||
provisionTopics: settings.KafkaProvisionTopics,
|
||||
produceTimeout: settings.RelayProduceTimeout,
|
||||
}
|
||||
return publisher, client.Close, nil
|
||||
}
|
||||
|
||||
// Prepare creates the events topic with the configured partitions,
|
||||
// replication factor, and min.insync.replicas unless it already exists; -1
|
||||
// and 0 leave the last two to the broker defaults. It does not change an
|
||||
// existing topic and warns once when that topic has another partition count
|
||||
// or replication factor. With topic provisioning disabled it does nothing,
|
||||
// and a missing topic makes every publish fail.
|
||||
func (publisher *Publisher) Prepare(ctx context.Context) error {
|
||||
if !publisher.provisionTopics {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, publisher.produceTimeout)
|
||||
defer cancel()
|
||||
var topicConfigs map[string]*string
|
||||
if publisher.minInsyncReplicas > 0 {
|
||||
value := strconv.Itoa(int(publisher.minInsyncReplicas))
|
||||
topicConfigs = map[string]*string{minInsyncReplicasConfig: &value}
|
||||
}
|
||||
responses, err := publisher.admin.CreateTopics(ctx, publisher.partitions, publisher.replicationFactor, topicConfigs, publisher.topic)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Publisher.Prepare - create topic %s: %w", publisher.topic, err)
|
||||
}
|
||||
response, err := responses.On(publisher.topic, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Publisher.Prepare - read create topic response for %s: %w", publisher.topic, err)
|
||||
}
|
||||
if response.Err != nil && !errors.Is(response.Err, kerr.TopicAlreadyExists) {
|
||||
return fmt.Errorf("Publisher.Prepare - create topic %s: %w", publisher.topic, response.Err)
|
||||
}
|
||||
if response.Err != nil {
|
||||
publisher.reportExistingLayout(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reportExistingLayout warns once when the existing topic differs from the
|
||||
// configured layout. The check is advisory: a failed metadata read leaves the
|
||||
// topic as it is and logs nothing.
|
||||
func (publisher *Publisher) reportExistingLayout(ctx context.Context) {
|
||||
if publisher.layoutReported.Load() {
|
||||
return
|
||||
}
|
||||
topics, err := publisher.admin.ListTopics(ctx, publisher.topic)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
detail, ok := topics[publisher.topic]
|
||||
if !ok || detail.Err != nil {
|
||||
return
|
||||
}
|
||||
partitions, replicas, differs := layoutDiffers(detail, publisher.partitions, publisher.replicationFactor)
|
||||
if differs && publisher.layoutReported.CompareAndSwap(false, true) {
|
||||
publisher.logger.Warn("existing events topic differs from the configured layout; the relay does not change it",
|
||||
slog.Int("partitions", partitions),
|
||||
slog.Int("configured_partitions", int(publisher.partitions)),
|
||||
slog.Int("replication_factor", replicas),
|
||||
slog.Int("configured_replication_factor", int(publisher.replicationFactor)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// layoutDiffers compares an existing topic with the configured partition
|
||||
// count and replication factor. A replication factor of -1 accepts any
|
||||
// broker default.
|
||||
func layoutDiffers(detail kadm.TopicDetail, partitions int32, replicationFactor int16) (actualPartitions, actualReplicas int, differs bool) {
|
||||
actualPartitions = len(detail.Partitions)
|
||||
actualReplicas = detail.Partitions.NumReplicas()
|
||||
differs = actualPartitions != int(partitions) ||
|
||||
(replicationFactor > 0 && actualReplicas != int(replicationFactor))
|
||||
return actualPartitions, actualReplicas, differs
|
||||
}
|
||||
|
||||
// Publish produces every event and waits at most the produce timeout for the
|
||||
// acknowledgements. Results that do not arrive in time stay errors; the
|
||||
// promises of abandoned records write to a buffered channel and never block.
|
||||
func (publisher *Publisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
results := make([]error, len(events))
|
||||
if len(events) == 0 {
|
||||
return results
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, publisher.produceTimeout)
|
||||
defer cancel()
|
||||
|
||||
type outcome struct {
|
||||
index int
|
||||
err error
|
||||
}
|
||||
outcomes := make(chan outcome, len(events))
|
||||
for index, event := range events {
|
||||
results[index] = errNotAcknowledged
|
||||
record, err := newRecord(publisher.topic, event)
|
||||
if err != nil {
|
||||
outcomes <- outcome{index: index, err: err}
|
||||
continue
|
||||
}
|
||||
publisher.client.Produce(ctx, record, func(_ *kgo.Record, err error) {
|
||||
outcomes <- outcome{index: index, err: err}
|
||||
})
|
||||
}
|
||||
|
||||
for range events {
|
||||
select {
|
||||
case result := <-outcomes:
|
||||
results[result.index] = nil
|
||||
if result.err != nil {
|
||||
results[result.index] = produceError(events[result.index], result.err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
for index, err := range results {
|
||||
if errors.Is(err, errNotAcknowledged) {
|
||||
results[index] = fmt.Errorf("Publisher.Publish - produce event %s: %w: %w", events[index].EventID, errNotAcknowledged, ctx.Err())
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// produceError wraps a failed record. A missing topic also matches
|
||||
// outbound.ErrEventDestinationMissing, so the relay provisions it again.
|
||||
func produceError(event outbound.OutboxEvent, err error) error {
|
||||
if errors.Is(err, kerr.UnknownTopicOrPartition) || errors.Is(err, kerr.UnknownTopicID) {
|
||||
return fmt.Errorf("Publisher.Publish - produce event %s: %w: %w", event.EventID, outbound.ErrEventDestinationMissing, err)
|
||||
}
|
||||
return fmt.Errorf("Publisher.Publish - produce event %s: %w", event.EventID, err)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kadm"
|
||||
"github.com/twmb/franz-go/pkg/kerr"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
unitProduceTimeout = time.Second
|
||||
// publishBoundSlack covers scheduling around the produce timeout.
|
||||
publishBoundSlack = 2 * time.Second
|
||||
)
|
||||
|
||||
// unreachableBroker returns the address of a closed local port, so every
|
||||
// connection attempt is refused.
|
||||
func unreachableBroker(t *testing.T) string {
|
||||
t.Helper()
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
address := listener.Addr().String()
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatalf("close listener: %v", err)
|
||||
}
|
||||
return address
|
||||
}
|
||||
|
||||
func newUnitPublisher(t *testing.T, provision bool) *Publisher {
|
||||
t.Helper()
|
||||
publisher, cleanup, err := NewPublisher(config.Config{
|
||||
KafkaBrokers: []string{unreachableBroker(t)},
|
||||
KafkaEventsTopic: testTopic,
|
||||
KafkaEventsTopicPartitions: 1,
|
||||
KafkaEventsTopicReplicationFactor: 1,
|
||||
KafkaProvisionTopics: provision,
|
||||
RelayProduceTimeout: unitProduceTimeout,
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("NewPublisher() error = %v", err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
return publisher
|
||||
}
|
||||
|
||||
func TestPublishFailsEveryEventWithinTheProduceTimeoutWhenBrokersAreDown(t *testing.T) {
|
||||
publisher := newUnitPublisher(t, true)
|
||||
events := []outbound.OutboxEvent{testEvent(), testEvent()}
|
||||
events[1].AggregateVersion++
|
||||
|
||||
started := time.Now()
|
||||
results := publisher.Publish(context.Background(), events)
|
||||
if elapsed := time.Since(started); elapsed > unitProduceTimeout+publishBoundSlack {
|
||||
t.Fatalf("Publish() took %s, want about the %s produce timeout", elapsed, unitProduceTimeout)
|
||||
}
|
||||
if len(results) != len(events) {
|
||||
t.Fatalf("Publish() returned %d results for %d events", len(results), len(events))
|
||||
}
|
||||
for index, err := range results {
|
||||
if err == nil {
|
||||
t.Fatalf("event %d acknowledged without a broker", index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishReportsAnUnencodableEventWithoutDroppingOthers(t *testing.T) {
|
||||
publisher := newUnitPublisher(t, true)
|
||||
invalid := testEvent()
|
||||
invalid.Payload = []byte(`{`)
|
||||
results := publisher.Publish(context.Background(), []outbound.OutboxEvent{invalid, testEvent()})
|
||||
if len(results) != 2 || results[0] == nil || results[1] == nil {
|
||||
t.Fatalf("Publish() results = %v, want two errors", results)
|
||||
}
|
||||
if errors.Is(results[0], errNotAcknowledged) {
|
||||
t.Fatalf("encoding failure reported as a timeout: %v", results[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishWithoutEventsDoesNothing(t *testing.T) {
|
||||
publisher := newUnitPublisher(t, true)
|
||||
if results := publisher.Publish(context.Background(), nil); len(results) != 0 {
|
||||
t.Fatalf("Publish(nil) = %v, want no results", results)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareSkipsProvisioningWhenDisabled(t *testing.T) {
|
||||
publisher := newUnitPublisher(t, false)
|
||||
if err := publisher.Prepare(context.Background()); err != nil {
|
||||
t.Fatalf("Prepare() error = %v, want nil without contacting the broker", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareFailsWithinTheTimeoutWhenBrokersAreDown(t *testing.T) {
|
||||
publisher := newUnitPublisher(t, true)
|
||||
started := time.Now()
|
||||
if err := publisher.Prepare(context.Background()); err == nil {
|
||||
t.Fatal("Prepare() created a topic without a broker")
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > unitProduceTimeout+publishBoundSlack {
|
||||
t.Fatalf("Prepare() took %s, want about the %s timeout", elapsed, unitProduceTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProduceErrorMarksAMissingTopic(t *testing.T) {
|
||||
event := testEvent()
|
||||
for _, cause := range []error{kerr.UnknownTopicOrPartition, fmt.Errorf("load metadata: %w", kerr.UnknownTopicID)} {
|
||||
if err := produceError(event, cause); !errors.Is(err, outbound.ErrEventDestinationMissing) || !errors.Is(err, cause) {
|
||||
t.Fatalf("produceError(%v) = %v, want ErrEventDestinationMissing and the cause", cause, err)
|
||||
}
|
||||
}
|
||||
if err := produceError(event, kerr.NotEnoughReplicas); errors.Is(err, outbound.ErrEventDestinationMissing) {
|
||||
t.Fatalf("produceError(NotEnoughReplicas) = %v, want no missing destination", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLayoutDiffersComparesPartitionsAndExplicitReplication(t *testing.T) {
|
||||
detail := kadm.TopicDetail{Partitions: kadm.PartitionDetails{
|
||||
0: {Partition: 0, Replicas: []int32{1, 2, 3}},
|
||||
1: {Partition: 1, Replicas: []int32{2, 3, 1}},
|
||||
}}
|
||||
tests := []struct {
|
||||
name string
|
||||
partitions int32
|
||||
replicationFactor int16
|
||||
want bool
|
||||
}{
|
||||
{name: "same layout", partitions: 2, replicationFactor: 3, want: false},
|
||||
{name: "broker default replication", partitions: 2, replicationFactor: -1, want: false},
|
||||
{name: "other partition count", partitions: 3, replicationFactor: -1, want: true},
|
||||
{name: "other replication factor", partitions: 2, replicationFactor: 1, want: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
partitions, replicas, differs := layoutDiffers(detail, test.partitions, test.replicationFactor)
|
||||
if differs != test.want || partitions != 2 || replicas != 3 {
|
||||
t.Fatalf("layoutDiffers() = %d, %d, %t; want 2, 3, %t", partitions, replicas, differs, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// OutboxRelayStore implements outbound.OutboxRelayStore with a pgx pool owned
|
||||
// by the caller. Each claim holds one connection and one transaction for the
|
||||
// duration of the publish callback.
|
||||
type OutboxRelayStore struct {
|
||||
pool *pgxpool.Pool
|
||||
timeouts OutboxRelayTimeouts
|
||||
}
|
||||
|
||||
// OutboxRelayTimeouts bound the claim transaction on the PostgreSQL server.
|
||||
//
|
||||
// The relay context already cancels a pass whose client is alive. These
|
||||
// limits are set with SET LOCAL at the start of the transaction because they
|
||||
// also hold when the client cannot act: a frozen process, or a network path
|
||||
// that drops without closing the connection, would otherwise keep the row
|
||||
// locks and an open transaction until TCP keepalive notices, which delays
|
||||
// other relays and vacuum.
|
||||
type OutboxRelayTimeouts struct {
|
||||
// Statement bounds every statement of the claim (statement_timeout).
|
||||
Statement time.Duration
|
||||
// IdleInTransaction bounds the gap between statements, which is the
|
||||
// publish call (idle_in_transaction_session_timeout). It must exceed the
|
||||
// publish deadline, or a slow but successful publish loses its mark.
|
||||
IdleInTransaction time.Duration
|
||||
}
|
||||
|
||||
func NewOutboxRelayStore(pool *pgxpool.Pool, timeouts OutboxRelayTimeouts) *OutboxRelayStore {
|
||||
return &OutboxRelayStore{pool: pool, timeouts: timeouts}
|
||||
}
|
||||
|
||||
var _ outbound.OutboxRelayStore = (*OutboxRelayStore)(nil)
|
||||
|
||||
func (store *OutboxRelayStore) ClaimPending(ctx context.Context, limit int, publish outbound.PublishOutboxBatch) error {
|
||||
if limit <= 0 || limit > math.MaxInt32 {
|
||||
return fmt.Errorf("OutboxRelayStore.ClaimPending - limit must be between 1 and %d", math.MaxInt32)
|
||||
}
|
||||
// PostgreSQL reads 0 as no limit, so a value below one millisecond would
|
||||
// silently remove the bound.
|
||||
if store.timeouts.Statement < time.Millisecond || store.timeouts.IdleInTransaction < time.Millisecond {
|
||||
return errors.New("OutboxRelayStore.ClaimPending - statement and idle timeouts must be at least 1ms")
|
||||
}
|
||||
tx, err := store.pool.BeginTx(ctx, transactionOptions)
|
||||
if err != nil {
|
||||
return fmt.Errorf("OutboxRelayStore.ClaimPending - begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
// Runs only when publish panics; the panic keeps its stack and the
|
||||
// rollback error cannot change that outcome.
|
||||
if !finished {
|
||||
_ = rollback(ctx, tx)
|
||||
}
|
||||
}()
|
||||
|
||||
claimErr := claimPending(ctx, tx, int32(limit), store.timeouts, publish)
|
||||
finished = true
|
||||
if claimErr != nil {
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return errors.Join(claimErr, fmt.Errorf("OutboxRelayStore.ClaimPending - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
return claimErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", relayDatabaseError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRelayTimeouts, publish outbound.PublishOutboxBatch) error {
|
||||
queries := sqlc.New(tx)
|
||||
err := queries.SetRelayTransactionTimeouts(ctx, sqlc.SetRelayTransactionTimeoutsParams{
|
||||
StatementTimeoutMs: milliseconds(timeouts.Statement),
|
||||
IdleTimeoutMs: milliseconds(timeouts.IdleInTransaction),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", relayDatabaseError(err))
|
||||
}
|
||||
rows, err := queries.LockPendingOutboxEvents(ctx, limit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.claimPending - lock pending events: %w", relayDatabaseError(err))
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
events := make([]outbound.OutboxEvent, 0, len(rows))
|
||||
claimed := make(map[uuid.UUID]bool, len(rows))
|
||||
for _, row := range rows {
|
||||
event := outboxEventFromRow(row)
|
||||
events = append(events, event)
|
||||
claimed[event.EventID] = true
|
||||
}
|
||||
|
||||
acknowledged := publish(ctx, events)
|
||||
marked := make([]pgtype.UUID, 0, len(acknowledged))
|
||||
seen := make(map[uuid.UUID]bool, len(acknowledged))
|
||||
for _, eventID := range acknowledged {
|
||||
// An ID outside the batch could be locked by another relay, and the
|
||||
// update would wait for it, so it is a caller error.
|
||||
if !claimed[eventID] {
|
||||
return errors.New("postgres.claimPending - acknowledged event is not in the claimed batch")
|
||||
}
|
||||
if seen[eventID] {
|
||||
continue
|
||||
}
|
||||
seen[eventID] = true
|
||||
marked = append(marked, pgtype.UUID{Bytes: eventID, Valid: true})
|
||||
}
|
||||
if len(marked) == 0 {
|
||||
return nil
|
||||
}
|
||||
count, err := queries.MarkOutboxEventsPublished(ctx, marked)
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.claimPending - mark published events: %w", relayDatabaseError(err))
|
||||
}
|
||||
if count != int64(len(marked)) {
|
||||
return fmt.Errorf("postgres.claimPending - marked %d events, want %d", count, len(marked))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Backlog reads the pending count and the age of the earliest pending event.
|
||||
func (store *OutboxRelayStore) Backlog(ctx context.Context) (outbound.OutboxBacklog, error) {
|
||||
row, err := sqlc.New(store.pool).GetOutboxBacklog(ctx)
|
||||
if err != nil {
|
||||
return outbound.OutboxBacklog{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", relayDatabaseError(err))
|
||||
}
|
||||
return outbound.OutboxBacklog{
|
||||
Pending: row.PendingEvents,
|
||||
OldestAge: time.Duration(row.OldestPendingAgeSeconds * float64(time.Second)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// milliseconds formats a duration as a PostgreSQL time setting in
|
||||
// milliseconds, the unit set_config assumes for these parameters.
|
||||
func milliseconds(duration time.Duration) string {
|
||||
return strconv.FormatInt(duration.Milliseconds(), 10)
|
||||
}
|
||||
|
||||
func outboxEventFromRow(row sqlc.LockPendingOutboxEventsRow) outbound.OutboxEvent {
|
||||
return outbound.OutboxEvent{
|
||||
EventID: row.EventID.Bytes,
|
||||
EventType: row.EventType,
|
||||
SchemaVersion: row.SchemaVersion,
|
||||
AggregateType: row.AggregateType,
|
||||
AggregateID: row.AggregateID.Bytes,
|
||||
AggregateVersion: row.AggregateVersion,
|
||||
Payload: json.RawMessage(row.Payload),
|
||||
OccurredAt: row.OccurredAt.Time,
|
||||
}
|
||||
}
|
||||
|
||||
// relayDatabaseError keeps only the SQLSTATE of a PostgreSQL error, whose
|
||||
// message or detail could quote an event payload, and drops the connection
|
||||
// prefix of a connect error.
|
||||
func relayDatabaseError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) {
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestClaimPendingRejectsAnInvalidLimitBeforeTheDatabase(t *testing.T) {
|
||||
// A nil pool proves that validation happens before any connection.
|
||||
valid := OutboxRelayTimeouts{Statement: time.Second, IdleInTransaction: time.Second}
|
||||
publish := func(context.Context, []outbound.OutboxEvent) []uuid.UUID {
|
||||
t.Fatal("publish called for an invalid claim")
|
||||
return nil
|
||||
}
|
||||
store := NewOutboxRelayStore(nil, valid)
|
||||
for _, limit := range []int{0, -1, 1 << 31} {
|
||||
if err := store.ClaimPending(t.Context(), limit, publish); err == nil {
|
||||
t.Fatalf("ClaimPending(limit %d) accepted the limit", limit)
|
||||
}
|
||||
}
|
||||
// A timeout that rounds to 0 ms would disable the server-side bound.
|
||||
for _, timeouts := range []OutboxRelayTimeouts{
|
||||
{Statement: time.Microsecond, IdleInTransaction: time.Second},
|
||||
{Statement: time.Second},
|
||||
} {
|
||||
if err := NewOutboxRelayStore(nil, timeouts).ClaimPending(t.Context(), 1, publish); err == nil {
|
||||
t.Fatalf("ClaimPending() accepted timeouts %+v", timeouts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayDatabaseErrorKeepsOnlyTheSQLState(t *testing.T) {
|
||||
original := &pgconn.PgError{
|
||||
Code: "22P02",
|
||||
Message: `invalid input syntax for type json: "secret-payload"`,
|
||||
Detail: `Token "secret-payload" is invalid.`,
|
||||
}
|
||||
err := relayDatabaseError(original)
|
||||
if strings.Contains(err.Error(), "secret-payload") {
|
||||
t.Fatalf("relayDatabaseError() kept the message: %v", err)
|
||||
}
|
||||
var stateError sqlStateError
|
||||
if !errors.As(err, &stateError) || stateError.SQLState() != "22P02" {
|
||||
t.Fatalf("relayDatabaseError() = %v, want SQLSTATE 22P02", err)
|
||||
}
|
||||
if conflict := relayDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("relayDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict)
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,9 @@ import (
|
||||
// requires the database before serving. The caller owns the pool and must
|
||||
// close it.
|
||||
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(databaseURL)
|
||||
poolConfig, err := parsePoolConfig(databaseURL)
|
||||
if err != nil {
|
||||
// pgx redacts passwords only on a best-effort basis, so the parse error
|
||||
// is not wrapped to keep the connection string out of logs.
|
||||
return nil, errors.New("postgres.NewPool - DATABASE_URL is not a valid PostgreSQL connection string")
|
||||
return nil, err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
@@ -28,6 +26,35 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// NewSizedPool is NewPool with at most maxConns connections, for a component
|
||||
// whose concurrency is known, so it cannot take connections that request
|
||||
// handling needs.
|
||||
func NewSizedPool(ctx context.Context, databaseURL string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
if maxConns < 1 {
|
||||
return nil, errors.New("postgres.NewSizedPool - maxConns must be positive")
|
||||
}
|
||||
poolConfig, err := parsePoolConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolConfig.MaxConns = maxConns
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("postgres.NewSizedPool - create PostgreSQL pool: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func parsePoolConfig(databaseURL string) (*pgxpool.Config, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
// pgx redacts passwords only on a best-effort basis, so the parse error
|
||||
// is not wrapped to keep the connection string out of logs.
|
||||
return nil, errors.New("postgres.parsePoolConfig - DATABASE_URL is not a valid PostgreSQL connection string")
|
||||
}
|
||||
return poolConfig, nil
|
||||
}
|
||||
|
||||
// sanitizeConnectError drops the pgx connection prefix, which names the
|
||||
// database user and database, while keeping the network or server cause.
|
||||
func sanitizeConnectError(err error) error {
|
||||
|
||||
@@ -11,6 +11,38 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getOutboxBacklog = `-- name: GetOutboxBacklog :one
|
||||
SELECT
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM outbox_events AS pending
|
||||
WHERE pending.published_at IS NULL
|
||||
)::bigint AS pending_events,
|
||||
coalesce((
|
||||
SELECT extract(EPOCH FROM clock_timestamp() - oldest.occurred_at)
|
||||
FROM outbox_events AS oldest
|
||||
WHERE oldest.published_at IS NULL
|
||||
ORDER BY oldest.position
|
||||
LIMIT 1
|
||||
), 0)::float8 AS oldest_pending_age_seconds
|
||||
`
|
||||
|
||||
type GetOutboxBacklogRow struct {
|
||||
PendingEvents int64
|
||||
OldestPendingAgeSeconds float64
|
||||
}
|
||||
|
||||
// Reads the relay backlog for metrics without locking. Both subqueries use
|
||||
// the partial index on unpublished positions, so the cost follows the backlog
|
||||
// size, not the table size. The age comes from the database clock, the same
|
||||
// clock that set occurred_at.
|
||||
func (q *Queries) GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error) {
|
||||
row := q.db.QueryRow(ctx, getOutboxBacklog)
|
||||
var i GetOutboxBacklogRow
|
||||
err := row.Scan(&i.PendingEvents, &i.OldestPendingAgeSeconds)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertOutboxEvent = `-- name: InsertOutboxEvent :exec
|
||||
INSERT INTO outbox_events (
|
||||
event_id,
|
||||
@@ -53,3 +85,124 @@ func (q *Queries) InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventPa
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const lockPendingOutboxEvents = `-- name: LockPendingOutboxEvents :many
|
||||
SELECT
|
||||
pending.event_id,
|
||||
pending.event_type,
|
||||
pending.schema_version,
|
||||
pending.aggregate_type,
|
||||
pending.aggregate_id,
|
||||
pending.aggregate_version,
|
||||
pending.payload,
|
||||
pending.occurred_at
|
||||
FROM outbox_events AS pending
|
||||
WHERE
|
||||
pending.published_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM outbox_events AS earlier
|
||||
WHERE
|
||||
earlier.aggregate_type = pending.aggregate_type
|
||||
AND earlier.aggregate_id = pending.aggregate_id
|
||||
AND earlier.published_at IS NULL
|
||||
AND (earlier.aggregate_version, earlier.position)
|
||||
< (pending.aggregate_version, pending.position)
|
||||
)
|
||||
ORDER BY pending.position
|
||||
LIMIT $1
|
||||
FOR UPDATE OF pending SKIP LOCKED
|
||||
`
|
||||
|
||||
type LockPendingOutboxEventsRow struct {
|
||||
EventID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID pgtype.UUID
|
||||
AggregateVersion int64
|
||||
Payload []byte
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Locks the next relay batch. For each aggregate only its earliest unpublished
|
||||
// event (lowest aggregate_version, then position) qualifies, so a relay never
|
||||
// holds a later version while an earlier one is still pending, whether that
|
||||
// earlier row is locked by another relay or was just rolled back. Rows locked
|
||||
// by another relay are skipped without waiting. The statement snapshot can
|
||||
// only see a later version after the earlier version's transaction committed,
|
||||
// because aggregate writers check the expected version, so scanning without a
|
||||
// position watermark cannot overtake an earlier version.
|
||||
func (q *Queries) LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error) {
|
||||
rows, err := q.db.Query(ctx, lockPendingOutboxEvents, batchLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []LockPendingOutboxEventsRow
|
||||
for rows.Next() {
|
||||
var i LockPendingOutboxEventsRow
|
||||
if err := rows.Scan(
|
||||
&i.EventID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.AggregateType,
|
||||
&i.AggregateID,
|
||||
&i.AggregateVersion,
|
||||
&i.Payload,
|
||||
&i.OccurredAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markOutboxEventsPublished = `-- name: MarkOutboxEventsPublished :execrows
|
||||
UPDATE outbox_events
|
||||
SET published_at = clock_timestamp()
|
||||
WHERE
|
||||
event_id = ANY($1::uuid [])
|
||||
AND published_at IS NULL
|
||||
`
|
||||
|
||||
// Marks the events that the broker acknowledged. The relay passes only IDs
|
||||
// whose rows its own transaction locked, so the statement never waits and the
|
||||
// count equals the number of distinct IDs.
|
||||
func (q *Queries) MarkOutboxEventsPublished(ctx context.Context, eventIds []pgtype.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, markOutboxEventsPublished, eventIds)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const setRelayTransactionTimeouts = `-- name: SetRelayTransactionTimeouts :exec
|
||||
SELECT
|
||||
set_config('statement_timeout', $1::text, true),
|
||||
set_config(
|
||||
'idle_in_transaction_session_timeout',
|
||||
$2::text,
|
||||
true
|
||||
)
|
||||
`
|
||||
|
||||
type SetRelayTransactionTimeoutsParams struct {
|
||||
StatementTimeoutMs string
|
||||
IdleTimeoutMs string
|
||||
}
|
||||
|
||||
// Bounds the claim transaction on the server. statement_timeout stops a
|
||||
// statement that runs too long; idle_in_transaction_session_timeout ends the
|
||||
// session, and with it the transaction and its row locks, when the client
|
||||
// stays silent longer than a publish may take, for example after the process
|
||||
// froze or lost the network without closing the connection. Both settings
|
||||
// are local to the transaction.
|
||||
func (q *Queries) SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error {
|
||||
_, err := q.db.Exec(ctx, setRelayTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
|
||||
return err
|
||||
}
|
||||
@@ -41,6 +41,11 @@ type Querier interface {
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
|
||||
// Reads the relay backlog for metrics without locking. Both subqueries use
|
||||
// the partial index on unpublished positions, so the cost follows the backlog
|
||||
// size, not the table size. The age comes from the database clock, the same
|
||||
// clock that set occurred_at.
|
||||
GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error)
|
||||
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
@@ -55,6 +60,19 @@ type Querier interface {
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// Locks the next relay batch. For each aggregate only its earliest unpublished
|
||||
// event (lowest aggregate_version, then position) qualifies, so a relay never
|
||||
// holds a later version while an earlier one is still pending, whether that
|
||||
// earlier row is locked by another relay or was just rolled back. Rows locked
|
||||
// by another relay are skipped without waiting. The statement snapshot can
|
||||
// only see a later version after the earlier version's transaction committed,
|
||||
// because aggregate writers check the expected version, so scanning without a
|
||||
// position watermark cannot overtake an earlier version.
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
|
||||
// Marks the events that the broker acknowledged. The relay passes only IDs
|
||||
// whose rows its own transaction locked, so the statement never waits and the
|
||||
// count equals the number of distinct IDs.
|
||||
MarkOutboxEventsPublished(ctx context.Context, eventIds []pgtype.UUID) (int64, error)
|
||||
// Verifies the email only for the registration version the consumed token
|
||||
// was issued for.
|
||||
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
|
||||
@@ -64,6 +82,13 @@ type Querier interface {
|
||||
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Bounds the claim transaction on the server. statement_timeout stops a
|
||||
// statement that runs too long; idle_in_transaction_session_timeout ends the
|
||||
// session, and with it the transaction and its row locks, when the client
|
||||
// stays silent longer than a publish may take, for example after the process
|
||||
// froze or lost the network without closing the connection. Both settings
|
||||
// are local to the transaction.
|
||||
SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
|
||||
@@ -8,14 +8,31 @@ import (
|
||||
client "github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type Metrics struct {
|
||||
registry *client.Registry
|
||||
requests *client.CounterVec
|
||||
latency *client.HistogramVec
|
||||
// relayEvents counts outbox events by relay outcome: published or
|
||||
// failed. A failed event stays pending and is counted again on every
|
||||
// retry.
|
||||
relayEvents *client.CounterVec
|
||||
// relayPending and relayOldestAge describe the unpublished outbox
|
||||
// events. Every backend instance reports the same database-wide values,
|
||||
// so dashboards aggregate them with max, not sum.
|
||||
relayPending client.Gauge
|
||||
relayOldestAge client.Gauge
|
||||
}
|
||||
|
||||
// Outbox relay outcome label values.
|
||||
const (
|
||||
relayOutcomePublished = "published"
|
||||
relayOutcomeFailed = "failed"
|
||||
)
|
||||
|
||||
func New() *Metrics {
|
||||
registry := client.NewRegistry()
|
||||
requests := client.NewCounterVec(client.CounterOpts{
|
||||
@@ -27,8 +44,51 @@ func New() *Metrics {
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Buckets: client.DefBuckets,
|
||||
}, []string{"method", "route"})
|
||||
registry.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), requests, latency)
|
||||
return &Metrics{registry: registry, requests: requests, latency: latency}
|
||||
relayEvents := client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_outbox_relay_events_total",
|
||||
Help: "Outbox events handled by the relay, by outcome; failed events stay pending and are retried.",
|
||||
}, []string{"outcome"})
|
||||
relayPending := client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_outbox_relay_pending_events",
|
||||
Help: "Unpublished outbox events at the last backlog read by the relay.",
|
||||
})
|
||||
relayOldestAge := client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_outbox_relay_oldest_pending_age_seconds",
|
||||
Help: "Age of the earliest unpublished outbox event at the last backlog read by the relay; 0 without pending events.",
|
||||
})
|
||||
registry.MustRegister(
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
requests, latency, relayEvents, relayPending, relayOldestAge,
|
||||
)
|
||||
// Expose both series from the start so rate queries see zero, not absence.
|
||||
relayEvents.WithLabelValues(relayOutcomePublished)
|
||||
relayEvents.WithLabelValues(relayOutcomeFailed)
|
||||
return &Metrics{
|
||||
registry: registry,
|
||||
requests: requests,
|
||||
latency: latency,
|
||||
relayEvents: relayEvents,
|
||||
relayPending: relayPending,
|
||||
relayOldestAge: relayOldestAge,
|
||||
}
|
||||
}
|
||||
|
||||
// ObserveOutboxBacklog records the latest backlog read.
|
||||
func (metrics *Metrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
|
||||
metrics.relayPending.Set(float64(backlog.Pending))
|
||||
metrics.relayOldestAge.Set(backlog.OldestAge.Seconds())
|
||||
}
|
||||
|
||||
// ObserveOutboxRelayPass adds the events one relay pass published and those
|
||||
// it claimed but could not publish.
|
||||
func (metrics *Metrics) ObserveOutboxRelayPass(published, failed int) {
|
||||
if published > 0 {
|
||||
metrics.relayEvents.WithLabelValues(relayOutcomePublished).Add(float64(published))
|
||||
}
|
||||
if failed > 0 {
|
||||
metrics.relayEvents.WithLabelValues(relayOutcomeFailed).Add(float64(failed))
|
||||
}
|
||||
}
|
||||
|
||||
func (metrics *Metrics) ObserveRequest(method, route string, status int, duration time.Duration) {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
|
||||
@@ -21,3 +23,38 @@ func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
|
||||
t.Fatalf("metrics output is missing request duration:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesOutboxRelayOutcomes(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveOutboxRelayPass(3, 0)
|
||||
metrics.ObserveOutboxRelayPass(1, 2)
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
|
||||
body := response.Body.String()
|
||||
for _, want := range []string{
|
||||
`lincodex_outbox_relay_events_total{outcome="published"} 4`,
|
||||
`lincodex_outbox_relay_events_total{outcome="failed"} 2`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesTheOutboxBacklog(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveOutboxBacklog(outbound.OutboxBacklog{Pending: 42, OldestAge: 90 * time.Second})
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
|
||||
body := response.Body.String()
|
||||
for _, want := range []string{
|
||||
"lincodex_outbox_relay_pending_events 42",
|
||||
"lincodex_outbox_relay_oldest_pending_age_seconds 90",
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/worker/outboxrelay"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -32,6 +33,9 @@ type Application struct {
|
||||
// mailSender is the transport selected by EMAIL_PROVIDER. No usecase
|
||||
// sends mail yet; the delivery layer will take it from here.
|
||||
mailSender outbound.MailSender
|
||||
// relay publishes outbox events while the servers run. It is nil when
|
||||
// the relay is disabled or the database is not configured.
|
||||
relay *outboxrelay.Relay
|
||||
}
|
||||
|
||||
func NewApplication(
|
||||
@@ -40,8 +44,16 @@ func NewApplication(
|
||||
metrics *prometheus.Metrics,
|
||||
logger *slog.Logger,
|
||||
mailSender outbound.MailSender,
|
||||
relay *outboxrelay.Relay,
|
||||
) *Application {
|
||||
return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger, mailSender: mailSender}
|
||||
return &Application{
|
||||
config: config,
|
||||
apiHandler: apiHandler,
|
||||
metrics: metrics,
|
||||
logger: logger,
|
||||
mailSender: mailSender,
|
||||
relay: relay,
|
||||
}
|
||||
}
|
||||
|
||||
func Run() (runErr error) {
|
||||
@@ -137,10 +149,16 @@ func (application *Application) run(ctx context.Context) error {
|
||||
slog.String("metrics_addr", application.config.MetricsAddr),
|
||||
)
|
||||
|
||||
// The relay stops when the servers stop, including after a server
|
||||
// failure that leaves ctx running.
|
||||
runCtx, stopRun := context.WithCancel(ctx)
|
||||
defer stopRun()
|
||||
relayStopped := application.startRelay(runCtx)
|
||||
|
||||
apiServer := newHTTPServer(application.apiHandler)
|
||||
metricsServer := newHTTPServer(application.metrics.Handler())
|
||||
err = serveServers(
|
||||
ctx,
|
||||
runCtx,
|
||||
apiListener,
|
||||
apiServer,
|
||||
metricsListener,
|
||||
@@ -148,9 +166,28 @@ func (application *Application) run(ctx context.Context) error {
|
||||
application.config.ShutdownTimeout,
|
||||
)
|
||||
application.logger.Info("servers stopped")
|
||||
stopRun()
|
||||
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, so
|
||||
// the cleanup that closes its pool and producer runs after it.
|
||||
<-relayStopped
|
||||
return err
|
||||
}
|
||||
|
||||
// startRelay runs the relay until ctx ends and returns a channel that closes
|
||||
// when it has stopped.
|
||||
func (application *Application) startRelay(ctx context.Context) <-chan struct{} {
|
||||
stopped := make(chan struct{})
|
||||
if application.relay == nil {
|
||||
close(stopped)
|
||||
return stopped
|
||||
}
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
application.relay.Run(ctx)
|
||||
}()
|
||||
return stopped
|
||||
}
|
||||
|
||||
func newHTTPServer(handler http.Handler) *http.Server {
|
||||
return &http.Server{
|
||||
Handler: handler,
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/kafka"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/worker/outboxrelay"
|
||||
)
|
||||
|
||||
const (
|
||||
// relayPoolMaxConns covers the claim transaction and the backlog read,
|
||||
// the only two statements the relay can have open at once.
|
||||
relayPoolMaxConns = 2
|
||||
// relayBacklogInterval matches the usual Prometheus scrape interval, so
|
||||
// the backlog gauges stay current without a count on every busy pass.
|
||||
relayBacklogInterval = 15 * time.Second
|
||||
)
|
||||
|
||||
// newOutboxRelay builds the outbox relay and the resources it owns: a
|
||||
// PostgreSQL pool and a Kafka producer. It returns a nil relay when
|
||||
// RELAY_ENABLED is false or DATABASE_URL is unset; the service then starts
|
||||
// without publishing events and the outbox keeps them. Neither the pool nor
|
||||
// the producer connects here, so an unavailable Kafka never blocks startup:
|
||||
// the relay retries in the background.
|
||||
func newOutboxRelay(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
metrics *prometheus.Metrics,
|
||||
) (*outboxrelay.Relay, func(), error) {
|
||||
if !settings.RelayEnabled {
|
||||
logger.Info("outbox relay is disabled; events stay in the outbox")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("outbox relay skipped because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, relayPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newOutboxRelay - create pool: %w", err)
|
||||
}
|
||||
relayLogger := logger.With(slog.String("component", "outbox_relay"), slog.String("topic", settings.KafkaEventsTopic))
|
||||
publisher, closePublisher, err := kafka.NewPublisher(settings, relayLogger)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newOutboxRelay - create Kafka publisher: %w", err)
|
||||
}
|
||||
relay := outboxrelay.New(
|
||||
postgres.NewOutboxRelayStore(pool, relayTransactionTimeouts(settings)),
|
||||
publisher,
|
||||
metrics,
|
||||
relayLogger,
|
||||
relaySettings(settings),
|
||||
)
|
||||
// The application stops the relay before this cleanup runs, so no pass
|
||||
// uses the producer or the pool while they close.
|
||||
return relay, func() {
|
||||
closePublisher()
|
||||
pool.Close()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func relaySettings(settings config.Config) outboxrelay.Settings {
|
||||
return outboxrelay.Settings{
|
||||
BatchSize: settings.RelayBatchSize,
|
||||
PollInterval: settings.RelayPollInterval,
|
||||
Backoff: outboxrelay.Backoff{
|
||||
Initial: settings.RelayBackoffInitial,
|
||||
Max: settings.RelayBackoffMax,
|
||||
},
|
||||
ShutdownTimeout: settings.ShutdownTimeout,
|
||||
BacklogInterval: relayBacklogInterval,
|
||||
}
|
||||
}
|
||||
|
||||
// relayTransactionTimeouts derives the server-side bounds of a claim. Between
|
||||
// its statements the transaction waits only for the publish, which ends by
|
||||
// RELAY_PRODUCE_TIMEOUT; one statement timeout on top covers the work around
|
||||
// it, so only a client that stopped responding hits the idle limit.
|
||||
func relayTransactionTimeouts(settings config.Config) postgres.OutboxRelayTimeouts {
|
||||
return postgres.OutboxRelayTimeouts{
|
||||
Statement: settings.RelayStatementTimeout,
|
||||
IdleInTransaction: settings.RelayProduceTimeout + settings.RelayStatementTimeout,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/worker/outboxrelay"
|
||||
)
|
||||
|
||||
const relayLifecycleTimeout = 5 * time.Second
|
||||
|
||||
func TestNewOutboxRelaySkipsWithoutWork(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
settings config.Config
|
||||
}{
|
||||
{name: "disabled", settings: config.Config{RelayEnabled: false, DatabaseURL: "postgres://app@db/app"}},
|
||||
{name: "database not configured", settings: config.Config{RelayEnabled: true}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
relay, cleanup, err := newOutboxRelay(t.Context(), test.settings, slog.New(slog.DiscardHandler), prometheus.New())
|
||||
if err != nil {
|
||||
t.Fatalf("newOutboxRelay() error = %v", err)
|
||||
}
|
||||
cleanup()
|
||||
if relay != nil {
|
||||
t.Fatal("newOutboxRelay() built a relay without work to do")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// claimCounter is an outbox store with no pending events that counts passes.
|
||||
type claimCounter struct {
|
||||
passes atomic.Int64
|
||||
}
|
||||
|
||||
func (store *claimCounter) ClaimPending(context.Context, int, outbound.PublishOutboxBatch) error {
|
||||
store.passes.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*claimCounter) Backlog(context.Context) (outbound.OutboxBacklog, error) {
|
||||
return outbound.OutboxBacklog{}, nil
|
||||
}
|
||||
|
||||
type readyPublisher struct{}
|
||||
|
||||
func (readyPublisher) Prepare(context.Context) error { return nil }
|
||||
|
||||
func (readyPublisher) Publish(_ context.Context, events []outbound.OutboxEvent) []error {
|
||||
return make([]error, len(events))
|
||||
}
|
||||
|
||||
func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
|
||||
store := &claimCounter{}
|
||||
metrics := prometheus.New()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
relay := outboxrelay.New(store, readyPublisher{}, metrics, logger, outboxrelay.Settings{
|
||||
BatchSize: 1,
|
||||
PollInterval: time.Millisecond,
|
||||
Backoff: outboxrelay.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: time.Second,
|
||||
})
|
||||
application := NewApplication(config.Config{
|
||||
HTTPAddr: "127.0.0.1:0",
|
||||
MetricsAddr: "127.0.0.1:0",
|
||||
ShutdownTimeout: time.Second,
|
||||
}, http.NotFoundHandler(), metrics, logger, nil, relay)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
finished := make(chan error, 1)
|
||||
go func() { finished <- application.run(ctx) }()
|
||||
|
||||
deadline := time.Now().Add(relayLifecycleTimeout)
|
||||
for store.passes.Load() < 2 {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the relay did not poll the outbox while the servers ran")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-finished:
|
||||
if err != nil {
|
||||
t.Fatalf("run() error = %v", err)
|
||||
}
|
||||
case <-time.After(relayLifecycleTimeout):
|
||||
t.Fatal("run() did not return after cancellation")
|
||||
}
|
||||
// run returns only after the relay stopped, so no pass follows.
|
||||
passes := store.passes.Load()
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if after := store.passes.Load(); after != passes {
|
||||
t.Fatalf("the relay ran %d passes after run() returned", after-passes)
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ func initialize(
|
||||
v1.NewHandler,
|
||||
v1.NewDenyAllSecurity,
|
||||
httpadapter.NewRouter,
|
||||
newOutboxRelay,
|
||||
NewApplication,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -55,8 +55,16 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
application := NewApplication(config2, httpHandler, metrics, logger, mailSender)
|
||||
relay, cleanup4, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay)
|
||||
return application, func() {
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrEventDestinationMissing reports that the event bus has no destination
|
||||
// for an event, for example a deleted topic. The relay runs
|
||||
// EventPublisher.Prepare again before its next pass.
|
||||
var ErrEventDestinationMissing = errors.New("event destination missing")
|
||||
|
||||
// OutboxBacklog describes the unpublished events at one moment.
|
||||
type OutboxBacklog struct {
|
||||
// Pending counts unpublished events.
|
||||
Pending int64
|
||||
// OldestAge is the age of the earliest unpublished event by position,
|
||||
// measured by the database clock; zero without pending events.
|
||||
OldestAge time.Duration
|
||||
}
|
||||
|
||||
// OutboxEvent is a committed outbox row that the relay publishes. Payload is
|
||||
// the stored jsonb object; PostgreSQL normalizes it, so it can differ in key
|
||||
// order and whitespace from what the writer appended.
|
||||
type OutboxEvent struct {
|
||||
EventID uuid.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID uuid.UUID
|
||||
AggregateVersion int64
|
||||
Payload json.RawMessage
|
||||
// OccurredAt is the informational insert time. It does not define order.
|
||||
OccurredAt time.Time
|
||||
}
|
||||
|
||||
// PublishOutboxBatch publishes a locked batch and returns the IDs of the
|
||||
// events that the event bus acknowledged. It must not return an ID it did not
|
||||
// see acknowledged.
|
||||
type PublishOutboxBatch func(ctx context.Context, events []OutboxEvent) (acknowledged []uuid.UUID)
|
||||
|
||||
// OutboxRelayStore hands pending outbox events to the relay under row locks.
|
||||
type OutboxRelayStore interface {
|
||||
// ClaimPending opens one transaction and locks up to limit pending events:
|
||||
// for each aggregate only its earliest unpublished event, skipping rows
|
||||
// that another relay holds. It calls publish with the events in position
|
||||
// order while it holds the locks, marks exactly the returned IDs as
|
||||
// published, and commits. With no pending event it returns without
|
||||
// calling publish.
|
||||
//
|
||||
// If ctx ends or the commit fails after publish returned, nothing is
|
||||
// marked and the acknowledged events are published again on a later
|
||||
// pass with the same event IDs. An error from the store never says
|
||||
// whether the event bus received the batch.
|
||||
ClaimPending(ctx context.Context, limit int, publish PublishOutboxBatch) error
|
||||
// Backlog reads the size and age of the unpublished events without
|
||||
// locking them.
|
||||
Backlog(ctx context.Context) (OutboxBacklog, error)
|
||||
}
|
||||
|
||||
// EventPublisher delivers outbox events to the event bus.
|
||||
type EventPublisher interface {
|
||||
// Prepare makes the destinations ready, for example by creating missing
|
||||
// topics. It is idempotent; the relay calls it before its first publish
|
||||
// and repeats it with backoff until it succeeds.
|
||||
Prepare(ctx context.Context) error
|
||||
// Publish sends the events and waits until the event bus acknowledges
|
||||
// each one or ctx ends. The result has one entry per event in input
|
||||
// order: nil means durably acknowledged. An error matches
|
||||
// ErrEventDestinationMissing when the destination does not exist. An
|
||||
// event that is not acknowledged may still reach the event bus later, so
|
||||
// a retry can deliver it twice with the same event ID.
|
||||
Publish(ctx context.Context, events []OutboxEvent) []error
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,40 @@
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Backoff is a capped exponential delay with equal jitter: the ceiling starts
|
||||
// at Initial, doubles with every consecutive failure, and stops at Max; the
|
||||
// delay is half the ceiling plus a random share of the other half. The fixed
|
||||
// half keeps retries from hammering a recovering broker, and the random half
|
||||
// spreads several relays apart.
|
||||
type Backoff struct {
|
||||
Initial time.Duration
|
||||
Max time.Duration
|
||||
// jitter returns a value in [0, limit]. Tests replace it.
|
||||
jitter func(limit time.Duration) time.Duration
|
||||
}
|
||||
|
||||
// Delay returns the wait before the next attempt after failures consecutive
|
||||
// failures. failures below 1 count as 1.
|
||||
func (backoff Backoff) Delay(failures int) time.Duration {
|
||||
ceiling := min(backoff.Initial, backoff.Max)
|
||||
for attempt := 1; attempt < failures && ceiling < backoff.Max; attempt++ {
|
||||
ceiling = min(ceiling*2, backoff.Max)
|
||||
}
|
||||
half := ceiling / 2
|
||||
jitter := backoff.jitter
|
||||
if jitter == nil {
|
||||
jitter = randomJitter
|
||||
}
|
||||
return half + jitter(ceiling-half)
|
||||
}
|
||||
|
||||
func randomJitter(limit time.Duration) time.Duration {
|
||||
if limit <= 0 {
|
||||
return 0
|
||||
}
|
||||
return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness.
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBackoffDoublesFromInitialToTheCap(t *testing.T) {
|
||||
noJitter := func(time.Duration) time.Duration { return 0 }
|
||||
fullJitter := func(limit time.Duration) time.Duration { return limit }
|
||||
backoff := Backoff{Initial: 500 * time.Millisecond, Max: 5 * time.Second}
|
||||
|
||||
ceilings := []time.Duration{
|
||||
500 * time.Millisecond, // failure 1
|
||||
time.Second,
|
||||
2 * time.Second,
|
||||
4 * time.Second,
|
||||
5 * time.Second, // capped
|
||||
5 * time.Second,
|
||||
}
|
||||
for index, ceiling := range ceilings {
|
||||
failures := index + 1
|
||||
backoff.jitter = noJitter
|
||||
if got := backoff.Delay(failures); got != ceiling/2 {
|
||||
t.Fatalf("Delay(%d) without jitter = %s, want %s", failures, got, ceiling/2)
|
||||
}
|
||||
backoff.jitter = fullJitter
|
||||
if got := backoff.Delay(failures); got != ceiling {
|
||||
t.Fatalf("Delay(%d) with full jitter = %s, want %s", failures, got, ceiling)
|
||||
}
|
||||
}
|
||||
backoff.jitter = fullJitter
|
||||
if got := backoff.Delay(0); got != 500*time.Millisecond {
|
||||
t.Fatalf("Delay(0) = %s, want the first delay", got)
|
||||
}
|
||||
if got := backoff.Delay(1 << 20); got != 5*time.Second {
|
||||
t.Fatalf("Delay(many) = %s, want the cap", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackoffRandomJitterStaysWithinTheCeiling(t *testing.T) {
|
||||
backoff := Backoff{Initial: 100 * time.Millisecond, Max: time.Second}
|
||||
for failures := 1; failures <= 8; failures++ {
|
||||
ceiling := min(100*time.Millisecond<<(failures-1), time.Second)
|
||||
for range 50 {
|
||||
delay := backoff.Delay(failures)
|
||||
if delay < ceiling/2 || delay > ceiling {
|
||||
t.Fatalf("Delay(%d) = %s, want between %s and %s", failures, delay, ceiling/2, ceiling)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// Package outboxrelay publishes committed transactional outbox events to the
|
||||
// event bus with at-least-once delivery.
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Metrics records relay outcomes and the backlog without per-event labels.
|
||||
type Metrics interface {
|
||||
ObserveOutboxRelayPass(published, failed int)
|
||||
ObserveOutboxBacklog(backlog outbound.OutboxBacklog)
|
||||
}
|
||||
|
||||
// Settings are the named relay limits; config validates their ranges.
|
||||
type Settings struct {
|
||||
// BatchSize bounds the events one pass locks and publishes.
|
||||
BatchSize int
|
||||
// PollInterval is the wait after a pass that found no pending event.
|
||||
PollInterval time.Duration
|
||||
// Backoff is the wait after a failed pass or a failed Prepare.
|
||||
Backoff Backoff
|
||||
// ShutdownTimeout bounds how long a pass in progress may continue after
|
||||
// Run's context ends. When it expires the pass is canceled and its
|
||||
// transaction rolls back, so nothing it published is marked.
|
||||
ShutdownTimeout time.Duration
|
||||
// BacklogInterval is the least time between two backlog reads for the
|
||||
// metrics, so a busy relay does not count the outbox on every pass. It
|
||||
// also bounds one read.
|
||||
BacklogInterval time.Duration
|
||||
}
|
||||
|
||||
// Relay moves pending outbox events to the event bus. Several relays may run
|
||||
// against one database: each pass locks its rows with SKIP LOCKED, and only
|
||||
// the earliest unpublished event of an aggregate can be claimed, so one
|
||||
// aggregate's events are published in order. A pass marks only events the
|
||||
// broker acknowledged. An event acknowledged in a pass that does not commit
|
||||
// is published again later with the same event ID; consumers deduplicate.
|
||||
type Relay struct {
|
||||
store outbound.OutboxRelayStore
|
||||
publisher outbound.EventPublisher
|
||||
metrics Metrics
|
||||
logger *slog.Logger
|
||||
settings Settings
|
||||
}
|
||||
|
||||
func New(
|
||||
store outbound.OutboxRelayStore,
|
||||
publisher outbound.EventPublisher,
|
||||
metrics Metrics,
|
||||
logger *slog.Logger,
|
||||
settings Settings,
|
||||
) *Relay {
|
||||
return &Relay{store: store, publisher: publisher, metrics: metrics, logger: logger, settings: settings}
|
||||
}
|
||||
|
||||
// PassResult counts the events of one pass.
|
||||
type PassResult struct {
|
||||
// Claimed events were locked and handed to the publisher.
|
||||
Claimed int
|
||||
// Published events were acknowledged and marked in a committed
|
||||
// transaction.
|
||||
Published int
|
||||
}
|
||||
|
||||
// PublishPending runs one pass: it locks a batch, publishes it, and marks the
|
||||
// acknowledged events in the same transaction. A nil error means every
|
||||
// claimed event was published. On an error Published counts only events whose
|
||||
// mark committed.
|
||||
func (relay *Relay) PublishPending(ctx context.Context) (PassResult, error) {
|
||||
var (
|
||||
result PassResult
|
||||
acknowledged int
|
||||
publishErr error
|
||||
)
|
||||
claimErr := relay.store.ClaimPending(ctx, relay.settings.BatchSize, func(ctx context.Context, events []outbound.OutboxEvent) []uuid.UUID {
|
||||
result.Claimed = len(events)
|
||||
ids, err := relay.publish(ctx, events)
|
||||
acknowledged, publishErr = len(ids), err
|
||||
return ids
|
||||
})
|
||||
if claimErr != nil {
|
||||
return result, fmt.Errorf("Relay.PublishPending - claim pending events: %w", errors.Join(claimErr, publishErr))
|
||||
}
|
||||
result.Published = acknowledged
|
||||
if publishErr != nil {
|
||||
return result, fmt.Errorf("Relay.PublishPending - publish events: %w", publishErr)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// publish returns the acknowledged event IDs and, when some events were not
|
||||
// acknowledged, an error with their count and the first cause. The other
|
||||
// causes are dropped to keep one log line per pass.
|
||||
func (relay *Relay) publish(ctx context.Context, events []outbound.OutboxEvent) ([]uuid.UUID, error) {
|
||||
outcomes := relay.publisher.Publish(ctx, events)
|
||||
if len(outcomes) != len(events) {
|
||||
return nil, fmt.Errorf("Relay.publish - publisher returned %d results for %d events", len(outcomes), len(events))
|
||||
}
|
||||
acknowledged := make([]uuid.UUID, 0, len(events))
|
||||
var firstErr error
|
||||
for index, err := range outcomes {
|
||||
if err == nil {
|
||||
acknowledged = append(acknowledged, events[index].EventID)
|
||||
continue
|
||||
}
|
||||
// A missing destination wins, so Run sees it and prepares again.
|
||||
if firstErr == nil || (errors.Is(err, outbound.ErrEventDestinationMissing) && !errors.Is(firstErr, outbound.ErrEventDestinationMissing)) {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
if firstErr != nil {
|
||||
return acknowledged, fmt.Errorf("Relay.publish - %d of %d events not acknowledged: %w", len(events)-len(acknowledged), len(events), firstErr)
|
||||
}
|
||||
return acknowledged, nil
|
||||
}
|
||||
|
||||
// Run prepares the event bus and then publishes pending events until ctx
|
||||
// ends. A pass that published events is followed immediately by the next one,
|
||||
// even when some of its events failed; an empty pass waits PollInterval; a
|
||||
// pass that published nothing and failed waits Backoff, which grows only
|
||||
// across such passes. A pass that reports a missing destination makes Run
|
||||
// call Prepare again first. Failures are logged and retried indefinitely, so
|
||||
// Run returns only after ctx ends and the pass in progress finishes or
|
||||
// ShutdownTimeout cancels it.
|
||||
func (relay *Relay) Run(ctx context.Context) {
|
||||
passCtx, stopPasses := relay.passContext(ctx)
|
||||
defer stopPasses()
|
||||
relay.logger.Info("outbox relay started",
|
||||
slog.Int("batch_size", relay.settings.BatchSize),
|
||||
slog.Duration("poll_interval", relay.settings.PollInterval),
|
||||
)
|
||||
defer relay.logger.Info("outbox relay stopped")
|
||||
|
||||
backlog := backlogRefresher{relay: relay}
|
||||
failures := 0
|
||||
needsPrepare := true
|
||||
for {
|
||||
if needsPrepare {
|
||||
if !relay.prepare(ctx, &backlog) {
|
||||
return
|
||||
}
|
||||
}
|
||||
result, err := relay.PublishPending(passCtx)
|
||||
relay.metrics.ObserveOutboxRelayPass(result.Published, result.Claimed-result.Published)
|
||||
backlog.refresh(ctx)
|
||||
needsPrepare = errors.Is(err, outbound.ErrEventDestinationMissing)
|
||||
var delay time.Duration
|
||||
delay, failures = relay.nextDelay(result, err, failures)
|
||||
if !wait(ctx, delay) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nextDelay returns the wait before the next pass and the new count of
|
||||
// consecutive failed passes that published nothing.
|
||||
func (relay *Relay) nextDelay(result PassResult, err error, failures int) (time.Duration, int) {
|
||||
switch {
|
||||
case err != nil && result.Published > 0:
|
||||
// The pass made progress, so the event bus works; the failed events
|
||||
// are retried at once instead of slowing the others down.
|
||||
relay.logger.Warn("outbox relay pass published part of its batch; the rest stay pending",
|
||||
slog.Int("claimed", result.Claimed),
|
||||
slog.Int("published", result.Published),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
return 0, 0
|
||||
case err != nil:
|
||||
failures++
|
||||
delay := relay.settings.Backoff.Delay(failures)
|
||||
relay.logger.Warn("outbox relay pass failed; unacknowledged events stay pending",
|
||||
slog.Int("claimed", result.Claimed),
|
||||
slog.Int("published", result.Published),
|
||||
slog.Int("consecutive_failures", failures),
|
||||
slog.Duration("retry_in", delay),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
return delay, failures
|
||||
case result.Claimed > 0:
|
||||
return 0, 0
|
||||
default:
|
||||
return relay.settings.PollInterval, 0
|
||||
}
|
||||
}
|
||||
|
||||
// prepare repeats Prepare with backoff until it succeeds or ctx ends. The
|
||||
// backlog metrics keep refreshing meanwhile, so a growing outbox stays visible.
|
||||
func (relay *Relay) prepare(ctx context.Context, backlog *backlogRefresher) bool {
|
||||
for failures := 1; ; failures++ {
|
||||
err := relay.publisher.Prepare(ctx)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
backlog.refresh(ctx)
|
||||
delay := relay.settings.Backoff.Delay(failures)
|
||||
relay.logger.Warn("outbox relay could not prepare the event bus; events stay pending",
|
||||
slog.Int("consecutive_failures", failures),
|
||||
slog.Duration("retry_in", delay),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
if !wait(ctx, delay) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// backlogRefresher reads the outbox backlog for the metrics at most once per
|
||||
// BacklogInterval.
|
||||
type backlogRefresher struct {
|
||||
relay *Relay
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (refresher *backlogRefresher) refresh(ctx context.Context) {
|
||||
interval := refresher.relay.settings.BacklogInterval
|
||||
if !refresher.last.IsZero() && time.Since(refresher.last) < interval {
|
||||
return
|
||||
}
|
||||
refresher.last = time.Now()
|
||||
readCtx, cancel := context.WithTimeout(ctx, interval)
|
||||
defer cancel()
|
||||
backlog, err := refresher.relay.store.Backlog(readCtx)
|
||||
if err != nil {
|
||||
// A read interrupted by shutdown is not worth a warning.
|
||||
if ctx.Err() == nil {
|
||||
refresher.relay.logger.Warn("outbox relay could not read the backlog; its metrics are stale", slog.Any("error", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
refresher.relay.metrics.ObserveOutboxBacklog(backlog)
|
||||
}
|
||||
|
||||
// passContext returns a context for passes that outlives ctx by at most
|
||||
// ShutdownTimeout, so a pass in progress at shutdown can finish and mark what
|
||||
// the broker acknowledged. stop releases the watcher goroutine.
|
||||
func (relay *Relay) passContext(ctx context.Context) (context.Context, func()) {
|
||||
passCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
stopWatching := context.AfterFunc(ctx, func() {
|
||||
timer := time.NewTimer(relay.settings.ShutdownTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
cancel()
|
||||
case <-passCtx.Done():
|
||||
}
|
||||
})
|
||||
return passCtx, func() {
|
||||
stopWatching()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// wait sleeps for delay and reports false when ctx ends first. A zero delay
|
||||
// still reports a canceled context.
|
||||
func wait(ctx context.Context, delay time.Duration) bool {
|
||||
if delay <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
testTimeout = 5 * time.Second
|
||||
testInterval = time.Millisecond
|
||||
)
|
||||
|
||||
var errBrokerDown = errors.New("broker down")
|
||||
|
||||
// fakeStore models the claim transaction: events acknowledged by publish are
|
||||
// marked only when ctx is still live afterwards, as a commit would require.
|
||||
type fakeStore struct {
|
||||
mu sync.Mutex
|
||||
pending []outbound.OutboxEvent
|
||||
marked []uuid.UUID
|
||||
passes int
|
||||
backlogReads int
|
||||
}
|
||||
|
||||
func newFakeStore(count int) *fakeStore {
|
||||
store := &fakeStore{}
|
||||
for version := range count {
|
||||
store.pending = append(store.pending, outbound.OutboxEvent{
|
||||
EventID: uuid.New(),
|
||||
EventType: "test.changed",
|
||||
SchemaVersion: 1,
|
||||
AggregateType: "test",
|
||||
AggregateID: uuid.New(),
|
||||
AggregateVersion: int64(version + 1),
|
||||
})
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
func (store *fakeStore) ClaimPending(ctx context.Context, limit int, publish outbound.PublishOutboxBatch) error {
|
||||
store.mu.Lock()
|
||||
store.passes++
|
||||
batch := slices.Clone(store.pending[:min(limit, len(store.pending))])
|
||||
store.mu.Unlock()
|
||||
if len(batch) == 0 {
|
||||
return nil
|
||||
}
|
||||
acknowledged := publish(ctx, batch)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
for _, eventID := range acknowledged {
|
||||
store.marked = append(store.marked, eventID)
|
||||
store.pending = slices.DeleteFunc(store.pending, func(event outbound.OutboxEvent) bool { return event.EventID == eventID })
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) Backlog(context.Context) (outbound.OutboxBacklog, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
store.backlogReads++
|
||||
return outbound.OutboxBacklog{Pending: int64(len(store.pending))}, nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) reads() int {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return store.backlogReads
|
||||
}
|
||||
|
||||
func (store *fakeStore) state() (pending int, marked []uuid.UUID, passes int) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return len(store.pending), slices.Clone(store.marked), store.passes
|
||||
}
|
||||
|
||||
type fakePublisher struct {
|
||||
prepare func(ctx context.Context) error
|
||||
publish func(ctx context.Context, events []outbound.OutboxEvent) []error
|
||||
}
|
||||
|
||||
func (publisher fakePublisher) Prepare(ctx context.Context) error {
|
||||
if publisher.prepare == nil {
|
||||
return nil
|
||||
}
|
||||
return publisher.prepare(ctx)
|
||||
}
|
||||
|
||||
func (publisher fakePublisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
return publisher.publish(ctx, events)
|
||||
}
|
||||
|
||||
func acknowledgeAll(_ context.Context, events []outbound.OutboxEvent) []error {
|
||||
return make([]error, len(events))
|
||||
}
|
||||
|
||||
type countingMetrics struct {
|
||||
mu sync.Mutex
|
||||
published, failed int
|
||||
backlogs []int64
|
||||
}
|
||||
|
||||
func (metrics *countingMetrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.backlogs = append(metrics.backlogs, backlog.Pending)
|
||||
}
|
||||
|
||||
func (metrics *countingMetrics) ObserveOutboxRelayPass(published, failed int) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.published += published
|
||||
metrics.failed += failed
|
||||
}
|
||||
|
||||
func (metrics *countingMetrics) totals() (published, failed int) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
return metrics.published, metrics.failed
|
||||
}
|
||||
|
||||
func newTestRelay(store outbound.OutboxRelayStore, publisher outbound.EventPublisher, metrics Metrics, shutdownTimeout time.Duration) *Relay {
|
||||
return New(store, publisher, metrics, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 2,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: testInterval, Max: 4 * testInterval},
|
||||
ShutdownTimeout: shutdownTimeout,
|
||||
BacklogInterval: testInterval,
|
||||
})
|
||||
}
|
||||
|
||||
// runRelay starts Run and returns a function that cancels it and waits for
|
||||
// it to return.
|
||||
func runRelay(t *testing.T, relay *Relay) (stop func() time.Duration) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
relay.Run(ctx)
|
||||
}()
|
||||
return func() time.Duration {
|
||||
started := time.Now()
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(testTimeout):
|
||||
t.Fatal("Run did not return after cancellation")
|
||||
}
|
||||
return time.Since(started)
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, condition func() bool, description string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(testTimeout)
|
||||
for !condition() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting for %s", description)
|
||||
}
|
||||
time.Sleep(testInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPendingMarksOnlyAcknowledgedEvents(t *testing.T) {
|
||||
store := newFakeStore(2)
|
||||
relay := newTestRelay(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
|
||||
return []error{nil, errBrokerDown}
|
||||
}}, &countingMetrics{}, time.Second)
|
||||
|
||||
result, err := relay.PublishPending(t.Context())
|
||||
if !errors.Is(err, errBrokerDown) {
|
||||
t.Fatalf("PublishPending() error = %v, want the publish failure", err)
|
||||
}
|
||||
if result != (PassResult{Claimed: 2, Published: 1}) {
|
||||
t.Fatalf("PublishPending() result = %+v, want 2 claimed and 1 published", result)
|
||||
}
|
||||
pending, marked, _ := store.state()
|
||||
if pending != 1 || len(marked) != 1 {
|
||||
t.Fatalf("pending %d, marked %v; want the failed event pending and one marked", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPendingMarksNothingWhenResultsDoNotMatchTheBatch(t *testing.T) {
|
||||
store := newFakeStore(2)
|
||||
relay := newTestRelay(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
|
||||
return []error{nil}
|
||||
}}, &countingMetrics{}, time.Second)
|
||||
|
||||
result, err := relay.PublishPending(t.Context())
|
||||
if err == nil || result.Published != 0 {
|
||||
t.Fatalf("PublishPending() = %+v, %v; want an error and nothing published", result, err)
|
||||
}
|
||||
if pending, marked, _ := store.state(); pending != 2 || len(marked) != 0 {
|
||||
t.Fatalf("pending %d, marked %v; want every event pending", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRetriesPrepareAndFailedPassesUntilEventsArePublished(t *testing.T) {
|
||||
store := newFakeStore(5)
|
||||
var mu sync.Mutex
|
||||
prepareFailures, publishFailures := 2, 3
|
||||
publisher := fakePublisher{
|
||||
prepare: func(context.Context) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if prepareFailures > 0 {
|
||||
prepareFailures--
|
||||
return errBrokerDown
|
||||
}
|
||||
return nil
|
||||
},
|
||||
publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if publishFailures > 0 {
|
||||
publishFailures--
|
||||
results := make([]error, len(events))
|
||||
for index := range results {
|
||||
results[index] = errBrokerDown
|
||||
}
|
||||
return results
|
||||
}
|
||||
return acknowledgeAll(ctx, events)
|
||||
},
|
||||
}
|
||||
metrics := &countingMetrics{}
|
||||
stop := runRelay(t, newTestRelay(store, publisher, metrics, time.Second))
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 0
|
||||
}, "every event to be published")
|
||||
stop()
|
||||
|
||||
_, marked, _ := store.state()
|
||||
if len(marked) != 5 {
|
||||
t.Fatalf("marked %d events, want 5", len(marked))
|
||||
}
|
||||
if published, failed := metrics.totals(); published != 5 || failed != 6 {
|
||||
t.Fatalf("metrics published=%d failed=%d, want 5 and 6 (three failed passes of two)", published, failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunLetsThePassInProgressFinishAfterCancellation(t *testing.T) {
|
||||
store := newFakeStore(1)
|
||||
publishing, release := make(chan struct{}), make(chan struct{})
|
||||
publisher := fakePublisher{publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
close(publishing)
|
||||
<-release
|
||||
return acknowledgeAll(ctx, events)
|
||||
}}
|
||||
stop := runRelay(t, newTestRelay(store, publisher, &countingMetrics{}, testTimeout))
|
||||
<-publishing
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
stop()
|
||||
}()
|
||||
// Run must still be waiting for the pass after cancellation.
|
||||
select {
|
||||
case <-stopped:
|
||||
t.Fatal("Run returned before the pass in progress finished")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
close(release)
|
||||
<-stopped
|
||||
if pending, marked, _ := store.state(); pending != 0 || len(marked) != 1 {
|
||||
t.Fatalf("pending %d, marked %v; want the acknowledged event marked", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCancelsAPassThatOutlivesTheShutdownTimeout(t *testing.T) {
|
||||
const shutdownTimeout = 50 * time.Millisecond
|
||||
store := newFakeStore(1)
|
||||
publishing := make(chan struct{})
|
||||
var once sync.Once
|
||||
publisher := fakePublisher{publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
once.Do(func() { close(publishing) })
|
||||
// A hung broker: the publish ends only with its context.
|
||||
<-ctx.Done()
|
||||
results := make([]error, len(events))
|
||||
for index := range results {
|
||||
results[index] = ctx.Err()
|
||||
}
|
||||
return results
|
||||
}}
|
||||
stop := runRelay(t, newTestRelay(store, publisher, &countingMetrics{}, shutdownTimeout))
|
||||
<-publishing
|
||||
if elapsed := stop(); elapsed < shutdownTimeout {
|
||||
t.Fatalf("Run returned after %s, before the %s shutdown timeout", elapsed, shutdownTimeout)
|
||||
}
|
||||
if pending, marked, _ := store.state(); pending != 1 || len(marked) != 0 {
|
||||
t.Fatalf("pending %d, marked %v; want the unacknowledged event pending", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStopsDuringBackoffWithoutAnotherPass(t *testing.T) {
|
||||
store := newFakeStore(1)
|
||||
relay := New(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
|
||||
return []error{errBrokerDown}
|
||||
}}, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 1,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: time.Hour,
|
||||
})
|
||||
stop := runRelay(t, relay)
|
||||
waitFor(t, func() bool {
|
||||
_, _, passes := store.state()
|
||||
return passes == 1
|
||||
}, "the first pass")
|
||||
if elapsed := stop(); elapsed > time.Second {
|
||||
t.Fatalf("Run took %s to stop during backoff", elapsed)
|
||||
}
|
||||
if _, _, passes := store.state(); passes != 1 {
|
||||
t.Fatalf("store saw %d passes, want 1", passes)
|
||||
}
|
||||
}
|
||||
|
||||
// hourBackoffRelay never retries a failed pass that published nothing within
|
||||
// a test, so a test that finishes proves the relay did not back off.
|
||||
func hourBackoffRelay(store outbound.OutboxRelayStore, publisher outbound.EventPublisher, backlogInterval time.Duration) *Relay {
|
||||
return New(store, publisher, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 2,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: backlogInterval,
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunDoesNotBackOffAfterAPassThatMadeProgress(t *testing.T) {
|
||||
store := newFakeStore(5)
|
||||
poison := store.pending[0].EventID
|
||||
publisher := fakePublisher{publish: func(_ context.Context, events []outbound.OutboxEvent) []error {
|
||||
results := make([]error, len(events))
|
||||
for index, event := range events {
|
||||
if event.EventID == poison {
|
||||
results[index] = errBrokerDown
|
||||
}
|
||||
}
|
||||
return results
|
||||
}}
|
||||
stop := runRelay(t, hourBackoffRelay(store, publisher, time.Hour))
|
||||
// The poison event leads every batch; the others drain only if a pass
|
||||
// that published something is followed at once by the next one.
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 1
|
||||
}, "every event except the poison event to be published")
|
||||
stop()
|
||||
if _, marked, _ := store.state(); slices.Contains(marked, poison) {
|
||||
t.Fatal("the failed event was marked as published")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPreparesAgainAfterAMissingDestination(t *testing.T) {
|
||||
store := newFakeStore(1)
|
||||
var mu sync.Mutex
|
||||
prepares, missing := 0, true
|
||||
publisher := fakePublisher{
|
||||
prepare: func(context.Context) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
prepares++
|
||||
return nil
|
||||
},
|
||||
publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if missing {
|
||||
missing = false
|
||||
return []error{fmt.Errorf("produce: %w", outbound.ErrEventDestinationMissing)}
|
||||
}
|
||||
return acknowledgeAll(ctx, events)
|
||||
},
|
||||
}
|
||||
relay := newTestRelay(store, publisher, &countingMetrics{}, time.Second)
|
||||
stop := runRelay(t, relay)
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 0
|
||||
}, "the event to be published after the topic was prepared again")
|
||||
stop()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if prepares != 2 {
|
||||
t.Fatalf("Prepare ran %d times, want 2 (start and after the missing destination)", prepares)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRefreshesTheBacklogAtMostOncePerInterval(t *testing.T) {
|
||||
store := newFakeStore(6)
|
||||
metrics := &countingMetrics{}
|
||||
relay := New(store, fakePublisher{publish: acknowledgeAll}, metrics, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 1,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: testInterval, Max: testInterval},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: time.Hour,
|
||||
})
|
||||
stop := runRelay(t, relay)
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 0
|
||||
}, "every event to be published")
|
||||
stop()
|
||||
_, _, passes := store.state()
|
||||
if reads := store.reads(); reads != 1 || passes < 6 {
|
||||
t.Fatalf("%d backlog reads over %d passes, want 1 read per interval", reads, passes)
|
||||
}
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
if len(metrics.backlogs) != 1 || metrics.backlogs[0] != 5 {
|
||||
t.Fatalf("backlog observations %v, want one with the 5 events left after the first pass", metrics.backlogs)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user