The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,615 lines 57.9 KB
Raw
1 import { Docker } from "@alchemy.run/docker/Docker";
2 import * as apprunner from "@distilled.cloud/aws/apprunner";
3 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
4 import * as ecr from "@distilled.cloud/aws/ecr";
5 import * as iam from "@distilled.cloud/aws/iam";
6 import type { Region } from "@distilled.cloud/aws/Region";
7 import { Unowned } from "alchemy/AdoptPolicy";
8 import { AlchemyContext } from "alchemy/AlchemyContext";
9 import * as Bundle from "alchemy/Bundle/Bundle";
10 import { findCwdForBundle, getStableContextDir, resolveMainPath } from "alchemy/Bundle/TempRoot";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
14 import * as Provider from "alchemy/Provider";
15 import { Resource, type ResourceBinding } from "alchemy/Resource";
16 import {
17 createHostRuntimeContext,
18 type HostRuntimeContext,
19 type ServerHost,
20 } from "alchemy/Runtime/Process";
21 import { Stack } from "alchemy/Stack";
22 import { createInternalTags, createTagsList, hasAlchemyTags, hasTags } from "alchemy/Tags";
23 import { toSeconds } from "alchemy/Util/Duration";
24 import * as Data from "effect/Data";
25 import type * as Duration from "effect/Duration";
26 import * as Effect from "effect/Effect";
27 import * as Option from "effect/Option";
28 import * as Redacted from "effect/Redacted";
29 import * as Schedule from "effect/Schedule";
30 import * as Stream from "effect/Stream";
31 import type * as rolldown from "rolldown";
32 import { roleHostBundle } from "../AWSBindings.ts";
33 import type { Credentials } from "../Credentials.ts";
34 import { buildAndPushEcrImage } from "../ECR/Image.ts";
35 import { AWSEnvironment } from "../Environment.ts";
36 import type { PolicyStatement } from "../IAM/Policy.ts";
37 import type { Providers } from "../Providers.ts";
38 import { readAppRunnerTags, syncAppRunnerTags, toWireTags } from "./internal.ts";
39
40 export class ServiceOperationFailed extends Data.TaggedError("ServiceOperationFailed")<{
41 readonly message: string;
42 readonly cause?: unknown;
43 }> {}
44
45 export class ServiceInvalidProps extends Data.TaggedError("ServiceInvalidProps")<{
46 readonly message: string;
47 readonly cause?: unknown;
48 }> {}
49
50 export class ServiceUnexpectedResponse extends Data.TaggedError("ServiceUnexpectedResponse")<{
51 readonly message: string;
52 readonly cause?: unknown;
53 }> {}
54
55 export class ServiceConflict extends Data.TaggedError("ServiceConflict")<{
56 readonly message: string;
57 readonly cause?: unknown;
58 }> {}
59
60 /**
61 * Container image source for an App Runner service.
62 */
63 export interface ServiceImageRepository {
64 /**
65 * Image identifier: a private ECR image URI
66 * (`{account}.dkr.ecr.{region}.amazonaws.com/{repo}:{tag}`) or a public
67 * ECR image (`public.ecr.aws/{alias}/{repo}:{tag}`).
68 */
69 imageIdentifier: string;
70 /**
71 * Repository type. `ECR` (private, requires `accessRoleArn`) or
72 * `ECR_PUBLIC` (public gallery images, no access role).
73 */
74 imageRepositoryType: "ECR" | "ECR_PUBLIC";
75 /**
76 * Port the application listens on.
77 * @default "8080"
78 */
79 port?: string;
80 /**
81 * Command App Runner runs to start the container. Overrides the image's
82 * default start command.
83 */
84 startCommand?: string;
85 /**
86 * Environment variables available to the running service.
87 */
88 runtimeEnvironmentVariables?: Record<string, string>;
89 /**
90 * Secrets exposed as environment variables. Values are Secrets Manager
91 * secret ARNs or SSM parameter ARNs (the instance role must be able to
92 * read them).
93 */
94 runtimeEnvironmentSecrets?: Record<string, string>;
95 }
96
97 /**
98 * Compute resources for each instance of the service.
99 */
100 export interface ServiceInstanceConfiguration {
101 /**
102 * CPU units per instance: `"256"` (0.25 vCPU), `"512"`, `"1024"`,
103 * `"2048"`, or `"4096"`. The `"0.25 vCPU"`-style forms are also
104 * accepted.
105 * @default "1024"
106 */
107 cpu?: string;
108 /**
109 * Memory per instance in MB: `"512"`, `"1024"`, `"2048"`, `"3072"`,
110 * `"4096"`, `"6144"`, `"8192"`, `"10240"`, or `"12288"`. The
111 * `"2 GB"`-style forms are also accepted.
112 * @default "2048"
113 */
114 memory?: string;
115 /**
116 * IAM role assumed by the running service (analogous to an ECS task
117 * role). Required when the app calls AWS APIs or reads
118 * `runtimeEnvironmentSecrets`. For the Effect-native form (`main`),
119 * Alchemy provisions and manages this role automatically.
120 */
121 instanceRoleArn?: string;
122 }
123
124 /**
125 * Health check App Runner performs against the service.
126 */
127 export interface ServiceHealthCheckConfiguration {
128 /**
129 * Health check protocol.
130 * @default "TCP"
131 */
132 protocol?: "TCP" | "HTTP";
133 /**
134 * URL path for HTTP health checks.
135 * @default "/"
136 */
137 path?: string;
138 /**
139 * Time between health checks, e.g. `"5 seconds"` or
140 * `Duration.seconds(5)` (1-20 seconds on the wire).
141 * @default "5 seconds"
142 */
143 interval?: Duration.Input;
144 /**
145 * Time to wait for a response, e.g. `"2 seconds"` or
146 * `Duration.seconds(2)` (1-20 seconds on the wire).
147 * @default "2 seconds"
148 */
149 timeout?: Duration.Input;
150 /**
151 * Consecutive successful checks before the target is healthy (1-20).
152 * @default 1
153 */
154 healthyThreshold?: number;
155 /**
156 * Consecutive failed checks before the target is unhealthy (1-20).
157 * @default 5
158 */
159 unhealthyThreshold?: number;
160 }
161
162 /**
163 * Network settings for inbound and outbound service traffic.
164 */
165 export interface ServiceNetworkConfiguration {
166 /**
167 * Outbound traffic routing. `DEFAULT` egresses through App Runner;
168 * `VPC` routes through the VPC connector named by `vpcConnectorArn`.
169 * @default "DEFAULT"
170 */
171 egressType?: "DEFAULT" | "VPC";
172 /**
173 * ARN of the App Runner VPC connector for `egressType: "VPC"`.
174 */
175 vpcConnectorArn?: string;
176 /**
177 * Whether the service is reachable from the public internet. Set to
178 * false to only allow access from a VPC ingress connection.
179 * @default true
180 */
181 isPubliclyAccessible?: boolean;
182 /**
183 * IP address type for the public endpoint.
184 * @default "IPV4"
185 */
186 ipAddressType?: "IPV4" | "DUAL_STACK";
187 }
188
189 /**
190 * Observability (tracing) settings for the service.
191 */
192 export interface ServiceObservabilityProps {
193 /**
194 * Whether observability (X-Ray tracing) is enabled for the service.
195 */
196 observabilityEnabled: boolean;
197 /**
198 * ARN of the App Runner observability configuration to use. Required
199 * when `observabilityEnabled` is true.
200 */
201 observabilityConfigurationArn?: string;
202 }
203
204 export interface ServiceProps extends PlatformProps {
205 /**
206 * Name of the service. Must be 4-40 characters. If omitted, a
207 * deterministic physical name is generated. Changing the name replaces
208 * the service.
209 */
210 serviceName?: string;
211 /**
212 * Container image source for the service (low-level form). Required
213 * unless `main` is given. Code-repository (GitHub) sources are not
214 * supported — they require an App Runner Connection whose handshake is
215 * completed manually in the console.
216 */
217 imageRepository?: ServiceImageRepository;
218 /**
219 * Module entrypoint for an Effect-native service (typically
220 * `import.meta.url` from an inline Effect program). Alchemy bundles the
221 * program, builds a container image, pushes it to a managed ECR
222 * repository, and provisions the instance/access IAM roles — mutually
223 * exclusive with a caller-supplied `imageRepository`.
224 */
225 main?: string;
226 /**
227 * Named export to load from `main`.
228 * @default "default"
229 */
230 handler?: string;
231 /**
232 * HTTP port the Effect-native program listens on (App Runner injects it
233 * as `PORT`). Only used with `main`; the low-level form configures
234 * `imageRepository.port` instead.
235 * @default 3000
236 */
237 port?: number;
238 /**
239 * Additional environment variables for the Effect-native container.
240 * Non-string values are JSON-encoded.
241 */
242 env?: Record<string, any>;
243 /**
244 * Bundler configuration for the Effect-native entrypoint. Unused
245 * code is tree-shaken. `effect`, alchemy, and `@distilled.cloud` are
246 * marked pure so unused parts prune more aggressively. List extra
247 * packages with `pure.packages`, or disable with `pure: false`.
248 */
249 build?: Bundle.BundleConfig;
250 /**
251 * Docker image build for the Effect-native form: optional full
252 * `dockerfile`. When omitted, Alchemy generates a Dockerfile for the
253 * bundled `index.mjs`.
254 */
255 docker?: {
256 /**
257 * Base image when Alchemy generates the Dockerfile.
258 * @default public.ecr.aws/docker/library/bun:1
259 */
260 base?: string;
261 /** Full Dockerfile content (replaces generated Dockerfile). */
262 dockerfile?: string;
263 };
264 /**
265 * Whether App Runner automatically deploys new image versions pushed to
266 * the (private ECR only) repository.
267 * @default false
268 */
269 autoDeploymentsEnabled?: boolean;
270 /**
271 * IAM role App Runner assumes to pull from private ECR (must trust
272 * `build.apprunner.amazonaws.com`). Required for
273 * `imageRepositoryType: "ECR"`, forbidden for `ECR_PUBLIC`. For the
274 * Effect-native form (`main`), Alchemy provisions and manages this role
275 * automatically.
276 */
277 accessRoleArn?: string;
278 /**
279 * CPU, memory, and instance role for the running service.
280 */
281 instanceConfiguration?: ServiceInstanceConfiguration;
282 /**
283 * Health check configuration.
284 */
285 healthCheckConfiguration?: ServiceHealthCheckConfiguration;
286 /**
287 * Inbound/outbound network configuration.
288 */
289 networkConfiguration?: ServiceNetworkConfiguration;
290 /**
291 * ARN of an App Runner auto scaling configuration. Defaults to the
292 * account's default configuration.
293 */
294 autoScalingConfigurationArn?: string;
295 /**
296 * Observability (X-Ray tracing) configuration, referencing an
297 * `AppRunner.ObservabilityConfiguration`.
298 */
299 observabilityConfiguration?: ServiceObservabilityProps;
300 /**
301 * Customer-managed KMS key ARN for encrypting stored copies of the
302 * image and configuration. Changing the key replaces the service.
303 * @default AWS-owned key
304 */
305 kmsKeyArn?: string;
306 /**
307 * Keep the CloudWatch log groups App Runner auto-creates for the service
308 * (`/aws/apprunner/{serviceName}/{serviceId}/application` and
309 * `.../service`) when the service is deleted.
310 *
311 * By default they are deleted along with the service — App Runner itself
312 * leaves them behind, so every deploy+destroy cycle would otherwise
313 * strand a pair. Set this when the logs must outlive the service (an
314 * incident post-mortem, a compliance retention window). The kept groups
315 * are inert: their names embed the service id, so no future service ever
316 * writes to them, and nothing but a manual delete (or
317 * `alchemy unsafe nuke`) removes them.
318 *
319 * @default false
320 */
321 retainLogGroups?: boolean;
322 /**
323 * User-defined tags for the service.
324 */
325 tags?: Record<string, string>;
326 }
327
328 export interface Service extends Resource<
329 "AWS.AppRunner.Service",
330 ServiceProps,
331 {
332 /**
333 * Name of the App Runner service.
334 */
335 serviceName: string;
336 /**
337 * ARN of the service.
338 */
339 serviceArn: string;
340 /**
341 * ID of the service.
342 */
343 serviceId: string;
344 /**
345 * Default HTTPS endpoint of the service (`xxxx.awsapprunner.com`).
346 */
347 serviceUrl: string | undefined;
348 /**
349 * Current status of the service (e.g. `RUNNING`, `OPERATION_IN_PROGRESS`).
350 */
351 status: string;
352 /**
353 * The full URI of the container image the service runs (Effect-native
354 * form only).
355 */
356 imageUri: string | undefined;
357 /**
358 * The name of the managed ECR repository holding the built image
359 * (Effect-native form only).
360 */
361 repositoryName: string | undefined;
362 /**
363 * The URI of the managed ECR repository (Effect-native form only).
364 */
365 repositoryUri: string | undefined;
366 /**
367 * The ARN of the managed instance role (Effect-native form only).
368 */
369 instanceRoleArn: string | undefined;
370 /**
371 * The name of the managed instance role (Effect-native form only).
372 */
373 instanceRoleName: string | undefined;
374 /**
375 * The ARN of the managed ECR access role (Effect-native form only).
376 */
377 accessRoleArn: string | undefined;
378 /**
379 * The name of the managed ECR access role (Effect-native form only).
380 */
381 accessRoleName: string | undefined;
382 /**
383 * The content hash of the bundled application code (Effect-native
384 * form only).
385 */
386 codeHash: string | undefined;
387 },
388 {
389 /** Environment variables injected into the service's containers. */
390 env?: Record<string, any>;
391 /** IAM policy statements attached to the managed instance role. */
392 policyStatements?: PolicyStatement[];
393 },
394 Providers
395 > {}
396
397 export type ServiceServices = Credentials | Region | ServerHost | AWSEnvironment;
398
399 export type ServiceShape = Main<ServiceServices>;
400
401 export interface ServiceRuntimeContext extends HostRuntimeContext {
402 readonly Type: "AWS.AppRunner.Service";
403 }
404
405 /**
406 * An AWS App Runner service — the zero-infrastructure way to run a
407 * container behind an HTTPS endpoint: App Runner provisions,
408 * load-balances, scales, and patches the fleet for you. Service creation
409 * and deletion are asynchronous and take several minutes; the provider
410 * waits (bounded) for operations to settle.
411 *
412 * `Service` is a Platform: alongside the low-level container-image form
413 * (`imageRepository`), it supports Effect-native implementations — an
414 * inline Effect HTTP program that Alchemy bundles, containerizes, pushes
415 * to a managed ECR repository, and deploys, provisioning the instance and
416 * ECR access roles automatically. Capability bindings (e.g. DynamoDB
417 * `GetItem`) attach IAM policy statements to the managed instance role.
418 * ### Creating a Service
419 * **Example:** Public ECR Image
420 * ```typescript
421 * const service = yield* AppRunner.Service("Hello", {
422 * imageRepository: {
423 * imageIdentifier: "public.ecr.aws/aws-containers/hello-app-runner:latest",
424 * imageRepositoryType: "ECR_PUBLIC",
425 * port: "8000",
426 * },
427 * instanceConfiguration: { cpu: "256", memory: "512" },
428 * });
429 * // service.serviceUrl -> "xxxxxxxx.us-west-2.awsapprunner.com"
430 * ```
431 *
432 * **Example:** Private ECR Image with Access Role
433 * ```typescript
434 * const service = yield* AppRunner.Service("Api", {
435 * imageRepository: {
436 * imageIdentifier: `${repository.repositoryUri}:latest`,
437 * imageRepositoryType: "ECR",
438 * port: "8080",
439 * runtimeEnvironmentVariables: { NODE_ENV: "production" },
440 * },
441 * accessRoleArn: accessRole.roleArn,
442 * autoDeploymentsEnabled: true,
443 * });
444 * ```
445 *
446 * ### Effect-Native Services
447 * **Example:** Inline Effect HTTP Program
448 * ```typescript
449 * export default class Api extends AppRunner.Service<Api>()(
450 * "Api",
451 * {
452 * main: import.meta.url,
453 * port: 3000,
454 * instanceConfiguration: { cpu: "256", memory: "512" },
455 * },
456 * Effect.gen(function* () {
457 * return {
458 * fetch: Effect.gen(function* () {
459 * const request = yield* HttpServerRequest;
460 * return HttpServerResponse.text("hello from app runner");
461 * }),
462 * };
463 * }),
464 * ) {}
465 * ```
466 *
467 * ### Bundling & Tree-shaking
468 * `main` is bundled with rolldown at deploy time. Unused code is
469 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
470 * pure so unused parts prune more aggressively. Your app is not
471 * marked pure.
472 *
473 * **Example:** Mark additional packages as pure
474 * Only list packages with no top-level side effects.
475 * ```typescript
476 * {
477 * main: import.meta.url,
478 * build: {
479 * pure: { packages: ["my-lib", "@my-scope/*"] },
480 * },
481 * }
482 * ```
483 *
484 * **Example:** Turn it off
485 * ```typescript
486 * {
487 * main: import.meta.url,
488 * build: { pure: false },
489 * }
490 * ```
491 *
492 * ### Scaling and Networking
493 * **Example:** Custom Auto Scaling and VPC Egress
494 * ```typescript
495 * const service = yield* AppRunner.Service("Api", {
496 * imageRepository: {
497 * imageIdentifier: "public.ecr.aws/aws-containers/hello-app-runner:latest",
498 * imageRepositoryType: "ECR_PUBLIC",
499 * port: "8000",
500 * },
501 * autoScalingConfigurationArn: scaling.autoScalingConfigurationArn,
502 * networkConfiguration: {
503 * egressType: "VPC",
504 * vpcConnectorArn: connector.vpcConnectorArn,
505 * },
506 * });
507 * ```
508 *
509 * @resource
510 */
511 export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> =
512 Platform("AWS.AppRunner.Service", {
513 createRuntimeContext: createHostRuntimeContext("AWS.AppRunner.Service") as (
514 id: string,
515 ) => ServiceRuntimeContext,
516 });
517
518 class AppRunnerServiceNotSettled extends Data.TaggedError("AppRunnerServiceNotSettled")<{
519 readonly serviceArn: string;
520 readonly status: string;
521 }> {}
522
523 /**
524 * Case-insensitive status comparison — App Runner returns lowercase
525 * statuses for some resource types despite documenting uppercase.
526 */
527 const statusIs = (status: string | undefined, expected: string): boolean =>
528 status?.toUpperCase() === expected;
529
530 /** Normalize the vCPU-style CPU forms to the numeric wire echo. */
531 const normalizeCpu = (cpu: string): string =>
532 ({
533 "0.25 vCPU": "256",
534 "0.5 vCPU": "512",
535 "1 vCPU": "1024",
536 "2 vCPU": "2048",
537 "4 vCPU": "4096",
538 })[cpu] ?? cpu;
539
540 /** Normalize the GB-style memory forms to the numeric wire echo. */
541 const normalizeMemory = (memory: string): string =>
542 ({
543 "0.5 GB": "512",
544 "1 GB": "1024",
545 "2 GB": "2048",
546 "3 GB": "3072",
547 "4 GB": "4096",
548 "6 GB": "6144",
549 "8 GB": "8192",
550 "10 GB": "10240",
551 "12 GB": "12288",
552 })[memory] ?? memory;
553
554 /** Unwrap distilled's sensitive-string decoding to a plain value. */
555 const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
556 value === undefined || typeof value === "string" ? value : Redacted.value(value);
557
558 const plainRecord = (
559 record: { [key: string]: string | Redacted.Redacted<string> | undefined } | undefined,
560 ): Record<string, string> =>
561 Object.fromEntries(
562 Object.entries(record ?? {}).flatMap(([key, value]) => {
563 const v = plain(value);
564 return v === undefined ? [] : [[key, v]];
565 }),
566 );
567
568 const sameRecord = (a: Record<string, string>, b: Record<string, string>): boolean => {
569 const aKeys = Object.keys(a).sort();
570 const bKeys = Object.keys(b).sort();
571 return aKeys.length === bKeys.length && aKeys.every((k, i) => k === bKeys[i] && a[k] === b[k]);
572 };
573
574 /** Props with the source resolved (either given or built from `main`). */
575 interface ResolvedServiceProps extends ServiceProps {
576 imageRepository: ServiceImageRepository;
577 }
578
579 const toWireSource = (props: ResolvedServiceProps): apprunner.SourceConfiguration => ({
580 ImageRepository: {
581 ImageIdentifier: props.imageRepository.imageIdentifier,
582 ImageRepositoryType: props.imageRepository.imageRepositoryType,
583 ImageConfiguration: {
584 Port: props.imageRepository.port,
585 StartCommand: props.imageRepository.startCommand,
586 RuntimeEnvironmentVariables: props.imageRepository.runtimeEnvironmentVariables,
587 RuntimeEnvironmentSecrets: props.imageRepository.runtimeEnvironmentSecrets,
588 },
589 },
590 AutoDeploymentsEnabled: props.autoDeploymentsEnabled,
591 AuthenticationConfiguration: props.accessRoleArn
592 ? { AccessRoleArn: props.accessRoleArn }
593 : undefined,
594 });
595
596 const toWireInstance = (
597 instance: ServiceInstanceConfiguration | undefined,
598 ): apprunner.InstanceConfiguration | undefined =>
599 instance === undefined
600 ? undefined
601 : {
602 Cpu: instance.cpu,
603 Memory: instance.memory,
604 InstanceRoleArn: instance.instanceRoleArn,
605 };
606
607 const toWireHealthCheck = (
608 healthCheck: ServiceHealthCheckConfiguration | undefined,
609 ): apprunner.HealthCheckConfiguration | undefined =>
610 healthCheck === undefined
611 ? undefined
612 : {
613 Protocol: healthCheck.protocol,
614 Path: healthCheck.path,
615 Interval: toSeconds(healthCheck.interval),
616 Timeout: toSeconds(healthCheck.timeout),
617 HealthyThreshold: healthCheck.healthyThreshold,
618 UnhealthyThreshold: healthCheck.unhealthyThreshold,
619 };
620
621 const toWireNetwork = (
622 network: ServiceNetworkConfiguration | undefined,
623 ): apprunner.NetworkConfiguration | undefined =>
624 network === undefined
625 ? undefined
626 : {
627 EgressConfiguration:
628 network.egressType !== undefined || network.vpcConnectorArn !== undefined
629 ? {
630 EgressType: network.egressType,
631 VpcConnectorArn: network.vpcConnectorArn,
632 }
633 : undefined,
634 IngressConfiguration:
635 network.isPubliclyAccessible !== undefined
636 ? { IsPubliclyAccessible: network.isPubliclyAccessible }
637 : undefined,
638 IpAddressType: network.ipAddressType,
639 };
640
641 const toWireObservability = (
642 observability: ServiceObservabilityProps | undefined,
643 ): apprunner.ServiceObservabilityConfiguration | undefined =>
644 observability === undefined
645 ? undefined
646 : {
647 ObservabilityEnabled: observability.observabilityEnabled,
648 ObservabilityConfigurationArn: observability.observabilityConfigurationArn,
649 };
650
651 /**
652 * True when any user-specified aspect of the source configuration differs
653 * from the observed one. Only fields the user actually specified are
654 * compared — the service fills in defaults that must not trigger
655 * spurious deployments.
656 */
657 const sourceDrifted = (
658 news: ResolvedServiceProps,
659 observed: apprunner.SourceConfiguration | undefined,
660 ): boolean => {
661 const image = observed?.ImageRepository;
662 const config = image?.ImageConfiguration;
663 const desired = news.imageRepository;
664 return (
665 image?.ImageIdentifier !== desired.imageIdentifier ||
666 image?.ImageRepositoryType !== desired.imageRepositoryType ||
667 (desired.port !== undefined && config?.Port !== desired.port) ||
668 (desired.startCommand !== undefined && plain(config?.StartCommand) !== desired.startCommand) ||
669 (desired.runtimeEnvironmentVariables !== undefined &&
670 !sameRecord(
671 plainRecord(config?.RuntimeEnvironmentVariables),
672 desired.runtimeEnvironmentVariables,
673 )) ||
674 (desired.runtimeEnvironmentSecrets !== undefined &&
675 !sameRecord(
676 plainRecord(config?.RuntimeEnvironmentSecrets),
677 desired.runtimeEnvironmentSecrets,
678 )) ||
679 (news.autoDeploymentsEnabled !== undefined &&
680 observed?.AutoDeploymentsEnabled !== news.autoDeploymentsEnabled) ||
681 (news.accessRoleArn !== undefined &&
682 observed?.AuthenticationConfiguration?.AccessRoleArn !== news.accessRoleArn)
683 );
684 };
685
686 const instanceDrifted = (
687 desired: ServiceInstanceConfiguration | undefined,
688 observed: apprunner.InstanceConfiguration | undefined,
689 ): boolean =>
690 desired !== undefined &&
691 ((desired.cpu !== undefined && normalizeCpu(observed?.Cpu ?? "") !== normalizeCpu(desired.cpu)) ||
692 (desired.memory !== undefined &&
693 normalizeMemory(observed?.Memory ?? "") !== normalizeMemory(desired.memory)) ||
694 (desired.instanceRoleArn !== undefined &&
695 observed?.InstanceRoleArn !== desired.instanceRoleArn));
696
697 const healthCheckDrifted = (
698 desired: ServiceHealthCheckConfiguration | undefined,
699 observed: apprunner.HealthCheckConfiguration | undefined,
700 ): boolean =>
701 desired !== undefined &&
702 ((desired.protocol !== undefined && observed?.Protocol !== desired.protocol) ||
703 (desired.path !== undefined && observed?.Path !== desired.path) ||
704 (desired.interval !== undefined && observed?.Interval !== toSeconds(desired.interval)) ||
705 (desired.timeout !== undefined && observed?.Timeout !== toSeconds(desired.timeout)) ||
706 (desired.healthyThreshold !== undefined &&
707 observed?.HealthyThreshold !== desired.healthyThreshold) ||
708 (desired.unhealthyThreshold !== undefined &&
709 observed?.UnhealthyThreshold !== desired.unhealthyThreshold));
710
711 const networkDrifted = (
712 desired: ServiceNetworkConfiguration | undefined,
713 observed: apprunner.NetworkConfiguration | undefined,
714 ): boolean =>
715 desired !== undefined &&
716 ((desired.egressType !== undefined &&
717 observed?.EgressConfiguration?.EgressType !== desired.egressType) ||
718 (desired.vpcConnectorArn !== undefined &&
719 observed?.EgressConfiguration?.VpcConnectorArn !== desired.vpcConnectorArn) ||
720 (desired.isPubliclyAccessible !== undefined &&
721 observed?.IngressConfiguration?.IsPubliclyAccessible !== desired.isPubliclyAccessible) ||
722 (desired.ipAddressType !== undefined && observed?.IpAddressType !== desired.ipAddressType));
723
724 const observabilityDrifted = (
725 desired: ServiceObservabilityProps | undefined,
726 observed: apprunner.ServiceObservabilityConfiguration | undefined,
727 ): boolean =>
728 desired !== undefined &&
729 ((observed?.ObservabilityEnabled ?? false) !== desired.observabilityEnabled ||
730 (desired.observabilityConfigurationArn !== undefined &&
731 // App Runner echoes the resolved (revision-qualified) ARN; compare
732 // on the revision-less name partial so both forms converge.
733 !(observed?.ObservabilityConfigurationArn ?? "").startsWith(
734 desired.observabilityConfigurationArn.split("/").slice(0, 2).join("/"),
735 )));
736
737 /** Attributes only produced by the Effect-native (`main`) form. */
738 interface PlatformAttributes {
739 imageUri: string | undefined;
740 repositoryName: string | undefined;
741 repositoryUri: string | undefined;
742 instanceRoleArn: string | undefined;
743 instanceRoleName: string | undefined;
744 accessRoleArn: string | undefined;
745 accessRoleName: string | undefined;
746 codeHash: string | undefined;
747 }
748
749 const emptyPlatformAttributes: PlatformAttributes = {
750 imageUri: undefined,
751 repositoryName: undefined,
752 repositoryUri: undefined,
753 instanceRoleArn: undefined,
754 instanceRoleName: undefined,
755 accessRoleArn: undefined,
756 accessRoleName: undefined,
757 codeHash: undefined,
758 };
759
760 /**
761 * The two CloudWatch log groups App Runner auto-creates for a service:
762 * `.../application` (the container's stdout/stderr) and `.../service`
763 * (App Runner's own deployment and health-check events).
764 *
765 * Both names embed the AWS-generated service id, so a pair belongs to
766 * exactly one service instance — it can never be shared with, or reused
767 * by, another service.
768 */
769 const logGroupNamesFor = (serviceName: string, serviceId: string) => [
770 `/aws/apprunner/${serviceName}/${serviceId}/application`,
771 `/aws/apprunner/${serviceName}/${serviceId}/service`,
772 ];
773
774 /**
775 * Delete one of a service's auto-created log groups, idempotently.
776 *
777 * `deleteService` does NOT remove them, so without this every
778 * deploy+destroy cycle strands a pair (matching how the Lambda and ECS
779 * providers reap `/aws/lambda/{name}` and their task log group).
780 *
781 * App Runner can flush a final batch of events after the service itself
782 * is gone, silently re-creating a just-deleted group, so the delete is
783 * followed by a bounded observe→delete convergence loop. A group that
784 * never reappears — the common case — costs a single extra describe.
785 * Reaping is auxiliary to an already-completed service deletion, so a
786 * group that survives the budget warns rather than failing the destroy.
787 */
788 const reapLogGroup = Effect.fn(function* (logGroupName: string) {
789 const deleteGroup = logs.deleteLogGroup({ logGroupName }).pipe(
790 Effect.retry({
791 while: (error) =>
792 error._tag === "OperationAbortedException" || error._tag === "ServiceUnavailableException",
793 schedule: Schedule.max([Schedule.exponential("250 millis"), Schedule.recurs(6)]),
794 }),
795 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
796 Effect.timeoutOrElse({
797 duration: "30 seconds",
798 orElse: () => Effect.logWarning(`Timed out deleting App Runner log group ${logGroupName}`),
799 }),
800 );
801
802 // A describe that cannot complete in time is not deletion proof —
803 // assume the group is still present and let the bounded loop converge.
804 const observeGroup = logs.describeLogGroups({ logGroupNamePrefix: logGroupName, limit: 1 }).pipe(
805 Effect.map((response) =>
806 (response.logGroups ?? []).some((group) => group.logGroupName === logGroupName),
807 ),
808 Effect.timeoutOrElse({
809 duration: "15 seconds",
810 orElse: () =>
811 Effect.logWarning(
812 `Timed out observing App Runner log group ${logGroupName} — assuming still present`,
813 ).pipe(Effect.as(true)),
814 }),
815 );
816
817 yield* deleteGroup;
818
819 // Re-reaps at t=0s/5s/…/30s, each attempt idempotent.
820 const stillPresent = yield* Effect.gen(function* () {
821 const present = yield* observeGroup;
822 if (present) yield* deleteGroup;
823 return present;
824 }).pipe(
825 Effect.repeat({
826 schedule: Schedule.spaced("5 seconds"),
827 until: (present) => !present,
828 times: 6,
829 }),
830 );
831
832 if (stillPresent) {
833 yield* Effect.logWarning(`App Runner log group ${logGroupName} kept reappearing after delete`);
834 }
835 });
836
837 export const ServiceProvider = () =>
838 Provider.effect(
839 Service,
840 Effect.gen(function* () {
841 const stack = yield* Stack;
842 const docker = yield* Docker;
843 const { dotAlchemy } = yield* AlchemyContext;
844 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
845
846 const alchemyEnv = {
847 ALCHEMY_STACK_NAME: stack.name,
848 ALCHEMY_STAGE: stack.stage,
849 ALCHEMY_PHASE: "runtime",
850 };
851
852 const toName = (id: string, props: Partial<ServiceProps>) =>
853 props.serviceName
854 ? Effect.succeed(props.serviceName)
855 : createPhysicalName({ id, maxLength: 40 });
856
857 const createRoleName = (id: string, suffix: string) =>
858 createPhysicalName({ id: `${id}-${suffix}`, maxLength: 64 });
859
860 const createRepositoryName = (id: string) =>
861 createPhysicalName({
862 id: `${id}-repo`,
863 maxLength: 256,
864 lowercase: true,
865 });
866
867 /**
868 * Ensure an IAM role trusted by the given App Runner principal exists
869 * (creates on miss, adopts on race when it carries our tags).
870 */
871 const ensureRole = Effect.fn(function* ({
872 id,
873 roleName,
874 principal,
875 managedPolicyArns,
876 }: {
877 id: string;
878 roleName: string;
879 principal: string;
880 managedPolicyArns?: string[];
881 }) {
882 const tags = yield* createInternalTags(id);
883 const role = yield* iam
884 .createRole({
885 RoleName: roleName,
886 AssumeRolePolicyDocument: JSON.stringify({
887 Version: "2012-10-17",
888 Statement: [
889 {
890 Effect: "Allow",
891 Principal: { Service: principal },
892 Action: "sts:AssumeRole",
893 },
894 ],
895 }),
896 Tags: createTagsList(tags),
897 })
898 .pipe(
899 Effect.catchTag("EntityAlreadyExistsException", () =>
900 iam.getRole({ RoleName: roleName }).pipe(
901 Effect.filterOrFail(
902 (existing) => hasTags(tags, existing.Role?.Tags),
903 () =>
904 new ServiceConflict({
905 message: `Role '${roleName}' already exists and is not managed by alchemy`,
906 }),
907 ),
908 ),
909 ),
910 );
911 for (const policyArn of managedPolicyArns ?? []) {
912 yield* iam
913 .attachRolePolicy({ RoleName: roleName, PolicyArn: policyArn })
914 .pipe(Effect.catchTag("LimitExceededException", () => Effect.void));
915 }
916 return role.Role!.Arn!;
917 });
918
919 /** Ensure the managed ECR repository for the built image exists. */
920 const ensureRepository = Effect.fn(function* ({
921 repositoryName,
922 tags,
923 }: {
924 repositoryName: string;
925 tags: Record<string, string>;
926 }) {
927 const created = yield* ecr
928 .createRepository({
929 repositoryName,
930 imageTagMutability: "MUTABLE",
931 imageScanningConfiguration: { scanOnPush: true },
932 tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })),
933 })
934 .pipe(
935 Effect.catchTag("RepositoryAlreadyExistsException", () =>
936 Effect.gen(function* () {
937 const existing = yield* ecr.describeRepositories({
938 repositoryNames: [repositoryName],
939 });
940 return { repository: existing.repositories?.[0] };
941 }),
942 ),
943 );
944 const repository = created.repository;
945 if (!repository?.repositoryUri) {
946 return yield* new ServiceOperationFailed({
947 message: `Failed to resolve ECR repository '${repositoryName}'`,
948 });
949 }
950 return { repositoryUri: repository.repositoryUri };
951 });
952
953 /**
954 * Attach binding-declared IAM policy statements to the managed
955 * instance role and collect binding-declared environment variables.
956 */
957 const attachBindings = Effect.fn(function* ({
958 roleName,
959 policyName,
960 bindings,
961 }: {
962 roleName: string;
963 policyName: string;
964 bindings: ResourceBinding<Service["Binding"]>[];
965 }) {
966 const activeBindings = bindings.filter(
967 (binding: ResourceBinding<Service["Binding"]> & { action?: string }) =>
968 binding.action !== "delete",
969 );
970
971 const env = activeBindings
972 .map((binding) => binding?.data?.env)
973 .reduce((acc, value) => ({ ...acc, ...value }), {});
974
975 const policyStatements = activeBindings.flatMap(
976 (binding) =>
977 binding?.data?.policyStatements?.map((statement) => ({
978 ...statement,
979 Sid: statement.Sid?.replace(/[^A-Za-z0-9]+/gi, ""),
980 })) ?? [],
981 );
982
983 if (policyStatements.length > 0) {
984 yield* iam.putRolePolicy({
985 RoleName: roleName,
986 PolicyName: policyName,
987 PolicyDocument: JSON.stringify({
988 Version: "2012-10-17",
989 Statement: policyStatements,
990 }),
991 });
992 } else {
993 yield* iam
994 .deleteRolePolicy({ RoleName: roleName, PolicyName: policyName })
995 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
996 }
997
998 return env;
999 });
1000
1001 /** Bundle the Effect-native program into container-ready files. */
1002 const bundleProgram = Effect.fn(function* (props: ServiceProps) {
1003 const handler = props.handler ?? "default";
1004 const realMain = yield* resolveMainPath(props.main!);
1005 const cwd = yield* findCwdForBundle(realMain);
1006
1007 const buildBundle = Effect.fn(function* (
1008 entry: string,
1009 plugins?: rolldown.RolldownPluginOption,
1010 ) {
1011 return yield* Bundle.build(
1012 roleHostBundle({
1013 ...props.build?.input,
1014 input: entry,
1015 cwd,
1016 platform: "node",
1017 // The container runs on `bun`; keep `bun`/`bun:*` external (the
1018 // runtime provides them) and resolve the `bun` export condition
1019 // so `@effect/platform-bun` picks its Bun implementations.
1020 external: [
1021 "bun",
1022 "bun:*",
1023 ...((props.build?.input?.external as string[] | undefined) ?? []),
1024 ],
1025 resolve: {
1026 conditionNames: [...Bundle.BUN_CONDITION_NAMES],
1027 ...props.build?.input?.resolve,
1028 },
1029 plugins: [props.build?.input?.plugins, plugins],
1030 }),
1031 {
1032 ...props.build?.output,
1033 format: "esm",
1034 sourcemap: props.build?.output?.sourcemap ?? false,
1035 minify: props.build?.output?.minify ?? false,
1036 entryFileNames: "index.mjs",
1037 },
1038 props.build,
1039 );
1040 });
1041
1042 const bundleOutput = props.isExternal
1043 ? yield* buildBundle(realMain)
1044 : yield* buildBundle(
1045 realMain,
1046 virtualEntryPlugin(
1047 (importPath) => `
1048 import { bootstrap } from "@alchemy.run/aws/Bootstrap/AppRunner";
1049 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
1050
1051 await bootstrap(entrypoint);
1052 `,
1053 ),
1054 );
1055
1056 // Return every emitted file (entry + shared chunks). Dynamic imports
1057 // in the Bun HTTP server / AWS SDK split into chunks; dropping any of
1058 // them crashes the container with `Cannot find module './chunk-X.js'`.
1059 const files = bundleOutput.files.map((file) => ({
1060 path: file.path,
1061 content:
1062 typeof file.content === "string"
1063 ? new TextEncoder().encode(file.content)
1064 : file.content,
1065 }));
1066
1067 return { files, hash: bundleOutput.hash };
1068 });
1069
1070 /** Build + push the container image for the bundled program. */
1071 const buildAndPushImage = Effect.fn(function* ({
1072 id,
1073 repositoryUri,
1074 hash,
1075 files,
1076 props,
1077 port,
1078 }: {
1079 id: string;
1080 repositoryUri: string;
1081 hash: string;
1082 files: { path: string; content: Uint8Array<ArrayBufferLike> }[];
1083 props: ServiceProps;
1084 port: number;
1085 }) {
1086 const realMain = yield* resolveMainPath(props.main!);
1087 const contextDir = yield* getStableContextDir(realMain, dotAlchemy, `${id}-image`);
1088 const imageUri = `${repositoryUri}:${hash}`;
1089
1090 const generatedDockerfile = (() => {
1091 const base = props.docker?.base ?? "public.ecr.aws/docker/library/bun:1";
1092 return [
1093 `FROM ${base}`,
1094 `WORKDIR /app`,
1095 `COPY index.mjs /app/index.mjs`,
1096 // Copy any additional rolldown chunks (`chunk-XXX.js`, ...).
1097 // Non-trivial bundles always emit at least one; minimal bundles
1098 // emit none and the COPY no-ops.
1099 `COPY *.js /app/`,
1100 `ENV PORT=${String(port)}`,
1101 `EXPOSE ${String(port)}`,
1102 `ENTRYPOINT ["bun", "/app/index.mjs"]`,
1103 ].join("\n");
1104 })();
1105
1106 const dockerfile = props.docker?.dockerfile ?? generatedDockerfile;
1107
1108 yield* docker.materialize({
1109 context: contextDir,
1110 dockerfile,
1111 // Entry chunk becomes `index.mjs`; all other chunks keep their
1112 // emitted `*.js` names so the entry's relative imports resolve.
1113 files: files.map((file, index) => ({
1114 path: index === 0 ? "index.mjs" : file.path,
1115 content: file.content,
1116 })),
1117 });
1118 // App Runner only runs x86_64 images — always build linux/amd64
1119 // (cross-built via emulation on ARM64 hosts).
1120 return yield* buildAndPushEcrImage(docker, {
1121 imageUri,
1122 context: contextDir,
1123 platform: "linux/amd64",
1124 });
1125 });
1126
1127 /** Describe a service; a missing or DELETED service reads as absent. */
1128 const readService = Effect.fn(function* (arn: string) {
1129 const response = yield* apprunner
1130 .describeService({ ServiceArn: arn })
1131 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
1132 const service = response?.Service;
1133 return service === undefined || statusIs(service.Status, "DELETED") ? undefined : service;
1134 });
1135
1136 /** Find a live service by name (list has no name filter). */
1137 const findByName = Effect.fn(function* (name: string) {
1138 const summary = yield* apprunner.listServices.pages({}).pipe(
1139 Stream.map((page) => page.ServiceSummaryList ?? []),
1140 Stream.flattenIterable,
1141 Stream.filter(
1142 (s) =>
1143 s.ServiceName === name &&
1144 !statusIs(s.Status, "DELETED") &&
1145 s.ServiceArn !== undefined,
1146 ),
1147 Stream.runHead,
1148 Effect.map(Option.getOrUndefined),
1149 );
1150 if (!summary?.ServiceArn) return undefined;
1151 return yield* readService(summary.ServiceArn);
1152 });
1153
1154 // Create/update/delete are asynchronous; App Runner reports
1155 // OPERATION_IN_PROGRESS while converging. Service provisioning
1156 // typically takes 3-5 minutes; budget ~10 min (60 * 10s).
1157 const waitForSettled = Effect.fn(function* (arn: string) {
1158 return yield* readService(arn).pipe(
1159 Effect.flatMap((service) =>
1160 service !== undefined && statusIs(service.Status, "OPERATION_IN_PROGRESS")
1161 ? Effect.fail(
1162 new AppRunnerServiceNotSettled({
1163 serviceArn: arn,
1164 status: service.Status,
1165 }),
1166 )
1167 : Effect.succeed(service),
1168 ),
1169 Effect.retry({
1170 while: (e) => e instanceof AppRunnerServiceNotSettled,
1171 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]),
1172 }),
1173 );
1174 });
1175
1176 // Deletion is asynchronous too; wait until the service is gone so
1177 // dependencies (auto scaling configurations, VPC connectors) can be
1178 // deleted right after.
1179 const waitUntilGone = Effect.fn(function* (arn: string) {
1180 yield* readService(arn).pipe(
1181 Effect.flatMap(
1182 Effect.fnUntraced(function* (service) {
1183 if (service === undefined) return;
1184 if (statusIs(service.Status, "DELETE_FAILED")) {
1185 return yield* new ServiceOperationFailed({
1186 message: `App Runner service '${arn}' failed to delete (status: DELETE_FAILED)`,
1187 });
1188 }
1189 return yield* new AppRunnerServiceNotSettled({
1190 serviceArn: arn,
1191 status: service.Status,
1192 });
1193 }),
1194 ),
1195 Effect.retry({
1196 while: (e) => e instanceof AppRunnerServiceNotSettled,
1197 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]),
1198 }),
1199 );
1200 });
1201
1202 const toAttrs = (
1203 service: apprunner.Service,
1204 platform: PlatformAttributes,
1205 ): Service["Attributes"] => ({
1206 serviceName: service.ServiceName,
1207 serviceArn: service.ServiceArn,
1208 serviceId: service.ServiceId,
1209 serviceUrl: service.ServiceUrl,
1210 status: service.Status,
1211 ...platform,
1212 });
1213
1214 const platformAttributesOf = (
1215 output: Service["Attributes"] | undefined,
1216 ): PlatformAttributes =>
1217 output === undefined
1218 ? emptyPlatformAttributes
1219 : {
1220 imageUri: output.imageUri,
1221 repositoryName: output.repositoryName,
1222 repositoryUri: output.repositoryUri,
1223 instanceRoleArn: output.instanceRoleArn,
1224 instanceRoleName: output.instanceRoleName,
1225 accessRoleArn: output.accessRoleArn,
1226 accessRoleName: output.accessRoleName,
1227 codeHash: output.codeHash,
1228 };
1229
1230 return {
1231 stables: [
1232 "serviceName",
1233 "serviceArn",
1234 "serviceId",
1235 "repositoryName",
1236 "repositoryUri",
1237 "instanceRoleArn",
1238 "instanceRoleName",
1239 "accessRoleArn",
1240 "accessRoleName",
1241 ],
1242
1243 diff: Effect.fn(function* ({ id, olds, news }) {
1244 if (!isResolved(news)) return undefined;
1245 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
1246 return { action: "replace" } as const;
1247 }
1248 // The encryption key is create-only.
1249 if ((news?.kmsKeyArn ?? undefined) !== (olds?.kmsKeyArn ?? undefined)) {
1250 return { action: "replace" } as const;
1251 }
1252 }),
1253
1254 read: Effect.fn(function* ({ id, olds, output }) {
1255 const service = output?.serviceArn
1256 ? yield* readService(output.serviceArn)
1257 : yield* findByName(yield* toName(id, olds ?? {}));
1258 if (service === undefined) return undefined;
1259 const attrs = toAttrs(service, platformAttributesOf(output));
1260 const tags = yield* readAppRunnerTags(attrs.serviceArn);
1261 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
1262 }),
1263
1264 reconcile: Effect.fn(function* ({ id, news, bindings, output, session }) {
1265 const name = output?.serviceName ?? (yield* toName(id, news));
1266 const internalTags = yield* createInternalTags(id);
1267 const desiredTags = { ...internalTags, ...news.tags };
1268
1269 const activeBindings = (
1270 bindings as (ResourceBinding<Service["Binding"]> & {
1271 action?: string;
1272 })[]
1273 ).filter((binding) => binding.action !== "delete");
1274
1275 // Effect-native form: bundle the program, build + push the image,
1276 // and provision the managed IAM roles + ECR repository, then fall
1277 // through to the same observe/ensure/sync flow with the derived
1278 // source configuration.
1279 let effective: ServiceProps = news;
1280 let platformAttributes = emptyPlatformAttributes;
1281 if (news.main !== undefined) {
1282 const instanceRoleName =
1283 output?.instanceRoleName ?? (yield* createRoleName(id, "instance-role"));
1284 const accessRoleName =
1285 output?.accessRoleName ?? (yield* createRoleName(id, "access-role"));
1286 const policyName = yield* createPhysicalName({
1287 id: `${id}-policy`,
1288 maxLength: 128,
1289 });
1290 const repositoryName = output?.repositoryName ?? (yield* createRepositoryName(id));
1291
1292 // Ensure roles + repository. Each helper is idempotent (creates
1293 // on miss, adopts on race) so the same sequence runs on initial
1294 // create, adoption, or update.
1295 const instanceRoleArn =
1296 output?.instanceRoleArn ??
1297 (yield* ensureRole({
1298 id,
1299 roleName: instanceRoleName,
1300 principal: "tasks.apprunner.amazonaws.com",
1301 }));
1302 const accessRoleArn =
1303 output?.accessRoleArn ??
1304 (yield* ensureRole({
1305 id,
1306 roleName: accessRoleName,
1307 principal: "build.apprunner.amazonaws.com",
1308 managedPolicyArns: [
1309 "arn:aws:iam::aws:policy/service-role/AWSAppRunnerServicePolicyForECRAccess",
1310 ],
1311 }));
1312
1313 const bindingEnv = yield* attachBindings({
1314 roleName: instanceRoleName,
1315 policyName,
1316 bindings,
1317 });
1318
1319 const { repositoryUri } =
1320 output?.repositoryUri && output?.repositoryName === repositoryName
1321 ? { repositoryUri: output.repositoryUri }
1322 : yield* ensureRepository({
1323 repositoryName,
1324 tags: desiredTags,
1325 });
1326
1327 const port = news.port ?? 3000;
1328 const { files, hash } = yield* bundleProgram(news);
1329 const imageUri = yield* buildAndPushImage({
1330 id,
1331 repositoryUri,
1332 hash,
1333 files,
1334 props: news,
1335 port,
1336 });
1337
1338 // App Runner env values must be strings — JSON-encode the rest.
1339 const runtimeEnvironmentVariables = Object.fromEntries(
1340 Object.entries({
1341 ...bindingEnv,
1342 ...alchemyEnv,
1343 ...news.env,
1344 }).map(([key, value]) => [
1345 key,
1346 typeof value === "string" ? value : JSON.stringify(value),
1347 ]),
1348 );
1349
1350 effective = {
1351 ...news,
1352 imageRepository: {
1353 imageIdentifier: imageUri,
1354 imageRepositoryType: "ECR",
1355 port: String(port),
1356 runtimeEnvironmentVariables,
1357 },
1358 accessRoleArn,
1359 autoDeploymentsEnabled: news.autoDeploymentsEnabled ?? false,
1360 instanceConfiguration: {
1361 ...news.instanceConfiguration,
1362 instanceRoleArn,
1363 },
1364 };
1365 platformAttributes = {
1366 imageUri,
1367 repositoryName,
1368 repositoryUri,
1369 instanceRoleArn,
1370 instanceRoleName,
1371 accessRoleArn,
1372 accessRoleName,
1373 codeHash: hash,
1374 };
1375 } else if (
1376 activeBindings.some(
1377 (binding) =>
1378 (binding.data?.policyStatements?.length ?? 0) > 0 ||
1379 Object.keys(binding.data?.env ?? {}).length > 0,
1380 )
1381 ) {
1382 return yield* new ServiceInvalidProps({
1383 message:
1384 `App Runner service '${name}' received capability bindings but uses ` +
1385 "the low-level `imageRepository` form. Bindings attach IAM policies " +
1386 "and environment variables to the Alchemy-managed instance role, " +
1387 "which only exists for Effect-native services (`main`). Either use " +
1388 "the Effect-native form or grant the permissions on your own " +
1389 "`instanceConfiguration.instanceRoleArn`.",
1390 });
1391 }
1392
1393 if (effective.imageRepository === undefined) {
1394 return yield* new ServiceInvalidProps({
1395 message:
1396 `App Runner service '${name}' needs either \`imageRepository\` ` +
1397 "(container-image form) or `main` (Effect-native form)",
1398 });
1399 }
1400 const desired = effective as ResolvedServiceProps;
1401
1402 // 1. Observe — cloud state is authoritative; output is only an
1403 // identifier cache.
1404 let observed = output?.serviceArn ? yield* readService(output.serviceArn) : undefined;
1405 if (observed === undefined) {
1406 observed = yield* findByName(name);
1407 }
1408
1409 // 2. Ensure — create if missing. A freshly-minted access role can
1410 // take a few seconds to become assumable by App Runner
1411 // (InvalidRequestException "Error in assuming access role") —
1412 // retry through that IAM-propagation window (bounded).
1413 if (observed === undefined) {
1414 const created = yield* apprunner
1415 .createService({
1416 ServiceName: name,
1417 SourceConfiguration: toWireSource(desired),
1418 InstanceConfiguration: toWireInstance(desired.instanceConfiguration),
1419 HealthCheckConfiguration: toWireHealthCheck(desired.healthCheckConfiguration),
1420 NetworkConfiguration: toWireNetwork(desired.networkConfiguration),
1421 AutoScalingConfigurationArn: desired.autoScalingConfigurationArn,
1422 ObservabilityConfiguration: toWireObservability(desired.observabilityConfiguration),
1423 EncryptionConfiguration: desired.kmsKeyArn
1424 ? { KmsKey: desired.kmsKeyArn }
1425 : undefined,
1426 Tags: toWireTags(desiredTags),
1427 })
1428 .pipe(
1429 Effect.retry({
1430 while: (e): boolean => e._tag === "InvalidRequestException",
1431 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(12)]),
1432 }),
1433 );
1434 observed = created.Service;
1435 }
1436
1437 // Creation and prior updates run asynchronously — wait (bounded)
1438 // for the service to settle before mutating it.
1439 const settled = yield* waitForSettled(observed.ServiceArn);
1440 if (settled === undefined) {
1441 return yield* new ServiceUnexpectedResponse({
1442 message: `App Runner service '${name}' disappeared while reconciling`,
1443 });
1444 }
1445 observed = settled;
1446 if (statusIs(observed.Status, "CREATE_FAILED")) {
1447 return yield* new ServiceOperationFailed({
1448 message:
1449 `App Runner service '${name}' failed to create (status: CREATE_FAILED). ` +
1450 "Check the service's event and application logs in CloudWatch.",
1451 });
1452 }
1453
1454 // 3. Sync — compare each user-specified aspect against OBSERVED
1455 // state and send a single updateService with only the drifted
1456 // groups.
1457 const update: Omit<apprunner.UpdateServiceRequest, "ServiceArn"> = {};
1458 if (sourceDrifted(desired, observed.SourceConfiguration)) {
1459 update.SourceConfiguration = toWireSource(desired);
1460 }
1461 if (instanceDrifted(desired.instanceConfiguration, observed.InstanceConfiguration)) {
1462 update.InstanceConfiguration = toWireInstance(desired.instanceConfiguration);
1463 }
1464 if (
1465 healthCheckDrifted(desired.healthCheckConfiguration, observed.HealthCheckConfiguration)
1466 ) {
1467 update.HealthCheckConfiguration = toWireHealthCheck(desired.healthCheckConfiguration);
1468 }
1469 if (networkDrifted(desired.networkConfiguration, observed.NetworkConfiguration)) {
1470 update.NetworkConfiguration = toWireNetwork(desired.networkConfiguration);
1471 }
1472 if (
1473 observabilityDrifted(
1474 desired.observabilityConfiguration,
1475 observed.ObservabilityConfiguration,
1476 )
1477 ) {
1478 update.ObservabilityConfiguration = toWireObservability(
1479 desired.observabilityConfiguration,
1480 );
1481 }
1482 if (
1483 desired.autoScalingConfigurationArn !== undefined &&
1484 observed.AutoScalingConfigurationSummary?.AutoScalingConfigurationArn !==
1485 desired.autoScalingConfigurationArn
1486 ) {
1487 update.AutoScalingConfigurationArn = desired.autoScalingConfigurationArn;
1488 }
1489
1490 if (Object.keys(update).length > 0) {
1491 yield* apprunner.updateService({
1492 ServiceArn: observed.ServiceArn,
1493 ...update,
1494 });
1495 const updated = yield* waitForSettled(observed.ServiceArn);
1496 if (updated === undefined) {
1497 return yield* new ServiceUnexpectedResponse({
1498 message: `App Runner service '${name}' disappeared while updating`,
1499 });
1500 }
1501 observed = updated;
1502 }
1503
1504 // 3b. Sync tags — diff against OBSERVED cloud tags.
1505 yield* syncAppRunnerTags(observed.ServiceArn, desiredTags);
1506
1507 // 4. Return fresh attributes.
1508 yield* session.note(name);
1509 return toAttrs(observed, platformAttributes);
1510 }),
1511
1512 delete: Effect.fn(function* ({ olds, output, force }) {
1513 // A service mid-operation rejects deletion with
1514 // InvalidStateException — wait (bounded) for it to settle first.
1515 const observed = yield* waitForSettled(output.serviceArn);
1516 if (observed !== undefined) {
1517 yield* apprunner.deleteService({ ServiceArn: output.serviceArn }).pipe(
1518 Effect.catchTags({
1519 ResourceNotFoundException: () => Effect.void,
1520 // Already deleting — deletion is in progress.
1521 InvalidStateException: () => Effect.void,
1522 }),
1523 );
1524 yield* waitUntilGone(output.serviceArn);
1525 }
1526
1527 // Effect-native form: also clean up the managed ECR repository and
1528 // IAM roles so destroying the service leaves zero leftovers.
1529 if (output.repositoryName !== undefined) {
1530 yield* ecr
1531 .deleteRepository({
1532 repositoryName: output.repositoryName,
1533 force: true,
1534 })
1535 .pipe(Effect.catchTag("RepositoryNotFoundException", () => Effect.void));
1536 }
1537 for (const roleName of [output.instanceRoleName, output.accessRoleName]) {
1538 if (roleName === undefined) continue;
1539 yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe(
1540 Stream.mapEffect((policyName) =>
1541 iam
1542 .deleteRolePolicy({
1543 RoleName: roleName,
1544 PolicyName: policyName,
1545 })
1546 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
1547 ),
1548 Stream.runDrain,
1549 // The role may already be gone (delete re-run / race) —
1550 // treat a missing role as "no policies" so delete is
1551 // idempotent.
1552 Effect.catchTag("NoSuchEntityException", () => Effect.void),
1553 );
1554 yield* iam.listAttachedRolePolicies.items({ RoleName: roleName }).pipe(
1555 Stream.mapEffect((policy) =>
1556 iam
1557 .detachRolePolicy({
1558 RoleName: roleName,
1559 PolicyArn: policy.PolicyArn!,
1560 })
1561 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
1562 ),
1563 Stream.runDrain,
1564 Effect.catchTag("NoSuchEntityException", () => Effect.void),
1565 );
1566 yield* iam
1567 .deleteRole({ RoleName: roleName })
1568 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
1569 }
1570
1571 // Last, because the reap can sit through App Runner's final log
1572 // flush: an interruption during that window must not strand the
1573 // repository or the roles, which cost money and block re-creates.
1574 //
1575 // `retainLogGroups` keeps them; account-wide teardown (`force`)
1576 // overrides that opt-out, since nuke's contract is to leave
1577 // nothing behind. Nuke also enumerates from the cloud, so `olds`
1578 // carries Attributes rather than Props there and the flag reads
1579 // as unset anyway.
1580 if (!olds.retainLogGroups || force) {
1581 for (const logGroupName of logGroupNamesFor(output.serviceName, output.serviceId)) {
1582 yield* reapLogGroup(logGroupName);
1583 }
1584 }
1585 }),
1586
1587 list: () =>
1588 apprunner.listServices.pages({}).pipe(
1589 Stream.runCollect,
1590 Effect.map((chunk) =>
1591 Array.from(chunk)
1592 .flatMap((page) => page.ServiceSummaryList ?? [])
1593 .flatMap((s) =>
1594 s.Status !== undefined &&
1595 !statusIs(s.Status, "DELETED") &&
1596 s.ServiceName !== undefined &&
1597 s.ServiceArn !== undefined &&
1598 s.ServiceId !== undefined
1599 ? [
1600 {
1601 serviceName: s.ServiceName,
1602 serviceArn: s.ServiceArn,
1603 serviceId: s.ServiceId,
1604 serviceUrl: s.ServiceUrl,
1605 status: s.Status,
1606 ...emptyPlatformAttributes,
1607 },
1608 ]
1609 : [],
1610 ),
1611 ),
1612 ),
1613 };
1614 }),
1615 );