Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as DateTime from "effect/DateTime";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Pull from "effect/Pull";
7import * as Schedule from "effect/Schedule";
8import * as Schema from "effect/Schema";
9import * as SqlClient from "effect/sql/SqlClient";
10
11const HOOK_INBOX_TTL_MS = 24 * 60 * 60 * 1000;
12
13const HOOK_INBOX_MAX_REQUESTS = 1_000;
14
15export const HOOK_INBOX_MAX_BYTES = 50 * 1_048_576;
16/**
17 * The relay cannot check tokens, so this keeps junk sent to one hook id from
18 * crowding out the others.
19 */
20export const HOOK_INBOX_MAX_PER_HOOK = 100;
21
22const DELIVERIES_PER_RUN = 20;
23
24const ROWS_READ_PER_PAGE = 50;
25
26const BUSY_RETRY_MS = 30_000;
27const MAX_RETRY_DELAY = Duration.minutes(10);
28
29const MAX_COUNTED_FAILURES = 25;
30
31/**
32 * A wake means its tunnel just connected, but Cloudflare can take a few
33 * minutes to route the hostname to it, so the first 3 minutes retry every
34 * 10 s. After that the environment is likely gone again: 30 s, 1 min, 2 min,
35 * ... up to 10 min.
36 */
37export const retrySchedule = Schedule.spaced("10 seconds").pipe(
38 Schedule.upTo({ times: 18 }),
39 Schedule.concat(
40 Schedule.exponential("30 seconds").pipe(
41 Schedule.modifyDelay(({ duration }) =>
42 Effect.succeed(Duration.min(Duration.fromInputUnsafe(duration), MAX_RETRY_DELAY)),
43 ),
44 ),
45 ),
46);
47
48export interface HeldHook {
49 readonly id: string;
50 readonly receivedAt: string;
51 readonly method: string;
52 /** Path segments exactly as the sender sent them; the environment decodes them. */
53 readonly rawHookId: string;
54 readonly rawToken: string;
55 /** The decoded hook id, so every spelling of one hook shares its cap. */
56 readonly hookKey: string;
57
58 readonly query: string;
59 readonly headers: Readonly<Record<string, string>>;
60 readonly body: Uint8Array;
61}
62
63export type DeliveryOutcome = "delivered" | "busy" | "unreachable";
64
65export const retryDelayMs = Effect.fn("HookInboxStore.retryDelayMs")(function* (failures: number) {
66 const step = yield* Schedule.toStep(retrySchedule);
67 let delay = MAX_RETRY_DELAY;
68 for (
69 let attempt = 0;
70 attempt < Math.min(Math.max(1, failures), MAX_COUNTED_FAILURES);
71 attempt++
72 ) {
73 const next = yield* step(0, undefined).pipe(
74 Effect.map(([, duration]) => Option.some(duration)),
75
76 Pull.catchDone(() => Effect.succeedNone),
77 );
78 if (Option.isNone(next)) break;
79 delay = next.value;
80 }
81 return Duration.toMillis(delay);
82});
83
84const HeadersJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
85const encodeHeaders = Schema.encodeSync(HeadersJson);
86const decodeHeaders = Schema.decodeUnknownOption(HeadersJson);
87
88interface HeldHookRow {
89 readonly seq: number;
90 readonly id: string;
91 readonly received_at: string;
92 readonly method: string;
93 readonly raw_hook_id: string;
94 readonly raw_token: string;
95 readonly hook_key: string;
96 readonly query: string;
97 readonly headers: string;
98 readonly body: Uint8Array;
99}
100
101interface TargetRow {
102 readonly base_url: string;
103 readonly failures: number;
104}
105
106const iso = (epochMillis: number) => DateTime.formatIso(DateTime.makeUnsafe(epochMillis));
107
108export const migrate = Effect.gen(function* () {
109 const sql = yield* SqlClient.SqlClient;
110 yield* sql`
111 CREATE TABLE IF NOT EXISTS held_hooks (
112 seq INTEGER PRIMARY KEY AUTOINCREMENT,
113 id TEXT NOT NULL UNIQUE,
114 received_at TEXT NOT NULL,
115 method TEXT NOT NULL,
116 raw_hook_id TEXT NOT NULL,
117 raw_token TEXT NOT NULL,
118 hook_key TEXT NOT NULL,
119 query TEXT NOT NULL,
120 headers TEXT NOT NULL,
121 body BLOB NOT NULL
122 )
123 `;
124 yield* sql`CREATE INDEX IF NOT EXISTS held_hooks_hook ON held_hooks (hook_key)`;
125
126 yield* sql`
127 CREATE TABLE IF NOT EXISTS held_hooks_target (
128 id INTEGER PRIMARY KEY CHECK (id = 1),
129 base_url TEXT NOT NULL,
130 failures INTEGER NOT NULL DEFAULT 0
131 )
132 `;
133});
134
135const setTarget = Effect.fn("HookInboxStore.setTarget")(function* (
136 baseUrl: string,
137 options: { readonly resetFailures: boolean },
138) {
139 const sql = yield* SqlClient.SqlClient;
140 yield* options.resetFailures
141 ? sql`
142 INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
143 ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url, failures = 0
144 `
145 : sql`
146 INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
147 ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url
148 `;
149});
150
151const readTarget = Effect.gen(function* () {
152 const sql = yield* SqlClient.SqlClient;
153 const rows = yield* sql<TargetRow>`SELECT base_url, failures FROM held_hooks_target WHERE id = 1`;
154 return rows[0] ?? null;
155});
156
157const resetFailures = Effect.gen(function* () {
158 const sql = yield* SqlClient.SqlClient;
159 yield* sql`UPDATE held_hooks_target SET failures = 0 WHERE id = 1`;
160});
161
162/**
163 * Incremented in place, so a wake that reset the count while this run's request
164 * was in flight is not overwritten.
165 */
166const countFailure = Effect.gen(function* () {
167 const sql = yield* SqlClient.SqlClient;
168 const rows = yield* sql<{ readonly failures: number }>`
169 UPDATE held_hooks_target SET failures = min(failures + 1, ${MAX_COUNTED_FAILURES})
170 WHERE id = 1 RETURNING failures
171 `;
172 return rows[0]?.failures ?? 1;
173});
174
175const hasPending = Effect.gen(function* () {
176 const sql = yield* SqlClient.SqlClient;
177 const rows = yield* sql<{ readonly id: string }>`SELECT id FROM held_hooks LIMIT 1`;
178 return rows.length > 0;
179});
180
181/**
182 * Returns the time the first attempt is due, or null when the inbox is full and
183 * nothing was stored.
184 */
185export const hold = Effect.fn("HookInboxStore.hold")(function* (hook: HeldHook, baseUrl: string) {
186 const sql = yield* SqlClient.SqlClient;
187 // One statement, so the caps hold however many requests arrive at once.
188 const inserted = yield* sql<{ readonly id: string }>`
189 INSERT INTO held_hooks
190 (id, received_at, method, raw_hook_id, raw_token, hook_key, query, headers, body)
191 SELECT ${hook.id}, ${hook.receivedAt}, ${hook.method}, ${hook.rawHookId}, ${hook.rawToken},
192 ${hook.hookKey}, ${hook.query}, ${encodeHeaders(hook.headers)}, ${hook.body}
193 WHERE (SELECT count(*) FROM held_hooks) < ${HOOK_INBOX_MAX_REQUESTS}
194 AND (SELECT count(*) FROM held_hooks WHERE hook_key = ${hook.hookKey})
195 < ${HOOK_INBOX_MAX_PER_HOOK}
196 AND (SELECT coalesce(sum(length(body)), 0) FROM held_hooks) + ${hook.body.byteLength}
197 <= ${HOOK_INBOX_MAX_BYTES}
198 ON CONFLICT (id) DO NOTHING
199 RETURNING id
200 `;
201 if (inserted.length === 0) {
202 yield* Effect.annotateCurrentSpan({ "relay.inbox.refused": yield* refusalReason(hook) });
203 return null;
204 }
205 yield* setTarget(baseUrl, { resetFailures: false });
206 const target = yield* readTarget;
207 const backlog = yield* backlogSize;
208 yield* Effect.annotateCurrentSpan({
209 "relay.inbox.held_count": backlog.count,
210 "relay.inbox.held_bytes": backlog.bytes,
211 });
212 return (yield* Clock.currentTimeMillis) + (yield* retryDelayMs(target?.failures ?? 0));
213});
214
215const backlogSize = Effect.gen(function* () {
216 const sql = yield* SqlClient.SqlClient;
217 const rows = yield* sql<{ readonly count: number; readonly bytes: number }>`
218 SELECT count(*) AS count, coalesce(sum(length(body)), 0) AS bytes FROM held_hooks
219 `;
220 return rows[0] ?? { count: 0, bytes: 0 };
221});
222
223const refusalReason = Effect.fn("HookInboxStore.refusalReason")(function* (hook: HeldHook) {
224 const sql = yield* SqlClient.SqlClient;
225 const existing = yield* sql<{ readonly id: string }>`
226 SELECT id FROM held_hooks WHERE id = ${hook.id}
227 `;
228 if (existing.length > 0) return "already_held";
229 const backlog = yield* backlogSize;
230 if (backlog.count >= HOOK_INBOX_MAX_REQUESTS) return "max_requests";
231 if (backlog.bytes + hook.body.byteLength > HOOK_INBOX_MAX_BYTES) return "max_bytes";
232 return "max_per_hook";
233});
234
235export const wake = Effect.fn("HookInboxStore.wake")(function* (baseUrl: string) {
236 if (!(yield* hasPending)) return false;
237 yield* setTarget(baseUrl, { resetFailures: true });
238 return true;
239});
240
241export const clear = Effect.gen(function* () {
242 const sql = yield* SqlClient.SqlClient;
243 yield* sql`DELETE FROM held_hooks`;
244 yield* sql`DELETE FROM held_hooks_target`;
245});
246
247export const deliverDue = Effect.fn("HookInboxStore.deliverDue")(function* <R>(
248 send: (baseUrl: string, hook: HeldHook) => Effect.Effect<DeliveryOutcome, never, R>,
249) {
250 const sql = yield* SqlClient.SqlClient;
251 const startedAt = yield* Clock.currentTimeMillis;
252 const expired = yield* sql<{ readonly id: string }>`
253 DELETE FROM held_hooks WHERE received_at < ${iso(startedAt - HOOK_INBOX_TTL_MS)}
254 RETURNING id
255 `;
256 const target = yield* readTarget;
257
258 const readPage = (afterSeq: number, skip: ReadonlySet<string>) =>
259 sql<HeldHookRow>`
260 SELECT seq, id, received_at, method, raw_hook_id, raw_token, hook_key, query, headers, body
261 FROM held_hooks
262 WHERE seq > ${afterSeq}
263 ${skip.size === 0 ? sql`` : sql`AND hook_key NOT IN ${sql.in([...skip])}`}
264 ORDER BY seq LIMIT ${ROWS_READ_PER_PAGE}
265 `;
266 let batch = yield* readPage(0, new Set());
267 if (batch.length === 0 || target === null) {
268 if (target === null) yield* sql`DELETE FROM held_hooks`;
269 else yield* resetFailures;
270 yield* Effect.annotateCurrentSpan({ "relay.inbox.expired": expired.length });
271 return null;
272 }
273
274 let failures = target.failures;
275 let sent = 0;
276 let delivered = 0;
277 let unreadable = 0;
278 let longestWaitMs = 0;
279 const busyHooks = new Set<string>();
280
281 // Delivery results and counts belong to the enclosing deliverDue span.
282 const annotateRun = Effect.fnUntraced(function* (result: string) {
283 const backlog = yield* backlogSize;
284 yield* Effect.annotateCurrentSpan({
285 "relay.inbox.run_result": result,
286 "relay.inbox.sent": sent,
287 "relay.inbox.delivered": delivered,
288 "relay.inbox.busy_hooks": busyHooks.size,
289 "relay.inbox.expired": expired.length,
290 "relay.inbox.unreadable": unreadable,
291 "relay.inbox.consecutive_failures": failures,
292 "relay.inbox.longest_wait_ms": longestWaitMs,
293 "relay.inbox.held_count": backlog.count,
294 "relay.inbox.held_bytes": backlog.bytes,
295 });
296 });
297 const stillHeld = (seq: number) =>
298 sql<{ readonly seq: number }>`SELECT seq FROM held_hooks WHERE seq = ${seq}`.pipe(
299 Effect.map((rows) => rows.length > 0),
300 );
301 // Pages run out only once every non-busy request has been tried, so a
302 // backlog behind busy hooks never hides another hook's requests.
303 pages: while (batch.length > 0) {
304 for (const row of batch) {
305 if (sent === DELIVERIES_PER_RUN) break pages;
306
307 if (busyHooks.has(row.hook_key)) continue;
308 // Clear can discard this prefetched page while an upstream send is in flight.
309 if (!(yield* stillHeld(row.seq))) {
310 yield* annotateRun("cleared");
311 return null;
312 }
313 const headers = decodeHeaders(row.headers);
314 if (Option.isNone(headers)) {
315 // Unreadable: it can never be delivered, and must not block the rest.
316 yield* sql`DELETE FROM held_hooks WHERE id = ${row.id}`;
317 unreadable += 1;
318 continue;
319 }
320 sent += 1;
321 const outcome = yield* send(target.base_url, {
322 id: row.id,
323 receivedAt: row.received_at,
324 method: row.method,
325 rawHookId: row.raw_hook_id,
326 rawToken: row.raw_token,
327 hookKey: row.hook_key,
328 query: row.query,
329 headers: headers.value,
330 body: row.body,
331 });
332 // A cleared request must neither advance this run nor schedule a retry.
333 if (!(yield* stillHeld(row.seq))) {
334 yield* annotateRun("cleared");
335 return null;
336 }
337 if (outcome === "unreachable") {
338 failures = yield* countFailure;
339 yield* annotateRun("unreachable");
340 return (yield* Clock.currentTimeMillis) + (yield* retryDelayMs(failures));
341 }
342 if (failures !== 0) {
343 failures = 0;
344 yield* resetFailures;
345 }
346 if (outcome === "busy") {
347 busyHooks.add(row.hook_key);
348 continue;
349 }
350 yield* sql`DELETE FROM held_hooks WHERE id = ${row.id}`;
351 delivered += 1;
352 const receivedAtMs = DateTime.toEpochMillis(DateTime.makeUnsafe(row.received_at));
353 longestWaitMs = Math.max(longestWaitMs, startedAt - receivedAtMs);
354 }
355 batch = yield* readPage(batch.at(-1)!.seq, busyHooks);
356 }
357 if (!(yield* hasPending)) {
358 yield* resetFailures;
359 yield* annotateRun("drained");
360 return null;
361 }
362
363 const now = yield* Clock.currentTimeMillis;
364 const idle = delivered === 0 && busyHooks.size > 0;
365 yield* annotateRun(idle ? "busy" : "more_pending");
366 return idle ? now + BUSY_RETRY_MS : now;
367});