-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathqueue.spec.ts
More file actions
326 lines (284 loc) · 11.9 KB
/
queue.spec.ts
File metadata and controls
326 lines (284 loc) · 11.9 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { describe, expect, it, vi } from "vitest";
import { DurableObjectQueueHandler } from "./queue";
vi.mock("cloudflare:workers", () => ({
DurableObject: class {
constructor(
public ctx: DurableObjectState,
public env: CloudflareEnv
) {}
},
}));
const createDurableObjectQueue = ({
fetchDuration,
statusCode,
headers,
}: {
fetchDuration: number;
statusCode?: number;
headers?: Headers;
}) => {
const mockState = {
waitUntil: vi.fn(),
blockConcurrencyWhile: vi.fn().mockImplementation(async (fn) => fn()),
storage: {
setAlarm: vi.fn(),
getAlarm: vi.fn(),
sql: {
exec: vi.fn().mockImplementation(() => ({
one: vi.fn(),
})),
},
},
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new DurableObjectQueueHandler(mockState as any, {
NEXT_CACHE_REVALIDATION_WORKER: {
fetch: vi.fn().mockReturnValue(
new Promise<Response>((res) =>
setTimeout(
() =>
res(
new Response(null, {
status: statusCode,
headers: headers ?? new Headers([["x-nextjs-cache", "REVALIDATED"]]),
})
),
fetchDuration
)
)
),
connect: vi.fn(),
},
});
};
const createMessage = (dedupId: string, lastModified = Date.now()) => ({
MessageBody: { host: "test.local", url: "/test", eTag: "test", lastModified },
MessageGroupId: "test.local/test",
MessageDeduplicationId: dedupId,
previewModeId: "test",
});
describe("DurableObjectQueue", () => {
describe("successful revalidation", () => {
it("should process a single revalidation", async () => {
process.env.__NEXT_PREVIEW_MODE_ID = "test";
const queue = createDurableObjectQueue({ fetchDuration: 10 });
const firstRequest = await queue.revalidate(createMessage("id"));
expect(firstRequest).toBeUndefined();
expect(queue.ongoingRevalidations.size).toBe(1);
expect(queue.ongoingRevalidations.has("id")).toBe(true);
await queue.ongoingRevalidations.get("id");
expect(queue.ongoingRevalidations.size).toBe(0);
expect(queue.ongoingRevalidations.has("id")).toBe(false);
expect(queue.service.fetch).toHaveBeenCalledWith("https://test.local/test", {
method: "HEAD",
headers: {
"x-prerender-revalidate": "test",
"x-isr": "1",
},
signal: expect.any(AbortSignal),
});
});
it("should dedupe revalidations", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
await queue.revalidate(createMessage("id"));
await queue.revalidate(createMessage("id"));
expect(queue.ongoingRevalidations.size).toBe(1);
expect(queue.ongoingRevalidations.has("id")).toBe(true);
});
it("should block concurrency", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
await queue.revalidate(createMessage("id"));
await queue.revalidate(createMessage("id2"));
await queue.revalidate(createMessage("id3"));
await queue.revalidate(createMessage("id4"));
await queue.revalidate(createMessage("id5"));
// the next one should block until one of the previous ones finishes
const blockedReq = queue.revalidate(createMessage("id6"));
expect(queue.ongoingRevalidations.size).toBe(queue.maxRevalidations);
expect(queue.ongoingRevalidations.has("id6")).toBe(false);
expect(Array.from(queue.ongoingRevalidations.keys())).toEqual(["id", "id2", "id3", "id4", "id5"]);
// BlockConcurrencyWhile is called twice here, first time during creation of the object and second time when we try to revalidate
// @ts-expect-error
expect(queue.ctx.blockConcurrencyWhile).toHaveBeenCalledTimes(2);
// Here we await the blocked request to ensure it's resolved
await blockedReq;
// We then need to await for the actual revalidation to finish
await Promise.all(Array.from(queue.ongoingRevalidations.values()));
expect(queue.ongoingRevalidations.size).toBe(0);
expect(queue.service.fetch).toHaveBeenCalledTimes(6);
});
});
describe("failed revalidation", () => {
it("should not put it in failed state for an incorrect 200", async () => {
const queue = createDurableObjectQueue({
fetchDuration: 10,
statusCode: 200,
headers: new Headers([["x-nextjs-cache", "MISS"]]),
});
await queue.revalidate(createMessage("id"));
await queue.ongoingRevalidations.get("id");
expect(queue.routeInFailedState.size).toBe(0);
});
it("should not put it in failed state for a failed revalidation with 404", async () => {
const queue = createDurableObjectQueue({
fetchDuration: 10,
statusCode: 404,
});
await queue.revalidate(createMessage("id"));
await queue.ongoingRevalidations.get("id");
expect(queue.routeInFailedState.size).toBe(0);
expect(queue.service.fetch).toHaveBeenCalledTimes(1);
await queue.revalidate(createMessage("id"));
expect(queue.routeInFailedState.size).toBe(0);
expect(queue.service.fetch).toHaveBeenCalledTimes(2);
});
it("should put it in failed state if revalidation fails with 500", async () => {
const queue = createDurableObjectQueue({
fetchDuration: 10,
statusCode: 500,
});
await queue.revalidate(createMessage("id"));
await queue.ongoingRevalidations.get("id");
expect(queue.routeInFailedState.size).toBe(1);
expect(queue.routeInFailedState.has("id")).toBe(true);
expect(queue.service.fetch).toHaveBeenCalledTimes(1);
await queue.revalidate(createMessage("id"));
expect(queue.routeInFailedState.size).toBe(1);
expect(queue.service.fetch).toHaveBeenCalledTimes(1);
});
it("should put it in failed state if revalidation fetch throw", async () => {
const queue = createDurableObjectQueue({
fetchDuration: 10,
});
// @ts-expect-error - This is mocked above
queue.service.fetch.mockImplementationOnce(() => Promise.reject(new Error("fetch error")));
await queue.revalidate(createMessage("id"));
await queue.ongoingRevalidations.get("id");
expect(queue.routeInFailedState.size).toBe(1);
expect(queue.routeInFailedState.has("id")).toBe(true);
expect(queue.ongoingRevalidations.size).toBe(0);
expect(queue.service.fetch).toHaveBeenCalledTimes(1);
await queue.revalidate(createMessage("id"));
expect(queue.routeInFailedState.size).toBe(1);
expect(queue.service.fetch).toHaveBeenCalledTimes(1);
});
});
describe("addAlarm", () => {
const getStorage = (queue: DurableObjectQueueHandler): DurableObjectStorage => {
// @ts-expect-error - ctx is a protected field
return queue.ctx.storage;
};
it("should not add an alarm if there are no failed states", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
await queue.addAlarm();
expect(getStorage(queue).setAlarm).not.toHaveBeenCalled();
});
it("should add an alarm if there are failed states", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
const nextAlarmMs = Date.now() + 1000;
queue.routeInFailedState.set("id", { msg: createMessage("id"), retryCount: 0, nextAlarmMs });
await queue.addAlarm();
expect(getStorage(queue).setAlarm).toHaveBeenCalledWith(nextAlarmMs);
});
it("should not add an alarm if there is already an alarm set", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
queue.routeInFailedState.set("id", { msg: createMessage("id"), retryCount: 0, nextAlarmMs: 1000 });
// @ts-expect-error
queue.ctx.storage.getAlarm.mockResolvedValueOnce(1000);
await queue.addAlarm();
expect(getStorage(queue).setAlarm).not.toHaveBeenCalled();
});
it("should set the alarm to the lowest nextAlarm", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
const nextAlarmMs = Date.now() + 1000;
const firstAlarm = Date.now() + 500;
queue.routeInFailedState.set("id", { msg: createMessage("id"), retryCount: 0, nextAlarmMs });
queue.routeInFailedState.set("id2", {
msg: createMessage("id2"),
retryCount: 0,
nextAlarmMs: firstAlarm,
});
await queue.addAlarm();
expect(getStorage(queue).setAlarm).toHaveBeenCalledWith(firstAlarm);
});
});
describe("addToFailedState", () => {
it("should add a failed state", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
await queue.addToFailedState(createMessage("id"));
expect(queue.routeInFailedState.size).toBe(1);
expect(queue.routeInFailedState.has("id")).toBe(true);
expect(queue.routeInFailedState.get("id")?.retryCount).toBe(1);
});
it("should add a failed state with the correct nextAlarm", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
await queue.addToFailedState(createMessage("id"));
expect(queue.routeInFailedState.get("id")?.nextAlarmMs).toBeGreaterThan(Date.now());
expect(queue.routeInFailedState.get("id")?.retryCount).toBe(1);
});
it("should add a failed state with the correct nextAlarm for a retry", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
await queue.addToFailedState(createMessage("id"));
await queue.addToFailedState(createMessage("id"));
expect(queue.routeInFailedState.get("id")?.nextAlarmMs).toBeGreaterThan(Date.now());
expect(queue.routeInFailedState.get("id")?.retryCount).toBe(2);
});
it("should not add a failed state if it has been retried 6 times", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
queue.routeInFailedState.set("id", { msg: createMessage("id"), retryCount: 6, nextAlarmMs: 1000 });
await queue.addToFailedState(createMessage("id"));
expect(queue.routeInFailedState.size).toBe(0);
});
});
describe("alarm", () => {
it("should execute revalidations for expired events", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
queue.routeInFailedState.set("id", {
msg: createMessage("id"),
retryCount: 0,
nextAlarmMs: Date.now() - 1000,
});
queue.routeInFailedState.set("id2", {
msg: createMessage("id2"),
retryCount: 0,
nextAlarmMs: Date.now() - 1000,
});
await queue.alarm();
expect(queue.routeInFailedState.size).toBe(0);
expect(queue.service.fetch).toHaveBeenCalledTimes(2);
});
it("should execute revalidations for the next event to retry", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
queue.routeInFailedState.set("id", {
msg: createMessage("id"),
retryCount: 0,
nextAlarmMs: Date.now() + 1000,
});
queue.routeInFailedState.set("id2", {
msg: createMessage("id2"),
retryCount: 0,
nextAlarmMs: Date.now() + 500,
});
await queue.alarm();
expect(queue.routeInFailedState.size).toBe(1);
expect(queue.service.fetch).toHaveBeenCalledTimes(1);
expect(queue.routeInFailedState.has("id2")).toBe(false);
});
it("should execute revalidations for the next event to retry and expired events", async () => {
const queue = createDurableObjectQueue({ fetchDuration: 10 });
queue.routeInFailedState.set("id", {
msg: createMessage("id"),
retryCount: 0,
nextAlarmMs: Date.now() + 1000,
});
queue.routeInFailedState.set("id2", {
msg: createMessage("id2"),
retryCount: 0,
nextAlarmMs: Date.now() - 1000,
});
await queue.alarm();
expect(queue.routeInFailedState.size).toBe(0);
expect(queue.service.fetch).toHaveBeenCalledTimes(2);
});
});
});