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

main
ts 370 lines 13.6 KB
Raw
1 import * as smsvoice from "@distilled.cloud/aws/pinpoint-sms-voice-v2";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { retrySmsVoiceThrottled } from "./internal.ts";
11
12 export interface CloudWatchLogsDestinationProps {
13 /**
14 * ARN of an IAM role that End User Messaging SMS assumes to write to
15 * the log group. The role must trust `sms-voice.amazonaws.com`.
16 */
17 iamRoleArn: string;
18 /**
19 * ARN of the CloudWatch Logs log group that receives the events.
20 */
21 logGroupArn: string;
22 }
23
24 export interface KinesisFirehoseDestinationProps {
25 /**
26 * ARN of an IAM role that End User Messaging SMS assumes to put
27 * records on the delivery stream. The role must trust
28 * `sms-voice.amazonaws.com`.
29 */
30 iamRoleArn: string;
31 /**
32 * ARN of the Kinesis Data Firehose delivery stream that receives the
33 * events.
34 */
35 deliveryStreamArn: string;
36 }
37
38 export interface SnsDestinationProps {
39 /**
40 * ARN of the SNS topic that receives the events.
41 */
42 topicArn: string;
43 }
44
45 export interface EventDestinationProps {
46 /**
47 * Name of the configuration set the event destination is attached to.
48 * Changing it replaces the event destination.
49 */
50 configurationSetName: string;
51 /**
52 * Name of the event destination (`[A-Za-z0-9_-]+`, 1-64 characters).
53 * Changing the name replaces the event destination.
54 * @default ${app}-${stage}-${id}
55 */
56 eventDestinationName?: string;
57 /**
58 * The message event types the destination receives, e.g. `ALL`,
59 * `TEXT_ALL`, `TEXT_SENT`, `TEXT_DELIVERED`, `VOICE_ALL`.
60 */
61 matchingEventTypes: string[];
62 /**
63 * Whether the event destination is enabled. Disabled destinations
64 * receive no events.
65 * @default true
66 */
67 enabled?: boolean;
68 /**
69 * Deliver events to a CloudWatch Logs log group. Exactly one of
70 * `cloudWatchLogsDestination`, `kinesisFirehoseDestination`, or
71 * `snsDestination` must be set.
72 */
73 cloudWatchLogsDestination?: CloudWatchLogsDestinationProps;
74 /**
75 * Deliver events to a Kinesis Data Firehose delivery stream. Exactly
76 * one of `cloudWatchLogsDestination`, `kinesisFirehoseDestination`, or
77 * `snsDestination` must be set.
78 */
79 kinesisFirehoseDestination?: KinesisFirehoseDestinationProps;
80 /**
81 * Deliver events to an SNS topic. Exactly one of
82 * `cloudWatchLogsDestination`, `kinesisFirehoseDestination`, or
83 * `snsDestination` must be set.
84 */
85 snsDestination?: SnsDestinationProps;
86 }
87
88 export interface EventDestination extends Resource<
89 "AWS.PinpointSMSVoiceV2.EventDestination",
90 EventDestinationProps,
91 {
92 /**
93 * Configuration set the destination belongs to.
94 */
95 configurationSetName: string;
96 /**
97 * ARN of the owning configuration set.
98 */
99 configurationSetArn: string;
100 /**
101 * Name of the event destination.
102 */
103 eventDestinationName: string;
104 /**
105 * Whether event delivery is enabled.
106 */
107 enabled: boolean;
108 /**
109 * Event types routed to the destination (e.g. `ALL`, `TEXT_DELIVERED`).
110 */
111 matchingEventTypes: string[];
112 },
113 never,
114 Providers
115 > {}
116
117 /**
118 * An AWS End User Messaging SMS (Pinpoint SMS Voice v2) event
119 * destination — routes message events (sends, deliveries, failures) from
120 * a `ConfigurationSet` to CloudWatch Logs, Kinesis Data Firehose, or SNS.
121 *
122 * Each configuration set holds up to five event destinations; each event
123 * destination references exactly one delivery target.
124 * ### Creating Event Destinations
125 * **Example:** Stream all events to SNS
126 * ```typescript
127 * import * as PinpointSMSVoiceV2 from "@alchemy.run/aws/PinpointSMSVoiceV2";
128 * import * as SNS from "@alchemy.run/aws/SNS";
129 *
130 * const configSet = yield* PinpointSMSVoiceV2.ConfigurationSet("Messaging");
131 * const events = yield* SNS.Topic("SmsEvents");
132 * const destination = yield* PinpointSMSVoiceV2.EventDestination("Events", {
133 * configurationSetName: configSet.configurationSetName,
134 * matchingEventTypes: ["ALL"],
135 * snsDestination: { topicArn: events.topicArn },
136 * });
137 * ```
138 *
139 * **Example:** CloudWatch Logs destination
140 * ```typescript
141 * const destination = yield* PinpointSMSVoiceV2.EventDestination("Logs", {
142 * configurationSetName: configSet.configurationSetName,
143 * matchingEventTypes: ["TEXT_ALL"],
144 * cloudWatchLogsDestination: {
145 * iamRoleArn: role.roleArn,
146 * logGroupArn: logGroup.logGroupArn,
147 * },
148 * });
149 * ```
150 *
151 * **Example:** Disable a destination without deleting it
152 * ```typescript
153 * const destination = yield* PinpointSMSVoiceV2.EventDestination("Events", {
154 * configurationSetName: configSet.configurationSetName,
155 * matchingEventTypes: ["ALL"],
156 * snsDestination: { topicArn: events.topicArn },
157 * enabled: false,
158 * });
159 * ```
160 *
161 * @resource
162 */
163 export const EventDestination = Resource<EventDestination>(
164 "AWS.PinpointSMSVoiceV2.EventDestination",
165 );
166
167 /**
168 * Raised when an event destination cannot be observed immediately after
169 * it was created — the create call succeeded (or raced a peer) but the
170 * follow-up describe found nothing.
171 */
172 export class SmsVoiceEventDestinationMissing extends Data.TaggedError(
173 "SmsVoiceEventDestinationMissing",
174 )<{ message: string }> {}
175
176 const sameStringSet = (left: readonly string[] | undefined, right: readonly string[]) => {
177 const l = [...(left ?? [])].sort();
178 const r = [...right].sort();
179 return l.length === r.length && l.every((v, i) => v === r[i]);
180 };
181
182 const toWireDestinations = (props: {
183 cloudWatchLogsDestination?: CloudWatchLogsDestinationProps | undefined;
184 kinesisFirehoseDestination?: KinesisFirehoseDestinationProps | undefined;
185 snsDestination?: SnsDestinationProps | undefined;
186 }) => ({
187 CloudWatchLogsDestination: props.cloudWatchLogsDestination
188 ? {
189 IamRoleArn: props.cloudWatchLogsDestination.iamRoleArn,
190 LogGroupArn: props.cloudWatchLogsDestination.logGroupArn,
191 }
192 : undefined,
193 KinesisFirehoseDestination: props.kinesisFirehoseDestination
194 ? {
195 IamRoleArn: props.kinesisFirehoseDestination.iamRoleArn,
196 DeliveryStreamArn: props.kinesisFirehoseDestination.deliveryStreamArn,
197 }
198 : undefined,
199 SnsDestination: props.snsDestination ? { TopicArn: props.snsDestination.topicArn } : undefined,
200 });
201
202 export const EventDestinationProvider = () =>
203 Provider.effect(
204 EventDestination,
205 Effect.gen(function* () {
206 const toName = (id: string, props: { eventDestinationName?: string | undefined }) =>
207 props.eventDestinationName
208 ? Effect.succeed(props.eventDestinationName)
209 : createPhysicalName({ id, maxLength: 64 });
210
211 /** Observe the parent configuration set (undefined when gone). */
212 const getConfigurationSet = Effect.fn(function* (name: string) {
213 const result = yield* smsvoice
214 .describeConfigurationSets({ ConfigurationSetNames: [name] })
215 .pipe(
216 retrySmsVoiceThrottled,
217 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
218 );
219 return result?.ConfigurationSets?.find((cs) => cs.ConfigurationSetName === name);
220 });
221
222 return {
223 stables: ["configurationSetName", "configurationSetArn", "eventDestinationName"],
224
225 read: Effect.fn(function* ({ id, olds, output }) {
226 const configurationSetName = output?.configurationSetName ?? olds?.configurationSetName;
227 if (configurationSetName === undefined) return undefined;
228 const eventDestinationName =
229 output?.eventDestinationName ?? (yield* toName(id, olds ?? {}));
230 const set = yield* getConfigurationSet(configurationSetName);
231 const observed = set?.EventDestinations?.find(
232 (ed) => ed.EventDestinationName === eventDestinationName,
233 );
234 if (set === undefined || observed === undefined) return undefined;
235 // Event destinations are not taggable, so there is no ownership
236 // marker to check — existence is the whole story.
237 return {
238 configurationSetName: set.ConfigurationSetName,
239 configurationSetArn: set.ConfigurationSetArn,
240 eventDestinationName: observed.EventDestinationName,
241 enabled: observed.Enabled,
242 matchingEventTypes: [...observed.MatchingEventTypes],
243 };
244 }),
245
246 diff: Effect.fn(function* ({ id, news, olds }) {
247 if (!isResolved(news)) return undefined;
248 if (
249 olds?.configurationSetName !== undefined &&
250 olds.configurationSetName !== news.configurationSetName
251 ) {
252 return { action: "replace" } as const;
253 }
254 const oldName = yield* toName(id, olds ?? {});
255 const newName = yield* toName(id, news);
256 if (oldName !== newName) return { action: "replace" } as const;
257 }),
258
259 reconcile: Effect.fn(function* ({ id, news, output, session }) {
260 const configurationSetName = news.configurationSetName;
261 const eventDestinationName = output?.eventDestinationName ?? (yield* toName(id, news));
262 const desiredEnabled = news.enabled ?? true;
263 const desiredDestinations = toWireDestinations(news);
264
265 // 1. Observe — the event destination lives inside its parent
266 // configuration set's describe output.
267 const set = yield* getConfigurationSet(configurationSetName);
268 let observed = set?.EventDestinations?.find(
269 (ed) => ed.EventDestinationName === eventDestinationName,
270 );
271
272 // 2. Ensure — create if missing; a ConflictException is a race
273 // with a peer reconciler, so fall through to the sync step.
274 if (observed === undefined) {
275 yield* smsvoice
276 .createEventDestination({
277 ConfigurationSetName: configurationSetName,
278 EventDestinationName: eventDestinationName,
279 MatchingEventTypes: news.matchingEventTypes,
280 ...desiredDestinations,
281 })
282 .pipe(
283 retrySmsVoiceThrottled,
284 Effect.catchTag("ConflictException", () => Effect.void),
285 Effect.asVoid,
286 );
287 }
288
289 // Re-observe so the sync step diffs actual cloud state (and the
290 // returned attributes carry the parent's ARN).
291 const finalSet = yield* getConfigurationSet(configurationSetName);
292 observed = finalSet?.EventDestinations?.find(
293 (ed) => ed.EventDestinationName === eventDestinationName,
294 );
295 if (finalSet === undefined || observed === undefined) {
296 return yield* new SmsVoiceEventDestinationMissing({
297 message: `event destination '${eventDestinationName}' on configuration set '${configurationSetName}' not observable after create`,
298 });
299 }
300
301 // 3. Sync — apply a single update when any mutable aspect
302 // (enabled, event types, delivery target) drifted.
303 const drifted =
304 observed.Enabled !== desiredEnabled ||
305 !sameStringSet(observed.MatchingEventTypes, news.matchingEventTypes) ||
306 JSON.stringify({
307 cw: observed.CloudWatchLogsDestination,
308 kf: observed.KinesisFirehoseDestination,
309 sns: observed.SnsDestination,
310 }) !==
311 JSON.stringify({
312 cw: desiredDestinations.CloudWatchLogsDestination,
313 kf: desiredDestinations.KinesisFirehoseDestination,
314 sns: desiredDestinations.SnsDestination,
315 });
316 if (drifted) {
317 yield* smsvoice
318 .updateEventDestination({
319 ConfigurationSetName: configurationSetName,
320 EventDestinationName: eventDestinationName,
321 Enabled: desiredEnabled,
322 MatchingEventTypes: news.matchingEventTypes,
323 ...desiredDestinations,
324 })
325 .pipe(retrySmsVoiceThrottled);
326 }
327
328 yield* session.note(`${finalSet.ConfigurationSetArn}/${eventDestinationName}`);
329 return {
330 configurationSetName: finalSet.ConfigurationSetName,
331 configurationSetArn: finalSet.ConfigurationSetArn,
332 eventDestinationName,
333 enabled: desiredEnabled,
334 matchingEventTypes: [...news.matchingEventTypes],
335 };
336 }),
337
338 delete: Effect.fn(function* ({ output }) {
339 yield* smsvoice
340 .deleteEventDestination({
341 ConfigurationSetName: output.configurationSetName,
342 EventDestinationName: output.eventDestinationName,
343 })
344 .pipe(
345 retrySmsVoiceThrottled,
346 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
347 Effect.asVoid,
348 );
349 }),
350
351 // Event destinations are enumerable by flattening every
352 // configuration set's embedded destination list.
353 list: () =>
354 smsvoice.describeConfigurationSets.items({}).pipe(
355 Stream.runCollect,
356 Effect.map((chunk) =>
357 Array.from(chunk).flatMap((cs) =>
358 (cs.EventDestinations ?? []).map((ed) => ({
359 configurationSetName: cs.ConfigurationSetName,
360 configurationSetArn: cs.ConfigurationSetArn,
361 eventDestinationName: ed.EventDestinationName,
362 enabled: ed.Enabled,
363 matchingEventTypes: [...ed.MatchingEventTypes],
364 })),
365 ),
366 ),
367 ),
368 };
369 }),
370 );