Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HookInboxStore.test.ts

319 lines12.6 KB

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