@portalshq/capability-video-delivery 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,34 @@
1
1
  # @portalshq/capability-video-delivery
2
2
 
3
- Live + VOD behind one interface so branching-film, game-show, and any
4
- future video-bearing channel type share the same delivery capability
5
- instead of each integrating their own transcoding/CDN stack. Edge target
6
- is Akamai (see infra/terraform/akamai-cdn) — chosen for video-egress cost,
7
- which the platform economics review flags as the dominant linear cost
8
- driver at audience scale.
3
+ `LiveDelivery` connects one configured HLS playback stream per instance. It
4
+ does not create an origin, schedule programs, or define whether content is
5
+ "live" or "VOD"; those are application business decisions. It verifies the
6
+ configured manifest on start, retries connection failures, and continues to
7
+ monitor its health while active.
8
+
9
+ `HlsPlaybackSession` is the common, token-free descriptor for an HLS-capable
10
+ application player. Queue Broadcast returns this descriptor after its trusted
11
+ backend has talked to the queue control plane; the player receives only the
12
+ public/unlisted manifest URL.
13
+
14
+ ## Scheduled and dual-format programming
15
+
16
+ Create separate delivery objects for independent stream windows. For example,
17
+ an application can start a `morning` instance for a 9am–12pm manifest and an
18
+ `afternoon` instance for a 1pm–5pm manifest. The application owns that clock,
19
+ its routing, and any VOD-versus-live presentation rules; each `LiveDelivery`
20
+ object only observes and returns its one configured HLS stream.
21
+
22
+ ```ts
23
+ const morning = new LiveDelivery({
24
+ sessionId: "morning-stream",
25
+ playbackManifestUrl: "https://media.example/morning/index.m3u8",
26
+ });
27
+ const afternoon = new LiveDelivery({
28
+ sessionId: "afternoon-stream",
29
+ playbackManifestUrl: "https://media.example/afternoon/index.m3u8",
30
+ });
31
+
32
+ await morning.start();
33
+ // Application-owned scheduler later calls morning.stop() and afternoon.start().
34
+ ```
package/dist/index.d.ts CHANGED
@@ -1,2 +1 @@
1
1
  export * from "./live-session.js";
2
- export * from "./vod-session.js";
package/dist/index.js CHANGED
@@ -1,2 +1 @@
1
1
  export * from "./live-session.js";
2
- export * from "./vod-session.js";
@@ -1,15 +1,52 @@
1
- /**
2
- * Live broadcast delivery. Origin -> Akamai edge -> audience. This package
3
- * intentionally exposes only session lifecycle + manifest URL — codec,
4
- * bitrate ladder, and origin packaging are implementation details that can
5
- * change without breaking any channel that consumes this capability.
6
- */
7
- export interface LiveSessionHandle {
1
+ /** A token-free HLS source that an application can hand to its player. */
2
+ export interface HlsPlaybackSession {
8
3
  sessionId: string;
9
- ingestUrl: string;
10
4
  playbackManifestUrl: string;
11
5
  }
6
+ export interface LiveDeliveryOptions extends HlsPlaybackSession {
7
+ /** Number of immediate connection attempts before start fails. */
8
+ retryAttempts?: number;
9
+ /** Delay between connection attempts. */
10
+ retryDelayMs?: number;
11
+ /** Recheck the configured manifest while the delivery is active. */
12
+ healthCheckIntervalMs?: number;
13
+ /** Abort an individual manifest request after this duration. Defaults to 10 seconds. */
14
+ requestTimeoutMs?: number;
15
+ /** Injectable for non-browser server runtimes and tests. */
16
+ fetch?: typeof fetch;
17
+ }
18
+ export interface LiveDeliveryStatus extends HlsPlaybackSession {
19
+ isRunning: boolean;
20
+ isHealthy: boolean;
21
+ lastCheckedAt?: string;
22
+ lastError?: string;
23
+ }
24
+ /**
25
+ * Connects one configured HLS playback stream. It never provisions an origin,
26
+ * schedules programming, or distinguishes live from on-demand business flows.
27
+ */
12
28
  export declare class LiveDelivery {
13
- start(sessionId: string): Promise<LiveSessionHandle>;
14
- stop(sessionId: string): Promise<void>;
29
+ private readonly session;
30
+ private readonly retryAttempts;
31
+ private readonly retryDelayMs;
32
+ private readonly healthCheckIntervalMs;
33
+ private readonly requestTimeoutMs;
34
+ private readonly requestFetch;
35
+ private healthCheckTimer;
36
+ private startPromise;
37
+ private activeRequest;
38
+ private lifecycleGeneration;
39
+ private isRunning;
40
+ private isHealthy;
41
+ private lastCheckedAt;
42
+ private lastError;
43
+ constructor(options: LiveDeliveryOptions);
44
+ start(): Promise<HlsPlaybackSession>;
45
+ stop(): Promise<void>;
46
+ getStatus(): LiveDeliveryStatus;
47
+ private connect;
48
+ private scheduleHealthCheck;
49
+ private refreshHealth;
50
+ private checkHealthWithRetry;
51
+ private assertCurrent;
15
52
  }
@@ -1,8 +1,173 @@
1
+ /**
2
+ * Connects one configured HLS playback stream. It never provisions an origin,
3
+ * schedules programming, or distinguishes live from on-demand business flows.
4
+ */
1
5
  export class LiveDelivery {
2
- async start(sessionId) {
3
- throw new Error("LiveDelivery.start: not yet wired to origin/Akamai config");
6
+ session;
7
+ retryAttempts;
8
+ retryDelayMs;
9
+ healthCheckIntervalMs;
10
+ requestTimeoutMs;
11
+ requestFetch;
12
+ healthCheckTimer = null;
13
+ startPromise = null;
14
+ activeRequest = null;
15
+ lifecycleGeneration = 0;
16
+ isRunning = false;
17
+ isHealthy = false;
18
+ lastCheckedAt;
19
+ lastError;
20
+ constructor(options) {
21
+ this.session = {
22
+ sessionId: assertSessionId(options.sessionId),
23
+ playbackManifestUrl: normalizeManifestUrl(options.playbackManifestUrl),
24
+ };
25
+ this.retryAttempts = options.retryAttempts ?? 3;
26
+ this.retryDelayMs = options.retryDelayMs ?? 1_000;
27
+ this.healthCheckIntervalMs = options.healthCheckIntervalMs ?? 30_000;
28
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 10_000;
29
+ this.requestFetch = options.fetch ?? fetch;
30
+ assertPositiveInteger("retryAttempts", this.retryAttempts);
31
+ assertNonNegativeInteger("retryDelayMs", this.retryDelayMs);
32
+ assertPositiveInteger("healthCheckIntervalMs", this.healthCheckIntervalMs);
33
+ assertPositiveInteger("requestTimeoutMs", this.requestTimeoutMs);
4
34
  }
5
- async stop(sessionId) {
6
- throw new Error("LiveDelivery.stop: not yet implemented");
35
+ async start() {
36
+ if (this.isRunning)
37
+ return this.session;
38
+ if (!this.startPromise) {
39
+ const generation = ++this.lifecycleGeneration;
40
+ this.startPromise = this.connect(generation);
41
+ }
42
+ const pendingStart = this.startPromise;
43
+ try {
44
+ return await pendingStart;
45
+ }
46
+ finally {
47
+ if (this.startPromise === pendingStart)
48
+ this.startPromise = null;
49
+ }
7
50
  }
51
+ async stop() {
52
+ this.lifecycleGeneration += 1;
53
+ this.isRunning = false;
54
+ this.isHealthy = false;
55
+ this.activeRequest?.abort(new Error("LiveDelivery stopped"));
56
+ this.activeRequest = null;
57
+ this.startPromise = null;
58
+ if (this.healthCheckTimer)
59
+ clearTimeout(this.healthCheckTimer);
60
+ this.healthCheckTimer = null;
61
+ }
62
+ getStatus() {
63
+ return {
64
+ ...this.session,
65
+ isRunning: this.isRunning,
66
+ isHealthy: this.isHealthy,
67
+ ...(this.lastCheckedAt ? { lastCheckedAt: this.lastCheckedAt } : {}),
68
+ ...(this.lastError ? { lastError: this.lastError } : {}),
69
+ };
70
+ }
71
+ async connect(generation) {
72
+ await this.checkHealthWithRetry(generation);
73
+ this.assertCurrent(generation);
74
+ this.isRunning = true;
75
+ this.scheduleHealthCheck(generation);
76
+ return this.session;
77
+ }
78
+ scheduleHealthCheck(generation) {
79
+ if (!this.isRunning || generation !== this.lifecycleGeneration)
80
+ return;
81
+ if (this.healthCheckTimer)
82
+ clearTimeout(this.healthCheckTimer);
83
+ this.healthCheckTimer = setTimeout(() => {
84
+ this.healthCheckTimer = null;
85
+ void this.refreshHealth(generation);
86
+ }, this.healthCheckIntervalMs);
87
+ this.healthCheckTimer.unref?.();
88
+ }
89
+ async refreshHealth(generation) {
90
+ try {
91
+ await this.checkHealthWithRetry(generation);
92
+ }
93
+ catch {
94
+ // The status records the error; an intermittent check must not crash the host process.
95
+ }
96
+ finally {
97
+ this.scheduleHealthCheck(generation);
98
+ }
99
+ }
100
+ async checkHealthWithRetry(generation) {
101
+ let error;
102
+ for (let attempt = 1; attempt <= this.retryAttempts; attempt++) {
103
+ this.assertCurrent(generation);
104
+ const controller = new AbortController();
105
+ const timeout = setTimeout(() => controller.abort(new Error(`manifest request timed out after ${this.requestTimeoutMs}ms`)), this.requestTimeoutMs);
106
+ timeout.unref?.();
107
+ this.activeRequest = controller;
108
+ try {
109
+ const response = await this.requestFetch(this.session.playbackManifestUrl, {
110
+ method: "GET",
111
+ headers: { Accept: "application/vnd.apple.mpegurl, application/x-mpegURL" },
112
+ signal: controller.signal,
113
+ });
114
+ this.assertCurrent(generation);
115
+ if (!response.ok)
116
+ throw new Error(`manifest returned HTTP ${response.status}`);
117
+ this.isHealthy = true;
118
+ this.lastError = undefined;
119
+ this.lastCheckedAt = new Date().toISOString();
120
+ return;
121
+ }
122
+ catch (caught) {
123
+ this.assertCurrent(generation);
124
+ error = caught;
125
+ if (attempt < this.retryAttempts) {
126
+ await wait(this.retryDelayMs);
127
+ this.assertCurrent(generation);
128
+ }
129
+ }
130
+ finally {
131
+ clearTimeout(timeout);
132
+ if (this.activeRequest === controller)
133
+ this.activeRequest = null;
134
+ }
135
+ }
136
+ this.isHealthy = false;
137
+ this.lastCheckedAt = new Date().toISOString();
138
+ this.lastError = error instanceof Error ? error.message : String(error);
139
+ throw new Error(`Unable to connect to configured stream: ${this.lastError}`, { cause: error });
140
+ }
141
+ assertCurrent(generation) {
142
+ if (generation !== this.lifecycleGeneration) {
143
+ throw new Error("LiveDelivery operation was stopped");
144
+ }
145
+ }
146
+ }
147
+ function assertSessionId(sessionId) {
148
+ const normalized = sessionId.trim();
149
+ if (!normalized)
150
+ throw new TypeError("sessionId is required");
151
+ return normalized;
152
+ }
153
+ function normalizeManifestUrl(value) {
154
+ const url = new URL(value);
155
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
156
+ throw new TypeError("playbackManifestUrl must use http or https");
157
+ }
158
+ if (url.username || url.password || url.hash) {
159
+ throw new TypeError("playbackManifestUrl cannot include credentials or a fragment");
160
+ }
161
+ return url.toString();
162
+ }
163
+ function assertPositiveInteger(name, value) {
164
+ if (!Number.isInteger(value) || value < 1)
165
+ throw new TypeError(`${name} must be a positive integer`);
166
+ }
167
+ function assertNonNegativeInteger(name, value) {
168
+ if (!Number.isInteger(value) || value < 0)
169
+ throw new TypeError(`${name} must be a non-negative integer`);
170
+ }
171
+ function wait(delayMs) {
172
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
8
173
  }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@portalshq/capability-video-delivery",
3
- "version": "0.1.1",
3
+ "version": "0.1.4",
4
4
  "repository": {
5
5
  "type": "git",
6
- "url": "git+https://github.com/portalshq/portals-cloud"
6
+ "url": "git+https://github.com/portalshq/portals-cloud.git"
7
7
  },
8
- "description": "Live and VOD session delivery, abstracted behind one interface. Edge delivery target: Akamai CDN.",
8
+ "description": "Configured HLS stream delivery for application-owned programming and scheduling.",
9
9
  "type": "module",
10
10
  "main": "dist/index.js",
11
11
  "types": "dist/index.d.ts",
@@ -13,14 +13,19 @@
13
13
  "dist"
14
14
  ],
15
15
  "scripts": {
16
- "build": "tsc -p tsconfig.json",
17
- "typecheck": "tsc -p tsconfig.json --noEmit"
16
+ "build": "rm -rf dist && tsc -p tsconfig.json",
17
+ "publish": "node ../../scripts/publish-workspace.mjs",
18
+ "typecheck": "tsc -p tsconfig.json --noEmit",
19
+ "test": "vitest run",
20
+ "test:coverage": "vitest run --coverage"
18
21
  },
19
22
  "dependencies": {
20
- "@portalshq/contracts": "*"
23
+ "@portalshq/contracts": "^0.0.3"
21
24
  },
22
25
  "devDependencies": {
26
+ "@types/node": "^20.0.0",
27
+ "@vitest/coverage-v8": "^3.2.7",
23
28
  "typescript": "^5.5.0",
24
- "@types/node": "^20.0.0"
29
+ "vitest": "^3.2.7"
25
30
  }
26
31
  }
@@ -1,8 +0,0 @@
1
- export interface VodAsset {
2
- assetId: string;
3
- playbackManifestUrl: string;
4
- durationSeconds: number;
5
- }
6
- export declare class VodDelivery {
7
- getAsset(assetId: string): Promise<VodAsset>;
8
- }
@@ -1,5 +0,0 @@
1
- export class VodDelivery {
2
- async getAsset(assetId) {
3
- throw new Error("VodDelivery.getAsset: not yet wired to object storage / Akamai edge");
4
- }
5
- }