@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 380 lines 13.2 KB
Raw
1 import * as ivschat from "@distilled.cloud/aws/ivschat";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
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 Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import {
12 retryWhileHandlerPermissionPropagating,
13 retryWhileThrottled,
14 syncIvsChatTags,
15 toTagRecord,
16 } from "./internal.ts";
17
18 export interface RoomMessageReviewHandler {
19 /**
20 * ARN of the Lambda function that reviews messages before they are
21 * delivered to the room.
22 */
23 uri?: string;
24 /**
25 * What happens to a message if the review handler errors or times out:
26 * `ALLOW` delivers it, `DENY` drops it.
27 * @default "ALLOW"
28 */
29 fallbackResult?: "ALLOW" | "DENY";
30 }
31
32 /**
33 * The binding contract of a room: the message review event source
34 * (`IVSChat.onReviewMessage`) contributes the reviewing Lambda's ARN as the
35 * room's `messageReviewHandler`, which the provider merges with
36 * `props.messageReviewHandler` and syncs onto the room.
37 */
38 export interface RoomBinding {
39 /** Review handler injected by `IVSChat.onReviewMessage`. */
40 messageReviewHandler?: RoomMessageReviewHandler;
41 }
42
43 export interface RoomProps {
44 /**
45 * Name of the room (not unique). If omitted, a deterministic physical
46 * name is generated. Room names are mutable — changing the name
47 * updates the room in place.
48 */
49 roomName?: string;
50 /**
51 * Maximum number of messages per second that can be sent to the room
52 * (`1` - `10`).
53 * @default 10
54 */
55 maximumMessageRatePerSecond?: number;
56 /**
57 * Maximum number of characters in a single message (`1` - `500`).
58 * @default 500
59 */
60 maximumMessageLength?: number;
61 /**
62 * A Lambda-backed handler that reviews (and can modify or deny)
63 * messages before delivery. Prefer wiring it through
64 * `IVSChat.onReviewMessage` — the event source also creates the invoke
65 * Permission and registers the runtime handler.
66 * @default no review handler
67 */
68 messageReviewHandler?: RoomMessageReviewHandler;
69 /**
70 * ARNs or IDs of `LoggingConfiguration`s that record the room's chat
71 * messages.
72 */
73 loggingConfigurationIdentifiers?: string[];
74 /**
75 * Tags to apply to the room. Merged with internal Alchemy tags.
76 */
77 tags?: Record<string, string>;
78 }
79
80 export interface Room extends Resource<
81 "AWS.IVSChat.Room",
82 RoomProps,
83 {
84 /**
85 * The room's physical name.
86 */
87 roomName: string;
88 /**
89 * ARN of the room.
90 */
91 roomArn: string;
92 /**
93 * Unique ID of the room.
94 */
95 roomId: string;
96 },
97 RoomBinding,
98 Providers
99 > {}
100
101 /**
102 * An Amazon IVS Chat room — a virtual space where chat participants
103 * exchange messages over WebSocket connections.
104 *
105 * Clients connect with chat tokens minted at runtime via
106 * `CreateChatToken`; message rate/length limits, a Lambda review handler,
107 * and logging configurations are all managed on the room.
108 * ### Creating Rooms
109 * **Example:** Basic Room
110 * ```typescript
111 * import * as IVSChat from "@alchemy.run/aws/IVSChat";
112 *
113 * const room = yield* IVSChat.Room("LiveChat");
114 * ```
115 *
116 * **Example:** Room with Message Limits
117 * ```typescript
118 * const room = yield* IVSChat.Room("LiveChat", {
119 * maximumMessageRatePerSecond: 5,
120 * maximumMessageLength: 200,
121 * });
122 * ```
123 *
124 * ### Logging
125 * **Example:** Room with Chat Logging
126 * ```typescript
127 * const logging = yield* IVSChat.LoggingConfiguration("ChatLogs", {
128 * destinationConfiguration: {
129 * cloudWatchLogs: { logGroupName: logGroup.logGroupName },
130 * },
131 * });
132 * const room = yield* IVSChat.Room("LiveChat", {
133 * loggingConfigurationIdentifiers: [logging.loggingConfigurationArn],
134 * });
135 * ```
136 *
137 * ### Message Review
138 * **Example:** Review Messages with a Lambda Handler
139 * ```typescript
140 * // inside a Lambda Function's effect — the handler reviews every message
141 * // sent to the room before delivery (allow / modify / deny)
142 * const room = yield* IVSChat.Room("LiveChat");
143 * yield* IVSChat.onReviewMessage(room, (event) =>
144 * Effect.succeed(
145 * event.Content.includes("banned-word")
146 * ? { ReviewResult: "DENY", Attributes: { Reason: "moderated" } }
147 * : undefined,
148 * ),
149 * );
150 * // on the Function effect:
151 * // .pipe(Effect.provide(Lambda.RoomMessageReviewEventSource))
152 * ```
153 *
154 * @resource
155 */
156 export const Room = Resource<Room>("AWS.IVSChat.Room");
157
158 /**
159 * Raised when the IVS Chat API returns a room missing its ARN, ID, or
160 * name.
161 */
162 export class IvsChatRoomIncomplete extends Data.TaggedError("IvsChatRoomIncomplete")<{
163 message: string;
164 }> {}
165
166 /**
167 * Two different Lambda functions were registered as the same room's message
168 * review handler — IVS Chat supports exactly one handler per room.
169 */
170 export class ConflictingRoomMessageReviewHandler extends Data.TaggedError(
171 "ConflictingRoomMessageReviewHandler",
172 )<{ readonly uris: readonly string[] }> {}
173
174 /**
175 * The room's desired `messageReviewHandler`: `props.messageReviewHandler`
176 * merged with the handler contributed through the binding contract
177 * (`IVSChat.onReviewMessage`). Fails when two different handler URIs are
178 * declared. Returns `undefined` when no handler is desired (which clears
179 * any associated handler on update).
180 */
181 const resolveMessageReviewHandler = Effect.fn(function* (
182 news: RoomProps,
183 bindings: ReadonlyArray<RoomBinding | { data?: RoomBinding }>,
184 ) {
185 const contributions = [
186 news.messageReviewHandler,
187 ...bindings.map(
188 (binding) =>
189 (binding as { data?: RoomBinding }).data?.messageReviewHandler ??
190 (binding as RoomBinding).messageReviewHandler,
191 ),
192 ].filter((handler) => handler !== undefined);
193 let resolved: RoomMessageReviewHandler | undefined;
194 for (const handler of contributions) {
195 if (resolved?.uri !== undefined && handler.uri !== undefined && resolved.uri !== handler.uri) {
196 return yield* new ConflictingRoomMessageReviewHandler({
197 uris: [resolved.uri, handler.uri],
198 });
199 }
200 resolved = { ...resolved, ...handler };
201 }
202 return resolved;
203 });
204
205 type RoomState = {
206 arn?: string | undefined;
207 id?: string | undefined;
208 name?: string | undefined;
209 maximumMessageRatePerSecond?: number | undefined;
210 maximumMessageLength?: number | undefined;
211 messageReviewHandler?: ivschat.MessageReviewHandler | undefined;
212 tags?: { [key: string]: string | undefined } | undefined;
213 loggingConfigurationIdentifiers?: string[] | undefined;
214 };
215
216 export const RoomProvider = () =>
217 Provider.effect(
218 Room,
219 Effect.gen(function* () {
220 const toName = (id: string, props: RoomProps) =>
221 props.roomName
222 ? Effect.succeed(props.roomName)
223 : createPhysicalName({ id, maxLength: 128 });
224
225 const toAttrs = Effect.fn(function* (room: RoomState) {
226 if (!room.arn || !room.id || !room.name) {
227 return yield* new IvsChatRoomIncomplete({
228 message: "IVS Chat room is missing its ARN, ID, or name",
229 });
230 }
231 return {
232 roomName: room.name,
233 roomArn: room.arn,
234 roomId: room.id,
235 };
236 });
237
238 const getByIdentifier = Effect.fn(function* (identifier: string) {
239 return yield* ivschat.getRoom({ identifier }).pipe(
240 retryWhileThrottled,
241 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
242 );
243 });
244
245 /** `ListRooms` filters by name server-side; match exactly. */
246 const findByName = Effect.fn(function* (name: string) {
247 const summaries = yield* ivschat.listRooms.pages({ name }).pipe(
248 Stream.runCollect,
249 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.rooms)),
250 retryWhileThrottled,
251 );
252 const match = summaries.find((s) => s.name === name && s.arn);
253 return match?.arn ? yield* getByIdentifier(match.arn) : undefined;
254 });
255
256 return {
257 stables: ["roomArn", "roomId"],
258
259 read: Effect.fn(function* ({ id, olds, output }) {
260 const room = output?.roomArn
261 ? yield* getByIdentifier(output.roomArn)
262 : yield* findByName(yield* toName(id, olds ?? {}));
263 if (room === undefined) return undefined;
264 const attrs = yield* toAttrs(room);
265 return (yield* hasAlchemyTags(id, toTagRecord(room.tags))) ? attrs : Unowned(attrs);
266 }),
267
268 reconcile: Effect.fn(function* ({ id, news, output, session, bindings }) {
269 const name = yield* toName(id, news);
270 const internalTags = yield* createInternalTags(id);
271 const desiredTags = { ...internalTags, ...news.tags };
272 const messageReviewHandler = yield* resolveMessageReviewHandler(news, bindings);
273
274 // 1. Observe.
275 let observed: RoomState | undefined = output?.roomArn
276 ? yield* getByIdentifier(output.roomArn)
277 : yield* findByName(name);
278
279 // 2. Ensure — create if missing.
280 if (observed === undefined) {
281 observed = yield* ivschat
282 .createRoom({
283 name,
284 maximumMessageRatePerSecond: news.maximumMessageRatePerSecond,
285 maximumMessageLength: news.maximumMessageLength,
286 messageReviewHandler,
287 loggingConfigurationIdentifiers: news.loggingConfigurationIdentifiers,
288 tags: desiredTags,
289 })
290 .pipe(retryWhileThrottled, retryWhileHandlerPermissionPropagating);
291 }
292 const arn = observed.arn;
293 if (arn === undefined) {
294 return yield* new IvsChatRoomIncomplete({
295 message: "IVS Chat CreateRoom returned no room ARN",
296 });
297 }
298
299 // 3. Sync — every room setting is mutable via UpdateRoom; apply
300 // only the drifted fields.
301 const patch: Partial<ivschat.UpdateRoomRequest> = {};
302 if (observed.name !== name) patch.name = name;
303 if (
304 news.maximumMessageRatePerSecond !== undefined &&
305 observed.maximumMessageRatePerSecond !== news.maximumMessageRatePerSecond
306 ) {
307 patch.maximumMessageRatePerSecond = news.maximumMessageRatePerSecond;
308 }
309 if (
310 news.maximumMessageLength !== undefined &&
311 observed.maximumMessageLength !== news.maximumMessageLength
312 ) {
313 patch.maximumMessageLength = news.maximumMessageLength;
314 }
315 // Handler sync: `uri: ""` disassociates, and the API defaults
316 // fallbackResult to ALLOW — compare normalized values so a
317 // no-handler desire converges from either direction.
318 const observedHandlerUri = observed.messageReviewHandler?.uri ?? "";
319 const desiredHandlerUri = messageReviewHandler?.uri ?? "";
320 const observedFallback = observed.messageReviewHandler?.fallbackResult ?? "ALLOW";
321 const desiredFallback = messageReviewHandler?.fallbackResult ?? "ALLOW";
322 if (
323 observedHandlerUri !== desiredHandlerUri ||
324 (desiredHandlerUri !== "" && observedFallback !== desiredFallback)
325 ) {
326 patch.messageReviewHandler = messageReviewHandler ?? { uri: "" };
327 }
328 if (
329 news.loggingConfigurationIdentifiers !== undefined &&
330 JSON.stringify(observed.loggingConfigurationIdentifiers ?? []) !==
331 JSON.stringify(news.loggingConfigurationIdentifiers)
332 ) {
333 patch.loggingConfigurationIdentifiers = news.loggingConfigurationIdentifiers;
334 }
335 if (Object.keys(patch).length > 0) {
336 yield* ivschat
337 .updateRoom({ identifier: arn, ...patch })
338 .pipe(retryWhileThrottled, retryWhileHandlerPermissionPropagating);
339 }
340
341 // 3b. Sync tags — diff against OBSERVED cloud tags.
342 yield* syncIvsChatTags(arn, desiredTags);
343
344 // 4. Return fresh attributes.
345 const final = yield* getByIdentifier(arn);
346 if (final === undefined) {
347 return yield* new IvsChatRoomIncomplete({
348 message: `IVS Chat room '${arn}' vanished during reconcile`,
349 });
350 }
351 yield* session.note(arn);
352 return yield* toAttrs(final);
353 }),
354
355 delete: Effect.fn(function* ({ output }) {
356 yield* ivschat.deleteRoom({ identifier: output.roomArn }).pipe(
357 retryWhileThrottled,
358 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
359 );
360 }),
361
362 list: () =>
363 ivschat.listRooms.pages({}).pipe(
364 Stream.runCollect,
365 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.rooms)),
366 Effect.flatMap(
367 Effect.forEach(
368 (summary) =>
369 toAttrs(summary).pipe(
370 // Tolerate a malformed/deleted summary — drop it.
371 Effect.catchTag("IvsChatRoomIncomplete", () => Effect.undefined),
372 ),
373 { concurrency: 5 },
374 ),
375 ),
376 Effect.map((items) => items.filter((item) => item !== undefined)),
377 ),
378 };
379 }),
380 );