import type { LivestreamSpec, Segment } from "../transport/livestream-session.ts"; import type { Clock } from "../clock.ts"; import type { ProtectError } from "../errors.ts"; import type { ProtectLogging } from "../logging.ts"; import type { ProtectWebSocket } from "../transport/ws.ts"; /** * The coarse, stable lifecycle of a pooled stream as a subscriber observes it. `connecting` is bounded establishment (no segment has ever flowed); `live` is a healthy * stream; `recovering` is an in-flight recovery episode (a recoverable stall shows here *without* ending iteration); `closed` is terminal (disposed, codec change, or the * policy gave up). * * @category Client */ export type LivestreamSubscriptionState = "closed" | "connecting" | "live" | "recovering"; /** * What the library can observe at a recovery decision point. Consumer-private state (buffer headroom, controller health) is deliberately *not* here - a consumer that * wants to correlate recovery with controller health reads it in its own policy closure. The fields are exactly what the library itself can compute. * * @category Client */ export interface RecoveryContext { /** Consecutive failed reconnect attempts this episode; resets to 0 once a media segment flows again. */ attempts: number; /** The camera this recovery episode belongs to, so a consumer policy can correlate the decision with per-camera state it alone observes. */ cameraId: string; /** Milliseconds since this episode began (the stall moment, or the first establish attempt). Lets a policy enforce a bounded establishment deadline. */ elapsedMs: number; /** Bounded establishment (fail fast if it never came up) vs. unbounded live recovery (it proved itself once). */ phase: "establishing" | "recovering"; /** Aggregated delay tolerance across subscribers - the MINIMUM reported, so the most-urgent governs; `Infinity` when none reported. */ toleranceMs: number; } /** * A recovery decision the {@link RecoveryPolicy} returns. Its arms are exhaustive: * * - `reconnect` tears down any socket and connects fresh; the attempt is treated as failed if no media segment arrives within `awaitMs`, then the policy is re-consulted. * `awaitMs` doubles as the inter-attempt spacing (a fast-failing attempt still occupies its full window), so the single policy governs both disposition and timing. * - `wait` does nothing for `forMs`, then re-consults - unifying defer-soak (a still-connecting session's late segment cancels it early) and inter-attempt backoff. * - `giveUp` is terminal: the give-up error is thrown into every subscriber and the stream is torn down. * * @category Client */ export type RecoveryDecision = { awaitMs: number; kind: "reconnect"; } | { forMs: number; kind: "wait"; } | { kind: "giveUp"; }; /** * The single decision authority for a stream's recovery, injected at the pool (the same dependency-inversion seam as `resolveUrl`). Pure: given the library-observable * {@link RecoveryContext}, it returns a {@link RecoveryDecision}. The library ships {@link defaultLivestreamRecoveryPolicy}, a health-agnostic default; a consumer * injects its own to add the controller-health correlation only it can observe. * * @category Client */ export type RecoveryPolicy = (context: RecoveryContext) => RecoveryDecision; /** * The library's default, health-agnostic recovery policy. It is **phase-split**, because the two regimes have different timing authorities: * * - **Establishment (`phase === "establishing"`) is hardware-bound and urgency-INDEPENDENT.** A fresh stream is minted at the camera's own first-segment latency, which * no consumer can hurry - so the per-attempt window follows the fixed, patient {@link PROTECT_LIVESTREAM_ESTABLISH_BACKOFF_MS} curve and ignores `toleranceMs` entirely * (tearing a fresh stream down early just churns the negotiation). It gives up once the episode runs past {@link PROTECT_LIVESTREAM_ESTABLISH_DEADLINE_MS} - the * stream that connects but never produces media, its windows walking the patient establishment curve and holding at the last stage until the deadline. * - **Live recovery (`phase === "recovering"`) is headroom-clamped and unbounded.** A stream that proved itself once is retried forever (never `giveUp`); each window * grows along {@link PROTECT_LIVESTREAM_RECOVERY_BACKOFF_MS}, capped by the consumer's headroom (the aggregated tolerance less a margin; the patient default when none * reported) and clamped to {@link PROTECT_LIVESTREAM_AWAIT_MIN_MS}/{@link PROTECT_LIVESTREAM_AWAIT_MAX_MS}. An urgent subscriber recovers at the floor; a patient one * follows the curve. * * These are safe **ecosystem** defaults - conservative across the diverse hardware real users run, not tuned for a fast controller. A consumer that has measured its own * controllers' latency (e.g. HBUP) injects a tighter policy; a consumer composing one may delegate here for the timing and override only the disposition, or replace it. * * @param context - The library-observable recovery context. * * @returns The recovery decision for this step. * * @category Client */ export declare function defaultLivestreamRecoveryPolicy(context: RecoveryContext): RecoveryDecision; /** * The delivery counters a {@link LivestreamSubscription} exposes, so a consumer can monitor its own slowness (a growing `queueDepth` / `peakQueueDepth`) and respond - * the only backpressure mechanism, since the queue itself is unbounded. * * @category Client */ export interface LivestreamSubscriptionStats { delivered: number; lastSegmentAt: number; peakQueueDepth: number; queueDepth: number; } /** * Construction options for {@link LivestreamPool}. `resolveUrl` is the transport-backed negotiation seam (build it with {@link livestreamUrlResolver}, the shared {@link * wsEndpointResolver}'s livestream specialization); `webSocket` is the injected I/O seam, shared with {@link EventStream}'s and threaded down to each session; * `recoveryPolicy` is the per-stream recovery decision authority, defaulting to {@link defaultLivestreamRecoveryPolicy}. * * @category Client */ export interface LivestreamPoolOptions { clock?: Clock; log?: ProtectLogging; recoveryPolicy?: RecoveryPolicy; resolveUrl: (params: URLSearchParams, opts: { signal?: AbortSignal; }) => Promise; webSocket?: (url: string) => ProtectWebSocket; } interface SubscriptionHost { get initSegment(): { codec: string; data: Buffer; } | null; get state(): LivestreamSubscriptionState; reassess(): void; whenEstablished(): Promise; } /** * A consumer's handle into a pooled livestream. It is an `AsyncIterable` (the iterator *is* the surface - no callback rail) and `AsyncDisposable`. Each * subscription has its **own unbounded queue**: the pool pushes every segment to every subscriber, so one slow consumer cannot stall a fast one, and nothing is dropped. * * The stream is **resilient by default**: a recoverable stall or reconnect is invisible to the iterator - it pauses while the underlying session is re-established and * resumes seamlessly when segments flow again (a same-codec reconnect suppresses the redundant init). The iterator terminates only on these conditions: disposal (a * clean `done`), a codec change across a reconnect (it throws {@link ProtectCodecChangeError}), and the recovery policy giving up (it throws {@link * ProtectLivestreamUnavailableError}). A recoverable stall is *not* one of them. * * @category Client */ export declare class LivestreamSubscription implements AsyncIterable, AsyncDisposable { #private; /** This subscription's unique id, correlated with the `subscription:created` / `:disposed` diagnostics. */ readonly id: string; constructor(opts: { clock: Clock; host: SubscriptionHost; onDispose: (subscription: LivestreamSubscription) => void; signal?: AbortSignal; }); /** The negotiated RFC 6381 codec descriptor once the init segment has arrived, otherwise `""`. Read through to the shared session's cached init, the single source. */ get codec(): string; /** * The cached initialization segment of the shared stream once it has arrived, otherwise `null`. Stable across same-codec reconnects (it is suppressed and the cache is * retained), and replaced only on a codec change - which is itself terminal, so a consumer never observes the cached init mutate beneath it mid-stream. */ get initSegment(): { codec: string; data: Buffer; } | null; /** The coarse, stable lifecycle state. `"closed"` once this subscription is disposed; else the shared stream's state (a recoverable stall reads `"recovering"`). */ get state(): LivestreamSubscriptionState; /** The live delivery counters for this subscription. `queueDepth` / `peakQueueDepth` let a consumer detect that it is falling behind. */ get stats(): LivestreamSubscriptionStats; /** * Iterate the segments of this subscription. The iterator yields every queued segment, then either ends (clean close / disposal) or throws the terminal error (codec * change or give-up). A recoverable stall is invisible - the iterator parks and resumes. Breaking out of the loop disposes the subscription. * * @returns An async iterator of segments. */ [Symbol.asyncIterator](): AsyncIterator; /** * Dispose the subscription: detach it from its shared session (decrementing the reference count, which tears the session down if it was the last), end any in-flight * iteration, and detach the consumer's abort listener. Idempotent. */ [Symbol.asyncDispose](): Promise; /** * Ask the shared stream's recovery policy to re-decide now - for example when this consumer's urgency just changed. It only re-decides an *in-flight* recovery episode, * so on a healthy stream it is a no-op; it never forces a reconnect of a working connection. */ reassess(): void; /** * Resolve once the shared stream has produced its first MEDIA segment (`true`), or once it has given up before ever establishing (`false`). Liveness is media-keyed: a * controller that connects and acks with an init but then produces no media is NOT established - it elapses its recovery window and reconnects, so this resolves `true` * only when media is actually flowing. This is the boundary the two recovery regimes hinge on - a consumer awaits it to know media came up at all before settling into * the resilient steady state. * * @returns A promise resolving `true` once the first media segment flows, `false` if establishment was abandoned. */ whenEstablished(): Promise; push(segment: Segment): void; fail(error: ProtectError): void; close(): void; } /** * The ref-counted, multi-subscriber, resilient-by-default livestream pool. Construct it at the composition root with a transport-backed {@link livestreamUrlResolver} * (the shared {@link wsEndpointResolver}'s livestream specialization) and an optional {@link RecoveryPolicy}; consumers reach it through `camera.livestream(...)`. * * @category Client */ export declare class LivestreamPool implements AsyncDisposable { #private; constructor(options: LivestreamPoolOptions); /** * Subscribe to a camera livestream. Returns immediately with a {@link LivestreamSubscription}; segments begin flowing once the underlying session connects (or * immediately, replayed from the cached init, for a shared session already live). Subscribers asking for an identical stream share one underlying WebSocket, and the * shared session recovers under the pool's policy without failing any subscriber. * * @param spec - The stream to subscribe to. * @param opts - An optional abort signal that disposes this subscription (and only this one), and an optional `urgency` closure reporting how many milliseconds this * consumer can tolerate receiving no segment (pulled at each recovery decision; aggregated across the shared stream by the minimum). * * @returns A live subscription. */ subscribe(spec: LivestreamSpec, opts?: { signal?: AbortSignal; urgency?: () => number; }): LivestreamSubscription; /** * Dispose the pool: close every managed session and clear the map. Called by the client's own disposal. */ [Symbol.asyncDispose](): Promise; } export {}; //# sourceMappingURL=livestream-pool.d.ts.map