The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as gkebackup from "@distilled.cloud/gcp/gkebackup_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 | listAtNested, |
| 16 | listLabeledPages, |
| 17 | normalizeLocation, |
| 18 | parseName, |
| 19 | replaceOnIdentity, |
| 20 | ResourceNotResolved, |
| 21 | sameText, |
| 22 | toPhysicalId, |
| 23 | userLabels, |
| 24 | waitForDeleteOperation, |
| 25 | waitForOperation, |
| 26 | waitUntilExists, |
| 27 | waitUntilGone, |
| 28 | } from "./internal.ts"; |
| 29 | import type { GroupKind, RestoreConfig } from "./RestorePlan.ts"; |
| 30 | |
| 31 | export type ResourceSelector = { |
| 32 | /** Select resources of this group kind. */ |
| 33 | groupKind?: GroupKind; |
| 34 | /** Select resources in this namespace. */ |
| 35 | namespace?: string; |
| 36 | /** Select resources with all of these labels. */ |
| 37 | labels?: Record<string, string>; |
| 38 | /** Select resources with this name. */ |
| 39 | name?: string; |
| 40 | }; |
| 41 | |
| 42 | export type RestoreFilter = { |
| 43 | /** Restore only resources matching any of these selectors. */ |
| 44 | inclusionFilters?: ResourceSelector[]; |
| 45 | /** Exclude resources matching any of these selectors. */ |
| 46 | exclusionFilters?: ResourceSelector[]; |
| 47 | }; |
| 48 | |
| 49 | export type VolumeDataRestorePolicyOverride = { |
| 50 | /** Policy applied to the selected PVCs. */ |
| 51 | policy?: gkebackup.VolumeDataRestorePolicyOverridePolicyEnum | (string & {}); |
| 52 | /** PVCs this override applies to. */ |
| 53 | selectedPvcs?: { |
| 54 | namespacedNames?: Array<{ |
| 55 | /** Kubernetes namespace. */ |
| 56 | namespace?: string; |
| 57 | /** Kubernetes resource name. */ |
| 58 | name?: string; |
| 59 | }>; |
| 60 | }; |
| 61 | }; |
| 62 | |
| 63 | export type RestorePlansRestoreProps = { |
| 64 | /** |
| 65 | * Parent RestorePlan. Full name |
| 66 | * `projects/{project}/locations/{location}/restorePlans/{restorePlan}` |
| 67 | * or the plan id (combined with `location`). Immutable — changing it |
| 68 | * replaces the restore. |
| 69 | */ |
| 70 | restorePlan: string; |
| 71 | /** |
| 72 | * Region used when `restorePlan` is a bare id. |
| 73 | * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) |
| 74 | */ |
| 75 | location?: string; |
| 76 | /** |
| 77 | * Restore id (the `{restore}` segment). If omitted, a unique RFC1035 |
| 78 | * name is generated from the stack, stage, and logical id. Immutable — |
| 79 | * changing it replaces the restore. |
| 80 | */ |
| 81 | restoreId?: string; |
| 82 | /** |
| 83 | * Source Backup. Full name |
| 84 | * `projects/{project}/locations/{location}/backupPlans/{backupPlan}/backups/{backup}` |
| 85 | * or a backup id under the RestorePlan's BackupPlan. Immutable — |
| 86 | * changing it replaces the restore. |
| 87 | */ |
| 88 | backup: string; |
| 89 | /** |
| 90 | * Filter that further refines resource selection. Immutable. |
| 91 | */ |
| 92 | filter?: RestoreFilter; |
| 93 | /** |
| 94 | * Per-PVC volume restore policy overrides. Immutable. |
| 95 | */ |
| 96 | volumeDataRestorePolicyOverrides?: VolumeDataRestorePolicyOverride[]; |
| 97 | /** |
| 98 | * Human-readable description. |
| 99 | */ |
| 100 | description?: string; |
| 101 | /** |
| 102 | * User labels. Alchemy ownership labels are merged in automatically. |
| 103 | */ |
| 104 | labels?: Record<string, string>; |
| 105 | }; |
| 106 | |
| 107 | export type RestorePlansRestore = Resource< |
| 108 | "GCP.GKEBackup.RestorePlansRestore", |
| 109 | RestorePlansRestoreProps, |
| 110 | { |
| 111 | /** Full resource name. */ |
| 112 | name: string; |
| 113 | /** Restore id (last path segment). */ |
| 114 | restoreId: string; |
| 115 | /** Parent RestorePlan name. */ |
| 116 | restorePlan: string; |
| 117 | /** Project id. */ |
| 118 | project: string; |
| 119 | /** Location id. */ |
| 120 | location: string; |
| 121 | /** Source Backup name. */ |
| 122 | backup: string | undefined; |
| 123 | /** Target cluster name. */ |
| 124 | cluster: string | undefined; |
| 125 | /** Restore configuration inherited from the plan. */ |
| 126 | restoreConfig: RestoreConfig | undefined; |
| 127 | /** Resource filter applied to this Restore. */ |
| 128 | filter: RestoreFilter | undefined; |
| 129 | /** Volume policy overrides. */ |
| 130 | volumeDataRestorePolicyOverrides: VolumeDataRestorePolicyOverride[] | undefined; |
| 131 | /** Human-readable description. */ |
| 132 | description: string | undefined; |
| 133 | /** User labels (Alchemy ownership labels stripped). */ |
| 134 | labels: Record<string, string>; |
| 135 | /** Server-reported state. */ |
| 136 | state: string | undefined; |
| 137 | /** Human-readable state reason. */ |
| 138 | stateReason: string | undefined; |
| 139 | /** Resources restored. */ |
| 140 | resourcesRestoredCount: number | undefined; |
| 141 | /** Resources that failed to restore. */ |
| 142 | resourcesFailedCount: number | undefined; |
| 143 | /** Resources excluded. */ |
| 144 | resourcesExcludedCount: number | undefined; |
| 145 | /** Volumes restored. */ |
| 146 | volumesRestoredCount: number | undefined; |
| 147 | /** Server-generated resource uid. */ |
| 148 | uid: string | undefined; |
| 149 | /** RFC3339 creation timestamp. */ |
| 150 | createTime: string | undefined; |
| 151 | /** RFC3339 completion timestamp. */ |
| 152 | completeTime: string | undefined; |
| 153 | }, |
| 154 | never, |
| 155 | Providers |
| 156 | >; |
| 157 | |
| 158 | /** |
| 159 | * A Backup for GKE restore — a request to restore a Backup into the |
| 160 | * target cluster of a RestorePlan. |
| 161 | * |
| 162 | * Changing `restoreId`, `restorePlan`, `location`, `backup`, `filter`, |
| 163 | * or `volumeDataRestorePolicyOverrides` replaces the restore. |
| 164 | * Description and labels update in place. |
| 165 | * |
| 166 | * ### Creating a Restore |
| 167 | * **Example:** Restore a backup |
| 168 | * ```typescript |
| 169 | * const restore = yield* GCP.GKEBackup.RestorePlansRestore("Rollback", { |
| 170 | * restorePlan: plan.name, |
| 171 | * backup: backup.name, |
| 172 | * }); |
| 173 | * ``` |
| 174 | * |
| 175 | * **Example:** Filtered restore |
| 176 | * ```typescript |
| 177 | * const restore = yield* GCP.GKEBackup.RestorePlansRestore("Rollback", { |
| 178 | * restorePlan: plan.name, |
| 179 | * backup: backup.name, |
| 180 | * filter: { |
| 181 | * inclusionFilters: [{ namespace: "app" }], |
| 182 | * }, |
| 183 | * description: "app-only rollback", |
| 184 | * labels: { env: "prod" }, |
| 185 | * }); |
| 186 | * ``` |
| 187 | * |
| 188 | * ### Updating a Restore |
| 189 | * **Example:** Description and labels |
| 190 | * ```typescript |
| 191 | * const restore = yield* GCP.GKEBackup.RestorePlansRestore("Rollback", { |
| 192 | * restorePlan: plan.name, |
| 193 | * backup: backup.name, |
| 194 | * description: "app-only rollback v2", |
| 195 | * labels: { env: "prod", team: "platform" }, |
| 196 | * }); |
| 197 | * ``` |
| 198 | * |
| 199 | * @resource |
| 200 | * @category GKEBackup |
| 201 | */ |
| 202 | export const RestorePlansRestore = Resource<RestorePlansRestore>( |
| 203 | "GCP.GKEBackup.RestorePlansRestore", |
| 204 | ); |
| 205 | |
| 206 | const resourceName = (plan: string, restoreId: string) => `${plan}/restores/${restoreId}`; |
| 207 | |
| 208 | const toSelector = (item: gkebackup.ResourceSelector): ResourceSelector => ({ |
| 209 | groupKind: item.groupKind, |
| 210 | namespace: item.namespace, |
| 211 | labels: |
| 212 | item.labels === undefined |
| 213 | ? undefined |
| 214 | : Object.fromEntries( |
| 215 | Object.entries(item.labels).filter( |
| 216 | (entry): entry is [string, string] => typeof entry[1] === "string", |
| 217 | ), |
| 218 | ), |
| 219 | name: item.name, |
| 220 | }); |
| 221 | |
| 222 | const toFilter = (filter: gkebackup.Filter | undefined): RestoreFilter | undefined => |
| 223 | filter === undefined |
| 224 | ? undefined |
| 225 | : { |
| 226 | inclusionFilters: filter.inclusionFilters?.map(toSelector), |
| 227 | exclusionFilters: filter.exclusionFilters?.map(toSelector), |
| 228 | }; |
| 229 | |
| 230 | const toOverrides = ( |
| 231 | overrides: gkebackup.VolumeDataRestorePolicyOverrideList | undefined, |
| 232 | ): VolumeDataRestorePolicyOverride[] | undefined => |
| 233 | overrides === undefined |
| 234 | ? undefined |
| 235 | : overrides.map((item) => ({ |
| 236 | policy: item.policy, |
| 237 | selectedPvcs: item.selectedPvcs, |
| 238 | })); |
| 239 | |
| 240 | const toRestoreConfig = (config: gkebackup.RestoreConfig | undefined): RestoreConfig | undefined => |
| 241 | config === undefined |
| 242 | ? undefined |
| 243 | : { |
| 244 | namespacedResourceRestoreMode: config.namespacedResourceRestoreMode, |
| 245 | substitutionRules: config.substitutionRules, |
| 246 | excludedNamespaces: config.excludedNamespaces, |
| 247 | volumeDataRestorePolicyBindings: config.volumeDataRestorePolicyBindings, |
| 248 | allNamespaces: config.allNamespaces, |
| 249 | transformationRules: config.transformationRules, |
| 250 | restoreOrder: config.restoreOrder, |
| 251 | volumeDataRestorePolicy: config.volumeDataRestorePolicy, |
| 252 | clusterResourceConflictPolicy: config.clusterResourceConflictPolicy, |
| 253 | clusterResourceRestoreScope: config.clusterResourceRestoreScope, |
| 254 | selectedNamespaces: config.selectedNamespaces, |
| 255 | selectedApplications: config.selectedApplications, |
| 256 | noNamespaces: config.noNamespaces, |
| 257 | }; |
| 258 | |
| 259 | const toAttrs = (item: gkebackup.Restore, project: string, region: string) => { |
| 260 | const name = item.name ?? ""; |
| 261 | const parsed = parseName(name, "restores", region); |
| 262 | return { |
| 263 | name, |
| 264 | restoreId: parsed.id, |
| 265 | restorePlan: parsed.parent, |
| 266 | project: parsed.project || project, |
| 267 | location: parsed.location, |
| 268 | backup: item.backup, |
| 269 | cluster: item.cluster, |
| 270 | restoreConfig: toRestoreConfig(item.restoreConfig), |
| 271 | filter: toFilter(item.filter), |
| 272 | volumeDataRestorePolicyOverrides: toOverrides(item.volumeDataRestorePolicyOverrides), |
| 273 | description: item.description, |
| 274 | labels: userLabels(item.labels), |
| 275 | state: item.state, |
| 276 | stateReason: item.stateReason, |
| 277 | resourcesRestoredCount: item.resourcesRestoredCount, |
| 278 | resourcesFailedCount: item.resourcesFailedCount, |
| 279 | resourcesExcludedCount: item.resourcesExcludedCount, |
| 280 | volumesRestoredCount: item.volumesRestoredCount, |
| 281 | uid: item.uid, |
| 282 | createTime: item.createTime, |
| 283 | completeTime: item.completeTime, |
| 284 | }; |
| 285 | }; |
| 286 | |
| 287 | const getByName = (name: string) => |
| 288 | gkebackup |
| 289 | .getProjectsLocationsRestorePlansRestores({ name }) |
| 290 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 291 | |
| 292 | const listOwned = (project: string) => |
| 293 | listAtNested(project, "restorePlans/-", (parent) => |
| 294 | listLabeledPages( |
| 295 | gkebackup.listProjectsLocationsRestorePlansRestores.pages({ |
| 296 | parent, |
| 297 | pageSize: 1000, |
| 298 | }), |
| 299 | (page) => page.restores, |
| 300 | (item) => item.labels, |
| 301 | ), |
| 302 | ); |
| 303 | |
| 304 | const expandBackup = (value: string, restorePlan: string) => { |
| 305 | if (value.includes("/")) return value.replace(/\/+$/, ""); |
| 306 | const parts = restorePlan.split("/").filter((part) => part.length > 0); |
| 307 | const restorePlansAt = parts.lastIndexOf("restorePlans"); |
| 308 | const locationParent = |
| 309 | restorePlansAt > 0 ? parts.slice(0, restorePlansAt).join("/") : restorePlan; |
| 310 | // Callers that pass a bare backup id must also pass a full backup |
| 311 | // plan path via restorePlan's backupPlan attribute at create time; |
| 312 | // without it we cannot guess the BackupPlan id, so treat the value as |
| 313 | // already relative to the restore plan's location. |
| 314 | return `${locationParent}/backupPlans/-/backups/${value}`; |
| 315 | }; |
| 316 | |
| 317 | export const RestorePlansRestoreProvider = () => |
| 318 | Provider.succeed(RestorePlansRestore, { |
| 319 | stables: ["name", "restoreId", "restorePlan", "project", "location", "uid", "createTime"], |
| 320 | |
| 321 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 322 | if (!isResolved(news)) return undefined; |
| 323 | const env = yield* GcpEnvironment.current; |
| 324 | const previousBackup = olds?.backup ?? output?.backup; |
| 325 | return replaceOnIdentity({ |
| 326 | previousId: olds?.restoreId ?? output?.restoreId, |
| 327 | nextId: news.restoreId ?? olds?.restoreId ?? output?.restoreId, |
| 328 | previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region), |
| 329 | nextLocation: normalizeLocation( |
| 330 | news.location ?? olds?.location ?? output?.location, |
| 331 | env.region, |
| 332 | ), |
| 333 | previousParent: olds?.restorePlan ?? output?.restorePlan, |
| 334 | nextParent: news.restorePlan, |
| 335 | extra: |
| 336 | previousBackup !== undefined && |
| 337 | news.backup !== undefined && |
| 338 | previousBackup !== news.backup && |
| 339 | !previousBackup.endsWith(`/${news.backup}`), |
| 340 | }); |
| 341 | }), |
| 342 | |
| 343 | read: Effect.fn(function* ({ id, olds, output }) { |
| 344 | const env = yield* GcpEnvironment.current; |
| 345 | const restoreId = yield* toPhysicalId(id, olds?.restoreId, output?.restoreId, "restore"); |
| 346 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 347 | const plan = expandParent( |
| 348 | olds?.restorePlan ?? output?.restorePlan ?? "", |
| 349 | env.project, |
| 350 | location, |
| 351 | "restorePlans", |
| 352 | ); |
| 353 | const name = output?.name ?? resourceName(plan, restoreId); |
| 354 | const existing = yield* getByName(name); |
| 355 | if (existing === undefined) return undefined; |
| 356 | const attrs = toAttrs(existing, env.project, env.region); |
| 357 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 358 | }), |
| 359 | |
| 360 | list: () => |
| 361 | Effect.gen(function* () { |
| 362 | const env = yield* GcpEnvironment.current; |
| 363 | const items = yield* listOwned(env.project); |
| 364 | return items.map((item) => toAttrs(item, env.project, env.region)); |
| 365 | }), |
| 366 | |
| 367 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 368 | const env = yield* GcpEnvironment.current; |
| 369 | const restoreId = yield* toPhysicalId(id, news.restoreId, output?.restoreId, "restore"); |
| 370 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 371 | const plan = expandParent(news.restorePlan, env.project, location, "restorePlans"); |
| 372 | const name = resourceName(plan, restoreId); |
| 373 | const backup = news.backup.includes("/") |
| 374 | ? news.backup.replace(/\/+$/, "") |
| 375 | : expandBackup(news.backup, plan); |
| 376 | const desiredLabels = { |
| 377 | ...toLabels(news.labels), |
| 378 | ...(yield* createInternalLabels(id)), |
| 379 | }; |
| 380 | |
| 381 | let current = yield* getByName(output?.name ?? name); |
| 382 | |
| 383 | if (current === undefined) { |
| 384 | const created = yield* gkebackup |
| 385 | .createProjectsLocationsRestorePlansRestores({ |
| 386 | parent: plan, |
| 387 | restoreId, |
| 388 | body: { |
| 389 | backup, |
| 390 | filter: news.filter, |
| 391 | volumeDataRestorePolicyOverrides: news.volumeDataRestorePolicyOverrides, |
| 392 | description: news.description, |
| 393 | labels: desiredLabels, |
| 394 | }, |
| 395 | }) |
| 396 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 397 | if (created !== undefined) { |
| 398 | yield* waitForOperation(created); |
| 399 | } |
| 400 | current = yield* waitUntilExists(getByName(name), name); |
| 401 | } |
| 402 | |
| 403 | if (current === undefined) { |
| 404 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 405 | } |
| 406 | |
| 407 | const observedLabels = tagRecord(current.labels); |
| 408 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 409 | const mask = fieldMask([ |
| 410 | (upsert.length > 0 || removed.length > 0) && "labels", |
| 411 | !sameText(current.description, news.description) && "description", |
| 412 | ]); |
| 413 | |
| 414 | if (mask.length > 0) { |
| 415 | const operation = yield* gkebackup.patchProjectsLocationsRestorePlansRestores({ |
| 416 | name: current.name ?? name, |
| 417 | updateMask: mask, |
| 418 | body: { |
| 419 | etag: current.etag, |
| 420 | labels: desiredLabels, |
| 421 | description: news.description, |
| 422 | }, |
| 423 | }); |
| 424 | yield* waitForOperation(operation); |
| 425 | current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name); |
| 426 | } |
| 427 | |
| 428 | return toAttrs(current, env.project, env.region); |
| 429 | }), |
| 430 | |
| 431 | delete: Effect.fn(function* ({ output }) { |
| 432 | const operation = yield* gkebackup |
| 433 | .deleteProjectsLocationsRestorePlansRestores({ |
| 434 | name: output.name, |
| 435 | force: true, |
| 436 | }) |
| 437 | .pipe( |
| 438 | Effect.retry({ |
| 439 | while: (error) => error._tag === "Conflict", |
| 440 | times: 8, |
| 441 | schedule: Schedule.spaced("2 seconds"), |
| 442 | }), |
| 443 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 444 | ); |
| 445 | if (operation !== undefined) { |
| 446 | yield* waitForDeleteOperation(operation); |
| 447 | } |
| 448 | yield* waitUntilGone(getByName(output.name), output.name); |
| 449 | }), |
| 450 | }); |