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

main
ts 276 lines 8.95 KB
Raw
1 import type { ResourceBinding } from "alchemy/Resource";
2 import { packEnvValue } from "alchemy/RuntimeContext";
3 import { Stack } from "alchemy/Stack";
4 import * as Effect from "effect/Effect";
5 import {
6 defaultComputeServiceAccount,
7 deleteHostServiceAccount,
8 ensureHostServiceAccount,
9 hostServiceAccountEmail,
10 hostServiceAccountId,
11 serviceAccountUniqueId,
12 syncHostIam,
13 type AppliedIamGrant,
14 type GcpHostBinding,
15 } from "./Host.ts";
16
17 /**
18 * Shared deploy-time plumbing for the GCP runtime hosts (`Run.Service`,
19 * `Run.Job`, `Run.WorkerPool`, `CloudFunctions.Function`): runtime
20 * identity, IAM sync, container env, and the generated bootstrap entry.
21 *
22 * NOT exported from `index.ts`.
23 */
24
25 /** Attributes every GCP host records about its runtime identity. */
26 export interface HostIdentityAttrs {
27 /** Runtime service account email. */
28 serviceAccount: string | undefined;
29 /**
30 * Numeric unique ID of the runtime service account, the `sub` of the
31 * Google ID tokens the host fetches. AWS bindings trust it to let the
32 * host assume an IAM role without a key.
33 */
34 serviceAccountUniqueId: string | undefined;
35 /** True when Alchemy minted the per-host runtime service account. */
36 managedServiceAccount: boolean;
37 /**
38 * IAM roles bindings granted to the runtime service account, by target
39 * resource. Used to revoke grants whose binding was removed.
40 */
41 iamGrants: AppliedIamGrant[];
42 }
43
44 /** True when `serviceAccount` is the account Alchemy mints for this host. */
45 export const isManagedServiceAccount = (options: {
46 project: string;
47 hostType: string;
48 resourceName: string;
49 serviceAccount: string | undefined;
50 }) =>
51 (options.serviceAccount ?? "") ===
52 hostServiceAccountEmail(
53 options.project,
54 hostServiceAccountId(options.hostType, options.resourceName),
55 );
56
57 /**
58 * Resolve the runtime identity for a host and converge its IAM.
59 *
60 * A user-supplied account is used as-is (grants are additive). Otherwise
61 * an Effect-native host, a host with IAM bindings, or a host that was
62 * already on a minted account gets its own minted account; a plain
63 * image-only host with no bindings keeps the project's default Compute
64 * account.
65 *
66 * The returned `cleanup` deletes an account minted by THIS call, for a
67 * create that fails before the host exists.
68 */
69 export const resolveHostIdentity = Effect.fn(function* (options: {
70 project: string;
71 hostType: string;
72 resourceName: string;
73 userServiceAccount: string | undefined;
74 effectNative: boolean;
75 bindings: readonly ResourceBinding<GcpHostBinding>[];
76 output: Partial<HostIdentityAttrs> | undefined;
77 }) {
78 const hasGrants = options.bindings.some((binding) => (binding.data?.iam?.length ?? 0) > 0);
79 const userSa =
80 options.userServiceAccount !== undefined && options.userServiceAccount.length > 0
81 ? options.userServiceAccount
82 : undefined;
83 const managed =
84 userSa === undefined &&
85 (options.effectNative || hasGrants || options.output?.managedServiceAccount === true);
86
87 let serviceAccount: string;
88 let created = false;
89 if (userSa !== undefined) {
90 serviceAccount = userSa;
91 } else if (managed) {
92 const ensured = yield* ensureHostServiceAccount({
93 project: options.project,
94 hostType: options.hostType,
95 resourceName: options.resourceName,
96 });
97 serviceAccount = ensured.email;
98 created = ensured.created;
99 } else {
100 serviceAccount = yield* defaultComputeServiceAccount(options.project);
101 }
102
103 // Grants recorded against a different account (the host switched
104 // identity) belong to that account; never replay them onto this one.
105 const previous =
106 options.output?.serviceAccount === serviceAccount ? options.output.iamGrants : undefined;
107 const synced = yield* syncHostIam({
108 project: options.project,
109 serviceAccount,
110 managed,
111 bindings: options.bindings,
112 previous,
113 }).pipe(
114 Effect.tapError(() =>
115 created
116 ? deleteHostServiceAccount({
117 project: options.project,
118 email: serviceAccount,
119 }).pipe(Effect.ignore)
120 : Effect.void,
121 ),
122 );
123
124 const uniqueId = yield* serviceAccountUniqueId(serviceAccount).pipe(
125 Effect.tapError(() =>
126 created
127 ? deleteHostServiceAccount({ project: options.project, email: serviceAccount }).pipe(
128 Effect.ignore,
129 )
130 : Effect.void,
131 ),
132 );
133
134 return {
135 serviceAccount,
136 uniqueId,
137 managed,
138 env: synced.env,
139 grants: synced.grants,
140 /** Undo a service account minted by this reconcile. */
141 cleanup: created
142 ? deleteHostServiceAccount({
143 project: options.project,
144 email: serviceAccount,
145 grants: synced.grants,
146 }).pipe(Effect.ignore)
147 : Effect.void,
148 };
149 });
150
151 /** Release a host's runtime identity on delete. */
152 export const releaseHostIdentity = (output: {
153 project: string;
154 serviceAccount: string | undefined;
155 managedServiceAccount: boolean;
156 iamGrants?: readonly AppliedIamGrant[];
157 }) =>
158 output.serviceAccount === undefined || !output.managedServiceAccount
159 ? Effect.void
160 : deleteHostServiceAccount({
161 project: output.project,
162 email: output.serviceAccount,
163 grants: output.iamGrants ?? [],
164 });
165
166 /**
167 * Env every Effect-native container needs to rebuild its `Stack` at boot
168 * (`stackFromEnv` in the bootstrap) — the GCP counterpart of the
169 * `alchemyEnv` block on `AWS.ECS.Task` / `AWS.Lambda.Function`.
170 */
171 export const alchemyRuntimeEnv = Effect.gen(function* () {
172 const stack = yield* Stack;
173 return {
174 ALCHEMY_STACK_NAME: stack.name,
175 ALCHEMY_STAGE: stack.stage,
176 ALCHEMY_PHASE: "runtime",
177 } as Record<string, string>;
178 });
179
180 export interface ContainerEnvVar {
181 name?: string;
182 value?: string;
183 valueSource?: unknown;
184 }
185
186 /**
187 * Merge env maps into a container's env list without mutating either.
188 * Later sources win by name; an explicit entry already on the container
189 * (the user's own `containers[].env`) wins over every injected value, and
190 * a name never appears twice (Cloud Run rejects duplicates).
191 */
192 export const mergeContainerEnv = <V extends ContainerEnvVar>(
193 explicit: readonly V[] | undefined,
194 ...injected: ReadonlyArray<Record<string, unknown> | undefined>
195 ): V[] => {
196 const byName = new Map<string, V>();
197 for (const source of injected) {
198 for (const [name, value] of Object.entries(source ?? {})) {
199 if (value === undefined) continue;
200 byName.set(name, { name, value: packEnvValue(value) } as V);
201 }
202 }
203 for (const entry of explicit ?? []) {
204 if (entry.name === undefined) continue;
205 byName.set(entry.name, entry);
206 }
207 return [...byName.values()].sort((left, right) =>
208 (left.name ?? "").localeCompare(right.name ?? ""),
209 );
210 };
211
212 /** Volume name and mount path Cloud Run uses for Cloud SQL Unix sockets. */
213 export const CLOUD_SQL_VOLUME = "cloudsql";
214 export const CLOUD_SQL_MOUNT_PATH = "/cloudsql";
215
216 type CloudSqlTemplate = {
217 volumes?: Array<{
218 name?: string;
219 cloudSqlInstance?: { instances?: string[] };
220 }>;
221 containers?: Array<{
222 volumeMounts?: Array<{ name?: string; mountPath?: string }>;
223 }>;
224 };
225
226 /**
227 * Mount the Cloud SQL instances requested by bindings (`cloudSqlInstances`)
228 * as the `cloudsql` volume on the first container, so each instance's
229 * socket appears at `/cloudsql/{connectionName}`. Instances the user
230 * already declared on a `cloudsql` volume are kept.
231 */
232 export const mountCloudSqlInstances = <T extends CloudSqlTemplate>(
233 template: T,
234 bindings: readonly ResourceBinding<GcpHostBinding>[],
235 ): T => {
236 const requested = bindings.flatMap((binding) => binding.data?.cloudSqlInstances ?? []);
237 if (requested.length === 0) return template;
238 const existing = template.volumes?.find((volume) => volume.name === CLOUD_SQL_VOLUME);
239 const instances = [
240 ...new Set([...(existing?.cloudSqlInstance?.instances ?? []), ...requested]),
241 ].sort();
242 const volumes = [
243 ...(template.volumes ?? []).filter((volume) => volume.name !== CLOUD_SQL_VOLUME),
244 { name: CLOUD_SQL_VOLUME, cloudSqlInstance: { instances } },
245 ];
246 const containers = (template.containers ?? []).map((container, index) =>
247 index === 0 && !(container.volumeMounts ?? []).some((mount) => mount.name === CLOUD_SQL_VOLUME)
248 ? {
249 ...container,
250 volumeMounts: [
251 ...(container.volumeMounts ?? []),
252 { name: CLOUD_SQL_VOLUME, mountPath: CLOUD_SQL_MOUNT_PATH },
253 ],
254 }
255 : container,
256 );
257 return { ...template, volumes, containers };
258 };
259
260 /**
261 * Generated entry for an Effect-native GCP container: imports only
262 * `@alchemy.run/gcp/Bootstrap/<module>` plus the user's `main`. The runtime
263 * flag is raised before the user's module evaluates (hence the dynamic
264 * import) so module-scope code sees it.
265 */
266 export const makeGcpBootstrap =
267 (module: "CloudRun" | "CloudRunJob", handler: string) =>
268 (importPath: string): string =>
269 `
270 import { bootstrap } from "@alchemy.run/gcp/Bootstrap/${module}";
271
272 globalThis.__ALCHEMY_RUNTIME__ = true;
273 const { ${handler}: entrypoint } = await import(${JSON.stringify(importPath)});
274
275 await bootstrap(entrypoint);
276 `;