Skip to content

API Reference parrot.integrations.liveavatar.broadcast.worker_transport

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.integrations.liveavatar.broadcast.worker_transport

View source

Authenticated worker-to-worker speaker relay (FEAT-537 — Module 4).

Spec §2: "For a socket connected to another worker, an internal aiohttp WebSocket relay authenticates the worker and carries participant/owner/floor epochs in bounded messages. Public clients cannot select an owner address … No raw microphone audio in Redis pub/sub. Live objects stay on the producer process."

The shape of the problem: a participant's browser can land on any HTTP worker, but the VoiceBot, the avatar session and the LiveKit publishers live only on the worker that won claim_owner. When the granted speaker's socket is not on that worker, their microphone PCM has to cross one hop — and that hop is the most security-sensitive surface in the feature, because anything that reaches it is about to be spoken by the agent to the whole audience.

Hence, deliberately:

  • The owner's address is never client-supplied. It comes from :class:WorkerAddressRegistry, written by workers themselves, and any value that is not a ws(s):// URL is refused outright.
  • Every frame re-states the full fencing tuple (owner epoch, lease, floor epoch, turn, sequence) and is re-validated on the owner immediately before push_audio. Passing ingress validation is not a permit.
  • A stale owner epoch closes the connection rather than being tolerated.
  • Bounded message size, bounded queue, idle timeout, and a constant-time shared service token compared with :func:hmac.compare_digest.

Class LocalSpeakerInput

Producer is on this worker: talk to the voice session directly.

Parameter Type Default Description
session Any The local :class:BroadcastVoiceSession.
lease_id str The speaking lease.
principal Any The speaker's scoped principal.
floor_epoch int Floor epoch this input was authorised under.

Method LocalSpeakerInput.start_turn

start_turn() -> None

Method LocalSpeakerInput.push_audio

push_audio(pcm: bytes) -> None

Parameter Type Default Description
pcm bytes

Method LocalSpeakerInput.end_turn

end_turn() -> None

Method LocalSpeakerInput.aclose

Release this input, but only if it still owns the speaker context.

A departing socket must not clear a context that has since been handed to somebody else: after an A→B handoff, closing A's socket would otherwise leave B unable to speak. The generation captured at start_turn identifies the turn this input started.

aclose() -> None

Attribute MAX_RELAY_MESSAGE_BYTES

Type: int

Attribute RELAY_IDLE_TIMEOUT_S

Type: float

Attribute RELAY_QUEUE_MAX_FRAMES

Type: int

Attribute RELAY_ROUTE

Type: str

Class RelayFrame

One validated relay message.

Parameter Type Default Description
kind str
owner_epoch int
lease_id str
floor_epoch int
turn_id Optional[str] None
seq int 0
pcm bytes b''

Fields:

Field Type Default Description
kind str start_turn / audio / end_turn / release.
owner_epoch int Ownership generation the sender believes is current.
lease_id str Speaker lease the audio is attributed to.
floor_epoch int Floor generation the input was captured under.
turn_id Optional[str] None Producing turn, when known.
seq int 0 Monotonic sequence within the turn.
pcm bytes b'' Decoded PCM, for audio frames.

Method RelayFrame.parse

Parse and validate one wire message.

parse(raw: str) -> 'RelayFrame'

Parameter Type Default Description
raw str The JSON text received.

Returns: 'RelayFrame' — The parsed frame.

Raises:

  • WorkerTransportError — On malformed JSON, a missing required field or undecodable audio.

Method RelayFrame.to_wire

Serialise this frame for the wire.

to_wire() -> str

Returns: str

Class RemoteSpeakerInput

Producer is on another worker: relay over the authenticated transport.

The queue is bounded on purpose. If the hop cannot keep up, dropping the newest frames and logging is correct — buffering microphone audio indefinitely would make the agent answer a question the speaker asked seconds ago.

Parameter Type Default Description
url str The owner's relay URL, resolved from :class:WorkerAddressRegistry — never from a client.
tenant_id str Tenant scope.
broadcast_id str Broadcast concerned.
owner_epoch int Ownership generation, restated on every frame.
lease_id str The speaking lease.
floor_epoch int Floor epoch this input was authorised under.
token Optional[str] None Shared service token.
session_factory Optional[Callable[[], Any]] None Override for aiohttp.ClientSession (tests).

Method RemoteSpeakerInput.start_turn

start_turn() -> None

Method RemoteSpeakerInput.push_audio

push_audio(pcm: bytes) -> None

Parameter Type Default Description
pcm bytes

Method RemoteSpeakerInput.end_turn

end_turn() -> None

Method RemoteSpeakerInput.aclose

aclose() -> None

Class SpeakerInput

What the WebSocket route uses to feed the producer, wherever it lives.

Method SpeakerInput.start_turn

Begin an input turn.

start_turn() -> None

Method SpeakerInput.push_audio

Forward one microphone PCM block.

push_audio(pcm: bytes) -> None

Parameter Type Default Description
pcm bytes

Method SpeakerInput.end_turn

End the input turn.

end_turn() -> None

Method SpeakerInput.aclose

Release the input. Idempotent, never raises.

aclose() -> None

Attribute WORKER_TOKEN_ENV

Type: str

Attribute WORKER_TOKEN_HEADER

Type: str

Attribute WS_CLOSE_POLICY_VIOLATION

Type: int

Attribute WS_CLOSE_TOO_BIG

Type: int

Class WorkerAddressRegistry

Maps worker ids to their internal relay URLs.

Backed by a Redis hash so every worker can resolve the current producer's address, and refreshed with a TTL so a dead worker's address disappears.

The only write path is a worker registering itself; the only read path returns what was registered. A client can name a worker id (indirectly, by which broadcast it joined) but never a URL.

Parameter Type Default Description
redis_client Any None An redis.asyncio.Redis with decode_responses=True, or None for a purely in-process registry (single-worker deployments and tests).
key_prefix str 'parrot:voice-broadcast' Namespace for the workers hash.
ttl_s int 30 Registration lifetime.

Method WorkerAddressRegistry.validate_url

Reject anything that is not a WebSocket URL.

validate_url(url: str) -> str

Parameter Type Default Description
url str Candidate address.

Returns: str — The validated URL.

Raises:

  • WorkerTransportError — If the scheme is not ws/wss or the host is missing. This is the choke point that stops an attacker-influenced value ever becoming an outbound connection.

Method WorkerAddressRegistry.register

Advertise this worker's relay address.

register(worker_id: str, url: str) -> None

Parameter Type Default Description
worker_id str The worker registering itself.
url str Its internal relay URL.

Raises:

  • WorkerTransportError — If url is not a WebSocket URL.

Method WorkerAddressRegistry.unregister

Remove a worker's address.

unregister(worker_id: str) -> None

Parameter Type Default Description
worker_id str

Method WorkerAddressRegistry.resolve

Look up a worker's relay URL.

resolve(worker_id: str) -> Optional[str]

Parameter Type Default Description
worker_id str The worker to reach.

Returns: Optional[str] — Its validated URL, or None when it is not registered.

Class WorkerRelayServer

Owner-side endpoint that accepts relayed speaker input.

Mounted only on the worker that owns a producer, and only on an internal application — never on the public one.

Parameter Type Default Description
service Any The local :class:BroadcastService, used to resolve the producer, its owner epoch and the live voice session.
token Optional[str] None Shared service token. Falls back to :data:WORKER_TOKEN_ENV.
require_tls bool True Refuse non-loopback peers that are not on TLS.

Method WorkerRelayServer.setup_routes

Mount the relay route on an internal aiohttp application.

setup_routes(app: web.Application, prefix: str = '') -> None

Parameter Type Default Description
app web.Application The internal application.
prefix str '' Optional URL prefix.

Raises:

  • WorkerTransportError — If no shared token is configured. Refusing to start is the right failure: an unauthenticated relay would let anything that can reach the port speak as the agent.

Method WorkerRelayServer.handle_relay

Accept one ingress worker's relayed speaker input.

handle_relay(request: web.Request) -> web.WebSocketResponse

Parameter Type Default Description
request web.Request The internal request.

Returns: web.WebSocketResponse — The prepared WebSocket response.

Raises:

  • web.HTTPUnauthorized — On a missing/incorrect service token.
  • web.HTTPForbidden — On a plaintext non-loopback peer.

Class WorkerTransportError

The relay refused or lost the connection.

Function resolve_worker_token

Return the shared worker token from the argument or the environment.

resolve_worker_token(explicit: Optional[str] = None) -> Optional[str]

Parameter Type Default Description
explicit Optional[str] None A token supplied by the caller, if any.

Returns: Optional[str] — The token, or None when none is configured.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally