simple-state-model-postgres
v0.4.0
Published
Simple State Model — Postgres provider: hydrates states from a table, backs up changed states on an interval, and re-fetches on LISTEN/NOTIFY
Downloads
421
Readme
simple-state-model-postgres
A simple-state-model provider that keeps states in memory and uses Postgres for durability.
Reads and patches stay synchronous — the in-memory behaviour is identical to the built-in
InMemoryKeyedStateProvider. Postgres is used for three things:
- hydration — the first
load()of a key reads its row; later loads are served from memory - writing back — keys changed since the last tick are written on a fixed interval
- reading back — a
NOTIFYfor a key held in memory re-reads the row and applies the difference as a patch, so existing subscribers just see an ordinary minimal patch
The caching, the write interval and the read-back are all
CachedKeyedStateProvider in
simple-state-model; this package is the table, the listener, and the DDL. The same base backs
simple-state-model-s3, which differs only in that a bucket announces nothing and so has to be
asked on a read interval.
Install
npm install simple-state-model-postgres pgpg is a peer dependency, so the host application controls the driver version.
Usage
import { StateModel } from "simple-state-model";
import { PostgresStateProvider } from "simple-state-model-postgres";
const stateProvider = new PostgresStateProvider({
connection: { url: process.env.STATE_DB_URL },
table: "states",
backupInterval: 5000,
logger: console
});
// fail fast at boot rather than on the first request
await stateProvider.initialize();
const stateModel = new StateModel({
providers: { postgres: stateProvider },
defaultProviderID: "postgres"
});
const stateController = await stateModel.load(undefined, { id: "element-1" });
stateController.patch([{ op: "add", path: "/title", value: "Hello" }]);
// on shutdown: writes outstanding changes, then closes the connections
await stateProvider.close();Options
| Option | Default | Meaning |
| --- | --- | --- |
| connection | — | { url }, or { host, port, user, password, database }. Also accepts sslRejectUnauthorized. |
| client | — | An already-connected pg Client/Pool to use instead of connecting. |
| schema | public | Schema holding the table. |
| table | states | Table name. |
| notifyChannel | states_change | NOTIFY channel for change events. |
| create | true | Create a row when the key has none. Set to false to reject unknown IDs. |
| ensureSchema | true | Create the table, notify function and trigger at startup. |
| listen | true | Read states back when the table changes elsewhere. |
| writeInterval | 5000 | Milliseconds between writes. 0 disables the timer — call flush() yourself. |
| refreshDebounceInterval | 50 | Milliseconds to coalesce notifications before re-reading. |
| retryInterval | 5000 | Milliseconds between listener reconnect attempts. |
| expires | null | Default expires written for newly created states. |
backupInterval, notifyDebounceInterval and reconnectInterval are still accepted as the
earlier names for the three intervals.
Table
ensureSchema() creates this, idempotently, along with a row-level trigger that publishes changes:
CREATE TABLE IF NOT EXISTS "public"."states" (
"key" text PRIMARY KEY,
"value" json,
"created" timestamptz NOT NULL DEFAULT now(),
"modified" timestamptz NOT NULL DEFAULT now(),
"expires" timestamptz DEFAULT NULL
);The NOTIFY payload carries only { op, key, modified }. Payloads are capped at 8000 bytes and
state values routinely exceed that, so listeners re-read the row rather than reading the payload.
If the database user cannot create objects, run the DDL out of band and start with
ensureSchema: false.
Concurrency
Writes replace the whole value, so two processes writing the same key are last-writer-wins.
A state holding changes that have not been written yet is ahead of the table rather than behind it, so when a change arrives for such a key the local changes are written out first and the row is then read back. Nothing somebody is looking at and believes they saved is discarded; the two whole -value writes resolve as last-writer-wins like any other pair. States that are only ever written by one process at a time — the usual case for element states — never reach this at all.
Config variant
PostgresConfigProvider is the same thing for ConfigControllers. A ConfigController has no
mutation queue, so external changes arrive as setValue() rather than as a patch; the cache handles
both, so the provider is nothing but the choice of controller class.
Lists take search: { text, paths } (case-insensitive, at those JSON pointers) as well as prefix and paging.
Permissions
PostgresPermissionsStore keeps ConfigPermissions' owners, grants and access requests in four tables
named from tablePrefix (<prefix>_owners, _permissions, _access_requests,
_access_request_recipients). ensureSchema() creates them; PostgresPermissionsStore.schemaSQL()
returns the same statements for a migration.
Give the store to a config provider over the same database as its listScope, and its lists are narrowed
to what the caller may read in SQL, so searches and pages only ever hold what the caller can see:
const permissionsStore = new PostgresPermissionsStore({ client, tablePrefix: "workspace_config" });
const workspaces = new PostgresConfigProvider({ client, connection, table: "workspaces", listScope: permissionsStore });Testing
The tests run against an in-memory stand-in for the table, so no server is needed:
npm test