Package postgres (module and import path
github.com/coder/chat/state/postgres) is a Postgres-backed implementation of
the chat.State interface from github.com/coder/chat [doc.go:postgres]. It
stores subscriptions, dedupe events, and thread locks in three tables that it
creates on startup. All expiry checks use the database clock now(). Every
row is scoped by a namespace string. It is a separate Go module with its own
go.mod [go.mod:module]. postgres.go imports github.com/coder/chat,
github.com/coder/chat/internal/tokens, and
github.com/jackc/pgx/v5/pgxpool.
Options[postgres.go:Options]:Pool *pgxpool.Pool,Namespace string.State[postgres.go:State]: unexported fieldspool,namespace, andonce(sync.Once).var _ chat.State = (*State)(nil)[postgres.go:State]: compile-time check that*Stateimplementschat.State.func New(ctx context.Context, opts Options) (*State, error)[postgres.go:New]: pings the pool and creates the schema.(*State).IsThreadSubscribed(ctx, id chat.ThreadID) (bool, error)[postgres.go:State.IsThreadSubscribed](*State).SubscribeThread(ctx, id chat.ThreadID) error[postgres.go:State.SubscribeThread](*State).UnsubscribeThread(ctx, id chat.ThreadID) error[postgres.go:State.UnsubscribeThread](*State).MarkEvent(ctx, id string, ttl time.Duration) (bool, error)[postgres.go:State.MarkEvent](*State).AcquireLock(ctx, key string, ttl time.Duration) (chat.LockLease, bool, error)[postgres.go:State.AcquireLock](*State).ExtendLock(ctx, lease chat.LockLease, ttl time.Duration) (bool, error)[postgres.go:State.ExtendLock](*State).ReleaseLock(ctx, lease chat.LockLease) (bool, error)[postgres.go:State.ReleaseLock](*State).Shutdown(context.Context) error[postgres.go:State.Shutdown]
Newrequiresopts.Pool. A nil pool fails with"postgres state: pool is required"before any database call [postgres.go:New].Newtrims whitespace fromNamespace. An empty result becomes"chat"[postgres.go:New].- Every table's primary key starts with
namespace[postgres.go:schemaStatements], and every query in theStatemethods filters on it [postgres.go:State.MarkEvent] [postgres.go:State.AcquireLock]. - Validation errors:
"postgres state: thread id is required"(empty thread ID in the three subscription methods),"postgres state: event id is required","postgres state: lock key is required", and"postgres state: lock lease is required"(emptyKeyorToken) [postgres.go:State.IsThreadSubscribed] [postgres.go:State.MarkEvent] [postgres.go:State.AcquireLock] [postgres.go:State.ExtendLock] [postgres.go:State.ReleaseLock]. positiveMicrosrejectsttl <= 0with"postgres state: dedupe ttl must be positive"or"postgres state: lock ttl must be positive". It converts the TTL withDuration.Microseconds()and rounds a positive sub-microsecond TTL up to1[postgres.go:positiveMicros].SubscribeThreadis idempotent throughON CONFLICT (namespace, thread_id) DO NOTHING[postgres.go:State.SubscribeThread].UnsubscribeThreadreturnsnilwhen no row exists [postgres.go:State.UnsubscribeThread].MarkEventreturnstrueonly when it inserts a row or replaces a row whoseexpires_at <= now(). An unexpired row returns(false, nil)[postgres.go:State.MarkEvent].AcquireLocktakes over an existing row only when itsexpires_at <= now(). It then writes a new token. When the lock is held it returns(chat.LockLease{}, false, nil)[postgres.go:State.AcquireLock].ExtendLockandReleaseLockmatch onnamespace,lock_key,token, andexpires_at > now(). They returntrueonly whenRowsAffected() == 1. An expired lease cannot be extended or released [postgres.go:State.ExtendLock] [postgres.go:State.ReleaseLock].- Schema setup runs in one transaction that first runs
SELECT pg_advisory_xact_lock(hashtext($1)::bigint)with$1 = "chat_runtime_state_schema". This serializes concurrent setup calls against one database [postgres.go:State.setup]. - Query errors from the state methods are returned unwrapped.
Newwraps its errors as"postgres state: ping: %w"and"postgres state: setup: %w"[postgres.go:New].AcquireLockwraps a token error as"postgres state: create lock token: %w"[postgres.go:State.AcquireLock]. Shutdowncloses the pool at most once and always returnsnil[postgres.go:State.Shutdown].
-
Newcallspool.Ping(ctx). If ping or setup fails,Newdoes not close the pool [postgres.go:New]. -
setupruns this DDL fromschemaStatementsinside the advisory-locked transaction. NoCREATE INDEXexists, so the only indexes are the primary keys. Each statement runs as its owntx.Exec. This README adds the semicolons [postgres.go:State.setup] [postgres.go:schemaStatements].CREATE TABLE IF NOT EXISTS chat_runtime_subscriptions ( namespace text NOT NULL, thread_id text NOT NULL, PRIMARY KEY (namespace, thread_id) ); CREATE TABLE IF NOT EXISTS chat_runtime_events ( namespace text NOT NULL, event_id text NOT NULL, expires_at timestamptz NOT NULL, PRIMARY KEY (namespace, event_id) ); CREATE TABLE IF NOT EXISTS chat_runtime_locks ( namespace text NOT NULL, lock_key text NOT NULL, token text NOT NULL, expires_at timestamptz NOT NULL, PRIMARY KEY (namespace, lock_key) );
-
IsThreadSubscribedreadschat_runtime_subscriptionswithSELECT EXISTS (...)[postgres.go:State.IsThreadSubscribed]. -
SubscribeThreadinserts intochat_runtime_subscriptions[postgres.go:State.SubscribeThread].UnsubscribeThreaddeletes from it [postgres.go:State.UnsubscribeThread]. -
MarkEventupserts intochat_runtime_eventswithexpires_at = now() + ($3::bigint * interval '1 microsecond')[postgres.go:State.MarkEvent]. -
AcquireLockupsertstokenandexpires_atintochat_runtime_locks[postgres.go:State.AcquireLock]. The token comes fromtokens.New()ingithub.com/coder/chat/internal/tokens. -
ExtendLockupdatesexpires_atinchat_runtime_locks[postgres.go:State.ExtendLock].ReleaseLockdeletes the row [postgres.go:State.ReleaseLock]. -
Expired rows are never deleted. They stay in the tables until a later
MarkEventorAcquireLockoverwrites them [postgres.go:State.MarkEvent] [postgres.go:State.AcquireLock]. -
ShutdowncallsCloseon the caller-supplied*pgxpool.Pool[postgres.go:State.Shutdown].
- Run:
cd state/postgres && go test ./... - The tests start Postgres with Testcontainers, so they need a running Docker
daemon (
test:postgrestask in the rootmise.toml). The test skips when no healthy container provider exists.