package kafka import ( "bytes" "encoding/json" "fmt" "strconv" "time" "github.com/google/uuid" "github.com/twmb/franz-go/pkg/kgo" "lincodex/backend/internal/domain" "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 } // decodeRecord turns a consumed record into an event. A value that is not a // valid envelope yields a record whose Invalid error matches // outbound.ErrInvalidEventRecord; the error names the broken rule and never // quotes the value. EventID then comes from the event_id header when it holds // a UUID, so an operator can still find the event. func decodeRecord(record *kgo.Record) outbound.ConsumedRecord { consumed := outbound.ConsumedRecord{ Topic: record.Topic, Partition: record.Partition, Offset: record.Offset, Value: record.Value, } headerID, headerErr := uuid.Parse(recordHeader(record, headerEventID)) if headerErr == nil { consumed.EventID = headerID } event, err := decodeEnvelope(record.Value) if err == nil && headerErr == nil && headerID != event.EventID { // A consumer that deduplicated by the header would disagree with one // that reads the value, so the record is not trusted. err = invalidRecord("event_id header differs from the envelope") } if err != nil { consumed.Invalid = err return consumed } consumed.Event = event consumed.EventID = event.EventID return consumed } func decodeEnvelope(value []byte) (outbound.ConsumedEvent, error) { var decoded envelope // The json error is dropped: its text can quote part of the value. if err := json.Unmarshal(value, &decoded); err != nil { return outbound.ConsumedEvent{}, invalidRecord("value is not a JSON event envelope") } if decoded.EnvelopeVersion != EnvelopeVersion { return outbound.ConsumedEvent{}, invalidRecord("unsupported envelope_version") } if decoded.EventID == uuid.Nil { return outbound.ConsumedEvent{}, invalidRecord("event_id is missing") } identity := domain.DomainEventInput{ EventType: decoded.EventType, SchemaVersion: decoded.SchemaVersion, AggregateType: decoded.AggregateType, AggregateID: decoded.AggregateID, AggregateVersion: decoded.AggregateVersion, } if err := identity.ValidateIdentity(); err != nil { return outbound.ConsumedEvent{}, fmt.Errorf("kafka.decodeEnvelope - %w: %w", outbound.ErrInvalidEventRecord, err) } if decoded.OccurredAt.IsZero() { return outbound.ConsumedEvent{}, invalidRecord("occurred_at is missing") } if !isJSONObject(decoded.Payload) { return outbound.ConsumedEvent{}, invalidRecord("payload is not a JSON object") } return outbound.ConsumedEvent{ EventID: decoded.EventID, EventType: decoded.EventType, SchemaVersion: decoded.SchemaVersion, AggregateType: decoded.AggregateType, AggregateID: decoded.AggregateID, AggregateVersion: decoded.AggregateVersion, OccurredAt: decoded.OccurredAt, Payload: decoded.Payload, }, nil } // isJSONObject reports whether raw, which json.Unmarshal already checked, is // an object rather than another value or null. func isJSONObject(raw json.RawMessage) bool { trimmed := bytes.TrimLeft(raw, " \t\r\n") return len(trimmed) > 0 && trimmed[0] == '{' } func invalidRecord(reason string) error { return fmt.Errorf("kafka.decodeEnvelope - %s: %w", reason, outbound.ErrInvalidEventRecord) } // recordHeader returns the last value of the header key, or "" without one. func recordHeader(record *kgo.Record, key string) string { value := "" for _, header := range record.Headers { if header.Key == key { value = string(header.Value) } } return value }