@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 306 lines 10.4 KB
Raw
1 import * as ses from "@distilled.cloud/aws/ses";
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 Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9
10 /**
11 * Whether SES requires (`Require`) or merely prefers (`Optional`) a TLS
12 * connection from the sending mail server before accepting a message that
13 * matches this rule.
14 */
15 export type ReceiptRuleTlsPolicy = ses.TlsPolicy;
16
17 /**
18 * A single receipt-rule action. Pass the distilled action shape directly — one
19 * of `S3Action`, `SNSAction`, `LambdaAction`, `BounceAction`, `AddHeaderAction`,
20 * `StopAction`, `WorkmailAction`, or `ConnectAction`. Actions run in array
21 * order; resource ARNs (bucket, topic, function) are supplied by the caller.
22 */
23 export type ReceiptRuleAction = ses.ReceiptAction;
24
25 export interface ReceiptRuleProps {
26 /**
27 * Name of the receipt rule set this rule belongs to. Typically the
28 * `ruleSetName` output of a `SES.ReceiptRuleSet`. Changing it replaces the
29 * rule.
30 */
31 ruleSetName: string;
32 /**
33 * Name of the receipt rule. May contain letters, numbers, dashes,
34 * underscores and periods, up to 64 characters. If omitted, a deterministic
35 * physical name is generated from the app, stage, and logical ID. Changing
36 * the name replaces the rule.
37 */
38 ruleName?: string;
39 /**
40 * Whether the rule is enabled. Disabled rules are skipped during receipt
41 * processing.
42 * @default true
43 */
44 enabled?: boolean;
45 /**
46 * Whether SES scans incoming messages that match this rule for spam and
47 * viruses.
48 * @default true
49 */
50 scanEnabled?: boolean;
51 /**
52 * Whether SES accepts email over a clear text connection (`Optional`) or
53 * requires TLS (`Require`) before applying this rule.
54 * @default "Optional"
55 */
56 tlsPolicy?: ReceiptRuleTlsPolicy;
57 /**
58 * Recipient email addresses or domains this rule applies to. An empty or
59 * omitted list matches all recipients.
60 */
61 recipients?: string[];
62 /**
63 * Name of an existing rule in the same rule set after which this rule should
64 * be placed. Omit to place the rule at the top of the rule set. Rules are
65 * evaluated in order.
66 */
67 after?: string;
68 /**
69 * Ordered list of actions SES performs when a message matches this rule
70 * (deliver to S3, publish to SNS, invoke Lambda, bounce, add a header, stop
71 * processing, etc.).
72 */
73 actions?: ReceiptRuleAction[];
74 }
75
76 export interface ReceiptRule extends Resource<
77 "AWS.SES.ReceiptRule",
78 ReceiptRuleProps,
79 {
80 /** Name of the rule set this rule belongs to. */
81 ruleSetName: string;
82 /** Name of the receipt rule. */
83 ruleName: string;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An Amazon SES receipt rule — a matcher plus an ordered list of actions that
91 * SES applies to inbound email received through the parent
92 * `SES.ReceiptRuleSet`.
93 *
94 * Actions are passed as the raw distilled action shapes (no marshalling): the
95 * caller supplies bucket names, topic ARNs, and function ARNs directly.
96 * ### Creating Rules
97 * **Example:** Deliver Matching Mail to S3
98 * ```typescript
99 * import * as SES from "@alchemy.run/aws/SES";
100 *
101 * const ruleSet = yield* SES.ReceiptRuleSet("Inbound", {});
102 * const rule = yield* SES.ReceiptRule("ToBucket", {
103 * ruleSetName: ruleSet.ruleSetName,
104 * recipients: ["support@example.com"],
105 * actions: [
106 * { S3Action: { BucketName: "my-inbound-mail" } },
107 * ],
108 * });
109 * ```
110 *
111 * **Example:** Invoke a Lambda and Add a Header
112 * ```typescript
113 * const rule = yield* SES.ReceiptRule("Process", {
114 * ruleSetName: ruleSet.ruleSetName,
115 * tlsPolicy: "Require",
116 * scanEnabled: true,
117 * actions: [
118 * { AddHeaderAction: { HeaderName: "X-Inbound", HeaderValue: "ses" } },
119 * { LambdaAction: { FunctionArn: fn.functionArn, InvocationType: "Event" } },
120 * ],
121 * });
122 * ```
123 *
124 * ### Ordering Rules
125 * **Example:** Place a Rule After Another
126 * ```typescript
127 * // A BounceAction's Sender must be a verified SES identity — SES rejects the
128 * // rule with IdentityNotVerified at create/update time otherwise.
129 * const first = yield* SES.ReceiptRule("First", {
130 * ruleSetName: ruleSet.ruleSetName,
131 * actions: [{ StopAction: { Scope: "RuleSet" } }],
132 * });
133 * const second = yield* SES.ReceiptRule("Second", {
134 * ruleSetName: ruleSet.ruleSetName,
135 * after: first.ruleName,
136 * actions: [{ BounceAction: {
137 * SmtpReplyCode: "550",
138 * Message: "Mailbox does not exist",
139 * Sender: "mailer-daemon@example.com",
140 * } }],
141 * });
142 * ```
143 *
144 * @resource
145 */
146 export const ReceiptRule = Resource<ReceiptRule>("AWS.SES.ReceiptRule");
147
148 /**
149 * The name of the rule immediately preceding `ruleName` in the rule set's
150 * ordered rule list, or `undefined` when the rule is first (or absent). This is
151 * the observed value of the `after` position.
152 */
153 const observedPredecessor = (
154 rules: ReadonlyArray<ses.ReceiptRule>,
155 ruleName: string,
156 ): string | undefined => {
157 const index = rules.findIndex((rule) => rule.Name === ruleName);
158 if (index <= 0) return undefined;
159 return rules[index - 1]?.Name;
160 };
161
162 /**
163 * An IAM role can exist before SES is able to assume it, so create and
164 * update retry that specific rejection while the role propagates.
165 */
166 const retryRolePropagation = <A, R>(
167 effect: Effect.Effect<A, ses.CreateReceiptRuleError | ses.UpdateReceiptRuleError, R>,
168 ) =>
169 effect.pipe(
170 Effect.retry({
171 while: (e) => e._tag === "ReceiptRuleRoleNotAssumable",
172 schedule: Schedule.spaced("5 seconds"),
173 times: 12,
174 }),
175 );
176
177 export const ReceiptRuleProvider = () =>
178 Provider.effect(
179 ReceiptRule,
180 Effect.gen(function* () {
181 const createName = Effect.fn(function* (
182 id: string,
183 props: Pick<ReceiptRuleProps, "ruleName">,
184 ) {
185 return props.ruleName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
186 });
187
188 const describeRule = Effect.fn(function* (ruleSetName: string, ruleName: string) {
189 return yield* ses
190 .describeReceiptRule({ RuleSetName: ruleSetName, RuleName: ruleName })
191 .pipe(
192 Effect.catchTags({
193 RuleDoesNotExistException: () => Effect.undefined,
194 RuleSetDoesNotExistException: () => Effect.undefined,
195 }),
196 );
197 });
198
199 const buildRule = (ruleName: string, props: ReceiptRuleProps): ses.ReceiptRule => ({
200 Name: ruleName,
201 // The classic API defaults an omitted Enabled/ScanEnabled to FALSE —
202 // apply the documented defaults explicitly so an undeclared rule is
203 // enabled (a silently disabled rule bounces all inbound mail).
204 Enabled: props.enabled ?? true,
205 TlsPolicy: props.tlsPolicy,
206 Recipients: props.recipients,
207 Actions: props.actions,
208 ScanEnabled: props.scanEnabled ?? true,
209 });
210
211 return ReceiptRule.Provider.of({
212 stables: ["ruleSetName", "ruleName"],
213
214 // Rules are sub-resources keyed entirely by their parent rule set;
215 // there is no flat account-level enumeration, so nuke handles them via
216 // the parent rule set's deletion.
217 list: () => Effect.succeed([]),
218
219 read: Effect.fn(function* ({ id, olds, output }) {
220 const ruleSetName = output?.ruleSetName ?? olds.ruleSetName;
221 if (!ruleSetName) return undefined;
222 const ruleName = output?.ruleName ?? (yield* createName(id, olds));
223 const found = yield* describeRule(ruleSetName, ruleName);
224 return found?.Rule ? { ruleSetName, ruleName } : undefined;
225 }),
226
227 diff: Effect.fn(function* ({ id, news, olds }) {
228 if (!isResolved(news)) return undefined;
229 if (news.ruleSetName !== olds.ruleSetName) {
230 return { action: "replace" } as const;
231 }
232 const oldName = yield* createName(id, olds);
233 const newName = yield* createName(id, news);
234 if (oldName !== newName) {
235 return { action: "replace" } as const;
236 }
237 }),
238
239 reconcile: Effect.fn(function* ({ id, news, output }) {
240 const ruleSetName = news.ruleSetName;
241 const ruleName = output?.ruleName ?? (yield* createName(id, news));
242 const rule = buildRule(ruleName, news);
243
244 // OBSERVE — cloud state is authoritative.
245 const observed = yield* describeRule(ruleSetName, ruleName);
246
247 // ENSURE / SYNC — a single full-replace call converges the rule's
248 // matcher and actions whether it is missing or already present.
249 if (observed?.Rule === undefined) {
250 yield* ses
251 .createReceiptRule({
252 RuleSetName: ruleSetName,
253 After: news.after,
254 Rule: rule,
255 })
256 .pipe(
257 retryRolePropagation,
258 Effect.catchTag("AlreadyExistsException", () =>
259 ses
260 .updateReceiptRule({
261 RuleSetName: ruleSetName,
262 Rule: rule,
263 })
264 .pipe(retryRolePropagation),
265 ),
266 );
267 } else {
268 yield* ses
269 .updateReceiptRule({
270 RuleSetName: ruleSetName,
271 Rule: rule,
272 })
273 .pipe(retryRolePropagation);
274 }
275
276 // SYNC POSITION — updateReceiptRule never moves the rule, so diff the
277 // observed predecessor against the desired `after` and reposition
278 // only on a mismatch.
279 const ruleSet = yield* ses.describeReceiptRuleSet({
280 RuleSetName: ruleSetName,
281 });
282 const predecessor = observedPredecessor(ruleSet.Rules ?? [], ruleName);
283 if (predecessor !== news.after) {
284 yield* ses.setReceiptRulePosition({
285 RuleSetName: ruleSetName,
286 RuleName: ruleName,
287 After: news.after,
288 });
289 }
290
291 return { ruleSetName, ruleName };
292 }),
293
294 delete: Effect.fn(function* ({ output }) {
295 // deleteReceiptRule is idempotent for a missing rule; a missing rule
296 // set means the rule is already gone.
297 yield* ses
298 .deleteReceiptRule({
299 RuleSetName: output.ruleSetName,
300 RuleName: output.ruleName,
301 })
302 .pipe(Effect.catchTag("RuleSetDoesNotExistException", () => Effect.void));
303 }),
304 });
305 }),
306 );