Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions apps/api/src/modules/demo/reset.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined>): boolean {
return env.DEMO_RESET_ON_BOOT === 'true' && env.APP_ENV === 'production';
}

export async function resetDemoDatabase(db: PrismaClient): Promise<ResetOutcome> {
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';
}
21 changes: 21 additions & 0 deletions apps/api/src/reset-demo.ts
Original file line number Diff line number Diff line change
@@ -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());
66 changes: 66 additions & 0 deletions apps/api/test/integration/modules/demo/reset.int.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
20 changes: 20 additions & 0 deletions apps/api/test/unit/modules/demo/reset.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
1 change: 1 addition & 0 deletions apps/api/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions deploy/render/start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 8 additions & 2 deletions docs/infra/DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**

Expand Down
3 changes: 2 additions & 1 deletion docs/infra/INFRA.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 5 additions & 0 deletions render.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading