UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

393 lines (391 loc) • 16.4 kB
import { getMigrationStorage, pluginMigrationSlug } from "../../db/core.mjs"; import { resolveDatabaseUrl } from "../../db/binding.mjs"; import { createDatabaseDriver, pluginSchemaName } from "../../db/driver.mjs"; import { workspaceIdentityFromWorkspaceDir } from "../../db/identity.mjs"; import { loadMigrations, runMigrations } from "../../db/run-migrations.mjs"; import { pruneDead, readRegistry } from "../processes/registry.mjs"; import { existsSync } from "node:fs"; import { join, resolve } from "node:path"; import { Effect } from "effect"; import { createHash, randomUUID } from "node:crypto"; import { sql } from "drizzle-orm"; import { spawn } from "node:child_process"; //#region src/services/seed/runner.ts /** * The seed phase (#865): run the app's declared seed before services serve. * * Ordering is forced by the database topology. In dev every workspace DB is a * PGlite data dir held open by its service process for the process's lifetime * (ADR 0044) — cross-process opens block on the file lock — so nothing here * may run while services are up. The phase therefore runs pre-spawn, which * also means it must ensure the schema itself: a fresh checkout has no tables * until the services' in-process migrate-on-boot fires, and this phase runs * before it. `loadMigrations` + `runMigrations` replay each local workspace's * migrations against the same per-workspace journal the services use (ADR * 0045), so the later in-process run converges to a no-op. * * Steps are the general surface — arbitrary idempotent scripts (upserts by * contract) against any workspace DB, run once per `seed.version`. The marker * (one `bos_seed_state` row in the api database) records the version that * produced the current state; a matching version short-circuits the whole * phase, a bump re-runs it deliberately. * * The owner-admin bootstrap is framework-provided and always first: direct * writes into the auth database in exactly the row shape the SIWN flow * expects (`user` + `near_account` + `account`), so the configured owner * signs in with platform-admin rights immediately — `/near/verify` finds the * pre-provisioned `near_account` row and hands out a session for the admin * user instead of creating a second user. The row shapes couple this module * to the auth plugin's schema; both ship in release lockstep from this repo, * and a missing `near_account` table (schema drift) fails loudly before any * write. */ const SEED_MARKER_TABLE = "bos_seed_state"; const SEED_MARKER_ID = "app"; var SeedPhaseError = class extends Error { stage; step; constructor(message, stage, step) { super(message); this.stage = stage; this.step = step; this.name = "SeedPhaseError"; } }; const migrationsJournalPath = (workspaceDir) => join(workspaceDir, "src", "db", "migrations", "meta", "_journal.json"); const secretNameForSlug = (slug) => `${slug.toUpperCase().replace(/-/g, "_")}_DATABASE_URL`; /** * The workspaces the phase touches, in dependency order: auth first (the * owner bootstrap writes there), then the api shell (the marker's home), * then every local plugin. Remote entries resolve to their secret name with * no local dir — migrations are skipped for them (nothing to load) but the * binding still addresses the right database. */ function resolveSeedWorkspaces(runtime, configDir, env) { const entries = [ { key: "auth", entry: runtime.auth ?? void 0, plugin: false }, { key: "api", entry: runtime.api ?? void 0, plugin: false }, ...Object.keys(runtime.plugins ?? {}).sort().map((key) => ({ key, entry: runtime.plugins?.[key], plugin: true })) ]; const workspaces = []; for (const { key, entry, plugin } of entries) { if (!entry) continue; const slug = pluginMigrationSlug(key); const workspaceDir = entry.localPath ? resolve(configDir, entry.localPath) : void 0; const identity = workspaceDir ? workspaceIdentityFromWorkspaceDir(workspaceDir) : { slug, secretName: secretNameForSlug(slug), journal: getMigrationStorage(slug), workspaceDir: void 0 }; const hasMigrations = workspaceDir !== void 0 && existsSync(migrationsJournalPath(workspaceDir)); if (!(hasMigrations || workspaceDir !== void 0 || Boolean(env[identity.secretName]))) continue; workspaces.push({ key, slug: identity.slug, workspaceDir, identity, url: resolveDatabaseUrl(identity, { env }), schemaName: plugin ? pluginSchemaName(identity.slug) : void 0, hasMigrations }); } return workspaces; } /** Sequential open → use → close — the phase holds no driver across steps. */ async function withWorkspaceDb(ws, run) { const driver = await createDatabaseDriver(ws.url, {}, ws.schemaName, `${ws.identity.journal.schema}.${ws.identity.journal.table}`); try { return await run(driver.db); } finally { await driver.close(); } } function rowsOf(result) { if (Array.isArray(result)) return result; const rows = result.rows; return Array.isArray(rows) ? rows : []; } async function ensureMarkerTable(db) { await db.execute(sql.raw(`CREATE TABLE IF NOT EXISTS "${SEED_MARKER_TABLE}" (id text PRIMARY KEY, version integer NOT NULL, seeded_at timestamptz NOT NULL DEFAULT now(), steps jsonb)`)); } async function readSeedMarker(api) { return withWorkspaceDb(api, async (db) => { await ensureMarkerTable(db); const row = rowsOf(await db.execute(sql`SELECT version FROM ${sql.identifier(SEED_MARKER_TABLE)} WHERE id = ${SEED_MARKER_ID}`))[0]; return typeof row?.version === "number" ? row.version : null; }); } async function writeSeedMarker(api, version, steps) { await withWorkspaceDb(api, async (db) => { await ensureMarkerTable(db); await db.execute(sql`INSERT INTO ${sql.identifier(SEED_MARKER_TABLE)} (id, version, steps) VALUES (${SEED_MARKER_ID}, ${version}, ${JSON.stringify(steps)}::jsonb) ON CONFLICT (id) DO UPDATE SET version = ${version}, seeded_at = now(), steps = ${JSON.stringify(steps)}::jsonb`); }); } /** Replay each local workspace's migrations against its own journal. */ async function ensureWorkspaceSchemas(workspaces) { const migrated = []; for (const ws of workspaces) { if (!ws.hasMigrations || !ws.workspaceDir) continue; const loaded = await Effect.runPromise(loadMigrations({ fromDir: join(ws.workspaceDir, "src", "db") })).catch((cause) => { throw new SeedPhaseError(`loading migrations for "${ws.key}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, "migrate"); }); if (loaded.migrations.length === 0) continue; await withWorkspaceDb(ws, (db) => Effect.runPromise(runMigrations(db, loaded.migrations, { journal: ws.identity.journal, schemaName: ws.schemaName })).catch((cause) => { throw new SeedPhaseError(`migrating "${ws.key}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, "migrate"); })); migrated.push(ws.slug); } return migrated; } /** * Mirror better-near-auth's `deriveEmail` with a deterministic tail: the * single-segment `.near` shape the SIWN flow derives, or the recognized * `temp-<hex>@<recipient>` synthetic form (stable hash — re-runs must not * mint a second identity). */ function ownerEmailForAccount(accountId, recipient) { if (accountId.endsWith(".near")) { const localPart = accountId.slice(0, -5); if (!localPart.includes(".")) return `${localPart}@near.email`; } return `temp-${createHash("sha256").update(accountId).digest("hex").slice(0, 8)}@${recipient}`; } function resolveOwnerCredential(ownerAdmin, fallbackAccount, override) { if (override) { if (!override.nearAccount && !override.email) return null; return override; } if (!ownerAdmin) return null; if (ownerAdmin === true) return fallbackAccount ? { nearAccount: fallbackAccount } : null; const credential = {}; if (ownerAdmin.nearAccount) credential.nearAccount = ownerAdmin.nearAccount; if (ownerAdmin.email) credential.email = ownerAdmin.email; return credential.nearAccount || credential.email ? credential : null; } const findUserIdByNearAccount = async (db, accountId) => { const row = rowsOf(await db.execute(sql`SELECT u.id FROM "user" u JOIN near_account na ON na.user_id = u.id WHERE na.account_id = ${accountId} LIMIT 1`))[0]; return typeof row?.id === "string" ? row.id : null; }; const findUserIdByEmail = async (db, email) => { const row = rowsOf(await db.execute(sql`SELECT id FROM "user" WHERE email = ${email} LIMIT 1`))[0]; return typeof row?.id === "string" ? row.id : null; }; const promoteToAdmin = async (db, userId) => { await db.execute(sql`UPDATE "user" SET role = 'admin', updated_at = now() WHERE id = ${userId}`); }; /** * Provision the owner as platform admin (`user.role = 'admin'`) in the auth * database. NEAR owners get the full SIWN row shape — `user`, `near_account` * (unique on `(account_id, network)`, which is exactly what `/near/verify` * resolves first), and the `account` provider row — so first sign-in finds * the admin user instead of minting a duplicate. */ async function provisionOwnerAdmin(auth, credential, options) { return withWorkspaceDb(auth, async (db) => { if (!rowsOf(await db.execute(sql`SELECT to_regclass('public.near_account') AS reg`))[0]?.reg) throw new SeedPhaseError("the auth database has no near_account table — the auth plugin schema is missing or from an incompatible version; run `bos db doctor auth`", "owner"); const networkId = options.networkId ?? "mainnet"; const recipient = options.recipient ?? "seed.internal"; const ensureAdmin = async (userId) => { if (rowsOf(await db.execute(sql`SELECT role FROM "user" WHERE id = ${userId}`))[0]?.role !== "admin") await promoteToAdmin(db, userId); }; if (credential.nearAccount) { const accountId = credential.nearAccount; const existing = await findUserIdByNearAccount(db, accountId) ?? await findUserIdByEmail(db, ownerEmailForAccount(accountId, recipient)); if (existing) { await ensureAdmin(existing); return { mode: "near", provisioned: true, accountId: existing }; } const userId = randomUUID(); const email = ownerEmailForAccount(accountId, recipient); await db.execute(sql`INSERT INTO "user" (id, name, email, email_verified, role, created_at, updated_at) VALUES (${userId}, ${accountId}, ${email}, true, 'admin', now(), now())`); await db.execute(sql`INSERT INTO near_account (id, user_id, account_id, network, public_key, is_primary, created_at) VALUES (${randomUUID()}, ${userId}, ${accountId}, ${networkId}, 'seed:pending', true, now())`); const providerAccountId = `${accountId}:${networkId}`; if (!rowsOf(await db.execute(sql`SELECT id FROM "account" WHERE provider_id = 'siwn' AND account_id = ${providerAccountId} LIMIT 1`))[0]) await db.execute(sql`INSERT INTO "account" (id, account_id, provider_id, user_id, created_at, updated_at) VALUES (${randomUUID()}, ${providerAccountId}, 'siwn', ${userId}, now(), now())`); return { mode: "near", provisioned: true, accountId: userId }; } const email = credential.email; const existing = await findUserIdByEmail(db, email); if (existing) { await ensureAdmin(existing); return { mode: "email", provisioned: true, accountId: existing }; } const userId = randomUUID(); await db.execute(sql`INSERT INTO "user" (id, name, email, email_verified, role, created_at, updated_at) VALUES (${userId}, ${email.split("@")[0]}, ${email}, true, 'admin', now(), now())`); return { mode: "email", provisioned: true, accountId: userId }; }); } async function runSeedStep(configDir, step, env) { const scriptPath = resolve(configDir, step); if (!existsSync(scriptPath)) throw new SeedPhaseError(`seed step not found: ${step}`, "steps", step); const timeoutRaw = env.SEED_STEP_TIMEOUT_MS; const timeoutParsed = timeoutRaw ? Number(timeoutRaw) : NaN; const timeoutMs = Number.isFinite(timeoutParsed) && timeoutParsed > 0 ? timeoutParsed : void 0; return new Promise((resolvePromise, reject) => { const child = spawn("pnpm", [ "exec", "tsx", scriptPath ], { cwd: configDir, env, stdio: "inherit", detached: process.platform !== "win32" }); let timedOut = false; let killTimer; const timer = timeoutMs ? setTimeout(() => { timedOut = true; try { if (child.pid) process.kill(-child.pid, "SIGTERM"); } catch { child.kill("SIGTERM"); } killTimer = setTimeout(() => { try { if (child.pid) process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); } }, 5e3); killTimer.unref(); }, timeoutMs) : void 0; timer?.unref(); const cleanup = () => { clearTimeout(timer); clearTimeout(killTimer); }; child.on("error", (cause) => { cleanup(); reject(new SeedPhaseError(`seed step "${step}" could not start (tsx must be installed at the workspace root): ${cause.message}`, "steps", step)); }); child.on("exit", (code) => { cleanup(); if (timedOut) { reject(new SeedPhaseError(`seed step "${step}" timed out after ${timeoutMs}ms (SEED_STEP_TIMEOUT_MS) — steps are idempotent by contract; fix and re-run (bump seed.version or pass --force)`, "steps", step)); return; } if (code === 0) { resolvePromise(); return; } reject(new SeedPhaseError(`seed step "${step}" exited with code ${code} — steps are idempotent by contract; fix and re-run (bump seed.version or pass --force)`, "steps", step)); }); }); } /** * A dev stack holds its PGlite data dirs open for its services' lifetime — a * cross-process seed run would queue on the file lock indefinitely (ADR 0044). * Fail fast when the shared pid registry shows a live session for this * project. Postgres workspaces are unaffected; an unreadable registry degrades * to best-effort (proceed). */ function guardAgainstLiveStack(configDir, workspaces) { if (!workspaces.some((ws) => ws.url.startsWith("pglite:"))) return; let live; try { live = pruneDead(readRegistry()); } catch { return; } const root = resolve(configDir); if (live.some((entry) => resolve(entry.configDir) === root)) throw new SeedPhaseError("a dev stack for this project appears to be running (`bos ps`) — its services hold this project's PGlite data dirs open and a seed run would block on the file lock. Stop it first (`bos kill`), then re-run.", "guard"); } async function runSeedPhase(input) { const { seed, configDir, env, runtime } = input; const workspaces = resolveSeedWorkspaces(runtime, configDir, env); guardAgainstLiveStack(configDir, workspaces); const api = workspaces.find((ws) => ws.key === "api"); if (!api) throw new SeedPhaseError("no api workspace binding — the seed marker lives in the api database", "marker"); const auth = workspaces.find((ws) => ws.key === "auth"); const markerWas = await readSeedMarker(api); const declaredSteps = seed.steps ?? []; if (!input.force && markerWas === seed.version) return { status: "already-seeded", version: seed.version, markerWas, workspaces: [], owner: null, steps: [] }; const migrated = await ensureWorkspaceSchemas(workspaces); const credential = resolveOwnerCredential(seed.auth?.ownerAdmin, input.fallbackAccount, input.ownerOverride); let owner = null; if (credential) { if (!auth) throw new SeedPhaseError("seed.auth.ownerAdmin is declared but the app has no auth slot to provision into", "owner"); owner = await provisionOwnerAdmin(auth, credential, { networkId: runtime.networkId, recipient: input.siwnRecipient }); } const stepEnv = { ...process.env, ...env }; for (const ws of workspaces) if (!stepEnv[ws.identity.secretName]) stepEnv[ws.identity.secretName] = ws.url; const outcomes = []; for (const step of declaredSteps) try { await runSeedStep(configDir, step, stepEnv); outcomes.push({ step, status: "ran" }); } catch (error) { const message = error instanceof Error ? error.message : String(error); outcomes.push({ step, status: "failed", error: message }); throw error; } await writeSeedMarker(api, seed.version, declaredSteps); return { status: "seeded", version: seed.version, markerWas, workspaces: migrated, owner, steps: outcomes }; } //#endregion export { SEED_MARKER_TABLE, SeedPhaseError, guardAgainstLiveStack, ownerEmailForAccount, provisionOwnerAdmin, resolveOwnerCredential, resolveSeedWorkspaces, runSeedPhase }; //# sourceMappingURL=runner.mjs.map