Repository navigation
Expand file tree
/
Copy pathworker.ts
More file actions
151 lines (123 loc) · 3.95 KB
/
Copy pathworker.ts
File metadata and controls
151 lines (123 loc) · 3.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { EmailLogStatus, Prisma } from "@/generated/prisma/client";
import { randomUUID } from "node:crypto";
import {
BOOKING_REMINDER_SCAN_INTERVAL_MS,
enqueueBookingReminder24hJobs,
} from "@/features/booking/lib/booking-reminders";
import { deliverEmailLog } from "@/lib/email/delivery";
import { getEmailWorkerStaleBefore } from "@/lib/email/booking-delivery-fence";
import { prisma } from "@/lib/prisma";
import { cleanupExpiredRateLimitReservations } from "@/lib/security/rate-limit-reservation-cleanup";
const WORKER_BATCH_SIZE = 10;
const WORKER_IDLE_DELAY_MS = 5_000;
const MAX_ITERATIONS_PER_RUN = 1_000;
const RATE_LIMIT_CLEANUP_INTERVAL_MS = 15 * 60 * 1_000;
export type EmailWorkerConfig = {
once?: boolean;
};
type ClaimedEmailLog = {
id: string;
processingToken: string;
};
async function claimDueEmailLogs(limit: number): Promise<ClaimedEmailLog[]> {
const now = new Date();
const staleBefore = getEmailWorkerStaleBefore(now);
return prisma.$transaction(async (tx) => {
const rows = await tx.$queryRaw<Array<{ id: string }>>(Prisma.sql`
SELECT "id"
FROM "EmailLog"
WHERE "status" = ${EmailLogStatus.PENDING}
AND "nextAttemptAt" <= ${now}
AND ("processingStartedAt" IS NULL OR "processingStartedAt" < ${staleBefore})
ORDER BY "createdAt" ASC
LIMIT ${limit}
FOR UPDATE SKIP LOCKED
`);
const claimed: ClaimedEmailLog[] = [];
for (const row of rows) {
const processingToken = randomUUID();
const updated = await tx.emailLog.update({
where: {
id: row.id,
},
data: {
attemptCount: {
increment: 1,
},
processingStartedAt: now,
processingToken,
},
select: {
id: true,
processingToken: true,
},
});
const claimedProcessingToken = updated.processingToken;
if (!claimedProcessingToken) {
throw new Error(`Claim e-mailu ${updated.id} nevytvořil processing token.`);
}
claimed.push({
id: updated.id,
processingToken: claimedProcessingToken,
});
}
return claimed;
});
}
export async function runEmailDeliveryWorkerOnce() {
let processed = 0;
while (processed < MAX_ITERATIONS_PER_RUN) {
const batch = await claimDueEmailLogs(WORKER_BATCH_SIZE);
if (batch.length === 0) {
break;
}
for (const emailLog of batch) {
await deliverEmailLog(emailLog.id, emailLog.processingToken);
processed += 1;
}
}
return processed;
}
export async function runBookingReminderSchedulerOnce(now = new Date()) {
const result = await enqueueBookingReminder24hJobs(now);
console.info("Booking reminder 24h scan finished", {
at: now.toISOString(),
foundBookings: result.foundBookings,
enqueued: result.enqueued,
failed: result.failed,
});
return result;
}
export async function runRateLimitReservationCleanupOnce(now = new Date()) {
const deleted = await cleanupExpiredRateLimitReservations(prisma, now);
if (deleted > 0) {
console.info("Rate-limit reservation cleanup finished", {
at: now.toISOString(),
deleted,
});
}
return deleted;
}
export async function startEmailDeliveryWorker() {
let nextReminderScanAt = 0;
let nextRateLimitCleanupAt = 0;
while (true) {
const now = Date.now();
if (now >= nextReminderScanAt) {
await runBookingReminderSchedulerOnce(new Date(now));
nextReminderScanAt = now + BOOKING_REMINDER_SCAN_INTERVAL_MS;
}
if (now >= nextRateLimitCleanupAt) {
try {
await runRateLimitReservationCleanupOnce(new Date(now));
} catch (error) {
console.error("Rate-limit reservation cleanup failed", error);
}
nextRateLimitCleanupAt = now + RATE_LIMIT_CLEANUP_INTERVAL_MS;
}
const processed = await runEmailDeliveryWorkerOnce();
if (processed === 0) {
await new Promise((resolve) => setTimeout(resolve, WORKER_IDLE_DELAY_MS));
}
}
}