The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as oam from "@distilled.cloud/aws/oam"; |
| 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 { hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { deleteSinkAndWait, readOamTags, retryOamMutation, syncOamTags } from "./internal.ts"; |
| 12 | |
| 13 | export interface SinkProps { |
| 14 | /** |
| 15 | * Name of the sink. If omitted, a unique name is generated from the app, |
| 16 | * stage and logical ID. Changing the name replaces the sink. |
| 17 | */ |
| 18 | sinkName?: string; |
| 19 | |
| 20 | /** |
| 21 | * The IAM resource policy that grants source accounts permission to link |
| 22 | * to this sink (`oam:CreateLink` / `oam:UpdateLink`). Provided as a JSON |
| 23 | * string or a plain policy document object. |
| 24 | * |
| 25 | * OAM has no delete-sink-policy API, so removing this prop leaves the |
| 26 | * last applied policy in place. |
| 27 | */ |
| 28 | policy?: string | Record<string, any>; |
| 29 | |
| 30 | /** |
| 31 | * User tags to attach to the sink. Merged with internal Alchemy tags. |
| 32 | */ |
| 33 | tags?: Record<string, string>; |
| 34 | } |
| 35 | |
| 36 | export interface Sink extends Resource< |
| 37 | "AWS.OAM.Sink", |
| 38 | SinkProps, |
| 39 | { |
| 40 | /** The name of the sink. */ |
| 41 | sinkName: string; |
| 42 | /** The ARN of the sink (used as the `sinkIdentifier` of a `Link`). */ |
| 43 | sinkArn: string; |
| 44 | /** The random ID string that AWS generated as part of the sink ARN. */ |
| 45 | sinkId: string; |
| 46 | }, |
| 47 | never, |
| 48 | Providers |
| 49 | > {} |
| 50 | |
| 51 | /** |
| 52 | * A CloudWatch cross-account observability **sink** — the attachment point |
| 53 | * in a monitoring account that source accounts link to in order to share |
| 54 | * metrics, logs, traces, and Application Signals data. |
| 55 | * |
| 56 | * Each account can contain **one sink per region**. After creating a sink, |
| 57 | * attach a sink policy (the `policy` prop) that authorizes source accounts |
| 58 | * (or an entire organization) to create links to it. |
| 59 | * |
| 60 | * ### Creating a Sink |
| 61 | * **Example:** Basic Sink |
| 62 | * ```typescript |
| 63 | * import * as OAM from "@alchemy.run/aws/OAM"; |
| 64 | * |
| 65 | * const sink = yield* OAM.Sink("MonitoringSink"); |
| 66 | * ``` |
| 67 | * |
| 68 | * **Example:** Sink with a policy authorizing source accounts |
| 69 | * ```typescript |
| 70 | * const sink = yield* OAM.Sink("MonitoringSink", { |
| 71 | * policy: { |
| 72 | * Version: "2012-10-17", |
| 73 | * Statement: [ |
| 74 | * { |
| 75 | * Effect: "Allow", |
| 76 | * Principal: { AWS: ["111122223333"] }, |
| 77 | * Action: ["oam:CreateLink", "oam:UpdateLink"], |
| 78 | * Resource: "*", |
| 79 | * Condition: { |
| 80 | * "ForAllValues:StringEquals": { |
| 81 | * "oam:ResourceTypes": [ |
| 82 | * "AWS::CloudWatch::Metric", |
| 83 | * "AWS::Logs::LogGroup", |
| 84 | * ], |
| 85 | * }, |
| 86 | * }, |
| 87 | * }, |
| 88 | * ], |
| 89 | * }, |
| 90 | * }); |
| 91 | * ``` |
| 92 | * |
| 93 | * **Example:** Authorize an entire organization |
| 94 | * ```typescript |
| 95 | * const sink = yield* OAM.Sink("OrgSink", { |
| 96 | * policy: { |
| 97 | * Version: "2012-10-17", |
| 98 | * Statement: [ |
| 99 | * { |
| 100 | * Effect: "Allow", |
| 101 | * Principal: "*", |
| 102 | * Action: ["oam:CreateLink", "oam:UpdateLink"], |
| 103 | * Resource: "*", |
| 104 | * Condition: { |
| 105 | * "ForAnyValue:StringEquals": { "aws:PrincipalOrgID": "o-xxxxxxxxxx" }, |
| 106 | * }, |
| 107 | * }, |
| 108 | * ], |
| 109 | * }, |
| 110 | * }); |
| 111 | * ``` |
| 112 | * |
| 113 | * @resource |
| 114 | */ |
| 115 | export const Sink = Resource<Sink>("AWS.OAM.Sink"); |
| 116 | |
| 117 | /** Normalize a `policy` prop to a JSON string for `putSinkPolicy`. */ |
| 118 | const toPolicyString = (policy: string | Record<string, any>): string => |
| 119 | typeof policy === "string" ? policy : JSON.stringify(policy); |
| 120 | |
| 121 | /** |
| 122 | * Semantic policy equality — AWS normalizes documents (e.g. account-ID |
| 123 | * principals become `arn:aws:iam::…:root`), so a raw string compare would |
| 124 | * re-put an unchanged policy forever. We compare parsed JSON; a normalized |
| 125 | * difference still re-puts, which is idempotent and harmless. |
| 126 | */ |
| 127 | const samePolicy = (a: string | undefined, b: string | undefined): boolean => { |
| 128 | if (a === undefined || b === undefined) return a === b; |
| 129 | try { |
| 130 | return JSON.stringify(JSON.parse(a)) === JSON.stringify(JSON.parse(b)); |
| 131 | } catch { |
| 132 | return a === b; |
| 133 | } |
| 134 | }; |
| 135 | |
| 136 | export const SinkProvider = () => |
| 137 | Provider.effect( |
| 138 | Sink, |
| 139 | Effect.gen(function* () { |
| 140 | // `props` may be undefined at runtime — all SinkProps fields are |
| 141 | // optional, so callers can omit the props object entirely. |
| 142 | const createName = Effect.fn(function* (id: string, props: SinkProps | undefined) { |
| 143 | return props?.sinkName ?? (yield* createPhysicalName({ id })); |
| 144 | }); |
| 145 | |
| 146 | // Find a sink by name via the (small — quota is 1/region) list API. |
| 147 | const findByName = Effect.fn(function* (sinkName: string) { |
| 148 | const pages = yield* oam.listSinks.pages({}).pipe(Stream.runCollect); |
| 149 | return Array.from(pages) |
| 150 | .flatMap((page) => page.Items) |
| 151 | .find((item) => item.Name === sinkName); |
| 152 | }); |
| 153 | |
| 154 | return Sink.Provider.of({ |
| 155 | stables: ["sinkName", "sinkArn", "sinkId"], |
| 156 | list: () => |
| 157 | oam.listSinks.pages({}).pipe( |
| 158 | Stream.runCollect, |
| 159 | Effect.map((chunk) => |
| 160 | Array.from(chunk).flatMap((page) => |
| 161 | page.Items.filter( |
| 162 | (item) => item.Name != null && item.Arn != null && item.Id != null, |
| 163 | ).map((item) => ({ |
| 164 | sinkName: item.Name!, |
| 165 | sinkArn: item.Arn!, |
| 166 | sinkId: item.Id!, |
| 167 | })), |
| 168 | ), |
| 169 | ), |
| 170 | ), |
| 171 | read: Effect.fn(function* ({ id, olds, output }) { |
| 172 | const sinkName = output?.sinkName ?? (yield* createName(id, olds ?? {})); |
| 173 | const found = output?.sinkArn |
| 174 | ? yield* oam |
| 175 | .getSink({ Identifier: output.sinkArn }) |
| 176 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)) |
| 177 | : yield* findByName(sinkName); |
| 178 | if (!found?.Arn) return undefined; |
| 179 | const attrs = { |
| 180 | sinkName: found.Name ?? sinkName, |
| 181 | sinkArn: found.Arn, |
| 182 | sinkId: found.Id!, |
| 183 | }; |
| 184 | const tags = yield* readOamTags(found.Arn); |
| 185 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 186 | }), |
| 187 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 188 | if (!isResolved(news)) return undefined; |
| 189 | const oldName = yield* createName(id, olds); |
| 190 | const newName = yield* createName(id, news); |
| 191 | if (oldName !== newName) return { action: "replace" } as const; |
| 192 | return undefined; |
| 193 | }), |
| 194 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 195 | const sinkName = output?.sinkName ?? (yield* createName(id, news)); |
| 196 | |
| 197 | // OBSERVE — cloud state is authoritative; `output` is only an |
| 198 | // identifier cache. A cached ARN that no longer resolves falls |
| 199 | // through to "missing". |
| 200 | let live = output?.sinkArn |
| 201 | ? yield* oam |
| 202 | .getSink({ Identifier: output.sinkArn }) |
| 203 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)) |
| 204 | : yield* findByName(sinkName); |
| 205 | |
| 206 | // ENSURE — create when missing; a ConflictException means a peer |
| 207 | // created the same-named sink concurrently, so re-observe. |
| 208 | if (live?.Arn == null) { |
| 209 | live = yield* retryOamMutation( |
| 210 | oam.createSink({ Name: sinkName, Tags: news?.tags }), |
| 211 | ).pipe(Effect.catchTag("ConflictException", () => findByName(sinkName))); |
| 212 | } |
| 213 | const sinkArn = live!.Arn!; |
| 214 | const sinkId = live!.Id!; |
| 215 | |
| 216 | // SYNC policy — diff the OBSERVED sink policy against the desired |
| 217 | // document and put only on change. There is no delete-policy API, |
| 218 | // so an absent `policy` prop leaves the current policy untouched. |
| 219 | const desiredPolicy = news?.policy; |
| 220 | if (desiredPolicy !== undefined) { |
| 221 | const desired = toPolicyString(desiredPolicy); |
| 222 | const observed = yield* oam.getSinkPolicy({ SinkIdentifier: sinkArn }).pipe( |
| 223 | Effect.map((r) => r.Policy), |
| 224 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 225 | ); |
| 226 | if (!samePolicy(observed, desired)) { |
| 227 | yield* retryOamMutation( |
| 228 | oam.putSinkPolicy({ |
| 229 | SinkIdentifier: sinkArn, |
| 230 | Policy: desired, |
| 231 | }), |
| 232 | ); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // SYNC tags — against observed cloud tags (adoption-safe). |
| 237 | yield* syncOamTags(sinkArn, id, news?.tags); |
| 238 | |
| 239 | yield* session.note(sinkArn); |
| 240 | return { sinkName, sinkArn, sinkId }; |
| 241 | }), |
| 242 | delete: Effect.fn(function* ({ output }) { |
| 243 | yield* deleteSinkAndWait(output.sinkArn); |
| 244 | }), |
| 245 | }); |
| 246 | }), |
| 247 | ); |