Files
mtusi2026lab7/app/src/jobs/jobs.cli.ts
T

259 lines
7.4 KiB
TypeScript

import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { WorkerConfigModule } from '../config/worker-config.module.js';
import type { AppConfig } from '../config/app-config.schema.js';
import { DatabaseModule } from '../database/database.module.js';
import { MetricsModule } from '../metrics/metrics.module.js';
import {
RuntimeSecretsStore,
type SecretRole,
} from '../openbao/runtime-secrets.service.js';
import { SecurityModule, registerBootstrappedSecurity } from '../security/security.module.js';
import { TlsMaterialManager } from '../security/tls-material.js';
import { ObjectStorage } from '../storage/object-storage.js';
import { StorageModule } from '../storage/storage.module.js';
import { BrokerClient } from './broker.client.js';
import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js';
import { JobsModule } from './jobs.module.js';
import { JobsRepository } from './jobs.repository.js';
@Module({
imports: [
WorkerConfigModule,
SecurityModule,
DatabaseModule,
MetricsModule,
StorageModule,
JobsModule,
],
})
class JobsCliModule {}
const SUPPORTED_PIPELINES = [1, 2];
function option(args: string[], name: string): string | undefined {
const index = args.indexOf(name);
if (index === -1) return undefined;
return args[index + 1];
}
async function readStdin(): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin)
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return Buffer.concat(chunks).toString('utf8');
}
async function s3State(
storage: ObjectStorage,
key: string,
): Promise<{
exists: boolean;
etag: string | null;
last_modified: string | null;
}> {
const head = await storage.head(key);
return head
? {
exists: true,
etag: head.etag ?? null,
last_modified: head.lastModified?.toISOString() ?? null,
}
: { exists: false, etag: null, last_modified: null };
}
function detectCliRole(raw: Record<string, unknown>): SecretRole {
const certRole = String(raw.BAO_CERT_ROLE ?? raw.BAO_AUTH_ROLE ?? '');
const brokerRole = String(raw.BROKER_ROLE ?? '');
if (certRole.includes('worker') || brokerRole === 'consumer') return 'worker';
return 'api';
}
async function main(): Promise<number> {
const args = process.argv.slice(2);
const command = args[0];
const rawEnv = process.env as Record<string, unknown>;
const role = detectCliRole(rawEnv);
const tlsMaterial = TlsMaterialManager.initFromEnv('cli', rawEnv);
const secretsStore = await RuntimeSecretsStore.bootstrap(
role,
tlsMaterial,
rawEnv,
undefined,
{ background: false },
);
registerBootstrappedSecurity(tlsMaterial, secretsStore);
const app = await NestFactory.createApplicationContext(JobsCliModule, {
logger: false,
});
try {
const repository = app.get(JobsRepository);
const storage = app.get(ObjectStorage);
const broker = app.get(BrokerClient);
const config = app.get(ConfigService<AppConfig>);
if (command === 'status') {
const attachmentId = args[1];
if (!attachmentId) return usage();
const status = await repository.statusOf(attachmentId);
if (!status) {
console.log(JSON.stringify({ error: 'attachment_not_found' }));
return 1;
}
const variants = [];
for (const variant of status.variants) {
variants.push({
pipeline_version: variant.pipeline_version,
variant: variant.variant,
sha256: variant.sha256,
size_bytes: Number(variant.size_bytes),
width: variant.width,
height: variant.height,
object_key: variant.object_key,
s3: await s3State(storage, variant.object_key),
});
}
console.log(
JSON.stringify({
attachment: {
id: status.attachment.id,
status: status.attachment.status,
error_code: status.attachment.error_code,
ready_pipeline_version:
status.attachment.ready_pipeline_version,
staging_present: status.attachment.staging_key !== null,
},
jobs: status.jobs.map((job) => ({
job_id: job.job_id,
pipeline_version: job.pipeline_version,
status: job.status,
attempt: job.attempt,
max_attempts: job.max_attempts,
last_error_code: job.last_error_code,
})),
variants,
original: await s3State(
storage,
status.attachment.object_key,
),
events: status.events.map((event) => ({
job_id: event.job_id,
event: event.event,
attempt: event.attempt,
detail: event.detail,
created_at: event.created_at.toISOString(),
})),
outbox: status.outbox,
}),
);
return 0;
}
if (command === 'find-by-chat') {
const chatId = args[1];
if (!chatId) return usage();
console.log(JSON.stringify(await repository.findByChat(chatId)));
return 0;
}
if (command === 'failed') {
console.log(JSON.stringify(await repository.failedJobs()));
return 0;
}
if (command === 'replay') {
const attachmentId = args[1];
const reason = option(args, '--reason') ?? 'operator replay';
const operator =
option(args, '--operator') ?? process.env.USER ?? 'operator';
if (!attachmentId) return usage();
const candidate = await repository.replayCandidate(attachmentId);
let sourceAvailable = false;
if (candidate) {
sourceAvailable =
candidate.staging_key !== null ||
(await storage.head(storage.objectKey(attachmentId))) !== null;
}
const result = await repository.replay(attachmentId, {
reason,
operator,
maxAttempts: config.getOrThrow('JOB_MAX_ATTEMPTS'),
sourceAvailable,
expectedStagingKey: candidate?.staging_key ?? null,
});
console.log(JSON.stringify(result));
return result.kind === 'replayed' ? 0 : 3;
}
if (command === 'reprocess') {
const attachmentId = args[1];
const rawVersion = option(args, '--pipeline-version');
const version = Number(rawVersion);
if (
!attachmentId ||
rawVersion === undefined ||
!SUPPORTED_PIPELINES.includes(version)
)
return usage();
const result = await repository.reprocess(attachmentId, version, {
reason: option(args, '--reason') ?? 'reprocess',
operator:
option(args, '--operator') ??
process.env.USER ??
'operator',
maxAttempts: config.getOrThrow('JOB_MAX_ATTEMPTS'),
});
console.log(JSON.stringify(result));
return result.kind === 'created' ? 0 : 3;
}
if (command === 'publish-raw') {
if (config.getOrThrow('FAULT_INJECTION_ENABLED') !== 1) {
console.log(
JSON.stringify({ refused: 'fault_injection_disabled' }),
);
return 3;
}
const text = await readStdin();
const lines = text.split(/\r?\n/u).filter((line) => line !== '');
for (const line of lines) await broker.publish(Buffer.from(line));
console.log(JSON.stringify({ published: lines.length }));
return 0;
}
if (command === 'queues') {
console.log(
JSON.stringify({
process: await broker.queueDepth(JOB_QUEUE),
dlq: await broker.queueDepth(DEAD_LETTER_QUEUE),
}),
);
return 0;
}
return usage();
} finally {
await app.close();
}
}
function usage(): number {
console.error(
'usage: jobs.cli.js status <id> | find-by-chat <chat> | failed | replay <id> --reason <text> [--operator <name>] | reprocess <id> --pipeline-version <n> [--reason <text>] | publish-raw | queues',
);
return 2;
}
main()
.then((code) => process.exit(code))
.catch((error: unknown) => {
console.log(
JSON.stringify({
error: error instanceof Error ? error.message : 'unknown error',
}),
);
process.exit(1);
});