package domain import ( "bytes" "encoding/json" "errors" "fmt" "regexp" "strings" "unicode/utf8" "github.com/google/uuid" ) const ( // MaxDomainEventPayloadBytes bounds the compact JSON payload. Events carry // identifiers and minimal facts; larger data stays in the source tables. MaxDomainEventPayloadBytes = 16 << 10 maxDomainEventTypeLength = 128 maxAggregateTypeLength = 64 // maxDomainEventPayloadDepth bounds object and array nesting. Minimal facts // do not need deep structures, and the bound keeps decoding cheap. maxDomainEventPayloadDepth = 32 ) var ( ErrInvalidDomainEvent = errors.New("invalid domain event") // Lowercase dotted names such as "identity.user_registered". domainEventTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`) // Lowercase snake_case names such as "user" or "company_member". aggregateTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) ) // DomainEvent is an immutable fact about one aggregate version, recorded in the // transactional outbox and later published to the event bus. // // The payload must carry identifiers and minimal facts only. It must never // contain contact data, tokens, passwords, document contents, or other personal // data that a consumer can read from the source of truth under its own access // rules. // // The outbox stores the payload as jsonb, which normalizes it: key order and // whitespace change and duplicate keys keep the last value. Consumers must // compare payloads as JSON values, not bytes. type DomainEvent struct { eventID uuid.UUID eventType string schemaVersion int32 aggregateType string aggregateID uuid.UUID aggregateVersion int64 payload []byte } // DomainEventInput describes a new event. Payload must be a JSON object of at // most MaxDomainEventPayloadBytes in compact form, nested at most 32 levels, // with numbers in float64 range and no NUL characters, which jsonb cannot // store. type DomainEventInput struct { EventType string SchemaVersion int32 AggregateType string AggregateID uuid.UUID AggregateVersion int64 Payload []byte } // NewDomainEvent validates input and assigns a time-ordered UUIDv7 event ID. // The stored payload is the compact form of input.Payload. func NewDomainEvent(input DomainEventInput) (DomainEvent, error) { if err := input.validateIdentity(); err != nil { return DomainEvent{}, err } payload, err := compactPayload(input.Payload) if err != nil { return DomainEvent{}, err } eventID, err := uuid.NewV7() if err != nil { return DomainEvent{}, fmt.Errorf("domain.NewDomainEvent - generate event ID: %w", err) } return DomainEvent{ eventID: eventID, eventType: input.EventType, schemaVersion: input.SchemaVersion, aggregateType: input.AggregateType, aggregateID: input.AggregateID, aggregateVersion: input.AggregateVersion, payload: payload, }, nil } func (input DomainEventInput) validateIdentity() error { if len(input.EventType) > maxDomainEventTypeLength || !domainEventTypePattern.MatchString(input.EventType) { return invalidDomainEvent("event type must be a lowercase dotted name of at most 128 bytes") } if input.SchemaVersion <= 0 { return invalidDomainEvent("schema version must be positive") } if len(input.AggregateType) > maxAggregateTypeLength || !aggregateTypePattern.MatchString(input.AggregateType) { return invalidDomainEvent("aggregate type must be a lowercase snake_case name of at most 64 bytes") } if input.AggregateID == uuid.Nil { return invalidDomainEvent("aggregate ID must not be nil") } if input.AggregateVersion <= 0 { return invalidDomainEvent("aggregate version must be positive") } return nil } func compactPayload(payload []byte) ([]byte, error) { // encoding/json accepts invalid UTF-8 inside strings; PostgreSQL does not. if !utf8.Valid(payload) { return nil, invalidDomainEvent("payload must be valid UTF-8") } var compact bytes.Buffer if err := json.Compact(&compact, payload); err != nil { return nil, invalidDomainEvent("payload must be valid JSON") } if compact.Len() == 0 || compact.Bytes()[0] != '{' { return nil, invalidDomainEvent("payload must be a JSON object") } if compact.Len() > MaxDomainEventPayloadBytes { return nil, invalidDomainEvent("payload exceeds 16 KiB") } var decoded any if err := json.Unmarshal(compact.Bytes(), &decoded); err != nil { // Compact already checked the syntax, so this is a number outside the // float64 range. return nil, invalidDomainEvent("payload numbers must fit a float64") } if err := checkPayloadValue(decoded, 1); err != nil { return nil, err } return compact.Bytes(), nil } // checkPayloadValue rejects values that PostgreSQL jsonb cannot store and // nesting deeper than maxDomainEventPayloadDepth. func checkPayloadValue(value any, depth int) error { switch typed := value.(type) { case map[string]any: if depth > maxDomainEventPayloadDepth { return invalidDomainEvent("payload nesting exceeds 32 levels") } for key, item := range typed { if strings.ContainsRune(key, 0) { return invalidDomainEvent("payload must not contain NUL characters") } if err := checkPayloadValue(item, depth+1); err != nil { return err } } case []any: if depth > maxDomainEventPayloadDepth { return invalidDomainEvent("payload nesting exceeds 32 levels") } for _, item := range typed { if err := checkPayloadValue(item, depth+1); err != nil { return err } } case string: if strings.ContainsRune(typed, 0) { return invalidDomainEvent("payload must not contain NUL characters") } } return nil } func invalidDomainEvent(reason string) error { return fmt.Errorf("domain.NewDomainEvent - %s: %w", reason, ErrInvalidDomainEvent) } func (event DomainEvent) EventID() uuid.UUID { return event.eventID } func (event DomainEvent) EventType() string { return event.eventType } func (event DomainEvent) SchemaVersion() int32 { return event.schemaVersion } func (event DomainEvent) AggregateType() string { return event.aggregateType } func (event DomainEvent) AggregateID() uuid.UUID { return event.aggregateID } func (event DomainEvent) AggregateVersion() int64 { return event.aggregateVersion } func (event DomainEvent) Payload() json.RawMessage { return bytes.Clone(event.payload) }