218 lines
5.1 KiB
TypeScript
218 lines
5.1 KiB
TypeScript
import { AttachmentJob, Prisma, PrismaClient } from '@prisma/client';
|
|
import { randomUUID } from 'crypto';
|
|
import { jobMessage, PIPELINE_VERSION } from './job-message';
|
|
|
|
type Tx = Prisma.TransactionClient;
|
|
|
|
export const RETRY_EXHAUSTED = 'retry_exhausted';
|
|
|
|
export function maxAttempts(): number {
|
|
return Number(process.env.JOB_MAX_ATTEMPTS ?? 5);
|
|
}
|
|
|
|
export function backoffMs(attempt: number, random = Math.random): number {
|
|
const base = Number(process.env.JOB_RETRY_BASE_MS ?? 1000);
|
|
const cap = Number(process.env.JOB_RETRY_MAX_MS ?? 30000);
|
|
const delay = Math.min(cap, base * 2 ** (attempt - 1));
|
|
return Math.round(delay / 2 + random() * (delay / 2));
|
|
}
|
|
|
|
export async function enqueueJob(
|
|
tx: Tx,
|
|
attachmentId: string,
|
|
now: Date,
|
|
): Promise<AttachmentJob> {
|
|
const job = await tx.attachmentJob.create({
|
|
data: {
|
|
id: randomUUID(),
|
|
attachmentId,
|
|
pipelineVersion: PIPELINE_VERSION,
|
|
status: 'queued',
|
|
attempt: 1,
|
|
maxAttempts: maxAttempts(),
|
|
nextAttemptAt: now,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
},
|
|
});
|
|
await tx.jobEvent.create({
|
|
data: { jobId: job.id, attempt: 1, event: 'enqueued', createdAt: now },
|
|
});
|
|
await publishLater(tx, job, now);
|
|
return job;
|
|
}
|
|
|
|
export async function scheduleRetry(
|
|
tx: Tx,
|
|
job: AttachmentJob,
|
|
reason: string,
|
|
now: Date,
|
|
event = 'retry_scheduled',
|
|
): Promise<AttachmentJob> {
|
|
const delay = backoffMs(job.attempt);
|
|
const next = await tx.attachmentJob.update({
|
|
where: { id: job.id },
|
|
data: {
|
|
status: 'queued',
|
|
attempt: job.attempt + 1,
|
|
nextAttemptAt: new Date(now.getTime() + delay),
|
|
leaseOwner: null,
|
|
leaseUntil: null,
|
|
lastError: reason,
|
|
},
|
|
});
|
|
await tx.attachment.update({
|
|
where: { id: job.attachmentId },
|
|
data: { status: 'queued' },
|
|
});
|
|
await tx.jobEvent.create({
|
|
data: {
|
|
jobId: job.id,
|
|
attempt: job.attempt,
|
|
event,
|
|
detail: `${reason}; next attempt ${next.attempt} in ${delay} ms`,
|
|
createdAt: now,
|
|
},
|
|
});
|
|
await publishLater(tx, next, next.nextAttemptAt);
|
|
return next;
|
|
}
|
|
|
|
export async function markFailed(
|
|
tx: Tx,
|
|
job: AttachmentJob,
|
|
errorCode: string,
|
|
reason: string,
|
|
now: Date,
|
|
): Promise<void> {
|
|
await tx.attachmentJob.update({
|
|
where: { id: job.id },
|
|
data: {
|
|
status: 'failed',
|
|
errorCode,
|
|
lastError: reason,
|
|
leaseOwner: null,
|
|
leaseUntil: null,
|
|
finishedAt: now,
|
|
},
|
|
});
|
|
await tx.attachment.update({
|
|
where: { id: job.attachmentId },
|
|
data: { status: 'failed', errorCode },
|
|
});
|
|
await tx.jobEvent.create({
|
|
data: {
|
|
jobId: job.id,
|
|
attempt: job.attempt,
|
|
event: 'failed',
|
|
detail: `${errorCode}: ${reason}`,
|
|
createdAt: now,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function retryOrFail(
|
|
tx: Tx,
|
|
job: AttachmentJob,
|
|
reason: string,
|
|
now: Date,
|
|
event?: string,
|
|
): Promise<'retry' | 'failed'> {
|
|
if (job.attempt >= job.maxAttempts) {
|
|
await markFailed(tx, job, RETRY_EXHAUSTED, reason, now);
|
|
return 'failed';
|
|
}
|
|
await scheduleRetry(tx, job, reason, now, event);
|
|
return 'retry';
|
|
}
|
|
|
|
export async function recoverExpiredLeases(
|
|
prisma: PrismaClient,
|
|
now = new Date(),
|
|
limit = 100,
|
|
): Promise<number> {
|
|
const expired = await prisma.attachmentJob.findMany({
|
|
where: { status: 'processing', leaseUntil: { lt: now } },
|
|
orderBy: { leaseUntil: 'asc' },
|
|
take: limit,
|
|
});
|
|
let recovered = 0;
|
|
for (const candidate of expired) {
|
|
await prisma.$transaction(async (tx) => {
|
|
const taken = await tx.attachmentJob.updateMany({
|
|
where: {
|
|
id: candidate.id,
|
|
status: 'processing',
|
|
leaseOwner: candidate.leaseOwner,
|
|
leaseUntil: { lt: now },
|
|
},
|
|
data: { leaseOwner: null, leaseUntil: null, status: 'queued' },
|
|
});
|
|
if (taken.count === 0) {
|
|
return;
|
|
}
|
|
await retryOrFail(tx, candidate, 'lease expired', now, 'lease_expired');
|
|
recovered++;
|
|
});
|
|
}
|
|
return recovered;
|
|
}
|
|
|
|
export type ReplayResult = 'replayed' | 'already_ready' | 'not_failed' | 'not_found';
|
|
|
|
export async function replayJob(
|
|
prisma: PrismaClient,
|
|
jobId: string,
|
|
actor: string,
|
|
now = new Date(),
|
|
): Promise<ReplayResult> {
|
|
return prisma.$transaction(async (tx) => {
|
|
const job = await tx.attachmentJob.findUnique({ where: { id: jobId } });
|
|
if (!job) {
|
|
return 'not_found';
|
|
}
|
|
if (job.status === 'ready') {
|
|
return 'already_ready';
|
|
}
|
|
const taken = await tx.attachmentJob.updateMany({
|
|
where: { id: jobId, status: 'failed' },
|
|
data: {
|
|
status: 'queued',
|
|
attempt: 1,
|
|
errorCode: null,
|
|
nextAttemptAt: now,
|
|
finishedAt: null,
|
|
},
|
|
});
|
|
if (taken.count === 0) {
|
|
return 'not_failed';
|
|
}
|
|
await tx.attachment.update({
|
|
where: { id: job.attachmentId },
|
|
data: { status: 'queued', errorCode: null },
|
|
});
|
|
await tx.jobEvent.create({
|
|
data: {
|
|
jobId,
|
|
attempt: 1,
|
|
event: 'replayed',
|
|
detail: `by ${actor}; previous ${job.errorCode} after attempt ${job.attempt}`,
|
|
createdAt: now,
|
|
},
|
|
});
|
|
await publishLater(tx, { ...job, attempt: 1 }, now);
|
|
return 'replayed';
|
|
});
|
|
}
|
|
|
|
async function publishLater(tx: Tx, job: AttachmentJob, availableAt: Date): Promise<void> {
|
|
await tx.outboxEntry.create({
|
|
data: {
|
|
jobId: job.id,
|
|
payload: jobMessage(job, availableAt) as unknown as Prisma.InputJsonObject,
|
|
availableAt,
|
|
createdAt: new Date(),
|
|
},
|
|
});
|
|
}
|