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

main
ts 341 lines 12.3 KB
Raw
1 import type * as sesv2Types from "@distilled.cloud/aws/sesv2";
2 import * as sesv2 from "@distilled.cloud/aws/sesv2";
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 * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { plainJson } from "../internal/Observe.ts";
10 import type { Providers } from "../Providers.ts";
11
12 /**
13 * The email-sending events an event destination can match, e.g. `SEND`,
14 * `DELIVERY`, `BOUNCE`, `COMPLAINT`, `OPEN`, `CLICK`.
15 */
16 export type EventType = sesv2Types.EventType;
17
18 export interface CloudWatchDimensionConfiguration {
19 /**
20 * The name of the CloudWatch dimension, e.g. `ses:configuration-set`.
21 */
22 dimensionName: string;
23 /**
24 * Where SES reads the dimension value from: a message tag
25 * (`MESSAGE_TAG`), an email header (`EMAIL_HEADER`), or a link tag
26 * (`LINK_TAG`).
27 */
28 dimensionValueSource: sesv2Types.DimensionValueSource;
29 /**
30 * The value SES publishes when the message doesn't carry the tag/header.
31 */
32 defaultDimensionValue: string;
33 }
34
35 export interface ConfigurationSetEventDestinationProps {
36 /**
37 * The name of the configuration set that owns this event destination.
38 * Changing it replaces the destination.
39 */
40 configurationSetName: string;
41 /**
42 * The name of the event destination. If omitted, a deterministic physical
43 * name is generated from the app, stage, and logical ID. Changing the
44 * name replaces the destination.
45 */
46 eventDestinationName?: string;
47 /**
48 * Whether the event destination is active.
49 * @default true
50 */
51 enabled?: boolean;
52 /**
53 * The event types to publish to the destination, e.g.
54 * `["SEND", "DELIVERY", "BOUNCE", "COMPLAINT"]`.
55 */
56 matchingEventTypes: EventType[];
57 /**
58 * Publish events to an SNS topic.
59 */
60 snsDestination?: {
61 /** The ARN of the SNS topic to publish events to. */
62 topicArn: string;
63 };
64 /**
65 * Publish events to an EventBridge event bus (the default bus only).
66 */
67 eventBridgeDestination?: {
68 /** The ARN of the EventBridge event bus (must be the default bus). */
69 eventBusArn: string;
70 };
71 /**
72 * Publish event metrics to CloudWatch.
73 */
74 cloudWatchDestination?: {
75 /** How SES maps message tags/headers to CloudWatch dimensions. */
76 dimensionConfigurations: CloudWatchDimensionConfiguration[];
77 };
78 }
79
80 export interface ConfigurationSetEventDestination extends Resource<
81 "AWS.SES.ConfigurationSetEventDestination",
82 ConfigurationSetEventDestinationProps,
83 {
84 configurationSetName: string;
85 eventDestinationName: string;
86 /**
87 * Enabled state, matching event types and destination, as observed.
88 * Lets `alchemy drift` detect out-of-band changes.
89 */
90 configuration?: {
91 enabled: boolean;
92 matchingEventTypes: string[];
93 snsTopicArn?: string;
94 eventBusArn?: string;
95 cloudWatchDimensionConfigurations?: unknown;
96 };
97 },
98 never,
99 Providers
100 > {}
101
102 /**
103 * An event destination on an SES v2 configuration set — streams
104 * send/delivery/bounce/complaint (and open/click) events to SNS,
105 * EventBridge, or CloudWatch.
106 * ### Creating Event Destinations
107 * **Example:** Publish Bounce and Complaint Events to SNS
108 * ```typescript
109 * import * as SES from "@alchemy.run/aws/SES";
110 * import * as SNS from "@alchemy.run/aws/SNS";
111 *
112 * const topic = yield* SNS.Topic("EmailEvents", {});
113 * const configSet = yield* SES.ConfigurationSet("Default", {});
114 *
115 * const destination = yield* SES.ConfigurationSetEventDestination("ToSns", {
116 * configurationSetName: configSet.configurationSetName,
117 * matchingEventTypes: ["BOUNCE", "COMPLAINT"],
118 * snsDestination: { topicArn: topic.topicArn },
119 * });
120 * ```
121 *
122 * **Example:** Publish Metrics to CloudWatch
123 * ```typescript
124 * const metrics = yield* SES.ConfigurationSetEventDestination("Metrics", {
125 * configurationSetName: configSet.configurationSetName,
126 * matchingEventTypes: ["SEND", "DELIVERY"],
127 * cloudWatchDestination: {
128 * dimensionConfigurations: [
129 * {
130 * dimensionName: "campaign",
131 * dimensionValueSource: "MESSAGE_TAG",
132 * defaultDimensionValue: "none",
133 * },
134 * ],
135 * },
136 * });
137 * ```
138 *
139 * @resource
140 */
141 export const ConfigurationSetEventDestination = Resource<ConfigurationSetEventDestination>(
142 "AWS.SES.ConfigurationSetEventDestination",
143 );
144
145 const toDefinition = (
146 props: ConfigurationSetEventDestinationProps,
147 ): sesv2Types.EventDestinationDefinition => ({
148 Enabled: props.enabled ?? true,
149 MatchingEventTypes: props.matchingEventTypes,
150 SnsDestination: props.snsDestination ? { TopicArn: props.snsDestination.topicArn } : undefined,
151 EventBridgeDestination: props.eventBridgeDestination
152 ? { EventBusArn: props.eventBridgeDestination.eventBusArn }
153 : undefined,
154 CloudWatchDestination: props.cloudWatchDestination
155 ? {
156 DimensionConfigurations: props.cloudWatchDestination.dimensionConfigurations.map((d) => ({
157 DimensionName: d.dimensionName,
158 DimensionValueSource: d.dimensionValueSource,
159 DefaultDimensionValue: d.defaultDimensionValue,
160 })),
161 }
162 : undefined,
163 });
164
165 const isInSync = (
166 observed: sesv2Types.EventDestination,
167 desired: sesv2Types.EventDestinationDefinition,
168 ) => {
169 const sortedTypes = (types: ReadonlyArray<string> | undefined) => [...(types ?? [])].sort();
170 const observedTypes = sortedTypes(observed.MatchingEventTypes);
171 const desiredTypes = sortedTypes(desired.MatchingEventTypes);
172 return (
173 (observed.Enabled ?? false) === (desired.Enabled ?? true) &&
174 observedTypes.length === desiredTypes.length &&
175 observedTypes.every((t, i) => t === desiredTypes[i]) &&
176 observed.SnsDestination?.TopicArn === desired.SnsDestination?.TopicArn &&
177 observed.EventBridgeDestination?.EventBusArn === desired.EventBridgeDestination?.EventBusArn &&
178 JSON.stringify(observed.CloudWatchDestination?.DimensionConfigurations ?? null) ===
179 JSON.stringify(desired.CloudWatchDestination?.DimensionConfigurations ?? null)
180 );
181 };
182
183 /**
184 * The destination settings `read` and `reconcile` both report, so a
185 * converged destination reads unchanged.
186 */
187 const observeDestination = (destination: sesv2Types.EventDestination) =>
188 plainJson({
189 enabled: destination.Enabled ?? false,
190 matchingEventTypes: [...(destination.MatchingEventTypes ?? [])].sort(),
191 snsTopicArn: destination.SnsDestination?.TopicArn,
192 eventBusArn: destination.EventBridgeDestination?.EventBusArn,
193 cloudWatchDimensionConfigurations: destination.CloudWatchDestination?.DimensionConfigurations,
194 });
195
196 export const ConfigurationSetEventDestinationProvider = () =>
197 Provider.effect(
198 ConfigurationSetEventDestination,
199 Effect.gen(function* () {
200 const createName = Effect.fn(function* (
201 id: string,
202 props: Pick<ConfigurationSetEventDestinationProps, "eventDestinationName">,
203 ) {
204 return props.eventDestinationName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
205 });
206
207 const findDestination = Effect.fn(function* (
208 configurationSetName: string,
209 eventDestinationName: string,
210 ) {
211 const destinations = yield* sesv2
212 .getConfigurationSetEventDestinations({
213 ConfigurationSetName: configurationSetName,
214 })
215 .pipe(
216 Effect.map((r) => r.EventDestinations ?? []),
217 // configuration set (or destination) missing → not found
218 Effect.catchTag("NotFoundException", () =>
219 Effect.succeed([] as sesv2Types.EventDestination[]),
220 ),
221 );
222 return destinations.find((d) => d.Name === eventDestinationName);
223 });
224
225 return ConfigurationSetEventDestination.Provider.of({
226 stables: ["configurationSetName", "eventDestinationName"],
227
228 list: () =>
229 Effect.gen(function* () {
230 const pages = yield* sesv2.listConfigurationSets.pages({}).pipe(Stream.runCollect);
231 const configSets = Array.from(pages).flatMap((page) => page.ConfigurationSets ?? []);
232 const nested = yield* Effect.forEach(
233 configSets,
234 (configurationSetName) =>
235 sesv2
236 .getConfigurationSetEventDestinations({
237 ConfigurationSetName: configurationSetName,
238 })
239 .pipe(
240 Effect.map((r) =>
241 (r.EventDestinations ?? []).map((d) => ({
242 configurationSetName,
243 eventDestinationName: d.Name,
244 })),
245 ),
246 Effect.catchTag("NotFoundException", () =>
247 Effect.succeed(
248 [] as {
249 configurationSetName: string;
250 eventDestinationName: string;
251 }[],
252 ),
253 ),
254 ),
255 { concurrency: 2 },
256 );
257 return nested.flat();
258 }),
259
260 read: Effect.fn(function* ({ id, olds, output }) {
261 const configurationSetName = output?.configurationSetName ?? olds?.configurationSetName;
262 if (configurationSetName === undefined) return undefined;
263 const name = output?.eventDestinationName ?? (yield* createName(id, olds ?? {}));
264 const found = yield* findDestination(configurationSetName, name);
265 if (!found) return undefined;
266 return {
267 configurationSetName,
268 eventDestinationName: name,
269 configuration: observeDestination(found),
270 };
271 }),
272
273 diff: Effect.fn(function* ({ id, news, olds }) {
274 if (!isResolved(news)) return undefined;
275 const oldName = yield* createName(id, olds ?? {});
276 const newName = yield* createName(id, news ?? {});
277 if (
278 oldName !== newName ||
279 (olds?.configurationSetName !== undefined &&
280 news?.configurationSetName !== undefined &&
281 olds.configurationSetName !== news.configurationSetName)
282 ) {
283 return { action: "replace" } as const;
284 }
285 }),
286
287 reconcile: Effect.fn(function* ({ id, news, output, session }) {
288 const configurationSetName = news.configurationSetName;
289 const name = output?.eventDestinationName ?? (yield* createName(id, news));
290 const desired = toDefinition(news);
291
292 // 1. OBSERVE — look the destination up on the owning set.
293 const observed = yield* findDestination(configurationSetName, name);
294
295 if (observed === undefined) {
296 // 2. ENSURE — create; AlreadyExists is a race → converge with
297 // an update instead.
298 yield* sesv2
299 .createConfigurationSetEventDestination({
300 ConfigurationSetName: configurationSetName,
301 EventDestinationName: name,
302 EventDestination: desired,
303 })
304 .pipe(
305 Effect.catchTag("AlreadyExistsException", () =>
306 sesv2.updateConfigurationSetEventDestination({
307 ConfigurationSetName: configurationSetName,
308 EventDestinationName: name,
309 EventDestination: desired,
310 }),
311 ),
312 );
313 } else if (!isInSync(observed, desired)) {
314 // 3. SYNC — apply the delta only when observed drifted.
315 yield* sesv2.updateConfigurationSetEventDestination({
316 ConfigurationSetName: configurationSetName,
317 EventDestinationName: name,
318 EventDestination: desired,
319 });
320 }
321
322 yield* session.note(`${configurationSetName}/${name}`);
323 const final = yield* findDestination(configurationSetName, name);
324 return {
325 configurationSetName,
326 eventDestinationName: name,
327 configuration: final && observeDestination(final),
328 };
329 }),
330
331 delete: Effect.fn(function* ({ output }) {
332 yield* sesv2
333 .deleteConfigurationSetEventDestination({
334 ConfigurationSetName: output.configurationSetName,
335 EventDestinationName: output.eventDestinationName,
336 })
337 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
338 }),
339 });
340 }),
341 );