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 { 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 { createInternalTags, hasAlchemyTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { AWSEnvironment } from "../Environment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { syncGrafanaTags, toTagRecord, unredact } from "./internal.ts"; |
| 14 | |
| 15 | export class GrafanaWorkspaceNotReady extends Data.TaggedError("GrafanaWorkspaceNotReady")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export interface WorkspaceProps { |
| 21 | /** |
| 22 | * A name for the workspace. If omitted, a deterministic physical name is |
| 23 | * generated. |
| 24 | */ |
| 25 | name?: string; |
| 26 | /** |
| 27 | * A description for the workspace. |
| 28 | */ |
| 29 | description?: string; |
| 30 | /** |
| 31 | * Whether the workspace can access AWS resources in only the current |
| 32 | * account (`CURRENT_ACCOUNT`) or throughout an organization |
| 33 | * (`ORGANIZATION`). Changing this replaces the workspace. |
| 34 | * @default "CURRENT_ACCOUNT" |
| 35 | */ |
| 36 | accountAccessType?: "CURRENT_ACCOUNT" | "ORGANIZATION"; |
| 37 | /** |
| 38 | * The user authentication providers for the workspace. `AWS_SSO` requires |
| 39 | * IAM Identity Center to be enabled in the account; `SAML` configures an |
| 40 | * external IdP after creation. Changing this replaces the workspace. |
| 41 | */ |
| 42 | authenticationProviders: Array<"AWS_SSO" | "SAML">; |
| 43 | /** |
| 44 | * Whether AWS manages the workspace's IAM role and permissions |
| 45 | * (`SERVICE_MANAGED`) or you supply `workspaceRoleArn` |
| 46 | * (`CUSTOMER_MANAGED`). Changing this replaces the workspace. |
| 47 | * @default "SERVICE_MANAGED" |
| 48 | */ |
| 49 | permissionType?: "SERVICE_MANAGED" | "CUSTOMER_MANAGED"; |
| 50 | /** |
| 51 | * ARN of an IAM role the workspace uses to access AWS data sources and |
| 52 | * notification channels. Required when `permissionType` is |
| 53 | * `CUSTOMER_MANAGED`. |
| 54 | */ |
| 55 | workspaceRoleArn?: string; |
| 56 | /** |
| 57 | * AWS services the workspace can query as data sources (e.g. |
| 58 | * `PROMETHEUS`, `CLOUDWATCH`, `XRAY`). |
| 59 | */ |
| 60 | dataSources?: string[]; |
| 61 | /** |
| 62 | * The Grafana version for the workspace (e.g. `"10.4"`). If omitted, AWS |
| 63 | * chooses the current default. |
| 64 | */ |
| 65 | grafanaVersion?: string; |
| 66 | /** |
| 67 | * User-defined tags for the workspace. |
| 68 | */ |
| 69 | tags?: Record<string, string>; |
| 70 | } |
| 71 | |
| 72 | export interface Workspace extends Resource< |
| 73 | "AWS.Grafana.Workspace", |
| 74 | WorkspaceProps, |
| 75 | { |
| 76 | /** The unique ID of the workspace. */ |
| 77 | workspaceId: string; |
| 78 | /** The ARN of the workspace. */ |
| 79 | workspaceArn: string; |
| 80 | /** The URL of the workspace's Grafana console. */ |
| 81 | endpoint: string; |
| 82 | /** The Grafana version the workspace runs. */ |
| 83 | grafanaVersion: string; |
| 84 | /** The current status of the workspace (`ACTIVE`, `CREATING`, ...). */ |
| 85 | status: string; |
| 86 | }, |
| 87 | never, |
| 88 | Providers |
| 89 | > {} |
| 90 | |
| 91 | /** |
| 92 | * An Amazon Managed Grafana workspace — a fully-managed Grafana server for |
| 93 | * visualizing operational metrics, logs, and traces. |
| 94 | * |
| 95 | * Grafana workspaces require IAM Identity Center (AWS SSO) to be enabled in |
| 96 | * the account when `authenticationProviders` includes `AWS_SSO`. Workspace |
| 97 | * provisioning is asynchronous and can take a few minutes. |
| 98 | * |
| 99 | * ### Creating a Workspace |
| 100 | * **Example:** SSO-Authenticated Workspace |
| 101 | * ```typescript |
| 102 | * const workspace = yield* Grafana.Workspace("Dashboards", { |
| 103 | * accountAccessType: "CURRENT_ACCOUNT", |
| 104 | * authenticationProviders: ["AWS_SSO"], |
| 105 | * permissionType: "SERVICE_MANAGED", |
| 106 | * dataSources: ["PROMETHEUS", "CLOUDWATCH"], |
| 107 | * }); |
| 108 | * ``` |
| 109 | * |
| 110 | * @resource |
| 111 | */ |
| 112 | export const Workspace = Resource<Workspace>("AWS.Grafana.Workspace"); |
| 113 | |
| 114 | export const WorkspaceProvider = () => |
| 115 | Provider.effect( |
| 116 | Workspace, |
| 117 | Effect.gen(function* () { |
| 118 | const arnFor = (accountId: string, region: string, id: string) => |
| 119 | `arn:aws:grafana:${region}:${accountId}:/workspaces/${id}`; |
| 120 | |
| 121 | const toAttrs = (accountId: string, region: string, ws: grafana.WorkspaceDescription) => ({ |
| 122 | workspaceId: ws.id, |
| 123 | workspaceArn: arnFor(accountId, region, ws.id), |
| 124 | endpoint: ws.endpoint, |
| 125 | grafanaVersion: ws.grafanaVersion, |
| 126 | status: ws.status, |
| 127 | }); |
| 128 | |
| 129 | /** Describe a workspace by id; typed not-found → undefined. */ |
| 130 | const describe = Effect.fn(function* (id: string) { |
| 131 | const response = yield* grafana |
| 132 | .describeWorkspace({ workspaceId: id }) |
| 133 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 134 | return response?.workspace; |
| 135 | }); |
| 136 | |
| 137 | /** Poll until the workspace reaches ACTIVE; fail fast on *FAILED*. */ |
| 138 | const waitActive = Effect.fn(function* (id: string) { |
| 139 | const ws = yield* grafana.describeWorkspace({ workspaceId: id }).pipe( |
| 140 | Effect.map((r) => r.workspace), |
| 141 | Effect.repeat({ |
| 142 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(36)]), |
| 143 | until: (w) => w.status === "ACTIVE" || w.status.endsWith("FAILED"), |
| 144 | }), |
| 145 | ); |
| 146 | if (ws.status !== "ACTIVE") { |
| 147 | return yield* new GrafanaWorkspaceNotReady({ |
| 148 | message: `Grafana workspace ${id} did not become ACTIVE (status: ${ws.status})`, |
| 149 | }); |
| 150 | } |
| 151 | return ws; |
| 152 | }); |
| 153 | |
| 154 | return { |
| 155 | stables: ["workspaceId", "workspaceArn", "endpoint"], |
| 156 | |
| 157 | diff: Effect.fn(function* ({ olds, news }) { |
| 158 | if (!isResolved(news)) return undefined; |
| 159 | const authChanged = |
| 160 | JSON.stringify([...(olds?.authenticationProviders ?? [])].sort()) !== |
| 161 | JSON.stringify([...news.authenticationProviders].sort()); |
| 162 | if ( |
| 163 | authChanged || |
| 164 | (olds?.accountAccessType ?? "CURRENT_ACCOUNT") !== |
| 165 | (news.accountAccessType ?? "CURRENT_ACCOUNT") || |
| 166 | (olds?.permissionType ?? "SERVICE_MANAGED") !== |
| 167 | (news.permissionType ?? "SERVICE_MANAGED") |
| 168 | ) { |
| 169 | return { action: "replace" } as const; |
| 170 | } |
| 171 | }), |
| 172 | |
| 173 | read: Effect.fn(function* ({ id, output }) { |
| 174 | if (!output?.workspaceId) return undefined; |
| 175 | const { accountId, region } = yield* AWSEnvironment.current; |
| 176 | const ws = yield* describe(output.workspaceId); |
| 177 | if (ws === undefined) return undefined; |
| 178 | const attrs = toAttrs(accountId, region, ws); |
| 179 | const tags = toTagRecord(ws.tags); |
| 180 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 181 | }), |
| 182 | |
| 183 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 184 | const { accountId, region } = yield* AWSEnvironment.current; |
| 185 | const internalTags = yield* createInternalTags(id); |
| 186 | const desiredTags = { ...internalTags, ...news!.tags }; |
| 187 | |
| 188 | // 1. Observe — cloud state is authoritative; output is an id cache. |
| 189 | let ws = |
| 190 | output?.workspaceId !== undefined ? yield* describe(output.workspaceId) : undefined; |
| 191 | |
| 192 | // 2. Ensure — create if missing, then wait for ACTIVE. |
| 193 | if (ws === undefined) { |
| 194 | const created = yield* grafana.createWorkspace({ |
| 195 | accountAccessType: news!.accountAccessType ?? "CURRENT_ACCOUNT", |
| 196 | permissionType: news!.permissionType ?? "SERVICE_MANAGED", |
| 197 | authenticationProviders: news!.authenticationProviders, |
| 198 | workspaceName: news!.name, |
| 199 | workspaceDescription: news!.description, |
| 200 | workspaceRoleArn: news!.workspaceRoleArn, |
| 201 | workspaceDataSources: news!.dataSources, |
| 202 | grafanaVersion: news!.grafanaVersion, |
| 203 | tags: desiredTags, |
| 204 | }); |
| 205 | ws = yield* waitActive(created.workspace.id); |
| 206 | } else { |
| 207 | // 3. Sync mutable settings via updateWorkspace when drifted. |
| 208 | const drifted = |
| 209 | (news!.name ?? undefined) !== unredact(ws.name) || |
| 210 | (news!.description ?? undefined) !== unredact(ws.description) || |
| 211 | JSON.stringify([...(news!.dataSources ?? [])].sort()) !== |
| 212 | JSON.stringify([...(ws.dataSources ?? [])].sort()); |
| 213 | if (drifted) { |
| 214 | yield* grafana.updateWorkspace({ |
| 215 | workspaceId: ws.id, |
| 216 | workspaceName: news!.name, |
| 217 | workspaceDescription: news!.description, |
| 218 | workspaceDataSources: news!.dataSources, |
| 219 | workspaceRoleArn: news!.workspaceRoleArn, |
| 220 | }); |
| 221 | ws = yield* waitActive(ws.id); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 226 | const arn = arnFor(accountId, region, ws.id); |
| 227 | yield* syncGrafanaTags(arn, desiredTags); |
| 228 | |
| 229 | yield* session.note(ws.id); |
| 230 | return toAttrs(accountId, region, ws); |
| 231 | }), |
| 232 | |
| 233 | delete: Effect.fn(function* ({ output }) { |
| 234 | yield* grafana.deleteWorkspace({ workspaceId: output.workspaceId }).pipe( |
| 235 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 236 | Effect.retry({ |
| 237 | while: (e) => e._tag === "ConflictException", |
| 238 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]), |
| 239 | }), |
| 240 | ); |
| 241 | }), |
| 242 | |
| 243 | list: () => |
| 244 | grafana.listWorkspaces.pages({}).pipe( |
| 245 | Stream.runCollect, |
| 246 | Effect.flatMap((chunk) => |
| 247 | Effect.gen(function* () { |
| 248 | const { accountId, region } = yield* AWSEnvironment.current; |
| 249 | return Array.from(chunk).flatMap((page) => |
| 250 | page.workspaces.map((summary) => ({ |
| 251 | workspaceId: summary.id, |
| 252 | workspaceArn: arnFor(accountId, region, summary.id), |
| 253 | endpoint: summary.endpoint, |
| 254 | grafanaVersion: summary.grafanaVersion, |
| 255 | status: summary.status, |
| 256 | })), |
| 257 | ); |
| 258 | }), |
| 259 | ), |
| 260 | ), |
| 261 | }; |
| 262 | }), |
| 263 | ); |