lab6: базовый коммит из lab5 (0790599)

Перенесено дерево lab5 целиком: NestJS-приложение (API + worker,
RabbitMQ, outbox, S3), Dockerfile, compose.yaml, infra/{haproxy,minio,
rabbitmq}, стендовые скрипты, scripts/lab4, scripts/lab5,
evidence/lab4, evidence/lab5 и contracts/extensions.openapi.json.

Задание lab6 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,
examples,observability}, tests, compose.example.yaml, infra/otel,
.github/pull_request_template.md.

Адаптации при переносе:
- docker-проект mtusi-lab5 -> mtusi-lab6 и тег образа
  mtusi-messenger:lab6 (compose.yaml, scripts/stop-one.sh, .env.example,
  infra/README.md), чтобы тома и контейнеры не пересекались с lab5;
- Makefile: цели lab5 сохранены целиком (skeleton lab6 не отличается
  от skeleton lab5);
- .env.example: переменные приложения и стенда lab5 + блок lab6
  (OTEL_*) из skeleton.
This commit is contained in:
2026-11-09 16:44:21 +03:00
parent 470d9d6f1e
commit 6889e77ab4
203 changed files with 27707 additions and 13 deletions
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest';
import { retryDelayMs } from './backoff.js';
describe('retryDelayMs', () => {
it('uses equal jitter', () => {
expect(retryDelayMs(1, 1000, 30000, () => 0)).toBe(500);
expect(retryDelayMs(1, 1000, 30000, () => 1)).toBe(1000);
expect(retryDelayMs(10, 1000, 30000, () => 1)).toBe(30000);
});
it('never exceeds the cap and grows monotonically at random 0.5', () => {
const values = Array.from({ length: 6 }, (_, index) =>
retryDelayMs(index + 1, 1000, 30000, () => 0.5),
);
for (const value of values) expect(value).toBeLessThanOrEqual(30000);
for (let index = 1; index < values.length; index += 1)
expect(values[index]).toBeGreaterThanOrEqual(values[index - 1]);
});
});
+14
View File
@@ -0,0 +1,14 @@
/**
* Equal jitter: half of the exponential delay is fixed, half is random. The
* result never exceeds `capMs`, so `max_attempts` bounds both attempts and
* total wait time.
*/
export function retryDelayMs(
attempt: number,
baseMs: number,
capMs: number,
random: () => number = Math.random,
): number {
const exponential = Math.min(capMs, baseMs * 2 ** (attempt - 1));
return Math.floor(exponential * (0.5 + 0.5 * random()));
}
+419
View File
@@ -0,0 +1,419 @@
import {
connect as amqpConnect,
type Channel,
type ChannelModel,
type ConfirmChannel,
type ConsumeMessage,
} from 'amqplib';
import {
Injectable,
Logger,
OnModuleDestroy,
ServiceUnavailableException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomUUID } from 'node:crypto';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import {
assertTopology,
JOB_EXCHANGE,
JOB_QUEUE,
JOB_ROUTING_KEY,
} from './broker.topology.js';
import type { JobMessage } from './job-message.js';
export class BrokerUnavailableError extends ServiceUnavailableException {
constructor() {
super('Broker unavailable');
}
}
export type ConsumeHandler = (
message: ConsumeMessage,
channel: Channel,
) => Promise<void>;
const MAX_RECONNECT_DELAY_MS = 10_000;
@Injectable()
export class BrokerClient implements OnModuleDestroy {
private readonly logger = new Logger(BrokerClient.name);
private readonly url: string;
private readonly deliveryLimit: number;
private readonly publishTimeoutMs: number;
private connection: ChannelModel | undefined;
private confirmChannel: ConfirmChannel | undefined;
private consumeChannel: Channel | undefined;
private consumerTag: string | undefined;
private prefetch = 0;
private handler: ConsumeHandler | undefined;
private connecting: Promise<void> | undefined;
private subscribing: Promise<void> | undefined;
private reconnectTimer: NodeJS.Timeout | undefined;
private subscribeTimer: NodeJS.Timeout | undefined;
private reconnectDelayMs = 1000;
private subscribeDelayMs = 1000;
private closing = false;
// Unroutable messages are returned before their confirm; the map lets the
// return listener reject the exact publish that produced it.
private readonly returned = new Map<string, () => void>();
constructor(
config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.url = config.getOrThrow('BROKER_URL');
this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT');
this.publishTimeoutMs = config.getOrThrow(
'BROKER_PUBLISH_TIMEOUT_MS',
);
}
async publish(message: JobMessage | Buffer): Promise<void> {
const channel = await this.withTimeout(
this.ensureConnected(),
this.publishTimeoutMs,
);
const content = Buffer.isBuffer(message)
? message
: Buffer.from(JSON.stringify(message));
const correlationId = randomUUID();
const options = {
persistent: true,
contentType: 'application/json',
mandatory: true,
correlationId,
...(Buffer.isBuffer(message)
? {}
: {
messageId: message.job_id,
type: message.type,
headers: { 'x-attempt': message.attempt },
}),
};
const { promise, resolve, reject } = Promise.withResolvers<void>();
let settled = false;
const fail = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.returned.delete(correlationId);
this.metrics.increment('broker.publish_failed');
reject(new BrokerUnavailableError());
};
const timer = setTimeout(fail, this.publishTimeoutMs);
this.returned.set(correlationId, fail);
try {
channel.publish(
JOB_EXCHANGE,
JOB_ROUTING_KEY,
content,
options,
(error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.returned.delete(correlationId);
if (error) {
this.metrics.increment('broker.publish_failed');
reject(new BrokerUnavailableError());
return;
}
this.metrics.increment('broker.published');
resolve();
},
);
} catch {
fail();
}
return promise;
}
consume(prefetch: number, handler: ConsumeHandler): void {
this.prefetch = prefetch;
this.handler = handler;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleSubscribe());
}
isConsuming(): boolean {
return this.consumerTag !== undefined;
}
async queueDepth(
queue: string,
): Promise<{ messages: number; consumers: number }> {
const channel = await this.withTimeout(
this.ensureConnected(),
this.publishTimeoutMs,
);
const result = await channel.checkQueue(queue);
return {
messages: result.messageCount,
consumers: result.consumerCount,
};
}
async stopConsuming(): Promise<void> {
clearTimeout(this.subscribeTimer);
this.subscribeTimer = undefined;
const channel = this.consumeChannel;
const tag = this.consumerTag;
this.consumerTag = undefined;
this.consumeChannel = undefined;
this.handler = undefined;
if (channel && tag) {
try {
await channel.cancel(tag);
} catch {
// The channel is already closing; there is nothing to cancel.
}
}
if (channel) {
try {
await channel.close();
} catch {
// Closing an already closed channel is harmless.
}
}
}
async onModuleDestroy(): Promise<void> {
this.closing = true;
clearTimeout(this.reconnectTimer);
clearTimeout(this.subscribeTimer);
this.reconnectTimer = undefined;
this.subscribeTimer = undefined;
for (const reject of this.returned.values()) reject();
this.returned.clear();
await this.stopConsuming();
const connection = this.connection;
this.connection = undefined;
this.confirmChannel = undefined;
if (connection) {
try {
await connection.close();
} catch {
// Shutdown is best effort; channels are already unusable.
}
}
}
private async ensureConnected(): Promise<ConfirmChannel> {
if (this.closing) throw new BrokerUnavailableError();
if (this.confirmChannel) return this.confirmChannel;
if (!this.connecting) {
this.connecting = this.connect()
.then(() => undefined)
.finally(() => {
this.connecting = undefined;
});
}
await this.connecting;
if (!this.confirmChannel) throw new BrokerUnavailableError();
return this.confirmChannel;
}
private async connect(): Promise<void> {
const connection = await amqpConnect(this.url);
connection.on('error', (error: Error) => {
this.metrics.increment('broker.error');
this.logger.warn(`Broker connection error: ${error.message}`);
});
connection.on('close', () => {
if (this.connection !== connection) return;
this.handleClose();
});
try {
const confirm = await connection.createConfirmChannel();
confirm.on('return', (message) => {
const correlationId = message.properties?.correlationId;
if (!correlationId) return;
const reject = this.returned.get(correlationId);
if (!reject) return;
this.returned.delete(correlationId);
this.logger.warn('Broker returned an unroutable job message');
reject();
});
await assertTopology(confirm, this.deliveryLimit);
confirm.on('error', (error: Error) => {
this.metrics.increment('broker.confirm_error');
this.logger.warn(`Broker confirm channel error: ${error.message}`);
});
confirm.on('close', () => this.handleConfirmClose(confirm));
this.connection = connection;
this.confirmChannel = confirm;
this.reconnectDelayMs = 1000;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
this.metrics.increment('broker.connected');
} catch (error) {
if (this.connection === connection) {
this.connection = undefined;
this.confirmChannel = undefined;
}
try {
await connection.close();
} catch {
// The connection is already unusable.
}
throw error;
}
if (this.handler)
void this.subscribe().catch(() => this.scheduleSubscribe());
}
private handleConfirmClose(confirm: ConfirmChannel): void {
if (this.confirmChannel !== confirm) return;
this.metrics.increment('broker.confirm_closed');
for (const reject of this.returned.values()) reject();
this.returned.clear();
this.confirmChannel = undefined;
const connection = this.connection;
if (connection) {
void connection.close().catch(() => this.handleClose());
} else {
this.handleClose();
}
}
private subscribe(): Promise<void> {
if (this.subscribing) return this.subscribing;
const connection = this.connection;
const handler = this.handler;
if (!connection || !handler || this.consumerTag)
return Promise.resolve();
this.subscribing = this.doSubscribe(connection, handler).finally(
() => {
this.subscribing = undefined;
},
);
return this.subscribing;
}
private async doSubscribe(
connection: ChannelModel,
handler: ConsumeHandler,
): Promise<void> {
const channel = await connection.createChannel();
try {
channel.on('error', (error: Error) => {
this.metrics.increment('broker.consumer_error');
this.logger.warn(
`Broker consumer channel error: ${error.message}`,
);
this.handleConsumerClose(channel);
});
channel.on('close', () => this.handleConsumerClose(channel));
await channel.prefetch(this.prefetch);
await assertTopology(channel, this.deliveryLimit);
if (this.handler !== handler) {
await channel.close();
return;
}
const consumer = await channel.consume(
JOB_QUEUE,
(message) => {
if (!message) {
// basic.cancel from the broker: the worker must not stay
// healthy while deaf.
this.handleConsumerClose(channel);
void channel.close().catch(() => undefined);
return;
}
handler(message, channel).catch((error: unknown) => {
this.metrics.increment('broker.handler_error');
this.logger.error(
`Job handler crashed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
// Hold the message briefly instead of burning the
// quorum delivery limit in a tight nack loop.
setTimeout(() => {
try {
channel.nack(message, false, true);
} catch {
// The channel is gone; the broker redelivers after the lease.
}
}, 1000);
});
},
{ noAck: false },
);
this.consumeChannel = channel;
this.consumerTag = consumer.consumerTag;
this.subscribeDelayMs = 1000;
} catch (error) {
try {
await channel.close();
} catch {
// The channel is already unusable.
}
throw error;
}
}
private handleConsumerClose(channel: Channel): void {
if (this.consumeChannel && this.consumeChannel !== channel) return;
this.consumeChannel = undefined;
this.consumerTag = undefined;
if (!this.closing && this.handler) this.scheduleSubscribe();
}
private handleClose(): void {
this.metrics.increment('broker.closed');
clearTimeout(this.subscribeTimer);
this.subscribeTimer = undefined;
this.connection = undefined;
this.confirmChannel = undefined;
this.consumeChannel = undefined;
this.consumerTag = undefined;
for (const reject of this.returned.values()) reject();
this.returned.clear();
if (this.closing) return;
this.scheduleReconnect();
}
private scheduleReconnect(): void {
if (this.closing || this.reconnectTimer) return;
const delay = this.reconnectDelayMs;
this.reconnectDelayMs = Math.min(
this.reconnectDelayMs * 2,
MAX_RECONNECT_DELAY_MS,
);
this.metrics.increment('broker.reconnect_scheduled');
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = undefined;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleReconnect());
}, delay);
}
private scheduleSubscribe(): void {
if (this.closing || !this.handler || this.subscribeTimer) return;
const delay = this.subscribeDelayMs;
this.subscribeDelayMs = Math.min(
this.subscribeDelayMs * 2,
MAX_RECONNECT_DELAY_MS,
);
this.metrics.increment('broker.subscribe_scheduled');
this.subscribeTimer = setTimeout(() => {
this.subscribeTimer = undefined;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleSubscribe());
}, delay);
}
private async withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
const { promise: timeout, reject } = Promise.withResolvers<never>();
const timer = setTimeout(() => reject(new BrokerUnavailableError()), ms);
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}
}
+37
View File
@@ -0,0 +1,37 @@
import type { Channel } from 'amqplib';
export const JOB_EXCHANGE = 'attachments.jobs';
export const JOB_ROUTING_KEY = 'attachment.process.v1';
export const JOB_QUEUE = 'attachments.process';
export const DEAD_LETTER_EXCHANGE = 'attachments.dlx';
export const DEAD_LETTER_QUEUE = 'attachments.process.dlq';
/**
* Idempotent declaration used by both the producer and the consumer on every
* (re)connect: a stand started from an empty volume and a reconnect after a
* broker restart converge to the same durable topology.
*/
export async function assertTopology(
channel: Channel,
deliveryLimit: number,
): Promise<void> {
await channel.assertExchange(DEAD_LETTER_EXCHANGE, 'fanout', {
durable: true,
});
await channel.assertQueue(DEAD_LETTER_QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
await channel.bindQueue(DEAD_LETTER_QUEUE, DEAD_LETTER_EXCHANGE, '');
await channel.assertExchange(JOB_EXCHANGE, 'direct', { durable: true });
await channel.assertQueue(JOB_QUEUE, {
durable: true,
arguments: {
'x-queue-type': 'quorum',
'x-dead-letter-exchange': DEAD_LETTER_EXCHANGE,
'x-delivery-limit': deliveryLimit,
},
});
await channel.bindQueue(JOB_QUEUE, JOB_EXCHANGE, JOB_ROUTING_KEY);
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest';
import { ObjectStorageUnavailableError } from '../storage/object-storage.js';
import { classifyError, JobTimeoutError } from './errors.js';
describe('classifyError', () => {
it('classifies unsupported sharp input as permanent invalid_image', () => {
expect(
classifyError(
new Error('Input buffer contains unsupported image format'),
),
).toEqual({ kind: 'permanent', code: 'invalid_image' });
});
it('classifies the pixel limit as permanent image_too_large', () => {
expect(
classifyError(new Error('Input image exceeds pixel limit')),
).toEqual({ kind: 'permanent', code: 'image_too_large' });
});
it('classifies object storage outages as transient', () => {
expect(classifyError(new ObjectStorageUnavailableError())).toEqual({
kind: 'transient',
code: 'processing_failed',
});
});
it('classifies a job timeout as transient processing_timeout', () => {
expect(classifyError(new JobTimeoutError(10))).toEqual({
kind: 'transient',
code: 'processing_timeout',
});
});
});
+65
View File
@@ -0,0 +1,65 @@
import { SERVER_FAULT } from '../attachments/image/image-decoder.js';
import { InjectedFaultError } from './fault-injector.js';
export class SourceMissingError extends Error {
constructor(message = 'Source object is missing') {
super(message);
this.name = 'SourceMissingError';
}
}
export class SourceMismatchError extends Error {
constructor(message = 'Source object does not match its metadata') {
super(message);
this.name = 'SourceMismatchError';
}
}
export class UnsupportedPipelineError extends Error {
constructor(version: number) {
super(`Unsupported pipeline version: ${version}`);
this.name = 'UnsupportedPipelineError';
}
}
export class JobTimeoutError extends Error {
constructor(seconds: number) {
super(`Job exceeded ${seconds}s deadline`);
this.name = 'JobTimeoutError';
}
}
export type ErrorClass = {
kind: 'permanent' | 'transient';
code: string;
};
const SHARP_INPUT =
/unsupported image format|input buffer|input file|bad seek|premature end|vipsjpeg|vippng|corrupt|truncated|invalid (?:image|pixel)|not a valid image|exceeded.*limit/iu;
/**
* Maps a processing failure to the contract's safe error class. Permanent
* errors are never retried; transient ones are retried until max_attempts,
* after which the job is failed as `retry_exhausted`.
*/
export function classifyError(error: unknown): ErrorClass {
if (error instanceof InjectedFaultError)
return { kind: error.kind, code: 'injected_fault' };
if (error instanceof SourceMissingError)
return { kind: 'permanent', code: 'source_missing' };
if (error instanceof SourceMismatchError)
return { kind: 'permanent', code: 'source_mismatch' };
if (error instanceof UnsupportedPipelineError)
return { kind: 'permanent', code: 'unsupported_pipeline' };
if (error instanceof JobTimeoutError)
return { kind: 'transient', code: 'processing_timeout' };
const message = error instanceof Error ? error.message : String(error);
if (/pixel limit/iu.test(message))
return { kind: 'permanent', code: 'image_too_large' };
if (SERVER_FAULT.test(message))
return { kind: 'transient', code: 'processing_failed' };
if (SHARP_INPUT.test(message))
return { kind: 'permanent', code: 'invalid_image' };
return { kind: 'transient', code: 'processing_failed' };
}
+134
View File
@@ -0,0 +1,134 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { RedisClient } from '../redis/redis.client.js';
export type FaultPoint =
| 'api.after_commit_before_publish'
| 'relay.after_publish_before_mark'
| 'worker.before_side_effect'
| 'worker.after_side_effect'
| 'worker.after_commit_before_ack';
export type FaultTarget = {
attachmentId: string;
pipelineVersion: number;
};
export type FaultKind = 'permanent' | 'transient';
// Node timers overflow above 2^31-1 ms and fire immediately.
const MAX_TIMER_MS = 2_147_483_647;
export class InjectedFaultError extends Error {
constructor(readonly kind: FaultKind) {
super(`Injected ${kind} fault`);
this.name = 'InjectedFaultError';
}
}
/**
* Active only with FAULT_INJECTION_ENABLED=1. The switch is deliberately
* checked before every Redis call so a normal stand never depends on Redis for
* job correctness.
*
* `transient` stays until the key is deleted; every other value is consumed by
* the first point that observes it. Worker points are addressed to one
* attachment and pipeline version; the untargeted key is a fallback.
*/
@Injectable()
export class FaultInjector {
private readonly logger = new Logger(FaultInjector.name);
private readonly enabled: boolean;
constructor(
config: ConfigService<AppConfig>,
private readonly redis: RedisClient,
private readonly metrics: MetricsService,
) {
this.enabled = config.getOrThrow('FAULT_INJECTION_ENABLED') === 1;
}
async point(
name: FaultPoint,
target?: FaultTarget,
signal?: AbortSignal,
): Promise<void> {
if (!this.enabled) return;
const keys = target
? [
`fault:${name}:${target.attachmentId}:${target.pipelineVersion}`,
`fault:${name}`,
]
: [`fault:${name}`];
for (const key of keys) {
let value: string | null;
let deleted: number;
try {
value = await this.redis.get(key);
if (value === null) continue;
if (value === 'transient') {
this.metrics.increment('faults.triggered');
throw new InjectedFaultError('transient');
}
deleted = await this.redis.del(key);
} catch (error) {
if (error instanceof InjectedFaultError) throw error;
this.logger.warn(
`Fault point ${name} could not read Redis: ${error instanceof Error ? error.message : 'unknown error'}`,
);
return;
}
if (deleted !== 1) continue;
// The action is outside the Redis try/catch: an abort or an injected
// fault must reach the job processor, not be logged as an outage.
await this.act(value, signal);
return;
}
}
private async act(value: string, signal?: AbortSignal): Promise<void> {
if (value === 'crash') {
this.metrics.increment('faults.triggered');
// PID 1 in a container namespace may not be killable by SIGKILL;
// exit 137 gives the same observable crash (no graceful shutdown).
process.kill(process.pid, 'SIGKILL');
process.exit(137);
}
if (value === 'permanent') {
this.metrics.increment('faults.triggered');
throw new InjectedFaultError('permanent');
}
if (value.startsWith('delay:')) {
const milliseconds = Number(value.slice('delay:'.length));
if (!Number.isFinite(milliseconds) || milliseconds < 0) return;
this.metrics.increment('faults.triggered');
await this.sleep(Math.min(milliseconds, MAX_TIMER_MS), signal);
}
}
private sleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
if (signal?.aborted)
return Promise.reject(
signal.reason instanceof Error
? signal.reason
: new Error('Aborted'),
);
const { promise, resolve, reject } = Promise.withResolvers<void>();
const timer = setTimeout(() => {
signal?.removeEventListener('abort', cancel);
resolve();
}, milliseconds);
const cancel = (): void => {
clearTimeout(timer);
reject(
signal?.reason instanceof Error
? signal.reason
: new Error('Aborted'),
);
};
signal?.addEventListener('abort', cancel, { once: true });
return promise;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest';
import { fitInside } from './fit-inside.js';
describe('fitInside', () => {
it.each([
[320, 200, 256, [256, 160]],
[1000, 335, 256, [256, 85]],
[100, 50, 256, [100, 50]],
[10000, 1, 256, [256, 1]],
[1, 10000, 256, [1, 256]],
])('fits %ix%i into %i as %j', (width, height, box, expected) => {
expect(fitInside(width, height, box)).toEqual(expected);
});
});
+15
View File
@@ -0,0 +1,15 @@
/**
* Fits `width`x`height` into a `box`x`box` square without upscaling.
* Integer arithmetic keeps the result exact for the contract's fixtures:
* 320x200 -> 256x160, 1000x335 -> 256x85, 10000x1 -> 256x1.
*/
export function fitInside(
width: number,
height: number,
box: number,
): [number, number] {
if (width <= box && height <= box) return [width, height];
if (width >= height)
return [box, Math.max(1, Math.floor((height * box) / width))];
return [Math.max(1, Math.floor((width * box) / height)), box];
}
+47
View File
@@ -0,0 +1,47 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { parseJobMessage } from './job-message.js';
const contract = JSON.parse(
readFileSync(
new URL('../../../contracts/jobs.schema.json', import.meta.url),
'utf8',
),
) as { examples: Record<string, unknown>[] };
const example = contract.examples[0];
describe('parseJobMessage', () => {
it('accepts the contract example', () => {
expect(parseJobMessage(Buffer.from(JSON.stringify(example)))).toEqual(
example,
);
});
it('rejects an extra property', () => {
expect(
parseJobMessage(
Buffer.from(JSON.stringify({ ...example, extra: true })),
),
).toBeUndefined();
});
it('rejects attempt 0', () => {
expect(
parseJobMessage(
Buffer.from(JSON.stringify({ ...example, attempt: 0 })),
),
).toBeUndefined();
});
it('rejects a wrong type', () => {
expect(
parseJobMessage(
Buffer.from(JSON.stringify({ ...example, type: 'other' })),
),
).toBeUndefined();
});
it('rejects non-JSON', () => {
expect(parseJobMessage(Buffer.from('not-json'))).toBeUndefined();
});
});
+53
View File
@@ -0,0 +1,53 @@
import { z } from 'zod';
export const JOB_TYPE = 'attachment.process.v1';
/**
* Mirrors contracts/jobs.schema.json. The broker message carries identifiers
* and scheduling data only: no bytes, URLs, file names or credentials.
*/
export const jobMessageSchema = z.strictObject({
schema_version: z.literal(1),
job_id: z.uuid(),
type: z.literal(JOB_TYPE),
attachment_id: z.uuid(),
pipeline_version: z.number().int().min(1),
attempt: z.number().int().min(1),
created_at: z.iso.datetime(),
traceparent: z
.string()
.regex(/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/u)
.optional(),
tracestate: z.string().max(512).optional(),
});
export type JobMessage = z.infer<typeof jobMessageSchema>;
export function buildJobMessage(job: {
job_id: string;
attachment_id: string;
pipeline_version: number;
attempt: number;
created_at: Date;
}): JobMessage {
return {
schema_version: 1,
job_id: job.job_id,
type: JOB_TYPE,
attachment_id: job.attachment_id,
pipeline_version: job.pipeline_version,
attempt: job.attempt,
created_at: job.created_at.toISOString(),
};
}
export function parseJobMessage(content: Buffer): JobMessage | undefined {
let value: unknown;
try {
value = JSON.parse(content.toString('utf8'));
} catch {
return undefined;
}
const parsed = jobMessageSchema.safeParse(value);
return parsed.success ? parsed.data : undefined;
}
+234
View File
@@ -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);
});
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module.js';
import { MetricsModule } from '../metrics/metrics.module.js';
import { RedisModule } from '../redis/redis.module.js';
import { BrokerClient } from './broker.client.js';
import { FaultInjector } from './fault-injector.js';
import { JobsRepository } from './jobs.repository.js';
@Module({
imports: [DatabaseModule, RedisModule, MetricsModule],
providers: [BrokerClient, JobsRepository, FaultInjector],
exports: [BrokerClient, JobsRepository, FaultInjector],
})
export class JobsModule {}
File diff suppressed because it is too large Load Diff
+110
View File
@@ -0,0 +1,110 @@
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnModuleDestroy,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { BrokerClient } from './broker.client.js';
import { FaultInjector } from './fault-injector.js';
import { JobsRepository } from './jobs.repository.js';
const BATCH_SIZE = 20;
/**
* Runs in the API and worker processes. `publishPending` holds one transaction around
* the broker confirms and the `published_at` update; a crash before the mark
* rolls the transaction back and republishes the same message after restart.
* That duplicate is expected: the worker fences it on job status.
*/
@Injectable()
export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
private readonly logger = new Logger(OutboxRelay.name);
private timer: NodeJS.Timeout | undefined;
private running = false;
private again = false;
private current: Promise<void> | undefined;
private failing = false;
private retryAt = 0;
private retryDelayMs = 1000;
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly repository: JobsRepository,
private readonly broker: BrokerClient,
private readonly faults: FaultInjector,
private readonly metrics: MetricsService,
) {}
onApplicationBootstrap(): void {
const interval = this.config.getOrThrow('OUTBOX_POLL_INTERVAL_MS');
this.timer = setInterval(() => this.kick(), interval);
this.timer.unref();
this.kick();
}
async onModuleDestroy(): Promise<void> {
clearInterval(this.timer);
this.timer = undefined;
await this.current;
}
kick(): void {
if (Date.now() < this.retryAt) return;
if (this.running) {
this.again = true;
return;
}
this.running = true;
this.current = this.drain()
.catch((error: unknown) => {
this.metrics.increment('outbox.publish_failed');
this.retryAt = Date.now() + this.retryDelayMs;
this.retryDelayMs = Math.min(this.retryDelayMs * 2, 10_000);
if (!this.failing) {
this.failing = true;
this.logger.warn(
`Outbox publish failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
})
.finally(() => {
this.running = false;
this.current = undefined;
if (this.again) {
this.again = false;
this.kick();
}
});
}
private async drain(): Promise<void> {
const budgetMs = Math.max(
1000,
Math.floor(
this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS') / 2,
),
);
const started = Date.now();
const published = await this.repository.publishPending(
BATCH_SIZE,
async (message) => {
if (Date.now() - started > budgetMs)
throw new Error('outbox batch deadline exceeded');
await this.broker.publish(message);
},
() => this.faults.point('relay.after_publish_before_mark'),
);
if (published > 0) {
this.metrics.add('outbox.published', published);
this.retryAt = 0;
this.retryDelayMs = 1000;
if (this.failing) {
this.failing = false;
this.logger.log('Outbox publishing recovered');
}
}
}
}