@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, 06:00 UTC

main
ts 102 lines 3.32 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as Stream from "effect/Stream";
6 import {
7 DeadOrderEvents,
8 decodeOrderEvent,
9 emailObjectFor,
10 OrderEvents,
11 Outbox,
12 type OrderEvent,
13 } from "./resources.ts";
14
15 /** How many times Pub/Sub tries a message before dead-lettering it. */
16 export const MAX_DELIVERY_ATTEMPTS = 5;
17
18 class UndeliverableEmail extends Data.TaggedError("UndeliverableEmail")<{
19 to: string;
20 }> {}
21
22 /**
23 * Stand-in for a mail provider. `.invalid` is reserved (RFC 2606) and
24 * never resolves, so mail to it always fails — a message this consumer
25 * can never process, which is what the dead-letter topic is for.
26 */
27 interface SentEmail {
28 to: string;
29 subject: string;
30 text: string;
31 sentAt: string;
32 }
33
34 const send = (event: OrderEvent): Effect.Effect<SentEmail, UndeliverableEmail> =>
35 event.email.endsWith(".invalid")
36 ? Effect.fail(new UndeliverableEmail({ to: event.email }))
37 : Effect.succeed({
38 to: event.email,
39 subject: `Order ${event.orderId} confirmed`,
40 text: `Thanks! We received your order totalling $${event.total.toFixed(2)}.`,
41 sentAt: new Date().toISOString(),
42 });
43
44 /**
45 * Sends an order confirmation for every `order.created` event.
46 *
47 * The `filter` is applied by Pub/Sub on the subscription, so other event
48 * types are never delivered here at all — this service is not woken up
49 * (or billed) for them.
50 *
51 * A failed send fails the push; Pub/Sub retries it, and after
52 * {@link MAX_DELIVERY_ATTEMPTS} attempts forwards it to
53 * `DeadOrderEvents` instead of retrying forever.
54 */
55 export default class Email extends GCP.Function<Email>()(
56 "Email",
57 {
58 main: import.meta.url,
59 },
60 Effect.gen(function* () {
61 const outbox = yield* GCP.Storage.WriteBucket(Outbox);
62
63 yield* GCP.PubSub.consumeTopicMessages(
64 OrderEvents,
65 {
66 filter: 'attributes.type = "order.created"',
67 deadLetter: {
68 topic: yield* DeadOrderEvents,
69 maxDeliveryAttempts: MAX_DELIVERY_ATTEMPTS,
70 },
71 },
72 (messages) =>
73 messages.pipe(
74 Stream.runForEach(({ message, deliveryAttempt }) =>
75 Effect.gen(function* () {
76 const event = yield* decodeOrderEvent(message.data);
77 const email = yield* send(event).pipe(
78 Effect.tapError((error) =>
79 Effect.logWarning(
80 `email: cannot send to ${error.to} (attempt ${deliveryAttempt ?? 1})`,
81 ),
82 ),
83 );
84 // Keyed by event id, so a redelivery overwrites instead of
85 // recording a second email.
86 yield* outbox.put(emailObjectFor(event.eventId), JSON.stringify(email), {
87 contentType: "application/json",
88 metadata: { orderId: event.orderId, to: email.to },
89 });
90 yield* Effect.log(`email: confirmed ${event.orderId}`);
91 }),
92 ),
93 // A failure answers the push with a 500, so Pub/Sub redelivers.
94 Effect.orDie,
95 ),
96 );
97
98 return {
99 fetch: Effect.succeed(HttpServerResponse.text("ok")),
100 };
101 }).pipe(Effect.provide([GCP.Run.TopicEventSource, GCP.Storage.WriteBucketHttp])),
102 ) {}