@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 369 lines 13.6 KB
Raw
1 import * as ivs from "@distilled.cloud/aws/ivs";
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 { toWireSeconds } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import type { Providers } from "../Providers.ts";
15 import { retryWhileConflict, retryWhileThrottled, syncIvsTags, toTagRecord } from "./internal.ts";
16
17 export interface RecordingDestinationConfiguration {
18 /**
19 * S3 destination for recordings.
20 */
21 s3?: {
22 /**
23 * Name of the S3 bucket recordings are written to. Must be in the
24 * same region and account as the recording configuration.
25 */
26 bucketName: string;
27 };
28 }
29
30 export interface RecordingThumbnailConfiguration {
31 /**
32 * Thumbnail recording mode (`DISABLED` or `INTERVAL`).
33 * @default "INTERVAL"
34 */
35 recordingMode?: "DISABLED" | "INTERVAL";
36 /**
37 * The targeted interval between thumbnails when `recordingMode` is
38 * `INTERVAL`. Accepts any `Duration.Input` (e.g. `"60 seconds"`,
39 * `Duration.minutes(2)`); converted to whole seconds on the wire.
40 * Minimum 1 second, maximum 60 seconds when `storage` includes
41 * `LATEST`.
42 * @default 60 seconds
43 */
44 targetInterval?: Duration.Input;
45 /**
46 * Desired resolution of recorded thumbnails (`SD`, `HD`, `FULL_HD`, or
47 * `LOWEST_RESOLUTION`).
48 * @default the source resolution
49 */
50 resolution?: "SD" | "HD" | "FULL_HD" | "LOWEST_RESOLUTION";
51 /**
52 * Where thumbnails are stored: `SEQUENTIAL` archives all thumbnails,
53 * `LATEST` keeps only the most recent (overwritten in place).
54 * @default ["SEQUENTIAL"]
55 */
56 storage?: ("SEQUENTIAL" | "LATEST")[];
57 }
58
59 export interface RecordingRenditionConfiguration {
60 /**
61 * Which renditions are recorded (`ALL`, `NONE`, or `CUSTOM`).
62 * @default "ALL"
63 */
64 renditionSelection?: "ALL" | "NONE" | "CUSTOM";
65 /**
66 * The renditions recorded when `renditionSelection` is `CUSTOM` (`SD`,
67 * `HD`, `FULL_HD`, `LOWEST_RESOLUTION`).
68 */
69 renditions?: ("SD" | "HD" | "FULL_HD" | "LOWEST_RESOLUTION")[];
70 }
71
72 export interface RecordingConfigurationProps {
73 /**
74 * Where recordings are written (an S3 bucket in the same region and
75 * account). Changing the destination replaces the recording
76 * configuration.
77 */
78 destinationConfiguration: RecordingDestinationConfiguration;
79 /**
80 * Name of the recording configuration. If omitted, a deterministic
81 * physical name is generated. There is no update operation, so
82 * changing the name replaces the recording configuration.
83 */
84 recordingConfigurationName?: string;
85 /**
86 * If a broadcast disconnects and reconnects within this window, the
87 * multiple streams are considered a single broadcast and merged into a
88 * single recording. Accepts any `Duration.Input` (e.g. `"2 minutes"`,
89 * `Duration.seconds(30)`); converted to whole seconds on the wire.
90 * Maximum 5 minutes. Changing the window replaces the recording
91 * configuration.
92 * @default 0 seconds (no merge)
93 */
94 recordingReconnectWindow?: Duration.Input;
95 /**
96 * Thumbnail generation settings for the recording. Changing them
97 * replaces the recording configuration.
98 */
99 thumbnailConfiguration?: RecordingThumbnailConfiguration;
100 /**
101 * Which renditions of the live stream are recorded. Changing them
102 * replaces the recording configuration.
103 */
104 renditionConfiguration?: RecordingRenditionConfiguration;
105 /**
106 * Tags to apply to the recording configuration. Merged with internal
107 * Alchemy tags.
108 */
109 tags?: Record<string, string>;
110 }
111
112 export interface RecordingConfiguration extends Resource<
113 "AWS.IVS.RecordingConfiguration",
114 RecordingConfigurationProps,
115 {
116 /**
117 * ARN of the recording configuration.
118 */
119 recordingConfigurationArn: string;
120 /**
121 * The recording configuration's physical name.
122 */
123 recordingConfigurationName: string | undefined;
124 /**
125 * Name of the S3 bucket recordings are written to.
126 */
127 bucketName: string | undefined;
128 /**
129 * State of the recording configuration (`CREATING`, `ACTIVE`, or
130 * `CREATE_FAILED`).
131 */
132 state: string;
133 },
134 never,
135 Providers
136 > {}
137
138 /**
139 * An Amazon IVS recording configuration, enabling automatic recording of
140 * live broadcasts to Amazon S3.
141 *
142 * Attach the configuration to a channel via the channel's
143 * `recordingConfigurationArn` prop; every broadcast on that channel is
144 * then archived to the configured bucket. Recording configurations are
145 * immutable — any settings change replaces the resource.
146 * ### Recording Broadcasts
147 * **Example:** Record a Channel to S3
148 * ```typescript
149 * import * as AWS from "@alchemy.run/aws";
150 * import * as IVS from "@alchemy.run/aws/IVS";
151 *
152 * const archive = yield* AWS.Bucket("StreamArchive");
153 * const recording = yield* IVS.RecordingConfiguration("Recording", {
154 * destinationConfiguration: { s3: { bucketName: archive.bucketName } },
155 * });
156 * const channel = yield* IVS.Channel("LiveChannel", {
157 * recordingConfigurationArn: recording.recordingConfigurationArn,
158 * });
159 * ```
160 *
161 * **Example:** Merge Reconnects and Record Thumbnails
162 * ```typescript
163 * const recording = yield* IVS.RecordingConfiguration("Recording", {
164 * destinationConfiguration: { s3: { bucketName: archive.bucketName } },
165 * recordingReconnectWindow: "2 minutes",
166 * thumbnailConfiguration: {
167 * recordingMode: "INTERVAL",
168 * targetInterval: "30 seconds",
169 * },
170 * });
171 * ```
172 *
173 * @resource
174 */
175 export const RecordingConfiguration = Resource<RecordingConfiguration>(
176 "AWS.IVS.RecordingConfiguration",
177 );
178
179 /**
180 * Raised when the IVS API returns a recording configuration in an
181 * unusable shape or state (missing from a create response, or stuck in
182 * `CREATE_FAILED`).
183 */
184 export class IvsRecordingConfigurationFailed extends Data.TaggedError(
185 "IvsRecordingConfigurationFailed",
186 )<{ message: string }> {}
187
188 export const RecordingConfigurationProvider = () =>
189 Provider.effect(
190 RecordingConfiguration,
191 Effect.gen(function* () {
192 const toName = (id: string, props: { recordingConfigurationName?: string | undefined }) =>
193 props.recordingConfigurationName
194 ? Effect.succeed(props.recordingConfigurationName)
195 : createPhysicalName({ id, maxLength: 128 });
196
197 const toAttrs = (config: {
198 arn: string;
199 name?: string | undefined;
200 destinationConfiguration: ivs.DestinationConfiguration;
201 state: string;
202 }) => ({
203 recordingConfigurationArn: config.arn,
204 recordingConfigurationName: config.name,
205 bucketName: config.destinationConfiguration.s3?.bucketName,
206 state: config.state,
207 });
208
209 const getByArn = Effect.fn(function* (arn: string) {
210 const response = yield* ivs.getRecordingConfiguration({ arn }).pipe(
211 retryWhileThrottled,
212 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
213 );
214 return response?.recordingConfiguration;
215 });
216
217 /**
218 * ListRecordingConfigurations has no name filter — enumerate and
219 * match exactly (names are not unique; first hit wins). Used only
220 * when the output ARN cache is unavailable.
221 */
222 const findByName = Effect.fn(function* (name: string) {
223 const summaries = yield* ivs.listRecordingConfigurations.pages({}).pipe(
224 Stream.runCollect,
225 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.recordingConfigurations)),
226 retryWhileThrottled,
227 );
228 const match = summaries.find((s) => s.name === name);
229 return match === undefined ? undefined : yield* getByArn(match.arn);
230 });
231
232 /**
233 * Wait (bounded) for a freshly created configuration to leave
234 * `CREATING`. `CREATE_FAILED` (e.g. the bucket is in another
235 * region) is surfaced as a typed failure.
236 */
237 const awaitActive = Effect.fn(function* (arn: string) {
238 const config = yield* getByArn(arn).pipe(
239 Effect.repeat({
240 schedule: Schedule.fixed("3 seconds"),
241 until: (c): boolean => c === undefined || c.state !== "CREATING",
242 times: 20,
243 }),
244 );
245 if (config === undefined) {
246 return yield* new IvsRecordingConfigurationFailed({
247 message: `IVS recording configuration '${arn}' vanished while awaiting ACTIVE`,
248 });
249 }
250 if (config.state === "CREATE_FAILED") {
251 return yield* new IvsRecordingConfigurationFailed({
252 message: `IVS recording configuration '${arn}' entered CREATE_FAILED — is the S3 bucket in the same region and account?`,
253 });
254 }
255 return config;
256 });
257
258 return {
259 stables: ["recordingConfigurationArn"],
260
261 read: Effect.fn(function* ({ id, olds, output }) {
262 const config = output?.recordingConfigurationArn
263 ? yield* getByArn(output.recordingConfigurationArn)
264 : yield* findByName(yield* toName(id, olds ?? {}));
265 if (config === undefined) return undefined;
266 const attrs = toAttrs(config);
267 return (yield* hasAlchemyTags(id, toTagRecord(config.tags))) ? attrs : Unowned(attrs);
268 }),
269
270 diff: Effect.fn(function* ({ id, news, olds }) {
271 if (!isResolved(news)) return undefined;
272 // There is no UpdateRecordingConfiguration — every setting
273 // except tags is immutable and requires a replacement.
274 const changed =
275 (yield* toName(id, olds)) !== (yield* toName(id, news)) ||
276 olds.destinationConfiguration.s3?.bucketName !==
277 news.destinationConfiguration.s3?.bucketName ||
278 toWireSeconds(olds.recordingReconnectWindow) !==
279 toWireSeconds(news.recordingReconnectWindow) ||
280 JSON.stringify({
281 ...olds.thumbnailConfiguration,
282 targetInterval: toWireSeconds(olds.thumbnailConfiguration?.targetInterval),
283 }) !==
284 JSON.stringify({
285 ...news.thumbnailConfiguration,
286 targetInterval: toWireSeconds(news.thumbnailConfiguration?.targetInterval),
287 }) ||
288 JSON.stringify(olds.renditionConfiguration) !==
289 JSON.stringify(news.renditionConfiguration);
290 if (changed) return { action: "replace" } as const;
291 }),
292
293 reconcile: Effect.fn(function* ({ id, news, output, session }) {
294 const name = yield* toName(id, news);
295 const internalTags = yield* createInternalTags(id);
296 const desiredTags = { ...internalTags, ...news.tags };
297
298 // 1. Observe — the live configuration is authoritative; the
299 // output ARN is only an identifier cache.
300 let observed = output?.recordingConfigurationArn
301 ? yield* getByArn(output.recordingConfigurationArn)
302 : yield* findByName(name);
303
304 // 2. Ensure — create if missing, then wait for ACTIVE.
305 if (observed === undefined) {
306 const thumbnail = news.thumbnailConfiguration;
307 const created = yield* ivs
308 .createRecordingConfiguration({
309 name,
310 destinationConfiguration: news.destinationConfiguration,
311 recordingReconnectWindowSeconds: toWireSeconds(news.recordingReconnectWindow),
312 thumbnailConfiguration:
313 thumbnail === undefined
314 ? undefined
315 : {
316 recordingMode: thumbnail.recordingMode,
317 targetIntervalSeconds: toWireSeconds(thumbnail.targetInterval),
318 resolution: thumbnail.resolution,
319 storage: thumbnail.storage,
320 },
321 renditionConfiguration: news.renditionConfiguration,
322 tags: desiredTags,
323 })
324 .pipe(retryWhileThrottled);
325 observed = created.recordingConfiguration;
326 }
327 if (observed === undefined) {
328 return yield* new IvsRecordingConfigurationFailed({
329 message: "IVS CreateRecordingConfiguration returned no configuration",
330 });
331 }
332 const arn = observed.arn;
333 yield* session.note(arn);
334 const active = yield* awaitActive(arn);
335
336 // 3. Sync tags — the only mutable aspect. Diff against OBSERVED
337 // cloud tags so adoption converges.
338 yield* syncIvsTags(arn, desiredTags);
339
340 // 4. Return fresh attributes.
341 return toAttrs(active);
342 }),
343
344 delete: Effect.fn(function* ({ output }) {
345 // Deleting a configuration still attached to a channel raises
346 // ConflictException — retry through a bounded window, then
347 // tolerate already-gone.
348 yield* ivs
349 .deleteRecordingConfiguration({
350 arn: output.recordingConfigurationArn,
351 })
352 .pipe(
353 retryWhileThrottled,
354 retryWhileConflict,
355 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
356 );
357 }),
358
359 list: () =>
360 ivs.listRecordingConfigurations.pages({}).pipe(
361 Stream.runCollect,
362 Effect.map((chunk) =>
363 Array.from(chunk).flatMap((page) => page.recordingConfigurations),
364 ),
365 Effect.map((summaries) => summaries.map((summary) => toAttrs(summary))),
366 ),
367 };
368 }),
369 );