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

main
ts 84 lines 3.04 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import type lambda from "aws-lambda";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Stream from "effect/Stream";
6 import { Subscription as SNSSubscription } from "../SNS/Subscription.ts";
7 import type { Topic } from "../SNS/Topic.ts";
8 import {
9 TopicEventSource as SNSTopicEventSource,
10 type TopicEventSourceProps,
11 type TopicEventSourceService,
12 type TopicNotification,
13 } from "../SNS/TopicEventSource.ts";
14 import * as Lambda from "./Function.ts";
15 import { Permission as LambdaPermission } from "./Permission.ts";
16
17 export const isSNSEvent = (event: any): event is lambda.SNSEvent =>
18 Array.isArray(event?.Records) &&
19 event.Records.some((record: any) => record.EventSource === "aws:sns");
20
21 /** @binding */
22 export const TopicEventSource = Layer.effect(
23 SNSTopicEventSource,
24 Effect.gen(function* () {
25 const host = yield* Lambda.eventSourceHost("AWS.Lambda.TopicEventSource");
26 const Permission = yield* LambdaPermission;
27 const Subscription = yield* SNSSubscription;
28
29 return Effect.fn(function* <StreamReq = never, Req = never>(
30 topic: Topic,
31 props: TopicEventSourceProps,
32 process: (
33 stream: Stream.Stream<TopicNotification, never, StreamReq>,
34 ) => Effect.Effect<void, never, Req>,
35 ) {
36 const TopicArn = yield* topic.topicArn;
37
38 // Deploy-time: grant invoke permission and create the SNS subscription.
39 // Skipped once running inside the deployed Function (the global guard),
40 // where the only work is registering the runtime handler below.
41 // Namespaced under the host so the sub-resources' logical identity matches
42 // the previous Binding.Policy.
43 if (!globalThis.__ALCHEMY_RUNTIME__) {
44 yield* Namespace.push(
45 host.LogicalId,
46 Effect.gen(function* () {
47 yield* Permission(`AWS.Lambda.InvokeFunction(${topic.LogicalId})`, {
48 action: "lambda:InvokeFunction",
49 functionName: Lambda.qualifiedNameOf(host),
50 principal: "sns.amazonaws.com",
51 sourceArn: topic.topicArn,
52 });
53
54 yield* Subscription(`AWS.SNS.Subscription(${topic.LogicalId}, ${host.LogicalId})`, {
55 topicArn: topic.topicArn,
56 protocol: "lambda",
57 endpoint: Lambda.qualifiedArnOf(host),
58 attributes: props.attributes,
59 returnSubscriptionArn: true,
60 });
61 }),
62 );
63 }
64
65 yield* host.listen(
66 Effect.gen(function* () {
67 const topicArn = yield* TopicArn;
68
69 return (event: any) => {
70 if (isSNSEvent(event)) {
71 const records = event.Records.filter((record) => record.Sns?.TopicArn === topicArn);
72
73 if (records.length > 0) {
74 return process(
75 Stream.fromArray(records.map((record) => record.Sns as TopicNotification)),
76 ).pipe(Effect.orDie);
77 }
78 }
79 };
80 }),
81 );
82 }) as TopicEventSourceService;
83 }),
84 );