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

main
ts 317 lines 10.5 KB
Raw
1 import * as workloadmanager from "@distilled.cloud/gcp/workloadmanager_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 expandNamed,
11 hasAlchemyActuationId,
12 lastSegment,
13 listAtNested,
14 listPages,
15 normalizeLocation,
16 parseName,
17 replaceOnIdentity,
18 resourceNameFromOperation,
19 ResourceNotResolved,
20 toActuationId,
21 waitForOperation,
22 waitUntilExists,
23 waitUntilGone,
24 } from "./internal.ts";
25
26 export type ActuationOutput = {
27 /** Blueprint Controller deployment and revision resource. */
28 blueprintId?: string;
29 /** Terraform template used. */
30 terraformTemplate?: string;
31 /** Cloud Storage file that stores build logs. */
32 actuateLogs?: string;
33 /** Error code when actuation failed. */
34 errorCode?: string;
35 /** Error message returned from Ansible. */
36 ansibleError?: string;
37 /** Error message returned from Terraform. */
38 terraformError?: string;
39 /** Cloud Build instance UUID. */
40 cloudbuildId?: string;
41 /** Failed Ansible task names. */
42 ansibleFailedTask?: string[];
43 /** Link to the actuation Cloud Build log. */
44 errorLogs?: string;
45 /** Whether the error message is user facing. */
46 hasUserFacingErrorMsg?: boolean;
47 };
48
49 export type DeploymentOutput = {
50 /** Type of the deployed resource. */
51 type?: string;
52 /** Name of the deployed resource. */
53 name?: string;
54 };
55
56 export type DeploymentsActuationProps = {
57 /**
58 * Parent Deployment. Full name
59 * `projects/{project}/locations/{location}/deployments/{deployment}`
60 * or the deployment id (combined with `location`). Immutable —
61 * changing it replaces the actuation.
62 */
63 deployment: string;
64 /**
65 * Region used when `deployment` is a bare id.
66 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
67 */
68 location?: string;
69 /**
70 * Actuation id (the `{actuation}` segment). If omitted, a unique
71 * RFC1035 name prefixed `alch-` is generated from the stack, stage,
72 * and logical id so `list` / nuke can find it (actuations have no
73 * labels or description). Immutable — changing it replaces the
74 * actuation. The API has no patch — actuations are existence-only.
75 */
76 actuationId?: string;
77 };
78
79 export type DeploymentsActuation = Resource<
80 "GCP.WorkloadManager.DeploymentsActuation",
81 DeploymentsActuationProps,
82 {
83 /** Full resource name. */
84 name: string;
85 /** Actuation id (last path segment). */
86 actuationId: string;
87 /** Parent Deployment name. */
88 deployment: string;
89 /** Project id. */
90 project: string;
91 /** Location id. */
92 location: string;
93 /** Server-reported actuation state. */
94 state: string | undefined;
95 /** Actuation output (logs, errors, Cloud Build id). */
96 actuationOutput: ActuationOutput | undefined;
97 /** Resources produced by the deployment. */
98 deploymentOutput: DeploymentOutput[];
99 /** RFC3339 start timestamp. */
100 startTime: string | undefined;
101 /** RFC3339 end timestamp. */
102 endTime: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * A Workload Manager actuation — a bootstrap run of a Deployment that
110 * applies Terraform/Ansible and records infrastructure output.
111 *
112 * Actuations have no labels, description, or patch API. Identity is
113 * `deployment` + `location` + `actuationId`; changing any replaces the
114 * actuation. Generated ids are prefixed `alch-` so `list` / nuke can
115 * find Alchemy-owned rows.
116 *
117 * ### Creating an Actuation
118 * **Example:** Generated name
119 * ```typescript
120 * const actuation = yield* GCP.WorkloadManager.DeploymentsActuation(
121 * "Bootstrap",
122 * { deployment: existingDeployment.name },
123 * );
124 * ```
125 *
126 * **Example:** Explicit id
127 * ```typescript
128 * const actuation = yield* GCP.WorkloadManager.DeploymentsActuation(
129 * "Bootstrap",
130 * {
131 * deployment: existingDeployment.name,
132 * actuationId: "alch-bootstrap-1",
133 * },
134 * );
135 * ```
136 *
137 * @resource
138 * @category WorkloadManager
139 */
140 export const DeploymentsActuation = Resource<DeploymentsActuation>(
141 "GCP.WorkloadManager.DeploymentsActuation",
142 );
143
144 const resourceName = (deployment: string, actuationId: string) =>
145 `${deployment}/actuations/${actuationId}`;
146
147 const toOutput = (
148 output: workloadmanager.ActuationOutput | undefined,
149 ): ActuationOutput | undefined =>
150 output === undefined
151 ? undefined
152 : {
153 blueprintId: output.blueprintId,
154 terraformTemplate: output.terraformTemplate,
155 actuateLogs: output.actuateLogs,
156 errorCode: output.errorCode,
157 ansibleError: output.ansibleError,
158 terraformError: output.terraformError,
159 cloudbuildId: output.cloudbuildId,
160 ansibleFailedTask: output.ansibleFailedTask,
161 errorLogs: output.errorLogs,
162 hasUserFacingErrorMsg: output.hasUserFacingErrorMsg,
163 };
164
165 const toAttrs = (item: workloadmanager.Actuation, project: string, region: string) => {
166 const name = item.name ?? "";
167 const parsed = parseName(name, "actuations", region);
168 return {
169 name,
170 actuationId: parsed.id,
171 deployment: parsed.parent,
172 project: parsed.project || project,
173 location: parsed.location,
174 state: item.state,
175 actuationOutput: toOutput(item.actuationOutput),
176 deploymentOutput: (item.deploymentOutput ?? []).map((entry) => ({
177 type: entry.type,
178 name: entry.name,
179 })),
180 startTime: item.startTime,
181 endTime: item.endTime,
182 };
183 };
184
185 const getByName = (name: string) =>
186 workloadmanager
187 .getProjectsLocationsDeploymentsActuations({ name })
188 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
189
190 const listOwned = (project: string, region: string) =>
191 listAtNested(project, region, "deployments/-", (parent) =>
192 listPages(
193 workloadmanager.listProjectsLocationsDeploymentsActuations.pages({
194 parent,
195 pageSize: 1000,
196 }),
197 (page) => page.actuations,
198 (item) => hasAlchemyActuationId(lastSegment(item.name ?? "")),
199 ),
200 );
201
202 export const DeploymentsActuationProvider = () =>
203 Provider.succeed(DeploymentsActuation, {
204 stables: ["name", "actuationId", "deployment", "project", "location", "startTime"],
205
206 diff: Effect.fn(function* ({ news, olds, output }) {
207 if (!isResolved(news)) return undefined;
208 const env = yield* GcpEnvironment.current;
209 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
210 const nextLocation = normalizeLocation(
211 news.location ?? olds?.location ?? output?.location,
212 env.region,
213 );
214 const previousParent =
215 (olds?.deployment ?? output?.deployment)
216 ? expandNamed(
217 olds?.deployment ?? output?.deployment ?? "",
218 env.project,
219 previousLocation,
220 "deployments",
221 )
222 : undefined;
223 const nextParent = expandNamed(news.deployment, env.project, nextLocation, "deployments");
224 return replaceOnIdentity({
225 previousId: olds?.actuationId ?? output?.actuationId,
226 nextId: news.actuationId ?? olds?.actuationId ?? output?.actuationId,
227 previousLocation,
228 nextLocation,
229 previousParent,
230 nextParent,
231 });
232 }),
233
234 read: Effect.fn(function* ({ id, olds, output }) {
235 const env = yield* GcpEnvironment.current;
236 const actuationId = yield* toActuationId(id, olds?.actuationId, output?.actuationId);
237 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
238 const deployment = expandNamed(
239 olds?.deployment ?? output?.deployment ?? "",
240 env.project,
241 location,
242 "deployments",
243 );
244 const name = output?.name ?? resourceName(deployment, actuationId);
245 const existing = yield* getByName(name);
246 if (existing === undefined) return undefined;
247 return toAttrs(existing, env.project, env.region);
248 }),
249
250 list: () =>
251 Effect.gen(function* () {
252 const env = yield* GcpEnvironment.current;
253 const items = yield* listOwned(env.project, env.region);
254 return items.map((item) => toAttrs(item, env.project, env.region));
255 }),
256
257 reconcile: Effect.fn(function* ({ id, news, output }) {
258 const env = yield* GcpEnvironment.current;
259 const actuationId = yield* toActuationId(id, news.actuationId, output?.actuationId);
260 const location = normalizeLocation(news.location ?? output?.location, env.region);
261 const deployment = expandNamed(news.deployment, env.project, location, "deployments");
262 const name = resourceName(deployment, actuationId);
263
264 let current = yield* getByName(output?.name ?? name);
265
266 if (current === undefined) {
267 const created = yield* workloadmanager
268 .createProjectsLocationsDeploymentsActuations({
269 parent: deployment,
270 body: { name },
271 })
272 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
273 if (created !== undefined) {
274 // ALREADY_EXISTS (6): a concurrent create won the race.
275 yield* waitForOperation(created).pipe(
276 Effect.catchTag("GCP.OperationFailed", (error) =>
277 error.code === 6 ? Effect.void : Effect.fail(error),
278 ),
279 );
280 const fromOp = resourceNameFromOperation(created);
281 current = yield* waitUntilExists(getByName(fromOp ?? name), fromOp ?? name);
282 } else {
283 current = yield* waitUntilExists(getByName(name), name);
284 }
285 }
286
287 if (current === undefined) {
288 return yield* new ResourceNotResolved({ resourceName: name });
289 }
290
291 return toAttrs(current, env.project, env.region);
292 }),
293
294 delete: Effect.fn(function* ({ output }) {
295 const operation = yield* workloadmanager
296 .deleteProjectsLocationsDeploymentsActuations({
297 name: output.name,
298 })
299 .pipe(
300 Effect.retry({
301 while: (error) => error._tag === "Conflict",
302 times: 8,
303 schedule: Schedule.spaced("2 seconds"),
304 }),
305 Effect.catchTag("NotFound", () => Effect.undefined),
306 );
307 if (operation !== undefined) {
308 // NOT_FOUND (5): already gone.
309 yield* waitForOperation(operation).pipe(
310 Effect.catchTag("GCP.OperationFailed", (error) =>
311 error.code === 5 ? Effect.void : Effect.fail(error),
312 ),
313 );
314 }
315 yield* waitUntilGone(getByName(output.name), output.name);
316 }),
317 });