The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ag from "@distilled.cloud/aws/api-gateway"; |
| 2 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { AWSEnvironment } from "../Environment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { syncTags, usagePlanArn } from "./common.ts"; |
| 12 | |
| 13 | export interface UsagePlanProps { |
| 14 | /** |
| 15 | * Friendly name for the usage plan. |
| 16 | * |
| 17 | * If omitted, Alchemy generates a deterministic physical name. |
| 18 | */ |
| 19 | name?: string; |
| 20 | /** |
| 21 | * Human-readable description for operators. |
| 22 | */ |
| 23 | description?: string; |
| 24 | /** |
| 25 | * API stages associated with this plan. |
| 26 | */ |
| 27 | apiStages?: ag.ApiStage[]; |
| 28 | /** |
| 29 | * Default request throttle applied by the plan. |
| 30 | */ |
| 31 | throttle?: ag.ThrottleSettings; |
| 32 | /** |
| 33 | * Quota limit and period applied by the plan. |
| 34 | */ |
| 35 | quota?: ag.QuotaSettings; |
| 36 | /** |
| 37 | * User-defined tags. Alchemy internal tags are merged automatically. |
| 38 | */ |
| 39 | tags?: Record<string, string>; |
| 40 | } |
| 41 | |
| 42 | /** @resource */ |
| 43 | export interface UsagePlan extends Resource< |
| 44 | "AWS.ApiGateway.UsagePlan", |
| 45 | UsagePlanProps, |
| 46 | { |
| 47 | id: string; |
| 48 | name: string | undefined; |
| 49 | description: string | undefined; |
| 50 | apiStages: ag.ApiStage[] | undefined; |
| 51 | throttle: ag.ThrottleSettings | undefined; |
| 52 | quota: ag.QuotaSettings | undefined; |
| 53 | tags: Record<string, string>; |
| 54 | }, |
| 55 | never, |
| 56 | Providers |
| 57 | > {} |
| 58 | |
| 59 | /** |
| 60 | * Usage plan for API stages, throttling, and quotas. |
| 61 | * |
| 62 | * ### Usage plans |
| 63 | * **Example:** Usage plan with stage |
| 64 | * ```typescript |
| 65 | * const plan = yield* ApiGateway.UsagePlan("Standard", { |
| 66 | * apiStages: [{ apiId: api.restApiId, stage: stage.stageName }], |
| 67 | * }); |
| 68 | * ``` |
| 69 | * |
| 70 | * **Example:** Throttled plan with a quota and an enrolled API key |
| 71 | * ```typescript |
| 72 | * const plan = yield* ApiGateway.UsagePlan("Partner", { |
| 73 | * throttle: { rateLimit: 10, burstLimit: 20 }, |
| 74 | * quota: { limit: 10_000, period: "MONTH" }, |
| 75 | * }); |
| 76 | * |
| 77 | * const key = yield* ApiGateway.ApiKey("PartnerKey", { |
| 78 | * generateDistinctId: true, |
| 79 | * }); |
| 80 | * |
| 81 | * yield* ApiGateway.UsagePlanKey("PartnerLink", { |
| 82 | * usagePlanId: plan.id, |
| 83 | * keyId: key.id, |
| 84 | * }); |
| 85 | * ``` |
| 86 | */ |
| 87 | const UsagePlanResource = Resource<UsagePlan>("AWS.ApiGateway.UsagePlan"); |
| 88 | |
| 89 | export { UsagePlanResource as UsagePlan }; |
| 90 | |
| 91 | const generatedName = (id: string, props: UsagePlanProps) => |
| 92 | props.name |
| 93 | ? Effect.succeed(props.name) |
| 94 | : createPhysicalName({ |
| 95 | id, |
| 96 | maxLength: 128, |
| 97 | }); |
| 98 | |
| 99 | const encodeJsonPointerSegment = (s: string) => s.replace(/~/g, "~0").replace(/\//g, "~1"); |
| 100 | |
| 101 | const apiStageKey = (stage: ag.ApiStage) => `${stage.apiId}:${stage.stage}`; |
| 102 | |
| 103 | const parseThrottleKey = (key: string) => { |
| 104 | const idx = key.lastIndexOf("/"); |
| 105 | if (idx <= 0) return { resourcePath: key, httpMethod: "*" }; |
| 106 | return { |
| 107 | resourcePath: key.slice(0, idx), |
| 108 | httpMethod: key.slice(idx + 1), |
| 109 | }; |
| 110 | }; |
| 111 | |
| 112 | const buildApiStageThrottlePatches = ( |
| 113 | stageKey: string, |
| 114 | prev: { [key: string]: ag.ThrottleSettings | undefined } | undefined, |
| 115 | next: { [key: string]: ag.ThrottleSettings | undefined } | undefined, |
| 116 | ): ag.PatchOperation[] => { |
| 117 | const keys = new Set([...Object.keys(prev ?? {}), ...Object.keys(next ?? {})]); |
| 118 | const patches: ag.PatchOperation[] = []; |
| 119 | for (const key of keys) { |
| 120 | const old = prev?.[key]; |
| 121 | const current = next?.[key]; |
| 122 | const { resourcePath, httpMethod } = parseThrottleKey(key); |
| 123 | const base = `/apiStages/${encodeJsonPointerSegment(stageKey)}/throttle/${encodeJsonPointerSegment(resourcePath)}/${encodeJsonPointerSegment(httpMethod)}`; |
| 124 | if (current?.burstLimit !== old?.burstLimit) { |
| 125 | patches.push( |
| 126 | current?.burstLimit === undefined |
| 127 | ? { op: "remove", path: `${base}/burstLimit` } |
| 128 | : { |
| 129 | op: "replace", |
| 130 | path: `${base}/burstLimit`, |
| 131 | value: String(current.burstLimit), |
| 132 | }, |
| 133 | ); |
| 134 | } |
| 135 | if (current?.rateLimit !== old?.rateLimit) { |
| 136 | patches.push( |
| 137 | current?.rateLimit === undefined |
| 138 | ? { op: "remove", path: `${base}/rateLimit` } |
| 139 | : { |
| 140 | op: "replace", |
| 141 | path: `${base}/rateLimit`, |
| 142 | value: String(current.rateLimit), |
| 143 | }, |
| 144 | ); |
| 145 | } |
| 146 | } |
| 147 | return patches; |
| 148 | }; |
| 149 | |
| 150 | const buildApiStagePatches = ( |
| 151 | prev: ag.ApiStage[] | undefined, |
| 152 | next: ag.ApiStage[] | undefined, |
| 153 | ): ag.PatchOperation[] => { |
| 154 | const prevMap = new Map((prev ?? []).map((s) => [apiStageKey(s), s])); |
| 155 | const nextMap = new Map((next ?? []).map((s) => [apiStageKey(s), s])); |
| 156 | const patches: ag.PatchOperation[] = []; |
| 157 | for (const [key] of prevMap) { |
| 158 | if (!nextMap.has(key)) { |
| 159 | patches.push({ op: "remove", path: "/apiStages", value: key }); |
| 160 | } |
| 161 | } |
| 162 | for (const [key, stage] of nextMap) { |
| 163 | const old = prevMap.get(key); |
| 164 | if (!old) { |
| 165 | patches.push({ op: "add", path: "/apiStages", value: key }); |
| 166 | patches.push(...buildApiStageThrottlePatches(key, undefined, stage.throttle)); |
| 167 | continue; |
| 168 | } |
| 169 | if (!deepEqual(stage.throttle, old.throttle)) { |
| 170 | patches.push(...buildApiStageThrottlePatches(key, old.throttle, stage.throttle)); |
| 171 | } |
| 172 | } |
| 173 | return patches; |
| 174 | }; |
| 175 | |
| 176 | const buildThrottlePatches = ( |
| 177 | prev: ag.ThrottleSettings | undefined, |
| 178 | next: ag.ThrottleSettings | undefined, |
| 179 | ) => { |
| 180 | const patches: ag.PatchOperation[] = []; |
| 181 | if (next?.burstLimit !== prev?.burstLimit) { |
| 182 | patches.push( |
| 183 | next?.burstLimit === undefined |
| 184 | ? { op: "remove", path: "/throttle/burstLimit" } |
| 185 | : { |
| 186 | op: "replace", |
| 187 | path: "/throttle/burstLimit", |
| 188 | value: String(next.burstLimit), |
| 189 | }, |
| 190 | ); |
| 191 | } |
| 192 | if (next?.rateLimit !== prev?.rateLimit) { |
| 193 | patches.push( |
| 194 | next?.rateLimit === undefined |
| 195 | ? { op: "remove", path: "/throttle/rateLimit" } |
| 196 | : { |
| 197 | op: "replace", |
| 198 | path: "/throttle/rateLimit", |
| 199 | value: String(next.rateLimit), |
| 200 | }, |
| 201 | ); |
| 202 | } |
| 203 | return patches; |
| 204 | }; |
| 205 | |
| 206 | const buildQuotaPatches = ( |
| 207 | prev: ag.QuotaSettings | undefined, |
| 208 | next: ag.QuotaSettings | undefined, |
| 209 | ) => { |
| 210 | const patches: ag.PatchOperation[] = []; |
| 211 | if (next?.limit !== prev?.limit) { |
| 212 | patches.push( |
| 213 | next?.limit === undefined |
| 214 | ? { op: "remove", path: "/quota/limit" } |
| 215 | : { |
| 216 | op: "replace", |
| 217 | path: "/quota/limit", |
| 218 | value: String(next.limit), |
| 219 | }, |
| 220 | ); |
| 221 | } |
| 222 | if (next?.offset !== prev?.offset) { |
| 223 | patches.push( |
| 224 | next?.offset === undefined |
| 225 | ? { op: "remove", path: "/quota/offset" } |
| 226 | : { |
| 227 | op: "replace", |
| 228 | path: "/quota/offset", |
| 229 | value: String(next.offset), |
| 230 | }, |
| 231 | ); |
| 232 | } |
| 233 | if (next?.period !== prev?.period) { |
| 234 | patches.push( |
| 235 | next?.period === undefined |
| 236 | ? { op: "remove", path: "/quota/period" } |
| 237 | : { op: "replace", path: "/quota/period", value: next.period }, |
| 238 | ); |
| 239 | } |
| 240 | return patches; |
| 241 | }; |
| 242 | |
| 243 | export const UsagePlanProvider = () => |
| 244 | Provider.effect( |
| 245 | UsagePlanResource, |
| 246 | Effect.gen(function* () { |
| 247 | return { |
| 248 | stables: ["id"] as const, |
| 249 | diff: Effect.fn(function* ({ news: newsIn, olds }) { |
| 250 | if (!isResolved(newsIn)) return; |
| 251 | const news = newsIn as UsagePlanProps; |
| 252 | if (news.name !== undefined && news.name !== olds.name) { |
| 253 | return { action: "replace" } as const; |
| 254 | } |
| 255 | }), |
| 256 | read: Effect.fn(function* ({ output }) { |
| 257 | if (!output?.id) return undefined; |
| 258 | const p = yield* ag |
| 259 | .getUsagePlan({ usagePlanId: output.id }) |
| 260 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)); |
| 261 | if (!p?.id) return undefined; |
| 262 | return { |
| 263 | id: p.id, |
| 264 | name: p.name, |
| 265 | description: p.description, |
| 266 | apiStages: p.apiStages, |
| 267 | throttle: p.throttle, |
| 268 | quota: p.quota, |
| 269 | tags: tagRecord(p.tags), |
| 270 | }; |
| 271 | }), |
| 272 | list: () => |
| 273 | ag.getUsagePlans.pages({}).pipe( |
| 274 | Stream.runCollect, |
| 275 | Effect.map((chunk) => |
| 276 | Array.from(chunk).flatMap((page) => |
| 277 | (page.items ?? []) |
| 278 | .filter((p): p is ag.UsagePlan & { id: string } => p.id != null) |
| 279 | .map((p) => ({ |
| 280 | id: p.id, |
| 281 | name: p.name, |
| 282 | description: p.description, |
| 283 | apiStages: p.apiStages, |
| 284 | throttle: p.throttle, |
| 285 | quota: p.quota, |
| 286 | tags: tagRecord(p.tags), |
| 287 | })), |
| 288 | ), |
| 289 | ), |
| 290 | ), |
| 291 | reconcile: Effect.fn(function* ({ id, news: newsIn, output, session }) { |
| 292 | const { region } = yield* AWSEnvironment.current; |
| 293 | if (!isResolved(newsIn)) { |
| 294 | return yield* Effect.die("UsagePlan props were not resolved"); |
| 295 | } |
| 296 | const news = newsIn as UsagePlanProps; |
| 297 | const name = yield* generatedName(id, news); |
| 298 | const internalTags = yield* createInternalTags(id); |
| 299 | const desiredTags = { ...news.tags, ...internalTags }; |
| 300 | |
| 301 | // Observe — fetch live usage plan if we have a cached id. We |
| 302 | // never trust `output.apiStages`/`output.throttle`/etc. for |
| 303 | // diffing; we re-read every reconcile so adoption converges. |
| 304 | let observed = output?.id |
| 305 | ? yield* ag |
| 306 | .getUsagePlan({ usagePlanId: output.id }) |
| 307 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)) |
| 308 | : undefined; |
| 309 | |
| 310 | // Ensure — create the usage plan if missing. |
| 311 | if (!observed?.id) { |
| 312 | const created = yield* ag.createUsagePlan({ |
| 313 | name, |
| 314 | description: news.description, |
| 315 | apiStages: news.apiStages, |
| 316 | throttle: news.throttle, |
| 317 | quota: news.quota, |
| 318 | tags: desiredTags, |
| 319 | }); |
| 320 | if (!created.id) return yield* Effect.die("createUsagePlan missing id"); |
| 321 | yield* session.note(`Created usage plan ${created.id}`); |
| 322 | observed = yield* ag.getUsagePlan({ usagePlanId: created.id }); |
| 323 | } |
| 324 | |
| 325 | const planId = observed.id!; |
| 326 | |
| 327 | // Sync mutable plan fields — diff observed cloud state against |
| 328 | // desired and emit only the delta as PATCH operations. |
| 329 | const patches: ag.PatchOperation[] = []; |
| 330 | if (news.description !== observed.description) { |
| 331 | patches.push({ |
| 332 | op: "replace", |
| 333 | path: "/description", |
| 334 | value: news.description ?? "", |
| 335 | }); |
| 336 | } |
| 337 | patches.push(...buildApiStagePatches(observed.apiStages, news.apiStages)); |
| 338 | patches.push(...buildThrottlePatches(observed.throttle, news.throttle)); |
| 339 | patches.push(...buildQuotaPatches(observed.quota, news.quota)); |
| 340 | if (patches.length > 0) { |
| 341 | yield* ag.updateUsagePlan({ |
| 342 | usagePlanId: planId, |
| 343 | patchOperations: patches, |
| 344 | }); |
| 345 | } |
| 346 | |
| 347 | // Sync tags — observed ↔ desired. |
| 348 | const observedTags = tagRecord(observed.tags); |
| 349 | if (!deepEqual(observedTags, desiredTags)) { |
| 350 | yield* syncTags({ |
| 351 | resourceArn: usagePlanArn(region, planId), |
| 352 | oldTags: observedTags, |
| 353 | newTags: desiredTags, |
| 354 | }); |
| 355 | } |
| 356 | |
| 357 | yield* session.note(`Reconciled usage plan ${planId}`); |
| 358 | const final = yield* ag.getUsagePlan({ usagePlanId: planId }); |
| 359 | return { |
| 360 | id: planId, |
| 361 | name: final.name, |
| 362 | description: final.description, |
| 363 | apiStages: final.apiStages, |
| 364 | throttle: final.throttle, |
| 365 | quota: final.quota, |
| 366 | tags: tagRecord(final.tags), |
| 367 | }; |
| 368 | }), |
| 369 | delete: Effect.fn(function* ({ output, session }) { |
| 370 | yield* ag |
| 371 | .deleteUsagePlan({ usagePlanId: output.id }) |
| 372 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)); |
| 373 | yield* session.note(`Deleted usage plan ${output.id}`); |
| 374 | }), |
| 375 | }; |
| 376 | }), |
| 377 | ); |