stock-bot/test/fixtures/canonical-paper-crash-owner.ts

77 lines
3.1 KiB
TypeScript

/** Runs only in a disposable schema; the parent kills this process at a durable boundary. */
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { CanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
import { canonicalConfig, counterProgram } from './canonical-paper';
import { logger } from './execution';
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const schema = process.env.CANONICAL_CRASH_SCHEMA;
const phase = process.env.CANONICAL_CRASH_PHASE;
if (
!url ||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
!schema ||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
!['decision', 'checkpoint', 'dispatch', 'fill'].includes(phase ?? '')
) {
throw new Error('Unsafe canonical crash fixture');
}
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const durable = new PostgresCanonicalExecutionRepository(postgres);
const block = async () => {
process.send?.({ phase });
await new Promise<void>(() => {});
};
const repository: CanonicalExecutionRepository = {
initialize: (account, owners) => durable.initialize(account, owners),
async transact(accountId, work) {
let committedBoundary = false;
const result = await durable.transact(accountId, tx =>
work({
...tx,
async putOwner(owner) {
// The callback has returned, but neither its next checkpoint nor its
// complete batch has committed. Killing here must roll both back.
if (phase === 'decision' && owner.diagnostic.nextDecisionSequence > 0) {
await block();
}
await tx.putOwner(owner);
},
async putBatch(batch) {
await tx.putBatch(batch);
committedBoundary =
(phase === 'checkpoint' && batch.status === 'pending') ||
(phase === 'dispatch' && batch.status === 'dispatched');
},
async putInput(input) {
await tx.putInput(input);
if (
phase === 'fill' &&
input.status === 'applied' &&
input.input.command.body.kind === 'execute'
) {
committedBoundary = true;
}
},
})
);
if (committedBoundary) {
// SQL has committed, but drain has not received its acknowledgement and
// cannot publish. Restart must use committed state without rerunning it.
await block();
}
return result;
},
};
const execution = new CanonicalPaperExecution({ repository, programs: [counterProgram()] });
await execution.initialize(canonicalConfig());
await execution.drain();
throw new Error('Canonical crash fixture did not reach its requested boundary');