@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 417 lines 12.8 KB
Raw
1 import * as deploymentmanager from "@distilled.cloud/gcp/deploymentmanager_v2";
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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 fingerprint,
13 getDeployment,
14 getManifest,
15 labelsToRecord,
16 listOwnedDeployments,
17 recordToLabels,
18 ResourceNotResolved,
19 sameText,
20 settleDeployment,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilExists,
25 waitUntilGone,
26 } from "./internal.ts";
27
28 export type ImportFile = {
29 /**
30 * Import name, as referenced from `target.config` (`path` / `type`).
31 */
32 name?: string;
33 /**
34 * Full contents of the imported template or file.
35 */
36 content?: string;
37 };
38
39 export type ConfigFile = {
40 /**
41 * YAML configuration that lists the resources in this deployment.
42 */
43 content: string;
44 };
45
46 export type TargetConfiguration = {
47 /**
48 * Root configuration file for the deployment.
49 */
50 config: ConfigFile;
51 /**
52 * Templates or other files imported by `config`.
53 */
54 imports?: ImportFile[];
55 };
56
57 export type DeploymentProps = {
58 /**
59 * Deployment name. If omitted, a unique RFC1035 name is generated
60 * from the stack, stage, and logical id. Immutable — changing it
61 * replaces the deployment.
62 */
63 deploymentId?: string;
64 /**
65 * User-provided description of the deployment.
66 */
67 description?: string;
68 /**
69 * User labels. Alchemy ownership labels are merged in automatically.
70 * Keys and values must match `[a-z]([-a-z0-9]*[a-z0-9])?`.
71 */
72 labels?: Record<string, string>;
73 /**
74 * Configuration and imports that describe the resources to deploy.
75 */
76 target: TargetConfiguration;
77 /**
78 * Policy for creating resources in the configuration
79 * (`CREATE_OR_ACQUIRE` or `ACQUIRE`).
80 * @default "CREATE_OR_ACQUIRE"
81 */
82 createPolicy?: deploymentmanager.InsertDeploymentsCreatePolicyEnum | (string & {});
83 /**
84 * Policy for deleting resources when the deployment is destroyed
85 * (`DELETE` or `ABANDON`).
86 * @default "DELETE"
87 */
88 deletePolicy?: deploymentmanager.DeleteDeploymentsDeletePolicyEnum | (string & {});
89 /**
90 * When true, create or update shell resources without instantiating
91 * them. A later reconcile with `preview: false` deploys the preview.
92 * @default false
93 */
94 preview?: boolean;
95 };
96
97 export type Deployment = Resource<
98 "GCP.DeploymentManager.Deployment",
99 DeploymentProps,
100 {
101 /** Deployment name (RFC1035). */
102 name: string;
103 /** Deployment id; same as `name`. */
104 deploymentId: string;
105 /** Project id. */
106 project: string;
107 /** User description. */
108 description: string | undefined;
109 /** User labels (Alchemy ownership labels stripped). */
110 labels: Record<string, string>;
111 /** Optimistic-locking fingerprint for update, stop, and cancelPreview. */
112 fingerprint: string | undefined;
113 /** URL of the last successfully deployed manifest. */
114 manifest: string | undefined;
115 /** Server-defined URL for the deployment. */
116 selfLink: string | undefined;
117 /** RFC3339 creation timestamp. */
118 insertTime: string | undefined;
119 /** RFC3339 last-update timestamp. */
120 updateTime: string | undefined;
121 /** Server-assigned numeric id. */
122 id: string | undefined;
123 /**
124 * True when Deployment Manager is previewing an update (`update` is
125 * present on the live resource).
126 */
127 preview: boolean;
128 /** Delete policy applied when destroying this deployment. */
129 deletePolicy: string;
130 },
131 never,
132 Providers
133 >;
134
135 /**
136 * A Google Cloud Deployment Manager deployment — a configuration that
137 * creates and manages a set of Google Cloud resources together.
138 *
139 * Changing `deploymentId` replaces the deployment. Description, labels,
140 * target configuration, and `preview` update in place. Create, patch,
141 * and delete return long-running operations.
142 *
143 * ### Creating a Deployment
144 * **Example:** Generated name
145 * ```typescript
146 * const deployment = yield* GCP.DeploymentManager.Deployment("App", {
147 * target: {
148 * config: {
149 * content: `resources:
150 * - name: topic
151 * type: pubsub.v1.topic
152 * properties:
153 * topic: my-topic
154 * `,
155 * },
156 * },
157 * });
158 * ```
159 *
160 * **Example:** Explicit name, labels, and imported template
161 * ```typescript
162 * const deployment = yield* GCP.DeploymentManager.Deployment("App", {
163 * deploymentId: "order-events",
164 * description: "pubsub topic for orders",
165 * labels: { env: "prod" },
166 * target: {
167 * config: {
168 * content: `imports:
169 * - path: topic.jinja
170 * resources:
171 * - name: topic
172 * type: topic.jinja
173 * `,
174 * },
175 * imports: [
176 * {
177 * name: "topic.jinja",
178 * content: `resources:
179 * - name: topic
180 * type: pubsub.v1.topic
181 * properties:
182 * topic: {{ env["deployment"] }}
183 * `,
184 * },
185 * ],
186 * },
187 * });
188 * ```
189 *
190 * ### Updating a Deployment
191 * Re-declare the same logical id with changed props; the engine keeps the
192 * physical resource and updates it in place.
193 *
194 * **Example:** Labels and description
195 * ```typescript
196 * const deployment = yield* GCP.DeploymentManager.Deployment("App", {
197 * description: "pubsub topic for orders (prod)",
198 * labels: { env: "prod", team: "platform" },
199 * target: existingTarget,
200 * });
201 * ```
202 *
203 * @resource
204 * @category DeploymentManager
205 */
206 export const Deployment = Resource<Deployment>("GCP.DeploymentManager.Deployment");
207
208 const DEFAULT_CREATE_POLICY = "CREATE_OR_ACQUIRE";
209 const DEFAULT_DELETE_POLICY = "DELETE";
210
211 const desiredTarget = (target: TargetConfiguration): deploymentmanager.TargetConfiguration => ({
212 config: { content: target.config.content },
213 imports:
214 target.imports === undefined
215 ? undefined
216 : target.imports.map((file) => ({
217 name: file.name,
218 content: file.content,
219 })),
220 });
221
222 const observedTarget = (
223 manifest: deploymentmanager.Manifest | undefined,
224 ): TargetConfiguration | undefined => {
225 if (manifest === undefined) return undefined;
226 return {
227 config: { content: manifest.config?.content ?? "" },
228 imports: (manifest.imports ?? []).map((file) => ({
229 name: file.name,
230 content: file.content,
231 })),
232 };
233 };
234
235 const toAttrs = (item: deploymentmanager.Deployment, project: string, deletePolicy: string) => ({
236 name: item.name ?? "",
237 deploymentId: item.name ?? "",
238 project,
239 description: item.description,
240 labels: userLabels(labelsToRecord(item.labels)),
241 fingerprint: item.fingerprint,
242 manifest: item.manifest,
243 selfLink: item.selfLink,
244 insertTime: item.insertTime,
245 updateTime: item.updateTime,
246 id: item.id,
247 preview: item.update !== undefined,
248 deletePolicy,
249 });
250
251 const replaceOnName = (input: { previousId: string | undefined; nextId: string | undefined }) => {
252 if (
253 input.previousId === undefined ||
254 input.nextId === undefined ||
255 input.nextId === input.previousId
256 ) {
257 return undefined;
258 }
259 return {
260 action: "replace" as const,
261 deleteFirst: false,
262 };
263 };
264
265 export const DeploymentProvider = () =>
266 Provider.succeed(Deployment, {
267 stables: ["name", "deploymentId", "project", "id", "insertTime"],
268
269 diff: Effect.fn(function* ({ news, olds, output }) {
270 if (!isResolved(news)) return undefined;
271 return replaceOnName({
272 previousId: olds?.deploymentId ?? output?.deploymentId,
273 nextId: news.deploymentId ?? olds?.deploymentId ?? output?.deploymentId,
274 });
275 }),
276
277 read: Effect.fn(function* ({ id, olds, output }) {
278 const env = yield* GcpEnvironment.current;
279 const deploymentId = yield* toPhysicalId(id, olds?.deploymentId, output?.deploymentId);
280 const existing = yield* getDeployment(env.project, output?.name ?? deploymentId);
281 if (existing === undefined) return undefined;
282 const attrs = toAttrs(
283 existing,
284 env.project,
285 olds?.deletePolicy ?? output?.deletePolicy ?? DEFAULT_DELETE_POLICY,
286 );
287 return (yield* hasAlchemyLabels(id, labelsToRecord(existing.labels)))
288 ? attrs
289 : Unowned(attrs);
290 }),
291
292 list: () =>
293 Effect.gen(function* () {
294 const env = yield* GcpEnvironment.current;
295 const items = yield* listOwnedDeployments(env.project);
296 return items.map((item) => toAttrs(item, env.project, DEFAULT_DELETE_POLICY));
297 }),
298
299 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
300 const env = yield* GcpEnvironment.current;
301 const deploymentId = yield* toPhysicalId(id, news.deploymentId, output?.deploymentId);
302 const desiredLabels = {
303 ...toLabels(news.labels),
304 ...(yield* createInternalLabels(id)),
305 };
306 const target = desiredTarget(news.target);
307 const preview = news.preview === true;
308 const createPolicy = news.createPolicy ?? DEFAULT_CREATE_POLICY;
309 const deletePolicy = news.deletePolicy ?? DEFAULT_DELETE_POLICY;
310
311 let current = yield* getDeployment(env.project, output?.name ?? deploymentId);
312 if (current !== undefined) {
313 yield* settleDeployment(env.project, current);
314 current = yield* getDeployment(env.project, current.name ?? deploymentId);
315 }
316
317 if (current === undefined) {
318 const created = yield* deploymentmanager
319 .insertDeployments({
320 project: env.project,
321 preview,
322 createPolicy,
323 body: {
324 name: deploymentId,
325 description: news.description,
326 labels: recordToLabels(desiredLabels),
327 target,
328 },
329 })
330 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
331 if (created !== undefined) {
332 yield* waitForOperation(env.project, created);
333 }
334 current = yield* waitUntilExists(getDeployment(env.project, deploymentId), deploymentId);
335 }
336
337 if (current === undefined) {
338 return yield* new ResourceNotResolved({ resourceName: deploymentId });
339 }
340
341 const name = current.name ?? deploymentId;
342 const observedLabels = labelsToRecord(current.labels);
343 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
344 const labelsChanged = upsert.length > 0 || removed.length > 0;
345 const descriptionChanged = !sameText(current.description, news.description);
346 const observedPreview = current.update !== undefined;
347 const previewChanged = observedPreview !== preview;
348 const manifest = yield* getManifest(
349 env.project,
350 name,
351 current.manifest ?? current.update?.manifest,
352 );
353 const targetChanged =
354 olds === undefined
355 ? fingerprint(observedTarget(manifest)) !== fingerprint(news.target)
356 : fingerprint(olds.target) !== fingerprint(news.target);
357
358 if (labelsChanged || descriptionChanged || previewChanged || targetChanged) {
359 const operation = yield* deploymentmanager
360 .patchDeployments({
361 project: env.project,
362 deployment: name,
363 preview,
364 createPolicy,
365 deletePolicy,
366 body: {
367 name,
368 fingerprint: current.fingerprint,
369 description: news.description,
370 labels: recordToLabels(desiredLabels),
371 target,
372 },
373 })
374 .pipe(
375 Effect.retry({
376 while: (error) => error._tag === "Conflict",
377 times: 8,
378 schedule: Schedule.spaced("2 seconds"),
379 }),
380 );
381 yield* waitForOperation(env.project, operation);
382 current = yield* waitUntilExists(getDeployment(env.project, name), name);
383 }
384
385 if (current === undefined) {
386 return yield* new ResourceNotResolved({ resourceName: name });
387 }
388
389 return toAttrs(current, env.project, deletePolicy);
390 }),
391
392 delete: Effect.fn(function* ({ output }) {
393 const env = yield* GcpEnvironment.current;
394 const existing = yield* getDeployment(env.project, output.name);
395 if (existing !== undefined) {
396 yield* settleDeployment(env.project, existing);
397 }
398 const operation = yield* deploymentmanager
399 .deleteDeployments({
400 project: env.project,
401 deployment: output.name,
402 deletePolicy: output.deletePolicy ?? DEFAULT_DELETE_POLICY,
403 })
404 .pipe(
405 Effect.retry({
406 while: (error) => error._tag === "Conflict",
407 times: 8,
408 schedule: Schedule.spaced("2 seconds"),
409 }),
410 Effect.catchTag("NotFound", () => Effect.undefined),
411 );
412 if (operation !== undefined) {
413 yield* waitForOperation(env.project, operation, { notFoundOk: true });
414 }
415 yield* waitUntilGone(getDeployment(env.project, output.name), output.name);
416 }),
417 });