Open History to see the last commit
1import * as SqliteClient from "@effect/sql-sqlite-do/SqliteClient";
2import type * as Alchemy from "alchemy";
3import * as Cloudflare from "alchemy/Cloudflare";
4import * as Clock from "effect/Clock";
5import * as Effect from "effect/Effect";
6import * as Option from "effect/Option";
7import * as Result from "effect/Result";
8import * as FetchHttpClient from "effect/http/FetchHttpClient";
9
10import * as HookInboxStore from "./HookInboxStore.ts";
11import { sendUpstream, TUNNEL_OFFLINE_STATUS } from "./upstream.ts";
12
13const UNREACHABLE_STATUSES = new Set([502, 503, 504, TUNNEL_OFFLINE_STATUS]);
14/**
15 * Statuses that mean the environment is there but did not take this request
16 * yet: its task's queue is full (429) or it failed while handling it (500).
17 * The environment drops a delivery id it has already run, so retrying is safe.
18 */
19const BUSY_STATUSES = new Set([429, 500]);
20const RUN_FAILURE_RETRY_MS = 60_000;
21
22type Call<A> = Effect.Effect<A, never, Alchemy.RuntimeContext>;
23
24export class HookInboxObject extends Cloudflare.DurableObject<
25 HookInboxObject,
26 {
27 /** Holds a request for `baseUrl`; false when the inbox is full and nothing was stored. */
28 readonly hold: (hook: HookInboxStore.HeldHook, baseUrl: string) => Call<boolean>;
29 readonly wake: (baseUrl: string) => Call<boolean>;
30 readonly clear: () => Call<void>;
31 }
32>()("HookInboxObject") {}
33
34const withInboxSpan =
35 (name: string, inboxId: string) =>
36 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
37 effect.pipe(
38 Effect.withSpan(name, { root: true, attributes: { "relay.hook.endpoint_key": inboxId } }),
39 );
40
41const deliver = (baseUrl: string, hook: HookInboxStore.HeldHook) =>
42 sendUpstream(baseUrl, hook).pipe(
43 Effect.result,
44 Effect.map((result) => {
45 // Unreachable or timed out: a timeout may still have run it, and the
46 // environment drops a delivery id it has already seen.
47 if (Result.isFailure(result)) {
48 return { outcome: "unreachable" as const, reason: result.failure._tag };
49 }
50 if (Option.isNone(result.success))
51 return { outcome: "unreachable" as const, reason: "timeout" };
52 const status = result.success.value.status;
53 const upstreamOutcome = result.success.value.outcome;
54 const outcome: HookInboxStore.DeliveryOutcome = UNREACHABLE_STATUSES.has(status)
55 ? "unreachable"
56 : BUSY_STATUSES.has(status)
57 ? "busy"
58 : "delivered";
59 return { outcome, reason: `status ${status}`, upstreamOutcome };
60 }),
61 Effect.tap(({ upstreamOutcome }) =>
62 upstreamOutcome === undefined
63 ? Effect.void
64 : Effect.annotateCurrentSpan({ "relay.hook.upstream_outcome": upstreamOutcome }),
65 ),
66 Effect.tap(({ outcome, reason }) =>
67 outcome === "delivered"
68 ? Effect.void
69 : Effect.logInfo("Held webhook not delivered yet", {
70 outcome,
71 reason,
72 deliveryId: hook.id,
73 }),
74 ),
75 Effect.map(({ outcome }) => outcome),
76 Effect.provide(FetchHttpClient.layer),
77 );
78
79export const layer = HookInboxObject.make(
80 Effect.gen(function* () {
81 const state = yield* Cloudflare.DurableObjectState;
82 // The init phase returns the per-instance Effect, which alchemy runs once
83 // per object; only that inner Effect may touch storage.
84 // @effect-diagnostics-next-line returnEffectInGen:off
85 return Effect.gen(function* () {
86 const layerSql = SqliteClient.layer({ storage: state.raw.storage });
87 const inboxId = state.raw.id.name ?? state.raw.id.toString();
88 const run = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
89 effect.pipe(Effect.provide(layerSql), Effect.orDie);
90 yield* run(HookInboxStore.migrate);
91
92 const scheduleBy = Effect.fn("HookInboxObject.scheduleBy")(function* (at: number) {
93 const current = yield* state.storage.getAlarm();
94 if (current === null || current > at) yield* state.storage.setAlarm(at);
95 });
96
97 // withInboxSpan supplies each method's root span; avoid a second wrapper span.
98 return {
99 hold: Effect.fnUntraced(
100 function* (hook: HookInboxStore.HeldHook, baseUrl: string) {
101 const dueAt = yield* run(HookInboxStore.hold(hook, baseUrl));
102 yield* Effect.annotateCurrentSpan({ "relay.inbox.stored": dueAt !== null });
103 if (dueAt === null) return false;
104 yield* scheduleBy(dueAt);
105 return true;
106 },
107 withInboxSpan("relay.inbox.hold", inboxId),
108 ),
109 wake: Effect.fnUntraced(
110 function* (baseUrl: string) {
111 const pending = yield* run(HookInboxStore.wake(baseUrl));
112 yield* Effect.annotateCurrentSpan({ "relay.inbox.pending": pending });
113 if (pending) yield* state.storage.setAlarm(yield* Clock.currentTimeMillis);
114 return pending;
115 },
116 withInboxSpan("relay.inbox.wake", inboxId),
117 ),
118 clear: Effect.fnUntraced(
119 function* () {
120 yield* run(HookInboxStore.clear);
121 yield* state.storage.deleteAlarm();
122 },
123 withInboxSpan("relay.inbox.clear", inboxId),
124 ),
125 alarm: () =>
126 run(HookInboxStore.deliverDue(deliver)).pipe(
127 // A wake during this run may already have asked for an earlier
128 // run; a backoff must not push it out.
129 Effect.flatMap((nextAt) => (nextAt === null ? Effect.void : scheduleBy(nextAt))),
130 Effect.catchCause((cause) =>
131 Effect.logWarning("Held webhook delivery run failed", { cause }).pipe(
132 Effect.andThen(Effect.annotateCurrentSpan({ "relay.inbox.run_result": "failed" })),
133 Effect.andThen(Clock.currentTimeMillis),
134 Effect.flatMap((now) => scheduleBy(now + RUN_FAILURE_RETRY_MS)),
135 ),
136 ),
137 withInboxSpan("relay.inbox.deliver", inboxId),
138 ),
139 };
140 });
141 }),
142);