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 }