The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as eventbridge from "@distilled.cloud/aws/eventbridge"; |
| 2 | import { 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 * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import type { AccountID } from "../Environment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import type { RegionID } from "../Region.ts"; |
| 12 | |
| 13 | export type { EndpointState } from "@distilled.cloud/aws/eventbridge"; |
| 14 | |
| 15 | export type EndpointName = string; |
| 16 | export type EndpointArn = `arn:aws:events:${RegionID}:${AccountID}:endpoint/${EndpointName}`; |
| 17 | |
| 18 | export interface EndpointFailoverConfig { |
| 19 | /** |
| 20 | * The Route 53 health check that decides when to fail over: while it is |
| 21 | * unhealthy, events sent to the endpoint go to the secondary region. |
| 22 | * Accepts the health check ID (`healthCheck.healthCheckId`) or its ARN. |
| 23 | */ |
| 24 | healthCheck: string; |
| 25 | /** |
| 26 | * The region events are routed to while the health check is unhealthy. |
| 27 | * It must be the region of the second event bus in `eventBuses`. |
| 28 | */ |
| 29 | secondaryRegion: string; |
| 30 | } |
| 31 | |
| 32 | export interface EndpointProps { |
| 33 | /** |
| 34 | * Name of the endpoint. Must match [\.\-_A-Za-z0-9]+, 1-64 characters. |
| 35 | * If omitted, a unique name will be generated. Changing it replaces the |
| 36 | * endpoint. |
| 37 | */ |
| 38 | name?: EndpointName; |
| 39 | |
| 40 | /** |
| 41 | * Description of the endpoint. Max 512 characters. |
| 42 | */ |
| 43 | description?: string; |
| 44 | |
| 45 | /** |
| 46 | * ARNs of the two event buses the endpoint routes to: the primary bus in |
| 47 | * the stack's region and the secondary bus in `failover.secondaryRegion`. |
| 48 | * Both buses must have the same name. |
| 49 | */ |
| 50 | eventBuses: [primary: string, secondary: string]; |
| 51 | |
| 52 | /** |
| 53 | * When to fail over, and to which region. |
| 54 | */ |
| 55 | failover: EndpointFailoverConfig; |
| 56 | |
| 57 | /** |
| 58 | * Whether events are replicated to the secondary region's bus, so they |
| 59 | * keep being processed there after a failover. |
| 60 | * @default true |
| 61 | */ |
| 62 | replication?: boolean; |
| 63 | |
| 64 | /** |
| 65 | * ARN of the IAM role EventBridge assumes to replicate events. It must |
| 66 | * trust `events.amazonaws.com`, allow `events:PutEvents` on both buses, and |
| 67 | * let EventBridge manage its replication rule on each bus |
| 68 | * (`rule/<bus>/GlobalEndpointManagedRule-*`) and pass the role to that rule's |
| 69 | * target (`iam:PassRole` on the role, for `events.amazonaws.com`). See the |
| 70 | * `Endpoint` examples for a least-privilege policy. |
| 71 | * Required when `replication` is enabled. |
| 72 | */ |
| 73 | roleArn?: string; |
| 74 | } |
| 75 | |
| 76 | /** The endpoint ended in `CREATE_FAILED` or `UPDATE_FAILED`. */ |
| 77 | export class EndpointFailed extends Data.TaggedError("EndpointFailed")<{ |
| 78 | readonly endpointName: string; |
| 79 | readonly state: string; |
| 80 | readonly reason: string | undefined; |
| 81 | }> { |
| 82 | override get message() { |
| 83 | return `Endpoint ${this.endpointName} is ${this.state}: ${this.reason ?? "no reason given"}`; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * An Amazon EventBridge global endpoint: one URL for publishing events that |
| 89 | * EventBridge routes to an event bus in the primary region, or to the |
| 90 | * same-named bus in a secondary region when a Route 53 health check fails. |
| 91 | * |
| 92 | * Create the same-named bus in both regions, a health check that reflects |
| 93 | * the primary region's health, and (for replication) a role EventBridge can |
| 94 | * use to forward events to the secondary bus. Publish through the endpoint by |
| 95 | * passing it to the `PutEvents` binding. |
| 96 | * |
| 97 | * Endpoints do not support tags, so ownership is tracked by the |
| 98 | * deterministic physical name. |
| 99 | * ### Creating a Global Endpoint |
| 100 | * **Example:** Fail Over Between Two Regions |
| 101 | * ```typescript |
| 102 | * const primary = yield* AWS.EventBridge.EventBus("Primary", { name: "orders" }); |
| 103 | * const secondary = yield* AWS.EventBridge.EventBus("Secondary", { |
| 104 | * name: "orders", |
| 105 | * region: "us-east-2", |
| 106 | * }); |
| 107 | * |
| 108 | * // Healthy while the primary region's API answers its health route. |
| 109 | * const health = yield* AWS.Route53.HealthCheck("PrimaryHealth", { |
| 110 | * type: "HTTPS", |
| 111 | * fullyQualifiedDomainName: "api.us-east-1.example.com", |
| 112 | * resourcePath: "/health", |
| 113 | * port: 443, |
| 114 | * }); |
| 115 | * |
| 116 | * const replication = yield* AWS.IAM.Role("ReplicationRole", { |
| 117 | * // `iam:PassRole` below is scoped to roles on this path. |
| 118 | * path: "/eventbridge-replication/", |
| 119 | * assumeRolePolicyDocument: { |
| 120 | * Version: "2012-10-17", |
| 121 | * Statement: [ |
| 122 | * { |
| 123 | * Effect: "Allow", |
| 124 | * Principal: { Service: "events.amazonaws.com" }, |
| 125 | * Action: "sts:AssumeRole", |
| 126 | * }, |
| 127 | * ], |
| 128 | * }, |
| 129 | * inlinePolicies: { |
| 130 | * Replicate: { |
| 131 | * Version: "2012-10-17", |
| 132 | * Statement: [ |
| 133 | * { |
| 134 | * Effect: "Allow", |
| 135 | * Action: "events:PutEvents", |
| 136 | * Resource: [primary.eventBusArn, secondary.eventBusArn], |
| 137 | * }, |
| 138 | * // EventBridge manages a replication rule on each bus. |
| 139 | * { |
| 140 | * Effect: "Allow", |
| 141 | * Action: [ |
| 142 | * "events:PutRule", |
| 143 | * "events:PutTargets", |
| 144 | * "events:DeleteRule", |
| 145 | * "events:RemoveTargets", |
| 146 | * ], |
| 147 | * Resource: [ |
| 148 | * "arn:aws:events:us-east-1:123456789012:rule/orders/GlobalEndpointManagedRule-*", |
| 149 | * "arn:aws:events:us-east-2:123456789012:rule/orders/GlobalEndpointManagedRule-*", |
| 150 | * ], |
| 151 | * }, |
| 152 | * // ...and passes this role to those rules' targets. |
| 153 | * { |
| 154 | * Effect: "Allow", |
| 155 | * Action: "iam:PassRole", |
| 156 | * Resource: "arn:aws:iam::123456789012:role/eventbridge-replication/*", |
| 157 | * Condition: { StringEquals: { "iam:PassedToService": "events.amazonaws.com" } }, |
| 158 | * }, |
| 159 | * ], |
| 160 | * }, |
| 161 | * }, |
| 162 | * }); |
| 163 | * |
| 164 | * const endpoint = yield* AWS.EventBridge.Endpoint("Orders", { |
| 165 | * eventBuses: [primary.eventBusArn, secondary.eventBusArn], |
| 166 | * failover: { |
| 167 | * healthCheck: health.healthCheckId, |
| 168 | * secondaryRegion: "us-east-2", |
| 169 | * }, |
| 170 | * roleArn: replication.roleArn, |
| 171 | * }); |
| 172 | * ``` |
| 173 | * |
| 174 | * **Example:** Fail Over Without Replication |
| 175 | * ```typescript |
| 176 | * const endpoint = yield* AWS.EventBridge.Endpoint("Orders", { |
| 177 | * eventBuses: [primary.eventBusArn, secondary.eventBusArn], |
| 178 | * failover: { |
| 179 | * healthCheck: health.healthCheckId, |
| 180 | * secondaryRegion: "us-east-2", |
| 181 | * }, |
| 182 | * replication: false, |
| 183 | * }); |
| 184 | * ``` |
| 185 | * |
| 186 | * ### Publishing Through the Endpoint |
| 187 | * **Example:** Publish from a Function |
| 188 | * ```typescript |
| 189 | * // init — bind the endpoint (provide AWS.EventBridge.PutEventsHttp) |
| 190 | * const putEvents = yield* AWS.EventBridge.PutEvents(endpoint); |
| 191 | * |
| 192 | * // runtime — EventBridge routes the event to the healthy region |
| 193 | * yield* putEvents({ |
| 194 | * Entries: [ |
| 195 | * { |
| 196 | * Source: "my.app", |
| 197 | * DetailType: "OrderCreated", |
| 198 | * Detail: JSON.stringify({ orderId: "123" }), |
| 199 | * }, |
| 200 | * ], |
| 201 | * }); |
| 202 | * ``` |
| 203 | * |
| 204 | * @resource |
| 205 | */ |
| 206 | export interface Endpoint extends Resource< |
| 207 | "AWS.EventBridge.Endpoint", |
| 208 | EndpointProps, |
| 209 | { |
| 210 | /** The name of the endpoint. */ |
| 211 | endpointName: EndpointName; |
| 212 | /** The ARN of the endpoint. */ |
| 213 | endpointArn: EndpointArn; |
| 214 | /** The ID of the endpoint, used as `EndpointId` when calling `PutEvents`. */ |
| 215 | endpointId: string; |
| 216 | /** The URL events are published to. */ |
| 217 | endpointUrl: string; |
| 218 | /** The ARNs of the primary and secondary event buses. */ |
| 219 | eventBusArns: string[]; |
| 220 | }, |
| 221 | never, |
| 222 | Providers |
| 223 | > {} |
| 224 | export const Endpoint = Resource<Endpoint>("AWS.EventBridge.Endpoint"); |
| 225 | |
| 226 | type EndpointAttrs = Endpoint["Attributes"]; |
| 227 | |
| 228 | /** The ARN EventBridge expects for a Route 53 health check, from its ID or ARN. */ |
| 229 | const toHealthCheckArn = (healthCheck: string) => |
| 230 | healthCheck.startsWith("arn:") ? healthCheck : `arn:aws:route53:::healthcheck/${healthCheck}`; |
| 231 | |
| 232 | const toAttrs = (endpoint: eventbridge.DescribeEndpointResponse): EndpointAttrs => ({ |
| 233 | endpointName: endpoint.Name!, |
| 234 | endpointArn: endpoint.Arn as EndpointArn, |
| 235 | endpointId: endpoint.EndpointId ?? "", |
| 236 | endpointUrl: endpoint.EndpointUrl ?? "", |
| 237 | eventBusArns: (endpoint.EventBuses ?? []).map((bus) => bus.EventBusArn), |
| 238 | }); |
| 239 | |
| 240 | export const EndpointProvider = () => |
| 241 | Provider.effect( |
| 242 | Endpoint, |
| 243 | Effect.gen(function* () { |
| 244 | const createEndpointName = (id: string, props: { name?: string } = {}) => |
| 245 | props.name |
| 246 | ? Effect.succeed(props.name) |
| 247 | : createPhysicalName({ |
| 248 | id, |
| 249 | maxLength: 64, |
| 250 | }); |
| 251 | |
| 252 | const describe = (name: string) => |
| 253 | eventbridge |
| 254 | .describeEndpoint({ Name: name }) |
| 255 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 256 | |
| 257 | /** |
| 258 | * Poll until the endpoint leaves CREATING/UPDATING. Endpoints settle in |
| 259 | * well under a minute; the wait is bounded so a stuck endpoint surfaces |
| 260 | * instead of hanging, and a failed one surfaces its reason. |
| 261 | */ |
| 262 | const awaitSettled = (name: string) => |
| 263 | eventbridge.describeEndpoint({ Name: name }).pipe( |
| 264 | // A describe fired immediately after create can be eventually |
| 265 | // consistent — absorb NotFound briefly before polling the state. |
| 266 | Effect.retry({ |
| 267 | while: (e): boolean => e._tag === "ResourceNotFoundException", |
| 268 | schedule: Schedule.spaced("1 second"), |
| 269 | times: 5, |
| 270 | }), |
| 271 | Effect.repeat({ |
| 272 | schedule: Schedule.spaced("3 seconds"), |
| 273 | until: (r): boolean => r.State !== "CREATING" && r.State !== "UPDATING", |
| 274 | times: 30, |
| 275 | }), |
| 276 | ); |
| 277 | |
| 278 | const failed = (name: string, r: eventbridge.DescribeEndpointResponse) => |
| 279 | new EndpointFailed({ endpointName: name, state: r.State ?? "", reason: r.StateReason }); |
| 280 | |
| 281 | /** Delete the endpoint and wait until it is gone. */ |
| 282 | const removeEndpoint = Effect.fn(function* (name: string) { |
| 283 | yield* eventbridge.deleteEndpoint({ Name: name }).pipe( |
| 284 | // An endpoint that is still CREATING/UPDATING rejects the delete. |
| 285 | Effect.retry({ |
| 286 | while: (e): boolean => e._tag === "ConcurrentModificationException", |
| 287 | schedule: Schedule.spaced("3 seconds"), |
| 288 | times: 10, |
| 289 | }), |
| 290 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 291 | ); |
| 292 | // Wait out DELETING so the same name can be recreated right away and |
| 293 | // the buses it routes to can be deleted. |
| 294 | yield* describe(name).pipe( |
| 295 | Effect.repeat({ |
| 296 | schedule: Schedule.spaced("3 seconds"), |
| 297 | until: (r): boolean => r === undefined, |
| 298 | times: 30, |
| 299 | }), |
| 300 | ); |
| 301 | }); |
| 302 | |
| 303 | const createEndpoint = Effect.fn(function* ( |
| 304 | name: string, |
| 305 | desired: Omit<eventbridge.CreateEndpointRequest, "Name">, |
| 306 | ) { |
| 307 | // Tolerate an AlreadyExists race with a peer reconciler; the settled |
| 308 | // state is observed below either way. |
| 309 | yield* eventbridge.createEndpoint({ Name: name, ...desired }).pipe( |
| 310 | Effect.retry({ |
| 311 | // A freshly created replication role takes a few seconds to |
| 312 | // become assumable by EventBridge (IAM propagation). |
| 313 | while: (e): boolean => e._tag === "EndpointRoleNotAssumable", |
| 314 | schedule: Schedule.spaced("3 seconds"), |
| 315 | times: 15, |
| 316 | }), |
| 317 | Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void), |
| 318 | ); |
| 319 | const settled = yield* awaitSettled(name); |
| 320 | if (settled.State === "CREATE_FAILED") { |
| 321 | yield* removeEndpoint(name); |
| 322 | return yield* failed(name, settled); |
| 323 | } |
| 324 | return settled; |
| 325 | }); |
| 326 | |
| 327 | const updateEndpoint = Effect.fn(function* ( |
| 328 | name: string, |
| 329 | desired: Omit<eventbridge.UpdateEndpointRequest, "Name">, |
| 330 | ) { |
| 331 | yield* eventbridge.updateEndpoint({ Name: name, ...desired }).pipe( |
| 332 | Effect.retry({ |
| 333 | while: (e): boolean => e._tag === "EndpointRoleNotAssumable", |
| 334 | schedule: Schedule.spaced("3 seconds"), |
| 335 | times: 15, |
| 336 | }), |
| 337 | Effect.retry({ |
| 338 | while: (e): boolean => e._tag === "ConcurrentModificationException", |
| 339 | schedule: Schedule.spaced("3 seconds"), |
| 340 | times: 10, |
| 341 | }), |
| 342 | ); |
| 343 | const settled = yield* awaitSettled(name); |
| 344 | if (settled.State === "UPDATE_FAILED") return yield* failed(name, settled); |
| 345 | return settled; |
| 346 | }); |
| 347 | |
| 348 | return { |
| 349 | stables: ["endpointName", "endpointArn", "endpointId", "endpointUrl"], |
| 350 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 351 | if (!isResolved(news)) return; |
| 352 | const oldName = yield* createEndpointName(id, olds); |
| 353 | const newName = yield* createEndpointName(id, news); |
| 354 | if (oldName !== newName) { |
| 355 | return { action: "replace" } as const; |
| 356 | } |
| 357 | }), |
| 358 | read: Effect.fn(function* ({ id, olds, output }) { |
| 359 | // Endpoints don't support tags; the deterministic physical name is |
| 360 | // the ownership signal (it embeds app/stage/logical id). |
| 361 | const name = output?.endpointName ?? (yield* createEndpointName(id, olds ?? {})); |
| 362 | const described = yield* describe(name); |
| 363 | if (!described?.Name || !described.Arn) { |
| 364 | return undefined; |
| 365 | } |
| 366 | return toAttrs(described); |
| 367 | }), |
| 368 | list: () => |
| 369 | Effect.gen(function* () { |
| 370 | const attrs: EndpointAttrs[] = []; |
| 371 | let nextToken: string | undefined; |
| 372 | do { |
| 373 | const page = yield* eventbridge.listEndpoints({ NextToken: nextToken }); |
| 374 | for (const endpoint of page.Endpoints ?? []) { |
| 375 | if (!endpoint.Name || !endpoint.Arn) continue; |
| 376 | attrs.push(toAttrs(endpoint)); |
| 377 | } |
| 378 | nextToken = page.NextToken; |
| 379 | } while (nextToken); |
| 380 | return attrs; |
| 381 | }), |
| 382 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 383 | const name = output?.endpointName ?? (yield* createEndpointName(id, news)); |
| 384 | const desired = { |
| 385 | Description: news.description, |
| 386 | RoutingConfig: { |
| 387 | FailoverConfig: { |
| 388 | Primary: { HealthCheck: toHealthCheckArn(news.failover.healthCheck) }, |
| 389 | Secondary: { Route: news.failover.secondaryRegion }, |
| 390 | }, |
| 391 | }, |
| 392 | ReplicationConfig: { |
| 393 | State: news.replication === false ? "DISABLED" : "ENABLED", |
| 394 | }, |
| 395 | EventBuses: news.eventBuses.map((arn) => ({ EventBusArn: arn })), |
| 396 | RoleArn: news.roleArn, |
| 397 | } satisfies Omit<eventbridge.UpdateEndpointRequest, "Name">; |
| 398 | |
| 399 | // Observe — live cloud state is authoritative. A vanished endpoint |
| 400 | // falls through to create, and so does one a previous run left in |
| 401 | // CREATE_FAILED (it can never become ACTIVE). |
| 402 | let observed = yield* describe(name); |
| 403 | if (observed?.Arn) { |
| 404 | observed = yield* awaitSettled(name); |
| 405 | if (observed.State === "CREATE_FAILED") { |
| 406 | yield* removeEndpoint(name); |
| 407 | observed = undefined; |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | // Ensure — create the endpoint and wait for it to settle. The |
| 412 | // replication role is checked again after the endpoint is accepted: |
| 413 | // while its policy is still propagating, the endpoint ends in |
| 414 | // CREATE_FAILED ("does not grant EventBridge the PutRule |
| 415 | // permission"), so a failed create is removed and retried. |
| 416 | if (!observed?.Arn) { |
| 417 | observed = yield* createEndpoint(name, desired).pipe( |
| 418 | Effect.retry({ |
| 419 | while: (e): boolean => e._tag === "EndpointFailed", |
| 420 | schedule: Schedule.spaced("10 seconds"), |
| 421 | times: 3, |
| 422 | }), |
| 423 | ); |
| 424 | } |
| 425 | |
| 426 | // Sync — diff the observed configuration against the desired one |
| 427 | // and update only when something differs (or the last update |
| 428 | // failed). |
| 429 | const drifted = |
| 430 | observed.State === "UPDATE_FAILED" || |
| 431 | (observed.Description ?? "") !== (desired.Description ?? "") || |
| 432 | observed.RoutingConfig?.FailoverConfig?.Primary?.HealthCheck !== |
| 433 | desired.RoutingConfig.FailoverConfig.Primary.HealthCheck || |
| 434 | observed.RoutingConfig?.FailoverConfig?.Secondary?.Route !== |
| 435 | desired.RoutingConfig.FailoverConfig.Secondary.Route || |
| 436 | (observed.ReplicationConfig?.State ?? "ENABLED") !== desired.ReplicationConfig.State || |
| 437 | (observed.RoleArn ?? "") !== (desired.RoleArn ?? "") || |
| 438 | (observed.EventBuses ?? []) |
| 439 | .map((bus) => bus.EventBusArn) |
| 440 | .sort() |
| 441 | .join(",") !== [...news.eventBuses].sort().join(","); |
| 442 | if (drifted) { |
| 443 | // Same propagation race as create, ending in UPDATE_FAILED. |
| 444 | observed = yield* updateEndpoint(name, desired).pipe( |
| 445 | Effect.retry({ |
| 446 | while: (e): boolean => e._tag === "EndpointFailed", |
| 447 | schedule: Schedule.spaced("10 seconds"), |
| 448 | times: 3, |
| 449 | }), |
| 450 | ); |
| 451 | } |
| 452 | |
| 453 | const attrs = toAttrs(observed); |
| 454 | yield* session.note(attrs.endpointUrl); |
| 455 | return attrs; |
| 456 | }), |
| 457 | delete: Effect.fn(function* ({ output }) { |
| 458 | yield* removeEndpoint(output.endpointName); |
| 459 | }), |
| 460 | }; |
| 461 | }), |
| 462 | ); |