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

main
ts 429 lines 15.8 KB
Raw
1 import * as medialive from "@distilled.cloud/aws/medialive";
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 MediaLiveResourcePending,
15 ensureIdentified,
16 ensurePresent,
17 retryWhileConflict,
18 retryWhilePending,
19 syncMlTags,
20 toTagRecord,
21 } from "./internal.ts";
22
23 /**
24 * The observed shape shared by `DescribeChannelResponse` and the `Channel`
25 * struct returned by create/update (and `ChannelSummary` from list).
26 */
27 type ObservedChannel = Pick<
28 medialive.Channel,
29 | "Arn"
30 | "Id"
31 | "Name"
32 | "State"
33 | "ChannelClass"
34 | "EgressEndpoints"
35 | "LogLevel"
36 | "RoleArn"
37 | "Tags"
38 >;
39
40 type IdentifiedChannel = ObservedChannel & { Id: string; Arn: string };
41
42 // Explicitly-typed pipeable retry helper (see internal.ts for why inline
43 // Effect.retry is forbidden in provider ops). A freshly-created IAM role is
44 // not immediately visible to MediaLive — createChannel rejects it with a
45 // message-discriminated UnprocessableEntityException naming the trust
46 // relationship (patched in distilled to the typed `MediaLiveRoleNotYetTrusted`
47 // tag) until IAM propagation settles.
48 const retryWhileRolePropagating = <A, E extends { readonly _tag: string }, R>(
49 self: Effect.Effect<A, E, R>,
50 ): Effect.Effect<A, E, R> =>
51 Effect.retry(self, {
52 while: (e) => e._tag === "MediaLiveRoleNotYetTrusted",
53 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
54 });
55
56 /**
57 * Raised when a MediaLive channel lands in `CREATE_FAILED` or `UPDATE_FAILED`
58 * instead of settling into `IDLE`.
59 */
60 export class MediaLiveChannelFailed extends Data.TaggedError("MediaLiveChannelFailed")<{
61 message: string;
62 }> {}
63
64 export interface ChannelProps {
65 /**
66 * Name of the channel. If omitted, a unique name is generated from the
67 * app, stage, and logical ID. Names are mutable — changing the name
68 * updates the channel in place.
69 */
70 name?: string;
71 /**
72 * The class of the channel. `STANDARD` runs two redundant encoder
73 * pipelines; `SINGLE_PIPELINE` runs one. Changing the class replaces the
74 * channel.
75 * @default "STANDARD"
76 */
77 channelClass?: medialive.ChannelClass;
78 /**
79 * ARN of the IAM role MediaLive assumes to read inputs and write outputs
80 * (trusts `medialive.amazonaws.com`).
81 */
82 roleArn?: string;
83 /**
84 * The inputs attached to this channel.
85 */
86 inputAttachments?: medialive.InputAttachment[];
87 /**
88 * The encoder settings — audio/video descriptions, output groups, and
89 * timecode configuration.
90 */
91 encoderSettings?: medialive.EncoderSettings;
92 /**
93 * Destinations referenced by the output groups in `encoderSettings`.
94 */
95 destinations?: medialive.OutputDestination[];
96 /**
97 * Specification of the input codec/resolution/bitrate tier (drives
98 * per-hour pricing).
99 */
100 inputSpecification?: medialive.InputSpecification;
101 /**
102 * Specification of CDI inputs for this channel.
103 */
104 cdiInputSpecification?: medialive.CdiInputSpecification;
105 /**
106 * The CloudWatch log level for the channel.
107 * @default "DISABLED"
108 */
109 logLevel?: medialive.LogLevel;
110 /**
111 * Maintenance window settings (day + start hour).
112 */
113 maintenance?: medialive.MaintenanceCreateSettings;
114 /**
115 * VPC output settings. Changing the VPC settings replaces the channel.
116 */
117 vpc?: medialive.VpcOutputSettings;
118 /**
119 * User-defined tags for the channel.
120 */
121 tags?: Record<string, string>;
122 }
123
124 export interface Channel extends Resource<
125 "AWS.MediaLive.Channel",
126 ChannelProps,
127 {
128 /** Server-assigned unique id of the channel. */
129 channelId: string;
130 /** ARN of the channel. */
131 channelArn: string;
132 /** Name of the channel. */
133 channelName: string | undefined;
134 /** Current lifecycle state (e.g. `IDLE`, `RUNNING`). */
135 state: medialive.ChannelState | undefined;
136 /** Pipeline class (`STANDARD` or `SINGLE_PIPELINE`). */
137 channelClass: medialive.ChannelClass | undefined;
138 /** Egress endpoints the channel writes output through. */
139 egressEndpoints: medialive.ChannelEgressEndpoint[];
140 },
141 never,
142 Providers
143 > {}
144
145 /**
146 * An AWS Elemental MediaLive channel — the live encoder that reads from
147 * attached inputs, transcodes per its encoder settings, and writes to output
148 * destinations (HLS, RTMP, MediaPackage, ...).
149 *
150 * Channels bill per running hour; Alchemy provisions channels in the `IDLE`
151 * state and never starts them — start/stop is a runtime operation.
152 *
153 * ### Creating a Channel
154 * **Example:** Single-pipeline HLS channel
155 * ```typescript
156 * const channel = yield* MediaLive.Channel("Live", {
157 * channelClass: "SINGLE_PIPELINE",
158 * roleArn: role.roleArn,
159 * inputAttachments: [
160 * { InputId: input.inputId, InputAttachmentName: "primary" },
161 * ],
162 * inputSpecification: {
163 * Codec: "AVC",
164 * Resolution: "SD",
165 * MaximumBitrate: "MAX_10_MBPS",
166 * },
167 * destinations,
168 * encoderSettings,
169 * });
170 * ```
171 *
172 * **Example:** IAM role for MediaLive
173 * ```typescript
174 * const role = yield* IAM.Role("MediaLiveRole", {
175 * assumeRolePolicyDocument: {
176 * Version: "2012-10-17",
177 * Statement: [
178 * {
179 * Effect: "Allow",
180 * Principal: { Service: "medialive.amazonaws.com" },
181 * Action: ["sts:AssumeRole"],
182 * },
183 * ],
184 * },
185 * });
186 * ```
187 *
188 * @resource
189 */
190 export const Channel = Resource<Channel>("AWS.MediaLive.Channel");
191
192 export const ChannelProvider = () =>
193 Provider.effect(
194 Channel,
195 Effect.gen(function* () {
196 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
197 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
198 });
199
200 const toAttrs = (channel: IdentifiedChannel) => ({
201 channelId: channel.Id,
202 channelArn: channel.Arn,
203 channelName: channel.Name,
204 state: channel.State,
205 channelClass: channel.ChannelClass,
206 egressEndpoints: [...(channel.EgressEndpoints ?? [])],
207 });
208
209 const isGone = (state: medialive.ChannelState | undefined) =>
210 state === "DELETED" || state === "DELETING";
211
212 /** Describe by id; typed not-found (or tombstone state) → undefined. */
213 const getChannel = Effect.fn(function* (channelId: string) {
214 const channel = yield* medialive
215 .describeChannel({ ChannelId: channelId })
216 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
217 if (channel === undefined || isGone(channel.State)) return undefined;
218 return yield* ensureIdentified(channel, "DescribeChannel Id/Arn");
219 });
220
221 /**
222 * Channels have server-assigned ids, so a read without cached output
223 * searches the account list by the deterministic physical name.
224 */
225 const findByName = Effect.fn(function* (name: string) {
226 const channels = yield* medialive.listChannels.items({}).pipe(
227 Stream.runCollect,
228 Effect.map((chunk) => Array.from(chunk)),
229 );
230 const match = channels.find((channel) => channel.Name === name && !isGone(channel.State));
231 if (match === undefined) return undefined;
232 return yield* ensureIdentified(match, "ListChannels item Id/Arn");
233 });
234
235 /**
236 * Wait (bounded, ~90s) for a channel to settle out of the transient
237 * `CREATING`/`UPDATING` states; fail typed on `*_FAILED`.
238 */
239 const awaitSettled = Effect.fn(function* (channelId: string) {
240 return yield* retryWhilePending(
241 Effect.gen(function* () {
242 const channel = yield* medialive.describeChannel({
243 ChannelId: channelId,
244 });
245 if (channel.State === "CREATE_FAILED" || channel.State === "UPDATE_FAILED") {
246 return yield* new MediaLiveChannelFailed({
247 message: `channel ${channelId} is in state ${channel.State}`,
248 });
249 }
250 if (channel.State === "CREATING" || channel.State === "UPDATING") {
251 return yield* new MediaLiveResourcePending({
252 message: `channel ${channelId} is still ${channel.State}`,
253 });
254 }
255 return yield* ensureIdentified(channel, "DescribeChannel Id/Arn");
256 }),
257 );
258 });
259
260 return Channel.Provider.of({
261 stables: ["channelId", "channelArn"],
262
263 list: () =>
264 medialive.listChannels.items({}).pipe(
265 Stream.runCollect,
266 Effect.map((chunk) =>
267 Array.from(chunk)
268 .filter(
269 (channel): channel is medialive.ChannelSummary & IdentifiedChannel =>
270 channel.Id !== undefined && channel.Arn !== undefined && !isGone(channel.State),
271 )
272 .map(toAttrs),
273 ),
274 ),
275
276 read: Effect.fn(function* ({ id, olds, output }) {
277 const channel =
278 output?.channelId !== undefined
279 ? yield* getChannel(output.channelId)
280 : yield* findByName(yield* createName(id, olds ?? {}));
281 if (channel === undefined) return undefined;
282 const attrs = toAttrs(channel);
283 return (yield* hasAlchemyTags(id, toTagRecord(channel.Tags))) ? attrs : Unowned(attrs);
284 }),
285
286 diff: Effect.fn(function* ({ news, olds }) {
287 if (!isResolved(news)) return undefined;
288 // The channel class and VPC placement are fixed at creation.
289 if ((olds.channelClass ?? "STANDARD") !== (news.channelClass ?? "STANDARD")) {
290 return { action: "replace" } as const;
291 }
292 if (JSON.stringify(olds.vpc) !== JSON.stringify(news.vpc)) {
293 return { action: "replace" } as const;
294 }
295 }),
296
297 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
298 const internalTags = yield* createInternalTags(id);
299 const desiredTags = { ...internalTags, ...news.tags };
300 const name = yield* createName(id, news);
301
302 // 1. Observe — cloud state is authoritative; output is an id cache.
303 // MediaLive channel names are not unique, so a name match is only
304 // trusted when its immutable class agrees with the desired state —
305 // during a replacement the same-named survivor is the doomed old
306 // instance, not this one.
307 let channel: IdentifiedChannel | undefined;
308 if (output?.channelId !== undefined) {
309 channel = yield* getChannel(output.channelId);
310 } else {
311 const found = yield* findByName(name);
312 channel =
313 found !== undefined &&
314 (found.ChannelClass ?? "STANDARD") === (news.channelClass ?? "STANDARD")
315 ? found
316 : undefined;
317 }
318
319 // 2. Ensure — create if missing, then wait for CREATING to settle.
320 if (channel === undefined) {
321 const created = yield* medialive
322 .createChannel({
323 Name: name,
324 ChannelClass: news.channelClass,
325 RoleArn: news.roleArn,
326 InputAttachments: news.inputAttachments,
327 EncoderSettings: news.encoderSettings,
328 Destinations: news.destinations,
329 InputSpecification: news.inputSpecification,
330 CdiInputSpecification: news.cdiInputSpecification,
331 LogLevel: news.logLevel,
332 Maintenance: news.maintenance,
333 Vpc: news.vpc,
334 Tags: desiredTags,
335 })
336 .pipe(retryWhileRolePropagating);
337 const fresh = yield* ensureIdentified(created.Channel, "CreateChannel Channel Id/Arn");
338 channel = yield* awaitSettled(fresh.Id);
339 } else {
340 // 3. Sync — cheap scalars are diffed against OBSERVED state; the
341 // deep encoder/attachment documents are diffed against `olds` as
342 // a no-op hint (Describe echoes them back default-expanded, so an
343 // observed-vs-desired deep compare would always report drift).
344 const nameDrift = channel.Name !== name;
345 const logDrift = news.logLevel !== undefined && channel.LogLevel !== news.logLevel;
346 const roleDrift = news.roleArn !== undefined && channel.RoleArn !== news.roleArn;
347 const deepDrift =
348 olds === undefined
349 ? true
350 : JSON.stringify({
351 a: olds.inputAttachments,
352 e: olds.encoderSettings,
353 d: olds.destinations,
354 i: olds.inputSpecification,
355 c: olds.cdiInputSpecification,
356 }) !==
357 JSON.stringify({
358 a: news.inputAttachments,
359 e: news.encoderSettings,
360 d: news.destinations,
361 i: news.inputSpecification,
362 c: news.cdiInputSpecification,
363 });
364 if (nameDrift || logDrift || roleDrift || deepDrift) {
365 yield* medialive
366 .updateChannel({
367 ChannelId: channel.Id,
368 Name: name,
369 RoleArn: news.roleArn,
370 InputAttachments: news.inputAttachments,
371 EncoderSettings: news.encoderSettings,
372 Destinations: news.destinations,
373 InputSpecification: news.inputSpecification,
374 CdiInputSpecification: news.cdiInputSpecification,
375 LogLevel: news.logLevel,
376 Maintenance: news.maintenance
377 ? {
378 MaintenanceDay: news.maintenance.MaintenanceDay,
379 MaintenanceStartTime: news.maintenance.MaintenanceStartTime,
380 }
381 : undefined,
382 })
383 .pipe(retryWhileConflict);
384 channel = yield* awaitSettled(channel.Id);
385 }
386 }
387
388 // Both the ensure and sync branches leave `channel` assigned from a
389 // typed describe; guard with a typed failure so TS sees it defined.
390 const settled = yield* ensurePresent(channel, "reconciled channel state");
391
392 // 3b. Sync tags — diff against OBSERVED cloud tags.
393 yield* syncMlTags(settled.Arn, desiredTags);
394
395 yield* session.note(settled.Id);
396 return toAttrs(settled);
397 }),
398
399 delete: Effect.fn(function* ({ output }) {
400 yield* medialive.deleteChannel({ ChannelId: output.channelId }).pipe(
401 retryWhileConflict,
402 Effect.catchTag("NotFoundException", () => Effect.void),
403 Effect.asVoid,
404 );
405 // Deletion is async (DELETING → DELETED). Wait (bounded) so that
406 // dependent Inputs/InputSecurityGroups can delete without long
407 // conflict-retry loops; if the channel is still draining after the
408 // window, deletion is initiated and irreversible — let downstream
409 // retries absorb the tail.
410 yield* medialive.describeChannel({ ChannelId: output.channelId }).pipe(
411 Effect.flatMap((channel) =>
412 channel.State === "DELETED"
413 ? Effect.void
414 : Effect.fail(
415 new MediaLiveResourcePending({
416 message: `channel ${output.channelId} is still ${channel.State}`,
417 }),
418 ),
419 ),
420 retryWhilePending,
421 Effect.catchTags({
422 NotFoundException: () => Effect.void,
423 MediaLiveResourcePending: () => Effect.void,
424 }),
425 );
426 }),
427 });
428 }),
429 );