The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as grafana from "@distilled.cloud/aws/grafana"; |
| 2 | import { diffTags } from "alchemy/Tags"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Redacted from "effect/Redacted"; |
| 5 | |
| 6 | /** Unwrap a possibly-redacted string field returned by the Grafana API. */ |
| 7 | export const unredact = ( |
| 8 | value: string | Redacted.Redacted<string> | undefined, |
| 9 | ): string | undefined => |
| 10 | value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value); |
| 11 | |
| 12 | /** |
| 13 | * Coerce a Grafana wire tag map (values are `string | undefined`) into a |
| 14 | * plain `Record<string, string>`. |
| 15 | */ |
| 16 | export const toTagRecord = ( |
| 17 | tags: { [key: string]: string | undefined } | undefined, |
| 18 | ): Record<string, string> => |
| 19 | Object.fromEntries( |
| 20 | Object.entries(tags ?? {}).filter( |
| 21 | (entry): entry is [string, string] => typeof entry[1] === "string", |
| 22 | ), |
| 23 | ); |
| 24 | |
| 25 | /** Read the observed tags of a Grafana resource by ARN (best-effort). */ |
| 26 | export const readGrafanaTags = Effect.fn(function* (arn: string) { |
| 27 | const response = yield* grafana |
| 28 | .listTagsForResource({ resourceArn: arn }) |
| 29 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 30 | return toTagRecord(response?.tags); |
| 31 | }); |
| 32 | |
| 33 | /** |
| 34 | * Sync tags on a Grafana resource: diff OBSERVED cloud tags against the |
| 35 | * desired set and apply only the delta. Grafana's `tagResource` takes a tag |
| 36 | * map, so the `upsert` delta is folded back into a record. |
| 37 | */ |
| 38 | export const syncGrafanaTags = Effect.fn(function* ( |
| 39 | arn: string, |
| 40 | desiredTags: Record<string, string>, |
| 41 | ) { |
| 42 | const observedTags = yield* readGrafanaTags(arn); |
| 43 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 44 | if (upsert.length > 0) { |
| 45 | yield* grafana.tagResource({ |
| 46 | resourceArn: arn, |
| 47 | tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 48 | }); |
| 49 | } |
| 50 | if (removed.length > 0) { |
| 51 | yield* grafana.untagResource({ resourceArn: arn, tagKeys: removed }); |
| 52 | } |
| 53 | }); |