feat(backend): add transactional outbox and embedded goose migrations

This commit is contained in:
shira committed 2026-10-05 23:32:43 +03:00
1 parent 653f3775f8
commit 15e2e50561
40 files changed
+2471 -67

No files matched your search

View File
Whitespace-only changes.
+183
View File
@@ -0,0 +1,183 @@
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) }
@@ -0,0 +1,138 @@
package domain
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/google/uuid"
)
func validDomainEventInput() DomainEventInput {
return DomainEventInput{
EventType: "identity.user_registered",
SchemaVersion: 1,
AggregateType: "user",
AggregateID: uuid.MustParse("0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"),
AggregateVersion: 1,
Payload: []byte(` { "user_id" : "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d" } `),
}
}
func TestNewDomainEventAcceptsValidInput(t *testing.T) {
input := validDomainEventInput()
event, err := NewDomainEvent(input)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
if event.EventID().Version() != 7 {
t.Fatalf("EventID version = %d, want UUIDv7", event.EventID().Version())
}
if event.EventType() != input.EventType || event.SchemaVersion() != input.SchemaVersion ||
event.AggregateType() != input.AggregateType || event.AggregateID() != input.AggregateID ||
event.AggregateVersion() != input.AggregateVersion {
t.Fatalf("NewDomainEvent() did not preserve identity fields: %+v", event)
}
if want := `{"user_id":"0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"}`; string(event.Payload()) != want {
t.Fatalf("Payload() = %s, want compact %s", event.Payload(), want)
}
event.Payload()[0] = '['
if event.Payload()[0] != '{' {
t.Fatal("Payload() exposed the event's internal buffer")
}
other, err := NewDomainEvent(input)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
if other.EventID() == event.EventID() {
t.Fatal("NewDomainEvent() reused an event ID")
}
}
func TestNewDomainEventAcceptsPayloadAtSizeLimit(t *testing.T) {
input := validDomainEventInput()
prefix, suffix := `{"padding":"`, `"}`
input.Payload = []byte(prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)) + suffix)
if _, err := NewDomainEvent(input); err != nil {
t.Fatalf("NewDomainEvent() rejected a payload at the limit: %v", err)
}
}
func TestNewDomainEventRejectsInvalidInput(t *testing.T) {
prefix, suffix := `{"padding":"`, `"}`
oversized := prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)+1) + suffix
tests := []struct {
name string
change func(*DomainEventInput)
}{
{name: "empty event type", change: func(input *DomainEventInput) { input.EventType = "" }},
{name: "event type without namespace", change: func(input *DomainEventInput) { input.EventType = "registered" }},
{name: "uppercase event type", change: func(input *DomainEventInput) { input.EventType = "Identity.UserRegistered" }},
{name: "long event type", change: func(input *DomainEventInput) { input.EventType = "a." + strings.Repeat("b", 127) }},
{name: "zero schema version", change: func(input *DomainEventInput) { input.SchemaVersion = 0 }},
{name: "negative schema version", change: func(input *DomainEventInput) { input.SchemaVersion = -1 }},
{name: "empty aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "" }},
{name: "dotted aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "identity.user" }},
{name: "long aggregate type", change: func(input *DomainEventInput) { input.AggregateType = strings.Repeat("a", 65) }},
{name: "nil aggregate ID", change: func(input *DomainEventInput) { input.AggregateID = uuid.Nil }},
{name: "zero aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = 0 }},
{name: "negative aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = -1 }},
{name: "empty payload", change: func(input *DomainEventInput) { input.Payload = nil }},
{name: "invalid JSON payload", change: func(input *DomainEventInput) { input.Payload = []byte(`{"user_id":`) }},
{name: "array payload", change: func(input *DomainEventInput) { input.Payload = []byte(`[1]`) }},
{name: "null payload", change: func(input *DomainEventInput) { input.Payload = []byte(`null`) }},
{name: "invalid UTF-8 payload", change: func(input *DomainEventInput) { input.Payload = []byte("{\"a\":\"\xff\"}") }},
{name: "escaped NUL in value", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":"x\u0000y"}`) }},
{name: "escaped NUL in key", change: func(input *DomainEventInput) { input.Payload = []byte(`{"\u0000":1}`) }},
{name: "escaped NUL in nested array", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":[{"b":"\u0000"}]}`) }},
{name: "number outside float64 range", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":1e400}`) }},
{name: "nesting too deep", change: func(input *DomainEventInput) { input.Payload = nestedPayload(maxDomainEventPayloadDepth + 1) }},
{name: "oversized payload", change: func(input *DomainEventInput) { input.Payload = []byte(oversized) }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := validDomainEventInput()
test.change(&input)
_, err := NewDomainEvent(input)
if !errors.Is(err, ErrInvalidDomainEvent) {
t.Fatalf("NewDomainEvent() error = %v, want ErrInvalidDomainEvent", err)
}
})
}
}
func TestNewDomainEventDoesNotKeepCallerPayload(t *testing.T) {
input := validDomainEventInput()
input.Payload = []byte(`{"a":1}`)
event, err := NewDomainEvent(input)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
copy(input.Payload, `{"b":2}`)
if !bytes.Equal(event.Payload(), []byte(`{"a":1}`)) {
t.Fatalf("Payload() = %s, changed with the caller's buffer", event.Payload())
}
}
func TestNewDomainEventAcceptsEdgePayloads(t *testing.T) {
for name, payload := range map[string][]byte{
"escaped backslash before u0000 text": []byte(`{"a":"\\u0000"}`),
"maximum nesting": nestedPayload(maxDomainEventPayloadDepth),
"large integer": []byte(`{"a":123456789012345678901234567890}`),
} {
t.Run(name, func(t *testing.T) {
input := validDomainEventInput()
input.Payload = payload
if _, err := NewDomainEvent(input); err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
})
}
}
// nestedPayload returns an object whose containers nest depth levels deep.
func nestedPayload(depth int) []byte {
return []byte(strings.Repeat(`{"a":`, depth) + "1" + strings.Repeat("}", depth))
}