@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, 06:00 UTC

main
ts 311 lines 11.1 KB
Raw
1 import * as sesv2 from "@distilled.cloud/aws/sesv2";
2 import { unownedUnlessPrevious } 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 * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 /**
15 * A subscription topic on a contact list. Pass the distilled shape directly:
16 * `TopicName` (the stable id), `DisplayName`, an optional `Description`, and a
17 * `DefaultSubscriptionStatus` of `"OPT_IN"` or `"OPT_OUT"`.
18 */
19 export type ContactListTopic = sesv2.Topic;
20
21 export interface ContactListProps {
22 /**
23 * Name of the contact list. May contain letters, numbers, dashes and
24 * underscores, up to 64 characters. If omitted, a deterministic physical
25 * name is generated from the app, stage, and logical ID. Changing the name
26 * replaces the contact list.
27 */
28 contactListName?: string;
29 /**
30 * A human-readable description of the contact list. Leave undefined to keep
31 * whatever SES currently has.
32 */
33 description?: string;
34 /**
35 * The interest topics contacts can subscribe to. Replaced wholesale when
36 * set — pass the full desired set. Leave undefined to keep whatever SES
37 * currently has.
38 */
39 topics?: ContactListTopic[];
40 /**
41 * Tags to apply to the contact list. Merged with internal Alchemy tags.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface ContactList extends Resource<
47 "AWS.SES.ContactList",
48 ContactListProps,
49 {
50 /** Name of the contact list. */
51 contactListName: string;
52 /** ARN of the contact list. */
53 contactListArn: string;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * An Amazon SES v2 contact list — a named audience of email contacts with
61 * subscription topics, used with SES's list-management and unsubscribe
62 * handling.
63 *
64 * Add contacts with `SES.Contact`. Deleting the list deletes all of its
65 * contacts.
66 *
67 * SES allows only **one contact list per AWS account**, so renaming a list
68 * replaces it by deleting the old list (and its contacts) before creating the
69 * new one — a create-then-delete replacement would exceed the account limit.
70 * ### Creating Contact Lists
71 * **Example:** Basic Contact List
72 * ```typescript
73 * import * as SES from "@alchemy.run/aws/SES";
74 *
75 * const list = yield* SES.ContactList("Newsletter", {
76 * description: "Weekly product newsletter",
77 * });
78 * ```
79 *
80 * **Example:** Contact List with Topics
81 * ```typescript
82 * const list = yield* SES.ContactList("Newsletter", {
83 * topics: [
84 * {
85 * TopicName: "product-updates",
86 * DisplayName: "Product Updates",
87 * DefaultSubscriptionStatus: "OPT_IN",
88 * },
89 * {
90 * TopicName: "promotions",
91 * DisplayName: "Promotions",
92 * DefaultSubscriptionStatus: "OPT_OUT",
93 * },
94 * ],
95 * });
96 * ```
97 *
98 * **Example:** Contact List with Tags
99 * ```typescript
100 * const list = yield* SES.ContactList("Newsletter", {
101 * tags: { Team: "growth", Environment: "prod" },
102 * });
103 * ```
104 *
105 * ### Populating the List
106 * **Example:** Add Contacts to the List
107 * ```typescript
108 * const list = yield* SES.ContactList("Newsletter", {
109 * topics: [
110 * {
111 * TopicName: "product-updates",
112 * DisplayName: "Product Updates",
113 * DefaultSubscriptionStatus: "OPT_IN",
114 * },
115 * ],
116 * });
117 *
118 * for (const email of ["a@example.com", "b@example.com"]) {
119 * yield* SES.Contact(`Subscriber-${email}`, {
120 * contactListName: list.contactListName,
121 * emailAddress: email,
122 * topicPreferences: [
123 * { TopicName: "product-updates", SubscriptionStatus: "OPT_IN" },
124 * ],
125 * });
126 * }
127 * ```
128 *
129 * @resource
130 */
131 export const ContactList = Resource<ContactList>("AWS.SES.ContactList");
132
133 const toTagRecord = (
134 tags: ReadonlyArray<{ Key: string; Value: string }> | undefined,
135 ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value]));
136
137 const contactListArnOf = (region: string, accountId: string, name: string) =>
138 `arn:aws:ses:${region}:${accountId}:contact-list/${name}`;
139
140 const sameTopics = (
141 a: ReadonlyArray<ContactListTopic> | undefined,
142 b: ReadonlyArray<ContactListTopic> | undefined,
143 ): boolean => {
144 const key = (topics: ReadonlyArray<ContactListTopic> | undefined) =>
145 JSON.stringify(
146 [...(topics ?? [])]
147 .map((t) => ({
148 TopicName: t.TopicName,
149 DisplayName: t.DisplayName,
150 Description: t.Description,
151 DefaultSubscriptionStatus: t.DefaultSubscriptionStatus,
152 }))
153 .sort((x, y) => x.TopicName.localeCompare(y.TopicName)),
154 );
155 return key(a) === key(b);
156 };
157
158 export const ContactListProvider = () =>
159 Provider.effect(
160 ContactList,
161 Effect.gen(function* () {
162 const createName = Effect.fn(function* (
163 id: string,
164 props: Pick<ContactListProps, "contactListName">,
165 ) {
166 return props.contactListName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
167 });
168
169 const getList = Effect.fn(function* (name: string) {
170 return yield* sesv2
171 .getContactList({ ContactListName: name })
172 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
173 });
174
175 return ContactList.Provider.of({
176 stables: ["contactListName", "contactListArn"],
177
178 list: Effect.fn(function* () {
179 const { accountId, region } = yield* AWSEnvironment.current;
180 const pages = yield* sesv2.listContactLists.pages({}).pipe(Stream.runCollect);
181 return Array.from(pages)
182 .flatMap((page) => page.ContactLists ?? [])
183 .flatMap((entry) =>
184 entry.ContactListName
185 ? [
186 {
187 contactListName: entry.ContactListName,
188 contactListArn: contactListArnOf(region, accountId, entry.ContactListName),
189 },
190 ]
191 : [],
192 );
193 }),
194
195 read: Effect.fn(function* ({ id, olds, output, previous }) {
196 const { accountId, region } = yield* AWSEnvironment.current;
197 const name = output?.contactListName ?? (yield* createName(id, olds ?? {}));
198 const found = yield* getList(name);
199 if (!found) return undefined;
200 const attrs = {
201 contactListName: name,
202 contactListArn: contactListArnOf(region, accountId, name),
203 };
204 const tags = toTagRecord(found.Tags);
205 return (yield* hasAlchemyTags(id, tags))
206 ? attrs
207 : unownedUnlessPrevious(attrs, previous, "contactListName");
208 }),
209
210 diff: Effect.fn(function* ({ id, news, olds }) {
211 if (!isResolved(news)) return undefined;
212 const oldName = yield* createName(id, olds ?? {});
213 const newName = yield* createName(id, news ?? {});
214 if (oldName !== newName) {
215 // Only one contact list is allowed per account, so the old list
216 // has to go before the new one can be created.
217 return { action: "replace", deleteFirst: true } as const;
218 }
219 }),
220
221 reconcile: Effect.fn(function* ({ id, news, output, session }) {
222 const { accountId, region } = yield* AWSEnvironment.current;
223 const name = output?.contactListName ?? (yield* createName(id, news));
224 const contactListArn = contactListArnOf(region, accountId, name);
225 const internalTags = yield* createInternalTags(id);
226 const desiredTags = { ...news.tags, ...internalTags };
227
228 // 1. OBSERVE — cloud state is authoritative.
229 let observed = yield* getList(name);
230
231 if (observed === undefined) {
232 // 2. ENSURE — create with the full desired set; AlreadyExists is a
233 // race → converge via update.
234 yield* sesv2
235 .createContactList({
236 ContactListName: name,
237 Description: news.description,
238 Topics: news.topics,
239 Tags: createTagsList(desiredTags),
240 })
241 .pipe(
242 Effect.catchTag("AlreadyExistsException", () =>
243 sesv2.updateContactList({
244 ContactListName: name,
245 Description: news.description,
246 Topics: news.topics,
247 }),
248 ),
249 );
250 // getList tolerates NotFound; the list is not always readable the
251 // instant create returns, and on the AlreadyExists race another
252 // writer may still be mid-create.
253 observed = (yield* getList(name).pipe(
254 Effect.repeat({
255 schedule: Schedule.spaced("1 second"),
256 until: (list) => list !== undefined,
257 times: 8,
258 }),
259 ))!;
260 } else {
261 // 3. SYNC — only the aspects the caller manages. An omitted prop
262 // keeps whatever SES currently has, matching every sibling
263 // resource in this service; updateContactList replaces each
264 // field it is given, so observed values are echoed back for the
265 // fields we are not managing.
266 const managesDescription = news.description !== undefined;
267 const managesTopics = news.topics !== undefined;
268 const descriptionChanged =
269 managesDescription && observed.Description !== news.description;
270 const topicsChanged = managesTopics && !sameTopics(observed.Topics, news.topics);
271
272 if (descriptionChanged || topicsChanged) {
273 yield* sesv2.updateContactList({
274 ContactListName: name,
275 Description: managesDescription ? news.description : observed.Description,
276 Topics: managesTopics ? news.topics : observed.Topics,
277 });
278 }
279 }
280
281 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
282 // converges.
283 const observedTags = toTagRecord(observed.Tags);
284 const { upsert, removed } = diffTags(observedTags, desiredTags);
285 if (upsert.length > 0) {
286 yield* sesv2.tagResource({
287 ResourceArn: contactListArn,
288 Tags: upsert,
289 });
290 }
291 if (removed.length > 0) {
292 yield* sesv2.untagResource({
293 ResourceArn: contactListArn,
294 TagKeys: removed,
295 });
296 }
297
298 yield* session.note(contactListArn);
299 return { contactListName: name, contactListArn };
300 }),
301
302 delete: Effect.fn(function* ({ output }) {
303 // deleteContactList removes the list and all of its contacts, and is
304 // idempotent for a missing list.
305 yield* sesv2
306 .deleteContactList({ ContactListName: output.contactListName })
307 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
308 }),
309 });
310 }),
311 );