The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as sesv2 from "@distilled.cloud/aws/sesv2"; |
| 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 { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { AWSEnvironment } from "../Environment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | |
| 15 | export class MultiRegionEndpointUnexpectedResponse extends Data.TaggedError( |
| 16 | "MultiRegionEndpointUnexpectedResponse", |
| 17 | )<{ |
| 18 | readonly message: string; |
| 19 | readonly cause?: unknown; |
| 20 | }> {} |
| 21 | |
| 22 | /** |
| 23 | * The lifecycle status of a multi-region endpoint: `CREATING`, `READY`, |
| 24 | * `FAILED`, or `DELETING`. |
| 25 | */ |
| 26 | export type MultiRegionEndpointStatus = sesv2.Status; |
| 27 | |
| 28 | export interface MultiRegionEndpointProps { |
| 29 | /** |
| 30 | * Name of the multi-region endpoint. If omitted, a deterministic physical |
| 31 | * name is generated from the app, stage, and logical ID. Changing the name |
| 32 | * replaces the endpoint. |
| 33 | */ |
| 34 | endpointName?: string; |
| 35 | /** |
| 36 | * The secondary AWS regions the endpoint routes traffic across, e.g. |
| 37 | * `["eu-west-1"]`. The primary region is wherever the resource is created; |
| 38 | * sending traffic is split across it and every region listed here. |
| 39 | * |
| 40 | * There is no update API, so any change to this list replaces the endpoint. |
| 41 | */ |
| 42 | regions: string[]; |
| 43 | /** |
| 44 | * Tags to apply to the endpoint. Merged with internal Alchemy tags. |
| 45 | */ |
| 46 | tags?: Record<string, string>; |
| 47 | } |
| 48 | |
| 49 | export interface MultiRegionEndpoint extends Resource< |
| 50 | "AWS.SES.MultiRegionEndpoint", |
| 51 | MultiRegionEndpointProps, |
| 52 | { |
| 53 | /** Name of the multi-region endpoint. */ |
| 54 | endpointName: string; |
| 55 | /** Opaque endpoint identifier assigned by SES. */ |
| 56 | endpointId: string; |
| 57 | /** |
| 58 | * The endpoint's provisioning status at the time reconcile returned. |
| 59 | * Provisioning is asynchronous and starts as `CREATING`; the endpoint is |
| 60 | * not usable until it reaches `READY`. Reconcile does NOT wait for |
| 61 | * `READY` — poll `getMultiRegionEndpoint` downstream if you need to block |
| 62 | * on readiness. |
| 63 | */ |
| 64 | status: MultiRegionEndpointStatus; |
| 65 | }, |
| 66 | never, |
| 67 | Providers |
| 68 | > {} |
| 69 | |
| 70 | /** |
| 71 | * An Amazon SES v2 multi-region endpoint (global endpoint) — a single sending |
| 72 | * endpoint that splits email traffic across a primary region (where the |
| 73 | * endpoint is created) and one or more secondary regions, improving |
| 74 | * resilience and deliverability. |
| 75 | * |
| 76 | * :::note |
| 77 | * Provisioning is asynchronous and can take a while: creation returns |
| 78 | * immediately with status `CREATING`, and the endpoint only becomes usable |
| 79 | * once it reaches `READY`. This resource does **not** wait for `READY` — the |
| 80 | * `status` attribute reflects the value observed when reconcile returned. |
| 81 | * Poll `getMultiRegionEndpoint` yourself if you need to block on readiness. |
| 82 | * ::: |
| 83 | * |
| 84 | * There is no update API, so any change to the name or routes replaces the |
| 85 | * endpoint. |
| 86 | * ### Creating Endpoints |
| 87 | * **Example:** Two-Region Endpoint |
| 88 | * ```typescript |
| 89 | * import * as SES from "@alchemy.run/aws/SES"; |
| 90 | * |
| 91 | * // The primary region is wherever the stack deploys; the route adds a |
| 92 | * // secondary region. |
| 93 | * const endpoint = yield* SES.MultiRegionEndpoint("Global", { |
| 94 | * regions: ["eu-west-1"], |
| 95 | * }); |
| 96 | * ``` |
| 97 | * |
| 98 | * **Example:** Three-Region Endpoint |
| 99 | * ```typescript |
| 100 | * // Traffic is split across the primary region plus every listed route. |
| 101 | * const endpoint = yield* SES.MultiRegionEndpoint("Global", { |
| 102 | * regions: ["eu-west-1", "ap-southeast-2"], |
| 103 | * }); |
| 104 | * ``` |
| 105 | * |
| 106 | * **Example:** Explicit Endpoint Name |
| 107 | * ```typescript |
| 108 | * const endpoint = yield* SES.MultiRegionEndpoint("Global", { |
| 109 | * endpointName: "acme-global", |
| 110 | * regions: ["eu-west-1"], |
| 111 | * }); |
| 112 | * ``` |
| 113 | * |
| 114 | * ### Waiting for READY |
| 115 | * **Example:** Poll Until the Endpoint Is Usable |
| 116 | * ```typescript |
| 117 | * import * as sesv2 from "@distilled.cloud/aws/sesv2"; |
| 118 | * import * as Effect from "effect/Effect"; |
| 119 | * import * as Schedule from "effect/Schedule"; |
| 120 | * |
| 121 | * const endpoint = yield* SES.MultiRegionEndpoint("Global", { |
| 122 | * regions: ["eu-west-1"], |
| 123 | * }); |
| 124 | * |
| 125 | * // Reconcile returns as soon as SES accepts the create, so status is |
| 126 | * // usually CREATING. Poll yourself when you need to block on readiness. |
| 127 | * const ready = yield* sesv2 |
| 128 | * .getMultiRegionEndpoint({ EndpointName: yield* endpoint.endpointName }) |
| 129 | * .pipe( |
| 130 | * Effect.repeat({ |
| 131 | * schedule: Schedule.spaced("30 seconds"), |
| 132 | * until: (r) => r.Status === "READY", |
| 133 | * times: 40, |
| 134 | * }), |
| 135 | * ); |
| 136 | * ``` |
| 137 | * |
| 138 | * @resource |
| 139 | */ |
| 140 | export const MultiRegionEndpoint = Resource<MultiRegionEndpoint>("AWS.SES.MultiRegionEndpoint"); |
| 141 | |
| 142 | const toTagRecord = ( |
| 143 | tags: ReadonlyArray<{ Key: string; Value: string }> | undefined, |
| 144 | ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value])); |
| 145 | |
| 146 | // getMultiRegionEndpoint returns no ARN, so the ARN listTagsForResource needs |
| 147 | // is derived from the endpoint NAME (not its id) — verified live. |
| 148 | const endpointArnOf = (region: string, accountId: string, name: string) => |
| 149 | `arn:aws:ses:${region}:${accountId}:multi-region-endpoint/${name}`; |
| 150 | |
| 151 | const sameRegions = ( |
| 152 | a: ReadonlyArray<string> | undefined, |
| 153 | b: ReadonlyArray<string> | undefined, |
| 154 | ): boolean => { |
| 155 | const key = (regions: ReadonlyArray<string> | undefined) => |
| 156 | JSON.stringify([...(regions ?? [])].sort()); |
| 157 | return key(a) === key(b); |
| 158 | }; |
| 159 | |
| 160 | export const MultiRegionEndpointProvider = () => |
| 161 | Provider.effect( |
| 162 | MultiRegionEndpoint, |
| 163 | Effect.gen(function* () { |
| 164 | const createName = Effect.fn(function* ( |
| 165 | id: string, |
| 166 | props: Pick<MultiRegionEndpointProps, "endpointName">, |
| 167 | ) { |
| 168 | return props.endpointName ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 169 | }); |
| 170 | |
| 171 | const getEndpoint = Effect.fn(function* (name: string) { |
| 172 | return yield* sesv2 |
| 173 | .getMultiRegionEndpoint({ EndpointName: name }) |
| 174 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)); |
| 175 | }); |
| 176 | |
| 177 | // getMultiRegionEndpoint does not return tags, so ownership costs a |
| 178 | // second API call. Only `read` pays it — `list` deletes by name. |
| 179 | const getEndpointTags = Effect.fn(function* (name: string) { |
| 180 | const { accountId, region } = yield* AWSEnvironment.current; |
| 181 | return yield* sesv2 |
| 182 | .listTagsForResource({ |
| 183 | ResourceArn: endpointArnOf(region, accountId, name), |
| 184 | }) |
| 185 | .pipe( |
| 186 | Effect.map((response) => toTagRecord(response.Tags)), |
| 187 | Effect.catchTag("NotFoundException", () => |
| 188 | Effect.succeed({} as Record<string, string>), |
| 189 | ), |
| 190 | ); |
| 191 | }); |
| 192 | |
| 193 | return MultiRegionEndpoint.Provider.of({ |
| 194 | stables: ["endpointName", "endpointId"], |
| 195 | |
| 196 | // Account/region-scoped: enumerate every endpoint so leaked test |
| 197 | // resources are cleaned by nuke. |
| 198 | list: Effect.fn(function* () { |
| 199 | const pages = yield* sesv2.listMultiRegionEndpoints.pages({}).pipe(Stream.runCollect); |
| 200 | return Array.from(pages) |
| 201 | .flatMap((page) => page.MultiRegionEndpoints ?? []) |
| 202 | .flatMap((entry) => |
| 203 | entry.EndpointName && entry.EndpointId |
| 204 | ? [ |
| 205 | { |
| 206 | endpointName: entry.EndpointName, |
| 207 | endpointId: entry.EndpointId, |
| 208 | status: entry.Status ?? "CREATING", |
| 209 | }, |
| 210 | ] |
| 211 | : [], |
| 212 | ); |
| 213 | }), |
| 214 | |
| 215 | read: Effect.fn(function* ({ id, olds, output }) { |
| 216 | const name = output?.endpointName ?? (yield* createName(id, olds ?? {})); |
| 217 | const found = yield* getEndpoint(name); |
| 218 | if (!found || !found.EndpointId) return undefined; |
| 219 | const attrs = { |
| 220 | endpointName: name, |
| 221 | endpointId: found.EndpointId, |
| 222 | status: found.Status ?? "CREATING", |
| 223 | }; |
| 224 | // Endpoints are taggable and reconcile brands the ones it creates, |
| 225 | // so existence at our deterministic name is not proof of ownership. |
| 226 | const tags = yield* getEndpointTags(name); |
| 227 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 228 | }), |
| 229 | |
| 230 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 231 | if (!isResolved(news)) return undefined; |
| 232 | const oldName = yield* createName(id, olds ?? {}); |
| 233 | const newName = yield* createName(id, news ?? {}); |
| 234 | // No update API: a rename or any routing change replaces the |
| 235 | // endpoint. |
| 236 | if (oldName !== newName || !sameRegions(olds?.regions, news.regions)) { |
| 237 | return { action: "replace" } as const; |
| 238 | } |
| 239 | }), |
| 240 | |
| 241 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 242 | const name = output?.endpointName ?? (yield* createName(id, news)); |
| 243 | const internalTags = yield* createInternalTags(id); |
| 244 | const desiredTags = { ...news.tags, ...internalTags }; |
| 245 | |
| 246 | // 1. OBSERVE — cloud state is authoritative. |
| 247 | let observed = yield* getEndpoint(name); |
| 248 | |
| 249 | if (observed === undefined) { |
| 250 | // 2. ENSURE — create; AlreadyExists is a race, not a failure. |
| 251 | // Provisioning is asynchronous: creation returns CREATING and we |
| 252 | // deliberately do NOT wait for READY (that exceeds the polling |
| 253 | // budget; downstream consumers poll if they need readiness). |
| 254 | yield* sesv2 |
| 255 | .createMultiRegionEndpoint({ |
| 256 | EndpointName: name, |
| 257 | Details: { |
| 258 | RoutesDetails: news.regions.map((region) => ({ |
| 259 | Region: region, |
| 260 | })), |
| 261 | }, |
| 262 | Tags: createTagsList(desiredTags), |
| 263 | }) |
| 264 | .pipe(Effect.catchTag("AlreadyExistsException", () => Effect.succeed({}))); |
| 265 | // The endpoint is not always readable the instant create returns |
| 266 | // (and on the AlreadyExists race another writer may still be |
| 267 | // mid-create), so poll briefly rather than failing outright. |
| 268 | observed = yield* getEndpoint(name).pipe( |
| 269 | Effect.repeat({ |
| 270 | schedule: Schedule.spaced("1 second"), |
| 271 | until: (endpoint) => endpoint !== undefined, |
| 272 | times: 8, |
| 273 | }), |
| 274 | ); |
| 275 | } |
| 276 | |
| 277 | if (observed === undefined || !observed.EndpointId) { |
| 278 | return yield* new MultiRegionEndpointUnexpectedResponse({ |
| 279 | message: `SES multi-region endpoint ${name} was not found after create`, |
| 280 | }); |
| 281 | } |
| 282 | |
| 283 | // 3. SYNC TAGS — diff against OBSERVED cloud tags so an adopted |
| 284 | // endpoint gets branded and stops reading as Unowned. |
| 285 | const observedTags = yield* getEndpointTags(name); |
| 286 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 287 | if (upsert.length > 0 || removed.length > 0) { |
| 288 | const { accountId, region } = yield* AWSEnvironment.current; |
| 289 | const endpointArn = endpointArnOf(region, accountId, name); |
| 290 | if (upsert.length > 0) { |
| 291 | yield* sesv2.tagResource({ |
| 292 | ResourceArn: endpointArn, |
| 293 | Tags: upsert, |
| 294 | }); |
| 295 | } |
| 296 | if (removed.length > 0) { |
| 297 | yield* sesv2.untagResource({ |
| 298 | ResourceArn: endpointArn, |
| 299 | TagKeys: removed, |
| 300 | }); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | yield* session.note(observed.EndpointId); |
| 305 | return { |
| 306 | endpointName: name, |
| 307 | endpointId: observed.EndpointId, |
| 308 | status: observed.Status ?? "CREATING", |
| 309 | }; |
| 310 | }), |
| 311 | |
| 312 | delete: Effect.fn(function* ({ output }) { |
| 313 | // deleteMultiRegionEndpoint is idempotent for a missing endpoint. |
| 314 | // |
| 315 | // Provisioning is asynchronous and reconcile deliberately returns at |
| 316 | // CREATING, so a destroy that follows closely enough hits an endpoint |
| 317 | // still coming up: SES answers ConcurrentModificationException |
| 318 | // ("Unable to delete resource in PROVISIONING status"). That is |
| 319 | // eventual consistency, not a failure — retry on a bounded schedule |
| 320 | // until the endpoint settles and the delete takes. |
| 321 | yield* sesv2.deleteMultiRegionEndpoint({ EndpointName: output.endpointName }).pipe( |
| 322 | Effect.retry({ |
| 323 | while: (e) => e._tag === "ConcurrentModificationException", |
| 324 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(12)]), |
| 325 | }), |
| 326 | Effect.catchTag("NotFoundException", () => Effect.void), |
| 327 | ); |
| 328 | }), |
| 329 | }); |
| 330 | }), |
| 331 | ); |