@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 514 lines 18.3 KB
Raw
1 import * as Lambda from "@distilled.cloud/aws/lambda";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Provider from "alchemy/Provider";
6 import { Resource, type ResourceClassLike } from "alchemy/Resource";
7 import { Stack } from "alchemy/Stack";
8 import { Stage } from "alchemy/Stage";
9 import { sha256Object } from "alchemy/Util/sha256";
10 import * as Effect from "effect/Effect";
11 import * as Redacted from "effect/Redacted";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import type { Providers } from "../Providers.ts";
15 import type { Function } from "./Function.ts";
16
17 export interface VersionProps {
18 /**
19 * Managed Lambda function whose current code and versioned configuration
20 * should be published.
21 */
22 function: Function;
23 }
24
25 type VersionAttributes = {
26 /**
27 * Name of the Lambda function this version belongs to.
28 */
29 functionName: string;
30 /**
31 * Unqualified ARN of the Lambda function.
32 */
33 functionArn: string;
34 /**
35 * Immutable version number assigned by Lambda, represented as a string.
36 */
37 version: string;
38 /**
39 * ARN qualified with this immutable version number.
40 */
41 versionArn: string;
42 /**
43 * Secret-safe fingerprint of the function ARN, code, and versioned
44 * configuration.
45 */
46 sourceHash: string;
47 /**
48 * Base64-encoded SHA-256 of the published function code, as reported by
49 * Lambda.
50 */
51 codeSha256: string;
52 /**
53 * SHA-256 of the post-binding, versioned Lambda configuration. Secret values
54 * contribute to this digest but are never stored in state.
55 */
56 configSha256: string;
57 };
58
59 export interface Version extends Resource<
60 "AWS.Lambda.Version",
61 VersionProps,
62 VersionAttributes,
63 never,
64 Providers
65 > {}
66
67 interface VersionResourceProps extends VersionProps {
68 /**
69 * Internal dependency on a non-stable Function attribute. Its value is not
70 * the release identity; it prevents publication from racing a Function
71 * update whose publishable configuration has not settled yet.
72 */
73 deploymentHash: string;
74 }
75
76 interface VersionResource extends Resource<
77 "AWS.Lambda.Version",
78 VersionResourceProps,
79 VersionAttributes,
80 never,
81 Providers
82 > {}
83
84 type ResolvedVersionProps = Input.ResolveProps<VersionResourceProps>;
85
86 /**
87 * Resource references resolve to their Attributes before provider lifecycle
88 * methods run. Provider's generic Props type intentionally preserves the
89 * author-facing resource type, so expose that engine guarantee in one place.
90 */
91 const resolvedProps = (props: VersionResourceProps): ResolvedVersionProps =>
92 props as unknown as ResolvedVersionProps;
93
94 const VersionResource = Resource<VersionResource>("AWS.Lambda.Version", {
95 defaultRemovalPolicy: "retain",
96 });
97
98 export interface VersionClass extends ResourceClassLike<Version> {
99 (id: string, props: { function: Function }): Effect.Effect<Version, never, Providers>;
100 ref(id: string, options?: { stage?: string; stack?: string }): Effect.Effect<Version>;
101 }
102
103 /**
104 * An immutable numbered version of a managed Lambda function.
105 *
106 * The provider publishes only after the Function's code and configuration
107 * have settled. Re-applying unchanged code and versioned configuration reuses
108 * the existing version. Function-level operational changes, such as reserved
109 * concurrency, do not publish a new version.
110 *
111 * Versions default to **retain** on removal. Moving or deleting an alias never
112 * deletes an older version, so in-flight durable executions can continue
113 * replaying against the code that started them. Use `destroy()` only when the
114 * exact numbered version is safe to remove.
115 *
116 * ### Publishing a Version
117 * **Example:** Publish a Managed Function
118 * ```typescript
119 * const fn = yield* AWS.Lambda.Function("Handler", {
120 * main: import.meta.resolve("./handler.ts"),
121 * });
122 * const version = yield* AWS.Lambda.Version("HandlerVersion", {
123 * function: fn,
124 * });
125 * ```
126 *
127 * ### Promoting with an Alias
128 * **Example:** Stable Production Alias
129 * ```typescript
130 * const version = yield* AWS.Lambda.Version("CampaignRunVersion", {
131 * function: campaign.function,
132 * });
133 * const live = yield* AWS.Lambda.Alias("CampaignRunLive", {
134 * version,
135 * aliasName: "live",
136 * });
137 * ```
138 *
139 * ### Explicit Deletion
140 * **Example:** Delete the Exact Version on Stack Destroy
141 * ```typescript
142 * import { destroy } from "alchemy/RemovalPolicy";
143 *
144 * const disposable = yield* AWS.Lambda.Version("PreviewVersion", {
145 * function: fn,
146 * }).pipe(destroy());
147 * ```
148 *
149 * @resource
150 */
151 export const Version = Object.assign(
152 (id: string, props: VersionProps) =>
153 VersionResource(id, {
154 function: props.function,
155 deploymentHash: props.function.code.hash,
156 }) as unknown as Effect.Effect<Version, never, Providers>,
157 {
158 Type: VersionResource.Type,
159 Provider: VersionResource.Provider,
160 Self: VersionResource.Self,
161 Aliases: VersionResource.Aliases,
162 ref: ((id, options) => VersionResource.ref(id, options)) as VersionClass["ref"],
163 },
164 ) as unknown as VersionClass;
165
166 interface VersionMarker {
167 ownerHash: string;
168 instanceHash: string;
169 sourceHash: string;
170 }
171
172 const MARKER_RE = /^\[alchemy:v=1;o=([a-f0-9]{64});i=([a-f0-9]{64});s=([a-f0-9]{64})\]$/;
173
174 const parseMarker = (description: string | undefined): VersionMarker | undefined => {
175 const match = description?.match(MARKER_RE);
176 return match
177 ? {
178 ownerHash: match[1],
179 instanceHash: match[2],
180 sourceHash: match[3],
181 }
182 : undefined;
183 };
184
185 const isNumberedVersion = (version: string | undefined): version is string =>
186 version !== undefined && /^[1-9]\d*$/.test(version);
187
188 export const VersionProvider = () =>
189 Provider.effect(
190 VersionResource,
191 Effect.gen(function* () {
192 const ownerIdentity = Effect.fn(function* (id: string, fqn: string, instanceId: string) {
193 const stack = yield* Stack;
194 const stage = yield* Stage;
195 return {
196 ownerHash: yield* sha256Object({
197 stack: stack.name,
198 stage,
199 fqn,
200 id,
201 }),
202 instanceHash: yield* sha256Object({ instanceId }),
203 };
204 });
205
206 const sourceHashOf = (functionArn: string, codeSha256: string, configSha256: string) =>
207 sha256Object({
208 functionArn,
209 codeSha256,
210 configSha256,
211 });
212
213 const markerFor = Effect.fn(function* (
214 id: string,
215 fqn: string,
216 instanceId: string,
217 sourceHash: string,
218 ) {
219 const identity = yield* ownerIdentity(id, fqn, instanceId);
220 return {
221 ...identity,
222 sourceHash,
223 description: `[alchemy:v=1;o=${identity.ownerHash};i=${identity.instanceHash};s=${sourceHash}]`,
224 };
225 });
226
227 const publishableConfiguration = (configuration: Lambda.FunctionConfiguration) => ({
228 runtime: configuration.Runtime,
229 role: configuration.Role,
230 handler: configuration.Handler,
231 timeout: configuration.Timeout,
232 memorySize: configuration.MemorySize,
233 vpc: configuration.VpcConfig
234 ? {
235 subnetIds: [...(configuration.VpcConfig.SubnetIds ?? [])].sort(),
236 securityGroupIds: [...(configuration.VpcConfig.SecurityGroupIds ?? [])].sort(),
237 ipv6AllowedForDualStack: configuration.VpcConfig.Ipv6AllowedForDualStack,
238 }
239 : undefined,
240 deadLetterConfig: configuration.DeadLetterConfig,
241 environment: Object.fromEntries(
242 Object.entries(configuration.Environment?.Variables ?? {}).map(([key, value]) => [
243 key,
244 Redacted.isRedacted(value) ? Redacted.value(value) : value,
245 ]),
246 ),
247 kmsKeyArn: configuration.KMSKeyArn,
248 tracingConfig: configuration.TracingConfig,
249 layers: configuration.Layers?.map((layer) => layer.Arn),
250 fileSystemConfigs: configuration.FileSystemConfigs,
251 packageType: configuration.PackageType,
252 imageConfig: configuration.ImageConfigResponse?.ImageConfig,
253 architectures: configuration.Architectures,
254 ephemeralStorage: configuration.EphemeralStorage,
255 snapStart: configuration.SnapStart?.ApplyOn,
256 loggingConfig: configuration.LoggingConfig,
257 tenancyConfig: configuration.TenancyConfig,
258 capacityProviderConfig: configuration.CapacityProviderConfig,
259 durableConfig: configuration.DurableConfig,
260 });
261
262 const completeConfiguration = Effect.fn(function* (
263 functionName: string,
264 configuration: Lambda.FunctionConfiguration,
265 ) {
266 if (
267 !configuration.FunctionArn ||
268 !configuration.FunctionName ||
269 !configuration.CodeSha256
270 ) {
271 throw new Error(
272 `Lambda function ${functionName} did not return the hashes required to publish a version.`,
273 );
274 }
275 return {
276 functionArn: configuration.FunctionArn.replace(/:(?:\$LATEST|[1-9]\d*)$/, ""),
277 functionName: configuration.FunctionName,
278 codeSha256: configuration.CodeSha256,
279 configSha256: yield* sha256Object(publishableConfiguration(configuration)),
280 };
281 });
282
283 const snapshot = Effect.fn(function* (configuration: Lambda.FunctionConfiguration) {
284 if (!isNumberedVersion(configuration.Version)) return undefined;
285 const complete = yield* completeConfiguration(
286 configuration.FunctionName ?? "unknown",
287 configuration,
288 );
289 const sourceHash = yield* sourceHashOf(
290 complete.functionArn,
291 complete.codeSha256,
292 complete.configSha256,
293 );
294 return {
295 ...complete,
296 version: configuration.Version,
297 versionArn: `${complete.functionArn}:${configuration.Version}`,
298 sourceHash,
299 } satisfies Version["Attributes"];
300 });
301
302 const getVersion = (functionName: string, version: string) =>
303 Lambda.getFunctionConfiguration({
304 FunctionName: functionName,
305 Qualifier: version,
306 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
307
308 const listVersions = (functionName: string) =>
309 Lambda.listVersionsByFunction.items({ FunctionName: functionName }).pipe(
310 Stream.runCollect,
311 Effect.map((chunk) =>
312 Array.from(chunk).filter((version) => isNumberedVersion(version.Version)),
313 ),
314 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
315 );
316
317 const waitForLatest = Effect.fn(function* (functionName: string) {
318 const configuration = yield* Lambda.getFunctionConfiguration({
319 FunctionName: functionName,
320 Qualifier: "$LATEST",
321 }).pipe(
322 Effect.repeat({
323 schedule: Schedule.spaced("1 second"),
324 until: (current) =>
325 current.State !== "Pending" &&
326 current.State !== "Deactivating" &&
327 current.LastUpdateStatus !== "InProgress",
328 times: 45,
329 }),
330 );
331 if (
332 configuration.State === "Failed" ||
333 configuration.State === "Deactivated" ||
334 configuration.State === "Deleting" ||
335 configuration.LastUpdateStatus === "Failed"
336 ) {
337 return yield* Effect.die(
338 new Error(
339 `Lambda function ${functionName} did not settle successfully: ${
340 configuration.LastUpdateStatusReason ??
341 configuration.StateReason ??
342 configuration.LastUpdateStatus ??
343 configuration.State ??
344 "unknown state"
345 }`,
346 ),
347 );
348 }
349 return configuration;
350 });
351
352 const findOwnedVersion = Effect.fn(function* (functionName: string, marker: VersionMarker) {
353 const versions = yield* listVersions(functionName);
354 const matches = versions
355 .flatMap((version) => {
356 const parsed = parseMarker(version.Description);
357 return parsed?.ownerHash === marker.ownerHash && parsed.sourceHash === marker.sourceHash
358 ? [version]
359 : [];
360 })
361 .sort((a, b) => Number.parseInt(b.Version!, 10) - Number.parseInt(a.Version!, 10));
362 return (
363 matches.find(
364 (version) => parseMarker(version.Description)?.instanceHash === marker.instanceHash,
365 ) ?? matches[0]
366 );
367 });
368
369 return {
370 nuke: { skip: true },
371 stables: ["functionName", "functionArn"],
372 diff: Effect.fn(function* ({ olds, news, output }) {
373 const pendingFunctionName = (
374 news as unknown as {
375 function?: { functionName?: Input<string> };
376 }
377 ).function?.functionName;
378 if (
379 output &&
380 pendingFunctionName !== undefined &&
381 isResolved(pendingFunctionName) &&
382 resolvedProps(olds).function.functionName !== pendingFunctionName
383 ) {
384 return { action: "replace" } as const;
385 }
386 if (!isResolved(news)) {
387 return output ? ({ action: "update" } as const) : undefined;
388 }
389 const resolvedOlds = resolvedProps(olds);
390 const resolvedNews = resolvedProps(news);
391 if (!output) return undefined;
392 if (
393 !Object.prototype.hasOwnProperty.call(resolvedNews.function, "code") ||
394 !deepEqual(resolvedOlds.function, resolvedNews.function)
395 ) {
396 return { action: "update" } as const;
397 }
398 return { action: "noop" } as const;
399 }),
400 read: Effect.fn(function* ({ id, fqn, instanceId, olds, output }) {
401 if (output) {
402 const observed = yield* getVersion(output.functionName, output.version);
403 if (!observed) return undefined;
404 const attrs = yield* snapshot(observed);
405 if (!attrs) return undefined;
406 const marker = parseMarker(observed.Description);
407 const identity = yield* ownerIdentity(id, fqn, instanceId);
408 return marker?.ownerHash === identity.ownerHash &&
409 marker.sourceHash === attrs.sourceHash
410 ? attrs
411 : Unowned(attrs);
412 }
413
414 // An interrupted create's first checkpoint strips the Function
415 // reference while the Function is still being created (see
416 // stripUnresolved), so `olds.function` can be missing. With no
417 // function name there is no version to recover.
418 const functionName = olds ? resolvedProps(olds).function?.functionName : undefined;
419 if (!functionName) return undefined;
420 const latest = yield* waitForLatest(functionName);
421 const complete = yield* completeConfiguration(functionName, latest);
422 const sourceHash = yield* sourceHashOf(
423 complete.functionArn,
424 complete.codeSha256,
425 complete.configSha256,
426 );
427 const desired = yield* markerFor(id, fqn, instanceId, sourceHash);
428 const recovered = yield* findOwnedVersion(functionName, desired);
429 return recovered ? yield* snapshot(recovered) : undefined;
430 }),
431 list: () =>
432 Effect.gen(function* () {
433 const functionNames = yield* Lambda.listFunctions.items({}).pipe(
434 Stream.runCollect,
435 Effect.map((chunk) =>
436 Array.from(chunk)
437 .map((fn) => fn.FunctionName)
438 .filter((name): name is string => name !== undefined),
439 ),
440 );
441 const versions = yield* Effect.forEach(
442 functionNames,
443 (functionName) =>
444 listVersions(functionName).pipe(
445 Effect.flatMap((items) => Effect.forEach(items, snapshot, { concurrency: 10 })),
446 Effect.map((items) =>
447 items.filter((item): item is Version["Attributes"] => item !== undefined),
448 ),
449 ),
450 { concurrency: 10 },
451 );
452 return versions.flat();
453 }),
454 reconcile: Effect.fn(function* ({ id, fqn, instanceId, news, session }) {
455 const resolvedNews = resolvedProps(news);
456 const ensure = Effect.gen(function* () {
457 const latest = yield* waitForLatest(resolvedNews.function.functionName);
458 const complete = yield* completeConfiguration(
459 resolvedNews.function.functionName,
460 latest,
461 );
462 const sourceHash = yield* sourceHashOf(
463 complete.functionArn,
464 complete.codeSha256,
465 complete.configSha256,
466 );
467 const marker = yield* markerFor(id, fqn, instanceId, sourceHash);
468 const existing = yield* findOwnedVersion(complete.functionName, marker);
469 if (existing) {
470 const attrs = yield* snapshot(existing);
471 if (attrs) return attrs;
472 }
473
474 const published = yield* Lambda.publishVersion({
475 FunctionName: complete.functionName,
476 CodeSha256: complete.codeSha256,
477 RevisionId: latest.RevisionId,
478 Description: marker.description,
479 });
480 const attrs = yield* snapshot(published);
481 if (
482 !attrs ||
483 attrs.sourceHash !== sourceHash ||
484 published.Description !== marker.description
485 ) {
486 return yield* Effect.die(
487 new Error(
488 `Lambda function ${complete.functionName} did not return the expected published version.`,
489 ),
490 );
491 }
492 return attrs;
493 }).pipe(
494 Effect.retry({
495 while: (error) =>
496 error._tag === "PreconditionFailedException" ||
497 error._tag === "ResourceConflictException",
498 schedule: Schedule.max([Schedule.exponential("250 millis"), Schedule.recurs(8)]),
499 }),
500 );
501
502 const attrs = yield* ensure;
503 yield* session.note(`Version ${attrs.functionName}:${attrs.version}`);
504 return attrs;
505 }),
506 delete: Effect.fn(function* ({ output }) {
507 yield* Lambda.deleteFunction({
508 FunctionName: output.functionName,
509 Qualifier: output.version,
510 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
511 }),
512 };
513 }),
514 );