@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 1,036 lines 39.3 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import * as iam from "@distilled.cloud/aws/iam";
3 import * as lambda from "@distilled.cloud/aws/lambda";
4 import * as synthetics from "@distilled.cloud/aws/synthetics";
5 import { Unowned } from "alchemy/AdoptPolicy";
6 import { isResolved } from "alchemy/Diff";
7 import { createPhysicalName } from "alchemy/PhysicalName";
8 import * as Provider from "alchemy/Provider";
9 import { Resource } from "alchemy/Resource";
10 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
11 import { toWireDays, toWireSeconds } from "alchemy/Util/Duration";
12 import { sha256Object } from "alchemy/Util/sha256";
13 import { zipFiles } from "alchemy/Util/zip";
14 import * as Data from "effect/Data";
15 import type * as Duration from "effect/Duration";
16 import * as Effect from "effect/Effect";
17 import * as Schedule from "effect/Schedule";
18 import * as Stream from "effect/Stream";
19 import { AWSEnvironment } from "../Environment.ts";
20 import type { Providers } from "../Providers.ts";
21
22 export interface CanaryProps {
23 /**
24 * Name of the canary. Must be lowercase, up to 255 characters, and match
25 * `^[0-9a-z_-]+$`. Keep it to 21 characters or fewer so the derived Lambda
26 * function name (`cwsyn-<name>-...`) stays within limits.
27 * @default ${app}-${id}-${stage}-${suffix} (lowercased, truncated to 21 chars)
28 */
29 canaryName?: string;
30 /**
31 * Inline canary script source. For Node.js runtimes
32 * (`syn-nodejs-puppeteer-*`, `syn-nodejs-playwright-*`) the script is
33 * packaged as `nodejs/node_modules/<file>.js`; for Python runtimes
34 * (`syn-python-selenium-*`) as `python/<file>.py`, where `<file>` is the
35 * first segment of `handler`.
36 */
37 script: string;
38 /**
39 * The entry point of the canary script, `<fileName>.<functionName>`.
40 * @default "index.handler"
41 */
42 handler?: string;
43 /**
44 * The Synthetics runtime version to use.
45 * @default "syn-nodejs-puppeteer-16.1"
46 */
47 runtimeVersion?: string;
48 /**
49 * S3 location where the canary stores run artifacts (screenshots, HAR
50 * files, logs), e.g. `s3://my-bucket/canary-artifacts`. The `s3://` prefix
51 * is added automatically if missing.
52 */
53 artifactS3Location: string;
54 /**
55 * ARN of the IAM role the canary's Lambda assumes. When omitted, a role is
56 * created automatically with write access to the artifact bucket,
57 * CloudWatch Logs, and the `CloudWatchSynthetics` metric namespace.
58 */
59 executionRoleArn?: string;
60 /**
61 * How often the canary runs.
62 */
63 schedule?: {
64 /**
65 * A `rate(...)` expression (`rate(1 minute)` to `rate(1 hour)`), a
66 * `cron(...)` expression, or `rate(0 minute)` to run only once when
67 * started.
68 * @default "rate(5 minutes)"
69 */
70 expression?: string;
71 /**
72 * How long the canary keeps running on this schedule after it starts
73 * (up to 1 year), e.g. `"12 hours"` or `Duration.hours(12)` (a bare
74 * number is milliseconds). Rounded to whole seconds on the wire.
75 * `"0 seconds"` (or omitted) runs the canary continuously.
76 */
77 duration?: Duration.Input;
78 };
79 /**
80 * Whether the canary is started (scheduled to run) after deployment.
81 * When `false`, the canary is created in the `READY` state and never runs
82 * until started.
83 * @default false
84 */
85 start?: boolean;
86 /**
87 * Per-run configuration of the canary's Lambda.
88 */
89 runConfig?: {
90 /**
91 * Run timeout (max 840 seconds), e.g. `"60 seconds"` or
92 * `Duration.minutes(1)` (a bare number is milliseconds). Rounded to
93 * whole seconds on the wire. Defaults to the schedule frequency
94 * capped at 14 minutes.
95 */
96 timeout?: Duration.Input;
97 /**
98 * Memory in MB (multiple of 64, between 960 and 3008).
99 */
100 memoryInMB?: number;
101 /**
102 * Enable X-Ray active tracing for canary runs.
103 * @default false
104 */
105 activeTracing?: boolean;
106 /**
107 * Environment variables exposed to the canary script. Not observable
108 * from the API after creation.
109 */
110 environmentVariables?: Record<string, string>;
111 };
112 /**
113 * How long to retain data on successful runs (1 - 455 days), e.g.
114 * `"7 days"` or `Duration.days(7)` (a bare number is milliseconds).
115 * Rounded to whole days on the wire.
116 * @default 31 days
117 */
118 successRetentionPeriod?: Duration.Input;
119 /**
120 * How long to retain data on failed runs (1 - 455 days), e.g.
121 * `"31 days"` or `Duration.days(31)` (a bare number is milliseconds).
122 * Rounded to whole days on the wire.
123 * @default 31 days
124 */
125 failureRetentionPeriod?: Duration.Input;
126 /**
127 * Run the canary inside a VPC. Both fields are required together.
128 */
129 vpcConfig?: {
130 /** Subnet IDs the canary's ENIs are placed in. */
131 subnetIds: string[];
132 /** Security group IDs applied to the canary's ENIs. */
133 securityGroupIds: string[];
134 };
135 /**
136 * Whether the Lambda function and layers backing the canary are deleted
137 * automatically when the canary is deleted.
138 * @default "AUTOMATIC"
139 */
140 provisionedResourceCleanup?: "AUTOMATIC" | "OFF";
141 /**
142 * Tags to apply to the canary. Merged with internal Alchemy tags.
143 */
144 tags?: Record<string, string>;
145 }
146
147 export interface Canary extends Resource<
148 "AWS.Synthetics.Canary",
149 CanaryProps,
150 {
151 /**
152 * Physical name of the canary.
153 */
154 canaryName: string;
155 /**
156 * ARN of the canary.
157 */
158 canaryArn: string;
159 /**
160 * Service-assigned unique ID of the canary.
161 */
162 canaryId: string;
163 /**
164 * ARN of the IAM role the canary runs as.
165 */
166 executionRoleArn: string;
167 /**
168 * S3 location where run artifacts (screenshots, HAR files, logs) land.
169 */
170 artifactS3Location: string;
171 /**
172 * Synthetics runtime version the canary executes on.
173 */
174 runtimeVersion: string;
175 /** Name of the auto-created execution role; `undefined` when the user supplied `executionRoleArn`. */
176 roleName: string | undefined;
177 /** Hash of the last-applied desired configuration; used to skip no-op updates. */
178 configHash: string | undefined;
179 /** Exact ARN of the service-created Lambda function backing the canary. */
180 engineArn: string | undefined;
181 },
182 {},
183 Providers
184 > {}
185
186 /**
187 * A CloudWatch Synthetics canary — a scripted probe that monitors your
188 * endpoints and APIs on a schedule from the outside in.
189 *
190 * The canary script is provided inline and packaged automatically for the
191 * chosen runtime. Unless you pass `executionRoleArn`, an IAM execution role
192 * is created with least-privilege access to the artifact bucket, CloudWatch
193 * Logs, and Synthetics metrics.
194 * ### Creating Canaries
195 * **Example:** Heartbeat Canary (created stopped)
196 * ```typescript
197 * import * as Synthetics from "@alchemy.run/aws/Synthetics";
198 *
199 * const canary = yield* Synthetics.Canary("Heartbeat", {
200 * script: `
201 * const synthetics = require("Synthetics");
202 * exports.handler = async () => {
203 * return await synthetics.executeStep("heartbeat", async () => {});
204 * };
205 * `,
206 * artifactS3Location: Output.interpolate`s3://${bucket.bucketName}/canary`,
207 * });
208 * ```
209 *
210 * **Example:** Started Canary on a Schedule
211 * ```typescript
212 * const canary = yield* Synthetics.Canary("ApiMonitor", {
213 * script: myCanaryScript,
214 * artifactS3Location: "s3://my-artifacts/api-monitor",
215 * schedule: { expression: "rate(5 minutes)" },
216 * start: true,
217 * });
218 * ```
219 *
220 * ### Configuration
221 * **Example:** Custom Runtime, Timeout and Environment
222 * ```typescript
223 * const canary = yield* Synthetics.Canary("Checkout", {
224 * script: checkoutScript,
225 * runtimeVersion: "syn-nodejs-puppeteer-16.1",
226 * artifactS3Location: "s3://my-artifacts/checkout",
227 * runConfig: {
228 * timeout: "60 seconds",
229 * environmentVariables: { TARGET_URL: "https://example.com" },
230 * },
231 * successRetentionPeriod: "7 days",
232 * failureRetentionPeriod: "31 days",
233 * });
234 * ```
235 *
236 * **Example:** Bring Your Own Execution Role
237 * ```typescript
238 * const canary = yield* Synthetics.Canary("Probe", {
239 * script: probeScript,
240 * artifactS3Location: "s3://my-artifacts/probe",
241 * executionRoleArn: role.roleArn,
242 * });
243 * ```
244 *
245 * @resource
246 */
247 export const Canary = Resource<Canary>("AWS.Synthetics.Canary");
248
249 const DEFAULT_RUNTIME_VERSION = "syn-nodejs-puppeteer-16.1";
250 const DEFAULT_SCHEDULE_EXPRESSION = "rate(5 minutes)";
251 const ROLE_POLICY_NAME = "AlchemyCanaryPolicy";
252 const VPC_ACCESS_POLICY_ARN =
253 "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole";
254
255 /**
256 * Canary create/update/start/stop are asynchronous; the canary reports a
257 * transitional state while converging. Raised internally to drive the
258 * bounded settle-polling retry loop.
259 */
260 export class CanaryNotSettled extends Data.TaggedError("CanaryNotSettled")<{
261 canaryName: string;
262 state: string | undefined;
263 }> {}
264
265 /**
266 * Raised when a canary lands in the `ERROR` state after a create or update
267 * instead of converging to `READY`/`STOPPED`.
268 */
269 export class CanaryFailed extends Data.TaggedError("CanaryFailed")<{
270 canaryName: string;
271 stateReasonCode: string | undefined;
272 message: string;
273 }> {}
274
275 class CanaryBackingResourceStillVisible extends Data.TaggedError(
276 "CanaryBackingResourceStillVisible",
277 )<{
278 readonly canaryName: string;
279 readonly resource: "LambdaFunction" | "LogGroup";
280 readonly identifier: string;
281 }> {}
282
283 class UnexpectedCanaryEngineArn extends Data.TaggedError("UnexpectedCanaryEngineArn")<{
284 readonly canaryName: string;
285 readonly engineArn: string;
286 }> {}
287
288 const TRANSITIONAL_STATES = ["CREATING", "UPDATING", "STARTING", "STOPPING", "DELETING"];
289
290 /**
291 * Retry an operation while the canary is briefly locked by a concurrent
292 * state transition (`ConflictException`), on a bounded schedule (~60s).
293 * Module-scope with an explicit return type so the conditional `Retry.Return`
294 * type never leaks into declaration emit (which would widen the provider
295 * layer to `unknown`).
296 */
297 const retryWhileConflict = <A, E extends { _tag: string }, R>(
298 self: Effect.Effect<A, E, R>,
299 ): Effect.Effect<A, E, R> =>
300 Effect.retry(self, {
301 while: (e) => e._tag === "ConflictException",
302 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
303 });
304
305 const parseArtifactLocation = (location: string) => {
306 const stripped = location.startsWith("s3://") ? location.slice(5) : location;
307 return {
308 artifactS3Location: `s3://${stripped}`,
309 artifactBucket: stripped.split("/")[0]!,
310 };
311 };
312
313 const scriptFilePath = (runtimeVersion: string, handler: string) => {
314 const fileName = handler.split(".")[0]!;
315 return runtimeVersion.startsWith("syn-python")
316 ? `python/${fileName}.py`
317 : `nodejs/node_modules/${fileName}.js`;
318 };
319
320 /** Package the inline script as the zip layout the runtime expects. */
321 const buildCode = Effect.fn(function* (script: string, handler: string, runtimeVersion: string) {
322 const buffer = yield* zipFiles([
323 { path: scriptFilePath(runtimeVersion, handler), content: script },
324 ]);
325 return {
326 ZipFile: new Uint8Array(buffer),
327 Handler: handler,
328 } satisfies synthetics.CanaryCodeInput;
329 });
330
331 const filterTags = (
332 tags: { [key: string]: string | undefined } | undefined,
333 ): Record<string, string> =>
334 Object.fromEntries(
335 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
336 );
337
338 export const CanaryProvider = () =>
339 Provider.effect(
340 Canary,
341 Effect.gen(function* () {
342 const createCanaryName = Effect.fn(function* (
343 id: string,
344 props: { canaryName?: string | undefined },
345 ) {
346 if (props.canaryName) return props.canaryName;
347 // Canary names must be lowercase [0-9a-z_-]; the console caps them at
348 // 21 chars because the backing Lambda is named `cwsyn-<name>-<uuid>`.
349 return yield* createPhysicalName({
350 id,
351 maxLength: 21,
352 suffixLength: 8,
353 lowercase: true,
354 });
355 });
356
357 const createRoleName = (id: string) => createPhysicalName({ id, maxLength: 64 });
358
359 const canaryArnOf = Effect.fn(function* (canaryName: string) {
360 const { accountId, region } = yield* AWSEnvironment.current;
361 return `arn:aws:synthetics:${region}:${accountId}:canary:${canaryName}`;
362 });
363
364 const getCanaryOrUndefined = Effect.fn(function* (canaryName: string) {
365 return yield* synthetics.getCanary({ Name: canaryName }).pipe(
366 Effect.map((r) => r.Canary),
367 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
368 );
369 });
370
371 // Poll until the canary leaves its transitional state. Create typically
372 // settles in 30-90s; budget 3 minutes (60 * 3s).
373 const waitForSettled = Effect.fn(function* (canaryName: string) {
374 return yield* getCanaryOrUndefined(canaryName).pipe(
375 Effect.flatMap((canary) =>
376 canary !== undefined && TRANSITIONAL_STATES.includes(canary.Status?.State ?? "")
377 ? Effect.fail(
378 new CanaryNotSettled({
379 canaryName,
380 state: canary.Status?.State,
381 }),
382 )
383 : Effect.succeed(canary),
384 ),
385 Effect.retry({
386 while: (e) => e instanceof CanaryNotSettled,
387 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(60)]),
388 }),
389 );
390 });
391
392 const failIfErrored = (canaryName: string, canary: synthetics.Canary | undefined) =>
393 canary?.Status?.State === "ERROR"
394 ? Effect.fail(
395 new CanaryFailed({
396 canaryName,
397 stateReasonCode: canary.Status?.StateReasonCode,
398 message: canary.Status?.StateReason ?? `canary ${canaryName} is in ERROR state`,
399 }),
400 )
401 : Effect.void;
402
403 // Deletion is asynchronous (DELETING); wait until gone so a
404 // destroy-then-deploy of the same logical resource (same physical
405 // name) does not race the pending delete.
406 const waitUntilGone = Effect.fn(function* (canaryName: string) {
407 yield* getCanaryOrUndefined(canaryName).pipe(
408 Effect.flatMap((canary) =>
409 canary === undefined
410 ? Effect.void
411 : Effect.fail(
412 new CanaryNotSettled({
413 canaryName,
414 state: canary.Status?.State,
415 }),
416 ),
417 ),
418 Effect.retry({
419 while: (e) => e instanceof CanaryNotSettled,
420 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(40)]),
421 }),
422 );
423 });
424
425 // Stop (if running) + delete + wait-until-gone. Also used by reconcile
426 // to self-heal a canary stuck in CREATE_FAILED.
427 const deleteCanaryAndWait = Effect.fn(function* (canaryName: string) {
428 const observed = yield* getCanaryOrUndefined(canaryName);
429 if (observed === undefined) return;
430 const state = observed.Status?.State;
431 if (state === "RUNNING" || state === "STARTING") {
432 yield* synthetics
433 .stopCanary({ Name: canaryName })
434 .pipe(
435 Effect.catchTag(
436 ["ResourceNotFoundException", "ConflictException"],
437 () => Effect.void,
438 ),
439 );
440 }
441 // wait out any transitional state (STOPPING, UPDATING, ...) — a
442 // canary can only be deleted from READY/STOPPED/ERROR.
443 yield* waitForSettled(canaryName);
444 yield* synthetics.deleteCanary({ Name: canaryName, DeleteLambda: true }).pipe(
445 // e.g. a run is still finishing; bounded retry
446 retryWhileConflict,
447 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
448 );
449 yield* waitUntilGone(canaryName);
450 });
451
452 const backingFunctionName = (canaryName: string, engineArn: string) => {
453 const marker = ":function:";
454 const markerIndex = engineArn.indexOf(marker);
455 const functionName =
456 markerIndex === -1
457 ? undefined
458 : engineArn.slice(markerIndex + marker.length).split(":")[0];
459 // EngineArn is observed directly from this owned canary. Retain an
460 // explicit name check so a malformed or unexpectedly-shaped response
461 // can never make deletion target another Lambda.
462 return functionName?.startsWith(`cwsyn-${canaryName}-`)
463 ? Effect.succeed(functionName)
464 : Effect.fail(new UnexpectedCanaryEngineArn({ canaryName, engineArn }));
465 };
466
467 const discoverBackingFunctionNames = Effect.fn(function* (
468 canaryName: string,
469 engineArn: string | undefined,
470 ) {
471 if (engineArn) {
472 return [yield* backingFunctionName(canaryName, engineArn)];
473 }
474
475 // EngineArn is optional and is absent on some Synthetics runtimes.
476 // The backing Lambda's only observable relationship is its service
477 // name. Require the complete canonical UUID suffix so a canary named
478 // `foo` can never capture another named `foo-bar`.
479 const escapedCanaryName = canaryName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
480 const exactBackingName = new RegExp(
481 `^cwsyn-${escapedCanaryName}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`,
482 "i",
483 );
484 const pages = yield* lambda.listFunctions.pages({}).pipe(Stream.runCollect);
485 return Array.from(pages)
486 .flatMap((page) => page.Functions ?? [])
487 .flatMap((fn) =>
488 fn.FunctionName && exactBackingName.test(fn.FunctionName) ? [fn.FunctionName] : [],
489 );
490 });
491
492 const backingFunctionExists = (functionName: string) =>
493 lambda.getFunction({ FunctionName: functionName }).pipe(
494 Effect.as(true),
495 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(false)),
496 );
497
498 const exactLogGroupExists = (logGroupName: string) =>
499 logs
500 .describeLogGroups({
501 logGroupNamePrefix: logGroupName,
502 limit: 50,
503 })
504 .pipe(
505 Effect.map((response) =>
506 (response.logGroups ?? []).some((group) => group.logGroupName === logGroupName),
507 ),
508 );
509
510 const waitForBackingResourceGone = <E extends { readonly _tag: string }, R>(
511 canaryName: string,
512 resource: "LambdaFunction" | "LogGroup",
513 identifier: string,
514 exists: Effect.Effect<boolean, E, R>,
515 ) =>
516 exists.pipe(
517 Effect.flatMap((visible) =>
518 visible
519 ? Effect.fail(
520 new CanaryBackingResourceStillVisible({
521 canaryName,
522 resource,
523 identifier,
524 }),
525 )
526 : Effect.void,
527 ),
528 Effect.retry({
529 while: (error) => error._tag === "CanaryBackingResourceStillVisible",
530 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
531 }),
532 );
533
534 const deleteBackingResources = Effect.fn(function* (
535 canaryName: string,
536 functionName: string,
537 ) {
538 const logGroupName = `/aws/lambda/${functionName}`;
539
540 yield* lambda.deleteFunction({ FunctionName: functionName }).pipe(
541 Effect.retry({
542 while: (error) => error._tag === "ResourceConflictException",
543 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
544 }),
545 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
546 );
547 yield* waitForBackingResourceGone(
548 canaryName,
549 "LambdaFunction",
550 functionName,
551 backingFunctionExists(functionName),
552 );
553
554 // Lambda never owns its log group lifecycle. A just-finished
555 // invocation can flush its final stream after Lambda deletion starts,
556 // so reap this exact group across a short quiescence window.
557 for (let attempt = 0; attempt < 5; attempt++) {
558 if (yield* exactLogGroupExists(logGroupName)) {
559 yield* logs.deleteLogGroup({ logGroupName }).pipe(
560 Effect.retry({
561 while: (error) => error._tag === "OperationAbortedException",
562 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
563 }),
564 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
565 );
566 }
567 yield* Effect.sleep("2 seconds");
568 }
569 yield* waitForBackingResourceGone(
570 canaryName,
571 "LogGroup",
572 logGroupName,
573 exactLogGroupExists(logGroupName),
574 );
575 });
576
577 /**
578 * Ensure the auto-created execution role exists and its inline policy
579 * matches the artifact bucket. Every step is idempotent: create
580 * tolerates AlreadyExists, putRolePolicy is an upsert.
581 */
582 const ensureExecutionRole = Effect.fn(function* ({
583 id,
584 roleName,
585 artifactBucket,
586 vpc,
587 }: {
588 id: string;
589 roleName: string;
590 artifactBucket: string;
591 vpc: boolean;
592 }) {
593 const { accountId, region } = yield* AWSEnvironment.current;
594 const internalTags = yield* createInternalTags(id);
595 // Track whether we actually created the role on this pass — a fresh
596 // role needs a propagation grace period before Synthetics can build
597 // the backing Lambda with it.
598 let created = true;
599 yield* iam
600 .createRole({
601 RoleName: roleName,
602 AssumeRolePolicyDocument: JSON.stringify({
603 Version: "2012-10-17",
604 Statement: [
605 {
606 Effect: "Allow",
607 Principal: { Service: "lambda.amazonaws.com" },
608 Action: "sts:AssumeRole",
609 },
610 ],
611 }),
612 Tags: createTagsList(internalTags),
613 })
614 .pipe(
615 Effect.catchTag("EntityAlreadyExistsException", () =>
616 Effect.sync(() => {
617 created = false;
618 }),
619 ),
620 );
621 yield* iam.putRolePolicy({
622 RoleName: roleName,
623 PolicyName: ROLE_POLICY_NAME,
624 PolicyDocument: JSON.stringify({
625 Version: "2012-10-17",
626 Statement: [
627 {
628 Effect: "Allow",
629 Action: ["s3:PutObject", "s3:GetObject"],
630 Resource: [`arn:aws:s3:::${artifactBucket}/*`],
631 },
632 {
633 Effect: "Allow",
634 Action: ["s3:GetBucketLocation"],
635 Resource: [`arn:aws:s3:::${artifactBucket}`],
636 },
637 {
638 Effect: "Allow",
639 Action: ["s3:ListAllMyBuckets"],
640 Resource: ["*"],
641 },
642 {
643 Effect: "Allow",
644 Action: ["cloudwatch:PutMetricData"],
645 Resource: ["*"],
646 Condition: {
647 StringEquals: {
648 "cloudwatch:namespace": "CloudWatchSynthetics",
649 },
650 },
651 },
652 {
653 Effect: "Allow",
654 Action: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
655 Resource: [`arn:aws:logs:${region}:${accountId}:log-group:/aws/lambda/cwsyn-*`],
656 },
657 {
658 Effect: "Allow",
659 Action: ["xray:PutTraceSegments"],
660 Resource: ["*"],
661 },
662 ],
663 }),
664 });
665 if (vpc) {
666 yield* iam.attachRolePolicy({
667 RoleName: roleName,
668 PolicyArn: VPC_ACCESS_POLICY_ARN,
669 });
670 }
671 if (created) {
672 // IAM is eventually consistent — a canary created immediately after
673 // the role lands in CREATE_FAILED with "The role defined for the
674 // function cannot be assumed by Lambda". Give the role time to
675 // propagate; the CREATE_FAILED recreate loop below covers stragglers.
676 yield* Effect.sleep("10 seconds");
677 }
678 return `arn:aws:iam::${accountId}:role/${roleName}`;
679 });
680
681 // Tear down the auto-created execution role. Idempotent: every step
682 // tolerates the entity being gone.
683 const deleteExecutionRole = Effect.fn(function* (roleName: string) {
684 yield* iam
685 .deleteRolePolicy({
686 RoleName: roleName,
687 PolicyName: ROLE_POLICY_NAME,
688 })
689 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
690 yield* iam
691 .detachRolePolicy({
692 RoleName: roleName,
693 PolicyArn: VPC_ACCESS_POLICY_ARN,
694 })
695 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
696 yield* iam.deleteRole({ RoleName: roleName }).pipe(
697 Effect.retry({
698 while: (error) =>
699 error._tag === "ConcurrentModificationException" ||
700 error._tag === "DeleteConflictException" ||
701 error._tag === "LimitExceededException" ||
702 error._tag === "ServiceFailureException",
703 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(20)]),
704 }),
705 Effect.catchTag("NoSuchEntityException", () => Effect.void),
706 );
707
708 // IAM deletion is eventually consistent. Keep the canary's state
709 // until its owned execution role is observably absent so a following
710 // nuke cannot race the successful DeleteRole request.
711 for (let attempt = 0; attempt < 30; attempt++) {
712 const remaining = yield* iam
713 .getRole({ RoleName: roleName })
714 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
715 if (remaining === undefined) return;
716 yield* Effect.sleep("1 second");
717 }
718 return yield* Effect.die(
719 new Error(
720 `Synthetics execution role ${roleName} remained observable 30 seconds after delete`,
721 ),
722 );
723 });
724
725 const desiredConfigHash = (
726 props: CanaryProps,
727 executionRoleArn: string,
728 artifactS3Location: string,
729 runtimeVersion: string,
730 ) =>
731 sha256Object({
732 script: props.script,
733 handler: props.handler ?? "index.handler",
734 runtimeVersion,
735 artifactS3Location,
736 executionRoleArn,
737 schedule: {
738 expression: props.schedule?.expression ?? DEFAULT_SCHEDULE_EXPRESSION,
739 durationInSeconds: toWireSeconds(props.schedule?.duration) ?? 0,
740 },
741 runConfig:
742 props.runConfig === undefined
743 ? {}
744 : {
745 ...props.runConfig,
746 timeout: undefined,
747 timeoutInSeconds: toWireSeconds(props.runConfig.timeout),
748 },
749 successRetentionPeriodInDays: toWireDays(props.successRetentionPeriod),
750 failureRetentionPeriodInDays: toWireDays(props.failureRetentionPeriod),
751 vpcConfig: props.vpcConfig,
752 provisionedResourceCleanup: props.provisionedResourceCleanup ?? "AUTOMATIC",
753 });
754
755 const toRunConfigInput = (props: CanaryProps): synthetics.CanaryRunConfigInput | undefined =>
756 props.runConfig === undefined
757 ? undefined
758 : {
759 TimeoutInSeconds: toWireSeconds(props.runConfig.timeout),
760 MemoryInMB: props.runConfig.memoryInMB,
761 ActiveTracing: props.runConfig.activeTracing,
762 EnvironmentVariables: props.runConfig.environmentVariables,
763 };
764
765 const toScheduleInput = (props: CanaryProps): synthetics.CanaryScheduleInput => ({
766 Expression: props.schedule?.expression ?? DEFAULT_SCHEDULE_EXPRESSION,
767 DurationInSeconds: toWireSeconds(props.schedule?.duration),
768 });
769
770 const toVpcConfigInput = (props: CanaryProps): synthetics.VpcConfigInput | undefined =>
771 props.vpcConfig === undefined
772 ? undefined
773 : {
774 SubnetIds: props.vpcConfig.subnetIds,
775 SecurityGroupIds: props.vpcConfig.securityGroupIds,
776 };
777
778 return Canary.Provider.of({
779 stables: ["canaryName", "canaryArn", "canaryId", "roleName", "engineArn"],
780
781 // Enumerate every canary in the ambient account/region.
782 list: () =>
783 Effect.gen(function* () {
784 const pages = yield* synthetics.describeCanaries.pages({}).pipe(Stream.runCollect);
785 const canaries = Array.from(pages).flatMap((page) => page.Canaries ?? []);
786 const items: Canary["Attributes"][] = [];
787 for (const canary of canaries) {
788 if (!canary.Name) continue;
789 items.push({
790 canaryName: canary.Name,
791 canaryArn: yield* canaryArnOf(canary.Name),
792 canaryId: canary.Id ?? "",
793 executionRoleArn: canary.ExecutionRoleArn ?? "",
794 artifactS3Location: canary.ArtifactS3Location
795 ? parseArtifactLocation(canary.ArtifactS3Location).artifactS3Location
796 : "",
797 runtimeVersion: canary.RuntimeVersion ?? "",
798 roleName: undefined,
799 configHash: undefined,
800 engineArn: canary.EngineArn,
801 });
802 }
803 return items;
804 }),
805
806 read: Effect.fn(function* ({ id, olds, output }) {
807 const canaryName = output?.canaryName ?? (yield* createCanaryName(id, olds ?? {}));
808 const canary = yield* getCanaryOrUndefined(canaryName);
809 if (canary === undefined) return undefined;
810 const attrs: Canary["Attributes"] = {
811 canaryName,
812 canaryArn: yield* canaryArnOf(canaryName),
813 canaryId: canary.Id ?? "",
814 executionRoleArn: canary.ExecutionRoleArn ?? "",
815 artifactS3Location: canary.ArtifactS3Location
816 ? parseArtifactLocation(canary.ArtifactS3Location).artifactS3Location
817 : "",
818 runtimeVersion: canary.RuntimeVersion ?? "",
819 roleName: output?.roleName,
820 configHash: output?.configHash,
821 engineArn: canary.EngineArn ?? output?.engineArn,
822 };
823 const tags = filterTags(canary.Tags);
824 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
825 }),
826
827 diff: Effect.fn(function* ({ id, news, olds }) {
828 if (!isResolved(news)) return undefined;
829 const oldName = yield* createCanaryName(id, olds);
830 const newName = yield* createCanaryName(id, news);
831 if (oldName !== newName) {
832 return { action: "replace" } as const;
833 }
834 // everything else converges through updateCanary
835 }),
836
837 reconcile: Effect.fn(function* ({ id, news, output, session }) {
838 const canaryName = output?.canaryName ?? (yield* createCanaryName(id, news));
839 const canaryArn = yield* canaryArnOf(canaryName);
840 const internalTags = yield* createInternalTags(id);
841 const desiredTags = { ...news.tags, ...internalTags };
842 const { artifactS3Location, artifactBucket } = parseArtifactLocation(
843 news.artifactS3Location,
844 );
845 const runtimeVersion = news.runtimeVersion ?? DEFAULT_RUNTIME_VERSION;
846 const handler = news.handler ?? "index.handler";
847
848 // Ensure the execution role (user-supplied or auto-created, with
849 // its inline policy converged to the current artifact bucket).
850 let roleName: string | undefined;
851 let executionRoleArn: string;
852 if (news.executionRoleArn) {
853 executionRoleArn = news.executionRoleArn;
854 } else {
855 roleName = output?.roleName ?? (yield* createRoleName(id));
856 executionRoleArn = yield* ensureExecutionRole({
857 id,
858 roleName,
859 artifactBucket,
860 vpc: news.vpcConfig !== undefined,
861 });
862 }
863
864 const configHash = yield* desiredConfigHash(
865 news,
866 executionRoleArn,
867 artifactS3Location,
868 runtimeVersion,
869 );
870
871 // 1. OBSERVE — cloud state is authoritative.
872 let observed = yield* getCanaryOrUndefined(canaryName);
873
874 // Self-heal a canary stuck in CREATE_FAILED (e.g. a crashed prior
875 // deploy): it cannot be updated, only deleted and recreated.
876 if (
877 observed?.Status?.State === "ERROR" &&
878 observed.Status?.StateReasonCode === "CREATE_FAILED"
879 ) {
880 yield* session.note(
881 `canary ${canaryName} is in CREATE_FAILED (${observed.Status?.StateReason}); recreating`,
882 );
883 yield* deleteCanaryAndWait(canaryName);
884 observed = undefined;
885 }
886
887 // 2. ENSURE — create if missing; wait for the async create to
888 // settle (CREATING → READY, typically 30-90s).
889 if (observed === undefined) {
890 const code = yield* buildCode(news.script, handler, runtimeVersion);
891 // Canary creation is asynchronous and validated in the backend:
892 // an execution role that hasn't finished propagating surfaces as
893 // CREATE_FAILED ("role ... cannot be assumed by Lambda") only
894 // AFTER the create settles. A CREATE_FAILED canary can't be
895 // updated — delete it and recreate, bounded to 3 attempts.
896 for (let attempt = 0; ; attempt++) {
897 yield* synthetics.createCanary({
898 Name: canaryName,
899 Code: code,
900 ArtifactS3Location: artifactS3Location,
901 ExecutionRoleArn: executionRoleArn,
902 Schedule: toScheduleInput(news),
903 RunConfig: toRunConfigInput(news),
904 RuntimeVersion: runtimeVersion,
905 SuccessRetentionPeriodInDays: toWireDays(news.successRetentionPeriod),
906 FailureRetentionPeriodInDays: toWireDays(news.failureRetentionPeriod),
907 VpcConfig: toVpcConfigInput(news),
908 ProvisionedResourceCleanup: news.provisionedResourceCleanup ?? "AUTOMATIC",
909 Tags: desiredTags,
910 });
911 yield* session.note(`created canary ${canaryName}, waiting for it to become ready`);
912 observed = yield* waitForSettled(canaryName);
913 if (
914 observed?.Status?.State === "ERROR" &&
915 observed.Status?.StateReasonCode === "CREATE_FAILED"
916 ) {
917 // A failed create is not persisted by the engine, so leaving
918 // the CREATE_FAILED canary behind would leak it — delete it
919 // whether we retry or give up.
920 yield* session.note(
921 `canary create failed (${observed.Status?.StateReason}); deleting`,
922 );
923 yield* deleteCanaryAndWait(canaryName);
924 if (attempt < 2) {
925 yield* Effect.sleep("10 seconds");
926 continue;
927 }
928 // Giving up — the engine does not persist a failed create, so
929 // also remove the execution role we auto-created this pass.
930 if (roleName !== undefined) {
931 yield* deleteExecutionRole(roleName);
932 }
933 }
934 yield* failIfErrored(canaryName, observed);
935 break;
936 }
937 } else {
938 // 3. SYNC config — the script content is not observable from the
939 // API (only a source-location ARN), so we use the persisted
940 // configHash as a skip-hint; on adoption (no hash) or any prop
941 // change we push the full desired configuration, which is
942 // idempotent.
943 observed = yield* waitForSettled(canaryName);
944 yield* failIfErrored(canaryName, observed);
945 if (output?.configHash !== configHash) {
946 const code = yield* buildCode(news.script, handler, runtimeVersion);
947 yield* synthetics
948 .updateCanary({
949 Name: canaryName,
950 Code: code,
951 ExecutionRoleArn: executionRoleArn,
952 RuntimeVersion: runtimeVersion,
953 Schedule: toScheduleInput(news),
954 RunConfig: toRunConfigInput(news),
955 SuccessRetentionPeriodInDays: toWireDays(news.successRetentionPeriod),
956 FailureRetentionPeriodInDays: toWireDays(news.failureRetentionPeriod),
957 VpcConfig: toVpcConfigInput(news),
958 ArtifactS3Location: artifactS3Location,
959 ProvisionedResourceCleanup: news.provisionedResourceCleanup ?? "AUTOMATIC",
960 })
961 .pipe(retryWhileConflict);
962 yield* session.note(`updated canary ${canaryName}`);
963 observed = yield* waitForSettled(canaryName);
964 yield* failIfErrored(canaryName, observed);
965 }
966 }
967
968 // 4. SYNC run state — start/stop to match the `start` prop.
969 const desiredRunning = news.start ?? false;
970 const state = observed?.Status?.State;
971 if (desiredRunning && state !== "RUNNING") {
972 yield* synthetics.startCanary({ Name: canaryName }).pipe(retryWhileConflict);
973 yield* session.note(`started canary ${canaryName}`);
974 observed = yield* waitForSettled(canaryName);
975 } else if (!desiredRunning && state === "RUNNING") {
976 yield* synthetics
977 .stopCanary({ Name: canaryName })
978 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
979 yield* session.note(`stopped canary ${canaryName}`);
980 observed = yield* waitForSettled(canaryName);
981 }
982
983 // 5. SYNC tags — diff against OBSERVED cloud tags so adoption
984 // converges (create already applied them; update cannot).
985 const currentTags = filterTags(observed?.Tags);
986 const { upsert, removed } = diffTags(currentTags, desiredTags);
987 if (upsert.length > 0) {
988 yield* synthetics.tagResource({
989 ResourceArn: canaryArn,
990 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
991 });
992 }
993 if (removed.length > 0) {
994 yield* synthetics.untagResource({
995 ResourceArn: canaryArn,
996 TagKeys: removed,
997 });
998 }
999
1000 yield* session.note(canaryName);
1001 return {
1002 canaryName,
1003 canaryArn,
1004 canaryId: observed?.Id ?? "",
1005 executionRoleArn,
1006 artifactS3Location,
1007 runtimeVersion,
1008 roleName,
1009 configHash,
1010 engineArn: observed?.EngineArn,
1011 };
1012 }),
1013
1014 delete: Effect.fn(function* ({ output, session }) {
1015 const observed = yield* getCanaryOrUndefined(output.canaryName);
1016 const engineArn = observed?.EngineArn ?? output.engineArn;
1017 const backingFunctions = yield* discoverBackingFunctionNames(
1018 output.canaryName,
1019 engineArn,
1020 );
1021 yield* deleteCanaryAndWait(output.canaryName);
1022 for (const functionName of backingFunctions) {
1023 yield* session.note(
1024 `deleting exact backing Lambda ${functionName} and log group /aws/lambda/${functionName}`,
1025 );
1026 yield* deleteBackingResources(output.canaryName, functionName);
1027 }
1028 // Clean up the auto-created execution role (never a user-supplied
1029 // one).
1030 if (output.roleName) {
1031 yield* deleteExecutionRole(output.roleName);
1032 }
1033 }),
1034 });
1035 }),
1036 );