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

main
ts 433 lines 13.7 KB
Raw
1 import * as sns from "@distilled.cloud/aws/sns";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 export type SubscriptionArn = string;
12
13 export interface SubscriptionProps {
14 /**
15 * ARN of the topic to subscribe to.
16 */
17 topicArn: Input<string>;
18 /**
19 * SNS subscription protocol, for example `lambda`, `sqs`, `https`, or `email`.
20 */
21 protocol: string;
22 /**
23 * Endpoint for the selected protocol, such as a Lambda function ARN or queue ARN.
24 */
25 endpoint?: Input<string>;
26 /**
27 * Raw SNS subscription attributes keyed by AWS attribute name.
28 */
29 attributes?: Record<string, string>;
30 /**
31 * Whether SNS should return the subscription ARN immediately, even while pending confirmation.
32 * @default true
33 */
34 returnSubscriptionArn?: boolean;
35 }
36
37 export interface Subscription extends Resource<
38 "AWS.SNS.Subscription",
39 SubscriptionProps,
40 {
41 /** ARN of the subscription. */
42 subscriptionArn: SubscriptionArn;
43 /** ARN of the topic the subscription is attached to. */
44 topicArn: string;
45 /** Delivery protocol of the subscription (e.g. `lambda`, `sqs`, `https`). */
46 protocol: string;
47 /** Endpoint receiving deliveries, such as a Lambda function or queue ARN. */
48 endpoint: string | undefined;
49 /** AWS account ID that owns the subscription. */
50 owner: string | undefined;
51 /** Whether the subscription is still awaiting endpoint confirmation. */
52 pendingConfirmation: boolean;
53 /** Raw SNS subscription attributes keyed by AWS attribute name. */
54 attributes: Record<string, string>;
55 },
56 never,
57 Providers
58 > {}
59
60 /**
61 * An Amazon SNS subscription that attaches an endpoint to a topic.
62 *
63 * `Subscription` keeps the lifecycle of the subscription itself separate from the
64 * topic, which lets Lambda event sources and manually managed subscriptions share
65 * the same canonical resource model.
66 * ### Creating Subscriptions
67 * **Example:** Lambda Subscription
68 * ```typescript
69 * const subscription = yield* Subscription("TopicSubscription", {
70 * topicArn: topic.topicArn,
71 * protocol: "lambda",
72 * endpoint: fn.functionArn,
73 * });
74 * ```
75 *
76 * **Example:** Fan Out a Topic to an SQS Queue
77 * ```typescript
78 * const topic = yield* SNS.Topic("Events");
79 * const queue = yield* SQS.Queue("Notifications");
80 *
81 * const subscription = yield* Subscription("QueueSubscription", {
82 * topicArn: topic.topicArn,
83 * protocol: "sqs",
84 * endpoint: queue.queueArn,
85 * returnSubscriptionArn: true,
86 * });
87 * ```
88 *
89 * **Example:** Filtered Subscription
90 * ```typescript
91 * const subscription = yield* Subscription("OrderSubscription", {
92 * topicArn: topic.topicArn,
93 * protocol: "sqs",
94 * endpoint: queue.queueArn,
95 * attributes: {
96 * FilterPolicy: JSON.stringify({ type: ["order"] }),
97 * },
98 * });
99 * ```
100 *
101 * @resource
102 */
103 export const Subscription = Resource<Subscription>("AWS.SNS.Subscription");
104
105 export const SubscriptionProvider = () =>
106 Provider.succeed(Subscription, {
107 read: Effect.fn(function* ({ olds, output }) {
108 return yield* readSubscription({
109 subscriptionArn: output?.subscriptionArn,
110 topicArn: (output?.topicArn ?? olds.topicArn) as string | undefined,
111 protocol: output?.protocol ?? olds.protocol,
112 endpoint: (output?.endpoint ?? olds.endpoint) as string | undefined,
113 });
114 }),
115 stables: ["subscriptionArn"],
116 // Account/region-scoped collection: paginate `listSubscriptions`
117 // exhaustively, then hydrate each concrete-ARN subscription via
118 // `getSubscriptionAttributes` (inside `readSubscription`) so each element
119 // matches the exact `read` Attributes shape. Pending-confirmation entries
120 // have no real ARN to hydrate or delete against, so they are skipped.
121 list: Effect.fn(function* () {
122 const subscriptions = yield* sns.listSubscriptions.pages({}).pipe(
123 Stream.runCollect,
124 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Subscriptions ?? [])),
125 );
126
127 const concrete = subscriptions.filter(
128 (
129 subscription,
130 ): subscription is sns.Subscription & {
131 SubscriptionArn: string;
132 } =>
133 typeof subscription.SubscriptionArn === "string" &&
134 !isPendingConfirmation(subscription.SubscriptionArn),
135 );
136
137 const rows = yield* Effect.forEach(
138 concrete,
139 (subscription) =>
140 readSubscription({
141 subscriptionArn: subscription.SubscriptionArn,
142 topicArn: subscription.TopicArn,
143 protocol: subscription.Protocol,
144 endpoint: subscription.Endpoint,
145 }),
146 { concurrency: 10 },
147 );
148
149 return rows.filter((row): row is NonNullable<typeof row> => row !== undefined);
150 }),
151 diff: Effect.fn(function* ({ news, olds }) {
152 if (!isResolved(news)) return undefined;
153 if (news.protocol !== olds.protocol) {
154 return { action: "replace" } as const;
155 }
156
157 if (
158 typeof news.topicArn === "string" &&
159 typeof olds.topicArn === "string" &&
160 news.topicArn !== olds.topicArn
161 ) {
162 return { action: "replace" } as const;
163 }
164
165 if (
166 typeof news.endpoint === "string" &&
167 typeof olds.endpoint === "string" &&
168 news.endpoint !== olds.endpoint
169 ) {
170 return { action: "replace" } as const;
171 }
172 }),
173 reconcile: Effect.fn(function* ({ news, output, session }) {
174 const topicArn = news.topicArn as string;
175 const protocol = news.protocol;
176 const endpoint = news.endpoint as string | undefined;
177 const desiredAttributes = toAttributeMap(news.attributes);
178
179 // Observe — derive the live SubscriptionArn. We can't trust a
180 // pending-confirmation ARN from `output`, since the user may have
181 // confirmed it out of band. Cached ARN is preferred when concrete;
182 // otherwise we list-and-match by (topicArn, protocol, endpoint).
183 let subscriptionArn: string | undefined;
184 if (output?.subscriptionArn && !isPendingConfirmation(output.subscriptionArn)) {
185 const observed = yield* sns
186 .getSubscriptionAttributes({
187 SubscriptionArn: output.subscriptionArn,
188 })
189 .pipe(
190 Effect.catchTags({
191 NotFoundException: () => Effect.undefined,
192 InvalidParameterException: () => Effect.undefined,
193 }),
194 );
195 if (observed) {
196 subscriptionArn = output.subscriptionArn;
197 }
198 } else {
199 subscriptionArn = yield* findSubscription({
200 topicArn,
201 protocol,
202 endpoint,
203 });
204 }
205
206 // Ensure — subscribe if no live subscription matches.
207 if (!subscriptionArn) {
208 const response = yield* sns.subscribe({
209 TopicArn: topicArn,
210 Protocol: protocol,
211 Endpoint: endpoint,
212 Attributes: news.attributes,
213 ReturnSubscriptionArn: news.returnSubscriptionArn ?? true,
214 });
215 if (!response.SubscriptionArn) {
216 return yield* Effect.die(new Error(`subscribe returned no ARN`));
217 }
218 subscriptionArn = response.SubscriptionArn;
219 yield* session.note(subscriptionArn);
220 return {
221 subscriptionArn,
222 topicArn,
223 protocol,
224 endpoint,
225 owner: undefined,
226 pendingConfirmation: isPendingConfirmation(subscriptionArn),
227 attributes: desiredAttributes,
228 };
229 }
230
231 // Sync attributes — fetch observed cloud attributes (FilterPolicy,
232 // RawMessageDelivery, etc.) and apply only the delta. We can only
233 // do this once the subscription is confirmed (pending confirmation
234 // returns no real ARN to mutate against).
235 const attrsResponse = yield* sns
236 .getSubscriptionAttributes({ SubscriptionArn: subscriptionArn })
237 .pipe(
238 Effect.catchTags({
239 NotFoundException: () => Effect.undefined,
240 InvalidParameterException: () => Effect.undefined,
241 }),
242 );
243 const observedAttributes = toAttributeMap(attrsResponse?.Attributes);
244
245 for (const [name, value] of Object.entries(desiredAttributes)) {
246 if (observedAttributes[name] !== value) {
247 yield* sns.setSubscriptionAttributes({
248 SubscriptionArn: subscriptionArn,
249 AttributeName: name,
250 AttributeValue: value,
251 });
252 }
253 }
254
255 // Reset attributes the user no longer specifies. We only clear
256 // user-specified keys (those present in `news.attributes`/`olds`),
257 // not all observed keys, because SNS exposes many read-only system
258 // attributes we should not touch.
259 const previousKeys = new Set(Object.keys(toAttributeMap(output?.attributes)));
260 for (const name of previousKeys) {
261 if (!(name in desiredAttributes)) {
262 yield* sns.setSubscriptionAttributes({
263 SubscriptionArn: subscriptionArn,
264 AttributeName: name,
265 });
266 }
267 }
268
269 yield* session.note(subscriptionArn);
270
271 return {
272 subscriptionArn,
273 topicArn,
274 protocol,
275 endpoint,
276 owner: output?.owner,
277 pendingConfirmation: isPendingConfirmation(subscriptionArn),
278 attributes: desiredAttributes,
279 };
280 }),
281 delete: Effect.fn(function* ({ olds, output }) {
282 const subscriptionArn = isPendingConfirmation(output.subscriptionArn)
283 ? yield* findSubscription({
284 topicArn: (output.topicArn ?? olds.topicArn) as string | undefined,
285 protocol: output.protocol ?? olds.protocol,
286 endpoint: (output.endpoint ?? olds.endpoint) as string | undefined,
287 }).pipe(
288 // The topic is already gone — SNS drops its subscriptions with
289 // it, so there is nothing left to unsubscribe.
290 Effect.catchTag("NotFoundException", () => Effect.undefined),
291 )
292 : output.subscriptionArn;
293
294 if (!subscriptionArn) {
295 return;
296 }
297
298 yield* sns
299 .unsubscribe({
300 SubscriptionArn: subscriptionArn,
301 })
302 .pipe(
303 Effect.catchTags({
304 NotFoundException: () => Effect.void,
305 InvalidParameterException: () => Effect.void,
306 }),
307 );
308 }),
309 });
310
311 const isPendingConfirmation = (subscriptionArn: string | undefined) =>
312 subscriptionArn === undefined || subscriptionArn.toLowerCase() === "pending confirmation";
313
314 const toAttributeMap = (
315 attributes: Record<string, string | undefined> | undefined,
316 ): Record<string, string> =>
317 Object.fromEntries(
318 Object.entries(attributes ?? {}).filter(
319 (entry): entry is [string, string] => typeof entry[1] === "string",
320 ),
321 );
322
323 const findSubscription = Effect.fn(function* ({
324 topicArn,
325 protocol,
326 endpoint,
327 }: {
328 topicArn: string | undefined;
329 protocol: string | undefined;
330 endpoint: string | undefined;
331 }) {
332 if (!topicArn || !protocol) {
333 return undefined;
334 }
335
336 const match = yield* sns.listSubscriptionsByTopic.items({ TopicArn: topicArn }).pipe(
337 Stream.filter(
338 (subscription) =>
339 subscription.Protocol === protocol &&
340 subscription.Endpoint === endpoint &&
341 !!subscription.SubscriptionArn,
342 ),
343 Stream.runHead,
344 Effect.map(Option.getOrUndefined),
345 );
346
347 return match?.SubscriptionArn;
348 });
349
350 const readSubscription = Effect.fn(function* ({
351 subscriptionArn,
352 topicArn,
353 protocol,
354 endpoint,
355 }: {
356 subscriptionArn?: string;
357 topicArn?: string;
358 protocol?: string;
359 endpoint: string | undefined;
360 }) {
361 let resolvedSubscriptionArn: string | undefined;
362 if (subscriptionArn && !isPendingConfirmation(subscriptionArn)) {
363 resolvedSubscriptionArn = subscriptionArn;
364 } else {
365 // No concrete ARN to hydrate — list the topic's subscriptions and match
366 // by (protocol, endpoint). If the topic itself no longer exists (deleted
367 // out of band, or by an interrupted destroy that committed the topic's
368 // state row late) then the subscription is gone too: report "missing"
369 // rather than failing the read, so a subsequent destroy can proceed.
370 const found = yield* findSubscription({
371 topicArn,
372 protocol,
373 endpoint,
374 }).pipe(
375 Effect.map((arn) => ({ arn })),
376 Effect.catchTag("NotFoundException", () => Effect.undefined),
377 );
378 if (found === undefined) {
379 return undefined;
380 }
381 resolvedSubscriptionArn = found.arn;
382 }
383
384 if (!resolvedSubscriptionArn) {
385 if (!topicArn || !protocol) {
386 return undefined;
387 }
388
389 return {
390 subscriptionArn: subscriptionArn ?? "pending confirmation",
391 topicArn,
392 protocol,
393 endpoint,
394 owner: undefined,
395 pendingConfirmation: true,
396 attributes: {},
397 };
398 }
399
400 const response = yield* sns
401 .getSubscriptionAttributes({
402 SubscriptionArn: resolvedSubscriptionArn,
403 })
404 .pipe(
405 Effect.catchTags({
406 NotFoundException: () => Effect.undefined,
407 InvalidParameterException: () => Effect.undefined,
408 }),
409 );
410
411 if (!response) {
412 return undefined;
413 }
414
415 const attributes = toAttributeMap(response.Attributes);
416 const resolvedTopicArn = attributes.TopicArn ?? topicArn;
417 const resolvedProtocol = attributes.Protocol ?? protocol;
418
419 if (!resolvedTopicArn || !resolvedProtocol) {
420 return undefined;
421 }
422
423 return {
424 subscriptionArn: resolvedSubscriptionArn,
425 topicArn: resolvedTopicArn,
426 protocol: resolvedProtocol,
427 endpoint: attributes.Endpoint ?? endpoint,
428 owner: attributes.Owner,
429 pendingConfirmation:
430 attributes.PendingConfirmation === "true" || isPendingConfirmation(resolvedSubscriptionArn),
431 attributes,
432 };
433 });