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

main
ts 111 lines 4.39 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 type { Bucket } from "../S3/Bucket.ts";
7 import {
8 BucketEventSource as S3BucketEventSource,
9 type BucketEventSourceService,
10 } from "../S3/BucketEventSource.ts";
11 import type { BucketNotification, NotificationsProps } from "../S3/BucketNotifications.ts";
12 import { normalizeBucketNotification } from "../S3/normalizeBucketNotification.ts";
13 import type { S3EventType } from "../S3/S3Event.ts";
14 import * as Lambda from "./Function.ts";
15 import { Permission as LambdaPermission } from "./Permission.ts";
16
17 /**
18 * Connects an S3 bucket notification stream to the current Lambda function.
19 *
20 * This layer listens for bucket notifications routed through the Lambda runtime
21 * and exposes them as an `Effect.Stream`, while the companion policy configures
22 * the invoke permission and bucket notification binding during deployment.
23 * ### Wiring Events
24 * **Example:** Listen for Object Created Events
25 * ```typescript
26 * yield* AWS.Lambda.BucketEventSource(
27 * bucket,
28 * { events: ["s3:ObjectCreated:*"] },
29 * (events) => Stream.runForEach(events, (event) => Effect.log(event.key)),
30 * );
31 * ```
32 *
33 * @binding
34 */
35 export const BucketEventSource = Layer.effect(
36 S3BucketEventSource,
37 Effect.gen(function* () {
38 // this layer can only be used in a Lambda Function
39 const func = yield* Lambda.eventSourceHost("AWS.Lambda.BucketEventSource");
40 const Permission = yield* LambdaPermission;
41
42 return Effect.fn(function* <Events extends S3EventType[], StreamReq = never, Req = never>(
43 bucket: Bucket,
44 props: NotificationsProps<Events>,
45 process: (
46 stream: Stream.Stream<BucketNotification, never, StreamReq>,
47 ) => Effect.Effect<void, never, Req>,
48 ) {
49 // this adds it to the Lambda Function's environment variables
50 const BucketName = yield* bucket.bucketName;
51
52 // Deploy-time: grant the invoke permission and attach the bucket
53 // notification config. Skipped once running inside the deployed Function
54 // (the global guard), where the only work is registering the runtime
55 // handler below. Namespaced under the host so the sub-resources' logical
56 // identity matches the previous Binding.Policy.
57 if (!globalThis.__ALCHEMY_RUNTIME__) {
58 yield* Namespace.push(
59 func.LogicalId,
60 Effect.gen(function* () {
61 const { events: Events = ["s3:ObjectCreated:*"], prefix, suffix } = props ?? {};
62 const filterRules = [
63 ...(prefix !== undefined ? [{ Name: "prefix" as const, Value: prefix }] : []),
64 ...(suffix !== undefined ? [{ Name: "suffix" as const, Value: suffix }] : []),
65 ];
66 yield* Permission(`AWS.Lambda.InvokeFunction(${bucket.LogicalId})`, {
67 action: "lambda:InvokeFunction",
68 functionName: Lambda.qualifiedNameOf(func),
69 principal: "s3.amazonaws.com",
70 sourceArn: bucket.bucketArn,
71 });
72 yield* bucket.bind(`AWS.S3.Notifications(${bucket.LogicalId})`, {
73 notificationConfiguration: {
74 LambdaFunctionConfigurations: [
75 {
76 LambdaFunctionArn: Lambda.qualifiedArnOf(func),
77 Events,
78 ...(filterRules.length > 0
79 ? { Filter: { Key: { FilterRules: filterRules } } }
80 : {}),
81 },
82 ],
83 },
84 });
85 }),
86 );
87 }
88
89 yield* func.listen(
90 Effect.gen(function* () {
91 // this accesses it
92 const bucketName = yield* BucketName;
93 return (event: any) => {
94 if (isS3Event(event)) {
95 const events = event.Records.filter((record) => record.s3.bucket.name === bucketName);
96 if (events.length > 0) {
97 return process(
98 Stream.fromArray(events).pipe(Stream.mapEffect(normalizeBucketNotification)),
99 // TODO(sam): don't die?
100 ).pipe(Effect.orDie);
101 }
102 }
103 };
104 }),
105 );
106 }) as BucketEventSourceService;
107 }),
108 );
109
110 const isS3Event = (event: any): event is lambda.S3Event =>
111 Array.isArray(event.Records) && event.Records.some((record: any) => record.s3);