moq_wasm

moq-wasm for Python

Async Python SDK for Media over QUIC Transport (MoQT). Connect to a relay over QUIC or WebTransport to exchange raw data tracks, publish or decode media broadcasts, and build Pipecat AI bots interoperable with the JavaScript and Rust SDKs.

Choose what to install

Package Module Use for
moq-wasm moq_wasm, moq_wasm.media Relay sessions, raw tracks, MSF broadcasts, and event timelines
moq-wasm[codecs] moq_wasm.codecs PyAV helpers: Opus encode/decode, video decode (H.264/H.265/VP8/VP9/AV1), video encode (H.264/VP8)
moq-wasm[pipecat] moq_wasm.pipecat MoqWasmTransport and MoqWasmParticipantInput for Pipecat bots

Core concepts

  • Session (connect): Connects via moqt:// (QUIC) or https:// (WebTransport), follows GOAWAY, and auto-reconnects for up to 60 s.
  • Namespace & track: A namespace is a list of path segments (e.g. ["anon", "room-1"]). Public demo namespaces start with "anon"; authenticated apps use a JWT whose appId is the first segment.
  • Broadcast (MSF): A namespace carrying a catalog track plus video, audio, or event timeline tracks (create_broadcast / watch_broadcasts).

Install

Requires Python 3.11+ on Linux (x86_64/aarch64, glibc 2.28+) or macOS (Apple silicon):

python -m pip install "moq-wasm==0.0.1" \
  --find-links https://github.com/nttcom/moq-wasm/releases/expanded_assets/python-sdk-v0.0.1

Replace "moq-wasm==0.0.1" with "moq-wasm[codecs]==0.0.1" or "moq-wasm[pipecat]==0.0.1" to include an extra.

Release note: This README tracks master. 0.0.1 runs the Quickstart below; later sections use unreleased APIs (SessionEnded, MoqWasmParticipantInput, empty_timeout, on_room_empty). To install from a repository checkout now (requires a Rust toolchain): python -m pip install "./sdk/python[pipecat]"

Quickstart: Send and receive a message

Save as hello.py and run python hello.py. It connects two sessions to the public demo relay on a fresh namespace and prints hello (subscribe before writing because live subscriptions receive objects published afterwards):

import asyncio
from uuid import uuid4

from moq_wasm import connect

RELAY = "https://relay-1.moqt.research.skyway.io:443"


async def main():
    namespace = ["anon", uuid4().hex]
    async with connect(RELAY) as publisher, connect(RELAY) as subscriber:
        writer = await publisher.publish_track(namespace, "messages")
        await publisher.announce(namespace)
        messages = await subscriber.subscribe(namespace, "messages")
        await writer.write(b"hello", new_group=True)
        print((await anext(messages)).payload.decode())


asyncio.run(main())

Keep a service connected

A session automatically replaces a dropped connection for up to 60 s, restoring its subscriptions and published tracks. If reconnection fails or the token expires, the session ends: session.run(...) cancels its workload and raises a moq_wasm.SessionEnded subclass:

Exception Cause
ConnectionLost Connection could not be restored (including token expiry without refresh_token); see close_info
TokenExpired refresh_token kept failing until the token expired
SessionClosed close() was called

Rejected MoQT requests raise moq_wasm.RequestError (a RuntimeError with message_type, code, and reason); initial connection failures raise RuntimeError.

For a long-running service, wrap connect(...) in a reconnect loop and run concurrent workers inside an asyncio.TaskGroup. Catching except* Exception retries transient worker and token-endpoint failures (such as TimeoutError), while KeyboardInterrupt and cancellation — which are not Exception — still stop the service:

import asyncio
import logging

import moq_wasm


async def publish(session: moq_wasm.Session) -> None:
    ...


async def follow(session: moq_wasm.Session) -> None:
    ...


async def serve(session: moq_wasm.Session) -> None:
    # TaskGroup ensures session.run waits for every worker's cleanup (unlike asyncio.gather).
    async with asyncio.TaskGroup() as workers:
        workers.create_task(publish(session))
        workers.create_task(follow(session))


async def fetch_token(current: str | None = None) -> str:
    ...  # fetch a JWT for your app (`current` is the expiring token)


async def main():
    moq_wasm.init(log_level="info")  # forward native logs to Python's `logging`
    while True:
        try:
            token = await asyncio.wait_for(fetch_token(), 30)
            async with moq_wasm.connect(RELAY, token=token, refresh_token=fetch_token) as session:
                await session.run(serve(session))
            return
        except* Exception as errors:
            logging.warning("relay session ended", exc_info=errors)
        await asyncio.sleep(2)

Token refresh runs 5 minutes before exp (or halfway through shorter lifetimes) and retries until expiry. connect reads appId and exp from the JWT without verifying the signature and rejects a refreshed token from a different appId.

Build a Pipecat voice bot

With moq-wasm[pipecat], MoqWasmTransport joins a room where every direct child namespace under room is a participant, and publishes the bot at [*room, participant_id] (playable from browsers via the JS SDK):

import moq_wasm
from moq_wasm.pipecat import MoqWasmParams, MoqWasmTransport
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker, ProcessorUnusablePolicy
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair, LLMUserAggregatorParams
from pipecat.workers.runner import WorkerRunner


def make_services():
    ...  # create fresh STT, LLM, and TTS services per session


async def talk(session: moq_wasm.Session, room: list[str]) -> None:
    stt, llm, tts = make_services()
    transport = MoqWasmTransport(
        session,
        MoqWasmParams(
            room=room,
            participant_id="bot",
            audio_in_enabled=True,
            audio_out_enabled=True,
            empty_timeout=30,
        ),
    )
    runner = WorkerRunner(handle_sigint=False)

    @transport.event_handler("on_room_empty")
    async def on_room_empty(transport):
        await runner.cancel()

    # Converts STT transcriptions into LLM context frames.
    context = LLMContextAggregatorPair(
        LLMContext(), user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer())
    )
    pipeline = Pipeline(
        [transport.input(), stt, context.user(), llm, tts, transport.output(), context.assistant()]
    )
    worker = PipelineWorker(
        pipeline,
        # Exit via `on_room_empty` instead of Pipecat's 5-minute idle timeout.
        idle_timeout_secs=None,
        # Stop the pipeline if the relay rejects the room.
        processor_unusable_policy=ProcessorUnusablePolicy.CANCEL,
    )
    await runner.add_workers(worker)
    await runner.run()

Notes:

  • Run talk inside the supervisor loop above as session.run(talk(session, [app_id, "my-room"])) (app_id is "anon" without a token).
  • Build fresh services in make_services() on every session (ending a session cancels the pipeline). SileroVADAnalyzer requires pipecat-ai[silero].
  • Participant audio arrives as UserAudioRawFrame tagged with user_id. In multi-speaker rooms where STT cannot separate speakers, run one pipeline per participant with MoqWasmParticipantInput.

Reference & examples

 1"""
 2.. include:: ../../README.md
 3"""
 4
 5from moq_wasm._errors import RequestErrorCode, SessionEnded
 6from moq_wasm._log import init, report_log
 7from moq_wasm._telemetry import TelemetryOptions
 8from moq_wasm._native import (
 9    CloseInfo,
10    Location,
11    Object,
12    PublishDone,
13    RequestError,
14    TransportStats,
15    parse_catalog,
16)
17from moq_wasm._session import (
18    Announcement,
19    ConnectionLost,
20    NamespaceEvent,
21    NamespaceWatch,
22    Session,
23    SessionClosed,
24    TrackWriter,
25    connect,
26)
27from moq_wasm._subscription import Fetch, Group, Subscription
28from moq_wasm._token import TokenExpired
29
30__all__ = [
31    "Announcement",
32    "CloseInfo",
33    "ConnectionLost",
34    "Fetch",
35    "Group",
36    "Location",
37    "NamespaceEvent",
38    "NamespaceWatch",
39    "Object",
40    "PublishDone",
41    "RequestError",
42    "RequestErrorCode",
43    "Session",
44    "SessionClosed",
45    "SessionEnded",
46    "Subscription",
47    "TelemetryOptions",
48    "TokenExpired",
49    "TrackWriter",
50    "TransportStats",
51    "connect",
52    "init",
53    "parse_catalog",
54    "report_log",
55]
class Announcement:
356class Announcement:
357    """A namespace the session publishes until `close()`."""
358
359    def __init__(self, session: "Session", namespace: list[str], *, owns: bool):
360        # Immutable, so a caller changing a list cannot redirect `close()`.
361        self._namespace = tuple(namespace)
362        self._session = session
363        # Whether the withdrawal ends the session's ownership of the namespace, which a broadcast
364        # keeps instead until it was left.
365        self._owns = owns
366        self._closing: Once[None] = Once()
367
368    @property
369    def namespace(self) -> list[str]:
370        """A copy: changing it changes nothing the announcement does."""
371        return list(self._namespace)
372
373    async def close(self) -> None:
374        """PUBLISH_NAMESPACE_DONE; the session stops publishing the namespace. Does nothing once the
375        namespace was withdrawn, even when the session publishes it again since. Every call returns
376        once the PUBLISH_NAMESPACE_DONE was sent, even after one was cancelled."""
377        await self._closing.run(lambda: self._session._unannounce(self))

A namespace the session publishes until close().

Announcement( session: Session, namespace: list[str], *, owns: bool)
359    def __init__(self, session: "Session", namespace: list[str], *, owns: bool):
360        # Immutable, so a caller changing a list cannot redirect `close()`.
361        self._namespace = tuple(namespace)
362        self._session = session
363        # Whether the withdrawal ends the session's ownership of the namespace, which a broadcast
364        # keeps instead until it was left.
365        self._owns = owns
366        self._closing: Once[None] = Once()
namespace: list[str]
368    @property
369    def namespace(self) -> list[str]:
370        """A copy: changing it changes nothing the announcement does."""
371        return list(self._namespace)

A copy: changing it changes nothing the announcement does.

async def close(self) -> None:
373    async def close(self) -> None:
374        """PUBLISH_NAMESPACE_DONE; the session stops publishing the namespace. Does nothing once the
375        namespace was withdrawn, even when the session publishes it again since. Every call returns
376        once the PUBLISH_NAMESPACE_DONE was sent, even after one was cancelled."""
377        await self._closing.run(lambda: self._session._unannounce(self))

PUBLISH_NAMESPACE_DONE; the session stops publishing the namespace. Does nothing once the namespace was withdrawn, even when the session publishes it again since. Every call returns once the PUBLISH_NAMESPACE_DONE was sent, even after one was cancelled.

class CloseInfo:

How the session's last connection closed.

reason
code

The termination code it closed with; None when the connection was lost without one.

class ConnectionLost(moq_wasm.SessionEnded):
31class ConnectionLost(SessionEnded):
32    """Raised by `Session.run`, `Session.closed`, and subsequent requests when the relay connection ended
33    (other than by `close()`) and could not be restored within 60 s, closed with a non-`EXPIRED_AUTH_TOKEN`
34    code, or expired without `refresh_token`."""
35
36    def __init__(self, message: str, close_info: _native.CloseInfo):
37        super().__init__(message)
38        self.close_info = close_info

Raised by Session.run, Session.closed, and subsequent requests when the relay connection ended (other than by close()) and could not be restored within 60 s, closed with a non-EXPIRED_AUTH_TOKEN code, or expired without refresh_token.

ConnectionLost(message: str, close_info: CloseInfo)
36    def __init__(self, message: str, close_info: _native.CloseInfo):
37        super().__init__(message)
38        self.close_info = close_info
close_info
class Fetch(collections.abc.AsyncIterator[moq_wasm.Object]):
202class Fetch(AsyncIterator[_native.Object]):
203    """The objects of one FETCH response that carry a payload, read one at a time as a
204    subscription's objects are."""
205
206    def __init__(self, native: _native.Fetch, session: "Session"):
207        self._objects = _Reads(native, "the fetch", session)
208
209    def __aiter__(self) -> "Fetch":
210        return self
211
212    async def __anext__(self) -> _native.Object:
213        """Raises StopAsyncIteration once the response ends."""
214        return await self._objects.next()

The objects of one FETCH response that carry a payload, read one at a time as a subscription's objects are.

Fetch(native: Fetch, session: Session)
206    def __init__(self, native: _native.Fetch, session: "Session"):
207        self._objects = _Reads(native, "the fetch", session)
class Group(collections.abc.AsyncIterator[moq_wasm.Object]):
184class Group(AsyncIterator[_native.Object]):
185    """One subgroup stream, iterated for its objects until the publisher finishes it, read one at a
186    time as a subscription's objects are."""
187
188    def __init__(self, native: _native.Group, session: "Session"):
189        self.group_id = native.group_id
190        self.subgroup_id = native.subgroup_id
191        self._objects = _Reads(native, f"group {native.group_id}", session)
192
193    def __aiter__(self) -> "Group":
194        return self
195
196    async def __anext__(self) -> _native.Object:
197        """Raises StopAsyncIteration once the publisher finished the stream, and RuntimeError when
198        the stream was reset."""
199        return await self._objects.next()

One subgroup stream, iterated for its objects until the publisher finishes it, read one at a time as a subscription's objects are.

Group(native: Group, session: Session)
188    def __init__(self, native: _native.Group, session: "Session"):
189        self.group_id = native.group_id
190        self.subgroup_id = native.subgroup_id
191        self._objects = _Reads(native, f"group {native.group_id}", session)
group_id
subgroup_id
class Location:

A Location (draft-14 §1.4.1).

group_id
object_id
@dataclass(frozen=True)
class NamespaceEvent:
41@dataclass(frozen=True)
42class NamespaceEvent:
43    namespace: list[str]
44    active: bool
45    """False once the namespace was withdrawn (PUBLISH_NAMESPACE_DONE)."""
NamespaceEvent(namespace: list[str], active: bool)
namespace: list[str]
active: bool

False once the namespace was withdrawn (PUBLISH_NAMESPACE_DONE).

class NamespaceWatch(collections.abc.AsyncIterator[moq_wasm._session.NamespaceEvent]):
 48class NamespaceWatch(AsyncIterator[NamespaceEvent]):
 49    """The namespaces published and withdrawn under a prefix, until `close()` or the session
 50    ends. One read at a time: a read while another waits raises RuntimeError."""
 51
 52    def __init__(self, session: "Session", prefix: list[str], events: _native.NamespaceWatch):
 53        self.prefix = prefix
 54        self._session = session
 55        self._events = events
 56        self._ended = asyncio.Event()
 57        self._next: asyncio.Future | None = None
 58        self._reading = False
 59        self._closing: Once[None] = Once()
 60
 61    def __aiter__(self) -> "NamespaceWatch":
 62        return self
 63
 64    async def __anext__(self) -> NamespaceEvent:
 65        if self._reading:
 66            raise RuntimeError(f"the watch of {self.prefix} is already being read")
 67        self._reading = True
 68        try:
 69            return await self._read()
 70        finally:
 71            self._reading = False
 72
 73    async def _read(self) -> NamespaceEvent:
 74        if self._ended.is_set():
 75            raise StopAsyncIteration
 76        # Kept across a cancelled call, as by a timeout, so the event it brings is not lost.
 77        if self._next is None:
 78            self._next = asyncio.ensure_future(anext(self._events))
 79        ended = asyncio.ensure_future(self._ended.wait())
 80        try:
 81            await wait([self._next, ended], return_when=asyncio.FIRST_COMPLETED)
 82        finally:
 83            ended.cancel()
 84        if self._ended.is_set():
 85            raise StopAsyncIteration
 86        event, self._next = self._next, None
 87        try:
 88            native_event = event.result()
 89        except StopAsyncIteration:
 90            self._ended.set()
 91            raise
 92        return NamespaceEvent(native_event.namespace, native_event.active)
 93
 94    async def close(self) -> None:
 95        """UNSUBSCRIBE_NAMESPACE, so the session may watch the prefix again; ends the iteration.
 96        Every call returns once the UNSUBSCRIBE_NAMESPACE was sent, even after one was cancelled."""
 97        if not self._closing.started:
 98            self._end()
 99            self._session._watches.discard(self)
100        await self._closing.run(self._unsubscribe)
101
102    async def _unsubscribe(self) -> None:
103        if not self._session._done.done():
104            await self._events.close()
105
106    def _end(self) -> None:
107        self._ended.set()
108        if self._next is not None:
109            self._next.cancel()

The namespaces published and withdrawn under a prefix, until close() or the session ends. One read at a time: a read while another waits raises RuntimeError.

NamespaceWatch( session: Session, prefix: list[str], events: NamespaceWatch)
52    def __init__(self, session: "Session", prefix: list[str], events: _native.NamespaceWatch):
53        self.prefix = prefix
54        self._session = session
55        self._events = events
56        self._ended = asyncio.Event()
57        self._next: asyncio.Future | None = None
58        self._reading = False
59        self._closing: Once[None] = Once()
prefix
async def close(self) -> None:
 94    async def close(self) -> None:
 95        """UNSUBSCRIBE_NAMESPACE, so the session may watch the prefix again; ends the iteration.
 96        Every call returns once the UNSUBSCRIBE_NAMESPACE was sent, even after one was cancelled."""
 97        if not self._closing.started:
 98            self._end()
 99            self._session._watches.discard(self)
100        await self._closing.run(self._unsubscribe)

UNSUBSCRIBE_NAMESPACE, so the session may watch the prefix again; ends the iteration. Every call returns once the UNSUBSCRIBE_NAMESPACE was sent, even after one was cancelled.

class Object:
status
object_id
extension_headers

The extension headers as (id, value) pairs in the order they came: an even id carries an integer, an odd one bytes.

payload
timestamp_micros

The LOC Timestamp property in µs (draft-ietf-moq-loc-04 §2.3.1): wall-clock time since the Unix epoch, or media time when a Timescale property comes with it; None without one.

subgroup_id
group_id
class PublishDone:

The PUBLISH_DONE that ended a subscription.

code

The PUBLISH_DONE code as draft-14 numbers it (§13.1.3), also on a draft-18 session.

reason
class RequestError(builtins.RuntimeError):

A request the peer rejected or that failed, with the draft-14 error code of its message.

class RequestErrorCode(enum.IntEnum):
 9class RequestErrorCode(IntEnum):
10    """The draft-14 numbers a `RequestError.code` takes for SUBSCRIBE, FETCH and TRACK_STATUS, as the
11    browser SDK's `RequestErrorCode` names them. SUBSCRIBE_NAMESPACE, PUBLISH_NAMESPACE and PUBLISH
12    give 0x4 and up other meanings."""
13
14    INTERNAL_ERROR = 0x0
15    TIMEOUT = 0x2
16    NOT_SUPPORTED = 0x3
17    TRACK_DOES_NOT_EXIST = 0x4
18    INVALID_RANGE = 0x5
19    NO_OBJECTS = 0x6
20    UNKNOWN_STATUS_IN_RANGE = 0x8

The draft-14 numbers a RequestError.code takes for SUBSCRIBE, FETCH and TRACK_STATUS, as the browser SDK's RequestErrorCode names them. SUBSCRIBE_NAMESPACE, PUBLISH_NAMESPACE and PUBLISH give 0x4 and up other meanings.

INTERNAL_ERROR = <RequestErrorCode.INTERNAL_ERROR: 0>
TIMEOUT = <RequestErrorCode.TIMEOUT: 2>
NOT_SUPPORTED = <RequestErrorCode.NOT_SUPPORTED: 3>
TRACK_DOES_NOT_EXIST = <RequestErrorCode.TRACK_DOES_NOT_EXIST: 4>
INVALID_RANGE = <RequestErrorCode.INVALID_RANGE: 5>
NO_OBJECTS = <RequestErrorCode.NO_OBJECTS: 6>
UNKNOWN_STATUS_IN_RANGE = <RequestErrorCode.UNKNOWN_STATUS_IN_RANGE: 8>
class Session:
380class Session:
381    """A relay session. Its native session follows GOAWAY and replaces a lost connection for up to
382    60 s, carrying its subscriptions, namespaces and namespace subscriptions over
383    (docs/architecture/moqt/session-migration.md); when it cannot, the session ends with
384    `ConnectionLost`."""
385
386    def __init__(self, native: _native.Session, keeper: TokenKeeper | None):
387        self._native = native
388        self._keeper = keeper
389        # The current announcement of each namespace the session publishes.
390        self._published: dict[tuple[str, ...], Announcement] = {}
391        # The owner of each track the session publishes, so no other one of the session publishes
392        # it, and closing one cannot end another's subscriptions.
393        self._tracks: dict[tuple[tuple[str, ...], str], object] = {}
394        # How the native origin keeps each track the session registered, as of its first
395        # registration, for the session's life.
396        self._registrations: dict[tuple[tuple[str, ...], str], _Registration] = {}
397        # The namespaces an announcement or a broadcast of the session owns, from its start until
398        # it finished withdrawing them, so no other one of the session publishes them meanwhile.
399        self._owned: set[tuple[str, ...]] = set()
400        self._watches: set[NamespaceWatch] = set()
401        # What `_end` calls with what ended the session: each ends a handle of the session.
402        self._enders: set[Callable[[BaseException], None]] = set()
403        # What `_end` calls with each handle that no part of the session owns yet, as one declared
404        # on a broadcast before it was entered, and with what ended the session: kept only while
405        # something else holds the handle, so a broadcast never entered is not kept alive.
406        self._held_enders: weakref.WeakKeyDictionary[Any, Callable[[Any, BaseException], None]] = (
407            weakref.WeakKeyDictionary()
408        )
409        # The tasks releasing what a request whose caller was cancelled acquired, with the key of
410        # what they release.
411        self._releases: dict[asyncio.Task, Hashable] = {}
412        self._done: asyncio.Future[None] = asyncio.get_running_loop().create_future()
413        self._closing: Once[None] = Once()
414        # The session's own tasks the shutdown waits for.
415        self._joined: list[asyncio.Task] = []
416        self._tasks = [asyncio.create_task(self._watch_connection())]
417        if keeper is not None:
418            self._tasks.append(asyncio.create_task(self._keep_token_fresh(keeper)))
419
420    async def subscribe(
421        self,
422        namespace: list[str],
423        name: str,
424        *,
425        filter: Literal["largest_object", "next_group_start"] = "largest_object",
426        forward: bool = True,
427        priority: int | None = None,
428        delivery_timeout: float | None = None,
429        group_order: Literal["ascending", "descending"] = "ascending",
430    ) -> Subscription:
431        """SUBSCRIBE (`_native.Session.subscribe`): by default only the objects published after
432        it. Cancelled before it returns, it unsubscribes once the relay answered."""
433        namespace = list(namespace)
434        return await self._subscription(
435            namespace,
436            name,
437            lambda native: native.subscribe(
438                namespace,
439                name,
440                filter=filter,
441                forward=forward,
442                priority=priority,
443                delivery_timeout=delivery_timeout,
444                group_order=group_order,
445            ),
446        )
447
448    async def subscribe_group_start(
449        self,
450        namespace: list[str],
451        name: str,
452        new_group_after: int,
453        *,
454        priority: int | None = None,
455        delivery_timeout: float | None = None,
456        group_order: Literal["ascending", "descending"] = "ascending",
457    ) -> Subscription:
458        """Subscribes from the first object of a group (`_native.Session.subscribe_group_start`);
459        cancelled as `subscribe`. It is read by object only."""
460        namespace = list(namespace)
461        return await self._subscription(
462            namespace,
463            name,
464            lambda native: native.subscribe_group_start(
465                namespace,
466                name,
467                new_group_after,
468                priority=priority,
469                delivery_timeout=delivery_timeout,
470                group_order=group_order,
471            ),
472            joining=True,
473        )
474
475    async def fetch(
476        self, namespace: list[str], name: str, start: _native.Location, end: _native.Location
477    ) -> Fetch:
478        """A Standalone FETCH (`_native.Session.fetch`)."""
479        return Fetch(await self._connected().fetch(namespace, name, start, end), self)
480
481    async def track_status(self, namespace: list[str], name: str) -> _native.Location | None:
482        """TRACK_STATUS (`_native.Session.track_status`)."""
483        return await self._connected().track_status(namespace, name)
484
485    async def subscribe_current_group(
486        self,
487        namespace: list[str],
488        name: str,
489        *,
490        priority: int | None = None,
491        delivery_timeout: float | None = None,
492        group_order: Literal["ascending", "descending"] = "ascending",
493    ) -> Subscription:
494        """The objects of the group the relay holds come first (a joining FETCH), then the live
495        ones (`_native.Session.subscribe_current_group`); cancelled as `subscribe`. It is read by
496        object only."""
497        namespace = list(namespace)
498        return await self._subscription(
499            namespace,
500            name,
501            lambda native: native.subscribe_current_group(
502                namespace,
503                name,
504                priority=priority,
505                delivery_timeout=delivery_timeout,
506                group_order=group_order,
507            ),
508            joining=True,
509        )
510
511    async def _subscription(
512        self,
513        namespace: list[str],
514        name: str,
515        request: Callable[[_native.Session], Awaitable[_native.Subscription]],
516        *,
517        joining: bool = False,
518    ) -> Subscription:
519        """`joining` for a subscription whose native reader merges a joining FETCH into its
520        objects, which is read by object from the start."""
521        native = await self._acquire(
522            _subscription_key(namespace, name),
523            lambda: request(self._connected()),
524            lambda subscription: subscription.close(),
525        )
526        return Subscription(native, self, read_by="object" if joining else None)
527
528    async def watch_namespaces(self, prefix: list[str]) -> NamespaceWatch:
529        """Raises `RequestError` when the relay refuses the SUBSCRIBE_NAMESPACE. Cancelled before
530        it returns, it unsubscribes once the relay answered, and a later watch of the prefix waits
531        for that."""
532        prefix = list(prefix)
533        native = await self._acquire(
534            ("prefix", tuple(prefix)),
535            lambda: self._connected().watch_namespaces(prefix),
536            lambda events: events.close(),
537        )
538        watch = NamespaceWatch(self, prefix, native)
539        self._watches.add(watch)
540        return watch
541
542    async def announce(self, namespace: list[str]) -> Announcement:
543        """PUBLISH_NAMESPACE. Raises `RequestError` when the relay refuses it, and RuntimeError while
544        another announcement or broadcast of the session publishes the namespace, until it finished
545        withdrawing it. Cancelled before it returns, it withdraws the namespace once the relay
546        answered, and a later announcement of the namespace waits for that."""
547        namespace = list(namespace)
548        self._raise_if_ended()
549        self._own(namespace)
550        try:
551            return await self._announce(namespace, lambda native: native.announce(namespace), owns=True)
552        except BaseException:
553            self._disown(namespace)
554            raise
555
556    def _own(self, namespace: list[str]) -> None:
557        """Raises RuntimeError while another announcement or broadcast of the session owns
558        `namespace`."""
559        key = tuple(namespace)
560        if key in self._owned:
561            raise RuntimeError(f"the session already publishes {namespace}")
562        self._owned.add(key)
563
564    def _disown(self, namespace: list[str]) -> None:
565        self._owned.discard(tuple(namespace))
566
567    async def _announce(
568        self, namespace: list[str], request: Callable[[_native.Session], Awaitable[None]], *, owns: bool
569    ) -> Announcement:
570        withdrawn = list(namespace)
571        await self._acquire(
572            _namespace_key(namespace),
573            lambda: request(self._connected()),
574            lambda _: self._native.unannounce(withdrawn),
575        )
576        return self._announced(namespace, owns=owns)
577
578    async def _acquire(
579        self, key: Hashable, request: Callable[[], Awaitable[T]], release: Callable[[T], Awaitable[None]]
580    ) -> T:
581        """`request()`, a native request whose success leaves something active on the relay, once
582        what an earlier request of `key` left was released. A caller cancelled before it takes the
583        result leaves the request running, and `release` undoes what it acquired, so nothing stays
584        active without an owner."""
585        await self._released(key)
586        acquiring = asyncio.ensure_future(request())
587        # Its failure goes to the caller, and to nobody once the caller and its release are gone.
588        acquiring.add_done_callback(retrieve)
589        try:
590            await asyncio.wait([acquiring])
591        except asyncio.CancelledError:
592            self._release_later(key, self._release(acquiring, release))
593            raise
594        return acquiring.result()
595
596    def _release_later(self, key: Hashable, releasing: Coroutine[Any, Any, None]) -> None:
597        """Runs `releasing`, which undoes what the session acquired for `key` and no caller owns;
598        a later request of `key` waits for it."""
599        task = asyncio.create_task(releasing)
600        self._releases[task] = key
601        task.add_done_callback(self._releases.pop)
602
603    async def _release(self, acquiring: asyncio.Future[T], release: Callable[[T], Awaitable[None]]) -> None:
604        await asyncio.wait([acquiring])
605        # The native session's close ends what it acquired.
606        if acquiring.cancelled() or acquiring.exception() is not None or self._done.done():
607            return
608        try:
609            await release(acquiring.result())
610        except Exception as error:
611            logger.debug("releasing what a cancelled request acquired failed: %r", error)
612
613    async def _released(self, key: Hashable) -> None:
614        """Waits until what the cancelled requests of `key` acquired was released."""
615        if releasing := self._releasing(key):
616            await asyncio.wait(releasing)
617
618    def _unsubscribing(self, namespace: list[str], name: str) -> set[asyncio.Task]:
619        """The tasks unsubscribing what the cancelled subscriptions to the track acquired, once the
620        relay answered them."""
621        return self._releasing(_subscription_key(namespace, name))
622
623    def _releasing(self, key: Hashable) -> set[asyncio.Task]:
624        """The tasks releasing what the cancelled requests of `key` acquired."""
625        return {task for task, released in self._releases.items() if released == key}
626
627    async def publish_track(
628        self,
629        namespace: list[str],
630        name: str,
631        *,
632        retention_seconds: float = DEFAULT_RETENTION_SECONDS,
633        publish: bool = False,
634        datagram: bool = False,
635        priority: int = DEFAULT_PRIORITY,
636    ) -> TrackWriter:
637        """Register a track to serve `SUBSCRIBE` and `FETCH` (`_native.Session.publish_track`).
638
639        Register before `announce()` when `publish=False`; announce first when `publish=True`.
640        `priority` is Publisher Priority (0–255; lower goes first).
641        If cancelled mid-call, the track is ended once registered before any later caller can claim it.
642
643        Raises:
644            SessionEnded: session already ended.
645            RuntimeError: another writer owns the track.
646            ValueError: invalid `retention_seconds` (nothing is registered), or `retention_seconds`/`datagram`
647                conflicts with a prior registration (media broadcasts use `0` for `catalog`, `60` s for other tracks).
648            OverflowError: `priority` outside 0–255.
649        """
650        self._raise_if_ended()
651        await self._released(_published_track_key(tuple(namespace), name))
652        self._raise_if_ended()
653        writer = self._track_writer(
654            namespace, name, retention_seconds, publish=publish, datagram=datagram, priority=priority
655        )
656        await self._register(writer)
657        return writer
658
659    def _track_writer(
660        self,
661        namespace: list[str],
662        name: str,
663        retention_seconds: float,
664        *,
665        publish: bool,
666        datagram: bool,
667        priority: int,
668    ) -> TrackWriter:
669        """Raises RuntimeError while another writer of the session publishes the track."""
670        writer = TrackWriter(
671            self, namespace, name, retention_seconds, publish=publish, datagram=datagram, priority=priority
672        )
673        self._claim_tracks(writer._namespace, {name: writer})
674        writer._end_with_session()
675        return writer
676
677    def _claim_tracks(self, namespace: tuple[str, ...], owners: dict[str, object]) -> None:
678        """Makes each owner the one of its track. Raises RuntimeError, claiming none of them, while
679        another owner of the session publishes one of the tracks."""
680        for name in owners:
681            if (namespace, name) in self._tracks:
682                raise RuntimeError(f"the session already publishes track {name} of {list(namespace)}")
683        for name, owner in owners.items():
684            self._tracks[(namespace, name)] = owner
685
686    def _release_tracks(self, namespace: tuple[str, ...], owners: dict[str, object]) -> None:
687        """Releases the tracks each owner still owns."""
688        for name, owner in owners.items():
689            if self._tracks.get((namespace, name)) is owner:
690                del self._tracks[(namespace, name)]
691
692    def _release_track(self, writer: TrackWriter) -> None:
693        """Releases the writer's track once what a cancelled registration of it acquired was
694        released: until then that cleanup may still end the track, which would end the
695        subscriptions of another owner of it."""
696        releasing = self._releasing(_published_track_key(writer._namespace, writer._name))
697        if not releasing:
698            self._release_tracks(writer._namespace, {writer._name: writer})
699            return
700
701        def released(task: asyncio.Task) -> None:
702            releasing.discard(task)
703            if not releasing:
704                self._release_tracks(writer._namespace, {writer._name: writer})
705
706        for task in list(releasing):
707            task.add_done_callback(released)
708
709    async def _register(self, writer: TrackWriter) -> None:
710        if writer._closed:
711            # Closing it released the track, which another writer may publish by now.
712            return
713        writer._not_registering.clear()
714        namespace = list(writer.namespace)
715        try:
716            # Cancelled, it ends the track once registered, before another writer registers it.
717            native = await self._acquire(
718                _published_track_key(writer._namespace, writer.name),
719                lambda: self._publish_track(writer),
720                lambda _: self._native.end_track(namespace, writer.name),
721            )
722        except BaseException as error:
723            # A cancellation is the cancelled caller's, not the track's: the writer's other callers
724            # raise that it was not registered.
725            writer._abandon(error if isinstance(error, Exception) else None)
726            self._release_track(writer)
727            raise
728        finally:
729            writer._not_registering.set()
730        await writer._bind(native)
731
732    async def _publish_track(self, writer: TrackWriter) -> _native.TrackWriter:
733        """`_native.Session.publish_track` for `writer`. Raises ValueError, before any native call,
734        when the writer asks for a retention other than the one the track was registered with first
735        in the session, which the native origin keeps; the native call raises ValueError for the
736        other delivery than the one the track sent its objects with. The registration is recorded
737        once the native origin registered the track: when it succeeded, and when only its PUBLISH
738        was refused, but not when the native call refused its arguments, as an invalid
739        `retention_seconds` or the other delivery, before registering anything."""
740        native = self._connected()
741        key = (writer._namespace, writer.name)
742        established = self._registrations.get(key)
743        if established is not None:
744            established.refuse_other_retention(writer)
745        registering = native.publish_track(
746            list(writer.namespace),
747            writer.name,
748            retention_seconds=writer.retention_seconds,
749            publish=writer.publish,
750            datagram=writer.datagram,
751            priority=writer.priority,
752        )
753        # The native origin takes the delivery of each registration, and keeps the retention of
754        # the first one.
755        registration = _Registration(writer.datagram, writer.retention_seconds)
756        try:
757            registered = await registering
758        except _native.RequestError:
759            # The relay refused the PUBLISH, which follows the track's registration.
760            self._registrations[key] = registration
761            raise
762        self._registrations[key] = registration
763        return registered
764
765    def _record_media_tracks(self, namespace: tuple[str, ...], retentions: dict[str, float]) -> None:
766        """Records the tracks of a media broadcast, which the native media broadcast may register
767        at any time from now on, on subgroup streams, each with the retention it gives it."""
768        for name, retention_seconds in retentions.items():
769            self._registrations.setdefault((namespace, name), _Registration(False, retention_seconds))
770
771    def _refuse_other_registrations(self, namespace: tuple[str, ...], retentions: dict[str, float]) -> None:
772        """Raises ValueError when the session registered one of a media broadcast's tracks, each
773        with the retention `retentions` gives it, in datagrams or with another retention, which the
774        native origin keeps: a media broadcast would send that track in datagrams too, which its
775        subscribers cannot read by group, or keep another span of its objects for late
776        subscribers."""
777        for name, retention_seconds in retentions.items():
778            registration = self._registrations.get((namespace, name))
779            if registration is None:
780                continue
781            if registration.datagram:
782                raise ValueError(
783                    f"track {name} of {list(namespace)} sends its objects in datagrams, which a media "
784                    "broadcast's track cannot: give the media track another name"
785                )
786            if registration.retention_seconds != retention_seconds:
787                raise ValueError(
788                    f"track {name} of {list(namespace)} keeps its objects for {registration.retention_seconds} s, "
789                    f"a media broadcast's for {retention_seconds} s: give the media track another name"
790                )
791
792    def _announced(self, namespace: list[str], *, owns: bool) -> Announcement:
793        announcement = Announcement(self, namespace, owns=owns)
794        self._published[tuple(namespace)] = announcement
795        return announcement
796
797    async def _unannounce(self, announcement: Announcement) -> None:
798        key = announcement._namespace
799        if self._published.get(key) is not announcement:
800            return
801        del self._published[key]
802        try:
803            if not self._done.done():
804                await self._native.unannounce(announcement.namespace)
805        finally:
806            if announcement._owns:
807                self._disown(announcement.namespace)
808
809    def _publishes(self, namespace: list[str]) -> bool:
810        """Whether the session publishes `namespace`, is publishing it or is still withdrawing it,
811        as the relay may forward the namespace before it answered the PUBLISH_NAMESPACE."""
812        key = tuple(namespace)
813        return (
814            key in self._owned
815            or key in self._published
816            or _namespace_key(namespace) in self._releases.values()
817        )
818
819    async def run(self, work: Awaitable[T]) -> T:
820        """Await `work`, cancelling it and waiting for its cleanup if the session ends or this call is cancelled.
821
822        Raises the session-ending error (`ConnectionLost`, `TokenExpired`, or `SessionClosed`).
823        If the session already ended, an unstarted coroutine is closed immediately, while an already-scheduled
824        task or future is cancelled and awaited through cleanup before raising.
825        For multiple concurrent tasks, run them inside an `asyncio.TaskGroup` so cleanup waits for every task.
826        """
827        if self._done.done():
828            if asyncio.iscoroutine(work):
829                work.close()
830            elif asyncio.isfuture(work):
831                await _cancel_work(work)
832            self._raise_if_ended()
833        running = asyncio.ensure_future(work)
834        try:
835            await wait([running, self._done], return_when=asyncio.FIRST_COMPLETED)
836            # A failure also ends the watches, so `work` may have returned because of it.
837            if self._done.done() and (failure := self._done.exception()) is not None:
838                raise failure
839            if running.done():
840                return running.result()
841            raise SessionClosed("the session was closed")
842        finally:
843            await _cancel_work(running)
844
845    async def closed(self) -> None:
846        """Waits until the session ends: `close()`, or a failure, which this raises."""
847        await asyncio.shield(self._done)
848
849    def transport_stats(self) -> _native.TransportStats:
850        return self._native.transport_stats()
851
852    async def close(self) -> None:
853        await self._end(None)
854
855    def _connected(self) -> _native.Session:
856        """The native session; raises what ended the session once it ended, which is no
857        RuntimeError, so a loop that retries a refused request stops."""
858        self._raise_if_ended()
859        return self._native
860
861    def _raise_if_ended(self) -> None:
862        if self._done.done():
863            raise copied(self._ended_with())
864
865    def _ended_with(self) -> BaseException:
866        """What ended the session, once it ended."""
867        return self._done.exception() or SessionClosed("the session was closed")
868
869    def _on_end(self, ender: Callable[[BaseException], None]) -> None:
870        """Calls `ender` with what ended the session once it ends, or at once when it ended."""
871        if self._done.done():
872            ender(self._ended_with())
873        else:
874            self._enders.add(ender)
875
876    def _forget_end(self, ender: Callable[[BaseException], None]) -> None:
877        self._enders.discard(ender)
878
879    def _on_end_while_held(self, handle: H, ender: Callable[[H, BaseException], None]) -> None:
880        """Calls `ender(handle, ...)` with what ended the session once it ends, or at once when it
881        ended, unless nothing but the session holds `handle` by then."""
882        if self._done.done():
883            ender(handle, self._ended_with())
884        else:
885            self._held_enders[handle] = ender
886
887    def _forget_end_while_held(self, handle: object) -> None:
888        self._held_enders.pop(handle, None)
889
890    async def _watch_connection(self) -> None:
891        close_info = await self._native.closed()
892        await self._end(ConnectionLost("the relay connection was lost", close_info))
893
894    async def _keep_token_fresh(self, keeper: TokenKeeper) -> None:
895        try:
896            await keeper.keep_fresh(self._hand_over_token)
897        except Exception as error:
898            # `_end` cancels the other tasks, not this one.
899            await self._end(error)
900
901    async def _hand_over_token(self, token: str) -> None:
902        """Raises RuntimeError when the relay refuses the token, which the keeper retries. The
903        native session presents the token on its next connection all the same, until a later one
904        the relay accepts replaces it."""
905        assert self._keeper is not None
906        await self._native.refresh_token(token, app_id=self._keeper.app_id)
907
908    async def _end(self, failure: BaseException | None) -> None:
909        """Ends the session once, with `failure` or as closed, and waits until the session's own
910        tasks finished, other than the one ending it, and the native session closed; a caller
911        cancelled meanwhile leaves the close running for the next one to await. A task the shutdown
912        waits for, such as a `refresh_token` call that calls `close()` from its cleanup, returns at
913        once instead."""
914        current = asyncio.current_task()
915        if self._closing.started and self._waited_by_shutdown(current):
916            return
917        if not self._closing.started:
918            if failure is None:
919                self._done.set_result(None)
920            else:
921                self._done.set_exception(failure)
922                # Retrieved by `closed()` or `run()`; a session nobody awaits does not warn.
923                self._done.exception()
924            others = [task for task in self._tasks if task is not current]
925            self._joined = others
926            for task in others:
927                task.cancel()
928            for watch in self._watches:
929                watch._end()
930            ended_with = self._ended_with()
931            for ender in list(self._enders):
932                ender(ended_with)
933            self._enders.clear()
934            for handle, held_ender in list(self._held_enders.items()):
935                held_ender(handle, ended_with)
936            self._held_enders.clear()
937        await self._closing.run(lambda: self._shut_down(current))
938
939    def _waited_by_shutdown(self, task: asyncio.Task | None) -> bool:
940        return task in self._joined or (self._keeper is not None and self._keeper.runs(task))
941
942    async def _shut_down(self, ending: asyncio.Task | None) -> None:
943        """Waits for the session's own tasks other than `ending`, the one that ended the session,
944        then closes the native session."""
945        # A cancelled task may still run cleanup.
946        await asyncio.gather(*self._joined, return_exceptions=True)
947        if self._keeper is not None:
948            # The calls of `refresh_token`, one abandoned at its deadline included, clean up too.
949            await self._keeper.stop(sparing=ending)
950        await self._native.close()

A relay session. Its native session follows GOAWAY and replaces a lost connection for up to 60 s, carrying its subscriptions, namespaces and namespace subscriptions over (docs/architecture/moqt/session-migration.md); when it cannot, the session ends with ConnectionLost.

Session(native: Session, keeper: moq_wasm._token.TokenKeeper | None)
386    def __init__(self, native: _native.Session, keeper: TokenKeeper | None):
387        self._native = native
388        self._keeper = keeper
389        # The current announcement of each namespace the session publishes.
390        self._published: dict[tuple[str, ...], Announcement] = {}
391        # The owner of each track the session publishes, so no other one of the session publishes
392        # it, and closing one cannot end another's subscriptions.
393        self._tracks: dict[tuple[tuple[str, ...], str], object] = {}
394        # How the native origin keeps each track the session registered, as of its first
395        # registration, for the session's life.
396        self._registrations: dict[tuple[tuple[str, ...], str], _Registration] = {}
397        # The namespaces an announcement or a broadcast of the session owns, from its start until
398        # it finished withdrawing them, so no other one of the session publishes them meanwhile.
399        self._owned: set[tuple[str, ...]] = set()
400        self._watches: set[NamespaceWatch] = set()
401        # What `_end` calls with what ended the session: each ends a handle of the session.
402        self._enders: set[Callable[[BaseException], None]] = set()
403        # What `_end` calls with each handle that no part of the session owns yet, as one declared
404        # on a broadcast before it was entered, and with what ended the session: kept only while
405        # something else holds the handle, so a broadcast never entered is not kept alive.
406        self._held_enders: weakref.WeakKeyDictionary[Any, Callable[[Any, BaseException], None]] = (
407            weakref.WeakKeyDictionary()
408        )
409        # The tasks releasing what a request whose caller was cancelled acquired, with the key of
410        # what they release.
411        self._releases: dict[asyncio.Task, Hashable] = {}
412        self._done: asyncio.Future[None] = asyncio.get_running_loop().create_future()
413        self._closing: Once[None] = Once()
414        # The session's own tasks the shutdown waits for.
415        self._joined: list[asyncio.Task] = []
416        self._tasks = [asyncio.create_task(self._watch_connection())]
417        if keeper is not None:
418            self._tasks.append(asyncio.create_task(self._keep_token_fresh(keeper)))
async def subscribe( self, namespace: list[str], name: str, *, filter: Literal['largest_object', 'next_group_start'] = 'largest_object', forward: bool = True, priority: int | None = None, delivery_timeout: float | None = None, group_order: Literal['ascending', 'descending'] = 'ascending') -> Subscription:
420    async def subscribe(
421        self,
422        namespace: list[str],
423        name: str,
424        *,
425        filter: Literal["largest_object", "next_group_start"] = "largest_object",
426        forward: bool = True,
427        priority: int | None = None,
428        delivery_timeout: float | None = None,
429        group_order: Literal["ascending", "descending"] = "ascending",
430    ) -> Subscription:
431        """SUBSCRIBE (`_native.Session.subscribe`): by default only the objects published after
432        it. Cancelled before it returns, it unsubscribes once the relay answered."""
433        namespace = list(namespace)
434        return await self._subscription(
435            namespace,
436            name,
437            lambda native: native.subscribe(
438                namespace,
439                name,
440                filter=filter,
441                forward=forward,
442                priority=priority,
443                delivery_timeout=delivery_timeout,
444                group_order=group_order,
445            ),
446        )

SUBSCRIBE (_native.Session.subscribe): by default only the objects published after it. Cancelled before it returns, it unsubscribes once the relay answered.

async def subscribe_group_start( self, namespace: list[str], name: str, new_group_after: int, *, priority: int | None = None, delivery_timeout: float | None = None, group_order: Literal['ascending', 'descending'] = 'ascending') -> Subscription:
448    async def subscribe_group_start(
449        self,
450        namespace: list[str],
451        name: str,
452        new_group_after: int,
453        *,
454        priority: int | None = None,
455        delivery_timeout: float | None = None,
456        group_order: Literal["ascending", "descending"] = "ascending",
457    ) -> Subscription:
458        """Subscribes from the first object of a group (`_native.Session.subscribe_group_start`);
459        cancelled as `subscribe`. It is read by object only."""
460        namespace = list(namespace)
461        return await self._subscription(
462            namespace,
463            name,
464            lambda native: native.subscribe_group_start(
465                namespace,
466                name,
467                new_group_after,
468                priority=priority,
469                delivery_timeout=delivery_timeout,
470                group_order=group_order,
471            ),
472            joining=True,
473        )

Subscribes from the first object of a group (_native.Session.subscribe_group_start); cancelled as subscribe. It is read by object only.

async def fetch( self, namespace: list[str], name: str, start: Location, end: Location) -> Fetch:
475    async def fetch(
476        self, namespace: list[str], name: str, start: _native.Location, end: _native.Location
477    ) -> Fetch:
478        """A Standalone FETCH (`_native.Session.fetch`)."""
479        return Fetch(await self._connected().fetch(namespace, name, start, end), self)

A Standalone FETCH (_native.Session.fetch).

async def track_status(self, namespace: list[str], name: str) -> Location | None:
481    async def track_status(self, namespace: list[str], name: str) -> _native.Location | None:
482        """TRACK_STATUS (`_native.Session.track_status`)."""
483        return await self._connected().track_status(namespace, name)

TRACK_STATUS (_native.Session.track_status).

async def subscribe_current_group( self, namespace: list[str], name: str, *, priority: int | None = None, delivery_timeout: float | None = None, group_order: Literal['ascending', 'descending'] = 'ascending') -> Subscription:
485    async def subscribe_current_group(
486        self,
487        namespace: list[str],
488        name: str,
489        *,
490        priority: int | None = None,
491        delivery_timeout: float | None = None,
492        group_order: Literal["ascending", "descending"] = "ascending",
493    ) -> Subscription:
494        """The objects of the group the relay holds come first (a joining FETCH), then the live
495        ones (`_native.Session.subscribe_current_group`); cancelled as `subscribe`. It is read by
496        object only."""
497        namespace = list(namespace)
498        return await self._subscription(
499            namespace,
500            name,
501            lambda native: native.subscribe_current_group(
502                namespace,
503                name,
504                priority=priority,
505                delivery_timeout=delivery_timeout,
506                group_order=group_order,
507            ),
508            joining=True,
509        )

The objects of the group the relay holds come first (a joining FETCH), then the live ones (_native.Session.subscribe_current_group); cancelled as subscribe. It is read by object only.

async def watch_namespaces(self, prefix: list[str]) -> NamespaceWatch:
528    async def watch_namespaces(self, prefix: list[str]) -> NamespaceWatch:
529        """Raises `RequestError` when the relay refuses the SUBSCRIBE_NAMESPACE. Cancelled before
530        it returns, it unsubscribes once the relay answered, and a later watch of the prefix waits
531        for that."""
532        prefix = list(prefix)
533        native = await self._acquire(
534            ("prefix", tuple(prefix)),
535            lambda: self._connected().watch_namespaces(prefix),
536            lambda events: events.close(),
537        )
538        watch = NamespaceWatch(self, prefix, native)
539        self._watches.add(watch)
540        return watch

Raises RequestError when the relay refuses the SUBSCRIBE_NAMESPACE. Cancelled before it returns, it unsubscribes once the relay answered, and a later watch of the prefix waits for that.

async def announce(self, namespace: list[str]) -> Announcement:
542    async def announce(self, namespace: list[str]) -> Announcement:
543        """PUBLISH_NAMESPACE. Raises `RequestError` when the relay refuses it, and RuntimeError while
544        another announcement or broadcast of the session publishes the namespace, until it finished
545        withdrawing it. Cancelled before it returns, it withdraws the namespace once the relay
546        answered, and a later announcement of the namespace waits for that."""
547        namespace = list(namespace)
548        self._raise_if_ended()
549        self._own(namespace)
550        try:
551            return await self._announce(namespace, lambda native: native.announce(namespace), owns=True)
552        except BaseException:
553            self._disown(namespace)
554            raise

PUBLISH_NAMESPACE. Raises RequestError when the relay refuses it, and RuntimeError while another announcement or broadcast of the session publishes the namespace, until it finished withdrawing it. Cancelled before it returns, it withdraws the namespace once the relay answered, and a later announcement of the namespace waits for that.

async def publish_track( self, namespace: list[str], name: str, *, retention_seconds: float = 60.0, publish: bool = False, datagram: bool = False, priority: int = 128) -> TrackWriter:
627    async def publish_track(
628        self,
629        namespace: list[str],
630        name: str,
631        *,
632        retention_seconds: float = DEFAULT_RETENTION_SECONDS,
633        publish: bool = False,
634        datagram: bool = False,
635        priority: int = DEFAULT_PRIORITY,
636    ) -> TrackWriter:
637        """Register a track to serve `SUBSCRIBE` and `FETCH` (`_native.Session.publish_track`).
638
639        Register before `announce()` when `publish=False`; announce first when `publish=True`.
640        `priority` is Publisher Priority (0–255; lower goes first).
641        If cancelled mid-call, the track is ended once registered before any later caller can claim it.
642
643        Raises:
644            SessionEnded: session already ended.
645            RuntimeError: another writer owns the track.
646            ValueError: invalid `retention_seconds` (nothing is registered), or `retention_seconds`/`datagram`
647                conflicts with a prior registration (media broadcasts use `0` for `catalog`, `60` s for other tracks).
648            OverflowError: `priority` outside 0–255.
649        """
650        self._raise_if_ended()
651        await self._released(_published_track_key(tuple(namespace), name))
652        self._raise_if_ended()
653        writer = self._track_writer(
654            namespace, name, retention_seconds, publish=publish, datagram=datagram, priority=priority
655        )
656        await self._register(writer)
657        return writer

Register a track to serve SUBSCRIBE and FETCH (_native.Session.publish_track).

Register before announce() when publish=False; announce first when publish=True. priority is Publisher Priority (0–255; lower goes first). If cancelled mid-call, the track is ended once registered before any later caller can claim it.

Raises: SessionEnded: session already ended. RuntimeError: another writer owns the track. ValueError: invalid retention_seconds (nothing is registered), or retention_seconds/datagram conflicts with a prior registration (media broadcasts use 0 for catalog, 60 s for other tracks). OverflowError: priority outside 0–255.

async def run(self, work: Awaitable[~T]) -> ~T:
819    async def run(self, work: Awaitable[T]) -> T:
820        """Await `work`, cancelling it and waiting for its cleanup if the session ends or this call is cancelled.
821
822        Raises the session-ending error (`ConnectionLost`, `TokenExpired`, or `SessionClosed`).
823        If the session already ended, an unstarted coroutine is closed immediately, while an already-scheduled
824        task or future is cancelled and awaited through cleanup before raising.
825        For multiple concurrent tasks, run them inside an `asyncio.TaskGroup` so cleanup waits for every task.
826        """
827        if self._done.done():
828            if asyncio.iscoroutine(work):
829                work.close()
830            elif asyncio.isfuture(work):
831                await _cancel_work(work)
832            self._raise_if_ended()
833        running = asyncio.ensure_future(work)
834        try:
835            await wait([running, self._done], return_when=asyncio.FIRST_COMPLETED)
836            # A failure also ends the watches, so `work` may have returned because of it.
837            if self._done.done() and (failure := self._done.exception()) is not None:
838                raise failure
839            if running.done():
840                return running.result()
841            raise SessionClosed("the session was closed")
842        finally:
843            await _cancel_work(running)

Await work, cancelling it and waiting for its cleanup if the session ends or this call is cancelled.

Raises the session-ending error (ConnectionLost, TokenExpired, or SessionClosed). If the session already ended, an unstarted coroutine is closed immediately, while an already-scheduled task or future is cancelled and awaited through cleanup before raising. For multiple concurrent tasks, run them inside an asyncio.TaskGroup so cleanup waits for every task.

async def closed(self) -> None:
845    async def closed(self) -> None:
846        """Waits until the session ends: `close()`, or a failure, which this raises."""
847        await asyncio.shield(self._done)

Waits until the session ends: close(), or a failure, which this raises.

def transport_stats(self) -> TransportStats:
849    def transport_stats(self) -> _native.TransportStats:
850        return self._native.transport_stats()
async def close(self) -> None:
852    async def close(self) -> None:
853        await self._end(None)
class SessionClosed(moq_wasm.SessionEnded):
27class SessionClosed(SessionEnded):
28    """Raised by `Session.run` and subsequent requests after `close()` was called."""

Raised by Session.run and subsequent requests after close() was called.

class SessionEnded(builtins.Exception):
5class SessionEnded(Exception):
6    """The base of what ends a session: `SessionClosed`, `ConnectionLost` and `TokenExpired`."""

The base of what ends a session: SessionClosed, ConnectionLost and TokenExpired.

class Subscription(collections.abc.AsyncIterator[moq_wasm.Object]):
 90class Subscription(AsyncIterator[_native.Object]):
 91    """A subscription (`_native.Subscription`), iterated for its objects until the publisher ends
 92    it. One read at a time: a read while another waits raises RuntimeError. A read cancelled once
 93    an object arrived leaves the object to the next read, unless the session ended. It is read
 94    either by object or by group (`groups()`), whichever is read first; reading the other raises
 95    RuntimeError at once. One that starts with a joining FETCH is read by object only. Its reads,
 96    and those of its groups, raise what ended the session once it ended, such as
 97    `SessionClosed`, a waiting one included."""
 98
 99    def __init__(self, native: _native.Subscription, session: "Session", *, read_by: str | None = None):
100        """`read_by` is the unit the native subscription is already read by, as "object" for one
101        that merges a joining FETCH into its objects."""
102        self._native = native
103        self._session = session
104        self._objects = _Reads(native, "the subscription", session)
105        self._groups: Groups | None = None
106        # "object" or "group", as the first read or the native subscription made it.
107        self._read_by = read_by
108        self._closing: Once[None] = Once()
109
110    def __aiter__(self) -> "Subscription":
111        return self
112
113    async def __anext__(self) -> _native.Object:
114        """Raises StopAsyncIteration once the publisher ends the track. A group whose stream fails
115        (reset by a publisher that left, or cut by a GOAWAY's cutover) ends early."""
116        self._read_as("object")
117        return await self._objects.next()
118
119    def _read_as(self, unit: str) -> None:
120        """Raises RuntimeError once the subscription was read by another unit, before the native
121        read, which would raise it only once something arrived."""
122        if self._read_by is None:
123            self._read_by = unit
124        elif self._read_by != unit:
125            raise RuntimeError(f"the subscription is read by {self._read_by}")
126
127    @property
128    def largest(self) -> _native.Location | None:
129        """The largest location SUBSCRIBE_OK reported."""
130        return self._native.largest
131
132    def done(self) -> asyncio.Future[_native.PublishDone | None]:
133        """`_native.Subscription.done`."""
134        return self._native.done()
135
136    def groups(self) -> "Groups":
137        """The subgroup streams (`_native.Subscription.groups`), read as the objects are. Every
138        call returns the same iterator, so a group a cancelled read took goes to the next read
139        through any of them."""
140        if self._groups is None:
141            self._groups = Groups(self._native.groups(), self)
142        return self._groups
143
144    def set_forward(self, forward: bool) -> asyncio.Future[None]:
145        """`_native.Subscription.set_forward`."""
146        return self._native.set_forward(forward)
147
148    def set_priority(self, priority: int) -> asyncio.Future[None]:
149        """`_native.Subscription.set_priority`."""
150        return self._native.set_priority(priority)
151
152    def request_new_group(self, largest_group: int | None = None) -> asyncio.Future[bool]:
153        """`_native.Subscription.request_new_group`."""
154        return self._native.request_new_group(largest_group)
155
156    def end_before_group(self, group_id: int) -> asyncio.Future[None]:
157        """`_native.Subscription.end_before_group`."""
158        return self._native.end_before_group(group_id)
159
160    def close(self) -> asyncio.Future[None]:
161        """UNSUBSCRIBE, sent at once, as `_native.Subscription.close` is; the iteration ends once
162        the relay stops the track. Every call returns a future of its own that resolves once the
163        UNSUBSCRIBE was sent, even after another was cancelled, and raises what failed it;
164        cancelling it leaves the UNSUBSCRIBE going."""
165        return self._closing.start(self._native.close)

A subscription (_native.Subscription), iterated for its objects until the publisher ends it. One read at a time: a read while another waits raises RuntimeError. A read cancelled once an object arrived leaves the object to the next read, unless the session ended. It is read either by object or by group (groups()), whichever is read first; reading the other raises RuntimeError at once. One that starts with a joining FETCH is read by object only. Its reads, and those of its groups, raise what ended the session once it ended, such as SessionClosed, a waiting one included.

Subscription( native: Subscription, session: Session, *, read_by: str | None = None)
 99    def __init__(self, native: _native.Subscription, session: "Session", *, read_by: str | None = None):
100        """`read_by` is the unit the native subscription is already read by, as "object" for one
101        that merges a joining FETCH into its objects."""
102        self._native = native
103        self._session = session
104        self._objects = _Reads(native, "the subscription", session)
105        self._groups: Groups | None = None
106        # "object" or "group", as the first read or the native subscription made it.
107        self._read_by = read_by
108        self._closing: Once[None] = Once()

read_by is the unit the native subscription is already read by, as "object" for one that merges a joining FETCH into its objects.

largest: Location | None
127    @property
128    def largest(self) -> _native.Location | None:
129        """The largest location SUBSCRIBE_OK reported."""
130        return self._native.largest

The largest location SUBSCRIBE_OK reported.

def done(self) -> _asyncio.Future[PublishDone | None]:
132    def done(self) -> asyncio.Future[_native.PublishDone | None]:
133        """`_native.Subscription.done`."""
134        return self._native.done()

_native.Subscription.done.

def groups(self) -> moq_wasm._subscription.Groups:
136    def groups(self) -> "Groups":
137        """The subgroup streams (`_native.Subscription.groups`), read as the objects are. Every
138        call returns the same iterator, so a group a cancelled read took goes to the next read
139        through any of them."""
140        if self._groups is None:
141            self._groups = Groups(self._native.groups(), self)
142        return self._groups

The subgroup streams (_native.Subscription.groups), read as the objects are. Every call returns the same iterator, so a group a cancelled read took goes to the next read through any of them.

def set_forward(self, forward: bool) -> _asyncio.Future[None]:
144    def set_forward(self, forward: bool) -> asyncio.Future[None]:
145        """`_native.Subscription.set_forward`."""
146        return self._native.set_forward(forward)

_native.Subscription.set_forward.

def set_priority(self, priority: int) -> _asyncio.Future[None]:
148    def set_priority(self, priority: int) -> asyncio.Future[None]:
149        """`_native.Subscription.set_priority`."""
150        return self._native.set_priority(priority)

_native.Subscription.set_priority.

def request_new_group(self, largest_group: int | None = None) -> _asyncio.Future[bool]:
152    def request_new_group(self, largest_group: int | None = None) -> asyncio.Future[bool]:
153        """`_native.Subscription.request_new_group`."""
154        return self._native.request_new_group(largest_group)

_native.Subscription.request_new_group.

def end_before_group(self, group_id: int) -> _asyncio.Future[None]:
156    def end_before_group(self, group_id: int) -> asyncio.Future[None]:
157        """`_native.Subscription.end_before_group`."""
158        return self._native.end_before_group(group_id)

_native.Subscription.end_before_group.

def close(self) -> _asyncio.Future[None]:
160    def close(self) -> asyncio.Future[None]:
161        """UNSUBSCRIBE, sent at once, as `_native.Subscription.close` is; the iteration ends once
162        the relay stops the track. Every call returns a future of its own that resolves once the
163        UNSUBSCRIBE was sent, even after another was cancelled, and raises what failed it;
164        cancelling it leaves the UNSUBSCRIBE going."""
165        return self._closing.start(self._native.close)

UNSUBSCRIBE, sent at once, as _native.Subscription.close is; the iteration ends once the relay stops the track. Every call returns a future of its own that resolves once the UNSUBSCRIBE was sent, even after another was cancelled, and raises what failed it; cancelling it leaves the UNSUBSCRIBE going.

@dataclass(frozen=True)
class TelemetryOptions:
30@dataclass(frozen=True)
31class TelemetryOptions:
32    """Where `moq_wasm.init` sends the native module's logs and spans, as the browser SDK's
33    `telemetry` option does."""
34
35    url: str | Callable[[], str]
36    """The observability server's origin (`https://observability.example`); reports go to its
37    `/api/client-telemetry`. A callable is called at each send."""
38    page: str
39    """Names the app in each report, at most 128 characters."""
40    redact: Callable[[Fields], Fields] | None = None
41    """Returns the fields a log or span is sent with, to mask or drop a value such as a
42    `track_namespace` that holds a user id. Messages and span names are sent as they are, and a
43    value JSON cannot hold, such as a NaN, as its `str`."""

Where moq_wasm.init sends the native module's logs and spans, as the browser SDK's telemetry option does.

TelemetryOptions( url: str | Callable[[], str], page: str, redact: Callable[[dict[str, Any]], dict[str, Any]] | None = None)
url: str | Callable[[], str]

The observability server's origin (https://observability.example); reports go to its /api/client-telemetry. A callable is called at each send.

page: str

Names the app in each report, at most 128 characters.

redact: Callable[[dict[str, Any]], dict[str, Any]] | None = None

Returns the fields a log or span is sent with, to mask or drop a value such as a track_namespace that holds a user id. Messages and span names are sent as they are, and a value JSON cannot hold, such as a NaN, as its str.

class TokenExpired(moq_wasm.SessionEnded):
55class TokenExpired(SessionEnded):
56    """The session's token expired before `refresh_token` returned a later one."""

The session's token expired before refresh_token returned a later one.

class TrackWriter:
112class TrackWriter:
113    """Publishes objects to a single track (no LOC extension headers).
114
115    Writes are serialized in call order; an in-flight native send finishes even if its caller is cancelled.
116    Objects written before registration completes are dropped.
117    Ends permanently on `close()`, session end, track registration failure, its broadcast's namespace publish
118    failure, or failure/cancellation of its opening write once registered (e.g. an event timeline). Thereafter,
119    pending and future writes raise the ending error immediately before any native call (`RuntimeError` after
120    `close()`). Only one active writer may own a track at a time.
121    """
122
123    def __init__(
124        self,
125        session: "Session",
126        namespace: list[str],
127        name: str,
128        retention_seconds: float,
129        *,
130        publish: bool = False,
131        datagram: bool = False,
132        priority: int = DEFAULT_PRIORITY,
133    ):
134        # Immutable, so a caller changing a list or the name cannot redirect `close()`.
135        self._namespace = tuple(namespace)
136        self._name = name
137        self.retention_seconds = retention_seconds
138        self.publish = publish
139        self.datagram = datagram
140        self.priority = priority
141        self._session = session
142        self._writer: _native.TrackWriter | None = None
143        # Set once the track is registered.
144        self._registered = asyncio.Event()
145        self._ended = Ended()
146        # Set by `close()`, after which the writer no longer owns its track.
147        self._closed = False
148        self._ending: Once[None] = Once()
149        # The native `next_subscriber` no caller took the answer of yet, as one whose caller was
150        # cancelled: the next caller takes it, so no subscriber is missed.
151        self._subscriber: asyncio.Future[bool] | None = None
152        self._awaiting_subscriber = False
153        # Clear while the track is being registered, so `close()` ends it once registered.
154        self._not_registering = asyncio.Event()
155        self._not_registering.set()
156        # The opening `_when_bound` runs once the track is registered.
157        self._on_bound: Callable[[], Awaitable[None]] | None = None
158        # Called once `close()` finished.
159        self._on_closed: list[Callable[[], None]] = []
160        # The turns of the writes, in the order they came: the first one's holds it, through its
161        # native send, and the others wait for theirs.
162        self._turns: deque[asyncio.Future[None]] = deque()
163        # The latest native send, which runs to its end even when its caller is cancelled.
164        self._sent: asyncio.Future[int | None] | None = None
165
166    @property
167    def namespace(self) -> list[str]:
168        """A copy: changing it changes nothing the writer does."""
169        return list(self._namespace)
170
171    @property
172    def name(self) -> str:
173        return self._name
174
175    async def write(self, payload: bytes, *, new_group: bool = False) -> int | None:
176        """`_native.TrackWriter.write` once the writes made before were sent; None for an object
177        dropped before the track is registered. Raises what ended the writer once it ended, even
178        when it ends while the write waits."""
179        return await self._send(lambda writer: writer.write(payload, new_group=new_group))
180
181    async def write_group(self, payload: bytes) -> int | None:
182        """`_native.TrackWriter.write_group` once the writes made before were sent; raises and
183        drops as `write`."""
184        return await self._send(lambda writer: writer.write_group(payload))
185
186    async def _send(self, send: Callable[[_native.TrackWriter], Awaitable[int | None]]) -> int | None:
187        # Checked before waiting, so a write after `close()` does not wait behind a stalled send.
188        self._raise_if_ended()
189        turn = await self._take_turn()
190        try:
191            if self._sent is not None:
192                # The native send a cancelled caller left.
193                await self._ended.until(self._sent)
194            # Checked again, as the writer may have ended meanwhile.
195            self._raise_if_ended()
196            if (writer := self._writer) is None:
197                return None
198            self._sent = asyncio.ensure_future(send(writer))
199            # Its failure goes to the caller, and to nobody once the caller was cancelled.
200            self._sent.add_done_callback(retrieve)
201            return await asyncio.shield(self._sent)
202        finally:
203            self._leave_turn(turn)
204
205    async def _take_turn(self) -> asyncio.Future[None]:
206        """Waits for the write's turn, which comes in the order the writes came, at once when no
207        other write has it. Raises what ended the writer instead once it ended, so a write queued
208        behind a stalled send does not wait for it."""
209        turn = asyncio.get_running_loop().create_future()
210        if not self._turns:
211            turn.set_result(None)
212        self._turns.append(turn)
213        if turn.done():
214            return turn
215        try:
216            await self._ended.until(turn)
217            self._raise_if_ended()
218        except BaseException:
219            self._leave_turn(turn)
220            raise
221        return turn
222
223    def _leave_turn(self, turn: asyncio.Future[None]) -> None:
224        """Gives `turn` up, passing it on to the next write when it was this write's."""
225        given = self._turns[0] is turn
226        self._turns.remove(turn)
227        if given and self._turns:
228            self._turns[0].set_result(None)
229
230    async def _sent_before(self) -> None:
231        if self._sent is not None:
232            await asyncio.wait([self._sent])
233
234    async def next_subscriber(self) -> bool:
235        """`_native.TrackWriter.next_subscriber`; False once the writer ended, as by `close()`,
236        leaving its broadcast or the session ending, and for a track that will not be registered,
237        a waiting call included. One caller at a time: a call while another waits raises
238        RuntimeError, and a subscriber that came as its caller was cancelled goes to the next
239        call."""
240        if self._awaiting_subscriber:
241            raise RuntimeError(f"next_subscriber of track {self.name} is already awaited")
242        self._awaiting_subscriber = True
243        try:
244            return await self._take_subscriber()
245        finally:
246            self._awaiting_subscriber = False
247
248    async def _take_subscriber(self) -> bool:
249        await self._registered_or_ended()
250        if self._ended.ended or self._writer is None:
251            return False
252        if self._subscriber is None:
253            self._subscriber = asyncio.ensure_future(self._writer.next_subscriber())
254            self._subscriber.add_done_callback(retrieve)
255        subscribed = self._subscriber
256        await self._ended.until(subscribed)
257        if self._ended.ended or subscribed.cancelled():
258            return False
259        self._subscriber = None
260        return subscribed.result()
261
262    async def registered(self) -> None:
263        """Waits until the track is registered. Raises what ended the writer once it ended, as
264        what failed the registration does, such as a `RequestError` for a refused PUBLISH, or a
265        RuntimeError for a track that will not be registered, as one of a broadcast left first."""
266        await self._registered_or_ended()
267        self._raise_if_ended()
268
269    async def _registered_or_ended(self) -> None:
270        registered = asyncio.ensure_future(self._registered.wait())
271        try:
272            await self._ended.until(registered)
273        finally:
274            registered.cancel()
275
276    async def close(self) -> None:
277        """Ends the subscriptions to the track with PUBLISH_DONE and stops writing to it. The
278        session keeps the track's numbering and cache, so a later `publish_track` of the same track
279        continues them. Writing raises at once; every call returns once the PUBLISH_DONE was sent,
280        even after one was cancelled."""
281        await self._close(RuntimeError(f"track {self.name} of {self.namespace} was closed"))
282
283    def _close(self, error: BaseException) -> asyncio.Future[None]:
284        """Ends the writer with `error`, unless it ended before, and starts closing it; the close
285        runs to its end even when the caller awaiting it is cancelled."""
286        self._closed = True
287        self._end_with(error)
288        return self._ending.start(self._end)
289
290    async def _end(self) -> None:
291        try:
292            await self._not_registering.wait()
293            # The send under way goes out before the track ends; the writes waiting after it raise,
294            # so none starts another.
295            await self._sent_before()
296            if self._writer is not None and not self._session._done.done():
297                await self._session._native.end_track(list(self._namespace), self._name)
298        finally:
299            self._session._release_track(self)
300            for closed in self._on_closed:
301                closed()
302
303    def _raise_if_ended(self) -> None:
304        if self._ended.ended:
305            raise self._ended.error()
306
307    async def _bind(self, writer: _native.TrackWriter) -> None:
308        self._writer = writer
309        if self._closed:
310            # Closed while it was being registered: `close()` ends the track now.
311            return
312        self._registered.set()
313        if self._on_bound is not None:
314            await self._open(self._on_bound)
315
316    def _when_bound(self, opening: Callable[[], Awaitable[None]]) -> None:
317        """Runs `opening`, a write ahead of every other, once the track is registered, or at once
318        when it is: its failure or cancellation closes the writer, as at its registration."""
319        if not self._registered.is_set():
320            self._on_bound = opening
321            return
322        asyncio.ensure_future(self._open(opening)).add_done_callback(retrieve)
323
324    async def _open(self, opening: Callable[[], Awaitable[None]]) -> None:
325        try:
326            await opening()
327        except BaseException as error:
328            # The opening failed or was cancelled, as by leaving the broadcast: the track is closed,
329            # so nothing is written to it without its opening, ended with the failure for its writes
330            # to raise.
331            closed = RuntimeError(f"track {self.name} of {self.namespace} was closed")
332            self._close(error if isinstance(error, Exception) else closed)
333            raise
334
335    def _end_with_session(self) -> None:
336        """Ends the writer once the session ends, or at once when it ended, the session holding it
337        until then. Called by its owner once it owns its track, so a writer refused its track leaves
338        the session nothing to call."""
339        self._session._on_end(self._end_with)
340
341    def _end_with(self, error: BaseException, *, raised: Callable[[], None] | None = None) -> None:
342        """Ends the writer with `error`, unless it ended before; `raised` is called each time a
343        write or a wait raises it. Stops waiting for the next subscriber."""
344        self._ended.end(error, raised=raised)
345        self._session._forget_end(self._end_with)
346        if self._subscriber is not None:
347            self._subscriber.cancel()
348            self._subscriber = None
349
350    def _abandon(self, failure: Exception | None = None) -> None:
351        """The track will not be registered, because of `failure` if given, which ends the
352        writer."""
353        self._end_with(failure or RuntimeError(f"track {self.name} of {self.namespace} was not registered"))

Publishes objects to a single track (no LOC extension headers).

Writes are serialized in call order; an in-flight native send finishes even if its caller is cancelled. Objects written before registration completes are dropped. Ends permanently on close(), session end, track registration failure, its broadcast's namespace publish failure, or failure/cancellation of its opening write once registered (e.g. an event timeline). Thereafter, pending and future writes raise the ending error immediately before any native call (RuntimeError after close()). Only one active writer may own a track at a time.

TrackWriter( session: Session, namespace: list[str], name: str, retention_seconds: float, *, publish: bool = False, datagram: bool = False, priority: int = 128)
123    def __init__(
124        self,
125        session: "Session",
126        namespace: list[str],
127        name: str,
128        retention_seconds: float,
129        *,
130        publish: bool = False,
131        datagram: bool = False,
132        priority: int = DEFAULT_PRIORITY,
133    ):
134        # Immutable, so a caller changing a list or the name cannot redirect `close()`.
135        self._namespace = tuple(namespace)
136        self._name = name
137        self.retention_seconds = retention_seconds
138        self.publish = publish
139        self.datagram = datagram
140        self.priority = priority
141        self._session = session
142        self._writer: _native.TrackWriter | None = None
143        # Set once the track is registered.
144        self._registered = asyncio.Event()
145        self._ended = Ended()
146        # Set by `close()`, after which the writer no longer owns its track.
147        self._closed = False
148        self._ending: Once[None] = Once()
149        # The native `next_subscriber` no caller took the answer of yet, as one whose caller was
150        # cancelled: the next caller takes it, so no subscriber is missed.
151        self._subscriber: asyncio.Future[bool] | None = None
152        self._awaiting_subscriber = False
153        # Clear while the track is being registered, so `close()` ends it once registered.
154        self._not_registering = asyncio.Event()
155        self._not_registering.set()
156        # The opening `_when_bound` runs once the track is registered.
157        self._on_bound: Callable[[], Awaitable[None]] | None = None
158        # Called once `close()` finished.
159        self._on_closed: list[Callable[[], None]] = []
160        # The turns of the writes, in the order they came: the first one's holds it, through its
161        # native send, and the others wait for theirs.
162        self._turns: deque[asyncio.Future[None]] = deque()
163        # The latest native send, which runs to its end even when its caller is cancelled.
164        self._sent: asyncio.Future[int | None] | None = None
retention_seconds
publish
datagram
priority
namespace: list[str]
166    @property
167    def namespace(self) -> list[str]:
168        """A copy: changing it changes nothing the writer does."""
169        return list(self._namespace)

A copy: changing it changes nothing the writer does.

name: str
171    @property
172    def name(self) -> str:
173        return self._name
async def write(self, payload: bytes, *, new_group: bool = False) -> int | None:
175    async def write(self, payload: bytes, *, new_group: bool = False) -> int | None:
176        """`_native.TrackWriter.write` once the writes made before were sent; None for an object
177        dropped before the track is registered. Raises what ended the writer once it ended, even
178        when it ends while the write waits."""
179        return await self._send(lambda writer: writer.write(payload, new_group=new_group))

_native.TrackWriter.write once the writes made before were sent; None for an object dropped before the track is registered. Raises what ended the writer once it ended, even when it ends while the write waits.

async def write_group(self, payload: bytes) -> int | None:
181    async def write_group(self, payload: bytes) -> int | None:
182        """`_native.TrackWriter.write_group` once the writes made before were sent; raises and
183        drops as `write`."""
184        return await self._send(lambda writer: writer.write_group(payload))

_native.TrackWriter.write_group once the writes made before were sent; raises and drops as write.

async def next_subscriber(self) -> bool:
234    async def next_subscriber(self) -> bool:
235        """`_native.TrackWriter.next_subscriber`; False once the writer ended, as by `close()`,
236        leaving its broadcast or the session ending, and for a track that will not be registered,
237        a waiting call included. One caller at a time: a call while another waits raises
238        RuntimeError, and a subscriber that came as its caller was cancelled goes to the next
239        call."""
240        if self._awaiting_subscriber:
241            raise RuntimeError(f"next_subscriber of track {self.name} is already awaited")
242        self._awaiting_subscriber = True
243        try:
244            return await self._take_subscriber()
245        finally:
246            self._awaiting_subscriber = False

_native.TrackWriter.next_subscriber; False once the writer ended, as by close(), leaving its broadcast or the session ending, and for a track that will not be registered, a waiting call included. One caller at a time: a call while another waits raises RuntimeError, and a subscriber that came as its caller was cancelled goes to the next call.

async def registered(self) -> None:
262    async def registered(self) -> None:
263        """Waits until the track is registered. Raises what ended the writer once it ended, as
264        what failed the registration does, such as a `RequestError` for a refused PUBLISH, or a
265        RuntimeError for a track that will not be registered, as one of a broadcast left first."""
266        await self._registered_or_ended()
267        self._raise_if_ended()

Waits until the track is registered. Raises what ended the writer once it ended, as what failed the registration does, such as a RequestError for a refused PUBLISH, or a RuntimeError for a track that will not be registered, as one of a broadcast left first.

async def close(self) -> None:
276    async def close(self) -> None:
277        """Ends the subscriptions to the track with PUBLISH_DONE and stops writing to it. The
278        session keeps the track's numbering and cache, so a later `publish_track` of the same track
279        continues them. Writing raises at once; every call returns once the PUBLISH_DONE was sent,
280        even after one was cancelled."""
281        await self._close(RuntimeError(f"track {self.name} of {self.namespace} was closed"))

Ends the subscriptions to the track with PUBLISH_DONE and stops writing to it. The session keeps the track's numbering and cache, so a later publish_track of the same track continues them. Writing raises at once; every call returns once the PUBLISH_DONE was sent, even after one was cancelled.

class TransportStats:

The bytes the session's connections carried.

sent_bytes
received_bytes
def connect( url: str, *, verify_certificate: bool = True, token: str | None = None, refresh_token: Callable[[str], Awaitable[str]] | None = None, versions: list[str] | None = None) -> moq_wasm._session._Connecting:
1044def connect(
1045    url: str,
1046    *,
1047    verify_certificate: bool = True,
1048    token: str | None = None,
1049    refresh_token: RefreshToken | None = None,
1050    versions: list[str] | None = None,
1051) -> _Connecting:
1052    """Connect to a MoQT relay (`moqt://` QUIC, `https://` WebTransport) with optional JWT `token`.
1053
1054    Use with `async with` or `await` + `close()`. Raises `RuntimeError` on failure or 30 s handshake timeout.
1055    `versions` lists drafts to offer, most preferred first (default: draft-18 then draft-14).
1056
1057    With `refresh_token` (requires `token`, else `ValueError`), the callback runs 5 min before `exp`
1058    (or halfway through shorter lifetimes) with the current token and must return a token for the same
1059    `appId` with a later `exp`. Refresh has a `min(30 s, remaining lifetime)` deadline across the callback
1060    and relay handover; any failed, timed-out, cancelled (while alive), or rejected refresh retries with
1061    the current token every 30 s (or half the remaining lifetime) until expiry, ending with `TokenExpired`
1062    (`ConnectionLost` without `refresh_token`).
1063    """
1064    if refresh_token is not None and token is None:
1065        raise ValueError("refresh_token needs a token")
1066    if refresh_token is not None and token is not None:
1067        # Raises ValueError for what is not a token before anything is dialed.
1068        read_claims(token)
1069
1070    async def dial(current_token: str | None) -> _native.Session:
1071        return await _native.connect(
1072            url,
1073            verify_certificate=verify_certificate,
1074            token=current_token,
1075            refreshes_token=refresh_token is not None,
1076            versions=versions,
1077        )
1078
1079    return _Connecting(dial, token, refresh_token)

Connect to a MoQT relay (moqt:// QUIC, https:// WebTransport) with optional JWT token.

Use with async with or await + close(). Raises RuntimeError on failure or 30 s handshake timeout. versions lists drafts to offer, most preferred first (default: draft-18 then draft-14).

With refresh_token (requires token, else ValueError), the callback runs 5 min before exp (or halfway through shorter lifetimes) with the current token and must return a token for the same appId with a later exp. Refresh has a min(30 s, remaining lifetime) deadline across the callback and relay handover; any failed, timed-out, cancelled (while alive), or rejected refresh retries with the current token every 30 s (or half the remaining lifetime) until expiry, ending with TokenExpired (ConnectionLost without refresh_token).

def init( *, log_level: str = 'warn', on_log: Callable[[dict[str, Any], str | None], None] | None = None, on_span: Callable[[dict[str, Any], str | None], None] | None = None, telemetry: TelemetryOptions | None = None) -> None:
 72def init(
 73    *,
 74    log_level: str = "warn",
 75    on_log: RecordCallback | None = None,
 76    on_span: RecordCallback | None = None,
 77    telemetry: TelemetryOptions | None = None,
 78) -> None:
 79    """Hands the native module's `tracing` events at `log_level` (`error`, `warn`, `info`, `debug`
 80    or `trace`) or above to Python's `logging`, under `moq_wasm.native` and the event's target with
 81    `.` for `::` (`moq_wasm.native.moqt.modules.client.routes`), and to `on_log`. With
 82    `on_span`, the native module's closed INFO or higher spans go to it, and the requests a session
 83    sends carry their trace, as the browser SDK's `init({ logLevel, onLog, onSpan })` does. The
 84    callbacks run on a thread of their own; the second argument is the token of the session the
 85    record belongs to (its newest, after a `refresh_token`), None for a record of no session or of a
 86    session without one. Put it only in a telemetry report's `token`. `telemetry` sends the logs and
 87    spans to an observability server every 10 s, and once more at exit with what the sink drained
 88    by then, each session's under its token, as the browser SDK's does. The sink is process-wide:
 89    only the first call takes effect. Raises ValueError for an unknown level."""
 90    global _sink
 91    with _sink_lock:
 92        if _sink is not None:
 93            return
 94        if log_level not in LEVELS:
 95            raise ValueError(f"unknown log level: {log_level}")
 96        logs = [on_log] if on_log is not None else []
 97        spans = [on_span] if on_span is not None else []
 98        reports = ClientTelemetry(telemetry) if telemetry is not None else None
 99        if reports is not None:
100            logs.append(reports.log)
101            spans.append(reports.span)
102        _native.set_log_sink(log_level, bool(spans))
103        if reports is not None:
104            _start_reporting(reports)
105        sink = _Sink(log_level, logs, spans)
106        pumping = threading.Thread(target=sink.pump, name="moq_wasm-log-sink", daemon=True)
107        pumping.start()
108
109        def stop() -> None:
110            sink.stopped.set()
111            pumping.join(STOP_TIMEOUT_SECONDS)
112
113        # atexit runs the last registered first, so the sink drains before the final report.
114        atexit.register(stop)
115        _sink = sink

Hands the native module's tracing events at log_level (error, warn, info, debug or trace) or above to Python's logging, under moq_wasm.native and the event's target with . for :: (moq_wasm.native.moqt.modules.client.routes), and to on_log. With on_span, the native module's closed INFO or higher spans go to it, and the requests a session sends carry their trace, as the browser SDK's init({ logLevel, onLog, onSpan }) does. The callbacks run on a thread of their own; the second argument is the token of the session the record belongs to (its newest, after a refresh_token), None for a record of no session or of a session without one. Put it only in a telemetry report's token. telemetry sends the logs and spans to an observability server every 10 s, and once more at exit with what the sink drained by then, each session's under its token, as the browser SDK's does. The sink is process-wide: only the first call takes effect. Raises ValueError for an unknown level.

def parse_catalog(payload):
def report_log(level: str, target: str, message: str, **fields: Any) -> None:
132def report_log(level: str, target: str, message: str, **fields: Any) -> None:
133    """Hands the app's own log to `init`'s `on_log` and `telemetry` at its `log_level` or above,
134    without a token, as the browser SDK's `reportLog` does; it is not written to `logging`. Values
135    that are not a string, number or boolean are sent as their `str`. Raises ValueError for an
136    unknown level."""
137    if level not in LEVELS:
138        raise ValueError(f"unknown log level: {level}")
139    sink = _sink
140    if sink is None or LEVELS[level] < sink.level:
141        return
142    record = {
143        "timeMs": int(time.time() * 1000),
144        "level": level,
145        "target": target,
146        "message": message,
147        "fields": {key: _field(value) for key, value in fields.items()},
148    }
149    _call(sink.on_log, record, None)

Hands the app's own log to init's on_log and telemetry at its log_level or above, without a token, as the browser SDK's reportLog does; it is not written to logging. Values that are not a string, number or boolean are sent as their str. Raises ValueError for an unknown level.