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
| 1 | import * as backup from "@distilled.cloud/aws/backup"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { |
| 12 | normalizePolicyDocument, |
| 13 | stringifyPolicyDocument, |
| 14 | type PolicyDocument, |
| 15 | } from "../IAM/Policy.ts"; |
| 16 | import type { Providers } from "../Providers.ts"; |
| 17 | |
| 18 | export interface BackupVaultProps { |
| 19 | /** |
| 20 | * Name of the backup vault. Must be between 2 and 50 characters and |
| 21 | * contain only letters, numbers, hyphens, and underscores. If omitted, a |
| 22 | * unique name is generated from the app, stage, and logical ID. |
| 23 | * |
| 24 | * Changing the name replaces the vault. |
| 25 | */ |
| 26 | backupVaultName?: string; |
| 27 | /** |
| 28 | * ARN of the KMS key used to encrypt the recovery points stored in this |
| 29 | * vault. If omitted, AWS Backup uses an AWS-owned key. |
| 30 | * |
| 31 | * The encryption key is fixed at creation — changing it replaces the vault. |
| 32 | */ |
| 33 | encryptionKeyArn?: string; |
| 34 | /** |
| 35 | * Resource-based access policy attached to the vault. Provided as a |
| 36 | * structured {@link PolicyDocument} (typed actions, drift-normalized on |
| 37 | * re-deploy) or a raw JSON string escape hatch. Omit to leave the vault |
| 38 | * without a resource policy. |
| 39 | */ |
| 40 | accessPolicy?: PolicyDocument | string; |
| 41 | /** |
| 42 | * Tags to apply to the vault. Merged with internal Alchemy tags. |
| 43 | */ |
| 44 | tags?: Record<string, string>; |
| 45 | } |
| 46 | |
| 47 | export interface BackupVault extends Resource< |
| 48 | "AWS.Backup.BackupVault", |
| 49 | BackupVaultProps, |
| 50 | { |
| 51 | /** |
| 52 | * Name of the backup vault. |
| 53 | */ |
| 54 | backupVaultName: string; |
| 55 | /** |
| 56 | * ARN of the backup vault. |
| 57 | */ |
| 58 | backupVaultArn: string; |
| 59 | }, |
| 60 | never, |
| 61 | Providers |
| 62 | > {} |
| 63 | |
| 64 | /** |
| 65 | * An AWS Backup vault — a logical container that stores and organizes |
| 66 | * recovery points created by backup jobs. |
| 67 | * |
| 68 | * A vault name is auto-generated from the app, stage, and logical ID unless |
| 69 | * you provide one explicitly. Recovery points can optionally be encrypted |
| 70 | * with a customer-managed KMS key, and access to the vault can be restricted |
| 71 | * with a resource-based policy. |
| 72 | * |
| 73 | * ### Creating a Vault |
| 74 | * **Example:** Basic Vault |
| 75 | * ```typescript |
| 76 | * import * as Backup from "@alchemy.run/aws/Backup"; |
| 77 | * |
| 78 | * const vault = yield* Backup.BackupVault("AppBackups"); |
| 79 | * ``` |
| 80 | * |
| 81 | * **Example:** Vault with a Customer-Managed KMS Key |
| 82 | * ```typescript |
| 83 | * const vault = yield* Backup.BackupVault("EncryptedBackups", { |
| 84 | * encryptionKeyArn: key.keyArn, |
| 85 | * }); |
| 86 | * ``` |
| 87 | * |
| 88 | * ### Vault Access Policy |
| 89 | * **Example:** Deny deletion of recovery points |
| 90 | * ```typescript |
| 91 | * const vault = yield* Backup.BackupVault("LockedBackups", { |
| 92 | * accessPolicy: { |
| 93 | * Version: "2012-10-17", |
| 94 | * Statement: [ |
| 95 | * { |
| 96 | * Effect: "Deny", |
| 97 | * Principal: { AWS: "*" }, |
| 98 | * Action: ["backup:DeleteRecoveryPoint"], |
| 99 | * Resource: "*", |
| 100 | * }, |
| 101 | * ], |
| 102 | * }, |
| 103 | * }); |
| 104 | * ``` |
| 105 | * |
| 106 | * @resource |
| 107 | */ |
| 108 | export const BackupVault = Resource<BackupVault>("AWS.Backup.BackupVault"); |
| 109 | |
| 110 | const toPolicyString = (policy: PolicyDocument | string | undefined): string | undefined => |
| 111 | policy === undefined |
| 112 | ? undefined |
| 113 | : typeof policy === "string" |
| 114 | ? policy |
| 115 | : stringifyPolicyDocument(policy); |
| 116 | |
| 117 | export const BackupVaultProvider = () => |
| 118 | Provider.effect( |
| 119 | BackupVault, |
| 120 | Effect.gen(function* () { |
| 121 | const createName = Effect.fn(function* (id: string, props: BackupVaultProps) { |
| 122 | return props.backupVaultName ?? (yield* createPhysicalName({ id, maxLength: 50 })); |
| 123 | }); |
| 124 | |
| 125 | return BackupVault.Provider.of({ |
| 126 | stables: ["backupVaultName", "backupVaultArn"], |
| 127 | list: () => |
| 128 | backup.listBackupVaults.pages({}).pipe( |
| 129 | Stream.runCollect, |
| 130 | Effect.map((chunk) => |
| 131 | Array.from(chunk) |
| 132 | .flatMap((page) => page.BackupVaultList ?? []) |
| 133 | .filter( |
| 134 | (v) => |
| 135 | v.BackupVaultName !== undefined && |
| 136 | v.BackupVaultArn !== undefined && |
| 137 | // Service-managed vaults (e.g. EFS automatic backups' |
| 138 | // `aws/efs/automatic-backup-vault`) reject |
| 139 | // DeleteBackupVault with a 403 even when empty (verified |
| 140 | // live) — keep them out of enumeration for account-wide |
| 141 | // teardown (nuke). |
| 142 | !v.BackupVaultName.startsWith("aws/"), |
| 143 | ) |
| 144 | .map((v) => ({ |
| 145 | backupVaultName: v.BackupVaultName!, |
| 146 | backupVaultArn: v.BackupVaultArn!, |
| 147 | })), |
| 148 | ), |
| 149 | ), |
| 150 | read: Effect.fn(function* ({ id, olds, output }) { |
| 151 | const name = output?.backupVaultName ?? (yield* createName(id, olds ?? {})); |
| 152 | // AWS Backup returns AccessDeniedException (with an empty message), |
| 153 | // not ResourceNotFoundException, when a vault does not exist — it |
| 154 | // hides existence behind a 403. Treat both as "absent". |
| 155 | const found = yield* backup |
| 156 | .describeBackupVault({ BackupVaultName: name }) |
| 157 | .pipe( |
| 158 | Effect.catchTag( |
| 159 | ["ResourceNotFoundException", "AccessDeniedException"], |
| 160 | () => Effect.undefined, |
| 161 | ), |
| 162 | ); |
| 163 | if (!found?.BackupVaultArn) return undefined; |
| 164 | const attrs = { |
| 165 | backupVaultName: name, |
| 166 | backupVaultArn: found.BackupVaultArn, |
| 167 | }; |
| 168 | const tags = yield* backup.listTags({ ResourceArn: found.BackupVaultArn }).pipe( |
| 169 | Effect.map((r) => r.Tags ?? {}), |
| 170 | Effect.orElseSucceed(() => ({}) as Record<string, string | undefined>), |
| 171 | ); |
| 172 | return (yield* hasAlchemyTags(id, tags as Record<string, string>)) |
| 173 | ? attrs |
| 174 | : Unowned(attrs); |
| 175 | }), |
| 176 | diff: Effect.fn(function* ({ id, news = {}, olds = {} }) { |
| 177 | if (!isResolved(news)) return undefined; |
| 178 | const oldName = yield* createName(id, olds); |
| 179 | const newName = yield* createName(id, news); |
| 180 | if (oldName !== newName) return { action: "replace" } as const; |
| 181 | if ((olds.encryptionKeyArn ?? "") !== (news.encryptionKeyArn ?? "")) { |
| 182 | return { action: "replace" } as const; |
| 183 | } |
| 184 | }), |
| 185 | reconcile: Effect.fn(function* ({ id, news = {}, output, session }) { |
| 186 | const name = output?.backupVaultName ?? (yield* createName(id, news)); |
| 187 | const internalTags = yield* createInternalTags(id); |
| 188 | |
| 189 | // OBSERVE — cloud state is authoritative; output is only an id cache. |
| 190 | // A missing vault surfaces as AccessDeniedException (see read()). |
| 191 | let live = yield* backup |
| 192 | .describeBackupVault({ BackupVaultName: name }) |
| 193 | .pipe( |
| 194 | Effect.catchTag( |
| 195 | ["ResourceNotFoundException", "AccessDeniedException"], |
| 196 | () => Effect.undefined, |
| 197 | ), |
| 198 | ); |
| 199 | |
| 200 | // ENSURE — create if missing; tolerate an AlreadyExists race. |
| 201 | if (!live?.BackupVaultArn) { |
| 202 | live = yield* backup |
| 203 | .createBackupVault({ |
| 204 | BackupVaultName: name, |
| 205 | EncryptionKeyArn: news.encryptionKeyArn, |
| 206 | BackupVaultTags: { ...internalTags, ...news.tags }, |
| 207 | }) |
| 208 | .pipe( |
| 209 | Effect.catchTag("AlreadyExistsException", () => |
| 210 | backup.describeBackupVault({ BackupVaultName: name }), |
| 211 | ), |
| 212 | ); |
| 213 | } |
| 214 | const backupVaultArn = live.BackupVaultArn!; |
| 215 | |
| 216 | // SYNC access policy — diff observed against desired, comparing |
| 217 | // canonicalized documents so a re-deploy of an equivalent policy |
| 218 | // (key order, whitespace) is a no-op. |
| 219 | const desiredPolicy = toPolicyString(news.accessPolicy); |
| 220 | const currentPolicy = yield* backup |
| 221 | .getBackupVaultAccessPolicy({ BackupVaultName: name }) |
| 222 | .pipe( |
| 223 | Effect.map((r) => (r.Policy ? r.Policy : undefined)), |
| 224 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 225 | ); |
| 226 | const policyDrifted = |
| 227 | desiredPolicy === undefined || currentPolicy === undefined |
| 228 | ? desiredPolicy !== currentPolicy |
| 229 | : normalizePolicyDocument(currentPolicy) !== normalizePolicyDocument(desiredPolicy); |
| 230 | if (policyDrifted) { |
| 231 | if (desiredPolicy === undefined) { |
| 232 | yield* backup |
| 233 | .deleteBackupVaultAccessPolicy({ BackupVaultName: name }) |
| 234 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 235 | } else { |
| 236 | yield* backup.putBackupVaultAccessPolicy({ |
| 237 | BackupVaultName: name, |
| 238 | Policy: desiredPolicy, |
| 239 | }); |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // SYNC tags — diff against observed cloud tags. |
| 244 | const currentTags = yield* backup.listTags({ ResourceArn: backupVaultArn }).pipe( |
| 245 | Effect.map((r) => r.Tags ?? {}), |
| 246 | Effect.orElseSucceed(() => ({}) as Record<string, string | undefined>), |
| 247 | ); |
| 248 | const { upsert, removed } = diffTags(currentTags as Record<string, string>, { |
| 249 | ...news.tags, |
| 250 | ...internalTags, |
| 251 | }); |
| 252 | if (upsert.length > 0) { |
| 253 | yield* backup.tagResource({ |
| 254 | ResourceArn: backupVaultArn, |
| 255 | Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 256 | }); |
| 257 | } |
| 258 | if (removed.length > 0) { |
| 259 | yield* backup.untagResource({ |
| 260 | ResourceArn: backupVaultArn, |
| 261 | TagKeyList: removed, |
| 262 | }); |
| 263 | } |
| 264 | |
| 265 | yield* session.note(backupVaultArn); |
| 266 | return { backupVaultName: name, backupVaultArn }; |
| 267 | }), |
| 268 | delete: Effect.fn(function* ({ output }) { |
| 269 | // A vault can only be deleted when it is empty — delete any |
| 270 | // remaining recovery points first. Each delete tolerates the point |
| 271 | // already being gone or being in a state that can't be deleted |
| 272 | // right now (EXPIRED/continuous points settle on their own). |
| 273 | const recoveryPoints = yield* backup.listRecoveryPointsByBackupVault |
| 274 | .pages({ BackupVaultName: output.backupVaultName }) |
| 275 | .pipe( |
| 276 | Stream.runCollect, |
| 277 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.RecoveryPoints ?? [])), |
| 278 | Effect.catchTag(["ResourceNotFoundException", "AccessDeniedException"], () => |
| 279 | Effect.succeed([]), |
| 280 | ), |
| 281 | ); |
| 282 | yield* Effect.forEach( |
| 283 | recoveryPoints, |
| 284 | (rp) => |
| 285 | rp.RecoveryPointArn |
| 286 | ? backup |
| 287 | .deleteRecoveryPoint({ |
| 288 | BackupVaultName: output.backupVaultName, |
| 289 | RecoveryPointArn: rp.RecoveryPointArn, |
| 290 | }) |
| 291 | .pipe( |
| 292 | Effect.catchTag( |
| 293 | ["ResourceNotFoundException", "InvalidResourceStateException"], |
| 294 | () => Effect.void, |
| 295 | ), |
| 296 | ) |
| 297 | : Effect.void, |
| 298 | { discard: true }, |
| 299 | ); |
| 300 | // A missing vault deletes as AccessDeniedException, not |
| 301 | // ResourceNotFoundException — both mean "already gone" here. |
| 302 | yield* backup.deleteBackupVault({ BackupVaultName: output.backupVaultName }).pipe( |
| 303 | Effect.catchTag( |
| 304 | ["ResourceNotFoundException", "AccessDeniedException"], |
| 305 | () => Effect.void, |
| 306 | ), |
| 307 | // Recovery-point deletion is asynchronous; the vault delete |
| 308 | // rejects with InvalidRequestException until the vault empties. |
| 309 | Effect.retry({ |
| 310 | while: (e) => e._tag === "InvalidRequestException", |
| 311 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]), |
| 312 | }), |
| 313 | ); |
| 314 | }), |
| 315 | }); |
| 316 | }), |
| 317 | ); |