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

main
ts 331 lines 11.8 KB
Raw
1 import * as ivschat from "@distilled.cloud/aws/ivschat";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import {
14 retryWhileConflict,
15 retryWhileThrottled,
16 syncIvsChatTags,
17 toTagRecord,
18 } from "./internal.ts";
19
20 export interface LoggingConfigurationDestination {
21 /**
22 * Deliver chat logs to an S3 bucket. Exactly one destination must be
23 * specified.
24 */
25 s3?: { bucketName: string };
26 /**
27 * Deliver chat logs to a CloudWatch Logs log group. Exactly one
28 * destination must be specified.
29 */
30 cloudWatchLogs?: { logGroupName: string };
31 /**
32 * Deliver chat logs to a Kinesis Data Firehose delivery stream.
33 * Exactly one destination must be specified.
34 */
35 firehose?: { deliveryStreamName: string };
36 }
37
38 export interface LoggingConfigurationProps {
39 /**
40 * Where chat messages are delivered: exactly one of `s3`,
41 * `cloudWatchLogs`, or `firehose`.
42 */
43 destinationConfiguration: LoggingConfigurationDestination;
44 /**
45 * Name of the logging configuration (not unique). If omitted, a
46 * deterministic physical name is generated. Mutable — changing the
47 * name updates the configuration in place.
48 */
49 loggingConfigurationName?: string;
50 /**
51 * Tags to apply to the logging configuration. Merged with internal
52 * Alchemy tags.
53 */
54 tags?: Record<string, string>;
55 }
56
57 export interface LoggingConfiguration extends Resource<
58 "AWS.IVSChat.LoggingConfiguration",
59 LoggingConfigurationProps,
60 {
61 /**
62 * The logging configuration's physical name.
63 */
64 loggingConfigurationName: string;
65 /**
66 * ARN of the logging configuration.
67 */
68 loggingConfigurationArn: string;
69 /**
70 * Unique ID of the logging configuration.
71 */
72 loggingConfigurationId: string;
73 /**
74 * Lifecycle state reported by IVS Chat (e.g. `ACTIVE`).
75 */
76 state: string | undefined;
77 },
78 never,
79 Providers
80 > {}
81
82 /**
83 * An Amazon IVS Chat logging configuration — records the chat messages of
84 * the rooms it is attached to into S3, CloudWatch Logs, or a Kinesis
85 * Data Firehose delivery stream.
86 * ### Creating Logging Configurations
87 * **Example:** CloudWatch Logs Destination
88 * ```typescript
89 * import * as IVSChat from "@alchemy.run/aws/IVSChat";
90 * import * as Logs from "@alchemy.run/aws/Logs";
91 *
92 * const logGroup = yield* Logs.LogGroup("ChatLogGroup");
93 * const logging = yield* IVSChat.LoggingConfiguration("ChatLogs", {
94 * destinationConfiguration: {
95 * cloudWatchLogs: { logGroupName: logGroup.logGroupName },
96 * },
97 * });
98 * ```
99 *
100 * **Example:** S3 Destination
101 * ```typescript
102 * const logging = yield* IVSChat.LoggingConfiguration("ChatLogs", {
103 * destinationConfiguration: {
104 * s3: { bucketName: bucket.bucketName },
105 * },
106 * });
107 * ```
108 *
109 * ### Attaching to Rooms
110 * **Example:** Log a Room's Messages
111 * ```typescript
112 * const room = yield* IVSChat.Room("LiveChat", {
113 * loggingConfigurationIdentifiers: [logging.loggingConfigurationArn],
114 * });
115 * ```
116 *
117 * @resource
118 */
119 export const LoggingConfiguration = Resource<LoggingConfiguration>(
120 "AWS.IVSChat.LoggingConfiguration",
121 );
122
123 /**
124 * Raised when a `LoggingConfiguration` does not specify exactly one of
125 * `s3`, `cloudWatchLogs`, or `firehose`, or when the API returns a
126 * configuration missing its identifiers.
127 */
128 export class IvsChatLoggingConfigurationInvalid extends Data.TaggedError(
129 "IvsChatLoggingConfigurationInvalid",
130 )<{ message: string }> {}
131
132 /** Narrow the plain destination prop to the exactly-one wire union. */
133 const toWireDestination = (
134 destination: LoggingConfigurationDestination,
135 ): Effect.Effect<ivschat.DestinationConfiguration, IvsChatLoggingConfigurationInvalid> => {
136 const specified = [destination.s3, destination.cloudWatchLogs, destination.firehose].filter(
137 (d) => d !== undefined,
138 );
139 if (specified.length !== 1) {
140 return Effect.fail(
141 new IvsChatLoggingConfigurationInvalid({
142 message:
143 "destinationConfiguration must specify exactly one of s3, cloudWatchLogs, or firehose",
144 }),
145 );
146 }
147 if (destination.s3) return Effect.succeed({ s3: destination.s3 });
148 if (destination.cloudWatchLogs) {
149 return Effect.succeed({ cloudWatchLogs: destination.cloudWatchLogs });
150 }
151 return Effect.succeed({ firehose: destination.firehose! });
152 };
153
154 /**
155 * Explicitly-typed pipeable poll helper: repeat a read until the
156 * configuration reaches a settled state (bounded — ~60s).
157 */
158 const pollUntilSettled = <A extends { state?: string | undefined } | undefined, E, R>(
159 self: Effect.Effect<A, E, R>,
160 ): Effect.Effect<A, E, R> =>
161 Effect.repeat(self, {
162 until: (config) =>
163 config === undefined || (config.state !== "CREATING" && config.state !== "UPDATING"),
164 schedule: Schedule.fixed("2 seconds"),
165 times: 30,
166 });
167
168 type LoggingConfigurationState = {
169 arn?: string | undefined;
170 id?: string | undefined;
171 name?: string | undefined;
172 destinationConfiguration?: ivschat.DestinationConfiguration | undefined;
173 state?: string | undefined;
174 tags?: { [key: string]: string | undefined } | undefined;
175 };
176
177 export const LoggingConfigurationProvider = () =>
178 Provider.effect(
179 LoggingConfiguration,
180 Effect.gen(function* () {
181 const toName = (id: string, props: { loggingConfigurationName?: string | undefined }) =>
182 props.loggingConfigurationName
183 ? Effect.succeed(props.loggingConfigurationName)
184 : createPhysicalName({ id, maxLength: 128 });
185
186 const toAttrs = Effect.fn(function* (config: LoggingConfigurationState) {
187 if (!config.arn || !config.id || !config.name) {
188 return yield* new IvsChatLoggingConfigurationInvalid({
189 message: "IVS Chat logging configuration is missing its ARN, ID, or name",
190 });
191 }
192 return {
193 loggingConfigurationName: config.name,
194 loggingConfigurationArn: config.arn,
195 loggingConfigurationId: config.id,
196 state: config.state,
197 };
198 });
199
200 const getByIdentifier = Effect.fn(function* (identifier: string) {
201 return yield* ivschat.getLoggingConfiguration({ identifier }).pipe(
202 retryWhileThrottled,
203 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
204 );
205 });
206
207 /** No name filter on ListLoggingConfigurations — enumerate + match. */
208 const findByName = Effect.fn(function* (name: string) {
209 const summaries = yield* ivschat.listLoggingConfigurations.pages({}).pipe(
210 Stream.runCollect,
211 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.loggingConfigurations)),
212 retryWhileThrottled,
213 );
214 const match = summaries.find((s) => s.name === name && s.arn);
215 return match?.arn ? yield* getByIdentifier(match.arn) : undefined;
216 });
217
218 return {
219 stables: ["loggingConfigurationArn", "loggingConfigurationId"],
220
221 read: Effect.fn(function* ({ id, olds, output }) {
222 const config = output?.loggingConfigurationArn
223 ? yield* getByIdentifier(output.loggingConfigurationArn)
224 : yield* findByName(yield* toName(id, olds ?? {}));
225 if (config === undefined) return undefined;
226 const attrs = yield* toAttrs(config);
227 return (yield* hasAlchemyTags(id, toTagRecord(config.tags))) ? attrs : Unowned(attrs);
228 }),
229
230 diff: Effect.fn(function* ({ news }) {
231 if (!isResolved(news)) return undefined;
232 // Validate the exactly-one destination shape before any AWS call.
233 yield* toWireDestination(news.destinationConfiguration);
234 }),
235
236 reconcile: Effect.fn(function* ({ id, news, output, session }) {
237 const name = yield* toName(id, news);
238 const internalTags = yield* createInternalTags(id);
239 const desiredTags = { ...internalTags, ...news.tags };
240 const desiredDestination = yield* toWireDestination(news.destinationConfiguration);
241
242 // 1. Observe — and wait out any in-flight state transition so
243 // the sync step below is allowed to mutate.
244 let observed = output?.loggingConfigurationArn
245 ? yield* pollUntilSettled(getByIdentifier(output.loggingConfigurationArn))
246 : yield* findByName(name);
247
248 // 2. Ensure — create if missing, then wait for ACTIVE (a
249 // configuration is created in state CREATING).
250 if (observed === undefined) {
251 const created = yield* ivschat
252 .createLoggingConfiguration({
253 name,
254 destinationConfiguration: desiredDestination,
255 tags: desiredTags,
256 })
257 .pipe(retryWhileThrottled);
258 if (created.arn !== undefined) {
259 observed = yield* pollUntilSettled(getByIdentifier(created.arn));
260 }
261 }
262 const arn = observed?.arn;
263 if (observed === undefined || arn === undefined) {
264 return yield* new IvsChatLoggingConfigurationInvalid({
265 message: "IVS Chat CreateLoggingConfiguration returned no ARN",
266 });
267 }
268
269 // 3. Sync — name and destination are mutable via
270 // UpdateLoggingConfiguration (allowed only in a settled state;
271 // Conflict retried through a bounded window).
272 const patch: Partial<ivschat.UpdateLoggingConfigurationRequest> = {};
273 if (observed.name !== name) patch.name = name;
274 if (
275 JSON.stringify(observed.destinationConfiguration) !== JSON.stringify(desiredDestination)
276 ) {
277 patch.destinationConfiguration = desiredDestination;
278 }
279 if (Object.keys(patch).length > 0) {
280 yield* ivschat
281 .updateLoggingConfiguration({ identifier: arn, ...patch })
282 .pipe(retryWhileThrottled, retryWhileConflict);
283 }
284
285 // 3b. Sync tags — diff against OBSERVED cloud tags.
286 yield* syncIvsChatTags(arn, desiredTags);
287
288 // 4. Return fresh, settled attributes.
289 const final = yield* pollUntilSettled(getByIdentifier(arn));
290 if (final === undefined) {
291 return yield* new IvsChatLoggingConfigurationInvalid({
292 message: `IVS Chat logging configuration '${arn}' vanished during reconcile`,
293 });
294 }
295 yield* session.note(arn);
296 return yield* toAttrs(final);
297 }),
298
299 delete: Effect.fn(function* ({ output }) {
300 // Deleting mid-transition raises ConflictException — retry
301 // through a bounded window, then tolerate already-gone.
302 yield* ivschat
303 .deleteLoggingConfiguration({
304 identifier: output.loggingConfigurationArn,
305 })
306 .pipe(
307 retryWhileThrottled,
308 retryWhileConflict,
309 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
310 );
311 }),
312
313 list: () =>
314 ivschat.listLoggingConfigurations.pages({}).pipe(
315 Stream.runCollect,
316 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.loggingConfigurations)),
317 Effect.flatMap(
318 Effect.forEach(
319 (summary) =>
320 toAttrs(summary).pipe(
321 // Tolerate a malformed/deleted summary — drop it.
322 Effect.catchTag("IvsChatLoggingConfigurationInvalid", () => Effect.undefined),
323 ),
324 { concurrency: 5 },
325 ),
326 ),
327 Effect.map((items) => items.filter((item) => item !== undefined)),
328 ),
329 };
330 }),
331 );