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 mm from "@distilled.cloud/aws/mailmanager"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, createTagsList, hasAlchemyTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { |
| 12 | readMailManagerTags, |
| 13 | retryWhileMailManagerConflict, |
| 14 | sameShape, |
| 15 | syncMailManagerTags, |
| 16 | } from "./internal.ts"; |
| 17 | |
| 18 | export class RuleSetUnexpectedResponse extends Data.TaggedError("RuleSetUnexpectedResponse")<{ |
| 19 | readonly message: string; |
| 20 | readonly cause?: unknown; |
| 21 | }> {} |
| 22 | |
| 23 | export interface RuleSetProps { |
| 24 | /** |
| 25 | * Name of the rule set. If omitted, a deterministic physical name is |
| 26 | * generated from the app, stage, and logical ID. Renames apply in place. |
| 27 | */ |
| 28 | ruleSetName?: string; |
| 29 | /** |
| 30 | * The ordered list of rules evaluated against emails arriving through an |
| 31 | * ingress point associated with this rule set. Each rule pairs optional |
| 32 | * conditions with one or more actions (Drop, Relay, Archive, WriteToS3, |
| 33 | * Send, AddHeader, ReplaceRecipient, DeliverToMailbox, DeliverToQBusiness, |
| 34 | * PublishToSns, Bounce, InvokeLambda). Updates apply in place. |
| 35 | * @default [] |
| 36 | */ |
| 37 | rules?: mm.Rule[]; |
| 38 | /** |
| 39 | * Tags applied to the rule set. Alchemy ownership tags are merged in |
| 40 | * automatically. |
| 41 | */ |
| 42 | tags?: Record<string, string>; |
| 43 | } |
| 44 | |
| 45 | export interface RuleSet extends Resource< |
| 46 | "AWS.MailManager.RuleSet", |
| 47 | RuleSetProps, |
| 48 | { |
| 49 | /** Server-assigned ID of the rule set. */ |
| 50 | ruleSetId: string; |
| 51 | /** ARN of the rule set. */ |
| 52 | ruleSetArn: string; |
| 53 | /** Name of the rule set. */ |
| 54 | ruleSetName: string; |
| 55 | }, |
| 56 | never, |
| 57 | Providers |
| 58 | > {} |
| 59 | |
| 60 | /** |
| 61 | * An SES Mail Manager rule set — the ordered rules an ingress point applies |
| 62 | * to incoming email (drop, archive, write to S3, deliver, bounce, invoke |
| 63 | * Lambda, ...). |
| 64 | * |
| 65 | * All aspects (name, rules, tags) update in place. |
| 66 | * ### Creating Rule Sets |
| 67 | * **Example:** Drop Everything |
| 68 | * ```typescript |
| 69 | * import * as MailManager from "@alchemy.run/aws/MailManager"; |
| 70 | * |
| 71 | * const ruleSet = yield* MailManager.RuleSet("Inbound", { |
| 72 | * rules: [{ Name: "DropAll", Actions: [{ Drop: {} }] }], |
| 73 | * }); |
| 74 | * ``` |
| 75 | * |
| 76 | * **Example:** Conditional Archive |
| 77 | * ```typescript |
| 78 | * const ruleSet = yield* MailManager.RuleSet("Inbound", { |
| 79 | * rules: [ |
| 80 | * { |
| 81 | * Name: "ArchiveLarge", |
| 82 | * Conditions: [ |
| 83 | * { |
| 84 | * NumberExpression: { |
| 85 | * Evaluate: { Attribute: "MESSAGE_SIZE" }, |
| 86 | * Operator: "GREATER_THAN", |
| 87 | * Value: 1024, |
| 88 | * }, |
| 89 | * }, |
| 90 | * ], |
| 91 | * Actions: [{ Archive: { TargetArchive: archive.archiveId } }], |
| 92 | * }, |
| 93 | * ], |
| 94 | * }); |
| 95 | * ``` |
| 96 | * |
| 97 | * ### Wiring to an Ingress Point |
| 98 | * **Example:** Rule Set + Traffic Policy + Ingress Point |
| 99 | * ```typescript |
| 100 | * const ingress = yield* MailManager.IngressPoint("Smtp", { |
| 101 | * type: "OPEN", |
| 102 | * ruleSetId: ruleSet.ruleSetId, |
| 103 | * trafficPolicyId: trafficPolicy.trafficPolicyId, |
| 104 | * }); |
| 105 | * ``` |
| 106 | * |
| 107 | * ### Delivering Email Events to Compute |
| 108 | * **Example:** Invoke a Lambda for Matching Mail |
| 109 | * ```typescript |
| 110 | * // Mail Manager has no EventBridge events or event-source mapping — email |
| 111 | * // events reach compute through rule actions: InvokeLambda (direct), |
| 112 | * // PublishToSns (SNS event source), or WriteToS3 (S3 event source). The |
| 113 | * // role must be assumable by ses.amazonaws.com with lambda:InvokeFunction. |
| 114 | * const ruleSet = yield* MailManager.RuleSet("Inbound", { |
| 115 | * rules: [ |
| 116 | * { |
| 117 | * Name: "NotifyOnMail", |
| 118 | * Actions: [ |
| 119 | * { |
| 120 | * InvokeLambda: { |
| 121 | * FunctionArn: fn.functionArn, |
| 122 | * InvocationType: "EVENT", |
| 123 | * RoleArn: invokeRole.roleArn, |
| 124 | * }, |
| 125 | * }, |
| 126 | * ], |
| 127 | * }, |
| 128 | * ], |
| 129 | * }); |
| 130 | * ``` |
| 131 | * |
| 132 | * @resource |
| 133 | */ |
| 134 | export const RuleSet = Resource<RuleSet>("AWS.MailManager.RuleSet"); |
| 135 | |
| 136 | export const RuleSetProvider = () => |
| 137 | Provider.effect( |
| 138 | RuleSet, |
| 139 | Effect.gen(function* () { |
| 140 | const createName = Effect.fn(function* (id: string, props: { ruleSetName?: string }) { |
| 141 | return props.ruleSetName ?? (yield* createPhysicalName({ id, maxLength: 100 })); |
| 142 | }); |
| 143 | |
| 144 | const getById = (ruleSetId: string) => |
| 145 | mm |
| 146 | .getRuleSet({ RuleSetId: ruleSetId }) |
| 147 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 148 | |
| 149 | // Rule sets have no name-keyed Get — enumerate and match. The physical |
| 150 | // name is deterministic, so this recovers identity after a lost state |
| 151 | // write. |
| 152 | const findByName = (name: string) => |
| 153 | mm.listRuleSets.pages({}).pipe( |
| 154 | Stream.runCollect, |
| 155 | Effect.map((chunk) => |
| 156 | Array.from(chunk) |
| 157 | .flatMap((page) => page.RuleSets ?? []) |
| 158 | .find((r) => r.RuleSetName === name), |
| 159 | ), |
| 160 | ); |
| 161 | |
| 162 | const observe = Effect.fn(function* ( |
| 163 | output: RuleSet["Attributes"] | undefined, |
| 164 | name: string, |
| 165 | ) { |
| 166 | if (output?.ruleSetId !== undefined) { |
| 167 | const found = yield* getById(output.ruleSetId); |
| 168 | if (found !== undefined) return found; |
| 169 | } |
| 170 | const summary = yield* findByName(name); |
| 171 | if (summary?.RuleSetId === undefined) return undefined; |
| 172 | return yield* getById(summary.RuleSetId); |
| 173 | }); |
| 174 | |
| 175 | const toAttrs = (ruleSet: mm.GetRuleSetResponse) => ({ |
| 176 | ruleSetId: ruleSet.RuleSetId, |
| 177 | ruleSetArn: ruleSet.RuleSetArn, |
| 178 | ruleSetName: ruleSet.RuleSetName, |
| 179 | }); |
| 180 | |
| 181 | return RuleSet.Provider.of({ |
| 182 | stables: ["ruleSetId", "ruleSetArn"], |
| 183 | |
| 184 | list: () => |
| 185 | mm.listRuleSets.pages({}).pipe( |
| 186 | Stream.runCollect, |
| 187 | Effect.flatMap((chunk) => |
| 188 | Effect.forEach( |
| 189 | Array.from(chunk) |
| 190 | .flatMap((page) => page.RuleSets ?? []) |
| 191 | .flatMap((r) => (r.RuleSetId !== undefined ? [r.RuleSetId] : [])), |
| 192 | (ruleSetId) => getById(ruleSetId), |
| 193 | ), |
| 194 | ), |
| 195 | Effect.map((results) => results.flatMap((r) => (r === undefined ? [] : [toAttrs(r)]))), |
| 196 | ), |
| 197 | |
| 198 | read: Effect.fn(function* ({ id, olds, output }) { |
| 199 | const name = output?.ruleSetName ?? (yield* createName(id, olds ?? {})); |
| 200 | const ruleSet = yield* observe(output, name); |
| 201 | if (ruleSet === undefined) return undefined; |
| 202 | const attrs = toAttrs(ruleSet); |
| 203 | const tags = yield* readMailManagerTags(attrs.ruleSetArn); |
| 204 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 205 | }), |
| 206 | |
| 207 | // Name and rules both update in place — no replacement triggers, so |
| 208 | // the engine's default update path applies (no diff needed). |
| 209 | |
| 210 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 211 | const name = yield* createName(id, news); |
| 212 | const internalTags = yield* createInternalTags(id); |
| 213 | const desiredTags = { ...news.tags, ...internalTags }; |
| 214 | const desiredRules = news.rules ?? []; |
| 215 | |
| 216 | // 1. OBSERVE — cloud state is authoritative; output is an id cache. |
| 217 | let ruleSet = yield* observe(output, name); |
| 218 | |
| 219 | // 2. ENSURE — create if missing; a Conflict race re-observes by |
| 220 | // name instead of failing. |
| 221 | if (ruleSet === undefined) { |
| 222 | yield* session.note(`creating rule set ${name}`); |
| 223 | const created = yield* mm |
| 224 | .createRuleSet({ |
| 225 | RuleSetName: name, |
| 226 | Rules: desiredRules, |
| 227 | Tags: createTagsList(desiredTags), |
| 228 | }) |
| 229 | .pipe(Effect.catchTag("ConflictException", () => Effect.undefined)); |
| 230 | ruleSet = |
| 231 | created !== undefined |
| 232 | ? yield* getById(created.RuleSetId) |
| 233 | : yield* observe(undefined, name); |
| 234 | } |
| 235 | if (ruleSet === undefined) { |
| 236 | return yield* new RuleSetUnexpectedResponse({ |
| 237 | message: `Mail Manager rule set '${name}' not found after create`, |
| 238 | }); |
| 239 | } |
| 240 | |
| 241 | // 3. SYNC — diff OBSERVED name/rules against desired; apply only |
| 242 | // the delta. |
| 243 | if (ruleSet.RuleSetName !== name || !sameShape(ruleSet.Rules, desiredRules)) { |
| 244 | yield* mm.updateRuleSet({ |
| 245 | RuleSetId: ruleSet.RuleSetId, |
| 246 | RuleSetName: name, |
| 247 | Rules: desiredRules, |
| 248 | }); |
| 249 | } |
| 250 | |
| 251 | // 3b. SYNC TAGS — against observed cloud tags. |
| 252 | yield* syncMailManagerTags(ruleSet.RuleSetArn, desiredTags); |
| 253 | |
| 254 | yield* session.note(ruleSet.RuleSetId); |
| 255 | return { |
| 256 | ruleSetId: ruleSet.RuleSetId, |
| 257 | ruleSetArn: ruleSet.RuleSetArn, |
| 258 | ruleSetName: name, |
| 259 | }; |
| 260 | }), |
| 261 | |
| 262 | delete: Effect.fn(function* ({ output }) { |
| 263 | // DeleteRuleSet is natively idempotent — deleting a nonexistent |
| 264 | // rule set succeeds (verified live by the delete probe test). A |
| 265 | // rule set stays "in use" while a deleted ingress point finishes |
| 266 | // deprovisioning — retry through the Conflict window. |
| 267 | yield* retryWhileMailManagerConflict( |
| 268 | mm.deleteRuleSet({ RuleSetId: output.ruleSetId }), |
| 269 | ).pipe(Effect.asVoid); |
| 270 | }), |
| 271 | }); |
| 272 | }), |
| 273 | ); |