@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 370 lines 12.4 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 listAtNested,
17 listLabeledPages,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 toPhysicalId,
23 userLabels,
24 waitForDeleteOperation,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 waitUntilReady,
29 } from "./internal.ts";
30
31 export type OntapSource = {
32 /** Storage pool that hosts the ONTAP volume. */
33 storagePool?: string;
34 /** ONTAP source volume UUID. */
35 volumeUuid?: string;
36 /** ONTAP source snapshot UUID. */
37 snapshotUuid?: string;
38 };
39
40 export type BackupVaultsBackupProps = {
41 /**
42 * Parent backup vault. Full name
43 * `projects/{project}/locations/{location}/backupVaults/{backupVault}`
44 * or the vault id (combined with `location`). Immutable — changing it
45 * replaces the backup.
46 */
47 backupVault: string;
48 /**
49 * Region used when `backupVault` is a bare id.
50 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
51 */
52 location?: string;
53 /**
54 * Backup id (the `{backup}` segment). If omitted, a unique RFC1035 name
55 * is generated from the stack, stage, and logical id. Immutable —
56 * changing it replaces the backup.
57 */
58 backupId?: string;
59 /**
60 * Source volume name or id. Immutable — changing it replaces the
61 * backup. Either `sourceVolume` or `ontapSource` is required.
62 */
63 sourceVolume?: string;
64 /**
65 * Snapshot to back up. If omitted, a new snapshot is taken. Immutable.
66 */
67 sourceSnapshot?: string;
68 /**
69 * ONTAP source details. Immutable — changing it replaces the backup.
70 */
71 ontapSource?: OntapSource;
72 /**
73 * Human-readable description. Max 2048 characters.
74 */
75 description?: string;
76 /**
77 * User labels. Alchemy ownership labels are merged in automatically.
78 */
79 labels?: Record<string, string>;
80 };
81
82 export type BackupVaultsBackup = Resource<
83 "GCP.NetApp.BackupVaultsBackup",
84 BackupVaultsBackupProps,
85 {
86 /** Full resource name. */
87 name: string;
88 /** Backup id (last path segment). */
89 backupId: string;
90 /** Parent backup vault name. */
91 backupVault: string;
92 /** Project id. */
93 project: string;
94 /** Location id. */
95 location: string;
96 /** Source volume name. */
97 sourceVolume: string | undefined;
98 /** Source snapshot name. */
99 sourceSnapshot: string | undefined;
100 /** ONTAP source details. */
101 ontapSource: OntapSource | undefined;
102 /** Backup type (`MANUAL` or `SCHEDULED`). */
103 backupType: string | undefined;
104 /** Region that stores the backup. */
105 backupRegion: string | undefined;
106 /** Region of the source volume. */
107 volumeRegion: string | undefined;
108 /** File-system size at backup time, in bytes. */
109 volumeUsageBytes: string | undefined;
110 /** Chain storage in bytes. */
111 chainStorageBytes: string | undefined;
112 /** Time until which the backup cannot be deleted. */
113 enforcedRetentionEndTime: string | undefined;
114 /** Human-readable description. */
115 description: string | undefined;
116 /** User labels (Alchemy ownership labels stripped). */
117 labels: Record<string, string>;
118 /** Server-reported state. */
119 state: string | undefined;
120 /** RFC3339 creation timestamp. */
121 createTime: string | undefined;
122 },
123 never,
124 Providers
125 >;
126
127 /**
128 * A Cloud NetApp Volumes backup stored in a backup vault.
129 *
130 * Changing `backupId`, `backupVault`, `location`, `sourceVolume`,
131 * `sourceSnapshot`, or `ontapSource` replaces the backup. Description and
132 * labels update in place.
133 *
134 * ### Creating a Backup
135 * **Example:** From a volume
136 * ```typescript
137 * const backup = yield* GCP.NetApp.BackupVaultsBackup("Nightly", {
138 * backupVault: vault.name,
139 * sourceVolume: volume.name,
140 * });
141 * ```
142 *
143 * **Example:** From a snapshot
144 * ```typescript
145 * const backup = yield* GCP.NetApp.BackupVaultsBackup("Nightly", {
146 * backupVault: vault.name,
147 * sourceVolume: volume.name,
148 * sourceSnapshot: snapshot.name,
149 * description: "pre-release",
150 * labels: { env: "prod" },
151 * });
152 * ```
153 *
154 * ### Updating a Backup
155 * **Example:** Description and labels
156 * ```typescript
157 * const backup = yield* GCP.NetApp.BackupVaultsBackup("Nightly", {
158 * backupVault: vault.name,
159 * sourceVolume: volume.name,
160 * description: "pre-release v2",
161 * labels: { env: "prod", team: "storage" },
162 * });
163 * ```
164 *
165 * @resource
166 * @category NetApp
167 */
168 export const BackupVaultsBackup = Resource<BackupVaultsBackup>("GCP.NetApp.BackupVaultsBackup");
169
170 const resourceName = (vault: string, backupId: string) => `${vault}/backups/${backupId}`;
171
172 const toOntap = (source: netapp.OntapSource | undefined): OntapSource | undefined =>
173 source === undefined
174 ? undefined
175 : {
176 storagePool: source.storagePool,
177 volumeUuid: source.volumeUuid,
178 snapshotUuid: source.snapshotUuid,
179 };
180
181 const toAttrs = (item: netapp.Backup, project: string, region: string) => {
182 const name = item.name ?? "";
183 const parsed = parseName(name, "backups", region);
184 return {
185 name,
186 backupId: parsed.id,
187 backupVault: parsed.parent,
188 project: parsed.project || project,
189 location: parsed.location,
190 sourceVolume: item.sourceVolume,
191 sourceSnapshot: item.sourceSnapshot,
192 ontapSource: toOntap(item.ontapSource),
193 backupType: item.backupType,
194 backupRegion: item.backupRegion,
195 volumeRegion: item.volumeRegion,
196 volumeUsageBytes: item.volumeUsageBytes,
197 chainStorageBytes: item.chainStorageBytes,
198 enforcedRetentionEndTime: item.enforcedRetentionEndTime,
199 description: item.description,
200 labels: userLabels(item.labels),
201 state: item.state,
202 createTime: item.createTime,
203 };
204 };
205
206 const getByName = (name: string) =>
207 netapp
208 .getProjectsLocationsBackupVaultsBackups({ name })
209 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
210
211 const listOwned = (project: string) =>
212 listAtNested(project, "backupVaults/-", (parent) =>
213 listLabeledPages(
214 netapp.listProjectsLocationsBackupVaultsBackups.pages({
215 parent,
216 pageSize: 1000,
217 }),
218 (page) => page.backups,
219 (item) => item.labels,
220 ),
221 );
222
223 export const BackupVaultsBackupProvider = () =>
224 Provider.succeed(BackupVaultsBackup, {
225 stables: ["name", "backupId", "backupVault", "project", "location", "createTime"],
226
227 diff: Effect.fn(function* ({ news, olds, output }) {
228 if (!isResolved(news)) return undefined;
229 const env = yield* GcpEnvironment.current;
230 const previousVolume = olds?.sourceVolume ?? output?.sourceVolume;
231 const previousSnapshot = olds?.sourceSnapshot ?? output?.sourceSnapshot;
232 const previousOntap = olds?.ontapSource ?? output?.ontapSource;
233 return replaceOnIdentity({
234 previousId: olds?.backupId ?? output?.backupId,
235 nextId: news.backupId ?? olds?.backupId ?? output?.backupId,
236 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
237 nextLocation: normalizeLocation(
238 news.location ?? olds?.location ?? output?.location,
239 env.region,
240 ),
241 previousParent: olds?.backupVault ?? output?.backupVault,
242 nextParent: news.backupVault,
243 extra:
244 (previousVolume !== undefined &&
245 news.sourceVolume !== undefined &&
246 news.sourceVolume !== previousVolume &&
247 !previousVolume.endsWith(`/${news.sourceVolume}`)) ||
248 (previousSnapshot !== undefined &&
249 news.sourceSnapshot !== undefined &&
250 news.sourceSnapshot !== previousSnapshot) ||
251 (previousOntap !== undefined &&
252 news.ontapSource !== undefined &&
253 fingerprint(previousOntap) !== fingerprint(news.ontapSource)),
254 });
255 }),
256
257 read: Effect.fn(function* ({ id, olds, output }) {
258 const env = yield* GcpEnvironment.current;
259 const backupId = yield* toPhysicalId(id, olds?.backupId, output?.backupId, "backup");
260 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
261 const parent = olds?.backupVault ?? output?.backupVault;
262 // A row whose parent never resolved (failed create) has nothing to read.
263 if (output?.name === undefined && !parent) return undefined;
264 const vault = expandParent(parent ?? "", env.project, location, "backupVaults");
265 const name = output?.name ?? resourceName(vault, backupId);
266 const existing = yield* getByName(name);
267 if (existing === undefined) return undefined;
268 const attrs = toAttrs(existing, env.project, env.region);
269 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
270 }),
271
272 list: () =>
273 Effect.gen(function* () {
274 const env = yield* GcpEnvironment.current;
275 const items = yield* listOwned(env.project);
276 return items.map((item) => toAttrs(item, env.project, env.region));
277 }),
278
279 reconcile: Effect.fn(function* ({ id, news, output }) {
280 const env = yield* GcpEnvironment.current;
281 const backupId = yield* toPhysicalId(id, news.backupId, output?.backupId, "backup");
282 const location = normalizeLocation(news.location ?? output?.location, env.region);
283 const vault = expandParent(news.backupVault, env.project, location, "backupVaults");
284 const name = resourceName(vault, backupId);
285 const sourceVolume =
286 news.sourceVolume === undefined
287 ? undefined
288 : expandParent(news.sourceVolume, env.project, location, "volumes");
289 const desiredLabels = {
290 ...toLabels(news.labels),
291 ...(yield* createInternalLabels(id)),
292 };
293
294 let current = yield* getByName(output?.name ?? name);
295
296 if (current === undefined) {
297 const created = yield* netapp
298 .createProjectsLocationsBackupVaultsBackups({
299 parent: vault,
300 backupId,
301 body: {
302 sourceVolume,
303 sourceSnapshot: news.sourceSnapshot,
304 ontapSource: news.ontapSource,
305 description: news.description,
306 labels: desiredLabels,
307 },
308 })
309 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
310 if (created !== undefined) {
311 yield* waitForOperation(created);
312 }
313 current = yield* waitUntilExists(getByName(name), name);
314 }
315
316 if (current === undefined) {
317 return yield* new ResourceNotResolved({ resourceName: name });
318 }
319
320 current = yield* waitUntilReady(
321 getByName(current.name ?? name),
322 current.name ?? name,
323 (item) => item.state,
324 );
325
326 const observedLabels = tagRecord(current.labels);
327 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
328 const mask = fieldMask([
329 (upsert.length > 0 || removed.length > 0) && "labels",
330 (current.description ?? "") !== (news.description ?? "") && "description",
331 ]);
332
333 if (mask.length > 0) {
334 const operation = yield* netapp.patchProjectsLocationsBackupVaultsBackups({
335 name: current.name ?? name,
336 updateMask: mask,
337 body: {
338 name: current.name ?? name,
339 labels: desiredLabels,
340 description: news.description,
341 },
342 });
343 yield* waitForOperation(operation);
344 current = yield* waitUntilReady(
345 getByName(current.name ?? name),
346 current.name ?? name,
347 (item) => item.state,
348 );
349 }
350
351 return toAttrs(current, env.project, env.region);
352 }),
353
354 delete: Effect.fn(function* ({ output }) {
355 const operation = yield* netapp
356 .deleteProjectsLocationsBackupVaultsBackups({ name: output.name })
357 .pipe(
358 Effect.retry({
359 while: (error) => error._tag === "Conflict",
360 times: 8,
361 schedule: Schedule.spaced("2 seconds"),
362 }),
363 Effect.catchTag("NotFound", () => Effect.undefined),
364 );
365 if (operation !== undefined) {
366 yield* waitForDeleteOperation(operation);
367 }
368 yield* waitUntilGone(getByName(output.name), output.name);
369 }),
370 });