@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 327 lines 12.1 KB
Raw
1 import * as sesv2 from "@distilled.cloud/aws/sesv2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8
9 /**
10 * A contact's subscription preference for a single topic. Pass the distilled
11 * shape directly: `TopicName` and a `SubscriptionStatus` of `"OPT_IN"` or
12 * `"OPT_OUT"`.
13 */
14 export type ContactTopicPreference = sesv2.TopicPreference;
15
16 export interface ContactProps {
17 /**
18 * Name of the contact list this contact belongs to. Typically the
19 * `contactListName` output of a `SES.ContactList`. Changing it replaces the
20 * contact.
21 */
22 contactListName: string;
23 /**
24 * The contact's email address — the stable identifier within the list.
25 * Changing it replaces the contact.
26 */
27 emailAddress: string;
28 /**
29 * The contact's per-topic subscription preferences. Replaced wholesale when
30 * set — pass the full desired set. Leave undefined to keep whatever SES
31 * currently has.
32 */
33 topicPreferences?: ContactTopicPreference[];
34 /**
35 * Whether the contact is unsubscribed from all topics. Leave undefined to
36 * keep SES's current setting.
37 * @default false
38 */
39 unsubscribeAll?: boolean;
40 /**
41 * Arbitrary application metadata attached to the contact. Serialized to the
42 * JSON string SES stores; equivalent representations (key order, whitespace)
43 * are ignored when detecting drift. Leave undefined to keep whatever SES
44 * currently has.
45 */
46 attributes?: Record<string, unknown>;
47 }
48
49 export interface Contact extends Resource<
50 "AWS.SES.Contact",
51 ContactProps,
52 {
53 /** Name of the contact list the contact belongs to. */
54 contactListName: string;
55 /** The contact's email address. */
56 emailAddress: string;
57 },
58 never,
59 Providers
60 > {}
61
62 /**
63 * An Amazon SES v2 contact — a single email address on a `SES.ContactList`,
64 * with its own topic subscription preferences and unsubscribe state.
65 * ### Adding Contacts
66 * **Example:** Basic Contact
67 * ```typescript
68 * import * as SES from "@alchemy.run/aws/SES";
69 *
70 * const list = yield* SES.ContactList("Newsletter", {});
71 * const contact = yield* SES.Contact("Subscriber", {
72 * contactListName: list.contactListName,
73 * emailAddress: "reader@example.com",
74 * });
75 * ```
76 *
77 * **Example:** Contact with Topic Preferences
78 * ```typescript
79 * const contact = yield* SES.Contact("Subscriber", {
80 * contactListName: list.contactListName,
81 * emailAddress: "reader@example.com",
82 * topicPreferences: [
83 * { TopicName: "product-updates", SubscriptionStatus: "OPT_IN" },
84 * { TopicName: "promotions", SubscriptionStatus: "OPT_OUT" },
85 * ],
86 * });
87 * ```
88 *
89 * **Example:** Unsubscribe a Contact from Everything
90 * ```typescript
91 * // unsubscribeAll overrides every per-topic preference.
92 * const contact = yield* SES.Contact("Subscriber", {
93 * contactListName: list.contactListName,
94 * emailAddress: "reader@example.com",
95 * unsubscribeAll: true,
96 * });
97 * ```
98 *
99 * ### Application Metadata
100 * **Example:** Attach Your Own Data to a Contact
101 * ```typescript
102 * // Serialized to the JSON string SES stores; re-ordering the keys is not a
103 * // change, so this does not churn on every deploy.
104 * const contact = yield* SES.Contact("Subscriber", {
105 * contactListName: list.contactListName,
106 * emailAddress: "reader@example.com",
107 * attributes: { plan: "pro", signupSource: "docs" },
108 * });
109 * ```
110 *
111 * @resource
112 */
113 export const Contact = Resource<Contact>("AWS.SES.Contact");
114
115 // SES stores contact metadata as an opaque JSON string. Serialize only at the
116 // API boundary, and compare on a canonical (sorted-key) form so a re-ordered
117 // object is not mistaken for a change.
118 const stringifyAttributes = (
119 attributes: Record<string, unknown> | undefined,
120 ): string | undefined => (attributes === undefined ? undefined : JSON.stringify(attributes));
121
122 const normalizeAttributes = (
123 attributes: Record<string, unknown> | string | undefined,
124 ): string | undefined => {
125 if (attributes === undefined) return undefined;
126 let value: unknown = attributes;
127 if (typeof attributes === "string") {
128 try {
129 value = JSON.parse(attributes) as unknown;
130 } catch {
131 // Not JSON (a hand-written contact, say) — compare the raw string.
132 return attributes;
133 }
134 }
135 const canonical = (input: unknown): unknown =>
136 Array.isArray(input)
137 ? input.map(canonical)
138 : input !== null && typeof input === "object"
139 ? Object.fromEntries(
140 Object.entries(input as Record<string, unknown>)
141 .sort(([a], [b]) => a.localeCompare(b))
142 .map(([key, val]) => [key, canonical(val)]),
143 )
144 : input;
145 return JSON.stringify(canonical(value));
146 };
147
148 const samePreferences = (
149 a: ReadonlyArray<ContactTopicPreference> | undefined,
150 b: ReadonlyArray<ContactTopicPreference> | undefined,
151 ): boolean => {
152 const key = (prefs: ReadonlyArray<ContactTopicPreference> | undefined) =>
153 JSON.stringify(
154 [...(prefs ?? [])]
155 .map((p) => ({
156 TopicName: p.TopicName,
157 SubscriptionStatus: p.SubscriptionStatus,
158 }))
159 .sort((x, y) => x.TopicName.localeCompare(y.TopicName)),
160 );
161 return key(a) === key(b);
162 };
163
164 export const ContactProvider = () =>
165 Provider.effect(
166 Contact,
167 Effect.gen(function* () {
168 const getContact = Effect.fn(function* (contactListName: string, emailAddress: string) {
169 return yield* sesv2
170 .getContact({
171 ContactListName: contactListName,
172 EmailAddress: emailAddress,
173 })
174 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
175 });
176
177 return Contact.Provider.of({
178 // Deleting a contact requires its parent list to still exist, so the
179 // list must outlive every contact nuke tears down.
180 nuke: { dependsOn: ["AWS.SES.ContactList"] },
181 stables: ["contactListName", "emailAddress"],
182
183 // Contacts are keyed by their parent list, so enumeration walks every
184 // contact list and pages through its contacts. SES allows one contact
185 // list per account, so the outer page is at most one entry.
186 list: Effect.fn(function* () {
187 const listPages = yield* sesv2.listContactLists.pages({}).pipe(Stream.runCollect);
188 const contactListNames = Array.from(listPages)
189 .flatMap((page) => page.ContactLists ?? [])
190 .flatMap((entry) => (entry.ContactListName ? [entry.ContactListName] : []));
191 const nested = yield* Effect.forEach(
192 contactListNames,
193 (contactListName) =>
194 sesv2.listContacts.pages({ ContactListName: contactListName }).pipe(
195 Stream.runCollect,
196 Effect.map((pages) =>
197 Array.from(pages)
198 .flatMap((page) => page.Contacts ?? [])
199 .flatMap((contact) =>
200 contact.EmailAddress
201 ? [
202 {
203 contactListName,
204 emailAddress: contact.EmailAddress,
205 },
206 ]
207 : [],
208 ),
209 ),
210 // The list can be deleted between the two calls.
211 Effect.catchTag("NotFoundException", () =>
212 Effect.succeed(
213 [] as {
214 contactListName: string;
215 emailAddress: string;
216 }[],
217 ),
218 ),
219 ),
220 { concurrency: 2 },
221 );
222 return nested.flat();
223 }),
224
225 read: Effect.fn(function* ({ olds, output }) {
226 const contactListName = output?.contactListName ?? olds?.contactListName;
227 const emailAddress = output?.emailAddress ?? olds?.emailAddress;
228 if (contactListName === undefined || emailAddress === undefined) {
229 return undefined;
230 }
231 const found = yield* getContact(contactListName, emailAddress);
232 // Contacts carry no tags, so existence at the (list, email) key is
233 // treated as ownership.
234 return found ? { contactListName, emailAddress } : undefined;
235 }),
236
237 diff: Effect.fn(function* ({ news, olds }) {
238 if (!isResolved(news)) return undefined;
239 if (
240 news.contactListName !== olds.contactListName ||
241 news.emailAddress !== olds.emailAddress
242 ) {
243 return { action: "replace" } as const;
244 }
245 }),
246
247 reconcile: Effect.fn(function* ({ news, output }) {
248 const contactListName = output?.contactListName ?? news.contactListName;
249 const emailAddress = output?.emailAddress ?? news.emailAddress;
250 const attributesData = yield* Effect.sync(() => stringifyAttributes(news.attributes));
251
252 // 1. OBSERVE — cloud state is authoritative.
253 const observed = yield* getContact(contactListName, emailAddress);
254
255 if (observed === undefined) {
256 // 2. ENSURE — create; AlreadyExists is a race → converge via update.
257 yield* sesv2
258 .createContact({
259 ContactListName: contactListName,
260 EmailAddress: emailAddress,
261 TopicPreferences: news.topicPreferences,
262 UnsubscribeAll: news.unsubscribeAll,
263 AttributesData: attributesData,
264 })
265 .pipe(
266 Effect.catchTag("AlreadyExistsException", () =>
267 sesv2.updateContact({
268 ContactListName: contactListName,
269 EmailAddress: emailAddress,
270 TopicPreferences: news.topicPreferences,
271 UnsubscribeAll: news.unsubscribeAll,
272 AttributesData: attributesData,
273 }),
274 ),
275 );
276 } else {
277 // 3. SYNC — only the aspects the caller manages. An omitted prop
278 // keeps whatever SES currently has, matching every sibling
279 // resource in this service; updateContact replaces each field
280 // it is given, so observed values are echoed back for the
281 // fields we are not managing.
282 const managesPreferences = news.topicPreferences !== undefined;
283 const managesUnsubscribe = news.unsubscribeAll !== undefined;
284 const managesAttributes = news.attributes !== undefined;
285
286 const preferencesChanged =
287 managesPreferences &&
288 !samePreferences(observed.TopicPreferences, news.topicPreferences);
289 const unsubscribeChanged =
290 managesUnsubscribe && (observed.UnsubscribeAll ?? false) !== news.unsubscribeAll;
291 const attributesChanged =
292 managesAttributes &&
293 (yield* Effect.sync(
294 () =>
295 normalizeAttributes(observed.AttributesData) !==
296 normalizeAttributes(news.attributes),
297 ));
298
299 if (preferencesChanged || unsubscribeChanged || attributesChanged) {
300 yield* sesv2.updateContact({
301 ContactListName: contactListName,
302 EmailAddress: emailAddress,
303 TopicPreferences: managesPreferences
304 ? news.topicPreferences
305 : observed.TopicPreferences,
306 UnsubscribeAll: managesUnsubscribe ? news.unsubscribeAll : observed.UnsubscribeAll,
307 AttributesData: managesAttributes ? attributesData : observed.AttributesData,
308 });
309 }
310 }
311
312 return { contactListName, emailAddress };
313 }),
314
315 delete: Effect.fn(function* ({ output }) {
316 // deleteContact is idempotent for a missing contact; a missing list
317 // means the contact is already gone.
318 yield* sesv2
319 .deleteContact({
320 ContactListName: output.contactListName,
321 EmailAddress: output.emailAddress,
322 })
323 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
324 }),
325 });
326 }),
327 );