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

main
ts 1,311 lines 48.7 KB
Raw
1 import { Docker } from "@alchemy.run/docker/Docker";
2 import * as batch from "@distilled.cloud/aws/batch";
3 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
4 import * as ecr from "@distilled.cloud/aws/ecr";
5 import * as ecs from "@distilled.cloud/aws/ecs";
6 import * as iam from "@distilled.cloud/aws/iam";
7 import type { Region } from "@distilled.cloud/aws/Region";
8 import { AlchemyContext } from "alchemy/AlchemyContext";
9 import * as Bundle from "alchemy/Bundle/Bundle";
10 import { findCwdForBundle, getStableContextDir, resolveMainPath } from "alchemy/Bundle/TempRoot";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import { Platform, type PlatformProps, type PlatformServices } from "alchemy/Platform";
14 import * as Provider from "alchemy/Provider";
15 import { Resource, type ResourceBinding } from "alchemy/Resource";
16 import {
17 createHostRuntimeContext,
18 type HostRuntimeContext,
19 type ServerHost,
20 } from "alchemy/Runtime/Process";
21 import type { RuntimeContext } from "alchemy/RuntimeContext";
22 import { Stack } from "alchemy/Stack";
23 import { createInternalTags, createTagsList, diffTags, hasTags } from "alchemy/Tags";
24 import { toWireSeconds } from "alchemy/Util/Duration";
25 import * as Data from "effect/Data";
26 import type * as Duration from "effect/Duration";
27 import * as Effect from "effect/Effect";
28 import * as Schedule from "effect/Schedule";
29 import type { Scope } from "effect/Scope";
30 import * as Stream from "effect/Stream";
31 import type * as rolldown from "rolldown";
32 import { roleHostBundle } from "../AWSBindings.ts";
33 import type { Credentials } from "../Credentials.ts";
34 import { buildAndPushEcrImage } from "../ECR/Image.ts";
35 import { AWSEnvironment, type AccountID } from "../Environment.ts";
36 import type { PolicyStatement } from "../IAM/Policy.ts";
37 import type { Providers } from "../Providers.ts";
38 import type { RegionID } from "../Region.ts";
39
40 export class JobDefinitionOperationFailed extends Data.TaggedError("JobDefinitionOperationFailed")<{
41 readonly message: string;
42 readonly cause?: unknown;
43 }> {}
44
45 export class JobDefinitionConflict extends Data.TaggedError("JobDefinitionConflict")<{
46 readonly message: string;
47 readonly cause?: unknown;
48 }> {}
49
50 export type JobDefinitionName = string;
51 /** Revision-qualified job definition ARN (`.../job-definition/{name}:{revision}`). */
52 export type JobDefinitionArn =
53 `arn:aws:batch:${RegionID}:${AccountID}:job-definition/${JobDefinitionName}:${number}`;
54
55 /**
56 * Raised when the props don't select exactly one of the two forms: the
57 * low-level container form (`image` + `executionRoleArn`) or the
58 * Effect-native form (`main`).
59 */
60 export class JobDefinitionConfigError extends Data.TaggedError("JobDefinitionConfigError")<{
61 readonly message: string;
62 }> {}
63
64 class JobDefinitionStillVisible extends Data.TaggedError("JobDefinitionStillVisible")<{
65 readonly family: string;
66 readonly service: "Batch" | "ECS";
67 readonly arns: readonly string[];
68 }> {}
69
70 export interface JobDefinitionProps extends PlatformProps {
71 /**
72 * Name (family) of the job definition. If omitted, a unique name is
73 * generated. Content changes register a new revision under the same name.
74 */
75 jobDefinitionName?: string;
76 /**
77 * Container image the job runs (low-level form, e.g.
78 * `public.ecr.aws/docker/library/busybox:latest`). Mutually exclusive
79 * with `main`.
80 */
81 image?: string;
82 /**
83 * Module entrypoint for an Effect-native run-to-completion job (typically
84 * `import.meta.url` from an inline Effect program). Alchemy bundles the
85 * program, builds a container image, pushes it to a managed ECR
86 * repository, and provisions the job/execution IAM roles — mutually
87 * exclusive with a caller-supplied `image`.
88 */
89 main?: string;
90 /**
91 * Named export to load from `main`.
92 * @default "default"
93 */
94 handler?: string;
95 /**
96 * Command to run in the container (low-level form). Overridable
97 * per-submission via `containerOverrides.command`. The Effect-native form
98 * bakes its entrypoint into the image instead.
99 */
100 command?: string[];
101 /**
102 * Fargate vCPUs for the job. Must be a valid Fargate size (0.25, 0.5, 1,
103 * 2, 4, 8, 16) compatible with `memory`.
104 * @default 0.25
105 */
106 vcpus?: number;
107 /**
108 * Memory (MiB) for the job. Must be compatible with `vcpus` per the
109 * Fargate size matrix.
110 * @default 512
111 */
112 memory?: number;
113 /**
114 * Environment variables set in the job container.
115 */
116 environment?: Record<string, string>;
117 /**
118 * Additional environment variables for the Effect-native container.
119 * Non-string values are JSON-encoded. (Capability bindings also inject
120 * their variables here automatically.)
121 */
122 env?: Record<string, any>;
123 /**
124 * IAM role assumed by the job's application code. For the Effect-native
125 * form (`main`), Alchemy provisions and manages this role automatically
126 * (binding policy statements attach to it).
127 */
128 jobRoleArn?: string;
129 /**
130 * Execution role used by ECS/Fargate to pull the image and write logs.
131 * Required for the low-level form; provisioned automatically for the
132 * Effect-native form.
133 */
134 executionRoleArn?: string;
135 /**
136 * Compute platforms that can run this definition. Use `EC2` for unmanaged
137 * ECS compute environments.
138 * @default ["FARGATE"]
139 */
140 platformCapabilities?: ("EC2" | "FARGATE")[];
141 /**
142 * Whether the Fargate task ENI gets a public IP. Required for image pulls
143 * from public registries when running in public subnets.
144 * @default "ENABLED"
145 */
146 assignPublicIp?: "ENABLED" | "DISABLED";
147 /**
148 * Default parameter substitutions for `Ref::` placeholders in `command`.
149 */
150 parameters?: Record<string, string>;
151 /**
152 * Number of times a failed job is retried (1-10).
153 * @default 1
154 */
155 retryAttempts?: number;
156 /**
157 * Job execution timeout (minimum 60 seconds), e.g. `"15 minutes"` or
158 * `Duration.minutes(15)`.
159 */
160 timeout?: Duration.Input;
161 /**
162 * Propagate job definition tags to the ECS task.
163 * @default false
164 */
165 propagateTags?: boolean;
166 /**
167 * Bundler configuration for the Effect-native entrypoint. Unused
168 * code is tree-shaken. `effect`, alchemy, and `@distilled.cloud` are
169 * marked pure so unused parts prune more aggressively. List extra
170 * packages with `pure.packages`, or disable with `pure: false`.
171 */
172 build?: Bundle.BundleConfig;
173 /**
174 * Docker image build for the Effect-native form: optional full
175 * `dockerfile`. When omitted, Alchemy generates a Dockerfile for the
176 * bundled `index.mjs`.
177 */
178 docker?: {
179 /**
180 * Base image when Alchemy generates the Dockerfile.
181 * @default public.ecr.aws/docker/library/bun:1
182 */
183 base?: string;
184 /** Full Dockerfile content (replaces generated Dockerfile). */
185 dockerfile?: string;
186 };
187 /**
188 * Additional managed policy ARNs for the managed job role
189 * (Effect-native form only).
190 */
191 jobRoleManagedPolicyArns?: string[];
192 /**
193 * User-defined tags to apply to the job definition.
194 */
195 tags?: Record<string, string>;
196 }
197
198 export interface JobDefinition extends Resource<
199 "AWS.Batch.JobDefinition",
200 JobDefinitionProps,
201 {
202 jobDefinitionName: JobDefinitionName;
203 jobDefinitionArn: JobDefinitionArn;
204 revision: number;
205 status: string;
206 tags: Record<string, string>;
207 /** The full URI of the built container image (Effect-native form only). */
208 imageUri: string | undefined;
209 /** The managed ECR repository name (Effect-native form only). */
210 repositoryName: string | undefined;
211 /** The managed ECR repository URI (Effect-native form only). */
212 repositoryUri: string | undefined;
213 /** The ARN of the managed job role (Effect-native form only). */
214 jobRoleArn: string | undefined;
215 /** The name of the managed job role (Effect-native form only). */
216 jobRoleName: string | undefined;
217 /** The ARN of the execution role the job definition uses. */
218 executionRoleArn: string | undefined;
219 /** The name of the managed execution role (Effect-native form only). */
220 executionRoleName: string | undefined;
221 /** Content hash of the bundled program (Effect-native form only). */
222 codeHash: string | undefined;
223 },
224 {
225 /** Environment variables injected into the job container. */
226 env?: Record<string, any>;
227 /** IAM policy statements attached to the managed job role. */
228 policyStatements?: PolicyStatement[];
229 },
230 Providers
231 > {}
232
233 export type JobDefinitionServices = Credentials | Region | ServerHost | AWSEnvironment;
234
235 /**
236 * The shape an Effect-native job implementation returns: a single `run`
237 * Effect that is the run-to-completion body of the job. The container exits
238 * 0 when it succeeds (job `SUCCEEDED`) and 1 when it fails (job `FAILED`,
239 * subject to the definition's `retryAttempts`).
240 */
241 export type JobDefinitionShape = void | {
242 run: Effect.Effect<
243 void,
244 unknown,
245 JobDefinitionServices | PlatformServices | RuntimeContext | Scope
246 >;
247 };
248
249 export interface JobDefinitionRuntimeContext extends HostRuntimeContext {
250 readonly Type: "AWS.Batch.JobDefinition";
251 }
252
253 const createJobDefinitionRuntimeContext = (id: string): JobDefinitionRuntimeContext => {
254 const base = createHostRuntimeContext("AWS.Batch.JobDefinition")(id);
255 return {
256 ...base,
257 // A Batch job is run-to-completion, not a server. `Platform` hands any
258 // non-`fetch` impl shape to `serve`; register the shape's `run` Effect
259 // as a host runner (collected into `exports.program`, executed by the
260 // generated container entrypoint) instead of booting an HTTP server.
261 serve: ((_handler, options) => {
262 const run = (options?.shape as { run?: unknown } | undefined)?.run;
263 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- untyped impl shape; runner is a host-provided Effect
264 return Effect.isEffect(run) ? base.run(run as Effect.Effect<void, never, any>) : Effect.void;
265 }) as HostRuntimeContext["serve"],
266 } as JobDefinitionRuntimeContext;
267 };
268
269 /**
270 * An AWS Batch job definition for Fargate container jobs. Job definitions are
271 * immutable revisions — changing the container configuration registers a new
272 * revision under the same name (like ECS task definitions); destroying the
273 * resource deregisters every active revision.
274 *
275 * `JobDefinition` is a Platform: alongside the low-level container form
276 * (`image` + `executionRoleArn`), it supports Effect-native run-to-completion
277 * implementations — an inline Effect program that Alchemy bundles,
278 * containerizes as the job container's command, pushes to a managed ECR
279 * repository, and registers, provisioning the job and execution roles
280 * automatically. Capability bindings (e.g. S3 `GetObject`) attach IAM policy
281 * statements to the managed job role and inject their environment variables
282 * into the container.
283 *
284 * ### Creating Job Definitions
285 * **Example:** Busybox echo job (low-level container form)
286 * ```typescript
287 * const jobDef = yield* Batch.JobDefinition("EchoJob", {
288 * image: "public.ecr.aws/docker/library/busybox:latest",
289 * command: ["echo", "hello from batch"],
290 * executionRoleArn: executionRole.roleArn,
291 * });
292 * ```
293 *
294 * **Example:** Sized job with environment
295 * ```typescript
296 * const jobDef = yield* Batch.JobDefinition("EtlJob", {
297 * image: image.imageUri,
298 * vcpus: 1,
299 * memory: 2048,
300 * environment: { STAGE: "prod" },
301 * jobRoleArn: jobRole.roleArn,
302 * executionRoleArn: executionRole.roleArn,
303 * retryAttempts: 3,
304 * timeout: "15 minutes",
305 * });
306 * ```
307 *
308 * ### Effect-Native Jobs
309 * **Example:** Tagged class with an inline run-to-completion Effect
310 * ```typescript
311 * export default class Nightly extends Batch.JobDefinition<Nightly>()(
312 * "Nightly",
313 * { main: import.meta.url, vcpus: 1, memory: 2048 },
314 * Effect.gen(function* () {
315 * const getObject = yield* AWS.S3.GetObject(bucket);
316 * return {
317 * run: Effect.gen(function* () {
318 * const data = yield* getObject({ key: "input.csv" });
319 * yield* Effect.log("processed nightly batch");
320 * }),
321 * };
322 * }),
323 * ) {}
324 * ```
325 *
326 * **Example:** Eager inline job
327 * ```typescript
328 * export default Batch.JobDefinition(
329 * "Reindex",
330 * { main: import.meta.url },
331 * Effect.succeed({
332 * run: Effect.log("reindex complete"),
333 * }),
334 * );
335 * ```
336 *
337 * **Example:** Plain external script (bundled as-is)
338 * ```typescript
339 * // ./job.ts runs top-level and exits; Alchemy bundles + containerizes it.
340 * const jobDef = yield* Batch.JobDefinition("Script", {
341 * main: path.join(import.meta.dirname, "job.ts"),
342 * });
343 * ```
344 *
345 * ### Bundling & Tree-shaking
346 * `main` is bundled with rolldown at deploy time. Unused code is
347 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
348 * pure so unused parts prune more aggressively. Your app is not
349 * marked pure.
350 *
351 * **Example:** Mark additional packages as pure
352 * Only list packages with no top-level side effects.
353 * ```typescript
354 * {
355 * main: import.meta.url,
356 * build: {
357 * pure: { packages: ["my-lib", "@my-scope/*"] },
358 * },
359 * }
360 * ```
361 *
362 * **Example:** Turn it off
363 * ```typescript
364 * {
365 * main: import.meta.url,
366 * build: { pure: false },
367 * }
368 * ```
369 *
370 * @resource
371 */
372 export const JobDefinition: Platform<
373 JobDefinition,
374 JobDefinitionServices,
375 JobDefinitionShape,
376 JobDefinitionRuntimeContext
377 > = Platform("AWS.Batch.JobDefinition", {
378 createRuntimeContext: createJobDefinitionRuntimeContext,
379 });
380
381 const observedTagsOf = (d: { tags?: { [key: string]: string | undefined } }) =>
382 Object.fromEntries(
383 Object.entries(d.tags ?? {}).filter((e): e is [string, string] => typeof e[1] === "string"),
384 );
385
386 /** Attributes only produced by the Effect-native (`main`) form. */
387 interface PlatformAttributes {
388 imageUri: string | undefined;
389 repositoryName: string | undefined;
390 repositoryUri: string | undefined;
391 jobRoleArn: string | undefined;
392 jobRoleName: string | undefined;
393 executionRoleName: string | undefined;
394 codeHash: string | undefined;
395 }
396
397 const emptyPlatformAttributes: PlatformAttributes = {
398 imageUri: undefined,
399 repositoryName: undefined,
400 repositoryUri: undefined,
401 jobRoleArn: undefined,
402 jobRoleName: undefined,
403 executionRoleName: undefined,
404 codeHash: undefined,
405 };
406
407 const toAttributes = (
408 d: batch.JobDefinition,
409 tags: Record<string, string>,
410 platform: PlatformAttributes = emptyPlatformAttributes,
411 ) => ({
412 jobDefinitionName: d.jobDefinitionName!,
413 jobDefinitionArn: d.jobDefinitionArn as JobDefinitionArn,
414 revision: d.revision ?? 1,
415 status: d.status ?? "ACTIVE",
416 tags,
417 executionRoleArn: d.containerProperties?.executionRoleArn,
418 ...platform,
419 });
420
421 /**
422 * The effective (resolved) container configuration a reconcile wants
423 * registered — identical for both forms once the Effect-native form has
424 * built its image and roles.
425 */
426 interface EffectiveContainer {
427 image: string;
428 command: string[] | undefined;
429 vcpus: string;
430 memory: string;
431 environment: Record<string, string>;
432 jobRoleArn: string | undefined;
433 executionRoleArn: string;
434 assignPublicIp: "ENABLED" | "DISABLED";
435 parameters: Record<string, string> | undefined;
436 retryAttempts: number | undefined;
437 timeoutSeconds: number | undefined;
438 propagateTags: boolean | undefined;
439 }
440
441 /**
442 * Normalized content fingerprint of a job definition — used to decide whether
443 * a new revision must be registered. Only covers the aspects this resource
444 * manages.
445 */
446 const fingerprint = (input: {
447 image?: string;
448 command?: string[];
449 vcpus?: string;
450 memory?: string;
451 environment?: Record<string, string>;
452 jobRoleArn?: string;
453 executionRoleArn?: string;
454 assignPublicIp?: string;
455 parameters?: Record<string, string>;
456 retryAttempts?: number;
457 timeoutSeconds?: number;
458 propagateTags?: boolean;
459 platformCapabilities?: ("EC2" | "FARGATE")[];
460 }) =>
461 JSON.stringify({
462 image: input.image,
463 command: input.command ?? [],
464 vcpus: input.vcpus,
465 memory: input.memory,
466 environment: Object.entries(input.environment ?? {}).sort(([a], [b]) => a.localeCompare(b)),
467 jobRoleArn: input.jobRoleArn,
468 executionRoleArn: input.executionRoleArn,
469 assignPublicIp: input.assignPublicIp ?? "ENABLED",
470 parameters: Object.entries(input.parameters ?? {}).sort(([a], [b]) => a.localeCompare(b)),
471 retryAttempts: input.retryAttempts ?? 1,
472 timeoutSeconds: input.timeoutSeconds,
473 propagateTags: input.propagateTags ?? false,
474 platformCapabilities: [...(input.platformCapabilities ?? ["FARGATE"])].sort(),
475 });
476
477 const observedFingerprint = (d: batch.JobDefinition) => {
478 const c = d.containerProperties ?? {};
479 const req = (type: string) => c.resourceRequirements?.find((r) => r.type === type)?.value;
480 return fingerprint({
481 image: c.image,
482 command: [...(c.command ?? [])],
483 vcpus: req("VCPU"),
484 memory: req("MEMORY"),
485 environment: Object.fromEntries(
486 (c.environment ?? []).flatMap((kv) =>
487 kv.name !== undefined ? [[kv.name, kv.value ?? ""]] : [],
488 ),
489 ),
490 jobRoleArn: c.jobRoleArn,
491 executionRoleArn: c.executionRoleArn,
492 assignPublicIp: c.networkConfiguration?.assignPublicIp,
493 parameters: Object.fromEntries(
494 Object.entries(d.parameters ?? {}).flatMap(([k, v]) => (v !== undefined ? [[k, v]] : [])),
495 ),
496 retryAttempts: d.retryStrategy?.attempts,
497 timeoutSeconds: d.timeout?.attemptDurationSeconds,
498 propagateTags: d.propagateTags,
499 platformCapabilities: d.platformCapabilities as ("EC2" | "FARGATE")[] | undefined,
500 });
501 };
502
503 const desiredFingerprint = (effective: EffectiveContainer, news: JobDefinitionProps) =>
504 fingerprint({
505 image: effective.image,
506 command: effective.command,
507 vcpus: effective.vcpus,
508 memory: effective.memory,
509 environment: effective.environment,
510 jobRoleArn: effective.jobRoleArn,
511 executionRoleArn: effective.executionRoleArn,
512 assignPublicIp: news.assignPublicIp,
513 parameters: effective.parameters,
514 retryAttempts: effective.retryAttempts,
515 timeoutSeconds: effective.timeoutSeconds,
516 propagateTags: effective.propagateTags,
517 platformCapabilities: news.platformCapabilities,
518 });
519
520 export const JobDefinitionProvider = () =>
521 Provider.effect(
522 JobDefinition,
523 Effect.gen(function* () {
524 const stack = yield* Stack;
525 const docker = yield* Docker;
526 const { dotAlchemy } = yield* AlchemyContext;
527 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
528
529 const alchemyEnv = {
530 ALCHEMY_STACK_NAME: stack.name,
531 ALCHEMY_STAGE: stack.stage,
532 ALCHEMY_PHASE: "runtime",
533 };
534
535 const toName = (id: string, props: { jobDefinitionName?: string } = {}) =>
536 props.jobDefinitionName
537 ? Effect.succeed(props.jobDefinitionName)
538 : createPhysicalName({ id, maxLength: 128 });
539
540 const createRoleName = (id: string, suffix: string) =>
541 createPhysicalName({ id: `${id}-${suffix}`, maxLength: 64 });
542
543 // Batch caps `containerProperties.image` at 255 characters, and the
544 // image ref is `<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>`
545 // — up to 52 characters of registry prefix plus the 16-character
546 // content tag — so the repository name (ECR itself allows 256) must
547 // stop at 180 to fit in every region.
548 const createRepositoryName = (id: string) =>
549 createPhysicalName({
550 id: `${id}-repo`,
551 maxLength: 180,
552 lowercase: true,
553 });
554
555 /** Every ACTIVE revision of the family, ascending by revision. */
556 const activeRevisions = (name: string) =>
557 batch.describeJobDefinitions.pages({ jobDefinitionName: name, status: "ACTIVE" }).pipe(
558 Stream.runCollect,
559 Effect.map((pages) =>
560 Array.from(pages)
561 .flatMap((page) => page.jobDefinitions ?? [])
562 .sort((a, b) => (a.revision ?? 0) - (b.revision ?? 0)),
563 ),
564 );
565
566 const latestRevision = (name: string) =>
567 activeRevisions(name).pipe(Effect.map((defs) => defs.at(-1)));
568
569 const waitUntilNoActiveBatchRevisions = (family: string) =>
570 Effect.gen(function* () {
571 const active = yield* activeRevisions(family);
572 if (active.length > 0) {
573 return yield* new JobDefinitionStillVisible({
574 family,
575 service: "Batch",
576 arns: active.flatMap((revision) =>
577 revision.jobDefinitionArn ? [revision.jobDefinitionArn] : [],
578 ),
579 });
580 }
581 }).pipe(
582 Effect.retry({
583 while: (error) => error._tag === "JobDefinitionStillVisible",
584 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
585 }),
586 );
587
588 const listBackingTaskDefinitions = (family: string, status: "ACTIVE" | "INACTIVE") =>
589 ecs.listTaskDefinitions.items({ familyPrefix: family, status }).pipe(
590 Stream.filter((arn) => {
591 const suffix = arn.split("/").at(-1);
592 return suffix?.slice(0, suffix.lastIndexOf(":")) === family;
593 }),
594 Stream.runCollect,
595 Effect.map((chunk) => Array.from(chunk)),
596 );
597
598 const waitUntilBackingRevisionDeletionStarted = (family: string, arn: string) =>
599 Effect.gen(function* () {
600 const status = yield* ecs.describeTaskDefinition({ taskDefinition: arn }).pipe(
601 Effect.map((response) => response.taskDefinition?.status),
602 // Not-found means ECS already completed the asynchronous
603 // deletion and is therefore terminal as well.
604 Effect.catchTag("ClientException", () => Effect.undefined),
605 );
606 if (status !== undefined && status !== "DELETE_IN_PROGRESS") {
607 return yield* new JobDefinitionStillVisible({
608 family,
609 service: "ECS",
610 arns: [arn],
611 });
612 }
613 }).pipe(
614 Effect.retry({
615 while: (error) => error._tag === "JobDefinitionStillVisible",
616 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
617 }),
618 );
619
620 /**
621 * AWS Batch registers an ECS task definition under the same family when
622 * a job first runs. It is not part of Batch's list API or Alchemy state,
623 * and Batch can leave it ACTIVE after the Batch definition is gone.
624 * Exact-family filtering keeps this cleanup scoped to the resource.
625 */
626 const reapBackingTaskDefinitions = (family: string) =>
627 Effect.gen(function* () {
628 const active = yield* listBackingTaskDefinitions(family, "ACTIVE");
629 yield* Effect.forEach(
630 active,
631 (arn) =>
632 ecs
633 .deregisterTaskDefinition({ taskDefinition: arn })
634 .pipe(Effect.catchTag("ClientException", () => Effect.void)),
635 { concurrency: 4, discard: true },
636 );
637
638 // Observe ACTIVE absence before attempting the hard delete. This is
639 // the transition ECS requires before deleteTaskDefinitions.
640 yield* Effect.gen(function* () {
641 const remaining = yield* listBackingTaskDefinitions(family, "ACTIVE");
642 if (remaining.length > 0) {
643 return yield* new JobDefinitionStillVisible({
644 family,
645 service: "ECS",
646 arns: remaining,
647 });
648 }
649 }).pipe(
650 Effect.retry({
651 while: (error) => error._tag === "JobDefinitionStillVisible",
652 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
653 }),
654 );
655
656 const inactive = [
657 ...new Set([...active, ...(yield* listBackingTaskDefinitions(family, "INACTIVE"))]),
658 ];
659 for (let i = 0; i < inactive.length; i += 10) {
660 const response = yield* ecs.deleteTaskDefinitions({
661 taskDefinitions: inactive.slice(i, i + 10),
662 });
663 if ((response.failures?.length ?? 0) > 0) {
664 return yield* new JobDefinitionOperationFailed({
665 message: `ECS failed to delete Batch backing task definitions for ${family}: ${response.failures
666 ?.map(
667 (failure) =>
668 `${failure.arn ?? "unknown"}: ${failure.reason ?? "unknown"} (${failure.detail ?? "no detail"})`,
669 )
670 .join(", ")}`,
671 });
672 }
673 }
674 yield* Effect.forEach(
675 inactive,
676 (arn) => waitUntilBackingRevisionDeletionStarted(family, arn),
677 { concurrency: 4, discard: true },
678 );
679 });
680
681 /**
682 * Ensure an IAM role trusted by ECS tasks exists (creates on miss,
683 * adopts on race when it carries our tags).
684 */
685 const ensureRole = Effect.fn(function* ({
686 id,
687 roleName,
688 managedPolicyArns,
689 }: {
690 id: string;
691 roleName: string;
692 managedPolicyArns?: string[];
693 }) {
694 const tags = yield* createInternalTags(id);
695 const role = yield* iam
696 .createRole({
697 RoleName: roleName,
698 AssumeRolePolicyDocument: JSON.stringify({
699 Version: "2012-10-17",
700 Statement: [
701 {
702 Effect: "Allow",
703 Principal: { Service: "ecs-tasks.amazonaws.com" },
704 Action: "sts:AssumeRole",
705 },
706 ],
707 }),
708 Tags: createTagsList(tags),
709 })
710 .pipe(
711 Effect.catchTag("EntityAlreadyExistsException", () =>
712 iam.getRole({ RoleName: roleName }).pipe(
713 Effect.filterOrFail(
714 (existing) => hasTags(tags, existing.Role?.Tags),
715 () =>
716 new JobDefinitionConflict({
717 message: `Role '${roleName}' already exists and is not managed by alchemy`,
718 }),
719 ),
720 ),
721 ),
722 );
723 for (const policyArn of managedPolicyArns ?? []) {
724 yield* iam
725 .attachRolePolicy({ RoleName: roleName, PolicyArn: policyArn })
726 .pipe(Effect.catchTag("LimitExceededException", () => Effect.void));
727 }
728 return role.Role!.Arn!;
729 });
730
731 /** Ensure the managed ECR repository for the built image exists. */
732 const ensureRepository = Effect.fn(function* ({
733 repositoryName,
734 tags,
735 }: {
736 repositoryName: string;
737 tags: Record<string, string>;
738 }) {
739 const created = yield* ecr
740 .createRepository({
741 repositoryName,
742 imageTagMutability: "MUTABLE",
743 imageScanningConfiguration: { scanOnPush: true },
744 tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })),
745 })
746 .pipe(
747 Effect.catchTag("RepositoryAlreadyExistsException", () =>
748 Effect.gen(function* () {
749 const existing = yield* ecr.describeRepositories({
750 repositoryNames: [repositoryName],
751 });
752 return { repository: existing.repositories?.[0] };
753 }),
754 ),
755 );
756 const repository = created.repository;
757 if (!repository?.repositoryUri) {
758 return yield* Effect.die(
759 new Error(`Failed to resolve ECR repository '${repositoryName}'`),
760 );
761 }
762 return { repositoryUri: repository.repositoryUri };
763 });
764
765 /**
766 * Attach binding-declared IAM policy statements to the managed job
767 * role and collect binding-declared environment variables.
768 */
769 const attachBindings = Effect.fn(function* ({
770 roleName,
771 policyName,
772 bindings,
773 }: {
774 roleName: string;
775 policyName: string;
776 bindings: ResourceBinding<JobDefinition["Binding"]>[];
777 }) {
778 const activeBindings = bindings.filter(
779 (
780 binding: ResourceBinding<JobDefinition["Binding"]> & {
781 action?: string;
782 },
783 ) => binding.action !== "delete",
784 );
785
786 const env = activeBindings
787 .map((binding) => binding?.data?.env)
788 .reduce((acc, value) => ({ ...acc, ...value }), {});
789
790 const policyStatements = activeBindings.flatMap(
791 (binding) =>
792 binding?.data?.policyStatements?.map((statement) => ({
793 ...statement,
794 Sid: statement.Sid?.replace(/[^A-Za-z0-9]+/gi, ""),
795 })) ?? [],
796 );
797
798 if (policyStatements.length > 0) {
799 yield* iam.putRolePolicy({
800 RoleName: roleName,
801 PolicyName: policyName,
802 PolicyDocument: JSON.stringify({
803 Version: "2012-10-17",
804 Statement: policyStatements,
805 }),
806 });
807 } else {
808 yield* iam
809 .deleteRolePolicy({ RoleName: roleName, PolicyName: policyName })
810 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
811 }
812
813 return env;
814 });
815
816 /** Bundle the Effect-native program into container-ready files. */
817 const bundleProgram = Effect.fn(function* (props: JobDefinitionProps) {
818 const handler = props.handler ?? "default";
819 const realMain = yield* resolveMainPath(props.main!);
820 const cwd = yield* findCwdForBundle(realMain);
821
822 const buildBundle = Effect.fn(function* (
823 entry: string,
824 plugins?: rolldown.RolldownPluginOption,
825 ) {
826 return yield* Bundle.build(
827 roleHostBundle({
828 ...props.build?.input,
829 input: entry,
830 cwd,
831 platform: "node",
832 // The container runs on `bun`; keep `bun`/`bun:*` external (the
833 // runtime provides them) and resolve the `bun` export condition
834 // so `@effect/platform-bun` picks its Bun implementations.
835 external: [
836 "bun",
837 "bun:*",
838 ...((props.build?.input?.external as string[] | undefined) ?? []),
839 ],
840 resolve: {
841 conditionNames: [...Bundle.BUN_CONDITION_NAMES],
842 ...props.build?.input?.resolve,
843 },
844 plugins: [props.build?.input?.plugins, plugins],
845 }),
846 {
847 ...props.build?.output,
848 format: "esm",
849 sourcemap: props.build?.output?.sourcemap ?? false,
850 minify: props.build?.output?.minify ?? false,
851 entryFileNames: "index.mjs",
852 },
853 props.build,
854 );
855 });
856
857 const bundleOutput = props.isExternal
858 ? yield* buildBundle(realMain)
859 : yield* buildBundle(
860 realMain,
861 virtualEntryPlugin(
862 (importPath) => `
863 import { bootstrap } from "@alchemy.run/aws/Bootstrap/Batch";
864 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
865
866 await bootstrap(entrypoint);
867 `,
868 ),
869 );
870
871 // Return every emitted file (entry + shared chunks). Dynamic imports
872 // in the AWS SDK split into chunks; dropping any of them crashes the
873 // container with `Cannot find module './chunk-X.js'`.
874 const files = bundleOutput.files.map((file) => ({
875 path: file.path,
876 content:
877 typeof file.content === "string"
878 ? new TextEncoder().encode(file.content)
879 : file.content,
880 }));
881
882 // 16 hex characters of the content hash, like the ECS/App Runner image
883 // sources: the full sha256 as a tag pushed long repository names over
884 // Batch's 255-character `image` limit.
885 return { files, hash: bundleOutput.hash.slice(0, 16) };
886 });
887
888 /** Build + push the container image for the bundled program. */
889 const buildAndPushImage = Effect.fn(function* ({
890 id,
891 repositoryUri,
892 hash,
893 files,
894 props,
895 }: {
896 id: string;
897 repositoryUri: string;
898 hash: string;
899 files: { path: string; content: Uint8Array<ArrayBufferLike> }[];
900 props: JobDefinitionProps;
901 }) {
902 const realMain = yield* resolveMainPath(props.main!);
903 const contextDir = yield* getStableContextDir(realMain, dotAlchemy, `${id}-image`);
904 const imageUri = `${repositoryUri}:${hash}`;
905
906 const generatedDockerfile = (() => {
907 const base = props.docker?.base ?? "public.ecr.aws/docker/library/bun:1";
908 return [
909 `FROM ${base}`,
910 `WORKDIR /app`,
911 `COPY index.mjs /app/index.mjs`,
912 // Copy any additional rolldown chunks (`chunk-XXX.js`, ...).
913 // Non-trivial bundles always emit at least one; minimal bundles
914 // emit none and the COPY no-ops.
915 `COPY *.js /app/`,
916 `ENTRYPOINT ["bun", "/app/index.mjs"]`,
917 ].join("\n");
918 })();
919
920 const dockerfile = props.docker?.dockerfile ?? generatedDockerfile;
921
922 yield* docker.materialize({
923 context: contextDir,
924 dockerfile,
925 // Entry chunk becomes `index.mjs`; all other chunks keep their
926 // emitted `*.js` names so the entry's relative imports resolve.
927 files: files.map((file, index) => ({
928 path: index === 0 ? "index.mjs" : file.path,
929 content: file.content,
930 })),
931 });
932 // Batch Fargate defaults to X86_64 — always build linux/amd64
933 // (cross-built via emulation on ARM64 hosts).
934 return yield* buildAndPushEcrImage(docker, {
935 imageUri,
936 context: contextDir,
937 platform: "linux/amd64",
938 });
939 });
940
941 /**
942 * Delete the managed platform resources (ECR repository, job +
943 * execution roles). Used by `delete` and by a reconcile that switches
944 * an Effect-native definition back to the low-level form. Idempotent.
945 */
946 const cleanupPlatformResources = Effect.fn(function* (platform: {
947 repositoryName?: string | undefined;
948 jobRoleName?: string | undefined;
949 executionRoleName?: string | undefined;
950 }) {
951 if (platform.repositoryName) {
952 yield* ecr
953 .deleteRepository({
954 repositoryName: platform.repositoryName,
955 force: true,
956 })
957 .pipe(Effect.catchTag("RepositoryNotFoundException", () => Effect.void));
958 }
959 for (const roleName of [platform.jobRoleName, platform.executionRoleName]) {
960 if (!roleName) continue;
961 yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe(
962 Stream.mapEffect((policyName) =>
963 iam
964 .deleteRolePolicy({
965 RoleName: roleName,
966 PolicyName: policyName,
967 })
968 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
969 ),
970 Stream.runDrain,
971 Effect.catchTag("NoSuchEntityException", () => Effect.void),
972 );
973 yield* iam.listAttachedRolePolicies.items({ RoleName: roleName }).pipe(
974 Stream.mapEffect((policy) =>
975 iam
976 .detachRolePolicy({
977 RoleName: roleName,
978 PolicyArn: policy.PolicyArn!,
979 })
980 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
981 ),
982 Stream.runDrain,
983 Effect.catchTag("NoSuchEntityException", () => Effect.void),
984 );
985 yield* iam
986 .deleteRole({ RoleName: roleName })
987 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
988 }
989 });
990
991 return {
992 stables: [
993 "jobDefinitionName",
994 "repositoryName",
995 "repositoryUri",
996 "jobRoleArn",
997 "jobRoleName",
998 "executionRoleName",
999 ],
1000 diff: Effect.fn(function* ({ id, olds, news }) {
1001 if (!isResolved(news)) return;
1002 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
1003 return { action: "replace" } as const;
1004 }
1005 }),
1006 read: Effect.fn(function* ({ id, olds, output }) {
1007 const name = output?.jobDefinitionName ?? (yield* toName(id, olds ?? {}));
1008 const latest = yield* latestRevision(name);
1009 if (!latest?.jobDefinitionArn) return undefined;
1010 // Managed platform resources (repo, roles) are stable identifiers —
1011 // carry them through from the cached output.
1012 return toAttributes(latest, observedTagsOf(latest), {
1013 ...emptyPlatformAttributes,
1014 ...(output
1015 ? {
1016 imageUri: output.imageUri,
1017 repositoryName: output.repositoryName,
1018 repositoryUri: output.repositoryUri,
1019 jobRoleArn: output.jobRoleArn,
1020 jobRoleName: output.jobRoleName,
1021 executionRoleName: output.executionRoleName,
1022 codeHash: output.codeHash,
1023 }
1024 : {}),
1025 });
1026 }),
1027 list: () =>
1028 Effect.gen(function* () {
1029 // Enumerate the latest ACTIVE revision of every family.
1030 const pages = yield* batch.describeJobDefinitions
1031 .pages({ status: "ACTIVE" })
1032 .pipe(Stream.runCollect);
1033 const latest = new Map<string, batch.JobDefinition>();
1034 for (const page of pages) {
1035 for (const d of page.jobDefinitions ?? []) {
1036 if (!d.jobDefinitionName || !d.jobDefinitionArn) continue;
1037 const prior = latest.get(d.jobDefinitionName);
1038 if (!prior || (prior.revision ?? 0) < (d.revision ?? 0)) {
1039 latest.set(d.jobDefinitionName, d);
1040 }
1041 }
1042 }
1043 return Array.from(latest.values()).map((d) => toAttributes(d, observedTagsOf(d)));
1044 }),
1045 reconcile: Effect.fn(function* ({ id, news, bindings, output, session }) {
1046 const { region } = yield* AWSEnvironment.current;
1047 const name = output?.jobDefinitionName ?? (yield* toName(id, news));
1048 const internalTags = yield* createInternalTags(id);
1049 const desiredTags = { ...internalTags, ...news.tags };
1050
1051 if (news.main !== undefined && news.image !== undefined) {
1052 return yield* new JobDefinitionConfigError({
1053 message:
1054 "`main` (Effect-native form) and `image` (low-level form) are mutually exclusive",
1055 });
1056 }
1057 if (news.main === undefined && news.image === undefined) {
1058 return yield* new JobDefinitionConfigError({
1059 message: "one of `main` (Effect-native form) or `image` (low-level form) is required",
1060 });
1061 }
1062 if (news.main === undefined && news.executionRoleArn === undefined) {
1063 return yield* new JobDefinitionConfigError({
1064 message:
1065 "`executionRoleArn` is required with `image` (Fargate jobs pull the image and write logs through it)",
1066 });
1067 }
1068
1069 // Resolve the effective container configuration. The Effect-native
1070 // form first ensures its managed roles + repository, bundles the
1071 // program, and builds + pushes the image; the low-level form uses
1072 // the caller-supplied image and roles directly. Each ensure step is
1073 // independently idempotent.
1074 let platformAttributes = emptyPlatformAttributes;
1075 let effective: EffectiveContainer;
1076 if (news.main !== undefined) {
1077 const jobRoleName = output?.jobRoleName ?? (yield* createRoleName(id, "job-role"));
1078 const executionRoleName =
1079 output?.executionRoleName ?? (yield* createRoleName(id, "execution-role"));
1080 const repositoryName = output?.repositoryName ?? (yield* createRepositoryName(id));
1081 const jobPolicyName = yield* createPhysicalName({
1082 id: `${id}-job-policy`,
1083 maxLength: 128,
1084 });
1085
1086 const jobRoleArn = yield* ensureRole({
1087 id,
1088 roleName: jobRoleName,
1089 managedPolicyArns: news.jobRoleManagedPolicyArns,
1090 });
1091 const executionRoleArn = yield* ensureRole({
1092 id,
1093 roleName: executionRoleName,
1094 managedPolicyArns: [
1095 "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
1096 ],
1097 });
1098
1099 const bindingEnv = yield* attachBindings({
1100 roleName: jobRoleName,
1101 policyName: jobPolicyName,
1102 bindings,
1103 });
1104
1105 const { repositoryUri } =
1106 output?.repositoryUri && output.repositoryName === repositoryName
1107 ? { repositoryUri: output.repositoryUri }
1108 : yield* ensureRepository({
1109 repositoryName,
1110 tags: desiredTags,
1111 });
1112
1113 const { files, hash } = yield* bundleProgram(news);
1114 const imageUri = yield* buildAndPushImage({
1115 id,
1116 repositoryUri,
1117 hash,
1118 files,
1119 props: news,
1120 });
1121
1122 platformAttributes = {
1123 imageUri,
1124 repositoryName,
1125 repositoryUri,
1126 jobRoleArn,
1127 jobRoleName,
1128 executionRoleName,
1129 codeHash: hash,
1130 };
1131 effective = {
1132 image: imageUri,
1133 command: undefined,
1134 vcpus: String(news.vcpus ?? 0.25),
1135 memory: String(news.memory ?? 512),
1136 environment: {
1137 // Bindings + alchemy runtime env first (JSON-encoded), then
1138 // the caller's `env`, then plain `environment` wins last.
1139 ...Object.fromEntries(
1140 Object.entries({
1141 ...bindingEnv,
1142 ...alchemyEnv,
1143 // Fargate does not inject AWS_REGION — the bundled
1144 // program's `Region.fromEnv()` needs it.
1145 AWS_REGION: region,
1146 ...news.env,
1147 }).map(([key, value]) => [
1148 key,
1149 typeof value === "string" ? value : JSON.stringify(value),
1150 ]),
1151 ),
1152 ...news.environment,
1153 },
1154 jobRoleArn,
1155 executionRoleArn,
1156 assignPublicIp: news.assignPublicIp ?? "ENABLED",
1157 parameters: news.parameters,
1158 retryAttempts: news.retryAttempts,
1159 timeoutSeconds: toWireSeconds(news.timeout),
1160 propagateTags: news.propagateTags,
1161 };
1162 } else {
1163 // Low-level form. If a previous deploy used the Effect-native
1164 // form, its managed repo/roles are no longer referenced — reap
1165 // them so nothing leaks.
1166 if (output?.repositoryName || output?.jobRoleName || output?.executionRoleName) {
1167 yield* cleanupPlatformResources(output);
1168 }
1169 effective = {
1170 image: news.image!,
1171 command: news.command,
1172 vcpus: String(news.vcpus ?? 0.25),
1173 memory: String(news.memory ?? 512),
1174 environment: { ...news.environment },
1175 jobRoleArn: news.jobRoleArn,
1176 executionRoleArn: news.executionRoleArn!,
1177 assignPublicIp: news.assignPublicIp ?? "ENABLED",
1178 parameters: news.parameters,
1179 retryAttempts: news.retryAttempts,
1180 timeoutSeconds: toWireSeconds(news.timeout),
1181 propagateTags: news.propagateTags,
1182 };
1183 }
1184
1185 // Observe — the latest ACTIVE revision is the live state.
1186 const latest = yield* latestRevision(name);
1187
1188 // Ensure/Sync — register a new revision only when managed content
1189 // differs (revisions are immutable; registration IS the update).
1190 if (!latest || observedFingerprint(latest) !== desiredFingerprint(effective, news)) {
1191 const platformCapabilities = news.platformCapabilities ?? ["FARGATE"];
1192 const registered = yield* batch.registerJobDefinition({
1193 jobDefinitionName: name,
1194 type: "container",
1195 platformCapabilities,
1196 containerProperties: {
1197 image: effective.image,
1198 command: effective.command,
1199 jobRoleArn: effective.jobRoleArn,
1200 executionRoleArn: effective.executionRoleArn,
1201 resourceRequirements: [
1202 { type: "VCPU", value: effective.vcpus },
1203 { type: "MEMORY", value: effective.memory },
1204 ],
1205 environment: Object.entries(effective.environment).map(([key, value]) => ({
1206 name: key,
1207 value,
1208 })),
1209 networkConfiguration: platformCapabilities.includes("FARGATE")
1210 ? { assignPublicIp: effective.assignPublicIp }
1211 : undefined,
1212 },
1213 parameters: effective.parameters,
1214 retryStrategy:
1215 effective.retryAttempts !== undefined
1216 ? { attempts: effective.retryAttempts }
1217 : undefined,
1218 timeout:
1219 effective.timeoutSeconds !== undefined
1220 ? { attemptDurationSeconds: effective.timeoutSeconds }
1221 : undefined,
1222 propagateTags: effective.propagateTags,
1223 tags: desiredTags,
1224 });
1225 yield* session.note(registered.jobDefinitionArn);
1226 return {
1227 jobDefinitionName: registered.jobDefinitionName,
1228 jobDefinitionArn: registered.jobDefinitionArn as JobDefinitionArn,
1229 revision: registered.revision,
1230 status: "ACTIVE",
1231 tags: desiredTags,
1232 executionRoleArn: effective.executionRoleArn,
1233 ...platformAttributes,
1234 };
1235 }
1236
1237 // Content unchanged — sync tags in place on the revision ARN.
1238 const { upsert, removed } = diffTags(observedTagsOf(latest), desiredTags);
1239 if (upsert.length > 0) {
1240 yield* batch.tagResource({
1241 resourceArn: latest.jobDefinitionArn!,
1242 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
1243 });
1244 }
1245 if (removed.length > 0) {
1246 yield* batch.untagResource({
1247 resourceArn: latest.jobDefinitionArn!,
1248 tagKeys: removed,
1249 });
1250 }
1251
1252 yield* session.note(latest.jobDefinitionArn!);
1253 return toAttributes(latest, desiredTags, platformAttributes);
1254 }),
1255 delete: Effect.fn(function* ({ output }) {
1256 // Deregister EVERY active revision of the family. Deregistration is
1257 // idempotent (succeeds when the revision is already gone).
1258 const revisions = yield* activeRevisions(output.jobDefinitionName);
1259 yield* Effect.forEach(
1260 revisions,
1261 (d) =>
1262 batch.deregisterJobDefinition({
1263 jobDefinition: `${d.jobDefinitionName}:${d.revision}`,
1264 }),
1265 { concurrency: 4 },
1266 );
1267 yield* waitUntilNoActiveBatchRevisions(output.jobDefinitionName);
1268
1269 // A submitted Batch job causes AWSServiceRoleForBatch to create a
1270 // backing ECS task-definition revision with the exact same family.
1271 // Batch deregistration does not reliably reclaim it, so delete it
1272 // explicitly only after the Batch family is observed inactive.
1273 yield* reapBackingTaskDefinitions(output.jobDefinitionName);
1274
1275 // Reap the managed platform resources (Effect-native form only).
1276 yield* cleanupPlatformResources(output);
1277
1278 // Reap this family's log streams from the shared, service-managed
1279 // `/aws/batch/job` group. The awslogs driver names streams
1280 // `{jobDefinitionName}/default/{taskId}`, so the family prefix is
1281 // exact; the group itself is account-level AWS infrastructure
1282 // (recreated by the Batch service on the next job) and is left
1283 // alone.
1284 const logGroupName = "/aws/batch/job";
1285 const streams = yield* logs.describeLogStreams
1286 .pages({
1287 logGroupName,
1288 logStreamNamePrefix: `${output.jobDefinitionName}/`,
1289 })
1290 .pipe(
1291 Stream.runCollect,
1292 Effect.map((pages) => Array.from(pages).flatMap((p) => p.logStreams ?? [])),
1293 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
1294 );
1295 yield* Effect.forEach(
1296 streams,
1297 (s) =>
1298 s.logStreamName === undefined
1299 ? Effect.void
1300 : logs
1301 .deleteLogStream({
1302 logGroupName,
1303 logStreamName: s.logStreamName,
1304 })
1305 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
1306 { concurrency: 4 },
1307 );
1308 }),
1309 };
1310 }),
1311 );