forked from mtusi2026/mtusi2026lab5
feat: add rabbitmq broker, outbox relay and worker services
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import amqp, { Channel, Connection } from 'amqplib';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
export const JOB_QUEUE = 'attachment.jobs';
|
||||
export const DEAD_LETTER_QUEUE = 'attachment.jobs.dlq';
|
||||
const DELIVERY_LIMIT = 20;
|
||||
const RECONNECT_MAX_MS = 10000;
|
||||
|
||||
export function brokerUrl(): string {
|
||||
const file = process.env.BROKER_URL_FILE;
|
||||
const url = file ? readFileSync(file, 'utf8').trim() : process.env.BROKER_URL;
|
||||
if (!url) {
|
||||
throw new Error('BROKER_URL_FILE or BROKER_URL must be set');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function assertTopology(channel: Channel): Promise<void> {
|
||||
await channel.assertQueue(DEAD_LETTER_QUEUE, {
|
||||
durable: true,
|
||||
arguments: { 'x-queue-type': 'quorum' },
|
||||
});
|
||||
await channel.assertQueue(JOB_QUEUE, {
|
||||
durable: true,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
'x-delivery-limit': DELIVERY_LIMIT,
|
||||
'x-dead-letter-exchange': '',
|
||||
'x-dead-letter-routing-key': DEAD_LETTER_QUEUE,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function connectWithRetry(
|
||||
logger: Logger,
|
||||
stopping: () => boolean,
|
||||
): Promise<Connection | null> {
|
||||
let delay = 500;
|
||||
while (!stopping()) {
|
||||
try {
|
||||
const connection = await amqp.connect(brokerUrl(), { timeout: 5000 });
|
||||
logger.log('connected to broker');
|
||||
return connection;
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message.split(' ')[0] : 'unknown';
|
||||
logger.warn(`broker unavailable (${reason}), retry in ${delay} ms`);
|
||||
await sleep(delay);
|
||||
delay = Math.min(RECONNECT_MAX_MS, delay * 2);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -158,6 +158,35 @@ export async function recoverExpiredLeases(
|
||||
return recovered;
|
||||
}
|
||||
|
||||
export async function republishStale(
|
||||
prisma: PrismaClient,
|
||||
staleMs: number,
|
||||
now = new Date(),
|
||||
limit = 100,
|
||||
): Promise<number> {
|
||||
const cutoff = new Date(now.getTime() - staleMs);
|
||||
const stale = await prisma.$queryRaw<AttachmentJob[]>`
|
||||
SELECT j.id, j.attachment_id AS "attachmentId", j.pipeline_version AS "pipelineVersion", j.attempt
|
||||
FROM attachment_jobs j
|
||||
WHERE j.status = 'queued'
|
||||
AND j.next_attempt_at < ${cutoff}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM outbox o
|
||||
WHERE o.job_id = j.id AND (o.published_at IS NULL OR o.published_at > ${cutoff})
|
||||
)
|
||||
ORDER BY j.next_attempt_at
|
||||
LIMIT ${limit}`;
|
||||
for (const job of stale) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.jobEvent.create({
|
||||
data: { jobId: job.id, attempt: job.attempt, event: 'republished', createdAt: now },
|
||||
});
|
||||
await publishLater(tx, job, now);
|
||||
});
|
||||
}
|
||||
return stale.length;
|
||||
}
|
||||
|
||||
export type ReplayResult = 'replayed' | 'already_ready' | 'not_failed' | 'not_found';
|
||||
|
||||
export async function replayJob(
|
||||
|
||||
@@ -29,6 +29,11 @@ export function processorOptions(): ProcessorOptions {
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProcessorHooks {
|
||||
afterStore?: () => Promise<void>;
|
||||
afterCommit?: () => Promise<void>;
|
||||
}
|
||||
|
||||
class PermanentError extends Error {
|
||||
constructor(
|
||||
readonly code: string,
|
||||
@@ -47,7 +52,7 @@ export class JobProcessor {
|
||||
private readonly prisma: PrismaClient,
|
||||
private readonly s3: S3Service,
|
||||
private readonly options: ProcessorOptions = processorOptions(),
|
||||
private readonly hooks: { afterStore?: () => Promise<void> } = {},
|
||||
private readonly hooks: ProcessorHooks = {},
|
||||
) {}
|
||||
|
||||
async handle(message: JobMessage): Promise<Outcome> {
|
||||
@@ -195,6 +200,7 @@ export class JobProcessor {
|
||||
this.logger.warn(`job ${lease.id}: lease lost before commit, result left to owner`);
|
||||
return 'skipped';
|
||||
}
|
||||
await this.hooks.afterCommit?.();
|
||||
await this.removeStaging(attachment);
|
||||
return 'ready';
|
||||
}
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { ConfirmChannel } from 'amqplib';
|
||||
import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker';
|
||||
import { PrismaService } from './db/prisma.service';
|
||||
import { JobMessage } from './jobs/job-message';
|
||||
import { recoverExpiredLeases, republishStale } from './jobs/job-store';
|
||||
|
||||
const BATCH_SIZE = 100;
|
||||
const POLL_MS = Number(process.env.RELAY_POLL_MS ?? 500);
|
||||
const SWEEP_MS = Number(process.env.RELAY_SWEEP_MS ?? 5000);
|
||||
const STALE_MS = Number(process.env.JOB_STALE_SECONDS ?? 300) * 1000;
|
||||
const FAULT = process.env.RELAY_FAULT;
|
||||
|
||||
const logger = new Logger('OutboxRelay');
|
||||
const prisma = new PrismaService();
|
||||
let stopping = false;
|
||||
|
||||
async function publishBatch(channel: ConfirmChannel): Promise<number> {
|
||||
return prisma.$transaction(
|
||||
async (tx) => {
|
||||
const rows = await tx.$queryRaw<{ id: bigint; payload: JobMessage }[]>`
|
||||
SELECT id, payload FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= ${new Date()}
|
||||
ORDER BY id
|
||||
LIMIT ${BATCH_SIZE}
|
||||
FOR UPDATE SKIP LOCKED`;
|
||||
if (rows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
for (const { payload } of rows) {
|
||||
channel.sendToQueue(JOB_QUEUE, Buffer.from(JSON.stringify(payload)), {
|
||||
persistent: true,
|
||||
contentType: 'application/json',
|
||||
messageId: payload.job_id,
|
||||
type: payload.type,
|
||||
});
|
||||
}
|
||||
await channel.waitForConfirms();
|
||||
logger.log(`published ${rows.length} job message(s), broker confirmed`);
|
||||
if (FAULT === 'exit-after-confirm') {
|
||||
logger.warn('fault injection: exit after broker confirm, before outbox is marked');
|
||||
process.kill(process.pid, 'SIGKILL');
|
||||
await sleep(60000);
|
||||
}
|
||||
await tx.outboxEntry.updateMany({
|
||||
where: { id: { in: rows.map((row) => row.id) } },
|
||||
data: { publishedAt: new Date(), publishAttempts: { increment: 1 } },
|
||||
});
|
||||
return rows.length;
|
||||
},
|
||||
{ timeout: 15000 },
|
||||
);
|
||||
}
|
||||
|
||||
async function sweep(): Promise<void> {
|
||||
const recovered = await recoverExpiredLeases(prisma);
|
||||
const republished = await republishStale(prisma, STALE_MS);
|
||||
if (recovered + republished > 0) {
|
||||
logger.log(`lease expired: ${recovered}, stale queued republished: ${republished}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function run(): Promise<void> {
|
||||
let lastSweep = 0;
|
||||
while (!stopping) {
|
||||
const connection = await connectWithRetry(logger, () => stopping);
|
||||
if (!connection) {
|
||||
break;
|
||||
}
|
||||
let closed = false;
|
||||
connection.on('close', () => {
|
||||
closed = true;
|
||||
});
|
||||
connection.on('error', () => {
|
||||
closed = true;
|
||||
});
|
||||
try {
|
||||
const channel = await connection.createConfirmChannel();
|
||||
channel.on('error', () => {
|
||||
closed = true;
|
||||
});
|
||||
channel.on('close', () => {
|
||||
closed = true;
|
||||
});
|
||||
await assertTopology(channel);
|
||||
while (!stopping && !closed) {
|
||||
let published = 0;
|
||||
try {
|
||||
published = await publishBatch(channel);
|
||||
if (Date.now() - lastSweep >= SWEEP_MS) {
|
||||
await sweep();
|
||||
lastSweep = Date.now();
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||
logger.error(`relay pass failed: ${reason}`);
|
||||
await sleep(1000);
|
||||
}
|
||||
if (published < BATCH_SIZE) {
|
||||
await sleep(POLL_MS);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||
logger.error(`broker channel failed: ${reason}`);
|
||||
}
|
||||
await connection.close().catch(() => undefined);
|
||||
if (!stopping) {
|
||||
logger.warn('broker connection lost, reconnecting');
|
||||
await sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
|
||||
process.once(signal, () => {
|
||||
stopping = true;
|
||||
});
|
||||
}
|
||||
|
||||
run()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
logger.log('stopped');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error(error instanceof Error ? error.message : 'fatal error');
|
||||
process.exit(1);
|
||||
});
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Channel, ConsumeMessage } from 'amqplib';
|
||||
import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker';
|
||||
import { PrismaService } from './db/prisma.service';
|
||||
import { parseJobMessage } from './jobs/job-message';
|
||||
import { JobProcessor, ProcessorHooks, processorOptions } from './jobs/processor';
|
||||
import { S3Service } from './storage/s3.service';
|
||||
|
||||
const CONCURRENCY = Number(process.env.WORKER_CONCURRENCY ?? 2);
|
||||
const INFRA_RETRY_MS = Number(process.env.WORKER_INFRA_RETRY_MS ?? 5000);
|
||||
const DRAIN_TIMEOUT_MS = Number(process.env.WORKER_DRAIN_TIMEOUT_MS ?? 25000);
|
||||
const FAULT = process.env.WORKER_FAULT;
|
||||
|
||||
const logger = new Logger('Worker');
|
||||
const prisma = new PrismaService();
|
||||
const s3 = new S3Service();
|
||||
const processor = new JobProcessor(prisma, s3, processorOptions(), faultHooks());
|
||||
let stopping = false;
|
||||
let inFlight = 0;
|
||||
|
||||
function faultHooks(): ProcessorHooks {
|
||||
const crash = (point: string) => async () => {
|
||||
logger.warn(`fault injection: worker killed ${point}`);
|
||||
process.kill(process.pid, 'SIGKILL');
|
||||
await sleep(60000);
|
||||
};
|
||||
if (FAULT === 'exit-after-store') {
|
||||
return { afterStore: crash('after storing objects, before commit and ack') };
|
||||
}
|
||||
if (FAULT === 'exit-after-commit') {
|
||||
return { afterCommit: crash('after commit, before ack') };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function handle(channel: Channel, delivery: ConsumeMessage): Promise<void> {
|
||||
inFlight++;
|
||||
try {
|
||||
const message = parseJobMessage(delivery.content);
|
||||
if (!message) {
|
||||
logger.warn('malformed job message moved to dead letter queue');
|
||||
channel.nack(delivery, false, false);
|
||||
return;
|
||||
}
|
||||
const outcome = await processor.handle(message);
|
||||
logger.log(
|
||||
`job ${message.job_id} attempt ${message.attempt}` +
|
||||
`${delivery.fields.redelivered ? ' (redelivered)' : ''}: ${outcome}`,
|
||||
);
|
||||
channel.ack(delivery);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||
logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`);
|
||||
await sleep(INFRA_RETRY_MS);
|
||||
try {
|
||||
channel.nack(delivery, false, true);
|
||||
} catch {
|
||||
logger.warn('channel closed, broker will redeliver unacked message');
|
||||
}
|
||||
} finally {
|
||||
inFlight--;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(): Promise<void> {
|
||||
while (!stopping) {
|
||||
const connection = await connectWithRetry(logger, () => stopping);
|
||||
if (!connection) {
|
||||
break;
|
||||
}
|
||||
const closed = new Promise<void>((resolve) => {
|
||||
connection.on('close', () => resolve());
|
||||
connection.on('error', () => resolve());
|
||||
});
|
||||
try {
|
||||
const channel = await connection.createChannel();
|
||||
await assertTopology(channel);
|
||||
await channel.prefetch(CONCURRENCY);
|
||||
const { consumerTag } = await channel.consume(
|
||||
JOB_QUEUE,
|
||||
(delivery) => {
|
||||
if (delivery) {
|
||||
void handle(channel, delivery);
|
||||
}
|
||||
},
|
||||
{ noAck: false },
|
||||
);
|
||||
logger.log(`consuming ${JOB_QUEUE} with prefetch ${CONCURRENCY}`);
|
||||
const stop = new Promise<void>((resolve) => {
|
||||
const timer = setInterval(() => {
|
||||
if (stopping) {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
}
|
||||
}, 200);
|
||||
void closed.then(() => {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
await stop;
|
||||
if (stopping) {
|
||||
await channel.cancel(consumerTag).catch(() => undefined);
|
||||
const deadline = Date.now() + DRAIN_TIMEOUT_MS;
|
||||
while (inFlight > 0 && Date.now() < deadline) {
|
||||
await sleep(100);
|
||||
}
|
||||
logger.log(`drained, ${inFlight} job(s) left unacked for redelivery`);
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||
logger.error(`broker channel failed: ${reason}`);
|
||||
}
|
||||
await connection.close().catch(() => undefined);
|
||||
if (!stopping) {
|
||||
logger.warn('broker connection lost, reconnecting');
|
||||
await sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
|
||||
process.once(signal, () => {
|
||||
stopping = true;
|
||||
});
|
||||
}
|
||||
|
||||
run()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
s3.onModuleDestroy();
|
||||
logger.log('stopped');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error(error instanceof Error ? error.message : 'fatal error');
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user