@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, 06:00 UTC

main
ts 498 lines 19 KB
Raw
1 import * as mediatailor from "@distilled.cloud/aws/mediatailor";
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, diffTags, hasAlchemyTags, tagRecord } 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 Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * CDN routing configuration for ad and content segment delivery.
17 */
18 export interface PlaybackConfigurationCdn {
19 /**
20 * A non-default content delivery network (CDN) prefix that MediaTailor
21 * routes ad segment requests through, e.g. a CloudFront distribution in
22 * front of `ads.mediatailor.<region>.amazonaws.com`.
23 */
24 adSegmentUrlPrefix?: string;
25 /**
26 * A content delivery network (CDN) prefix that content segment URLs in
27 * manifests are rewritten to, so players request content through the CDN.
28 */
29 contentSegmentUrlPrefix?: string;
30 }
31
32 /**
33 * DASH manifest handling configuration.
34 */
35 export interface PlaybackConfigurationDash {
36 /**
37 * Where the `Location` element is placed in the DASH manifest.
38 * @default "EMT_DEFAULT"
39 */
40 mpdLocation?: string;
41 /**
42 * Whether the origin server produces single-period or multi-period DASH
43 * manifests. One of `SINGLE_PERIOD` or `MULTI_PERIOD`.
44 * @default "MULTI_PERIOD"
45 */
46 originManifestType?: "SINGLE_PERIOD" | "MULTI_PERIOD";
47 }
48
49 /**
50 * Controls how MediaTailor suppresses ad insertion near the live edge.
51 */
52 export interface PlaybackConfigurationAvailSuppression {
53 /**
54 * `BEHIND_LIVE_EDGE` suppresses ads behind the configured point in the
55 * stream; `AFTER_LIVE_EDGE` suppresses ads after it.
56 * @default "OFF"
57 */
58 mode?: "OFF" | "BEHIND_LIVE_EDGE" | "AFTER_LIVE_EDGE";
59 /**
60 * A live-edge offset timestamp (HH:MM:SS) that defines the suppression
61 * boundary.
62 */
63 value?: string;
64 /**
65 * `PARTIAL_AVAIL` fills partial ad breaks; `FULL_AVAIL_ONLY` only fills
66 * complete ad breaks.
67 */
68 fillPolicy?: "FULL_AVAIL_ONLY" | "PARTIAL_AVAIL";
69 }
70
71 /**
72 * Bumpers are short branded videos played before and after ad breaks.
73 */
74 export interface PlaybackConfigurationBumper {
75 /** URL of the bumper asset played before each ad break. */
76 startUrl?: string;
77 /** URL of the bumper asset played after each ad break. */
78 endUrl?: string;
79 }
80
81 /**
82 * Configuration for pre-roll ad insertion on live streams.
83 */
84 export interface PlaybackConfigurationLivePreRoll {
85 /** The ad decision server URL used for live pre-roll ads. */
86 adDecisionServerUrl?: string;
87 /**
88 * Maximum allowed duration for the pre-roll ad avail, e.g. `"30 seconds"`.
89 * Sent to the API in whole seconds (`MaxDurationSeconds`).
90 */
91 maxDuration?: Duration.Input;
92 }
93
94 /**
95 * CloudWatch log configuration for the playback configuration
96 * (`ConfigureLogsForPlaybackConfiguration`).
97 */
98 export interface PlaybackConfigurationLogs {
99 /**
100 * The percentage of session logs MediaTailor sends to CloudWatch Logs
101 * (0–100). Session logs land in the `MediaTailor/PlaybackConfiguration`
102 * log group (legacy) or the vended-log delivery you configure.
103 */
104 percentEnabled: number;
105 /**
106 * The method MediaTailor uses to deliver the logs:
107 * `LEGACY_CLOUDWATCH` (direct to CloudWatch Logs) and/or `VENDED_LOGS`
108 * (CloudWatch vended log delivery to CloudWatch/S3/Firehose).
109 */
110 enabledLoggingStrategies?: ("LEGACY_CLOUDWATCH" | "VENDED_LOGS")[];
111 }
112
113 /**
114 * Rules that customize how MediaTailor processes the origin manifest.
115 */
116 export interface PlaybackConfigurationManifestProcessingRules {
117 /**
118 * When enabled, `EXT-X-CUE-IN`/`EXT-X-CUE-OUT` (and other ad markers) from
119 * the origin manifest pass through into the personalized manifest.
120 * @default false
121 */
122 adMarkerPassthroughEnabled?: boolean;
123 }
124
125 export interface PlaybackConfigurationProps {
126 /**
127 * The identifier for the playback configuration. Maximum 64 characters,
128 * letters, digits, hyphens, and underscores.
129 *
130 * Changing the name replaces the configuration.
131 * @default ${app}-${stage}-${id}
132 */
133 name?: string;
134 /**
135 * The URL for the ad decision server (ADS). This includes the
136 * specification of static parameters and placeholders for dynamic
137 * parameters, e.g. `https://ads.example.com/vast?ip=[client_ip]`.
138 * Maximum 25,000 characters.
139 */
140 adDecisionServerUrl: string;
141 /**
142 * The URL prefix for the source of the content stream (the origin server),
143 * minus the asset ID. Maximum 512 characters.
144 */
145 videoContentSourceUrl: string;
146 /**
147 * The URL for a video asset to transcode and use to fill in time that's
148 * not used by ads. MediaTailor shows the slate when there is no ad to
149 * fill an avail.
150 */
151 slateAdUrl?: string;
152 /**
153 * Defines the maximum duration of underfilled ad time (e.g. `"2 seconds"`)
154 * allowed in an ad break. Underfilled time beyond the threshold is not
155 * filled with slate. Sent to the API in whole seconds
156 * (`PersonalizationThresholdSeconds`).
157 */
158 personalizationThreshold?: Duration.Input;
159 /**
160 * The name that is used to associate this playback configuration with a
161 * custom transcode profile (set up with AWS Support).
162 */
163 transcodeProfileName?: string;
164 /**
165 * The setting that controls whether players can use stitched or guided ad
166 * insertion. One of `STITCHED_ONLY` or `PLAYER_SELECT`.
167 * @default "STITCHED_ONLY"
168 */
169 insertionMode?: "STITCHED_ONLY" | "PLAYER_SELECT";
170 /**
171 * CDN prefixes for routing ad and content segment requests.
172 */
173 cdnConfiguration?: PlaybackConfigurationCdn;
174 /**
175 * DASH manifest configuration.
176 */
177 dashConfiguration?: PlaybackConfigurationDash;
178 /**
179 * Ad suppression behavior near the live edge.
180 */
181 availSuppression?: PlaybackConfigurationAvailSuppression;
182 /**
183 * Bumper videos played before and after ad breaks.
184 */
185 bumper?: PlaybackConfigurationBumper;
186 /**
187 * Pre-roll ad insertion for live streams.
188 */
189 livePreRollConfiguration?: PlaybackConfigurationLivePreRoll;
190 /**
191 * Origin-manifest processing rules (e.g. ad marker passthrough).
192 */
193 manifestProcessingRules?: PlaybackConfigurationManifestProcessingRules;
194 /**
195 * CloudWatch session-log configuration. Omit (or set `percentEnabled: 0`)
196 * to disable session logging.
197 */
198 logConfiguration?: PlaybackConfigurationLogs;
199 /**
200 * Tags to apply to the playback configuration. Merged with internal
201 * Alchemy tags.
202 */
203 tags?: Record<string, string>;
204 }
205
206 export interface PlaybackConfiguration extends Resource<
207 "AWS.MediaTailor.PlaybackConfiguration",
208 PlaybackConfigurationProps,
209 {
210 /** The identifier for the playback configuration. */
211 name: string;
212 /** The ARN of the playback configuration. */
213 playbackConfigurationArn: string;
214 /** The URL that the player accesses to get a manifest from MediaTailor. */
215 playbackEndpointPrefix: string;
216 /** The URL that the player uses to initialize a session that uses client-side reporting. */
217 sessionInitializationEndpointPrefix: string;
218 /** The HLS manifest endpoint prefix, if HLS is configured. */
219 hlsManifestEndpointPrefix: string | undefined;
220 /** The DASH manifest endpoint prefix, if DASH is configured. */
221 dashManifestEndpointPrefix: string | undefined;
222 },
223 never,
224 Providers
225 > {}
226
227 /**
228 * An AWS Elemental MediaTailor playback configuration for server-side ad
229 * insertion (SSAI) into HLS and DASH video streams.
230 *
231 * ### Creating Playback Configurations
232 * **Example:** Basic ad-inserted stream
233 * ```typescript
234 * import * as MediaTailor from "@alchemy.run/aws/MediaTailor";
235 *
236 * const config = yield* MediaTailor.PlaybackConfiguration("Ads", {
237 * adDecisionServerUrl: "https://ads.example.com/vast?ip=[client_ip]",
238 * videoContentSourceUrl: "https://origin.example.com/live",
239 * });
240 * ```
241 *
242 * **Example:** Slate fill and personalization threshold
243 * ```typescript
244 * const config = yield* MediaTailor.PlaybackConfiguration("Ads", {
245 * adDecisionServerUrl: "https://ads.example.com/vast",
246 * videoContentSourceUrl: "https://origin.example.com/vod",
247 * slateAdUrl: "https://origin.example.com/slate.mp4",
248 * personalizationThreshold: "2 seconds",
249 * });
250 * ```
251 *
252 * ### Manifest Behavior
253 * **Example:** Ad marker passthrough and avail suppression
254 * ```typescript
255 * const config = yield* MediaTailor.PlaybackConfiguration("Live", {
256 * adDecisionServerUrl: "https://ads.example.com/vast",
257 * videoContentSourceUrl: "https://origin.example.com/live",
258 * manifestProcessingRules: { adMarkerPassthroughEnabled: true },
259 * availSuppression: { mode: "BEHIND_LIVE_EDGE", value: "00:00:30" },
260 * });
261 * ```
262 *
263 * ### Session Logging
264 * **Example:** Send 10% of session logs to CloudWatch
265 * ```typescript
266 * const config = yield* MediaTailor.PlaybackConfiguration("Logged", {
267 * adDecisionServerUrl: "https://ads.example.com/vast",
268 * videoContentSourceUrl: "https://origin.example.com/live",
269 * logConfiguration: { percentEnabled: 10 },
270 * });
271 * ```
272 *
273 * @resource
274 */
275 export const PlaybackConfiguration = Resource<PlaybackConfiguration>(
276 "AWS.MediaTailor.PlaybackConfiguration",
277 );
278
279 /**
280 * Raised when MediaTailor returns a playback configuration without the
281 * attributes the provider needs (ARN and playback endpoints). This indicates
282 * an unexpected API response rather than a user error.
283 */
284 export class MediaTailorIncompletePlaybackConfiguration extends Data.TaggedError(
285 "MediaTailorIncompletePlaybackConfiguration",
286 )<{ message: string }> {}
287
288 type PlaybackConfigurationAttributes = {
289 name: string;
290 playbackConfigurationArn: string;
291 playbackEndpointPrefix: string;
292 sessionInitializationEndpointPrefix: string;
293 hlsManifestEndpointPrefix: string | undefined;
294 dashManifestEndpointPrefix: string | undefined;
295 };
296
297 export const PlaybackConfigurationProvider = () =>
298 Provider.effect(
299 PlaybackConfiguration,
300 Effect.gen(function* () {
301 const createName = Effect.fn(function* (
302 id: string,
303 props: Pick<PlaybackConfigurationProps, "name">,
304 ) {
305 // MediaTailor playback configuration names max out at 64 characters.
306 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
307 });
308
309 const toAttributes = Effect.fn(function* (
310 config: mediatailor.GetPlaybackConfigurationResponse,
311 ) {
312 if (
313 config.Name === undefined ||
314 config.PlaybackConfigurationArn === undefined ||
315 config.PlaybackEndpointPrefix === undefined ||
316 config.SessionInitializationEndpointPrefix === undefined
317 ) {
318 return yield* new MediaTailorIncompletePlaybackConfiguration({
319 message: `playback configuration '${config.Name}' is missing its ARN or endpoint prefixes`,
320 });
321 }
322 return {
323 name: config.Name,
324 playbackConfigurationArn: config.PlaybackConfigurationArn,
325 playbackEndpointPrefix: config.PlaybackEndpointPrefix,
326 sessionInitializationEndpointPrefix: config.SessionInitializationEndpointPrefix,
327 hlsManifestEndpointPrefix: config.HlsConfiguration?.ManifestEndpointPrefix,
328 dashManifestEndpointPrefix: config.DashConfiguration?.ManifestEndpointPrefix,
329 } satisfies PlaybackConfigurationAttributes;
330 });
331
332 const observe = (name: string) =>
333 mediatailor.getPlaybackConfiguration({ Name: name }).pipe(
334 Effect.map((config): mediatailor.GetPlaybackConfigurationResponse | undefined => config),
335 // Typed synthetic tag for a missing playback configuration.
336 Effect.catchTag("PlaybackConfigurationNotFound", () => Effect.undefined),
337 );
338
339 const desiredRequest = (
340 name: string,
341 props: PlaybackConfigurationProps,
342 ): mediatailor.PutPlaybackConfigurationRequest => ({
343 Name: name,
344 AdDecisionServerUrl: props.adDecisionServerUrl,
345 VideoContentSourceUrl: props.videoContentSourceUrl,
346 SlateAdUrl: props.slateAdUrl,
347 PersonalizationThresholdSeconds: toWireSeconds(props.personalizationThreshold),
348 TranscodeProfileName: props.transcodeProfileName,
349 InsertionMode: props.insertionMode,
350 CdnConfiguration: props.cdnConfiguration && {
351 AdSegmentUrlPrefix: props.cdnConfiguration.adSegmentUrlPrefix,
352 ContentSegmentUrlPrefix: props.cdnConfiguration.contentSegmentUrlPrefix,
353 },
354 DashConfiguration: props.dashConfiguration && {
355 MpdLocation: props.dashConfiguration.mpdLocation,
356 OriginManifestType: props.dashConfiguration.originManifestType,
357 },
358 AvailSuppression: props.availSuppression && {
359 Mode: props.availSuppression.mode,
360 Value: props.availSuppression.value,
361 FillPolicy: props.availSuppression.fillPolicy,
362 },
363 Bumper: props.bumper && {
364 StartUrl: props.bumper.startUrl,
365 EndUrl: props.bumper.endUrl,
366 },
367 LivePreRollConfiguration: props.livePreRollConfiguration && {
368 AdDecisionServerUrl: props.livePreRollConfiguration.adDecisionServerUrl,
369 MaxDurationSeconds: toWireSeconds(props.livePreRollConfiguration.maxDuration),
370 },
371 ManifestProcessingRules: props.manifestProcessingRules && {
372 AdMarkerPassthrough: {
373 Enabled: props.manifestProcessingRules.adMarkerPassthroughEnabled,
374 },
375 },
376 });
377
378 return PlaybackConfiguration.Provider.of({
379 stables: ["name", "playbackConfigurationArn"],
380 list: () =>
381 Effect.gen(function* () {
382 const items = yield* mediatailor.listPlaybackConfigurations
383 .items({})
384 .pipe(Stream.runCollect);
385 return Array.from(items).flatMap((config) =>
386 config.Name !== undefined &&
387 config.PlaybackConfigurationArn !== undefined &&
388 config.PlaybackEndpointPrefix !== undefined &&
389 config.SessionInitializationEndpointPrefix !== undefined
390 ? [
391 {
392 name: config.Name,
393 playbackConfigurationArn: config.PlaybackConfigurationArn,
394 playbackEndpointPrefix: config.PlaybackEndpointPrefix,
395 sessionInitializationEndpointPrefix:
396 config.SessionInitializationEndpointPrefix,
397 hlsManifestEndpointPrefix: config.HlsConfiguration?.ManifestEndpointPrefix,
398 dashManifestEndpointPrefix: config.DashConfiguration?.ManifestEndpointPrefix,
399 },
400 ]
401 : [],
402 );
403 }),
404 read: Effect.fn(function* ({ id, olds, output }) {
405 const name = output?.name ?? (yield* createName(id, olds ?? {}));
406 const found = yield* observe(name);
407 if (found === undefined) return undefined;
408 const attrs = yield* toAttributes(found);
409 return (yield* hasAlchemyTags(id, tagRecord(found.Tags))) ? attrs : Unowned(attrs);
410 }),
411 diff: Effect.fn(function* ({ id, news, olds }) {
412 if (!isResolved(news)) return undefined;
413 const oldName = yield* createName(id, olds ?? {});
414 const newName = yield* createName(id, news ?? {});
415 if (oldName !== newName) {
416 return { action: "replace" } as const;
417 }
418 // fall through: engine default update logic for mutable fields
419 }),
420 reconcile: Effect.fn(function* ({ id, news, output, session }) {
421 const name = output?.name ?? (yield* createName(id, news));
422 const internalTags = yield* createInternalTags(id);
423 const desiredTags = { ...news.tags, ...internalTags };
424
425 // 1. ENSURE + SYNC — PutPlaybackConfiguration is a full-replace
426 // upsert: omitted fields are cleared server-side. Because a
427 // prop the user removed must be un-set on the cloud config,
428 // the put is always applied (a subset comparison against the
429 // observed config cannot see removals, and server-side
430 // defaults make full-equality checks fragile). This one call
431 // converges greenfield, update, and adoption identically.
432 const put = yield* mediatailor.putPlaybackConfiguration({
433 ...desiredRequest(name, news),
434 Tags: desiredTags,
435 });
436 const attrs = yield* toAttributes(put);
437
438 // 2. SYNC LOGS — ConfigureLogsForPlaybackConfiguration is a
439 // separate API; diff the OBSERVED post-put log configuration
440 // against the desired one and only call the API on a delta.
441 // A removed `logConfiguration` prop converges to percent 0
442 // (session logging disabled).
443 const desiredLogs = news.logConfiguration;
444 const observedLogs = put.LogConfiguration;
445 const observedPercent = observedLogs?.PercentEnabled ?? 0;
446 const desiredPercent = desiredLogs?.percentEnabled ?? 0;
447 const observedStrategies = [...(observedLogs?.EnabledLoggingStrategies ?? [])].sort();
448 const desiredStrategies =
449 desiredLogs === undefined
450 ? observedStrategies // nothing desired: only percent converges
451 : [...(desiredLogs.enabledLoggingStrategies ?? [])].sort();
452 if (
453 observedPercent !== desiredPercent ||
454 observedStrategies.join(",") !== desiredStrategies.join(",")
455 ) {
456 yield* mediatailor.configureLogsForPlaybackConfiguration({
457 PlaybackConfigurationName: name,
458 PercentEnabled: desiredPercent,
459 ...(desiredLogs?.enabledLoggingStrategies
460 ? {
461 EnabledLoggingStrategies: desiredLogs.enabledLoggingStrategies,
462 }
463 : {}),
464 });
465 }
466
467 // 3. SYNC TAGS — diff against the OBSERVED post-put tags so
468 // adoption (which can bring foreign tags the put may not
469 // remove) converges.
470 const currentTags = tagRecord(put.Tags);
471 const { upsert, removed } = diffTags(currentTags, desiredTags);
472 if (upsert.length > 0) {
473 yield* mediatailor.tagResource({
474 ResourceArn: attrs.playbackConfigurationArn,
475 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
476 });
477 }
478 if (removed.length > 0) {
479 yield* mediatailor.untagResource({
480 ResourceArn: attrs.playbackConfigurationArn,
481 TagKeys: removed,
482 });
483 }
484
485 yield* session.note(name);
486 return attrs;
487 }),
488 delete: Effect.fn(function* ({ output }) {
489 // DeletePlaybackConfiguration is idempotent server-side: deleting
490 // a configuration that does not exist succeeds with an empty body
491 // (verified live), so no not-found handling is required.
492 yield* mediatailor.deletePlaybackConfiguration({
493 Name: output.name,
494 });
495 }),
496 });
497 }),
498 );