Files
mtusi2026lab3-fork/test/epoch-variants-experiment.cjs
T
qrtx 5c8bcf0f80 test: cover persistence failover and graceful draining
Add API integration checks, migration compatibility, rolling restart scenarios and a report verification collector.
2026-10-29 11:47:46 +03:00

262 lines
9.0 KiB
JavaScript

const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { randomUUID, createHash } = require('node:crypto');
const { spawn } = require('node:child_process');
const ts = require('typescript');
require('dotenv').config({ quiet: true });
const root = path.resolve(__dirname, '..');
const statePath = path.join(root, '.epoch-variants-state.json');
const files = [
'Auth/auth.service.ts',
'User/user.service.ts',
'User/user.guard.ts',
'Chat/chat.service.ts',
'Chat/chat.controller.ts',
];
const digest = (value) => createHash('sha256').update(value).digest('hex');
const command = process.argv[2];
async function main() {
let state;
if (command === 'init') {
assert.ok(!fs.existsSync(statePath));
assert.ok(
/messagesEpoch\s+BigInt/.test(
fs.readFileSync(path.join(root, 'prisma/schema.prisma'), 'utf8'),
),
'Historical comparison requires the pre-bucket schema. Original sources are saved in evidence/epoch-variants-sources.json',
);
state = {
directory: fs.mkdtempSync(path.join(os.tmpdir(), 'lab2-epoch-variants-')),
schema: 'epoch_variants_' + randomUUID().replaceAll('-', ''),
variants: [],
};
await database(async (client) => {
await client.query(`CREATE SCHEMA "${state.schema}"`);
await client.query(
`CREATE TABLE "${state.schema}".chat_message_epochs (chat_id uuid NOT NULL REFERENCES public.chats(id) ON DELETE CASCADE, bucket smallint NOT NULL CHECK (bucket BETWEEN 0 AND 15), epoch bigint NOT NULL DEFAULT 0, PRIMARY KEY (chat_id, bucket))`,
);
});
capture(state, 'baseline');
} else {
state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
}
if (command === 'capture') capture(state, process.argv[3]);
if (command === 'capture-striped') capture(state, 'striped', true);
if (command === 'apply-striped') {
const sources = {};
for (const variant of state.variants) {
sources[variant.name] = Object.fromEntries(
files.map((relative) => [
relative,
fs.readFileSync(
path.join(state.directory, variant.name, relative),
'utf8',
),
]),
);
}
fs.writeFileSync(
path.join(root, 'evidence/epoch-variants-sources.json'),
JSON.stringify(sources, null, 2) + '\n',
);
for (const relative of ['Auth/auth.service.ts', 'Chat/chat.service.ts']) {
const source = sources.striped[relative].replaceAll(
`"${state.schema}".chat_message_epochs`,
'"public"."chat_message_epochs"',
);
fs.writeFileSync(path.join(root, 'src', relative), source);
}
console.log(
'Applied striped epochs to application sources; saved all source snapshots',
);
}
if (['init', 'capture', 'capture-striped'].includes(command)) {
fs.writeFileSync(statePath, JSON.stringify(state, null, 2));
console.log(
'Captured:',
state.variants.map((variant) => variant.name).join(', '),
);
return;
}
if (command === 'run') {
assert.equal(state.variants.length, 4);
fs.writeFileSync(
path.join(state.directory, 'manifest.json'),
JSON.stringify(state, null, 2),
);
const override = path.join(state.directory, 'compose.json');
fs.writeFileSync(
override,
JSON.stringify({
services: {
benchmark: {
volumes: [
{
type: 'bind',
source: state.directory,
target: '/variants',
read_only: true,
},
],
},
},
}),
);
const args = [
'compose',
'-f',
'compose.yaml',
'-f',
'test/compose.benchmark.yaml',
'-f',
override,
'run',
'--rm',
'--no-deps',
'--pull',
'never',
'benchmark',
'node',
'test/epoch-variants-benchmark.mjs',
];
const code = await new Promise((resolve, reject) => {
const child = spawn('docker', args, { cwd: root, stdio: 'inherit' });
child.once('error', reject);
child.once('exit', resolve);
});
fs.writeFileSync(
path.join(root, 'evidence/epoch-variants-code.json'),
JSON.stringify(
{
variants: state.variants,
schema: state.schema,
exit_code: code,
implementation:
'TypeScript source snapshots; variant methods activated sequentially before HTTP workloads. Separate cache prefixes and API instances, shared fixtures and Node process.',
},
null,
2,
),
);
process.exitCode = code ?? 1;
}
if (command === 'seed-read-fixture') {
await database(async (client) => {
const result = await client.query(
`SELECT c.id FROM public.chats c JOIN public.messages m ON m.chat_id = c.id WHERE c.title = 'Variant benchmark' GROUP BY c.id HAVING COUNT(*) = 100000`,
);
assert.equal(result.rows.length, 1);
const chatId = result.rows[0].id;
await client.query(
'UPDATE public.chats SET messages_epoch = 100000 WHERE id = $1::uuid',
[chatId],
);
await client.query(
`INSERT INTO "${state.schema}".chat_message_epochs (chat_id, bucket, epoch) SELECT $1::uuid, bucket::smallint, 6250 FROM generate_series(0, 15) AS bucket ON CONFLICT (chat_id, bucket) DO UPDATE SET epoch = EXCLUDED.epoch`,
[chatId],
);
console.log('Seeded read fixture with 16 nonzero epoch buckets');
});
}
if (command === 'cleanup') {
await database((client) =>
client.query(`DROP SCHEMA "${state.schema}" CASCADE`),
);
const resolved = path.resolve(state.directory);
assert.equal(path.dirname(resolved), path.resolve(os.tmpdir()));
assert.ok(path.basename(resolved).startsWith('lab2-epoch-variants-'));
fs.rmSync(resolved, { recursive: true, force: true });
fs.unlinkSync(statePath);
console.log('Removed experiment schema and temporary source snapshots');
}
}
function capture(state, name, striped = false) {
assert.match(name, /^[a-z-]+$/);
assert.ok(!state.variants.some((variant) => variant.name === name));
const modules = {};
const table = `"${state.schema}".chat_message_epochs`;
for (const relative of files) {
let source = fs
.readFileSync(path.join(root, 'src', relative), 'utf8')
.replace(/\r\n/g, '\n');
if (
striped &&
['Auth/auth.service.ts', 'Chat/chat.service.ts'].includes(relative)
) {
source = source.replaceAll(
'c.messages_epoch',
`COALESCE((SELECT SUM(e.epoch) FROM ${table} AS e WHERE e.chat_id = c.id), 0)::bigint`,
);
if (relative === 'Chat/chat.service.ts') {
const start = source.indexOf(' const [message] =');
const end = source.indexOf(' if (!message)', start);
assert.ok(start !== -1 && end > start);
source =
source.slice(0, start) +
' const messageId = randomUUID();\n' +
' const bucket = parseInt(messageId.slice(0, 2), 16) % 16;\n' +
' const [message] = await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n' +
` WITH updated AS (\n INSERT INTO ${table} AS e (chat_id, bucket, epoch)\n` +
' SELECT cm.chat_id, ${bucket}::smallint, 1 FROM chat_members AS cm\n' +
' WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid\n' +
' ON CONFLICT (chat_id, bucket) DO UPDATE SET epoch = e.epoch + 1\n' +
' RETURNING chat_id\n )\n' +
' INSERT INTO messages (id, chat_id, sender_id, text)\n' +
' SELECT ${messageId}::uuid, updated.chat_id, ${userId}::uuid, ${text} FROM updated\n' +
' RETURNING id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"\n' +
' `);\n' +
source.slice(end);
}
}
const compiled = ts.transpileModule(source, {
compilerOptions: {
target: ts.ScriptTarget.ES2023,
module: ts.ModuleKind.CommonJS,
experimentalDecorators: true,
emitDecoratorMetadata: true,
},
reportDiagnostics: true,
});
assert.ok(
!compiled.diagnostics.some(
(diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error,
),
);
const destination = path.join(
state.directory,
name,
relative.replace(/\.ts$/, '.js'),
);
fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.writeFileSync(destination, compiled.outputText);
fs.writeFileSync(destination.replace(/\.js$/, '.ts'), source);
modules[relative] = {
source_sha256: digest(source),
js_sha256: digest(compiled.outputText),
};
}
state.variants.push({ name, modules, striped });
}
async function database(operation) {
const client = new (require('pg').Client)({
connectionString: process.env.DATABASE_URL,
});
await client.connect();
try {
return await operation(client);
} finally {
await client.end();
}
}
main().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});