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

main
ts 244 lines 9.46 KB
Raw
1 import * as Output from "alchemy/Output";
2 import * as Effect from "effect/Effect";
3 import * as AWSBindings from "../AWSBindings.ts";
4 import type { Cluster } from "./Cluster.ts";
5 import type { Service } from "./Service.ts";
6 import { type Task } from "./Task.ts";
7
8 /**
9 * Shared scaffolding for AWS ECS HTTP bindings.
10 *
11 * NOT exported from `index.ts` — every `{Op}Http.ts` in this service is a
12 * thin `Layer.effect(Cap, make…HttpBinding({ … }))` over one of the three
13 * builders below. Everything except the operation, the IAM action list, and
14 * the IAM resource scope is boilerplate.
15 *
16 * ECS scopes cluster-addressed actions against sub-resource ARNs derived
17 * from the cluster ARN — `arn:…:task/{clusterName}/*`,
18 * `arn:…:service/{clusterName}/*`, `arn:…:container-instance/{clusterName}/*`
19 * — or, for list actions with no usable resource type on Fargate, against
20 * `*` conditioned on the bound cluster.
21 */
22
23 /**
24 * `iam:PassRole` pre-typed as `string[]` (a declared alternative of
25 * `PolicyStatement.Action`). A fresh literal array at the `host.bind` call
26 * site would be contextually typed against `Input<IamAction[] | string[]>`
27 * across the `Function | Task` host union, forcing normalization of the
28 * ~18k-literal `IamAction` union and tripping TS2590 ("union type too
29 * complex") under TypeScript 7.
30 */
31 const passRoleActions: string[] = ["iam:PassRole"];
32
33 /** IAM resource scopes for cluster-bound ECS operations. */
34 export type EcsClusterIamResource = "cluster" | "task" | "service" | "container-instance";
35
36 const clusterSubresourcePattern = (
37 cluster: Cluster,
38 kind: Exclude<EcsClusterIamResource, "cluster">,
39 ) => Output.map(cluster.clusterArn, (arn) => `${arn.replace(":cluster/", `:${kind}/`)}/*`);
40
41 const clusterIamResources = (cluster: Cluster, resources: readonly EcsClusterIamResource[]) =>
42 resources.map((kind) =>
43 kind === "cluster"
44 ? Output.interpolate`${cluster.clusterArn}`
45 : clusterSubresourcePattern(cluster, kind),
46 );
47
48 /**
49 * Build the impl Effect for a cluster-addressed operation whose request
50 * carries a `cluster` field: the runtime callable injects the bound
51 * {@link Cluster}'s ARN and the deploy-time half grants `actions` on the
52 * requested `resources` scopes (or on `*` conditioned on the bound cluster
53 * when `resources` is `"cluster-condition"` — for list actions that have no
54 * usable resource type on Fargate).
55 */
56 export const makeEcsClusterHttpBinding = <I extends { cluster?: string }, A, E, R>(options: {
57 /** Fully-qualified binding tag, e.g. `AWS.ECS.DescribeServices`. */
58 tag: string;
59 /** The distilled operation; `cluster` is injected from the bound cluster. */
60 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
61 /** IAM actions granted. */
62 actions: readonly string[];
63 /** IAM resource scopes derived from the cluster ARN. */
64 resources: readonly EcsClusterIamResource[] | "cluster-condition";
65 }) =>
66 Effect.gen(function* () {
67 const bind = yield* AWSBindings.Bind;
68 const op = yield* AWSBindings.withCredentials(options.operation);
69
70 return Effect.fn(function* (cluster: Cluster) {
71 const ClusterArn = yield* cluster.clusterArn;
72 if (!globalThis.__ALCHEMY_RUNTIME__) {
73 yield* bind`${options.tag}(${cluster})`({
74 policyStatements: [
75 options.resources === "cluster-condition"
76 ? {
77 Effect: "Allow",
78 Action: [...options.actions],
79 Resource: ["*"],
80 Condition: {
81 ArnEquals: { "ecs:cluster": cluster.clusterArn },
82 },
83 }
84 : {
85 Effect: "Allow",
86 Action: [...options.actions],
87 Resource: clusterIamResources(cluster, options.resources),
88 },
89 ],
90 });
91 }
92 return Effect.fn(`${options.tag}(${cluster.LogicalId})`)(function* (
93 request: Omit<I, "cluster">,
94 ) {
95 return yield* op({
96 ...request,
97 cluster: yield* ClusterArn,
98 } as I);
99 });
100 });
101 });
102
103 /**
104 * Strip the revision suffix from a task-definition ARN. The bound
105 * `taskDefinitionArn` attribute pins whatever revision existed when the
106 * HOST was reconciled — for a circularly-bound task that is the pre-create
107 * STUB revision, not the real one registered afterwards. Launching by
108 * family makes ECS resolve the latest ACTIVE revision, which is the
109 * binding's intended semantics (like invoking a Lambda by name).
110 */
111 const revisionlessTaskDefinitionArn = (arn: string) => arn.replace(/:\d+$/, "");
112
113 /** The task-definition family name from its (possibly revisioned) ARN. */
114 const taskDefinitionFamilyOf = (arn: string) =>
115 revisionlessTaskDefinitionArn(arn).split("/").pop()!;
116
117 /**
118 * Build the impl Effect for a task-launch operation (`RunTask`/`StartTask`):
119 * the runtime callable injects the bound {@link Cluster}'s ARN as `cluster`
120 * and the bound {@link Task}'s definition family (revision-less ARN) as
121 * `taskDefinition`; the deploy-time half grants `actions` on every revision
122 * of the task definition plus `iam:PassRole` on the task and execution
123 * roles.
124 */
125 export const makeEcsTaskLaunchHttpBinding = <
126 I extends { cluster?: string; taskDefinition: string },
127 A,
128 E,
129 R,
130 >(options: {
131 /** Fully-qualified binding tag, e.g. `AWS.ECS.RunTask`. */
132 tag: string;
133 /** The distilled operation; `cluster` + `taskDefinition` are injected. */
134 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
135 /** IAM actions granted on the task definition ARN. */
136 actions: readonly string[];
137 }) =>
138 Effect.gen(function* () {
139 const bind = yield* AWSBindings.Bind;
140 const op = yield* AWSBindings.withCredentials(options.operation);
141
142 return Effect.fn(function* (cluster: Cluster, task: Task) {
143 const ClusterArn = yield* cluster.clusterArn;
144 const TaskDefinitionArn = yield* task.taskDefinitionArn;
145 if (!globalThis.__ALCHEMY_RUNTIME__) {
146 yield* bind`${options.tag}(${cluster}, ${task})`({
147 policyStatements: [
148 {
149 Effect: "Allow",
150 Action: [...options.actions],
151 // All revisions: the launch resolves the latest ACTIVE
152 // revision, which may be registered after this grant.
153 Resource: [
154 Output.map(
155 task.taskDefinitionArn,
156 (arn) => `${revisionlessTaskDefinitionArn(arn)}:*`,
157 ),
158 ],
159 },
160 {
161 Effect: "Allow",
162 Action: passRoleActions,
163 Resource: [task.taskRoleArn, task.executionRoleArn],
164 },
165 ],
166 });
167 }
168 return Effect.fn(`${options.tag}(${cluster.LogicalId}, ${task.LogicalId})`)(function* (
169 request: Omit<I, "cluster" | "taskDefinition">,
170 ) {
171 return yield* op({
172 ...request,
173 cluster: yield* ClusterArn,
174 // Family, not the pinned ARN: resolves the latest ACTIVE revision.
175 taskDefinition: taskDefinitionFamilyOf(yield* TaskDefinitionArn),
176 } as I);
177 });
178 });
179 });
180
181 /** IAM resource scopes for service-bound ECS operations. */
182 export type EcsServiceIamResource = "service" | "service-deployment" | "service-revision";
183
184 const serviceIamResources = (service: Service, resources: readonly EcsServiceIamResource[]) =>
185 resources.map((kind) =>
186 kind === "service"
187 ? Output.interpolate`${service.serviceArn}`
188 : Output.map(service.serviceArn, (arn) => `${arn.replace(":service/", `:${kind}/`)}/*`),
189 );
190
191 /**
192 * Build the impl Effect for a service-addressed operation (deployment
193 * observation and blue/green lifecycle-hook control). The deploy-time half
194 * grants `actions` on the requested scopes derived from the bound
195 * {@link Service}'s ARN. When `inject` is set, the runtime callable injects
196 * the service ARN as `service` and the cluster ARN as `cluster`; otherwise
197 * the request passes through as-is (deployment/revision ARNs are only known
198 * at runtime).
199 */
200 export const makeEcsServiceHttpBinding = <I, A, E, R>(options: {
201 /** Fully-qualified binding tag, e.g. `AWS.ECS.StopServiceDeployment`. */
202 tag: string;
203 /** The distilled operation. */
204 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
205 /** IAM actions granted. */
206 actions: readonly string[];
207 /** IAM resource scopes derived from the service ARN. */
208 resources: readonly EcsServiceIamResource[];
209 /** Inject `service` (service ARN) + `cluster` (cluster ARN) into requests. */
210 inject?: boolean;
211 }) =>
212 Effect.gen(function* () {
213 const bind = yield* AWSBindings.Bind;
214 const op = yield* AWSBindings.withCredentials(options.operation);
215
216 return Effect.fn(function* (service: Service) {
217 const ServiceArn = yield* service.serviceArn;
218 const ClusterArn = yield* service.clusterArn;
219 if (!globalThis.__ALCHEMY_RUNTIME__) {
220 yield* bind`${options.tag}(${service})`({
221 policyStatements: [
222 {
223 Effect: "Allow",
224 Action: [...options.actions],
225 Resource: serviceIamResources(service, options.resources),
226 },
227 ],
228 });
229 }
230 return Effect.fn(`${options.tag}(${service.LogicalId})`)(function* (
231 request: Omit<I, "service" | "cluster">,
232 ) {
233 return yield* op(
234 (options.inject
235 ? {
236 ...request,
237 service: yield* ServiceArn,
238 cluster: yield* ClusterArn,
239 }
240 : request) as I,
241 );
242 });
243 });
244 });