| 1 | import * as backupsearch from "@distilled.cloud/aws/backupsearch"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import { diffTags } from "../../Tags.ts"; |
| 4 | |
| 5 | /** |
| 6 | * Coerce a BackupSearch wire tag map (a sparse `Record<string, string | |
| 7 | * undefined>`) into a plain `Record<string, string>`. |
| 8 | */ |
| 9 | export const toTagRecord = ( |
| 10 | tags: { [key: string]: string | undefined } | undefined, |
| 11 | ): Record<string, string> => |
| 12 | Object.fromEntries( |
| 13 | Object.entries(tags ?? {}).filter( |
| 14 | (entry): entry is [string, string] => entry[1] !== undefined, |
| 15 | ), |
| 16 | ); |
| 17 | |
| 18 | /** |
| 19 | * Read the observed tags of a BackupSearch resource by ARN. Tag reads are |
| 20 | * best-effort — a failure (e.g. a race with job expiry) reports no tags. |
| 21 | */ |
| 22 | export const readBackupSearchTags = Effect.fn(function* (arn: string) { |
| 23 | const response = yield* backupsearch |
| 24 | .listTagsForResource({ ResourceArn: arn }) |
| 25 | .pipe(Effect.catch(() => Effect.succeed(undefined))); |
| 26 | return toTagRecord(response?.Tags); |
| 27 | }); |
| 28 | |
| 29 | /** |
| 30 | * Sync tags on a BackupSearch resource: diff the OBSERVED cloud tags against |
| 31 | * the desired set and apply only the delta. |
| 32 | */ |
| 33 | export const syncBackupSearchTags = Effect.fn(function* ( |
| 34 | arn: string, |
| 35 | desiredTags: Record<string, string>, |
| 36 | ) { |
| 37 | const observedTags = yield* readBackupSearchTags(arn); |
| 38 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 39 | if (upsert.length > 0) { |
| 40 | yield* backupsearch.tagResource({ |
| 41 | ResourceArn: arn, |
| 42 | Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 43 | }); |
| 44 | } |
| 45 | if (removed.length > 0) { |
| 46 | yield* backupsearch.untagResource({ ResourceArn: arn, TagKeys: removed }); |
| 47 | } |
| 48 | }); |