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

+25
View File
@@ -0,0 +1,25 @@
// Package db embeds the versioned SQL migrations so the backend binary applies
// exactly the schema it was built with. The SQL files stay in db/migrations,
// where sqlc and sqlfluff also read them; go:embed cannot reach a parent
// directory, so the embedding package lives next to that directory.
package db
import (
"embed"
"fmt"
"io/fs"
)
const migrationsDirectory = "migrations"
//go:embed migrations/*.sql
var migrationFiles embed.FS
// Migrations returns the goose SQL migrations with file names at the root.
func Migrations() (fs.FS, error) {
migrations, err := fs.Sub(migrationFiles, migrationsDirectory)
if err != nil {
return nil, fmt.Errorf("db.Migrations - open embedded migrations: %w", err)
}
return migrations, nil
}
-1
View File
@@ -1 +0,0 @@
@@ -0,0 +1,54 @@
-- +goose Up
-- Transactional outbox: a business transaction appends its domain events here
-- in the same PostgreSQL transaction as the business change. A relay publishes
-- unpublished rows to Kafka. Payloads carry identifiers and minimal facts only,
-- never contact data, tokens, passwords, or document contents.
CREATE TABLE outbox_events (
-- Monotonic insertion key for the relay scan. It is assigned at insert
-- time, so a transaction that waited on a row lock gets a larger value
-- than the transaction it waited for.
position bigint GENERATED ALWAYS AS IDENTITY,
event_id uuid NOT NULL,
event_type text NOT NULL,
schema_version integer NOT NULL,
aggregate_type text NOT NULL,
aggregate_id uuid NOT NULL,
aggregate_version bigint NOT NULL,
payload jsonb NOT NULL,
-- Statement time rather than transaction start time. Informational only:
-- ordering uses position and aggregate_version.
occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
CONSTRAINT outbox_events_pkey PRIMARY KEY (event_id),
CONSTRAINT outbox_events_position_key UNIQUE (position),
CONSTRAINT outbox_events_aggregate_version_event_type_key UNIQUE (
aggregate_type, aggregate_id, aggregate_version, event_type
),
CONSTRAINT outbox_events_event_type_format CHECK (
char_length(event_type) <= 128
AND event_type ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$'
),
CONSTRAINT outbox_events_schema_version_positive CHECK (schema_version > 0),
CONSTRAINT outbox_events_aggregate_type_format CHECK (
char_length(aggregate_type) <= 64
AND aggregate_type ~ '^[a-z][a-z0-9_]*$'
),
CONSTRAINT outbox_events_aggregate_version_positive CHECK (
aggregate_version > 0
),
-- The payload size limit is enforced in Go on compact JSON. The jsonb text
-- and binary forms differ in size from that input, so a database length
-- check could reject an event that the domain accepted.
CONSTRAINT outbox_events_payload_object CHECK (
jsonb_typeof(payload) = 'object'
)
);
-- Supports the relay scan of unpublished events in insertion order. The index
-- shrinks as events are published.
CREATE INDEX outbox_events_unpublished_idx
ON outbox_events (position)
WHERE published_at IS NULL;
-- +goose Down
DROP TABLE outbox_events;
+44
View File
@@ -0,0 +1,44 @@
package db
import (
"io/fs"
"regexp"
"strings"
"testing"
)
var migrationNamePattern = regexp.MustCompile(`^[0-9]{5}_[a-z0-9_]+\.sql$`)
// TestMigrationsHaveSequentialNamesAndBothDirections runs without a database so
// make -C backend check catches a malformed or one-way migration.
func TestMigrationsHaveSequentialNamesAndBothDirections(t *testing.T) {
migrations, err := Migrations()
if err != nil {
t.Fatalf("Migrations() error = %v", err)
}
names, err := fs.Glob(migrations, "*.sql")
if err != nil {
t.Fatalf("list migrations: %v", err)
}
if len(names) == 0 {
t.Fatal("no embedded migrations")
}
for _, name := range names {
if !migrationNamePattern.MatchString(name) {
t.Fatalf("migration %s does not match NNNNN_description.sql", name)
}
content, err := fs.ReadFile(migrations, name)
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
text := string(content)
up := strings.Index(text, "-- +goose Up")
down := strings.Index(text, "-- +goose Down")
if up < 0 || down < up {
t.Fatalf("migration %s needs a -- +goose Up section followed by a -- +goose Down section", name)
}
if strings.TrimSpace(text[down+len("-- +goose Down"):]) == "" {
t.Fatalf("migration %s has an empty Down section", name)
}
}
}
+18
View File
@@ -0,0 +1,18 @@
-- name: InsertOutboxEvent :exec
INSERT INTO outbox_events (
event_id,
event_type,
schema_version,
aggregate_type,
aggregate_id,
aggregate_version,
payload
) VALUES (
sqlc.arg(event_id),
sqlc.arg(event_type),
sqlc.arg(schema_version),
sqlc.arg(aggregate_type),
sqlc.arg(aggregate_id),
sqlc.arg(aggregate_version),
sqlc.arg(payload)
);