@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 218 lines 7.89 KB
Raw
1 import * as mm from "@distilled.cloud/aws/mailmanager";
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, createTagsList, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 readMailManagerTags,
14 retryWhileMailManagerConflict,
15 syncMailManagerTags,
16 } from "./internal.ts";
17
18 export class AddressListUnexpectedResponse extends Data.TaggedError(
19 "AddressListUnexpectedResponse",
20 )<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export interface AddressListProps {
26 /**
27 * Name of the address list. If omitted, a deterministic physical name is
28 * generated from the app, stage, and logical ID. Mail Manager has no
29 * update operation for address lists, so a rename replaces the list (its
30 * members are NOT carried over).
31 */
32 addressListName?: string;
33 /**
34 * Tags applied to the address list. Alchemy ownership tags are merged in
35 * automatically.
36 */
37 tags?: Record<string, string>;
38 }
39
40 export interface AddressList extends Resource<
41 "AWS.MailManager.AddressList",
42 AddressListProps,
43 {
44 /** Server-assigned ID of the address list. */
45 addressListId: string;
46 /** ARN of the address list. */
47 addressListArn: string;
48 /** Name of the address list. */
49 addressListName: string;
50 },
51 never,
52 Providers
53 > {}
54
55 /**
56 * An SES Mail Manager address list — a named set of email addresses that
57 * traffic policies and rule conditions can match against (allow lists,
58 * block lists, routing groups).
59 *
60 * The list itself is create-only config (name + tags); its members are
61 * data managed at runtime via the member capabilities
62 * ({@link RegisterMemberToAddressList}, {@link ListMembersOfAddressList},
63 * ...) or bulk import jobs.
64 * ### Creating Address Lists
65 * **Example:** Block List
66 * ```typescript
67 * import * as MailManager from "@alchemy.run/aws/MailManager";
68 *
69 * const blockList = yield* MailManager.AddressList("BlockList", {
70 * tags: { purpose: "smtp-block-list" },
71 * });
72 * ```
73 *
74 * ### Managing Members at Runtime
75 * **Example:** Register and List Members from a Lambda
76 * ```typescript
77 * // init — bind the member capabilities to the list
78 * const registerMember = yield* MailManager.RegisterMemberToAddressList(blockList);
79 * const listMembers = yield* MailManager.ListMembersOfAddressList(blockList);
80 *
81 * // runtime
82 * yield* registerMember({ Address: "spammer@example.com" });
83 * const { Addresses } = yield* listMembers({});
84 * ```
85 *
86 * @resource
87 */
88 export const AddressList = Resource<AddressList>("AWS.MailManager.AddressList");
89
90 export const AddressListProvider = () =>
91 Provider.effect(
92 AddressList,
93 Effect.gen(function* () {
94 const createName = Effect.fn(function* (id: string, props: { addressListName?: string }) {
95 return props.addressListName ?? (yield* createPhysicalName({ id, maxLength: 255 }));
96 });
97
98 const getById = (addressListId: string) =>
99 mm
100 .getAddressList({ AddressListId: addressListId })
101 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
102
103 // Address lists have no name-keyed Get — enumerate and match. The
104 // physical name is deterministic, so this recovers identity after a
105 // lost state write.
106 const findByName = (name: string) =>
107 mm.listAddressLists.pages({}).pipe(
108 Stream.runCollect,
109 Effect.map((chunk) =>
110 Array.from(chunk)
111 .flatMap((page) => page.AddressLists ?? [])
112 .find((l) => l.AddressListName === name),
113 ),
114 );
115
116 const observe = Effect.fn(function* (
117 output: AddressList["Attributes"] | undefined,
118 name: string,
119 ) {
120 if (output?.addressListId !== undefined) {
121 const found = yield* getById(output.addressListId);
122 if (found !== undefined) return found;
123 }
124 const summary = yield* findByName(name);
125 if (summary?.AddressListId === undefined) return undefined;
126 return yield* getById(summary.AddressListId);
127 });
128
129 const toAttrs = (list: mm.GetAddressListResponse) => ({
130 addressListId: list.AddressListId,
131 addressListArn: list.AddressListArn,
132 addressListName: list.AddressListName,
133 });
134
135 return AddressList.Provider.of({
136 stables: ["addressListId", "addressListArn"],
137
138 list: () =>
139 mm.listAddressLists.pages({}).pipe(
140 Stream.runCollect,
141 Effect.map((chunk) =>
142 Array.from(chunk)
143 .flatMap((page) => page.AddressLists ?? [])
144 .map((l) => ({
145 addressListId: l.AddressListId,
146 addressListArn: l.AddressListArn,
147 addressListName: l.AddressListName,
148 })),
149 ),
150 ),
151
152 read: Effect.fn(function* ({ id, olds, output }) {
153 const name = output?.addressListName ?? (yield* createName(id, olds ?? {}));
154 const list = yield* observe(output, name);
155 if (list === undefined) return undefined;
156 const attrs = toAttrs(list);
157 const tags = yield* readMailManagerTags(attrs.addressListArn);
158 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
159 }),
160
161 // Mail Manager exposes no UpdateAddressList — a name change can only
162 // be realized by replacement.
163 diff: Effect.fn(function* ({ news, olds }) {
164 if (!isResolved(news)) return undefined;
165 if (olds === undefined) return undefined;
166 if (news.addressListName !== undefined && olds.addressListName !== news.addressListName) {
167 return { action: "replace" } as const;
168 }
169 }),
170
171 reconcile: Effect.fn(function* ({ id, news, output, session }) {
172 const name = yield* createName(id, news);
173 const internalTags = yield* createInternalTags(id);
174 const desiredTags = { ...news.tags, ...internalTags };
175
176 // 1. OBSERVE — cloud state is authoritative; output is an id cache.
177 let list = yield* observe(output, name);
178
179 // 2. ENSURE — create if missing; a Conflict race re-observes by
180 // name instead of failing.
181 if (list === undefined) {
182 yield* session.note(`creating address list ${name}`);
183 const created = yield* mm
184 .createAddressList({
185 AddressListName: name,
186 Tags: createTagsList(desiredTags),
187 })
188 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
189 list =
190 created !== undefined
191 ? yield* getById(created.AddressListId)
192 : yield* observe(undefined, name);
193 }
194 if (list === undefined) {
195 return yield* new AddressListUnexpectedResponse({
196 message: `Mail Manager address list '${name}' not found after create`,
197 });
198 }
199
200 // 3. SYNC TAGS — the only mutable aspect; diffed against observed
201 // cloud tags so adoption converges.
202 yield* syncMailManagerTags(list.AddressListArn, desiredTags);
203
204 yield* session.note(list.AddressListId);
205 return toAttrs(list);
206 }),
207
208 delete: Effect.fn(function* ({ output }) {
209 // DeleteAddressList's error union carries no not-found tag —
210 // deletion is natively idempotent. A list referenced by an
211 // in-flight import job reports Conflict — retry through it.
212 yield* retryWhileMailManagerConflict(
213 mm.deleteAddressList({ AddressListId: output.addressListId }),
214 ).pipe(Effect.asVoid);
215 }),
216 });
217 }),
218 );