From 776d59c758a4806dbc4643bebaa5e850bc8f4a0a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:08:33 +0000 Subject: [PATCH] Run every process on AUTOCRAFT_DB_URL: the dashboard, runner, worker threads and job processes open dbTarget() (job processes get dbEnv(), only the variable that names the database); the GitHub identity read uses the process handle in read transactions on Postgres; AUTOCRAFT_DATA_DIR (default: the SQLite file's directory; the image sets /data) holds reference documents, artifacts and the item snapshot; lock files are named by dbLockName(); the item snapshot, backup.sh, the predeploy snapshot and the periodic loops say that Postgres has no SQLite snapshot instead of succeeding; db.attempt(fn) runs fn under a savepoint on Postgres so a caught statement error leaves the write usable --- README.md | 1 + deploy/backup.sh | 9 ++++++++- deploy/compose/compose.yaml | 5 ++++- deploy/container/Dockerfile | 2 +- deploy/hook.sh | 5 ++++- deploy/k8s/autocraft.yaml | 5 ++++- docs/operations.md | 10 ++++++---- src/build/artifacts.ts | 6 +++--- src/dash/index.ts | 4 ++-- src/dash/server/config.ts | 14 +++++++++++--- src/db.ts | 14 ++++++++++++-- src/db/handle.ts | 19 +++++++++++++++++++ src/db/index.ts | 7 +++++++ src/db/open.ts | 24 ++++++++++++++++++++++- src/github/read.ts | 23 +++++++++++++--------- src/itemtools/snapshot.ts | 14 +++++++++++--- src/mirror.ts | 9 ++++----- src/reference-search.ts | 3 +-- src/reference.ts | 8 ++++---- src/runner/cli-job.ts | 4 ++-- src/runner/offthread.ts | 8 ++++---- src/runner/runner.ts | 20 +++++++++---------- src/runner/worker.ts | 2 +- test/pg-db.test.ts | 21 ++++++++++++++++++++ test/runner.test.ts | 38 +++++++++++++++++++++++++++++++------ test/step-repo.test.ts | 2 +- test/stuck-jobs.test.ts | 2 +- 27 files changed, 211 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index bdf9dedf8..b6c390e02 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ To sign in through a GitHub App instead, register it from the dashboard's GitHub | `AUTOCRAFT_BASE_URL` | Public origin of the dashboard, no path | | `AUTOCRAFT_LISTEN` | `host:port`, default `127.0.0.1:8993` | | `AUTOCRAFT_DB` | Database path | +| `AUTOCRAFT_DB_URL` | A `postgres://` URL, to use Postgres instead of the SQLite file | | `AUTOCRAFT_SECRETS_FILE` | The secrets file above | | `AUTOCRAFT_GITHUB_APP_NAME` | App name suggested on the registration form, default `AutoCraft` | | `AUTOCRAFT_WEB_DIST` | Built frontend, default `web/dist` | diff --git a/deploy/backup.sh b/deploy/backup.sh index 42c24b969..49787485e 100755 --- a/deploy/backup.sh +++ b/deploy/backup.sh @@ -3,11 +3,18 @@ # deploy/backup.sh [PREFIX [KEEP]] defaults: daily 7 # Writes $AUTOCRAFT_BACKUP_DIR/PREFIX-.db.zst (gzip without zstd), # then deletes all but the newest KEEP files of that prefix. The database is -# $AUTOCRAFT_DB; backups default to /backups. +# $AUTOCRAFT_DB, else mirror.db in $AUTOCRAFT_DATA_DIR; backups default to /backups. +# SQLite only: with AUTOCRAFT_DB_URL (Postgres) the database provider keeps the backups, and this exits 3 without one. set -euo pipefail prefix="${1:-daily}" keep="${2:-7}" +if [ -n "${AUTOCRAFT_DB_URL:-${CRAFT_AUTO_DB_URL:-}}" ]; then + echo "backup skipped: AUTOCRAFT_DB_URL names a Postgres database, whose backups are the database provider's; this script snapshots SQLite only" >&2 + exit 3 +fi db="${AUTOCRAFT_DB:-${CRAFT_AUTO_DB:-}}" +data_dir="${AUTOCRAFT_DATA_DIR:-${CRAFT_AUTO_DATA_DIR:-}}" +[ -n "$db" ] || [ -z "$data_dir" ] || db="$data_dir/mirror.db" [ -n "$db" ] || { echo "AUTOCRAFT_DB is not set" >&2; exit 1; } dir="${AUTOCRAFT_BACKUP_DIR:-$(dirname "$db")/backups}" umask 077 diff --git a/deploy/compose/compose.yaml b/deploy/compose/compose.yaml index 3816b7a81..d66974f85 100644 --- a/deploy/compose/compose.yaml +++ b/deploy/compose/compose.yaml @@ -77,9 +77,12 @@ services: f=$$(ls -1t /data/backups/daily-*.db.* 2>/dev/null | head -n 1) if [ -n "$$f" ]; then stat -c %Y "$$f"; else echo 0; fi } + # A Postgres database (AUTOCRAFT_DB_URL) is backed up by its provider; the snapshot covers SQLite only. + snapshots=1 + if [ -n "$${AUTOCRAFT_DB_URL:-}" ]; then snapshots=0; echo "backup: AUTOCRAFT_DB_URL is set; no snapshots here, the database provider keeps the backups" >&2; fi while true; do /app/deploy/entrypoint.sh sync || echo "sync exited $$?" >&2 - if [ $$(( $$(date +%s) - $$(last_backup) )) -ge 86400 ]; then + if [ "$$snapshots" = 1 ] && [ $$(( $$(date +%s) - $$(last_backup) )) -ge 86400 ]; then /app/deploy/entrypoint.sh backup daily 7 || echo "backup exited $$?" >&2 fi sleep 60 & wait $$! diff --git a/deploy/container/Dockerfile b/deploy/container/Dockerfile index fbaa96234..d6acce537 100644 --- a/deploy/container/Dockerfile +++ b/deploy/container/Dockerfile @@ -144,7 +144,7 @@ ENV HOME=/data/home \ XDG_CACHE_HOME=/data/cache \ DISABLE_AUTOUPDATER=1 \ AUTOCRAFT_CLAUDE_BIN=/usr/local/bin/claude \ - AUTOCRAFT_DB=/data/mirror.db \ + AUTOCRAFT_DATA_DIR=/data \ AUTOCRAFT_LISTEN=0.0.0.0:3005 \ AUTOCRAFT_WORKER_LISTEN=0.0.0.0:8981 \ AUTOCRAFT_SECRETS_FILE=/config/secrets.json \ diff --git a/deploy/hook.sh b/deploy/hook.sh index ed0ef7177..48f67463c 100755 --- a/deploy/hook.sh +++ b/deploy/hook.sh @@ -54,6 +54,7 @@ if [ -r "$ENV_FILE" ]; then . "$ENV_FILE" set +a AUTOCRAFT_DB="${AUTOCRAFT_DB:-${CRAFT_AUTO_DB:-}}" + AUTOCRAFT_DB_URL="${AUTOCRAFT_DB_URL:-${CRAFT_AUTO_DB_URL:-}}" AUTOCRAFT_LISTEN="${AUTOCRAFT_LISTEN:-${CRAFT_AUTO_LISTEN:-}}" else echo "!! $ENV_FILE is missing; create it first (README, Production install)" >&2 @@ -83,7 +84,9 @@ REL="$ROOT/releases/$sha" echo "-- Deploying ${sha:0:12} to $REL --" # Snapshot first: nothing of the new code has touched the database yet. -if [ -n "${AUTOCRAFT_DB:-}" ] && [ -f "$AUTOCRAFT_DB" ]; then +if [ -n "${AUTOCRAFT_DB_URL:-}" ]; then + echo "-> No snapshot: AUTOCRAFT_DB_URL names a Postgres database, whose backups are the database provider's." +elif [ -n "${AUTOCRAFT_DB:-}" ] && [ -f "$AUTOCRAFT_DB" ]; then echo "-> Snapshotting the database..." bash "$ROOT/app/deploy/backup.sh" predeploy 3 2>/dev/null || { # First deploy of this layout has no app/ yet: use the checkout about to be built. diff --git a/deploy/k8s/autocraft.yaml b/deploy/k8s/autocraft.yaml index 375477de4..c438df1e8 100644 --- a/deploy/k8s/autocraft.yaml +++ b/deploy/k8s/autocraft.yaml @@ -117,9 +117,12 @@ spec: f=$(ls -1t /data/backups/daily-*.db.* 2>/dev/null | head -n 1) if [ -n "$f" ]; then stat -c %Y "$f"; else echo 0; fi } + # A Postgres database (AUTOCRAFT_DB_URL) is backed up by its provider; the snapshot covers SQLite only. + snapshots=1 + if [ -n "${AUTOCRAFT_DB_URL:-}" ]; then snapshots=0; echo "backup: AUTOCRAFT_DB_URL is set; no snapshots here, the database provider keeps the backups" >&2; fi while true; do /app/deploy/entrypoint.sh sync || echo "sync exited $?" >&2 - if [ $(( $(date +%s) - $(last_backup) )) -ge 86400 ]; then + if [ "$snapshots" = 1 ] && [ $(( $(date +%s) - $(last_backup) )) -ge 86400 ]; then /app/deploy/entrypoint.sh backup daily 7 || echo "backup exited $?" >&2 fi sleep 60 & wait $! diff --git a/docs/operations.md b/docs/operations.md index e0ccb7360..54e051a2d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -84,6 +84,7 @@ The frontend is the React app in `web/`. Build it before serving: `pnpm -C web i | `AUTOCRAFT_BASE_URL` | Public origin of the dashboard, such as `https://dashboard.example.org` (no path). The OAuth App's callback URL must be exactly `/auth/callback`. Required unless dev auth is on. | | `AUTOCRAFT_LISTEN` | `host:port` to listen on. Default `127.0.0.1:8993`; with dev auth, `127.0.0.1:8994`. | | `AUTOCRAFT_DB` | SQLite database path (the mirror database). | +| `AUTOCRAFT_DB_URL` | A `postgres://` URL: the database is Postgres instead of SQLite. Set it or `AUTOCRAFT_DB`, not both. The runner hands it to its worker threads and job processes. | | `AUTOCRAFT_REVIEW_BOTS` | Comma-separated logins of review bots whose comments never make a review stale, besides accounts of type Bot or ending in `[bot]`. Default `coderabbitai,dependabot,renovate`. Read by `sync` (when it stores a comment), the database backfill and the runner, so set it for all three alike. | | `AUTOCRAFT_WEB_DIST` | Directory of the built frontend. Default `web/dist` in the repo. | | `AUTOCRAFT_SECRETS_FILE` | JSON file with `github_client_id`, `github_client_secret` and `session_key` (at least 32 characters, random). Must be mode 0600; the server refuses to start if it is missing, incomplete, or readable by group or others. Registering the GitHub App from the dashboard (GitHub App page, operators only) adds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner` (`{"login", "type"}`, the user or organization that owns the app). The GitHub App page's Remove button deletes every `github_app_*` key through the same atomic write (refused while the GitHub identity is the GitHub App) and links to the app's GitHub settings page, where the operator deletes the app. The dashboard rewrites this file itself for that: it writes a temporary file beside it and renames it over the file (a symlink stays a symlink), so the directory must be writable by the server user. Registration checks this first and refuses to start when it cannot write. The server reads the app's keys again whenever the file changes, so registering or removing the app needs no restart. Whether GitHub reads, writes and dashboard sign-in use the box account or the GitHub App is one instance-wide setting (GitHub App page, or `autocraft-server identity [box|app]`); switching ends every dashboard session and takes effect in the runner and the dashboard at their next GitHub call, without a restart. Under `box`, every `gh` and `git` call uses the server user's own `gh` login. Under `app`, every read (GraphQL, REST, git fetch over HTTPS, the image proxy, repository checks when tracking) runs with an installation token of the owner it concerns (the first tracked repo's owner when a read names none) and never sees the box account's credentials; the `gh` login of the server user is not needed. A read for which no installation token can be minted fails with an error naming the owner. The GitHub rate figures shown on the Pipeline page and used by the sync's reserve are those of the token in use. Permission checks of a signed-in person use that person's own token in both modes. | @@ -762,7 +763,7 @@ A production install runs the dashboard, the runner, the sync timer and a daily | `post-receive` | Bootstrap hook for `/repo.git` (a bare repo). Install it once; each deploy replaces it with the copy in the deployed commit. It runs `deploy/hook.sh` from the pushed commit and passes that commit (`AUTOCRAFT_DEPLOY_SHA`), so the release is the commit that was pushed even if the branch moves during the deploy. | | `hook.sh` | Snapshots the database, pauses the sync timer, builds `/releases/` (dependencies, `web/dist`), updates the sandbox worker code (when `AUTOCRAFT_WORKER_SSH` is set; SSH accepts only a known host key, from `.known_hosts` when it exists, else the user's `known_hosts`) switches the `/app` symlink and restarts the units named by `AUTOCRAFT_UNITS`. A failed deploy prints the command that redeploys the same commit. | | `push.sh` | `deploy/push.sh REMOTE [REF]`: pushes a branch to the bare repo. | -| `backup.sh` | `backup.sh [PREFIX [KEEP]]`: consistent snapshot with `sqlite3 .backup`, compressed, newest KEEP kept. | +| `backup.sh` | `backup.sh [PREFIX [KEEP]]`: consistent SQLite snapshot (`VACUUM INTO`), compressed, newest KEEP kept. With `AUTOCRAFT_DB_URL` it makes no backup and exits 3: the Postgres provider keeps the backups. | Layout: `/{repo.git,releases,app,data,cache,config}` (`app` is a symlink to the current release). `/config` holds the settings file, `secrets.json` (mode 0600), `accounts.json` and the per-account Claude config directories. The user needs `node` 24, `git`, `pnpm`, `sqlite3`, `curl`, `bwrap`, `gh` (logged in, with its git credential helper), `claude` (logged in per account) and `jev` on its PATH (`/.local/bin` comes first). The restart needs a sudoers entry allowing the user `systemctl restart` of its own units, and `start`/`stop` of the sync timer, without a password. The units load `autocraft.env` themselves as the app user. The dashboard unit sees that file, `releases/`, `repo.git` and `.local` read-only (`ReadOnlyPaths=`): the process that faces the network cannot change what the other units source or run. The worker runs as a separate user (see Running a worker); `AUTOCRAFT_WORKER_SSH` and an SSH key at `/.ssh/id_craftsandbox` let the hook install its code through the worker's forced-command key. @@ -812,7 +813,8 @@ Every path is set by an environment variable. When a variable is unset, the code | Variable | Code default | Image | Systemd example | |---|---|---|---| -| `AUTOCRAFT_DB` | `~/.local/share/autocraft/mirror.db` | `/data/mirror.db` | `/data/mirror.db` | +| `AUTOCRAFT_DATA_DIR` (reference documents, artifacts, item snapshot) | the SQLite file's directory | `/data` | unset | +| `AUTOCRAFT_DB` | `mirror.db` in `AUTOCRAFT_DATA_DIR` when that is set, else `~/.local/share/autocraft/mirror.db` | unset (`/data/mirror.db`) | `/data/mirror.db` | | `AUTOCRAFT_SECRETS_FILE` | none (required) | `/config/secrets.json` | `/config/secrets.json` | | `AUTOCRAFT_ACCOUNTS` | none | `/config/accounts.json` | `/config/accounts.json` | | `AUTOCRAFT_ACCOUNTS_ROOT` (Claude config directories) | none | `/config/claude` | `/config/claude` | @@ -824,8 +826,8 @@ Every path is set by an environment variable. When a variable is unset, the code | `AUTOCRAFT_CHECKOUT_DIR` | `~/.cache/autocraft/checkouts-v2` | `/data/cache/autocraft/checkouts` | `/cache/autocraft/checkouts` | | `AUTOCRAFT_FIXUP_DIR` (bare git cache) | `~/.cache/autocraft/fixups` | `/data/cache/autocraft/fixups` | `/cache/autocraft/fixups` | | `AUTOCRAFT_BACKUP_DIR` | `/backups` | `/data/backups` | `/backups` | -| `AUTOCRAFT_ARTIFACT_DIR` | `/artifacts` | unset | unset | -| `AUTOCRAFT_SNAPSHOT_DIR` | `/item-snapshot` | unset | unset | +| `AUTOCRAFT_ARTIFACT_DIR` | `/artifacts` | unset | unset | +| `AUTOCRAFT_SNAPSHOT_DIR` | `/item-snapshot` | unset | unset | | `AUTOCRAFT_CLAUDE_CWD` | `~/.cache/autocraft/claude-cwd` | unset | unset | | `AUTOCRAFT_MODEL_CACHE` | `$XDG_CACHE_HOME/autocraft/models` | unset | unset | | `AUTOCRAFT_WEB_DIST` | `web/dist` of the code | unset | unset | diff --git a/src/build/artifacts.ts b/src/build/artifacts.ts index c5cdd4426..9d080bc94 100644 --- a/src/build/artifacts.ts +++ b/src/build/artifacts.ts @@ -3,9 +3,9 @@ // them, only a few kinds are accepted, and nothing here ever executes or // renders them. import { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, rmSync } from "node:fs"; -import { dirname, join, resolve, sep } from "node:path"; +import { join, resolve, sep } from "node:path"; import { createHash } from "node:crypto"; -import { dbPath } from "../db.ts"; +import { dataDir } from "../db.ts"; import { envVar } from "../env.ts"; import type { Db } from "../db/index.ts"; @@ -16,7 +16,7 @@ export const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; /** AUTOCRAFT_ARTIFACT_DIR, else `artifacts` beside the database. */ export function artifactDir(): string { - return resolve(envVar("ARTIFACT_DIR") ?? join(dirname(dbPath()), "artifacts")); + return resolve(envVar("ARTIFACT_DIR") ?? join(dataDir(), "artifacts")); } const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); diff --git a/src/dash/index.ts b/src/dash/index.ts index 43b1fb89a..25356bdf3 100644 --- a/src/dash/index.ts +++ b/src/dash/index.ts @@ -16,11 +16,11 @@ async function serve(): Promise { console.error(`dash serve: ${e.message}`); process.exit(2); } - const db = await connectDb(config.dbPath, { role: "dashboard" }); + const db = await connectDb(config.dbTarget, { role: "dashboard" }); await scopeToTracked(db); await sweepRunningCards(db); // The helper routes' own connection: they wait at most REMOTE_BUSY_MS for a write lock and then answer 503. - const remoteDb = await connectDb(config.dbPath, { busyTimeoutMs: REMOTE_BUSY_MS, role: "dashboard-remote" }); + const remoteDb = await connectDb(config.dbTarget, { busyTimeoutMs: REMOTE_BUSY_MS, role: "dashboard-remote" }); const { url, close } = await startServer({ config, db, remoteDb }); console.log(`dashboard listening on ${url}${config.devAuth ? " (development sign-in)" : ""}`); const stop = () => void close().then(async () => { diff --git a/src/dash/server/config.ts b/src/dash/server/config.ts index 6d6af1096..fc096502e 100644 --- a/src/dash/server/config.ts +++ b/src/dash/server/config.ts @@ -3,7 +3,7 @@ import { isIP } from "node:net"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { randomToken } from "./crypto.ts"; -import { dbPath } from "../../db.ts"; +import { dbTarget } from "../../db/open.ts"; import { defaultImageCacheDir } from "./images.ts"; import { envVar } from "../../env.ts"; @@ -43,11 +43,19 @@ export function followAppSecrets(secrets: Secrets, file: string): void { }); } +function configuredDb(env: NodeJS.ProcessEnv): string { + try { + return dbTarget(env); + } catch (e) { + throw new ConfigError((e as Error).message); + } +} + export type Config = { host: string; port: number; baseUrl: string | null; // null only with dev auth, where every URL the server builds is relative - dbPath: string; + dbTarget: string; // a SQLite path or a postgres:// URL (dbTarget()) webDist: string; // the frontend's build output (web/dist) devAuth: boolean; devPermsFile: string | null; @@ -252,7 +260,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { if (!/^[0-9]$/.test(trustRaw)) throw new ConfigError("AUTOCRAFT_TRUST_PROXY must be the number of trusted proxies in front of the server, 0 to 9"); return { host, port, baseUrl, devAuth, secrets, secretsFile, - dbPath: envVar("DB", env) ?? dbPath(), + dbTarget: configuredDb(env), webDist: webDistEnv ? resolve(webDistEnv) : DEFAULT_WEB_DIST, devPermsFile: devAuth ? (envVar("DEV_PERMS", env) ?? null) : null, devTokenTtlMs: devAuth && envVar("DEV_TOKEN_TTL", env) ? Number(envVar("DEV_TOKEN_TTL", env)) * 1000 || null : null, diff --git a/src/db.ts b/src/db.ts index d45966401..63c80884f 100644 --- a/src/db.ts +++ b/src/db.ts @@ -20,8 +20,18 @@ import { SIM_THRESHOLD } from "./dupes/scan.ts"; export const DEFAULT_DB = join(homedir(), ".local/share/autocraft/mirror.db"); -export function dbPath(): string { - return envVar("DB") ?? DEFAULT_DB; +/** The SQLite file: `AUTOCRAFT_DB`, else mirror.db in `AUTOCRAFT_DATA_DIR`, else the default under the home. */ +export function dbPath(env: NodeJS.ProcessEnv = process.env): string { + const dir = envVar("DATA_DIR", env); + return envVar("DB", env) ?? (dir ? join(dir, "mirror.db") : DEFAULT_DB); +} + +/** + * The instance's data directory (reference documents, artifacts, the item snapshot): `AUTOCRAFT_DATA_DIR`, else the + * SQLite file's directory. A Postgres instance keeps its files here too. + */ +export function dataDir(env: NodeJS.ProcessEnv = process.env): string { + return envVar("DATA_DIR", env) || dirname(dbPath(env)); } // Columns added to existing tables after their first release. CREATE TABLE IF diff --git a/src/db/handle.ts b/src/db/handle.ts index 9fe1f20c1..c8dfee422 100644 --- a/src/db/handle.ts +++ b/src/db/handle.ts @@ -16,6 +16,8 @@ export interface Tx { /** The connection the transaction runs on, recorded by the engine's driver at BEGIN. */ conn?: DatabaseConnection; trx?: Transaction; + /** Savepoints taken by `attempt`, for unique names. */ + savepoints?: number; } /** What a handle gives its engine. */ @@ -143,6 +145,23 @@ export class Handle implements Db { } as Statement; } + async attempt(fn: () => Promise): Promise { + const tx = this.#current(); + if (this.dialect !== "postgres" || !tx) return await fn(); + tx.savepoints = (tx.savepoints ?? 0) + 1; + const name = `attempt_${tx.savepoints}`; + await this.#engine.script(`SAVEPOINT ${name}`, tx); + let r: T; + try { + r = await fn(); + } catch (e) { + await this.#engine.script(`ROLLBACK TO SAVEPOINT ${name}; RELEASE SAVEPOINT ${name}`, tx); + throw e; + } + await this.#engine.script(`RELEASE SAVEPOINT ${name}`, tx); + return r; + } + inTransaction(): boolean { return this.#current() !== undefined; } diff --git a/src/db/index.ts b/src/db/index.ts index b7beb411a..006d8e68e 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -97,6 +97,13 @@ export interface Db { * inside a read snapshot it throws. Never retries itself. */ write(fn: () => Promise, opts?: WriteOptions): Promise; + /** + * Runs `fn` so that a statement error inside it leaves the open transaction usable: on Postgres, where a failed + * statement aborts the whole transaction, `fn` runs under a savepoint that is rolled back when it throws; on SQLite, and + * outside a transaction, it is a plain call. The error still reaches the caller, which catches it and carries on. + * Attempts in one transaction run one at a time, like its statements. + */ + attempt(fn: () => Promise): Promise; /** Whether a transaction is open in the current async context. */ inTransaction(): boolean; /** Runs several statements with no parameters (schema scripts, PRAGMAs). */ diff --git a/src/db/open.ts b/src/db/open.ts index 944ef885e..322d48cfa 100644 --- a/src/db/open.ts +++ b/src/db/open.ts @@ -1,5 +1,7 @@ // Opens database handles. The only module that loads the kysely and pg packages, with dynamic imports: the build worker // runs src/ without node_modules and never opens the app database (test/no-package-imports.test.ts). +import { createHash } from "node:crypto"; +import { basename } from "node:path"; import type { DatabaseSync } from "node:sqlite"; import { connect, dbPath } from "../db.ts"; import { envVar } from "../env.ts"; @@ -43,7 +45,27 @@ export function dbTarget(env: NodeJS.ProcessEnv = process.env): string { const path = envVar("DB", env); if (url !== undefined && path !== undefined && url !== path) throw new Error("AUTOCRAFT_DB_URL and AUTOCRAFT_DB are both set and differ: set only one"); if (url !== undefined && !isPgUrl(url)) throw new Error("AUTOCRAFT_DB_URL must be a postgres:// or postgresql:// URL"); - return url ?? dbPath(); + return url ?? dbPath(env); +} + +const DB_VARS = ["AUTOCRAFT_DB", "CRAFT_AUTO_DB", "AUTOCRAFT_DB_URL", "CRAFT_AUTO_DB_URL"]; + +/** `env` for a child process that opens `target`: the one variable that names it, and no other database variable. */ +export function dbEnv(target: string, env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { + const out = { ...env }; + for (const k of DB_VARS) delete out[k]; + out[isPgUrl(target) ? "AUTOCRAFT_DB_URL" : "AUTOCRAFT_DB"] = target; + return out; +} + +/** + * A file-name-safe name for `target`, for lock files that exclude a second run on the same database: a SQLite file's + * base name, or for Postgres a hash of the host, port and database name (no credentials). + */ +export function dbLockName(target: string = dbTarget()): string { + if (!isPgUrl(target)) return basename(target); + const u = new URL(target); + return `pg-${createHash("sha256").update(`${u.hostname}:${u.port || "5432"}${u.pathname}`).digest("hex").slice(0, 12)}`; } let role: DbRole = "cli"; diff --git a/src/github/read.ts b/src/github/read.ts index b023140b9..09348bb86 100644 --- a/src/github/read.ts +++ b/src/github/read.ts @@ -7,11 +7,10 @@ // once, on first use. import { existsSync } from "node:fs"; import { DatabaseSync } from "node:sqlite"; -import { dbPath } from "../db.ts"; import { DEFAULT_OWNER, OWNER } from "../owners.ts"; import { AppNotInstalledError, TOKEN_ENV, appChildEnv, installationToken } from "./install-token.ts"; import type { Db } from "../db/index.ts"; -import { dbFor } from "../db/open.ts"; +import { dbFor, dbTarget, isPgUrl, openDb } from "../db/open.ts"; export type ReadEnv = Record; export type ReadDeps = { db?: Db; mint?: (owner: string) => Promise; defaultOwner?: () => Promise }; @@ -19,11 +18,14 @@ export type ReadDeps = { db?: Db; mint?: (owner: string) => Promise; def // The promise is kept, so two first calls at once share one open. let shared: { path: string; db: Promise } | null = null; /** - * A read-only handle on the instance database, opened on first use. Null only when there is no database file (nothing - * configured the identity); a file that cannot be opened is an error, never a silent read as the box account. + * A handle on the instance database for reads, opened on first use; callers read through it inside `db.read`. On + * SQLite a read-only connection of its own; on Postgres the process's handle. Null only when there is no SQLite file + * (nothing configured the identity); a database that cannot be opened is an error, never a silent read as the box + * account. */ async function sharedDb(): Promise { - const path = dbPath(); + const path = dbTarget(); + if (isPgUrl(path)) return await openDb(); if (shared?.path === path) return await shared.db; if (!existsSync(path)) return null; const mine = { path, db: openShared(path) }; @@ -48,11 +50,13 @@ async function openShared(path: string): Promise { throw new Error(`cannot read the GitHub identity setting: ${String((last as Error)?.message ?? last).slice(0, 120)}`); } -async function settingOf(db: Db): Promise { +/** The identity setting. `snapshot`: each attempt in a read transaction of its own (the shared handle is read-only). */ +async function settingOf(db: Db, snapshot = false): Promise { + const read = async () => (await db.prepare("SELECT value FROM main.settings WHERE key = 'github_identity'").get() as { value: string } | undefined)?.value; let last: unknown; for (let i = 0; i < 3; i++) { try { - return (await db.prepare("SELECT value FROM main.settings WHERE key = 'github_identity'").get() as { value: string } | undefined)?.value; + return snapshot ? await db.read(read) : await read(); } catch (e) { last = e; } } throw new Error(`cannot read the GitHub identity setting: ${String((last as Error)?.message ?? last).slice(0, 120)}`); @@ -90,7 +94,7 @@ export async function readsUseApp(db?: Db): Promise { if (held) return held.app; firstRead ??= (async () => { const d = await sharedDb(); - return d !== null && await settingOf(d) === "app"; + return d !== null && await settingOf(d, true) === "app"; })().catch((e: unknown) => { firstRead = null; throw e; }); const app = await firstRead; held ??= { app, seq: null }; @@ -101,7 +105,8 @@ export async function readsUseApp(db?: Db): Promise { export async function trackedOwner(db?: Db): Promise { const d = db ?? await sharedDb(); try { - const rows = await d?.prepare("SELECT r.owner FROM main.tracked_repos t JOIN main.repos r ON r.name = t.name WHERE r.owner IS NOT NULL ORDER BY t.added_at").all() as { owner: string }[] | undefined; + const q = async () => await d?.prepare("SELECT r.owner FROM main.tracked_repos t JOIN main.repos r ON r.name = t.name WHERE r.owner IS NOT NULL ORDER BY t.added_at").all() as { owner: string }[] | undefined; + const rows = db || !d ? await q() : await d.read(q); const owners = (rows ?? []).map((r) => r.owner).filter((o) => OWNER.test(o)); if (owners.some((o) => o.toLowerCase() === DEFAULT_OWNER)) return DEFAULT_OWNER; if (owners[0]) return owners[0]; diff --git a/src/itemtools/snapshot.ts b/src/itemtools/snapshot.ts index 3d17c7161..071aa1f82 100644 --- a/src/itemtools/snapshot.ts +++ b/src/itemtools/snapshot.ts @@ -7,14 +7,22 @@ import { existsSync, mkdirSync, renameSync, rmSync, statSync, unlinkSync } from "node:fs"; import { dirname, join } from "node:path"; import { DatabaseSync } from "node:sqlite"; -import { dbPath } from "../db.ts"; +import { dataDir } from "../db.ts"; +import { dbTarget, isPgUrl } from "../db/open.ts"; import { envVar } from "../env.ts"; export function snapshotDir(): string { - return envVar("SNAPSHOT_DIR") ?? join(dirname(dbPath()), "item-snapshot"); + return envVar("SNAPSHOT_DIR") ?? join(dataDir(), "item-snapshot"); } export const snapshotFile = (): string => join(snapshotDir(), "items.db"); +/** The SQLite database the snapshot is copied from: the configured one. */ +function snapshotSource(): string { + const target = dbTarget(); + if (isPgUrl(target)) throw new Error("the item snapshot is copied from a SQLite database; building it from Postgres (AUTOCRAFT_DB_URL) is not implemented"); + return target; +} + const ITEM_COLUMNS = ["repo", "number", "kind", "state", "title", "body", "url", "author", "author_association", "created_at", "updated_at", "closed_at", "merged_at", "state_reason", "is_draft", "labels", "comments_count", "additions", "deletions", "changed_files", "head_ref", "head_oid", "head_repo", "base_ref", "review_decision", "mergeable", "ci_state"]; @@ -91,7 +99,7 @@ const differs = (a: string, b: string, names: string[]) => names.filter((c) => c * missing or has another schema version. Only repositories with visibility * `public` are copied. The source is only read. */ -export function writeSnapshot(src: string = dbPath(), dest: string = snapshotFile()): SnapshotStats { +export function writeSnapshot(src: string = snapshotSource(), dest: string = snapshotFile()): SnapshotStats { mkdirSync(dirname(dest), { recursive: true }); recoverJournal(dest); let rebuilt = false; diff --git a/src/mirror.ts b/src/mirror.ts index 8a0cada66..cdbd5318f 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -6,8 +6,7 @@ import { setTimeout as sleep } from "node:timers/promises"; import type { SQLInputValue } from "node:sqlite"; import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs"; import { homedir } from "node:os"; -import { basename, dirname, join } from "node:path"; -import { dbPath } from "./db.ts"; +import { dirname, join } from "node:path"; import { trackedNames } from "./repos.ts"; import { audit } from "./dash/audit.ts"; import { hashColumns } from "./itemhash.ts"; @@ -21,7 +20,7 @@ import { DEFAULT_OWNER, reloadOwners, ownerOf, slugOf } from "./owners.ts"; import { classifyFailure, clearRepoFailure, recordRepoFailure } from "./sync-errors.ts"; import { filterSeq } from "./async-seq.ts"; import type { Db } from "./db/index.ts"; -import { openDb, setDbRole } from "./db/open.ts"; +import { dbLockName, openDb, setDbRole } from "./db/open.ts"; const OVERLAP_MS = 10 * 60 * 1000; const FULL_PAGE = 30; @@ -675,12 +674,12 @@ function lockDir(): string { // The incremental sync's lock. export function lockPath(): string { - return join(lockDir(), `sync-${basename(dbPath())}.lock`); + return join(lockDir(), `sync-${dbLockName()}.lock`); } // A full re-sync has its own lock, so it never blocks the incremental sync. export function fullLockPath(): string { - return join(lockDir(), `sync-full-${basename(dbPath())}.lock`); + return join(lockDir(), `sync-full-${dbLockName()}.lock`); } // Wraps a client for a full re-sync, which runs beside the incremental sync and gives way to it: diff --git a/src/reference-search.ts b/src/reference-search.ts index 5c5e45007..999d134fe 100644 --- a/src/reference-search.ts +++ b/src/reference-search.ts @@ -6,7 +6,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } fr import { DatabaseSync } from "node:sqlite"; import { dirname, join } from "node:path"; import { Worker } from "node:worker_threads"; -import { dbPath } from "./db.ts"; +import { dataDir } from "./db.ts"; import { DEFAULT_MODEL, localEmbedder, type Embedder } from "./embed/model.ts"; import { toBlob } from "./embed/store.ts"; import type { ScoreReply, ScoreRequest } from "./reference-score-worker.ts"; @@ -23,7 +23,6 @@ const REPO = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/; const TEXT = /\.(txt|md)$/; const SCHEMA_VERSION = "1"; -const dataDir = (): string => dirname(dbPath()); const referenceFolder = (repo: string): string => join(dataDir(), "reference", repo); export const indexPath = (repo: string): string => join(dataDir(), "reference-index", `${repo}.db`); diff --git a/src/reference.ts b/src/reference.ts index 13e043df8..be707a3db 100644 --- a/src/reference.ts +++ b/src/reference.ts @@ -5,9 +5,9 @@ import { execFileSync } from "node:child_process"; import { chmodSync, createWriteStream, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"; import { Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import { audit } from "./dash/audit.ts"; -import { dbPath } from "./db.ts"; +import { dataDir } from "./db.ts"; import { isTracked } from "./repos.ts"; import { buildReferenceIndex, referenceSearch } from "./reference-search.ts"; import { isInstructionPath } from "./sandbox/instruction-paths.ts"; @@ -22,7 +22,7 @@ const REPO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; const SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/; const EXTENSION = /\.(txt|md|pdf|png|jpe?g|gif|webp|svg)$/; -export const referenceRoot = (): string => join(dirname(dbPath()), "reference"); +export const referenceRoot = (): string => join(dataDir(), "reference"); /** The host folder to mount for a repo, or undefined when none was imported. */ export function referenceDir(repo: string): string | undefined { @@ -157,7 +157,7 @@ export const commands = { await buildReferenceIndex(rest[0]!, {}, "stat"); for (const p of await referenceSearch(rest[0]!, rest.slice(1).join(" "), 5)) console.log(`#${p.id} ${p.title} (${p.page})\n${p.text}\n`); } else if (sub === "import" && rest[0] && rest.every((a, i) => i === 0 || a === "--replace")) { - const tmp = mkdtempSync(join(dirname(dbPath()), ".reference-tar-")); + const tmp = mkdtempSync(join(dataDir(), ".reference-tar-")); try { const file = join(tmp, "in.tar"); await saveStdin(file); diff --git a/src/runner/cli-job.ts b/src/runner/cli-job.ts index 705394bed..7a9154e92 100644 --- a/src/runner/cli-job.ts +++ b/src/runner/cli-job.ts @@ -5,7 +5,7 @@ // Commands not listed in CLI_STEPS, and runs with options a step has no parameter for, keep their own direct path. import { spawn } from "node:child_process"; import { closeSync, createWriteStream, mkdirSync, openSync } from "node:fs"; -import { dbPath } from "../db.ts"; +import { dbEnv, dbTarget } from "../db/open.ts"; import { cliGate, jobLimit } from "./autopilot.ts"; import { checkRequest, endJob, JobError, now } from "./jobs.ts"; import { logsDir } from "./runner.ts"; @@ -75,7 +75,7 @@ export async function runCliJob(db: Db, req: CliRequest): Promise { await db.prepare("UPDATE jobs SET log_path = ? WHERE id = ?").run(logPath, job); const log = createWriteStream(logPath, { flags: "a" }); const child = spawn(process.execPath, [new URL("../cli.ts", import.meta.url).pathname, "runner", "exec", String(job)], { - stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, AUTOCRAFT_DB: dbPath() }, + stdio: ["ignore", "pipe", "pipe"], env: dbEnv(dbTarget()), }); await db.prepare("UPDATE jobs SET pid = ? WHERE id = ?").run(child.pid ?? null, job); child.stdout.on("data", (b: Buffer) => { log.write(b); process.stdout.write(b); }); diff --git a/src/runner/offthread.ts b/src/runner/offthread.ts index 79d65b3f0..f88e29d31 100644 --- a/src/runner/offthread.ts +++ b/src/runner/offthread.ts @@ -12,15 +12,15 @@ export class OffThread { private readonly pending = new Map(); private next = 1; - private readonly dbFile: string; + private readonly dbTarget: string; - constructor(dbFile: string) { - this.dbFile = dbFile; + constructor(dbTarget: string) { + this.dbTarget = dbTarget; } private spawn(): Worker { if (this.worker) return this.worker; - const w = new Worker(new URL("./worker.ts", import.meta.url), { workerData: { dbFile: this.dbFile } }); + const w = new Worker(new URL("./worker.ts", import.meta.url), { workerData: { dbTarget: this.dbTarget } }); const fail = (e: Error) => { if (this.worker === w) this.worker = null; for (const p of this.pending.values()) p.reject(e); diff --git a/src/runner/runner.ts b/src/runner/runner.ts index 77127f059..f3066b5e4 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -7,8 +7,8 @@ import { spawn, type ChildProcess } from "node:child_process"; import { appendFileSync, statSync, closeSync, mkdirSync, openSync, readFileSync, utimesSync } from "node:fs"; import { homedir } from "node:os"; -import { basename, join } from "node:path"; -import { dbPath } from "../db.ts"; +import { join } from "node:path"; +import { dbEnv, dbLockName, dbTarget } from "../db/open.ts"; import { advancePreapprovals } from "../preapproval/index.ts"; import { applyProposals, AUTOPILOT_USER, isDraining, isEnabled, planDue, type Detected } from "./autopilot.ts"; import { recordUsageSamples } from "../agents/accounts.ts"; @@ -39,7 +39,7 @@ export const logsDir = (): string => envVar("RUNNER_LOGS") ?? join(homedir(), ". export function runnerLockPath(): string { const dir = envVar("LOCK_DIR") ?? join(homedir(), ".cache/autocraft-logs"); - return join(dir, `runner-${basename(dbPath())}.lock`); + return join(dir, `runner-${dbLockName()}.lock`); } export const HEARTBEAT_KEY = "runner_heartbeat"; @@ -56,8 +56,8 @@ export const DEFAULT_MAX_JOBS = 32; export type RunnerOptions = { db: Db; - /** Database file the children open; default AUTOCRAFT_DB or the default path. */ - dbFile?: string; + /** Database the children and worker threads open (a SQLite path or a postgres:// URL); default `dbTarget()`. */ + dbTarget?: string; logs?: string; /** Most job processes running at once. */ maxJobs?: number; @@ -65,7 +65,7 @@ export type RunnerOptions = { killAfterMs?: number; lockFile?: string; log?: (line: string) => void; - /** The planner's detection pass (default: a worker thread on its own connection to `dbFile`). Tests pass a fake. */ + /** The planner's detection pass (default: a worker thread on its own connection to `dbTarget`). Tests pass a fake. */ detect?: (nowMs: number) => Promise; /** The flowchart summary refresh (default: a worker thread). */ refreshFlow?: () => Promise; @@ -128,12 +128,12 @@ export class Runner { constructor(opts: RunnerOptions) { this.db = opts.db; this.o = { - dbFile: opts.dbFile ?? dbPath(), logs: opts.logs ?? logsDir(), maxJobs: opts.maxJobs ?? DEFAULT_MAX_JOBS, killAfterMs: opts.killAfterMs ?? 10_000, + dbTarget: opts.dbTarget ?? dbTarget(), logs: opts.logs ?? logsDir(), maxJobs: opts.maxJobs ?? DEFAULT_MAX_JOBS, killAfterMs: opts.killAfterMs ?? 10_000, lockFile: opts.lockFile ?? null, log: opts.log ?? ((l) => console.log(l)), }; mkdirSync(this.o.logs, { recursive: true }); - this.planThread = new OffThread(this.o.dbFile); - this.flowThread = new OffThread(this.o.dbFile); + this.planThread = new OffThread(this.o.dbTarget); + this.flowThread = new OffThread(this.o.dbTarget); this.detect = opts.detect ?? ((t) => this.planThread.plan(t)); this.maxMin = opts.maxMin ?? stepDeadlineMin; this.graceMs = opts.graceMs ?? 600_000; @@ -490,7 +490,7 @@ export class Runner { child = spawn(process.execPath, [CLI, "runner", "exec", String(id)], { detached: true, stdio: ["ignore", fd, fd], - env: { ...process.env, AUTOCRAFT_DB: this.o.dbFile }, + env: dbEnv(this.o.dbTarget), }); } finally { closeSync(fd); diff --git a/src/runner/worker.ts b/src/runner/worker.ts index d80e3193b..22ea479a0 100644 --- a/src/runner/worker.ts +++ b/src/runner/worker.ts @@ -9,7 +9,7 @@ import { connectDb } from "../db/open.ts"; export type WorkerTask = { id: number; task: "plan"; nowMs?: number } | { id: number; task: "flow"; budgetMs?: number }; export type WorkerReply = { id: number; ok: true; result: unknown } | { id: number; ok: false; error: string }; -const db = await connectDb((workerData as { dbFile: string }).dbFile, { role: "planner" }); +const db = await connectDb((workerData as { dbTarget: string }).dbTarget, { role: "planner" }); parentPort!.on("message", async (m: WorkerTask) => { try { diff --git a/test/pg-db.test.ts b/test/pg-db.test.ts index a63260123..eff4aa35b 100644 --- a/test/pg-db.test.ts +++ b/test/pg-db.test.ts @@ -78,6 +78,27 @@ test("a nested write joins the outer one on its connection and rolls back with i } }); +test("a statement error inside db.attempt leaves the write usable: its own changes are undone, the rest commit", { skip: needsPg }, async () => { + const t = await testDatabase(`${SCHEMA}; CREATE UNIQUE INDEX t_v ON t (v)`); + try { + const a = await t.open(); + await a.write(async () => { + await a.prepare("INSERT INTO t (v) VALUES ('kept')").run(); + const dup = await a.attempt(async () => { + await a.prepare("INSERT INTO t (v) VALUES ('undone')").run(); + await a.prepare("INSERT INTO t (v) VALUES ('kept')").run(); + }).catch((e: unknown) => e); + assert.equal((dup as { code?: string }).code, "23505"); + assert.equal(await a.attempt(() => count(a)), 1); + await a.prepare("INSERT INTO t (v) VALUES ('after')").run(); + }); + const rows = await a.prepare("SELECT v FROM t ORDER BY id").all(); + assert.deepEqual(rows.map((r) => r.v), ["kept", "after"]); + } finally { + await t.close(); + } +}); + test("? and :name placeholders become $n by node:sqlite's binding rules, outside literals and casts", { skip: needsPg }, async () => { const t = await testDatabase(); try { diff --git a/test/runner.test.ts b/test/runner.test.ts index a7510a421..0f438d84b 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -3,6 +3,7 @@ // left running, runs one job per step and repo at a time. import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { createServer, type AddressInfo } from "node:net"; import { join } from "node:path"; import { after, describe, test } from "node:test"; import { fileURLToPath } from "node:url"; @@ -23,7 +24,7 @@ const dir = mkdtempSync(join(SCRATCH, "runner-test-")); const dbFile = join(dir, "runner.db"); const db = await connectDb(dbFile); await db.script("INSERT OR IGNORE INTO tracked_repos (name, pipeline) VALUES ('app', 1); UPDATE tracked_repos SET pipeline = 1"); -const runner = new Runner({ db, dbFile, logs: join(dir, "logs"), killAfterMs: 2000, log: () => {} }); +const runner = new Runner({ db, dbTarget: dbFile, logs: join(dir, "logs"), killAfterMs: 2000, log: () => {} }); after(async () => { await runner.stop(); @@ -56,9 +57,34 @@ describe("runner", () => { assert.equal((await getJob(db, bad.id)).error, "echo failed on purpose"); }); - - - - - + test("with AUTOCRAFT_DB_URL set, a job process opens that Postgres database, not a SQLite file", async () => { + // A stand-in server that records the startup packet a Postgres client sends first (it names the database), then hangs up. + const seen: Buffer[] = []; + const server = createServer((s) => s.on("data", (b: Buffer) => { seen.push(b); s.destroy(); })); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const port = (server.address() as AddressInfo).port; + const saved = { url: process.env.AUTOCRAFT_DB_URL, db: process.env.AUTOCRAFT_DB }; + const pgDir = mkdtempSync(join(dir, "pg-")); + const pgDb = await connectDb(join(pgDir, "jobs.db")); + process.env.AUTOCRAFT_DB_URL = `postgres://autocraft@127.0.0.1:${port}/childjob`; + delete process.env.AUTOCRAFT_DB; + const pgRunner = new Runner({ db: pgDb, logs: join(pgDir, "logs"), killAfterMs: 2000, log: () => {}, detect: async () => ({ proposals: [], logs: [] }), refreshFlow: async () => undefined }); + try { + const job = await enqueue(pgDb, "test-echo", { n: 1 }, "boss"); + const end = Date.now() + 20_000; + while (!Buffer.concat(seen).includes("database\0childjob\0")) { + if (Date.now() > end) throw new Error(`the job process did not connect; job ${job.id} is ${(await getJob(pgDb, job.id)).state}`); + await pgRunner.tick(); + await new Promise((r) => setTimeout(r, 50)); + } + } finally { + await pgRunner.stop(); + await pgDb.close(); + await new Promise((r) => server.close(r)); + for (const [k, v] of [["AUTOCRAFT_DB_URL", saved.url], ["AUTOCRAFT_DB", saved.db]] as const) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } + }); }); diff --git a/test/step-repo.test.ts b/test/step-repo.test.ts index d13ed6e60..78dce710d 100644 --- a/test/step-repo.test.ts +++ b/test/step-repo.test.ts @@ -20,7 +20,7 @@ mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "step-repo-")); const db = await connectDb(join(dir, "t.db")); for (const r of ["a", "b"]) await db.prepare("INSERT OR IGNORE INTO tracked_repos (name, pipeline) VALUES (?, 1)").run(r); -const make = (maxJobs?: number) => new Runner({ db, dbFile: join(dir, "t.db"), logs: join(dir, "logs"), killAfterMs: 2000, log: () => {}, ...(maxJobs ? { maxJobs } : {}) }); +const make = (maxJobs?: number) => new Runner({ db, dbTarget: join(dir, "t.db"), logs: join(dir, "logs"), killAfterMs: 2000, log: () => {}, ...(maxJobs ? { maxJobs } : {}) }); const runners: InstanceType[] = []; after(async () => { for (const r of runners) await r.stop(); await db.close(); rmSync(dir, { recursive: true, force: true }); }); diff --git a/test/stuck-jobs.test.ts b/test/stuck-jobs.test.ts index f3ace1618..cb4bb4e98 100644 --- a/test/stuck-jobs.test.ts +++ b/test/stuck-jobs.test.ts @@ -25,7 +25,7 @@ mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "stuck-jobs-")); const dbFile = join(dir, "runner.db"); const db = await connectDb(dbFile); -const runner = new Runner({ db, dbFile, logs: join(dir, "logs"), killAfterMs: 2000, log: () => {}, maxMin: (s) => (s === "test-sleep" ? 0.02 : 999), noProgressMin: (s) => (s === "test-other" ? 0.02 : 999), graceMs: 500 }); +const runner = new Runner({ db, dbTarget: dbFile, logs: join(dir, "logs"), killAfterMs: 2000, log: () => {}, maxMin: (s) => (s === "test-sleep" ? 0.02 : 999), noProgressMin: (s) => (s === "test-other" ? 0.02 : 999), graceMs: 500 }); after(async () => { await runner.stop(); await db.close();