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

main
ts 347 lines 11.9 KB
Raw
1 import * as ivs from "@distilled.cloud/aws/ivs";
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 { retryWhileConflict, retryWhileThrottled, syncIvsTags, toTagRecord } from "./internal.ts";
12
13 export interface ChannelProps {
14 /**
15 * Name of the channel (letters, digits, `-` and `_`; not unique across
16 * channels). If omitted, a deterministic physical name is generated.
17 * Channel names are mutable — changing the name updates the channel in
18 * place.
19 */
20 channelName?: string;
21 /**
22 * Channel latency mode. `LOW` enables low-latency live video (~3s);
23 * `NORMAL` broadcasts at higher latency for a lower cost.
24 * @default "LOW"
25 */
26 latencyMode?: "NORMAL" | "LOW";
27 /**
28 * Channel type, which determines the allowable resolution and bitrate
29 * of the delivered video (e.g. `STANDARD`, `BASIC`, `ADVANCED_SD`,
30 * `ADVANCED_HD`).
31 * @default "STANDARD"
32 */
33 type?: string;
34 /**
35 * Whether the channel is private (viewers require a playback
36 * authorization token generated with a `PlaybackKeyPair`).
37 * @default false
38 */
39 authorized?: boolean;
40 /**
41 * ARN of a recording configuration to record live broadcasts to S3.
42 * @default no recording
43 */
44 recordingConfigurationArn?: string;
45 /**
46 * Whether the channel allows insecure RTMP ingest.
47 * @default false
48 */
49 insecureIngest?: boolean;
50 /**
51 * Optional transcode preset for `ADVANCED_SD`/`ADVANCED_HD` channel
52 * types (`HIGHER_BANDWIDTH_DELIVERY` or `CONSTRAINED_BANDWIDTH_DELIVERY`).
53 */
54 preset?: string;
55 /**
56 * ARN of a playback restriction policy constraining playback by
57 * country and/or origin.
58 */
59 playbackRestrictionPolicyArn?: string;
60 /**
61 * Tags to apply to the channel. Merged with internal Alchemy tags.
62 */
63 tags?: Record<string, string>;
64 }
65
66 export interface Channel extends Resource<
67 "AWS.IVS.Channel",
68 ChannelProps,
69 {
70 /**
71 * The channel's physical name.
72 */
73 channelName: string;
74 /**
75 * ARN of the channel.
76 */
77 channelArn: string;
78 /**
79 * RTMPS ingest endpoint broadcast software sends video to
80 * (authenticated with a `StreamKey`).
81 */
82 ingestEndpoint: string;
83 /**
84 * Playback URL viewers use to watch the channel's live stream.
85 */
86 playbackUrl: string;
87 /**
88 * Channel type (resolution/bitrate tier) reported by IVS.
89 */
90 type: string | undefined;
91 /**
92 * Latency mode reported by IVS (`LOW` or `NORMAL`).
93 */
94 latencyMode: string | undefined;
95 /**
96 * Whether playback requires a signed authorization token.
97 */
98 authorized: boolean | undefined;
99 },
100 never,
101 Providers
102 > {}
103
104 /**
105 * An Amazon IVS (Interactive Video Service) channel for low-latency live
106 * video streaming.
107 *
108 * A channel stores configuration for broadcasting live streams: broadcast
109 * software sends video to the channel's `ingestEndpoint` (authenticated
110 * with a `StreamKey`) and viewers watch via the channel's `playbackUrl`.
111 * ### Creating Channels
112 * **Example:** Basic Channel
113 * ```typescript
114 * import * as IVS from "@alchemy.run/aws/IVS";
115 *
116 * const channel = yield* IVS.Channel("LiveChannel");
117 * ```
118 *
119 * **Example:** Basic Low-Cost Channel
120 * ```typescript
121 * const channel = yield* IVS.Channel("LiveChannel", {
122 * type: "BASIC",
123 * latencyMode: "NORMAL",
124 * });
125 * ```
126 *
127 * ### Private Channels
128 * **Example:** Channel with Playback Authorization
129 * ```typescript
130 * const channel = yield* IVS.Channel("PrivateChannel", {
131 * authorized: true,
132 * });
133 * ```
134 *
135 * ### Streaming
136 * **Example:** Channel with a Stream Key
137 * ```typescript
138 * const channel = yield* IVS.Channel("LiveChannel");
139 * const streamKey = yield* IVS.StreamKey("LiveKey", {
140 * channelArn: channel.channelArn,
141 * });
142 * // broadcast to rtmps://{channel.ingestEndpoint}:443/app/ with streamKey.value
143 * ```
144 *
145 * @resource
146 */
147 export const Channel = Resource<Channel>("AWS.IVS.Channel");
148
149 /**
150 * Raised when the IVS API returns a channel that is missing its ARN, name,
151 * ingest endpoint, or playback URL.
152 */
153 export class IvsChannelIncomplete extends Data.TaggedError("IvsChannelIncomplete")<{
154 message: string;
155 }> {}
156
157 export const ChannelProvider = () =>
158 Provider.effect(
159 Channel,
160 Effect.gen(function* () {
161 const toName = (id: string, props: ChannelProps) =>
162 props.channelName
163 ? Effect.succeed(props.channelName)
164 : createPhysicalName({ id, maxLength: 128 });
165
166 const toAttrs = Effect.fn(function* (channel: ivs.Channel) {
167 if (
168 !channel.arn ||
169 !channel.name ||
170 channel.ingestEndpoint === undefined ||
171 channel.playbackUrl === undefined
172 ) {
173 return yield* new IvsChannelIncomplete({
174 message: "IVS channel is missing its ARN, name, ingest endpoint, or playback URL",
175 });
176 }
177 return {
178 channelName: channel.name,
179 channelArn: channel.arn,
180 ingestEndpoint: channel.ingestEndpoint,
181 playbackUrl: channel.playbackUrl,
182 type: channel.type,
183 latencyMode: channel.latencyMode,
184 authorized: channel.authorized,
185 };
186 });
187
188 const getByArn = Effect.fn(function* (arn: string) {
189 const response = yield* ivs.getChannel({ arn }).pipe(
190 retryWhileThrottled,
191 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
192 );
193 return response?.channel;
194 });
195
196 /**
197 * Channel names are not unique — `filterByName` narrows server-side
198 * and we match exactly, taking the first hit. Used only when the
199 * output ARN cache is unavailable (state-persistence failure).
200 */
201 const findByName = Effect.fn(function* (name: string) {
202 const summaries = yield* ivs.listChannels.pages({ filterByName: name }).pipe(
203 Stream.runCollect,
204 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.channels)),
205 retryWhileThrottled,
206 );
207 const match = summaries.find((s) => s.name === name && s.arn);
208 return match?.arn ? yield* getByArn(match.arn) : undefined;
209 });
210
211 return {
212 stables: ["channelArn"],
213
214 read: Effect.fn(function* ({ id, olds, output }) {
215 const channel = output?.channelArn
216 ? yield* getByArn(output.channelArn)
217 : yield* findByName(yield* toName(id, olds ?? {}));
218 if (channel === undefined) return undefined;
219 const attrs = yield* toAttrs(channel);
220 return (yield* hasAlchemyTags(id, toTagRecord(channel.tags))) ? attrs : Unowned(attrs);
221 }),
222
223 reconcile: Effect.fn(function* ({ id, news, output, session }) {
224 const name = yield* toName(id, news);
225 const internalTags = yield* createInternalTags(id);
226 const desiredTags = { ...internalTags, ...news.tags };
227
228 // 1. Observe — the live channel is authoritative; the output ARN
229 // is only an identifier cache.
230 let observed = output?.channelArn
231 ? yield* getByArn(output.channelArn)
232 : yield* findByName(name);
233
234 // 2. Ensure — create if missing. CreateChannel also provisions
235 // the channel's default stream key, which we leave in place (see
236 // the StreamKey resource).
237 if (observed === undefined) {
238 const created = yield* ivs
239 .createChannel({
240 name,
241 latencyMode: news.latencyMode,
242 type: news.type,
243 authorized: news.authorized,
244 recordingConfigurationArn: news.recordingConfigurationArn,
245 insecureIngest: news.insecureIngest,
246 preset: news.preset,
247 playbackRestrictionPolicyArn: news.playbackRestrictionPolicyArn,
248 tags: desiredTags,
249 })
250 .pipe(retryWhileThrottled);
251 observed = created.channel;
252 }
253 const arn = observed?.arn;
254 if (observed === undefined || arn === undefined) {
255 return yield* new IvsChannelIncomplete({
256 message: "IVS CreateChannel returned no channel ARN",
257 });
258 }
259
260 // 3. Sync — diff observed against desired for each prop the user
261 // specified and apply only the delta. All channel settings
262 // (including the name) are mutable via UpdateChannel.
263 const patch: Partial<ivs.UpdateChannelRequest> = {};
264 if (observed.name !== name) patch.name = name;
265 if (news.latencyMode !== undefined && observed.latencyMode !== news.latencyMode) {
266 patch.latencyMode = news.latencyMode;
267 }
268 if (news.type !== undefined && observed.type !== news.type) {
269 patch.type = news.type;
270 }
271 if (news.authorized !== undefined && observed.authorized !== news.authorized) {
272 patch.authorized = news.authorized;
273 }
274 if (
275 news.recordingConfigurationArn !== undefined &&
276 observed.recordingConfigurationArn !== news.recordingConfigurationArn
277 ) {
278 patch.recordingConfigurationArn = news.recordingConfigurationArn;
279 }
280 if (
281 news.insecureIngest !== undefined &&
282 observed.insecureIngest !== news.insecureIngest
283 ) {
284 patch.insecureIngest = news.insecureIngest;
285 }
286 if (news.preset !== undefined && observed.preset !== news.preset) {
287 patch.preset = news.preset;
288 }
289 if (
290 news.playbackRestrictionPolicyArn !== undefined &&
291 observed.playbackRestrictionPolicyArn !== news.playbackRestrictionPolicyArn
292 ) {
293 patch.playbackRestrictionPolicyArn = news.playbackRestrictionPolicyArn;
294 }
295 if (Object.keys(patch).length > 0) {
296 yield* ivs
297 .updateChannel({ arn, ...patch })
298 .pipe(retryWhileThrottled, retryWhileConflict);
299 }
300
301 // 3b. Sync tags — diff against OBSERVED cloud tags so adoption
302 // converges.
303 yield* syncIvsTags(arn, desiredTags);
304
305 // 4. Return fresh attributes.
306 const final = yield* getByArn(arn);
307 if (final === undefined) {
308 return yield* new IvsChannelIncomplete({
309 message: `IVS channel '${arn}' vanished during reconcile`,
310 });
311 }
312 yield* session.note(arn);
313 return yield* toAttrs(final);
314 }),
315
316 delete: Effect.fn(function* ({ output }) {
317 // DeleteChannel raises ConflictException while a stream is live
318 // — retry through a bounded window, then tolerate already-gone.
319 yield* ivs.deleteChannel({ arn: output.channelArn }).pipe(
320 retryWhileThrottled,
321 retryWhileConflict,
322 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
323 );
324 }),
325
326 list: () =>
327 ivs.listChannels.pages({}).pipe(
328 Stream.runCollect,
329 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.channels)),
330 Effect.flatMap(
331 Effect.forEach(
332 (summary) =>
333 summary.arn === undefined
334 ? Effect.undefined
335 : getByArn(summary.arn).pipe(
336 Effect.flatMap((channel) =>
337 channel === undefined ? Effect.undefined : toAttrs(channel),
338 ),
339 ),
340 { concurrency: 5 },
341 ),
342 ),
343 Effect.map((items) => items.filter((item) => item !== undefined)),
344 ),
345 };
346 }),
347 );