@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, 06:00 UTC

main
ts 355 lines 12.1 KB
Raw
1 import * as Lambda from "@distilled.cloud/aws/lambda";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 observeEventInvokeConfig,
14 syncEventInvokeConfig,
15 type EventInvokeConfig,
16 type ObservedEventInvokeConfig,
17 } from "./EventInvokeConfig.ts";
18 import type { Version } from "./Version.ts";
19
20 export interface AliasProps {
21 /**
22 * Managed Lambda version that this alias invokes.
23 */
24 version: Version;
25 /**
26 * Name of the alias. If omitted, a unique name is generated.
27 */
28 aliasName?: string;
29 /**
30 * Description of the alias.
31 */
32 description?: string;
33 /**
34 * Weighted routing configuration for shifting traffic to an additional
35 * function version.
36 */
37 routingConfig?: Lambda.AliasRoutingConfiguration;
38 /**
39 * Asynchronous invocation settings (retries, event age, destinations)
40 * scoped to this alias. Omit to remove any existing alias-level config and
41 * fall back to Lambda's defaults (2 retries, 6-hour max event age, no
42 * destinations).
43 */
44 eventInvokeConfig?: EventInvokeConfig;
45 }
46
47 export interface Alias extends Resource<
48 "AWS.Lambda.Alias",
49 AliasProps,
50 {
51 /**
52 * ARN of the Lambda alias.
53 */
54 aliasArn: string;
55 /**
56 * Name of the alias.
57 */
58 aliasName: string;
59 /**
60 * Name or ARN of the Lambda function this alias belongs to.
61 */
62 functionName: string;
63 /**
64 * Lambda function version that this alias invokes.
65 */
66 functionVersion: string;
67 /**
68 * API Gateway-compatible invocation ARN for this alias.
69 */
70 invokeArn: string;
71 /**
72 * Description of the alias.
73 */
74 description?: string;
75 /**
76 * Weighted routing configuration for this alias.
77 */
78 routingConfig?: Lambda.AliasRoutingConfiguration;
79 /**
80 * Latest Lambda revision id for this alias.
81 */
82 revisionId?: string;
83 /**
84 * Asynchronous invocation config (retries, maximum event age,
85 * destinations) scoped to the alias, as observed. Lets `alchemy drift`
86 * detect out-of-band changes.
87 */
88 eventInvokeConfig?: ObservedEventInvokeConfig;
89 },
90 never,
91 Providers
92 > {}
93
94 type ResolvedAliasProps = Input.ResolveProps<AliasProps>;
95
96 const resolvedProps = (props: AliasProps): ResolvedAliasProps =>
97 props as unknown as ResolvedAliasProps;
98
99 /**
100 * A Lambda alias for routing invocations to a stable function version.
101 *
102 * ### Creating Aliases
103 * **Example:** Production Alias
104 * ```typescript
105 * const version = yield* Version("ProductionVersion", { function: fn });
106 * const alias = yield* Alias("ProductionAlias", {
107 * version,
108 * aliasName: "production",
109 * });
110 * ```
111 *
112 * ### Weighted Routing
113 * **Example:** Shift Traffic to Another Version
114 * ```typescript
115 * const version = yield* Version("LiveVersion", { function: fn });
116 * const alias = yield* Alias("LiveAlias", {
117 * version,
118 * aliasName: "live",
119 * routingConfig: {
120 * AdditionalVersionWeights: {
121 * "3": 0.1,
122 * },
123 * },
124 * });
125 * ```
126 *
127 * ### Async Invocation
128 * **Example:** Alias-Scoped Retry Behavior
129 * ```typescript
130 * const version = yield* Version("LiveVersion", { function: fn });
131 * const alias = yield* Alias("LiveAlias", {
132 * version,
133 * aliasName: "live",
134 * eventInvokeConfig: {
135 * maximumRetryAttempts: 0,
136 * destinationConfig: {
137 * OnFailure: {
138 * Destination: queue.queueArn,
139 * },
140 * },
141 * },
142 * });
143 * ```
144 */
145 export const Alias = Resource<Alias>("AWS.Lambda.Alias");
146
147 const normalizeRoutingConfig = (
148 config: Lambda.AliasRoutingConfiguration | undefined,
149 ): Lambda.AliasRoutingConfiguration | undefined => {
150 const weights = Object.fromEntries(
151 Object.entries(config?.AdditionalVersionWeights ?? {}).filter(
152 (entry): entry is [string, number] => entry[1] !== undefined,
153 ),
154 );
155 return Object.keys(weights).length > 0 ? { AdditionalVersionWeights: weights } : undefined;
156 };
157
158 export const AliasProvider = () =>
159 Provider.effect(
160 Alias,
161 Effect.gen(function* () {
162 const createAliasName = (id: string, aliasName?: string) =>
163 aliasName
164 ? Effect.succeed(aliasName)
165 : createPhysicalName({
166 id,
167 maxLength: 128,
168 delimiter: "-",
169 });
170
171 const retryOnAliasConflict = <A, E extends { _tag: string }, R>(
172 effect: Effect.Effect<A, E, R>,
173 ) =>
174 effect.pipe(
175 Effect.retry({
176 while: (e) => e._tag === "ResourceConflictException",
177 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(10)]),
178 }),
179 );
180
181 const snapshotAlias = (
182 functionName: string,
183 alias: Lambda.AliasConfiguration,
184 region: string,
185 ): Alias["Attributes"] | undefined => {
186 if (!alias.AliasArn || !alias.Name || !alias.FunctionVersion) {
187 return undefined;
188 }
189 return {
190 aliasArn: alias.AliasArn,
191 aliasName: alias.Name,
192 functionName,
193 functionVersion: alias.FunctionVersion,
194 invokeArn: `arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${alias.AliasArn}/invocations`,
195 description: alias.Description || undefined,
196 routingConfig: normalizeRoutingConfig(alias.RoutingConfig),
197 revisionId: alias.RevisionId,
198 };
199 };
200
201 return {
202 stables: ["aliasArn", "aliasName", "functionName"],
203 diff: Effect.fn(function* ({ id, olds, news }) {
204 if (!isResolved(news)) return;
205 const resolvedOlds = resolvedProps(olds);
206 const resolvedNews = resolvedProps(news);
207 // An interrupted create persists the Version reference as missing
208 // (see stripUnresolved); there is no old function to compare.
209 if (resolvedOlds.version === undefined) return;
210 const oldAliasName = yield* createAliasName(id, resolvedOlds.aliasName);
211 const newAliasName = yield* createAliasName(id, resolvedNews.aliasName);
212 if (
213 resolvedOlds.version.functionName !== resolvedNews.version.functionName ||
214 oldAliasName !== newAliasName
215 ) {
216 return { action: "replace" } as const;
217 }
218 }),
219 read: Effect.fn(function* ({ id, olds, output }) {
220 // An interrupted create's first checkpoint strips the Version
221 // reference while the Version is still being created (see
222 // stripUnresolved), so `olds.version` can be missing.
223 const functionName =
224 output?.functionName ?? (olds ? resolvedProps(olds).version?.functionName : undefined);
225 if (!functionName) return undefined;
226 const aliasName =
227 output?.aliasName ??
228 (yield* createAliasName(id, olds ? resolvedProps(olds).aliasName : undefined));
229 const { region } = yield* AWSEnvironment.current;
230 const alias = yield* Lambda.getAlias({
231 FunctionName: functionName,
232 Name: aliasName,
233 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
234 const attrs = alias ? snapshotAlias(functionName, alias, region) : undefined;
235 if (!attrs) return undefined;
236 return {
237 ...attrs,
238 eventInvokeConfig: yield* observeEventInvokeConfig(functionName, attrs.aliasName),
239 };
240 }),
241 list: () =>
242 Effect.gen(function* () {
243 const { region } = yield* AWSEnvironment.current;
244 const functionNames = yield* Lambda.listFunctions.pages({}).pipe(
245 Stream.runCollect,
246 Effect.map((chunk) =>
247 Array.from(chunk).flatMap((page) =>
248 (page.Functions ?? [])
249 .map((fn) => fn.FunctionName)
250 .filter((name): name is string => name !== undefined),
251 ),
252 ),
253 );
254 const aliases = yield* Effect.forEach(
255 functionNames,
256 (functionName) =>
257 Lambda.listAliases.items({ FunctionName: functionName }).pipe(
258 Stream.runCollect,
259 Effect.map((chunk) =>
260 Array.from(chunk).flatMap((alias) => {
261 const attrs = snapshotAlias(functionName, alias, region);
262 return attrs ? [attrs] : [];
263 }),
264 ),
265 Effect.catchTag("ResourceNotFoundException", () =>
266 Effect.succeed([] as Alias["Attributes"][]),
267 ),
268 ),
269 { concurrency: 10 },
270 );
271 return aliases.flat();
272 }),
273 reconcile: Effect.fn(function* ({ id, news, output, session }) {
274 const resolvedNews = resolvedProps(news);
275 const functionName = resolvedNews.version.functionName;
276 const functionVersion = resolvedNews.version.version;
277 const { region } = yield* AWSEnvironment.current;
278 const aliasName =
279 output?.aliasName ?? (yield* createAliasName(id, resolvedNews.aliasName));
280 const desiredRoutingConfig = normalizeRoutingConfig(resolvedNews.routingConfig);
281 const getAlias = Lambda.getAlias({
282 FunctionName: functionName,
283 Name: aliasName,
284 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
285
286 let alias = yield* getAlias;
287
288 if (!alias) {
289 alias = yield* Lambda.createAlias({
290 FunctionName: functionName,
291 Name: aliasName,
292 FunctionVersion: functionVersion,
293 Description: resolvedNews.description,
294 RoutingConfig: desiredRoutingConfig,
295 }).pipe(Effect.catchTag("ResourceConflictException", () => getAlias));
296 }
297
298 const observedRoutingConfig = normalizeRoutingConfig(alias?.RoutingConfig);
299 if (
300 !alias ||
301 alias.FunctionVersion !== functionVersion ||
302 (alias.Description || undefined) !== resolvedNews.description ||
303 !deepEqual(observedRoutingConfig, desiredRoutingConfig)
304 ) {
305 alias = yield* retryOnAliasConflict(
306 Lambda.updateAlias({
307 FunctionName: functionName,
308 Name: aliasName,
309 FunctionVersion: functionVersion,
310 Description: resolvedNews.description ?? "",
311 RoutingConfig:
312 desiredRoutingConfig ??
313 (observedRoutingConfig ? { AdditionalVersionWeights: {} } : undefined),
314 }),
315 );
316 }
317
318 const attrs = snapshotAlias(functionName, alias, region);
319 if (!attrs) {
320 return yield* Effect.die(
321 `Lambda alias ${aliasName} did not return complete attributes.`,
322 );
323 }
324
325 yield* syncEventInvokeConfig({
326 functionName,
327 qualifier: attrs.aliasName,
328 config: resolvedNews.eventInvokeConfig,
329 });
330
331 yield* session.note(`Alias ${attrs.aliasName} on ${attrs.functionName}`);
332
333 return {
334 ...attrs,
335 eventInvokeConfig: yield* observeEventInvokeConfig(functionName, attrs.aliasName),
336 };
337 }),
338 delete: Effect.fn(function* ({ output }) {
339 // The alias-scoped async config does not die with the alias — clear
340 // it first so a later alias of the same name starts clean.
341 yield* syncEventInvokeConfig({
342 functionName: output.functionName,
343 qualifier: output.aliasName,
344 config: undefined,
345 });
346 yield* retryOnAliasConflict(
347 Lambda.deleteAlias({
348 FunctionName: output.functionName,
349 Name: output.aliasName,
350 }),
351 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
352 }),
353 };
354 }),
355 );