feat(outbox): relay committed outbox events to Kafka

This commit is contained in:
shira committed 2026-10-06 03:01:53 +03:00
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)
}
}
}