Documentation
¶
Overview ¶
Package postgres is the durable PostgreSQL storage plugin for cyoda-go.
It ships in the stock binary alongside the memory plugin and serves as the reference example for the DescribablePlugin pattern (ConfigVars() drives --help output) and for the txID-to-physical-handle bridge (pgx.Tx lookup via the internal txRegistry).
Configuration ¶
Plugin-namespaced env vars, all read via the injected getenv:
CYODA_POSTGRES_URL (required) PostgreSQL connection string CYODA_POSTGRES_MAX_CONNS default 25 CYODA_POSTGRES_MIN_CONNS default 5 CYODA_POSTGRES_MAX_CONN_IDLE_TIME default 5m CYODA_POSTGRES_AUTO_MIGRATE default true (runs embedded SQL migrations at startup) CYODA_POSTGRES_SCHEDULER_CONNS default 10 (scheduler's own pool; at least 2) CYODA_POSTGRES_MODEL_CONNS default 8 (model store's own pool; extensions use at most half; at least 2)
Ceilings, each accepting 0 to disable. All but the acquire timeout are applied server-side; pgxpool.Config has no acquire-timeout field, so that one is a Go-side pool deadline:
CYODA_POSTGRES_STATEMENT_TIMEOUT default 5m max run time for one statement
CYODA_POSTGRES_IDLE_IN_TX_TIMEOUT default 5m max idle time inside an open transaction
CYODA_POSTGRES_ACQUIRE_TIMEOUT default 10s max wait for a free pooled connection when
opening a transaction or a second one inside it
CYODA_POSTGRES_SEARCH_STATEMENT_TIMEOUT default 30m statement ceiling for async search scans
CYODA_POSTGRES_MIGRATE_LOCK_TIMEOUT default 5m max lock wait during schema migration
Exceeding the acquire or idle-in-transaction ceiling is transient contention and surfaces as a retryable 503 STORAGE_UNAVAILABLE. Exceeding the statement ceiling is not: re-running the same work would exceed it again, so it surfaces as a 500 with a ticket.
The search ceiling is neither. It applies only to async-search scans (see AsyncScanContext), which have no HTTP response to carry a status: classifyScanError returns a searchCeilingError, and the domain records the job FAILED with a fixed message that GetJob serves back verbatim.
In every case the server log names the setting that fired.
Not plugin-namespaced, but read here and advertised via ConfigVars():
CYODA_SCHEMA_SAVEPOINT_INTERVAL default 64 a model's deltas per savepoint; bounds the deltas a read folds
Migrations and context cancellation ¶
NewFactory receives a startup context with a deadline. The embedded SQL migrations run via golang-migrate/migrate/v4, whose m.Up() method does not accept a context. To honor the deadline, runMigrations runs m.Up() in a goroutine and signals m.GracefulStop on ctx.Done() to interrupt at the next migration-step boundary.
TransactionManager and RLS ¶
The plugin's TM is a lifecycle tracker over a thread-safe txRegistry mapping txID → pgx.Tx. TM.Begin starts a REPEATABLE READ transaction (snapshot isolation; first-committer-wins is layered on top in the TM), runs SELECT set_config('app.current_tenant', $1, true) for row-level security (the set_config function accepts bound parameters where SET LOCAL does not under pgx's extended-query protocol), and records the handle in the registry. Stores hold a ctxQuerier that re-resolves the underlying pgx.Tx on every call from the passed-in context — so the active tx, discovered via spi.GetTransaction(ctx), is always used when one is present, and the pool is used otherwise. The model store is the exception: it never joins a transaction on ctx (Model pool, below).
Model pool ¶
Model reads, schema extensions and model administration run on a pool of their own (CYODA_POSTGRES_MODEL_CONNS) with lock_timeout 0, so entity transactions cannot starve them, and never join a transaction on ctx: a read returns the latest committed model in one statement, and each extension commits in a short READ COMMITTED transaction of its own under the model row's FOR NO KEY UPDATE lock. Extensions hold at most half the pool's connections. See model_pool.go and modelStore.ExtendSchema.
Scheduler pool ¶
The scheduled-task store's never-joining methods, and the async-search heartbeat and claim, run on a pool of their own (CYODA_POSTGRES_SCHEDULER_CONNS) with fixed ceilings: READ COMMITTED, statement_timeout 30s, idle_in_transaction_session_timeout 10s, lock_timeout 2s, and a 5s acquire. The scheduler heartbeat has one more connection of its own. See scheduler_pool.go.
Registration:
import _ "github.com/cyoda/cyoda-go/plugins/postgres"
Index ¶
- Variables
- func Migrate(pool *pgxpool.Pool) error
- func NewPool(ctx context.Context, cfg DBConfig) (*pgxpool.Pool, error)
- func RunMigrateWithDSN(ctx context.Context, dsn string) error
- type ApplyFunc
- type DBConfig
- type Querier
- type StoreFactory
- func (f *StoreFactory) AsyncSearchStore(_ context.Context) (spi.AsyncSearchStore, error)
- func (f *StoreFactory) Close() error
- func (f *StoreFactory) EntityStore(ctx context.Context) (spi.EntityStore, error)
- func (f *StoreFactory) InitTransactionManager(uuids spi.UUIDGenerator)
- func (f *StoreFactory) KeyValueStore(ctx context.Context) (spi.KeyValueStore, error)
- func (f *StoreFactory) MessageStore(ctx context.Context) (spi.MessageStore, error)
- func (f *StoreFactory) ModelStore(ctx context.Context) (spi.ModelStore, error)
- func (f *StoreFactory) Ping(ctx context.Context) error
- func (f *StoreFactory) Pool() *pgxpool.Pool
- func (f *StoreFactory) ScheduledTaskStore(_ context.Context) (spi.ScheduledTaskStore, error)
- func (f *StoreFactory) SetApplyFunc(fn func(base []byte, deltas []spi.SchemaDelta) ([]byte, error))
- func (f *StoreFactory) StateMachineAuditStore(ctx context.Context) (spi.StateMachineAuditStore, error)
- func (f *StoreFactory) SupportsCompositeUniqueKeys() bool
- func (f *StoreFactory) TransactionManager(ctx context.Context) (spi.TransactionManager, error)
- func (f *StoreFactory) WorkflowStore(ctx context.Context) (spi.WorkflowStore, error)
- type TransactionManager
- func (tm *TransactionManager) Begin(ctx context.Context) (string, context.Context, error)
- func (tm *TransactionManager) Commit(ctx context.Context, txID string) error
- func (tm *TransactionManager) ConsistencyTime(ctx context.Context) (time.Time, error)
- func (tm *TransactionManager) GetSubmitTime(ctx context.Context, txID string) (time.Time, error)
- func (tm *TransactionManager) Join(ctx context.Context, txID string) (context.Context, error)
- func (tm *TransactionManager) LatestRecordedTime(ctx context.Context) (time.Time, error)
- func (tm *TransactionManager) LookupTx(txID string) (pgx.Tx, bool)
- func (tm *TransactionManager) LostRace(ctx context.Context, txID string) (bool, error)
- func (tm *TransactionManager) ReleaseSavepoint(ctx context.Context, txID string, savepointID string) error
- func (tm *TransactionManager) Rollback(ctx context.Context, txID string) error
- func (tm *TransactionManager) RollbackToSavepoint(ctx context.Context, txID string, savepointID string) error
- func (tm *TransactionManager) Savepoint(ctx context.Context, txID string) (string, error)
- type TransactionManagerOption
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidAggregate = errors.New("invalid aggregate expression")
ErrInvalidAggregate signals a malformed AggregateExpr reaching the plugin.
var ErrInvalidFilterPath = fmt.Errorf("%w", spi.ErrInvalidFilterPath)
ErrInvalidFilterPath is returned when a Filter.Path, GroupExpr.Path, or AggregateExpr.Field contains characters that could break out of a JSONB path literal in a doc->>'<path>' style expression. Sentinel for callers that want to distinguish input validation errors from storage errors.
The same grammar is enforced in plugins/sqlite/path_validation.go; the two implementations are kept structurally identical so cross-backend parity tests can rely on the same rejection set.
It wraps spi.ErrInvalidFilterPath, the cross-backend sentinel, so errors.Is matches against either this one or the SPI one. The "%w"-only wrap adds no prefix, leaving the message text unchanged.
var ErrInvalidGroupExpr = errors.New("invalid group expression")
ErrInvalidGroupExpr signals a malformed spi.GroupExpr reaching the plugin. Inputs are normally validated upstream (Task 6); this is defence-in-depth.
Functions ¶
func Migrate ¶
Migrate preserves the existing exported API for test fixtures. It applies the shipped lock-timeout default: a fixture migrates a database nothing else is touching, so its lock waits are uncontended and there is no second source of truth to keep in step.
func RunMigrateWithDSN ¶
RunMigrateWithDSN is the entry point for the `cyoda migrate` subcommand. It opens a connection pool from dsn, runs the same ensureSchema sequence a booting node runs, and closes the pool before returning. The caller supplies a context for timeout/cancellation control.
Returns a descriptive error when:
- dsn is empty
- the pool cannot be opened or pinged
- the schema is newer than this binary's embedded migrations
- the migration state is dirty (manual intervention required)
- the wait for the migration lock exceeds CYODA_POSTGRES_MIGRATE_LOCK_TIMEOUT
- any migration step fails
Types ¶
type ApplyFunc ¶
type ApplyFunc func(base []byte, deltas []spi.SchemaDelta) ([]byte, error)
ApplyFunc replays opaque SchemaDeltas, in order, onto a base schema in one call and returns the new schema bytes; an empty list re-encodes base. The composition root (app/app.go) passes schema.ApplyMany, which decodes and encodes the schema once per call, so the fold makes one call for the whole log after the savepoint.
type DBConfig ¶
type DBConfig struct {
URL string
MaxConns int32
MinConns int32
MaxConnIdleTime string
AutoMigrate bool
SchemaSavepointInterval int // 0 falls back to defaultSchemaSavepointInterval
}
DBConfig is the exported config type retained for test-fixture callers. Production code in the plugin uses the internal config{} directly via parseConfig(getenv). Tests can construct a DBConfig, convert to config, and call NewPool as a thin wrapper.
type Querier ¶
type Querier interface {
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
Querier abstracts pgxpool.Pool and pgx.Tx so that store implementations work both outside and inside transactions. Both pgxpool.Pool and pgx.Tx satisfy this interface natively — no adapter needed.
type StoreFactory ¶
type StoreFactory struct {
// contains filtered or unexported fields
}
StoreFactory implements spi.StoreFactory backed by PostgreSQL.
func NewStoreFactory ¶
func NewStoreFactory(pool *pgxpool.Pool) *StoreFactory
NewStoreFactory creates a new PostgreSQL-backed StoreFactory. The factory is configured with defaults equivalent to parseConfig on an empty environment — callers that need non-default config (e.g. a custom SchemaSavepointInterval) should use newStoreFactoryWithConfig.
func (*StoreFactory) AsyncSearchStore ¶
func (f *StoreFactory) AsyncSearchStore(_ context.Context) (spi.AsyncSearchStore, error)
func (*StoreFactory) Close ¶
func (f *StoreFactory) Close() error
func (*StoreFactory) EntityStore ¶
func (f *StoreFactory) EntityStore(ctx context.Context) (spi.EntityStore, error)
func (*StoreFactory) InitTransactionManager ¶
func (f *StoreFactory) InitTransactionManager(uuids spi.UUIDGenerator)
InitTransactionManager installs a TransactionManager on the factory using the given UUID generator. It must be called before the factory is used to manage transactions; until it is called, TransactionManager() returns an error. Calling it more than once overwrites the previous manager.
The internal alias initTransactionManager (same body, unexported) remains for use within the package; external callers — including test packages — should call this exported form.
func (*StoreFactory) KeyValueStore ¶
func (f *StoreFactory) KeyValueStore(ctx context.Context) (spi.KeyValueStore, error)
KeyValueStore never joins the caller's transaction (spi.KeyValueStore contract): each operation is applied when it returns. Inside a transaction the connection acquire is bounded, so a saturated pool fails the call with a retryable storage-unavailable error instead of waiting without end.
func (*StoreFactory) MessageStore ¶
func (f *StoreFactory) MessageStore(ctx context.Context) (spi.MessageStore, error)
MessageStore never joins the caller's transaction (spi.MessageStore contract): a message is applied when Save returns and survives a rollback.
func (*StoreFactory) ModelStore ¶
func (f *StoreFactory) ModelStore(ctx context.Context) (spi.ModelStore, error)
func (*StoreFactory) Ping ¶
func (f *StoreFactory) Ping(ctx context.Context) error
Ping implements spi.StoreFactory. It checks the main pool only; the scheduler pools are not consulted. After Close the pool is closed and the ping fails.
func (*StoreFactory) Pool ¶
func (f *StoreFactory) Pool() *pgxpool.Pool
Pool returns the underlying connection pool.
func (*StoreFactory) ScheduledTaskStore ¶
func (f *StoreFactory) ScheduledTaskStore(_ context.Context) (spi.ScheduledTaskStore, error)
ScheduledTaskStore returns the scheduled-task store. It resolves no tenant: tenant-facing methods take the tenant as an argument, and ClaimDue, GiveBackIdle, the owner methods and the sweeps are cross-tenant. See scheduledTaskStore for which methods join the transaction on ctx.
func (*StoreFactory) SetApplyFunc ¶
func (f *StoreFactory) SetApplyFunc(fn func(base []byte, deltas []spi.SchemaDelta) ([]byte, error))
SetApplyFunc installs the apply function the model store folds the extension log with and checks each extension against; ExtendSchema refuses to run without it. It may be called at most once — typically at factory-construction time in app/app.go. Calling it twice is a programmer error (panic).
The parameter is the unnamed function type (not postgres.ApplyFunc) so that an interface type-assertion in app/app.go can satisfy the setter uniformly across plugins whose named ApplyFunc types differ. Values of postgres.ApplyFunc are assignable to this parameter because the underlying signatures are identical.
func (*StoreFactory) StateMachineAuditStore ¶
func (f *StoreFactory) StateMachineAuditStore(ctx context.Context) (spi.StateMachineAuditStore, error)
func (*StoreFactory) SupportsCompositeUniqueKeys ¶
func (f *StoreFactory) SupportsCompositeUniqueKeys() bool
SupportsCompositeUniqueKeys advertises composite-unique-key enforcement.
func (*StoreFactory) TransactionManager ¶
func (f *StoreFactory) TransactionManager(ctx context.Context) (spi.TransactionManager, error)
TransactionManager implements spi.StoreFactory. Returns the TM configured on the factory. Errors if none was set.
func (*StoreFactory) WorkflowStore ¶
func (f *StoreFactory) WorkflowStore(ctx context.Context) (spi.WorkflowStore, error)
type TransactionManager ¶
type TransactionManager struct {
// contains filtered or unexported fields
}
TransactionManager implements spi.TransactionManager backed by PostgreSQL with REPEATABLE READ isolation plus application-layer row-granular first-committer-wins validation. Each Begin() acquires a real pgx.Tx, registers it in the txRegistry, and allocates a *txState for read/write bookkeeping used by Commit.
func NewTransactionManager ¶
func NewTransactionManager(pool *pgxpool.Pool, uuids spi.UUIDGenerator, opts ...TransactionManagerOption) *TransactionManager
NewTransactionManager creates a new PostgreSQL-backed TransactionManager.
func (*TransactionManager) Begin ¶
Begin starts a new REPEATABLE READ transaction (snapshot isolation) and returns the transaction ID and a context carrying the TransactionState.
Row-granular first-committer-wins is enforced in application code via txState bookkeeping (readSet/writeSet) and commit-time validation — see Commit() and docs/superpowers/specs/2026-04-15-postgres-si-first-committer-wins-design.md.
func (*TransactionManager) Commit ¶
func (tm *TransactionManager) Commit(ctx context.Context, txID string) error
Commit commits the transaction and records its submit time. Returns spi.ErrConflict on serialization failure (PostgreSQL error 40001), including one a savepoint rollback has since undone, or when the application-layer first-committer-wins validation detects a stale read or write set. The commit checks unique keys on the transaction's final entities (commitWrittenClaims): spi.ErrPartialUniqueKey for a partial composite key, spi.ErrUniqueViolation for a value already held, and spi.ErrConflict when two commits deadlock claiming values each frees.
Tenant isolation: rejects callers whose UserContext tenant does not match the transaction's tenant. RLS protects data-path access (every DML is row-level filtered) but does not extend to transaction-lifecycle commands (BEGIN/COMMIT/ROLLBACK/SAVEPOINT/etc.) — those operate on connections and don't trigger any policy. So the application-layer tenant gate is the only protection against a caller authenticated as tenant A committing tenant B's in-flight work.
func (*TransactionManager) ConsistencyTime ¶
ConsistencyTime implements spi.TransactionManager by "reserve, then wait" (cyoda_consistency_time, migrations 000016, 000017): it raises the stamp floor to C = max(DB clock or business clock, highest stamp issued), so every later stamp is above C, then waits for each of the tenant's in-flight markers — commits that hold a stamp at or below C and have not yet ended. The markers are found by the tenant's key (tenantKeys), resolved on the same connection first.
It runs on a pool connection of its own, in autocommit, never on the transaction in ctx, so it is safe to call from inside one. The acquire is bounded as Begin's is: inside a transaction this is a second connection, and an unbounded wait for it would be hold-and-wait. A commit waited on never waits on a lock after its stamp (see stampCommitInstant), so the caller's transaction cannot be what holds it up.
On an error from cyoda_consistency_time the connection is closed instead of being returned to the pool, so no session-level lock can outlive the error (the key lookup before it ends its own transaction and holds no lock, and its connection is released as usual). After a client-side cancel the server statement can keep waiting until its budget ends; until then it holds a server connection the pool no longer counts.
func (*TransactionManager) GetSubmitTime ¶
GetSubmitTime returns the database timestamp recorded when the transaction was committed.
Tenant isolation: like every other tx-lifecycle method, the caller's tenant must match the transaction's tenant. The check runs before any state-dependent response so a cross-tenant caller learns neither the submit time nor whether the transaction is in flight or committed.
func (*TransactionManager) Join ¶
Join attaches to an existing transaction, returning a context carrying its TransactionState.
Tenant isolation: rejects mismatched-tenant callers. Returning a context for another tenant's tx would let the joining caller drive arbitrary lifecycle operations on that tx — see Commit's godoc.
func (*TransactionManager) LatestRecordedTime ¶
LatestRecordedTime implements spi.TransactionManager: the last value of the cyoda_stamp_floor sequence, the highest stamp or consistency time issued (migration 000016). A plain read: it takes no advisory lock, does not move the floor and waits for nothing. The floor is shared by all tenants, so ctx needs no tenant. 0, the sequence's start, is the zero time.
func (*TransactionManager) LookupTx ¶
func (tm *TransactionManager) LookupTx(txID string) (pgx.Tx, bool)
LookupTx exposes the registry lookup for use in tests and by the store layer (resolveQuerier). Production code should prefer resolveQuerier.
func (*TransactionManager) LostRace ¶
LostRace reports whether the transaction has already lost a write race. PostgreSQL refuses the losing write itself — 40001 when a concurrent committer changed the row, 40P01 for a deadlock victim — and classifyTxError records that as the transaction's abort cause, which a rollback to a savepoint keeps (see txState.RestoreSavepoint). So the answer is whether the recorded cause is a concurrent writer. It issues no statement, so it answers on the aborted transaction, and it changes nothing.
Tenant isolation: rejects mismatched-tenant callers.
func (*TransactionManager) ReleaseSavepoint ¶
func (tm *TransactionManager) ReleaseSavepoint(ctx context.Context, txID string, savepointID string) error
ReleaseSavepoint releases a savepoint, merging its work into the parent transaction. The txState snapshot for this savepoint is dropped; work done after the push is kept.
Tenant isolation: rejects mismatched-tenant callers.
func (*TransactionManager) Rollback ¶
func (tm *TransactionManager) Rollback(ctx context.Context, txID string) error
Rollback aborts the transaction.
Tenant isolation: rejects mismatched-tenant callers. See Commit's godoc for the design rationale.
func (*TransactionManager) RollbackToSavepoint ¶
func (tm *TransactionManager) RollbackToSavepoint(ctx context.Context, txID string, savepointID string) error
RollbackToSavepoint rolls back all work done since the named savepoint and restores the txState readSet/writeSet to the snapshot captured at that savepoint.
Tenant isolation: rejects mismatched-tenant callers — destructive on tx-state.
type TransactionManagerOption ¶
type TransactionManagerOption func(*TransactionManager)
TransactionManagerOption configures a TransactionManager at construction.
func WithAcquireTimeout ¶
func WithAcquireTimeout(d time.Duration) TransactionManagerOption
WithAcquireTimeout bounds how long Begin waits for a pooled connection before failing with the storage-unavailable marker. Zero disables the deadline, matching the convention the GUC ceilings use. Production wiring passes cfg.AcquireTimeout (CYODA_POSTGRES_ACQUIRE_TIMEOUT); without this option the manager still gets the shipped default rather than an unbounded wait.
Source Files
¶
- ceilings.go
- classifying_querier.go
- commit_claims.go
- commit_validator.go
- config.go
- consistency_time.go
- doc.go
- entity_doc.go
- entity_store.go
- grouped_stats.go
- kv_store.go
- message_store.go
- metrics.go
- migrate.go
- model_extensions.go
- model_pool.go
- model_store.go
- path_validation.go
- platform_clock.go
- plugin.go
- querier.go
- query_planner.go
- scheduled_task_store.go
- scheduler_pool.go
- search_base.go
- search_store.go
- searcher.go
- sm_audit_store.go
- store_factory.go
- transaction_manager.go
- tx_registry.go
- txstate.go
- unique_claims.go
- unjoined_querier.go
- uuid.go
- workflow_store.go