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)
}
})
}
}