Documentation
¶
Overview ¶
Package store is the persistent state that is not the registry: users, sessions, API tokens, webhook registrations and delivery logs, the terminal audit, host variables, SSO, host settings, Loki's settings, and the custom routes (an alias name -> the deployment it points at).
── WHY SQLITE, AND WHY THE REGISTRY STAYS FILES ─────────────────────────────────────────────────
SQLite needs no new container, no credential, no migration tooling — one file under DATA_DIR, so "back up the host" remains "copy the directory". The deployment registry does NOT move here: it is a deliberate cache-of-intent (a directory of YAML an operator can read and repair over SSH), and nothing about accounts changes that. SQLite is only for the domains that are *relational and secret-bearing* — exactly what a directory of YAML is bad at.
Open takes a directory, not a file, because WAL mode creates `-wal`/`-shm` siblings — permissions have to be right on the *directory* (0700), not just the db file.
── LOCATION ─────────────────────────────────────────────────────────────────────────────────────
`<dataDir>/db/pstack.db`. NOT `<dataDir>/pstack.db`: the control container mounts only chosen subdirectories of DATA_DIR (`deployments/`, and `db/`) — a file at the top level would live in the container's own filesystem and silently vanish on every `docker compose up -d` that recreates it. `pstack init` creates the directory 0700.
── MIGRATIONS ───────────────────────────────────────────────────────────────────────────────────
`PRAGMA user_version` + an ordered list. Each entry runs once, in a transaction, and the version is bumped after it. Editing a shipped migration is forbidden (it will not re-run anywhere it already ran) — append a new one. This is deliberately the whole framework: a table of two-line DDL strings does not need a dependency.
── ONE CONNECTION (rule 16) ─────────────────────────────────────────────────────────────────────
The pool is capped at ONE connection, which is what makes the port behave like the single synchronous bun:sqlite handle the TypeScript had: statements from concurrent requests serialise instead of interleaving. The consequences are strict. Inside Tx only the *sql.Tx is used — a nested `DB.*` call waits for the one connection the transaction holds, forever. And a *sql.Rows must be read fully and closed before the next statement, for the same reason.
Index ¶
- Variables
- func AssignCustomRoute(q Querier, name, deploymentID string, force bool) (previous string, err error)
- func CreateCustomRoute(q Querier, name, deploymentID string) error
- func DeleteCustomRoute(q Querier, name string) (previous string, err error)
- func UnassignCustomRoute(q Querier, name string) (previous string, err error)
- func UnassignDeploymentRoutes(q Querier, deploymentID string) ([]string, error)
- type CustomRoute
- type ErrCustomRouteHeld
- type Querier
- type Store
Constants ¶
This section is empty.
Variables ¶
var ( ErrCustomRouteExists = errors.New("custom route exists") ErrCustomRouteNotFound = errors.New("custom route not found") )
var Migrations = []string{
`
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
-- argon2id via Bun.password; never a raw or reversible form.
password_hash TEXT NOT NULL,
-- Everyone is 'admin' until real access control lands; the column exists so adding roles is a
-- data change, not a schema change.
role TEXT NOT NULL DEFAULT 'admin',
created_at INTEGER NOT NULL
);
CREATE TABLE sessions (
-- SHA-256 of the cookie value. A database read must not be a session hijack.
id_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE tokens (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-- Label like "ci-deploy" — the only handle an operator has once the secret is gone.
name TEXT NOT NULL,
-- SHA-256 of the full token. The plaintext is shown exactly once, at creation.
token_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
last_used_at INTEGER
);
`,
`
CREATE TABLE notifiers (
id INTEGER PRIMARY KEY,
-- The COMPOSABILITY seam: 'webhook' today; 'slack', 'discord', 'email' later are new values
-- with their own config shape and their own delivery module. Adding one is a new file, not a
-- migration.
type TEXT NOT NULL,
-- Human label, the only handle in a list view.
name TEXT NOT NULL,
-- JSON, shape owned by the type: {url} for webhook, {webhookUrl,channel} for slack, …
config TEXT NOT NULL,
-- JSON array of event names, or the single entry '*' for everything including events added in
-- later versions. Validated against events.ts at write time, so an unsubscribable typo is
-- refused rather than discovered as silence months later.
events TEXT NOT NULL,
--
-- THE SIGNING SECRET IS STORED, NOT HASHED — and that is not an oversight.
--
-- A session id or an API token is verified by hashing what the caller presented and comparing;
-- the plaintext is never needed again, so one-way is strictly better. An HMAC signing secret is
-- the opposite: this process must COMPUTE HMAC(secret, body) on every delivery, so it needs the
-- secret itself. Hashing it would make signing impossible.
--
-- "Write-only" therefore means what it means for a docker registry credential: never returned by
-- any route, shown exactly once at creation. The protection is the 0700 directory, the 0600 file,
-- and the fact that no read path exists — not a one-way function.
secret TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
-- Bookkeeping for a list view: was this thing ever actually reached?
last_status TEXT,
last_at INTEGER
);
CREATE TABLE deliveries (
id INTEGER PRIMARY KEY,
notifier_id INTEGER NOT NULL REFERENCES notifiers(id) ON DELETE CASCADE,
event_id TEXT NOT NULL,
event TEXT NOT NULL,
-- 'ok' | 'failed' | 'pending'
status TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
-- HTTP status of the last attempt, or null when the request never completed.
response_code INTEGER,
-- First line of the failure, for a list view. NEVER the request body — that would put the
-- payload (and anything an emit site got wrong) into a second store.
error TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX deliveries_by_notifier ON deliveries (notifier_id, created_at DESC);
`,
`
CREATE TABLE terminal_sessions (
id INTEGER PRIMARY KEY,
-- 'root (PSTACK_TOKEN)' or a username. Denormalized on purpose: deleting the account must not
-- erase the record that it opened a shell on the host.
actor TEXT NOT NULL,
deployment TEXT NOT NULL,
container TEXT NOT NULL,
container_id TEXT NOT NULL,
shell TEXT NOT NULL,
started_at INTEGER NOT NULL,
-- Null while open, and STAYS null if pstack dies mid-session. An audit log that only records
-- tidy endings misses exactly the sessions worth auditing.
ended_at INTEGER
);
CREATE INDEX terminal_sessions_recent ON terminal_sessions (started_at DESC);
`,
`
CREATE TABLE host_vars (
name TEXT PRIMARY KEY,
-- Stored plainly for BOTH kinds. A variable is meant to be read back; a secret is the notifier
-- precedent (see the comment on notifiers.secret): this process must hand the plaintext to
-- hooks and compose, so one-way storage is impossible. "Write-only" means no API route returns
-- it — the protection is the 0700 directory, the 0600 file, and the absence of a read path.
value TEXT NOT NULL,
-- 1 = secret: value never leaves the server, and it is scrubbed from job and compose logs.
secret INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`,
`
ALTER TABLE deliveries ADD COLUMN payload TEXT;
`,
`
-- Nullable, and NULL for every account that predates SSO. That is not a gap to backfill: the
-- email-matching branch in Auth.ssoSignIn is deliberately unable to fire for those rows, so an
-- account created before this change can only ever be linked by an operator on purpose.
ALTER TABLE users ADD COLUMN email TEXT;
CREATE INDEX users_by_email ON users (email);
-- ONE provider. ` + "`" + `CHECK (id = 1)` + "`" + ` is the schema saying so: multiple simultaneous providers are
-- explicitly out of scope, and a single row means there is no "which one is active" question to
-- get wrong.
CREATE TABLE sso_config (
id INTEGER PRIMARY KEY CHECK (id = 1),
-- JSON, the SsoConfig shape in sso.ts, WITHOUT the secret.
config TEXT NOT NULL,
--
-- STORED, NOT HASHED — the notifier-secret precedent (see notifiers.secret above). The token
-- exchange must PRESENT this string to the provider, so a one-way form makes the feature
-- impossible. "Write-only" means what it means there: no route returns it, the read endpoint
-- answers with a mask, and a submit that leaves it empty keeps what is stored rather than
-- clearing it. The protection is the 0700 directory and the 0600 file.
client_secret TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
-- IDENTITY IS (provider_key, subject) AND NEVER EMAIL. People change email addresses; a provider
-- subject is stable for the life of the account, which is the entire reason this table is keyed
-- the way it is. provider_key is kept even though only one provider can be configured, so that
-- swapping providers later cannot silently re-link one org's subjects onto another's accounts.
CREATE TABLE sso_links (
provider_key TEXT NOT NULL,
subject TEXT NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
last_login_at INTEGER,
PRIMARY KEY (provider_key, subject)
);
CREATE INDEX sso_links_by_user ON sso_links (user_id);
-- The PKCE verifier, for the length of one round trip and no longer. The only table here whose
-- rows are garbage five minutes after they are written; SqliteTransientStore sweeps on write.
CREATE TABLE sso_state (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
expires_at INTEGER NOT NULL
);
`,
`
-- N simultaneous providers now. The key is an operator-chosen slug (^[a-z0-9][a-z0-9-]{0,31}$,
-- enforced by internal/auth — SQLite cannot). It names the ROW, not the identity:
-- sso_links.provider_key stays what the callback derives (the discovery ISSUER for oidc, the
-- preset key or "custom" for oauth2), so two rows on the same github preset share a link
-- namespace — the same subject from the same upstream directory is the same person.
CREATE TABLE sso_providers (
key TEXT PRIMARY KEY,
-- JSON, the same shape sso_config.config held, WITHOUT the secret.
config TEXT NOT NULL,
--
-- STORED, NOT HASHED — the notifier-secret precedent (see notifiers.secret above). The token
-- exchange must PRESENT this string to the provider, so a one-way form makes the feature
-- impossible. "Write-only" means what it means there: no route returns it, the read endpoint
-- answers with a mask, and a submit that leaves it empty keeps what is stored rather than
-- clearing it. The protection is the 0700 directory and the 0600 file.
client_secret TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
-- The stored provider moves over under a DERIVED key: the config's provider field when non-empty
-- (github/gitlab/bitbucket/custom — ParseConfig only ever set it in oauth2 mode), else 'oidc'.
-- Keep sso.Config.DerivedKey in sync with this CASE. json_extract is available because
-- modernc.org/sqlite compiles in the JSON1 functions — proven by the migration-7 test in
-- store_test.go, which runs this statement over a real v6 database.
INSERT INTO sso_providers (key, config, client_secret, updated_at)
SELECT CASE WHEN COALESCE(json_extract(config, '$.provider'), '') <> ''
THEN json_extract(config, '$.provider')
ELSE 'oidc' END,
config, client_secret, updated_at
FROM sso_config;
DROP TABLE sso_config;
`,
`
-- NOT a general dumping ground, and not a hole in invariant 10. Every row is CONFIGURATION an
-- operator chose; nothing here describes what is RUNNING — that stays in Docker and in each
-- axis's assert_gone probe. The keys are a CLOSED SET validated by internal/settings on write:
-- an unknown key is refused rather than stored. SQLite cannot express that check (a CHECK
-- constraint would have to be edited by a migration for every new key), so the table is plain and
-- the guard lives one layer up — the same division as users.role, which is TEXT with no CHECK.
--
-- PRECEDENCE IS PER KEY, and the environment is a DEFAULT rather than the authority — an operator
-- who never opens the UI keeps exactly the pre-0.33 behaviour, and one who sets a value in the UI
-- is not overridden by the container's environment on the next restart:
--
-- max_jobs integer >= 1 database > PSTACK_MAX_JOBS > jobs.DefaultMaxRunning (4)
-- default_role one of the four database > 'viewer' (there is no environment variable)
--
-- An EMPTY table therefore behaves exactly like every version before it.
CREATE TABLE settings (
key TEXT PRIMARY KEY,
-- TEXT for every key; internal/settings owns the parse and the canonical form ("008" is stored
-- as "8"). One column type means adding a key is a validator, not a migration.
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`,
`
-- 9 — Loki's settings (logging slice 2). ONE row: one Loki per host.
--
-- CONFIGURATION AN OPERATOR SAVED, not a record of what is running (invariant 10). What Loki runs
-- is control/loki/config.yaml plus its container, and every decision about Loki's schema periods
-- reads that file, never this row. An EMPTY table means slice 1's fixed config.
CREATE TABLE loki_config (
id INTEGER PRIMARY KEY CHECK (id = 1),
-- JSON, loki.Settings WITHOUT the secret.
config TEXT NOT NULL,
--
-- The S3 secret access key, '' on filesystem. STORED, NOT HASHED — the notifier-secret precedent:
-- pstack must WRITE it into the credentials file Loki reads. No route returns it; a read answers
-- secretSet. The protection is the 0700 db directory and the absence of a read path.
secret TEXT NOT NULL,
--
-- WRITE-AHEAD FOR ONE APPLY. The row as it stood before this save, stored in the same statement
-- as the save and cleared when the apply finishes or is undone. Non-NULL when a job starts means
-- an apply was cut off; the job finishes or undoes it. '' means the table was empty before.
previous_config TEXT,
previous_secret TEXT,
updated_at INTEGER NOT NULL
);
`,
`
-- CONFIGURATION AN OPERATOR CHOSE (invariant 10): which deployment a name points at, never
-- whether anything is running. Traefik reads the derived pstack-routes.yml; this table is its
-- source, and the file is re-rendered from it. An EMPTY table renders no file.
CREATE TABLE custom_routes (
-- A DNS label; internal/api validates it (SQLite cannot).
name TEXT PRIMARY KEY,
-- The registry deployment id. NULL = unassigned: the name is kept, nothing is routed.
deployment_id TEXT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`,
}
Migrations is append-only. Version N is applied when `user_version` < N; the slice index (1-based) IS the version, so ordering mistakes are structurally impossible.
Functions ¶
func AssignCustomRoute ¶ added in v0.44.0
func AssignCustomRoute(q Querier, name, deploymentID string, force bool) (previous string, err error)
AssignCustomRoute points name at deploymentID and returns the previous holder ("" if none). Already held by deploymentID is a no-op. Held by another deployment is ErrCustomRouteHeld unless force. It reads then writes, so a forced move must run inside Store.Tx to be one transaction.
func CreateCustomRoute ¶ added in v0.44.0
CreateCustomRoute adds a route, unassigned when deploymentID is "". ErrCustomRouteExists on a duplicate name.
func DeleteCustomRoute ¶ added in v0.44.0
DeleteCustomRoute removes name and returns the deployment that held it ("" if none).
func UnassignCustomRoute ¶ added in v0.44.0
UnassignCustomRoute clears name's deployment and returns the previous holder ("" if none).
Types ¶
type CustomRoute ¶ added in v0.44.0
type CustomRoute struct {
Name string
// DeploymentID is "" when the route is unassigned (NULL in the table).
DeploymentID string
CreatedAt, UpdatedAt int64
}
CustomRoute is one row of custom_routes: a stable alias name and the deployment it points at.
func GetCustomRoute ¶ added in v0.44.0
func GetCustomRoute(q Querier, name string) (CustomRoute, bool, error)
GetCustomRoute reads one route; false when no route has that name.
func ListCustomRoutes ¶ added in v0.44.0
func ListCustomRoutes(q Querier) ([]CustomRoute, error)
ListCustomRoutes returns every route, ordered by name.
type ErrCustomRouteHeld ¶ added in v0.44.0
type ErrCustomRouteHeld struct{ DeploymentID string }
ErrCustomRouteHeld refuses an unforced assign of a route another deployment holds.
func (ErrCustomRouteHeld) Error ¶ added in v0.44.0
func (e ErrCustomRouteHeld) Error() string
type Querier ¶
type Querier interface {
QueryRow(query string, args ...any) *sql.Row
Query(query string, args ...any) (*sql.Rows, error)
Exec(query string, args ...any) (sql.Result, error)
}
Querier is the statement surface both *sql.DB and *sql.Tx satisfy. Code that must run inside and outside a transaction takes one of these.
type Store ¶
Store is the open database.
func Open ¶
Open creates the directory (0700) and the database (0600), enables WAL and foreign keys, and applies every pending migration.
func (*Store) Tx ¶
Tx runs fn in a transaction (BEGIN IMMEDIATE — it is a write lock from the first statement) and commits unless fn errors or panics. fn MUST use only the Querier it is handed: with one pooled connection, a `store.DB.*` call from inside fn waits for the connection fn's own transaction holds — a permanent self-deadlock, not a slow query.