@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, 04:45 UTC

main
ts 395 lines 12.9 KB
Raw
1 import * as netapp from "@distilled.cloud/gcp/netapp_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 expandParent,
14 fieldMask,
15 fingerprint,
16 listAtLocation,
17 listLabeledPages,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 toPhysicalId,
24 userLabels,
25 waitForDeleteOperation,
26 waitForOperation,
27 waitUntilExists,
28 waitUntilGone,
29 waitUntilReady,
30 } from "./internal.ts";
31
32 export type BackupRetentionPolicy = {
33 /**
34 * Minimum retention duration in days for backups in the vault.
35 */
36 backupMinimumEnforcedRetentionDays?: number;
37 /**
38 * Whether daily backups are immutable.
39 */
40 dailyBackupImmutable?: boolean;
41 /**
42 * Whether weekly backups are immutable.
43 */
44 weeklyBackupImmutable?: boolean;
45 /**
46 * Whether monthly backups are immutable.
47 */
48 monthlyBackupImmutable?: boolean;
49 /**
50 * Whether manual backups are immutable.
51 */
52 manualBackupImmutable?: boolean;
53 };
54
55 export type BackupVaultProps = {
56 /**
57 * Backup vault id (the `{backupVault}` segment of
58 * `projects/{project}/locations/{location}/backupVaults/{backupVault}`).
59 * If omitted, a unique RFC1035 name is generated from the stack, stage,
60 * and logical id. Immutable — changing it replaces the vault.
61 */
62 backupVaultId?: string;
63 /**
64 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
65 * replaces the vault. `US-CENTRAL1` is accepted and normalized to
66 * `us-central1`.
67 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
68 */
69 location?: string;
70 /**
71 * Vault type. Immutable — changing it replaces the vault.
72 * @default "IN_REGION"
73 */
74 backupVaultType?: netapp.BackupVaultBackupVaultTypeEnum | (string & {});
75 /**
76 * Region that stores backups for a cross-region vault. Full location
77 * name or id. Immutable — changing it replaces the vault.
78 */
79 backupRegion?: string;
80 /**
81 * KMS config used to encrypt backups. Full name or id. Immutable —
82 * changing it replaces the vault.
83 */
84 kmsConfig?: string;
85 /**
86 * Backup retention policy. At least one immutable flag must be true
87 * when the policy is set.
88 */
89 backupRetentionPolicy?: BackupRetentionPolicy;
90 /**
91 * Human-readable description.
92 */
93 description?: string;
94 /**
95 * User labels. Alchemy ownership labels are merged in automatically.
96 */
97 labels?: Record<string, string>;
98 };
99
100 export type BackupVault = Resource<
101 "GCP.NetApp.BackupVault",
102 BackupVaultProps,
103 {
104 /** Full resource name. */
105 name: string;
106 /** Backup vault id (last path segment). */
107 backupVaultId: string;
108 /** Project id. */
109 project: string;
110 /** Location id. */
111 location: string;
112 /** Vault type. */
113 backupVaultType: string | undefined;
114 /** Backup region. */
115 backupRegion: string | undefined;
116 /** Source region. */
117 sourceRegion: string | undefined;
118 /** Source vault name. */
119 sourceBackupVault: string | undefined;
120 /** Destination vault name. */
121 destinationBackupVault: string | undefined;
122 /** KMS config name. */
123 kmsConfig: string | undefined;
124 /** Crypto key version used to encrypt backups. */
125 backupsCryptoKeyVersion: string | undefined;
126 /** Encryption state of CMEK backups. */
127 encryptionState: string | undefined;
128 /** Retention policy. */
129 backupRetentionPolicy: BackupRetentionPolicy | undefined;
130 /** Human-readable description. */
131 description: string | undefined;
132 /** User labels (Alchemy ownership labels stripped). */
133 labels: Record<string, string>;
134 /** Server-reported state. */
135 state: string | undefined;
136 /** RFC3339 creation timestamp. */
137 createTime: string | undefined;
138 },
139 never,
140 Providers
141 >;
142
143 /**
144 * A Cloud NetApp Volumes backup vault that stores volume backups.
145 *
146 * Changing `backupVaultId`, `location`, `backupVaultType`, `backupRegion`,
147 * or `kmsConfig` replaces the vault. Description, labels, and retention
148 * policy update in place.
149 *
150 * ### Creating a Backup Vault
151 * **Example:** Generated name
152 * ```typescript
153 * const vault = yield* GCP.NetApp.BackupVault("Vault", {});
154 * ```
155 *
156 * **Example:** Explicit id and description
157 * ```typescript
158 * const vault = yield* GCP.NetApp.BackupVault("Vault", {
159 * backupVaultId: "app-backups",
160 * description: "nightly backups",
161 * labels: { env: "prod" },
162 * });
163 * ```
164 *
165 * ### Updating a Backup Vault
166 * **Example:** Description and labels
167 * ```typescript
168 * const vault = yield* GCP.NetApp.BackupVault("Vault", {
169 * description: "nightly backups v2",
170 * labels: { env: "prod", team: "storage" },
171 * });
172 * ```
173 *
174 * @resource
175 * @category NetApp
176 */
177 export const BackupVault = Resource<BackupVault>("GCP.NetApp.BackupVault");
178
179 const resourceName = (project: string, location: string, backupVaultId: string) =>
180 `projects/${project}/locations/${location}/backupVaults/${backupVaultId}`;
181
182 const toRetention = (
183 policy: netapp.BackupRetentionPolicy | undefined,
184 ): BackupRetentionPolicy | undefined =>
185 policy === undefined
186 ? undefined
187 : {
188 backupMinimumEnforcedRetentionDays: policy.backupMinimumEnforcedRetentionDays,
189 dailyBackupImmutable: policy.dailyBackupImmutable,
190 weeklyBackupImmutable: policy.weeklyBackupImmutable,
191 monthlyBackupImmutable: policy.monthlyBackupImmutable,
192 manualBackupImmutable: policy.manualBackupImmutable,
193 };
194
195 const toAttrs = (item: netapp.BackupVault, project: string, region: string) => {
196 const name = item.name ?? "";
197 const parsed = parseName(name, "backupVaults", region);
198 return {
199 name,
200 backupVaultId: parsed.id,
201 project: parsed.project || project,
202 location: parsed.location,
203 backupVaultType: item.backupVaultType,
204 backupRegion: item.backupRegion,
205 sourceRegion: item.sourceRegion,
206 sourceBackupVault: item.sourceBackupVault,
207 destinationBackupVault: item.destinationBackupVault,
208 kmsConfig: item.kmsConfig,
209 backupsCryptoKeyVersion: item.backupsCryptoKeyVersion,
210 encryptionState: item.encryptionState,
211 backupRetentionPolicy: toRetention(item.backupRetentionPolicy),
212 description: item.description,
213 labels: userLabels(item.labels),
214 state: item.state,
215 createTime: item.createTime,
216 };
217 };
218
219 const getByName = (name: string) =>
220 netapp
221 .getProjectsLocationsBackupVaults({ name })
222 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
223
224 const listOwned = (project: string) =>
225 listAtLocation(project, (parent) =>
226 listLabeledPages(
227 netapp.listProjectsLocationsBackupVaults.pages({
228 parent,
229 pageSize: 1000,
230 }),
231 (page) => page.backupVaults,
232 (item) => item.labels,
233 ),
234 );
235
236 export const BackupVaultProvider = () =>
237 Provider.succeed(BackupVault, {
238 stables: ["name", "backupVaultId", "project", "location", "createTime"],
239
240 diff: Effect.fn(function* ({ news, olds, output }) {
241 if (!isResolved(news)) return undefined;
242 const env = yield* GcpEnvironment.current;
243 const previousType = olds?.backupVaultType ?? output?.backupVaultType;
244 const previousRegion = olds?.backupRegion ?? output?.backupRegion;
245 const previousKms = olds?.kmsConfig ?? output?.kmsConfig;
246 return replaceOnIdentity({
247 previousId: olds?.backupVaultId ?? output?.backupVaultId,
248 nextId: news.backupVaultId ?? olds?.backupVaultId ?? output?.backupVaultId,
249 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
250 nextLocation: normalizeLocation(
251 news.location ?? olds?.location ?? output?.location,
252 env.region,
253 ),
254 extra:
255 (previousType !== undefined &&
256 news.backupVaultType !== undefined &&
257 news.backupVaultType !== previousType) ||
258 (previousRegion !== undefined &&
259 news.backupRegion !== undefined &&
260 news.backupRegion !== previousRegion) ||
261 (previousKms !== undefined &&
262 news.kmsConfig !== undefined &&
263 news.kmsConfig !== previousKms),
264 });
265 }),
266
267 read: Effect.fn(function* ({ id, olds, output }) {
268 const env = yield* GcpEnvironment.current;
269 const backupVaultId = yield* toPhysicalId(
270 id,
271 olds?.backupVaultId,
272 output?.backupVaultId,
273 "backupvault",
274 );
275 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
276 const name = output?.name ?? resourceName(env.project, location, backupVaultId);
277 const existing = yield* getByName(name);
278 if (existing === undefined) return undefined;
279 const attrs = toAttrs(existing, env.project, env.region);
280 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
281 }),
282
283 list: () =>
284 Effect.gen(function* () {
285 const env = yield* GcpEnvironment.current;
286 const items = yield* listOwned(env.project);
287 return items.map((item) => toAttrs(item, env.project, env.region));
288 }),
289
290 reconcile: Effect.fn(function* ({ id, news, output }) {
291 const env = yield* GcpEnvironment.current;
292 const backupVaultId = yield* toPhysicalId(
293 id,
294 news.backupVaultId,
295 output?.backupVaultId,
296 "backupvault",
297 );
298 const location = normalizeLocation(news.location ?? output?.location, env.region);
299 const name = resourceName(env.project, location, backupVaultId);
300 const desiredLabels = {
301 ...toLabels(news.labels),
302 ...(yield* createInternalLabels(id)),
303 };
304 const backupRegion =
305 news.backupRegion === undefined
306 ? undefined
307 : news.backupRegion.includes("/")
308 ? news.backupRegion
309 : parentOf(env.project, news.backupRegion);
310 const kmsConfig =
311 news.kmsConfig === undefined
312 ? undefined
313 : expandParent(news.kmsConfig, env.project, location, "kmsConfigs");
314
315 let current = yield* getByName(output?.name ?? name);
316
317 if (current === undefined) {
318 const created = yield* netapp
319 .createProjectsLocationsBackupVaults({
320 parent: parentOf(env.project, location),
321 backupVaultId,
322 body: {
323 backupVaultType: news.backupVaultType,
324 backupRegion,
325 kmsConfig,
326 backupRetentionPolicy: news.backupRetentionPolicy,
327 description: news.description,
328 labels: desiredLabels,
329 },
330 })
331 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
332 if (created !== undefined) {
333 yield* waitForOperation(created);
334 }
335 current = yield* waitUntilExists(getByName(name), name);
336 }
337
338 if (current === undefined) {
339 return yield* new ResourceNotResolved({ resourceName: name });
340 }
341
342 current = yield* waitUntilReady(
343 getByName(current.name ?? name),
344 current.name ?? name,
345 (item) => item.state,
346 );
347
348 const observedLabels = tagRecord(current.labels);
349 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
350 const mask = fieldMask([
351 (upsert.length > 0 || removed.length > 0) && "labels",
352 (current.description ?? "") !== (news.description ?? "") && "description",
353 fingerprint(toRetention(current.backupRetentionPolicy)) !==
354 fingerprint(news.backupRetentionPolicy) && "backupRetentionPolicy",
355 ]);
356
357 if (mask.length > 0) {
358 const operation = yield* netapp.patchProjectsLocationsBackupVaults({
359 name: current.name ?? name,
360 updateMask: mask,
361 body: {
362 name: current.name ?? name,
363 labels: desiredLabels,
364 description: news.description,
365 backupRetentionPolicy: news.backupRetentionPolicy,
366 },
367 });
368 yield* waitForOperation(operation);
369 current = yield* waitUntilReady(
370 getByName(current.name ?? name),
371 current.name ?? name,
372 (item) => item.state,
373 );
374 }
375
376 return toAttrs(current, env.project, env.region);
377 }),
378
379 delete: Effect.fn(function* ({ output }) {
380 const operation = yield* netapp
381 .deleteProjectsLocationsBackupVaults({ name: output.name })
382 .pipe(
383 Effect.retry({
384 while: (error) => error._tag === "Conflict",
385 times: 8,
386 schedule: Schedule.spaced("2 seconds"),
387 }),
388 Effect.catchTag("NotFound", () => Effect.undefined),
389 );
390 if (operation !== undefined) {
391 yield* waitForDeleteOperation(operation);
392 }
393 yield* waitUntilGone(getByName(output.name), output.name);
394 }),
395 });