The best way to control Claude Code, Codex and more from any computer or phone

main
ts 266 lines 9.28 KB
Raw
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 TrafficPolicyUnexpectedResponse extends Data.TaggedError(
19 "TrafficPolicyUnexpectedResponse",
20 )<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export interface TrafficPolicyProps {
26 /**
27 * Name of the traffic policy. If omitted, a deterministic physical name is
28 * generated from the app, stage, and logical ID. Renames apply in place.
29 */
30 trafficPolicyName?: string;
31 /**
32 * Conditional statements evaluated against incoming SMTP connections and
33 * message metadata (sender IP, recipient, TLS protocol, analyzer verdicts,
34 * address-list membership). Each statement ALLOWs or DENYs matching
35 * traffic. Updates apply in place.
36 * @default []
37 */
38 policyStatements?: mm.PolicyStatement[];
39 /**
40 * Action applied to traffic that matches no policy statement.
41 */
42 defaultAction: mm.AcceptAction;
43 /**
44 * Maximum message size in bytes; larger messages are rejected.
45 */
46 maxMessageSizeBytes?: number;
47 /**
48 * Tags applied to the traffic policy. Alchemy ownership tags are merged in
49 * automatically.
50 */
51 tags?: Record<string, string>;
52 }
53
54 export interface TrafficPolicy extends Resource<
55 "AWS.MailManager.TrafficPolicy",
56 TrafficPolicyProps,
57 {
58 /** Server-assigned ID of the traffic policy. */
59 trafficPolicyId: string;
60 /** ARN of the traffic policy. */
61 trafficPolicyArn: string;
62 /** Name of the traffic policy. */
63 trafficPolicyName: string;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * An SES Mail Manager traffic policy — connection-level ALLOW/DENY rules an
71 * ingress point applies before email reaches the rule set (sender CIDRs,
72 * recipient patterns, TLS floor, message size cap).
73 *
74 * All aspects (name, statements, default action, size cap, tags) update in
75 * place.
76 * ### Creating Traffic Policies
77 * **Example:** Deny-by-Default with an Allowed CIDR
78 * ```typescript
79 * import * as MailManager from "@alchemy.run/aws/MailManager";
80 *
81 * const policy = yield* MailManager.TrafficPolicy("Edge", {
82 * defaultAction: "DENY",
83 * policyStatements: [
84 * {
85 * Action: "ALLOW",
86 * Conditions: [
87 * {
88 * IpExpression: {
89 * Evaluate: { Attribute: "SENDER_IP" },
90 * Operator: "CIDR_MATCHES",
91 * Values: ["10.0.0.0/8"],
92 * },
93 * },
94 * ],
95 * },
96 * ],
97 * });
98 * ```
99 *
100 * **Example:** Allow All with a Size Cap
101 * ```typescript
102 * const policy = yield* MailManager.TrafficPolicy("Edge", {
103 * defaultAction: "ALLOW",
104 * maxMessageSizeBytes: 10 * 1024 * 1024,
105 * });
106 * ```
107 *
108 * @resource
109 */
110 export const TrafficPolicy = Resource<TrafficPolicy>("AWS.MailManager.TrafficPolicy");
111
112 export const TrafficPolicyProvider = () =>
113 Provider.effect(
114 TrafficPolicy,
115 Effect.gen(function* () {
116 const createName = Effect.fn(function* (id: string, props: { trafficPolicyName?: string }) {
117 return props.trafficPolicyName ?? (yield* createPhysicalName({ id, maxLength: 63 }));
118 });
119
120 const getById = (trafficPolicyId: string) =>
121 mm
122 .getTrafficPolicy({ TrafficPolicyId: trafficPolicyId })
123 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
124
125 const findByName = (name: string) =>
126 mm.listTrafficPolicies.pages({}).pipe(
127 Stream.runCollect,
128 Effect.map((chunk) =>
129 Array.from(chunk)
130 .flatMap((page) => page.TrafficPolicies ?? [])
131 .find((p) => p.TrafficPolicyName === name),
132 ),
133 );
134
135 const observe = Effect.fn(function* (
136 output: TrafficPolicy["Attributes"] | undefined,
137 name: string,
138 ) {
139 if (output?.trafficPolicyId !== undefined) {
140 const found = yield* getById(output.trafficPolicyId);
141 if (found !== undefined) return found;
142 }
143 const summary = yield* findByName(name);
144 if (summary?.TrafficPolicyId === undefined) return undefined;
145 return yield* getById(summary.TrafficPolicyId);
146 });
147
148 const toAttrs = Effect.fn(function* (policy: mm.GetTrafficPolicyResponse) {
149 if (policy.TrafficPolicyArn === undefined) {
150 return yield* new TrafficPolicyUnexpectedResponse({
151 message: `Mail Manager traffic policy '${policy.TrafficPolicyId}' returned without an ARN`,
152 });
153 }
154 return {
155 trafficPolicyId: policy.TrafficPolicyId,
156 trafficPolicyArn: policy.TrafficPolicyArn,
157 trafficPolicyName: policy.TrafficPolicyName,
158 };
159 });
160
161 return TrafficPolicy.Provider.of({
162 stables: ["trafficPolicyId", "trafficPolicyArn"],
163
164 list: () =>
165 mm.listTrafficPolicies.pages({}).pipe(
166 Stream.runCollect,
167 Effect.flatMap((chunk) =>
168 Effect.forEach(
169 Array.from(chunk)
170 .flatMap((page) => page.TrafficPolicies ?? [])
171 .flatMap((p) => (p.TrafficPolicyId !== undefined ? [p.TrafficPolicyId] : [])),
172 (trafficPolicyId) => getById(trafficPolicyId),
173 ),
174 ),
175 Effect.flatMap((results) =>
176 Effect.forEach(
177 results.flatMap((p) => (p === undefined ? [] : [p])),
178 (p) => toAttrs(p),
179 ),
180 ),
181 ),
182
183 read: Effect.fn(function* ({ id, olds, output }) {
184 const name = output?.trafficPolicyName ?? (yield* createName(id, olds ?? {}));
185 const policy = yield* observe(output, name);
186 if (policy === undefined) return undefined;
187 const attrs = yield* toAttrs(policy);
188 const tags = yield* readMailManagerTags(attrs.trafficPolicyArn);
189 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
190 }),
191
192 // Every prop updates in place — no replacement triggers, so the
193 // engine's default update path applies (no diff needed).
194
195 reconcile: Effect.fn(function* ({ id, news, output, session }) {
196 const name = yield* createName(id, news);
197 const internalTags = yield* createInternalTags(id);
198 const desiredTags = { ...news.tags, ...internalTags };
199 const desiredStatements = news.policyStatements ?? [];
200
201 // 1. OBSERVE.
202 let policy = yield* observe(output, name);
203
204 // 2. ENSURE — create if missing; a Conflict race re-observes.
205 if (policy === undefined) {
206 yield* session.note(`creating traffic policy ${name}`);
207 const created = yield* mm
208 .createTrafficPolicy({
209 TrafficPolicyName: name,
210 PolicyStatements: desiredStatements,
211 DefaultAction: news.defaultAction,
212 MaxMessageSizeBytes: news.maxMessageSizeBytes,
213 Tags: createTagsList(desiredTags),
214 })
215 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
216 policy =
217 created !== undefined
218 ? yield* getById(created.TrafficPolicyId)
219 : yield* observe(undefined, name);
220 }
221 if (policy === undefined) {
222 return yield* new TrafficPolicyUnexpectedResponse({
223 message: `Mail Manager traffic policy '${name}' not found after create`,
224 });
225 }
226
227 // 3. SYNC — diff OBSERVED state against desired; apply only the
228 // delta.
229 if (
230 policy.TrafficPolicyName !== name ||
231 policy.DefaultAction !== news.defaultAction ||
232 policy.MaxMessageSizeBytes !== news.maxMessageSizeBytes ||
233 !sameShape(policy.PolicyStatements ?? [], desiredStatements)
234 ) {
235 yield* mm.updateTrafficPolicy({
236 TrafficPolicyId: policy.TrafficPolicyId,
237 TrafficPolicyName: name,
238 PolicyStatements: desiredStatements,
239 DefaultAction: news.defaultAction,
240 MaxMessageSizeBytes: news.maxMessageSizeBytes,
241 });
242 }
243
244 // 3b. SYNC TAGS.
245 const attrs = yield* toAttrs(policy);
246 yield* syncMailManagerTags(attrs.trafficPolicyArn, desiredTags);
247
248 yield* session.note(attrs.trafficPolicyId);
249 return { ...attrs, trafficPolicyName: name };
250 }),
251
252 delete: Effect.fn(function* ({ output }) {
253 // A traffic policy stays "in use" while a deleted ingress point
254 // finishes deprovisioning — retry through the Conflict window.
255 yield* retryWhileMailManagerConflict(
256 mm.deleteTrafficPolicy({
257 TrafficPolicyId: output.trafficPolicyId,
258 }),
259 ).pipe(
260 Effect.asVoid,
261 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
262 );
263 }),
264 });
265 }),
266 );