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

main
ts 182 lines 5.84 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type * as lambda from "aws-lambda";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5 import type { Cluster } from "../ECS/Cluster.ts";
6 import type { Function as LambdaFunction } from "../Lambda/Function.ts";
7 import type { Queue } from "../SQS/Queue.ts";
8 import type { EventBus } from "./EventBus.ts";
9 import type { RuleProps } from "./Rule.ts";
10 import { toEcsTask as createEcsTaskRoute, type EcsRouteTargetProps } from "./ToEcsTask.ts";
11 import { toLambda as createLambdaRoute, type LambdaRouteTargetProps } from "./ToLambda.ts";
12 import { toQueue as createQueueRoute, type QueueRouteTargetProps } from "./ToQueue.ts";
13
14 export type EventPattern = Record<string, any>;
15 export type EventRecord<Detail = unknown> = lambda.EventBridgeEvent<string, Detail>;
16
17 export interface EventRouteProps extends Pick<RuleProps, "description" | "state"> {}
18
19 export interface SubscribeProps extends EventRouteProps {}
20
21 export type { EcsRouteTargetProps } from "./ToEcsTask.ts";
22 export type { LambdaRouteTargetProps } from "./ToLambda.ts";
23 export type { QueueRouteTargetProps } from "./ToQueue.ts";
24
25 interface EventDescriptor {
26 id?: string;
27 bus?: EventBus;
28 pattern: EventPattern;
29 props?: EventRouteProps;
30 }
31
32 /**
33 * Event source connecting an EventBridge {@link EventBus} to the hosting
34 * compute (Lambda function or ServerHost process). Matching events invoke
35 * the host with a stream of {@link EventRecord}s.
36 *
37 * Use it through the {@link consumeBusEvents} helper; the host-specific
38 * implementation layer (e.g. `AWS.Lambda.EventSource`) creates the rule,
39 * grants EventBridge invoke permission, and dispatches events at runtime.
40 * ### Consuming Events
41 * **Example:** Consume Matching Events on a Lambda Function
42 * ```typescript
43 * // init — subscribe to matching events (provide AWS.Lambda.EventSource on the Function)
44 * yield* AWS.EventBridge.consumeBusEvents(
45 * bus,
46 * { source: ["my.app"] },
47 * (events: Stream.Stream<AWS.EventBridge.EventRecord>) =>
48 * events.pipe(
49 * Stream.runForEach((event) =>
50 * Effect.log(event["detail-type"], event.detail),
51 * ),
52 * ),
53 * );
54 * ```
55 *
56 * @binding
57 */
58 export interface EventSource extends Binding.Service<
59 EventSource,
60 "AWS.EventBridge.EventSource",
61 EventSourceService
62 > {}
63 export const EventSource = Binding.Service<EventSource>("AWS.EventBridge.EventSource");
64
65 export type EventSourceService = <Detail = unknown, StreamReq = never, Req = never>(
66 descriptor: EventDescriptor,
67 process: (
68 events: Stream.Stream<EventRecord<Detail>, never, StreamReq>,
69 ) => Effect.Effect<void, never, Req>,
70 ) => Effect.Effect<void, never, never>;
71
72 /**
73 * Build a routing target for an EventBridge event bus. Pass the bus and
74 * pattern (no handler) and chain `.toLambda` / `.toQueue` / `.toEcsTask` to
75 * route matching events to a target resource.
76 *
77 * @example Route matching events to a Lambda function
78 * ```typescript
79 * yield* events(bus, { source: ["my.app"] }).toLambda(fn);
80 * ```
81 *
82 * @example Route matching events to an SQS queue
83 * ```typescript
84 * yield* events(bus, { source: ["my.app"] }).toQueue(queue);
85 * ```
86 *
87 * To consume events locally with a handler, use {@link consumeBusEvents}.
88 */
89 export const events = (...args: any[]) => {
90 const descriptor = parseEventDescriptor(args);
91
92 return {
93 toLambda: (fn: LambdaFunction, props: LambdaRouteTargetProps = {}) =>
94 createLambdaRoute(descriptor, fn, props),
95 toQueue: (queue: Queue, props: QueueRouteTargetProps = {}) =>
96 createQueueRoute(descriptor, queue, props),
97 toEcsTask: (cluster: Cluster, props: EcsRouteTargetProps) =>
98 createEcsTaskRoute(descriptor, cluster, props),
99 };
100 };
101
102 /**
103 * Consume events from an EventBridge event bus with a handler. The handler is
104 * the LAST positional argument; the event bus, pattern, and optional props
105 * precede it.
106 *
107 * @example Consume matching events with a handler
108 * ```typescript
109 * yield* consumeBusEvents(bus, { source: ["my.app"] }, (events) =>
110 * events.pipe(Stream.runForEach((event) => Effect.log(event))),
111 * );
112 * ```
113 *
114 * To route events to another resource instead of consuming them locally, use
115 * {@link events}.
116 */
117 export const consumeBusEvents = (...args: any[]) => {
118 // The handler is the LAST positional argument. Peel it off and run the
119 // subscribe body directly.
120 const process = args[args.length - 1] as (
121 events: Stream.Stream<EventRecord, never, never>,
122 ) => Effect.Effect<void, never, never>;
123 const descriptor = parseEventDescriptor(args.slice(0, -1));
124 return EventSource.use((source) => source(descriptor, process));
125 };
126
127 export const matchesEventPattern = (pattern: EventPattern, event: Record<string, any>): boolean =>
128 Object.entries(pattern).every(([key, expected]) => matchValue(expected, event[key]));
129
130 const matchValue = (expected: any, actual: any): boolean => {
131 if (Array.isArray(expected)) {
132 return expected.some((value) => matchValue(value, actual));
133 }
134
135 if (expected && typeof expected === "object") {
136 if (actual === null || typeof actual !== "object") {
137 return false;
138 }
139
140 return Object.entries(expected).every(([key, value]) => matchValue(value, actual[key]));
141 }
142
143 return actual === expected;
144 };
145
146 const parseEventDescriptor = (args: any[]): EventDescriptor => {
147 if (typeof args[0] === "string") {
148 if (isEventBus(args[1])) {
149 return {
150 id: args[0],
151 bus: args[1],
152 pattern: args[2],
153 props: args[3],
154 };
155 }
156
157 return {
158 id: args[0],
159 pattern: args[1],
160 props: args[2],
161 };
162 }
163
164 if (isEventBus(args[0])) {
165 return {
166 bus: args[0],
167 pattern: args[1],
168 props: args[2],
169 };
170 }
171
172 return {
173 pattern: args[0],
174 props: args[1],
175 };
176 };
177
178 const isEventBus = (value: any): value is EventBus =>
179 value &&
180 typeof value === "object" &&
181 "Type" in value &&
182 value.Type === "AWS.EventBridge.EventBus";