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

main
ts 493 lines 19.4 KB
Raw
1 import * as mediapackagev2 from "@distilled.cloud/aws/mediapackagev2";
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 Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Predicate from "effect/Predicate";
12 import type { Providers } from "../Providers.ts";
13 import {
14 listAllChannelGroups,
15 listChannelEndpoints,
16 listGroupChannels,
17 matchesDesired,
18 policiesEqual,
19 retryWhileMpConflict,
20 syncMpTags,
21 toMpTagRecord,
22 } from "./internal.ts";
23
24 export interface OriginEndpointProps {
25 /**
26 * Name of the channel group the endpoint belongs to. Changing it replaces
27 * the endpoint.
28 */
29 channelGroupName: string;
30 /**
31 * Name of the channel the endpoint packages content from. Changing it
32 * replaces the endpoint.
33 */
34 channelName: string;
35 /**
36 * Name of the origin endpoint. Must be unique within the channel and match
37 * `^[a-zA-Z0-9_-]+$`. If omitted, a unique name is generated. Changing the
38 * name replaces the endpoint.
39 */
40 originEndpointName?: string;
41 /**
42 * The container format packaged for the endpoint's manifests: `TS`,
43 * `CMAF`, or `ISM`. Immutable — changing it replaces the endpoint.
44 */
45 containerType: mediapackagev2.ContainerType;
46 /**
47 * Segment settings: duration, name, SCTE-35 ad-marker filtering, and DRM
48 * encryption (SPEKE key provider).
49 */
50 segment?: mediapackagev2.Segment;
51 /**
52 * Optional description of the origin endpoint (up to 1024 characters).
53 */
54 description?: string;
55 /**
56 * The size of the window (1 minute - 14 days, e.g. `"1 hour"` or
57 * `Duration.hours(1)`) from which viewers can start over or catch up on
58 * previously streamed content. Sent to the API in whole seconds.
59 */
60 startoverWindow?: Duration.Input;
61 /**
62 * HLS manifest configurations served by the endpoint.
63 */
64 hlsManifests?: mediapackagev2.CreateHlsManifestConfiguration[];
65 /**
66 * Low-latency HLS manifest configurations served by the endpoint.
67 */
68 lowLatencyHlsManifests?: mediapackagev2.CreateLowLatencyHlsManifestConfiguration[];
69 /**
70 * DASH manifest configurations served by the endpoint.
71 */
72 dashManifests?: mediapackagev2.CreateDashManifestConfiguration[];
73 /**
74 * Microsoft Smooth Streaming (MSS) manifest configurations served by the
75 * endpoint. Requires the `ISM` container type.
76 */
77 mssManifests?: mediapackagev2.CreateMssManifestConfiguration[];
78 /**
79 * Conditions (stale manifest, missing DRM key, ...) under which the
80 * endpoint deliberately serves errors, for testing player behavior.
81 */
82 forceEndpointErrorConfiguration?: mediapackagev2.ForceEndpointErrorConfiguration;
83 /**
84 * The separator (`UNDERSCORE` or `HYPHEN`) inserted into manifest and
85 * segment URIs.
86 */
87 uriSeparator?: mediapackagev2.UriSeparator;
88 /**
89 * IAM resource policy (JSON) attached to the origin endpoint, controlling
90 * which principals may retrieve content from it
91 * (`mediapackagev2:GetObject` / `mediapackagev2:GetHeadObject`). Omitting
92 * it removes any existing policy.
93 */
94 policy?: string;
95 /**
96 * CDN authorization for the endpoint policy: the Secrets Manager secrets
97 * holding the CDN identifier and the role MediaPackage assumes to read
98 * them. Only applied together with {@link OriginEndpointProps.policy}.
99 */
100 cdnAuthConfiguration?: mediapackagev2.CdnAuthConfiguration;
101 /**
102 * User-defined tags for the origin endpoint. Merged with internal Alchemy
103 * tags.
104 */
105 tags?: Record<string, string>;
106 }
107
108 interface ManifestRef {
109 /** Name of the manifest. */
110 manifestName: string;
111 /** Playback URL of the manifest on the group's egress domain. */
112 url: string;
113 }
114
115 export interface OriginEndpoint extends Resource<
116 "AWS.MediaPackageV2.OriginEndpoint",
117 OriginEndpointProps,
118 {
119 /** Name of the channel group the endpoint belongs to. */
120 channelGroupName: string;
121 /** Name of the channel the endpoint packages content from. */
122 channelName: string;
123 /** Name of the origin endpoint. */
124 originEndpointName: string;
125 /** ARN of the origin endpoint. */
126 originEndpointArn: string;
127 /** Output container type (`TS`, `CMAF`, or `ISM`). */
128 containerType: string;
129 /** HLS manifests served by the endpoint. */
130 hlsManifests: ManifestRef[];
131 /** Low-latency HLS manifests served by the endpoint. */
132 lowLatencyHlsManifests: ManifestRef[];
133 /** DASH manifests served by the endpoint. */
134 dashManifests: ManifestRef[];
135 /** Microsoft Smooth Streaming manifests served by the endpoint. */
136 mssManifests: ManifestRef[];
137 },
138 never,
139 Providers
140 > {}
141
142 /**
143 * An AWS Elemental MediaPackage v2 origin endpoint — the output side of a
144 * channel. The endpoint packages the channel's ingested content into HLS,
145 * low-latency HLS, DASH, and/or MSS manifests and serves them to downstream
146 * devices (players or CDNs) on the channel group's egress domain.
147 *
148 * ### Creating an Origin Endpoint
149 * **Example:** HLS Endpoint on a Channel
150 * ```typescript
151 * import * as MediaPackageV2 from "@alchemy.run/aws/MediaPackageV2";
152 *
153 * const group = yield* MediaPackageV2.ChannelGroup("Live");
154 * const channel = yield* MediaPackageV2.Channel("Feed", {
155 * channelGroupName: group.channelGroupName,
156 * });
157 * const endpoint = yield* MediaPackageV2.OriginEndpoint("Playback", {
158 * channelGroupName: group.channelGroupName,
159 * channelName: channel.channelName,
160 * containerType: "TS",
161 * hlsManifests: [{ ManifestName: "index" }],
162 * });
163 * ```
164 *
165 * **Example:** CMAF Endpoint with DASH and Low-Latency HLS
166 * ```typescript
167 * const endpoint = yield* MediaPackageV2.OriginEndpoint("Playback", {
168 * channelGroupName: group.channelGroupName,
169 * channelName: channel.channelName,
170 * containerType: "CMAF",
171 * segment: { SegmentDurationSeconds: 4 },
172 * dashManifests: [{ ManifestName: "dash" }],
173 * lowLatencyHlsManifests: [{ ManifestName: "ll-hls" }],
174 * });
175 * ```
176 *
177 * ### Startover Window
178 * **Example:** Allow viewers to catch up on the last hour
179 * ```typescript
180 * const endpoint = yield* MediaPackageV2.OriginEndpoint("Playback", {
181 * channelGroupName: group.channelGroupName,
182 * channelName: channel.channelName,
183 * containerType: "TS",
184 * startoverWindow: "1 hour",
185 * hlsManifests: [{ ManifestName: "index" }],
186 * });
187 * ```
188 *
189 * ### Resource Policy
190 * **Example:** Restrict playback to a CDN principal
191 * ```typescript
192 * const endpoint = yield* MediaPackageV2.OriginEndpoint("Playback", {
193 * channelGroupName: group.channelGroupName,
194 * channelName: channel.channelName,
195 * containerType: "TS",
196 * hlsManifests: [{ ManifestName: "index" }],
197 * policy: JSON.stringify({
198 * Version: "2012-10-17",
199 * Statement: [{
200 * Effect: "Allow",
201 * Principal: { AWS: "arn:aws:iam::111122223333:root" },
202 * Action: ["mediapackagev2:GetObject", "mediapackagev2:GetHeadObject"],
203 * Resource: "arn:aws:mediapackagev2:us-east-1:111122223333:channelGroup/live/channel/feed/originEndpoint/playback",
204 * }],
205 * }),
206 * });
207 * ```
208 *
209 * ### Playback URLs
210 * **Example:** Read the served manifest URLs
211 * ```typescript
212 * const playbackUrl = endpoint.hlsManifests.map((m) => m.url);
213 * ```
214 *
215 * @resource
216 */
217 export const OriginEndpoint = Resource<OriginEndpoint>("AWS.MediaPackageV2.OriginEndpoint");
218
219 export const OriginEndpointProvider = () =>
220 Provider.effect(
221 OriginEndpoint,
222 Effect.gen(function* () {
223 const createName = Effect.fn(function* (id: string, props: { originEndpointName?: string }) {
224 return props.originEndpointName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
225 });
226
227 const manifestRefs = (
228 manifests: { ManifestName: string; Url: string }[] | undefined,
229 ): ManifestRef[] =>
230 (manifests ?? []).map((m) => ({
231 manifestName: m.ManifestName,
232 url: m.Url,
233 }));
234
235 const toAttrs = (endpoint: {
236 Arn: string;
237 ChannelGroupName: string;
238 ChannelName: string;
239 OriginEndpointName: string;
240 ContainerType: mediapackagev2.ContainerType;
241 HlsManifests?: mediapackagev2.GetHlsManifestConfiguration[];
242 LowLatencyHlsManifests?: mediapackagev2.GetLowLatencyHlsManifestConfiguration[];
243 DashManifests?: mediapackagev2.GetDashManifestConfiguration[];
244 MssManifests?: mediapackagev2.GetMssManifestConfiguration[];
245 }) => ({
246 channelGroupName: endpoint.ChannelGroupName,
247 channelName: endpoint.ChannelName,
248 originEndpointName: endpoint.OriginEndpointName,
249 originEndpointArn: endpoint.Arn,
250 containerType: endpoint.ContainerType,
251 hlsManifests: manifestRefs(endpoint.HlsManifests),
252 lowLatencyHlsManifests: manifestRefs(endpoint.LowLatencyHlsManifests),
253 dashManifests: manifestRefs(endpoint.DashManifests),
254 mssManifests: manifestRefs(endpoint.MssManifests),
255 });
256
257 /** Get an origin endpoint; typed not-found → undefined. */
258 const getEndpoint = Effect.fn(function* (
259 channelGroupName: string,
260 channelName: string,
261 originEndpointName: string,
262 ) {
263 return yield* mediapackagev2
264 .getOriginEndpoint({
265 ChannelGroupName: channelGroupName,
266 ChannelName: channelName,
267 OriginEndpointName: originEndpointName,
268 })
269 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
270 });
271
272 return {
273 stables: [
274 "channelGroupName",
275 "channelName",
276 "originEndpointName",
277 "originEndpointArn",
278 "containerType",
279 ],
280
281 diff: Effect.fn(function* ({ id, olds, news }) {
282 if (!isResolved(news)) return undefined;
283 // Group, channel, name, and container type are the endpoint's
284 // identity.
285 if (olds.channelGroupName !== news.channelGroupName) {
286 return { action: "replace" } as const;
287 }
288 if (olds.channelName !== news.channelName) {
289 return { action: "replace" } as const;
290 }
291 const oldName = yield* createName(id, olds);
292 const newName = yield* createName(id, news);
293 if (oldName !== newName) return { action: "replace" } as const;
294 if (olds.containerType !== news.containerType) {
295 return { action: "replace" } as const;
296 }
297 }),
298
299 read: Effect.fn(function* ({ id, olds, output }) {
300 const channelGroupName = output?.channelGroupName ?? olds?.channelGroupName;
301 const channelName = output?.channelName ?? olds?.channelName;
302 if (channelGroupName === undefined || channelName === undefined) {
303 return undefined;
304 }
305 const name = output?.originEndpointName ?? (yield* createName(id, olds ?? {}));
306 const endpoint = yield* getEndpoint(channelGroupName, channelName, name);
307 if (endpoint === undefined) return undefined;
308 const attrs = toAttrs(endpoint);
309 return (yield* hasAlchemyTags(id, toMpTagRecord(endpoint.Tags))) ? attrs : Unowned(attrs);
310 }),
311
312 reconcile: Effect.fn(function* ({ id, news, output, session }) {
313 const internalTags = yield* createInternalTags(id);
314 const desiredTags = { ...internalTags, ...news.tags };
315 const channelGroupName = news.channelGroupName;
316 const channelName = news.channelName;
317 // The wire field is whole seconds.
318 const startoverWindowSeconds = toWireSeconds(news.startoverWindow);
319 const name = output?.originEndpointName ?? (yield* createName(id, news));
320
321 // 1. Observe — cloud state is authoritative; output is an id cache.
322 let endpoint = yield* getEndpoint(channelGroupName, channelName, name);
323
324 // 2. Ensure — create if missing; a Conflict means a peer created it
325 // concurrently, so fall through to observing the winner.
326 if (endpoint === undefined) {
327 endpoint = yield* mediapackagev2
328 .createOriginEndpoint({
329 ChannelGroupName: channelGroupName,
330 ChannelName: channelName,
331 OriginEndpointName: name,
332 ContainerType: news.containerType,
333 Segment: news.segment,
334 Description: news.description,
335 StartoverWindowSeconds: startoverWindowSeconds,
336 HlsManifests: news.hlsManifests,
337 LowLatencyHlsManifests: news.lowLatencyHlsManifests,
338 DashManifests: news.dashManifests,
339 MssManifests: news.mssManifests,
340 ForceEndpointErrorConfiguration: news.forceEndpointErrorConfiguration,
341 UriSeparator: news.uriSeparator,
342 Tags: desiredTags,
343 })
344 .pipe(
345 Effect.catchTag("ConflictException", () =>
346 mediapackagev2.getOriginEndpoint({
347 ChannelGroupName: channelGroupName,
348 ChannelName: channelName,
349 OriginEndpointName: name,
350 }),
351 ),
352 );
353 } else {
354 // 3. Sync — the update is a full PUT of the mutable aspects, so
355 // apply it only when the observed state has drifted from the
356 // desired subset. Manifest arrays are compared by length and
357 // by the fields the desired config specifies, so server-side
358 // defaults never register as drift.
359 const desired = {
360 Segment: news.segment,
361 Description: news.description ?? "",
362 StartoverWindowSeconds: startoverWindowSeconds,
363 HlsManifests: news.hlsManifests ?? [],
364 LowLatencyHlsManifests: news.lowLatencyHlsManifests ?? [],
365 DashManifests: news.dashManifests ?? [],
366 MssManifests: news.mssManifests ?? [],
367 ForceEndpointErrorConfiguration: news.forceEndpointErrorConfiguration,
368 UriSeparator: news.uriSeparator,
369 };
370 const observed = {
371 Segment: endpoint.Segment,
372 Description: endpoint.Description ?? "",
373 StartoverWindowSeconds: endpoint.StartoverWindowSeconds,
374 HlsManifests: endpoint.HlsManifests ?? [],
375 LowLatencyHlsManifests: endpoint.LowLatencyHlsManifests ?? [],
376 DashManifests: endpoint.DashManifests ?? [],
377 MssManifests: endpoint.MssManifests ?? [],
378 ForceEndpointErrorConfiguration: endpoint.ForceEndpointErrorConfiguration,
379 UriSeparator: endpoint.UriSeparator,
380 };
381 if (!matchesDesired(desired, observed)) {
382 endpoint = yield* mediapackagev2.updateOriginEndpoint({
383 ChannelGroupName: channelGroupName,
384 ChannelName: channelName,
385 OriginEndpointName: name,
386 ContainerType: news.containerType,
387 Segment: news.segment,
388 Description: news.description,
389 StartoverWindowSeconds: startoverWindowSeconds,
390 HlsManifests: news.hlsManifests,
391 LowLatencyHlsManifests: news.lowLatencyHlsManifests,
392 DashManifests: news.dashManifests,
393 MssManifests: news.mssManifests,
394 ForceEndpointErrorConfiguration: news.forceEndpointErrorConfiguration,
395 UriSeparator: news.uriSeparator,
396 });
397 }
398 }
399
400 // 3b. Sync tags — diff against OBSERVED cloud tags.
401 yield* syncMpTags(endpoint.Arn, toMpTagRecord(endpoint.Tags), desiredTags);
402
403 // 3c. Sync the resource policy — observe the live policy (absent
404 // policy is the typed not-found) and apply only the delta.
405 const observedPolicy = yield* mediapackagev2
406 .getOriginEndpointPolicy({
407 ChannelGroupName: channelGroupName,
408 ChannelName: channelName,
409 OriginEndpointName: name,
410 })
411 .pipe(
412 Effect.map((response) => ({
413 policy: response.Policy as string | undefined,
414 cdnAuth: response.CdnAuthConfiguration,
415 })),
416 Effect.catchTag("ResourceNotFoundException", () =>
417 Effect.succeed({
418 policy: undefined as string | undefined,
419 cdnAuth: undefined as mediapackagev2.CdnAuthConfiguration | undefined,
420 }),
421 ),
422 );
423 if (news.policy !== undefined) {
424 const cdnDrift =
425 news.cdnAuthConfiguration === undefined
426 ? observedPolicy.cdnAuth !== undefined
427 : !matchesDesired(news.cdnAuthConfiguration, observedPolicy.cdnAuth);
428 if (!policiesEqual(observedPolicy.policy, news.policy) || cdnDrift) {
429 yield* mediapackagev2.putOriginEndpointPolicy({
430 ChannelGroupName: channelGroupName,
431 ChannelName: channelName,
432 OriginEndpointName: name,
433 Policy: news.policy,
434 CdnAuthConfiguration: news.cdnAuthConfiguration,
435 });
436 }
437 } else if (observedPolicy.policy !== undefined) {
438 yield* mediapackagev2.deleteOriginEndpointPolicy({
439 ChannelGroupName: channelGroupName,
440 ChannelName: channelName,
441 OriginEndpointName: name,
442 });
443 }
444
445 yield* session.note(name);
446 return toAttrs(endpoint);
447 }),
448
449 delete: Effect.fn(function* ({ output }) {
450 // MediaPackage v2 deletes are idempotent (deleting a missing
451 // endpoint succeeds); a Conflict from a concurrent mutation is
452 // transient.
453 yield* mediapackagev2
454 .deleteOriginEndpoint({
455 ChannelGroupName: output.channelGroupName,
456 ChannelName: output.channelName,
457 OriginEndpointName: output.originEndpointName,
458 })
459 .pipe(retryWhileMpConflict);
460 }),
461
462 // Origin endpoints are keyed by their parent channel, so enumerate
463 // groups → channels → endpoints.
464 list: () =>
465 Effect.gen(function* () {
466 const groups = yield* listAllChannelGroups();
467 const channels = yield* Effect.forEach(
468 groups,
469 (group) => listGroupChannels(group.ChannelGroupName),
470 { concurrency: 5 },
471 ).pipe(Effect.map((nested) => nested.flat()));
472 const items = yield* Effect.forEach(
473 channels,
474 (channel) => listChannelEndpoints(channel.ChannelGroupName, channel.ChannelName),
475 { concurrency: 5 },
476 ).pipe(Effect.map((nested) => nested.flat()));
477 // Hydrate each item via get so the attributes carry the manifest
478 // URLs; an endpoint can vanish between enumeration and hydration.
479 const endpoints = yield* Effect.forEach(
480 items,
481 (item) =>
482 getEndpoint(item.ChannelGroupName, item.ChannelName, item.OriginEndpointName).pipe(
483 Effect.map((endpoint) =>
484 endpoint === undefined ? undefined : toAttrs(endpoint),
485 ),
486 ),
487 { concurrency: 5 },
488 );
489 return endpoints.filter(Predicate.isNotUndefined);
490 }),
491 };
492 }),
493 );