mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Pull request CI verifies every change before merge across build, typecheck, server tests, Runner tests, and Playwright E2E shards. > - After Phase 1 (#22679) and Phase 2 (#22729), full-fanout PR CI still takes 9m45s wall-clock on 4-core AWS runners because of five bottlenecks: an unsharded 7m22s `Runner support suite`, stale server/chat/Runner shard duration manifests plus newly landed SSH/soak whales, 28s of `pnpm -r run postinstall` replay on every job, cold server/UI typecheck and single-build overhead, and 3 oversized (>180s) Playwright E2E specs across 8 shards with double-start Postgres template boot. > - Docs-only prose edits under `doc/**` and `docs/**` also fanned out to 66 CI jobs because only three doc paths bypassed global dependencies. > - This pull request shards `Runner support suite` 4 ways with `pool: "threads"`, shards E2E 12 ways after splitting the 3 oversized specs and removing double-start Postgres boot, adds pure-Node workspace postinstall replay, adds read-only master-warmed incremental TS 7 and Runner dist caches, rebalances all server/chat/Runner duration manifests, demotes 48 new non-invariant soak whales to nightly, and routes audited prose docs without triggering 66-job storms. > - The benefit is driving ordinary PR CI toward under 3 minutes wall-clock while preserving every invariant check, cache boundary, and full master/nightly test coverage. ## Linked Issues or Issue Description Refs #22679 Refs #22729 **What existing behavior does this improve?** Pull request CI wall-clock latency across `.github/workflows/pr-trusted.yml`, `.github/workflows/release-verify.yml`, `.github/actions/setup-ci-dependencies/action.yml`, typecheck orchestration, Vitest/Runner lanes, and Playwright E2E shards. **Subsystem affected** Cross-cutting (multiple of the above) **Current behavior** Full-fanout PR CI takes 9m45s on 4-core runners (run `45440355579`), dominated by `Runner support suite` (7m22s), `e2e shards` (5m02s–6m24s), `General tests (server/chat)` (5m37s–6m01s), `Verify Paperclip Runner (vitest package)` (6m25s on stale manifests), `Typecheck` (4m13s–6m30s), `Build` (~4m), and 28s of `pnpm -r postinstall` per job. Prose edits under `doc/**` trigger 66 jobs. **Proposed behavior** Shard `Runner support suite` (4x) and `e2e_shards` (12x), split the 3 oversized E2E specs, boot disposable E2E Postgres in a single non-durable start, replay workspace `postinstall` in pure Node (<1s), cache prebuilt Runner dist and TS 7 `.tsbuildinfo` from canonical `master` pushes (read-only in PRs), use emit-only server compile in ordinary PR `Build`, rebalance all shard duration manifests, demote 48 new non-invariant soak whales to nightly, and route audited prose docs cleanly. ## What Changed - **Pure-Node postinstall replay (`scripts/replay-workspace-postinstall.mjs`, `.github/actions/setup-ci-dependencies/action.yml`):** Replaces the 28s `pnpm -r --if-present run postinstall && pnpm run postinstall` call on every CI job with a pure-Node parallel runner (~0.84s locally) with fallback for older checkouts. - **4-way sharded `Runner support suite` + `threads` pool (`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`, `tests/runner-e2e/run-unit.mjs`, `tests/runner-e2e/vitest.config.ts`):** Shards Vitest and `node:test` suites 4 ways (`--shard-index 0..3 --shard-count 4`) and switches `tests/runner-e2e` to `pool: "threads"` with CPU-aware `maxWorkers` while preserving `isolate: true`. - **12-way E2E shards, single-start E2E Postgres boot, and 3 oversized spec splits (`tests/e2e/start-e2e-server.ts`, `tests/e2e/*.spec.ts`, `tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`, `.github/ci-task-matrix.json`):** Boots cold ephemeral E2E Postgres in one `initdb --no-sync` + non-durable `postgresql.conf` start overlapped with server module import; splits `agent-chat-projects`, `chat-adapters-ui-providers`, and `chat-adapters-ui-messaging` cleanly with zero tests removed; balances all 54 specs across 12 shards (6.8s spread). - **Incremental TS 7 typecheck & Runner dist caching (`server/scripts/typecheck-layers.mjs`, `scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`, `scripts/typecheck-test-projects.mjs`, `.github/workflows/pr-trusted.yml`, `.github/workflows/release-verify.yml`):** Preserves portable `.tsbuildinfo`/`.d.ts` with `layer-map.json` invalidation and stale-declaration pruning, wires read-only `runner-dist-v1` and `typecheck-incremental-v1` restores in `pr-trusted.yml` (zero `actions/cache/save`) paired with canonical-`master`-only guarded writers in `release-verify.yml`, skips redundant Runner Rust `cargo check` on TS-only shared PRs, and uses LPT scheduling with concurrency 3 (4-core) / 4 (8-core). - **Emit-only PR `Build` & audited prose doc routing (`.github/workflows/pr-trusted.yml`, `.github/scripts/ci-inputs.mjs`):** Passes `PAPERCLIP_TSC_EMIT_ONLY=1` on ordinary PR `Build` jobs (full `pnpm build` on `full-ci` / `master`), and classifies audited prose Markdown under `doc/**` and `docs/**` as `guidance` / `historical` while keeping `docs/api/**`, JSON/TS fixtures, `maps/**`, and unknown files fail-closed. - **Rebalanced shard manifests & new soak demotions (`scripts/ci/nightly-only-suites.json`, `scripts/*-shard-durations.json`, `packages/paperclip-runner/scripts/vitest-lane-durations.json`, `packages/paperclip-runner/vitest.config.ts`, `packages/paperclip-runner/scripts/vitest-sequencer.mjs`):** Demotes 48 newly landed/grown non-invariant soak suites (including 4 real-SSH integration suites) to nightly, refreshes all 4 timing manifests from live CI measurements (0.1s–0.6s LPT skew), and scales Runner package Vitest CI `maxWorkers` to 3 on 4-core / 6 on 8-core. ## Verification - `node --test .github/scripts/tests/*.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/public-install-closure.test.mjs scripts/__tests__/merge-queue-checks-workflow.test.mjs scripts/__tests__/e2e-shard.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/__tests__/run-vitest-stable-shard.test.mjs scripts/__tests__/run-vitest-stable-pr-mode.test.mjs scripts/__tests__/runner-vitest-package-lanes.test.mjs scripts/typecheck-test-programs.test.mjs scripts/check-test-budget.test.mjs scripts/ci/test-selection-pr-timings.test.mjs scripts/ci/test-selection-timings.test.mjs` — **973/973 PASS** - `node scripts/check-test-budget.mjs --base origin/master` — **PASS** (`609` nightly suites validated, zero protected invariants demoted) - `node scripts/check-maps.mjs` — **PASS** - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs tests/runner-e2e/unit-launcher.test.mjs` — **PASS** - `pnpm --filter @paperclipai/paperclip-runner exec vitest run scripts/vitest-sequencer.test.mjs` — **PASS** - `cd server && node ../node_modules/vitest/vitest.mjs run scripts/typecheck-layers.test.mjs scripts/typecheck-layers-incremental.test.mjs` — **56/56 PASS** (real TS 7.0.2 incremental soundness tests) - `node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit && pnpm run test:e2e:runner:typecheck` — **0 errors** - Live Playwright smoke passed across all 6 split E2E spec files on the cold non-durable Postgres boot path (`PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`). - Live sharded `tests/runner-e2e` runs passed under `pool: "threads", maxWorkers: 4` (shard `1/4` 172/172 PASS; shard `2/4` all Vitest + 65/65 `node:test` PASS). ## Risks - **Cache invalidation on incremental typecheck / Runner dist:** Mitigated by exact-key hashing (including `packages/{shared,adapter-utils,plugins/sdk}/src/**` and `packages/paperclip-runner/spec/**`) with no `restore-keys:` on `runner-dist-v1`, SHA-256 self-validation inside `prepare-runner-vendor.mjs`, `layer-map.json` invalidation + stale `.d.ts` pruning in `typecheck-layers.mjs`, and read-only PR restores (only canonical `master` pushes save caches). - **Shard rebalancing & soak demotions:** All demoted suites remain in `nightly-only-suites.json` and run on `full-ci` / `master` / nightly; `check-test-budget.mjs` enforces zero protected invariants are demoted. - **Workflow security boundaries:** `ci-routing.yml`, `pr.yml`, `CODEOWNERS`, and all `runs-on:` expressions are unchanged; `pr-trusted.yml` performs zero `actions/cache/save` calls. ## Model Used - Google Gemini (Antigravity agent swarm) with extended reasoning, tool use, and local code/test execution across 6 parallel worker roles (`ci-pipeline`, `vitest-runner`, `server-prune`, `e2e-opt`, `typecheck-opt`, `verifier`). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
403 lines
14 KiB
TypeScript
403 lines
14 KiB
TypeScript
import { randomBytes } from "node:crypto";
|
|
import fs from "node:fs";
|
|
import { createRequire } from "node:module";
|
|
import net from "node:net";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import {
|
|
applyPendingMigrations,
|
|
closeRegisteredClients,
|
|
createDb,
|
|
ensurePostgresDatabase,
|
|
} from "../../packages/db/src/client.js";
|
|
import { loadWithoutEmbeddedPostgresExitHooks } from "../../packages/db/src/embedded-postgres-lifecycle.js";
|
|
import { prepareEmbeddedPostgresNativeRuntime } from "../../packages/db/src/embedded-postgres-native.js";
|
|
import {
|
|
computeEmbeddedPostgresTemplateKey,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "../../packages/db/src/test-embedded-postgres.js";
|
|
import {
|
|
beforeTestPostgresShutdown,
|
|
ownTestPostgres,
|
|
type TestPostgresInstance,
|
|
} from "../../packages/db/src/test-postgres-owner.js";
|
|
|
|
// Fast throwaway server bootstrap for Playwright E2E shards.
|
|
// Replaces `cli onboard --yes --run` (and avoids building/copying a durable
|
|
// template cluster on ephemeral CI runners where only one server boots per job):
|
|
// 1. Writes the minimal throwaway local_trusted config + secrets key directly.
|
|
// 2. Boots a single disposable embedded Postgres with `initdb --no-sync` and
|
|
// non-durable settings (`fsync=off`, `synchronous_commit=off`,
|
|
// `full_page_writes=off`, `autovacuum=off`) written to `postgresql.conf`
|
|
// BEFORE `start()`, so all migrations and E2E test writes run at memory
|
|
// speed without stop/copy/restart overhead.
|
|
// 3. Overlaps `import("../../server/src/index.js")` with Postgres bootstrap
|
|
// and starts `server/src/index.ts` directly via `startServer()`.
|
|
|
|
type EmbeddedPostgresCtor = new (opts: {
|
|
databaseDir: string;
|
|
user: string;
|
|
password: string;
|
|
port: number;
|
|
persistent: boolean;
|
|
initdbFlags?: string[];
|
|
onLog?: (message: unknown) => void;
|
|
onError?: (message: unknown) => void;
|
|
}) => TestPostgresInstance;
|
|
|
|
type DisposableDatabase = {
|
|
connectionString: string;
|
|
cleanup(): Promise<void>;
|
|
};
|
|
|
|
const EMBEDDED_USER = "paperclip";
|
|
const EMBEDDED_PASSWORD = "paperclip";
|
|
const EMBEDDED_DB = "paperclip";
|
|
const INITDB_FLAGS = ["--encoding=UTF8", "--locale=C", "--lc-messages=C", "--no-sync"];
|
|
const DISPOSABLE_PG_CONF = [
|
|
"",
|
|
"# Disposable E2E test cluster tuning — zero crash durability required",
|
|
"fsync = off",
|
|
"synchronous_commit = off",
|
|
"full_page_writes = off",
|
|
"autovacuum = off",
|
|
"checkpoint_timeout = 1h",
|
|
"max_wal_size = 1GB",
|
|
"log_min_messages = warning",
|
|
"",
|
|
].join("\n");
|
|
|
|
const MAX_START_ATTEMPTS = 5;
|
|
|
|
async function getAvailablePort(): Promise<number> {
|
|
return await new Promise<number>((resolve, reject) => {
|
|
const server = net.createServer();
|
|
server.unref();
|
|
server.on("error", reject);
|
|
server.listen(0, "127.0.0.1", () => {
|
|
const address = server.address();
|
|
if (!address || typeof address === "string") {
|
|
server.close(() => reject(new Error("Failed to allocate E2E Postgres port")));
|
|
return;
|
|
}
|
|
const { port } = address;
|
|
server.close((error) => (error ? reject(error) : resolve(port)));
|
|
});
|
|
});
|
|
}
|
|
|
|
async function loadEmbeddedPostgresCtor(): Promise<EmbeddedPostgresCtor> {
|
|
const dbRequire = createRequire(new URL("../../packages/db/package.json", import.meta.url));
|
|
const mod = await loadWithoutEmbeddedPostgresExitHooks(async () => {
|
|
const loaded = dbRequire("embedded-postgres") as { default?: EmbeddedPostgresCtor } | EmbeddedPostgresCtor;
|
|
return typeof loaded === "function" ? loaded : loaded.default;
|
|
});
|
|
if (!mod) {
|
|
throw new Error("Failed to load embedded-postgres constructor from @paperclipai/db");
|
|
}
|
|
await prepareEmbeddedPostgresNativeRuntime();
|
|
return mod;
|
|
}
|
|
|
|
type FastPostgresHandle = {
|
|
ready: Promise<DisposableDatabase>;
|
|
};
|
|
|
|
async function startFastDisposablePostgres(
|
|
EmbeddedPostgres: EmbeddedPostgresCtor,
|
|
): Promise<FastPostgresHandle> {
|
|
// Allocate port and kick off `initdb` BEFORE returning so the `initdb` child
|
|
// process runs in parallel on another core while the caller concurrently
|
|
// transpiles `server/src/index.ts` via `tsx`.
|
|
const firstDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-pg-"));
|
|
const firstPort = await getAvailablePort();
|
|
|
|
const attemptStart = async (
|
|
dataDir: string,
|
|
pgPort: number,
|
|
preStartedInit?: Promise<void>,
|
|
preOwnedInstance?: ReturnType<typeof ownTestPostgres>,
|
|
preLogs?: string[],
|
|
): Promise<DisposableDatabase> => {
|
|
const recentLogs = preLogs ?? [];
|
|
const appendLog = (message: unknown) => {
|
|
const text = String(message ?? "").trim();
|
|
if (!text) return;
|
|
recentLogs.push(text);
|
|
if (recentLogs.length > 40) recentLogs.shift();
|
|
};
|
|
const instance =
|
|
preOwnedInstance ??
|
|
ownTestPostgres(
|
|
new EmbeddedPostgres({
|
|
databaseDir: dataDir,
|
|
user: EMBEDDED_USER,
|
|
password: EMBEDDED_PASSWORD,
|
|
port: pgPort,
|
|
persistent: true,
|
|
initdbFlags: INITDB_FLAGS,
|
|
onLog: appendLog,
|
|
onError: appendLog,
|
|
}),
|
|
dataDir,
|
|
);
|
|
|
|
try {
|
|
await (preStartedInit ?? instance.initialise());
|
|
fs.appendFileSync(path.join(dataDir, "postgresql.conf"), DISPOSABLE_PG_CONF, "utf8");
|
|
await instance.start();
|
|
|
|
const adminUrl = `postgres://${EMBEDDED_USER}:${EMBEDDED_PASSWORD}@127.0.0.1:${pgPort}/postgres`;
|
|
const connectionString = `postgres://${EMBEDDED_USER}:${EMBEDDED_PASSWORD}@127.0.0.1:${pgPort}/${EMBEDDED_DB}`;
|
|
await ensurePostgresDatabase(adminUrl, EMBEDDED_DB);
|
|
await applyPendingMigrations(connectionString);
|
|
|
|
let cleaned = false;
|
|
return {
|
|
connectionString,
|
|
cleanup: async () => {
|
|
if (cleaned) return;
|
|
cleaned = true;
|
|
try {
|
|
await closeRegisteredClients(connectionString).catch(() => {});
|
|
} finally {
|
|
await instance.stop().catch(() => {});
|
|
await fs.promises.rm(dataDir, { recursive: true, force: true });
|
|
}
|
|
},
|
|
};
|
|
} catch (error) {
|
|
try {
|
|
await instance.stop();
|
|
} catch {
|
|
// Ignore stop error on failed start attempt.
|
|
}
|
|
await fs.promises.rm(dataDir, { recursive: true, force: true });
|
|
const combined = `${error instanceof Error ? error.message : String(error)}\n${recentLogs.join("\n")}`;
|
|
if (!/address already in use/i.test(combined)) {
|
|
throw new Error(`Fast E2E embedded Postgres startup failed: ${combined}`);
|
|
}
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const firstLogs: string[] = [];
|
|
const appendFirstLog = (message: unknown) => {
|
|
const text = String(message ?? "").trim();
|
|
if (!text) return;
|
|
firstLogs.push(text);
|
|
if (firstLogs.length > 40) firstLogs.shift();
|
|
};
|
|
const firstInstance = ownTestPostgres(
|
|
new EmbeddedPostgres({
|
|
databaseDir: firstDataDir,
|
|
user: EMBEDDED_USER,
|
|
password: EMBEDDED_PASSWORD,
|
|
port: firstPort,
|
|
persistent: true,
|
|
initdbFlags: INITDB_FLAGS,
|
|
onLog: appendFirstLog,
|
|
onError: appendFirstLog,
|
|
}),
|
|
firstDataDir,
|
|
);
|
|
// Spawns the `initdb` child process synchronously before returning.
|
|
const firstInitPromise = firstInstance.initialise();
|
|
|
|
const ready = (async () => {
|
|
let lastError: unknown = new Error("embedded Postgres startup failed");
|
|
try {
|
|
return await attemptStart(firstDataDir, firstPort, firstInitPromise, firstInstance, firstLogs);
|
|
} catch (error) {
|
|
lastError = error;
|
|
if (!/address already in use/i.test(error instanceof Error ? error.message : String(error))) {
|
|
throw error;
|
|
}
|
|
}
|
|
for (let attempt = 2; attempt <= MAX_START_ATTEMPTS; attempt += 1) {
|
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-pg-"));
|
|
const pgPort = await getAvailablePort();
|
|
try {
|
|
return await attemptStart(dataDir, pgPort);
|
|
} catch (error) {
|
|
lastError = error;
|
|
if (!/address already in use/i.test(error instanceof Error ? error.message : String(error))) {
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
})();
|
|
|
|
return { ready };
|
|
}
|
|
|
|
const port = Number(process.env.PORT ?? process.env.PAPERCLIP_E2E_PORT ?? 3199);
|
|
const instanceId = process.env.PAPERCLIP_INSTANCE_ID ?? "playwright-e2e";
|
|
const homeDir =
|
|
process.env.PAPERCLIP_HOME ??
|
|
fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-home-"));
|
|
const instanceRoot = path.join(homeDir, "instances", instanceId);
|
|
const configPath =
|
|
process.env.PAPERCLIP_CONFIG ?? path.join(instanceRoot, "config.json");
|
|
const logsDir = path.join(instanceRoot, "logs");
|
|
const storageDir = path.join(instanceRoot, "data", "storage");
|
|
const masterKeyPath = path.join(instanceRoot, "secrets", "master.key");
|
|
|
|
fs.mkdirSync(logsDir, { recursive: true });
|
|
fs.mkdirSync(storageDir, { recursive: true });
|
|
fs.mkdirSync(path.dirname(masterKeyPath), { recursive: true });
|
|
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
|
|
|
if (!fs.existsSync(masterKeyPath)) {
|
|
fs.writeFileSync(masterKeyPath, randomBytes(32).toString("base64"), {
|
|
encoding: "utf8",
|
|
mode: 0o600,
|
|
});
|
|
}
|
|
|
|
process.env.PAPERCLIP_HOME = homeDir;
|
|
process.env.PAPERCLIP_INSTANCE_ID = instanceId;
|
|
process.env.PAPERCLIP_CONFIG = configPath;
|
|
process.env.PAPERCLIP_STORAGE_LOCAL_DIR = storageDir;
|
|
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = masterKeyPath;
|
|
process.env.PAPERCLIP_DB_BACKUP_ENABLED = "false";
|
|
|
|
let db: DisposableDatabase | undefined;
|
|
let shutdownServer: ((signal?: "SIGINT" | "SIGTERM") => Promise<void>) | undefined;
|
|
let shuttingDown = false;
|
|
|
|
function hasWarmEmbeddedPostgresTemplate(): boolean {
|
|
if (process.env.PAPERCLIP_TEST_POSTGRES_TEMPLATE === "0") return false;
|
|
const uid = process.getuid?.();
|
|
if (uid === undefined) return false;
|
|
const templateDir = path.join(
|
|
os.tmpdir(),
|
|
`paperclip-embedded-postgres-templates-${uid}`,
|
|
computeEmbeddedPostgresTemplateKey(),
|
|
);
|
|
return (
|
|
fs.existsSync(path.join(templateDir, "PG_VERSION")) &&
|
|
!fs.existsSync(path.join(templateDir, "postmaster.pid"))
|
|
);
|
|
}
|
|
|
|
async function tuneDisposableCluster(connectionString: string): Promise<void> {
|
|
const adminUrl = new URL(connectionString);
|
|
adminUrl.pathname = "/postgres";
|
|
const admin = createDb(adminUrl.toString(), { maxConnections: 1 });
|
|
try {
|
|
await admin.$client.unsafe("ALTER SYSTEM SET fsync = off");
|
|
await admin.$client.unsafe("ALTER SYSTEM SET synchronous_commit = off");
|
|
await admin.$client.unsafe("ALTER SYSTEM SET full_page_writes = off");
|
|
await admin.$client.unsafe("ALTER SYSTEM SET autovacuum = off");
|
|
await admin.$client.unsafe("SELECT pg_reload_conf()");
|
|
} finally {
|
|
await admin.$client.end({ timeout: 1 });
|
|
}
|
|
}
|
|
|
|
const usesExternalPostgres = Boolean(process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim());
|
|
const useWarmTemplate = !usesExternalPostgres && hasWarmEmbeddedPostgresTemplate();
|
|
|
|
if (usesExternalPostgres) {
|
|
const shutdownExternal = async (signal: "SIGINT" | "SIGTERM") => {
|
|
if (shuttingDown) return;
|
|
shuttingDown = true;
|
|
try {
|
|
await shutdownServer?.(signal);
|
|
} finally {
|
|
await db?.cleanup();
|
|
}
|
|
process.exit(0);
|
|
};
|
|
process.once("SIGINT", () => void shutdownExternal("SIGINT"));
|
|
process.once("SIGTERM", () => void shutdownExternal("SIGTERM"));
|
|
} else {
|
|
beforeTestPostgresShutdown({
|
|
stop: async (signal) => {
|
|
if (shuttingDown) return;
|
|
shuttingDown = true;
|
|
await shutdownServer?.(signal === "SIGINT" ? "SIGINT" : "SIGTERM");
|
|
if (db) await closeRegisteredClients(db.connectionString).catch(() => {});
|
|
},
|
|
interrupt() {},
|
|
afterStop: async () => {
|
|
await db?.cleanup();
|
|
},
|
|
});
|
|
}
|
|
|
|
try {
|
|
let startedDb: DisposableDatabase;
|
|
let serverModule: typeof import("../../server/src/index.js");
|
|
|
|
if (usesExternalPostgres) {
|
|
startedDb = await startEmbeddedPostgresTestDatabase("paperclip-e2e-pg-");
|
|
serverModule = await import("../../server/src/index.js");
|
|
} else if (useWarmTemplate) {
|
|
startedDb = await startEmbeddedPostgresTestDatabase("paperclip-e2e-pg-");
|
|
await tuneDisposableCluster(startedDb.connectionString);
|
|
serverModule = await import("../../server/src/index.js");
|
|
} else {
|
|
// Load `embedded-postgres` and spawn `initdb` BEFORE calling
|
|
// `import("../../server/src/index.js")` so synchronous `createRequire`
|
|
// never races `tsx`'s ESM loader AND `initdb` runs in a separate OS
|
|
// process while `tsx` transpiles the server graph.
|
|
const embeddedPostgresCtor = await loadEmbeddedPostgresCtor();
|
|
const fastPg = await startFastDisposablePostgres(embeddedPostgresCtor);
|
|
[startedDb, serverModule] = await Promise.all([
|
|
fastPg.ready,
|
|
import("../../server/src/index.js"),
|
|
]);
|
|
}
|
|
db = startedDb;
|
|
|
|
const config = {
|
|
$meta: {
|
|
version: 1,
|
|
updatedAt: new Date().toISOString(),
|
|
source: "onboard",
|
|
},
|
|
database: {
|
|
mode: "postgres",
|
|
connectionString: db.connectionString,
|
|
backup: {
|
|
enabled: false,
|
|
intervalMinutes: 60,
|
|
retentionDays: 7,
|
|
dir: path.join(instanceRoot, "data", "backups"),
|
|
},
|
|
},
|
|
logging: { mode: "file", logDir: logsDir },
|
|
server: {
|
|
deploymentMode: "local_trusted",
|
|
exposure: "private",
|
|
bind: "loopback",
|
|
host: "127.0.0.1",
|
|
port,
|
|
allowedHostnames: [],
|
|
serveUi: true,
|
|
},
|
|
auth: { baseUrlMode: "auto", disableSignUp: false },
|
|
storage: { provider: "local_disk", localDisk: { baseDir: storageDir } },
|
|
secrets: {
|
|
provider: "local_encrypted",
|
|
strictMode: false,
|
|
localEncrypted: { keyFilePath: masterKeyPath },
|
|
},
|
|
};
|
|
fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, {
|
|
encoding: "utf8",
|
|
mode: 0o600,
|
|
});
|
|
|
|
process.env.DATABASE_URL = db.connectionString;
|
|
|
|
const started = await serverModule.startServer();
|
|
shutdownServer = started.shutdown;
|
|
} catch (error) {
|
|
await db?.cleanup();
|
|
throw error;
|
|
}
|