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

main
ts 502 lines 19.5 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 { toWireSeconds } from "alchemy/Util/Duration";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Stream from "effect/Stream";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * Whether SES requires (`REQUIRE`) or merely prefers (`OPTIONAL`) a TLS
17 * connection when delivering email through this configuration set.
18 */
19 export type TlsPolicy = "REQUIRE" | "OPTIONAL";
20
21 /**
22 * The reasons for which SES automatically adds recipients to the account
23 * suppression list when sending through this configuration set.
24 */
25 export type SuppressionListReason = "BOUNCE" | "COMPLAINT";
26
27 export interface ConfigurationSetTrackingSettings {
28 /**
29 * A custom domain — a verified subdomain you own, with a valid certificate —
30 * that SES uses to host open- and click-tracking links for email sent
31 * through this configuration set.
32 *
33 * Required: SES has no way to set an HTTPS policy for the default tracking
34 * domain, so `httpsPolicy` is only meaningful alongside a custom domain.
35 */
36 customRedirectDomain: string;
37 /**
38 * Whether tracking links use HTTPS (`REQUIRE`), plain HTTP (`OPTIONAL`), or
39 * HTTPS only for the open pixel (`REQUIRE_OPEN_ONLY`).
40 */
41 httpsPolicy?: sesv2.HttpsPolicy;
42 }
43
44 export interface ConfigurationSetVdmSettings {
45 /**
46 * Whether SES collects engagement (open/click) metrics for the Virtual
47 * Deliverability Manager dashboard for email sent through this configuration
48 * set.
49 */
50 dashboardEngagementMetrics?: sesv2.FeatureStatus;
51 /**
52 * Whether SES applies Guardian optimized shared delivery to email sent
53 * through this configuration set.
54 */
55 guardianOptimizedSharedDelivery?: sesv2.FeatureStatus;
56 }
57
58 export interface ConfigurationSetProps {
59 /**
60 * The name of the configuration set. May contain letters, numbers, hyphens
61 * and underscores, up to 64 characters. If omitted, a deterministic
62 * physical name is generated from the app, stage, and logical ID.
63 * Changing the name replaces the configuration set.
64 */
65 configurationSetName?: string;
66 /**
67 * Whether email sending through this configuration set is enabled.
68 * @default true
69 */
70 sendingEnabled?: boolean;
71 /**
72 * Whether SES publishes reputation metrics (bounce and complaint rates)
73 * for this configuration set to CloudWatch.
74 * @default false
75 */
76 reputationMetricsEnabled?: boolean;
77 /**
78 * Whether SES requires a TLS connection when delivering email through
79 * this configuration set. Messages are dropped when `REQUIRE` is set and
80 * TLS cannot be established.
81 * @default "OPTIONAL"
82 */
83 tlsPolicy?: TlsPolicy;
84 /**
85 * The maximum amount of time (5 minutes to 14 hours) that SES will attempt
86 * delivery of email through this configuration set. Accepts any
87 * `Duration.Input` (e.g. `"1 hour"`, `Duration.hours(1)`; a bare number
88 * is milliseconds); the wire unit is whole seconds.
89 */
90 maxDelivery?: Duration.Input;
91 /**
92 * Which events cause SES to add a recipient to the account suppression
93 * list when sending through this configuration set. Overrides the
94 * account-level setting; leave undefined to inherit it.
95 */
96 suppressedReasons?: SuppressionListReason[];
97 /**
98 * Open- and click-tracking configuration. Leave undefined to keep whatever
99 * SES currently has.
100 *
101 * Members cannot be unset once set: SES exposes no API to remove a custom
102 * redirect domain, so dropping this prop keeps the current state rather
103 * than restoring the default SES tracking domain.
104 */
105 tracking?: ConfigurationSetTrackingSettings;
106 /**
107 * Virtual Deliverability Manager configuration for this configuration set.
108 * Requires account-level VDM to be enabled — see `SES.AccountSettings`.
109 *
110 * Members cannot be unset once set: dropping this prop keeps the current
111 * state rather than clearing it. A member you do omit while managing its
112 * sibling is preserved (SES replaces VdmOptions wholesale, so the
113 * unmanaged member is backfilled from observed state).
114 */
115 vdm?: ConfigurationSetVdmSettings;
116 /**
117 * Tags to apply to the configuration set. Merged with internal Alchemy
118 * tags.
119 */
120 tags?: Record<string, string>;
121 }
122
123 export interface ConfigurationSet extends Resource<
124 "AWS.SES.ConfigurationSet",
125 ConfigurationSetProps,
126 {
127 configurationSetName: string;
128 configurationSetArn: string;
129 /**
130 * Sending, reputation and delivery options, the declared suppression,
131 * tracking and VDM options, and the tags, as observed. Lets
132 * `alchemy drift` detect out-of-band changes.
133 */
134 configuration?: Record<string, unknown>;
135 },
136 never,
137 Providers
138 > {}
139
140 /**
141 * An Amazon SES v2 configuration set — a named group of sending options
142 * (TLS policy, reputation metrics, suppression overrides) that you apply to
143 * outbound email, either per-message or as an identity's default.
144 *
145 * Attach event destinations with `SES.ConfigurationSetEventDestination` to
146 * stream send/delivery/bounce/complaint events to SNS, EventBridge, or
147 * CloudWatch.
148 * ### Creating Configuration Sets
149 * **Example:** Basic Configuration Set
150 * ```typescript
151 * import * as SES from "@alchemy.run/aws/SES";
152 *
153 * const configSet = yield* SES.ConfigurationSet("Default", {});
154 * ```
155 *
156 * **Example:** Require TLS and Publish Reputation Metrics
157 * ```typescript
158 * const configSet = yield* SES.ConfigurationSet("Strict", {
159 * tlsPolicy: "REQUIRE",
160 * reputationMetricsEnabled: true,
161 * });
162 * ```
163 *
164 * **Example:** Suppress Bounces and Complaints
165 * ```typescript
166 * const configSet = yield* SES.ConfigurationSet("Suppressing", {
167 * suppressedReasons: ["BOUNCE", "COMPLAINT"],
168 * });
169 * ```
170 *
171 * ### Open and Click Tracking
172 * **Example:** Host Tracking Links on Your Own Domain
173 * ```typescript
174 * // The redirect domain must be a verified subdomain you own with a valid
175 * // certificate. Omit `tracking` entirely to keep SES's current setting.
176 * const configSet = yield* SES.ConfigurationSet("Tracked", {
177 * tracking: {
178 * customRedirectDomain: "links.example.com",
179 * httpsPolicy: "REQUIRE",
180 * },
181 * });
182 * ```
183 *
184 * ### Virtual Deliverability Manager
185 * **Example:** Collect Engagement Metrics for This Configuration Set
186 * ```typescript
187 * // Requires account-level VDM — see SES.AccountSettings.
188 * const configSet = yield* SES.ConfigurationSet("Measured", {
189 * vdm: {
190 * dashboardEngagementMetrics: "ENABLED",
191 * guardianOptimizedSharedDelivery: "ENABLED",
192 * },
193 * });
194 * ```
195 *
196 * ### Event Destinations
197 * **Example:** Stream Events to SNS
198 * ```typescript
199 * const topic = yield* SNS.Topic("EmailEvents", {});
200 * const destination = yield* SES.ConfigurationSetEventDestination("ToSns", {
201 * configurationSetName: configSet.configurationSetName,
202 * matchingEventTypes: ["SEND", "DELIVERY", "BOUNCE", "COMPLAINT"],
203 * snsDestination: { topicArn: topic.topicArn },
204 * });
205 * ```
206 *
207 * @resource
208 */
209 export const ConfigurationSet = Resource<ConfigurationSet>("AWS.SES.ConfigurationSet");
210
211 const toTagRecord = (
212 tags: ReadonlyArray<{ Key: string; Value: string }> | undefined,
213 ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value]));
214
215 const configurationSetArnOf = (region: string, accountId: string, name: string) =>
216 `arn:aws:ses:${region}:${accountId}:configuration-set/${name}`;
217
218 const sameReasons = (a: ReadonlyArray<string> | undefined, b: ReadonlyArray<string>) => {
219 const left = [...(a ?? [])].sort();
220 const right = [...b].sort();
221 return left.length === right.length && left.every((v, i) => v === right[i]);
222 };
223
224 /**
225 * The options reconcile converges, as observed. Options reconcile only
226 * applies when declared are only observed when declared. `read` and
227 * `reconcile` share it so a converged configuration set reads unchanged.
228 */
229 const observeConfigurationSetOptions = (
230 observed: sesv2.GetConfigurationSetResponse,
231 props: ConfigurationSetProps | undefined,
232 ) => ({
233 sendingEnabled: observed.SendingOptions?.SendingEnabled ?? true,
234 reputationMetricsEnabled: observed.ReputationOptions?.ReputationMetricsEnabled ?? false,
235 tlsPolicy: observed.DeliveryOptions?.TlsPolicy ?? "OPTIONAL",
236 maxDeliverySeconds:
237 props?.maxDelivery === undefined ? undefined : observed.DeliveryOptions?.MaxDeliverySeconds,
238 suppressedReasons:
239 props?.suppressedReasons === undefined
240 ? undefined
241 : [...(observed.SuppressionOptions?.SuppressedReasons ?? [])].sort(),
242 tracking:
243 props?.tracking === undefined
244 ? undefined
245 : {
246 customRedirectDomain: observed.TrackingOptions?.CustomRedirectDomain,
247 httpsPolicy:
248 props.tracking.httpsPolicy === undefined
249 ? undefined
250 : observed.TrackingOptions?.HttpsPolicy,
251 },
252 vdm:
253 props?.vdm === undefined
254 ? undefined
255 : {
256 dashboardEngagementMetrics: observed.VdmOptions?.DashboardOptions?.EngagementMetrics,
257 guardianOptimizedSharedDelivery:
258 observed.VdmOptions?.GuardianOptions?.OptimizedSharedDelivery,
259 },
260 tags: toTagRecord(observed.Tags),
261 });
262
263 export const ConfigurationSetProvider = () =>
264 Provider.effect(
265 ConfigurationSet,
266 Effect.gen(function* () {
267 const createName = Effect.fn(function* (
268 id: string,
269 props: Pick<ConfigurationSetProps, "configurationSetName">,
270 ) {
271 return props.configurationSetName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
272 });
273
274 const getConfigurationSet = Effect.fn(function* (name: string) {
275 return yield* sesv2
276 .getConfigurationSet({ ConfigurationSetName: name })
277 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
278 });
279
280 return ConfigurationSet.Provider.of({
281 stables: ["configurationSetName", "configurationSetArn"],
282
283 list: () =>
284 Effect.gen(function* () {
285 const { accountId, region } = yield* AWSEnvironment.current;
286 const pages = yield* sesv2.listConfigurationSets.pages({}).pipe(Stream.runCollect);
287 return Array.from(pages)
288 .flatMap((page) => page.ConfigurationSets ?? [])
289 .map((name) => ({
290 configurationSetName: name,
291 configurationSetArn: configurationSetArnOf(region, accountId, name),
292 }));
293 }),
294
295 read: Effect.fn(function* ({ id, olds, output }) {
296 const { accountId, region } = yield* AWSEnvironment.current;
297 const name = output?.configurationSetName ?? (yield* createName(id, olds ?? {}));
298 const found = yield* getConfigurationSet(name);
299 if (!found) return undefined;
300 const attrs = {
301 configurationSetName: name,
302 configurationSetArn: configurationSetArnOf(region, accountId, name),
303 configuration: observeConfigurationSetOptions(found, olds),
304 };
305 const tags = toTagRecord(found.Tags);
306 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
307 }),
308
309 diff: Effect.fn(function* ({ id, news, olds }) {
310 if (!isResolved(news)) return undefined;
311 const oldName = yield* createName(id, olds ?? {});
312 const newName = yield* createName(id, news ?? {});
313 if (oldName !== newName) {
314 return { action: "replace" } as const;
315 }
316 }),
317
318 reconcile: Effect.fn(function* ({ id, news, output, session }) {
319 const { accountId, region } = yield* AWSEnvironment.current;
320 const name = output?.configurationSetName ?? (yield* createName(id, news));
321 const configurationSetArn = configurationSetArnOf(region, accountId, name);
322 const internalTags = yield* createInternalTags(id);
323 const desiredTags = { ...news.tags, ...internalTags };
324 const desiredMaxDelivery = toWireSeconds(news.maxDelivery);
325
326 // 1. OBSERVE — cloud state is authoritative.
327 let observed = yield* getConfigurationSet(name);
328
329 // 2. ENSURE — create with the full desired option set in one call;
330 // AlreadyExists is a race, not a failure.
331 if (observed === undefined) {
332 yield* sesv2
333 .createConfigurationSet({
334 ConfigurationSetName: name,
335 SendingOptions:
336 news.sendingEnabled !== undefined
337 ? { SendingEnabled: news.sendingEnabled }
338 : undefined,
339 ReputationOptions:
340 news.reputationMetricsEnabled !== undefined
341 ? {
342 ReputationMetricsEnabled: news.reputationMetricsEnabled,
343 }
344 : undefined,
345 DeliveryOptions:
346 news.tlsPolicy !== undefined || desiredMaxDelivery !== undefined
347 ? {
348 TlsPolicy: news.tlsPolicy,
349 MaxDeliverySeconds: desiredMaxDelivery,
350 }
351 : undefined,
352 SuppressionOptions:
353 news.suppressedReasons !== undefined
354 ? { SuppressedReasons: news.suppressedReasons }
355 : undefined,
356 Tags: createTagsList(desiredTags),
357 })
358 .pipe(Effect.catchTag("AlreadyExistsException", () => Effect.succeed({})));
359 observed = yield* sesv2.getConfigurationSet({
360 ConfigurationSetName: name,
361 });
362 }
363
364 // 3. SYNC — per mutable aspect: diff observed against desired and
365 // apply only the delta.
366 const desiredSending = news.sendingEnabled ?? true;
367 if ((observed.SendingOptions?.SendingEnabled ?? true) !== desiredSending) {
368 yield* sesv2.putConfigurationSetSendingOptions({
369 ConfigurationSetName: name,
370 SendingEnabled: desiredSending,
371 });
372 }
373
374 const desiredReputation = news.reputationMetricsEnabled ?? false;
375 if (
376 (observed.ReputationOptions?.ReputationMetricsEnabled ?? false) !== desiredReputation
377 ) {
378 yield* sesv2.putConfigurationSetReputationOptions({
379 ConfigurationSetName: name,
380 ReputationMetricsEnabled: desiredReputation,
381 });
382 }
383
384 const desiredTls = news.tlsPolicy ?? "OPTIONAL";
385 const observedTls = observed.DeliveryOptions?.TlsPolicy ?? "OPTIONAL";
386 const observedMaxDelivery = observed.DeliveryOptions?.MaxDeliverySeconds;
387 if (
388 observedTls !== desiredTls ||
389 (desiredMaxDelivery !== undefined && observedMaxDelivery !== desiredMaxDelivery)
390 ) {
391 yield* sesv2.putConfigurationSetDeliveryOptions({
392 ConfigurationSetName: name,
393 TlsPolicy: desiredTls,
394 MaxDeliverySeconds: desiredMaxDelivery ?? observedMaxDelivery,
395 // preserve any dedicated sending pool configured out-of-band
396 SendingPoolName: observed.DeliveryOptions?.SendingPoolName,
397 });
398 }
399
400 // Suppression is only synced when explicitly configured so an
401 // unset prop keeps inheriting the account-level defaults.
402 if (
403 news.suppressedReasons !== undefined &&
404 !sameReasons(observed.SuppressionOptions?.SuppressedReasons, news.suppressedReasons)
405 ) {
406 yield* sesv2.putConfigurationSetSuppressionOptions({
407 ConfigurationSetName: name,
408 SuppressedReasons: news.suppressedReasons,
409 });
410 }
411
412 // Tracking is only synced when the caller manages it; leaving the
413 // prop undefined keeps whatever SES currently has. `httpsPolicy`
414 // cannot drift on its own — the type requires a custom domain
415 // alongside it, because SES has no way to set an HTTPS policy for
416 // the default tracking domain.
417 if (
418 news.tracking !== undefined &&
419 (observed.TrackingOptions?.CustomRedirectDomain !==
420 news.tracking.customRedirectDomain ||
421 (news.tracking.httpsPolicy !== undefined &&
422 observed.TrackingOptions?.HttpsPolicy !== news.tracking.httpsPolicy))
423 ) {
424 yield* sesv2.putConfigurationSetTrackingOptions({
425 ConfigurationSetName: name,
426 CustomRedirectDomain: news.tracking.customRedirectDomain,
427 HttpsPolicy: news.tracking.httpsPolicy,
428 });
429 }
430
431 // VDM is only synced when explicitly configured; it requires
432 // account-level VDM to be enabled.
433 //
434 // putConfigurationSetVdmOptions REPLACES VdmOptions wholesale: an
435 // omitted DashboardOptions/GuardianOptions is dropped, not left
436 // alone (verified against the live API). So a caller who manages
437 // only one of the two would silently wipe the other on every
438 // deploy. Backfill the unmanaged member from observed state.
439 const desiredDashboard =
440 news.vdm?.dashboardEngagementMetrics ??
441 observed.VdmOptions?.DashboardOptions?.EngagementMetrics;
442 const desiredGuardian =
443 news.vdm?.guardianOptimizedSharedDelivery ??
444 observed.VdmOptions?.GuardianOptions?.OptimizedSharedDelivery;
445 if (
446 news.vdm !== undefined &&
447 (observed.VdmOptions?.DashboardOptions?.EngagementMetrics !== desiredDashboard ||
448 observed.VdmOptions?.GuardianOptions?.OptimizedSharedDelivery !== desiredGuardian)
449 ) {
450 yield* sesv2.putConfigurationSetVdmOptions({
451 ConfigurationSetName: name,
452 VdmOptions: {
453 DashboardOptions:
454 desiredDashboard !== undefined
455 ? { EngagementMetrics: desiredDashboard }
456 : undefined,
457 GuardianOptions:
458 desiredGuardian !== undefined
459 ? { OptimizedSharedDelivery: desiredGuardian }
460 : undefined,
461 },
462 });
463 }
464
465 // 3b. SYNC TAGS — diff against OBSERVED cloud tags.
466 const observedTags = toTagRecord(observed.Tags);
467 const { upsert, removed } = diffTags(observedTags, desiredTags);
468 if (upsert.length > 0) {
469 yield* sesv2.tagResource({
470 ResourceArn: configurationSetArn,
471 Tags: upsert,
472 });
473 }
474 if (removed.length > 0) {
475 yield* sesv2.untagResource({
476 ResourceArn: configurationSetArn,
477 TagKeys: removed,
478 });
479 }
480
481 yield* session.note(configurationSetArn);
482 const final = yield* sesv2.getConfigurationSet({ ConfigurationSetName: name });
483 return {
484 configurationSetName: name,
485 configurationSetArn,
486 configuration: {
487 ...observeConfigurationSetOptions(final, news),
488 tags: desiredTags,
489 },
490 };
491 }),
492
493 delete: Effect.fn(function* ({ output }) {
494 yield* sesv2
495 .deleteConfigurationSet({
496 ConfigurationSetName: output.configurationSetName,
497 })
498 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
499 }),
500 });
501 }),
502 );