lab5: брокер RabbitMQ, worker и асинхронная обработка

This commit is contained in:
2026-11-05 01:17:58 +03:00
parent 1982bdb690
commit d19824f546
44 changed files with 3486 additions and 150 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()));
}
+259
View File
@@ -0,0 +1,259 @@
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 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 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 reconnectTimer: NodeJS.Timeout | undefined;
private reconnectDelayMs = 1000;
private closing = false;
constructor(
config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.url = config.getOrThrow('BROKER_URL');
this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT');
}
async publish(message: JobMessage | Buffer): Promise<void> {
const channel = await this.ensureConnected();
const content = Buffer.isBuffer(message)
? message
: Buffer.from(JSON.stringify(message));
const options = Buffer.isBuffer(message)
? { persistent: true, contentType: 'application/json' }
: {
persistent: true,
contentType: 'application/json',
messageId: message.job_id,
type: message.type,
headers: { 'x-attempt': message.attempt },
};
const { promise, resolve, reject } = Promise.withResolvers<void>();
try {
channel.publish(
JOB_EXCHANGE,
JOB_ROUTING_KEY,
content,
options,
(error) => {
if (error) {
this.metrics.increment('broker.publish_failed');
reject(new BrokerUnavailableError());
return;
}
this.metrics.increment('broker.published');
resolve();
},
);
} catch {
this.metrics.increment('broker.publish_failed');
reject(new BrokerUnavailableError());
}
return promise;
}
consume(prefetch: number, handler: ConsumeHandler): void {
this.prefetch = prefetch;
this.handler = handler;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleReconnect());
}
isConsuming(): boolean {
return this.consumerTag !== undefined;
}
async queueDepth(
queue: string,
): Promise<{ messages: number; consumers: number }> {
const channel = await this.ensureConnected();
const result = await channel.checkQueue(queue);
return {
messages: result.messageCount,
consumers: result.consumerCount,
};
}
async stopConsuming(): Promise<void> {
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);
this.reconnectTimer = undefined;
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();
});
const confirm = await connection.createConfirmChannel();
await assertTopology(confirm, this.deliveryLimit);
this.connection = connection;
this.confirmChannel = confirm;
this.reconnectDelayMs = 1000;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
this.metrics.increment('broker.connected');
if (this.handler) await this.subscribe();
}
private async subscribe(): Promise<void> {
const connection = this.connection;
const handler = this.handler;
if (!connection || !handler || this.consumerTag) return;
const channel = await connection.createChannel();
channel.on('error', (error: Error) => {
this.metrics.increment('broker.consumer_error');
this.logger.warn(`Broker consumer channel error: ${error.message}`);
});
channel.on('close', () => {
if (this.consumeChannel !== channel) return;
this.consumeChannel = undefined;
this.consumerTag = undefined;
});
await channel.prefetch(this.prefetch);
await assertTopology(channel, this.deliveryLimit);
const consumer = await channel.consume(
JOB_QUEUE,
(message) => {
if (!message) 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'}`,
);
try {
channel.nack(message, false, true);
} catch {
// The channel is gone; the broker redelivers after the lease.
}
});
},
{ noAck: false },
);
this.consumeChannel = channel;
this.consumerTag = consumer.consumerTag;
}
private handleClose(): void {
this.metrics.increment('broker.closed');
this.connection = undefined;
this.confirmChannel = undefined;
this.consumeChannel = undefined;
this.consumerTag = undefined;
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().catch(() => this.scheduleReconnect());
}, delay);
}
}
+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' };
}
+131
View File
@@ -0,0 +1,131 @@
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';
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(milliseconds, 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 = true;
if (candidate && candidate.staging_key === null) {
const original = await storage.head(
storage.objectKey(attachmentId),
);
sourceAvailable = original !== null;
}
const result = await repository.replay(attachmentId, {
reason,
operator,
maxAttempts: config.getOrThrow('JOB_MAX_ATTEMPTS'),
sourceAvailable,
});
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 {}
+910
View File
@@ -0,0 +1,910 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import type { PoolClient } from 'pg';
import type { AttachmentRow, VariantRow } from '../attachments/attachment.js';
import { DatabaseClient } from '../database/database.client.js';
import { buildJobMessage, type JobMessage } from './job-message.js';
export type JobStatus =
'queued' | 'processing' | 'succeeded' | 'failed' | 'superseded';
export type AttachmentJobRow = {
job_id: string;
attachment_id: string;
pipeline_version: number;
status: JobStatus;
attempt: number;
max_attempts: number;
next_attempt_at: Date;
lease_owner: string | null;
lease_token: string | null;
lease_until: Date | null;
last_error_code: string | null;
created_at: Date;
updated_at: Date;
finished_at: Date | null;
};
export type VariantWrite = {
name: 'thumbnail' | 'crop' | 'optimized';
objectKey: string;
contentType: 'image/jpeg' | 'image/png' | 'image/webp';
sizeBytes: number;
width: number;
height: number;
sha256: string;
};
export type ClaimResult =
| { kind: 'skip'; reason: string }
| {
kind: 'claimed';
job: AttachmentJobRow;
attachment: AttachmentRow;
leaseToken: string;
};
export type CommitFailureResult = 'retry' | 'failed' | 'lease_lost';
export type CommitSuccessResult = 'succeeded' | 'superseded' | 'lease_lost';
export type ReplayResult =
| { kind: 'replayed'; job_id: string; attempt: number }
| { kind: 'refused'; reason: string; job_id?: string };
export type ReprocessResult =
| { kind: 'created'; job_id: string }
| { kind: 'refused'; reason: string; job_id?: string };
type AttachmentJobExtra = AttachmentJobRow & {
attachment_status: AttachmentRow['status'];
ready_pipeline_version: number | null;
};
@Injectable()
export class JobsRepository {
constructor(private readonly database: DatabaseClient) {}
async acceptUpload(
attachmentId: string,
fields: {
sizeBytes: number;
sha256: string;
width: number;
height: number;
},
pipelineVersion: number,
maxAttempts: number,
): Promise<AttachmentRow | undefined> {
return this.database.withTransaction(async (client) => {
const accepted = await client.query<AttachmentRow>(
`UPDATE attachments
SET status = 'queued', size_bytes = $2, sha256 = $3,
width = $4, height = $5, expires_at = NULL, updated_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING *`,
[
attachmentId,
fields.sizeBytes,
fields.sha256,
fields.width,
fields.height,
],
);
const attachment = accepted.rows[0];
if (!attachment) return undefined;
const jobId = randomUUID();
const created = await client.query<AttachmentJobRow>(
`INSERT INTO attachment_jobs
(job_id, attachment_id, pipeline_version, status, attempt,
max_attempts, next_attempt_at)
VALUES ($1, $2, $3, 'queued', 1, $4, now())
RETURNING *`,
[jobId, attachmentId, pipelineVersion, maxAttempts],
);
const job = created.rows[0];
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb, now())`,
[
job.job_id,
JSON.stringify(
buildJobMessage({
...job,
created_at: job.created_at,
}),
),
],
);
await this.event(client, job.job_id, 'created', 1, {});
return attachment;
});
}
async claim(
message: JobMessage,
workerId: string,
leaseSeconds: number,
): Promise<ClaimResult> {
return this.database.withTransaction(async (client) => {
const found = await client.query<AttachmentJobExtra>(
`SELECT j.*, a.status AS attachment_status,
a.ready_pipeline_version
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.job_id = $1
FOR UPDATE OF j, a`,
[message.job_id],
);
const job = found.rows[0];
if (!job) return { kind: 'skip', reason: 'unknown_job' };
if (
job.attachment_id !== message.attachment_id ||
job.pipeline_version !== message.pipeline_version
)
return this.skip(client, message, 'mismatch');
if (job.status === 'succeeded')
return this.skip(client, message, 'already_succeeded');
if (job.status === 'failed')
return this.skip(client, message, 'already_failed');
if (job.status === 'superseded')
return this.skip(client, message, 'superseded');
if (job.status === 'processing')
return this.skip(client, message, 'in_progress');
if (job.attempt !== message.attempt)
return this.skip(client, message, 'stale_attempt');
if (new Date(job.next_attempt_at).getTime() > Date.now())
return this.skip(client, message, 'not_due');
if (
job.ready_pipeline_version !== null &&
job.ready_pipeline_version > job.pipeline_version
) {
await client.query(
`UPDATE attachment_jobs
SET status = 'superseded', updated_at = now(), finished_at = now()
WHERE job_id = $1`,
[job.job_id],
);
await this.event(
client,
job.job_id,
'superseded',
job.attempt,
{
ready_pipeline_version: job.ready_pipeline_version,
},
);
return this.skip(client, message, 'superseded');
}
const leaseToken = randomUUID();
const claimed = await client.query<AttachmentJobRow>(
`UPDATE attachment_jobs
SET status = 'processing', lease_owner = $2, lease_token = $3,
lease_until = now() + make_interval(secs => $4::double precision),
updated_at = now()
WHERE job_id = $1
RETURNING *`,
[job.job_id, workerId, leaseToken, leaseSeconds],
);
const attachment = await client.query<AttachmentRow>(
`SELECT * FROM attachments WHERE id = $1`,
[job.attachment_id],
);
await client.query(
`UPDATE attachments SET status = 'processing', updated_at = now()
WHERE id = $1 AND status = 'queued'`,
[job.attachment_id],
);
await this.event(
client,
job.job_id,
'claimed',
claimed.rows[0].attempt,
{ lease_owner: workerId },
);
return {
kind: 'claimed',
job: claimed.rows[0],
attachment: attachment.rows[0],
leaseToken,
};
});
}
async extendLease(
jobId: string,
token: string,
leaseSeconds: number,
): Promise<boolean> {
const result = await this.database.query(
'jobs.extend_lease',
`UPDATE attachment_jobs
SET lease_until = now() + make_interval(secs => $3::double precision),
updated_at = now()
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'`,
[jobId, token, leaseSeconds],
);
return result.rowCount === 1;
}
async commitSuccess(
jobId: string,
token: string,
variants: VariantWrite[],
): Promise<CommitSuccessResult> {
return this.database.withTransaction(async (client) => {
const succeeded = await client.query<AttachmentJobRow>(
`UPDATE attachment_jobs
SET status = 'succeeded', lease_owner = NULL, lease_token = NULL,
lease_until = NULL, updated_at = now(), finished_at = now()
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
RETURNING *`,
[jobId, token],
);
const job = succeeded.rows[0];
if (!job) return 'lease_lost';
const attachment = await client.query<AttachmentRow>(
`SELECT * FROM attachments WHERE id = $1 FOR UPDATE`,
[job.attachment_id],
);
const row = attachment.rows[0];
if (
row.ready_pipeline_version !== null &&
row.ready_pipeline_version > job.pipeline_version
) {
await client.query(
`UPDATE attachment_jobs
SET status = 'superseded', updated_at = now()
WHERE job_id = $1`,
[job.job_id],
);
await this.event(
client,
job.job_id,
'superseded',
job.attempt,
{
ready_pipeline_version: row.ready_pipeline_version,
},
);
return 'superseded';
}
for (const variant of variants) {
await client.query(
`INSERT INTO attachment_variants
(attachment_id, pipeline_version, variant, object_key,
content_type, size_bytes, width, height, sha256, job_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (attachment_id, pipeline_version, variant)
DO UPDATE SET object_key = EXCLUDED.object_key,
content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
job_id = EXCLUDED.job_id`,
[
job.attachment_id,
job.pipeline_version,
variant.name,
variant.objectKey,
variant.contentType,
variant.sizeBytes,
variant.width,
variant.height,
variant.sha256,
job.job_id,
],
);
}
await client.query(
`UPDATE attachments
SET status = 'ready', ready_pipeline_version = $2,
error_code = NULL, updated_at = now()
WHERE id = $1`,
[job.attachment_id, job.pipeline_version],
);
await this.event(client, job.job_id, 'succeeded', job.attempt, {});
return 'succeeded';
});
}
async commitFailure(
jobId: string,
token: string,
failure: { kind: 'permanent' | 'transient'; code: string },
delayMs: number,
): Promise<CommitFailureResult> {
return this.database.withTransaction(async (client) => {
const found = await client.query<AttachmentJobRow>(
`SELECT * FROM attachment_jobs
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
FOR UPDATE`,
[jobId, token],
);
const job = found.rows[0];
if (!job) return 'lease_lost';
const finalCode =
failure.kind === 'permanent' || job.attempt >= job.max_attempts
? failure.kind === 'transient'
? 'retry_exhausted'
: failure.code
: failure.code;
if (
failure.kind === 'permanent' ||
job.attempt >= job.max_attempts
) {
await client.query(
`UPDATE attachment_jobs
SET status = 'failed', last_error_code = $2,
lease_owner = NULL, lease_token = NULL, lease_until = NULL,
updated_at = now(), finished_at = now()
WHERE job_id = $1`,
[job.job_id, finalCode],
);
await client.query(
`UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = now()
WHERE id = $1 AND status <> 'ready'`,
[job.attachment_id, finalCode],
);
await this.event(client, job.job_id, 'failed', job.attempt, {
code: finalCode,
cause: failure.code,
});
return 'failed';
}
const nextAttempt = job.attempt + 1;
await client.query(
`UPDATE attachment_jobs
SET status = 'queued', attempt = $2,
next_attempt_at = now() + make_interval(secs => $3::double precision),
lease_owner = NULL, lease_token = NULL, lease_until = NULL,
last_error_code = $4, updated_at = now()
WHERE job_id = $1`,
[job.job_id, nextAttempt, delayMs / 1000, failure.code],
);
await client.query(
`UPDATE attachments SET status = 'queued', updated_at = now()
WHERE id = $1 AND status = 'processing'`,
[job.attachment_id],
);
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb,
now() + make_interval(secs => $3::double precision))`,
[
job.job_id,
JSON.stringify(
buildJobMessage({ ...job, attempt: nextAttempt }),
),
delayMs / 1000,
],
);
await this.event(
client,
job.job_id,
'retry_scheduled',
nextAttempt,
{
code: failure.code,
delay_ms: delayMs,
},
);
return 'retry';
});
}
async reapExpiredLeases(
limit: number,
delayFor: (attempt: number) => number,
): Promise<number> {
return this.database.withTransaction(async (client) => {
const expired = await client.query<AttachmentJobExtra>(
`SELECT j.*, a.status AS attachment_status,
a.ready_pipeline_version
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.status = 'processing' AND j.lease_until < now()
ORDER BY j.lease_until
LIMIT $1
FOR UPDATE OF j, a`,
[limit],
);
for (const job of expired.rows) {
if (job.attempt >= job.max_attempts) {
await client.query(
`UPDATE attachment_jobs
SET status = 'failed', last_error_code = 'retry_exhausted',
lease_owner = NULL, lease_token = NULL,
lease_until = NULL, updated_at = now(),
finished_at = now()
WHERE job_id = $1`,
[job.job_id],
);
await client.query(
`UPDATE attachments
SET status = 'failed', error_code = 'retry_exhausted',
updated_at = now()
WHERE id = $1 AND status <> 'ready'`,
[job.attachment_id],
);
await this.event(
client,
job.job_id,
'lease_expired',
job.attempt,
{
lease_owner: job.lease_owner,
code: 'retry_exhausted',
},
);
continue;
}
const nextAttempt = job.attempt + 1;
const delayMs = delayFor(job.attempt);
await client.query(
`UPDATE attachment_jobs
SET status = 'queued', attempt = $2,
next_attempt_at = now() + make_interval(secs => $3::double precision),
lease_owner = NULL, lease_token = NULL,
lease_until = NULL, last_error_code = 'lease_expired',
updated_at = now()
WHERE job_id = $1`,
[job.job_id, nextAttempt, delayMs / 1000],
);
await client.query(
`UPDATE attachments SET status = 'queued', updated_at = now()
WHERE id = $1 AND status = 'processing'`,
[job.attachment_id],
);
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb,
now() + make_interval(secs => $3::double precision))`,
[
job.job_id,
JSON.stringify(
buildJobMessage({ ...job, attempt: nextAttempt }),
),
delayMs / 1000,
],
);
await this.event(
client,
job.job_id,
'lease_expired',
job.attempt,
{ lease_owner: job.lease_owner },
);
}
return expired.rows.length;
});
}
async publishPending(
limit: number,
publish: (message: JobMessage) => Promise<void>,
afterPublish: () => Promise<void>,
): Promise<number> {
return this.database.withTransaction(async (client) => {
const pending = await client.query<{
id: string;
payload: JobMessage;
}>(
`SELECT id, payload FROM job_outbox
WHERE published_at IS NULL AND available_at <= now()
ORDER BY available_at, id
LIMIT $1
FOR UPDATE SKIP LOCKED`,
[limit],
);
const published: string[] = [];
let failure: unknown;
for (const row of pending.rows) {
try {
await publish(row.payload);
published.push(row.id);
} catch (error) {
failure = error;
break;
}
}
if (published.length === 0) {
if (failure) throw failure;
return 0;
}
await afterPublish();
await client.query(
`UPDATE job_outbox SET published_at = now() WHERE id = ANY($1::bigint[])`,
[published],
);
if (failure) throw failure;
return published.length;
});
}
async variantsFor(
attachmentId: string,
pipelineVersion: number,
): Promise<VariantRow[]> {
const result = await this.database.query<VariantRow>(
'jobs.variants',
`SELECT * FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY array_position(ARRAY['thumbnail','crop','optimized']::text[], variant)`,
[attachmentId, pipelineVersion],
);
return result.rows;
}
async stagingCleanupCandidates(
retentionSeconds: number,
limit: number,
): Promise<{ id: string; staging_key: string }[]> {
const result = await this.database.query<{
id: string;
staging_key: string;
}>(
'jobs.staging_candidates',
`SELECT id, staging_key FROM attachments
WHERE staging_key IS NOT NULL
AND ((status = 'ready' AND updated_at < now() - interval '1 minute')
OR (status = 'failed' AND updated_at < now() - make_interval(secs => $1::double precision)))
ORDER BY updated_at
LIMIT $2`,
[retentionSeconds, limit],
);
return result.rows;
}
async clearStaging(id: string, key: string): Promise<boolean> {
return this.database.withTransaction(async (client) => {
const cleared = await client.query(
`UPDATE attachments SET staging_key = NULL, updated_at = now()
WHERE id = $1 AND staging_key = $2 AND status IN ('ready','failed')`,
[id, key],
);
if (cleared.rowCount !== 1) return false;
await client.query(
`INSERT INTO job_events (job_id, event, attempt, detail)
SELECT job_id, 'staging_deleted', attempt, $2::jsonb
FROM attachment_jobs
WHERE attachment_id = $1
ORDER BY created_at DESC
LIMIT 1`,
[id, JSON.stringify({ staging_key: key })],
);
return true;
});
}
async statusOf(attachmentId: string): Promise<
| {
attachment: AttachmentRow;
jobs: AttachmentJobRow[];
variants: VariantRow[];
events: {
job_id: string;
event: string;
attempt: number;
detail: unknown;
created_at: Date;
}[];
outbox: { pending: number; published: number };
}
| undefined
> {
const attachment = await this.database.query<AttachmentRow>(
'jobs.status_attachment',
`SELECT * FROM attachments WHERE id = $1`,
[attachmentId],
);
if (!attachment.rows[0]) return undefined;
const jobs = await this.database.query<AttachmentJobRow>(
'jobs.status_jobs',
`SELECT * FROM attachment_jobs WHERE attachment_id = $1 ORDER BY created_at`,
[attachmentId],
);
const variants = await this.database.query<VariantRow>(
'jobs.status_variants',
`SELECT * FROM attachment_variants WHERE attachment_id = $1
ORDER BY pipeline_version,
array_position(ARRAY['thumbnail','crop','optimized']::text[], variant)`,
[attachmentId],
);
const events = await this.database.query<{
job_id: string;
event: string;
attempt: number;
detail: unknown;
created_at: Date;
}>(
'jobs.status_events',
`SELECT e.job_id, e.event, e.attempt, e.detail, e.created_at
FROM job_events e
JOIN attachment_jobs j ON j.job_id = e.job_id
WHERE j.attachment_id = $1
ORDER BY e.id`,
[attachmentId],
);
const outbox = await this.database.query<{
pending: string;
published: string;
}>(
'jobs.status_outbox',
`SELECT count(*) FILTER (WHERE o.published_at IS NULL) AS pending,
count(*) FILTER (WHERE o.published_at IS NOT NULL) AS published
FROM job_outbox o
JOIN attachment_jobs j ON j.job_id = o.job_id
WHERE j.attachment_id = $1`,
[attachmentId],
);
return {
attachment: attachment.rows[0],
jobs: jobs.rows,
variants: variants.rows,
events: events.rows,
outbox: {
pending: Number(outbox.rows[0]?.pending ?? 0),
published: Number(outbox.rows[0]?.published ?? 0),
},
};
}
async findByChat(
chatId: string,
): Promise<{ id: string; status: string; created_at: Date }[]> {
const result = await this.database.query<{
id: string;
status: string;
created_at: Date;
}>(
'jobs.find_by_chat',
`SELECT id, status, created_at FROM attachments
WHERE chat_id = $1 ORDER BY created_at`,
[chatId],
);
return result.rows;
}
async failedJobs(): Promise<
{
attachment_id: string;
job_id: string;
pipeline_version: number;
attempt: number;
last_error_code: string | null;
updated_at: Date;
}[]
> {
const result = await this.database.query<{
attachment_id: string;
job_id: string;
pipeline_version: number;
attempt: number;
last_error_code: string | null;
updated_at: Date;
}>(
'jobs.failed',
`SELECT attachment_id, job_id, pipeline_version, attempt,
last_error_code, updated_at
FROM attachment_jobs WHERE status = 'failed'
ORDER BY updated_at`,
);
return result.rows;
}
async replayCandidate(attachmentId: string): Promise<
| {
job_id: string;
pipeline_version: number;
staging_key: string | null;
}
| undefined
> {
const result = await this.database.query<{
job_id: string;
pipeline_version: number;
staging_key: string | null;
}>(
'jobs.replay_candidate',
`SELECT j.job_id, j.pipeline_version, a.staging_key
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.attachment_id = $1 AND j.status = 'failed'
ORDER BY j.updated_at DESC
LIMIT 1`,
[attachmentId],
);
return result.rows[0];
}
async replay(
attachmentId: string,
options: {
reason: string;
operator: string;
maxAttempts: number;
sourceAvailable: boolean;
},
): Promise<ReplayResult> {
return this.database.withTransaction(async (client) => {
const found = await client.query<
AttachmentJobRow & { staging_key: string | null }
>(
`SELECT j.*, a.staging_key
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.attachment_id = $1 AND j.status = 'failed'
ORDER BY j.updated_at DESC
LIMIT 1
FOR UPDATE OF j, a`,
[attachmentId],
);
const job = found.rows[0];
if (!job) return { kind: 'refused', reason: 'no_failed_job' };
const attachment = await client.query<AttachmentRow>(
`SELECT * FROM attachments WHERE id = $1`,
[attachmentId],
);
const row = attachment.rows[0];
if (
row.status === 'ready' &&
row.ready_pipeline_version !== null &&
row.ready_pipeline_version >= job.pipeline_version
)
return {
kind: 'refused',
reason: 'already_ready',
job_id: job.job_id,
};
const active = await client.query(
`SELECT 1 FROM attachment_jobs
WHERE attachment_id = $1 AND status IN ('queued','processing')
LIMIT 1`,
[attachmentId],
);
if (active.rowCount !== 0)
return {
kind: 'refused',
reason: 'job_active',
job_id: job.job_id,
};
if (row.staging_key === null && !options.sourceAvailable)
return {
kind: 'refused',
reason: 'source_expired',
job_id: job.job_id,
};
const attempt = job.attempt + 1;
await client.query(
`UPDATE attachment_jobs
SET status = 'queued', attempt = $2,
max_attempts = $2::integer + $3::integer - 1,
next_attempt_at = now(), lease_owner = NULL,
lease_token = NULL, lease_until = NULL,
updated_at = now(), finished_at = NULL
WHERE job_id = $1`,
[job.job_id, attempt, options.maxAttempts],
);
await client.query(
`UPDATE attachments SET status = 'queued', error_code = NULL,
updated_at = now()
WHERE id = $1 AND status = 'failed'`,
[attachmentId],
);
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb, now())`,
[
job.job_id,
JSON.stringify(buildJobMessage({ ...job, attempt })),
],
);
await this.event(client, job.job_id, 'replayed', attempt, {
operator: options.operator,
reason: options.reason,
previous_error: job.last_error_code,
});
return { kind: 'replayed', job_id: job.job_id, attempt };
});
}
async reprocess(
attachmentId: string,
pipelineVersion: number,
options: { reason: string; operator: string; maxAttempts: number },
): Promise<ReprocessResult> {
return this.database.withTransaction(async (client) => {
const attachment = await client.query<AttachmentRow>(
`SELECT * FROM attachments WHERE id = $1 FOR UPDATE`,
[attachmentId],
);
const row = attachment.rows[0];
if (
!row ||
!['queued', 'processing', 'ready', 'failed'].includes(
row.status,
)
)
return { kind: 'refused', reason: 'not_accepted' };
const jobId = randomUUID();
const created = await client.query<AttachmentJobRow>(
`INSERT INTO attachment_jobs
(job_id, attachment_id, pipeline_version, status, attempt,
max_attempts, next_attempt_at)
VALUES ($1, $2, $3, 'queued', 1, $4, now())
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING
RETURNING *`,
[jobId, attachmentId, pipelineVersion, options.maxAttempts],
);
const job = created.rows[0];
if (!job) {
const existing = await client.query<{ job_id: string }>(
`SELECT job_id FROM attachment_jobs
WHERE attachment_id = $1 AND pipeline_version = $2`,
[attachmentId, pipelineVersion],
);
return {
kind: 'refused',
reason: 'job_exists',
job_id: existing.rows[0]?.job_id,
};
}
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb, now())`,
[job.job_id, JSON.stringify(buildJobMessage(job))],
);
await this.event(client, job.job_id, 'created', 1, {
reason: options.reason,
operator: options.operator,
});
return { kind: 'created', job_id: job.job_id };
});
}
private async skip(
client: PoolClient,
message: JobMessage,
reason: string,
): Promise<ClaimResult> {
await this.event(
client,
message.job_id,
'duplicate_skipped',
message.attempt,
{ reason, message_attempt: message.attempt },
);
return { kind: 'skip', reason };
}
private async event(
client: PoolClient,
jobId: string,
event: string,
attempt: number,
detail: Record<string, unknown>,
): Promise<void> {
await client.query(
`INSERT INTO job_events (job_id, event, attempt, detail)
VALUES ($1, $2, $3, $4::jsonb)`,
[jobId, event, attempt, JSON.stringify(detail)],
);
}
}
+92
View File
@@ -0,0 +1,92 @@
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 = 100;
/**
* Runs only in the API process. `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;
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 (this.running) {
this.again = true;
return;
}
this.running = true;
this.current = this.drain()
.catch((error: unknown) => {
this.metrics.increment('outbox.publish_failed');
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 published = await this.repository.publishPending(
BATCH_SIZE,
(message) => this.broker.publish(message),
() => this.faults.point('relay.after_publish_before_mark'),
);
if (published > 0) {
this.metrics.add('outbox.published', published);
if (this.failing) {
this.failing = false;
this.logger.log('Outbox publishing recovered');
}
}
}
}