The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as iot from "@distilled.cloud/aws/iot"; |
| 2 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | |
| 5 | /** |
| 6 | * IoT rule names accept only `[a-zA-Z0-9_]`. Coerce any other character |
| 7 | * (hyphens from generated physical names, colons, etc.) to an underscore so |
| 8 | * a name derived from the stack/id/stage is always valid. |
| 9 | */ |
| 10 | export const sanitizeRuleName = (name: string): string => name.replace(/[^a-zA-Z0-9_]/g, "_"); |
| 11 | |
| 12 | /** |
| 13 | * Reads the observed tag map for an IoT resource ARN. A missing resource |
| 14 | * yields `{}` so callers treat it as "no tags observed". |
| 15 | */ |
| 16 | export const readIotTags = Effect.fn(function* (resourceArn: string) { |
| 17 | const { tags } = yield* iot |
| 18 | .listTagsForResource({ resourceArn }) |
| 19 | .pipe( |
| 20 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({ tags: [] as iot.Tag[] })), |
| 21 | ); |
| 22 | const record: Record<string, string> = {}; |
| 23 | for (const tag of tags ?? []) { |
| 24 | if (tag.Value !== undefined) record[tag.Key] = tag.Value; |
| 25 | } |
| 26 | return record; |
| 27 | }); |
| 28 | |
| 29 | /** |
| 30 | * Reconciles the tags on an IoT resource to `{ ...user, ...internal }`, |
| 31 | * diffing against the OBSERVED cloud tags (so adoption converges). Applies |
| 32 | * only the delta: `tagResource` for upserts, `untagResource` for removals. |
| 33 | */ |
| 34 | export const syncIotTags = Effect.fn(function* ( |
| 35 | resourceArn: string, |
| 36 | id: string, |
| 37 | userTags: Record<string, string> | undefined, |
| 38 | ) { |
| 39 | const internalTags = yield* createInternalTags(id); |
| 40 | const desired = { ...userTags, ...internalTags }; |
| 41 | const observed = yield* readIotTags(resourceArn); |
| 42 | const { upsert, removed } = diffTags(observed, desired); |
| 43 | if (upsert.length > 0) { |
| 44 | yield* iot.tagResource({ |
| 45 | resourceArn, |
| 46 | tags: upsert.map((t) => ({ Key: t.Key, Value: t.Value })), |
| 47 | }); |
| 48 | } |
| 49 | if (removed.length > 0) { |
| 50 | yield* iot.untagResource({ resourceArn, tagKeys: removed }); |
| 51 | } |
| 52 | }); |