Files
openmotion/tests/cloud/render-lambda.test.ts

147 lines
7.3 KiB
TypeScript

import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import test from 'node:test';
import { Queue } from 'bullmq';
import { availableRenderWakes, routesToLambda, startRenderWakeDispatcher } from '../../src/infra/render-lambda-queue.ts';
import { createLogger } from '../../src/infra/logger.ts';
import { createRedisClient } from '../../src/infra/redis.ts';
import { InvocationRenderWorker } from '../../src/workers/worker.ts';
import { handler } from '../../src/entrypoints/render-lambda.ts';
test('only selected projects enter the canary; global catalog tasks join at full cutover', () => {
const project = { projectId: 'canary' };
assert.equal(routesToLambda(new Set(), project), false);
assert.equal(routesToLambda(new Set(['other']), project), false);
assert.equal(routesToLambda(new Set(['canary']), project), true);
assert.equal(routesToLambda(new Set(['canary']), { templateId: 'a' }), false);
assert.equal(routesToLambda(new Set(['*']), { templateId: 'a' }), true);
});
test('invalid SQS envelopes fail before opening runtime connections', async () => {
await assert.rejects(handler({ Records: [] }, { awsRequestId: 'fixture' }));
await assert.rejects(handler({ Records: [{ eventSource: 'aws:sqs', body: 'wrong' }] }, { awsRequestId: 'fixture' }));
});
const redisUrl = process.env.TEST_REDIS_URL;
test('a submission during repair dispatches its IDs before the next timer tick', { skip: !redisUrl, timeout: 3000 }, async () => {
const redis = createRedisClient(redisUrl!, 'command');
const queue = new Queue(`dispatch-${randomUUID()}`, { connection: redis });
const started = Promise.withResolvers<void>();
const resume = Promise.withResolvers<void>();
const calls: Array<string[] | undefined> = [];
const dispatcher = startRenderWakeDispatcher({
queue, redis, url: 'unused', region: 'us-east-1', concurrency: 1, logger: createLogger(),
async dispatch(_notify, ids) {
calls.push(ids);
if (!ids) {
started.resolve();
await resume.promise;
}
},
});
try {
await started.promise;
dispatcher.wake('first');
dispatcher.wake('first');
dispatcher.wake('second');
resume.resolve();
await dispatcher.close();
assert.deepEqual(calls, [undefined, ['first', 'second']]);
} finally {
resume.resolve();
await dispatcher.close();
await queue.close();
await redis.quit();
}
});
test('a wake claims one priority job, duplicate and empty wakes are harmless', { skip: !redisUrl }, async () => {
const url = new URL(redisUrl!);
const connection = { host: url.hostname, port: Number(url.port || 6379), password: url.password || undefined };
const name = `render-test-${randomUUID()}`;
const queue = new Queue(name, { connection });
const seen: string[] = [];
const worker = new InvocationRenderWorker(name, async job => { seen.push(job.name); }, { connection, autorun: false });
const redis = createRedisClient(redisUrl!, 'command');
try {
assert.equal(await availableRenderWakes(queue, redis, 2), 0);
await queue.add('thumbnail', {}, { priority: 5 });
await queue.add('export', {}, { priority: 1, jobId: 'export' });
await queue.add('export', {}, { priority: 1, jobId: 'export' });
assert.equal(await availableRenderWakes(queue, redis, 2), 2);
await worker.processOne();
assert.deepEqual(seen, ['export']);
await worker.processOne();
await worker.processOne();
assert.deepEqual(seen, ['export', 'thumbnail']);
assert.equal(await queue.getCompletedCount(), 2);
} finally {
await worker.close();
await redis.quit();
await queue.obliterate({ force: true });
await queue.close();
}
});
const databaseUrl = process.env.TEST_RENDER_DATABASE_URL;
test('committed exports survive producer failure and timed-out invocations release their project', { skip: !databaseUrl || !redisUrl }, async () => {
const { readFile } = await import('node:fs/promises');
const { createDbHandle } = await import('../../src/db/client.ts');
const { reconcileLambdaExports } = await import('../../src/services/lambda-export-dispatch.ts');
const db = createDbHandle({ connectionString: databaseUrl!, max: 1 });
const url = new URL(redisUrl!);
const queue = new Queue(`render-repair-${randomUUID()}`, { connection: { host: url.hostname, port: Number(url.port || 6379) } });
const events: unknown[] = [];
const publish = async (_channel: string, event: unknown) => events.push(event);
try {
const migration = await readFile(new URL('../../src/db/migrations/0000_yellow_caretaker.sql', import.meta.url), 'utf8');
const ddl = migration.match(/CREATE TABLE "jobs" \([\s\S]*?\n\);/)![0];
await db.pool.query(ddl.replace('CREATE TABLE', 'CREATE TEMPORARY TABLE'));
const id = randomUUID();
const payload = { format: 'mp4', outputName: 'test.mp4', lambdaDispatchPending: true };
await db.pool.query(`INSERT INTO jobs(id,workspace_id,project_id,version_id,revision,kind,input_payload)
VALUES($1,$2,$3,$4,$5,'export_render',$6)`, [id, randomUUID(), randomUUID(), randomUUID(), 'a'.repeat(64), payload]);
const notify = async () => true;
await reconcileLambdaExports(db.db, queue, { publish }, notify, [randomUUID()]);
assert.equal(await queue.getPrioritizedCount(), 0);
await assert.rejects(reconcileLambdaExports(db.db, queue, { publish }, async () => {
throw new Error('SQS unavailable');
}, [id]), /SQS unavailable/);
assert.equal((await db.pool.query('SELECT input_payload FROM jobs WHERE id=$1', [id])).rows[0].input_payload.lambdaDispatchPending, true);
await reconcileLambdaExports(db.db, queue, { publish }, notify);
const queued = await queue.getJob(id);
assert.equal(queued?.data.outputName, 'test.mp4');
assert.equal(await queue.getPrioritizedCount(), 1);
assert.equal((await db.pool.query('SELECT input_payload FROM jobs WHERE id=$1', [id])).rows[0].input_payload.lambdaDispatchPending, true);
let claims = 0;
const worker = new InvocationRenderWorker(queue.name, async () => {
if (++claims === 1) throw new Error('claim unavailable');
}, {
connection: { host: url.hostname, port: Number(url.port || 6379) }, autorun: false,
});
try {
await worker.processOne();
assert.equal(await queued!.getState(), 'failed');
await reconcileLambdaExports(db.db, queue, { publish }, notify);
assert.equal(await queue.getPrioritizedCount(), 1);
assert.equal(await queue.getFailedCount(), 0);
await worker.processOne();
assert.equal(await queued!.getState(), 'completed');
assert.equal(claims, 2);
} finally {
await worker.close();
}
await db.pool.query("UPDATE jobs SET state='running',worker_id='lambda-test',started_at=now()-interval '17 minutes' WHERE id=$1", [id]);
await reconcileLambdaExports(db.db, queue, { publish }, notify);
assert.deepEqual((await db.pool.query('SELECT state,error_code FROM jobs WHERE id=$1', [id])).rows[0], { state: 'failed', error_code: 'EXPORT_WORKER_LOST' });
const message = 'Render worker disconnected before finishing the export.';
assert.equal((await db.pool.query('SELECT error_message FROM jobs WHERE id=$1', [id])).rows[0].error_message, message);
assert.equal(events.length, 1);
assert.equal((events[0] as { errorMessage: string }).errorMessage, message);
} finally {
await db.close();
await queue.obliterate({ force: true });
await queue.close();
}
});