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
| 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 | clusterName, |
| 14 | expandParent, |
| 15 | fieldMask, |
| 16 | fingerprint, |
| 17 | listAtLocation, |
| 18 | listLabeledPages, |
| 19 | normalizeLocation, |
| 20 | parentOf, |
| 21 | parseName, |
| 22 | replaceOnIdentity, |
| 23 | ResourceNotResolved, |
| 24 | sameText, |
| 25 | toPhysicalId, |
| 26 | userLabels, |
| 27 | waitForDeleteOperation, |
| 28 | waitForOperation, |
| 29 | waitUntilExists, |
| 30 | waitUntilGone, |
| 31 | waitUntilReady, |
| 32 | } from "./internal.ts"; |
| 33 | |
| 34 | export type GroupKind = { |
| 35 | /** API group string (empty string for the core group). */ |
| 36 | resourceGroup?: string; |
| 37 | /** Kind in UpperCamelCase singular form. */ |
| 38 | resourceKind?: string; |
| 39 | }; |
| 40 | |
| 41 | export type SubstitutionRule = { |
| 42 | /** Regex compared against fields matched by `targetJsonPath`. */ |
| 43 | originalValuePattern?: string; |
| 44 | /** JSONPath that selects fields to substitute. */ |
| 45 | targetJsonPath?: string; |
| 46 | /** Replacement value. Empty string removes the field. */ |
| 47 | newValue?: string; |
| 48 | /** Restrict substitution to these group kinds. */ |
| 49 | targetGroupKinds?: GroupKind[]; |
| 50 | /** Restrict substitution to these namespaces. */ |
| 51 | targetNamespaces?: string[]; |
| 52 | }; |
| 53 | |
| 54 | export type VolumeDataRestorePolicyBinding = { |
| 55 | /** Policy applied to volumes in scope. */ |
| 56 | policy?: gkebackup.VolumeDataRestorePolicyBindingPolicyEnum | (string & {}); |
| 57 | /** Volume type this binding applies to. */ |
| 58 | volumeType?: gkebackup.VolumeDataRestorePolicyBindingVolumeTypeEnum | (string & {}); |
| 59 | }; |
| 60 | |
| 61 | export type TransformationRuleAction = { |
| 62 | /** JSON Pointer for the operation path. */ |
| 63 | path?: string; |
| 64 | /** JSON Patch operation. */ |
| 65 | op?: gkebackup.TransformationRuleActionOpEnum | (string & {}); |
| 66 | /** JSON Pointer for move/copy source. */ |
| 67 | fromPath?: string; |
| 68 | /** Desired value for add/replace/test. */ |
| 69 | value?: string; |
| 70 | }; |
| 71 | |
| 72 | export type ResourceFilter = { |
| 73 | /** JSONPath filtering expression. */ |
| 74 | jsonPath?: string; |
| 75 | /** Restrict transformation to these group kinds. */ |
| 76 | groupKinds?: GroupKind[]; |
| 77 | /** Restrict transformation to these namespaces. */ |
| 78 | namespaces?: string[]; |
| 79 | }; |
| 80 | |
| 81 | export type TransformationRule = { |
| 82 | /** JSON Patch actions, executed in order. */ |
| 83 | fieldActions?: TransformationRuleAction[]; |
| 84 | /** Human-readable description of the rule. */ |
| 85 | description?: string; |
| 86 | /** Filter selecting which restored resources the rule applies to. */ |
| 87 | resourceFilter?: ResourceFilter; |
| 88 | }; |
| 89 | |
| 90 | export type RestoreOrder = { |
| 91 | /** Group-kind dependency pairs that order restore. */ |
| 92 | groupKindDependencies?: Array<{ |
| 93 | /** Group kind that must be restored first. */ |
| 94 | satisfying?: GroupKind; |
| 95 | /** Group kind that depends on `satisfying`. */ |
| 96 | requiring?: GroupKind; |
| 97 | }>; |
| 98 | }; |
| 99 | |
| 100 | export type ClusterResourceRestoreScope = { |
| 101 | /** Restore only these cluster-scoped group kinds. */ |
| 102 | selectedGroupKinds?: GroupKind[]; |
| 103 | /** When true, restore no cluster-scoped resources. */ |
| 104 | noGroupKinds?: boolean; |
| 105 | /** When true, restore all valid cluster-scoped resources. */ |
| 106 | allGroupKinds?: boolean; |
| 107 | /** Restore all valid cluster-scoped resources except these. */ |
| 108 | excludedGroupKinds?: GroupKind[]; |
| 109 | }; |
| 110 | |
| 111 | export type RestoreConfig = { |
| 112 | /** |
| 113 | * How to handle namespaced resources that already exist in the target |
| 114 | * cluster. |
| 115 | */ |
| 116 | namespacedResourceRestoreMode?: |
| 117 | | gkebackup.RestoreConfigNamespacedResourceRestoreModeEnum |
| 118 | | (string & {}); |
| 119 | /** Substitution rules applied during restore. */ |
| 120 | substitutionRules?: SubstitutionRule[]; |
| 121 | /** Namespaces excluded from restoration. */ |
| 122 | excludedNamespaces?: { namespaces?: string[] }; |
| 123 | /** Per-volume-type restore policy bindings. */ |
| 124 | volumeDataRestorePolicyBindings?: VolumeDataRestorePolicyBinding[]; |
| 125 | /** When true, restore all namespaced resources in the Backup. */ |
| 126 | allNamespaces?: boolean; |
| 127 | /** Transformation rules applied during restore. */ |
| 128 | transformationRules?: TransformationRule[]; |
| 129 | /** Custom restore ordering. */ |
| 130 | restoreOrder?: RestoreOrder; |
| 131 | /** |
| 132 | * How volume data is restored. |
| 133 | * @default "NO_VOLUME_DATA_RESTORATION" |
| 134 | */ |
| 135 | volumeDataRestorePolicy?: gkebackup.RestoreConfigVolumeDataRestorePolicyEnum | (string & {}); |
| 136 | /** |
| 137 | * How to handle cluster-scoped resources that already exist. |
| 138 | */ |
| 139 | clusterResourceConflictPolicy?: |
| 140 | | gkebackup.RestoreConfigClusterResourceConflictPolicyEnum |
| 141 | | (string & {}); |
| 142 | /** Cluster-scoped resources to restore. */ |
| 143 | clusterResourceRestoreScope?: ClusterResourceRestoreScope; |
| 144 | /** Restore only these namespaces and their resources. */ |
| 145 | selectedNamespaces?: { namespaces?: string[] }; |
| 146 | /** Restore only these ProtectedApplications and their resources. */ |
| 147 | selectedApplications?: { |
| 148 | namespacedNames?: Array<{ |
| 149 | /** Kubernetes namespace. */ |
| 150 | namespace?: string; |
| 151 | /** Kubernetes resource name. */ |
| 152 | name?: string; |
| 153 | }>; |
| 154 | }; |
| 155 | /** When true, restore no namespaced resources. */ |
| 156 | noNamespaces?: boolean; |
| 157 | }; |
| 158 | |
| 159 | export type RestorePlanProps = { |
| 160 | /** |
| 161 | * Restore plan id (the `{restorePlan}` segment of |
| 162 | * `projects/{project}/locations/{location}/restorePlans/{restorePlan}`). |
| 163 | * If omitted, a unique RFC1035 name is generated from the stack, stage, |
| 164 | * and logical id. Immutable — changing it replaces the plan. |
| 165 | */ |
| 166 | restorePlanId?: string; |
| 167 | /** |
| 168 | * Region (`us-central1`, `us-east1`, …). Immutable — changing it |
| 169 | * replaces the plan. Must match the target cluster region. |
| 170 | * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) |
| 171 | */ |
| 172 | location?: string; |
| 173 | /** |
| 174 | * Target GKE cluster. Full name or a cluster id combined with |
| 175 | * `location`. Immutable — changing it replaces the plan. |
| 176 | */ |
| 177 | cluster: string; |
| 178 | /** |
| 179 | * Source BackupPlan. Full name |
| 180 | * `projects/{project}/locations/{location}/backupPlans/{backupPlan}` |
| 181 | * or a plan id combined with `location`. Immutable — changing it |
| 182 | * replaces the plan. |
| 183 | */ |
| 184 | backupPlan: string; |
| 185 | /** |
| 186 | * Configuration of Restores created via this plan. |
| 187 | */ |
| 188 | restoreConfig: RestoreConfig; |
| 189 | /** |
| 190 | * Human-readable description. |
| 191 | */ |
| 192 | description?: string; |
| 193 | /** |
| 194 | * User labels. Alchemy ownership labels are merged in automatically. |
| 195 | */ |
| 196 | labels?: Record<string, string>; |
| 197 | }; |
| 198 | |
| 199 | export type RestorePlan = Resource< |
| 200 | "GCP.GKEBackup.RestorePlan", |
| 201 | RestorePlanProps, |
| 202 | { |
| 203 | /** Full resource name. */ |
| 204 | name: string; |
| 205 | /** Restore plan id (last path segment). */ |
| 206 | restorePlanId: string; |
| 207 | /** Project id. */ |
| 208 | project: string; |
| 209 | /** Location id. */ |
| 210 | location: string; |
| 211 | /** Target cluster name. */ |
| 212 | cluster: string | undefined; |
| 213 | /** Source BackupPlan name. */ |
| 214 | backupPlan: string | undefined; |
| 215 | /** Cross-project restore channel, if any. */ |
| 216 | restoreChannel: string | undefined; |
| 217 | /** Restore configuration. */ |
| 218 | restoreConfig: RestoreConfig | undefined; |
| 219 | /** Human-readable description. */ |
| 220 | description: string | undefined; |
| 221 | /** User labels (Alchemy ownership labels stripped). */ |
| 222 | labels: Record<string, string>; |
| 223 | /** Server-reported state. */ |
| 224 | state: string | undefined; |
| 225 | /** Human-readable state reason. */ |
| 226 | stateReason: string | undefined; |
| 227 | /** Server-generated resource uid. */ |
| 228 | uid: string | undefined; |
| 229 | /** RFC3339 creation timestamp. */ |
| 230 | createTime: string | undefined; |
| 231 | /** RFC3339 last-update timestamp. */ |
| 232 | updateTime: string | undefined; |
| 233 | }, |
| 234 | never, |
| 235 | Providers |
| 236 | >; |
| 237 | |
| 238 | /** |
| 239 | * A Backup for GKE restore plan — the configuration for restoring |
| 240 | * Backups from a BackupPlan into a target cluster. |
| 241 | * |
| 242 | * Changing `restorePlanId`, `location`, `cluster`, or `backupPlan` |
| 243 | * replaces the plan. Description, labels, and `restoreConfig` update in |
| 244 | * place. |
| 245 | * |
| 246 | * ### Creating a Restore Plan |
| 247 | * **Example:** Restore all namespaces |
| 248 | * ```typescript |
| 249 | * const plan = yield* GCP.GKEBackup.RestorePlan("Rollback", { |
| 250 | * cluster: cluster.name, |
| 251 | * backupPlan: backupPlan.name, |
| 252 | * restoreConfig: { |
| 253 | * allNamespaces: true, |
| 254 | * namespacedResourceRestoreMode: "FAIL_ON_CONFLICT", |
| 255 | * volumeDataRestorePolicy: "NO_VOLUME_DATA_RESTORATION", |
| 256 | * }, |
| 257 | * }); |
| 258 | * ``` |
| 259 | * |
| 260 | * **Example:** Selected namespaces |
| 261 | * ```typescript |
| 262 | * const plan = yield* GCP.GKEBackup.RestorePlan("Rollback", { |
| 263 | * cluster: cluster.name, |
| 264 | * backupPlan: backupPlan.name, |
| 265 | * restoreConfig: { |
| 266 | * selectedNamespaces: { namespaces: ["app"] }, |
| 267 | * namespacedResourceRestoreMode: "MERGE_SKIP_ON_CONFLICT", |
| 268 | * }, |
| 269 | * labels: { env: "prod" }, |
| 270 | * }); |
| 271 | * ``` |
| 272 | * |
| 273 | * ### Updating a Restore Plan |
| 274 | * **Example:** Description and labels |
| 275 | * ```typescript |
| 276 | * const plan = yield* GCP.GKEBackup.RestorePlan("Rollback", { |
| 277 | * cluster: cluster.name, |
| 278 | * backupPlan: backupPlan.name, |
| 279 | * restoreConfig: { allNamespaces: true }, |
| 280 | * description: "rollback v2", |
| 281 | * labels: { env: "prod", team: "platform" }, |
| 282 | * }); |
| 283 | * ``` |
| 284 | * |
| 285 | * @resource |
| 286 | * @category GKEBackup |
| 287 | */ |
| 288 | export const RestorePlan = Resource<RestorePlan>("GCP.GKEBackup.RestorePlan"); |
| 289 | |
| 290 | const resourceName = (project: string, location: string, restorePlanId: string) => |
| 291 | `projects/${project}/locations/${location}/restorePlans/${restorePlanId}`; |
| 292 | |
| 293 | const toRestoreConfig = (config: gkebackup.RestoreConfig | undefined): RestoreConfig | undefined => |
| 294 | config === undefined |
| 295 | ? undefined |
| 296 | : { |
| 297 | namespacedResourceRestoreMode: config.namespacedResourceRestoreMode, |
| 298 | substitutionRules: config.substitutionRules, |
| 299 | excludedNamespaces: config.excludedNamespaces, |
| 300 | volumeDataRestorePolicyBindings: config.volumeDataRestorePolicyBindings, |
| 301 | allNamespaces: config.allNamespaces, |
| 302 | transformationRules: config.transformationRules, |
| 303 | restoreOrder: config.restoreOrder, |
| 304 | volumeDataRestorePolicy: config.volumeDataRestorePolicy, |
| 305 | clusterResourceConflictPolicy: config.clusterResourceConflictPolicy, |
| 306 | clusterResourceRestoreScope: config.clusterResourceRestoreScope, |
| 307 | selectedNamespaces: config.selectedNamespaces, |
| 308 | selectedApplications: config.selectedApplications, |
| 309 | noNamespaces: config.noNamespaces, |
| 310 | }; |
| 311 | |
| 312 | const toAttrs = (item: gkebackup.RestorePlan, project: string, region: string) => { |
| 313 | const name = item.name ?? ""; |
| 314 | const parsed = parseName(name, "restorePlans", region); |
| 315 | return { |
| 316 | name, |
| 317 | restorePlanId: parsed.id, |
| 318 | project: parsed.project || project, |
| 319 | location: parsed.location, |
| 320 | cluster: item.cluster, |
| 321 | backupPlan: item.backupPlan, |
| 322 | restoreChannel: item.restoreChannel, |
| 323 | restoreConfig: toRestoreConfig(item.restoreConfig), |
| 324 | description: item.description, |
| 325 | labels: userLabels(item.labels), |
| 326 | state: item.state, |
| 327 | stateReason: item.stateReason, |
| 328 | uid: item.uid, |
| 329 | createTime: item.createTime, |
| 330 | updateTime: item.updateTime, |
| 331 | }; |
| 332 | }; |
| 333 | |
| 334 | const getByName = (name: string) => |
| 335 | gkebackup |
| 336 | .getProjectsLocationsRestorePlans({ name }) |
| 337 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 338 | |
| 339 | const listOwned = (project: string) => |
| 340 | listAtLocation(project, (parent) => |
| 341 | listLabeledPages( |
| 342 | gkebackup.listProjectsLocationsRestorePlans.pages({ |
| 343 | parent, |
| 344 | pageSize: 1000, |
| 345 | }), |
| 346 | (page) => page.restorePlans, |
| 347 | (item) => item.labels, |
| 348 | ), |
| 349 | ); |
| 350 | |
| 351 | export const RestorePlanProvider = () => |
| 352 | Provider.succeed(RestorePlan, { |
| 353 | stables: ["name", "restorePlanId", "project", "location", "uid", "createTime"], |
| 354 | |
| 355 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 356 | if (!isResolved(news)) return undefined; |
| 357 | const env = yield* GcpEnvironment.current; |
| 358 | const previousCluster = olds?.cluster ?? output?.cluster; |
| 359 | const previousPlan = olds?.backupPlan ?? output?.backupPlan; |
| 360 | return replaceOnIdentity({ |
| 361 | previousId: olds?.restorePlanId ?? output?.restorePlanId, |
| 362 | nextId: news.restorePlanId ?? olds?.restorePlanId ?? output?.restorePlanId, |
| 363 | previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region), |
| 364 | nextLocation: normalizeLocation( |
| 365 | news.location ?? olds?.location ?? output?.location, |
| 366 | env.region, |
| 367 | ), |
| 368 | extra: |
| 369 | (previousCluster !== undefined && |
| 370 | news.cluster !== undefined && |
| 371 | previousCluster !== news.cluster && |
| 372 | !previousCluster.endsWith(`/${news.cluster}`)) || |
| 373 | (previousPlan !== undefined && |
| 374 | news.backupPlan !== undefined && |
| 375 | previousPlan !== news.backupPlan && |
| 376 | !previousPlan.endsWith(`/${news.backupPlan}`)), |
| 377 | }); |
| 378 | }), |
| 379 | |
| 380 | read: Effect.fn(function* ({ id, olds, output }) { |
| 381 | const env = yield* GcpEnvironment.current; |
| 382 | const restorePlanId = yield* toPhysicalId( |
| 383 | id, |
| 384 | olds?.restorePlanId, |
| 385 | output?.restorePlanId, |
| 386 | "restoreplan", |
| 387 | ); |
| 388 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 389 | const name = output?.name ?? resourceName(env.project, location, restorePlanId); |
| 390 | const existing = yield* getByName(name); |
| 391 | if (existing === undefined) return undefined; |
| 392 | const attrs = toAttrs(existing, env.project, env.region); |
| 393 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 394 | }), |
| 395 | |
| 396 | list: () => |
| 397 | Effect.gen(function* () { |
| 398 | const env = yield* GcpEnvironment.current; |
| 399 | const items = yield* listOwned(env.project); |
| 400 | return items.map((item) => toAttrs(item, env.project, env.region)); |
| 401 | }), |
| 402 | |
| 403 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 404 | const env = yield* GcpEnvironment.current; |
| 405 | const restorePlanId = yield* toPhysicalId( |
| 406 | id, |
| 407 | news.restorePlanId, |
| 408 | output?.restorePlanId, |
| 409 | "restoreplan", |
| 410 | ); |
| 411 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 412 | const name = resourceName(env.project, location, restorePlanId); |
| 413 | const cluster = clusterName(news.cluster, env.project, location); |
| 414 | const backupPlan = expandParent(news.backupPlan, env.project, location, "backupPlans"); |
| 415 | const desiredLabels = { |
| 416 | ...toLabels(news.labels), |
| 417 | ...(yield* createInternalLabels(id)), |
| 418 | }; |
| 419 | |
| 420 | let current = yield* getByName(output?.name ?? name); |
| 421 | |
| 422 | if (current === undefined) { |
| 423 | const created = yield* gkebackup |
| 424 | .createProjectsLocationsRestorePlans({ |
| 425 | parent: parentOf(env.project, location), |
| 426 | restorePlanId, |
| 427 | body: { |
| 428 | cluster, |
| 429 | backupPlan, |
| 430 | restoreConfig: news.restoreConfig, |
| 431 | description: news.description, |
| 432 | labels: desiredLabels, |
| 433 | }, |
| 434 | }) |
| 435 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 436 | if (created !== undefined) { |
| 437 | yield* waitForOperation(created); |
| 438 | } |
| 439 | current = yield* waitUntilExists(getByName(name), name); |
| 440 | } |
| 441 | |
| 442 | if (current === undefined) { |
| 443 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 444 | } |
| 445 | |
| 446 | current = yield* waitUntilReady( |
| 447 | getByName(current.name ?? name), |
| 448 | current.name ?? name, |
| 449 | (item) => item.state, |
| 450 | (item) => item.stateReason, |
| 451 | ); |
| 452 | if (current === undefined) { |
| 453 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 454 | } |
| 455 | |
| 456 | const observedLabels = tagRecord(current.labels); |
| 457 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 458 | const mask = fieldMask([ |
| 459 | (upsert.length > 0 || removed.length > 0) && "labels", |
| 460 | !sameText(current.description, news.description) && "description", |
| 461 | fingerprint(toRestoreConfig(current.restoreConfig)) !== fingerprint(news.restoreConfig) && |
| 462 | "restoreConfig", |
| 463 | ]); |
| 464 | |
| 465 | if (mask.length > 0) { |
| 466 | const operation = yield* gkebackup.patchProjectsLocationsRestorePlans({ |
| 467 | name: current.name ?? name, |
| 468 | updateMask: mask, |
| 469 | body: { |
| 470 | etag: current.etag, |
| 471 | labels: desiredLabels, |
| 472 | description: news.description, |
| 473 | restoreConfig: news.restoreConfig, |
| 474 | }, |
| 475 | }); |
| 476 | yield* waitForOperation(operation); |
| 477 | current = yield* waitUntilReady( |
| 478 | getByName(current.name ?? name), |
| 479 | current.name ?? name, |
| 480 | (item) => item.state, |
| 481 | (item) => item.stateReason, |
| 482 | ); |
| 483 | if (current === undefined) { |
| 484 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | return toAttrs(current, env.project, env.region); |
| 489 | }), |
| 490 | |
| 491 | delete: Effect.fn(function* ({ output }) { |
| 492 | const operation = yield* gkebackup |
| 493 | .deleteProjectsLocationsRestorePlans({ |
| 494 | name: output.name, |
| 495 | force: true, |
| 496 | }) |
| 497 | .pipe( |
| 498 | Effect.retry({ |
| 499 | while: (error) => error._tag === "Conflict", |
| 500 | times: 8, |
| 501 | schedule: Schedule.spaced("2 seconds"), |
| 502 | }), |
| 503 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 504 | ); |
| 505 | if (operation !== undefined) { |
| 506 | yield* waitForDeleteOperation(operation); |
| 507 | } |
| 508 | yield* waitUntilGone(getByName(output.name), output.name); |
| 509 | }), |
| 510 | }); |