@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, 04:45 UTC

main
ts 471 lines 15.1 KB
Raw
1 import * as sns from "@distilled.cloud/aws/sns";
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, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Stream from "effect/Stream";
11 import type { AccountID } from "../Environment.ts";
12 import { normalizePolicyDocument } from "../IAM/Policy.ts";
13 import type { Providers } from "../Providers.ts";
14 import type { RegionID } from "../Region.ts";
15
16 export type TopicName = string;
17 export type TopicArn = `arn:aws:sns:${RegionID}:${AccountID}:${TopicName}`;
18
19 export interface TopicProps {
20 /**
21 * Name of the topic.
22 * @default ${app}-${stage}-${id}?.fifo
23 */
24 topicName?: string;
25 /**
26 * Whether to create a FIFO topic.
27 * @default false
28 */
29 fifo?: boolean;
30 /**
31 * Raw SNS topic attributes keyed by AWS attribute name.
32 * Use this for delivery policies, tracing, KMS, signatures, archive policy, and
33 * other SNS topic attributes not modeled as first-class props.
34 */
35 attributes?: Record<string, string>;
36 /**
37 * SNS data protection policy JSON for the topic.
38 *
39 * TODO(sam): should this be a typed object that we serialize/deserialize?
40 */
41 dataProtectionPolicy?: string;
42 /**
43 * User-defined tags to apply to the topic.
44 */
45 tags?: Record<string, string>;
46 }
47
48 export interface Topic extends Resource<
49 "AWS.SNS.Topic",
50 TopicProps,
51 {
52 topicArn: TopicArn;
53 topicName: TopicName;
54 fifo: boolean;
55 attributes: Record<string, string>;
56 dataProtectionPolicy: string | undefined;
57 tags: Record<string, string>;
58 },
59 never,
60 Providers
61 > {}
62
63 /**
64 * An Amazon SNS topic for fan-out messaging and notifications.
65 *
66 * `Topic` owns the SNS topic lifecycle while raw AWS topic attributes remain
67 * available through the `attributes` prop so the full core pub/sub surface can
68 * be configured without waiting on additional typed wrappers. A topic name is
69 * auto-generated unless you provide one explicitly.
70 * ### Creating Topics
71 * **Example:** Standard Topic
72 * ```typescript
73 * import * as SNS from "@alchemy.run/aws/SNS";
74 *
75 * const topic = yield* SNS.Topic("OrdersTopic");
76 * ```
77 *
78 * **Example:** Topic with Display Name
79 * ```typescript
80 * const topic = yield* SNS.Topic("NotificationsTopic", {
81 * attributes: {
82 * DisplayName: "App Notifications",
83 * },
84 * });
85 * ```
86 *
87 * **Example:** FIFO Topic
88 * ```typescript
89 * const topic = yield* SNS.Topic("OrdersFifoTopic", {
90 * fifo: true,
91 * attributes: {
92 * ContentBasedDeduplication: "true",
93 * },
94 * });
95 * ```
96 *
97 * ### Runtime Publishing
98 * Bind publish operations in the init phase and use them in runtime
99 * handlers.
100 *
101 * **Example:** Publish from a handler
102 * ```typescript
103 * // init
104 * const publish = yield* SNS.Publish(topic);
105 *
106 * return {
107 * fetch: Effect.gen(function* () {
108 * // runtime
109 * yield* publish({
110 * Message: JSON.stringify({ orderId: "123" }),
111 * Subject: "OrderCreated",
112 * });
113 * return HttpServerResponse.text("Published");
114 * }),
115 * };
116 * ```
117 *
118 * ### Subscriptions
119 * Subscribe a Lambda function to process messages published to the
120 * topic. The subscription and invoke permissions are created
121 * automatically.
122 *
123 * **Example:** Process topic notifications
124 * ```typescript
125 * // init
126 * yield* SNS.consumeTopicNotifications(topic, (stream) =>
127 * stream.pipe(
128 * Stream.runForEach((message) =>
129 * Effect.log(`Received: ${message.Message}`),
130 * ),
131 * ),
132 * );
133 * ```
134 *
135 * @resource
136 */
137 export const Topic = Resource<Topic>("AWS.SNS.Topic");
138
139 export const TopicProvider = () =>
140 Provider.succeed(Topic, {
141 // AWS account/region collection: `listTopics` enumerates every topic ARN
142 // in the ambient account+region (paginated, ARN-only), then each ARN is
143 // hydrated via `readTopic` into the exact `read` Attributes shape
144 // (attributes + tags + data protection policy). Per-item not-found is
145 // handled inside `readTopic` (returns undefined) for topics deleted
146 // between enumeration and hydration.
147 list: Effect.fn(function* () {
148 const topicArns = yield* sns.listTopics.pages({}).pipe(
149 Stream.runCollect,
150 Effect.map((chunk) =>
151 Array.from(chunk).flatMap((page) =>
152 (page.Topics ?? [])
153 .map((topic) => topic.TopicArn)
154 .filter((arn): arn is string => typeof arn === "string"),
155 ),
156 ),
157 );
158
159 const rows = yield* Effect.forEach(
160 topicArns,
161 (topicArn) =>
162 readTopic({
163 id: "",
164 topicArn,
165 topicName: topicArn.split(":").at(-1) ?? topicArn,
166 }),
167 { concurrency: 10 },
168 );
169
170 return rows.filter((row): row is NonNullable<typeof row> => row !== undefined);
171 }),
172 read: Effect.fn(function* ({ id, olds, output }) {
173 const topicName = output?.topicName ?? (yield* toTopicName(id, olds ?? {}));
174
175 const state = yield* readTopic({
176 id,
177 topicArn: output?.topicArn,
178 topicName,
179 });
180 if (!state) return undefined;
181 // Reconcile manages (and returns) only the declared attributes; SNS
182 // also reports server-filled ones (`Policy`, `Owner`, subscription
183 // counters). Project onto the declared keys so an untouched topic
184 // does not read as drifted, keeping the persisted value wherever SNS
185 // returns an equivalent JSON document in its own form.
186 const declared = olds ? toAttributes(olds) : undefined;
187 const attrs = {
188 ...state,
189 attributes: declared
190 ? Object.fromEntries(
191 Object.entries(declared).flatMap(([name, value]) => {
192 const observed = state.attributes[name];
193 return observed === undefined
194 ? []
195 : [[name, sameDocument(value, observed) ? value : observed]];
196 }),
197 )
198 : state.attributes,
199 dataProtectionPolicy:
200 output?.dataProtectionPolicy !== undefined &&
201 state.dataProtectionPolicy !== undefined &&
202 sameDocument(output.dataProtectionPolicy, state.dataProtectionPolicy)
203 ? output.dataProtectionPolicy
204 : state.dataProtectionPolicy,
205 };
206 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
207 }),
208 stables: ["topicArn", "topicName", "fifo"],
209 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
210 if (!isResolved(news)) return undefined;
211 if ((news.fifo ?? false) !== (olds.fifo ?? false)) {
212 return { action: "replace" } as const;
213 }
214
215 const oldTopicName = yield* toTopicName(id, olds);
216 const newTopicName = yield* toTopicName(id, news);
217
218 if (oldTopicName !== newTopicName) {
219 return { action: "replace" } as const;
220 }
221
222 if (olds.dataProtectionPolicy !== undefined && news.dataProtectionPolicy === undefined) {
223 return { action: "replace" } as const;
224 }
225 }),
226 reconcile: Effect.fn(function* ({ id, news = {}, olds, session }) {
227 const topicName = yield* toTopicName(id, news);
228 const internalTags = yield* createInternalTags(id);
229 const desiredTags = { ...internalTags, ...news.tags };
230 const desiredAttributes = toAttributes(news);
231 const isFifo = news.fifo ?? false;
232
233 // Observe + ensure — `createTopic` is idempotent for an identical
234 // (name, FifoTopic) pair, so we use it both to ensure-on-greenfield
235 // and to fetch the ARN for adoption. We deliberately pass ONLY the
236 // FifoTopic attribute (which is stable at create time): AWS rejects
237 // createTopic for an existing topic if any other attribute, tag,
238 // or DataProtectionPolicy differs from what's already attached.
239 // Mutable attributes are reconciled below against observed state.
240 const createResponse = yield* sns.createTopic({
241 Name: topicName,
242 Attributes: isFifo ? { FifoTopic: "true" } : undefined,
243 });
244 const topicArn = createResponse.TopicArn;
245 if (!topicArn) {
246 return yield* Effect.die(new Error(`createTopic returned no ARN`));
247 }
248
249 // Sync attributes — fetch observed cloud attributes and apply only
250 // the delta.
251 const observedState = yield* sns
252 .getTopicAttributes({ TopicArn: topicArn })
253 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
254 const observedAttributes = toAttributeMap(observedState?.Attributes);
255
256 for (const [name, value] of Object.entries(desiredAttributes)) {
257 if (observedAttributes[name] !== value) {
258 yield* sns.setTopicAttributes({
259 TopicArn: topicArn,
260 AttributeName: name,
261 AttributeValue: value,
262 });
263 }
264 }
265
266 // Reset previously-user-specified attributes that the user no
267 // longer specifies. Use `olds.attributes` (the prior props) — NOT
268 // `output.attributes`, which on adoption holds every attribute SNS
269 // returns and would erroneously try to reset SNS-managed values
270 // like the auto-generated Policy.
271 const previouslyManaged = olds?.attributes ?? {};
272 for (const name of Object.keys(previouslyManaged)) {
273 if (!(name in desiredAttributes) && name !== "FifoTopic") {
274 yield* sns.setTopicAttributes({
275 TopicArn: topicArn,
276 AttributeName: name,
277 });
278 }
279 }
280
281 // Sync tags — diff observed cloud tags against desired so that an
282 // adoption-takeover (cloud tags identify a different logical id)
283 // correctly rewrites ownership tags.
284 const observedTagsResp = yield* sns
285 .listTagsForResource({ ResourceArn: topicArn })
286 .pipe(
287 Effect.catchTag("ResourceNotFoundException", () =>
288 Effect.succeed({ Tags: [] as sns.Tag[] }),
289 ),
290 );
291 const observedTags = toTagMap(observedTagsResp.Tags);
292 const { removed, upsert } = diffTags(observedTags, desiredTags);
293
294 if (upsert.length > 0) {
295 yield* sns.tagResource({
296 ResourceArn: topicArn,
297 Tags: upsert,
298 });
299 }
300
301 if (removed.length > 0) {
302 yield* sns.untagResource({
303 ResourceArn: topicArn,
304 TagKeys: removed,
305 });
306 }
307
308 // Sync data protection policy — observed ↔ desired. SNS rejects
309 // getDataProtectionPolicy on FIFO topics, so we skip it there.
310 let observedPolicy: string | undefined;
311 if (!isFifo) {
312 observedPolicy = yield* sns.getDataProtectionPolicy({ ResourceArn: topicArn }).pipe(
313 Effect.map((r) => r.DataProtectionPolicy),
314 Effect.catchTags({
315 NotFoundException: () => Effect.undefined,
316 InvalidParameterException: () => Effect.undefined,
317 }),
318 );
319 }
320 if (
321 !isFifo &&
322 news.dataProtectionPolicy !== undefined &&
323 news.dataProtectionPolicy !== observedPolicy
324 ) {
325 yield* sns.putDataProtectionPolicy({
326 ResourceArn: topicArn,
327 DataProtectionPolicy: news.dataProtectionPolicy,
328 });
329 }
330
331 yield* session.note(topicArn);
332
333 return {
334 topicArn: topicArn as TopicArn,
335 topicName,
336 fifo: isFifo,
337 attributes: desiredAttributes,
338 dataProtectionPolicy: news.dataProtectionPolicy ?? observedPolicy,
339 tags: desiredTags,
340 };
341 }),
342 delete: Effect.fn(function* ({ output }) {
343 yield* sns
344 .deleteTopic({
345 TopicArn: output.topicArn,
346 })
347 .pipe(
348 Effect.catchTags({
349 NotFoundException: () => Effect.void,
350 InvalidParameterException: () => Effect.void,
351 }),
352 );
353 }),
354 });
355
356 const toTopicName = Effect.fn(function* (id: string, props: TopicProps) {
357 if (props.topicName) {
358 return props.topicName;
359 }
360
361 const baseName = yield* createPhysicalName({
362 id,
363 maxLength: props.fifo ? 256 - ".fifo".length : 256,
364 });
365
366 return props.fifo ? `${baseName}.fifo` : baseName;
367 });
368
369 const toAttributes = (props: TopicProps): Record<string, string> => ({
370 ...props.attributes,
371 ...(props.fifo ? { FifoTopic: "true" } : undefined),
372 });
373
374 // Whether two attribute values mean the same: equal strings, or JSON
375 // documents (policies) that differ only in SNS's formatting.
376 const sameDocument = (a: string, b: string) =>
377 a === b || normalizePolicyDocument(a) === normalizePolicyDocument(b);
378
379 const toTagMap = (tags: sns.Tag[] | undefined): Record<string, string> =>
380 Object.fromEntries(
381 (tags ?? [])
382 .filter(
383 (tag): tag is Required<Pick<sns.Tag, "Key" | "Value">> =>
384 typeof tag.Key === "string" && typeof tag.Value === "string",
385 )
386 .map((tag) => [tag.Key, tag.Value]),
387 );
388
389 const toAttributeMap = (
390 attributes: Record<string, string | undefined> | undefined,
391 ): Record<string, string> =>
392 Object.fromEntries(
393 Object.entries(attributes ?? {}).filter(
394 (entry): entry is [string, string] => typeof entry[1] === "string",
395 ),
396 );
397
398 const findTopicArnByName = Effect.fn(function* (topicName: string) {
399 const match = yield* sns.listTopics.items({}).pipe(
400 Stream.filter((topic) => topic.TopicArn?.split(":").at(-1) === topicName),
401 Stream.runHead,
402 Effect.map(Option.getOrUndefined),
403 );
404 return match?.TopicArn;
405 });
406
407 const readTopic = Effect.fn(function* ({
408 topicArn,
409 topicName,
410 }: {
411 id: string;
412 topicArn?: string;
413 topicName: string;
414 }) {
415 const resolvedTopicArn = topicArn ?? (yield* findTopicArnByName(topicName));
416
417 if (!resolvedTopicArn) {
418 return undefined;
419 }
420
421 const topicState = yield* Effect.all(
422 [
423 sns.getTopicAttributes({
424 TopicArn: resolvedTopicArn,
425 }),
426 sns.listTagsForResource({
427 ResourceArn: resolvedTopicArn,
428 }),
429 sns
430 .getDataProtectionPolicy({
431 ResourceArn: resolvedTopicArn,
432 })
433 .pipe(
434 Effect.map((response) => response.DataProtectionPolicy),
435 Effect.catchTag(
436 ["NotFoundException", "FifoTopicDataProtectionUnsupported"],
437 () => Effect.undefined,
438 ),
439 ),
440 ],
441 { concurrency: "unbounded" },
442 ).pipe(
443 Effect.catchTags({
444 NotFoundException: () => Effect.undefined,
445 InvalidParameterException: () => Effect.undefined,
446 }),
447 // `list()` hydrates every topic in the account, so a topic deleted by a
448 // parallel test between enumeration and hydration surfaces here —
449 // `listTagsForResource` reports it as `ResourceNotFoundException`. Treat a
450 // vanished topic as "not present" rather than failing the whole listing.
451 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
452 );
453
454 if (!topicState) {
455 return undefined;
456 }
457
458 const [attributes, tags, dataProtectionPolicy] = topicState;
459
460 const topicAttributes = toAttributeMap(attributes.Attributes);
461
462 const apiTags = toTagMap(tags.Tags);
463 return {
464 topicArn: resolvedTopicArn as TopicArn,
465 topicName: topicAttributes.TopicArn?.split(":").at(-1) ?? topicName,
466 fifo: topicAttributes.FifoTopic === "true",
467 attributes: topicAttributes,
468 dataProtectionPolicy,
469 tags: apiTags,
470 };
471 });