pgstore

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package pgstore implements storage.Adapter on PostgreSQL via pgx v5.

It is the adapter for deployments that outgrow a single process. Unlike sqlitestore, several server nodes may share one database, and writes to different workspaces commit concurrently instead of queueing behind one writer connection — the concurrency the storage contract permits and SQLite declines to take.

Connection model

By default one pgxpool.Pool serves both reads and writes; a transaction holds one connection for its duration. There is no reader/writer split within one database because there is nothing to split around: Postgres readers never block on writers, so the separate pool sqlitestore keeps to escape its single write lock buys nothing here.

WithReadReplica adds a second pool, exposed through storage.ReplicaProvider, pointed at a hot standby (or at the primary itself). It carries only read-only snapshot transactions and the two workspace-list queries — no session state, no advisory locks, never migrations — and every floored read validates the replica's freshness against the workspace's last_seq inside the already-open transaction, falling back to the primary when the replica is behind. See replica.go.

Write mutual exclusion

WithWriteTx takes pg_advisory_xact_lock over a hash of the workspace id as the statement after BEGIN. Both travel in one batch with fn's first statement (see Batching), so the lock is held before anything fn reads or writes reaches the server; what fn does before that touches nothing another transaction can observe. The contract demands exclusion from fn's first statement, including the reads it makes before its first write (the push path reads a client watermark, then writes it back), and row locks cannot give that: lazy registration means a workspace's first write has no workspaces row to lock, and SELECT ... FOR UPDATE on a row that does not exist locks nothing.

The lock is keyed by a 64-bit hash, so two workspaces can collide and serialize against each other needlessly. That costs throughput, never correctness — and at 64 bits it takes on the order of 2^32 workspaces before a collision is likely at all.

Isolation

Read transactions run REPEATABLE READ READ ONLY. READ COMMITTED would take a fresh snapshot per statement, and since every scan here interleaves reads (below), the single consistent snapshot WithReadTx promises would quietly not hold across a scan.

Write transactions run READ COMMITTED: the advisory lock, not the isolation level, is what makes their pre-write reads stable. They still retry on serialization failure (40001) and deadlock (40P01), which cross-table writes inside one workspace can produce; the contract licenses re-running fn.

A replica read is a time-shifted read: the same REPEATABLE READ snapshot a primary read would have taken at some earlier moment. Convergence never depends on freshness — the engine's cursors and floors do — which is why the replica path bounds staleness per read by workspace sequence rather than by replication position.

Batching

A transaction sends nothing when it opens. BEGIN, a write transaction's workspace lock and its write-only statements wait in a queue, and the queue travels as one pgx batch with the next read, the next statement whose command tag is inspected, or COMMIT. A read transaction therefore costs a round trip per read and one for its ROLLBACK, a push of N mutations a handful rather than three per mutation, and a transaction that issues no statement nothing at all. Savepoints ride in the queue with the writes they bracket. See queue.go, which carries the rules this rests on.

The index entries of a transaction's rows reach the queue as one delete and one replace statement for each 500 rows, when the transaction commits or first reads an index (see index.go), and its search postings in the same manner (see postings.go).

Scans and re-entrant reads

Every scan method decodes rows into memory before handing any of them to the callback (see scanRows). This is the one mechanism here that is not a transliteration of sqlitestore, and it exists because the engine reads from INSIDE scan callbacks — ScanIndex re-reads each candidate row, ScanChanges reads FieldDeltas to ship a text delta. SQLite tolerates interleaved statements on one connection; pgx does not, so holding one result set open across the callback would fail on the engine's first indexed query or first pull of a text entity.

A scan whose limit already bounds the result reads it in a single statement. An unlimited one — ScanEntity takes no limit, and bootstrap walks whole entities through it — reads its first batch in a single statement too, and pages through a server-side cursor only when the result is larger than that, so its memory stays off the size of the entity at the cost of a round trip per batch.

Schema and physical layout

Open applies any outstanding migrations at boot, serialized across nodes by an advisory lock. Migrate and Statements expose the same ledger to a deployment that would rather own its DDL as a deploy step, and WithoutMigrations turns the boot-time application into a check that the step has run. WithPartitions hash-partitions the workspace-scoped tables at creation time, which is the one schema decision this adapter cannot make for a database after it holds data. See schema.go.

Collation and integer width

Every text column is declared COLLATE "C". The engine compares keys with Go's <, which is bytewise, and shares that order with the adapter across page boundaries — under a locale collation an afterKey scan silently drops or repeats rows rather than failing. Index entry keys are bytea, which Postgres already compares bytewise.

Postgres has no unsigned bigint, so sequences, versions and the store epoch round-trip through int64 by reinterpreting the bits. The epoch matters most: it is a genuinely random 64 bits (see ReadTx.StoreEpoch), not a counter that stays inside int63.

Re-entrancy

Opening a write transaction from inside another write transaction on the same workspace deadlocks: the inner transaction takes a second pooled connection and waits for an advisory lock the outer one holds until commit. This is the same trap sqlitestore has for a different reason, and the server's re-entrancy guards (Mutate, Invoke, CollectGarbage) keep it from being reachable.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CanServe

func CanServe(binaryVersion, schemaVersion int) bool

CanServe reports whether a binary that knows binaryVersion migrations can serve a database migrated to schemaVersion — true when every step between them only added to the schema.

It answers from THIS binary's migration list, so it is for a process that knows schemaVersion: a deploy step asking, before it migrates, whether the fleet it is about to run ahead of will survive until the roll reaches it. A schemaVersion this binary does not know is unanswerable and reports false.

The running node's own version of this question is decided at Open, out of the ledger, since a binary cannot judge steps it does not carry.

func Migrate

func Migrate(ctx context.Context, dsn string, opts ...Option) error

Migrate applies any outstanding migrations to the database at dsn and closes its connection before returning.

Open does the same at boot. Running it from a deploy step instead lets the fleet boot against a database already at the head — at the cost Statements describes, since a node older than the ledger cannot open the database at all. Give those nodes WithoutMigrations so the step is the only thing that applies DDL.

Several processes may run it concurrently: each step is applied once, serialized by an advisory lock. That lock is session-scoped and held across the transactions applying the steps, so dsn must not name a transaction-pooling proxy.

WithPartitions applies only to a database with no migrations recorded.

Example

A deploy step owns the schema: it migrates once, choosing the table layout, and the nodes behind it never apply DDL of their own.

package main

import (
	"context"
	"log"

	"github.com/levelfourab/syncplane/engine/storage/pgstore"
)

// The DSN both examples migrate. Neither runs — they have no Output comment —
// so no Postgres is needed to build them.
const exampleDSN = "postgres://syncplane@db.internal:5432/syncplane"

func main() {
	ctx := context.Background()

	if err := pgstore.Migrate(ctx, exampleDSN, pgstore.WithPartitions(32)); err != nil {
		log.Fatal(err)
	}

	// On every node, at boot, and under a role with no privilege to change the
	// schema. WithoutMigrations is what makes the step above authoritative:
	// this fails rather than migrating if the step has not run.
	store, err := pgstore.Open(ctx, exampleDSN, pgstore.WithoutMigrations())
	if err != nil {
		log.Fatal(err)
	}
	defer store.Close()
}

func SchemaVersion

func SchemaVersion() int

SchemaVersion returns the ledger version this binary migrates a database to, counting from 1. A database Open accepts without complaint is at this version or, when every step between is additive, above it.

Types

type Migration

type Migration struct {
	// Version is the ledger version the step brings the database to, counting
	// from 1.
	Version int
	// SQL is the whole step — its DDL and the row recording it in
	// schema_migrations — as a script to run in a single transaction.
	SQL string
}

Migration is one step of pgstore's schema ledger.

func Statements

func Statements(opts ...Option) ([]Migration, error)

Statements returns every migration this binary knows, in order, as SQL for a database that has none of them yet.

Applying them all, each in its own transaction, leaves a database Open accepts as fully migrated: each script records itself in the ledger and the first creates the ledger, so nothing needs stamping afterwards. It is the offline form of Migrate, for DDL that a migration tool owns or that is read before it runs.

Only WithPartitions changes the output; every other option is ignored, and an invalid one is the only error returned.

Open applies whatever the ledger is missing, so a node that boots before these have run migrates the database itself; WithoutMigrations makes it fail instead. A node whose binary does not know the ledger's highest version fails Open either way, which is what a step applied ahead of a roll costs.

Example

Where the DDL is reviewed or applied by a migration tool, the same steps come out as SQL. Each script ends with its own row in schema_migrations, so a database they were applied to needs no stamping before Open accepts it.

package main

import (
	"fmt"
	"log"

	"github.com/levelfourab/syncplane/engine/storage/pgstore"
)

func main() {
	migrations, err := pgstore.Statements(pgstore.WithPartitions(32))
	if err != nil {
		log.Fatal(err)
	}
	for _, m := range migrations {
		fmt.Printf("-- migration %d\n%s\n", m.Version, m.SQL)
	}
}

type Option

type Option func(*config)

Option configures Open, Migrate and Statements.

func WithMaxConns

func WithMaxConns(n int32) Option

WithMaxConns caps the connection pool. A write transaction holds a connection while it waits for its workspace's advisory lock, so the pool bounds how many writers can be in flight — not how many can make progress, since the lock holder always has its own connection. Zero leaves pgx's default (or whatever the DSN's pool_max_conns says).

func WithPartitions

func WithPartitions(n int) Option

WithPartitions hash-partitions the workspace-scoped tables with the given modulus.

The tables rows and idempotency are partitioned by workspace_id, the tables index_rows, index_entries, field_deltas and consumer_shadows by the workspace number that index_scopes gives each workspace, and the posting tables posting_rows, posting_chunks and posting_pages by their posting scope. The modulus must be a power of two up to 1024; zero, the default, leaves each table whole, and Open, Migrate and Statements reject any other value.

It is honoured only when the database has no migrations recorded yet; both Open and Migrate otherwise adopt the layout they find. A deploy step may therefore choose the layout once and every node boot without the option, and a boot naming a different modulus is ignored rather than obeyed. Nothing here converts a database that already holds data.

docs/how-to/deploy-for-high-availability.md carries what the layout buys and what it costs.

func WithReadReplica

func WithReadReplica(dsn string) Option

WithReadReplica adds a read-replica pool at dsn — a hot standby of the primary, or the primary itself — and makes the store implement storage.ReplicaProvider. The replica serves read-only snapshot transactions through that capability and the workspace-list queries; everything else, including migrations and leases, stays on the primary.

Open fails when the schema at dsn is not at the primary's migration version, which is what catches a DSN that is not a standby of the primary's database.

func WithReplicaMaxConns

func WithReplicaMaxConns(n int32) Option

WithReplicaMaxConns caps the replica pool. A replica connection is held for the duration of one read transaction, so this bounds concurrent replica reads; callers past the cap queue on the pool exactly as they do on the primary's. Zero leaves pgx's default (or whatever the replica DSN's pool_max_conns says).

func WithoutMigrations

func WithoutMigrations() Option

WithoutMigrations makes Open verify the schema instead of applying it: it reads the migration ledger and fails unless the database is already at this binary's version, leaving Migrate or Statements to have brought it there.

It is what makes a deploy step that owns the DDL authoritative rather than advisory, since otherwise the first node to boot with a newer binary migrates the database itself. A node opening this way issues no DDL and takes no advisory lock, so it may connect as a role with no privilege beyond the rows it serves.

Migrate and Statements ignore it, as does WithPartitions alongside it — nothing is created for a modulus to apply to.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store implements storage.Adapter.

func Open

func Open(ctx context.Context, dsn string, opts ...Option) (*Store, error)

Open connects to the Postgres database named by dsn (a libpq URI or key/value string) and applies any outstanding migrations, or under WithoutMigrations verifies that something else already has.

Several processes may Open the same database concurrently: migration is serialized by an advisory lock, which is the difference from sqlitestore's "never open the same file twice". Use prefixstore to multiplex apps over one database.

func (*Store) Close

func (s *Store) Close() error

Close closes the pools and the lease session.

func (*Store) CursorStateStore

func (s *Store) CursorStateStore() cursorstate.Store

CursorStateStore returns a cursorstate.Store backed by this database, making the adapter a cursorstate.Provider: a server constructed on this store gets cursors that reference their membership sets instead of restating them, and — because the entries are in the shared database — a client can present its cursor to any node. Entries are pruned on write (see the constants above); a client presenting a pruned entry is reset, exactly as one below the tombstone horizon is.

func (*Store) DeleteCatalogEntry

func (s *Store) DeleteCatalogEntry(ctx context.Context, id string) error

func (*Store) DeleteWorkspace added in v0.4.0

func (s *Store) DeleteWorkspace(ctx context.Context, workspaceID string) error

DeleteWorkspace empties every table in scopedTables, numberedTables and workspaceTables for the workspace and records its mark, in one write transaction under the workspace lock. The statements are queued, so they travel with COMMIT as one batch.

func (*Store) Leases

func (s *Store) Leases() lease.Locker

Leases returns a lease.Locker backed by Postgres session advisory locks, making the adapter a lease.Provider: every node sharing the database leases out of one space, so a server constructed on this store dedups its background work across the deployment with no configuration.

Every lease of a Store is held on one dedicated connection, dialled on the first TryAcquire. A node that crashes or loses that connection releases everything it held at once, with no TTL to wait out, and is never told its leases are gone — so leased work stays idempotent. TryAcquire returns the underlying error when the session cannot be dialled or the lock statement fails, and ctx's error, with no lease, when ctx is already done. A caller's cancellation never costs the Store the leases its other holders have.

Two holders on one Store exclude each other, as two Stores do.

Lock keys are 64-bit hashes of (schema, role, workspace). The schema keeps deployments that share one database server but live in separate schemas out of each other's lease space; a hash collision within one space makes two pairs exclude each other, which costs deferred work and never correctness.

func (*Store) ListCatalogEntries

func (s *Store) ListCatalogEntries(ctx context.Context) ([]storage.CatalogEntry, error)

func (*Store) ListCollectableWorkspaceIDs

func (s *Store) ListCollectableWorkspaceIDs(ctx context.Context, cutoffs storage.GCCutoffs, rng storage.Range, limit int) ([]string, error)

ListCollectableWorkspaceIDs answers "which workspaces hold something this pass would reclaim" as a single query: the workspace scan is in primary-key order, and every candidate table is reached through its _gc index on (workspace_id, updated_at) — correlated per workspace or hashed once, whichever the planner costs lower. Either way a workspace with nothing collectable costs index reads and no transaction, where a pass without this took the workspace's advisory lock and ran six DELETEs to learn the same thing.

The entity purges are the exception. Live rows of an aging entity are found on rows_by_entity_version's (workspace_id, entity) prefix with updated_at left as a filter, so a workspace whose entity has no expired row reads that entity's entries to say so — the same range PurgeEntityRows walks to delete them, read instead of written.

On the primary rather than the replica, unlike the other two workspace-list queries: a lagging replica would keep returning workspaces a pass has just collected, and each of those costs the write transaction this query exists to avoid. Its cost is one query a minute, so there is nothing to offload.

func (*Store) ListCompactableWorkspaceIDs

func (s *Store) ListCompactableWorkspaceIDs(ctx context.Context, minPurged int, rng storage.Range, limit int) ([]string, error)

ListCompactableWorkspaceIDs compares two columns of the workspace row and reads nothing else. Whether a row is worth compacting is a question only decoding its text can answer, so the query does not ask it: it asks the cheaper question of whether the sweep has fallen behind the delta prune, which is the one the mark already records.

Scanned rather than indexed, like ListStaleIndexWorkspaceIDs: the predicate compares two columns to each other, which no btree serves. On the primary, for the same reason that query is — a lagging replica re-selects workspaces whose mark is already written, and each costs a lease and a write transaction.

func (*Store) ListPendingWorkspaceIDs

func (s *Store) ListPendingWorkspaceIDs(ctx context.Context, consumer string, rng storage.Range, limit int) ([]string, error)

ListPendingWorkspaceIDs answers "which workspaces owe this consumer work" as a single indexed query: the workspace scan is in primary-key order, and each row probes consumer_positions on its own primary key prefix (workspace_id, consumer). A workspace with no position row for the consumer is pending by the LEFT JOIN — a first run has acted on nothing.

A non-empty entity or key is pending whatever the sequence says: that is a sub-position inside a same-sequence group, so the group has changes after it even when the sequence has reached the head. Only a clean boundary — the cursor a drained pass records — means caught up.

func (*Store) ListStaleIndexWorkspaceIDs

func (s *Store) ListStaleIndexWorkspaceIDs(ctx context.Context, mark string, rng storage.Range, limit int) ([]string, error)

ListStaleIndexWorkspaceIDs scans the workspaces table and compares one column. There is no index for it — a btree cannot serve `<>` — and none is wanted: the scan is one row per workspace, which is what replaces the point read per (workspace × entity × index) the pass did to learn the same thing.

On the primary, for ListCollectableWorkspaceIDs' reason: a lagging replica would re-select workspaces whose mark is already written, and each of those costs a lease and a write transaction.

func (*Store) ListWorkspaceIDs

func (s *Store) ListWorkspaceIDs(ctx context.Context, rng storage.Range) ([]string, error)

func (*Store) PutCatalogEntry

func (s *Store) PutCatalogEntry(ctx context.Context, id string, payload []byte, revision string) error

PutCatalogEntry upserts an entry into the server-global catalog.

func (*Store) ReplicaReader

func (s *Store) ReplicaReader() storage.ReplicaReader

ReplicaReader returns the store's replica-capable reader, or nil when Open was not given WithReadReplica (see storage.ReplicaProvider).

func (*Store) RestoreWorkspace added in v0.4.0

func (s *Store) RestoreWorkspace(ctx context.Context, workspaceID string) error

RestoreWorkspace removes the workspace's deletion mark, under the workspace lock so that it cannot land halfway through a write transaction.

func (*Store) SwapCatalogEntry added in v0.2.0

func (s *Store) SwapCatalogEntry(ctx context.Context, id string, payload []byte, revision, prev string) error

SwapCatalogEntry stores an entry of the server-global catalog when its stored revision is prev.

func (*Store) WithReadTx

func (s *Store) WithReadTx(ctx context.Context, workspaceID string, fn func(storage.ReadTx) error) error

func (*Store) WithWriteTx

func (s *Store) WithWriteTx(ctx context.Context, workspaceID string, fn func(storage.WriteTx) error) error

func (*Store) WorkspaceDeleted added in v0.4.0

func (s *Store) WorkspaceDeleted(ctx context.Context, workspaceID string) (bool, error)

WorkspaceDeleted reads the mark from the primary. The replica is never asked: one that has not replayed a deletion would admit clients to a workspace that is gone.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL