diff --git a/apps/api/src/modules/demo/reset.ts b/apps/api/src/modules/demo/reset.ts new file mode 100644 index 0000000..f7722a2 --- /dev/null +++ b/apps/api/src/modules/demo/reset.ts @@ -0,0 +1,39 @@ +// Demo hosts only: drops every table so the boot that follows migrates and +// seeds a fresh scenario. A shared demo otherwise stays resolved after its +// first visitor and ages out of the dashboard's windows. The audit trail's +// triggers block DELETE and TRUNCATE but not DROP, so this resets the schema, +// which is acceptable only for a database that has held nothing but the demo. + +import type { PrismaClient } from '@prisma/client'; + +export type ResetOutcome = 'empty' | 'reset'; + +export class ResetRefused extends Error { + constructor(reason: string) { + super(`demo reset refused: ${reason}`); + this.name = 'ResetRefused'; + } +} + +/** Both switches, so neither a stray flag nor a dev machine can wipe a database. */ +export function resetAllowed(env: Record): boolean { + return env.DEMO_RESET_ON_BOOT === 'true' && env.APP_ENV === 'production'; +} + +export async function resetDemoDatabase(db: PrismaClient): Promise { + const [{ schema, migrated }] = await db.$queryRaw<[{ schema: string; migrated: boolean }]>` + SELECT current_schema() AS schema, to_regclass('"Lab"') IS NOT NULL AS migrated`; + if (!migrated) return 'empty'; + // The identifier is spliced into DDL below, so it must be a plain name. + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) throw new ResetRefused('unexpected schema name'); + + // Anything a provider sent means this is not a demo database: never wipe it. + const [{ real }] = await db.$queryRaw<[{ real: number }]>` + SELECT (SELECT count(*) FROM "Lab" WHERE source <> 'simulated')::int + + (SELECT count(*) FROM "OperationalEvent" WHERE source <> 'simulated')::int AS real`; + if (real > 0) throw new ResetRefused('the database holds non-simulated data'); + + await db.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`); + await db.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`); + return 'reset'; +} diff --git a/apps/api/src/reset-demo.ts b/apps/api/src/reset-demo.ts new file mode 100644 index 0000000..fa4cd80 --- /dev/null +++ b/apps/api/src/reset-demo.ts @@ -0,0 +1,21 @@ +// One-shot entrypoint for a demo host: wipes the database so the boot can +// migrate and seed it fresh (deploy/render/start.sh). See modules/demo/reset.ts. + +import { prisma } from './db.js'; +import { resetAllowed, resetDemoDatabase } from './modules/demo/reset.js'; +import { logger } from './platform/observability/logger.js'; + +async function main() { + if (!resetAllowed(process.env)) { + throw new Error('refusing to reset: needs DEMO_RESET_ON_BOOT=true and APP_ENV=production'); + } + const outcome = await resetDemoDatabase(prisma); + logger.warn({ simulated: true, outcome }, 'demo database reset'); +} + +main() + .catch((error: unknown) => { + logger.fatal({ err: error }, 'demo reset failed'); + process.exitCode = 1; + }) + .finally(() => prisma.$disconnect()); diff --git a/apps/api/test/integration/modules/demo/reset.int.test.ts b/apps/api/test/integration/modules/demo/reset.int.test.ts new file mode 100644 index 0000000..ef18eaf --- /dev/null +++ b/apps/api/test/integration/modules/demo/reset.int.test.ts @@ -0,0 +1,66 @@ +// The reset drops a schema, so it runs against a database this file creates +// and drops, never the shared test database. + +import { execFileSync } from 'node:child_process'; +import { createRequire } from 'node:module'; +import { PrismaClient } from '@prisma/client'; +import { afterAll, beforeEach, describe, expect, it } from 'vitest'; +import { prisma } from '../../../../src/db.js'; +import { ResetRefused, resetDemoDatabase } from '../../../../src/modules/demo/reset.js'; + +const prismaCli = createRequire(import.meta.url).resolve('prisma/build/index.js'); +const name = `labops_reset_${process.pid}`; +const url = new URL(process.env.DATABASE_URL ?? ''); +url.pathname = `/${name}`; +const scratch = new PrismaClient({ datasourceUrl: url.toString() }); + +const migrate = () => + execFileSync(process.execPath, [prismaCli, 'migrate', 'deploy'], { + env: { ...process.env, DATABASE_URL: url.toString() }, + stdio: ['ignore', 'ignore', 'inherit'], + }); +const tableExists = async (table: string) => + (await scratch.$queryRaw<[{ found: boolean }]>`SELECT to_regclass(${table}) IS NOT NULL AS found`)[0].found; + +beforeEach(async () => { + await scratch.$disconnect(); + await prisma.$executeRawUnsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); + await prisma.$executeRawUnsafe(`CREATE DATABASE ${name}`); +}); + +afterAll(async () => { + await scratch.$disconnect(); + await prisma.$executeRawUnsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); + await prisma.$disconnect(); +}); + +describe('resetDemoDatabase', () => { + it('leaves a never-migrated database alone', async () => { + expect(await resetDemoDatabase(scratch)).toBe('empty'); + }); + + it('drops a demo database completely, audit trail included, so it can migrate again', async () => { + migrate(); + await scratch.lab.create({ data: { name: 'demo-lab' } }); + await scratch.auditEntry.create({ + data: { actorType: 'system', actorId: 'test', action: 'scenario.run', targetType: 'scenario', targetId: 's', outcome: 'created' }, + }); + + expect(await resetDemoDatabase(scratch)).toBe('reset'); + + expect(await tableExists('"Lab"')).toBe(false); + expect(await tableExists('"AuditEntry"')).toBe(false); + expect(await tableExists('"_prisma_migrations"')).toBe(false); + migrate(); + expect(await scratch.lab.count()).toBe(0); + }); + + // Negative: a database holding anything a provider sent is not a demo. + it('refuses to wipe a database with non-simulated data, and leaves it intact', async () => { + migrate(); + await scratch.lab.create({ data: { name: 'real-lab', source: 'provider' } }); + + await expect(resetDemoDatabase(scratch)).rejects.toBeInstanceOf(ResetRefused); + expect(await scratch.lab.count()).toBe(1); + }); +}); diff --git a/apps/api/test/unit/modules/demo/reset.test.ts b/apps/api/test/unit/modules/demo/reset.test.ts new file mode 100644 index 0000000..e1ce0f5 --- /dev/null +++ b/apps/api/test/unit/modules/demo/reset.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { resetAllowed } from '../../../../src/modules/demo/reset.js'; + +describe('resetAllowed', () => { + it('allows a reset only with the flag on a production host', () => { + expect(resetAllowed({ DEMO_RESET_ON_BOOT: 'true', APP_ENV: 'production' })).toBe(true); + }); + + // Negative: either switch alone, or a near miss, must never wipe a database. + it.each([ + [{}], + [{ DEMO_RESET_ON_BOOT: 'true' }], + [{ APP_ENV: 'production' }], + [{ DEMO_RESET_ON_BOOT: 'true', APP_ENV: 'development' }], + [{ DEMO_RESET_ON_BOOT: '1', APP_ENV: 'production' }], + [{ DEMO_RESET_ON_BOOT: 'TRUE', APP_ENV: 'production' }], + ])('refuses %o', (env) => { + expect(resetAllowed(env)).toBe(false); + }); +}); diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index b657769..ddc4dc2 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -19,6 +19,7 @@ export default defineConfig({ 'src/worker.ts', 'src/seed-operator.ts', 'src/seed-demo.ts', + 'src/reset-demo.ts', ], thresholds: { lines: 70, diff --git a/deploy/render/start.sh b/deploy/render/start.sh index 38af614..45442f4 100755 --- a/deploy/render/start.sh +++ b/deploy/render/start.sh @@ -28,6 +28,11 @@ stop() { kill $worker $api $web 2>/dev/null || true; } trap 'stop; wait; exit 0' TERM INT cd /repo/apps/api +# A shared demo stays resolved after its first visitor and ages out of the +# dashboard's windows, so a demo host starts every boot from an empty database. +if [ "${DEMO_RESET_ON_BOOT:-}" = true ]; then + node dist/reset-demo.js +fi node /repo/node_modules/prisma/build/index.js migrate deploy node dist/seed-operator.js diff --git a/docs/infra/DEPLOYMENT.md b/docs/infra/DEPLOYMENT.md index 7f074c6..802163b 100644 --- a/docs/infra/DEPLOYMENT.md +++ b/docs/infra/DEPLOYMENT.md @@ -42,8 +42,14 @@ demo routes stay off; nothing on the internet can trigger a scenario. - **Any process exiting stops the container**, so the platform restarts all three together rather than serving a site whose worker is dead. - **750 free hours a month**, shared: exactly one always-on service fits. -- **Data persists in Neon**, so an incident a visitor resolves stays resolved; - the seed only adds what is missing. +- **Every boot starts from an empty database** (`DEMO_RESET_ON_BOOT=true` in + `render.yaml`): `dist/reset-demo.js` drops the schema, then the boot migrates + and seeds. A shared demo would otherwise stay resolved after its first + visitor and age out of the dashboard's 7-day window. Anything a visitor did + is gone after the service sleeps. The reset needs both `DEMO_RESET_ON_BOOT` + and `APP_ENV=production`, and refuses, failing the boot, if any lab or event + is not simulated; it drops the schema because the audit trail's triggers + block deleting rows (`apps/api/src/modules/demo/reset.ts`). **Standing it up:** diff --git a/docs/infra/INFRA.md b/docs/infra/INFRA.md index 93c9db8..8793b6c 100644 --- a/docs/infra/INFRA.md +++ b/docs/infra/INFRA.md @@ -239,7 +239,8 @@ before it is genuinely public. The summary: **Without a card: Render and Neon** (`render.yaml`, `deploy/render/`). One container runs the API, worker and web app as three processes, with Redis on -Render Key Value and PostgreSQL on Neon. It boots by migrating, seeding the +Render Key Value and PostgreSQL on Neon. It boots by resetting the demo +database (`DEMO_RESET_ON_BOOT`), migrating, seeding the `demo` operator and ingesting the demo scenario (`dist/seed-demo.js`), and it sleeps after 15 minutes idle. `DEPLOYMENT.md` ยง0 has the costs and the steps. diff --git a/render.yaml b/render.yaml index fdc568a..30a861c 100644 --- a/render.yaml +++ b/render.yaml @@ -32,6 +32,11 @@ services: generateValue: true - key: LLM_PROVIDER value: fixture + # Wipes the database on every boot (deploy/render/start.sh), so each + # session after the service sleeps starts from a fresh demo. Demo only: + # the reset refuses any database holding non-simulated data. + - key: DEMO_RESET_ON_BOOT + value: "true" - type: keyvalue name: labops-redis