### Start MySQL and run the example Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-mysql/README.md Commands to start MySQL via Docker Compose, install dependencies, and run the Go application from the example directory. ```sh docker compose --profile mysql up -d cd examples/base-app-mysql go mod tidy go run . ``` -------------------------------- ### Install Picodata backend with go get Source: https://github.com/assurrussa/outbox/blob/master/backends/picodata/README.md Install the Picodata backend module using the go get command. ```sh go get github.com/assurrussa/outbox/backends/picodata@latest ``` -------------------------------- ### Run SQLite example Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Runs the SQLite example from the examples/base-app-sqlite directory. ```sh cd examples/base-app-sqlite go run . ``` -------------------------------- ### Quick Start Commands Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-pgsql/README.md Commands to start the PostgreSQL service, run the example app, and stop services. Run from the repo root. ```sh docker compose --profile pgsql up -d cd examples/base-app-pgsql go mod tidy go run . ``` ```sh docker compose down --remove-orphans ``` -------------------------------- ### Quick Start Commands Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-picodata/README.md Commands to set up and run the example with local compose. Exports the admin password, starts Picodata, and runs the app. ```sh export TEST_OUTBOXLIB_PICODATA_ADMIN_PASSWORD=passWord!123 docker compose --profile picodata up -d cd examples/base-app-picodata go mod tidy go run . ``` -------------------------------- ### Install MySQL Backend Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Install the MySQL backend module using go get. ```sh go get github.com/assurrussa/outbox/backends/mysql@latest ``` -------------------------------- ### Run the base app example Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-sqlite/README.md Commands to run the example: navigate to the example directory, tidy modules, and run the app. Expected output includes processed jobs, queue stats, and the path to the local database file. ```sh cd examples/base-app-sqlite go mod tidy go run . ``` -------------------------------- ### Run core-only in-memory example Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Runs the core-only in-memory example from the examples/base-app directory. ```sh cd examples/base-app go run . ``` -------------------------------- ### Install core with go get Source: https://github.com/assurrussa/outbox/blob/master/README.md Install the core outbox library using the go get command. ```sh go get github.com/assurrussa/outbox@latest ``` -------------------------------- ### Set DSN and run the example Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-pgsql/transactional/README.md Exports the OUTBOX_PG_DSN environment variable and runs the example from the repository root. The database must already exist and the user must have permission to create and remove schemas. Each invocation creates a uniquely named outbox_quickstart_* schema, runs embedded migrations, and removes only that schema on exit. ```sh export OUTBOX_PG_DSN='postgres://tests-service:tests-service@127.0.0.1:54335/tests-db-pgsql?sslmode=disable' go run ./examples/base-app-pgsql/transactional ``` -------------------------------- ### Install SQLite backend with go get Source: https://github.com/assurrussa/outbox/blob/master/backends/sqlite/README.md Install the SQLite backend module at the latest version. ```sh go get github.com/assurrussa/outbox/backends/sqlite@latest ``` -------------------------------- ### Start integration services Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Starts MySQL, Postgres, and Picodata via Docker Compose profiles. Waits for all three services before returning. SQLite tests do not need Docker. ```sh make devup ``` -------------------------------- ### Run the batch consumer with Docker Compose and Go Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-pgsql/batch/README.md Starts a disposable PostgreSQL database via Docker Compose, sets the OUTBOX_PG_DSN environment variable, and runs the batch example. The database role must be able to create schemas. The command creates a uniquely named schema, runs migrations, and removes only that schema on exit. ```sh docker compose --profile pgsql up -d export OUTBOX_PG_DSN='postgres://tests-service:tests-service@127.0.0.1:54335/tests-db-pgsql?sslmode=disable' cd examples/base-app-pgsql GOWORK=off go run ./batch ``` -------------------------------- ### Run all benchmarks with make bench-all Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Runs the complete benchmark suite. BenchmarkExecutionPaths compares single execution, sequential prefetch of 16/100/1000 jobs, and true batches of 1/100/1000 jobs with leases of 1s, 5s, 10s, and 5m. Each operation processes 1000 jobs and reports ns/job, B/job, allocs/job, claim calls/job, handler calls/job, finalization calls/job, lease extension calls/job, and extended rows/job. This in-memory benchmark is a fast regression and mechanism diagnostic; it does not establish PostgreSQL/NATS capacity or a production advantage. ```sh make bench-all ``` -------------------------------- ### Integration services commands Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Start and stop integration services. `make devup` and `make devdown` provide safe local defaults; copy `.env.example` only when local overrides are needed. ```sh make devup make test-integration-all make devdown ``` -------------------------------- ### Import backend storage modules Source: https://github.com/assurrussa/outbox/blob/master/MIGRATION.md Import exactly one backend module for storage-specific wiring. The example shows all available backend imports. ```go import mysqlstorage "github.com/assurrussa/outbox/backends/mysql/storage" import sqlitestorage "github.com/assurrussa/outbox/backends/sqlite/storage" import "github.com/assurrussa/outbox/backends/pgsql/storage/pgsqlinit" import "github.com/assurrussa/outbox/backends/pgsql/storage/pgsqlclient" import picostorage "github.com/assurrussa/outbox/backends/picodata/storage" ``` -------------------------------- ### mysqlmigrator.Run Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Runs migrations from a filesystem directory with the specified command. ```APIDOC ## mysqlmigrator.Run ### Description Runs migrations from a filesystem directory with the specified command. ### Method Run ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **db** (*sql.DB) - Required - Database connection. - **log** (logger) - Required - Logger instance. - **options** (mysqlmigrator.Option) - Optional - Migration options, e.g., WithCommand, WithDirectory. ### Example ```go _ = mysqlmigrator.Run(ctx, db, log, mysqlmigrator.WithCommand("up"), mysqlmigrator.WithDirectory("/path/to/migrations"), ) ``` ``` -------------------------------- ### Run transactional quickstart integration test Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Run the integration test for the transactional base app with a disposable PostgreSQL database and OUTBOX_PG_DSN set. The test owns a unique schema, covers commit/rollback/enqueue failure, and drops only that schema. Without a DSN it skips. ```sh go test -tags integration ./examples/base-app-pgsql/transactional -count=1 ``` -------------------------------- ### Start and stop integration services Source: https://github.com/assurrussa/outbox/blob/master/README.md Use make devup to bring up integration services and make devdown to tear them down. ```sh make devup make devdown ``` -------------------------------- ### Install pgsql backend with go get Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/README.md Install the PostgreSQL backend module using the latest version. ```sh go get github.com/assurrussa/outbox/backends/pgsql@latest ``` -------------------------------- ### Compare lease benchmarks against a base commit Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Runs an isolated before/after comparison of the current sources against a commit. The output directory must be new. Requires Python 3, Go, and benchstat on PATH. Copies both source trees, applies the identical current benchmark harness to both, builds binaries, and runs ten alternating pairs at GOMAXPROCS=2, GOGC=100, GOMEMLIMIT=off, -benchtime=300ms, without race. Records source checksums, tool versions, raw samples, and the comparison. Run after source checks and without concurrent tests or load campaigns. ```sh python3 scripts/compare-lease-benchmarks.py --base d853a50 --output /tmp/outbox-lease-comparison ``` -------------------------------- ### Run all integration tests Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Runs all integration tests across all backends. ```sh make test-integration-all ``` -------------------------------- ### Copy environment template Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Copy the .env.example template to .env to override local integration defaults. Only needed when you need custom overrides. ```sh cp .env.example .env ``` -------------------------------- ### Paginate through jobs with ListPage Source: https://github.com/assurrussa/outbox/blob/master/backends/picodata/README.md Example loop using ListPage to iterate over all rows. Starts with nil cursor, processes each page, and uses the last row to create the next cursor. The loop breaks when no rows are returned. ```go var before *picodata.PageCursor for { rows, err := jobs.ListPage(ctx, 100, before) if err != nil { return err } if len(rows) == 0 { break } // Consume rows before requesting the next page. last := rows[len(rows)-1] before = &picodata.PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} } ``` -------------------------------- ### Run MySQL migrations from filesystem with mysqlmigrator.Run Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Filesystem mode for running migrations from a directory. Specify the 'up' command and the path to migration files. ```go _ = mysqlmigrator.Run(ctx, db, log, mysqlmigrator.WithCommand("up"), mysqlmigrator.WithDirectory("/path/to/migrations"), ) ``` -------------------------------- ### Pin backend modules to core version Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Mutating command that pins all backend modules to a published core version and refreshes sums. Updates all four backend and example go.mod and go.sum pairs in one release change. ```sh make release-ready-backends CORE_VERSION=v0.17.0 ``` -------------------------------- ### jobsrepo.Repo.ListPage Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Lists jobs in pages, ordered by created_at DESC, id DESC. Use the returned cursor for the next page. ```APIDOC ## jobsrepo.Repo.ListPage ### Description Lists jobs in pages, ordered by created_at DESC, id DESC. Use the returned cursor for the next page. ### Method ListPage ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **limit** (int) - Required - Maximum number of rows to return. Non-positive values use DefaultPageSize (10). Values above MaxPageSize (1000) return an error. - **before** (*mysql.PageCursor) - Optional - Cursor for pagination. nil starts the first page. ### Response Returns a slice of job rows. The last row's CreatedAt and ID form the next cursor. ### Example ```go var before *mysql.PageCursor for { rows, err := jobs.ListPage(ctx, 100, before) if err != nil { return err } if len(rows) == 0 { break } // Consume rows before requesting the next page. last := rows[len(rows)-1] before = &mysql.PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} } ``` ``` -------------------------------- ### Run embedded MySQL migrations with mysqlmigrator.RunEmbedded Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Recommended way to run embedded MySQL migrations. Uses the 'up' command and requires a context, database handle, and logger. ```go _ = mysqlmigrator.RunEmbedded(ctx, db, log, mysqlmigrator.WithCommand("up")) ``` -------------------------------- ### Stop integration services Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Stops the integration services started with make devup. ```sh make devdown ``` -------------------------------- ### Core outbox service setup and graceful shutdown Source: https://github.com/assurrussa/outbox/blob/master/README.md Configures an outbox service with one worker, reserve and idle times, a logger, repositories, and a transactor. Registers a job, puts a message, and runs the service with graceful drain: BeginDrain is called before cancelling the Run context, and a 10-second timer bounds the drain. Readiness is a non-mutating probe; JobsStatRepository is optional and auto-detected. ```go package main import ( "context" "errors" "fmt" "os" "os/signal" "syscall" "time" "golang.org/x/sync/errgroup" "github.com/assurrussa/outbox/outbox" outboxlogger "github.com/assurrussa/outbox/outbox/logger" ) type SendEmailJob struct { outbox.DefaultJob } func (*SendEmailJob) Name() string { return "send_email" } func (*SendEmailJob) Handle(_ context.Context, _ string) error { return nil } func main() { // Use signal notification only as a shutdown trigger. sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() svc, err := outbox.New( outbox.WithWorkers(1), outbox.WithReserveFor(time.Second), outbox.WithIdleTime(5*time.Second), outbox.WithLogger(outboxlogger.Default()), outbox.WithJobsRepo(jobsRepo), outbox.WithJobsFailedRepo(jobsFailedRepo), outbox.WithTransactor(txManager), ) if err != nil { panic(err) } emailJob := &SendEmailJob{} svc.MustRegisterJob(emailJob) // Keep a separate run context active during graceful drain. runCtx, cancelRun := context.WithCancel(context.Background()) defer cancelRun() group, groupCtx := errgroup.WithContext(runCtx) group.Go(func() error { return svc.Run(groupCtx) }) if _, err := svc.Put(groupCtx, "send_email", `{"id":"1"}`, time.Now()); err != nil { panic(err) } // Wait for shutdown trigger or worker failure. select { case <-sigCtx.Done(): stop() // Bound both claim-admission shutdown and in-flight handler drain. drainTimer := time.AfterFunc(10*time.Second, cancelRun) defer drainTimer.Stop() // Drain new claims while in-flight jobs keep their lease heartbeats. svc.BeginDrain() case <-groupCtx.Done(): } if err := group.Wait(); err != nil && !errors.Is(err, context.Canceled) { fmt.Printf("service stopped: %v\n", err) os.Exit(1) } } ``` -------------------------------- ### mysqlmigrator.RunEmbedded Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Runs embedded migrations with the specified command. Recommended for most use cases. ```APIDOC ## mysqlmigrator.RunEmbedded ### Description Runs embedded migrations with the specified command. Recommended for most use cases. ### Method RunEmbedded ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **db** (*sql.DB) - Required - Database connection. - **log** (logger) - Required - Logger instance. - **options** (mysqlmigrator.Option) - Optional - Migration options, e.g., WithCommand. ### Example ```go _ = mysqlmigrator.RunEmbedded(ctx, db, log, mysqlmigrator.WithCommand("up")) ``` ``` -------------------------------- ### Run tests for the batch consumer Source: https://github.com/assurrussa/outbox/blob/master/examples/base-app-pgsql/batch/README.md Runs the unit tests and the integration tests for the batch example. The integration test requires the database and skips if the DSN is unset. It verifies multi-item invocation, all staged IDs, zero active/failed jobs, bounded completion, and schema cleanup. ```sh GOWORK=off go test -race ./batch OUTBOX_PG_DSN="$OUTBOX_PG_DSN" GOWORK=off go test -race -count=1 -tags integration ./batch ``` -------------------------------- ### Run Full Local Check with make check Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Run the full local check target `make check` which verifies formatting, vet, and lint, then runs one race+coverage traversal for core and one normal traversal for each backend. Use `make prepare` for generation, formatting, and lint fixes. ```sh make check ``` -------------------------------- ### Build Outbox Service with MySQL Backend Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Constructs an outbox.Service using the MySQL backend. It creates a storage client, runs embedded migrations, initializes repositories and transaction, then configures the service with workers, batch size, idle time, reservation duration, and repositories. The jobs repository is auto-detected for exact grouped queue stats and unique puts; fan-out is explicitly enabled via WithFanoutJobsRepo. ```go import ( "context" "time" mysqlmigrator "github.com/assurrussa/outbox/backends/mysql/migrator" "github.com/assurrussa/outbox/backends/mysql/repositories/jobsfailedrepo" "github.com/assurrussa/outbox/backends/mysql/repositories/jobsrepo" mysqlstorage "github.com/assurrussa/outbox/backends/mysql/storage" mysqltx "github.com/assurrussa/outbox/backends/mysql/storage/transaction" "github.com/assurrussa/outbox/outbox" "github.com/assurrussa/outbox/outbox/logger" ) func build(ctx context.Context, dsn string) (*outbox.Service, error) { lg := logger.Default() client, err := mysqlstorage.Create(ctx, dsn) if err != nil { return nil, err } if err := mysqlmigrator.RunEmbedded(ctx, client.DB(), lg, mysqlmigrator.WithCommand("up")); err != nil { return nil, err } jobs := jobsrepo.Must(client) failed := jobsfailedrepo.Must(client) trx := mysqltx.New(client.DB()) return outbox.New( outbox.WithWorkers(1), outbox.WithReservationBatchSize(32), outbox.WithIdleTime(100*time.Millisecond), outbox.WithReserveFor(time.Second), outbox.WithJobsRepo(jobs), outbox.WithFanoutJobsRepo(jobs), outbox.WithJobsFailedRepo(failed), outbox.WithTransactor(trx), outbox.WithLogger(lg), ) } ``` -------------------------------- ### Verify backend modules as standalone Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Verifies backend modules as standalone modules using GOWORK=off. Use before claiming backend modules are consumable outside the local workspace. ```sh make release-verify-backends ``` -------------------------------- ### Service.Run Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Starts the worker loops for the outbox service. Returns an error if called while already running or if called concurrently. ```APIDOC ## Service.Run ### Description Starts the worker loops for the outbox service. Returns an error if called while already running or if called concurrently. ### Method Run ### Errors - `ErrServiceRunning` - Returned when called twice concurrently or while already running. ``` -------------------------------- ### jobsrepo.Repo.ListPaged Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Deprecated. Lists jobs with a time-only boundary. Retained unchanged but deprecated; use ListPage instead. ```APIDOC ## jobsrepo.Repo.ListPaged ### Description Deprecated. Lists jobs with a time-only boundary. Retained unchanged but deprecated; use ListPage instead. ### Method ListPaged ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **limit** (int) - Required - Maximum number of rows to return. - **before** (time.Time) - Required - Time boundary for pagination. ### Response Returns a slice of job rows. ### Note This method is deprecated and may skip rows when a page ends inside a group with identical creation times. Migrate to ListPage. ``` -------------------------------- ### Run Fast Checks with make test-core, test-backends, test Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Run core tests, backend tests, and all tests from the repository root. `make test-core` runs `go test ./...` in the core workspace context; `make test-backends` iterates each backend module and runs `go test ./...`. ```sh make test-core make test-backends make test ``` -------------------------------- ### Set repo-local Go build cache and run tests Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Use a repo-local build cache when the default Go build cache is outside the writable workspace and fails with 'operation not permitted'. Run from the repository root; tmp/ is git-ignored and should not be committed. ```sh mkdir -p tmp/gocache GOCACHE=$PWD/tmp/gocache go test ./... ``` -------------------------------- ### Paginate through jobs with ListPage and PageCursor Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Iterates over all rows using ListPage with a cursor. Rows are ordered by created_at DESC, id DESC. The loop breaks when no rows are returned. The cursor uses the last row's CreatedAt and ID. Works for both jobsrepo.Repo and jobsfailedrepo.Repo. ```go var before *mysql.PageCursor for { rows, err := jobs.ListPage(ctx, 100, before) if err != nil { return err } if len(rows) == 0 { break } // Consume rows before requesting the next page. last := rows[len(rows)-1] before = &mysql.PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} } ``` -------------------------------- ### jobsfailedrepo.Repo.ListPage Source: https://github.com/assurrussa/outbox/blob/master/backends/mysql/README.md Lists failed jobs in pages, ordered by created_at DESC, id DESC. The cursor uses the failed row's ID, never the source JobID. ```APIDOC ## jobsfailedrepo.Repo.ListPage ### Description Lists failed jobs in pages, ordered by created_at DESC, id DESC. The cursor uses the failed row's ID, never the source JobID. ### Method ListPage ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **limit** (int) - Required - Maximum number of rows to return. Non-positive values use DefaultPageSize (10). Values above MaxPageSize (1000) return an error. - **before** (*mysql.PageCursor) - Optional - Cursor for pagination. nil starts the first page. ### Response Returns a slice of failed job rows. The last row's CreatedAt and ID form the next cursor. ### Example ```go var before *mysql.PageCursor for { rows, err := failedJobs.ListPage(ctx, 100, before) if err != nil { return err } if len(rows) == 0 { break } // Consume rows before requesting the next page. last := rows[len(rows)-1] before = &mysql.PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} } ``` ``` -------------------------------- ### Run embedded migrations with pgmigrator.RunEmbedded Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/README.md Recommended migration runner for embedded SQL migrations. Uses pgmigrator.WithCommand("up") to apply pending migrations. Apply migration 00003 before starting v0.12 workers and keep producers on v1 until pre-v0.12 unfiltered workers drain. ```go _ = pgmigrator.RunEmbedded(ctx, db, log, pgmigrator.WithCommand("up")) ``` -------------------------------- ### Build outbox service with Picodata backend Source: https://github.com/assurrussa/outbox/blob/master/backends/picodata/README.md Shows how to create an outbox service using the Picodata backend. It creates a storage client, runs migrations, initializes repositories, and configures the outbox service with required options like WithAllowNonAtomicDLQ(). ```go import ( "context" "os" "time" "github.com/assurrussa/outbox/backends/picodata/deployenv" picomigrator "github.com/assurrussa/outbox/backends/picodata/migrator" "github.com/assurrussa/outbox/backends/picodata/repositories/jobsfailedrepo" "github.com/assurrussa/outbox/backends/picodata/repositories/jobsrepo" picostorage "github.com/assurrussa/outbox/backends/picodata/storage" picotx "github.com/assurrussa/outbox/backends/picodata/storage/transaction" "github.com/assurrussa/outbox/outbox" "github.com/assurrussa/outbox/outbox/logger" ) func build(ctx context.Context, dsn string) (*outbox.Service, error) { lg := logger.Default() client, err := picostorage.Create(ctx, dsn) if err != nil { return nil, err } if err := picomigrator.RunEmbedded(ctx, client, lg, picomigrator.WithCommand("up")); err != nil { return nil, err } jobs := jobsrepo.Must(client) failed := jobsfailedrepo.Must(client) trx := picotx.New(client.Pool()) return outbox.New( outbox.WithWorkers(1), outbox.WithIdleTime(100*time.Millisecond), outbox.WithReserveFor(time.Second), outbox.WithJobsRepo(jobs), outbox.WithJobsFailedRepo(failed), outbox.WithTransactor(trx), outbox.WithAllowNonAtomicDLQ(), outbox.WithLogger(lg), ) } ``` -------------------------------- ### Load connection config from environment Source: https://github.com/assurrussa/outbox/blob/master/backends/picodata/README.md Shows how to load the connection configuration from environment variables using deployenv.LoadAppConnFromEnv and obtain the DSN via cfg.ConnectionURL(). ```go cfg, err := deployenv.LoadAppConnFromEnv(os.Getenv) if err != nil { return nil, err } dsn := cfg.ConnectionURL() ``` -------------------------------- ### Run core, backend, and integration tests Source: https://github.com/assurrussa/outbox/blob/master/README.md Workspace-aware make targets for testing the core, backend modules, and all integration services. ```sh make test-core make test-backends make test-integration-all ``` -------------------------------- ### Import core runtime package Source: https://github.com/assurrussa/outbox/blob/master/MIGRATION.md Import the core outbox runtime package. ```go import "github.com/assurrussa/outbox/outbox" ``` -------------------------------- ### Run filesystem migrations with picomigrator Source: https://github.com/assurrussa/outbox/blob/master/backends/picodata/README.md Filesystem mode for running migrations from a directory. Uses picomigrator.Run with the 'up' command and a directory path. ```go _ = picomigrator.Run(ctx, client, log, picomigrator.WithCommand("up"), picomigrator.WithDirectory("/path/to/migrations"), ) ``` -------------------------------- ### Initialize outbox with WithAllowNonAtomicDLQ for Picodata Source: https://github.com/assurrussa/outbox/blob/master/MIGRATION.md Required for Picodata consumers because its BestEffortRunner declares SupportsAtomicDLQ() == false. Add WithAllowNonAtomicDLQ() when initializing the service to permit non-atomic DLQ delivery. ```go svc, err := outbox.New( outbox.WithJobsRepo(jobsRepo), outbox.WithJobsFailedRepo(jobsFailedRepo), outbox.WithTransactor(transactor), outbox.WithAllowNonAtomicDLQ(), // Required for Picodata or best-effort transactors ) ``` -------------------------------- ### Configure observer with WithObserver Source: https://github.com/assurrussa/outbox/blob/master/docs/contracts.md Creates a buffered channel for RuntimeOutcome values and appends the WithObserver option to the service options. The observer is configured during core service construction; nil is the default no-op. Sends are nonblocking and full sinks drop events; keep the sink open throughout Run and close only after Run joins its workers. ```go events := make(chan outbox.RuntimeOutcome, 128) options = append(options, outbox.WithObserver(events)) svc, err := outbox.New(options...) // Include the existing required dependencies. ``` -------------------------------- ### Compile transactional test without database access Source: https://github.com/assurrussa/outbox/blob/master/docs/development.md Compile the transactional integration test without requiring database access by using -run '^$' to skip all tests. ```sh go test -tags integration ./examples/base-app-pgsql/transactional -run '^$' ``` -------------------------------- ### replay.New Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/replay/README.md Constructs a new Replay instance using the provided PostgreSQL client. The client is borrowed, not owned. Returns an error if construction fails. ```APIDOC ## replay.New ### Description Constructs a new Replay instance using the provided PostgreSQL client. The client is borrowed, not owned. Returns an error if construction fails. ### Method New ### Signature func New(client *sql.DB) (*Replay, error) ### Parameters - **client** (*sql.DB) - Required - The PostgreSQL client used by the runtime. ### Returns - **r** (*Replay) - The constructed Replay instance. - **err** (error) - An error if construction fails. ### Example ```go r, err := replay.New(runtime.Client()) if err != nil { return err } ``` ``` -------------------------------- ### Run embedded migrations with picomigrator Source: https://github.com/assurrussa/outbox/blob/master/backends/picodata/README.md Recommended way to run migrations using embedded migrations. Uses picomigrator.RunEmbedded with the 'up' command. ```go _ = picomigrator.RunEmbedded(ctx, client, log, picomigrator.WithCommand("up")) ``` -------------------------------- ### outbox.New Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Creates a new outbox service instance. Validates required dependencies and options, and returns an error if any required dependency is missing or an option is invalid. ```APIDOC ## outbox.New ### Description Creates a new outbox service instance. Validates required dependencies and options, and returns an error if any required dependency is missing or an option is invalid. ### Method New ### Parameters #### Required Dependencies - `WithJobsRepo(...)` - Required - Jobs repository dependency. - `WithJobsFailedRepo(...)` - Required - Failed jobs repository dependency. - `WithTransactor(...)` - Required - Transactor dependency. #### Optional Dependencies - `WithLogger(...)` - Optional - Overrides the default logger. - `WithJobsRepo(...)` - Optional - Auto-detects stats and unique-put extensions; `WithJobsStatRepo(...)` and `WithUniqueJobsRepo(...)` are split-composition overrides. - `WithFanoutJobsRepo(...)` - Optional - Enables durable independent fan-out using immutable event-time snapshots; the built-in dispatcher creates one fenced job per target. ### Behavior - Option bounds are part of the public behavior: workers must be positive, idle time `100ms..10s`, reserve time `1s..10m`. ``` -------------------------------- ### Pin backend modules to a core tag and refresh sums Source: https://github.com/assurrussa/outbox/blob/master/README.md Mutating release prep: pins all backend modules to the given core tag and refreshes their sums. Requires the core tag to be published and immutable. ```sh # pin all backend modules to a published core tag and refresh their sums make release-ready-backends CORE_VERSION=v0.17.0 ``` -------------------------------- ### Construct Exponential Retry Policy and Pass to outbox.New Source: https://github.com/assurrussa/outbox/blob/master/docs/contracts.md Creates an exponential retry policy with a base delay of 1s, max delay of 1m, and no jitter. The policy is appended to existing options and passed to outbox.New. Requires positive bounds with baseDelay <= maxDelay; nil jitter is deterministic. Errors from policy construction are returned. ```go policy, err := outbox.NewExponentialRetryPolicy(time.Second, time.Minute, nil) if err != nil { return err } options = append(options, outbox.WithRetryPolicy(policy)) svc, err := outbox.New(options...) ``` -------------------------------- ### Run PostgreSQL replay integration tests Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/replay/README.md Runs the integration test suite for the replay backend against a disposable PostgreSQL database. Requires the OUTBOX_PG_DSN environment variable; without it, the live test skips. The command creates and drops a unique outbox_replay_* schema and tests atomic staging, retained evidence, admission failures, repeated requests, concurrency, persistence rollback, and commit response faults. ```sh cd backends/pgsql OUTBOX_PG_DSN='postgres://user:password@127.0.0.1:5432/test?sslmode=disable' \ go test -count=1 -tags integration -race ./replay ``` -------------------------------- ### Release-oriented backend checks Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Run release-readiness checks for backends with a specific core version. The `CORE_VERSION` variable is required. ```sh make release-readiness-backends CORE_VERSION=v0.17.0 ``` -------------------------------- ### outbox.New Source: https://github.com/assurrussa/outbox/blob/master/docs/contracts.md Constructs the core outbox service. Requires WithJobsRepo, WithJobsFailedRepo, and WithTransactor options. Validates configuration and fails closed on unsupported transaction capabilities. ```APIDOC ## outbox.New ### Description Constructs the core outbox service. Requires WithJobsRepo, WithJobsFailedRepo, and WithTransactor options. Validates configuration and fails closed on unsupported transaction capabilities. ### Parameters #### Options - **WithJobsRepo(...)** (Option) - Required - Sets the jobs repository. - **WithJobsFailedRepo(...)** (Option) - Required - Sets the failed jobs repository. - **WithTransactor(...)** (Option) - Required - Sets the transactor; must implement TransactionCapabilities and report SupportsAtomicDLQ() true unless WithAllowNonAtomicDLQ() is passed. - **WithAllowNonAtomicDLQ()** (Option) - Optional - Allows non-atomic DLQ when transactor reports false. - **WithJobsStatRepo(...)** (Option) - Optional - Sets stats repository; takes priority over auto-detection. - **WithUniqueJobsRepo(...)** (Option) - Optional - Sets unique jobs repository; takes priority over auto-detection. - **WithFanoutJobsRepo(...)** (Option) - Optional - Explicitly sets fan-out jobs repository; never auto-detected. - **WithRetryPolicy(policy)** (Option) - Optional - Sets retry policy for ordinary retryable failures. ### Response Returns a service instance or an error (e.g., ErrTransactionCapabilitiesRequired, ErrNonAtomicDLQUnsupported). ``` -------------------------------- ### Formatting and generated mocks commands Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Generate code, format, and lint. These commands are part of the `make prepare` workflow. ```sh make generate make fmt make lint ``` -------------------------------- ### Run filesystem migrations with sqlitemigrator.Run Source: https://github.com/assurrussa/outbox/blob/master/backends/sqlite/README.md Runs migrations from a directory on the filesystem. Specify the directory with WithDirectory and the command with WithCommand. ```go _ = sqlitemigrator.Run(ctx, db, log, sqlitemigrator.WithCommand("up"), sqlitemigrator.WithDirectory("/path/to/migrations"), ) ``` -------------------------------- ### Run bounded race tests and benchmarks with GOMEMLIMIT and timeout Source: https://github.com/assurrussa/outbox/blob/master/docs/performance/fanout-planning-baseline.md Run from repository root on Linux with GNU timeout. The first command runs focused race tests with a 256MiB memory limit and 1 CPU. The second runs a one-iteration benchmark with a 180-second timeout and 10-second kill grace. The third runs a 5-iteration benchmark with memory profiling, 5 counts, and a 120-second timeout. GOMEMLIMIT is a soft limit, not a hard guarantee. Go's test timeout does not bound benchmarks. ```sh GOMEMLIMIT=256MiB GOMAXPROCS=1 go test -race -count=1 \ -run '^Test(PutFanout|Fanout)' ./outbox ``` ```sh GOMEMLIMIT=256MiB GOMAXPROCS=1 timeout --kill-after=10s 180s go test -race -run '^$' \ -bench '^BenchmarkFanoutPlanning$' -benchtime=1x -count=1 \ -cpu=1 ./outbox ``` ```sh GOMEMLIMIT=256MiB GOMAXPROCS=1 timeout --kill-after=10s 120s go test -run '^$' \ -bench '^BenchmarkFanoutPlanning$' -benchmem -benchtime=5x \ -count=5 -cpu=1 ./outbox ``` -------------------------------- ### Workspace-aware test commands Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Run from the repository root. `make check` is source-read-only and runs one race+coverage traversal for the core plus one normal traversal per backend. `make prepare` owns generation, formatting, and safe lint fixes. ```sh make test-core make test-backends make test make check ``` -------------------------------- ### Open SQLite runtime with synchronous mode Source: https://github.com/assurrussa/outbox/blob/master/backends/sqlite/README.md Use sqliteruntime.Open with a Config struct to set the synchronous mode to FULL when opening a runtime. Import backends/sqlite/runtime as sqliteruntime. Empty mode preserves NORMAL; only exported NORMAL/FULL values are accepted. ```go rt, err := sqliteruntime.Open(ctx, sqliteruntime.Config{ DSN: dsn, SynchronousMode: sqlitestorage.SynchronousFull, }) ``` -------------------------------- ### Run filesystem migrations with pgmigrator.Run Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/README.md Alternative migration runner for filesystem-based SQL migrations. Uses pgmigrator.WithCommand("up") and pgmigrator.WithDirectory("/path/to/migrations") to specify the migration directory. ```go _ = pgmigrator.Run(ctx, db, log, pgmigrator.WithCommand("up"), pgmigrator.WithDirectory("/path/to/migrations"), ) ``` -------------------------------- ### RegisterBatchJob with BatchConfig Source: https://github.com/assurrussa/outbox/blob/master/README.md Activates a true handler batch with zero config meaning 100 jobs, 4 MiB payload, and 25 ms fill window. Use MaxMessages: 1 for a same-path singleton control. The handler receives one ordered []BatchJobItem and returns one keyed BatchItemResult per input JobID; missing, duplicate, or unknown IDs fail the service closed. ```go if err := svc.RegisterBatchJob(applicationBatchJob, outbox.BatchConfig{ MaxMessages: 100, MaxBytes: 4 << 20, MaxWait: 25 * time.Millisecond, }); err != nil { return err } ``` -------------------------------- ### Construct replay and execute a replay request Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/replay/README.md Constructs the replay object with the runtime PostgreSQL client and executes a replay request. The callback runs on every request within a transaction holding the failed row; it must be bounded and read-only. Authorization, handler support, and deduplication must be explicitly checked before admission. ```go r, err := replay.New(runtime.Client()) if err != nil { return err } result, err := r.Replay(ctx, replay.Request{ RequestID: requestID, // persist once before the first attempt FailedJobID: failedID, // jobs_failed.id, not jobs_failed.job_id }, func(ctx context.Context, source replay.Source) (string, error) { if err := hostAuthorizeReplay(ctx, source); err != nil { return "", err } if source.Capability != (outbox.JobCapability{ Name: "order.created", SchemaVersion: 2, }) { return "", errUnsupportedHandler } // The registered handler already consumes this original effect key. return originalEffectKeyFromPayload(source.Payload) }) ``` -------------------------------- ### Run embedded migrations with sqlitemigrator.RunEmbedded Source: https://github.com/assurrussa/outbox/blob/master/backends/sqlite/README.md Recommended way to run migrations using embedded migration files. Uses the 'up' command. ```go _ = sqlitemigrator.RunEmbedded(ctx, db, log, sqlitemigrator.WithCommand("up")) ``` -------------------------------- ### runtime.Config.Observer Source: https://github.com/assurrussa/outbox/blob/master/docs/contracts.md Configures the observer through the runtime facades for PostgreSQL, MySQL, and SQLite. This is an alternative to WithObserver for setting the Observer channel during runtime configuration. ```APIDOC ## runtime.Config.Observer ### Description Configures the observer through the runtime facades for PostgreSQL, MySQL, and SQLite. This is an alternative to WithObserver for setting the Observer channel during runtime configuration. ### Method Config.Observer ### Parameters #### Configuration Field - **Observer** (chan outbox.RuntimeOutcome) - Optional - Send-only Observer channel of RuntimeOutcome values. Nil is the default no-op. ### Response No direct response; configuration is used during runtime construction. ### Notes - Notifications describe successful configured storage/transaction returns, not handler completion. - Sends are nonblocking; full sinks drop events and closed-sink sends are contained. - Keep the sink open throughout Run; callers must not race a channel close with active senders. Close only after Run joins its workers. ``` -------------------------------- ### WithObserver(events) Source: https://github.com/assurrussa/outbox/blob/master/docs/contracts.md Configures a send-only Observer channel of RuntimeOutcome values during core service construction. Notifications describe successful configured storage/transaction returns, not handler completion. Sends are nonblocking; full sinks drop events and closed-sink sends are contained. ```APIDOC ## WithObserver(events) ### Description Configures a send-only Observer channel of RuntimeOutcome values during core service construction. Notifications describe successful configured storage/transaction returns, not handler completion. Sends are nonblocking; full sinks drop events and closed-sink sends are contained. ### Method WithObserver ### Parameters #### Function Parameters - **events** (chan outbox.RuntimeOutcome) - Required - Send-only Observer channel of RuntimeOutcome values. Nil is the default no-op. ### Response #### Success Response - **options** ([]Option) - Returns options to be passed to outbox.New. ### Request Example ```go events := make(chan outbox.RuntimeOutcome, 128) options = append(options, outbox.WithObserver(events)) svc, err := outbox.New(options...) // Include the existing required dependencies. ``` ### Notes - Consume events in caller-owned code while svc.Run is active, then join Run and close/drain the channel according to the application's lifecycle. - Keep the sink open throughout Run; callers must not race a channel close with active senders. Close only after Run joins its workers. - The runtime owns no observer goroutine or queue and never executes consumer callbacks. - This best-effort stream is not a durable audit log or replay API; it has no total ordering across workers and events may be dropped. ``` -------------------------------- ### Build outbox service with SQLite backend Source: https://github.com/assurrussa/outbox/blob/master/backends/sqlite/README.md Constructs an outbox.Service using the SQLite backend. It creates the storage client, runs embedded migrations with the 'up' command, and wires repositories and a transaction. The jobs repository is auto-detected for exact grouped queue stats and unique puts; fan-out is explicitly enabled via WithFanoutJobsRepo. The runtime does not migrate automatically and pins the pool to one connection because SQLite is a single-writer database. ```go import ( "context" "time" sqlitemigrator "github.com/assurrussa/outbox/backends/sqlite/migrator" "github.com/assurrussa/outbox/backends/sqlite/repositories/jobsfailedrepo" "github.com/assurrussa/outbox/backends/sqlite/repositories/jobsrepo" sqlitestorage "github.com/assurrussa/outbox/backends/sqlite/storage" sqlitetx "github.com/assurrussa/outbox/backends/sqlite/storage/transaction" "github.com/assurrussa/outbox/outbox" "github.com/assurrussa/outbox/outbox/logger" ) func build(ctx context.Context, dsn string) (*outbox.Service, error) { lg := logger.Default() client, err := sqlitestorage.Create(ctx, dsn) if err != nil { return nil, err } if err := sqlitemigrator.RunEmbedded(ctx, client.DB(), lg, sqlitemigrator.WithCommand("up")); err != nil { return nil, err } jobs := jobsrepo.Must(client) failed := jobsfailedrepo.Must(client) trx := sqlitetx.New(client.DB()) return outbox.New( outbox.WithWorkers(1), outbox.WithReservationBatchSize(32), outbox.WithIdleTime(100*time.Millisecond), outbox.WithReserveFor(time.Second), outbox.WithJobsRepo(jobs), outbox.WithFanoutJobsRepo(jobs), outbox.WithJobsFailedRepo(failed), outbox.WithTransactor(trx), outbox.WithLogger(lg), ) } ``` -------------------------------- ### Shared wiki context path Source: https://github.com/assurrussa/outbox/blob/master/docs/project-map.md Path to the shared platform context file for outbox. ```text ${AGENT_CONTEXT_ROOT}/streams/wiki/platforms/outbox.md ``` -------------------------------- ### Run stable core release readiness gate Source: https://github.com/assurrussa/outbox/blob/master/RELEASING.md Run before tagging the root module for a stable core release. The command performs mutating preparation once, then a source-read-only check with one race+coverage core traversal and one normal traversal per backend. Commit generated files before running; tag and publish only after the command is clean. ```sh make release-readiness-core CORE_VERSION=v0.17.0 ``` -------------------------------- ### Focused integration checks Source: https://github.com/assurrussa/outbox/blob/master/AGENTS.md Run integration tests for a specific backend. Each command targets one backend: MySQL, SQLite, PostgreSQL, or Picodata. ```sh make test-integration-mysql make test-integration-sqlite make test-integration-pgsql make test-integration-picodata ``` -------------------------------- ### Run canonical SQLite integration gate Source: https://github.com/assurrussa/outbox/blob/master/docs/recipient-process-recovery.md Runs the existing make target that includes the fixture as part of the canonical integration gate. No workflow or automatic trigger change is required. ```sh make test-integration-sqlite ``` -------------------------------- ### Permanent Source: https://github.com/assurrussa/outbox/blob/master/README.md Moves the owned job directly to DLQ. Fenced by job ID, lease token, and an unexpired lease. ```APIDOC ## Permanent ### Description Moves the owned job directly to DLQ. Fenced by job ID, lease token, and an unexpired lease. ### Method Permanent ### Parameters #### Arguments - err (error) - Required - The error causing the permanent failure. ### Response #### Success Response - error (error) - The wrapped error to return from Handle. ### Request Example ```go return outbox.Permanent(err) ``` ``` -------------------------------- ### Open pgsql runtime with bounded pool config Source: https://github.com/assurrussa/outbox/blob/master/backends/pgsql/README.md Opens the pgsql runtime with explicit connection limits and reservation batch size. A 0/0 connection configuration keeps historical min=5/max=10 defaults; set both values to reserve a bounded pool. ReservationBatchSize zero keeps core default of 1. RetryPolicy and Observer are optional and forwarded to outbox.New. ```go runtime, err := pgsqlruntime.Open(ctx, pgsqlruntime.Config{ DSN: relayDSN, ReservationBatchSize: 32, // zero keeps the core default of 1 MinConnectionsCount: 1, MaxConnectionsCount: 1, // Optional: RetryPolicy and Observer are forwarded to outbox.New. }) ``` -------------------------------- ### Fast gates: make test-core, test-backends, test-race-core Source: https://github.com/assurrussa/outbox/blob/master/docs/tasks/outbox-backend-parity.md Run the fast verification gates for core and backend tests. These are the quick checks to run before more extensive integration tests. ```sh make test-core make test-backends make test-race-core ``` -------------------------------- ### Import core package Source: https://github.com/assurrussa/outbox/blob/master/README.md Import the core outbox package in Go code. ```go import "github.com/assurrussa/outbox/outbox" ``` -------------------------------- ### Run canonical PostgreSQL integration gate Source: https://github.com/assurrussa/outbox/blob/master/docs/postgresql-connection-recovery.md Runs the canonical integration gate that includes the connection-outage recovery regression. Requires the existing integration environment to be running. ```sh make test-integration-pgsql ```