lab7: базовый коммит из lab6 (bf06167)
Перенесена кодовая база и инфраструктура lab6: NestJS-приложение (API +
worker, RabbitMQ, outbox, S3, OpenTelemetry), Dockerfile, compose.yaml,
infra/{grafana,haproxy,loki,minio,otel/collector.yaml,prometheus,
rabbitmq,tempo}, docs/runbooks, стендовые скрипты, scripts/lab{4,5,6} и
contracts/extensions.openapi.json.
Задание lab7 оставлено своим: README, REPORT, COURSE, CONTRIBUTING,
MAINTAINERS, lab.json, contracts/{openapi,infrastructure,jobs.schema,
attachment-states,examples,observability,trust-matrix,README},
security/THREAT_MODEL.md, tests (включая security.py), compose.example.yaml,
infra/{openbao,otel}/README.md, .github/pull_request_template.md.
Не переносились старые evidence/lab4..lab6 (18 МБ трека lab6) и
неотслеживаемый docs/lab6.html.
Адаптации при переносе:
- docker-проект mtusi-lab6 -> mtusi-lab7, тег образа mtusi-messenger:lab7
и папка Grafana Messenger lab7 (compose.yaml, scripts/stop-one.sh,
.env.example, infra/README.md, infra/grafana/provisioning/dashboards),
чтобы тома и контейнеры не пересекались с lab6;
- Makefile: сохранены BASE_URL=https://localhost:8443 и цель test-security
из skeleton lab7, добавлены стендовые и проверочные цели lab6;
- .env.example: рабочие переменные приложения и стенда lab6 + блок
переменных lab7 (PUBLIC_BASE_URL, TLS_*, BAO_*, ARGON2_*) из skeleton.
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { AppConfigModule } from '../config/app-config.module.js';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { StorageModule } from '../storage/storage.module.js';
|
||||
import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js';
|
||||
import { BrokerClient } from './broker.client.js';
|
||||
import { JobsModule } from './jobs.module.js';
|
||||
import { JobsRepository } from './jobs.repository.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
DatabaseModule,
|
||||
RedisModule,
|
||||
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 };
|
||||
}
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const args = process.argv.slice(2);
|
||||
const command = args[0];
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user