@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 341 lines 12.8 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { Input } from "alchemy/Input";
3 import * as Namespace from "alchemy/Namespace";
4 import * as RemovalPolicy from "alchemy/RemovalPolicy";
5 import type { FunctionContext } from "alchemy/Runtime/Function";
6 import { RuntimeContext } from "alchemy/RuntimeContext";
7 import * as Cause from "effect/Cause";
8 import * as Context from "effect/Context";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Layer from "effect/Layer";
12 import { CatchAll } from "../Email/CatchAll.ts";
13 import { Routing } from "../Email/Routing.ts";
14 import { Rule, type Matcher } from "../Email/Rule.ts";
15 import type { Reference } from "../Zone/lookup.ts";
16 import { isWorkerEvent, Worker } from "./Worker.ts";
17
18 /**
19 * Effect-native wrapper around Cloudflare's
20 * [`ForwardableEmailMessage`](https://developers.cloudflare.com/email-routing/email-workers/runtime-api/#forwardableemailmessage).
21 *
22 * Follows the same shape as the other Cloudflare bindings (R2, KV, …):
23 *
24 * - `raw` is the underlying `cf.ForwardableEmailMessage` — an escape
25 * hatch for any field or future API not yet wrapped.
26 * - Ergonomic fields (`from`, `to`, `headers`, `body`, `bodySize`) are
27 * forwarded verbatim.
28 * - Action methods (`forward`, `reply`, `setReject`) return `Effect`s
29 * instead of `Promise`/`void`.
30 */
31 export interface ForwardableEmailMessage {
32 /** Underlying Cloudflare message — escape hatch for unwrapped APIs. */
33 readonly raw: cf.ForwardableEmailMessage;
34 /** Envelope From address. */
35 readonly from: string;
36 /** Envelope To address. */
37 readonly to: string;
38 /** RFC 5322 headers. */
39 readonly headers: cf.Headers;
40 /** Raw message body stream (RFC 5322 wire bytes). */
41 readonly body: cf.ReadableStream<Uint8Array>;
42 /** Size of the raw message body in bytes. */
43 readonly bodySize: number;
44 /**
45 * Reject this message back to the connecting client with a permanent
46 * SMTP error and the given reason.
47 */
48 setReject(reason: string): Effect.Effect<void>;
49 /**
50 * Forward this message to a verified destination address on the
51 * account. Fails with `EmailError` if Cloudflare rejects the forward
52 * (e.g. unverified destination).
53 */
54 forward(rcptTo: string, headers?: cf.Headers): Effect.Effect<void, EmailError>;
55 /**
56 * Reply to the sender with a new outbound message. Fails with
57 * `EmailError` if Cloudflare rejects the reply.
58 */
59 reply(message: cf.EmailMessage): Effect.Effect<void, EmailError>;
60 }
61
62 export class EmailError extends Data.TaggedError("EmailError")<{
63 action: "forward" | "reply";
64 message: string;
65 cause: unknown;
66 }> {}
67
68 const wrap = (raw: cf.ForwardableEmailMessage): ForwardableEmailMessage => ({
69 raw,
70 from: raw.from,
71 to: raw.to,
72 headers: raw.headers,
73 body: raw.raw,
74 bodySize: raw.rawSize,
75 setReject: (reason) => Effect.sync(() => raw.setReject(reason)),
76 forward: (rcptTo, headers) =>
77 Effect.tryPromise({
78 try: () => raw.forward(rcptTo, headers),
79 catch: (cause) =>
80 new EmailError({
81 action: "forward",
82 message: `Cloudflare email forward failed: ${formatCause(cause)}`,
83 cause,
84 }),
85 }),
86 reply: (msg) =>
87 Effect.tryPromise({
88 try: () => raw.reply(msg),
89 catch: (cause) =>
90 new EmailError({
91 action: "reply",
92 message: `Cloudflare email reply failed: ${formatCause(cause)}`,
93 cause,
94 }),
95 }),
96 });
97
98 /**
99 * Whether a subscription's matchers describe the zone's catch-all — either
100 * omitted entirely (the documented default) or a lone `{ type: "all" }`.
101 * Cloudflare models that as a per-zone singleton behind `/rules/catch_all`,
102 * so it maps to `Email.CatchAll` rather than `Email.Rule`.
103 */
104 const isCatchAll = (matchers: Matcher[] | undefined): boolean =>
105 matchers === undefined || (matchers.length === 1 && matchers[0]?.type === "all");
106
107 const formatCause = (cause: unknown): string =>
108 cause instanceof Error ? cause.message : String(cause);
109
110 /**
111 * Settings for {@link email} — both halves of the consumer in one place.
112 * `zone` opts in to the deploy-time setup: an `Email.Routing` toggle on the
113 * zone plus the routing resource that hands matched mail to the host
114 * Worker. Omit `zone` to manage routing yourself.
115 *
116 * Which routing resource depends on {@link EmailSubscribeProps.matchers}:
117 * a catch-all subscription yields `Email.CatchAll` (Cloudflare models the
118 * zone catch-all as a singleton behind its own endpoint), anything more
119 * specific yields `Email.Rule`.
120 */
121 export interface EmailSubscribeProps {
122 /**
123 * Zone to enable email routing on and attach the routing resource to.
124 * Accepts a zone id, a zone name (`example.com`), or a
125 * `{ zoneId, name? }` object (a `Cloudflare.Zone` resource works).
126 * Required to auto-create routing resources; omit if you're managing
127 * `Email.Routing` and `Email.Rule`/`Email.CatchAll` yourself.
128 */
129 zone?: Input<Reference>;
130 /**
131 * Which envelopes Cloudflare delivers to this Worker. Ignored when
132 * `zone` is omitted.
133 *
134 * Omitting this (or passing a lone `{ type: "all" }`) subscribes to the
135 * zone's catch-all, provisioned as `Email.CatchAll`. There is exactly one
136 * catch-all per zone, so a second Worker subscribing to it takes the
137 * zone's mail from the first.
138 *
139 * @default [{ type: "all" }]
140 */
141 matchers?: Matcher[];
142 /**
143 * Display name for the auto-created `Email.Rule` / `Email.CatchAll`.
144 *
145 * @default the host worker's logical id
146 */
147 ruleName?: string;
148 /**
149 * Priority of the auto-created `Email.Rule`. Lower numbers run first.
150 * Ignored for a catch-all subscription — the catch-all is always
151 * evaluated last.
152 *
153 * @default 0
154 */
155 priority?: number;
156 /**
157 * Whether the auto-created `Email.Rule` / `Email.CatchAll` is enabled.
158 *
159 * @default true
160 */
161 enabled?: boolean;
162 }
163
164 /**
165 * Subscribe to Cloudflare Email Worker events with an Effect handler.
166 *
167 * Wires both halves of the consumer in one call:
168 *
169 * - **Runtime**: registers an `email` event listener on the Worker.
170 * The handler receives a {@link ForwardableEmailMessage} whose
171 * action methods (`forward`, `reply`, `setReject`) return `Effect`s.
172 * - **Deploy-time** (when `zone` is set): yields a
173 * `Cloudflare.Email.Routing` toggle on the zone plus the routing
174 * resource whose `actions: [{ type: "worker", … }]` targets this
175 * Worker — `Cloudflare.Email.CatchAll` for a catch-all subscription,
176 * `Cloudflare.Email.Rule` for anything more specific. No manual
177 * wiring needed in `alchemy.run.ts`.
178 *
179 * Requires `EmailEventSourceLive` provided on the Worker's Effect.
180 *
181 * **Failure semantics**: a failing handler is logged and the failure is
182 * re-raised. Cloudflare turns that into a temporary SMTP failure, so the
183 * sending server keeps the message and retries later — mail is never
184 * accepted and then silently dropped. Handle the failures you consider
185 * final inside the handler (`Effect.retry`, `Effect.catchTag`, or
186 * `message.setReject(...)` to bounce permanently); anything you let
187 * escape becomes a retryable delivery failure.
188 *
189 * ### Subscribing to Inbound Mail
190 * **Example:** Catch-all on a zone — auto-creates routing + catch-all
191 * ```typescript
192 * import * as Cloudflare from "@alchemy.run/cloudflare";
193 * import * as Effect from "effect/Effect";
194 *
195 * export default Cloudflare.Worker(
196 * "Inbox",
197 * { main: import.meta.url },
198 * Effect.gen(function* () {
199 * yield* Cloudflare.email({ zone: "example.com" }).subscribe(
200 * (message) => message.forward("ops@example.com"),
201 * );
202 * return {};
203 * }).pipe(Effect.provide(Cloudflare.EmailEventSourceLive)),
204 * );
205 * ```
206 *
207 * **Example:** Match a specific address
208 * ```typescript
209 * yield* Cloudflare.email({
210 * zone: "example.com",
211 * matchers: [{ type: "literal", field: "to", value: "hello@example.com" }],
212 * }).subscribe((message) => message.forward("ops@example.com"));
213 * ```
214 *
215 * **Example:** Reject (bounce) a message
216 * ```typescript
217 * yield* Cloudflare.email({ zone: "example.com" }).subscribe((message) =>
218 * message.setReject("Mailbox closed"),
219 * );
220 * ```
221 *
222 * **Example:** Bring-your-own routing — no `zone`, no auto-create
223 * ```typescript
224 * // Manage `Email.Routing` / `Email.Rule` yourself in alchemy.run.ts.
225 * yield* Cloudflare.email().subscribe((message) =>
226 * Effect.log(`from ${message.from}`),
227 * );
228 * ```
229 *
230 * @see https://developers.cloudflare.com/email-routing/email-workers/
231 *
232 * @binding
233 * @product Workers
234 * @category Workers & Compute
235 */
236 export const email = (props: EmailSubscribeProps = {}) => ({
237 subscribe: <E = never, Req = never>(
238 process: (message: ForwardableEmailMessage) => Effect.Effect<void, E, Req>,
239 ) => EmailEventSource.use((source) => source(props, process)),
240 });
241
242 export type EmailEventSourceService = <E = never, Req = never>(
243 props: EmailSubscribeProps,
244 process: (message: ForwardableEmailMessage) => Effect.Effect<void, E, Req>,
245 ) => Effect.Effect<void, never, never>;
246
247 export class EmailEventSource extends Context.Service<EmailEventSource, EmailEventSourceService>()(
248 "Cloudflare.Workers.EmailEventSource",
249 ) {}
250
251 export const EmailEventSourceLive = Layer.effect(
252 EmailEventSource,
253 Effect.gen(function* () {
254 const host = yield* Worker;
255 return Effect.fn(function* <E, Req>(
256 props: EmailSubscribeProps,
257 process: (message: ForwardableEmailMessage) => Effect.Effect<void, E, Req>,
258 ) {
259 // Deploy-time: provision the Email.Routing toggle plus the routing
260 // resource that hands matched mail to this Worker. Skipped once
261 // running inside the deployed Worker (the global guard) and when
262 // `zone` is omitted (bring-your-own routing). Namespaced under the
263 // host so logical identity is stable per Worker.
264 if (!globalThis.__ALCHEMY_RUNTIME__ && props.zone !== undefined) {
265 const zone = props.zone;
266 const matchers = props.matchers;
267 yield* Namespace.push(
268 host.LogicalId,
269 Effect.gen(function* () {
270 // Routing is a per-zone singleton shared with other rules on
271 // the zone, so destroying this Worker must not disable it.
272 yield* Routing("EmailRouting", {
273 zone,
274 enabled: true,
275 }).pipe(RemovalPolicy.retain());
276
277 const action = {
278 type: "worker" as const,
279 value: [host.workerName],
280 };
281
282 // Catch-all is a per-zone SINGLETON living behind
283 // `/rules/catch_all`, not an ordinary rule. Cloudflare surfaces
284 // it in `listRules` but rejects mutating it through the rule
285 // endpoint ("Invalid rule operation"), so creating it as an
286 // `Email.Rule` would produce a row the engine cannot delete.
287 // Route an all-matcher subscription to `Email.CatchAll`
288 // instead — the resource that owns that endpoint.
289 if (isCatchAll(matchers)) {
290 yield* CatchAll("EmailCatchAll", {
291 zone,
292 name: props.ruleName ?? host.LogicalId,
293 enabled: props.enabled ?? true,
294 actions: [action],
295 });
296 return;
297 }
298
299 yield* Rule("EmailRule", {
300 zone,
301 name: props.ruleName ?? host.LogicalId,
302 enabled: props.enabled ?? true,
303 priority: props.priority ?? 0,
304 matchers: matchers!,
305 actions: [action],
306 });
307 }),
308 );
309 }
310
311 // Resolve the runtime context per-call rather than at layer
312 // construction (mirrors `Queues.EventSourceLive`).
313 const ctx = (yield* RuntimeContext) as unknown as FunctionContext;
314 yield* ctx.listen<void, Req>((event) => {
315 if (!isWorkerEvent(event) || event.type !== "email") return;
316
317 const message = wrap(event.input as cf.ForwardableEmailMessage);
318 // Log, then let the failure propagate. Cloudflare turns an
319 // exception out of the `email` handler into a temporary SMTP
320 // failure, so the sending server keeps the message and retries.
321 // Swallowing it here would instead ACCEPT the envelope and then
322 // drop it: a transient dependency outage would silently destroy
323 // mail with nothing left to retry from.
324 return process(message).pipe(
325 Effect.tapCause((cause) =>
326 Effect.sync(() => {
327 console.error(
328 `[EmailEventSource] handler failed for message to ` +
329 `"${message.to}": ${Cause.pretty(cause)}`,
330 );
331 }),
332 ),
333 // The listener contract is `E = never`, so surface the failure as
334 // a defect rather than discarding it: the invocation fails, which
335 // is what Cloudflare turns into the temporary SMTP failure.
336 Effect.orDie,
337 );
338 });
339 }) as EmailEventSourceService;
340 }),
341 );