@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 318 lines 10.7 KB
Raw
1 import * as stream from "@distilled.cloud/cloudflare/stream";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9
10 const TypeId = "Cloudflare.Stream.LiveInput" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * Recording behavior of a live input.
15 */
16 export type LiveInputRecording = {
17 /**
18 * Origins allowed to display videos created from this live input.
19 * Enter allowed origin domains in an array, e.g. `["example.com"]`.
20 */
21 allowedOrigins?: string[];
22 /**
23 * Disables reporting the number of live viewers when this is set to
24 * `true`.
25 * @default false
26 */
27 hideLiveViewerCount?: boolean;
28 /**
29 * Specifies the recording behavior for the live input. `off` prevents
30 * the input from being recorded; `automatic` records the input as a
31 * Cloudflare Stream video whenever a stream is live.
32 * @default "off"
33 */
34 mode?: "off" | "automatic";
35 /**
36 * Indicates if signed URL tokens are required to view the recorded
37 * video.
38 * @default false
39 */
40 requireSignedURLs?: boolean;
41 /**
42 * Number of seconds the live input is considered live after the
43 * broadcast stops, before the recording transitions to on-demand.
44 * @default 0
45 */
46 timeoutSeconds?: number;
47 };
48
49 export type LiveInputProps = {
50 /**
51 * Sets the creator ID associated with this live input. Mutable.
52 */
53 defaultCreator?: string;
54 /**
55 * Number of days after which the live input's recordings are deleted.
56 * The minimum accepted value is 30. Omit to retain recordings
57 * indefinitely. Mutable.
58 */
59 deleteRecordingAfterDays?: number;
60 /**
61 * Whether the live input is enabled and can accept streams. Mutable.
62 * @default true
63 */
64 enabled?: boolean;
65 /**
66 * A user modifiable key-value store used to reference other systems of
67 * record for managing live inputs. By convention, set a `name` field
68 * for display in the Cloudflare dashboard. If omitted, a `name`
69 * derived from the app, stage, and logical ID is used. Mutable.
70 * @default { name: ${app}-${stage}-${id} }
71 */
72 meta?: Record<string, unknown>;
73 /**
74 * Records the input to a Cloudflare Stream video when set to
75 * `automatic` mode. Mutable.
76 * @default { mode: "off" }
77 */
78 recording?: LiveInputRecording;
79 };
80
81 export type LiveInputAttributes = {
82 /**
83 * The unique identifier for the live input (Cloudflare `uid`).
84 */
85 liveInputId: string;
86 /**
87 * The Cloudflare account the live input belongs to.
88 */
89 accountId: string;
90 /**
91 * The date and time the live input was created.
92 */
93 created: string | undefined;
94 /**
95 * The date and time the live input was last modified.
96 */
97 modified: string | undefined;
98 /**
99 * Whether the live input is enabled and can accept streams.
100 */
101 enabled: boolean;
102 /**
103 * Number of days after which the live input's recordings are deleted,
104 * if configured.
105 */
106 deleteRecordingAfterDays: number | undefined;
107 /**
108 * The user-modifiable key-value store associated with the live input.
109 */
110 meta: Record<string, unknown>;
111 };
112
113 export type LiveInput = Resource<TypeId, LiveInputProps, LiveInputAttributes, never, Providers>;
114
115 /**
116 * A Cloudflare Stream live input — an ingest endpoint (RTMPS/SRT/WebRTC)
117 * that accepts live video and optionally records it as a Stream video.
118 *
119 * Live inputs are identified by an auto-assigned `uid`; every prop is
120 * mutable in place via Cloudflare's PUT endpoint, so the resource is
121 * never replaced. Deleting a live input does not delete videos already
122 * recorded from it.
123 *
124 * Requires the Stream subscription to be enabled on the account.
125 * ### Creating a live input
126 * **Example:** Basic live input
127 * ```typescript
128 * const input = yield* Cloudflare.Stream.LiveInput("Broadcast", {});
129 * ```
130 *
131 * **Example:** Live input with automatic recording
132 * ```typescript
133 * const input = yield* Cloudflare.Stream.LiveInput("Broadcast", {
134 * meta: { name: "town-hall" },
135 * recording: {
136 * mode: "automatic",
137 * timeoutSeconds: 10,
138 * },
139 * deleteRecordingAfterDays: 30,
140 * });
141 * ```
142 *
143 * ### Managing a live input
144 * **Example:** Disable ingest without deleting the input
145 * ```typescript
146 * const input = yield* Cloudflare.Stream.LiveInput("Broadcast", {
147 * enabled: false,
148 * });
149 * ```
150 *
151 * @see https://developers.cloudflare.com/stream/stream-live/
152 *
153 * @resource
154 * @product Stream
155 * @category Media
156 */
157 export const LiveInput = Resource<LiveInput>(TypeId);
158
159 /**
160 * Returns true if the given value is a LiveInput resource.
161 */
162 export const isLiveInput = (value: unknown): value is LiveInput =>
163 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
164
165 export const LiveInputProvider = () =>
166 Provider.succeed(LiveInput, {
167 stables: ["liveInputId", "accountId", "created"],
168
169 diff: Effect.fn(function* ({ output }) {
170 const { accountId } = yield* yield* CloudflareEnvironment;
171 if (output !== undefined && output.accountId !== accountId) {
172 return { action: "replace" } as const;
173 }
174 // Everything else is mutable via PUT.
175 return undefined;
176 }),
177
178 read: Effect.fn(function* ({ output }) {
179 // Live inputs have no deterministic name or tags, so a cold read
180 // (state lost before the uid was persisted) cannot recover the
181 // resource — rely on the cached uid.
182 if (output?.liveInputId === undefined) return undefined;
183 const accountId = output.accountId;
184 const observed = yield* getLiveInput(accountId, output.liveInputId);
185 return observed ? toAttributes(observed, accountId) : undefined;
186 }),
187
188 // Account collection: enumerate every live input in the account. The
189 // Cloudflare list endpoint returns all inputs in a single response
190 // (no cursor), so there is no extra pagination to drive. Hydrate each
191 // item into the same Attributes shape `read` produces.
192 list: Effect.fn(function* () {
193 const { accountId } = yield* yield* CloudflareEnvironment;
194 const inputs = yield* stream.listLiveInputs({ accountId });
195 return inputs
196 .filter((li): li is typeof li & { uid: string } => li.uid !== null && li.uid !== undefined)
197 .map((li) => toAttributes(li, accountId));
198 }),
199
200 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
201 const { accountId } = yield* yield* CloudflareEnvironment;
202 const meta = news.meta ?? {
203 name: yield* createPhysicalName({ id, lowercase: true }),
204 };
205
206 // Observe — the uid cached on `output` is a hint, not a guarantee:
207 // a not-found falls through to "missing" and we recreate.
208 const observed = output?.liveInputId
209 ? yield* getLiveInput(output.accountId ?? accountId, output.liveInputId)
210 : undefined;
211
212 if (!observed) {
213 // Ensure — greenfield (or out-of-band delete): create with the
214 // full desired body. uids are auto-assigned so there is no
215 // AlreadyExists race to tolerate.
216 const created = yield* stream.createLiveInput({
217 accountId,
218 defaultCreator: news.defaultCreator,
219 deleteRecordingAfterDays: news.deleteRecordingAfterDays,
220 enabled: news.enabled,
221 meta,
222 recording: news.recording,
223 });
224 return toAttributes(created, accountId);
225 }
226
227 // Sync — diff observed cloud state against desired. The update API
228 // is a PUT, so send the full desired body, but skip the call
229 // entirely on a no-op. `defaultCreator` and `recording` are not
230 // echoed by the API, so `olds` is the best available baseline for
231 // them.
232 const observedAccount = output?.accountId ?? accountId;
233 const dirty =
234 (news.enabled ?? true) !== (observed.enabled ?? true) ||
235 (news.deleteRecordingAfterDays ?? undefined) !==
236 (observed.deleteRecordingAfterDays ?? undefined) ||
237 !deepValueEquals(meta, observed.meta ?? {}) ||
238 news.defaultCreator !== olds?.defaultCreator ||
239 !deepValueEquals(news.recording ?? {}, olds?.recording ?? {});
240
241 if (!dirty) {
242 return toAttributes(observed, observedAccount);
243 }
244
245 const updated = yield* stream.updateLiveInput({
246 accountId: observedAccount,
247 liveInputIdentifier: observed.uid ?? output!.liveInputId,
248 defaultCreator: news.defaultCreator,
249 deleteRecordingAfterDays: news.deleteRecordingAfterDays,
250 enabled: news.enabled,
251 meta,
252 recording: news.recording,
253 });
254 return toAttributes(updated, observedAccount);
255 }),
256
257 delete: Effect.fn(function* ({ output }) {
258 // Idempotent — a live input already deleted out-of-band surfaces
259 // as `LiveInputNotFound` (Cloudflare error code 10003).
260 yield* stream
261 .deleteLiveInput({
262 accountId: output.accountId,
263 liveInputIdentifier: output.liveInputId,
264 })
265 .pipe(Effect.catchTag("LiveInputNotFound", () => Effect.void));
266 }),
267 });
268
269 /**
270 * Read a live input by uid, mapping "gone" (`LiveInputNotFound`,
271 * Cloudflare error code 10003) to `undefined`.
272 */
273 const getLiveInput = (accountId: string, liveInputId: string) =>
274 stream
275 .getLiveInput({ accountId, liveInputIdentifier: liveInputId })
276 .pipe(Effect.catchTag("LiveInputNotFound", () => Effect.undefined));
277
278 const toAttributes = (
279 input:
280 | stream.GetLiveInputResponse
281 | stream.CreateLiveInputResponse
282 | stream.UpdateLiveInputResponse,
283 accountId: string,
284 ): LiveInputAttributes => ({
285 liveInputId: input.uid ?? "",
286 accountId,
287 created: input.created ?? undefined,
288 modified: input.modified ?? undefined,
289 enabled: input.enabled ?? true,
290 deleteRecordingAfterDays: input.deleteRecordingAfterDays ?? undefined,
291 meta: (input.meta ?? {}) as Record<string, unknown>,
292 });
293
294 /**
295 * Structural equality for plain-JSON values (`meta`, `recording`) —
296 * primitives, arrays, and plain objects, `null`-tolerant and key-order
297 * insensitive.
298 */
299 const deepValueEquals = (a: unknown, b: unknown): boolean => {
300 if (a === b) return true;
301 if (a === null || b === null || a === undefined || b === undefined) {
302 return false;
303 }
304 if (Array.isArray(a) && Array.isArray(b)) {
305 return a.length === b.length && a.every((v, i) => deepValueEquals(v, b[i]));
306 }
307 if (typeof a === "object" && typeof b === "object") {
308 const ka = Object.keys(a as Record<string, unknown>);
309 const kb = Object.keys(b as Record<string, unknown>);
310 return (
311 ka.length === kb.length &&
312 ka.every((k) =>
313 deepValueEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),
314 )
315 );
316 }
317 return false;
318 };