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

main
ts 347 lines 11.7 KB
Raw
1 import * as osconfig from "@distilled.cloud/gcp/osconfig_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 { 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 DEFAULT_ACTION,
14 DEFAULT_STATE,
15 OsconfigNotResolved,
16 collectOrchestrators,
17 defaultOrchestratedResource,
18 fieldMask,
19 fingerprint,
20 globalParent,
21 hasAlchemyLabelMap,
22 orchestratedPayload,
23 parseName,
24 projectParent,
25 replaceOnIdentity,
26 resourceName,
27 toPhysicalId,
28 userLabels,
29 waitForOperation,
30 waitUntilExists,
31 waitUntilGone,
32 type OrchestratedResource,
33 type OrchestrationScope,
34 } from "./internal.ts";
35
36 export type ProjectsLocationsGlobalPolicyOrchestratorProps = {
37 /**
38 * Orchestrator id (the `{policyOrchestrator}` segment of
39 * `projects/{project}/locations/global/policyOrchestrators/{policyOrchestrator}`).
40 * If omitted, a unique RFC1035 name is generated. Immutable — changing
41 * it replaces the orchestrator.
42 */
43 policyOrchestratorId?: string;
44 /**
45 * Action applied to matching OS policy assignments.
46 * `UPSERT` creates or updates; `DELETE` removes them.
47 * @default "UPSERT"
48 */
49 action?: string;
50 /**
51 * Orchestrator state. `ACTIVE` applies changes; `STOPPED` is idle.
52 * Defaults to `STOPPED` so create does not roll out assignments.
53 * @default "STOPPED"
54 */
55 state?: string;
56 /**
57 * Free-form description of the orchestrator.
58 */
59 description?: string;
60 /**
61 * User labels. Alchemy ownership labels are merged in automatically.
62 */
63 labels?: Record<string, string>;
64 /**
65 * Resource the orchestrator creates, updates, or deletes. When omitted,
66 * a no-op VALIDATION OS policy assignment is used.
67 */
68 orchestratedResource?: OrchestratedResource;
69 /**
70 * Scope of projects, folders, and zones the orchestrator targets.
71 * When omitted, the parent project is the entire scope.
72 */
73 orchestrationScope?: OrchestrationScope;
74 };
75
76 export type ProjectsLocationsGlobalPolicyOrchestrator = Resource<
77 "GCP.OSConfig.ProjectsLocationsGlobalPolicyOrchestrator",
78 ProjectsLocationsGlobalPolicyOrchestratorProps,
79 {
80 /** Full resource name. */
81 name: string;
82 /** Orchestrator id (last path segment). */
83 policyOrchestratorId: string;
84 /** Parent `projects/{project}/locations/global`. */
85 parent: string;
86 /** Project id. */
87 project: string;
88 /** Orchestration action (`UPSERT` or `DELETE`). */
89 action: string | undefined;
90 /** Orchestrator state (`ACTIVE` or `STOPPED`). */
91 state: string | undefined;
92 /** User description. */
93 description: string | undefined;
94 /** User labels (Alchemy ownership labels stripped). */
95 labels: Record<string, string>;
96 /** Orchestrated OS policy assignment payload. */
97 orchestratedResource: OrchestratedResource | undefined;
98 /** Orchestration scope selectors. */
99 orchestrationScope: OrchestrationScope | undefined;
100 /** Whether the orchestrator is currently applying changes. */
101 reconciling: boolean | undefined;
102 /** Server checksum used on update and delete. */
103 etag: string | undefined;
104 /** RFC3339 creation timestamp. */
105 createTime: string | undefined;
106 /** RFC3339 last-update timestamp. */
107 updateTime: string | undefined;
108 },
109 never,
110 Providers
111 >;
112
113 /**
114 * A project-scoped OS Config policy orchestrator.
115 *
116 * Policy orchestrators upsert or delete OS policy assignments across
117 * zones in a project. Id is identity — changing `policyOrchestratorId`
118 * replaces the resource. Action, state, description, labels, the
119 * orchestrated payload, and scope update in place.
120 *
121 * ### Creating a Policy Orchestrator
122 * **Example:** Generated name, stopped
123 * ```typescript
124 * const orch = yield* GCP.OSConfig.ProjectsLocationsGlobalPolicyOrchestrator(
125 * "Debian",
126 * { labels: { env: "test" } },
127 * );
128 * ```
129 *
130 * **Example:** Explicit id and description
131 * ```typescript
132 * const orch = yield* GCP.OSConfig.ProjectsLocationsGlobalPolicyOrchestrator(
133 * "Debian",
134 * {
135 * policyOrchestratorId: "debian-noop",
136 * description: "validation only",
137 * state: "STOPPED",
138 * },
139 * );
140 * ```
141 *
142 * ### Updating a Policy Orchestrator
143 * **Example:** Change labels and description
144 * ```typescript
145 * const orch = yield* GCP.OSConfig.ProjectsLocationsGlobalPolicyOrchestrator(
146 * "Debian",
147 * {
148 * description: "updated",
149 * labels: { env: "prod" },
150 * },
151 * );
152 * ```
153 *
154 * @resource
155 * @category OSConfig
156 */
157 export const ProjectsLocationsGlobalPolicyOrchestrator =
158 Resource<ProjectsLocationsGlobalPolicyOrchestrator>(
159 "GCP.OSConfig.ProjectsLocationsGlobalPolicyOrchestrator",
160 );
161
162 const toAttrs = (item: osconfig.GoogleCloudOsconfigV2__PolicyOrchestrator, project: string) => {
163 const name = item.name ?? "";
164 const parsed = parseName(name);
165 return {
166 name,
167 policyOrchestratorId: parsed.id,
168 parent: parsed.parent,
169 project: parsed.project || project,
170 action: item.action,
171 state: item.state,
172 description: item.description,
173 labels: userLabels(item.labels),
174 orchestratedResource: item.orchestratedResource,
175 orchestrationScope: item.orchestrationScope,
176 reconciling: item.reconciling,
177 etag: item.etag,
178 createTime: item.createTime,
179 updateTime: item.updateTime,
180 };
181 };
182
183 const getByName = (name: string) =>
184 name.length === 0
185 ? Effect.undefined
186 : osconfig
187 .getProjectsLocationsGlobalPolicyOrchestrators({ name })
188 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
189
190 const desiredBody = (
191 news: ProjectsLocationsGlobalPolicyOrchestratorProps,
192 policyOrchestratorId: string,
193 desiredLabels: Record<string, string>,
194 ): osconfig.GoogleCloudOsconfigV2__PolicyOrchestrator => ({
195 action: news.action ?? DEFAULT_ACTION,
196 state: news.state ?? DEFAULT_STATE,
197 description: news.description,
198 labels: desiredLabels,
199 orchestratedResource: orchestratedPayload(
200 news.orchestratedResource ?? defaultOrchestratedResource(rfcResourceId(policyOrchestratorId)),
201 ),
202 orchestrationScope: news.orchestrationScope,
203 });
204
205 const rfcResourceId = (policyOrchestratorId: string) => policyOrchestratorId.slice(0, 63);
206
207 export const ProjectsLocationsGlobalPolicyOrchestratorProvider = () =>
208 Provider.succeed(ProjectsLocationsGlobalPolicyOrchestrator, {
209 stables: ["name", "policyOrchestratorId", "parent", "project", "createTime"],
210
211 diff: Effect.fn(function* ({ news, olds, output }) {
212 if (!isResolved(news)) return undefined;
213 const previousParent = output?.parent ?? "";
214 const nextParent = previousParent;
215 return replaceOnIdentity({
216 previousId: olds?.policyOrchestratorId ?? output?.policyOrchestratorId,
217 nextId:
218 news.policyOrchestratorId ?? olds?.policyOrchestratorId ?? output?.policyOrchestratorId,
219 previousParent,
220 nextParent,
221 });
222 }),
223
224 read: Effect.fn(function* ({ id, olds, output }) {
225 const env = yield* GcpEnvironment.current;
226 const policyOrchestratorId = yield* toPhysicalId(
227 id,
228 olds?.policyOrchestratorId,
229 output?.policyOrchestratorId,
230 );
231 const parent = globalParent(projectParent(env.project));
232 const name = output?.name ?? resourceName(parent, policyOrchestratorId);
233 const existing = yield* getByName(name);
234 if (existing === undefined) return undefined;
235 const attrs = toAttrs(existing, env.project);
236 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
237 }),
238
239 list: () =>
240 Effect.gen(function* () {
241 const env = yield* GcpEnvironment.current;
242 const items = yield* collectOrchestrators(
243 osconfig.listProjectsLocationsGlobalPolicyOrchestrators.pages({
244 parent: globalParent(projectParent(env.project)),
245 pageSize: 1000,
246 }),
247 );
248 return items
249 .filter((item) => hasAlchemyLabelMap(item.labels))
250 .map((item) => toAttrs(item, env.project));
251 }),
252
253 reconcile: Effect.fn(function* ({ id, news, output }) {
254 const env = yield* GcpEnvironment.current;
255 const policyOrchestratorId = yield* toPhysicalId(
256 id,
257 news.policyOrchestratorId,
258 output?.policyOrchestratorId,
259 );
260 const parent = globalParent(projectParent(env.project));
261 const name = resourceName(parent, policyOrchestratorId);
262 const desiredLabels = {
263 ...toLabels(news.labels),
264 ...(yield* createInternalLabels(id)),
265 };
266 const desired = desiredBody(news, policyOrchestratorId, desiredLabels);
267
268 let current = yield* getByName(output?.name ?? name);
269
270 if (current === undefined) {
271 const created = yield* osconfig
272 .createProjectsLocationsGlobalPolicyOrchestrators({
273 parent,
274 policyOrchestratorId,
275 body: desired,
276 })
277 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
278 if (created !== undefined) {
279 yield* waitForOperation(created);
280 }
281 current = yield* waitUntilExists(getByName(name), name);
282 }
283
284 if (current === undefined) {
285 return yield* new OsconfigNotResolved({ resourceName: name });
286 }
287
288 const observedLabels = tagRecord(current.labels);
289 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
290 const labelsChanged = upsert.length > 0 || removed.length > 0;
291 const actionChanged =
292 (current.action ?? DEFAULT_ACTION) !== (desired.action ?? DEFAULT_ACTION);
293 const stateChanged = (current.state ?? DEFAULT_STATE) !== (desired.state ?? DEFAULT_STATE);
294 const descriptionChanged = (current.description ?? "") !== (desired.description ?? "");
295 const resourceChanged =
296 fingerprint(orchestratedPayload(current.orchestratedResource)) !==
297 fingerprint(desired.orchestratedResource);
298 const scopeChanged =
299 desired.orchestrationScope !== undefined &&
300 fingerprint(current.orchestrationScope) !== fingerprint(desired.orchestrationScope);
301 const mask = fieldMask([
302 labelsChanged && "labels",
303 actionChanged && "action",
304 stateChanged && "state",
305 descriptionChanged && "description",
306 resourceChanged && "orchestratedResource",
307 scopeChanged && "orchestrationScope",
308 ]);
309
310 if (mask.length > 0) {
311 const operation = yield* osconfig.patchProjectsLocationsGlobalPolicyOrchestrators({
312 name: current.name ?? name,
313 updateMask: mask,
314 body: {
315 ...desired,
316 name: current.name ?? name,
317 etag: current.etag,
318 },
319 });
320 yield* waitForOperation(operation);
321 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
322 }
323
324 return toAttrs(current, env.project);
325 }),
326
327 delete: Effect.fn(function* ({ output }) {
328 if (!output.name) return;
329 const operation = yield* osconfig
330 .deleteProjectsLocationsGlobalPolicyOrchestrators({
331 name: output.name,
332 etag: output.etag,
333 })
334 .pipe(
335 Effect.retry({
336 while: (error) => error._tag === "Conflict",
337 times: 8,
338 schedule: Schedule.spaced("2 seconds"),
339 }),
340 Effect.catchTag("NotFound", () => Effect.undefined),
341 );
342 if (operation !== undefined) {
343 yield* waitForOperation(operation, { notFoundOk: true });
344 }
345 yield* waitUntilGone(getByName(output.name), output.name);
346 }),
347 });