@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 354 lines 12.6 KB
Raw
1 import * as appconfig from "@distilled.cloud/aws/appconfig";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readAppConfigTags, syncAppConfigTags } from "./internal.ts";
13
14 /**
15 * The workflow points at which AppConfig invokes an extension's actions.
16 * `PRE_*` action points run synchronously and can validate or modify the
17 * operation; `ON_*` action points are notifications fired as a deployment
18 * progresses.
19 */
20 export type ExtensionActionPoint =
21 | "PRE_CREATE_HOSTED_CONFIGURATION_VERSION"
22 | "PRE_START_DEPLOYMENT"
23 | "AT_DEPLOYMENT_TICK"
24 | "ON_DEPLOYMENT_START"
25 | "ON_DEPLOYMENT_STEP"
26 | "ON_DEPLOYMENT_BAKING"
27 | "ON_DEPLOYMENT_COMPLETE"
28 | "ON_DEPLOYMENT_ROLLED_BACK";
29
30 /**
31 * A single action AppConfig performs when the owning action point fires.
32 */
33 export interface ExtensionAction {
34 /** Name of the action (unique within the extension). */
35 name: string;
36 /** Description of what the action does. */
37 description?: string;
38 /**
39 * ARN of the integration target: a Lambda function, SNS topic, SQS queue,
40 * or EventBridge event bus.
41 */
42 uri: string;
43 /**
44 * ARN of an IAM role AppConfig assumes to invoke the target. Required for
45 * Lambda, SNS, and SQS targets; not used for EventBridge targets.
46 */
47 roleArn?: string;
48 }
49
50 /**
51 * A parameter the extension accepts. Values are supplied per association via
52 * {@link ExtensionAssociationProps.parameters}.
53 */
54 export interface ExtensionParameter {
55 /** Description of the parameter. */
56 description?: string;
57 /** Whether every association must supply a value. */
58 required?: boolean;
59 /** Whether the value may be supplied at deployment time. */
60 dynamic?: boolean;
61 }
62
63 export interface ExtensionProps {
64 /**
65 * Name of the extension. If omitted, a deterministic physical name is
66 * generated. Changing the name replaces the extension.
67 */
68 extensionName?: string;
69 /**
70 * Description of the extension.
71 */
72 description?: string;
73 /**
74 * The actions to perform, keyed by the action point that triggers them.
75 */
76 actions: { [P in ExtensionActionPoint]?: ExtensionAction[] };
77 /**
78 * Parameters accepted by the extension, keyed by parameter name. Values are
79 * supplied when the extension is associated with a resource.
80 */
81 parameters?: Record<string, ExtensionParameter>;
82 /**
83 * User-defined tags for the extension.
84 */
85 tags?: Record<string, string>;
86 }
87
88 export interface Extension extends Resource<
89 "AWS.AppConfig.Extension",
90 ExtensionProps,
91 {
92 extensionId: string;
93 extensionName: string;
94 extensionArn: string;
95 versionNumber: number;
96 },
97 never,
98 Providers
99 > {}
100
101 /**
102 * An AWS AppConfig extension — a set of actions AppConfig performs at
103 * specific points of the configuration workflow (before a version is
104 * created, before/while/after a deployment). Actions can invoke Lambda
105 * functions, publish to SNS/SQS, or emit EventBridge events.
106 *
107 * Associate the extension with an application, environment, or configuration
108 * profile using {@link ExtensionAssociation}.
109 *
110 * ### Creating an Extension
111 * **Example:** Notify a Lambda when a deployment completes
112 * ```typescript
113 * const extension = yield* AppConfig.Extension("DeployHook", {
114 * actions: {
115 * ON_DEPLOYMENT_COMPLETE: [
116 * {
117 * name: "notify",
118 * uri: fn.functionArn,
119 * roleArn: role.roleArn,
120 * },
121 * ],
122 * },
123 * });
124 * ```
125 *
126 * **Example:** Validate content before a deployment starts
127 * ```typescript
128 * const extension = yield* AppConfig.Extension("PreflightCheck", {
129 * description: "Reject deployments outside business hours",
130 * actions: {
131 * PRE_START_DEPLOYMENT: [
132 * { name: "preflight", uri: fn.functionArn, roleArn: role.roleArn },
133 * ],
134 * },
135 * });
136 * ```
137 *
138 * @resource
139 */
140 export const Extension = Resource<Extension>("AWS.AppConfig.Extension");
141
142 const toWireActions = (
143 actions: ExtensionProps["actions"],
144 ): { [key: string]: appconfig.Action[] | undefined } =>
145 Object.fromEntries(
146 Object.entries(actions).map(([point, list]) => [
147 point,
148 list?.map((action) => ({
149 Name: action.name,
150 Description: action.description,
151 Uri: action.uri,
152 RoleArn: action.roleArn,
153 })),
154 ]),
155 );
156
157 const toWireParameters = (
158 parameters: ExtensionProps["parameters"],
159 ): { [key: string]: appconfig.Parameter | undefined } | undefined =>
160 parameters === undefined
161 ? undefined
162 : Object.fromEntries(
163 Object.entries(parameters).map(([name, parameter]) => [
164 name,
165 {
166 Description: parameter.description,
167 Required: parameter.required,
168 Dynamic: parameter.dynamic,
169 },
170 ]),
171 );
172
173 /** Stable JSON for order-insensitive comparison of wire action/param maps. */
174 const stableJson = (value: unknown): string =>
175 JSON.stringify(value, (_, v) =>
176 v !== null && typeof v === "object" && !Array.isArray(v)
177 ? Object.fromEntries(
178 Object.entries(v as Record<string, unknown>)
179 .filter(([, fieldValue]) => fieldValue !== undefined)
180 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
181 )
182 : v,
183 );
184
185 export const ExtensionProvider = () =>
186 Provider.effect(
187 Extension,
188 Effect.gen(function* () {
189 const toName = (id: string, props: Partial<ExtensionProps>) =>
190 props.extensionName
191 ? Effect.succeed(props.extensionName)
192 : createPhysicalName({ id, maxLength: 64 });
193
194 const readExtension = Effect.fn(function* (extensionId: string) {
195 return yield* appconfig
196 .getExtension({ ExtensionIdentifier: extensionId })
197 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
198 });
199
200 const findByName = Effect.fn(function* (name: string) {
201 const summaries = yield* appconfig.listExtensions.pages({ Name: name }).pipe(
202 Stream.runCollect,
203 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
204 );
205 // listExtensions returns one summary per version — take the latest.
206 const latest = summaries.reduce(
207 (acc: appconfig.ExtensionSummary | undefined, summary: appconfig.ExtensionSummary) =>
208 acc === undefined || (summary.VersionNumber ?? 0) > (acc.VersionNumber ?? 0)
209 ? summary
210 : acc,
211 undefined,
212 );
213 return latest?.Id === undefined ? undefined : yield* readExtension(latest.Id);
214 });
215
216 const toAttrs = (extension: appconfig.Extension) => ({
217 extensionId: extension.Id!,
218 extensionName: extension.Name!,
219 extensionArn: extension.Arn!,
220 versionNumber: extension.VersionNumber ?? 1,
221 });
222
223 return {
224 stables: ["extensionId", "extensionName", "extensionArn"],
225
226 diff: Effect.fn(function* ({ id, olds, news }) {
227 if (!isResolved(news)) return undefined;
228 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
229 return { action: "replace" } as const;
230 }
231 }),
232
233 read: Effect.fn(function* ({ id, olds, output }) {
234 const extension = output?.extensionId
235 ? yield* readExtension(output.extensionId)
236 : yield* findByName(yield* toName(id, olds ?? {}));
237 if (extension?.Id === undefined) return undefined;
238 const attrs = toAttrs(extension);
239 const tags = yield* readAppConfigTags(attrs.extensionArn);
240 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
241 }),
242
243 reconcile: Effect.fn(function* ({ id, news, output, session }) {
244 const name = output?.extensionName ?? (yield* toName(id, news));
245 const internalTags = yield* createInternalTags(id);
246 const desiredTags = { ...internalTags, ...news.tags };
247 const desiredActions = toWireActions(news.actions);
248 const desiredParameters = toWireParameters(news.parameters);
249
250 // 1. Observe.
251 let observed = output?.extensionId ? yield* readExtension(output.extensionId) : undefined;
252 if (observed === undefined) {
253 observed = yield* findByName(name);
254 }
255
256 // 2. Ensure. A freshly created invoke role may not be assumable
257 // yet (IAM propagation), which AppConfig surfaces as
258 // BadRequestException — absorb that window with a bounded retry.
259 if (observed?.Id === undefined) {
260 observed = yield* appconfig
261 .createExtension({
262 Name: name,
263 Description: news.description,
264 Actions: desiredActions,
265 Parameters: desiredParameters,
266 Tags: desiredTags,
267 })
268 .pipe(
269 Effect.retry({
270 while: (e): boolean => e._tag === "BadRequestException",
271 schedule: Schedule.fixed("3 seconds"),
272 times: 5,
273 }),
274 );
275 } else if (
276 (observed.Description ?? undefined) !== (news.description ?? undefined) ||
277 stableJson(observed.Actions ?? {}) !== stableJson(desiredActions) ||
278 stableJson(observed.Parameters ?? {}) !== stableJson(desiredParameters ?? {})
279 ) {
280 // 3. Sync — description, actions, and parameters are mutable
281 // (AppConfig records the change as a new extension version).
282 observed = yield* appconfig.updateExtension({
283 ExtensionIdentifier: observed.Id,
284 Description: news.description,
285 Actions: desiredActions,
286 Parameters: desiredParameters,
287 });
288 }
289
290 const attrs = toAttrs(observed);
291
292 // 3b. Sync tags against observed cloud tags.
293 yield* syncAppConfigTags(attrs.extensionArn, desiredTags);
294
295 yield* session.note(name);
296 return attrs;
297 }),
298
299 delete: Effect.fn(function* ({ output }) {
300 // Associations must be gone before the extension can be deleted;
301 // the engine deletes them first, but the API is eventually
302 // consistent, so absorb the dependency-violation window (surfaced
303 // as BadRequestException) with a bounded retry.
304 yield* appconfig.deleteExtension({ ExtensionIdentifier: output.extensionId }).pipe(
305 Effect.retry({
306 while: (e): boolean => e._tag === "BadRequestException",
307 schedule: Schedule.fixed("3 seconds"),
308 times: 5,
309 }),
310 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
311 );
312 }),
313
314 list: () =>
315 Effect.gen(function* () {
316 const summaries = yield* appconfig.listExtensions.pages({}).pipe(
317 Stream.runCollect,
318 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
319 );
320 // One summary per version — keep the latest version per id.
321 const latest = new Map<string, appconfig.ExtensionSummary>();
322 for (const summary of summaries) {
323 if (summary.Id === undefined) continue;
324 const existing = latest.get(summary.Id);
325 if (
326 existing === undefined ||
327 (summary.VersionNumber ?? 0) > (existing.VersionNumber ?? 0)
328 ) {
329 latest.set(summary.Id, summary);
330 }
331 }
332 return Array.from(latest.values()).flatMap((summary) =>
333 summary.Id !== undefined &&
334 summary.Name !== undefined &&
335 summary.Arn !== undefined &&
336 // AWS-authored extensions (AWS.AppConfig.FeatureFlags,
337 // AWS.AppConfig.DeploymentNotificationsTo*, ...) are managed by
338 // AWS and cannot be deleted; their ARNs have an empty account
339 // segment (arn:aws:appconfig:{region}::extension/...).
340 summary.Arn.split(":")[4] !== ""
341 ? [
342 {
343 extensionId: summary.Id,
344 extensionName: summary.Name,
345 extensionArn: summary.Arn,
346 versionNumber: summary.VersionNumber ?? 1,
347 },
348 ]
349 : [],
350 );
351 }),
352 };
353 }),
354 );