wishforge-ide/tests/integration/postgres.test.ts
eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

98 lines
3.9 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { randomUUID } from 'node:crypto';
import pg from 'pg';
import { PgStore } from '../../apps/api/src/db/store.js';
import { ControlPlane } from '../../apps/api/src/domain/control-plane.js';
import type { Actor } from '@wishforge/contracts';
const enabled = process.env.WF_INTEGRATION === '1';
if (enabled) {
try {
process.loadEnvFile('.env.local');
} catch {}
}
describe.skipIf(!enabled)('PostgreSQL RLS, transaction concurrency and persistence', () => {
let store: PgStore, admin: pg.Client, control: ControlPlane;
const tenantA = `test-${randomUUID()}`,
tenantB = `test-${randomUUID()}`;
const actor: Actor = { tenantId: tenantA, userId: 'test-owner', kind: 'human', role: 'owner' };
beforeAll(async () => {
admin = new pg.Client({ connectionString: process.env.DATABASE_ADMIN_URL });
await admin.connect();
for (const id of [tenantA, tenantB]) {
await admin.query('INSERT INTO tenants(id,name,region) VALUES($1,$1,$2)', [id, 'integration']);
await admin.query("INSERT INTO memberships(tenant_id,user_id,role) VALUES($1,'test-owner','owner')", [id]);
}
store = new PgStore(process.env.DATABASE_URL!);
await store.assertSafeRole();
control = new ControlPlane(store, { NODE_ENV: 'test' });
});
afterAll(async () => {
await store?.close();
if (admin) {
for (const table of [
'memberships',
'entities',
'run_events',
'idempotency',
'outbox',
'usage_ledger',
'audit_events',
'tenants',
])
await admin.query(`DELETE FROM ${table} WHERE ${table === 'tenants' ? 'id' : 'tenant_id'} = ANY($1::text[])`, [
[tenantA, tenantB],
]);
await admin.end();
}
});
it('enforces RLS even if a caller omits a tenant WHERE clause', async () => {
const project = await control.createProject(actor, { name: 'Isolated fixture' });
expect(await control.projects({ ...actor, tenantId: tenantB })).toEqual([]);
const c = await store.pool.connect();
try {
await c.query('BEGIN');
await c.query("SELECT set_config('app.tenant_id',$1,true)", [tenantB]);
const rows = await c.query('SELECT data FROM entities WHERE id=$1', [project.id]);
expect(rows.rowCount).toBe(0);
await expect(
c.query("INSERT INTO entities(tenant_id,kind,id,version,data) VALUES($1,'project','escape',1,$2)", [
tenantA,
{ id: 'escape', tenantId: tenantA },
]),
).rejects.toMatchObject({ code: '42501' });
} finally {
await c.query('ROLLBACK');
c.release();
}
});
it('deduplicates 12 concurrent requests with durable sequence numbers', async () => {
const project = await control.createProject(actor, { name: 'Concurrent fixture' });
const input = { goal: 'Test idempotency only', acceptanceCriteria: ['Only one run is created'] };
const results = await Promise.all(
Array.from({ length: 12 }, () => control.submit(actor, project.id, input, 'postgres-concurrent-key')),
);
expect(new Set(results.map(r => r.run_id)).size).toBe(1);
const events = await control.events(actor, results[0].run_id);
expect(events.map(e => e.seq)).toEqual([1, 2]);
const secondStore = new PgStore(process.env.DATABASE_URL!);
try {
const reopened = new ControlPlane(secondStore);
expect((await reopened.run(actor, results[0].run_id)).goal).toBe(input.goal);
} finally {
await secondStore.close();
}
});
it('rolls back entity, outbox and quota changes together', async () => {
const before = await control.usage(actor);
await expect(
store.transaction(tenantA, async tx => {
await tx.enqueue('test.abort', {});
throw new Error('Injected transaction crash');
}),
).rejects.toThrow('Injected');
expect(await store.transaction(tenantA, tx => tx.outbox())).toEqual([]);
expect(await control.usage(actor)).toEqual(before);
});
});