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

main
ts 326 lines 11.6 KB
Raw
1 import * as smsvoice from "@distilled.cloud/aws/pinpoint-sms-voice-v2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 readSmsVoiceTags,
14 retrySmsVoiceThrottled,
15 syncSmsVoiceTags,
16 toTagList,
17 } from "./internal.ts";
18
19 export interface PhoneNumberProps {
20 /**
21 * Two-character ISO country code of the requested number, e.g. `US`.
22 * Changing it replaces the phone number.
23 */
24 isoCountryCode: string;
25 /**
26 * Type of messages sent from the number: `TRANSACTIONAL` for
27 * time-sensitive messages or `PROMOTIONAL` for marketing content.
28 * Changing it replaces the phone number.
29 */
30 messageType: "TRANSACTIONAL" | "PROMOTIONAL";
31 /**
32 * Capabilities the number must support: `SMS`, `VOICE`, and/or `MMS`.
33 * Changing them replaces the phone number.
34 */
35 numberCapabilities: string[];
36 /**
37 * Type of number to lease: `SIMULATOR`, `LONG_CODE`, `TOLL_FREE`, or
38 * `TEN_DLC`. `SIMULATOR` numbers only exchange messages with other
39 * simulator destinations and carry the smallest cost — use them for
40 * testing. Changing it replaces the phone number.
41 */
42 numberType: string;
43 /**
44 * Name of the opt-out list to associate with the number.
45 * @default the account's Default opt-out list
46 */
47 optOutListName?: string;
48 /**
49 * When `true`, `ReleasePhoneNumber` is rejected until protection is
50 * disabled again.
51 * @default false
52 */
53 deletionProtectionEnabled?: boolean;
54 /**
55 * Tags to apply to the phone number. Merged with internal Alchemy tags.
56 */
57 tags?: Record<string, string>;
58 }
59
60 export interface PhoneNumber extends Resource<
61 "AWS.PinpointSMSVoiceV2.PhoneNumber",
62 PhoneNumberProps,
63 {
64 /**
65 * ID of the phone number.
66 */
67 phoneNumberId: string;
68 /**
69 * ARN of the phone number.
70 */
71 phoneNumberArn: string;
72 /**
73 * The provisioned phone number in E.164 format.
74 */
75 phoneNumber: string;
76 /**
77 * Provisioning status (e.g. `PENDING`, `ACTIVE`).
78 */
79 status: string;
80 /**
81 * Two-letter ISO country code of the number.
82 */
83 isoCountryCode: string;
84 /**
85 * Message type the number is registered for (`TRANSACTIONAL` or
86 * `PROMOTIONAL`).
87 */
88 messageType: string;
89 /**
90 * Capabilities of the number (`SMS`, `VOICE`, `MMS`).
91 */
92 numberCapabilities: string[];
93 /**
94 * Number type (e.g. `LONG_CODE`, `TOLL_FREE`, `TEN_DLC`).
95 */
96 numberType: string;
97 /**
98 * Monthly leasing price in USD.
99 */
100 monthlyLeasingPrice: string;
101 /**
102 * Opt-out list associated with the number.
103 */
104 optOutListName: string;
105 },
106 never,
107 Providers
108 > {}
109
110 /**
111 * An AWS End User Messaging SMS (Pinpoint SMS Voice v2) origination
112 * phone number leased into your account.
113 *
114 * Requesting a number incurs a monthly leasing fee and most number types
115 * require account-level entitlement (spending limits, registration).
116 * `SIMULATOR` numbers are the cheap, entitlement-free option for testing.
117 * ### Requesting Phone Numbers
118 * **Example:** Simulator Number
119 * ```typescript
120 * import * as PinpointSMSVoiceV2 from "@alchemy.run/aws/PinpointSMSVoiceV2";
121 *
122 * const number = yield* PinpointSMSVoiceV2.PhoneNumber("TestNumber", {
123 * isoCountryCode: "US",
124 * messageType: "TRANSACTIONAL",
125 * numberCapabilities: ["SMS"],
126 * numberType: "SIMULATOR",
127 * });
128 * ```
129 *
130 * **Example:** Toll-Free Number with a Custom Opt-Out List
131 * ```typescript
132 * const optOuts = yield* PinpointSMSVoiceV2.OptOutList("OptOuts");
133 * const number = yield* PinpointSMSVoiceV2.PhoneNumber("Sender", {
134 * isoCountryCode: "US",
135 * messageType: "TRANSACTIONAL",
136 * numberCapabilities: ["SMS", "VOICE"],
137 * numberType: "TOLL_FREE",
138 * optOutListName: optOuts.optOutListName,
139 * });
140 * ```
141 *
142 * @resource
143 */
144 export const PhoneNumber = Resource<PhoneNumber>("AWS.PinpointSMSVoiceV2.PhoneNumber");
145
146 /**
147 * Raised when a phone number cannot be observed after `RequestPhoneNumber`
148 * succeeded, or the API returned a number without its ID.
149 */
150 export class SmsVoicePhoneNumberMissing extends Data.TaggedError("SmsVoicePhoneNumberMissing")<{
151 message: string;
152 }> {}
153
154 /**
155 * Poll a freshly-requested number out of `PENDING` on a bounded schedule
156 * (extracted so declaration emit keeps the provider layer type narrow).
157 */
158 const untilNotPending = <E, R>(
159 self: Effect.Effect<smsvoice.PhoneNumberInformation | undefined, E, R>,
160 ): Effect.Effect<smsvoice.PhoneNumberInformation | undefined, E, R> =>
161 Effect.repeat(self, {
162 until: (p) => p === undefined || p.Status !== "PENDING",
163 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
164 });
165
166 const toAttrs = (info: smsvoice.PhoneNumberInformation) =>
167 Effect.gen(function* () {
168 if (info.PhoneNumberId === undefined) {
169 return yield* new SmsVoicePhoneNumberMissing({
170 message: `phone number '${info.PhoneNumberArn}' is missing its ID`,
171 });
172 }
173 return {
174 phoneNumberId: info.PhoneNumberId,
175 phoneNumberArn: info.PhoneNumberArn,
176 phoneNumber: info.PhoneNumber,
177 status: info.Status,
178 isoCountryCode: info.IsoCountryCode,
179 messageType: info.MessageType,
180 numberCapabilities: [...info.NumberCapabilities],
181 numberType: info.NumberType,
182 monthlyLeasingPrice: info.MonthlyLeasingPrice,
183 optOutListName: info.OptOutListName,
184 };
185 });
186
187 const sameCapabilities = (left: readonly string[], right: readonly string[]) => {
188 const l = [...left].sort();
189 const r = [...right].sort();
190 return l.length === r.length && l.every((v, i) => v === r[i]);
191 };
192
193 export const PhoneNumberProvider = () =>
194 Provider.effect(
195 PhoneNumber,
196 Effect.gen(function* () {
197 const getById = Effect.fn(function* (phoneNumberId: string) {
198 const result = yield* smsvoice
199 .describePhoneNumbers({ PhoneNumberIds: [phoneNumberId] })
200 .pipe(
201 retrySmsVoiceThrottled,
202 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
203 );
204 return result?.PhoneNumbers?.find((p) => p.PhoneNumberId === phoneNumberId);
205 });
206
207 return {
208 stables: ["phoneNumberId", "phoneNumberArn", "phoneNumber", "isoCountryCode", "numberType"],
209
210 read: Effect.fn(function* ({ id, output }) {
211 // Phone number IDs are assigned by AWS — without a cached output
212 // there is no deterministic identity to look up.
213 if (output?.phoneNumberId === undefined) return undefined;
214 const observed = yield* getById(output.phoneNumberId);
215 if (observed === undefined) return undefined;
216 const attrs = yield* toAttrs(observed);
217 const tags = yield* readSmsVoiceTags(observed.PhoneNumberArn);
218 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
219 }),
220
221 diff: Effect.fn(function* ({ news, olds }) {
222 if (!isResolved(news)) return undefined;
223 if (olds === undefined) return undefined;
224 if (
225 olds.isoCountryCode !== news.isoCountryCode ||
226 olds.messageType !== news.messageType ||
227 olds.numberType !== news.numberType ||
228 !sameCapabilities(olds.numberCapabilities ?? [], news.numberCapabilities)
229 ) {
230 return { action: "replace" } as const;
231 }
232 }),
233
234 reconcile: Effect.fn(function* ({ id, news, output, session }) {
235 const internalTags = yield* createInternalTags(id);
236 const desiredTags = { ...news.tags, ...internalTags };
237
238 // 1. Observe — the ID cache in `output` is the only identity.
239 let observed =
240 output?.phoneNumberId === undefined ? undefined : yield* getById(output.phoneNumberId);
241
242 // 2. Ensure — request a number if missing, then wait out PENDING.
243 if (observed === undefined) {
244 const requested = yield* smsvoice
245 .requestPhoneNumber({
246 IsoCountryCode: news.isoCountryCode,
247 MessageType: news.messageType,
248 NumberCapabilities: news.numberCapabilities,
249 NumberType: news.numberType,
250 OptOutListName: news.optOutListName,
251 DeletionProtectionEnabled: news.deletionProtectionEnabled,
252 Tags: toTagList(desiredTags),
253 })
254 .pipe(retrySmsVoiceThrottled);
255 if (requested.PhoneNumberId === undefined) {
256 return yield* new SmsVoicePhoneNumberMissing({
257 message: "RequestPhoneNumber returned no PhoneNumberId",
258 });
259 }
260 observed = yield* getById(requested.PhoneNumberId).pipe(untilNotPending);
261 }
262 if (observed === undefined || observed.PhoneNumberId === undefined) {
263 return yield* new SmsVoicePhoneNumberMissing({
264 message: "phone number not observable after request",
265 });
266 }
267 const phoneNumberId = observed.PhoneNumberId;
268
269 // 3. Sync — apply a single update carrying only the drifted
270 // aspects (opt-out list, deletion protection). Fields the API
271 // couples to unmodeled features (e.g. self-managed opt-outs
272 // require a two-way channel) are never sent.
273 const desiredProtection = news.deletionProtectionEnabled ?? false;
274 const optOutDrift =
275 news.optOutListName !== undefined && observed.OptOutListName !== news.optOutListName;
276 const protectionDrift = observed.DeletionProtectionEnabled !== desiredProtection;
277 if (optOutDrift || protectionDrift) {
278 yield* smsvoice
279 .updatePhoneNumber({
280 PhoneNumberId: phoneNumberId,
281 OptOutListName: optOutDrift ? news.optOutListName : undefined,
282 DeletionProtectionEnabled: protectionDrift ? desiredProtection : undefined,
283 })
284 .pipe(retrySmsVoiceThrottled);
285 }
286
287 // 3b. Sync tags — diff against OBSERVED cloud tags.
288 yield* syncSmsVoiceTags(observed.PhoneNumberArn, desiredTags);
289
290 // 4. Return fresh attributes.
291 const final = yield* getById(phoneNumberId);
292 if (final === undefined) {
293 return yield* new SmsVoicePhoneNumberMissing({
294 message: `phone number '${phoneNumberId}' vanished during reconcile`,
295 });
296 }
297 yield* session.note(final.PhoneNumberArn);
298 return yield* toAttrs(final);
299 }),
300
301 delete: Effect.fn(function* ({ output }) {
302 yield* smsvoice.releasePhoneNumber({ PhoneNumberId: output.phoneNumberId }).pipe(
303 retrySmsVoiceThrottled,
304 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
305 Effect.asVoid,
306 );
307 }),
308
309 list: () =>
310 smsvoice.describePhoneNumbers.items({}).pipe(
311 Stream.runCollect,
312 Effect.flatMap(
313 Effect.forEach(
314 (info) =>
315 toAttrs(info).pipe(
316 // Tolerate a number missing its ID — drop it.
317 Effect.catchTag("SmsVoicePhoneNumberMissing", () => Effect.undefined),
318 ),
319 { concurrency: 5 },
320 ),
321 ),
322 Effect.map((items) => items.filter((item) => item !== undefined)),
323 ),
324 };
325 }),
326 );