@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 376 lines 13.2 KB
Raw
1 import * as backupdr from "@distilled.cloud/gcp/backupdr_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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 backupPlanOf,
12 collectPages,
13 hasAlchemyLabelMap,
14 listAtLocation,
15 normalizeLocation,
16 parentOf,
17 parseName,
18 replaceOnIdentity,
19 ResourceNotResolved,
20 sameText,
21 toPhysicalId,
22 waitForOperation,
23 waitUntilExists,
24 waitUntilGone,
25 waitUntilReady,
26 } from "./internal.ts";
27
28 export type RuleConfigInfo = {
29 /** Backup rule id from the plan. */
30 ruleId?: string;
31 /** Last backup state for the rule. */
32 lastBackupState?: string;
33 /** Last backup error message. */
34 lastBackupError?: string;
35 /** Last successful backup consistency time. */
36 lastSuccessfulBackupConsistencyTime?: string;
37 };
38
39 export type BackupPlanAssociationProps = {
40 /**
41 * Association id (the `{backupPlanAssociation}` segment of
42 * `projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociation}`).
43 * If omitted, a unique RFC1035 name is generated from the stack, stage,
44 * and logical id. Immutable — changing it replaces the association.
45 */
46 backupPlanAssociationId?: string;
47 /**
48 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
49 * replaces the association. `US-CENTRAL1` is accepted and normalized to
50 * `us-central1`.
51 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
52 */
53 location?: string;
54 /**
55 * Workload resource the plan is applied to. Resource name
56 * (`projects/{project}/zones/{zone}/instances/{instance}`) or full URI.
57 * Immutable — changing it replaces the association.
58 */
59 resource: string;
60 /**
61 * Workload resource type, e.g. `compute.googleapis.com/Instance`.
62 * Immutable — changing it replaces the association.
63 */
64 resourceType: string;
65 /**
66 * Backup plan to apply. Full name
67 * `projects/{project}/locations/{location}/backupPlans/{backupPlan}`
68 * or a plan id combined with `location`.
69 */
70 backupPlan: string;
71 };
72
73 export type BackupPlanAssociation = Resource<
74 "GCP.BackupDR.BackupPlanAssociation",
75 BackupPlanAssociationProps,
76 {
77 /** Full resource name. */
78 name: string;
79 /** Association id (last path segment). */
80 backupPlanAssociationId: string;
81 /** Project id. */
82 project: string;
83 /** Location id. */
84 location: string;
85 /** Workload resource name. */
86 resource: string | undefined;
87 /** Workload resource type. */
88 resourceType: string | undefined;
89 /** Backup plan name. */
90 backupPlan: string | undefined;
91 /** Data source used as the backup storage location. */
92 dataSource: string | undefined;
93 /** Backup plan revision name. */
94 backupPlanRevisionName: string | undefined;
95 /** User-friendly revision id (`v0`, `v1`, …). */
96 backupPlanRevisionId: string | undefined;
97 /** Per-rule backup status. */
98 rulesConfigInfo: RuleConfigInfo[];
99 /** Cloud SQL instance create time, if applicable. */
100 cloudSqlInstanceCreateTime: string | undefined;
101 /** Filestore instance create time, if applicable. */
102 filestoreInstanceCreateTime: string | undefined;
103 /** AlloyDB cluster uid, if applicable. */
104 alloydbClusterUid: string | undefined;
105 /** Server-reported state. */
106 state: string | undefined;
107 /** RFC3339 creation timestamp. */
108 createTime: string | undefined;
109 /** RFC3339 last-update timestamp. */
110 updateTime: string | undefined;
111 },
112 never,
113 Providers
114 >;
115
116 /**
117 * A Backup and DR backup plan association — applies a Backup Plan to a
118 * workload (Compute instance, Cloud SQL, AlloyDB, Filestore, or disk).
119 *
120 * Associations have no labels field. Nuke discovers them by following the
121 * referenced Backup Plan's Alchemy ownership labels.
122 *
123 * Changing `backupPlanAssociationId`, `location`, `resource`, or
124 * `resourceType` replaces the association. `backupPlan` updates in place.
125 *
126 * ### Creating an Association
127 * **Example:** Protect a Compute instance
128 * ```typescript
129 * const association = yield* GCP.BackupDR.BackupPlanAssociation("VmPlan", {
130 * resource: instance.selfLink,
131 * resourceType: "compute.googleapis.com/Instance",
132 * backupPlan: plan.name,
133 * });
134 * ```
135 *
136 * ### Updating an Association
137 * **Example:** Point at a new plan
138 * ```typescript
139 * // Same logical id, changed props: the engine updates it in place.
140 * const association = yield* GCP.BackupDR.BackupPlanAssociation("VmPlan", {
141 * resource: instance.selfLink,
142 * resourceType: "compute.googleapis.com/Instance",
143 * backupPlan: otherPlan.name,
144 * });
145 * ```
146 *
147 * @resource
148 * @category BackupDR
149 */
150 export const BackupPlanAssociation = Resource<BackupPlanAssociation>(
151 "GCP.BackupDR.BackupPlanAssociation",
152 );
153
154 const resourceName = (project: string, location: string, backupPlanAssociationId: string) =>
155 `projects/${project}/locations/${location}/backupPlanAssociations/${backupPlanAssociationId}`;
156
157 const toRules = (rules: readonly backupdr.RuleConfigInfo[] | undefined): RuleConfigInfo[] =>
158 (rules ?? []).map((rule) => ({
159 ruleId: rule.ruleId,
160 lastBackupState: rule.lastBackupState,
161 lastBackupError: rule.lastBackupError?.message,
162 lastSuccessfulBackupConsistencyTime: rule.lastSuccessfulBackupConsistencyTime,
163 }));
164
165 const toAttrs = (item: backupdr.BackupPlanAssociation, project: string, region: string) => {
166 const name = item.name ?? "";
167 const parsed = parseName(name, "backupPlanAssociations", region);
168 return {
169 name,
170 backupPlanAssociationId: parsed.id,
171 project: parsed.project || project,
172 location: parsed.location,
173 resource: item.resource,
174 resourceType: item.resourceType,
175 backupPlan: item.backupPlan,
176 dataSource: item.dataSource,
177 backupPlanRevisionName: item.backupPlanRevisionName,
178 backupPlanRevisionId: item.backupPlanRevisionId,
179 rulesConfigInfo: toRules(item.rulesConfigInfo),
180 cloudSqlInstanceCreateTime:
181 item.cloudSqlInstanceBackupPlanAssociationProperties?.instanceCreateTime,
182 filestoreInstanceCreateTime:
183 item.filestoreInstanceBackupPlanAssociationProperties?.instanceCreateTime,
184 alloydbClusterUid: item.alloydbClusterBackupPlanAssociationProperties?.clusterUid,
185 state: item.state,
186 createTime: item.createTime,
187 updateTime: item.updateTime,
188 };
189 };
190
191 const getByName = (name: string) =>
192 backupdr
193 .getProjectsLocationsBackupPlanAssociations({ name })
194 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
195
196 const getPlan = (name: string | undefined) =>
197 name === undefined || name.length === 0
198 ? Effect.undefined
199 : backupdr
200 .getProjectsLocationsBackupPlans({ name })
201 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
202
203 const listOwned = (project: string, region: string) =>
204 Effect.gen(function* () {
205 const items = yield* listAtLocation(project, region, (parent) =>
206 collectPages(
207 backupdr.listProjectsLocationsBackupPlanAssociations.pages({
208 parent,
209 pageSize: 1000,
210 }),
211 (page) => page.backupPlanAssociations,
212 ),
213 );
214 const planNames = [
215 ...new Set(
216 items
217 .map((item) => item.backupPlan)
218 .filter((name): name is string => name !== undefined && name.length > 0),
219 ),
220 ];
221 const ownedPlans = yield* Effect.forEach(
222 planNames,
223 (name) =>
224 getPlan(name).pipe(
225 Effect.map((plan) =>
226 plan !== undefined && hasAlchemyLabelMap(plan.labels) ? name : undefined,
227 ),
228 ),
229 { concurrency: 8 },
230 );
231 const owned = new Set(ownedPlans.filter((name): name is string => name !== undefined));
232 return items.filter((item) => item.backupPlan !== undefined && owned.has(item.backupPlan));
233 });
234
235 export const BackupPlanAssociationProvider = () =>
236 Provider.succeed(BackupPlanAssociation, {
237 stables: ["name", "backupPlanAssociationId", "project", "location", "createTime"],
238
239 diff: Effect.fn(function* ({ news, olds, output }) {
240 if (!isResolved(news)) return undefined;
241 const env = yield* GcpEnvironment.current;
242 const previousResource = olds?.resource ?? output?.resource;
243 const previousType = olds?.resourceType ?? output?.resourceType;
244 return replaceOnIdentity({
245 previousId: olds?.backupPlanAssociationId ?? output?.backupPlanAssociationId,
246 nextId:
247 news.backupPlanAssociationId ??
248 olds?.backupPlanAssociationId ??
249 output?.backupPlanAssociationId,
250 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
251 nextLocation: normalizeLocation(
252 news.location ?? olds?.location ?? output?.location,
253 env.region,
254 ),
255 extra:
256 (previousType !== undefined &&
257 news.resourceType !== undefined &&
258 previousType !== news.resourceType) ||
259 (previousResource !== undefined &&
260 news.resource !== undefined &&
261 previousResource !== news.resource &&
262 !previousResource.endsWith(`/${news.resource}`)),
263 });
264 }),
265
266 read: Effect.fn(function* ({ id, olds, output }) {
267 const env = yield* GcpEnvironment.current;
268 const backupPlanAssociationId = yield* toPhysicalId(
269 id,
270 olds?.backupPlanAssociationId,
271 output?.backupPlanAssociationId,
272 "backupplanassoc",
273 );
274 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
275 const name = output?.name ?? resourceName(env.project, location, backupPlanAssociationId);
276 const existing = yield* getByName(name);
277 if (existing === undefined) return undefined;
278 const attrs = toAttrs(existing, env.project, env.region);
279 if (output !== undefined) return attrs;
280 const plan = yield* getPlan(existing.backupPlan);
281 return plan !== undefined && hasAlchemyLabelMap(plan.labels) ? attrs : Unowned(attrs);
282 }),
283
284 list: () =>
285 Effect.gen(function* () {
286 const env = yield* GcpEnvironment.current;
287 const items = yield* listOwned(env.project, env.region);
288 return items.map((item) => toAttrs(item, env.project, env.region));
289 }),
290
291 reconcile: Effect.fn(function* ({ id, news, output }) {
292 const env = yield* GcpEnvironment.current;
293 const backupPlanAssociationId = yield* toPhysicalId(
294 id,
295 news.backupPlanAssociationId,
296 output?.backupPlanAssociationId,
297 "backupplanassoc",
298 );
299 const location = normalizeLocation(news.location ?? output?.location, env.region);
300 const name = resourceName(env.project, location, backupPlanAssociationId);
301 const backupPlan = backupPlanOf(news.backupPlan, env.project, location);
302
303 let current = yield* getByName(output?.name ?? name);
304
305 if (current === undefined) {
306 const created = yield* backupdr
307 .createProjectsLocationsBackupPlanAssociations({
308 parent: parentOf(env.project, location),
309 backupPlanAssociationId,
310 body: {
311 resource: news.resource,
312 resourceType: news.resourceType,
313 backupPlan,
314 },
315 })
316 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
317 if (created !== undefined) {
318 // ALREADY_EXISTS (6): a concurrent create won the race.
319 yield* waitForOperation(created).pipe(
320 Effect.catchTag("GCP.OperationFailed", (error) =>
321 error.code === 6 ? Effect.void : Effect.fail(error),
322 ),
323 );
324 }
325 current = yield* waitUntilExists(getByName(name), name);
326 }
327
328 if (current === undefined) {
329 return yield* new ResourceNotResolved({ resourceName: name });
330 }
331
332 current = yield* waitUntilReady(
333 getByName(current.name ?? name),
334 current.name ?? name,
335 (item) => item.state,
336 );
337
338 if (!sameText(current.backupPlan, backupPlan)) {
339 const operation = yield* backupdr.patchProjectsLocationsBackupPlanAssociations({
340 name: current.name ?? name,
341 updateMask: "backupPlan",
342 body: { backupPlan },
343 });
344 yield* waitForOperation(operation);
345 current = yield* waitUntilReady(
346 getByName(current.name ?? name),
347 current.name ?? name,
348 (item) => item.state,
349 );
350 }
351
352 return toAttrs(current, env.project, env.region);
353 }),
354
355 delete: Effect.fn(function* ({ output }) {
356 const operation = yield* backupdr
357 .deleteProjectsLocationsBackupPlanAssociations({ name: output.name })
358 .pipe(
359 Effect.retry({
360 while: (error) => error._tag === "Conflict",
361 times: 8,
362 schedule: Schedule.spaced("2 seconds"),
363 }),
364 Effect.catchTag("NotFound", () => Effect.undefined),
365 );
366 if (operation !== undefined) {
367 // NOT_FOUND (5): already gone.
368 yield* waitForOperation(operation).pipe(
369 Effect.catchTag("GCP.OperationFailed", (error) =>
370 error.code === 5 ? Effect.void : Effect.fail(error),
371 ),
372 );
373 }
374 yield* waitUntilGone(getByName(output.name), output.name);
375 }),
376 });