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, 06:00 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 type { Providers } from "../Providers.ts"; |
| 13 | import type { SuppressionListReason } from "./ConfigurationSet.ts"; |
| 14 | |
| 15 | export class TenantUnexpectedResponse extends Data.TaggedError("TenantUnexpectedResponse")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | /** |
| 21 | * The scope of the tenant's suppression list: `ACCOUNT` shares the |
| 22 | * account-level suppression list, `TENANT` maintains a separate list scoped to |
| 23 | * this tenant. |
| 24 | */ |
| 25 | export type SuppressionListScope = sesv2.SuppressionListScope; |
| 26 | |
| 27 | export interface TenantSuppressionSettings { |
| 28 | /** |
| 29 | * The bounce/complaint reasons for which SES adds destinations to the |
| 30 | * tenant's suppression list. |
| 31 | */ |
| 32 | reasons: SuppressionListReason[]; |
| 33 | /** |
| 34 | * Whether the tenant uses the account-level suppression list (`ACCOUNT`) or |
| 35 | * maintains its own tenant-scoped list (`TENANT`). |
| 36 | */ |
| 37 | scope: SuppressionListScope; |
| 38 | } |
| 39 | |
| 40 | export interface TenantProps { |
| 41 | /** |
| 42 | * Name of the tenant. If omitted, a deterministic physical name is generated |
| 43 | * from the app, stage, and logical ID. Changing the name replaces the |
| 44 | * tenant. |
| 45 | */ |
| 46 | tenantName?: string; |
| 47 | /** |
| 48 | * The tenant's suppression list configuration, synced in place via |
| 49 | * `putTenantSuppressionAttributes`. Leave undefined to keep SES's current |
| 50 | * setting. |
| 51 | * |
| 52 | * `reasons` and `scope` are both required together: SES rejects a |
| 53 | * suppression update carrying only one of them |
| 54 | * (`BadRequestException: SuppressedReasons cannot be specified without |
| 55 | * SuppressionScope`, and vice versa). |
| 56 | */ |
| 57 | suppression?: TenantSuppressionSettings; |
| 58 | /** |
| 59 | * Tags to apply to the tenant. Merged with internal Alchemy tags. |
| 60 | */ |
| 61 | tags?: Record<string, string>; |
| 62 | } |
| 63 | |
| 64 | export interface Tenant extends Resource< |
| 65 | "AWS.SES.Tenant", |
| 66 | TenantProps, |
| 67 | { |
| 68 | /** Name of the tenant. */ |
| 69 | tenantName: string; |
| 70 | /** Opaque tenant identifier assigned by SES. */ |
| 71 | tenantId: string; |
| 72 | /** ARN of the tenant. */ |
| 73 | tenantArn: string; |
| 74 | }, |
| 75 | never, |
| 76 | Providers |
| 77 | > {} |
| 78 | |
| 79 | /** |
| 80 | * An Amazon SES v2 tenant — a logical container that groups related SES |
| 81 | * resources (email identities, configuration sets, templates) together, each |
| 82 | * with its own reputation metrics, sending status, and optional |
| 83 | * tenant-scoped suppression list. Useful for isolating email sending across |
| 84 | * customers or business units within a single SES account. |
| 85 | * |
| 86 | * Associate resources with a tenant using `SES.TenantResourceAssociation`. |
| 87 | * Deleting the tenant removes its resource associations but leaves the |
| 88 | * underlying resources in place. |
| 89 | * ### Creating Tenants |
| 90 | * **Example:** Basic Tenant |
| 91 | * ```typescript |
| 92 | * import * as SES from "@alchemy.run/aws/SES"; |
| 93 | * |
| 94 | * const tenant = yield* SES.Tenant("CustomerA", {}); |
| 95 | * ``` |
| 96 | * |
| 97 | * **Example:** Tenant with a Scoped Suppression List |
| 98 | * ```typescript |
| 99 | * // SES requires the reasons and the scope together, so they travel as one |
| 100 | * // prop rather than two independently-optional ones. |
| 101 | * const tenant = yield* SES.Tenant("CustomerA", { |
| 102 | * suppression: { reasons: ["BOUNCE", "COMPLAINT"], scope: "TENANT" }, |
| 103 | * }); |
| 104 | * ``` |
| 105 | * |
| 106 | * **Example:** Tenant with Tags |
| 107 | * ```typescript |
| 108 | * const tenant = yield* SES.Tenant("CustomerA", { |
| 109 | * tags: { Customer: "acme", CostCenter: "growth" }, |
| 110 | * }); |
| 111 | * ``` |
| 112 | * |
| 113 | * ### Associating Resources |
| 114 | * **Example:** Give the Tenant an Identity, Config Set, and Template |
| 115 | * ```typescript |
| 116 | * const tenant = yield* SES.Tenant("CustomerA", {}); |
| 117 | * const identity = yield* SES.EmailIdentity("Sender", { |
| 118 | * emailIdentity: "mail.acme.example.com", |
| 119 | * }); |
| 120 | * const configSet = yield* SES.ConfigurationSet("AcmeTracking", {}); |
| 121 | * |
| 122 | * // A resource must be associated before the tenant can send with it. |
| 123 | * yield* SES.TenantResourceAssociation("AcmeIdentity", { |
| 124 | * tenantName: tenant.tenantName, |
| 125 | * resourceArn: identity.identityArn, |
| 126 | * }); |
| 127 | * yield* SES.TenantResourceAssociation("AcmeConfigSet", { |
| 128 | * tenantName: tenant.tenantName, |
| 129 | * resourceArn: configSet.configurationSetArn, |
| 130 | * }); |
| 131 | * ``` |
| 132 | * |
| 133 | * ### Tenant Suppression Lists |
| 134 | * **Example:** Read and Write the Tenant's Own Suppression List |
| 135 | * ```typescript |
| 136 | * // With scope "TENANT" the list is separate from the account's. |
| 137 | * const tenant = yield* SES.Tenant("CustomerA", { |
| 138 | * suppression: { reasons: ["BOUNCE", "COMPLAINT"], scope: "TENANT" }, |
| 139 | * }); |
| 140 | * |
| 141 | * // init — account-level bindings, scoped per call via TenantName |
| 142 | * const suppress = yield* SES.PutSuppressedDestination(); |
| 143 | * const listSuppressed = yield* SES.ListSuppressedDestinations(); |
| 144 | * |
| 145 | * // runtime |
| 146 | * yield* suppress({ |
| 147 | * EmailAddress: "hard-bounce@example.com", |
| 148 | * Reason: "BOUNCE", |
| 149 | * TenantName: yield* tenant.tenantName, |
| 150 | * }); |
| 151 | * const { SuppressedDestinationSummaries } = yield* listSuppressed({ |
| 152 | * TenantName: yield* tenant.tenantName, |
| 153 | * }); |
| 154 | * ``` |
| 155 | * |
| 156 | * @resource |
| 157 | */ |
| 158 | export const Tenant = Resource<Tenant>("AWS.SES.Tenant"); |
| 159 | |
| 160 | const toTagRecord = ( |
| 161 | tags: ReadonlyArray<{ Key: string; Value: string }> | undefined, |
| 162 | ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value])); |
| 163 | |
| 164 | const sameReasons = ( |
| 165 | a: ReadonlyArray<sesv2.SuppressionListReason> | undefined, |
| 166 | b: ReadonlyArray<sesv2.SuppressionListReason> | undefined, |
| 167 | ): boolean => { |
| 168 | const key = (reasons: ReadonlyArray<sesv2.SuppressionListReason> | undefined) => |
| 169 | JSON.stringify([...(reasons ?? [])].sort()); |
| 170 | return key(a) === key(b); |
| 171 | }; |
| 172 | |
| 173 | export const TenantProvider = () => |
| 174 | Provider.effect( |
| 175 | Tenant, |
| 176 | Effect.gen(function* () { |
| 177 | const createName = Effect.fn(function* (id: string, props: Pick<TenantProps, "tenantName">) { |
| 178 | return props.tenantName ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 179 | }); |
| 180 | |
| 181 | const getTenant = Effect.fn(function* (name: string) { |
| 182 | return yield* sesv2.getTenant({ TenantName: name }).pipe( |
| 183 | Effect.map((response) => response.Tenant), |
| 184 | Effect.catchTag("NotFoundException", () => Effect.undefined), |
| 185 | ); |
| 186 | }); |
| 187 | |
| 188 | return Tenant.Provider.of({ |
| 189 | stables: ["tenantName", "tenantId", "tenantArn"], |
| 190 | |
| 191 | // Account-scoped: enumerate every tenant so leaked test resources are |
| 192 | // cleaned by nuke. |
| 193 | list: Effect.fn(function* () { |
| 194 | const pages = yield* sesv2.listTenants.pages({}).pipe(Stream.runCollect); |
| 195 | return Array.from(pages) |
| 196 | .flatMap((page) => page.Tenants ?? []) |
| 197 | .flatMap((entry) => |
| 198 | entry.TenantName && entry.TenantId && entry.TenantArn |
| 199 | ? [ |
| 200 | { |
| 201 | tenantName: entry.TenantName, |
| 202 | tenantId: entry.TenantId, |
| 203 | tenantArn: entry.TenantArn, |
| 204 | }, |
| 205 | ] |
| 206 | : [], |
| 207 | ); |
| 208 | }), |
| 209 | |
| 210 | read: Effect.fn(function* ({ id, olds, output }) { |
| 211 | const name = output?.tenantName ?? (yield* createName(id, olds ?? {})); |
| 212 | const found = yield* getTenant(name); |
| 213 | if (!found || !found.TenantId || !found.TenantArn) return undefined; |
| 214 | const attrs = { |
| 215 | tenantName: name, |
| 216 | tenantId: found.TenantId, |
| 217 | tenantArn: found.TenantArn, |
| 218 | }; |
| 219 | const tags = toTagRecord(found.Tags); |
| 220 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 221 | }), |
| 222 | |
| 223 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 224 | if (!isResolved(news)) return undefined; |
| 225 | const oldName = yield* createName(id, olds ?? {}); |
| 226 | const newName = yield* createName(id, news ?? {}); |
| 227 | if (oldName !== newName) { |
| 228 | return { action: "replace" } as const; |
| 229 | } |
| 230 | }), |
| 231 | |
| 232 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 233 | const name = output?.tenantName ?? (yield* createName(id, news)); |
| 234 | const internalTags = yield* createInternalTags(id); |
| 235 | const desiredTags = { ...news.tags, ...internalTags }; |
| 236 | |
| 237 | // 1. OBSERVE — cloud state is authoritative. |
| 238 | let observed = yield* getTenant(name); |
| 239 | |
| 240 | if (observed === undefined) { |
| 241 | // 2. ENSURE — create with the full desired set. AlreadyExists is a |
| 242 | // race → fall through to the sync steps to converge. |
| 243 | yield* sesv2 |
| 244 | .createTenant({ |
| 245 | TenantName: name, |
| 246 | Tags: createTagsList(desiredTags), |
| 247 | SuppressionAttributes: news.suppression |
| 248 | ? { |
| 249 | SuppressedReasons: news.suppression.reasons, |
| 250 | SuppressionScope: news.suppression.scope, |
| 251 | } |
| 252 | : undefined, |
| 253 | }) |
| 254 | .pipe(Effect.catchTag("AlreadyExistsException", () => Effect.succeed({}))); |
| 255 | // Not always readable the instant create returns, and on the |
| 256 | // AlreadyExists race another writer may still be mid-create. |
| 257 | observed = yield* getTenant(name).pipe( |
| 258 | Effect.repeat({ |
| 259 | schedule: Schedule.spaced("1 second"), |
| 260 | until: (tenant) => tenant !== undefined, |
| 261 | times: 8, |
| 262 | }), |
| 263 | ); |
| 264 | } |
| 265 | |
| 266 | if (observed === undefined || !observed.TenantId || !observed.TenantArn) { |
| 267 | return yield* new TenantUnexpectedResponse({ |
| 268 | message: `SES tenant ${name} was not found after create`, |
| 269 | }); |
| 270 | } |
| 271 | const tenantArn = observed.TenantArn; |
| 272 | |
| 273 | // 3. SYNC SUPPRESSION — diff observed suppression against desired and |
| 274 | // apply only on a real delta. |
| 275 | // |
| 276 | // SES requires both members together — a put carrying only one |
| 277 | // fails with BadRequestException ("SuppressedReasons cannot be |
| 278 | // specified without SuppressionScope", and the mirror image). The |
| 279 | // prop nests them so that invalid state is unrepresentable and |
| 280 | // the put below always carries both. |
| 281 | const observedReasons = observed.SuppressionAttributes?.SuppressedReasons; |
| 282 | const observedScope = observed.SuppressionAttributes?.SuppressionScope; |
| 283 | if ( |
| 284 | news.suppression !== undefined && |
| 285 | (!sameReasons(observedReasons, news.suppression.reasons) || |
| 286 | observedScope !== news.suppression.scope) |
| 287 | ) { |
| 288 | yield* sesv2.putTenantSuppressionAttributes({ |
| 289 | TenantName: name, |
| 290 | SuppressedReasons: news.suppression.reasons, |
| 291 | SuppressionScope: news.suppression.scope, |
| 292 | }); |
| 293 | } |
| 294 | |
| 295 | // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption |
| 296 | // converges. |
| 297 | const observedTags = toTagRecord(observed.Tags); |
| 298 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 299 | if (upsert.length > 0) { |
| 300 | yield* sesv2.tagResource({ ResourceArn: tenantArn, Tags: upsert }); |
| 301 | } |
| 302 | if (removed.length > 0) { |
| 303 | yield* sesv2.untagResource({ |
| 304 | ResourceArn: tenantArn, |
| 305 | TagKeys: removed, |
| 306 | }); |
| 307 | } |
| 308 | |
| 309 | yield* session.note(tenantArn); |
| 310 | return { |
| 311 | tenantName: name, |
| 312 | tenantId: observed.TenantId, |
| 313 | tenantArn, |
| 314 | }; |
| 315 | }), |
| 316 | |
| 317 | delete: Effect.fn(function* ({ output }) { |
| 318 | // deleteTenant removes the tenant and its resource associations (not |
| 319 | // the resources themselves), and is idempotent for a missing tenant. |
| 320 | yield* sesv2 |
| 321 | .deleteTenant({ TenantName: output.tenantName }) |
| 322 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)); |
| 323 | }), |
| 324 | }); |
| 325 | }), |
| 326 | ); |