@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 300 lines 11.9 KB
Raw
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 Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 /**
15 * The pool's scaling mode. `STANDARD` pools use a fixed set of dedicated IPs
16 * you request and warm up yourself; `MANAGED` pools let SES automatically
17 * scale the dedicated IP capacity for you.
18 */
19 export type DedicatedIpPoolScalingMode = sesv2.ScalingMode;
20
21 export interface DedicatedIpPoolProps {
22 /**
23 * Name of the dedicated IP pool. May contain lowercase letters, numbers and
24 * dashes, up to 64 characters. If omitted, a deterministic lowercase
25 * physical name is generated from the app, stage, and logical ID. Changing
26 * the name replaces the pool.
27 */
28 poolName?: string;
29 /**
30 * The pool's scaling mode. Switching `STANDARD` → `MANAGED` is applied in
31 * place via `putDedicatedIpPoolScalingAttributes`; AWS does not support
32 * `MANAGED` → `STANDARD`, so that direction replaces the pool.
33 * @default "STANDARD"
34 */
35 scalingMode?: DedicatedIpPoolScalingMode;
36 /**
37 * Tags to apply to the pool. Merged with internal Alchemy tags.
38 */
39 tags?: Record<string, string>;
40 }
41
42 export interface DedicatedIpPool extends Resource<
43 "AWS.SES.DedicatedIpPool",
44 DedicatedIpPoolProps,
45 {
46 /** Name of the dedicated IP pool. */
47 poolName: string;
48 /** The pool's scaling mode. */
49 scalingMode: DedicatedIpPoolScalingMode;
50 },
51 never,
52 Providers
53 > {}
54
55 /**
56 * An Amazon SES v2 dedicated IP pool — a named group of dedicated IP addresses
57 * used to send email, so you can isolate the sending reputation of different
58 * kinds of mail (e.g. marketing vs. transactional).
59 *
60 * :::caution
61 * Creating a dedicated IP pool provisions dedicated IP capacity and **starts
62 * billing immediately** — `MANAGED` pools bill for managed dedicated IP usage
63 * as soon as they exist, and `STANDARD` pools bill per dedicated IP you add.
64 * Only create pools you intend to pay for.
65 * :::
66 *
67 * `STANDARD` → `MANAGED` is an in-place scaling change. `MANAGED` → `STANDARD`
68 * is not supported by AWS and replaces the pool.
69 * ### Creating Pools
70 * **Example:** Standard Pool
71 * ```typescript
72 * import * as SES from "@alchemy.run/aws/SES";
73 *
74 * const pool = yield* SES.DedicatedIpPool("Marketing", {
75 * scalingMode: "STANDARD",
76 * });
77 * ```
78 *
79 * **Example:** Managed Pool
80 * ```typescript
81 * const pool = yield* SES.DedicatedIpPool("Transactional", {
82 * scalingMode: "MANAGED",
83 * });
84 * ```
85 *
86 * **Example:** Explicit Pool Name
87 * ```typescript
88 * // Without poolName a deterministic lowercase name is derived from
89 * // app/stage/id. Pool names allow lowercase letters, numbers, and dashes.
90 * const pool = yield* SES.DedicatedIpPool("Marketing", {
91 * poolName: "acme-marketing",
92 * });
93 * ```
94 *
95 * ### Changing the Scaling Mode
96 * **Example:** Migrate a Standard Pool to Managed
97 * ```typescript
98 * // STANDARD -> MANAGED is applied in place — the pool keeps its name and
99 * // its dedicated IPs.
100 * const pool = yield* SES.DedicatedIpPool("Marketing", {
101 * scalingMode: "MANAGED", // was "STANDARD"
102 * });
103 *
104 * // MANAGED -> STANDARD has no AWS API, so it REPLACES the pool: a new pool
105 * // is created and the old one deleted, dropping its dedicated IPs.
106 * ```
107 *
108 * ### Isolating Reputation
109 * **Example:** Separate Marketing and Transactional Reputation
110 * ```typescript
111 * // Give each kind of mail its own pool so a marketing reputation hit
112 * // cannot take down password resets.
113 * const marketing = yield* SES.DedicatedIpPool("Marketing", {
114 * scalingMode: "STANDARD",
115 * });
116 * const transactional = yield* SES.DedicatedIpPool("Transactional", {
117 * scalingMode: "MANAGED",
118 * });
119 * ```
120 *
121 * @resource
122 */
123 export const DedicatedIpPool = Resource<DedicatedIpPool>("AWS.SES.DedicatedIpPool");
124
125 const DEFAULT_SCALING_MODE = "STANDARD" as const;
126
127 const toTagRecord = (
128 tags: ReadonlyArray<{ Key: string; Value: string }> | undefined,
129 ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value]));
130
131 // Dedicated IP pools are taggable but their API never returns an ARN — not
132 // from getDedicatedIpPool, not from listDedicatedIpPools — so the ARN that
133 // listTagsForResource requires has to be derived.
134 const dedicatedIpPoolArnOf = (region: string, accountId: string, name: string) =>
135 `arn:aws:ses:${region}:${accountId}:dedicated-ip-pool/${name}`;
136
137 export const DedicatedIpPoolProvider = () =>
138 Provider.effect(
139 DedicatedIpPool,
140 Effect.gen(function* () {
141 const createName = Effect.fn(function* (
142 id: string,
143 props: Pick<DedicatedIpPoolProps, "poolName">,
144 ) {
145 return (
146 props.poolName ?? (yield* createPhysicalName({ id, maxLength: 64, lowercase: true }))
147 );
148 });
149
150 const getPool = Effect.fn(function* (name: string) {
151 return yield* sesv2.getDedicatedIpPool({ PoolName: name }).pipe(
152 Effect.map((response) => response.DedicatedIpPool),
153 Effect.catchTag("NotFoundException", () => Effect.undefined),
154 );
155 });
156
157 // getDedicatedIpPool does not return tags, so ownership costs a second
158 // API call. Only `read` pays it — `list` deletes by name and does not
159 // need to know who owns a pool.
160 const getPoolTags = Effect.fn(function* (name: string) {
161 const { accountId, region } = yield* AWSEnvironment.current;
162 return yield* sesv2
163 .listTagsForResource({
164 ResourceArn: dedicatedIpPoolArnOf(region, accountId, name),
165 })
166 .pipe(
167 Effect.map((response) => toTagRecord(response.Tags)),
168 // The pool went away between the two calls.
169 Effect.catchTag("NotFoundException", () =>
170 Effect.succeed({} as Record<string, string>),
171 ),
172 );
173 });
174
175 return DedicatedIpPool.Provider.of({
176 stables: ["poolName"],
177
178 // Account/region-scoped: enumerate every pool so leaked test resources
179 // are cleaned by nuke.
180 //
181 // listDedicatedIpPools returns names only, so the real ScalingMode
182 // needs a read per pool — `list` must produce the same Attributes
183 // shape as `read`, and reporting every pool as STANDARD would
184 // misdescribe a MANAGED one. Pools that vanish mid-walk drop out.
185 list: Effect.fn(function* () {
186 const pages = yield* sesv2.listDedicatedIpPools.pages({}).pipe(Stream.runCollect);
187 const poolNames = Array.from(pages).flatMap((page) => page.DedicatedIpPools ?? []);
188 const pools = yield* Effect.forEach(
189 poolNames,
190 (poolName) =>
191 getPool(poolName).pipe(
192 Effect.map((pool) => (pool ? [{ poolName, scalingMode: pool.ScalingMode }] : [])),
193 ),
194 { concurrency: 2 },
195 );
196 return pools.flat();
197 }),
198
199 read: Effect.fn(function* ({ id, olds, output }) {
200 const name = output?.poolName ?? (yield* createName(id, olds ?? {}));
201 const found = yield* getPool(name);
202 if (!found) return undefined;
203 const attrs = { poolName: name, scalingMode: found.ScalingMode };
204 // A pool provisions billable dedicated IP capacity, and reconcile
205 // brands the ones it creates with internal tags. So existence at our
206 // deterministic name is NOT proof of ownership — a pre-existing pool
207 // someone else pays for must be adopted deliberately (`--adopt` /
208 // `adopt(true)`) rather than silently taken over.
209 const tags = yield* getPoolTags(name);
210 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
211 }),
212
213 diff: Effect.fn(function* ({ id, news, olds }) {
214 if (!isResolved(news)) return undefined;
215 const oldName = yield* createName(id, olds ?? {});
216 const newName = yield* createName(id, news ?? {});
217 const oldMode = olds?.scalingMode ?? DEFAULT_SCALING_MODE;
218 const newMode = news?.scalingMode ?? DEFAULT_SCALING_MODE;
219 // A rename replaces the pool. So does a MANAGED → STANDARD switch,
220 // which AWS has no API to perform in place (STANDARD → MANAGED is a
221 // supported in-place scaling change, handled in reconcile).
222 if (oldName !== newName || (oldMode === "MANAGED" && newMode === "STANDARD")) {
223 return { action: "replace" } as const;
224 }
225 }),
226
227 reconcile: Effect.fn(function* ({ id, news, output }) {
228 const name = output?.poolName ?? (yield* createName(id, news));
229 const desiredMode = news.scalingMode ?? DEFAULT_SCALING_MODE;
230 const internalTags = yield* createInternalTags(id);
231 const desiredTags = { ...news.tags, ...internalTags };
232
233 // 1. OBSERVE — cloud state is authoritative.
234 let observed = yield* getPool(name);
235
236 if (observed === undefined) {
237 // 2. ENSURE — create with the desired scaling mode, branding the
238 // pool with internal tags. AlreadyExists is a race, not a
239 // failure.
240 yield* sesv2
241 .createDedicatedIpPool({
242 PoolName: name,
243 ScalingMode: desiredMode,
244 Tags: createTagsList(desiredTags),
245 })
246 .pipe(Effect.catchTag("AlreadyExistsException", () => Effect.succeed({})));
247 // Not always readable the instant create returns, and on the
248 // AlreadyExists race another writer may still be mid-create.
249 observed = yield* getPool(name).pipe(
250 Effect.repeat({
251 schedule: Schedule.spaced("1 second"),
252 until: (pool) => pool !== undefined,
253 times: 8,
254 }),
255 );
256 }
257
258 // 3. SYNC — the only in-place scaling change AWS supports is
259 // STANDARD → MANAGED (MANAGED → STANDARD is a replacement, gated
260 // in diff above).
261 if (observed?.ScalingMode !== desiredMode) {
262 yield* sesv2.putDedicatedIpPoolScalingAttributes({
263 PoolName: name,
264 ScalingMode: desiredMode,
265 });
266 }
267
268 // 3b. SYNC TAGS — brand the pool if it is not already ours. An
269 // adopted pool reaches this point without ever passing through
270 // the create above, so without this it would stay unbranded and
271 // `read` would keep reporting it Unowned on every later deploy.
272 // Diffed against OBSERVED cloud tags, never against olds.
273 const observedTags = yield* getPoolTags(name);
274 const { upsert, removed } = diffTags(observedTags, desiredTags);
275 if (upsert.length > 0 || removed.length > 0) {
276 const { accountId, region } = yield* AWSEnvironment.current;
277 const poolArn = dedicatedIpPoolArnOf(region, accountId, name);
278 if (upsert.length > 0) {
279 yield* sesv2.tagResource({ ResourceArn: poolArn, Tags: upsert });
280 }
281 if (removed.length > 0) {
282 yield* sesv2.untagResource({
283 ResourceArn: poolArn,
284 TagKeys: removed,
285 });
286 }
287 }
288
289 return { poolName: name, scalingMode: desiredMode };
290 }),
291
292 delete: Effect.fn(function* ({ output }) {
293 // deleteDedicatedIpPool is idempotent for a missing pool.
294 yield* sesv2
295 .deleteDedicatedIpPool({ PoolName: output.poolName })
296 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
297 }),
298 });
299 }),
300 );