@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 95 lines 2.8 KB
Raw
1 import { createHash } from "node:crypto";
2 import * as Effect from "effect/Effect";
3 import type { PolicyStatement } from "../IAM/Policy.ts";
4 import type { Queue } from "../SQS/Queue.ts";
5 import type { EventBus } from "./EventBus.ts";
6 import { Rule, type RuleProps, type RuleTarget } from "./Rule.ts";
7
8 interface EventDescriptor {
9 id?: string;
10 bus?: EventBus;
11 pattern: Record<string, any>;
12 props?: Pick<RuleProps, "description" | "state">;
13 }
14
15 export interface QueueRouteTargetProps extends Pick<
16 RuleTarget,
17 "Input" | "InputPath" | "InputTransformer" | "RetryPolicy" | "DeadLetterConfig"
18 > {
19 sqsParameters?: RuleTarget["SqsParameters"];
20 }
21
22 /**
23 * Routes matching events from an EventBridge bus to an SQS queue.
24 *
25 * Creates a {@link Rule} targeting the queue and binds a queue policy that
26 * allows `events.amazonaws.com` to send messages from that rule. Usually
27 * reached through the `events(...)` builder rather than called directly.
28 * **Example:** Route Matching Events to an SQS Queue
29 * ```typescript
30 * yield* AWS.EventBridge.events(bus, { source: ["my.app"] }).toQueue(queue);
31 * ```
32 *
33 * @binding
34 */
35 export const toQueue = (
36 descriptor: EventDescriptor,
37 queue: Queue,
38 props: QueueRouteTargetProps = {},
39 ) =>
40 Effect.gen(function* () {
41 const routeId = descriptor.id ?? createRouteId(descriptor, `${queue.LogicalId}Queue`);
42
43 const rule = yield* Rule(routeId, {
44 description: descriptor.props?.description,
45 state: descriptor.props?.state,
46 eventBusName: descriptor.bus?.eventBusName,
47 eventPattern: descriptor.pattern,
48 targets: [
49 {
50 Id: `${queue.LogicalId}Target`,
51 Arn: queue.queueArn as any,
52 Input: props.Input,
53 InputPath: props.InputPath,
54 InputTransformer: props.InputTransformer,
55 RetryPolicy: props.RetryPolicy,
56 DeadLetterConfig: props.DeadLetterConfig,
57 SqsParameters: props.sqsParameters,
58 },
59 ],
60 });
61
62 if (!globalThis.__ALCHEMY_RUNTIME__) {
63 yield* queue.bind`Allow(${rule}, AWS.EventBridge.toQueue(${queue}))`({
64 policyStatements: [
65 {
66 Effect: "Allow",
67 Principal: {
68 Service: "events.amazonaws.com",
69 },
70 Action: ["sqs:SendMessage"],
71 Resource: [queue.queueArn as any],
72 Condition: {
73 ArnEquals: {
74 "aws:SourceArn": [rule.ruleArn as any],
75 },
76 },
77 } satisfies PolicyStatement,
78 ],
79 });
80 }
81
82 return rule;
83 });
84
85 const createRouteId = (descriptor: EventDescriptor, suffix: string) =>
86 `EventBridge${createHash("sha1")
87 .update(
88 JSON.stringify({
89 bus: descriptor.bus?.LogicalId ?? "default",
90 pattern: descriptor.pattern,
91 suffix,
92 }),
93 )
94 .digest("hex")
95 .slice(0, 10)}`;