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 = (baseUrl: string, options: { readonly resetFailures: boolean }) =>
136 Effect.gen(function* () {
137 const sql = yield* SqlClient.SqlClient;
138 yield* options.resetFailures
139 ? sql`
140 INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
141 ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url, failures = 0
142 `
143 : sql`
144 INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
145 ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url
146 `;
147 });
148
149const readTarget = Effect.gen(function* () {
150 const sql = yield* SqlClient.SqlClient;
151 const rows = yield* sql<TargetRow>`SELECT base_url, failures FROM held_hooks_target WHERE id = 1`;
152 return rows[0] ?? null;
153});
154
155const resetFailures = Effect.gen(function* () {
156 const sql = yield* SqlClient.SqlClient;
157 yield* sql`UPDATE held_hooks_target SET failures = 0 WHERE id = 1`;
158});
159
160/**
161 * Incremented in place, so a wake that reset the count while this run's request
162 * was in flight is not overwritten.
163 */
164const countFailure = Effect.gen(function* () {
165 const sql = yield* SqlClient.SqlClient;
166 const rows = yield* sql<{ readonly failures: number }>`
167 UPDATE held_hooks_target SET failures = min(failures + 1, ${MAX_COUNTED_FAILURES})
168 WHERE id = 1 RETURNING failures
169 `;
170 return rows[0]?.failures ?? 1;
171});
172
173const hasPending = Effect.gen(function* () {
174 const sql = yield* SqlClient.SqlClient;
175 const rows = yield* sql<{ readonly id: string }>`SELECT id FROM held_hooks LIMIT 1`;
176 return rows.length > 0;
177});
178
179/**
180 * Returns the time the first attempt is due, or null when the inbox is full and
181 * nothing was stored.
182 */
183export const hold = Effect.fn("HookInboxStore.hold")(function* (hook: HeldHook, baseUrl: string) {
184 const sql = yield* SqlClient.SqlClient;
185 // One statement, so the caps hold however many requests arrive at once.
186 const inserted = yield* sql<{ readonly id: string }>`
187 INSERT INTO held_hooks
188 (id, received_at, method, raw_hook_id, raw_token, hook_key, query, headers, body)
189 SELECT ${hook.id}, ${hook.receivedAt}, ${hook.method}, ${hook.rawHookId}, ${hook.rawToken},
190 ${hook.hookKey}, ${hook.query}, ${encodeHeaders(hook.headers)}, ${hook.body}
191 WHERE (SELECT count(*) FROM held_hooks) < ${HOOK_INBOX_MAX_REQUESTS}
192 AND (SELECT count(*) FROM held_hooks WHERE hook_key = ${hook.hookKey})
193 < ${HOOK_INBOX_MAX_PER_HOOK}
194 AND (SELECT coalesce(sum(length(body)), 0) FROM held_hooks) + ${hook.body.byteLength}
195 <= ${HOOK_INBOX_MAX_BYTES}
196 ON CONFLICT (id) DO NOTHING
197 RETURNING id
198 `;
199 if (inserted.length === 0) {
200 yield* Effect.annotateCurrentSpan({ "relay.inbox.refused": yield* refusalReason(hook) });
201 return null;
202 }
203 yield* setTarget(baseUrl, { resetFailures: false });
204 const target = yield* readTarget;
205 const backlog = yield* backlogSize;
206 yield* Effect.annotateCurrentSpan({
207 "relay.inbox.held_count": backlog.count,
208 "relay.inbox.held_bytes": backlog.bytes,
209 });
210 return (yield* Clock.currentTimeMillis) + (yield* retryDelayMs(target?.failures ?? 0));
211});
212
213const backlogSize = Effect.gen(function* () {
214 const sql = yield* SqlClient.SqlClient;
215 const rows = yield* sql<{ readonly count: number; readonly bytes: number }>`
216 SELECT count(*) AS count, coalesce(sum(length(body)), 0) AS bytes FROM held_hooks
217 `;
218 return rows[0] ?? { count: 0, bytes: 0 };
219});
220
221const refusalReason = (hook: HeldHook) =>
222 Effect.gen(function* () {
223 const sql = yield* SqlClient.SqlClient;
224 const existing = yield* sql<{ readonly id: string }>`
225 SELECT id FROM held_hooks WHERE id = ${hook.id}
226 `;
227 if (existing.length > 0) return "already_held";
228 const backlog = yield* backlogSize;
229 if (backlog.count >= HOOK_INBOX_MAX_REQUESTS) return "max_requests";
230 if (backlog.bytes + hook.body.byteLength > HOOK_INBOX_MAX_BYTES) return "max_bytes";
231 return "max_per_hook";
232 });
233
234export const wake = Effect.fn("HookInboxStore.wake")(function* (baseUrl: string) {
235 if (!(yield* hasPending)) return false;
236 yield* setTarget(baseUrl, { resetFailures: true });
237 return true;
238});
239
240export const clear = Effect.gen(function* () {
241 const sql = yield* SqlClient.SqlClient;
242 yield* sql`DELETE FROM held_hooks`;
243 yield* sql`DELETE FROM held_hooks_target`;
244});
245
246export const deliverDue = Effect.fn("HookInboxStore.deliverDue")(function* <R>(
247 send: (baseUrl: string, hook: HeldHook) => Effect.Effect<DeliveryOutcome, never, R>,
248) {
249 const sql = yield* SqlClient.SqlClient;
250 const startedAt = yield* Clock.currentTimeMillis;
251 const expired = yield* sql<{ readonly id: string }>`
252 DELETE FROM held_hooks WHERE received_at < ${iso(startedAt - HOOK_INBOX_TTL_MS)}
253 RETURNING id
254 `;
255 const target = yield* readTarget;
256
257 const readPage = (afterSeq: number, skip: ReadonlySet<string>) =>
258 sql<HeldHookRow>`
259 SELECT seq, id, received_at, method, raw_hook_id, raw_token, hook_key, query, headers, body
260 FROM held_hooks
261 WHERE seq > ${afterSeq}
262 ${skip.size === 0 ? sql`` : sql`AND hook_key NOT IN ${sql.in([...skip])}`}
263 ORDER BY seq LIMIT ${ROWS_READ_PER_PAGE}
264 `;
265 let batch = yield* readPage(0, new Set());
266 if (batch.length === 0 || target === null) {
267 if (target === null) yield* sql`DELETE FROM held_hooks`;
268 else yield* resetFailures;
269 yield* Effect.annotateCurrentSpan({ "relay.inbox.expired": expired.length });
270 return null;
271 }
272
273 let failures = target.failures;
274 let sent = 0;
275 let delivered = 0;
276 let unreadable = 0;
277 let longestWaitMs = 0;
278 const busyHooks = new Set<string>();
279
280 const annotateRun = (result: string) =>
281 Effect.gen(function* () {
282 const backlog = yield* backlogSize;
283 yield* Effect.annotateCurrentSpan({
284 "relay.inbox.run_result": result,
285 "relay.inbox.sent": sent,
286 "relay.inbox.delivered": delivered,
287 "relay.inbox.busy_hooks": busyHooks.size,
288 "relay.inbox.expired": expired.length,
289 "relay.inbox.unreadable": unreadable,
290 "relay.inbox.consecutive_failures": failures,
291 "relay.inbox.longest_wait_ms": longestWaitMs,
292 "relay.inbox.held_count": backlog.count,
293 "relay.inbox.held_bytes": backlog.bytes,
294 });
295 });
296 const stillHeld = (seq: number) =>
297 sql<{ readonly seq: number }>`SELECT seq FROM held_hooks WHERE seq = ${seq}`.pipe(
298 Effect.map((rows) => rows.length > 0),
299 );
300 // Pages run out only once every non-busy request has been tried, so a
301 // backlog behind busy hooks never hides another hook's requests.
302 pages: while (batch.length > 0) {
303 for (const row of batch) {
304 if (sent === DELIVERIES_PER_RUN) break pages;
305
306 if (busyHooks.has(row.hook_key)) continue;
307 // Clear can discard this prefetched page while an upstream send is in flight.
308 if (!(yield* stillHeld(row.seq))) {
309 yield* annotateRun("cleared");
310 return null;
311 }
312 const headers = decodeHeaders(row.headers);
313 if (Option.isNone(headers)) {
314 // Unreadable: it can never be delivered, and must not block the rest.
315 yield* sql`DELETE FROM held_hooks WHERE id = ${row.id}`;
316 unreadable += 1;
317 continue;
318 }
319 sent += 1;
320 const outcome = yield* send(target.base_url, {
321 id: row.id,
322 receivedAt: row.received_at,
323 method: row.method,
324 rawHookId: row.raw_hook_id,
325 rawToken: row.raw_token,
326 hookKey: row.hook_key,
327 query: row.query,
328 headers: headers.value,
329 body: row.body,
330 });
331 // A cleared request must neither advance this run nor schedule a retry.
332 if (!(yield* stillHeld(row.seq))) {
333 yield* annotateRun("cleared");
334 return null;
335 }
336 if (outcome === "unreachable") {
337 failures = yield* countFailure;
338 yield* annotateRun("unreachable");
339 return (yield* Clock.currentTimeMillis) + (yield* retryDelayMs(failures));
340 }
341 if (failures !== 0) {
342 failures = 0;
343 yield* resetFailures;
344 }
345 if (outcome === "busy") {
346 busyHooks.add(row.hook_key);
347 continue;
348 }
349 yield* sql`DELETE FROM held_hooks WHERE id = ${row.id}`;
350 delivered += 1;
351 const receivedAtMs = DateTime.toEpochMillis(DateTime.makeUnsafe(row.received_at));
352 longestWaitMs = Math.max(longestWaitMs, startedAt - receivedAtMs);
353 }
354 batch = yield* readPage(batch.at(-1)!.seq, busyHooks);
355 }
356 if (!(yield* hasPending)) {
357 yield* resetFailures;
358 yield* annotateRun("drained");
359 return null;
360 }
361
362 const now = yield* Clock.currentTimeMillis;
363 const idle = delivered === 0 && busyHooks.size > 0;
364 yield* annotateRun(idle ? "busy" : "more_pending");
365 return idle ? now + BUSY_RETRY_MS : now;
366});