Documentation
¶
Overview ¶
Telemetry session tokens (R28 TM1, docs/33 D2 + §4.2).
The load-bearing gap R28 closes is that /statusz names a subscriber by a random per-session key and NOTHING ever tells that client its own key — so the relay's view of a viewer and the viewer's view of itself are two datasets that cannot be joined. "Per-viewer experience" is exactly that join. A token minted here is both halves of the fix: the sessionId inside it appears on both sides, and the tag around it is what makes an unauthenticated public write surface tolerable — the ingest accepts records only from clients that actually connected to a relay in this fleet.
token = expHour (uint32 BE) ‖ nonce (12 B) ‖ tag (8 B) # 24 bytes tag = HMAC-SHA256(key, expHour ‖ nonce ‖ broadcastKey ‖ role)[:8]
Stateless by construction, exactly R17's resume-token pattern: any pod mints, the telemetry service verifies with one HMAC — no lookup, no shared database, no chatter with the relay. Expiry is a field rather than a bucket sweep, and role is bound into the tag so a viewer's token cannot submit broadcaster-shaped records.
This lives in the public wire package (not internal/) for the same reason the rest of it does: gawk-telemetry is a separate module and must consume the real implementation rather than mirror it (R14 Decision 1).
Tokens are never logged. Only the sessionId — hex(nonce) — is ever stored, by either end.
Package wire implements the frozen datagram wire format shared by the relay server, the broadcasters, and the viewers.
This package is deliberately public (R14 Decision 1, docs/19): the native Linux broadcaster lives in its own top-level module (gawk-broadcast/) and imports it, because a second hand-written implementation of the format is exactly what the golden vectors below exist to prevent. Go's internal/ rule forbids that import from another module, so wire sits outside internal/. It may still import internal/broadcastid — the rule restricts importers by path prefix, and gawk-server/wire qualifies.
This file is the allocation map and source of truth. Three hand-written mirrors restate its golden vectors byte-identically and must be updated with every wire change: the TS frontend (gawk-app/src/transport/wire.ts), the Go broadcaster's checks (gawk-broadcast/internal/wirecheck), and the Rust Windows broadcaster (gawk-broadcast-desktop/crates/wire, R34 — docs/38 D4; note its CI job is path-filtered, so the mirror's gates only run once its own commit lands).
Every datagram starts with a common 2-byte prefix: byte 0 is the protocol version (Version) and byte 1 is the message type (TypeVideoChunk or TypeDecoderConfig). All multi-byte integers are big-endian, which maps directly onto a TypeScript DataView in the frontend mirror of this package.
Message layouts:
0x01 VideoChunk (VideoChunkHeaderSize = 20 bytes of header, then payload): byte 2 uint8 flags bit0 = keyframe, bits 1-7 reserved (0) byte 3 uint8 reserved (0) bytes 4-7 uint32 frameID bytes 8-9 uint16 chunkIndex 0-based bytes 10-11 uint16 chunkCount total chunks in the frame (>= 1) bytes 12-19 uint64 timestampUs bytes 20+ payload, at most MaxChunkPayload bytes 0x02 DecoderConfig: byte 2 uint8 reserved (0) byte 3 uint8 codecLen bytes 4.. codecLen bytes of ASCII codec string rest extradata (may be empty)
Parse functions never copy: returned payload/extradata slices alias the input datagram. Callers that retain parsed data past the lifetime of the datagram buffer must copy it themselves.
Index ¶
- Constants
- Variables
- func AppendAudioConfig(dst []byte, c AudioConfig) ([]byte, error)
- func AppendAudioFrame(dst []byte, h AudioFrameHeader, payload []byte) ([]byte, error)
- func AppendBroadcastAnnounce(dst []byte, id string) ([]byte, error)
- func AppendCarrierPrologue(dst []byte) []byte
- func AppendCarrierRecord(dst []byte, dgram []byte) ([]byte, error)
- func AppendClockMapping(dst []byte, offsetUs int64) []byte
- func AppendDecoderConfig(dst []byte, c DecoderConfig) ([]byte, error)
- func AppendDeliveryAck(dst []byte, mode DeliveryMode, bufferMs uint16) []byte
- func AppendParityChunk(dst []byte, h ParityChunkHeader, payload []byte) ([]byte, error)
- func AppendRelayCapabilities(dst []byte, c RelayCapabilities) ([]byte, error)
- func AppendRelayIdentity(dst []byte, id RelayIdentity) ([]byte, error)
- func AppendResumeToken(dst []byte, token []byte) ([]byte, error)
- func AppendRoomCommand(dst []byte, c RoomCommand) ([]byte, error)
- func AppendRoomEvent(dst []byte, e RoomEvent) ([]byte, error)
- func AppendRoomHello(dst []byte, h RoomHello) ([]byte, error)
- func AppendRoomRecord(dst, msg []byte) ([]byte, error)
- func AppendRoomState(dst []byte, s RoomState) ([]byte, error)
- func AppendSessionClosing(dst []byte, code uint32) ([]byte, error)
- func AppendStreamFrameHeader(dst []byte, h StreamFrameHeader) ([]byte, error)
- func AppendStripeState(dst []byte, s StripeState) ([]byte, error)
- func AppendTelemetryEndpoint(dst []byte, ingestURL string) ([]byte, error)
- func AppendTelemetryHello(dst []byte, h TelemetryHello) ([]byte, error)
- func AppendTimeSync(dst []byte, clientTimeUs, serverTimeUs uint64) []byte
- func AppendVideoChunk(dst []byte, h VideoChunkHeader, payload []byte) ([]byte, error)
- func AppendViewerCount(dst []byte, count uint32) []byte
- func ComputeParity(chunks [][]byte, k int) ([][]byte, error)
- func MintTelemetrySessionToken(key []byte, broadcastKey []byte, role TelemetryRole, now time.Time) ([]byte, error)
- func ParseBroadcastAnnounce(dgram []byte) (string, error)
- func ParseCarrierPrologue(buf []byte) error
- func ParseCarrierRecord(buf []byte) (record, rest []byte, err error)
- func ParseClockMapping(dgram []byte) (offsetUs int64, err error)
- func ParseResumeToken(msg []byte) ([]byte, error)
- func ParseRoomRecordLength(hdr []byte) (int, error)
- func ParseSessionClosing(msg []byte) (uint32, error)
- func ParseTelemetryEndpoint(msg []byte) (string, error)
- func ParseTimeSync(dgram []byte) (clientTimeUs, serverTimeUs uint64, err error)
- func ParseViewerCount(dgram []byte) (count uint32, err error)
- func PeekType(dgram []byte) (version, msgType uint8, err error)
- func RecoverChunks(chunks [][]byte, parity [][]byte, frameBytes int) error
- func StripeOrdinal(chunkIndex, chunkCount uint16, parityIndex int) uint32
- func TelemetrySessionID(token []byte) (string, error)
- func ValidTelemetryRole(r TelemetryRole) bool
- func VerifyTelemetrySessionToken(key, token, broadcastKey []byte, role TelemetryRole, now time.Time) (string, error)
- type AudioConfig
- type AudioFrameHeader
- type DecoderConfig
- type DeliveryMode
- type ParityChunkHeader
- type RelayCapabilities
- type RelayIdentity
- type RoomAttachment
- type RoomCommand
- type RoomEvent
- type RoomHello
- type RoomParticipant
- type RoomState
- type StreamFrameHeader
- type StripeState
- type TelemetryHello
- type TelemetryRole
- type VideoChunkHeader
Constants ¶
const ( // TypeSessionClosing identifies a SessionClosing message. Allocated // 2026-09-24 after the room control types 0x13–0x16. TypeSessionClosing = 0x17 // SessionClosingSize is the exact size of a SessionClosing message. SessionClosingSize = 6 // MinGawkCloseCode / MaxGawkCloseCode bound the application close codes // gawk allocates (4000 CloseCodeBroadcastEnded upward). MinGawkCloseCode = 4000 MaxGawkCloseCode = 4999 )
SessionClosing (R57, docs/59): relay→client, the close code of a session the relay is about to close, sent on its own server-opened unidirectional stream a settle interval before the WebTransport close itself.
It exists because the close code does not reach Chrome. webtransport-go writes the WT_CLOSE_SESSION capsule and then STOP_SENDINGs the CONNECT stream, quic-go packs that control frame ahead of the capsule in the same packet, and Chrome fails the session on it before it reads the capsule: `WebTransport.closed` rejects "Connection lost." with no code (measured 2026-09-24: 1 close code of 84 reached Chrome; quic-go/webtransport-go#242, closed upstream as a Chromium bug). The in-band copy is what a browser acts on when the close arrives without one; a client that did read the close code keeps using it.
Sent only for the codes that change what a client does next — 4000 to a viewer, 4004 and 4006 to a publisher or viewer — and only on external publish/subscribe sessions: never on /internal/* (the edge client reads every uni stream as a keyframe), and not on room control sessions, whose RoomEnding event already carries 4007's meaning in-band (docs/44 §4.6).
Layout (SessionClosingSize bytes):
byte 0 uint8 version (Version)
byte 1 uint8 type (TypeSessionClosing)
bytes 2-5 uint32 code, big-endian, in the gawk application range
[MinGawkCloseCode, MaxGawkCloseCode]
Clients parse it and never send it. Strict: exactly SessionClosingSize bytes. A client that does not know the type ignores the stream, like every other unknown server message (the native broadcasters already do).
const ( // ParityChunkHeaderSize is the fixed header size of a ParityChunk // datagram: version, type, frameID, parityIndex, chunkCount, frameBytes. // // It is deliberately 13 and not 20. A parity symbol is as long as the // longest data chunk, i.e. up to MaxChunkPayload (1180), so a 20-byte // header carrying a timestamp would produce a 1201-byte datagram and // breach MaxDatagramSize. The cost of omitting the timestamp is that // reconstruction needs at least one surviving data chunk to source it // from — which holds whenever recovery is possible at all, except the // degenerate n <= k case that is deliberately not recovered. ParityChunkHeaderSize = 13 // MaxParitySymbols is the largest k the P/Q scheme supports. MaxParitySymbols = 2 // MaxParityDataChunks bounds n. g^i has period 255, so at n > 255 the Q // coefficients repeat, two data chunks share a coefficient, and the // 2-erasure solve divides by zero — the code silently stops being MDS. // A delta needing more than 255 chunks would be ~300 KB, which is // unreachable at any sane bitrate, and keyframes never carry parity // (they ride reliable streams already). This is an explicit guard rather // than an assumption. MaxParityDataChunks = 255 // RelayCapabilitiesSize is the exact size of a RelayCapabilities message: // version, type, flags (uint16 BE), parity level. RelayCapabilitiesSize = 5 )
const ( // CapParityChunks means the relay understands ParityChunk datagrams and // will filter them per subscriber. A producer that does not see this bit // sends no parity, so a new broadcaster against an old relay stays // byte-identical to pre-R29 (docs/34 §4.4). CapParityChunks uint16 = 1 << 0 // CapStripedDelivery means the relay accepts ?stripe=N&leg=j subscribe // sessions and StripeState datagrams (R30, docs/35). A viewer that does // not see this bit never dials a leg and never sends StripeState, so a // new viewer against an old relay stays byte-identical to pre-R30. The // message stays 5 bytes: capability GROWTH is new bits in this flags // word, never new bytes — the R29 broadcaster parses this message // strictly by size, and extending it would break that parser mid-skew. CapStripedDelivery uint16 = 1 << 1 )
Capability flags carried by RelayCapabilities. Append, never renumber.
const ( // TypeRoomHello identifies a RoomHello record: client → relay, the first // record on a room control stream. TypeRoomHello = 0x13 // TypeRoomState identifies a RoomState record: relay → client, a full // snapshot sent once after RoomHello and again after any adoption or // proxy re-establishment. Clients replace, never merge. TypeRoomState = 0x14 // TypeRoomEvent identifies a RoomEvent record: relay → client, one delta. TypeRoomEvent = 0x15 // TypeRoomCommand identifies a RoomCommand record: client → relay. TypeRoomCommand = 0x16 )
Room control message types (docs/44 D15).
const ( // RoomProtocolVersion is the room control protocol version a RoomHello // carries. Independent of the datagram Version byte so the control // protocol can evolve (chat, voice) without touching the media wire. RoomProtocolVersion = 1 // RoomRecordHeaderSize is the uint16 length prefix in front of every // record on a room control stream — the carrier record shape. RoomRecordHeaderSize = 2 // MaxRoomRecordSize bounds one record's framed bytes (Version ‖ Type ‖ // payload, what the length prefix counts): a reader must never allocate // more than this from an untrusted length. A RoomState for a full room // (-max-room-participants default 50, four attachments) is under 4 KiB. MaxRoomRecordSize = 16384 // MaxRoomNicknameLen bounds a participant nickname in bytes (UTF-8). MaxRoomNicknameLen = 32 // MaxRoomCodeLen bounds a room's display code: a static slug is 3–32 // characters (docs/44 §4.1); a dynamic code is broadcastid.Length. MaxRoomCodeLen = 32 // MaxRoomDisplayNameLen bounds a static room's optional display name. MaxRoomDisplayNameLen = 64 // MaxRoomLabelLen bounds a broadcaster-chosen attachment label. MaxRoomLabelLen = 32 // MaxRoomIdentityLen bounds the reserved participant identity field // (docs/44 §4.11: a key fingerprint later; empty in v1). MaxRoomIdentityLen = 64 // MaxRoomRejectMessageLen bounds a CommandRejected message. MaxRoomRejectMessageLen = 128 // RoomCreatorTokenSize is the byte length of a dynamic room's creator // token: the same truncated-HMAC construction as the resume token // (docs/44 D8), with its own domain-separation prefix. RoomCreatorTokenSize = 16 // RoomKeySize is the byte length of a room's HMAC'd key as carried in // RoomState — the same 6-byte digest TelemetryHello carries for a // broadcast (TelemetryBroadcastKeySize), so telemetry keys both kinds // of object the same way. RoomKeySize = 6 // ResumeTokenSize is the byte length of a broadcast resume token // (R17 W2) as it appears inside a RoomCommand.Attach — the attach proof // (docs/44 D9). 128 bits of HMAC-SHA256. ResumeTokenSize = 16 )
Room protocol constants.
const ( RoomClientWebViewer = 0 RoomClientWebBroadcaster = 1 RoomClientNative = 2 )
RoomClientKind names what kind of client a participant is (RoomHello clientKind, Participant.kind).
const ( RoomCapChat = 0x01 RoomCapVoice = 0x02 )
Room capability bits (RoomHello wantCaps, RoomState caps). Both reserved for docs/44 §4.11's integrations; a v1 room advertises none.
const ( // RoomStateFlagDynamic is set for a dynamic room (clear: static). RoomStateFlagDynamic = 0x01 // RoomStateFlagCreator is set when the receiving participant presented // a valid creator token (may detach anyone, may end the room). RoomStateFlagCreator = 0x02 // RoomStateFlagAttachOK is set when the receiving participant is allowed // to attach (a dynamic room, or a static room whose attach secret was // presented or is unset). RoomStateFlagAttachOK = 0x04 )
RoomState flags.
const ( // RoomParticipantFlagSpeaking is reserved for the voice integration // (docs/44 §4.11) and carried from day one so the roster's speaking // indicator does not need a wire change later. RoomParticipantFlagSpeaking = 0x01 // RoomParticipantFlagStreaming is set while the participant has at least // one attached broadcast. RoomParticipantFlagStreaming = 0x02 )
Participant flags.
const ( RoomEventParticipantJoined = 0x01 RoomEventParticipantLeft = 0x02 RoomEventParticipantUpdated = 0x03 RoomEventAttachmentAdded = 0x10 RoomEventAttachmentRemoved = 0x11 RoomEventAttachmentUpdated = 0x12 RoomEventRoomEnding = 0x20 RoomEventCommandRejected = 0x30 )
RoomEvent kinds. 0x40–0x4F (chat) and 0x50–0x5F (voice) are reserved; a parser returns ErrUnknownRoomKind for any kind it does not know.
const ( RoomCommandAttach = 0x01 RoomCommandDetach = 0x02 RoomCommandSetNickname = 0x03 RoomCommandEndRoom = 0x04 RoomCommandResync = 0x05 )
RoomCommand kinds. Same reserved sub-ranges as events.
const ( RoomEndReasonEmpty = 1 RoomEndReasonCreator = 2 RoomEndReasonOperator = 3 )
RoomEndReason values (RoomEvent.RoomEnding).
const ( RoomDetachReasonPublisher = 0 RoomDetachReasonCreator = 1 RoomDetachReasonExpired = 2 RoomDetachReasonRoomEnd = 3 )
RoomDetachReason values (RoomEvent.AttachmentRemoved).
const ( // RoomRejectLimit: -max-room-broadcasts (or the CR's override) reached. RoomRejectLimit = 1 // RoomRejectBadProof: the attach resume token does not verify. RoomRejectBadProof = 2 // RoomRejectNotFound: the broadcast is unknown to the fleet, or the // attachment to detach does not exist. RoomRejectNotFound = 3 // RoomRejectForbidden: the participant lacks the grant (attach without // the attach secret, detach-other / end without the creator token). RoomRejectForbidden = 4 // RoomRejectAlreadyAttached: the broadcast is attached to another room // (D1: at most one room per broadcast). RoomRejectAlreadyAttached = 5 // RoomRejectUnsupported: the relay does not implement the command kind // (a reserved chat/voice command on a v1 relay). RoomRejectUnsupported = 6 // unreachable (docs/44 §6, fail closed). RoomRejectUnavailable = 7 )
RoomRejectReason values (RoomEvent.CommandRejected). Every distinct failure a command can hit crosses the wire as its own reason, never a catch-all (CODE-REVIEW.md "error mapping at boundaries").
const ( // StripeStateSize is the exact size of a StripeState datagram: // version, type, flags, stripeN, reserved. StripeStateSize = 5 // MaxStripeLegs bounds a viewer's stripe width. Evidence-bound, not // tuned: docs/34 finding 5 measured per-connection headroom at up to 4 // simultaneous connections and no further, and 4 legs at the burst // target of 6 chunks cover every delta frame size observed (~23 chunks // max). A constant, not a knob (docs/35 §11) — revisit only with a new // finding-5-shaped measurement at higher N. MaxStripeLegs = 4 )
const ( // TelemetrySessionTokenSize is the minted token length: 4-byte expiry // hour, 12-byte nonce, 8-byte tag. TelemetrySessionTokenSize = 24 // TelemetryNonceSize is the random part, and the sessionId's source. // 96 bits: collision-free across every session this fleet will ever carry, // and short enough that a sessionId stays a readable 24-char handle. TelemetryNonceSize = 12 // TelemetryTagSize truncates the HMAC to 64 bits. The token is not a // long-lived credential — it expires in a day and can only pollute the one // session it names — so 64 bits of forgery resistance is the right point // on the size/strength curve for a field that also rides a 35-byte // fixed-width wire message. TelemetryTagSize = 8 // TelemetrySessionIDLen is the hex length of a sessionId. TelemetrySessionIDLen = TelemetryNonceSize * 2 // TelemetryTokenTTL is how long a minted token stays valid. A day covers // every plausible broadcast; a token outliving its session is only good // for submitting records attributed to a session that already ended // (docs/33 §8 records the periodic-re-hello fix as deferred until a // broadcast actually outlives this). TelemetryTokenTTL = 24 * time.Hour // TelemetryKeySize is the fleet Secret's length, matching R17's statsKey / // resumeTokenKey / internalPsk shape. TelemetryKeySize = 32 )
const ( // TypeVideoChunk identifies a VideoChunk datagram. TypeVideoChunk = 0x01 // TypeDecoderConfig identifies a DecoderConfig datagram. TypeDecoderConfig = 0x02 // TypeBroadcastAnnounce identifies a BroadcastAnnounce message. TypeBroadcastAnnounce = 0x03 // TypeStreamFrame identifies a StreamFrame message. Unlike the others it // never travels as a datagram — it is the payload of a reliable // unidirectional stream carrying exactly one keyframe (R8, docs/12). TypeStreamFrame = 0x04 // TypeTimeSync identifies a TimeSync datagram (R5 Q2, docs/15): a // client↔relay clock-sync ping/pong. The client sends it with // serverTimeUs = 0; the relay echoes clientTimeUs and fills serverTimeUs // from its monotonic clock, giving the client an NTP-style offset + RTT // sample against the relay clock. TypeTimeSync = 0x05 // TypeClockMapping identifies a ClockMapping datagram (R5 Q2, docs/15): // broadcaster→viewers, relayed and cached by the hub like the keyframe // prime. It maps frame timestamps onto the relay clock // (relayClockUs = timestampUs + offsetUs) so a viewer holding its own // TimeSync offset can compute absolute capture→render latency. TypeClockMapping = 0x06 // TypeAudioFrame identifies an AudioFrame datagram (R15, docs/20 // Decision 2): broadcaster→viewers, one complete Opus packet per // datagram — audio has no keyframes, no chunking, and no reassembly. // seq is audio's own uint32 sequence space (independent of video // frameIDs, same serial arithmetic); timestampUs is on the broadcaster's // performance.now() µs clock, the same clock video capture stamps, so // A/V skew is a subtraction. TypeAudioFrame = 0x07 // TypeAudioConfig identifies an AudioConfig datagram (R15, docs/20): // broadcaster→viewers, relayed and cached by the hub like ClockMapping // (join-primed, invalidated on a new publisher session and on edge // upstream loss). Audio has no keyframe to anchor config re-emits to, so // the broadcaster re-sends it at 1 Hz; both paths are idempotent on the // viewer. TypeAudioConfig = 0x08 // TypeResumeToken identifies a ResumeToken message (R17 W2, docs/22 // Decision 7): server→publisher on its own unidirectional stream right // after the session upgrade (the browser WebTransport API exposes no // response headers, so delivery must be in-band). The token is what a // publisher presents (as the `resume` query param) to claim /publish/{id} // — reclaim of a graced hub AND claim of an ID unknown to the receiving // pod, which then creates the hub. Stateless HMAC: any pod can mint and // verify. Never sent by clients as a wire message. TypeResumeToken = 0x09 // TypeReliableCarrier identifies a reliable carrier stream (R19, docs/24 // Decision 3): the stream-kind discriminator byte of a relay→subscriber // unidirectional stream that conveys delta datagrams reliably to an // opted-in resilient subscriber. Never a datagram. The stream opens with // the two-byte prologue Version‖TypeReliableCarrier (a keyframe stream's // first two bytes are Version‖TypeStreamFrame, so a bare length prefix // would be ambiguous), followed by records of // uint16 length (BE) ‖ verbatim datagram bytes — each record a complete, // already-golden-vectored datagram the relay would otherwise have sent // via SendDatagram. The relay stays a byte forwarder: it never // reassembles frames for this path. TypeReliableCarrier = 0x0A // TypeViewerCount identifies a ViewerCount datagram (R18, docs/23 // Decision 2): only ever produced by a relay, reused in both directions // and disambiguated by which read loop receives it, exactly like // TimeSync's ping/pong. Downstream (relay→viewers and relay→publisher) // count is the broadcast's global viewer total G; upstream (edge→origin // over the internal subscribe session) count is that edge's local // external-subscriber count. Clients parse it and never send it — a // ViewerCount arriving where a client is the sender is dropped. TypeViewerCount = 0x0B // TypeDeliveryAck identifies a DeliveryAck datagram (R21, docs/26 // Decision 7a): relay→viewer, sent once at join, telling the subscriber // what it was ACTUALLY served. Delivery is negotiated by query param, and // R21's replayed GOPs are byte-identical on the wire to live ones — so // without this a viewer cannot tell an honoured request from a downgraded // one, or from a relay too old to know the parameter. That gap is the one // the 2026-07-22 investigation was lost in (BUGS.md); the R19 truthful // "reliable requested / datagrams served" row exists for the same reason // and extends naturally from this. Clients parse it and never send it. TypeDeliveryAck = 0x0C // TypeTelemetryHello identifies a TelemetryHello message (R28, docs/33 // D2): relay→client, sent once per session on its own reliable // unidirectional stream right after the upgrade — the ResumeToken (0x09) // precedent, chosen over DeliveryAck's datagram because a lost hello is a // session that silently never reports, and DeliveryAck's own re-announce // loop exists precisely because one-shot join-time datagrams get lost. // // It carries the three things a client cannot otherwise know: its // telemetry session token (the ingest credential AND the join key that // makes the relay's view of a viewer and the viewer's view of itself one // dataset), the OBFUSCATED broadcast key (so a client never reports a // joinable raw ID — R9 D3), and whether the fleet collects telemetry at // all and at what cadence. Never sent on /internal/subscribe: an edge is // plumbing, not a client. Clients parse it and never send it — a // TelemetryHello arriving where a client is the sender is dropped, // matching TypeViewerCount's rule. TypeTelemetryHello = 0x0D // TypeParityChunk identifies a ParityChunk datagram (R29, docs/34): // broadcaster→relay→viewers, carrying one RAID-6 P/Q parity symbol over // a delta frame's data chunks so a live-edge viewer can repair chunk // loss without the latency of R19's reliable carriers. // // Deltas only. Keyframes already ride reliable uni streams (R8), so they // are not exposed to datagram loss and carry no parity. // // The relay computes nothing: it forwards a per-subscriber PREFIX of the // symbols the producer emitted (parityIndex < subscriber's k), which is // what keeps it a byte forwarder and what makes the origin/edge cascade // work unchanged (docs/34 §5). TypeParityChunk = 0x0E // TypeRelayCapabilities identifies a RelayCapabilities message (R29, // docs/34 §4.4): relay→client, sent once per session at session start on // both routes, telling a producer which optional features this fleet // supports and at what level. // // It exists as its own message rather than as extra fields on // BroadcastAnnounce because the parsers are strict (appending bytes to an // existing message breaks old readers) and because the browser // WebTransport API exposes no HTTP response headers, so a capability // cannot ride the connect response. A producer that never sees it emits // no parity, which is what makes a new broadcaster against an old relay // byte-identical to pre-R29. Clients parse it and never send it. TypeRelayCapabilities = 0x0F // TypeStripeState identifies a StripeState datagram (R30, docs/35 §5.3): // client→relay, the ONE message a striping viewer sends on its primary // subscribe session to suppress (or restore) delta datagrams there while // stripe legs carry them. Level state re-sent at 1 Hz while striped; the // relay expires a stale suppression (StripeStateTTL) so a lost message // converges to duplicates, never holes. Accepted only on an external // datagram-delivery subscribe session that is not itself a leg — // anywhere else it is silently discarded like any unknown datagram. TypeStripeState = 0x10 // TypeRelayIdentity identifies a RelayIdentity message (R37, docs/40 // §4.4): relay→client on a server-opened unidirectional stream at // /echo session start, carrying the relay's release version and an // operator-set display name so a server picker can label a probed // relay. Echo-route only in R37 — publish/subscribe sessions stay // byte-identical. The browser WebTransport API exposes no response // headers (the ResumeToken/TelemetryHello precedent), so identity is // in-band. // // Deliberate deviation from house parser strictness (docs/40 §4.4, // stated there so it survives review): TRAILING BYTES ARE TOLERATED — // this message is the managed-mode extension point, and appended // fields are its extension mechanism. The flags byte stays strict // (reserved-must-be-zero): flags gate interpretation of what a parser // already reads, so an unknown flag genuinely is unparseable, unlike // appended fields. Clients parse it and never send it — a // RelayIdentity arriving where a client is the sender is dropped (the // ViewerCount rule). TypeRelayIdentity = 0x11 // TypeTelemetryEndpoint identifies a TelemetryEndpoint message (R37, // docs/40 §4.10 D14): relay→client on its own unidirectional stream on // publish/subscribe sessions, advertising the fleet's telemetry ingest // URL. It composes with the frozen 0x0D TelemetryHello (whose strict // exact-length parser cannot be extended without breaking every // existing reader — the RelayCapabilities append-trap); sent only when // the relay both collects telemetry and has an advertised URL // configured, and never on /internal/subscribe (an edge is plumbing, // not a client). A relay-advertised URL always wins over the client's // configured telemetry URL (docs/40 D15). Same trailing-bytes // tolerance and strict flags byte as RelayIdentity, same // never-sent-by-clients rule. TypeTelemetryEndpoint = 0x12 )
Message types, occupying byte 1 of every datagram (or, for TypeStreamFrame, byte 1 of a unidirectional-stream payload).
const ( // MaxDatagramSize is the largest datagram we ever produce. It is chosen // conservatively below typical QUIC datagram MTU limits. MaxDatagramSize = 1200 // VideoChunkHeaderSize is the fixed size of a VideoChunk header, // including the common 2-byte version/type prefix. VideoChunkHeaderSize = 20 // MaxChunkPayload is the largest payload a single VideoChunk may carry. MaxChunkPayload = MaxDatagramSize - VideoChunkHeaderSize // MaxChunkCount is the maximum number of chunks permitted in a keyframe // to prevent memory inflation attacks. MaxChunkCount = 3000 // StreamFrameHeaderSize is the fixed size of a StreamFrame header (R8). StreamFrameHeaderSize = 24 // MaxKeyframeBytes is the absolute ceiling on a single StreamFrame message // (header + config + payload). It is the stream analogue of MaxChunkCount: // a reader must never allocate a keyframe buffer larger than this from an // untrusted length field. The hub's configurable cap defaults to it. MaxKeyframeBytes = 8 << 20 // 8 MiB // TimeSyncSize is the exact size of a TimeSync datagram (R5 Q2). TimeSyncSize = 18 // ClockMappingSize is the exact size of a ClockMapping datagram (R5 Q2). ClockMappingSize = 10 // ViewerCountSize is the exact size of a ViewerCount datagram (R18). ViewerCountSize = 6 // CarrierPrologueSize is the size of the reliable-carrier stream prologue // (Version + TypeReliableCarrier), written once when the stream opens. CarrierPrologueSize = 2 // CarrierRecordHeaderSize is the size of the uint16 length prefix in front // of every carrier record. CarrierRecordHeaderSize = 2 // AudioFrameHeaderSize is the fixed size of an AudioFrame header (R15), // including the common 2-byte version/type prefix. AudioFrameHeaderSize = 16 // TelemetryHelloSize is the exact size of a TelemetryHello message (R28). TelemetryHelloSize = 35 // TelemetryBroadcastKeySize is the byte length of the obfuscated broadcast // key a TelemetryHello carries — the raw digest behind Registry.ObfuscateID, // which the client hex-encodes for the ingest envelope. TelemetryBroadcastKeySize = 6 // MaxRelayIdentityVersionLen / MaxRelayIdentityNameLen bound the two // variable fields of a RelayIdentity (R37): a release version is a short // ASCII string, and the display name cap is enforced AFTER UTF-8 // validation with rune-boundary truncation on the producing side // (docs/40 §4.4 F6). MaxRelayIdentityVersionLen = 32 MaxRelayIdentityNameLen = 64 // MaxTelemetryEndpointURLLen bounds a TelemetryEndpoint's advertised // ingest URL (R37, docs/40 §4.10) — generous for any real ingress path, // small enough that a hostile relay cannot stuff kilobytes into it. MaxTelemetryEndpointURLLen = 512 // MaxAudioPayload is the largest payload a single AudioFrame may carry — // one Opus packet. 20 ms at 128 kbps is ~320 bytes; anything up to // ~470 kbps fits, so a conforming encoder never comes near this. MaxAudioPayload = MaxDatagramSize - AudioFrameHeaderSize )
Size constants for the wire format.
const CloseCodeBroadcastEnded = 4000
CloseCodeBroadcastEnded is the WebTransport application close code sent to subscribers when their broadcast is garbage-collected.
const CloseCodeOriginMoved = 4003
CloseCodeOriginMoved is sent on INTERNAL edge sessions only (R17 W5, docs/22 Decision 11): the origin lost its Lease (force-take — the broadcaster re-homed) and is demoting itself. The Go edge client re-resolves the lease on any close; 4003 exists for log clarity, never for browsers.
const CloseCodePublisherSuperseded = 4004
CloseCodePublisherSuperseded is sent to a publisher session when a newer session claims its broadcast ID with a verified resume token (docs/06 revision 2026-07-18). The relay cannot tell a silently-dead publisher from a live one inside the QUIC idle window, so a token-bearing claim that completes its upgrade deposes the incumbent — newest publisher wins, the same-pod counterpart of R17 W3's force-take of the origin Lease. In practice this lands on the broadcaster's own zombie session; a live client receiving it has been replaced and must NOT auto-resume back (terminal for resume, like CloseCodeBroadcastEnded is for viewers).
const CloseCodeRoomEnded = 4007
CloseCodeRoomEnded (4007) is sent on a room CONTROL session when the room ends: empty-grace expiry, an explicit end from a creator-token holder, or deletion of the Room CR by the operator (docs/44 §4.4). TERMINAL for the room session only — a client must not reconnect to the room — while the participant's media sessions have their own lifecycle and are untouched (D1: attached broadcasts keep streaming to anyone watching them directly). Never sent on a publish or subscribe session. Allocated 2026-09-03 (R42).
const CloseCodeServerDraining = 4002
CloseCodeServerDraining is sent to every open session when the relay drains on SIGTERM (R17 W1, docs/22 Decision 2): the pod is shutting down for a planned rollout while still Ready, so its conntrack entries still point at it and the close frame actually reaches the peer. Non-terminal and explicitly fast: clients reconnect immediately (0 ms first retry) — a ready replacement pod is behind the same Service by construction.
const CloseCodeStripeLegOrphaned = 4005
CloseCodeStripeLegOrphaned is sent to an R30 stripe-leg session the relay reaps because its owner is gone (docs/35 §14): the primary session sharing its ?owner= token ended (eviction, clean close, or abrupt death), or the leg's liveness lease expired with no inbound datagram. NOT terminal — the leg-death fallback applies (the viewer unstripes and re-engages through a fresh session set), exactly as for any other leg death. Never sent to a primary or any non-leg session.
const CloseCodeSubscriberUnresponsive = 4001
CloseCodeSubscriberUnresponsive is sent when the relay evicts a subscriber whose keyframe stream opens fail persistently (R10, docs/14 — typically a session whose client stopped reading uni streams and exhausted its stream credit). Unlike CloseCodeBroadcastEnded it is NOT terminal for a live client: the viewer's reconnect policy retries, and a fresh session restores the stream credit.
const CloseCodeTerminatedByOperator = 4006
CloseCodeTerminatedByOperator (4006) is sent when the operator (or, later, the R40 auto-tier) terminates a broadcast: to the publisher session being killed, to every viewer of that broadcast, and to internal edge sessions so downstream pods tear down too. TERMINAL in every role: a viewer must not reconnect, a publisher must not auto-resume — the ID is banned for at least the kill cooldown, so a resume attempt would only burn the 451 rejection budget. Allocated 2026-08-20 (R39, docs/42).
const DeliveryAckSize = 5
DeliveryAckSize is the exact size of a DeliveryAck datagram: version, type, mode, then the accepted buffer in ms (big-endian uint16).
const ( // RoomAttachmentFlagLive is set while the broadcast's publisher session // is up; clear means "broadcaster away" (within the broadcast grace). RoomAttachmentFlagLive = 0x01 )
Attachment flags.
const Version = 0x01
Version is the only wire protocol version currently defined. It occupies byte 0 of every datagram.
Variables ¶
var ( // ErrParityUnsupported reports a frame shape parity cannot cover. ErrParityUnsupported = errors.New("wire: parity unsupported for this frame") // ErrParityUnrecoverable reports more erasures than the parity present // can repair. It is an expected outcome on a lossy link, not a fault. ErrParityUnrecoverable = errors.New("wire: too many erasures to recover") )
var ( // ErrBadRoomRecord indicates a room record whose length prefix is zero // or exceeds MaxRoomRecordSize. ErrBadRoomRecord = errors.New("wire: invalid room record") // ErrBadRoomHello indicates a RoomHello that fails validation. ErrBadRoomHello = errors.New("wire: invalid room hello") // ErrBadRoomState indicates a RoomState that fails validation. ErrBadRoomState = errors.New("wire: invalid room state") // ErrBadRoomEvent indicates a RoomEvent that fails validation. ErrBadRoomEvent = errors.New("wire: invalid room event") // ErrBadRoomCommand indicates a RoomCommand that fails validation. ErrBadRoomCommand = errors.New("wire: invalid room command") // ErrUnknownRoomKind indicates a RoomEvent or RoomCommand of a kind this // implementation does not know — the docs/44 §4.11 reserved ranges. A // reader skips the record; a relay answers RoomRejectUnsupported. ErrUnknownRoomKind = errors.New("wire: unknown room event/command kind") )
Sentinel errors for the room protocol.
var ( // ErrTelemetryTokenInvalid covers every malformed or unauthentic token: // wrong length, bad hex, unknown role, tampered broadcast key, wrong // fleet key. Deliberately one error — an attacker learns nothing from // which check failed, and no caller behaves differently. ErrTelemetryTokenInvalid = errors.New("wire: invalid telemetry token") // ErrTelemetryTokenExpired is separate because it IS actionable: a client // holding one needs a fresh hello, not a bug report. ErrTelemetryTokenExpired = errors.New("wire: expired telemetry token") // ErrTelemetryKey indicates a fleet key that is not TelemetryKeySize // bytes. Minting with a short key would produce tokens the verifier // silently accepts under an equally short key, so it fails loudly. ErrTelemetryKey = errors.New("wire: invalid telemetry key") )
Sentinel errors from the token functions. Check with errors.Is.
var ( // ErrShortDatagram indicates the datagram is too small to contain the // expected header. ErrShortDatagram = errors.New("wire: datagram too short") // ErrBadVersion indicates byte 0 is not Version. ErrBadVersion = errors.New("wire: unsupported version") // ErrBadType indicates byte 1 is not the expected message type. ErrBadType = errors.New("wire: unexpected message type") // ErrBadChunkCount indicates chunkCount == 0 or chunkIndex >= chunkCount. ErrBadChunkCount = errors.New("wire: invalid chunk index/count") // ErrPayloadTooLarge indicates a VideoChunk payload exceeds MaxChunkPayload. ErrPayloadTooLarge = errors.New("wire: payload exceeds MaxChunkPayload") // ErrBadCodec indicates a DecoderConfig codec string that is empty, // longer than 255 bytes, or (on parse) overruns the datagram. ErrBadCodec = errors.New("wire: invalid codec string") // ErrDatagramTooLarge indicates an encoded datagram would exceed // MaxDatagramSize. ErrDatagramTooLarge = errors.New("wire: datagram exceeds MaxDatagramSize") // ErrBadBroadcastID indicates a BroadcastAnnounce message with an invalid ID. ErrBadBroadcastID = errors.New("wire: invalid broadcast ID") // ErrKeyframeTooLarge indicates a StreamFrame whose declared or actual // size exceeds MaxKeyframeBytes. ErrKeyframeTooLarge = errors.New("wire: keyframe exceeds MaxKeyframeBytes") // ErrBadLength indicates a fixed-size message (TimeSync, ClockMapping) // whose length is not exactly the expected size. ErrBadLength = errors.New("wire: unexpected message length") // ErrBadResumeToken indicates a ResumeToken message with an invalid // (empty, oversized, or length-mismatched) token. ErrBadResumeToken = errors.New("wire: invalid resume token") // ErrBadCarrierRecord indicates a carrier record whose declared length is // zero or exceeds MaxDatagramSize (R19) — records carry verbatim // datagrams, so any other length is a framing corruption. ErrBadCarrierRecord = errors.New("wire: invalid carrier record") // ErrBadAudioPayload indicates an AudioFrame payload that is empty or // exceeds MaxAudioPayload (R15) — a datagram carries exactly one Opus // packet, and there is no such thing as a zero-byte one (DTX is off). ErrBadAudioPayload = errors.New("wire: invalid audio payload") // ErrBadAudioConfig indicates an AudioConfig with a zero sample rate or // zero channels (R15). ErrBadAudioConfig = errors.New("wire: invalid audio config") // ErrBadTelemetryHello indicates a TelemetryHello whose token or broadcast // key is the wrong length, or which sets a reserved flag bit (R28). ErrBadTelemetryHello = errors.New("wire: invalid telemetry hello") // ErrBadRelayIdentity indicates a RelayIdentity with a set reserved flag // bit, an out-of-range version/name length, a non-printable version, or // a name that is not valid UTF-8 (R37). ErrBadRelayIdentity = errors.New("wire: invalid relay identity") // ErrBadTelemetryEndpoint indicates a TelemetryEndpoint with a set // reserved flag bit, an out-of-range URL length, or a URL that is not an // absolute https URL (R37). ErrBadTelemetryEndpoint = errors.New("wire: invalid telemetry endpoint") )
Sentinel errors returned (possibly wrapped) by the parse and append functions. Check with errors.Is.
var ErrBadSessionClosing = errors.New("wire: invalid session closing")
ErrBadSessionClosing indicates a SessionClosing message of the wrong size or carrying a code outside the gawk range.
Functions ¶
func AppendAudioConfig ¶
func AppendAudioConfig(dst []byte, c AudioConfig) ([]byte, error)
AppendAudioConfig appends an AudioConfig datagram (R15) to dst and returns the extended slice. Layout: version, type 0x08, reserved (0), uint8 codecLen, codec bytes, uint32 sampleRate, uint8 channels, then the description (may be empty). It returns ErrBadCodec for an empty or oversize codec string, ErrBadAudioConfig for a zero sample rate or zero channels, and ErrDatagramTooLarge if the encoded datagram would exceed MaxDatagramSize.
func AppendAudioFrame ¶
func AppendAudioFrame(dst []byte, h AudioFrameHeader, payload []byte) ([]byte, error)
AppendAudioFrame appends an AudioFrame datagram (R15) to dst and returns the extended slice. Layout: version, type 0x07, flags (0), reserved (0), uint32 seq, uint64 timestampUs, then the payload — exactly one Opus packet. It returns ErrBadAudioPayload if the payload is empty or exceeds MaxAudioPayload.
func AppendBroadcastAnnounce ¶
AppendBroadcastAnnounce appends a BroadcastAnnounce message encoding ID to dst and returns the extended slice.
func AppendCarrierPrologue ¶
AppendCarrierPrologue appends the two-byte reliable-carrier stream prologue (R19): Version, then TypeReliableCarrier. Written exactly once per carrier stream, before the first record.
func AppendCarrierRecord ¶
AppendCarrierRecord appends one carrier record (uint16 big-endian length, then the datagram verbatim) to dst and returns the extended slice. It returns ErrBadCarrierRecord for an empty datagram or one exceeding MaxDatagramSize — the record framing carries exactly what SendDatagram would have.
func AppendClockMapping ¶
AppendClockMapping appends a ClockMapping datagram to dst and returns the extended slice (R5 Q2). offsetUs is signed: relayClockUs = frame timestampUs + offsetUs (two's complement wraparound intended on both sides).
func AppendDecoderConfig ¶
func AppendDecoderConfig(dst []byte, c DecoderConfig) ([]byte, error)
AppendDecoderConfig appends a DecoderConfig datagram encoding c to dst and returns the extended slice. It returns an error if the codec string is empty or longer than 255 bytes, or if the encoded datagram would exceed MaxDatagramSize.
func AppendDeliveryAck ¶
func AppendDeliveryAck(dst []byte, mode DeliveryMode, bufferMs uint16) []byte
AppendDeliveryAck appends a DeliveryAck datagram (R21) to dst. bufferMs is the buffer the relay accepted after clamping — 0 whenever mode is not DeliveryDVR, since no other mode has one.
func AppendParityChunk ¶
func AppendParityChunk(dst []byte, h ParityChunkHeader, payload []byte) ([]byte, error)
AppendParityChunk appends a ParityChunk datagram to dst.
func AppendRelayCapabilities ¶
func AppendRelayCapabilities(dst []byte, c RelayCapabilities) ([]byte, error)
AppendRelayCapabilities appends a RelayCapabilities message to dst.
func AppendRelayIdentity ¶ added in v0.25.0
func AppendRelayIdentity(dst []byte, id RelayIdentity) ([]byte, error)
AppendRelayIdentity appends a RelayIdentity message encoding id to dst and returns the extended slice. It returns ErrBadRelayIdentity for an empty or oversize version, a non-printable-ASCII version, an oversize name, or a name that is not valid UTF-8.
func AppendResumeToken ¶
AppendResumeToken appends a ResumeToken message (R17 W2) to dst and returns the extended slice. Layout: version, type 0x09, uint8 tokenLen, then the token bytes. The token is opaque on the wire (the server mints truncated HMACs, but the format doesn't care).
func AppendRoomCommand ¶ added in v0.27.0
func AppendRoomCommand(dst []byte, c RoomCommand) ([]byte, error)
AppendRoomCommand appends a RoomCommand message encoding c to dst.
func AppendRoomEvent ¶ added in v0.27.0
AppendRoomEvent appends a RoomEvent message encoding e to dst. Unknown kinds are refused with ErrUnknownRoomKind: a relay only emits what it implements.
func AppendRoomHello ¶ added in v0.27.0
AppendRoomHello appends a RoomHello message encoding h to dst.
func AppendRoomRecord ¶ added in v0.27.0
AppendRoomRecord frames one already-encoded room message (Version ‖ Type ‖ payload, as produced by the AppendRoom* functions) as a length-prefixed record for a room control stream.
func AppendRoomState ¶ added in v0.27.0
AppendRoomState appends a RoomState message encoding s to dst.
func AppendSessionClosing ¶ added in v0.29.1
AppendSessionClosing appends a SessionClosing message for code to dst and returns the extended slice.
func AppendStreamFrameHeader ¶
func AppendStreamFrameHeader(dst []byte, h StreamFrameHeader) ([]byte, error)
AppendStreamFrameHeader appends the 24-byte StreamFrame header encoding h to dst and returns the extended slice. Reserved bits are written as 0. It returns ErrKeyframeTooLarge if the declared total (header + config + payload) exceeds MaxKeyframeBytes.
func AppendStripeState ¶
func AppendStripeState(dst []byte, s StripeState) ([]byte, error)
AppendStripeState appends a StripeState datagram to dst.
func AppendTelemetryEndpoint ¶ added in v0.25.0
AppendTelemetryEndpoint appends a TelemetryEndpoint message (R37, docs/40 §4.10) to dst and returns the extended slice. Layout after the common prefix: uint8 flags (0), uint16 urlLen (big-endian), then urlLen bytes of an absolute https URL. It returns ErrBadTelemetryEndpoint for an empty, oversize, non-https, or unparseable URL.
func AppendTelemetryHello ¶
func AppendTelemetryHello(dst []byte, h TelemetryHello) ([]byte, error)
AppendTelemetryHello appends a TelemetryHello message encoding h to dst and returns the extended slice. It returns ErrBadTelemetryHello if the token or broadcast key is not exactly its fixed size — both are fixed-width fields, so a wrong length is a bug on the minting side, never a truncation to paper over.
func AppendTimeSync ¶
AppendTimeSync appends a TimeSync datagram to dst and returns the extended slice (R5 Q2). clientTimeUs is the requester's clock at send (echoed back by the relay); serverTimeUs is the relay's monotonic clock in replies and 0 in requests.
func AppendVideoChunk ¶
func AppendVideoChunk(dst []byte, h VideoChunkHeader, payload []byte) ([]byte, error)
AppendVideoChunk appends a VideoChunk datagram encoding h and payload to dst and returns the extended slice. It returns an error if payload exceeds MaxChunkPayload, h.ChunkCount is 0, or h.ChunkIndex >= h.ChunkCount. Reserved header bits are written as 0.
func AppendViewerCount ¶
AppendViewerCount appends a ViewerCount datagram (R18, docs/23) to dst and returns the extended slice. count is uint32 by convention with the codebase's frameID/counter integers — deliberate overkill for the audience sizes involved, zero doubt about overflow.
func ComputeParity ¶
ComputeParity returns min(k, len(chunks)) parity symbols over chunks, each as long as the longest chunk (shorter chunks are treated as zero-padded). k == 0 returns nil. Chunks are not modified.
func MintTelemetrySessionToken ¶
func MintTelemetrySessionToken(key []byte, broadcastKey []byte, role TelemetryRole, now time.Time) ([]byte, error)
MintTelemetrySessionToken mints a token for one session, using crypto/rand for the nonce. broadcastKey is the raw obfuscated-ID digest (TelemetryBroadcastKeySize bytes) — never the joinable broadcast ID.
func ParseBroadcastAnnounce ¶
ParseBroadcastAnnounce parses a BroadcastAnnounce message. It returns an error if the message is shorter than 3 bytes, has the wrong version or type, or if the ID length is invalid or characters are outside the alphabet.
func ParseCarrierPrologue ¶
ParseCarrierPrologue validates the two-byte carrier prologue at the start of buf. Like ParseStreamFrameHeader it does not require buf to hold anything beyond the prologue — records follow on the stream.
func ParseCarrierRecord ¶
ParseCarrierRecord parses one carrier record at the start of buf, returning the record's datagram bytes (aliasing buf) and the remainder after it. An incomplete record returns ErrShortDatagram (the caller reads more from the stream); a zero or oversize declared length returns ErrBadCarrierRecord (framing corruption — the caller must abandon the stream).
func ParseClockMapping ¶
ParseClockMapping parses a ClockMapping datagram. Strict: the datagram must be exactly ClockMappingSize bytes with the right version and type.
func ParseResumeToken ¶
ParseResumeToken parses a ResumeToken message. Strict: the declared token length must account for the entire message. The returned slice aliases msg.
func ParseRoomRecordLength ¶ added in v0.27.0
ParseRoomRecordLength validates a room record's length prefix and returns the framed message length. It exists so a stream reader never allocates from an unvalidated length.
func ParseSessionClosing ¶ added in v0.29.1
ParseSessionClosing parses a SessionClosing message and returns its code.
func ParseTelemetryEndpoint ¶ added in v0.25.0
ParseTelemetryEndpoint parses a TelemetryEndpoint message. Same parser stance as RelayIdentity: strict flags, tolerated trailing bytes, and the URL must validate (absolute, https, parseable) — a message that fails here degrades client-side to "no advertised URL", never to a failed session.
func ParseTimeSync ¶
ParseTimeSync parses a TimeSync datagram. Strict: the datagram must be exactly TimeSyncSize bytes with the right version and type.
func ParseViewerCount ¶
ParseViewerCount parses a ViewerCount datagram. Strict: the datagram must be exactly ViewerCountSize bytes with the right version and type.
func PeekType ¶
PeekType reports the version and message type bytes of a datagram without validating them; parsers perform validation. It returns an error only if the datagram is shorter than the 2-byte common prefix.
func RecoverChunks ¶
RecoverChunks reconstructs missing data chunks in place. A nil entry in chunks or parity means "not received". frameBytes is the total encoded frame length, which is the only thing that says how long the final (short) chunk is.
The symbol width is taken from a surviving parity symbol, not inferred: every parity symbol is exactly as long as the longest data chunk, and a parity symbol is present whenever recovery is possible at all.
Returns ErrParityUnrecoverable when there are more data erasures than usable parity symbols. That is a routine outcome on a lossy link and the caller is expected to count it, not treat it as a fault.
func StripeOrdinal ¶
StripeOrdinal returns the stripe ordinal of a delta datagram: data chunk i has ordinal i, parity symbol r over an n-chunk frame has ordinal n+r. Leg j of stripe N carries the datagrams with StripeOrdinal % N == j.
func TelemetrySessionID ¶
TelemetrySessionID returns the sessionId a token names, without verifying it. Only for the minting side, which just authenticated the token by construction — an ingest path must use VerifyTelemetrySessionToken, whose sessionId is the authenticated one.
func ValidTelemetryRole ¶
func ValidTelemetryRole(r TelemetryRole) bool
ValidTelemetryRole reports whether r is a role this build knows. The ingest checks it before verifying, so an unknown role is a 400 rather than a mysterious tag mismatch.
func VerifyTelemetrySessionToken ¶
func VerifyTelemetrySessionToken(key, token, broadcastKey []byte, role TelemetryRole, now time.Time) (string, error)
VerifyTelemetrySessionToken checks a token against the fleet key, the broadcast key and the role it claims, and returns the sessionId it names. Constant-time; expiry is checked before the tag so an expired-but-authentic token reports the actionable error.
Types ¶
type AudioConfig ¶
type AudioConfig struct {
// Codec is the WebCodecs codec string, e.g. "opus". Always 1-255 bytes
// on the wire.
Codec string
// SampleRate is the capture sample rate in Hz (48000 for opus).
SampleRate uint32
// Channels is the channel count (2 for the stereo default).
Channels uint8
// Description is codec-specific configuration. Empty for opus. When
// produced by ParseAudioConfig it aliases the input datagram.
Description []byte
}
AudioConfig is the parsed contents of an AudioConfig datagram (R15).
func ParseAudioConfig ¶
func ParseAudioConfig(dgram []byte) (AudioConfig, error)
ParseAudioConfig parses an AudioConfig datagram. The returned Description aliases dgram (no copy). Strict: it returns an error if the datagram is shorter than its declared layout, has the wrong version or type, has an empty codec string, or declares a zero sample rate or zero channels.
type AudioFrameHeader ¶
type AudioFrameHeader struct {
// Seq is audio's own uint32 sequence space, monotonic per publisher
// session and independent of video frameIDs. Consumers compare with the
// same serial arithmetic as frameIDs (wrap-aware).
Seq uint32
// TimestampUs is the packet timestamp in microseconds on the
// broadcaster's performance.now() clock — the same clock video capture
// stamps, which is what makes A/V skew a subtraction.
TimestampUs uint64
}
AudioFrameHeader is the parsed header of an AudioFrame datagram (R15).
func ParseAudioFrame ¶
func ParseAudioFrame(dgram []byte) (h AudioFrameHeader, payload []byte, err error)
ParseAudioFrame parses an AudioFrame datagram. The returned payload aliases dgram (no copy). Strict: it returns an error if the datagram is shorter than AudioFrameHeaderSize, has the wrong version or type, or carries an empty payload (there is no zero-byte Opus packet).
type DecoderConfig ¶
type DecoderConfig struct {
// Codec is the WebCodecs codec string, e.g. "avc1.42E02A". Always 1-255
// bytes on the wire.
Codec string
// Extradata is codec-specific configuration (e.g. AVCC bytes for H.264).
// May be empty (VP8/VP9). When produced by ParseDecoderConfig it aliases
// the input datagram.
Extradata []byte
}
DecoderConfig is the parsed contents of a DecoderConfig datagram.
func ParseDecoderConfig ¶
func ParseDecoderConfig(dgram []byte) (DecoderConfig, error)
ParseDecoderConfig parses a DecoderConfig datagram. The returned Extradata aliases dgram (no copy), consistent with ParseVideoChunk. It returns an error if the datagram is shorter than 4 bytes, has the wrong version or type, or if codecLen overruns the datagram or is zero.
type DeliveryMode ¶
type DeliveryMode uint8
DeliveryMode names what a subscriber is actually being served, as carried by DeliveryAck. Values are wire-visible: append, never renumber.
const ( // DeliveryDatagrams is the default live-edge path: unreliable datagrams. // Also what a viewer is told when it asked for more and was refused. DeliveryDatagrams DeliveryMode = 0 // DeliveryReliable is R19 carrier delivery without a DVR ring. DeliveryReliable DeliveryMode = 1 // DeliveryDVR is R21: carrier delivery served from the broadcast's ring // at this subscriber's own cursor. DeliveryDVR DeliveryMode = 2 )
func ParseDeliveryAck ¶
func ParseDeliveryAck(dgram []byte) (mode DeliveryMode, bufferMs uint16, err error)
ParseDeliveryAck parses a DeliveryAck datagram. Strict, like every other parser here: exact length, right version and type, and a mode this build knows. An unknown mode is an error rather than a silent fallback — a viewer that cannot name what it was served is the gap this message closes.
type ParityChunkHeader ¶
type ParityChunkHeader struct {
FrameID uint32
ParityIndex uint8 // 0 = P, 1 = Q
ChunkCount uint16 // n, the DATA chunk count of the frame
FrameBytes uint32 // total encoded frame length
}
ParityChunkHeader is the header of a ParityChunk datagram.
func ParseParityChunk ¶
func ParseParityChunk(dgram []byte) (h ParityChunkHeader, payload []byte, err error)
ParseParityChunk parses a ParityChunk datagram. The returned payload aliases dgram (no copy).
type RelayCapabilities ¶
type RelayCapabilities struct {
Flags uint16
ParityLevel uint8 // the fleet parity level producers should emit
}
RelayCapabilities is what the relay tells a client about optional features it supports, sent once per session at session start on both routes.
It is a separate message rather than extra fields on BroadcastAnnounce for two reasons already settled elsewhere: the parsers are strict, so appending bytes to an existing message breaks old readers; and the browser WebTransport API exposes no HTTP response headers, so a capability cannot ride the connect response (docs/34 §4.4).
func ParseRelayCapabilities ¶
func ParseRelayCapabilities(b []byte) (RelayCapabilities, error)
ParseRelayCapabilities parses a RelayCapabilities message.
type RelayIdentity ¶ added in v0.25.0
type RelayIdentity struct {
// ServerVersion is the relay's release version string, e.g. "1.42.0".
ServerVersion string
// Name is the operator-set display name (-server-name), possibly empty.
// Attacker-influenced trust UI: renderers sanitize and never show it in
// place of the host (docs/40 §4.4 F6).
Name string
}
RelayIdentity is the parsed contents of a RelayIdentity message (R37, docs/40 §4.4). Layout, after the common prefix:
byte 2 uint8 flags — all bits reserved, must be 0
byte 3 uint8 versionLen (1–MaxRelayIdentityVersionLen), then that many
bytes of printable-ASCII release version ("1.42.0")
next uint8 nameLen (0–MaxRelayIdentityNameLen), then that many bytes
of valid UTF-8 operator display name (empty = unset)
rest reserved extension bytes — ignored by parsers (see the type
constant's doc comment for why this deviates from house
strictness)
func ParseRelayIdentity ¶ added in v0.25.0
func ParseRelayIdentity(msg []byte) (RelayIdentity, error)
ParseRelayIdentity parses a RelayIdentity message. Trailing bytes beyond the name are IGNORED — they are the message's reserved extension space (docs/40 §4.9) — but the flags byte is strict (reserved bits must be 0) and the declared version/name must fit inside msg and pass validation.
type RoomAttachment ¶ added in v0.27.0
RoomAttachment is one attached broadcast as carried in RoomState and the attachment events.
type RoomCommand ¶ added in v0.27.0
type RoomCommand struct {
Kind uint8
// BroadcastID is set for Attach / Detach.
BroadcastID string
// ResumeToken is the attach proof (Attach only), exactly ResumeTokenSize
// bytes. Aliases the input record on parse.
ResumeToken []byte
// Label is the attachment label (Attach only).
Label string
// Nickname is the new nickname (SetNickname only).
Nickname string
}
RoomCommand is the parsed contents of a RoomCommand record.
func ParseRoomCommand ¶ added in v0.27.0
func ParseRoomCommand(msg []byte) (RoomCommand, error)
ParseRoomCommand parses a RoomCommand message. The returned ResumeToken aliases msg. An unknown kind returns ErrUnknownRoomKind with Kind filled in, so the relay can answer RoomRejectUnsupported.
type RoomEvent ¶ added in v0.27.0
type RoomEvent struct {
Seq uint32
Kind uint8
// Participant is set for ParticipantJoined / ParticipantUpdated; only
// its ID for ParticipantLeft.
Participant RoomParticipant
// Attachment is set for AttachmentAdded / AttachmentUpdated; only its
// BroadcastID for AttachmentRemoved.
Attachment RoomAttachment
// Reason is the RoomEndReason* (RoomEnding), RoomDetachReason*
// (AttachmentRemoved) or RoomRejectReason* (CommandRejected).
Reason uint8
// Command is the rejected command's kind (CommandRejected).
Command uint8
// Message is the human-readable rejection detail (CommandRejected).
Message string
}
RoomEvent is the parsed contents of a RoomEvent record. Which fields are meaningful depends on Kind (see the layout comment at the top of the file).
func ParseRoomEvent ¶ added in v0.27.0
ParseRoomEvent parses a RoomEvent message. An unknown kind (including the reserved chat/voice ranges) returns ErrUnknownRoomKind with the Seq and Kind filled in, so a reader can skip it without losing its place in the sequence.
type RoomHello ¶ added in v0.27.0
type RoomHello struct {
// Protocol is the room protocol version; RoomProtocolVersion today.
Protocol uint8
// ClientKind is one of the RoomClient* constants.
ClientKind uint8
// WantCaps is the requested RoomCap* bitmap (0 in v1 clients).
WantCaps uint8
// Nickname is the requested display name; may be empty (the relay then
// assigns one).
Nickname string
}
RoomHello is the parsed contents of a RoomHello record.
func ParseRoomHello ¶ added in v0.27.0
ParseRoomHello parses a RoomHello message. Strict: exact length, known protocol version and client kind, reserved capability bits zero.
type RoomParticipant ¶ added in v0.27.0
type RoomParticipant struct {
ID uint16
Kind uint8
Flags uint8
Nickname string
// Identity is reserved (docs/44 §4.11); empty in v1.
Identity string
}
RoomParticipant is one participant as carried in RoomState and the participant events.
type RoomState ¶ added in v0.27.0
type RoomState struct {
Flags uint8
Caps uint8
Seq uint32
YourID uint16
Code string
DisplayName string
CreatorToken []byte
// Key is the room's HMAC'd handle (RoomKeySize bytes) or empty when
// the relay has none to give.
Key []byte
Attachments []RoomAttachment
Participants []RoomParticipant
}
RoomState is the parsed contents of a RoomState record.
func ParseRoomState ¶ added in v0.27.0
ParseRoomState parses a RoomState message. The returned CreatorToken and Key alias msg (no copy, like every other parser here): a caller that keeps the state past the record buffer's lifetime must copy them. Strict: exact length, reserved bits zero.
type StreamFrameHeader ¶
type StreamFrameHeader struct {
// Keyframe is true if this stream frame is a keyframe (always true for
// now; the flag is reserved so future non-keyframe stream frames stay
// distinguishable).
Keyframe bool
// FrameID identifies the encoded frame, monotonic per publisher session,
// shared with the datagram VideoChunk numbering so the viewer can order
// keyframes (streams) against deltas (datagrams).
FrameID uint32
// TimestampUs is the frame timestamp in microseconds.
TimestampUs uint64
// ConfigLen is the byte length of the embedded DecoderConfig datagram
// that follows the header (0 if none).
ConfigLen uint32
// PayloadLen is the byte length of the encoded keyframe that follows the
// config block.
PayloadLen uint32
}
StreamFrameHeader is the parsed 24-byte header of a StreamFrame message (R8, docs/12). A StreamFrame is the entire payload of one unidirectional stream: this header, then ConfigLen bytes of an embedded DecoderConfig datagram (its 0x01/0x02 prefix included, or empty when ConfigLen == 0), then PayloadLen bytes of the raw encoded keyframe.
func ParseStreamFrameHeader ¶
func ParseStreamFrameHeader(buf []byte) (StreamFrameHeader, error)
ParseStreamFrameHeader parses the 24-byte StreamFrame header at the start of buf. It validates version and type and rejects a declared total that exceeds MaxKeyframeBytes, but does not require buf to contain the whole message — the caller reads ConfigLen + PayloadLen further bytes from the stream. It returns an error if buf is shorter than StreamFrameHeaderSize, has the wrong version or type, or declares more than MaxKeyframeBytes.
type StripeState ¶
type StripeState struct {
// Striped reports whether delta datagrams should be suppressed on the
// session this message arrived on.
Striped bool
// StripeN is the viewer's current stripe width, informational (for
// /statusz and metrics — the relay's own behavior never depends on it).
// In [1, MaxStripeLegs] when Striped, 0 otherwise.
StripeN uint8
}
StripeState is the primary-suppression signal (R30, docs/35 §5.3): client→relay, datagram, valid only on an external datagram-delivery subscribe session that is not itself a leg.
It is LEVEL state, not an edge: the viewer re-sends it at 1 Hz while striped (plus a short burst on the unstripe transition), and the relay expires the suppression if refreshes stop — so every lost-message state converges to duplicates, never to holes.
func ParseStripeState ¶
func ParseStripeState(b []byte) (StripeState, error)
ParseStripeState parses a StripeState datagram. Strict: unknown flag bits are rejected rather than ignored — a future revision of this message would gate on a new RelayCapabilities bit, never on old relays guessing.
type TelemetryHello ¶
type TelemetryHello struct {
// Enabled reports whether this fleet collects telemetry at all. False
// means the client collects nothing and ignores the remaining fields —
// which is also, deliberately, exactly what a client does when a relay
// predating R28 sends no hello at all.
Enabled bool
// ReportIntervalMs is the sampling cadence the relay asks clients to use.
// The relay is the authority so a fleet can turn the volume down without
// shipping a new frontend.
ReportIntervalMs uint16
// Token is the stateless-verifiable session credential. Never logged,
// never stored: the service verifies it and keeps only the sessionId
// derived from its nonce.
Token []byte
// BroadcastKey is the raw obfuscated-ID digest (Registry.ObfuscateID's
// pre-hex bytes). Aliases the input message when produced by Parse.
BroadcastKey []byte
}
TelemetryHello is the parsed contents of a TelemetryHello message (R28, docs/33 §4.1). Layout, big-endian, exactly TelemetryHelloSize bytes:
byte 0 Version byte 1 TypeTelemetryHello byte 2 flags — bit 0 Enabled; bits 1-7 reserved, must be 0 bytes 3-4 uint16 ReportIntervalMs bytes 5-28 session token (TelemetrySessionTokenSize) bytes 29-34 obfuscated broadcast key (TelemetryBroadcastKeySize)
func ParseTelemetryHello ¶
func ParseTelemetryHello(msg []byte) (TelemetryHello, error)
ParseTelemetryHello parses a TelemetryHello message. The returned Token and BroadcastKey alias msg (no copy), consistent with every other parser here. Strict: exact length, right version and type, and reserved flag bits clear — a set reserved bit means a future field this build would misread, so it is an error rather than a mask-and-hope.
type TelemetryRole ¶
type TelemetryRole string
TelemetryRole distinguishes the two session shapes a token may authorize. Bound into the tag, so a viewer's token cannot submit broadcaster records.
const ( // TelemetryRoleViewer is a /subscribe/{id} session. TelemetryRoleViewer TelemetryRole = "viewer" // TelemetryRoleBroadcaster is a /publish or /publish/{id} session. TelemetryRoleBroadcaster TelemetryRole = "broadcaster" )
type VideoChunkHeader ¶
type VideoChunkHeader struct {
// Keyframe is true if this chunk belongs to a keyframe.
Keyframe bool
// FrameID identifies the encoded frame this chunk belongs to. It is
// monotonic per publisher session, starting at 0.
FrameID uint32
// ChunkIndex is the 0-based index of this chunk within the frame.
ChunkIndex uint16
// ChunkCount is the total number of chunks in the frame. Always >= 1
// and > ChunkIndex.
ChunkCount uint16
// TimestampUs is the frame timestamp in microseconds
// (EncodedVideoChunk.timestamp).
TimestampUs uint64
}
VideoChunkHeader is the parsed header of a VideoChunk datagram.
func ParseVideoChunk ¶
func ParseVideoChunk(dgram []byte) (h VideoChunkHeader, payload []byte, err error)
ParseVideoChunk parses a VideoChunk datagram. The returned payload aliases dgram (no copy); it may be empty. It returns an error if the datagram is shorter than VideoChunkHeaderSize, has the wrong version or type, has chunkCount == 0, or has chunkIndex >= chunkCount.