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

main
ts 142 lines 5.34 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import * as Output from "alchemy/Output";
3 import type lambda from "aws-lambda";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import {
7 TableEventSource as DynamoDBTableEventSource,
8 type StreamRecord,
9 type StreamsProps,
10 type TableChangesHandler,
11 type TableEventSourceService,
12 } from "../DynamoDB/Stream.ts";
13 import type { Table } from "../DynamoDB/Table.ts";
14 import { processBatch } from "../internal/EventSourceBatch.ts";
15 import { EventSourceMapping } from "./EventSourceMapping.ts";
16 import * as Lambda from "./Function.ts";
17
18 export const isDynamoDBStreamEvent = (event: any): event is lambda.DynamoDBStreamEvent =>
19 Array.isArray(event?.Records) &&
20 event.Records.length > 0 &&
21 event.Records[0].eventSource === "aws:dynamodb";
22
23 /** @binding */
24 export const TableEventSource = Layer.effect(
25 DynamoDBTableEventSource,
26 Effect.gen(function* () {
27 const host = yield* Lambda.eventSourceHost("AWS.Lambda.TableEventSource");
28 const Mapping = yield* EventSourceMapping;
29
30 return Effect.fn(function* <E = never, Req = never>(
31 table: Table,
32 props: StreamsProps,
33 process: TableChangesHandler<E, Req>,
34 ) {
35 const TableArn = yield* table.tableArn;
36
37 // Deploy-time: enable the table stream, grant IAM, and create the
38 // event-source mapping. Skipped once running inside the deployed Function
39 // (the global guard), where the only work is registering the runtime
40 // handler below. Namespaced under the host so the mapping's logical
41 // identity matches the previous Binding.Policy.
42 if (!globalThis.__ALCHEMY_RUNTIME__) {
43 yield* Namespace.push(
44 host.LogicalId,
45 Effect.gen(function* () {
46 const latestStreamArn = table.latestStreamArn.pipe(
47 Output.mapEffect((arn) =>
48 typeof arn === "string"
49 ? Effect.succeed(arn)
50 : Effect.die(`latestStreamArn is not a string: ${arn}`),
51 ),
52 );
53
54 const streamViewType = props.streamViewType ?? "NEW_AND_OLD_IMAGES";
55
56 yield* Effect.logInfo(
57 `Lambda TableEventSource: binding stream ${streamViewType} for ${table.LogicalId}`,
58 );
59 yield* table.bind`AWS.DynamoDB.Stream(${host}, ${table}, ${streamViewType})`({
60 streamSpecification: {
61 StreamEnabled: true,
62 StreamViewType: streamViewType,
63 },
64 });
65
66 yield* Effect.logInfo(
67 `Lambda TableEventSourcePolicy: creating mapping for ${host.LogicalId} <- ${table.LogicalId}`,
68 );
69
70 yield* host.bind`Allow(${host}, AWS.DynamoDB.Table.ReadStream(${table}))`({
71 policyStatements: [
72 {
73 Effect: "Allow",
74 Action: [
75 "dynamodb:DescribeStream",
76 "dynamodb:GetRecords",
77 "dynamodb:GetShardIterator",
78 ],
79 Resource: [latestStreamArn],
80 },
81 ],
82 });
83
84 yield* host.bind`Allow(${host}, AWS.DynamoDB.ListStreams(${table}))`({
85 policyStatements: [
86 {
87 Effect: "Allow",
88 Action: ["dynamodb:ListStreams"],
89 Resource: [table.tableArn],
90 },
91 ],
92 });
93
94 yield* Mapping(`AWS.Lambda.EventSourceMapping(${host.LogicalId}, ${table.LogicalId})`, {
95 functionName: Lambda.qualifiedNameOf(host),
96 eventSourceArn: latestStreamArn,
97 batchSize: props.batchSize,
98 maximumBatchingWindow: props.maximumBatchingWindow,
99 enabled: true,
100 startingPosition: props.startingPosition ?? "LATEST",
101 startingPositionTimestamp: props.startingPositionTimestamp,
102 parallelizationFactor: props.parallelizationFactor,
103 bisectBatchOnFunctionError: props.bisectBatchOnFunctionError,
104 maximumRecordAge: props.maximumRecordAge,
105 maximumRetryAttempts: props.maximumRetryAttempts,
106 tumblingWindow: props.tumblingWindow,
107 });
108 }),
109 );
110 }
111
112 yield* host.listen(
113 Effect.gen(function* () {
114 const tableArn = yield* TableArn;
115 const streamArnPrefix = `${tableArn}/stream/`;
116
117 return (event: any) => {
118 if (isDynamoDBStreamEvent(event)) {
119 const records = event.Records.filter(
120 (record) => record.eventSourceARN?.startsWith(streamArnPrefix) === true,
121 );
122 if (records.length > 0) {
123 return process({
124 Records: records as StreamRecord<Record<string, lambda.AttributeValue>>[],
125 }).pipe(
126 Effect.map((response) => response ?? { batchItemFailures: [] }),
127 processBatch({
128 system: "aws_dynamodb",
129 destination: tableArn.split("/")[1] ?? tableArn,
130 count: records.length,
131 }),
132 // A failure fails the invocation, so Lambda retries the whole batch.
133 Effect.orDie,
134 );
135 }
136 }
137 };
138 }),
139 );
140 }) as TableEventSourceService;
141 }),
142 );