@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 353 lines 13.3 KB
Raw
1 import * as mm from "@distilled.cloud/aws/mailmanager";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 readMailManagerTags,
14 repeatUntilMailManagerStable,
15 retryWhileMailManagerConflict,
16 sameShape,
17 syncMailManagerTags,
18 } from "./internal.ts";
19
20 export class IngressPointUnexpectedResponse extends Data.TaggedError(
21 "IngressPointUnexpectedResponse",
22 )<{
23 readonly message: string;
24 readonly cause?: unknown;
25 }> {}
26
27 export interface IngressPointProps {
28 /**
29 * Name of the ingress point. If omitted, a deterministic physical name is
30 * generated from the app, stage, and logical ID. Renames apply in place.
31 */
32 ingressPointName?: string;
33 /**
34 * Type of the ingress endpoint: `OPEN` accepts unauthenticated SMTP;
35 * `AUTH` requires SMTP AUTH credentials (see
36 * {@link IngressPointProps.ingressPointConfiguration}); `MTLS` requires
37 * client certificates. Immutable — changing the type replaces the ingress
38 * point.
39 */
40 type: mm.IngressPointType;
41 /**
42 * ID of the rule set applied to email arriving through this ingress
43 * point. Updates apply in place.
44 */
45 ruleSetId: string;
46 /**
47 * ID of the traffic policy evaluated against connections to this ingress
48 * point. Updates apply in place.
49 */
50 trafficPolicyId: string;
51 /**
52 * Authentication configuration for `AUTH`/`MTLS` ingress points: an SMTP
53 * password, a Secrets Manager secret ARN, or a TLS trust store. Updates
54 * apply in place.
55 */
56 ingressPointConfiguration?: mm.IngressPointConfiguration;
57 /**
58 * Network configuration: public (with IP type) or VPC-endpoint private.
59 * Immutable — changing it replaces the ingress point.
60 * @default public IPV4
61 */
62 networkConfiguration?: mm.NetworkConfiguration;
63 /**
64 * TLS policy for inbound connections: `REQUIRED`, `OPTIONAL`, or `FIPS`.
65 * Omitting it applies AWS's `FIPS` default. Changes between `REQUIRED` and
66 * `OPTIONAL` update in place; AWS rejects updates from or to `FIPS`
67 * (including the omitted default), so those transitions replace the
68 * ingress point.
69 */
70 tlsPolicy?: mm.TlsPolicy;
71 /**
72 * Tags applied to the ingress point. Alchemy ownership tags are merged in
73 * automatically.
74 */
75 tags?: Record<string, string>;
76 }
77
78 export interface IngressPoint extends Resource<
79 "AWS.MailManager.IngressPoint",
80 IngressPointProps,
81 {
82 /** Server-assigned ID of the ingress point. */
83 ingressPointId: string;
84 /** ARN of the ingress point. */
85 ingressPointArn: string;
86 /** Name of the ingress point. */
87 ingressPointName: string;
88 /** DNS A record (SMTP endpoint host) of the ingress point. */
89 aRecord: string | undefined;
90 /** Current status (PROVISIONING, ACTIVE, CLOSED, FAILED, ...). */
91 status: string | undefined;
92 },
93 never,
94 Providers
95 > {}
96
97 /**
98 * An SES Mail Manager ingress point — the SMTP endpoint that receives
99 * incoming email, screens it with a traffic policy, and processes it with a
100 * rule set.
101 *
102 * `type` and `networkConfiguration` are immutable (changes replace the
103 * endpoint); everything else updates in place.
104 * ### Creating Ingress Points
105 * **Example:** Open Ingress Point
106 * ```typescript
107 * import * as MailManager from "@alchemy.run/aws/MailManager";
108 *
109 * const ruleSet = yield* MailManager.RuleSet("Inbound", {
110 * rules: [{ Name: "DropAll", Actions: [{ Drop: {} }] }],
111 * });
112 * const trafficPolicy = yield* MailManager.TrafficPolicy("Edge", {
113 * defaultAction: "ALLOW",
114 * });
115 * const ingress = yield* MailManager.IngressPoint("Smtp", {
116 * type: "OPEN",
117 * ruleSetId: ruleSet.ruleSetId,
118 * trafficPolicyId: trafficPolicy.trafficPolicyId,
119 * });
120 * // point your domain's MX record at ingress.aRecord
121 * ```
122 *
123 * **Example:** Authenticated Ingress Point
124 * ```typescript
125 * const ingress = yield* MailManager.IngressPoint("Smtp", {
126 * type: "AUTH",
127 * ruleSetId: ruleSet.ruleSetId,
128 * trafficPolicyId: trafficPolicy.trafficPolicyId,
129 * ingressPointConfiguration: { SecretArn: secret.secretArn },
130 * tlsPolicy: "REQUIRED",
131 * });
132 * ```
133 *
134 * @resource
135 */
136 export const IngressPoint = Resource<IngressPoint>("AWS.MailManager.IngressPoint");
137
138 export const IngressPointProvider = () =>
139 Provider.effect(
140 IngressPoint,
141 Effect.gen(function* () {
142 const createName = Effect.fn(function* (id: string, props: { ingressPointName?: string }) {
143 return (
144 props.ingressPointName ??
145 (yield* createPhysicalName({ id, maxLength: 63, lowercase: true }))
146 );
147 });
148
149 const getById = (ingressPointId: string) =>
150 mm
151 .getIngressPoint({ IngressPointId: ingressPointId })
152 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
153
154 const findByName = (name: string) =>
155 mm.listIngressPoints.pages({}).pipe(
156 Stream.runCollect,
157 Effect.map((chunk) =>
158 Array.from(chunk)
159 .flatMap((page) => page.IngressPoints ?? [])
160 .find((p) => p.IngressPointName === name),
161 ),
162 );
163
164 const observe = Effect.fn(function* (
165 output: IngressPoint["Attributes"] | undefined,
166 name: string,
167 ) {
168 if (output?.ingressPointId !== undefined) {
169 const found = yield* getById(output.ingressPointId);
170 if (found !== undefined) return found;
171 }
172 const summary = yield* findByName(name);
173 if (summary?.IngressPointId === undefined) return undefined;
174 return yield* getById(summary.IngressPointId);
175 });
176
177 // Provisioning/updating is asynchronous — wait (bounded, ~2 min) for
178 // the endpoint to leave its transitional state before mutating it.
179 const waitForStable = (ingressPointId: string) =>
180 repeatUntilMailManagerStable(
181 getById(ingressPointId),
182 (r) => r === undefined || (r.Status !== "PROVISIONING" && r.Status !== "UPDATING"),
183 );
184
185 const toAttrs = Effect.fn(function* (ingress: mm.GetIngressPointResponse) {
186 if (ingress.IngressPointArn === undefined) {
187 return yield* new IngressPointUnexpectedResponse({
188 message: `Mail Manager ingress point '${ingress.IngressPointId}' returned without an ARN`,
189 });
190 }
191 return {
192 ingressPointId: ingress.IngressPointId,
193 ingressPointArn: ingress.IngressPointArn,
194 ingressPointName: ingress.IngressPointName,
195 aRecord: ingress.ARecord,
196 status: ingress.Status,
197 };
198 });
199
200 return IngressPoint.Provider.of({
201 stables: ["ingressPointId", "ingressPointArn"],
202
203 list: () =>
204 mm.listIngressPoints.pages({}).pipe(
205 Stream.runCollect,
206 Effect.flatMap((chunk) =>
207 Effect.forEach(
208 Array.from(chunk)
209 .flatMap((page) => page.IngressPoints ?? [])
210 .map((p) => p.IngressPointId),
211 (ingressPointId) => getById(ingressPointId),
212 ),
213 ),
214 Effect.flatMap((results) =>
215 Effect.forEach(
216 results.flatMap((p) => (p === undefined ? [] : [p])),
217 (p) => toAttrs(p),
218 ),
219 ),
220 ),
221
222 read: Effect.fn(function* ({ id, olds, output }) {
223 const name = output?.ingressPointName ?? (yield* createName(id, olds ?? {}));
224 const ingress = yield* observe(output, name);
225 if (ingress === undefined) return undefined;
226 const attrs = yield* toAttrs(ingress);
227 const tags = yield* readMailManagerTags(attrs.ingressPointArn);
228 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
229 }),
230
231 // `type` and `networkConfiguration` are create-only — changing
232 // either replaces the ingress point. TlsPolicy transitions from or
233 // to FIPS (including the omitted-default, which AWS creates as
234 // FIPS) are rejected by UpdateIngressPoint, so they replace too.
235 diff: Effect.fn(function* ({ news, olds }) {
236 if (!isResolved(news)) return undefined;
237 if (olds === undefined) return undefined;
238 if (olds.type !== news.type) {
239 return { action: "replace" } as const;
240 }
241 if (!sameShape(olds.networkConfiguration, news.networkConfiguration)) {
242 return { action: "replace" } as const;
243 }
244 if (olds.tlsPolicy !== news.tlsPolicy) {
245 const fipsInvolved =
246 olds.tlsPolicy === undefined ||
247 news.tlsPolicy === undefined ||
248 olds.tlsPolicy === "FIPS" ||
249 news.tlsPolicy === "FIPS";
250 if (fipsInvolved) return { action: "replace" } as const;
251 }
252 }),
253
254 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
255 const name = yield* createName(id, news);
256 const internalTags = yield* createInternalTags(id);
257 const desiredTags = { ...news.tags, ...internalTags };
258
259 // 1. OBSERVE.
260 let ingress = yield* observe(output, name);
261
262 // 2. ENSURE — create if missing; a Conflict race re-observes.
263 if (ingress === undefined) {
264 yield* session.note(`creating ingress point ${name}`);
265 const created = yield* mm
266 .createIngressPoint({
267 IngressPointName: name,
268 Type: news.type,
269 RuleSetId: news.ruleSetId,
270 TrafficPolicyId: news.trafficPolicyId,
271 IngressPointConfiguration: news.ingressPointConfiguration,
272 NetworkConfiguration: news.networkConfiguration,
273 TlsPolicy: news.tlsPolicy,
274 Tags: createTagsList(desiredTags),
275 })
276 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
277 ingress =
278 created !== undefined
279 ? yield* getById(created.IngressPointId)
280 : yield* observe(undefined, name);
281 }
282 if (ingress === undefined) {
283 return yield* new IngressPointUnexpectedResponse({
284 message: `Mail Manager ingress point '${name}' not found after create`,
285 });
286 }
287
288 // Provisioning is asynchronous — settle before mutating.
289 const settled = yield* waitForStable(ingress.IngressPointId);
290 ingress = settled ?? ingress;
291
292 // 3. SYNC — diff OBSERVED state against desired. The auth
293 // configuration is write-only (the Get response only exposes
294 // password versions / secret ARN), so `olds` is used as a hint
295 // to push it when the prop changed.
296 const configChanged =
297 news.ingressPointConfiguration !== undefined &&
298 !sameShape(olds?.ingressPointConfiguration, news.ingressPointConfiguration);
299 // AWS rejects any update from or to FIPS — those transitions go
300 // through replacement (see diff), so only non-FIPS deltas are
301 // pushed here.
302 const tlsChanged =
303 news.tlsPolicy !== undefined &&
304 news.tlsPolicy !== "FIPS" &&
305 ingress.TlsPolicy !== "FIPS" &&
306 ingress.TlsPolicy !== news.tlsPolicy;
307 if (
308 ingress.IngressPointName !== name ||
309 ingress.RuleSetId !== news.ruleSetId ||
310 ingress.TrafficPolicyId !== news.trafficPolicyId ||
311 tlsChanged ||
312 configChanged
313 ) {
314 yield* mm.updateIngressPoint({
315 IngressPointId: ingress.IngressPointId,
316 IngressPointName: name,
317 RuleSetId: news.ruleSetId,
318 TrafficPolicyId: news.trafficPolicyId,
319 IngressPointConfiguration: configChanged ? news.ingressPointConfiguration : undefined,
320 TlsPolicy: tlsChanged ? news.tlsPolicy : undefined,
321 });
322 const updated = yield* waitForStable(ingress.IngressPointId);
323 ingress = updated ?? ingress;
324 }
325
326 // 3b. SYNC TAGS.
327 const attrs = yield* toAttrs(ingress);
328 yield* syncMailManagerTags(attrs.ingressPointArn, desiredTags);
329
330 yield* session.note(attrs.ingressPointId);
331 return { ...attrs, ingressPointName: name };
332 }),
333
334 delete: Effect.fn(function* ({ output }) {
335 // Deleting mid-provision conflicts — retry through the window.
336 yield* retryWhileMailManagerConflict(
337 mm.deleteIngressPoint({ IngressPointId: output.ingressPointId }),
338 ).pipe(
339 Effect.asVoid,
340 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
341 );
342 // Deprovisioning is asynchronous and the endpoint keeps its rule
343 // set and traffic policy "in use" until it is fully gone — wait
344 // (bounded, ~3 min) so dependent deletes don't conflict.
345 yield* repeatUntilMailManagerStable(
346 getById(output.ingressPointId),
347 (r) => r === undefined,
348 36,
349 );
350 }),
351 });
352 }),
353 );