Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3import * as Clock from "effect/Clock";
4import * as DateTime from "effect/DateTime";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as SqlClient from "effect/sql/SqlClient";
10import * as TestClock from "effect/testing/TestClock";
11
12import * as HookInboxStore from "./HookInboxStore.ts";
13
14const BASE_URL = "https://env.example.test/";
15
16const hook = (id: string, overrides: Partial<HookInboxStore.HeldHook> = {}) =>
17 Effect.map(Clock.currentTimeMillis, (now): HookInboxStore.HeldHook => ({
18 id,
19 receivedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
20 method: "POST",
21 rawHookId: "hook-1",
22 hookKey: "hook-1",
23 rawToken: "tok%2Fen",
24 query: "a=1",
25 headers: { "content-type": "application/json", "x-sig": "s" },
26 body: new Uint8Array([0, 255, 10]),
27 ...overrides,
28 }));
29
30const deliverer = (outcome: (hook: HookInboxStore.HeldHook) => HookInboxStore.DeliveryOutcome) => {
31 const sent: Array<{ readonly baseUrl: string; readonly hook: HookInboxStore.HeldHook }> = [];
32 const send = (baseUrl: string, held: HookInboxStore.HeldHook) =>
33 Effect.sync(() => {
34 sent.push({ baseUrl, hook: held });
35 return outcome(held);
36 });
37 return { sent, send };
38};
39
40const withInbox = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
41 HookInboxStore.migrate.pipe(
42 Effect.andThen(effect),
43 Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" })),
44 );
45
46describe("HookInboxStore", () => {
47 it.effect.each(["delivered", "busy", "unreachable"] as const)(
48 "stops a prefetched batch cleared during a %s send",
49 (outcome) =>
50 withInbox(
51 Effect.gen(function* () {
52 for (const id of ["first", "second", "third"]) {
53 yield* HookInboxStore.hold(yield* hook(id), BASE_URL);
54 }
55 const started = yield* Deferred.make<void>();
56 const released = yield* Deferred.make<void>();
57 const sent: Array<string> = [];
58 const run = yield* HookInboxStore.deliverDue((_baseUrl, held) =>
59 Effect.gen(function* () {
60 sent.push(held.id);
61 if (held.id === "first") {
62 yield* Deferred.succeed(started, undefined);
63 yield* Deferred.await(released);
64 }
65 return outcome;
66 }),
67 ).pipe(Effect.forkChild);
68 yield* Deferred.await(started);
69 yield* HookInboxStore.clear;
70 yield* Deferred.succeed(released, undefined);
71 const nextAt = yield* Fiber.join(run);
72 expect(sent).toEqual(["first"]);
73 // The alarm must not be rescheduled, even if the in-flight send failed.
74 expect(nextAt).toBeNull();
75 const sql = yield* SqlClient.SqlClient;
76 expect(yield* sql`SELECT id FROM held_hooks`).toEqual([]);
77 expect(yield* sql`SELECT id FROM held_hooks_target`).toEqual([]);
78 }),
79 ),
80 );
81
82 it.effect("delivers held requests oldest first, byte for byte", () =>
83 withInbox(
84 Effect.gen(function* () {
85 const first = yield* hook("first");
86 expect(yield* HookInboxStore.hold(first, BASE_URL)).not.toBeNull();
87 yield* HookInboxStore.hold(yield* hook("second"), BASE_URL);
88 const { sent, send } = deliverer(() => "delivered");
89 expect(yield* HookInboxStore.deliverDue(send)).toBeNull();
90 expect(sent.map((entry) => entry.hook.id)).toEqual(["first", "second"]);
91 expect(sent[0]).toEqual({ baseUrl: BASE_URL, hook: first });
92 expect(yield* HookInboxStore.deliverDue(send)).toBeNull();
93 expect(sent).toHaveLength(2);
94 }),
95 ),
96 );
97
98 it.effect("keeps a request the environment did not take and backs off", () =>
99 withInbox(
100 Effect.gen(function* () {
101 yield* HookInboxStore.hold(yield* hook("first"), BASE_URL);
102 yield* HookInboxStore.hold(yield* hook("second"), BASE_URL);
103 const offline = deliverer(() => "unreachable");
104 const now = yield* Clock.currentTimeMillis;
105 expect(yield* HookInboxStore.deliverDue(offline.send)).toBe(now + 10_000);
106 expect(offline.sent.map((entry) => entry.hook.id)).toEqual(["first"]);
107 expect(yield* HookInboxStore.deliverDue(offline.send)).toBe(now + 10_000);
108
109 const online = deliverer(() => "delivered");
110 expect(yield* HookInboxStore.deliverDue(online.send)).toBeNull();
111 expect(online.sent.map((entry) => entry.hook.id)).toEqual(["first", "second"]);
112 }),
113 ),
114 );
115
116 it.effect("lets other hooks through while one hook's environment is busy", () =>
117 withInbox(
118 Effect.gen(function* () {
119 const stuck = { rawHookId: "stuck", hookKey: "stuck" };
120 yield* HookInboxStore.hold(yield* hook("stuck-1", stuck), BASE_URL);
121 yield* HookInboxStore.hold(yield* hook("other-1"), BASE_URL);
122 yield* HookInboxStore.hold(yield* hook("stuck-2", stuck), BASE_URL);
123 const busy = deliverer((held) => (held.hookKey === "stuck" ? "busy" : "delivered"));
124 const now = yield* Clock.currentTimeMillis;
125 expect(yield* HookInboxStore.deliverDue(busy.send)).toBe(now);
126 expect(busy.sent.map((entry) => entry.hook.id)).toEqual(["stuck-1", "other-1"]);
127 expect(yield* HookInboxStore.deliverDue(busy.send)).toBe(now + 30_000);
128
129 const drained = deliverer(() => "delivered");
130 expect(yield* HookInboxStore.deliverDue(drained.send)).toBeNull();
131 expect(drained.sent.map((entry) => entry.hook.id)).toEqual(["stuck-1", "stuck-2"]);
132 }),
133 ),
134 );
135
136 it.effect("reaches a hook queued behind busy hooks' full backlogs in the same run", () =>
137 withInbox(
138 Effect.gen(function* () {
139 for (const name of ["stuck-a", "stuck-b"]) {
140 const stuck = { rawHookId: name, hookKey: name };
141 for (let index = 0; index < HookInboxStore.HOOK_INBOX_MAX_PER_HOOK; index++) {
142 yield* HookInboxStore.hold(yield* hook(`${name}-${index}`, stuck), BASE_URL);
143 }
144 }
145 yield* HookInboxStore.hold(yield* hook("other-1"), BASE_URL);
146 const busy = deliverer((held) => (held.hookKey.startsWith("stuck") ? "busy" : "delivered"));
147 yield* HookInboxStore.deliverDue(busy.send);
148 expect(busy.sent.map((entry) => entry.hook.id)).toEqual([
149 "stuck-a-0",
150 "stuck-b-0",
151 "other-1",
152 ]);
153 }),
154 ),
155 );
156
157 it.effect("drops a held request it cannot read instead of stalling on it", () =>
158 withInbox(
159 Effect.gen(function* () {
160 yield* HookInboxStore.hold(yield* hook("broken"), BASE_URL);
161 yield* HookInboxStore.hold(yield* hook("fine"), BASE_URL);
162 const sql = yield* SqlClient.SqlClient;
163 yield* sql`UPDATE held_hooks SET headers = 'not json' WHERE id = 'broken'`;
164 const { sent, send } = deliverer(() => "delivered");
165 expect(yield* HookInboxStore.deliverDue(send)).toBeNull();
166 expect(sent.map((entry) => entry.hook.id)).toEqual(["fine"]);
167 }),
168 ),
169 );
170
171 it.effect("retries every 10 s for 3 minutes, then backs off to 10 minutes", () =>
172 Effect.gen(function* () {
173 const delays = yield* Effect.forEach(
174 [1, 18, 19, 20, 21, 23, 24, 40],
175 HookInboxStore.retryDelayMs,
176 );
177 expect(delays).toEqual([10_000, 10_000, 30_000, 60_000, 120_000, 480_000, 600_000, 600_000]);
178 }),
179 );
180
181 it.effect("waking resets the backoff and reports whether anything waits", () =>
182 withInbox(
183 Effect.gen(function* () {
184 expect(yield* HookInboxStore.wake(BASE_URL)).toBe(false);
185 yield* HookInboxStore.hold(yield* hook("first"), "https://old.example.test/");
186 const offline = deliverer(() => "unreachable");
187 yield* HookInboxStore.deliverDue(offline.send);
188 yield* HookInboxStore.deliverDue(offline.send);
189
190 for (let failure = 0; failure < 20; failure++) {
191 yield* HookInboxStore.deliverDue(offline.send);
192 }
193 const now = yield* Clock.currentTimeMillis;
194 expect(yield* HookInboxStore.deliverDue(offline.send)).toBeGreaterThan(now + 60_000);
195
196 // A wake means its tunnel just connected, which Cloudflare may not
197 // route to for a few minutes: back to retrying every 10 s, sent to
198 // where the environment is now.
199 expect(yield* HookInboxStore.wake(BASE_URL)).toBe(true);
200 expect(yield* HookInboxStore.deliverDue(offline.send)).toBe(now + 10_000);
201 expect(offline.sent.at(-1)?.baseUrl).toBe(BASE_URL);
202 }),
203 ),
204 );
205
206 it.effect("starts the schedule over once the inbox drains", () =>
207 withInbox(
208 Effect.gen(function* () {
209 yield* HookInboxStore.hold(yield* hook("old"), BASE_URL);
210 const offline = deliverer(() => "unreachable");
211 for (let failure = 0; failure < 30; failure++) {
212 yield* HookInboxStore.deliverDue(offline.send);
213 }
214 yield* TestClock.adjust(Duration.hours(25));
215 expect(yield* HookInboxStore.deliverDue(offline.send)).toBeNull();
216
217 const now = yield* Clock.currentTimeMillis;
218 expect(yield* HookInboxStore.hold(yield* hook("new"), BASE_URL)).toBe(now + 10_000);
219 }),
220 ),
221 );
222
223 it.effect("drops requests older than 24 hours", () =>
224 withInbox(
225 Effect.gen(function* () {
226 yield* HookInboxStore.hold(yield* hook("old"), BASE_URL);
227 yield* TestClock.adjust(Duration.hours(1));
228 yield* HookInboxStore.hold(yield* hook("new"), BASE_URL);
229 yield* TestClock.adjust(Duration.minutes(23 * 60 + 1));
230 const { sent, send } = deliverer(() => "delivered");
231 yield* HookInboxStore.deliverDue(send);
232 expect(sent.map((entry) => entry.hook.id)).toEqual(["new"]);
233 }),
234 ),
235 );
236
237 it.effect("refuses requests past the per-hook cap", () =>
238 withInbox(
239 Effect.gen(function* () {
240 for (let index = 0; index < HookInboxStore.HOOK_INBOX_MAX_PER_HOOK; index++) {
241 expect(yield* HookInboxStore.hold(yield* hook(`a-${index}`), BASE_URL)).not.toBeNull();
242 }
243 expect(yield* HookInboxStore.hold(yield* hook("one-too-many"), BASE_URL)).toBeNull();
244 const other = yield* hook("other", { rawHookId: "hook-2", hookKey: "hook-2" });
245 expect(yield* HookInboxStore.hold(other, BASE_URL)).not.toBeNull();
246 }),
247 ),
248 );
249
250 it.effect("refuses a request that would pass the byte cap", () =>
251 withInbox(
252 Effect.gen(function* () {
253 const big = new Uint8Array(HookInboxStore.HOOK_INBOX_MAX_BYTES - 10);
254 expect(
255 yield* HookInboxStore.hold(yield* hook("big", { body: big }), BASE_URL),
256 ).not.toBeNull();
257 const small = new Uint8Array(11);
258 expect(
259 yield* HookInboxStore.hold(
260 yield* hook("small", { rawHookId: "x", hookKey: "x", body: small }),
261 BASE_URL,
262 ),
263 ).toBeNull();
264 }),
265 ),
266 );
267
268 it.effect("stores a request id once", () =>
269 withInbox(
270 Effect.gen(function* () {
271 const first = yield* hook("same");
272 expect(yield* HookInboxStore.hold(first, BASE_URL)).not.toBeNull();
273 expect(yield* HookInboxStore.hold(first, BASE_URL)).toBeNull();
274 }),
275 ),
276 );
277
278 it.effect("clear drops everything held", () =>
279 withInbox(
280 Effect.gen(function* () {
281 yield* HookInboxStore.hold(yield* hook("first"), BASE_URL);
282 yield* HookInboxStore.clear;
283 const { sent, send } = deliverer(() => "delivered");
284 expect(yield* HookInboxStore.deliverDue(send)).toBeNull();
285 expect(sent).toHaveLength(0);
286 }),
287 ),
288 );
289});