@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 205 lines 7.57 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import * as Stream from "effect/Stream";
5 import type { Application } from "../AppConfig/Application.ts";
6 import {
7 DeploymentEventSource as AppConfigDeploymentEventSourceContract,
8 type DeploymentEventRecord,
9 type DeploymentEventSourceProps,
10 type DeploymentEventSourceService,
11 type DeploymentEventType,
12 } from "../AppConfig/DeploymentEventSource.ts";
13 import type { Environment } from "../AppConfig/Environment.ts";
14 import { Extension } from "../AppConfig/Extension.ts";
15 import { ExtensionAssociation } from "../AppConfig/ExtensionAssociation.ts";
16 import { Role } from "../IAM/Role.ts";
17 import * as Lambda from "./Function.ts";
18
19 const ALL_DEPLOYMENT_EVENTS: DeploymentEventType[] = [
20 "ON_DEPLOYMENT_START",
21 "ON_DEPLOYMENT_STEP",
22 "ON_DEPLOYMENT_BAKING",
23 "ON_DEPLOYMENT_COMPLETE",
24 "ON_DEPLOYMENT_ROLLED_BACK",
25 ];
26
27 /** Short, deterministic suffix distinguishing subscriptions by action-point set. */
28 const eventSetSuffix = (events: DeploymentEventType[]): string =>
29 [...events]
30 .sort()
31 .map((event) =>
32 event
33 .replace("ON_DEPLOYMENT_", "")
34 .toLowerCase()
35 .split("_")
36 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
37 .join(""),
38 )
39 .join("");
40
41 /**
42 * Narrow an arbitrary Lambda invocation payload to an AppConfig extension
43 * deployment notification.
44 */
45 export const isAppConfigDeploymentEvent = (event: any): event is DeploymentEventRecord =>
46 typeof event?.InvocationId === "string" &&
47 typeof event?.Type === "string" &&
48 typeof event?.Application === "object";
49
50 const isEnvironment = (target: Application | Environment): target is Environment =>
51 target.Type === "AWS.AppConfig.Environment";
52
53 /**
54 * Lambda runtime implementation for `AWS.AppConfig.consumeDeploymentEvents(...)`.
55 *
56 * This layer does two things:
57 *
58 * 1. At deploy time it provisions an AppConfig {@link Extension} whose
59 * actions invoke the current Lambda function at the subscribed deployment
60 * action points, the IAM role AppConfig assumes to perform the
61 * invocation, and an {@link ExtensionAssociation} attaching the extension
62 * to the target application or environment.
63 * 2. At runtime it narrows incoming invocations to AppConfig deployment
64 * notifications for the bound target and forwards them into the supplied
65 * handler as a typed `DeploymentEventRecord` stream.
66 * ### Consuming Deployment Events
67 * **Example:** Record Completed Deployments
68 * ```typescript
69 * yield* AppConfig.consumeDeploymentEvents(
70 * env,
71 * { events: ["ON_DEPLOYMENT_COMPLETE"] },
72 * (events) =>
73 * events.pipe(
74 * Stream.runForEach((event) =>
75 * Effect.log(`deployment ${event.DeploymentNumber} completed`),
76 * ),
77 * ),
78 * );
79 * ```
80 *
81 * @binding
82 */
83 export const AppConfigDeploymentEventSource = Layer.effect(
84 AppConfigDeploymentEventSourceContract,
85 // The impl resolves plan-time services (Role, Extension, Association)
86 // whereas DeploymentEventSourceService erases the requirement channel to
87 // `never`.
88 // @effect-diagnostics-next-line missingEffectContext:off
89 Effect.gen(function* () {
90 const host = yield* Lambda.eventSourceHost("AWS.Lambda.AppConfigDeploymentEventSource");
91 const InvokeRole = yield* Role;
92 const DeploymentExtension = yield* Extension;
93 const DeploymentExtensionAssociation = yield* ExtensionAssociation;
94
95 return Effect.fn(function* <Req = never>(
96 target: Application | Environment,
97 props: DeploymentEventSourceProps,
98 process: (events: Stream.Stream<DeploymentEventRecord>) => Effect.Effect<void, never, Req>,
99 ) {
100 const events = props.events ?? ALL_DEPLOYMENT_EVENTS;
101 const suffix = eventSetSuffix(events);
102
103 // Resolving the target's id also registers it on the host environment;
104 // re-yield per invocation inside the listener below.
105 const TargetId = yield* isEnvironment(target) ? target.environmentId : target.applicationId;
106
107 // Deploy-time: provision the invoke role, the extension whose actions
108 // call this function at each subscribed action point, and the
109 // association binding the extension to the target. Skipped once running
110 // inside the deployed Function (the global guard), where the only work
111 // is registering the runtime handler below. Namespaced under the host
112 // so the sub-resources' logical identity is stable per host function.
113 if (!globalThis.__ALCHEMY_RUNTIME__) {
114 yield* Namespace.push(
115 host.LogicalId,
116 Effect.gen(function* () {
117 // NB: hyphenated logical ids only — the id lands in the
118 // `alchemy::id` tag value, and IAM/AppConfig tag values reject
119 // `(`, `)` and `,`.
120 const role = yield* InvokeRole(`${target.LogicalId}-${suffix}-InvokeRole`, {
121 assumeRolePolicyDocument: {
122 Version: "2012-10-17",
123 Statement: [
124 {
125 Effect: "Allow",
126 Principal: { Service: "appconfig.amazonaws.com" },
127 Action: ["sts:AssumeRole"],
128 },
129 ],
130 },
131 inlinePolicies: {
132 InvokeFunction: {
133 Version: "2012-10-17",
134 Statement: [
135 {
136 Effect: "Allow",
137 Action: ["lambda:InvokeFunction"],
138 Resource: [Lambda.qualifiedArnOf(host) as any],
139 },
140 ],
141 },
142 },
143 });
144
145 const extension = yield* DeploymentExtension(
146 `${target.LogicalId}-${suffix}-DeploymentEvents`,
147 {
148 description: `Deployment notifications for ${target.LogicalId} -> ${host.LogicalId}`,
149 actions: Object.fromEntries(
150 events.map((event) => [
151 event,
152 [
153 {
154 name: event,
155 uri: Lambda.qualifiedArnOf(host) as any,
156 roleArn: role.roleArn as any,
157 },
158 ],
159 ]),
160 ),
161 },
162 );
163
164 yield* DeploymentExtensionAssociation(
165 `${target.LogicalId}-${suffix}-DeploymentEventsAssociation`,
166 {
167 extensionIdentifier: extension.extensionId as any,
168 resourceIdentifier: (isEnvironment(target)
169 ? target.environmentArn
170 : target.applicationArn) as any,
171 },
172 );
173 }),
174 );
175 }
176
177 yield* host.listen(
178 Effect.gen(function* () {
179 const targetId = yield* TargetId;
180 const subscribed = new Set(
181 events.map((event) =>
182 // "ON_DEPLOYMENT_START" -> "OnDeploymentStart" (payload `Type`)
183 event
184 .toLowerCase()
185 .split("_")
186 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
187 .join(""),
188 ),
189 );
190 return (event: any) => {
191 if (
192 isAppConfigDeploymentEvent(event) &&
193 subscribed.has(event.Type) &&
194 (isEnvironment(target)
195 ? event.Environment?.Id === targetId
196 : event.Application?.Id === targetId)
197 ) {
198 return process(Stream.succeed(event)).pipe(Effect.orDie);
199 }
200 };
201 }),
202 );
203 }) as DeploymentEventSourceService;
204 }),
205 );