lab5: устойчивость очереди, восстановление job и права broker

This commit is contained in:
2026-11-05 04:05:07 +03:00
parent 2638e1c2c4
commit 0790599d2f
44 changed files with 1122 additions and 343 deletions
+49 -18
View File
@@ -18,34 +18,65 @@ export type InsertPending = {
const VISIBLE_MEMBER = `JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2`;
const INSERT_PENDING_SQL = `INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, upload_mode, status,
object_key, staging_key, size_bytes, sha256, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8, $9, $10,
now() + make_interval(secs => $11::double precision / 1000.0))`;
@Injectable()
export class AttachmentsRepository {
constructor(private readonly database: DatabaseClient) {}
private values(input: InsertPending): unknown[] {
return [
input.id,
input.chatId,
input.ownerId,
input.filename,
input.contentType,
input.uploadMode,
input.objectKey,
input.stagingKey,
input.sizeBytes,
input.sha256,
input.ttlMs,
];
}
async insertPending(input: InsertPending): Promise<void> {
await this.database.query(
'attachments.insert_pending',
`INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, upload_mode, status,
object_key, staging_key, size_bytes, sha256, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8, $9, $10,
now() + make_interval(secs => $11::double precision / 1000.0))`,
[
input.id,
input.chatId,
input.ownerId,
input.filename,
input.contentType,
input.uploadMode,
input.objectKey,
input.stagingKey,
input.sizeBytes,
input.sha256,
input.ttlMs,
],
INSERT_PENDING_SQL,
this.values(input),
);
}
/**
* Serializes the per-owner pending check with the insert. Two parallel
* `init` calls cannot both pass the limit.
*/
async insertPendingLimited(
input: InsertPending,
maxPending: number,
): Promise<boolean> {
return this.database.withTransaction(async (client) => {
await client.query(
`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`,
[input.ownerId],
);
const count = await client.query<{ count: string }>(
`SELECT count(*) AS count FROM attachments
WHERE owner_id = $1 AND status IN ('pending', 'rejected')
AND upload_mode = 'direct' AND expires_at > now()`,
[input.ownerId],
);
if (Number(count.rows[0].count) >= maxPending) return false;
await client.query(INSERT_PENDING_SQL, this.values(input));
return true;
});
}
async deletePending(id: string): Promise<void> {
await this.database.query(
'attachments.delete_pending',
+19 -20
View File
@@ -90,10 +90,25 @@ export class DirectUploadsService {
if (dto.size_bytes > this.maxUploadBytes)
throw new PayloadTooLargeException('Image is too large');
await this.chats.getForUser(chatId, user);
if (
(await this.repository.countPendingDirect(user.id)) >=
this.maxPending
)
const id = randomUUID();
const stagingKey = this.storage.stagingKey(id);
const inserted = await this.repository.insertPendingLimited(
{
id,
chatId,
ownerId: user.id,
filename,
contentType: dto.content_type,
uploadMode: 'direct',
objectKey: this.storage.objectKey(id),
stagingKey,
sizeBytes: dto.size_bytes,
sha256: dto.sha256,
ttlMs: this.ttlSeconds * 1000,
},
this.maxPending,
);
if (!inserted)
throw new HttpException(
{
message: 'Too many unfinished direct uploads',
@@ -101,22 +116,6 @@ export class DirectUploadsService {
},
429,
);
const id = randomUUID();
const stagingKey = this.storage.stagingKey(id);
await this.repository.insertPending({
id,
chatId,
ownerId: user.id,
filename,
contentType: dto.content_type,
uploadMode: 'direct',
objectKey: this.storage.objectKey(id),
stagingKey,
sizeBytes: dto.size_bytes,
sha256: dto.sha256,
ttlMs: this.ttlSeconds * 1000,
});
const checksum = Buffer.from(dto.sha256, 'hex').toString('base64');
let url: string;
try {
+31
View File
@@ -36,6 +36,12 @@ export const appConfigSchema = z
DATABASE_URL: requiredString('DATABASE_URL'),
REDIS_URL: requiredString('REDIS_URL'),
BROKER_URL: requiredString('BROKER_URL'),
BROKER_PUBLISH_TIMEOUT_MS: numeric(
'BROKER_PUBLISH_TIMEOUT_MS',
100,
60000,
5000,
),
DATABASE_POOL_MAX: numeric('DATABASE_POOL_MAX', 1, 100, 10),
DATABASE_CONNECTION_TIMEOUT_MS: numeric(
'DATABASE_CONNECTION_TIMEOUT_MS',
@@ -49,6 +55,12 @@ export const appConfigSchema = z
undefined,
5000,
),
DATABASE_IDLE_TX_TIMEOUT_MS: numeric(
'DATABASE_IDLE_TX_TIMEOUT_MS',
1000,
undefined,
30000,
),
// Бюджет зависимостей в /health/ready: LB проверяет ту же ручку, поэтому
// проба готовности обязана уложиться в timeout check HAProxy (500 ms).
HEALTH_TIMEOUT_MS: numeric('HEALTH_TIMEOUT_MS', 1, undefined, 400),
@@ -159,6 +171,24 @@ export const appConfigSchema = z
),
WORKER_HEALTH_PORT: numeric('WORKER_HEALTH_PORT', 1, 65535, 8081),
FAULT_INJECTION_ENABLED: numeric('FAULT_INJECTION_ENABLED', 0, 1, 0),
QUEUED_RECONCILE_GRACE_SECONDS: numeric(
'QUEUED_RECONCILE_GRACE_SECONDS',
5,
3600,
15,
),
OUTBOX_RETENTION_SECONDS: numeric(
'OUTBOX_RETENTION_SECONDS',
60,
undefined,
86400,
),
JOB_EVENTS_RETENTION_SECONDS: numeric(
'JOB_EVENTS_RETENTION_SECONDS',
3600,
undefined,
2592000,
),
})
.strip();
@@ -167,6 +197,7 @@ export const databaseConfigSchema = appConfigSchema.pick({
DATABASE_POOL_MAX: true,
DATABASE_CONNECTION_TIMEOUT_MS: true,
DATABASE_STATEMENT_TIMEOUT_MS: true,
DATABASE_IDLE_TX_TIMEOUT_MS: true,
HEALTH_TIMEOUT_MS: true,
IDEMPOTENCY_TTL_SECONDS: true,
});
+13 -1
View File
@@ -23,6 +23,9 @@ export class DatabaseClient implements OnModuleDestroy {
statement_timeout: this.config.getOrThrow(
'DATABASE_STATEMENT_TIMEOUT_MS',
),
// A relay that waits on the broker must not leave the transaction
// idle forever if confirm handling stalls.
options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`,
});
// Idle clients emit 'error' on the pool when the database drops; without a
// listener Node treats it as uncaught and terminates the process.
@@ -66,6 +69,14 @@ export class DatabaseClient implements OnModuleDestroy {
work: (client: pg.PoolClient) => Promise<T>,
): Promise<T> {
const client = await this.pool.connect();
// A server-side idle_in_transaction_session_timeout or a network drop
// can emit 'error' on a checked-out client after pg-pool removed its
// idle listener. Without this listener Node treats it as uncaught.
let fatal: Error | undefined;
const onError = (error: Error): void => {
fatal = error;
};
client.on('error', onError);
try {
await client.query('BEGIN');
const result = await work(client);
@@ -83,7 +94,8 @@ export class DatabaseClient implements OnModuleDestroy {
// Callers must see the operation error, not the rollback error.
throw error;
} finally {
client.release();
client.removeListener('error', onError);
client.release(fatal);
}
}
@@ -0,0 +1,37 @@
ALTER TABLE attachment_jobs ADD COLUMN last_reconciled_at timestamptz(3);
CREATE INDEX job_outbox_job_idx ON job_outbox (job_id);
-- lab4 rows are ready but predate variants. Requeue them once so the worker
-- materializes the same v1 variants every other ready attachment has. The
-- INSERT ... RETURNING CTE keeps the job, outbox and audit event atomic.
WITH legacy AS (
INSERT INTO attachment_jobs
(job_id, attachment_id, pipeline_version, status, attempt, max_attempts,
next_attempt_at, created_at)
SELECT gen_random_uuid(), a.id, 1, 'queued', 1, 5, now(), now()
FROM attachments a
WHERE a.status = 'ready'
AND NOT EXISTS (
SELECT 1 FROM attachment_variants v WHERE v.attachment_id = a.id)
AND NOT EXISTS (
SELECT 1 FROM attachment_jobs j
WHERE j.attachment_id = a.id AND j.pipeline_version = 1)
RETURNING job_id, attachment_id, pipeline_version, attempt, created_at
), queued AS (
INSERT INTO job_outbox (job_id, payload, available_at)
SELECT job_id,
jsonb_build_object(
'schema_version', 1,
'job_id', job_id,
'type', 'attachment.process.v1',
'attachment_id', attachment_id,
'pipeline_version', pipeline_version,
'attempt', attempt,
'created_at', to_char(created_at AT TIME ZONE 'UTC',
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')),
now()
FROM legacy
RETURNING job_id
)
INSERT INTO job_events (job_id, event, attempt, detail)
SELECT job_id, 'created', 1, '{"backfill":true}'::jsonb FROM legacy;
@@ -0,0 +1,10 @@
CREATE INDEX attachment_jobs_queued_idx
ON attachment_jobs (next_attempt_at) WHERE status = 'queued';
CREATE INDEX job_events_created_idx ON job_events (created_at);
CREATE INDEX job_outbox_published_idx
ON job_outbox (published_at) WHERE published_at IS NOT NULL;
ALTER TABLE job_events DROP CONSTRAINT job_events_event_check;
ALTER TABLE job_events ADD CONSTRAINT job_events_event_check CHECK (event IN
('created','claimed','retry_scheduled','lease_expired','succeeded','failed',
'superseded','replayed','duplicate_skipped','staging_deleted','reconciled'));
+216 -56
View File
@@ -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);
}
}
}
+4 -1
View File
@@ -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);
}
}
+6 -6
View File
@@ -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
View File
@@ -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],
+21 -3
View File
@@ -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');
+4 -1
View File
@@ -100,8 +100,11 @@ export class ObjectStorage {
pipelineVersion: number,
variant: 'thumbnail' | 'crop' | 'optimized',
extension: 'jpg' | 'webp',
attempt = 1,
): string {
return `attachments/${attachmentId}/v${pipelineVersion}/${variant}.${extension}`;
// The attempt suffix makes a stale worker's write harmless: the DB
// points at the key of the attempt that won the lease fence.
return `attachments/${attachmentId}/v${pipelineVersion}/${variant}-a${attempt}.${extension}`;
}
async putStream(
+113 -19
View File
@@ -16,7 +16,8 @@ import {
type ErrorClass,
} from '../jobs/errors.js';
import { FaultInjector } from '../jobs/fault-injector.js';
import { parseJobMessage } from '../jobs/job-message.js';
import { parseJobMessage, type JobMessage } from '../jobs/job-message.js';
import { OutboxRelay } from '../jobs/outbox-relay.service.js';
import {
JobsRepository,
type ClaimResult,
@@ -26,6 +27,11 @@ import { MetricsService } from '../metrics/metrics.service.js';
import { renderVariants, type RenderedVariant } from './pipelines.js';
const SHUTDOWN_DRAIN_MS = 30_000;
const VARIANT_EXTENSIONS = [
['thumbnail', 'jpg'],
['crop', 'jpg'],
['optimized', 'webp'],
] as const;
function throwIfAborted(signal: AbortSignal): void {
if (!signal.aborted) return;
@@ -53,6 +59,7 @@ export class JobProcessor implements OnApplicationBootstrap {
private readonly config: ConfigService<AppConfig>,
private readonly broker: BrokerClient,
private readonly jobs: JobsRepository,
private readonly relay: OutboxRelay,
private readonly faults: FaultInjector,
private readonly storage: ObjectStorage,
private readonly metrics: MetricsService,
@@ -92,18 +99,12 @@ export class JobProcessor implements OnApplicationBootstrap {
return;
}
let claim: ClaimResult;
try {
claim = await this.jobs.claim(
parsed,
this.workerId,
this.leaseSeconds,
);
} catch (error) {
this.logger.warn(
`Claim failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
this.safeNack(channel, message, true);
const claim = await this.claimWithRetry(parsed);
if (!claim) {
this.metrics.increment('worker.jobs.claim_failed');
// Do not burn the delivery limit in a tight nack loop while the
// database is briefly unavailable.
this.safeNackAfter(channel, message, true, 5000);
return;
}
if (claim.kind === 'skip') {
@@ -188,10 +189,19 @@ export class JobProcessor implements OnApplicationBootstrap {
{
maxPixels: this.maxPixels,
timeoutSeconds: this.timeoutSeconds,
signal: controller.signal,
},
);
throwIfAborted(controller.signal);
for (const variant of variants) {
if (
!(await this.jobs.extendLease(
job.job_id,
leaseToken,
this.leaseSeconds,
))
)
throw new Error('Lease lost');
await this.storage.putBuffer(
this.variantKey(job, variant),
variant.data,
@@ -219,7 +229,12 @@ export class JobProcessor implements OnApplicationBootstrap {
controller.signal,
);
this.safeAck(channel, message);
if (result === 'succeeded') await this.cleanupStaging(attachment);
if (result === 'succeeded') {
await this.cleanupStaging(attachment);
await this.cleanupAttemptObjects(job, job.attempt);
} else if (result === 'superseded') {
await this.cleanupAttemptObjects(job, null);
}
} catch (error) {
if (committed) {
// The durable effect is already committed; a failure at the ack
@@ -241,7 +256,10 @@ export class JobProcessor implements OnApplicationBootstrap {
delay,
);
this.metrics.increment(`worker.jobs.${outcome}`);
if (outcome === 'retry') this.relay.kick();
this.safeAck(channel, message);
if (outcome === 'retry' || outcome === 'failed')
await this.cleanupAttemptObjects(job, null);
} catch (commitError) {
this.metrics.increment('worker.jobs.commit_failed');
this.logger.warn(
@@ -332,7 +350,11 @@ export class JobProcessor implements OnApplicationBootstrap {
}
private variantKey(
job: { attachment_id: string; pipeline_version: number },
job: {
attachment_id: string;
pipeline_version: number;
attempt: number;
},
variant: RenderedVariant,
): string {
return this.storage.variantKey(
@@ -340,11 +362,16 @@ export class JobProcessor implements OnApplicationBootstrap {
job.pipeline_version,
variant.name,
variant.ext,
job.attempt,
);
}
private variantWrite(
job: { attachment_id: string; pipeline_version: number },
job: {
attachment_id: string;
pipeline_version: number;
attempt: number;
},
variant: RenderedVariant,
): VariantWrite {
return {
@@ -358,13 +385,42 @@ export class JobProcessor implements OnApplicationBootstrap {
};
}
private async cleanupAttemptObjects(
job: { attachment_id: string; pipeline_version: number; attempt: number },
keepAttempt: number | null,
): Promise<void> {
for (let attempt = 1; attempt <= job.attempt; attempt += 1) {
if (attempt === keepAttempt) continue;
for (const [name, extension] of VARIANT_EXTENSIONS) {
try {
await this.storage.delete(
this.storage.variantKey(
job.attachment_id,
job.pipeline_version,
name,
extension,
attempt,
),
);
} catch (error) {
this.logger.warn(
`Variant cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
}
}
}
private async cleanupStaging(attachment: AttachmentRow): Promise<void> {
const key = attachment.staging_key;
if (key === null) return;
try {
await this.storage.delete(key);
await this.jobs.clearStaging(attachment.id, key);
this.metrics.increment('worker.staging.deleted');
const cleared = await this.jobs.clearStaging(
attachment.id,
key,
(stagingKey) => this.storage.delete(stagingKey),
);
if (cleared) this.metrics.increment('worker.staging.deleted');
} catch (error) {
this.metrics.increment('worker.staging.error');
this.logger.warn(
@@ -373,6 +429,44 @@ export class JobProcessor implements OnApplicationBootstrap {
}
}
private async claimWithRetry(
message: JobMessage,
): Promise<ClaimResult | undefined> {
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
return await this.jobs.claim(
message,
this.workerId,
this.leaseSeconds,
);
} catch (error) {
if (attempt === 3) {
this.logger.warn(
`Claim failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
return undefined;
}
await this.sleep(300 * attempt);
}
}
return undefined;
}
private sleep(milliseconds: number): Promise<void> {
const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(resolve, milliseconds);
return promise;
}
private safeNackAfter(
channel: Channel,
message: ConsumeMessage,
requeue: boolean,
delayMs: number,
): void {
setTimeout(() => this.safeNack(channel, message, requeue), delayMs);
}
private safeAck(channel: Channel, message: ConsumeMessage): void {
try {
channel.ack(message);
+50 -14
View File
@@ -7,43 +7,49 @@ import {
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
import { retryDelayMs } from '../jobs/backoff.js';
import { BrokerClient } from '../jobs/broker.client.js';
import { JOB_QUEUE } from '../jobs/broker.topology.js';
import { JobsRepository } from '../jobs/jobs.repository.js';
import { OutboxRelay } from '../jobs/outbox-relay.service.js';
import { MetricsService } from '../metrics/metrics.service.js';
const REAP_BATCH = 20;
/**
* The reaper is the backstop for a worker that was killed mid-job: the lease
* expires and the job returns to `queued` without waiting for the broker's
* delivery limit.
* The reaper recovers a worker killed mid-job (expired lease) and re-emits
* queued jobs whose broker message disappeared, for example after a DLQ
* dead-letter or a lost publish. Both paths only insert an outbox row; the
* claim fence absorbs duplicates.
*/
@Injectable()
export class LeaseReaper implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(LeaseReaper.name);
private timer: NodeJS.Timeout | undefined;
private running = false;
private readonly retryBaseMs: number;
private readonly retryMaxMs: number;
private readonly reconcileGraceSeconds: number;
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly jobs: JobsRepository,
private readonly broker: BrokerClient,
private readonly relay: OutboxRelay,
private readonly metrics: MetricsService,
) {}
) {
this.retryBaseMs = config.getOrThrow('JOB_RETRY_BASE_MS');
this.retryMaxMs = config.getOrThrow('JOB_RETRY_MAX_MS');
this.reconcileGraceSeconds = config.getOrThrow(
'QUEUED_RECONCILE_GRACE_SECONDS',
);
}
onModuleInit(): void {
const interval = this.config.getOrThrow('LEASE_REAPER_INTERVAL_MS');
const base = this.config.getOrThrow('JOB_RETRY_BASE_MS');
const cap = this.config.getOrThrow('JOB_RETRY_MAX_MS');
this.timer = setInterval(() => {
if (this.running) return;
this.running = true;
this.jobs
.reapExpiredLeases(REAP_BATCH, (attempt) =>
retryDelayMs(attempt, base, cap),
)
.then((count) => {
if (count > 0)
this.metrics.add('worker.leases.reaped', count);
})
this.tick()
.catch((error: unknown) => {
this.metrics.increment('worker.leases.reap_error');
this.logger.warn(
@@ -61,4 +67,34 @@ export class LeaseReaper implements OnModuleInit, OnModuleDestroy {
clearInterval(this.timer);
this.timer = undefined;
}
private async tick(): Promise<void> {
const reaped = await this.jobs.reapExpiredLeases(
REAP_BATCH,
(attempt) =>
retryDelayMs(attempt, this.retryBaseMs, this.retryMaxMs),
);
if (reaped > 0) {
this.metrics.add('worker.leases.reaped', reaped);
this.relay.kick();
}
// A normal backlog also has queued jobs with a published outbox row.
// Re-emitting them would multiply broker messages; only reconcile when
// the queue looks empty.
let queueEmpty = false;
try {
queueEmpty = (await this.broker.queueDepth(JOB_QUEUE)).messages === 0;
} catch {
queueEmpty = false;
}
if (!queueEmpty) return;
const reconciled = await this.jobs.reconcileQueuedJobs(
REAP_BATCH,
this.reconcileGraceSeconds,
);
if (reconciled > 0) {
this.metrics.add('worker.jobs.reconciled', reconciled);
this.relay.kick();
}
}
}
+12
View File
@@ -1,6 +1,7 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import sharp from 'sharp';
import { JobTimeoutError } from '../jobs/errors.js';
import { renderVariants, type RenderedVariant } from './pipelines.js';
const sample = readFileSync(
@@ -81,6 +82,17 @@ describe('renderVariants', () => {
);
});
it('honours an aborted job deadline before starting a render', async () => {
const controller = new AbortController();
controller.abort(new JobTimeoutError(1));
await expect(
renderVariants(sample, 1, {
...limits,
signal: controller.signal,
}),
).rejects.toBeInstanceOf(JobTimeoutError);
});
it('produces a different v2 thumbnail', async () => {
const v1 = byName(await renderVariants(sample, 1, limits), 'thumbnail');
const v2 = byName(await renderVariants(sample, 2, limits), 'thumbnail');
+40 -7
View File
@@ -1,6 +1,9 @@
import { createHash } from 'node:crypto';
import sharp from 'sharp';
import { UnsupportedPipelineError } from '../jobs/errors.js';
import {
JobTimeoutError,
UnsupportedPipelineError,
} from '../jobs/errors.js';
import { fitInside } from '../jobs/fit-inside.js';
// Same policy as the API decoder: one libvips worker, no operation cache.
@@ -24,15 +27,33 @@ export type RenderedVariant = {
export type RenderLimits = {
maxPixels: number;
timeoutSeconds: number;
signal?: AbortSignal;
};
function input(data: Buffer, limits: RenderLimits): SharpImage {
function throwIfAborted(signal?: AbortSignal): void {
if (!signal?.aborted) return;
throw signal.reason instanceof Error
? signal.reason
: new Error('Aborted');
}
function remainingSeconds(deadline: number, total: number): number {
const remaining = Math.ceil((deadline - Date.now()) / 1000);
if (remaining <= 0) throw new JobTimeoutError(total);
return Math.min(total, remaining);
}
function input(
data: Buffer,
limits: RenderLimits,
deadline: number,
): SharpImage {
return sharp(data, {
failOn: 'warning',
limitInputPixels: limits.maxPixels,
sequentialRead: true,
})
.timeout({ seconds: limits.timeoutSeconds })
.timeout({ seconds: remainingSeconds(deadline, limits.timeoutSeconds) })
.rotate();
}
@@ -91,11 +112,16 @@ export async function renderVariants(
)
throw new UnsupportedPipelineError(pipelineVersion);
const deadline = Date.now() + limits.timeoutSeconds * 1000;
throwIfAborted(limits.signal);
const metadata = await sharp(data, {
failOn: 'warning',
limitInputPixels: limits.maxPixels,
sequentialRead: true,
}).metadata();
})
.timeout({ seconds: remainingSeconds(deadline, limits.timeoutSeconds) })
.metadata();
throwIfAborted(limits.signal);
const width = metadata.autoOrient?.width ?? metadata.width;
const height = metadata.autoOrient?.height ?? metadata.height;
const [thumbnailWidth, thumbnailHeight] = fitInside(width, height, 256);
@@ -103,9 +129,11 @@ export async function renderVariants(
const v2 = pipelineVersion >= 2;
const thumbnail = v2 ? jpegV2 : jpegV1;
throwIfAborted(limits.signal);
remainingSeconds(deadline, limits.timeoutSeconds);
const thumbnailOutput = await output(
thumbnail(
input(data, limits)
input(data, limits, deadline)
.flatten({ background: '#ffffff' })
.resize(thumbnailWidth, thumbnailHeight, { fit: 'fill' }),
),
@@ -114,9 +142,11 @@ export async function renderVariants(
'image/jpeg',
);
throwIfAborted(limits.signal);
remainingSeconds(deadline, limits.timeoutSeconds);
const cropOutput = await output(
thumbnail(
input(data, limits)
input(data, limits, deadline)
.flatten({ background: '#ffffff' })
.resize(128, 128, { fit: 'cover', position: 'centre' }),
),
@@ -125,8 +155,10 @@ export async function renderVariants(
'image/jpeg',
);
throwIfAborted(limits.signal);
remainingSeconds(deadline, limits.timeoutSeconds);
const optimizedOutput = await output(
input(data, limits)
input(data, limits, deadline)
.resize(optimizedWidth, optimizedHeight, { fit: 'fill' })
.webp(
v2
@@ -138,5 +170,6 @@ export async function renderVariants(
'image/webp',
);
throwIfAborted(limits.signal);
return [thumbnailOutput, cropOutput, optimizedOutput];
}
+9 -1
View File
@@ -63,11 +63,11 @@ export class StagingCleaner implements OnModuleInit, OnModuleDestroy {
let deleted = 0;
for (const candidate of candidates) {
try {
await this.storage.delete(candidate.staging_key);
if (
await this.jobs.clearStaging(
candidate.id,
candidate.staging_key,
(key) => this.storage.delete(key),
)
)
deleted += 1;
@@ -79,6 +79,14 @@ export class StagingCleaner implements OnModuleInit, OnModuleDestroy {
}
}
if (deleted > 0) this.metrics.add('worker.staging.deleted', deleted);
const outbox = await this.jobs.pruneOutbox(
this.config.getOrThrow('OUTBOX_RETENTION_SECONDS'),
);
if (outbox > 0) this.metrics.add('jobs.outbox.pruned', outbox);
const events = await this.jobs.pruneEvents(
this.config.getOrThrow('JOB_EVENTS_RETENTION_SECONDS'),
);
if (events > 0) this.metrics.add('jobs.events.pruned', events);
return deleted;
}
}
+4 -1
View File
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { AppConfigModule } from '../config/app-config.module.js';
import { DatabaseModule } from '../database/database.module.js';
import { JobsModule } from '../jobs/jobs.module.js';
import { OutboxRelay } from '../jobs/outbox-relay.service.js';
import { MetricsModule } from '../metrics/metrics.module.js';
import { RedisModule } from '../redis/redis.module.js';
import { StorageModule } from '../storage/storage.module.js';
@@ -18,6 +19,8 @@ import { StagingCleaner } from './staging-cleaner.service.js';
StorageModule,
JobsModule,
],
providers: [JobProcessor, LeaseReaper, StagingCleaner],
// The worker publishes retry and lease-expiry outbox rows itself; the same
// relay also runs in the API process. SKIP LOCKED makes that safe.
providers: [JobProcessor, LeaseReaper, StagingCleaner, OutboxRelay],
})
export class WorkerModule {}