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