@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 365 lines 12 KB
Raw
1 import * as config from "@distilled.cloud/gcp/config_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 expandNamed,
14 fieldMask,
15 fingerprint,
16 listAtLocation,
17 listLabeledPages,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 stringMap,
24 toPhysicalId,
25 userLabels,
26 waitForOperation,
27 waitUntilExists,
28 waitUntilGone,
29 } from "./internal.ts";
30
31 export type DeploymentUnit = {
32 /**
33 * Unit id. Must be unique within the deployment group.
34 */
35 id?: string;
36 /**
37 * Existing deployment this unit points at, as
38 * `projects/{project}/locations/{location}/deployments/{deployment}`
39 * or a deployment id (expanded in the group's location).
40 */
41 deployment?: string;
42 /**
43 * IDs of other units in this group that must finish first.
44 */
45 dependencies?: string[];
46 };
47
48 export type DeploymentGroupProps = {
49 /**
50 * Deployment group id (the `{deploymentGroup}` segment of
51 * `projects/{project}/locations/{location}/deploymentGroups/{deploymentGroup}`).
52 * If omitted, a unique RFC1035 name is generated from the stack, stage,
53 * and logical id. Immutable — changing it replaces the group.
54 */
55 deploymentGroupId?: string;
56 /**
57 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
58 * replaces the group. `US-CENTRAL1` is accepted and normalized to
59 * `us-central1`.
60 * @default the stack's GCP region (`GCP.Region`, else the profile
61 * region, else `us-central1`)
62 */
63 location?: string;
64 /**
65 * Deployment units arranged as a DAG. Units may reference an existing
66 * deployment or act as placeholders for a later provision call.
67 */
68 deploymentUnits?: DeploymentUnit[];
69 /**
70 * User annotations (not used by Infra Manager).
71 */
72 annotations?: Record<string, string>;
73 /**
74 * User labels. Alchemy ownership labels are merged in automatically.
75 */
76 labels?: Record<string, string>;
77 };
78
79 export type DeploymentGroup = Resource<
80 "GCP.Config.DeploymentGroup",
81 DeploymentGroupProps,
82 {
83 /** Full resource name. */
84 name: string;
85 /** Deployment group id (last path segment). */
86 deploymentGroupId: string;
87 /** Project id. */
88 project: string;
89 /** Location id. */
90 location: string;
91 /** Deployment units. */
92 deploymentUnits: DeploymentUnit[];
93 /** Server-reported resource state. */
94 state: string | undefined;
95 /** Extra state information. */
96 stateDescription: string | undefined;
97 /** Server-reported provisioning state. */
98 provisioningState: string | undefined;
99 /** Extra provisioning-state information. */
100 provisioningStateDescription: string | undefined;
101 /** User annotations. */
102 annotations: Record<string, string>;
103 /** User labels (Alchemy ownership labels stripped). */
104 labels: Record<string, string>;
105 /** RFC3339 creation timestamp. */
106 createTime: string | undefined;
107 /** RFC3339 last-update timestamp. */
108 updateTime: string | undefined;
109 },
110 never,
111 Providers
112 >;
113
114 /**
115 * An Infrastructure Manager deployment group — a DAG of deployment units
116 * provisioned together.
117 *
118 * Changing `deploymentGroupId` or `location` replaces the group. Units,
119 * labels, and annotations update in place. Create, patch, and delete are
120 * long-running operations.
121 *
122 * ### Creating a Deployment Group
123 * **Example:** Generated name
124 * ```typescript
125 * const group = yield* GCP.Config.DeploymentGroup("App", {
126 * deploymentUnits: [{ id: "network", dependencies: [] }],
127 * });
128 * ```
129 *
130 * **Example:** Explicit id and labels
131 * ```typescript
132 * const group = yield* GCP.Config.DeploymentGroup("App", {
133 * deploymentGroupId: "app-group",
134 * deploymentUnits: [
135 * { id: "network", dependencies: [] },
136 * { id: "cluster", dependencies: ["network"] },
137 * ],
138 * labels: { env: "prod" },
139 * });
140 * ```
141 *
142 * ### Updating a Deployment Group
143 * **Example:** Labels and units
144 * ```typescript
145 * // Same logical id as before; only the changed props differ.
146 * const group = yield* GCP.Config.DeploymentGroup("App", {
147 * deploymentGroupId: "app-group",
148 * deploymentUnits: [
149 * { id: "network", dependencies: [] },
150 * { id: "cluster", dependencies: ["network"] },
151 * { id: "apps", dependencies: ["cluster"] },
152 * ],
153 * labels: { env: "prod", team: "platform" },
154 * });
155 * ```
156 *
157 * @resource
158 * @category Config
159 */
160 export const DeploymentGroup = Resource<DeploymentGroup>("GCP.Config.DeploymentGroup");
161
162 const resourceName = (project: string, location: string, deploymentGroupId: string) =>
163 `projects/${project}/locations/${location}/deploymentGroups/${deploymentGroupId}`;
164
165 const toUnits = (
166 units: readonly config.DeploymentUnit[] | undefined,
167 project: string,
168 location: string,
169 ): DeploymentUnit[] =>
170 (units ?? []).map((unit) => ({
171 id: unit.id,
172 deployment:
173 unit.deployment === undefined
174 ? undefined
175 : expandNamed(unit.deployment, project, location, "deployments"),
176 dependencies: unit.dependencies,
177 }));
178
179 const desiredUnits = (
180 units: readonly DeploymentUnit[] | undefined,
181 project: string,
182 location: string,
183 ): config.DeploymentUnit[] =>
184 (units ?? []).map((unit) => ({
185 id: unit.id,
186 deployment:
187 unit.deployment === undefined
188 ? undefined
189 : expandNamed(unit.deployment, project, location, "deployments"),
190 dependencies: unit.dependencies,
191 }));
192
193 const toAttrs = (item: config.DeploymentGroup, project: string, region: string) => {
194 const name = item.name ?? "";
195 const parsed = parseName(name, "deploymentGroups", region);
196 const resolvedProject = parsed.project || project;
197 return {
198 name,
199 deploymentGroupId: parsed.id,
200 project: resolvedProject,
201 location: parsed.location,
202 deploymentUnits: toUnits(item.deploymentUnits, resolvedProject, parsed.location),
203 state: item.state,
204 stateDescription: item.stateDescription,
205 provisioningState: item.provisioningState,
206 provisioningStateDescription: item.provisioningStateDescription,
207 annotations: stringMap(item.annotations),
208 labels: userLabels(item.labels),
209 createTime: item.createTime,
210 updateTime: item.updateTime,
211 };
212 };
213
214 const getByName = (name: string) =>
215 config
216 .getProjectsLocationsDeploymentGroups({ name })
217 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
218
219 const listOwned = (project: string, region: string) =>
220 listAtLocation(project, region, (parent) =>
221 listLabeledPages(
222 config.listProjectsLocationsDeploymentGroups.pages({
223 parent,
224 pageSize: 1000,
225 }),
226 (page) => page.deploymentGroups,
227 (item) => item.labels,
228 ),
229 );
230
231 /** Deployment group ids are at most 40 characters. */
232 const MAX_DEPLOYMENT_GROUP_ID_LENGTH = 40;
233
234 export const DeploymentGroupProvider = () =>
235 Provider.succeed(DeploymentGroup, {
236 stables: ["name", "deploymentGroupId", "project", "location", "createTime"],
237
238 diff: Effect.fn(function* ({ news, olds, output }) {
239 if (!isResolved(news)) return undefined;
240 const env = yield* GcpEnvironment.current;
241 return replaceOnIdentity({
242 previousId: olds?.deploymentGroupId ?? output?.deploymentGroupId,
243 nextId: news.deploymentGroupId ?? olds?.deploymentGroupId ?? output?.deploymentGroupId,
244 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
245 nextLocation: normalizeLocation(
246 news.location ?? olds?.location ?? output?.location,
247 env.region,
248 ),
249 });
250 }),
251
252 read: Effect.fn(function* ({ id, olds, output }) {
253 const env = yield* GcpEnvironment.current;
254 const deploymentGroupId = yield* toPhysicalId(
255 id,
256 olds?.deploymentGroupId,
257 output?.deploymentGroupId,
258 "deploymentgroup",
259 MAX_DEPLOYMENT_GROUP_ID_LENGTH,
260 );
261 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
262 const name = output?.name ?? resourceName(env.project, location, deploymentGroupId);
263 const existing = yield* getByName(name);
264 if (existing === undefined) return undefined;
265 const attrs = toAttrs(existing, env.project, env.region);
266 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
267 }),
268
269 list: () =>
270 Effect.gen(function* () {
271 const env = yield* GcpEnvironment.current;
272 const items = yield* listOwned(env.project, env.region);
273 return items.map((item) => toAttrs(item, env.project, env.region));
274 }),
275
276 reconcile: Effect.fn(function* ({ id, news, output }) {
277 const env = yield* GcpEnvironment.current;
278 const deploymentGroupId = yield* toPhysicalId(
279 id,
280 news.deploymentGroupId,
281 output?.deploymentGroupId,
282 "deploymentgroup",
283 MAX_DEPLOYMENT_GROUP_ID_LENGTH,
284 );
285 const location = normalizeLocation(news.location ?? output?.location, env.region);
286 const name = resourceName(env.project, location, deploymentGroupId);
287 const desiredLabels = {
288 ...toLabels(news.labels),
289 ...(yield* createInternalLabels(id)),
290 };
291 const desiredAnnotations = news.annotations ?? {};
292 const units = desiredUnits(news.deploymentUnits, env.project, location);
293
294 let current = yield* getByName(output?.name ?? name);
295
296 if (current === undefined) {
297 const created = yield* config
298 .createProjectsLocationsDeploymentGroups({
299 parent: parentOf(env.project, location),
300 deploymentGroupId,
301 body: {
302 deploymentUnits: units,
303 annotations: desiredAnnotations,
304 labels: desiredLabels,
305 },
306 })
307 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
308 if (created !== undefined) {
309 yield* waitForOperation(created);
310 }
311 current = yield* waitUntilExists(getByName(name), name);
312 }
313
314 if (current === undefined) {
315 return yield* new ResourceNotResolved({ resourceName: name });
316 }
317
318 const observedLabels = tagRecord(current.labels);
319 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
320 const mask = fieldMask([
321 (upsert.length > 0 || removed.length > 0) && "labels",
322 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
323 "annotations",
324 fingerprint(toUnits(current.deploymentUnits, env.project, location)) !==
325 fingerprint(units) && "deploymentUnits",
326 ]);
327
328 if (mask.length > 0) {
329 const operation = yield* config.patchProjectsLocationsDeploymentGroups({
330 name: current.name ?? name,
331 updateMask: mask,
332 body: {
333 labels: desiredLabels,
334 annotations: desiredAnnotations,
335 deploymentUnits: units,
336 },
337 });
338 yield* waitForOperation(operation);
339 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
340 }
341
342 return toAttrs(current, env.project, env.region);
343 }),
344
345 delete: Effect.fn(function* ({ output }) {
346 const operation = yield* config
347 .deleteProjectsLocationsDeploymentGroups({
348 name: output.name,
349 force: true,
350 deploymentReferencePolicy: "IGNORE_DEPLOYMENT_REFERENCES",
351 })
352 .pipe(
353 Effect.retry({
354 while: (error) => error._tag === "Conflict",
355 times: 8,
356 schedule: Schedule.spaced("2 seconds"),
357 }),
358 Effect.catchTag("NotFound", () => Effect.undefined),
359 );
360 if (operation !== undefined) {
361 yield* waitForOperation(operation, { notFoundOk: true });
362 }
363 yield* waitUntilGone(getByName(output.name), output.name);
364 }),
365 });