The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ec2 from "@distilled.cloud/aws/ec2"; |
| 2 | import * as ecs from "@distilled.cloud/aws/ecs"; |
| 3 | import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2"; |
| 4 | import * as iam from "@distilled.cloud/aws/iam"; |
| 5 | import type { Region } from "@distilled.cloud/aws/Region"; |
| 6 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 7 | import type { DnsConfig } from "alchemy/DNS/Adapter"; |
| 8 | import * as Namespace from "alchemy/Namespace"; |
| 9 | import * as Output from "alchemy/Output"; |
| 10 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 11 | import { Platform, type Main, type PlatformProps } from "alchemy/Platform"; |
| 12 | import * as Provider from "alchemy/Provider"; |
| 13 | import { Resource } from "alchemy/Resource"; |
| 14 | import type { HostRuntimeContext, ServerHost } from "alchemy/Runtime/Process"; |
| 15 | import { Stack } from "alchemy/Stack"; |
| 16 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 17 | import { toMillis, toWireSeconds } from "alchemy/Util/Duration"; |
| 18 | import * as Data from "effect/Data"; |
| 19 | import type * as Duration from "effect/Duration"; |
| 20 | import * as Effect from "effect/Effect"; |
| 21 | import type { HttpClient } from "effect/http/HttpClient"; |
| 22 | import * as Option from "effect/Option"; |
| 23 | import * as Schedule from "effect/Schedule"; |
| 24 | import * as Stream from "effect/Stream"; |
| 25 | import { ScalableTarget } from "../ApplicationAutoScaling/ScalableTarget.ts"; |
| 26 | import { ScalingPolicy } from "../ApplicationAutoScaling/ScalingPolicy.ts"; |
| 27 | import { Service as CloudMapService } from "../CloudMap/Service.ts"; |
| 28 | import type { Credentials } from "../Credentials.ts"; |
| 29 | import { domainCertificate, isRoute53Dns, resolveDomainDns } from "../CustomDomain.ts"; |
| 30 | import { |
| 31 | SecurityGroup, |
| 32 | type SecurityGroupId, |
| 33 | type SecurityGroupRuleData, |
| 34 | } from "../EC2/SecurityGroup.ts"; |
| 35 | import type { SubnetId } from "../EC2/Subnet.ts"; |
| 36 | import type { VpcId } from "../EC2/Vpc.ts"; |
| 37 | import { |
| 38 | makeBunBootstrap, |
| 39 | makeImageSource, |
| 40 | type BundledImageSource, |
| 41 | type DockerfileImageSource, |
| 42 | type ImageSourceLike, |
| 43 | type RegistryImageSource, |
| 44 | } from "../ECR/ImageSource.ts"; |
| 45 | import type { ListenerAction, ListenerRuleCondition } from "../ELBv2/common.ts"; |
| 46 | import { Listener } from "../ELBv2/Listener.ts"; |
| 47 | import { ListenerRule } from "../ELBv2/ListenerRule.ts"; |
| 48 | import { LoadBalancer } from "../ELBv2/LoadBalancer.ts"; |
| 49 | import { TargetGroup, type TargetGroupArn } from "../ELBv2/TargetGroup.ts"; |
| 50 | import { AWSEnvironment, type AccountID } from "../Environment.ts"; |
| 51 | import { plainJson } from "../internal/Observe.ts"; |
| 52 | import { syncLogGroupRetention, type LogRetentionConfig } from "../Logs/LogRetention.ts"; |
| 53 | import type { Providers } from "../Providers.ts"; |
| 54 | import type { RegionID } from "../Region.ts"; |
| 55 | import { findPublicHostedZoneId } from "../Route53/HostedZoneLookup.ts"; |
| 56 | import type { ClusterArn } from "./Cluster.ts"; |
| 57 | import { |
| 58 | attachTaskBindings, |
| 59 | createContainerRuntimeContext, |
| 60 | createTaskRoleIfNotExists, |
| 61 | deleteTaskDefinitionInfrastructure, |
| 62 | ensureTaskExecutionRole, |
| 63 | ensureTaskLogGroup, |
| 64 | reapSupersededTaskDefinitionRevision, |
| 65 | registerTaskDefinitionRevision, |
| 66 | syncEnvironmentFilesPolicy, |
| 67 | syncTaskDefinitionTags, |
| 68 | taskImagePlatform, |
| 69 | type TaskBindingContract, |
| 70 | type TaskDefinitionConfig, |
| 71 | } from "./Task.ts"; |
| 72 | |
| 73 | export type ServiceName = string; |
| 74 | export type ServiceArn = `arn:aws:ecs:${RegionID}:${AccountID}:service/${string}/${ServiceName}`; |
| 75 | |
| 76 | export const isService = (value: any): value is Service => |
| 77 | typeof value === "object" && |
| 78 | value !== null && |
| 79 | "Type" in value && |
| 80 | value.Type === "AWS.ECS.Service"; |
| 81 | |
| 82 | // ─────────────────────────────────────────────────────────────────────────── |
| 83 | // Managed load balancer (owned + shared) — types |
| 84 | // ─────────────────────────────────────────────────────────────────────────── |
| 85 | |
| 86 | /** ALB (layer-7) listener protocols. */ |
| 87 | export type ServiceApplicationProtocol = "http" | "https"; |
| 88 | |
| 89 | /** NLB (layer-4) listener protocols. */ |
| 90 | export type ServiceNetworkProtocol = "tcp" | "udp" | "tcp_udp" | "tls"; |
| 91 | |
| 92 | /** |
| 93 | * Listener protocols supported by managed service ingress. `http`/`https` |
| 94 | * compose an Application Load Balancer; `tcp`/`udp`/`tcp_udp`/`tls` compose a |
| 95 | * Network Load Balancer. Mixing the two families in one service is a typed |
| 96 | * error ({@link MixedLoadBalancerProtocols}). |
| 97 | */ |
| 98 | export type ServiceListenerProtocol = ServiceApplicationProtocol | ServiceNetworkProtocol; |
| 99 | |
| 100 | const NETWORK_PROTOCOLS: ReadonlySet<string> = new Set(["tcp", "udp", "tcp_udp", "tls"]); |
| 101 | |
| 102 | /** A `"80/http"`-style port/protocol spec. */ |
| 103 | export type ServiceListenSpec = `${number}/${ServiceListenerProtocol}`; |
| 104 | |
| 105 | /** |
| 106 | * A routing rule for the service's managed load balancer. Conditions are FLAT |
| 107 | * on the rule (no `conditions: {}` wrapper) and are AND-ed together; a rule |
| 108 | * with no conditions matches every request (`path: "/*"` on a shared |
| 109 | * listener, or becomes the owned listener's default action). |
| 110 | */ |
| 111 | export interface ServiceLoadBalancerRule { |
| 112 | /** |
| 113 | * Where the rule listens. A `"80/http"`-style string means the service OWNS |
| 114 | * the listener (and its ALB); an `ELBv2.Listener` reference means the rule |
| 115 | * attaches to that existing (shared) listener. Omitting it falls back to |
| 116 | * the config-level `listener` (shared) or the service's default owned |
| 117 | * listener. Mixing owned strings and shared references within one service |
| 118 | * is a typed error ({@link MixedListenerOwnership}). |
| 119 | */ |
| 120 | listen?: ServiceListenSpec | Listener; |
| 121 | /** |
| 122 | * Forward matched requests to the container at this port/protocol. A target |
| 123 | * group is created per distinct `forward` + `container` pair. |
| 124 | * @default the main container's port |
| 125 | */ |
| 126 | forward?: ServiceListenSpec; |
| 127 | /** |
| 128 | * Redirect matched requests (HTTP 301) to this port/protocol. Mutually |
| 129 | * exclusive with {@link forward}. |
| 130 | */ |
| 131 | redirect?: ServiceListenSpec; |
| 132 | /** |
| 133 | * Name of the container receiving traffic — the main container by default, |
| 134 | * or a sidecar's container name. |
| 135 | */ |
| 136 | container?: string; |
| 137 | /** Match on the request path (`*` and `?` wildcards). */ |
| 138 | path?: string | string[]; |
| 139 | /** Match on the `Host` header (`*` and `?` wildcards). */ |
| 140 | host?: string | string[]; |
| 141 | /** Match on a named HTTP header. */ |
| 142 | header?: { name: string; values: string[] }; |
| 143 | /** Match on query-string key/value pairs. */ |
| 144 | query?: { key?: string; value: string }[]; |
| 145 | /** |
| 146 | * The rule's evaluation priority (1–50000, lower first). When omitted, a |
| 147 | * deterministic priority is derived by hashing the rule's namespaced |
| 148 | * logical id — stable across deploys and distinct across services. On a |
| 149 | * live collision the deploy fails with a typed |
| 150 | * `ListenerRulePriorityInUse` error naming the priority; set an explicit |
| 151 | * `priority` to resolve it (the engine never probes for free slots). |
| 152 | */ |
| 153 | priority?: number; |
| 154 | } |
| 155 | |
| 156 | /** Object form of the {@link ServiceLoadBalancerConfig.domain} prop. */ |
| 157 | export interface ServiceDomainConfig { |
| 158 | /** Domain name pointed at the owned load balancer, e.g. `api.example.com`. */ |
| 159 | name: string; |
| 160 | /** |
| 161 | * Additional domain names aliased to the load balancer. Each alias gets |
| 162 | * its own Route 53 alias records and (when the certificate is composed) a |
| 163 | * subject alternative name on the ACM certificate. |
| 164 | */ |
| 165 | aliases?: string[]; |
| 166 | /** |
| 167 | * ARN of an existing ACM certificate (in the service's region) for the |
| 168 | * HTTPS/TLS listener. When omitted, a DNS-validated `AWS.ACM.Certificate` |
| 169 | * is composed in the matching Route 53 hosted zone (or through |
| 170 | * {@link dns}). |
| 171 | */ |
| 172 | cert?: string; |
| 173 | /** |
| 174 | * DNS host for the certificate validation and alias records (see |
| 175 | * [DNS Adapters](/infrastructure-as-code/dns-adapters)). Omitted: Route |
| 176 | * 53 (a matching public hosted zone must exist; alias `A` + `AAAA` |
| 177 | * records). Pass `Cloudflare.DNS.Adapter()` or `Hetzner.DNS.Adapter()` |
| 178 | * for a domain whose DNS lives there — each name gets a `CNAME` to the |
| 179 | * load balancer and the certificate is validated through that host. |
| 180 | */ |
| 181 | dns?: DnsConfig; |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * Per-target-group health-check overrides, keyed by the target's |
| 186 | * `"{port}/{protocol}"` spec (see {@link ServiceLoadBalancerConfig.health}). |
| 187 | */ |
| 188 | export interface ServiceTargetHealthCheck { |
| 189 | /** Health-check path (HTTP/HTTPS checks). */ |
| 190 | path?: string; |
| 191 | /** Approximate interval between checks, e.g. `"15 seconds"`. */ |
| 192 | interval?: Duration.Input; |
| 193 | /** Time to wait for a response, e.g. `"5 seconds"`. */ |
| 194 | timeout?: Duration.Input; |
| 195 | /** Consecutive successes before a target is healthy. */ |
| 196 | healthyThreshold?: number; |
| 197 | /** Consecutive failures before a target is unhealthy. */ |
| 198 | unhealthyThreshold?: number; |
| 199 | /** HTTP codes counted as healthy, e.g. `"200-299"`. */ |
| 200 | successCodes?: string; |
| 201 | } |
| 202 | |
| 203 | /** Object form of the {@link ServicePropsBase.loadBalancer} prop. */ |
| 204 | export interface ServiceLoadBalancerConfig { |
| 205 | /** |
| 206 | * Default (shared) listener for rules that omit `listen`. Referencing an |
| 207 | * `ELBv2.Listener` means the service only creates target groups and |
| 208 | * listener rules — the ALB and listener belong to whoever composed them. |
| 209 | */ |
| 210 | listener?: Listener; |
| 211 | /** Routing rules. Defaults to a single catch-all (`path: "/*"`) rule when a `listener` is referenced. */ |
| 212 | rules?: ServiceLoadBalancerRule[]; |
| 213 | /** |
| 214 | * Owned-only: whether the composed ALB is internet-facing (`true`, the |
| 215 | * default) or internal (`false`). A typed error on shared listeners. |
| 216 | */ |
| 217 | public?: boolean; |
| 218 | /** |
| 219 | * Owned-only: point a custom domain at the composed load balancer. |
| 220 | * |
| 221 | * By default a matching Route 53 hosted zone must exist (looked up by |
| 222 | * walking the domain's labels) and alias A + AAAA records are composed for |
| 223 | * the domain and every alias; set {@link ServiceDomainConfig.dns} to |
| 224 | * `Cloudflare.DNS.Adapter()` for a domain whose DNS lives in Cloudflare. |
| 225 | * Unless {@link ServiceDomainConfig.cert} supplies an existing certificate |
| 226 | * ARN, a DNS-validated `AWS.ACM.Certificate` is composed in the service's |
| 227 | * region and attached to the HTTPS listener (the default listener becomes |
| 228 | * `443/https`). The service `url` prefers |
| 229 | * the domain. |
| 230 | */ |
| 231 | domain?: string | ServiceDomainConfig; |
| 232 | /** |
| 233 | * Per-target-group health-check overrides, keyed by the target's |
| 234 | * `"{port}/{protocol}"` spec — the rule's `forward` spec, or |
| 235 | * `"{containerPort}/http"` (`/tcp` for network load balancers) for the |
| 236 | * default target group. Overrides the fast-converge defaults |
| 237 | * (10s interval / 2 healthy / 2 unhealthy). A key matching no target |
| 238 | * group is a typed error ({@link ServiceHealthTargetNotFound}). |
| 239 | */ |
| 240 | health?: Record<string, ServiceTargetHealthCheck>; |
| 241 | } |
| 242 | |
| 243 | /** |
| 244 | * @internal Resolved managed-ingress wiring computed by the Service factory's |
| 245 | * composition step — never set by hand. Carries the composed (or shared) |
| 246 | * ELBv2 child-resource outputs into the core service provider. |
| 247 | */ |
| 248 | export interface ServiceManagedIngress { |
| 249 | /** Whether the service owns its ALB or shares a foreign listener. */ |
| 250 | kind: "owned" | "shared"; |
| 251 | /** ARN of the (owned or shared) load balancer, for URL derivation. */ |
| 252 | loadBalancerArn?: string; |
| 253 | /** ARN of the primary listener. */ |
| 254 | listenerArn?: string; |
| 255 | /** Port of the primary listener. */ |
| 256 | listenerPort?: number; |
| 257 | /** Protocol of the primary listener (`HTTP` / `HTTPS`). */ |
| 258 | listenerProtocol?: string; |
| 259 | /** Id of the composed managed security group, when no `securityGroups` were supplied. */ |
| 260 | securityGroupId?: string; |
| 261 | /** Custom domain pointed at the owned load balancer (URL derivation prefers it). */ |
| 262 | domain?: string; |
| 263 | /** Target groups to wire into the ECS service definition. */ |
| 264 | targets: { |
| 265 | /** ARN of the composed target group. */ |
| 266 | targetGroupArn: string; |
| 267 | /** Container port receiving traffic. Defaults to the main container's port. */ |
| 268 | containerPort?: number; |
| 269 | /** Container name receiving traffic. Defaults to the main container. */ |
| 270 | container?: string; |
| 271 | }[]; |
| 272 | } |
| 273 | |
| 274 | /** Owned `"80/http"` listen strings mixed with shared `ELBv2.Listener` references in one service. */ |
| 275 | export class MixedListenerOwnership extends Data.TaggedError("MixedListenerOwnership")<{ |
| 276 | readonly serviceId: string; |
| 277 | readonly message: string; |
| 278 | }> {} |
| 279 | |
| 280 | /** A rule declared both `forward` and `redirect` (mutually exclusive). */ |
| 281 | export class ServiceRuleActionConflict extends Data.TaggedError("ServiceRuleActionConflict")<{ |
| 282 | readonly serviceId: string; |
| 283 | readonly ruleIndex: number; |
| 284 | readonly message: string; |
| 285 | }> {} |
| 286 | |
| 287 | /** A `listen`/`forward`/`redirect` spec used a protocol outside the supported set. */ |
| 288 | export class UnsupportedListenerProtocol extends Data.TaggedError("UnsupportedListenerProtocol")<{ |
| 289 | readonly serviceId: string; |
| 290 | readonly spec: string; |
| 291 | readonly message: string; |
| 292 | }> {} |
| 293 | |
| 294 | /** An owned `https` listener was requested without a `certificateArn`. */ |
| 295 | export class MissingListenerCertificate extends Data.TaggedError("MissingListenerCertificate")<{ |
| 296 | readonly serviceId: string; |
| 297 | readonly spec: string; |
| 298 | readonly message: string; |
| 299 | }> {} |
| 300 | |
| 301 | /** An owned-only option (e.g. `public`) was set while sharing a foreign listener. */ |
| 302 | export class OwnedOnlyLoadBalancerOption extends Data.TaggedError("OwnedOnlyLoadBalancerOption")<{ |
| 303 | readonly serviceId: string; |
| 304 | readonly option: string; |
| 305 | readonly message: string; |
| 306 | }> {} |
| 307 | |
| 308 | /** A rule has neither its own `listen` nor a config-level default `listener`. */ |
| 309 | export class MissingRuleListener extends Data.TaggedError("MissingRuleListener")<{ |
| 310 | readonly serviceId: string; |
| 311 | readonly ruleIndex: number; |
| 312 | readonly message: string; |
| 313 | }> {} |
| 314 | |
| 315 | /** Application (`http`/`https`) and network (`tcp`/`udp`/`tls`/`tcp_udp`) protocols mixed in one service. */ |
| 316 | export class MixedLoadBalancerProtocols extends Data.TaggedError("MixedLoadBalancerProtocols")<{ |
| 317 | readonly serviceId: string; |
| 318 | readonly message: string; |
| 319 | }> {} |
| 320 | |
| 321 | /** A network (NLB) rule used a feature NLB listeners don't support (conditions, `redirect`, shared listeners, or a missing/duplicate `listen`). */ |
| 322 | export class NetworkListenerRuleUnsupported extends Data.TaggedError( |
| 323 | "NetworkListenerRuleUnsupported", |
| 324 | )<{ |
| 325 | readonly serviceId: string; |
| 326 | readonly ruleIndex: number; |
| 327 | readonly message: string; |
| 328 | }> {} |
| 329 | |
| 330 | /** No public Route 53 hosted zone matches the requested `domain`. */ |
| 331 | export class ServiceHostedZoneNotFound extends Data.TaggedError("ServiceHostedZoneNotFound")<{ |
| 332 | readonly serviceId: string; |
| 333 | readonly domainName: string; |
| 334 | readonly message: string; |
| 335 | }> {} |
| 336 | |
| 337 | /** A `health` key matched none of the service's composed target groups. */ |
| 338 | export class ServiceHealthTargetNotFound extends Data.TaggedError("ServiceHealthTargetNotFound")<{ |
| 339 | readonly serviceId: string; |
| 340 | readonly key: string; |
| 341 | readonly message: string; |
| 342 | }> {} |
| 343 | |
| 344 | /** `scaling.requestCount` needs a managed (owned or shared) target group to track. */ |
| 345 | export class RequestCountScalingRequiresLoadBalancer extends Data.TaggedError( |
| 346 | "RequestCountScalingRequiresLoadBalancer", |
| 347 | )<{ |
| 348 | readonly serviceId: string; |
| 349 | readonly message: string; |
| 350 | }> {} |
| 351 | |
| 352 | /** An ECS service did not converge to the requested deployment before timeout. */ |
| 353 | export class ServiceDidNotStabilize extends Data.TaggedError("ServiceDidNotStabilize")<{ |
| 354 | readonly clusterArn: string; |
| 355 | readonly serviceName: string; |
| 356 | readonly expectedTaskDefinitionArn: string | undefined; |
| 357 | readonly status: string | undefined; |
| 358 | readonly desiredCount: number | undefined; |
| 359 | readonly runningCount: number | undefined; |
| 360 | readonly pendingCount: number | undefined; |
| 361 | readonly deploymentCount: number; |
| 362 | readonly unhealthyTargetCount: number; |
| 363 | readonly message: string; |
| 364 | }> {} |
| 365 | |
| 366 | /** |
| 367 | * Derive a deterministic listener-rule priority (1–50000) from the rule's |
| 368 | * namespaced logical id (FNV-1a 32-bit). Stable across deploys for the same |
| 369 | * id and distinct for distinct ids; on a live `PriorityInUse` collision the |
| 370 | * deploy fails with a typed error rather than probing for a free slot. |
| 371 | */ |
| 372 | export const deriveRulePriority = (namespacedLogicalId: string): number => { |
| 373 | let hash = 0x811c9dc5; |
| 374 | for (let i = 0; i < namespacedLogicalId.length; i++) { |
| 375 | hash ^= namespacedLogicalId.charCodeAt(i); |
| 376 | hash = Math.imul(hash, 0x01000193) >>> 0; |
| 377 | } |
| 378 | return (hash % 50000) + 1; |
| 379 | }; |
| 380 | |
| 381 | /** |
| 382 | * Autoscaling configuration for the service's desired count. Composes an |
| 383 | * `AWS.ApplicationAutoScaling.ScalableTarget` plus one target-tracking |
| 384 | * `ScalingPolicy` per declared metric under the service's namespace. |
| 385 | */ |
| 386 | export interface ServiceScalingConfig { |
| 387 | /** |
| 388 | * Minimum number of running tasks Application Auto Scaling may scale in to. |
| 389 | * @default 1 |
| 390 | */ |
| 391 | min?: number; |
| 392 | /** |
| 393 | * Maximum number of running tasks Application Auto Scaling may scale out to. |
| 394 | * @default `min` |
| 395 | */ |
| 396 | max?: number; |
| 397 | /** Target average CPU utilization (percent) to track. */ |
| 398 | cpuUtilization?: number; |
| 399 | /** Target average memory utilization (percent) to track. */ |
| 400 | memoryUtilization?: number; |
| 401 | /** |
| 402 | * Target `ALBRequestCountPerTarget` to track. Requires a managed load |
| 403 | * balancer target group ({@link ServicePropsBase.loadBalancer}) — a typed |
| 404 | * error ({@link RequestCountScalingRequiresLoadBalancer}) otherwise. |
| 405 | */ |
| 406 | requestCount?: number; |
| 407 | /** Cooldown after a scale-in activity, e.g. `"5 minutes"`. */ |
| 408 | scaleInCooldown?: Duration.Input; |
| 409 | /** Cooldown after a scale-out activity, e.g. `"1 minute"`. */ |
| 410 | scaleOutCooldown?: Duration.Input; |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * Fargate capacity split for the service. `"spot"` runs everything on |
| 415 | * `FARGATE_SPOT`; the object form weights on-demand (`fargate`) against |
| 416 | * `spot` capacity. Normalized into |
| 417 | * {@link ServicePropsBase.capacityProviderStrategy}. The cluster must have |
| 418 | * the `FARGATE` / `FARGATE_SPOT` capacity providers associated (see |
| 419 | * `AWS.ECS.Cluster`'s `capacityProviders` prop). |
| 420 | */ |
| 421 | export type ServiceCapacityConfig = |
| 422 | | "spot" |
| 423 | | { |
| 424 | /** On-demand Fargate share. */ |
| 425 | fargate?: { |
| 426 | /** Baseline task count placed on this provider before weights apply. */ |
| 427 | base?: number; |
| 428 | /** Relative share of tasks placed on this provider. */ |
| 429 | weight: number; |
| 430 | }; |
| 431 | /** Fargate Spot share. */ |
| 432 | spot?: { |
| 433 | /** Baseline task count placed on this provider before weights apply. */ |
| 434 | base?: number; |
| 435 | /** Relative share of tasks placed on this provider. */ |
| 436 | weight: number; |
| 437 | }; |
| 438 | }; |
| 439 | |
| 440 | /** |
| 441 | * Cloud Map service-discovery registration. Composes an |
| 442 | * `AWS.CloudMap.Service` in the given namespace and wires it into the ECS |
| 443 | * service's `serviceRegistries`. |
| 444 | */ |
| 445 | export interface ServiceRegistryConfig { |
| 446 | /** |
| 447 | * The Cloud Map namespace to register in — an |
| 448 | * `AWS.CloudMap.PrivateDnsNamespace` or `HttpNamespace` (anything with a |
| 449 | * `namespaceId`). |
| 450 | */ |
| 451 | namespace: { namespaceId: string }; |
| 452 | /** |
| 453 | * SRV port to publish. When set, the composed Cloud Map service uses SRV |
| 454 | * records; otherwise A records (DNS namespaces) or API-only discovery |
| 455 | * (HTTP namespaces). |
| 456 | */ |
| 457 | port?: number; |
| 458 | } |
| 459 | |
| 460 | /** Container-level health check (Docker `HEALTHCHECK` shape) for the primary container. */ |
| 461 | export interface ServiceContainerHealthCheck { |
| 462 | /** |
| 463 | * The check command, e.g. |
| 464 | * `["CMD-SHELL", "curl -f http://localhost/ || exit 1"]`. |
| 465 | */ |
| 466 | command: string[]; |
| 467 | /** Seconds-granularity period between checks, e.g. `"30 seconds"`. */ |
| 468 | interval?: Duration.Input; |
| 469 | /** Time to wait for a check before counting it failed, e.g. `"5 seconds"`. */ |
| 470 | timeout?: Duration.Input; |
| 471 | /** Consecutive failures before the container is unhealthy. */ |
| 472 | retries?: number; |
| 473 | /** Grace period before failed checks count, e.g. `"10 seconds"`. */ |
| 474 | startPeriod?: Duration.Input; |
| 475 | } |
| 476 | |
| 477 | /** Retention policy for the service's auto-created CloudWatch log group. */ |
| 478 | export type ServiceLoggingConfig = LogRetentionConfig; |
| 479 | |
| 480 | /** EFS volume sugar for {@link ImageOwningServicePropsBase.volumes}. */ |
| 481 | export interface ServiceEfsVolume { |
| 482 | /** |
| 483 | * The EFS file system to mount — an `AWS.EFS.FileSystem` (anything with a |
| 484 | * `fileSystemId`), or `{ fileSystem, accessPoint }` to mount through an |
| 485 | * `AWS.EFS.AccessPoint`. Transit encryption is always enabled. |
| 486 | */ |
| 487 | efs: |
| 488 | | { fileSystemId: string } |
| 489 | | { |
| 490 | /** The EFS file system. */ |
| 491 | fileSystem: { fileSystemId: string }; |
| 492 | /** Optional access point to mount through. */ |
| 493 | accessPoint?: { accessPointId: string }; |
| 494 | }; |
| 495 | /** Container path to mount the file system at, e.g. `"/mnt/data"`. */ |
| 496 | path: string; |
| 497 | } |
| 498 | |
| 499 | export interface ServicePropsBase extends PlatformProps { |
| 500 | /** |
| 501 | * ECS cluster that will own the service. |
| 502 | */ |
| 503 | cluster: ClusterArn | { clusterArn: ClusterArn }; |
| 504 | |
| 505 | /** |
| 506 | * Name of the ECS service. |
| 507 | * If omitted, a unique name will be generated. |
| 508 | * |
| 509 | * Changing this replaces the service (delete-first). |
| 510 | */ |
| 511 | serviceName?: string; |
| 512 | |
| 513 | /** |
| 514 | * Desired number of running tasks. Updated in place. |
| 515 | * @default 1 |
| 516 | */ |
| 517 | desiredCount?: number; |
| 518 | |
| 519 | /** |
| 520 | * VPC that hosts the service networking and optional public ingress. |
| 521 | * When omitted (together with {@link subnets}), the account's default VPC |
| 522 | * is used. |
| 523 | */ |
| 524 | vpcId?: string; |
| 525 | |
| 526 | /** |
| 527 | * Subnets used by the service's awsvpc network configuration. Updated in |
| 528 | * place via `updateService`. When omitted (together with {@link vpcId}), |
| 529 | * the default VPC's per-AZ default subnets are used. |
| 530 | */ |
| 531 | subnets?: string[]; |
| 532 | |
| 533 | /** |
| 534 | * Security groups attached to the service ENIs and any Alchemy-managed |
| 535 | * load balancer. When omitted and {@link loadBalancer} is set, Alchemy |
| 536 | * provisions (and owns) a security group that admits the listener port |
| 537 | * from anywhere and the container port from within the group. |
| 538 | */ |
| 539 | securityGroups?: string[]; |
| 540 | |
| 541 | /** |
| 542 | * Whether the service ENIs should receive public IPs. |
| 543 | * @default false — but `true` when networking defaulted to the default |
| 544 | * VPC (public subnets need a public IP to pull images without a NAT). |
| 545 | */ |
| 546 | assignPublicIp?: boolean; |
| 547 | |
| 548 | /** |
| 549 | * Launch type for the service. Mutually exclusive with |
| 550 | * {@link capacityProviderStrategy}. Switching between launch type and |
| 551 | * capacity-provider strategy replaces the service. |
| 552 | * @default "FARGATE" |
| 553 | */ |
| 554 | launchType?: ecs.LaunchType; |
| 555 | |
| 556 | /** |
| 557 | * Capacity provider strategy for the service (e.g. `FARGATE`/`FARGATE_SPOT` |
| 558 | * weights, or a custom ASG-backed provider). Mutually exclusive with |
| 559 | * {@link launchType}. Switching to/from a launch type replaces the service; |
| 560 | * weight/base changes apply in place. |
| 561 | */ |
| 562 | capacityProviderStrategy?: ecs.CapacityProviderStrategyItem[]; |
| 563 | |
| 564 | /** |
| 565 | * Fargate capacity sugar: `"spot"` runs every task on `FARGATE_SPOT`, or |
| 566 | * weight on-demand against spot capacity. Normalized into |
| 567 | * {@link capacityProviderStrategy} (which it must not be combined with). |
| 568 | * The cluster needs the Fargate capacity providers associated. |
| 569 | */ |
| 570 | capacity?: ServiceCapacityConfig; |
| 571 | |
| 572 | /** |
| 573 | * Autoscale the service's desired count: composes an Application Auto |
| 574 | * Scaling scalable target (bounded by `min`/`max`) plus a target-tracking |
| 575 | * policy per declared metric (`cpuUtilization`, `memoryUtilization`, |
| 576 | * `requestCount`). While set, deploys stop pinning `desiredCount` so the |
| 577 | * autoscaler's decisions survive redeploys. |
| 578 | */ |
| 579 | scaling?: ServiceScalingConfig; |
| 580 | |
| 581 | /** |
| 582 | * Register the service in an AWS Cloud Map namespace: composes an |
| 583 | * `AWS.CloudMap.Service` and wires it into the ECS service's |
| 584 | * {@link serviceRegistries}. |
| 585 | */ |
| 586 | serviceRegistry?: ServiceRegistryConfig; |
| 587 | |
| 588 | /** |
| 589 | * Load balancer target groups to wire to the service. **User-supplied** — |
| 590 | * Alchemy does NOT create these. Each entry references an existing ELBv2 |
| 591 | * target group (or CLB) plus the container/port that receives traffic. |
| 592 | * Updated in place for rolling deployments. |
| 593 | * |
| 594 | * For an Alchemy-managed public ALB instead, set {@link loadBalancer} to |
| 595 | * `true`. |
| 596 | */ |
| 597 | loadBalancers?: ecs.LoadBalancer[]; |
| 598 | |
| 599 | /** |
| 600 | * Cloud Map service registries (service discovery) to associate with the |
| 601 | * service. |
| 602 | */ |
| 603 | serviceRegistries?: ecs.ServiceRegistry[]; |
| 604 | |
| 605 | /** |
| 606 | * Managed load balancing for the service, composed as REAL |
| 607 | * `AWS.ELBv2.LoadBalancer` / `Listener` / `TargetGroup` / `ListenerRule` |
| 608 | * child resources under the service's namespace: |
| 609 | * |
| 610 | * - `true` — the service OWNS a public ALB with a single HTTP listener |
| 611 | * forwarding to the container port. The `url` attribute is populated |
| 612 | * from the ALB's DNS name. |
| 613 | * - an `ELBv2.Listener` reference — the listener (and its ALB) are SHARED: |
| 614 | * the service only creates a target group and a catch-all |
| 615 | * (`path: "/*"`) listener rule on that listener. Destroying the service |
| 616 | * removes its rules and target groups; the shared listener/ALB are never |
| 617 | * touched. |
| 618 | * - an object — `listener` (default shared listener) + `rules` (path/host/ |
| 619 | * header/query routing, `forward`/`redirect` actions) + `public` |
| 620 | * (owned-only; `false` composes an internal ALB). Rules with |
| 621 | * `"80/http"`-style `listen` strings make the service own the ALB and |
| 622 | * those listeners; `ELBv2.Listener` references share existing ones. |
| 623 | * Mixing both in one service is a typed error. |
| 624 | * |
| 625 | * Migration note: services deployed before composed ingress recorded their |
| 626 | * inline-created ALB/TG/listener/security group in the service's own |
| 627 | * attributes. The first deploy under the composed shape performs a |
| 628 | * breaking redeploy — new composed resources are created and the legacy |
| 629 | * inline infrastructure is reaped (deleted) so nothing is stranded. |
| 630 | * @default false |
| 631 | */ |
| 632 | loadBalancer?: boolean | Listener | ServiceLoadBalancerConfig; |
| 633 | |
| 634 | /** |
| 635 | * Legacy alias for {@link loadBalancer}. |
| 636 | * @deprecated use `loadBalancer: true` |
| 637 | */ |
| 638 | public?: boolean; |
| 639 | |
| 640 | /** |
| 641 | * @internal Resolved managed-ingress wiring computed by the Service |
| 642 | * factory's composition step. Never set by hand. |
| 643 | */ |
| 644 | ingress?: ServiceManagedIngress; |
| 645 | |
| 646 | /** |
| 647 | * Listener port for generated public ingress. |
| 648 | * @default 80 when `certificateArn` is omitted, otherwise 443 |
| 649 | */ |
| 650 | listenerPort?: number; |
| 651 | |
| 652 | /** |
| 653 | * ACM certificate ARN for HTTPS public ingress. |
| 654 | * When provided, the generated listener uses HTTPS. |
| 655 | */ |
| 656 | certificateArn?: string; |
| 657 | |
| 658 | /** |
| 659 | * Target group health check path for public HTTP services. |
| 660 | * @default "/" |
| 661 | */ |
| 662 | healthCheckPath?: string; |
| 663 | |
| 664 | /** |
| 665 | * Fargate platform version for the service. Updated in place. |
| 666 | */ |
| 667 | platformVersion?: string; |
| 668 | |
| 669 | /** |
| 670 | * Raw ECS deployment configuration (rolling update percentages, circuit |
| 671 | * breaker, deployment strategy, alarms). Updated in place. |
| 672 | */ |
| 673 | deploymentConfiguration?: ecs.DeploymentConfiguration; |
| 674 | |
| 675 | /** |
| 676 | * Maximum time to wait for an ECS deployment, old-task drain, and target |
| 677 | * health to converge before failing the resource operation. The provider |
| 678 | * hard-caps this at 30 minutes so polling always remains bounded. |
| 679 | * @default "10 minutes" |
| 680 | */ |
| 681 | deploymentStabilizationTimeout?: Duration.Input; |
| 682 | |
| 683 | /** |
| 684 | * Deployment controller (`ECS`, `CODE_DEPLOY`, `EXTERNAL`). The controller |
| 685 | * type is immutable — changing it replaces the service. |
| 686 | */ |
| 687 | deploymentController?: ecs.DeploymentController; |
| 688 | |
| 689 | /** |
| 690 | * Placement constraints (`distinctInstance` / `memberOf`). Updated in place. |
| 691 | */ |
| 692 | placementConstraints?: ecs.PlacementConstraint[]; |
| 693 | |
| 694 | /** |
| 695 | * Placement strategy (`random` / `spread` / `binpack`). Updated in place. |
| 696 | */ |
| 697 | placementStrategy?: ecs.PlacementStrategy[]; |
| 698 | |
| 699 | /** |
| 700 | * Scheduling strategy. `REPLICA` runs and maintains `desiredCount` copies; |
| 701 | * `DAEMON` runs one task per eligible instance. Immutable — changing it |
| 702 | * replaces the service. |
| 703 | * @default "REPLICA" |
| 704 | */ |
| 705 | schedulingStrategy?: ecs.SchedulingStrategy; |
| 706 | |
| 707 | /** |
| 708 | * Whether to enable ECS Exec on the service tasks. Updated in place. |
| 709 | * @default false |
| 710 | */ |
| 711 | enableExecuteCommand?: boolean; |
| 712 | |
| 713 | /** |
| 714 | * Whether to enable ECS managed tags. Immutable post-create. |
| 715 | * @default true |
| 716 | */ |
| 717 | enableECSManagedTags?: boolean; |
| 718 | |
| 719 | /** |
| 720 | * How to propagate tags to tasks (`TASK_DEFINITION`, `SERVICE`, `NONE`). |
| 721 | * Updated in place. |
| 722 | */ |
| 723 | propagateTags?: ecs.PropagateTags; |
| 724 | |
| 725 | /** |
| 726 | * Availability zone rebalancing behavior. Updated in place. |
| 727 | */ |
| 728 | availabilityZoneRebalancing?: ecs.AvailabilityZoneRebalancing; |
| 729 | |
| 730 | /** |
| 731 | * ECS Service Connect configuration. Updated in place. |
| 732 | */ |
| 733 | serviceConnectConfiguration?: ecs.ServiceConnectConfiguration; |
| 734 | |
| 735 | /** |
| 736 | * Service-managed volume configurations. Updated in place. |
| 737 | */ |
| 738 | volumeConfigurations?: ecs.ServiceVolumeConfiguration[]; |
| 739 | |
| 740 | /** |
| 741 | * IAM role for the ELB integration (only for non-awsvpc / CLB services). |
| 742 | * Immutable — changing it replaces the service. |
| 743 | */ |
| 744 | role?: string; |
| 745 | |
| 746 | /** |
| 747 | * Grace period before ECS starts evaluating target health checks, e.g. |
| 748 | * `"30 seconds"` or `Duration.seconds(30)`. Rounded to whole seconds on |
| 749 | * the wire. Updated in place. |
| 750 | */ |
| 751 | healthCheckGracePeriod?: Duration.Input; |
| 752 | |
| 753 | /** |
| 754 | * User-defined tags to apply to the ECS service and generated ingress |
| 755 | * resources. Reconciled in place against observed service tags. |
| 756 | */ |
| 757 | tags?: Record<string, string>; |
| 758 | } |
| 759 | |
| 760 | /** |
| 761 | * Deploy an existing `AWS.ECS.Task`'s definition as a service (shared |
| 762 | * image/roles/config; the Service adds `desiredCount` / load balancing / |
| 763 | * deployment configuration). |
| 764 | */ |
| 765 | export interface TaskReferenceServiceProps extends ServicePropsBase { |
| 766 | /** |
| 767 | * Bundled ECS task to run for each service replica: the runtime-facing |
| 768 | * subset of `AWS.ECS.Task` attributes the service needs to deploy and |
| 769 | * wire load balancer traffic (a full `Task` satisfies it structurally). |
| 770 | */ |
| 771 | task: { |
| 772 | /** |
| 773 | * Registered task definition ARN to deploy. |
| 774 | */ |
| 775 | taskDefinitionArn: string; |
| 776 | /** |
| 777 | * Container name inside the task definition that should receive traffic. |
| 778 | */ |
| 779 | containerName: string; |
| 780 | /** |
| 781 | * Container port that the service should expose and forward traffic to. |
| 782 | */ |
| 783 | port: number; |
| 784 | }; |
| 785 | } |
| 786 | |
| 787 | /** |
| 788 | * Image-owning base: the Service synthesizes its own task definition |
| 789 | * (roles, log group, ECR repository, image) from the shared |
| 790 | * {@link TaskDefinitionConfig} surface. |
| 791 | */ |
| 792 | export interface ImageOwningServicePropsBase |
| 793 | extends ServicePropsBase, Omit<TaskDefinitionConfig, "placementConstraints" | "volumes"> { |
| 794 | /** |
| 795 | * Task definition placement constraints (`memberOf` expressions) for the |
| 796 | * synthesized task definition. (`placementConstraints` on the service |
| 797 | * itself remains the service-level ECS placement constraint list.) |
| 798 | */ |
| 799 | taskPlacementConstraints?: ecs.TaskDefinitionPlacementConstraint[]; |
| 800 | |
| 801 | /** |
| 802 | * Secrets injected into the primary container as environment variables: |
| 803 | * env-var name → SSM Parameter Store parameter ARN or Secrets Manager |
| 804 | * secret ARN. Wired as container `secrets` (`valueFrom`), with the |
| 805 | * execution role granted `ssm:GetParameters` / |
| 806 | * `secretsmanager:GetSecretValue` on exactly the referenced ARNs. |
| 807 | */ |
| 808 | secrets?: Record<string, string>; |
| 809 | |
| 810 | /** |
| 811 | * Container-level health check (Docker `HEALTHCHECK`) for the primary |
| 812 | * container, e.g. |
| 813 | * `{ command: ["CMD-SHELL", "curl -f http://localhost/ || exit 1"] }`. |
| 814 | */ |
| 815 | healthCheck?: ServiceContainerHealthCheck; |
| 816 | |
| 817 | /** |
| 818 | * Task-level data volumes. Accepts raw {@link ecs.Volume} entries |
| 819 | * (referenced by the container via `mountPoints`) or the EFS sugar |
| 820 | * `{ efs, path }`, which composes the volume AND mounts it at `path` on |
| 821 | * the primary container with transit encryption enabled. |
| 822 | */ |
| 823 | volumes?: (ecs.Volume | ServiceEfsVolume)[]; |
| 824 | } |
| 825 | |
| 826 | /** Bundle an inline Effect program (`main`) into the service's image. */ |
| 827 | export interface BundledServiceProps extends ImageOwningServicePropsBase, BundledImageSource {} |
| 828 | /** Build the user's own Dockerfile into the service's image. */ |
| 829 | export interface DockerfileServiceProps |
| 830 | extends ImageOwningServicePropsBase, DockerfileImageSource {} |
| 831 | /** Run a pre-built registry image, mirrored into ECR. */ |
| 832 | export interface ImageServiceProps extends ImageOwningServicePropsBase, RegistryImageSource {} |
| 833 | |
| 834 | /** |
| 835 | * Service props — either reference an existing task definition (`task:`) or |
| 836 | * own the image via exactly one of `main` / `context` / `image` (the |
| 837 | * Service then synthesizes its own task definition). |
| 838 | */ |
| 839 | export type ServiceProps = |
| 840 | | TaskReferenceServiceProps |
| 841 | | BundledServiceProps |
| 842 | | DockerfileServiceProps |
| 843 | | ImageServiceProps; |
| 844 | |
| 845 | export interface Service extends Resource< |
| 846 | "AWS.ECS.Service", |
| 847 | ServiceProps, |
| 848 | { |
| 849 | /** |
| 850 | * ARN of the ECS service. |
| 851 | */ |
| 852 | serviceArn: ServiceArn; |
| 853 | |
| 854 | /** |
| 855 | * Name of the ECS service. |
| 856 | */ |
| 857 | serviceName: ServiceName; |
| 858 | |
| 859 | /** |
| 860 | * ARN of the cluster that owns the service. |
| 861 | */ |
| 862 | clusterArn: ClusterArn; |
| 863 | |
| 864 | /** |
| 865 | * Task definition revision currently deployed by the service. |
| 866 | */ |
| 867 | taskDefinitionArn: string; |
| 868 | |
| 869 | /** |
| 870 | * ECS service status such as `ACTIVE` or `DRAINING`. |
| 871 | */ |
| 872 | status: string; |
| 873 | |
| 874 | /** |
| 875 | * URL of the service through its managed ingress. Owned load balancers |
| 876 | * use the composed ALB's DNS name; shared listeners derive it from the |
| 877 | * foreign listener's ALB DNS + protocol/port (best-effort — undefined |
| 878 | * when not derivable). |
| 879 | */ |
| 880 | url?: string; |
| 881 | |
| 882 | /** |
| 883 | * ARN of the load balancer serving the service's managed ingress (the |
| 884 | * composed ALB when owned; the shared listener's ALB otherwise). |
| 885 | */ |
| 886 | loadBalancerArn?: string; |
| 887 | |
| 888 | /** |
| 889 | * ARN of the first managed target group, when `loadBalancer` is set. |
| 890 | */ |
| 891 | targetGroupArn?: string; |
| 892 | |
| 893 | /** |
| 894 | * ARN of the primary listener, when `loadBalancer` is set. |
| 895 | */ |
| 896 | listenerArn?: string; |
| 897 | |
| 898 | /** |
| 899 | * Id of the Alchemy-managed security group composed for managed ingress |
| 900 | * (only when `loadBalancer` is set and no `securityGroups` supplied). |
| 901 | */ |
| 902 | securityGroupId?: string; |
| 903 | |
| 904 | /** |
| 905 | * @internal Marks attrs written by the composed-ingress shape ("owned" | |
| 906 | * "shared"). Absent on legacy state rows whose ALB/TG/listener were |
| 907 | * created inline by the provider — the marker gates the migration reap |
| 908 | * and the legacy delete path. |
| 909 | */ |
| 910 | ingressKind?: "owned" | "shared"; |
| 911 | |
| 912 | /** |
| 913 | * Desired count, networking, load balancers, service registries, the |
| 914 | * declared deployment/placement/execute-command settings and the tags, |
| 915 | * as observed. Lets `alchemy drift` detect out-of-band changes. |
| 916 | */ |
| 917 | configuration?: Record<string, unknown>; |
| 918 | |
| 919 | /** Family of the synthesized task definition (image-owning form only). */ |
| 920 | taskFamily?: string; |
| 921 | /** Name of the primary container (image-owning form only). */ |
| 922 | containerName?: string; |
| 923 | /** Container port receiving traffic (image-owning form only). */ |
| 924 | port?: number; |
| 925 | /** Image URI the synthesized task definition runs. */ |
| 926 | imageUri?: string; |
| 927 | /** ECR repository name holding the service's image. */ |
| 928 | repositoryName?: string; |
| 929 | /** ECR repository URI holding the service's image. */ |
| 930 | repositoryUri?: string; |
| 931 | /** ARN of the synthesized task role. */ |
| 932 | taskRoleArn?: string; |
| 933 | /** Name of the synthesized task role. */ |
| 934 | taskRoleName?: string; |
| 935 | /** ARN of the synthesized execution role. */ |
| 936 | executionRoleArn?: string; |
| 937 | /** Name of the synthesized execution role. */ |
| 938 | executionRoleName?: string; |
| 939 | /** CloudWatch log group of the synthesized task definition. */ |
| 940 | logGroupName?: string; |
| 941 | /** ARN of the CloudWatch log group. */ |
| 942 | logGroupArn?: string; |
| 943 | /** Content hash of the service's container image. */ |
| 944 | code?: { |
| 945 | /** Content hash of the service's container image. */ |
| 946 | hash: string; |
| 947 | }; |
| 948 | }, |
| 949 | TaskBindingContract, |
| 950 | Providers |
| 951 | > {} |
| 952 | |
| 953 | export type ServiceServices = Credentials | Region | ServerHost | AWSEnvironment; |
| 954 | |
| 955 | /** |
| 956 | * The impl shape for an effectful `Service`: a long-running server returning |
| 957 | * `{ fetch }` (plus optional RPC methods). |
| 958 | */ |
| 959 | export type ServiceShape = Main<ServiceServices>; |
| 960 | |
| 961 | export interface ServiceRuntimeContext extends HostRuntimeContext { |
| 962 | readonly Type: "AWS.ECS.Service"; |
| 963 | } |
| 964 | |
| 965 | /** |
| 966 | * An ECS service: N copies of a container kept alive, optionally behind a |
| 967 | * load balancer. |
| 968 | * |
| 969 | * The service's image comes from one of four sources: |
| 970 | * |
| 971 | * - `image` — run a pre-built registry image, mirrored into ECR. |
| 972 | * - `context` — build your own Dockerfile. |
| 973 | * - `main` — bundle an inline Effect program (servers return `{ fetch }`). |
| 974 | * - `task:` — deploy an existing `AWS.ECS.Task`'s definition; the Service |
| 975 | * adds `desiredCount` / load balancing / deployment configuration. |
| 976 | * |
| 977 | * With any of the first three the Service synthesizes its own task |
| 978 | * definition (task + execution roles, log group, ECR repository). |
| 979 | * `loadBalancer: true` wires a public ALB + target group + listener and |
| 980 | * populates the `url` attribute. When `vpcId`/`subnets` are omitted the |
| 981 | * account's default VPC (and its per-AZ subnets) is used. |
| 982 | * |
| 983 | * Most configuration is updated **in place** via `updateService` |
| 984 | * (desiredCount, task definition, network, deployment config, placement, |
| 985 | * exec, load balancers, tags). Only truly-immutable aspects — `serviceName`, |
| 986 | * `cluster`, launchType↔capacityProviderStrategy switch, `deploymentController` |
| 987 | * type, `schedulingStrategy`, `enableECSManagedTags`, `role` — replace the |
| 988 | * service. |
| 989 | * ### Creating Services |
| 990 | * **Example:** Remote Image Behind a Load Balancer |
| 991 | * ```typescript |
| 992 | * const nginx = yield* Service("Edge", { |
| 993 | * cluster, |
| 994 | * image: "public.ecr.aws/nginx/nginx:1.27", |
| 995 | * port: 80, |
| 996 | * desiredCount: 2, |
| 997 | * loadBalancer: true, // ALB + target group + listener wiring |
| 998 | * }); |
| 999 | * nginx.url; // http://<alb-dns-name> |
| 1000 | * ``` |
| 1001 | * |
| 1002 | * **Example:** Run an Existing Task's Definition |
| 1003 | * ```typescript |
| 1004 | * const api = yield* Service("Api", { |
| 1005 | * cluster, |
| 1006 | * task: apiTask, // shared image/roles/config; Service adds |
| 1007 | * desiredCount: 2, // desiredCount / LB / deployment config |
| 1008 | * loadBalancer: true, |
| 1009 | * }); |
| 1010 | * ``` |
| 1011 | * |
| 1012 | * **Example:** Inline Effect Server |
| 1013 | * ```typescript |
| 1014 | * const api = yield* Service( |
| 1015 | * "Api", |
| 1016 | * { cluster, main: import.meta.url, port: 3000, desiredCount: 2, cpu: 256, memory: 512 }, |
| 1017 | * Effect.gen(function* () { |
| 1018 | * const putItem = yield* AWS.DynamoDB.PutItem(table); |
| 1019 | * return { |
| 1020 | * fetch: Effect.gen(function* () { |
| 1021 | * return yield* HttpServerResponse.json({ ok: true }); |
| 1022 | * }), |
| 1023 | * }; |
| 1024 | * }).pipe(Effect.provide(AWS.DynamoDB.PutItemHttp)), |
| 1025 | * ); |
| 1026 | * ``` |
| 1027 | * |
| 1028 | * ### Bundling & Tree-shaking |
| 1029 | * `main` is bundled with rolldown at deploy time. Unused code is |
| 1030 | * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked |
| 1031 | * pure so unused parts prune more aggressively. Your app is not |
| 1032 | * marked pure. |
| 1033 | * |
| 1034 | * **Example:** Mark additional packages as pure |
| 1035 | * Only list packages with no top-level side effects. |
| 1036 | * ```typescript |
| 1037 | * { |
| 1038 | * main: import.meta.url, |
| 1039 | * build: { |
| 1040 | * pure: { packages: ["my-lib", "@my-scope/*"] }, |
| 1041 | * }, |
| 1042 | * } |
| 1043 | * ``` |
| 1044 | * |
| 1045 | * **Example:** Turn it off |
| 1046 | * ```typescript |
| 1047 | * { |
| 1048 | * main: import.meta.url, |
| 1049 | * build: { pure: false }, |
| 1050 | * } |
| 1051 | * ``` |
| 1052 | * |
| 1053 | * ### Shared Load Balancers |
| 1054 | * **Example:** Two Services Sharing One Listener |
| 1055 | * ```typescript |
| 1056 | * // The ALB + listener are stack-level resources owned by neither service. |
| 1057 | * const lb = yield* AWS.ELBv2.LoadBalancer("Alb", { |
| 1058 | * subnets: [subnetA.subnetId, subnetB.subnetId], |
| 1059 | * securityGroups: [sg.groupId], |
| 1060 | * }); |
| 1061 | * const listener = yield* AWS.ELBv2.Listener("Http", { |
| 1062 | * loadBalancerArn: lb.loadBalancerArn, |
| 1063 | * port: 80, |
| 1064 | * defaultActions: [ |
| 1065 | * { type: "fixedResponse", statusCode: "404", messageBody: "no route" }, |
| 1066 | * ], |
| 1067 | * }); |
| 1068 | * |
| 1069 | * // Each service composes only its own TargetGroup + ListenerRule on the |
| 1070 | * // shared listener. Destroying one service removes its rule + target |
| 1071 | * // group; the ALB, listener, and the other service are untouched. |
| 1072 | * const api = yield* Service("Api", { |
| 1073 | * cluster, |
| 1074 | * image: "my-org/api:latest", |
| 1075 | * port: 3000, |
| 1076 | * loadBalancer: { listener, rules: [{ path: "/api/*" }] }, |
| 1077 | * }); |
| 1078 | * const web = yield* Service("Web", { |
| 1079 | * cluster, |
| 1080 | * image: "my-org/web:latest", |
| 1081 | * port: 8080, |
| 1082 | * loadBalancer: { listener, rules: [{ path: "/*" }] }, |
| 1083 | * }); |
| 1084 | * ``` |
| 1085 | * |
| 1086 | * **Example:** Catch-All on a Shared Listener |
| 1087 | * ```typescript |
| 1088 | * // A bare listener reference adds a single `path: "/*"` rule. |
| 1089 | * const svc = yield* Service("Svc", { |
| 1090 | * cluster, |
| 1091 | * image: "my-org/web:latest", |
| 1092 | * port: 8080, |
| 1093 | * loadBalancer: listener, |
| 1094 | * }); |
| 1095 | * ``` |
| 1096 | * |
| 1097 | * **Example:** Owned ALB with Routing Rules and an HTTP → HTTPS Redirect |
| 1098 | * ```typescript |
| 1099 | * // `"80/http"`-style `listen` strings mean the service OWNS the ALB and |
| 1100 | * // these listeners (mixing them with shared listener references is a |
| 1101 | * // typed error). |
| 1102 | * const svc = yield* Service("Svc", { |
| 1103 | * cluster, |
| 1104 | * image: "my-org/web:latest", |
| 1105 | * port: 8080, |
| 1106 | * certificateArn, |
| 1107 | * loadBalancer: { |
| 1108 | * rules: [ |
| 1109 | * { listen: "80/http", redirect: "443/https" }, |
| 1110 | * { listen: "443/https", forward: "8080/http" }, |
| 1111 | * ], |
| 1112 | * }, |
| 1113 | * }); |
| 1114 | * ``` |
| 1115 | * |
| 1116 | * ### Custom Domains |
| 1117 | * **Example:** Domain with a Composed Certificate |
| 1118 | * ```typescript |
| 1119 | * // Looks up the matching Route 53 hosted zone, composes a DNS-validated |
| 1120 | * // ACM certificate in the service's region, wires it to the HTTPS |
| 1121 | * // listener, and creates alias A/AAAA records. `url` becomes |
| 1122 | * // https://api.example.com. |
| 1123 | * const svc = yield* Service("Api", { |
| 1124 | * cluster, |
| 1125 | * image: "my-org/api:latest", |
| 1126 | * port: 3000, |
| 1127 | * loadBalancer: { domain: "api.example.com" }, |
| 1128 | * }); |
| 1129 | * ``` |
| 1130 | * |
| 1131 | * **Example:** Domain with an Existing Certificate |
| 1132 | * ```typescript |
| 1133 | * const svc = yield* Service("Api", { |
| 1134 | * cluster, |
| 1135 | * image: "my-org/api:latest", |
| 1136 | * port: 3000, |
| 1137 | * loadBalancer: { |
| 1138 | * domain: { name: "api.example.com", aliases: ["www.api.example.com"], cert: certificateArn }, |
| 1139 | * }, |
| 1140 | * }); |
| 1141 | * ``` |
| 1142 | * |
| 1143 | * **Example:** Domain on Cloudflare DNS |
| 1144 | * ```typescript |
| 1145 | * // The certificate is validated through the Cloudflare zone and each |
| 1146 | * // name gets a CNAME to the load balancer. Requires |
| 1147 | * // `Cloudflare.providers()` in the stack. |
| 1148 | * const svc = yield* Service("Api", { |
| 1149 | * cluster, |
| 1150 | * image: "my-org/api:latest", |
| 1151 | * port: 3000, |
| 1152 | * loadBalancer: { |
| 1153 | * domain: { name: "api.example.com", dns: Cloudflare.DNS.Adapter() }, |
| 1154 | * }, |
| 1155 | * }); |
| 1156 | * ``` |
| 1157 | * |
| 1158 | * ### Network Load Balancers |
| 1159 | * **Example:** TCP Service Behind an NLB |
| 1160 | * ```typescript |
| 1161 | * // tcp/udp/tls/tcp_udp listen protocols compose a Network Load Balancer; |
| 1162 | * // each rule's action becomes its listener's default forward (NLB |
| 1163 | * // listeners route by port alone). |
| 1164 | * const svc = yield* Service("Tcp", { |
| 1165 | * cluster, |
| 1166 | * image: "my-org/tcp-echo:latest", |
| 1167 | * port: 9000, |
| 1168 | * loadBalancer: { rules: [{ listen: "80/tcp" }] }, |
| 1169 | * }); |
| 1170 | * ``` |
| 1171 | * |
| 1172 | * ### Health Checks |
| 1173 | * **Example:** Per-Target-Group Health Overrides |
| 1174 | * ```typescript |
| 1175 | * const svc = yield* Service("Api", { |
| 1176 | * cluster, |
| 1177 | * image: "my-org/api:latest", |
| 1178 | * port: 3000, |
| 1179 | * loadBalancer: { |
| 1180 | * rules: [{ listen: "80/http" }], |
| 1181 | * health: { |
| 1182 | * "3000/http": { |
| 1183 | * path: "/healthz", |
| 1184 | * interval: "15 seconds", |
| 1185 | * healthyThreshold: 3, |
| 1186 | * successCodes: "200-299", |
| 1187 | * }, |
| 1188 | * }, |
| 1189 | * }, |
| 1190 | * }); |
| 1191 | * ``` |
| 1192 | * |
| 1193 | * **Example:** Container Health Check |
| 1194 | * ```typescript |
| 1195 | * const svc = yield* Service("Api", { |
| 1196 | * cluster, |
| 1197 | * image: "my-org/api:latest", |
| 1198 | * port: 3000, |
| 1199 | * healthCheck: { |
| 1200 | * command: ["CMD-SHELL", "curl -f http://localhost:3000/ || exit 1"], |
| 1201 | * interval: "30 seconds", |
| 1202 | * retries: 3, |
| 1203 | * }, |
| 1204 | * }); |
| 1205 | * ``` |
| 1206 | * |
| 1207 | * ### Autoscaling |
| 1208 | * **Example:** Target-Tracking Autoscaling |
| 1209 | * ```typescript |
| 1210 | * // Composes a ScalableTarget (min/max) plus one target-tracking policy |
| 1211 | * // per metric. Redeploys stop pinning desiredCount while scaling is set. |
| 1212 | * const svc = yield* Service("Api", { |
| 1213 | * cluster, |
| 1214 | * image: "my-org/api:latest", |
| 1215 | * port: 3000, |
| 1216 | * loadBalancer: true, |
| 1217 | * scaling: { |
| 1218 | * min: 1, |
| 1219 | * max: 4, |
| 1220 | * cpuUtilization: 70, |
| 1221 | * requestCount: 200, |
| 1222 | * scaleInCooldown: "5 minutes", |
| 1223 | * }, |
| 1224 | * }); |
| 1225 | * ``` |
| 1226 | * |
| 1227 | * ### Secrets & Logging |
| 1228 | * **Example:** Inject SSM / Secrets Manager Secrets |
| 1229 | * ```typescript |
| 1230 | * // Values are ARNs; the container gets them as env vars via `valueFrom` |
| 1231 | * // and the execution role is granted read on exactly these ARNs. |
| 1232 | * const svc = yield* Service("Api", { |
| 1233 | * cluster, |
| 1234 | * image: "my-org/api:latest", |
| 1235 | * port: 3000, |
| 1236 | * secrets: { |
| 1237 | * DB_PASSWORD: dbPasswordSecret.secretArn, |
| 1238 | * API_KEY: apiKeyParameter.parameterArn, |
| 1239 | * }, |
| 1240 | * logging: { retention: "2 weeks" }, |
| 1241 | * }); |
| 1242 | * ``` |
| 1243 | * |
| 1244 | * ### Service Discovery |
| 1245 | * **Example:** Register in a Cloud Map Namespace |
| 1246 | * ```typescript |
| 1247 | * const namespace = yield* AWS.CloudMap.PrivateDnsNamespace("AppNs", { |
| 1248 | * name: "internal.example.com", |
| 1249 | * vpc: vpc.vpcId, |
| 1250 | * }); |
| 1251 | * const svc = yield* Service("Api", { |
| 1252 | * cluster, |
| 1253 | * image: "my-org/api:latest", |
| 1254 | * port: 3000, |
| 1255 | * serviceRegistry: { namespace }, |
| 1256 | * }); |
| 1257 | * ``` |
| 1258 | * |
| 1259 | * ### Volumes |
| 1260 | * **Example:** Mount an EFS File System |
| 1261 | * ```typescript |
| 1262 | * const svc = yield* Service("Api", { |
| 1263 | * cluster, |
| 1264 | * image: "my-org/api:latest", |
| 1265 | * port: 3000, |
| 1266 | * volumes: [{ efs: fileSystem, path: "/mnt/data" }], |
| 1267 | * }); |
| 1268 | * ``` |
| 1269 | * |
| 1270 | * ### Capacity |
| 1271 | * **Example:** Fargate Spot |
| 1272 | * ```typescript |
| 1273 | * // The cluster must have the Fargate capacity providers associated: |
| 1274 | * // Cluster("C", { capacityProviders: ["FARGATE", "FARGATE_SPOT"] }). |
| 1275 | * const svc = yield* Service("Worker", { |
| 1276 | * cluster, |
| 1277 | * image: "my-org/worker:latest", |
| 1278 | * capacity: { fargate: { weight: 1, base: 1 }, spot: { weight: 4 } }, |
| 1279 | * }); |
| 1280 | * ``` |
| 1281 | * |
| 1282 | * ### Load Balancing |
| 1283 | * **Example:** Manual (User-Supplied) Target Group |
| 1284 | * ```typescript |
| 1285 | * const service = yield* Service("ApiService", { |
| 1286 | * cluster, |
| 1287 | * task: apiTask, |
| 1288 | * vpcId: vpc.vpcId, |
| 1289 | * subnets: [subnet1.subnetId, subnet2.subnetId], |
| 1290 | * loadBalancers: [ |
| 1291 | * { |
| 1292 | * targetGroupArn, |
| 1293 | * containerName: apiTask.containerName, |
| 1294 | * containerPort: apiTask.port, |
| 1295 | * }, |
| 1296 | * ], |
| 1297 | * }); |
| 1298 | * ``` |
| 1299 | * |
| 1300 | * ### Capacity & Placement |
| 1301 | * **Example:** FARGATE_SPOT Capacity Provider Strategy |
| 1302 | * ```typescript |
| 1303 | * const service = yield* Service("WorkerService", { |
| 1304 | * cluster, |
| 1305 | * task: workerTask, |
| 1306 | * vpcId: vpc.vpcId, |
| 1307 | * subnets: [subnet.subnetId], |
| 1308 | * capacityProviderStrategy: [ |
| 1309 | * { capacityProvider: "FARGATE_SPOT", weight: 4 }, |
| 1310 | * { capacityProvider: "FARGATE", weight: 1, base: 1 }, |
| 1311 | * ], |
| 1312 | * placementStrategy: [{ type: "spread", field: "attribute:ecs.availability-zone" }], |
| 1313 | * }); |
| 1314 | * ``` |
| 1315 | * |
| 1316 | * ### Deployment |
| 1317 | * **Example:** Rolling Update with Circuit Breaker |
| 1318 | * ```typescript |
| 1319 | * const service = yield* Service("ApiService", { |
| 1320 | * cluster, |
| 1321 | * task: apiTask, |
| 1322 | * vpcId: vpc.vpcId, |
| 1323 | * subnets: [subnet1.subnetId, subnet2.subnetId], |
| 1324 | * desiredCount: 3, |
| 1325 | * enableExecuteCommand: true, |
| 1326 | * deploymentConfiguration: { |
| 1327 | * minimumHealthyPercent: 100, |
| 1328 | * maximumPercent: 200, |
| 1329 | * deploymentCircuitBreaker: { enable: true, rollback: true }, |
| 1330 | * }, |
| 1331 | * healthCheckGracePeriod: "30 seconds", |
| 1332 | * }); |
| 1333 | * ``` |
| 1334 | * |
| 1335 | * @resource |
| 1336 | */ |
| 1337 | export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> = |
| 1338 | Platform("AWS.ECS.Service", { |
| 1339 | createRuntimeContext: createContainerRuntimeContext("AWS.ECS.Service") as ( |
| 1340 | id: string, |
| 1341 | ) => ServiceRuntimeContext, |
| 1342 | // Compose the managed load balancer (owned ALB/listeners or shared-listener |
| 1343 | // rules + target groups) as REAL namespaced child resources before the core |
| 1344 | // service resource is declared. |
| 1345 | transformProps: (id, props) => transformServiceProps(id, props), |
| 1346 | // Autoscaling references the service's own Output attributes (cluster/name/ |
| 1347 | // target-group ARNs), so it composes AFTER the resource exists. |
| 1348 | onCreate: (resource, props) => |
| 1349 | // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- Platform onCreate hook type is Effect<void, never, any>; failures still propagate at runtime |
| 1350 | composeServiceScaling( |
| 1351 | resource as Service, |
| 1352 | props as ServiceProps, |
| 1353 | // Typed failures (e.g. RequestCountScalingRequiresLoadBalancer) |
| 1354 | // surface through the deploy like any resource-construction error. |
| 1355 | ) as Effect.Effect<void, never, any>, |
| 1356 | }); |
| 1357 | |
| 1358 | /** The BYO task reference, when the props use the `task:` form. */ |
| 1359 | /** |
| 1360 | * The service settings reconcile converges, as observed on `service`. |
| 1361 | * `read` and `reconcile` share it so a converged service reads unchanged. |
| 1362 | * Settings whose prop is unset are left unchanged by `updateService`, so |
| 1363 | * they are only observed when declared; the desired count is not observed |
| 1364 | * while autoscaling owns it. |
| 1365 | */ |
| 1366 | const observeServiceConfiguration = ( |
| 1367 | service: ecs.Service, |
| 1368 | props: ServiceProps | undefined, |
| 1369 | tags: Record<string, string>, |
| 1370 | ) => { |
| 1371 | const declared = <V>(key: keyof ServiceProps, value: V) => |
| 1372 | props?.[key] === undefined ? undefined : value; |
| 1373 | const vpc = service.networkConfiguration?.awsvpcConfiguration; |
| 1374 | return plainJson({ |
| 1375 | desiredCount: props?.scaling === undefined ? service.desiredCount : undefined, |
| 1376 | networkConfiguration: vpc && { |
| 1377 | subnets: [...(vpc.subnets ?? [])].sort(), |
| 1378 | securityGroups: [...(vpc.securityGroups ?? [])].sort(), |
| 1379 | assignPublicIp: vpc.assignPublicIp, |
| 1380 | }, |
| 1381 | loadBalancers: service.loadBalancers?.length |
| 1382 | ? [...service.loadBalancers].sort((a, b) => |
| 1383 | JSON.stringify(a).localeCompare(JSON.stringify(b)), |
| 1384 | ) |
| 1385 | : undefined, |
| 1386 | serviceRegistries: service.serviceRegistries?.length ? service.serviceRegistries : undefined, |
| 1387 | platformVersion: declared("platformVersion", service.platformVersion), |
| 1388 | deploymentConfiguration: declared("deploymentConfiguration", service.deploymentConfiguration), |
| 1389 | healthCheckGracePeriodSeconds: declared( |
| 1390 | "healthCheckGracePeriod", |
| 1391 | service.healthCheckGracePeriodSeconds, |
| 1392 | ), |
| 1393 | capacityProviderStrategy: declared( |
| 1394 | "capacityProviderStrategy", |
| 1395 | service.capacityProviderStrategy, |
| 1396 | ), |
| 1397 | placementConstraints: declared("placementConstraints", service.placementConstraints), |
| 1398 | placementStrategy: declared("placementStrategy", service.placementStrategy), |
| 1399 | enableExecuteCommand: declared("enableExecuteCommand", service.enableExecuteCommand), |
| 1400 | propagateTags: declared("propagateTags", service.propagateTags), |
| 1401 | availabilityZoneRebalancing: declared( |
| 1402 | "availabilityZoneRebalancing", |
| 1403 | service.availabilityZoneRebalancing, |
| 1404 | ), |
| 1405 | tags, |
| 1406 | }); |
| 1407 | }; |
| 1408 | |
| 1409 | const ecsTagRecord = (tags: ecs.Tag[] | undefined): Record<string, string> => |
| 1410 | Object.fromEntries( |
| 1411 | (tags ?? []).flatMap((t) => |
| 1412 | typeof t.key === "string" && typeof t.value === "string" ? [[t.key, t.value]] : [], |
| 1413 | ), |
| 1414 | ); |
| 1415 | |
| 1416 | const taskRefOf = (props: ServiceProps | undefined) => |
| 1417 | props !== undefined && "task" in props ? props.task : undefined; |
| 1418 | |
| 1419 | // ─────────────────────────────────────────────────────────────────────────── |
| 1420 | // Managed load balancer — composition (the StaticSite pattern) |
| 1421 | // ─────────────────────────────────────────────────────────────────────────── |
| 1422 | |
| 1423 | const isELBv2Listener = (value: unknown): value is Listener => |
| 1424 | typeof value === "object" && |
| 1425 | value !== null && |
| 1426 | "Type" in value && |
| 1427 | (value as { Type?: unknown }).Type === "AWS.ELBv2.Listener"; |
| 1428 | |
| 1429 | interface ParsedListen { |
| 1430 | port: number; |
| 1431 | protocol: ServiceListenerProtocol; |
| 1432 | } |
| 1433 | |
| 1434 | const LISTENER_PROTOCOLS: ReadonlySet<string> = new Set([ |
| 1435 | "http", |
| 1436 | "https", |
| 1437 | "tcp", |
| 1438 | "udp", |
| 1439 | "tcp_udp", |
| 1440 | "tls", |
| 1441 | ]); |
| 1442 | |
| 1443 | const parseListenSpec = (serviceId: string, spec: string, kind: string) => |
| 1444 | Effect.gen(function* () { |
| 1445 | const [portString, protocol] = spec.split("/"); |
| 1446 | const port = Number(portString); |
| 1447 | if ( |
| 1448 | !Number.isInteger(port) || |
| 1449 | port <= 0 || |
| 1450 | port > 65535 || |
| 1451 | protocol === undefined || |
| 1452 | !LISTENER_PROTOCOLS.has(protocol) |
| 1453 | ) { |
| 1454 | return yield* new UnsupportedListenerProtocol({ |
| 1455 | serviceId, |
| 1456 | spec, |
| 1457 | message: `AWS.ECS.Service "${serviceId}": unsupported ${kind} spec '${spec}' — expected "<port>/<protocol>" with protocol one of http, https (ALB) or tcp, udp, tcp_udp, tls (NLB)`, |
| 1458 | }); |
| 1459 | } |
| 1460 | return { port, protocol } as ParsedListen; |
| 1461 | }); |
| 1462 | |
| 1463 | /** |
| 1464 | * Resolve the account's default VPC and its per-AZ default subnets. Shared by |
| 1465 | * the composition step (target group / security group VPC, owned ALB subnets) |
| 1466 | * and the provider's network resolution. |
| 1467 | */ |
| 1468 | const lookupDefaultNetwork = Effect.gen(function* () { |
| 1469 | const vpc = yield* ec2.describeVpcs |
| 1470 | .items({ |
| 1471 | Filters: [{ Name: "isDefault", Values: ["true"] }], |
| 1472 | }) |
| 1473 | .pipe( |
| 1474 | Stream.filter((v) => v.IsDefault === true), |
| 1475 | Stream.runHead, |
| 1476 | Effect.map(Option.getOrUndefined), |
| 1477 | ); |
| 1478 | if (!vpc?.VpcId) { |
| 1479 | return yield* Effect.die( |
| 1480 | new Error( |
| 1481 | "AWS.ECS.Service: no default VPC in this account/region — pass `vpcId` and `subnets` explicitly", |
| 1482 | ), |
| 1483 | ); |
| 1484 | } |
| 1485 | const subnetIds = yield* ec2.describeSubnets |
| 1486 | .items({ |
| 1487 | Filters: [ |
| 1488 | { Name: "vpc-id", Values: [vpc.VpcId] }, |
| 1489 | { Name: "default-for-az", Values: ["true"] }, |
| 1490 | ], |
| 1491 | }) |
| 1492 | .pipe( |
| 1493 | Stream.map((s) => s.SubnetId), |
| 1494 | Stream.filter((s): s is string => s !== undefined), |
| 1495 | Stream.runCollect, |
| 1496 | Effect.map((chunk) => Array.from(chunk)), |
| 1497 | ); |
| 1498 | if (subnetIds.length === 0) { |
| 1499 | return yield* Effect.die( |
| 1500 | new Error( |
| 1501 | "AWS.ECS.Service: the default VPC has no default subnets — pass `subnets` explicitly", |
| 1502 | ), |
| 1503 | ); |
| 1504 | } |
| 1505 | return { vpcId: vpc.VpcId, subnets: subnetIds }; |
| 1506 | }); |
| 1507 | |
| 1508 | const toValuesArray = (value: string | string[] | undefined) => |
| 1509 | value === undefined ? undefined : Array.isArray(value) ? value : [value]; |
| 1510 | |
| 1511 | /** Flat rule conditions → the `ELBv2.ListenerRule` condition shape. */ |
| 1512 | const ruleConditionsOf = (rule: ServiceLoadBalancerRule): ListenerRuleCondition[] => { |
| 1513 | const conditions: ListenerRuleCondition[] = []; |
| 1514 | const path = toValuesArray(rule.path); |
| 1515 | if (path) conditions.push({ pathPattern: { values: path } }); |
| 1516 | const host = toValuesArray(rule.host); |
| 1517 | if (host) conditions.push({ hostHeader: { values: host } }); |
| 1518 | if (rule.header) { |
| 1519 | conditions.push({ |
| 1520 | httpHeader: { name: rule.header.name, values: rule.header.values }, |
| 1521 | }); |
| 1522 | } |
| 1523 | if (rule.query) conditions.push({ queryString: { values: rule.query } }); |
| 1524 | return conditions; |
| 1525 | }; |
| 1526 | |
| 1527 | /** IP protocols a listener protocol admits through the managed security group. */ |
| 1528 | const sgProtocolsOf = (protocol: string): string[] => |
| 1529 | protocol === "udp" ? ["udp"] : protocol === "tcp_udp" ? ["tcp", "udp"] : ["tcp"]; |
| 1530 | |
| 1531 | interface ManagedSgPort { |
| 1532 | port: number; |
| 1533 | ipProtocol: string; |
| 1534 | } |
| 1535 | |
| 1536 | /** |
| 1537 | * Ingress rules for the managed security group. `dynamicPort` is the main |
| 1538 | * container's port when it is only known as an Output (the `task:` form) — |
| 1539 | * the rule list is then computed at resolve time so ports can be deduped. |
| 1540 | */ |
| 1541 | const managedSgIngress = ( |
| 1542 | staticPorts: ManagedSgPort[], |
| 1543 | dynamicPort: unknown, |
| 1544 | ): SecurityGroupRuleData[] => { |
| 1545 | const rulesOf = (entries: ManagedSgPort[]): SecurityGroupRuleData[] => { |
| 1546 | const seen = new Set<string>(); |
| 1547 | return entries.flatMap(({ port, ipProtocol }) => { |
| 1548 | const dedupeKey = `${ipProtocol}:${port}`; |
| 1549 | if (seen.has(dedupeKey)) { |
| 1550 | return []; |
| 1551 | } |
| 1552 | seen.add(dedupeKey); |
| 1553 | return [ |
| 1554 | { |
| 1555 | ipProtocol, |
| 1556 | fromPort: port, |
| 1557 | toPort: port, |
| 1558 | cidrIpv4: "0.0.0.0/0", |
| 1559 | description: "Alchemy-managed ECS service ingress", |
| 1560 | }, |
| 1561 | ]; |
| 1562 | }); |
| 1563 | }; |
| 1564 | if (dynamicPort === undefined) { |
| 1565 | return rulesOf(staticPorts); |
| 1566 | } |
| 1567 | if (typeof dynamicPort === "number") { |
| 1568 | return rulesOf([...staticPorts, { port: dynamicPort, ipProtocol: "tcp" }]); |
| 1569 | } |
| 1570 | return Output.map(dynamicPort as Output.Output<number>, (port) => |
| 1571 | rulesOf([...staticPorts, { port, ipProtocol: "tcp" }]), |
| 1572 | ) as unknown as SecurityGroupRuleData[]; |
| 1573 | }; |
| 1574 | |
| 1575 | /** Normalize the {@link ServiceCapacityConfig} sugar into a capacity provider strategy. */ |
| 1576 | const capacityProviderStrategyOf = ( |
| 1577 | capacity: ServiceCapacityConfig, |
| 1578 | ): ecs.CapacityProviderStrategyItem[] => |
| 1579 | capacity === "spot" |
| 1580 | ? [{ capacityProvider: "FARGATE_SPOT", weight: 1 }] |
| 1581 | : [ |
| 1582 | ...(capacity.fargate |
| 1583 | ? [ |
| 1584 | { |
| 1585 | capacityProvider: "FARGATE", |
| 1586 | weight: capacity.fargate.weight, |
| 1587 | base: capacity.fargate.base, |
| 1588 | }, |
| 1589 | ] |
| 1590 | : []), |
| 1591 | ...(capacity.spot |
| 1592 | ? [ |
| 1593 | { |
| 1594 | capacityProvider: "FARGATE_SPOT", |
| 1595 | weight: capacity.spot.weight, |
| 1596 | base: capacity.spot.base, |
| 1597 | }, |
| 1598 | ] |
| 1599 | : []), |
| 1600 | ]; |
| 1601 | |
| 1602 | /** |
| 1603 | * Compose the Cloud Map service for {@link ServicePropsBase.serviceRegistry} |
| 1604 | * and rewrite it into the raw `serviceRegistries` list. |
| 1605 | */ |
| 1606 | const composeServiceRegistry = (id: string, props: ServiceProps) => |
| 1607 | Effect.gen(function* () { |
| 1608 | const registry = props.serviceRegistry!; |
| 1609 | const namespace = registry.namespace; |
| 1610 | const isHttpNamespace = |
| 1611 | typeof namespace === "object" && |
| 1612 | namespace !== null && |
| 1613 | "Type" in namespace && |
| 1614 | (namespace as { Type?: unknown }).Type === "AWS.CloudMap.HttpNamespace"; |
| 1615 | const cloudMapService = yield* CloudMapService("ServiceRegistry", { |
| 1616 | namespaceId: namespace.namespaceId, |
| 1617 | dnsRecords: isHttpNamespace |
| 1618 | ? undefined |
| 1619 | : [ |
| 1620 | registry.port !== undefined |
| 1621 | ? { type: "SRV", ttl: "10 seconds" } |
| 1622 | : { type: "A", ttl: "10 seconds" }, |
| 1623 | ], |
| 1624 | tags: props.tags, |
| 1625 | }); |
| 1626 | return { |
| 1627 | ...props, |
| 1628 | serviceRegistry: undefined, |
| 1629 | serviceRegistries: [ |
| 1630 | ...(props.serviceRegistries ?? []), |
| 1631 | { |
| 1632 | registryArn: cloudMapService.serviceArn as unknown as string, |
| 1633 | port: registry.port, |
| 1634 | }, |
| 1635 | ], |
| 1636 | } as ServiceProps; |
| 1637 | }); |
| 1638 | |
| 1639 | /** |
| 1640 | * The `transformProps` hook: normalize the `capacity` sugar, then — when |
| 1641 | * service discovery or managed load balancing is requested — compose the |
| 1642 | * Cloud Map / ELBv2 (and security group) child resources under the service's |
| 1643 | * namespace and rewrite the props to reference their outputs (the internal |
| 1644 | * `ingress` prop and `serviceRegistries`). A no-op at runtime. |
| 1645 | */ |
| 1646 | const transformServiceProps = ( |
| 1647 | id: string, |
| 1648 | props: ServiceProps, |
| 1649 | ): Effect.Effect<ServiceProps, unknown, any> => |
| 1650 | Effect.gen(function* () { |
| 1651 | // Composition is a plan/deploy concern — never runs inside bundles. |
| 1652 | if (globalThis.__ALCHEMY_RUNTIME__) { |
| 1653 | return props; |
| 1654 | } |
| 1655 | let next: ServiceProps = props; |
| 1656 | if (next.capacity !== undefined) { |
| 1657 | next = { |
| 1658 | ...next, |
| 1659 | capacityProviderStrategy: |
| 1660 | next.capacityProviderStrategy ?? capacityProviderStrategyOf(next.capacity), |
| 1661 | capacity: undefined, |
| 1662 | }; |
| 1663 | } |
| 1664 | const lbProp = |
| 1665 | next.loadBalancer !== undefined ? next.loadBalancer : ((next.public ?? false) as boolean); |
| 1666 | const wantsIngress = lbProp !== false && lbProp !== undefined; |
| 1667 | if (!wantsIngress && next.serviceRegistry === undefined) { |
| 1668 | return next; |
| 1669 | } |
| 1670 | return yield* Effect.gen(function* () { |
| 1671 | if (next.serviceRegistry !== undefined) { |
| 1672 | next = yield* composeServiceRegistry(id, next); |
| 1673 | } |
| 1674 | if (wantsIngress) { |
| 1675 | next = yield* composeManagedIngress( |
| 1676 | id, |
| 1677 | next, |
| 1678 | lbProp as true | Listener | ServiceLoadBalancerConfig, |
| 1679 | ); |
| 1680 | } |
| 1681 | return next; |
| 1682 | }).pipe(Namespace.push(id)); |
| 1683 | }); |
| 1684 | |
| 1685 | // Tasks in `host`/`bridge` mode have no ENI of their own. |
| 1686 | const usesAwsvpc = (props: ServiceProps) => |
| 1687 | !("networkMode" in props) || (props.networkMode ?? "awsvpc") === "awsvpc"; |
| 1688 | |
| 1689 | const composeManagedIngress = ( |
| 1690 | id: string, |
| 1691 | props: ServiceProps, |
| 1692 | lbProp: true | Listener | ServiceLoadBalancerConfig, |
| 1693 | ) => |
| 1694 | Effect.gen(function* () { |
| 1695 | const config: ServiceLoadBalancerConfig = |
| 1696 | lbProp === true ? {} : isELBv2Listener(lbProp) ? { listener: lbProp } : lbProp; |
| 1697 | const rules = config.rules ?? (config.listener !== undefined ? [{}] : []); |
| 1698 | |
| 1699 | // ── classify ownership ─────────────────────────────────────────────── |
| 1700 | const hasSharedRefs = |
| 1701 | config.listener !== undefined || rules.some((rule) => isELBv2Listener(rule.listen)); |
| 1702 | const hasOwnedStrings = rules.some((rule) => typeof rule.listen === "string"); |
| 1703 | if (hasSharedRefs && hasOwnedStrings) { |
| 1704 | return yield* new MixedListenerOwnership({ |
| 1705 | serviceId: id, |
| 1706 | message: `AWS.ECS.Service "${id}": rules mix owned "<port>/<protocol>" listen strings with shared ELBv2.Listener references — a service either owns its ALB (strings only) or attaches rules to shared listeners (references only)`, |
| 1707 | }); |
| 1708 | } |
| 1709 | const owned = !hasSharedRefs; |
| 1710 | if (!owned && config.public !== undefined) { |
| 1711 | return yield* new OwnedOnlyLoadBalancerOption({ |
| 1712 | serviceId: id, |
| 1713 | option: "public", |
| 1714 | message: `AWS.ECS.Service "${id}": \`public\` only applies to an owned load balancer — the shared listener's ALB controls its own scheme`, |
| 1715 | }); |
| 1716 | } |
| 1717 | // `true`, a bare `{}`, or an owned config with zero rules: single default |
| 1718 | // listener forwarding to the container port. |
| 1719 | const trueLike = owned && rules.length === 0; |
| 1720 | |
| 1721 | // ── protocol family: ALB (http/https) vs NLB (tcp/udp/tls/tcp_udp) ── |
| 1722 | const families = new Set<"application" | "network">(); |
| 1723 | for (const rule of rules) { |
| 1724 | const specs: [string | Listener | undefined, string][] = [ |
| 1725 | [rule.listen, "listen"], |
| 1726 | [rule.forward, "forward"], |
| 1727 | [rule.redirect, "redirect"], |
| 1728 | ]; |
| 1729 | for (const [spec, kind] of specs) { |
| 1730 | if (typeof spec === "string") { |
| 1731 | const parsed = yield* parseListenSpec(id, spec, kind); |
| 1732 | families.add(NETWORK_PROTOCOLS.has(parsed.protocol) ? "network" : "application"); |
| 1733 | } |
| 1734 | } |
| 1735 | } |
| 1736 | if (families.size > 1) { |
| 1737 | return yield* new MixedLoadBalancerProtocols({ |
| 1738 | serviceId: id, |
| 1739 | message: `AWS.ECS.Service "${id}": rules mix application (http/https) and network (tcp/udp/tls/tcp_udp) protocols — one service composes exactly one load balancer type`, |
| 1740 | }); |
| 1741 | } |
| 1742 | const lbType: "application" | "network" = families.has("network") ? "network" : "application"; |
| 1743 | if (lbType === "network") { |
| 1744 | // NLB listeners route by port alone: no rule conditions, no redirect |
| 1745 | // actions, no attaching rules to shared listeners, and exactly one |
| 1746 | // rule per listener port (it becomes the listener's default action). |
| 1747 | const failNetworkRule = (ruleIndex: number, reason: string) => |
| 1748 | Effect.fail( |
| 1749 | new NetworkListenerRuleUnsupported({ |
| 1750 | serviceId: id, |
| 1751 | ruleIndex, |
| 1752 | message: `AWS.ECS.Service "${id}": rule ${ruleIndex} ${reason}`, |
| 1753 | }), |
| 1754 | ); |
| 1755 | if (!owned) { |
| 1756 | return yield* failNetworkRule( |
| 1757 | 0, |
| 1758 | "uses network (tcp/udp/tls/tcp_udp) protocols with a shared listener — NLB listeners have no rules, so network ingress is always owned", |
| 1759 | ); |
| 1760 | } |
| 1761 | const seenPorts = new Set<number>(); |
| 1762 | for (const [index, rule] of rules.entries()) { |
| 1763 | if (typeof rule.listen !== "string") { |
| 1764 | return yield* failNetworkRule( |
| 1765 | index, |
| 1766 | "must declare an explicit `listen` — network listeners have no default", |
| 1767 | ); |
| 1768 | } |
| 1769 | if (rule.redirect !== undefined) { |
| 1770 | return yield* failNetworkRule(index, "sets `redirect` — NLB listeners cannot redirect"); |
| 1771 | } |
| 1772 | if ( |
| 1773 | rule.path !== undefined || |
| 1774 | rule.host !== undefined || |
| 1775 | rule.header !== undefined || |
| 1776 | rule.query !== undefined |
| 1777 | ) { |
| 1778 | return yield* failNetworkRule( |
| 1779 | index, |
| 1780 | "sets routing conditions — NLB listeners route by port alone", |
| 1781 | ); |
| 1782 | } |
| 1783 | const { port } = yield* parseListenSpec(id, rule.listen, "listen"); |
| 1784 | if (seenPorts.has(port)) { |
| 1785 | return yield* failNetworkRule( |
| 1786 | index, |
| 1787 | `re-declares listener port ${port} — a network listener forwards to exactly one target group`, |
| 1788 | ); |
| 1789 | } |
| 1790 | seenPorts.add(port); |
| 1791 | } |
| 1792 | } |
| 1793 | |
| 1794 | // ── custom domain (owned only): hosted zones + certificate ────────── |
| 1795 | const domain = |
| 1796 | config.domain === undefined |
| 1797 | ? undefined |
| 1798 | : typeof config.domain === "string" |
| 1799 | ? { name: config.domain } |
| 1800 | : config.domain; |
| 1801 | if (domain !== undefined && !owned) { |
| 1802 | return yield* new OwnedOnlyLoadBalancerOption({ |
| 1803 | serviceId: id, |
| 1804 | option: "domain", |
| 1805 | message: `AWS.ECS.Service "${id}": \`domain\` only applies to an owned load balancer — the shared listener's ALB owns its DNS and certificates`, |
| 1806 | }); |
| 1807 | } |
| 1808 | let certificateArn: string | undefined = props.certificateArn; |
| 1809 | const domainNames = domain !== undefined ? [domain.name, ...(domain.aliases ?? [])] : []; |
| 1810 | const domainZones = new Map<string, string>(); |
| 1811 | // Route 53 (the default) needs a matching hosted zone up front; other |
| 1812 | // DNS hosts (e.g. Cloudflare) infer their zone at reconcile time. |
| 1813 | const usesRoute53 = domain !== undefined && isRoute53Dns(domain.dns); |
| 1814 | const pinnedZoneId = domain?.dns?.zone as string | undefined; |
| 1815 | if (domain !== undefined) { |
| 1816 | for (const name of usesRoute53 ? domainNames : []) { |
| 1817 | const zoneId = pinnedZoneId ?? (yield* findPublicHostedZoneId(name)); |
| 1818 | if (zoneId === undefined) { |
| 1819 | return yield* new ServiceHostedZoneNotFound({ |
| 1820 | serviceId: id, |
| 1821 | domainName: name, |
| 1822 | message: `AWS.ECS.Service "${id}": no public Route 53 hosted zone contains '${name}' — create the hosted zone first (alias records land in it)`, |
| 1823 | }); |
| 1824 | } |
| 1825 | domainZones.set(name, zoneId); |
| 1826 | } |
| 1827 | if (domain.cert !== undefined) { |
| 1828 | certificateArn = domain.cert; |
| 1829 | } else { |
| 1830 | // DNS-validated certificate in the service's own region (an ALB/NLB |
| 1831 | // listener requires an in-region certificate). |
| 1832 | const { region } = yield* AWSEnvironment.current; |
| 1833 | const certificate = yield* domainCertificate( |
| 1834 | "Certificate", |
| 1835 | { |
| 1836 | domainName: domain.name, |
| 1837 | subjectAlternativeNames: domain.aliases, |
| 1838 | ...(usesRoute53 ? { hostedZoneId: domainZones.get(domain.name)! } : {}), |
| 1839 | region, |
| 1840 | tags: props.tags, |
| 1841 | }, |
| 1842 | domain.dns, |
| 1843 | ); |
| 1844 | // Resolves once the certificate is issued. |
| 1845 | certificateArn = certificate.certificateArn as unknown as string; |
| 1846 | } |
| 1847 | } |
| 1848 | |
| 1849 | // ── normalize rules + target-group specs ──────────────────────────── |
| 1850 | const byoTask = taskRefOf(props); |
| 1851 | const defaultContainerPort: unknown = |
| 1852 | byoTask !== undefined ? byoTask.port : ((props as { port?: number }).port ?? 3000); |
| 1853 | |
| 1854 | interface TgSpec { |
| 1855 | key: string; |
| 1856 | logicalId: string; |
| 1857 | port: unknown; |
| 1858 | protocol: "HTTP" | "HTTPS" | "TCP" | "UDP" | "TCP_UDP" | "TLS"; |
| 1859 | container: string | undefined; |
| 1860 | forwardPort: number | undefined; |
| 1861 | forwardProtocol: ServiceListenerProtocol | undefined; |
| 1862 | } |
| 1863 | const tgSpecs = new Map<string, TgSpec>(); |
| 1864 | const ensureTgSpec = ( |
| 1865 | forward: ParsedListen | undefined, |
| 1866 | container: string | undefined, |
| 1867 | ): string => { |
| 1868 | const key = `${forward ? `${forward.port}/${forward.protocol}` : "default"}|${container ?? ""}`; |
| 1869 | if (!tgSpecs.has(key)) { |
| 1870 | tgSpecs.set(key, { |
| 1871 | key, |
| 1872 | logicalId: [ |
| 1873 | "TargetGroup", |
| 1874 | forward ? `${forward.port}-${forward.protocol}` : undefined, |
| 1875 | container, |
| 1876 | ] |
| 1877 | .filter((part): part is string => part !== undefined) |
| 1878 | .join("-"), |
| 1879 | port: forward?.port ?? defaultContainerPort, |
| 1880 | protocol: forward |
| 1881 | ? (forward.protocol.toUpperCase() as TgSpec["protocol"]) |
| 1882 | : lbType === "network" |
| 1883 | ? "TCP" |
| 1884 | : "HTTP", |
| 1885 | container, |
| 1886 | forwardPort: forward?.port, |
| 1887 | forwardProtocol: forward?.protocol, |
| 1888 | }); |
| 1889 | } |
| 1890 | return key; |
| 1891 | }; |
| 1892 | |
| 1893 | type NormalizedAction = |
| 1894 | | { type: "forward"; tgKey: string } |
| 1895 | | { type: "redirect"; port: number; protocol: ServiceListenerProtocol }; |
| 1896 | interface NormalizedRule { |
| 1897 | index: number; |
| 1898 | rule: ServiceLoadBalancerRule; |
| 1899 | /** Parsed owned listen spec, shared listener ref, or undefined (default). */ |
| 1900 | listen: ParsedListen | Listener | undefined; |
| 1901 | action: NormalizedAction; |
| 1902 | conditions: ListenerRuleCondition[]; |
| 1903 | } |
| 1904 | const normalized: NormalizedRule[] = []; |
| 1905 | for (const [index, rule] of rules.entries()) { |
| 1906 | if (rule.forward !== undefined && rule.redirect !== undefined) { |
| 1907 | return yield* new ServiceRuleActionConflict({ |
| 1908 | serviceId: id, |
| 1909 | ruleIndex: index, |
| 1910 | message: `AWS.ECS.Service "${id}": rule ${index} sets both \`forward\` and \`redirect\` — they are mutually exclusive`, |
| 1911 | }); |
| 1912 | } |
| 1913 | const listen = |
| 1914 | typeof rule.listen === "string" |
| 1915 | ? yield* parseListenSpec(id, rule.listen, "listen") |
| 1916 | : rule.listen; |
| 1917 | if (!owned && listen === undefined && config.listener === undefined) { |
| 1918 | return yield* new MissingRuleListener({ |
| 1919 | serviceId: id, |
| 1920 | ruleIndex: index, |
| 1921 | message: `AWS.ECS.Service "${id}": rule ${index} has no \`listen\` and the config has no default \`listener\``, |
| 1922 | }); |
| 1923 | } |
| 1924 | const action: NormalizedAction = |
| 1925 | rule.redirect !== undefined |
| 1926 | ? { |
| 1927 | type: "redirect", |
| 1928 | ...(yield* parseListenSpec(id, rule.redirect, "redirect")), |
| 1929 | } |
| 1930 | : { |
| 1931 | type: "forward", |
| 1932 | tgKey: ensureTgSpec( |
| 1933 | rule.forward !== undefined |
| 1934 | ? yield* parseListenSpec(id, rule.forward, "forward") |
| 1935 | : undefined, |
| 1936 | rule.container, |
| 1937 | ), |
| 1938 | }; |
| 1939 | normalized.push({ |
| 1940 | index, |
| 1941 | rule, |
| 1942 | listen, |
| 1943 | action, |
| 1944 | conditions: ruleConditionsOf(rule), |
| 1945 | }); |
| 1946 | } |
| 1947 | if (trueLike) { |
| 1948 | ensureTgSpec(undefined, undefined); |
| 1949 | } |
| 1950 | |
| 1951 | // ── owned listener specs ──────────────────────────────────────────── |
| 1952 | // Network rules always declare an explicit `listen` (validated above), |
| 1953 | // so the implicit default listener is application-only. |
| 1954 | const defaultOwnedListen: ParsedListen = { |
| 1955 | port: props.listenerPort ?? (certificateArn !== undefined ? 443 : 80), |
| 1956 | protocol: certificateArn !== undefined ? "https" : "http", |
| 1957 | }; |
| 1958 | const ownedListenSpecs = new Map<number, ParsedListen>(); |
| 1959 | if (owned) { |
| 1960 | if (trueLike || normalized.some((r) => r.listen === undefined)) { |
| 1961 | ownedListenSpecs.set(defaultOwnedListen.port, defaultOwnedListen); |
| 1962 | } |
| 1963 | for (const r of normalized) { |
| 1964 | if (r.listen !== undefined && !isELBv2Listener(r.listen)) { |
| 1965 | const spec = r.listen as ParsedListen; |
| 1966 | const existing = ownedListenSpecs.get(spec.port); |
| 1967 | if (existing !== undefined && existing.protocol !== spec.protocol) { |
| 1968 | return yield* new UnsupportedListenerProtocol({ |
| 1969 | serviceId: id, |
| 1970 | spec: `${spec.port}/${spec.protocol}`, |
| 1971 | message: `AWS.ECS.Service "${id}": port ${spec.port} is declared with both "${existing.protocol}" and "${spec.protocol}" — one protocol per listener port`, |
| 1972 | }); |
| 1973 | } |
| 1974 | ownedListenSpecs.set(spec.port, spec); |
| 1975 | } |
| 1976 | } |
| 1977 | for (const spec of ownedListenSpecs.values()) { |
| 1978 | if ( |
| 1979 | (spec.protocol === "https" || spec.protocol === "tls") && |
| 1980 | certificateArn === undefined |
| 1981 | ) { |
| 1982 | return yield* new MissingListenerCertificate({ |
| 1983 | serviceId: id, |
| 1984 | spec: `${spec.port}/${spec.protocol}`, |
| 1985 | message: `AWS.ECS.Service "${id}": listener "${spec.port}/${spec.protocol}" requires a certificate — pass \`certificateArn\` or a \`domain\``, |
| 1986 | }); |
| 1987 | } |
| 1988 | } |
| 1989 | } |
| 1990 | |
| 1991 | /** The owned listener port a rule attaches to. */ |
| 1992 | const ownedPortOf = (r: NormalizedRule): number => |
| 1993 | r.listen !== undefined && !isELBv2Listener(r.listen) |
| 1994 | ? (r.listen as ParsedListen).port |
| 1995 | : defaultOwnedListen.port; |
| 1996 | |
| 1997 | // ── network (VPC for TGs + SG, subnets for an owned ALB) ──────────── |
| 1998 | const network = |
| 1999 | props.vpcId !== undefined && props.subnets !== undefined |
| 2000 | ? { vpcId: props.vpcId, subnets: props.subnets } |
| 2001 | : yield* lookupDefaultNetwork; |
| 2002 | |
| 2003 | // ── managed security group ────────────────────────────────────────── |
| 2004 | const staticPorts: ManagedSgPort[] = [ |
| 2005 | ...(owned |
| 2006 | ? [...ownedListenSpecs.values()].flatMap((spec) => |
| 2007 | sgProtocolsOf(spec.protocol).map((ipProtocol) => ({ |
| 2008 | port: spec.port, |
| 2009 | ipProtocol, |
| 2010 | })), |
| 2011 | ) |
| 2012 | : []), |
| 2013 | ...[...tgSpecs.values()].flatMap((spec) => |
| 2014 | spec.forwardPort !== undefined |
| 2015 | ? sgProtocolsOf(spec.forwardProtocol ?? "tcp").map((ipProtocol) => ({ |
| 2016 | port: spec.forwardPort!, |
| 2017 | ipProtocol, |
| 2018 | })) |
| 2019 | : [], |
| 2020 | ), |
| 2021 | ]; |
| 2022 | const usesDefaultPort = [...tgSpecs.values()].some((spec) => spec.forwardPort === undefined); |
| 2023 | const managedSg = props.securityGroups |
| 2024 | ? undefined |
| 2025 | : yield* SecurityGroup("SecurityGroup", { |
| 2026 | vpcId: network.vpcId as VpcId, |
| 2027 | description: `Alchemy-managed ingress for ECS service ${id}`, |
| 2028 | ingress: managedSgIngress( |
| 2029 | staticPorts, |
| 2030 | usesDefaultPort ? defaultContainerPort : undefined, |
| 2031 | ), |
| 2032 | tags: props.tags, |
| 2033 | }); |
| 2034 | |
| 2035 | // ── target groups (one per distinct forward + container pair) ─────── |
| 2036 | // Per-TG health overrides are keyed by the target's "{port}/{protocol}" |
| 2037 | // spec: the rule's `forward` spec, or the container port + the LB |
| 2038 | // type's default protocol for the default target group. |
| 2039 | const healthOverrides = config.health ?? {}; |
| 2040 | const healthKeyOf = (spec: TgSpec): string | undefined => { |
| 2041 | const protocol = spec.forwardProtocol ?? (lbType === "network" ? "tcp" : "http"); |
| 2042 | const port = |
| 2043 | spec.forwardPort ?? |
| 2044 | (typeof defaultContainerPort === "number" ? defaultContainerPort : undefined); |
| 2045 | return port === undefined ? undefined : `${port}/${protocol}`; |
| 2046 | }; |
| 2047 | const matchedHealthKeys = new Set<string>(); |
| 2048 | const targetGroups = new Map<string, TargetGroup>(); |
| 2049 | for (const spec of tgSpecs.values()) { |
| 2050 | const healthKey = healthKeyOf(spec); |
| 2051 | const health = healthKey !== undefined ? healthOverrides[healthKey] : undefined; |
| 2052 | if (healthKey !== undefined && health !== undefined) { |
| 2053 | matchedHealthKeys.add(healthKey); |
| 2054 | } |
| 2055 | const isNetworkTg = |
| 2056 | spec.protocol === "TCP" || |
| 2057 | spec.protocol === "UDP" || |
| 2058 | spec.protocol === "TCP_UDP" || |
| 2059 | spec.protocol === "TLS"; |
| 2060 | // A path/successCodes override on a network target group opts its |
| 2061 | // health check into HTTP; otherwise NLB targets get TCP checks. |
| 2062 | const wantsHttpCheck = health?.path !== undefined || health?.successCodes !== undefined; |
| 2063 | targetGroups.set( |
| 2064 | spec.key, |
| 2065 | yield* TargetGroup(spec.logicalId, { |
| 2066 | vpcId: network.vpcId as string, |
| 2067 | port: spec.port as number, |
| 2068 | protocol: spec.protocol, |
| 2069 | targetType: usesAwsvpc(props) ? "ip" : "instance", |
| 2070 | healthCheckPath: isNetworkTg |
| 2071 | ? wantsHttpCheck |
| 2072 | ? (health?.path ?? "/") |
| 2073 | : undefined |
| 2074 | : (health?.path ?? props.healthCheckPath ?? "/"), |
| 2075 | healthCheckProtocol: isNetworkTg && wantsHttpCheck ? "HTTP" : undefined, |
| 2076 | // Fast-converge defaults: targets go healthy in ~20s instead of |
| 2077 | // the AWS default ~150s, and drain in 30s instead of 300s. |
| 2078 | healthCheckInterval: health?.interval ?? "10 seconds", |
| 2079 | healthCheckTimeout: health?.timeout, |
| 2080 | healthyThresholdCount: health?.healthyThreshold ?? 2, |
| 2081 | unhealthyThresholdCount: health?.unhealthyThreshold ?? 2, |
| 2082 | matcher: |
| 2083 | health?.successCodes !== undefined ? { HttpCode: health.successCodes } : undefined, |
| 2084 | attributes: { "deregistration_delay.timeout_seconds": "30" }, |
| 2085 | tags: props.tags, |
| 2086 | }), |
| 2087 | ); |
| 2088 | } |
| 2089 | for (const key of Object.keys(healthOverrides)) { |
| 2090 | if (!matchedHealthKeys.has(key)) { |
| 2091 | const validKeys = [...tgSpecs.values()] |
| 2092 | .map(healthKeyOf) |
| 2093 | .filter((candidate): candidate is string => candidate !== undefined); |
| 2094 | return yield* new ServiceHealthTargetNotFound({ |
| 2095 | serviceId: id, |
| 2096 | key, |
| 2097 | message: `AWS.ECS.Service "${id}": \`health\` key '${key}' matches no target group — valid keys: ${validKeys.length > 0 ? validKeys.join(", ") : "(none statically derivable)"}`, |
| 2098 | }); |
| 2099 | } |
| 2100 | } |
| 2101 | |
| 2102 | const actionToListenerAction = (action: NormalizedAction): ListenerAction => |
| 2103 | action.type === "redirect" |
| 2104 | ? { |
| 2105 | type: "redirect", |
| 2106 | statusCode: "HTTP_301", |
| 2107 | protocol: action.protocol.toUpperCase(), |
| 2108 | port: String(action.port), |
| 2109 | } |
| 2110 | : { |
| 2111 | type: "forward", |
| 2112 | targetGroups: [ |
| 2113 | { |
| 2114 | targetGroupArn: targetGroups.get(action.tgKey)! |
| 2115 | .targetGroupArn as unknown as TargetGroupArn, |
| 2116 | }, |
| 2117 | ], |
| 2118 | }; |
| 2119 | |
| 2120 | // ── owned ALB + listeners ─────────────────────────────────────────── |
| 2121 | let alb: LoadBalancer | undefined; |
| 2122 | const ownedListeners = new Map<number, Listener>(); |
| 2123 | /** Rules absorbed into a listener's default action (no ListenerRule). */ |
| 2124 | const defaultsTaken = new Set<NormalizedRule>(); |
| 2125 | if (owned) { |
| 2126 | alb = yield* LoadBalancer("LoadBalancer", { |
| 2127 | type: lbType, |
| 2128 | scheme: config.public === false ? "internal" : "internet-facing", |
| 2129 | subnets: (props.subnets ?? network.subnets) as unknown as SubnetId[], |
| 2130 | securityGroups: (props.securityGroups ?? [ |
| 2131 | managedSg!.groupId, |
| 2132 | ]) as unknown as SecurityGroupId[], |
| 2133 | tags: props.tags, |
| 2134 | }); |
| 2135 | for (const spec of ownedListenSpecs.values()) { |
| 2136 | // Default action: the first conditionless rule on this listener |
| 2137 | // wins; the `true`-like form forwards to the sole target group; |
| 2138 | // otherwise unmatched requests get a 404. |
| 2139 | const conditionless = normalized.find( |
| 2140 | (r) => r.conditions.length === 0 && ownedPortOf(r) === spec.port, |
| 2141 | ); |
| 2142 | if (conditionless) { |
| 2143 | defaultsTaken.add(conditionless); |
| 2144 | } |
| 2145 | const defaultActions: ListenerAction[] = conditionless |
| 2146 | ? [actionToListenerAction(conditionless.action)] |
| 2147 | : trueLike |
| 2148 | ? [ |
| 2149 | { |
| 2150 | type: "forward", |
| 2151 | targetGroups: [ |
| 2152 | { |
| 2153 | targetGroupArn: targetGroups.get("default|")! |
| 2154 | .targetGroupArn as unknown as TargetGroupArn, |
| 2155 | }, |
| 2156 | ], |
| 2157 | }, |
| 2158 | ] |
| 2159 | : [ |
| 2160 | { |
| 2161 | type: "fixedResponse", |
| 2162 | statusCode: "404", |
| 2163 | contentType: "text/plain", |
| 2164 | messageBody: "Not Found", |
| 2165 | }, |
| 2166 | ]; |
| 2167 | ownedListeners.set( |
| 2168 | spec.port, |
| 2169 | yield* Listener(`Listener-${spec.port}`, { |
| 2170 | loadBalancerArn: alb.loadBalancerArn as any, |
| 2171 | port: spec.port, |
| 2172 | protocol: spec.protocol.toUpperCase() as |
| 2173 | | "HTTP" |
| 2174 | | "HTTPS" |
| 2175 | | "TCP" |
| 2176 | | "UDP" |
| 2177 | | "TCP_UDP" |
| 2178 | | "TLS", |
| 2179 | certificateArn: |
| 2180 | spec.protocol === "https" || spec.protocol === "tls" ? certificateArn : undefined, |
| 2181 | defaultActions, |
| 2182 | }), |
| 2183 | ); |
| 2184 | } |
| 2185 | } |
| 2186 | |
| 2187 | // ── domain: alias records pointing at the owned load balancer ─────── |
| 2188 | if (domain !== undefined && alb !== undefined) { |
| 2189 | for (const name of domainNames) { |
| 2190 | const sanitizedName = name.replaceAll(/[^a-zA-Z0-9-]/g, "-"); |
| 2191 | const dns = yield* resolveDomainDns( |
| 2192 | usesRoute53 ? undefined : domain.dns, |
| 2193 | domainZones.get(name), |
| 2194 | ); |
| 2195 | // Route 53: alias `A` + `AAAA` (`Domain-{name}-A` / `-AAAA`); |
| 2196 | // other hosts: a single CNAME to the load balancer. |
| 2197 | yield* dns.alias(`Domain-${sanitizedName}`, { |
| 2198 | name, |
| 2199 | ipv6: true, |
| 2200 | target: { |
| 2201 | hostname: alb.dnsName, |
| 2202 | route53Alias: { |
| 2203 | hostedZoneId: alb.canonicalHostedZoneId, |
| 2204 | evaluateTargetHealth: false, |
| 2205 | }, |
| 2206 | }, |
| 2207 | }); |
| 2208 | } |
| 2209 | } |
| 2210 | |
| 2211 | // ── listener rules ────────────────────────────────────────────────── |
| 2212 | const chain = yield* Namespace.CurrentChain; |
| 2213 | const namespacePrefix = [...chain].reverse().join("/"); |
| 2214 | for (const r of normalized) { |
| 2215 | if (defaultsTaken.has(r)) { |
| 2216 | continue; |
| 2217 | } |
| 2218 | const ruleId = `Rule-${r.index}`; |
| 2219 | // A conditionless rule still needs at least one ELBv2 condition — use |
| 2220 | // the catch-all path (this is also the bare-listener default rule). |
| 2221 | const conditions = |
| 2222 | r.conditions.length > 0 ? r.conditions : [{ pathPattern: { values: ["/*"] } }]; |
| 2223 | const ruleListener = owned |
| 2224 | ? ownedListeners.get(ownedPortOf(r))! |
| 2225 | : isELBv2Listener(r.listen) |
| 2226 | ? r.listen |
| 2227 | : config.listener!; |
| 2228 | const priority = r.rule.priority ?? deriveRulePriority(`${namespacePrefix}/${ruleId}`); |
| 2229 | yield* ListenerRule(ruleId, { |
| 2230 | listenerArn: ruleListener.listenerArn as any, |
| 2231 | priority, |
| 2232 | conditions, |
| 2233 | actions: [actionToListenerAction(r.action)], |
| 2234 | tags: props.tags, |
| 2235 | }); |
| 2236 | } |
| 2237 | |
| 2238 | // ── primary listener (attrs + URL derivation) ─────────────────────── |
| 2239 | const primary = owned |
| 2240 | ? (() => { |
| 2241 | const spec = |
| 2242 | ownedListenSpecs.get(defaultOwnedListen.port) ?? [...ownedListenSpecs.values()][0]; |
| 2243 | const listener = ownedListeners.get(spec.port)!; |
| 2244 | return { |
| 2245 | listenerArn: listener.listenerArn, |
| 2246 | loadBalancerArn: alb!.loadBalancerArn, |
| 2247 | port: spec.port as unknown, |
| 2248 | protocol: spec.protocol.toUpperCase() as unknown, |
| 2249 | }; |
| 2250 | })() |
| 2251 | : (() => { |
| 2252 | const ref = |
| 2253 | config.listener ?? (normalized.map((r) => r.listen).find(isELBv2Listener) as Listener); |
| 2254 | return { |
| 2255 | listenerArn: ref.listenerArn, |
| 2256 | loadBalancerArn: ref.loadBalancerArn, |
| 2257 | port: ref.port as unknown, |
| 2258 | protocol: ref.protocol as unknown, |
| 2259 | }; |
| 2260 | })(); |
| 2261 | |
| 2262 | const ingress: ServiceManagedIngress = { |
| 2263 | kind: owned ? "owned" : "shared", |
| 2264 | loadBalancerArn: primary.loadBalancerArn as unknown as string, |
| 2265 | listenerArn: primary.listenerArn as unknown as string, |
| 2266 | listenerPort: primary.port as number, |
| 2267 | listenerProtocol: primary.protocol as string, |
| 2268 | securityGroupId: managedSg?.groupId as unknown as string | undefined, |
| 2269 | domain: domain?.name, |
| 2270 | targets: [...tgSpecs.values()].map((spec) => ({ |
| 2271 | targetGroupArn: targetGroups.get(spec.key)!.targetGroupArn as unknown as string, |
| 2272 | containerPort: spec.forwardPort, |
| 2273 | container: spec.container, |
| 2274 | })), |
| 2275 | }; |
| 2276 | |
| 2277 | return { |
| 2278 | ...props, |
| 2279 | loadBalancer: undefined, |
| 2280 | public: undefined, |
| 2281 | ingress, |
| 2282 | } as ServiceProps; |
| 2283 | }); |
| 2284 | |
| 2285 | // ─────────────────────────────────────────────────────────────────────────── |
| 2286 | // Autoscaling — composition (the `onCreate` hook) |
| 2287 | // ─────────────────────────────────────────────────────────────────────────── |
| 2288 | |
| 2289 | /** |
| 2290 | * Compose the Application Auto Scaling resources for the `scaling` prop: |
| 2291 | * a `ScalableTarget` bounding the service's desired count plus one |
| 2292 | * target-tracking `ScalingPolicy` per declared metric. Runs as the |
| 2293 | * platform's `onCreate` hook (AFTER the service resource is declared) |
| 2294 | * because the scalable target's `resourceId` and the request-count metric's |
| 2295 | * `ResourceLabel` are derived from the service's own Output attributes. |
| 2296 | */ |
| 2297 | const composeServiceScaling = ( |
| 2298 | service: Service, |
| 2299 | props: ServiceProps | undefined, |
| 2300 | ): Effect.Effect<void, unknown, any> => |
| 2301 | Effect.gen(function* () { |
| 2302 | // Composition is a plan/deploy concern — never runs inside bundles. |
| 2303 | if (globalThis.__ALCHEMY_RUNTIME__) { |
| 2304 | return; |
| 2305 | } |
| 2306 | const scaling = props?.scaling; |
| 2307 | if (scaling === undefined) { |
| 2308 | return; |
| 2309 | } |
| 2310 | const id = service.LogicalId; |
| 2311 | if ( |
| 2312 | scaling.requestCount !== undefined && |
| 2313 | props?.loadBalancer === undefined && |
| 2314 | props?.public === undefined && |
| 2315 | props?.ingress === undefined |
| 2316 | ) { |
| 2317 | return yield* new RequestCountScalingRequiresLoadBalancer({ |
| 2318 | serviceId: id, |
| 2319 | message: `AWS.ECS.Service "${id}": \`scaling.requestCount\` tracks ALBRequestCountPerTarget, which needs a managed target group — set \`loadBalancer\``, |
| 2320 | }); |
| 2321 | } |
| 2322 | yield* Effect.gen(function* () { |
| 2323 | const clusterName = Output.map( |
| 2324 | service.clusterArn as unknown as Output.Output<string>, |
| 2325 | (arn) => arn.split("/").pop()!, |
| 2326 | ); |
| 2327 | const min = scaling.min ?? 1; |
| 2328 | const max = scaling.max ?? min; |
| 2329 | const target = yield* ScalableTarget("ScalableTarget", { |
| 2330 | serviceNamespace: "ecs", |
| 2331 | resourceId: |
| 2332 | Output.interpolate`service/${clusterName}/${service.serviceName}` as unknown as string, |
| 2333 | scalableDimension: "ecs:service:DesiredCount", |
| 2334 | minCapacity: min, |
| 2335 | maxCapacity: max, |
| 2336 | tags: props?.tags, |
| 2337 | }); |
| 2338 | // Reference the target's outputs so policies deploy after (and are |
| 2339 | // destroyed before) the scalable target. |
| 2340 | const policyBase = { |
| 2341 | serviceNamespace: "ecs" as const, |
| 2342 | resourceId: target.resourceId as unknown as string, |
| 2343 | scalableDimension: "ecs:service:DesiredCount" as const, |
| 2344 | }; |
| 2345 | const cooldowns = { |
| 2346 | ScaleInCooldown: toWireSeconds(scaling.scaleInCooldown), |
| 2347 | ScaleOutCooldown: toWireSeconds(scaling.scaleOutCooldown), |
| 2348 | }; |
| 2349 | if (scaling.cpuUtilization !== undefined) { |
| 2350 | yield* ScalingPolicy("CpuScaling", { |
| 2351 | ...policyBase, |
| 2352 | targetTracking: { |
| 2353 | TargetValue: scaling.cpuUtilization, |
| 2354 | PredefinedMetricSpecification: { |
| 2355 | PredefinedMetricType: "ECSServiceAverageCPUUtilization", |
| 2356 | }, |
| 2357 | ...cooldowns, |
| 2358 | }, |
| 2359 | }); |
| 2360 | } |
| 2361 | if (scaling.memoryUtilization !== undefined) { |
| 2362 | yield* ScalingPolicy("MemoryScaling", { |
| 2363 | ...policyBase, |
| 2364 | targetTracking: { |
| 2365 | TargetValue: scaling.memoryUtilization, |
| 2366 | PredefinedMetricSpecification: { |
| 2367 | PredefinedMetricType: "ECSServiceAverageMemoryUtilization", |
| 2368 | }, |
| 2369 | ...cooldowns, |
| 2370 | }, |
| 2371 | }); |
| 2372 | } |
| 2373 | if (scaling.requestCount !== undefined) { |
| 2374 | // ALBRequestCountPerTarget's ResourceLabel is |
| 2375 | // `app/{lb-name}/{lb-id}/targetgroup/{tg-name}/{tg-id}` — both |
| 2376 | // halves parsed from the managed-ingress ARNs on the service. |
| 2377 | const loadBalancerPart = Output.map( |
| 2378 | service.loadBalancerArn as unknown as Output.Output<string>, |
| 2379 | (arn) => arn.slice(arn.indexOf("loadbalancer/") + "loadbalancer/".length), |
| 2380 | ); |
| 2381 | const targetGroupPart = Output.map( |
| 2382 | service.targetGroupArn as unknown as Output.Output<string>, |
| 2383 | (arn) => arn.slice(arn.indexOf("targetgroup/")), |
| 2384 | ); |
| 2385 | yield* ScalingPolicy("RequestCountScaling", { |
| 2386 | ...policyBase, |
| 2387 | targetTracking: { |
| 2388 | TargetValue: scaling.requestCount, |
| 2389 | PredefinedMetricSpecification: { |
| 2390 | PredefinedMetricType: "ALBRequestCountPerTarget", |
| 2391 | ResourceLabel: |
| 2392 | Output.interpolate`${loadBalancerPart}/${targetGroupPart}` as unknown as string, |
| 2393 | }, |
| 2394 | ...cooldowns, |
| 2395 | }, |
| 2396 | }); |
| 2397 | } |
| 2398 | }).pipe(Namespace.push(id)); |
| 2399 | }); |
| 2400 | |
| 2401 | // ─────────────────────────────────────────────────────────────────────────── |
| 2402 | // Task-definition sugar (secrets / logging / volumes) — helpers |
| 2403 | // ─────────────────────────────────────────────────────────────────────────── |
| 2404 | |
| 2405 | const SECRETS_POLICY_NAME = "alchemy-secrets"; |
| 2406 | |
| 2407 | /** |
| 2408 | * Sync the execution role's inline secrets-read policy to exactly the |
| 2409 | * SSM parameter / Secrets Manager ARNs referenced by the `secrets` prop |
| 2410 | * (deleted when no secrets remain). |
| 2411 | */ |
| 2412 | const syncTaskSecretsPolicy = Effect.fn(function* ({ |
| 2413 | roleName, |
| 2414 | secretArns, |
| 2415 | }: { |
| 2416 | roleName: string; |
| 2417 | secretArns: string[]; |
| 2418 | }) { |
| 2419 | if (secretArns.length === 0) { |
| 2420 | yield* iam |
| 2421 | .deleteRolePolicy({ |
| 2422 | RoleName: roleName, |
| 2423 | PolicyName: SECRETS_POLICY_NAME, |
| 2424 | }) |
| 2425 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 2426 | return; |
| 2427 | } |
| 2428 | const serviceOf = (arn: string) => arn.split(":")[2]; |
| 2429 | const ssmArns = secretArns.filter((arn) => serviceOf(arn) === "ssm"); |
| 2430 | const secretsManagerArns = secretArns.filter((arn) => serviceOf(arn) === "secretsmanager"); |
| 2431 | yield* iam.putRolePolicy({ |
| 2432 | RoleName: roleName, |
| 2433 | PolicyName: SECRETS_POLICY_NAME, |
| 2434 | PolicyDocument: JSON.stringify({ |
| 2435 | Version: "2012-10-17", |
| 2436 | Statement: [ |
| 2437 | ...(ssmArns.length > 0 |
| 2438 | ? [ |
| 2439 | { |
| 2440 | Effect: "Allow", |
| 2441 | Action: ["ssm:GetParameters"], |
| 2442 | Resource: ssmArns, |
| 2443 | }, |
| 2444 | ] |
| 2445 | : []), |
| 2446 | ...(secretsManagerArns.length > 0 |
| 2447 | ? [ |
| 2448 | { |
| 2449 | Effect: "Allow", |
| 2450 | Action: ["secretsmanager:GetSecretValue"], |
| 2451 | Resource: secretsManagerArns, |
| 2452 | }, |
| 2453 | ] |
| 2454 | : []), |
| 2455 | ], |
| 2456 | }), |
| 2457 | }); |
| 2458 | }); |
| 2459 | |
| 2460 | /** |
| 2461 | * Desugar the `volumes` prop: raw {@link ecs.Volume} entries pass through; |
| 2462 | * `{ efs, path }` entries become an EFS task volume (transit encryption |
| 2463 | * enabled, access-point auth when given) plus a primary-container mount |
| 2464 | * point at `path`. |
| 2465 | */ |
| 2466 | const resolveServiceVolumes = ( |
| 2467 | volumes: (ecs.Volume | ServiceEfsVolume)[] | undefined, |
| 2468 | ): { volumes: ecs.Volume[]; mountPoints: ecs.MountPoint[] } => { |
| 2469 | const resolved: ecs.Volume[] = []; |
| 2470 | const mountPoints: ecs.MountPoint[] = []; |
| 2471 | for (const [index, volume] of (volumes ?? []).entries()) { |
| 2472 | if ("efs" in volume) { |
| 2473 | const efs = volume.efs; |
| 2474 | const fileSystemId = "fileSystemId" in efs ? efs.fileSystemId : efs.fileSystem.fileSystemId; |
| 2475 | const accessPointId = "fileSystemId" in efs ? undefined : efs.accessPoint?.accessPointId; |
| 2476 | const name = `efs-${index}`; |
| 2477 | resolved.push({ |
| 2478 | name, |
| 2479 | efsVolumeConfiguration: { |
| 2480 | fileSystemId, |
| 2481 | transitEncryption: "ENABLED", |
| 2482 | authorizationConfig: accessPointId !== undefined ? { accessPointId } : undefined, |
| 2483 | }, |
| 2484 | }); |
| 2485 | mountPoints.push({ sourceVolume: name, containerPath: volume.path }); |
| 2486 | } else { |
| 2487 | resolved.push(volume); |
| 2488 | } |
| 2489 | } |
| 2490 | return { volumes: resolved, mountPoints }; |
| 2491 | }; |
| 2492 | |
| 2493 | type ServiceConvergenceDependencies = Credentials | HttpClient | Region; |
| 2494 | |
| 2495 | interface ServiceConvergenceSnapshot { |
| 2496 | readonly service: ecs.Service | undefined; |
| 2497 | readonly targetGroups: readonly { |
| 2498 | readonly missing: boolean; |
| 2499 | readonly states: readonly (string | undefined)[]; |
| 2500 | }[]; |
| 2501 | readonly converged: boolean; |
| 2502 | } |
| 2503 | |
| 2504 | type ServiceConvergenceMode = "stable" | "drained" | "deleted"; |
| 2505 | |
| 2506 | /** |
| 2507 | * Observe the complete service deployment boundary: ECS rollout state, |
| 2508 | * desired/running/pending counts, superseded deployments, and every target |
| 2509 | * group's registered target state. |
| 2510 | */ |
| 2511 | const observeServiceConvergence = (input: { |
| 2512 | clusterArn: string; |
| 2513 | serviceName: string; |
| 2514 | expectedTaskDefinitionArn?: string; |
| 2515 | expectedDeploymentId?: string; |
| 2516 | mode: ServiceConvergenceMode; |
| 2517 | }): Effect.Effect< |
| 2518 | ServiceConvergenceSnapshot, |
| 2519 | ecs.DescribeServicesError | elbv2.DescribeTargetHealthError, |
| 2520 | ServiceConvergenceDependencies |
| 2521 | > => |
| 2522 | Effect.gen(function* () { |
| 2523 | const described = yield* ecs |
| 2524 | .describeServices({ |
| 2525 | cluster: input.clusterArn, |
| 2526 | services: [input.serviceName], |
| 2527 | }) |
| 2528 | .pipe(Effect.catchTag("ClusterNotFoundException", () => Effect.undefined)); |
| 2529 | const service = described?.services?.find( |
| 2530 | (candidate) => candidate.serviceName === input.serviceName && candidate.status !== "INACTIVE", |
| 2531 | ); |
| 2532 | |
| 2533 | if (service === undefined) { |
| 2534 | return { |
| 2535 | service, |
| 2536 | targetGroups: [], |
| 2537 | converged: input.mode === "drained" || input.mode === "deleted", |
| 2538 | }; |
| 2539 | } |
| 2540 | |
| 2541 | const targetGroupArns = [ |
| 2542 | ...new Set( |
| 2543 | (service.loadBalancers ?? []).flatMap((loadBalancer) => |
| 2544 | loadBalancer.targetGroupArn ? [loadBalancer.targetGroupArn] : [], |
| 2545 | ), |
| 2546 | ), |
| 2547 | ]; |
| 2548 | const targetGroups = yield* Effect.forEach( |
| 2549 | targetGroupArns, |
| 2550 | (targetGroupArn) => |
| 2551 | elbv2.describeTargetHealth({ TargetGroupArn: targetGroupArn }).pipe( |
| 2552 | Effect.map((health) => ({ |
| 2553 | missing: false, |
| 2554 | states: (health.TargetHealthDescriptions ?? []).map( |
| 2555 | (target) => target.TargetHealth?.State, |
| 2556 | ), |
| 2557 | })), |
| 2558 | Effect.catchTag("TargetGroupNotFoundException", () => |
| 2559 | Effect.succeed({ |
| 2560 | missing: true, |
| 2561 | states: [] as (string | undefined)[], |
| 2562 | }), |
| 2563 | ), |
| 2564 | ), |
| 2565 | { concurrency: 4 }, |
| 2566 | ); |
| 2567 | |
| 2568 | if (input.mode === "deleted") { |
| 2569 | return { service, targetGroups, converged: false }; |
| 2570 | } |
| 2571 | |
| 2572 | const runningCount = service.runningCount ?? 0; |
| 2573 | const pendingCount = service.pendingCount ?? 0; |
| 2574 | const desiredCount = service.desiredCount ?? 0; |
| 2575 | const expectedTargetCount = |
| 2576 | service.schedulingStrategy === "DAEMON" ? runningCount : desiredCount; |
| 2577 | |
| 2578 | if (input.mode === "drained") { |
| 2579 | return { |
| 2580 | service, |
| 2581 | targetGroups, |
| 2582 | converged: |
| 2583 | runningCount === 0 && |
| 2584 | pendingCount === 0 && |
| 2585 | targetGroups.every( |
| 2586 | (targetGroup) => targetGroup.missing || targetGroup.states.length === 0, |
| 2587 | ), |
| 2588 | }; |
| 2589 | } |
| 2590 | |
| 2591 | const deployments = service.deployments ?? []; |
| 2592 | const primary = deployments.find((deployment) => deployment.status === "PRIMARY"); |
| 2593 | const deploymentController = service.deploymentController?.type ?? "ECS"; |
| 2594 | const countsConverged = |
| 2595 | service.schedulingStrategy === "DAEMON" |
| 2596 | ? pendingCount === 0 |
| 2597 | : runningCount === desiredCount && pendingCount === 0; |
| 2598 | const deploymentConverged = |
| 2599 | deployments.length === 1 && |
| 2600 | primary !== undefined && |
| 2601 | (input.expectedDeploymentId === undefined || primary.id === input.expectedDeploymentId) && |
| 2602 | primary.taskDefinition === input.expectedTaskDefinitionArn && |
| 2603 | (deploymentController === "ECS" |
| 2604 | ? primary.rolloutState === "COMPLETED" |
| 2605 | : primary.rolloutState === undefined || primary.rolloutState === "COMPLETED"); |
| 2606 | const targetsConverged = targetGroups.every( |
| 2607 | (targetGroup) => |
| 2608 | !targetGroup.missing && |
| 2609 | targetGroup.states.length === expectedTargetCount && |
| 2610 | targetGroup.states.every((state) => state === "healthy"), |
| 2611 | ); |
| 2612 | |
| 2613 | return { |
| 2614 | service, |
| 2615 | targetGroups, |
| 2616 | converged: |
| 2617 | service.status === "ACTIVE" && |
| 2618 | service.taskDefinition === input.expectedTaskDefinitionArn && |
| 2619 | countsConverged && |
| 2620 | deploymentConverged && |
| 2621 | targetsConverged, |
| 2622 | }; |
| 2623 | }); |
| 2624 | |
| 2625 | const waitForServiceConvergence = (input: { |
| 2626 | clusterArn: string; |
| 2627 | serviceName: string; |
| 2628 | expectedTaskDefinitionArn?: string; |
| 2629 | expectedDeploymentId?: string; |
| 2630 | mode: ServiceConvergenceMode; |
| 2631 | timeout?: Duration.Input; |
| 2632 | }): Effect.Effect< |
| 2633 | ServiceConvergenceSnapshot, |
| 2634 | ecs.DescribeServicesError | elbv2.DescribeTargetHealthError | ServiceDidNotStabilize, |
| 2635 | ServiceConvergenceDependencies |
| 2636 | > => { |
| 2637 | const pollIntervalMillis = 5_000; |
| 2638 | const timeoutMillis = Math.min(toMillis(input.timeout ?? "10 minutes")!, 30 * 60 * 1_000); |
| 2639 | const attempts = Math.max(1, Math.ceil(timeoutMillis / pollIntervalMillis)); |
| 2640 | const expectedDeploymentFailed = (snapshot: ServiceConvergenceSnapshot) => |
| 2641 | input.mode === "stable" && |
| 2642 | snapshot.service?.deployments?.some( |
| 2643 | (deployment) => |
| 2644 | (input.expectedDeploymentId !== undefined |
| 2645 | ? deployment.id === input.expectedDeploymentId |
| 2646 | : deployment.status === "PRIMARY" && |
| 2647 | deployment.taskDefinition === input.expectedTaskDefinitionArn) && |
| 2648 | deployment.rolloutState === "FAILED", |
| 2649 | ) === true; |
| 2650 | |
| 2651 | return observeServiceConvergence(input).pipe( |
| 2652 | Effect.repeat({ |
| 2653 | schedule: Schedule.max([Schedule.spaced(pollIntervalMillis), Schedule.recurs(attempts)]), |
| 2654 | until: (snapshot) => snapshot.converged || expectedDeploymentFailed(snapshot), |
| 2655 | }), |
| 2656 | Effect.flatMap((snapshot) => { |
| 2657 | if (snapshot.converged) { |
| 2658 | return Effect.succeed(snapshot); |
| 2659 | } |
| 2660 | const service = snapshot.service; |
| 2661 | const expectedTargetCount = |
| 2662 | service?.schedulingStrategy === "DAEMON" |
| 2663 | ? (service.runningCount ?? 0) |
| 2664 | : (service?.desiredCount ?? 0); |
| 2665 | const unhealthyTargetCount = snapshot.targetGroups.reduce( |
| 2666 | (total, targetGroup) => |
| 2667 | total + |
| 2668 | (targetGroup.missing |
| 2669 | ? Math.max(1, expectedTargetCount) |
| 2670 | : targetGroup.states.filter((state) => state !== "healthy").length + |
| 2671 | Math.abs(targetGroup.states.length - expectedTargetCount)), |
| 2672 | 0, |
| 2673 | ); |
| 2674 | return Effect.fail( |
| 2675 | new ServiceDidNotStabilize({ |
| 2676 | clusterArn: input.clusterArn, |
| 2677 | serviceName: input.serviceName, |
| 2678 | expectedTaskDefinitionArn: input.expectedTaskDefinitionArn, |
| 2679 | status: service?.status, |
| 2680 | desiredCount: service?.desiredCount, |
| 2681 | runningCount: service?.runningCount, |
| 2682 | pendingCount: service?.pendingCount, |
| 2683 | deploymentCount: service?.deployments?.length ?? 0, |
| 2684 | unhealthyTargetCount, |
| 2685 | message: expectedDeploymentFailed(snapshot) |
| 2686 | ? `ECS service ${input.serviceName} reported a failed deployment` |
| 2687 | : `ECS service ${input.serviceName} did not become ${input.mode} before timeout`, |
| 2688 | }), |
| 2689 | ); |
| 2690 | }), |
| 2691 | ); |
| 2692 | }; |
| 2693 | |
| 2694 | /** Keep image resolution, drift detection and dev watching on the same inputs. */ |
| 2695 | export const serviceImageInput = (props: ServiceProps) => { |
| 2696 | const imageProps = props as ImageOwningServicePropsBase; |
| 2697 | const source = props as ImageSourceLike; |
| 2698 | return { |
| 2699 | source, |
| 2700 | platform: taskImagePlatform(imageProps.runtimePlatform), |
| 2701 | port: imageProps.port, |
| 2702 | isExternal: imageProps.isExternal, |
| 2703 | bootstrap: makeBunBootstrap(source.handler ?? "default"), |
| 2704 | }; |
| 2705 | }; |
| 2706 | |
| 2707 | export const ServiceProvider = () => |
| 2708 | Provider.effect( |
| 2709 | Service, |
| 2710 | Effect.gen(function* () { |
| 2711 | const stack = yield* Stack; |
| 2712 | const imageSource = yield* makeImageSource; |
| 2713 | |
| 2714 | const alchemyEnv = { |
| 2715 | ALCHEMY_STACK_NAME: stack.name, |
| 2716 | ALCHEMY_STAGE: stack.stage, |
| 2717 | ALCHEMY_PHASE: "runtime", |
| 2718 | }; |
| 2719 | |
| 2720 | // Derive the cluster ARN from either form of the `cluster` prop. May |
| 2721 | // legitimately receive `undefined`: a `creating` state row persisted |
| 2722 | // before upstream Outputs resolved can't round-trip an Output-valued |
| 2723 | // `cluster` (it deserializes as `undefined`), and recovery paths hand |
| 2724 | // those props back as `olds`. |
| 2725 | const clusterArnOf = ( |
| 2726 | cluster: ServiceProps["cluster"] | ClusterArn | undefined, |
| 2727 | ): ClusterArn | undefined => |
| 2728 | typeof cluster === "string" |
| 2729 | ? (cluster as ClusterArn) |
| 2730 | : typeof (cluster as { clusterArn?: unknown } | undefined)?.clusterArn === "string" |
| 2731 | ? ((cluster as { clusterArn: string }).clusterArn as ClusterArn) |
| 2732 | : undefined; |
| 2733 | const toEcsTags = (tags: Record<string, string>): ecs.Tag[] => |
| 2734 | Object.entries(tags).map(([key, value]) => ({ key, value })); |
| 2735 | |
| 2736 | const toServiceName = (id: string, props: { serviceName?: string } = {}) => |
| 2737 | props.serviceName |
| 2738 | ? Effect.succeed(props.serviceName) |
| 2739 | : createPhysicalName({ |
| 2740 | id, |
| 2741 | maxLength: 255, |
| 2742 | lowercase: true, |
| 2743 | }); |
| 2744 | |
| 2745 | // ── networking ──────────────────────────────────────────────────── |
| 2746 | |
| 2747 | /** |
| 2748 | * Resolve the VPC + subnets the service runs in. Explicit props win; |
| 2749 | * otherwise fall back to the account's default VPC and its per-AZ |
| 2750 | * default subnets (public — so `assignPublicIp` then defaults to true |
| 2751 | * to allow image pulls without a NAT). |
| 2752 | */ |
| 2753 | const resolveNetwork = Effect.fn(function* (news: { |
| 2754 | vpcId?: string; |
| 2755 | subnets?: string[]; |
| 2756 | assignPublicIp?: boolean; |
| 2757 | }) { |
| 2758 | if (news.vpcId !== undefined && news.subnets !== undefined) { |
| 2759 | return { |
| 2760 | vpcId: news.vpcId, |
| 2761 | subnets: news.subnets, |
| 2762 | assignPublicIp: news.assignPublicIp ?? false, |
| 2763 | }; |
| 2764 | } |
| 2765 | const network = yield* lookupDefaultNetwork; |
| 2766 | return { |
| 2767 | vpcId: network.vpcId, |
| 2768 | subnets: news.subnets ?? network.subnets, |
| 2769 | assignPublicIp: news.assignPublicIp ?? true, |
| 2770 | }; |
| 2771 | }); |
| 2772 | |
| 2773 | // ── managed ingress (composed ELBv2 resources) ──────────────────── |
| 2774 | |
| 2775 | /** |
| 2776 | * Best-effort public URL for managed ingress: resolve the (owned or |
| 2777 | * shared) load balancer's DNS name and combine it with the primary |
| 2778 | * listener's protocol/port. Returns undefined when not derivable. |
| 2779 | */ |
| 2780 | const deriveIngressUrl = Effect.fn(function* (ingress: ServiceManagedIngress | undefined) { |
| 2781 | // A custom domain wins: it aliases the load balancer and carries |
| 2782 | // the listener's protocol/port. |
| 2783 | if (ingress?.domain !== undefined) { |
| 2784 | const domainProtocol = (ingress.listenerProtocol ?? "HTTPS").toLowerCase(); |
| 2785 | const domainPort = ingress.listenerPort; |
| 2786 | const isWellKnownPort = |
| 2787 | domainPort === undefined || |
| 2788 | (domainProtocol === "http" && domainPort === 80) || |
| 2789 | (domainProtocol === "https" && domainPort === 443); |
| 2790 | return `${domainProtocol}://${ingress.domain}${isWellKnownPort ? "" : `:${domainPort}`}`; |
| 2791 | } |
| 2792 | if (!ingress?.loadBalancerArn) { |
| 2793 | return undefined; |
| 2794 | } |
| 2795 | const described = yield* elbv2 |
| 2796 | .describeLoadBalancers({ |
| 2797 | LoadBalancerArns: [ingress.loadBalancerArn], |
| 2798 | }) |
| 2799 | .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.undefined)); |
| 2800 | const dnsName = described?.LoadBalancers?.[0]?.DNSName; |
| 2801 | if (!dnsName) { |
| 2802 | return undefined; |
| 2803 | } |
| 2804 | // Works unchanged against the local emulator: floci's ALB DNS |
| 2805 | // (`*.elb.localhost.floci.io`) resolves to 127.0.0.1 and its data |
| 2806 | // plane serves each listener on the listener's own port, which |
| 2807 | // `ensureFloci` publishes on the managed container (80/443). |
| 2808 | const protocol = (ingress.listenerProtocol ?? "HTTP").toLowerCase(); |
| 2809 | const port = ingress.listenerPort; |
| 2810 | const isDefaultPort = |
| 2811 | port === undefined || |
| 2812 | (protocol === "http" && port === 80) || |
| 2813 | (protocol === "https" && port === 443); |
| 2814 | return `${protocol}://${dnsName}${isDefaultPort ? "" : `:${port}`}`; |
| 2815 | }); |
| 2816 | |
| 2817 | /** |
| 2818 | * Reap the ALB/TG/listener/security group that the pre-composition |
| 2819 | * provider created INLINE and recorded in the service's own attributes. |
| 2820 | * Those legacy state rows carry the ingress ARNs with no `ingressKind` |
| 2821 | * marker; the composed shape stamps the marker and owns its ingress as |
| 2822 | * real child resources (deleted by the engine, never here). Reaping on |
| 2823 | * the first reconcile under the new shape keeps the breaking redeploy |
| 2824 | * from stranding the old inline infrastructure. |
| 2825 | */ |
| 2826 | const reapLegacyIngress = Effect.fn(function* ({ |
| 2827 | output, |
| 2828 | session, |
| 2829 | }: { |
| 2830 | output: Service["Attributes"] | undefined; |
| 2831 | session: { note: (message: string) => Effect.Effect<void> }; |
| 2832 | }) { |
| 2833 | if (!output || output.ingressKind !== undefined) { |
| 2834 | return; |
| 2835 | } |
| 2836 | if ( |
| 2837 | !output.listenerArn && |
| 2838 | !output.targetGroupArn && |
| 2839 | !output.loadBalancerArn && |
| 2840 | !output.securityGroupId |
| 2841 | ) { |
| 2842 | return; |
| 2843 | } |
| 2844 | yield* session.note( |
| 2845 | "Migrating to composed load balancer resources — deleting the legacy inline ALB/TG/listener", |
| 2846 | ); |
| 2847 | if (output.listenerArn) { |
| 2848 | yield* elbv2 |
| 2849 | .deleteListener({ ListenerArn: output.listenerArn }) |
| 2850 | .pipe(Effect.catchTag("ListenerNotFoundException", () => Effect.void)); |
| 2851 | } |
| 2852 | if (output.targetGroupArn) { |
| 2853 | yield* elbv2.deleteTargetGroup({ TargetGroupArn: output.targetGroupArn }).pipe( |
| 2854 | Effect.retry({ |
| 2855 | while: (e) => e._tag === "ResourceInUseException", |
| 2856 | schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(8)]), |
| 2857 | }), |
| 2858 | Effect.catch(() => Effect.void), |
| 2859 | ); |
| 2860 | } |
| 2861 | if (output.loadBalancerArn) { |
| 2862 | yield* elbv2 |
| 2863 | .deleteLoadBalancer({ LoadBalancerArn: output.loadBalancerArn }) |
| 2864 | .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.void)); |
| 2865 | } |
| 2866 | if (output.securityGroupId) { |
| 2867 | // The old ALB/service ENIs release the group asynchronously; retry |
| 2868 | // bounded, then give up with a note rather than fail the migration |
| 2869 | // deploy. |
| 2870 | yield* ec2.deleteSecurityGroup({ GroupId: output.securityGroupId }).pipe( |
| 2871 | Effect.catchTag("InvalidGroup.NotFound", () => Effect.void), |
| 2872 | Effect.retry({ |
| 2873 | while: (e) => e._tag === "DependencyViolation", |
| 2874 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(24)]), |
| 2875 | }), |
| 2876 | Effect.catchTag("DependencyViolation", () => |
| 2877 | session.note( |
| 2878 | "Legacy ingress security group still has attached ENIs; leaving it to release asynchronously", |
| 2879 | ), |
| 2880 | ), |
| 2881 | ); |
| 2882 | } |
| 2883 | }); |
| 2884 | |
| 2885 | // ── task definition synthesis (image-owning forms) ──────────────── |
| 2886 | |
| 2887 | /** |
| 2888 | * Synthesize (or roll) the service-owned task definition from the |
| 2889 | * image source + `TaskDefinitionConfig` surface. Mirrors the |
| 2890 | * `AWS.ECS.Task` reconcile flow. |
| 2891 | */ |
| 2892 | const synthesizeTaskDefinition = Effect.fn(function* ({ |
| 2893 | id, |
| 2894 | news, |
| 2895 | output, |
| 2896 | bindings, |
| 2897 | tags, |
| 2898 | session, |
| 2899 | }: { |
| 2900 | id: string; |
| 2901 | news: BundledServiceProps | DockerfileServiceProps | ImageServiceProps; |
| 2902 | output: Service["Attributes"] | undefined; |
| 2903 | bindings: Parameters<typeof attachTaskBindings>[0]["bindings"]; |
| 2904 | tags: Record<string, string>; |
| 2905 | session: { note: (message: string) => Effect.Effect<void> }; |
| 2906 | }) { |
| 2907 | const family = |
| 2908 | output?.taskFamily ?? |
| 2909 | (yield* createPhysicalName({ |
| 2910 | id: `${id}-task`, |
| 2911 | maxLength: 255, |
| 2912 | lowercase: true, |
| 2913 | })); |
| 2914 | const taskRoleName = |
| 2915 | output?.taskRoleName ?? |
| 2916 | (yield* createPhysicalName({ |
| 2917 | id: `${id}-task-role`, |
| 2918 | maxLength: 64, |
| 2919 | })); |
| 2920 | const executionRoleName = |
| 2921 | output?.executionRoleName ?? |
| 2922 | (yield* createPhysicalName({ |
| 2923 | id: `${id}-execution-role`, |
| 2924 | maxLength: 64, |
| 2925 | })); |
| 2926 | const taskPolicyName = yield* createPhysicalName({ |
| 2927 | id: `${id}-task-policy`, |
| 2928 | maxLength: 128, |
| 2929 | }); |
| 2930 | const repositoryName = |
| 2931 | output?.repositoryName ?? |
| 2932 | (yield* createPhysicalName({ |
| 2933 | id: `${id}-repo`, |
| 2934 | maxLength: 256, |
| 2935 | lowercase: true, |
| 2936 | })); |
| 2937 | const logGroupName = |
| 2938 | output?.logGroupName ?? |
| 2939 | (yield* createPhysicalName({ |
| 2940 | id: `${id}-logs`, |
| 2941 | maxLength: 512, |
| 2942 | lowercase: true, |
| 2943 | })); |
| 2944 | |
| 2945 | const taskRoleArn = |
| 2946 | output?.taskRoleArn ?? (yield* createTaskRoleIfNotExists({ id, roleName: taskRoleName })); |
| 2947 | |
| 2948 | // `taskRoleManagedPolicyArns` is part of the inherited |
| 2949 | // `TaskDefinitionConfig` surface — attach it like the standalone |
| 2950 | // Task provider does (its sibling `executionRoleManagedPolicyArns` |
| 2951 | // is already honored below). `attachRolePolicy` is idempotent for |
| 2952 | // already-attached ARNs; a `LimitExceededException` means the |
| 2953 | // policy was NOT attached, so it propagates and fails the deploy |
| 2954 | // rather than silently shipping a role with missing permissions. |
| 2955 | yield* Effect.forEach( |
| 2956 | news.taskRoleManagedPolicyArns ?? [], |
| 2957 | (policyArn) => |
| 2958 | iam.attachRolePolicy({ |
| 2959 | RoleName: taskRoleName, |
| 2960 | PolicyArn: policyArn, |
| 2961 | }), |
| 2962 | { concurrency: "unbounded" }, |
| 2963 | ); |
| 2964 | |
| 2965 | const executionRoleArn = |
| 2966 | output?.executionRoleArn ?? |
| 2967 | (yield* ensureTaskExecutionRole({ |
| 2968 | id, |
| 2969 | roleName: executionRoleName, |
| 2970 | managedPolicyArns: news.executionRoleManagedPolicyArns, |
| 2971 | })); |
| 2972 | |
| 2973 | const { |
| 2974 | env: bindingEnv, |
| 2975 | volumes: bindingVolumes, |
| 2976 | mountPoints: bindingMountPoints, |
| 2977 | } = yield* attachTaskBindings({ |
| 2978 | roleName: taskRoleName, |
| 2979 | policyName: taskPolicyName, |
| 2980 | bindings, |
| 2981 | }); |
| 2982 | |
| 2983 | // Secrets: container `secrets` (valueFrom) + the execution role's |
| 2984 | // read permissions on exactly the referenced ARNs. |
| 2985 | const secretEntries = Object.entries(news.secrets ?? {}); |
| 2986 | yield* syncTaskSecretsPolicy({ |
| 2987 | roleName: executionRoleName, |
| 2988 | secretArns: secretEntries.map(([, arn]) => arn), |
| 2989 | }); |
| 2990 | |
| 2991 | // Environment files: the execution role reads the referenced S3 |
| 2992 | // objects at task start. |
| 2993 | yield* syncEnvironmentFilesPolicy({ |
| 2994 | roleName: executionRoleName, |
| 2995 | environmentFiles: news.environmentFiles, |
| 2996 | }); |
| 2997 | |
| 2998 | const logGroupArn = |
| 2999 | output?.logGroupArn ?? (yield* ensureTaskLogGroup({ id, logGroupName })); |
| 3000 | yield* syncLogGroupRetention({ |
| 3001 | logGroupName, |
| 3002 | retention: news.logging?.retention, |
| 3003 | }); |
| 3004 | |
| 3005 | const resolved = yield* imageSource.resolve({ |
| 3006 | ...serviceImageInput(news), |
| 3007 | id, |
| 3008 | repositoryName, |
| 3009 | repositoryUri: |
| 3010 | output?.repositoryUri && output.repositoryName === repositoryName |
| 3011 | ? output.repositoryUri |
| 3012 | : undefined, |
| 3013 | tags, |
| 3014 | session, |
| 3015 | }); |
| 3016 | |
| 3017 | // Desugar `{ efs, path }` volumes into task volumes + primary |
| 3018 | // container mount points, then fold the secrets / container health |
| 3019 | // check sugar into the primary-container overrides. |
| 3020 | const { volumes: resolvedVolumes, mountPoints: efsMountPoints } = resolveServiceVolumes( |
| 3021 | news.volumes, |
| 3022 | ); |
| 3023 | const containerOverrides: Partial<ecs.ContainerDefinition> = { |
| 3024 | ...news.container, |
| 3025 | ...(secretEntries.length > 0 |
| 3026 | ? { |
| 3027 | secrets: [ |
| 3028 | ...(news.container?.secrets ?? []), |
| 3029 | ...secretEntries.map(([name, valueFrom]) => ({ |
| 3030 | name, |
| 3031 | valueFrom, |
| 3032 | })), |
| 3033 | ], |
| 3034 | } |
| 3035 | : {}), |
| 3036 | ...(news.healthCheck !== undefined |
| 3037 | ? { |
| 3038 | healthCheck: { |
| 3039 | command: news.healthCheck.command, |
| 3040 | interval: toWireSeconds(news.healthCheck.interval), |
| 3041 | timeout: toWireSeconds(news.healthCheck.timeout), |
| 3042 | retries: news.healthCheck.retries, |
| 3043 | startPeriod: toWireSeconds(news.healthCheck.startPeriod), |
| 3044 | }, |
| 3045 | } |
| 3046 | : {}), |
| 3047 | ...(efsMountPoints.length > 0 |
| 3048 | ? { |
| 3049 | mountPoints: [...(news.container?.mountPoints ?? []), ...efsMountPoints], |
| 3050 | } |
| 3051 | : {}), |
| 3052 | }; |
| 3053 | |
| 3054 | const taskDefinition = yield* registerTaskDefinitionRevision({ |
| 3055 | props: { |
| 3056 | ...news, |
| 3057 | placementConstraints: news.taskPlacementConstraints, |
| 3058 | volumes: resolvedVolumes.length > 0 ? resolvedVolumes : undefined, |
| 3059 | container: containerOverrides, |
| 3060 | env: { |
| 3061 | ...bindingEnv, |
| 3062 | ...alchemyEnv, |
| 3063 | ...news.env, |
| 3064 | }, |
| 3065 | }, |
| 3066 | family, |
| 3067 | imageUri: resolved.imageUri, |
| 3068 | taskRoleArn, |
| 3069 | executionRoleArn, |
| 3070 | logGroupName, |
| 3071 | tags, |
| 3072 | bindingVolumes, |
| 3073 | bindingMountPoints, |
| 3074 | }); |
| 3075 | |
| 3076 | yield* syncTaskDefinitionTags({ |
| 3077 | revisionArn: taskDefinition.taskDefinitionArn!, |
| 3078 | tags, |
| 3079 | }); |
| 3080 | |
| 3081 | const containerName = taskDefinition.containerDefinitions?.[0]?.name ?? family; |
| 3082 | return { |
| 3083 | taskDefinitionArn: taskDefinition.taskDefinitionArn!, |
| 3084 | taskFamily: family, |
| 3085 | containerName, |
| 3086 | port: news.port ?? 3000, |
| 3087 | imageUri: resolved.imageUri, |
| 3088 | repositoryName: resolved.repositoryName, |
| 3089 | repositoryUri: resolved.repositoryUri, |
| 3090 | taskRoleArn, |
| 3091 | taskRoleName, |
| 3092 | executionRoleArn, |
| 3093 | executionRoleName, |
| 3094 | logGroupName, |
| 3095 | logGroupArn, |
| 3096 | code: { hash: resolved.codeHash }, |
| 3097 | }; |
| 3098 | }); |
| 3099 | |
| 3100 | const networkConfigurationOf = ( |
| 3101 | network: { |
| 3102 | subnets: string[]; |
| 3103 | assignPublicIp: boolean; |
| 3104 | }, |
| 3105 | securityGroups: string[] | undefined, |
| 3106 | ) => ({ |
| 3107 | awsvpcConfiguration: { |
| 3108 | subnets: network.subnets, |
| 3109 | securityGroups, |
| 3110 | assignPublicIp: (network.assignPublicIp ? "ENABLED" : "DISABLED") as |
| 3111 | | "ENABLED" |
| 3112 | | "DISABLED", |
| 3113 | }, |
| 3114 | }); |
| 3115 | |
| 3116 | // load balancers passed to create/update: explicit user-supplied list |
| 3117 | // plus the composed managed-ingress target groups. |
| 3118 | const loadBalancersOf = ( |
| 3119 | news: ServiceProps, |
| 3120 | task: { containerName: string; port: number }, |
| 3121 | ): ecs.LoadBalancer[] | undefined => { |
| 3122 | const managed: ecs.LoadBalancer[] = (news.ingress?.targets ?? []).map((target) => ({ |
| 3123 | targetGroupArn: target.targetGroupArn, |
| 3124 | containerName: target.container ?? task.containerName, |
| 3125 | containerPort: target.containerPort ?? task.port, |
| 3126 | })); |
| 3127 | const all = [...(news.loadBalancers ?? []), ...managed]; |
| 3128 | return all.length > 0 ? all : undefined; |
| 3129 | }; |
| 3130 | |
| 3131 | // In-place mutable fields shared by createService and updateService. |
| 3132 | const mutableInput = ( |
| 3133 | news: ServiceProps, |
| 3134 | task: { taskDefinitionArn: string }, |
| 3135 | network: { subnets: string[]; assignPublicIp: boolean }, |
| 3136 | securityGroups: string[] | undefined, |
| 3137 | ) => ({ |
| 3138 | taskDefinition: task.taskDefinitionArn, |
| 3139 | platformVersion: news.platformVersion, |
| 3140 | deploymentConfiguration: news.deploymentConfiguration, |
| 3141 | healthCheckGracePeriodSeconds: toWireSeconds(news.healthCheckGracePeriod), |
| 3142 | networkConfiguration: usesAwsvpc(news) |
| 3143 | ? networkConfigurationOf(network, securityGroups) |
| 3144 | : undefined, |
| 3145 | capacityProviderStrategy: news.capacityProviderStrategy, |
| 3146 | placementConstraints: news.placementConstraints, |
| 3147 | placementStrategy: news.placementStrategy, |
| 3148 | enableExecuteCommand: news.enableExecuteCommand, |
| 3149 | propagateTags: news.propagateTags, |
| 3150 | availabilityZoneRebalancing: news.availabilityZoneRebalancing, |
| 3151 | serviceConnectConfiguration: news.serviceConnectConfiguration, |
| 3152 | volumeConfigurations: news.volumeConfigurations, |
| 3153 | // launchType and capacityProviderStrategy are mutually exclusive; |
| 3154 | // only send launchType when no strategy is provided. |
| 3155 | launchType: news.capacityProviderStrategy ? undefined : (news.launchType ?? "FARGATE"), |
| 3156 | }); |
| 3157 | |
| 3158 | return { |
| 3159 | stables: ["serviceArn", "serviceName", "clusterArn"], |
| 3160 | diff: Effect.fn(function* ({ id, olds, news, output }) { |
| 3161 | if (!isResolved(news)) return; |
| 3162 | // serviceName change → delete-first replace (name is the identity). |
| 3163 | if ((yield* toServiceName(id, olds ?? {})) !== (yield* toServiceName(id, news ?? {}))) { |
| 3164 | return { action: "replace", deleteFirst: true } as const; |
| 3165 | } |
| 3166 | // cluster change → replace (a service can't move clusters). Only |
| 3167 | // when both sides are known — a half-created state row may have |
| 3168 | // lost an Output-valued `cluster` (see `clusterArnOf`), and an |
| 3169 | // unknown old cluster must fall through to the create/update |
| 3170 | // recovery path rather than force a replacement. |
| 3171 | const oldClusterArn = clusterArnOf(olds?.cluster); |
| 3172 | const newClusterArn = clusterArnOf(news.cluster); |
| 3173 | if ( |
| 3174 | oldClusterArn !== undefined && |
| 3175 | newClusterArn !== undefined && |
| 3176 | oldClusterArn !== newClusterArn |
| 3177 | ) { |
| 3178 | return { action: "replace", deleteFirst: true } as const; |
| 3179 | } |
| 3180 | // Truly-immutable post-create fields. Everything else (desiredCount, |
| 3181 | // taskDefinition, network, deployment config, placement, loadBalancers, |
| 3182 | // exec, tags, …) is applied in place by `updateService`. |
| 3183 | if ( |
| 3184 | olds !== undefined && |
| 3185 | !deepEqual( |
| 3186 | { |
| 3187 | // launchType ↔ capacityProviderStrategy switch is immutable. |
| 3188 | usesStrategy: !!olds.capacityProviderStrategy, |
| 3189 | schedulingStrategy: olds.schedulingStrategy ?? "REPLICA", |
| 3190 | deploymentControllerType: olds.deploymentController?.type ?? "ECS", |
| 3191 | enableECSManagedTags: olds.enableECSManagedTags ?? true, |
| 3192 | role: olds.role, |
| 3193 | }, |
| 3194 | { |
| 3195 | usesStrategy: !!news.capacityProviderStrategy, |
| 3196 | schedulingStrategy: news.schedulingStrategy ?? "REPLICA", |
| 3197 | deploymentControllerType: news.deploymentController?.type ?? "ECS", |
| 3198 | enableECSManagedTags: news.enableECSManagedTags ?? true, |
| 3199 | role: news.role, |
| 3200 | }, |
| 3201 | ) |
| 3202 | ) { |
| 3203 | return { action: "replace", deleteFirst: true } as const; |
| 3204 | } |
| 3205 | // Content drift for image-owning sources: props don't change when |
| 3206 | // the files under `context`/`main` do, so hash the source at plan |
| 3207 | // time (`main` runs the bundler, covering the bootstrap entry) and |
| 3208 | // surface drift as an update; without this a bootstrap or code-only |
| 3209 | // change would silently no-op until `--force`. |
| 3210 | if (output?.code && taskRefOf(news) === undefined) { |
| 3211 | const hash = yield* imageSource.hash(serviceImageInput(news)); |
| 3212 | if (hash !== undefined && hash !== output.code.hash) { |
| 3213 | return { action: "update" } as const; |
| 3214 | } |
| 3215 | } |
| 3216 | }), |
| 3217 | read: Effect.fn(function* ({ id, olds, output }) { |
| 3218 | const clusterArn = output?.clusterArn ?? clusterArnOf(olds?.cluster); |
| 3219 | if (clusterArn === undefined) { |
| 3220 | // No attributes and no recoverable cluster from the persisted |
| 3221 | // props (an Output-valued `cluster` doesn't survive a |
| 3222 | // `creating`-state round-trip). We can't locate the service, so |
| 3223 | // report "not found" — the engine re-drives the create and |
| 3224 | // reconcile converges on any half-created service by name. |
| 3225 | return undefined; |
| 3226 | } |
| 3227 | const serviceName = output?.serviceName ?? (yield* toServiceName(id, olds ?? {})); |
| 3228 | const described = yield* ecs |
| 3229 | .describeServices({ |
| 3230 | cluster: clusterArn, |
| 3231 | services: [serviceName], |
| 3232 | include: ["TAGS"], |
| 3233 | }) |
| 3234 | .pipe(Effect.catchTag("ClusterNotFoundException", () => Effect.undefined)); |
| 3235 | const service = described?.services?.[0]; |
| 3236 | if (!service?.serviceArn) { |
| 3237 | return undefined; |
| 3238 | } |
| 3239 | return { |
| 3240 | ...output!, |
| 3241 | serviceArn: service.serviceArn as ServiceArn, |
| 3242 | serviceName: service.serviceName!, |
| 3243 | clusterArn: service.clusterArn as ClusterArn, |
| 3244 | taskDefinitionArn: service.taskDefinition!, |
| 3245 | status: service.status ?? "ACTIVE", |
| 3246 | configuration: observeServiceConfiguration(service, olds, ecsTagRecord(service.tags)), |
| 3247 | }; |
| 3248 | }), |
| 3249 | list: () => |
| 3250 | Effect.gen(function* () { |
| 3251 | // ECS services are scoped to a cluster, so enumerate every cluster |
| 3252 | // first, then list services per cluster, then hydrate via |
| 3253 | // describeServices (which accepts up to 10 services per call). |
| 3254 | const clusterArns = yield* ecs.listClusters.pages({}).pipe( |
| 3255 | Stream.runCollect, |
| 3256 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.clusterArns ?? [])), |
| 3257 | ); |
| 3258 | |
| 3259 | const perCluster = yield* Effect.forEach( |
| 3260 | clusterArns, |
| 3261 | (clusterArn) => |
| 3262 | Effect.gen(function* () { |
| 3263 | const serviceArns = yield* ecs.listServices.pages({ cluster: clusterArn }).pipe( |
| 3264 | Stream.runCollect, |
| 3265 | Effect.map((chunk) => |
| 3266 | Array.from(chunk).flatMap((page) => page.serviceArns ?? []), |
| 3267 | ), |
| 3268 | Effect.catchTag("ClusterNotFoundException", () => |
| 3269 | Effect.succeed([] as string[]), |
| 3270 | ), |
| 3271 | ); |
| 3272 | if (serviceArns.length === 0) { |
| 3273 | return [] as Service["Attributes"][]; |
| 3274 | } |
| 3275 | |
| 3276 | const batches: string[][] = []; |
| 3277 | for (let i = 0; i < serviceArns.length; i += 10) { |
| 3278 | batches.push(serviceArns.slice(i, i + 10)); |
| 3279 | } |
| 3280 | |
| 3281 | const described = yield* Effect.forEach( |
| 3282 | batches, |
| 3283 | (services) => |
| 3284 | ecs.describeServices({ cluster: clusterArn, services }).pipe( |
| 3285 | Effect.map((res) => res.services ?? []), |
| 3286 | Effect.catchTag("ClusterNotFoundException", () => |
| 3287 | Effect.succeed([] as ecs.Service[]), |
| 3288 | ), |
| 3289 | ), |
| 3290 | { concurrency: 4 }, |
| 3291 | ); |
| 3292 | |
| 3293 | return described.flat().flatMap((service) => |
| 3294 | service.serviceArn && service.status !== "INACTIVE" |
| 3295 | ? [ |
| 3296 | { |
| 3297 | serviceArn: service.serviceArn as ServiceArn, |
| 3298 | serviceName: service.serviceName!, |
| 3299 | clusterArn: service.clusterArn as ClusterArn, |
| 3300 | taskDefinitionArn: service.taskDefinition!, |
| 3301 | status: service.status ?? "ACTIVE", |
| 3302 | } satisfies Service["Attributes"], |
| 3303 | ] |
| 3304 | : [], |
| 3305 | ); |
| 3306 | }), |
| 3307 | { concurrency: 5 }, |
| 3308 | ); |
| 3309 | |
| 3310 | return perCluster.flat(); |
| 3311 | }), |
| 3312 | reconcile: Effect.fn(function* ({ id, news, olds, output, bindings, session }) { |
| 3313 | const serviceName = yield* toServiceName(id, news); |
| 3314 | const clusterArn = clusterArnOf(news.cluster) as ClusterArn; |
| 3315 | const desiredTags = { |
| 3316 | ...(yield* createInternalTags(id)), |
| 3317 | ...news.tags, |
| 3318 | }; |
| 3319 | |
| 3320 | // Resolve the task definition: BYO reference, or synthesize the |
| 3321 | // service-owned definition from the image source. |
| 3322 | const byoTask = taskRefOf(news); |
| 3323 | const owned = |
| 3324 | byoTask === undefined |
| 3325 | ? yield* synthesizeTaskDefinition({ |
| 3326 | id, |
| 3327 | news: news as BundledServiceProps | DockerfileServiceProps | ImageServiceProps, |
| 3328 | output, |
| 3329 | bindings, |
| 3330 | tags: desiredTags, |
| 3331 | session, |
| 3332 | }) |
| 3333 | : undefined; |
| 3334 | const task = byoTask ?? { |
| 3335 | taskDefinitionArn: owned!.taskDefinitionArn, |
| 3336 | containerName: owned!.containerName, |
| 3337 | port: owned!.port, |
| 3338 | }; |
| 3339 | |
| 3340 | // Resolve networking (explicit props or the default VPC). |
| 3341 | const network = yield* resolveNetwork(news); |
| 3342 | |
| 3343 | // Managed ingress: the composed child-resource outputs arrive via |
| 3344 | // the internal `ingress` prop (written by the factory's |
| 3345 | // composition step). The managed security group — when composed — |
| 3346 | // is attached to the service ENIs as well. |
| 3347 | const ingress = news.ingress; |
| 3348 | const securityGroups = |
| 3349 | news.securityGroups ?? |
| 3350 | (ingress?.securityGroupId ? [ingress.securityGroupId] : undefined); |
| 3351 | |
| 3352 | // Observe — describe service in target cluster. The cluster may |
| 3353 | // not yet exist on first reconcile, so we tolerate |
| 3354 | // `ClusterNotFoundException`. |
| 3355 | const described = yield* ecs |
| 3356 | .describeServices({ |
| 3357 | cluster: clusterArn, |
| 3358 | services: [serviceName], |
| 3359 | include: ["TAGS"], |
| 3360 | }) |
| 3361 | .pipe(Effect.catchTag("ClusterNotFoundException", () => Effect.undefined)); |
| 3362 | const observed = described?.services?.find( |
| 3363 | (s) => |
| 3364 | s.serviceName === serviceName && s.status !== "INACTIVE" && s.status !== "DRAINING", |
| 3365 | ); |
| 3366 | |
| 3367 | // Managed-ingress attributes: derived from the composed (or |
| 3368 | // shared) child-resource outputs; the URL comes from the load |
| 3369 | // balancer's DNS name (best-effort). |
| 3370 | const ingressAttrs = { |
| 3371 | url: yield* deriveIngressUrl(ingress), |
| 3372 | loadBalancerArn: ingress?.loadBalancerArn, |
| 3373 | targetGroupArn: ingress?.targets[0]?.targetGroupArn, |
| 3374 | listenerArn: ingress?.listenerArn, |
| 3375 | securityGroupId: ingress?.securityGroupId, |
| 3376 | ingressKind: ingress?.kind, |
| 3377 | }; |
| 3378 | |
| 3379 | const ownedAttributes = { |
| 3380 | taskFamily: owned?.taskFamily, |
| 3381 | containerName: owned?.containerName, |
| 3382 | port: owned?.port, |
| 3383 | imageUri: owned?.imageUri, |
| 3384 | repositoryName: owned?.repositoryName, |
| 3385 | repositoryUri: owned?.repositoryUri, |
| 3386 | taskRoleArn: owned?.taskRoleArn, |
| 3387 | taskRoleName: owned?.taskRoleName, |
| 3388 | executionRoleArn: owned?.executionRoleArn, |
| 3389 | executionRoleName: owned?.executionRoleName, |
| 3390 | logGroupName: owned?.logGroupName, |
| 3391 | logGroupArn: owned?.logGroupArn, |
| 3392 | code: owned?.code, |
| 3393 | }; |
| 3394 | |
| 3395 | if (!observed?.serviceArn) { |
| 3396 | const created = yield* ecs.createService({ |
| 3397 | ...mutableInput(news, task, network, securityGroups), |
| 3398 | // With autoscaling, `desiredCount` is only the initial size |
| 3399 | // (defaulting to `scaling.min`) — the scalable target owns it |
| 3400 | // from then on. |
| 3401 | desiredCount: news.desiredCount ?? news.scaling?.min ?? 1, |
| 3402 | serviceName, |
| 3403 | cluster: clusterArn, |
| 3404 | loadBalancers: loadBalancersOf(news, task), |
| 3405 | serviceRegistries: news.serviceRegistries, |
| 3406 | deploymentController: news.deploymentController, |
| 3407 | schedulingStrategy: news.schedulingStrategy, |
| 3408 | role: news.role, |
| 3409 | tags: toEcsTags(desiredTags), |
| 3410 | enableECSManagedTags: news.enableECSManagedTags ?? true, |
| 3411 | }); |
| 3412 | const service = created.service; |
| 3413 | if (!service?.serviceArn) { |
| 3414 | return yield* Effect.die(new Error("createService returned no service")); |
| 3415 | } |
| 3416 | yield* session.note(`Waiting for ECS service ${serviceName} to stabilize`); |
| 3417 | const stable = yield* waitForServiceConvergence({ |
| 3418 | clusterArn, |
| 3419 | serviceName, |
| 3420 | expectedTaskDefinitionArn: task.taskDefinitionArn, |
| 3421 | expectedDeploymentId: service.deployments?.find( |
| 3422 | (deployment) => deployment.status === "PRIMARY", |
| 3423 | )?.id, |
| 3424 | mode: "stable", |
| 3425 | timeout: news.deploymentStabilizationTimeout, |
| 3426 | }); |
| 3427 | const stableService = stable.service!; |
| 3428 | // Legacy inline ingress recorded in prior attrs (service itself |
| 3429 | // was missing — e.g. recreated) is stale now: reap it. |
| 3430 | yield* reapLegacyIngress({ output, session }); |
| 3431 | // Synthesizing registered a NEW revision; reap the superseded |
| 3432 | // one so revisions don't accumulate ACTIVE forever (same-family |
| 3433 | // guarded — a prior BYO `task:` reference is left untouched). |
| 3434 | if (owned !== undefined) { |
| 3435 | yield* reapSupersededTaskDefinitionRevision({ |
| 3436 | previousArn: output?.taskDefinitionArn, |
| 3437 | nextArn: owned.taskDefinitionArn, |
| 3438 | }); |
| 3439 | } |
| 3440 | yield* session.note(service.serviceArn); |
| 3441 | return { |
| 3442 | serviceArn: stableService.serviceArn as ServiceArn, |
| 3443 | serviceName: stableService.serviceName!, |
| 3444 | clusterArn: stableService.clusterArn as ClusterArn, |
| 3445 | taskDefinitionArn: stableService.taskDefinition!, |
| 3446 | status: stableService.status ?? "ACTIVE", |
| 3447 | configuration: observeServiceConfiguration(stableService, news, desiredTags), |
| 3448 | ...ingressAttrs, |
| 3449 | ...ownedAttributes, |
| 3450 | }; |
| 3451 | } |
| 3452 | |
| 3453 | // Sync — apply in-place mutable fields via updateService. Force a new |
| 3454 | // deployment so a changed task definition (same revision-less ARN) or |
| 3455 | // load-balancer wiring rolls out. |
| 3456 | const updated = yield* ecs |
| 3457 | .updateService({ |
| 3458 | ...mutableInput(news, task, network, securityGroups), |
| 3459 | // While autoscaling manages the desired count, leave it |
| 3460 | // unchanged on updates (undefined on the wire) so redeploys |
| 3461 | // don't fight the autoscaler's decisions. |
| 3462 | desiredCount: news.scaling !== undefined ? undefined : (news.desiredCount ?? 1), |
| 3463 | service: serviceName, |
| 3464 | cluster: clusterArn, |
| 3465 | // `undefined` means "leave unchanged" on the wire, so pass an |
| 3466 | // explicit empty list to DETACH when a previously-managed |
| 3467 | // target group is no longer desired. |
| 3468 | loadBalancers: |
| 3469 | loadBalancersOf(news, task) ?? |
| 3470 | (output?.targetGroupArn !== undefined ? [] : undefined), |
| 3471 | // Same wire semantics for service registries: detach with an |
| 3472 | // explicit empty list when a previously-declared registry is |
| 3473 | // no longer desired. |
| 3474 | serviceRegistries: |
| 3475 | news.serviceRegistries ?? |
| 3476 | ((olds?.serviceRegistries?.length ?? 0) > 0 ? [] : undefined), |
| 3477 | enableExecuteCommand: news.enableExecuteCommand, |
| 3478 | forceNewDeployment: true, |
| 3479 | }) |
| 3480 | .pipe( |
| 3481 | // The service may still be transitioning (e.g. a prior |
| 3482 | // deployment settling). updateService rejects with |
| 3483 | // ServiceNotActiveException until it returns to ACTIVE — retry |
| 3484 | // bounded. |
| 3485 | Effect.retry({ |
| 3486 | while: (e) => e._tag === "ServiceNotActiveException", |
| 3487 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(8)]), |
| 3488 | }), |
| 3489 | ); |
| 3490 | yield* session.note(`Waiting for ECS service ${serviceName} to stabilize`); |
| 3491 | const stable = yield* waitForServiceConvergence({ |
| 3492 | clusterArn, |
| 3493 | serviceName, |
| 3494 | expectedTaskDefinitionArn: task.taskDefinitionArn, |
| 3495 | expectedDeploymentId: updated.service?.deployments?.find( |
| 3496 | (deployment) => deployment.status === "PRIMARY", |
| 3497 | )?.id, |
| 3498 | mode: "stable", |
| 3499 | timeout: news.deploymentStabilizationTimeout, |
| 3500 | }); |
| 3501 | const stableService = stable.service!; |
| 3502 | |
| 3503 | // Sync tags — diff observed service tags against desired. |
| 3504 | const observedTags = Object.fromEntries( |
| 3505 | (observed.tags ?? []) |
| 3506 | .filter( |
| 3507 | (t): t is { key: string; value: string } => |
| 3508 | typeof t.key === "string" && typeof t.value === "string", |
| 3509 | ) |
| 3510 | .map((t) => [t.key, t.value]), |
| 3511 | ); |
| 3512 | const { removed: removedTags, upsert: upsertTags } = diffTags(observedTags, desiredTags); |
| 3513 | if (upsertTags.length > 0) { |
| 3514 | yield* ecs.tagResource({ |
| 3515 | resourceArn: observed.serviceArn, |
| 3516 | tags: upsertTags.map((t) => ({ key: t.Key, value: t.Value })), |
| 3517 | }); |
| 3518 | } |
| 3519 | if (removedTags.length > 0) { |
| 3520 | yield* ecs.untagResource({ |
| 3521 | resourceArn: observed.serviceArn, |
| 3522 | tagKeys: removedTags, |
| 3523 | }); |
| 3524 | } |
| 3525 | |
| 3526 | // First reconcile under the composed shape: the service now points |
| 3527 | // at the composed target groups, so the legacy inline ingress can |
| 3528 | // be reaped without dropping traffic wiring. |
| 3529 | yield* reapLegacyIngress({ output, session }); |
| 3530 | |
| 3531 | // Synthesizing registered a NEW revision and `updateService` above |
| 3532 | // rolled the service onto it — reap the superseded revision so |
| 3533 | // revisions don't accumulate ACTIVE forever (same-family guarded — |
| 3534 | // a prior BYO `task:` reference is left untouched). |
| 3535 | if (owned !== undefined) { |
| 3536 | yield* reapSupersededTaskDefinitionRevision({ |
| 3537 | previousArn: output?.taskDefinitionArn, |
| 3538 | nextArn: owned.taskDefinitionArn, |
| 3539 | }); |
| 3540 | } |
| 3541 | |
| 3542 | yield* session.note(observed.serviceArn); |
| 3543 | return { |
| 3544 | serviceArn: stableService.serviceArn as ServiceArn, |
| 3545 | serviceName: stableService.serviceName!, |
| 3546 | clusterArn: stableService.clusterArn as ClusterArn, |
| 3547 | taskDefinitionArn: stableService.taskDefinition!, |
| 3548 | status: stableService.status ?? "ACTIVE", |
| 3549 | configuration: observeServiceConfiguration(stableService, news, desiredTags), |
| 3550 | ...ingressAttrs, |
| 3551 | ...ownedAttributes, |
| 3552 | }; |
| 3553 | }), |
| 3554 | delete: Effect.fn(function* ({ output, session }) { |
| 3555 | // Scale to zero and prove every task/target has drained before |
| 3556 | // deleting the service or its dependent task-definition resources. |
| 3557 | yield* ecs |
| 3558 | .updateService({ |
| 3559 | cluster: output.clusterArn, |
| 3560 | service: output.serviceName, |
| 3561 | desiredCount: 0, |
| 3562 | }) |
| 3563 | .pipe( |
| 3564 | // `ServiceNotActiveException` means the service is DRAINING or |
| 3565 | // INACTIVE — an earlier, interrupted delete already issued |
| 3566 | // `deleteService`. Neither status ever returns to ACTIVE, so |
| 3567 | // there is nothing to scale: fall through to the drain/delete |
| 3568 | // waits below, which treat both as progress toward "gone". |
| 3569 | Effect.catchTags({ |
| 3570 | ServiceNotActiveException: () => Effect.void, |
| 3571 | ServiceNotFoundException: () => Effect.void, |
| 3572 | ClusterNotFoundException: () => Effect.void, |
| 3573 | }), |
| 3574 | ); |
| 3575 | |
| 3576 | yield* session.note(`Waiting for ECS service ${output.serviceName} to drain`); |
| 3577 | yield* waitForServiceConvergence({ |
| 3578 | clusterArn: output.clusterArn, |
| 3579 | serviceName: output.serviceName, |
| 3580 | mode: "drained", |
| 3581 | }); |
| 3582 | |
| 3583 | yield* ecs |
| 3584 | .deleteService({ |
| 3585 | cluster: output.clusterArn, |
| 3586 | service: output.serviceName, |
| 3587 | force: true, |
| 3588 | }) |
| 3589 | .pipe( |
| 3590 | Effect.catchTags({ |
| 3591 | ServiceNotFoundException: () => Effect.void, |
| 3592 | ClusterNotFoundException: () => Effect.void, |
| 3593 | }), |
| 3594 | ); |
| 3595 | |
| 3596 | yield* waitForServiceConvergence({ |
| 3597 | clusterArn: output.clusterArn, |
| 3598 | serviceName: output.serviceName, |
| 3599 | mode: "deleted", |
| 3600 | }); |
| 3601 | |
| 3602 | // Inline ingress teardown applies ONLY to legacy state rows (no |
| 3603 | // `ingressKind` marker) whose ALB/TG/listener/SG were created |
| 3604 | // inline by the pre-composition provider. Composed ingress is made |
| 3605 | // of real child resources the engine deletes itself — and in the |
| 3606 | // shared form the listener/ALB recorded here belong to someone |
| 3607 | // else entirely and must never be touched. |
| 3608 | if (output.ingressKind === undefined) { |
| 3609 | if (output.listenerArn) { |
| 3610 | yield* elbv2 |
| 3611 | .deleteListener({ |
| 3612 | ListenerArn: output.listenerArn, |
| 3613 | }) |
| 3614 | .pipe(Effect.catchTag("ListenerNotFoundException", () => Effect.void)); |
| 3615 | } |
| 3616 | if (output.targetGroupArn) { |
| 3617 | yield* elbv2 |
| 3618 | .deleteTargetGroup({ |
| 3619 | TargetGroupArn: output.targetGroupArn, |
| 3620 | }) |
| 3621 | .pipe(Effect.catch(() => Effect.void)); |
| 3622 | } |
| 3623 | if (output.loadBalancerArn) { |
| 3624 | yield* elbv2 |
| 3625 | .deleteLoadBalancer({ |
| 3626 | LoadBalancerArn: output.loadBalancerArn, |
| 3627 | }) |
| 3628 | .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.void)); |
| 3629 | } |
| 3630 | |
| 3631 | // Owned ingress security group: the ALB/service ENIs release it |
| 3632 | // asynchronously, so retry the dependency violation, bounded. |
| 3633 | if (output.securityGroupId) { |
| 3634 | yield* ec2 |
| 3635 | .deleteSecurityGroup({ |
| 3636 | GroupId: output.securityGroupId, |
| 3637 | }) |
| 3638 | .pipe( |
| 3639 | Effect.catchTag("InvalidGroup.NotFound", () => Effect.void), |
| 3640 | Effect.retry({ |
| 3641 | while: (e) => e._tag === "DependencyViolation", |
| 3642 | schedule: Schedule.max([ |
| 3643 | Schedule.spaced("5 seconds"), |
| 3644 | Schedule.recurs(24), |
| 3645 | ]).pipe( |
| 3646 | Schedule.tap(() => |
| 3647 | session.note("Waiting for ENIs to release the ingress security group..."), |
| 3648 | ), |
| 3649 | ), |
| 3650 | }), |
| 3651 | ); |
| 3652 | } |
| 3653 | } |
| 3654 | |
| 3655 | // Synthesized task definition infrastructure (image-owning form). |
| 3656 | if ( |
| 3657 | output.taskFamily && |
| 3658 | output.repositoryName && |
| 3659 | output.logGroupName && |
| 3660 | output.taskRoleName && |
| 3661 | output.executionRoleName |
| 3662 | ) { |
| 3663 | yield* deleteTaskDefinitionInfrastructure({ |
| 3664 | taskDefinitionArn: output.taskDefinitionArn, |
| 3665 | taskFamily: output.taskFamily, |
| 3666 | repositoryName: output.repositoryName, |
| 3667 | logGroupName: output.logGroupName, |
| 3668 | taskRoleName: output.taskRoleName, |
| 3669 | executionRoleName: output.executionRoleName, |
| 3670 | }); |
| 3671 | } |
| 3672 | }), |
| 3673 | }; |
| 3674 | }), |
| 3675 | ); |