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

main
ts 152 lines 5.67 KB
Raw
1 import { gunzipSync } from "node:zlib";
2 import * as Namespace from "alchemy/Namespace";
3 import * as Output from "alchemy/Output";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Stream from "effect/Stream";
8 import type { LogGroup } from "../Logs/LogGroup.ts";
9 import {
10 LogGroupEventSource as LogsLogGroupEventSource,
11 type CloudWatchLogsEvent,
12 type LogEventRecord,
13 type LogGroupEventSourceProps,
14 type LogGroupEventSourceService,
15 type LogsSubscriptionPayload,
16 } from "../Logs/LogGroupEventSource.ts";
17 import { SubscriptionFilter } from "../Logs/SubscriptionFilter.ts";
18 import * as Lambda from "./Function.ts";
19 import { Permission as LambdaPermission } from "./Permission.ts";
20
21 /**
22 * Narrow an arbitrary Lambda invocation payload to a CloudWatch Logs
23 * subscription event.
24 */
25 export const isCloudWatchLogsEvent = (event: any): event is CloudWatchLogsEvent =>
26 typeof event?.awslogs?.data === "string";
27
28 /** A CloudWatch Logs subscription payload could not be decoded. */
29 export class CloudWatchLogsDecodeError extends Data.TaggedError("CloudWatchLogsDecodeError")<{
30 message: string;
31 cause?: unknown;
32 }> {}
33
34 /**
35 * Decode the gzipped, base64-encoded CloudWatch Logs subscription payload.
36 */
37 export const decodeCloudWatchLogsEvent = (
38 event: CloudWatchLogsEvent,
39 ): Effect.Effect<LogsSubscriptionPayload, CloudWatchLogsDecodeError> =>
40 Effect.try({
41 try: () =>
42 JSON.parse(
43 gunzipSync(Buffer.from(event.awslogs.data, "base64")).toString(),
44 ) as LogsSubscriptionPayload,
45 catch: (cause) =>
46 new CloudWatchLogsDecodeError({
47 message: "failed to decode CloudWatch Logs subscription payload",
48 cause,
49 }),
50 });
51
52 /**
53 * Lambda runtime implementation for `AWS.Logs.consumeLogEvents(...)`.
54 *
55 * This layer does two things:
56 *
57 * 1. At deploy time it creates the backing `AWS.Logs.SubscriptionFilter`
58 * targeting the current Lambda function plus the `lambda:InvokeFunction`
59 * permission for `logs.amazonaws.com`.
60 * 2. At runtime it decodes the gzipped/base64 `awslogs.data` payload of
61 * incoming invocations and forwards each log event into the supplied
62 * handler as a typed `LogEventRecord` stream.
63 * ### Consuming Log Events
64 * **Example:** Forward Another Function's Error Logs
65 * ```typescript
66 * yield* AWS.Logs.consumeLogEvents(
67 * logGroup,
68 * { filterPattern: "?ERROR ?Error" },
69 * (events) =>
70 * Stream.runForEach(events, (event) =>
71 * Effect.log(`${event.logStream}: ${event.message}`),
72 * ),
73 * );
74 * ```
75 *
76 * @binding
77 */
78 export const LogGroupEventSource = Layer.effect(
79 LogsLogGroupEventSource,
80 // The impl resolves plan-time services (SubscriptionFilter, Permission)
81 // whereas LogGroupEventSourceService erases the requirement channel to
82 // `never`.
83 // @effect-diagnostics-next-line missingEffectContext:off
84 Effect.gen(function* () {
85 const host = yield* Lambda.eventSourceHost("AWS.Lambda.LogGroupEventSource");
86 const Permission = yield* LambdaPermission;
87 const Filter = yield* SubscriptionFilter;
88
89 return Effect.fn(function* <Req = never>(
90 logGroup: LogGroup,
91 props: LogGroupEventSourceProps,
92 process: (events: Stream.Stream<LogEventRecord>) => Effect.Effect<void, never, Req>,
93 ) {
94 // this adds it to the Lambda Function's environment variables
95 const LogGroupName = yield* logGroup.logGroupName;
96
97 // Deploy-time: grant CloudWatch Logs permission to invoke this function
98 // and create the subscription filter targeting it. Skipped once running
99 // inside the deployed Function (the global guard), where the only work
100 // is registering the runtime handler below. Namespaced under the host so
101 // the sub-resources' logical identity is stable per host function.
102 if (!globalThis.__ALCHEMY_RUNTIME__) {
103 yield* Namespace.push(
104 host.LogicalId,
105 Effect.gen(function* () {
106 yield* Permission(`AWS.Logs.InvokePermission(${logGroup.LogicalId})`, {
107 action: "lambda:InvokeFunction",
108 functionName: Lambda.qualifiedNameOf(host),
109 principal: "logs.amazonaws.com",
110 sourceArn: Output.interpolate`${logGroup.logGroupArn}:*`,
111 });
112 yield* Filter(`AWS.Logs.SubscriptionFilter(${logGroup.LogicalId})`, {
113 logGroupName: logGroup.logGroupName,
114 filterName: props.filterName,
115 filterPattern: props.filterPattern ?? "",
116 destinationArn: Lambda.qualifiedArnOf(host),
117 });
118 }),
119 );
120 }
121
122 yield* host.listen(
123 Effect.gen(function* () {
124 const logGroupName = yield* LogGroupName;
125 return (event: any) => {
126 if (isCloudWatchLogsEvent(event)) {
127 return Effect.gen(function* () {
128 const payload = yield* decodeCloudWatchLogsEvent(event);
129 if (payload.messageType !== "DATA_MESSAGE" || payload.logGroup !== logGroupName) {
130 return;
131 }
132 yield* process(
133 Stream.fromArray(
134 payload.logEvents.map((logEvent): LogEventRecord => ({
135 id: logEvent.id,
136 timestamp: logEvent.timestamp,
137 message: logEvent.message,
138 logGroup: payload.logGroup,
139 logStream: payload.logStream,
140 owner: payload.owner,
141 subscriptionFilters: payload.subscriptionFilters,
142 })),
143 ),
144 );
145 }).pipe(Effect.orDie);
146 }
147 };
148 }),
149 );
150 }) as LogGroupEventSourceService;
151 }),
152 );