Heimdall/src/store/index.ts
Meta Vens 8541ae3f2f Startup proves the database can take Heimdall's writes
Soul pass 4, F4: the startup check passed on databases where every request
still failed: a role granted SELECT only (O2), and a table whose primary
key and key column were dropped (N), including on a start that applied the
schema, since CREATE ... IF NOT EXISTS leaves a damaged table as it is.

Every start now ends in checkSchema, after applying the schema or not. It
requires, read from the schema SQL: every relation; every column the
created tables declare, not only the added one (read from pg_attribute, so
a column the role may not see is not reported as missing); every primary
key and unique constraint as a non-partial unique index on exactly its
columns, which is what the store's ON CONFLICT clauses and the foreign
keys rely on; and SELECT, INSERT and UPDATE on every table. A missing
piece refuses with SCHEMA_MISSING, a missing privilege with
SCHEMA_PRIVILEGES, through the same fixed startup message.

A live-Postgres block drives createStore itself, skipped unless
HEIMDALL_TEST_PG_ADMIN_URL names a role that may create databases and
roles: a read-only role (and its canary password stays out of the
message), a dropped primary key with and without applying, a unique key
replaced by a partial one, and a dropped column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:15:34 +02:00

38 lines
1.6 KiB
TypeScript

import { type HeimdallConfig } from "../config.js";
import { InMemoryStore } from "./in-memory.js";
import { createPostgresStore } from "./postgres.js";
import { type HeimdallStore } from "./types.js";
export * from "./types.js";
export { InMemoryStore } from "./in-memory.js";
export { PostgresStore, createPostgresStore } from "./postgres.js";
export async function createStore(config: HeimdallConfig): Promise<HeimdallStore> {
if (config.storage.backend !== "postgres") {
return new InMemoryStore();
}
const store = createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall");
try {
// Every start connects and proves the database can take its requests,
// whether or not it applied the schema first (CREATE ... IF NOT EXISTS
// leaves a damaged table as it is), so a misbound URL, an empty or
// damaged database, or a role that may not write fails here rather than
// in the first request.
if (config.storage.applySchemaOnStartup) {
await store.ensureSchema();
}
await store.checkSchema();
} catch (error) {
// pg's and Node's errors name the host, the database or the URL itself,
// and any of those can hold part of a secret that was bound or escaped
// wrongly. Startup prints this error, so it names only the input and a
// code, and carries no cause.
const code = (error as { code?: unknown }).code;
throw new Error(
`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); check GC_ACCESS_DATABASE_URL_FILE.`
);
}
return store;
}