forked from mtusi2026/mtusi2026lab5
lab5: устойчивость очереди, восстановление job и права broker
This commit is contained in:
+216
-56
@@ -12,6 +12,7 @@ import {
|
||||
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 {
|
||||
@@ -40,6 +41,7 @@ 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;
|
||||
@@ -47,9 +49,15 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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>,
|
||||
@@ -57,23 +65,45 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
) {
|
||||
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.ensureConnected();
|
||||
const channel = await this.withTimeout(
|
||||
this.ensureConnected(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
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 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,
|
||||
@@ -81,6 +111,10 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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());
|
||||
@@ -91,8 +125,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
this.metrics.increment('broker.publish_failed');
|
||||
reject(new BrokerUnavailableError());
|
||||
fail();
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
@@ -102,7 +135,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.handler = handler;
|
||||
this.ensureConnected()
|
||||
.then(() => this.subscribe())
|
||||
.catch(() => this.scheduleReconnect());
|
||||
.catch(() => this.scheduleSubscribe());
|
||||
}
|
||||
|
||||
isConsuming(): boolean {
|
||||
@@ -112,7 +145,10 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
async queueDepth(
|
||||
queue: string,
|
||||
): Promise<{ messages: number; consumers: number }> {
|
||||
const channel = await this.ensureConnected();
|
||||
const channel = await this.withTimeout(
|
||||
this.ensureConnected(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
const result = await channel.checkQueue(queue);
|
||||
return {
|
||||
messages: result.messageCount,
|
||||
@@ -121,6 +157,8 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
async stopConsuming(): Promise<void> {
|
||||
clearTimeout(this.subscribeTimer);
|
||||
this.subscribeTimer = undefined;
|
||||
const channel = this.consumeChannel;
|
||||
const tag = this.consumerTag;
|
||||
this.consumerTag = undefined;
|
||||
@@ -145,7 +183,11 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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;
|
||||
@@ -184,61 +226,151 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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();
|
||||
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 async subscribe(): Promise<void> {
|
||||
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;
|
||||
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.
|
||||
}
|
||||
});
|
||||
if (!connection || !handler || this.consumerTag)
|
||||
return Promise.resolve();
|
||||
this.subscribing = this.doSubscribe(connection, handler).finally(
|
||||
() => {
|
||||
this.subscribing = undefined;
|
||||
},
|
||||
{ noAck: false },
|
||||
);
|
||||
this.consumeChannel = channel;
|
||||
this.consumerTag = consumer.consumerTag;
|
||||
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();
|
||||
}
|
||||
@@ -253,7 +385,35 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.metrics.increment('broker.reconnect_scheduled');
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = undefined;
|
||||
this.ensureConnected().catch(() => this.scheduleReconnect());
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ export type FaultTarget = {
|
||||
|
||||
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`);
|
||||
@@ -101,7 +104,7 @@ export class FaultInjector {
|
||||
const milliseconds = Number(value.slice('delay:'.length));
|
||||
if (!Number.isFinite(milliseconds) || milliseconds < 0) return;
|
||||
this.metrics.increment('faults.triggered');
|
||||
await this.sleep(milliseconds, signal);
|
||||
await this.sleep(Math.min(milliseconds, MAX_TIMER_MS), signal);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,18 +146,18 @@ async function main(): Promise<number> {
|
||||
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;
|
||||
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;
|
||||
|
||||
+179
-46
@@ -55,11 +55,6 @@ 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) {}
|
||||
@@ -127,18 +122,27 @@ export class JobsRepository {
|
||||
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`,
|
||||
// Lock order is always job -> attachment, matching commitSuccess and
|
||||
// commitFailure. A join FOR UPDATE would let the planner choose the
|
||||
// opposite order under a concurrent duplicate delivery.
|
||||
const foundJob = await client.query<
|
||||
AttachmentJobRow & { due: boolean }
|
||||
>(
|
||||
`SELECT *, (next_attempt_at <= now()) AS due
|
||||
FROM attachment_jobs
|
||||
WHERE job_id = $1
|
||||
FOR UPDATE`,
|
||||
[message.job_id],
|
||||
);
|
||||
const job = found.rows[0];
|
||||
const job = foundJob.rows[0];
|
||||
if (!job) return { kind: 'skip', reason: 'unknown_job' };
|
||||
|
||||
const foundAttachment = await client.query<AttachmentRow>(
|
||||
`SELECT * FROM attachments WHERE id = $1 FOR UPDATE`,
|
||||
[job.attachment_id],
|
||||
);
|
||||
const attachment = foundAttachment.rows[0];
|
||||
|
||||
if (
|
||||
job.attachment_id !== message.attachment_id ||
|
||||
job.pipeline_version !== message.pipeline_version
|
||||
@@ -155,12 +159,14 @@ export class JobsRepository {
|
||||
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())
|
||||
// Both `next_attempt_at` and `now()` come from PostgreSQL; a worker
|
||||
// clock skew must not turn a future retry into a lost job.
|
||||
if (!job.due)
|
||||
return this.skip(client, message, 'not_due');
|
||||
|
||||
if (
|
||||
job.ready_pipeline_version !== null &&
|
||||
job.ready_pipeline_version > job.pipeline_version
|
||||
attachment.ready_pipeline_version !== null &&
|
||||
attachment.ready_pipeline_version > job.pipeline_version
|
||||
) {
|
||||
await client.query(
|
||||
`UPDATE attachment_jobs
|
||||
@@ -174,7 +180,8 @@ export class JobsRepository {
|
||||
'superseded',
|
||||
job.attempt,
|
||||
{
|
||||
ready_pipeline_version: job.ready_pipeline_version,
|
||||
ready_pipeline_version:
|
||||
attachment.ready_pipeline_version,
|
||||
},
|
||||
);
|
||||
return this.skip(client, message, 'superseded');
|
||||
@@ -185,15 +192,12 @@ export class JobsRepository {
|
||||
`UPDATE attachment_jobs
|
||||
SET status = 'processing', lease_owner = $2, lease_token = $3,
|
||||
lease_until = now() + make_interval(secs => $4::double precision),
|
||||
last_reconciled_at = NULL,
|
||||
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'`,
|
||||
@@ -209,7 +213,7 @@ export class JobsRepository {
|
||||
return {
|
||||
kind: 'claimed',
|
||||
job: claimed.rows[0],
|
||||
attachment: attachment.rows[0],
|
||||
attachment,
|
||||
leaseToken,
|
||||
};
|
||||
});
|
||||
@@ -368,7 +372,8 @@ export class JobsRepository {
|
||||
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()
|
||||
last_error_code = $4, last_reconciled_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE job_id = $1`,
|
||||
[job.job_id, nextAttempt, delayMs / 1000, failure.code],
|
||||
);
|
||||
@@ -408,18 +413,20 @@ export class JobsRepository {
|
||||
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
|
||||
const expired = await client.query<AttachmentJobRow>(
|
||||
`SELECT * FROM attachment_jobs
|
||||
WHERE status = 'processing' AND lease_until < now()
|
||||
ORDER BY lease_until
|
||||
LIMIT $1
|
||||
FOR UPDATE OF j, a`,
|
||||
FOR UPDATE SKIP LOCKED`,
|
||||
[limit],
|
||||
);
|
||||
for (const job of expired.rows) {
|
||||
// Keep the same lock order as claim/commit: job, then attachment.
|
||||
await client.query(
|
||||
`SELECT 1 FROM attachments WHERE id = $1 FOR UPDATE`,
|
||||
[job.attachment_id],
|
||||
);
|
||||
if (job.attempt >= job.max_attempts) {
|
||||
await client.query(
|
||||
`UPDATE attachment_jobs
|
||||
@@ -447,6 +454,16 @@ export class JobsRepository {
|
||||
code: 'retry_exhausted',
|
||||
},
|
||||
);
|
||||
await this.event(
|
||||
client,
|
||||
job.job_id,
|
||||
'failed',
|
||||
job.attempt,
|
||||
{
|
||||
code: 'retry_exhausted',
|
||||
cause: 'lease_expired',
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -458,6 +475,7 @@ export class JobsRepository {
|
||||
next_attempt_at = now() + make_interval(secs => $3::double precision),
|
||||
lease_owner = NULL, lease_token = NULL,
|
||||
lease_until = NULL, last_error_code = 'lease_expired',
|
||||
last_reconciled_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE job_id = $1`,
|
||||
[job.job_id, nextAttempt, delayMs / 1000],
|
||||
@@ -491,6 +509,57 @@ export class JobsRepository {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Backstop for a queued job whose broker message was lost or dead-lettered
|
||||
* while the outbox row was already marked published. Re-emitting is safe:
|
||||
* claim fences duplicates by job status and attempt.
|
||||
*/
|
||||
async reconcileQueuedJobs(
|
||||
limit: number,
|
||||
graceSeconds: number,
|
||||
): Promise<number> {
|
||||
return this.database.withTransaction(async (client) => {
|
||||
const stuck = await client.query<AttachmentJobRow>(
|
||||
`SELECT j.* FROM attachment_jobs j
|
||||
WHERE j.status = 'queued'
|
||||
AND j.next_attempt_at <= now()
|
||||
AND COALESCE(
|
||||
(SELECT max(o.published_at) FROM job_outbox o
|
||||
WHERE o.job_id = j.job_id AND o.published_at IS NOT NULL),
|
||||
j.updated_at) <= now() - make_interval(secs => $2::double precision)
|
||||
AND (j.last_reconciled_at IS NULL
|
||||
OR j.last_reconciled_at <= now() - make_interval(secs => $2::double precision))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM job_outbox o
|
||||
WHERE o.job_id = j.job_id AND o.published_at IS NULL)
|
||||
ORDER BY j.next_attempt_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED`,
|
||||
[limit, graceSeconds],
|
||||
);
|
||||
for (const job of stuck.rows) {
|
||||
await client.query(
|
||||
`UPDATE attachment_jobs SET last_reconciled_at = now(), updated_at = now()
|
||||
WHERE job_id = $1`,
|
||||
[job.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,
|
||||
'reconciled',
|
||||
job.attempt,
|
||||
{ code: 'queue_message_missing' },
|
||||
);
|
||||
}
|
||||
return stuck.rows.length;
|
||||
});
|
||||
}
|
||||
|
||||
async publishPending(
|
||||
limit: number,
|
||||
publish: (message: JobMessage) => Promise<void>,
|
||||
@@ -567,14 +636,39 @@ export class JobsRepository {
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async clearStaging(id: string, key: string): Promise<boolean> {
|
||||
async clearStaging(
|
||||
id: string,
|
||||
key: string,
|
||||
removeObject: (key: string) => Promise<void>,
|
||||
): Promise<boolean> {
|
||||
return this.database.withTransaction(async (client) => {
|
||||
const cleared = await client.query(
|
||||
// Keep the same job -> attachment lock order as claim/replay, then
|
||||
// serialize cleanup with replay on the attachment row.
|
||||
await client.query(
|
||||
`SELECT job_id FROM attachment_jobs
|
||||
WHERE attachment_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE`,
|
||||
[id],
|
||||
);
|
||||
const locked = await client.query<AttachmentRow>(
|
||||
`SELECT * FROM attachments WHERE id = $1 FOR UPDATE`,
|
||||
[id],
|
||||
);
|
||||
const row = locked.rows[0];
|
||||
if (
|
||||
!row ||
|
||||
row.staging_key !== key ||
|
||||
!['ready', 'failed'].includes(row.status)
|
||||
)
|
||||
return false;
|
||||
await removeObject(key);
|
||||
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],
|
||||
WHERE id = $1`,
|
||||
[id],
|
||||
);
|
||||
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
|
||||
@@ -588,6 +682,41 @@ export class JobsRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async pruneOutbox(
|
||||
retentionSeconds: number,
|
||||
limit = 5000,
|
||||
): Promise<number> {
|
||||
const result = await this.database.query(
|
||||
'jobs.outbox_prune',
|
||||
`DELETE FROM job_outbox
|
||||
WHERE id IN (
|
||||
SELECT id FROM job_outbox
|
||||
WHERE published_at IS NOT NULL
|
||||
AND published_at < now() - make_interval(secs => $1::double precision)
|
||||
ORDER BY published_at
|
||||
LIMIT $2)`,
|
||||
[retentionSeconds, limit],
|
||||
);
|
||||
return result.rowCount ?? 0;
|
||||
}
|
||||
|
||||
async pruneEvents(
|
||||
retentionSeconds: number,
|
||||
limit = 5000,
|
||||
): Promise<number> {
|
||||
const result = await this.database.query(
|
||||
'jobs.events_prune',
|
||||
`DELETE FROM job_events
|
||||
WHERE id IN (
|
||||
SELECT id FROM job_events
|
||||
WHERE created_at < now() - make_interval(secs => $1::double precision)
|
||||
ORDER BY created_at
|
||||
LIMIT $2)`,
|
||||
[retentionSeconds, limit],
|
||||
);
|
||||
return result.rowCount ?? 0;
|
||||
}
|
||||
|
||||
async statusOf(attachmentId: string): Promise<
|
||||
| {
|
||||
attachment: AttachmentRow;
|
||||
@@ -736,26 +865,23 @@ export class JobsRepository {
|
||||
operator: string;
|
||||
maxAttempts: number;
|
||||
sourceAvailable: boolean;
|
||||
expectedStagingKey: string | null;
|
||||
},
|
||||
): 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
|
||||
const found = await client.query<AttachmentJobRow>(
|
||||
`SELECT * FROM attachment_jobs
|
||||
WHERE attachment_id = $1 AND status = 'failed'
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE OF j, a`,
|
||||
FOR UPDATE`,
|
||||
[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`,
|
||||
`SELECT * FROM attachments WHERE id = $1 FOR UPDATE`,
|
||||
[attachmentId],
|
||||
);
|
||||
const row = attachment.rows[0];
|
||||
@@ -783,6 +909,12 @@ export class JobsRepository {
|
||||
job_id: job.job_id,
|
||||
};
|
||||
|
||||
if (row.staging_key !== options.expectedStagingKey)
|
||||
return {
|
||||
kind: 'refused',
|
||||
reason: 'source_changed',
|
||||
job_id: job.job_id,
|
||||
};
|
||||
if (row.staging_key === null && !options.sourceAvailable)
|
||||
return {
|
||||
kind: 'refused',
|
||||
@@ -797,6 +929,7 @@ export class JobsRepository {
|
||||
max_attempts = $2::integer + $3::integer - 1,
|
||||
next_attempt_at = now(), lease_owner = NULL,
|
||||
lease_token = NULL, lease_until = NULL,
|
||||
last_reconciled_at = NULL,
|
||||
updated_at = now(), finished_at = NULL
|
||||
WHERE job_id = $1`,
|
||||
[job.job_id, attempt, options.maxAttempts],
|
||||
|
||||
@@ -11,10 +11,10 @@ import { BrokerClient } from './broker.client.js';
|
||||
import { FaultInjector } from './fault-injector.js';
|
||||
import { JobsRepository } from './jobs.repository.js';
|
||||
|
||||
const BATCH_SIZE = 100;
|
||||
const BATCH_SIZE = 20;
|
||||
|
||||
/**
|
||||
* Runs only in the API process. `publishPending` holds one transaction around
|
||||
* 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.
|
||||
@@ -27,6 +27,8 @@ export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
|
||||
private again = false;
|
||||
private current: Promise<void> | undefined;
|
||||
private failing = false;
|
||||
private retryAt = 0;
|
||||
private retryDelayMs = 1000;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
@@ -50,6 +52,7 @@ export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
|
||||
}
|
||||
|
||||
kick(): void {
|
||||
if (Date.now() < this.retryAt) return;
|
||||
if (this.running) {
|
||||
this.again = true;
|
||||
return;
|
||||
@@ -58,6 +61,8 @@ export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
|
||||
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(
|
||||
@@ -76,13 +81,26 @@ export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
|
||||
}
|
||||
|
||||
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,
|
||||
(message) => this.broker.publish(message),
|
||||
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');
|
||||
|
||||
Reference in New Issue
Block a user