kolo docsbeta

kolo-moq

Publica, suscríbete y reenvía tracks en vivo por conexiones Kolo, con MoQ Transport draft 22. Un relay comparte una suscripción hacia el publicador entre muchos suscriptores, y el paquete secobj sella los objetos para que un relay los reenvíe sin leerlos.

En esta página

kolo-moq implementa MoQ Transport, draft-ietf-moq-transport-22, sobre una conexión que kolo-secure o kolo-relay ya autenticó. Un publicador escribe tracks formados por grupos de objetos. Los suscriptores reciben un track en vivo, o piden grupos en caché con un fetch, y un relay reparte un track entre muchos suscriptores. No sabe nada de medios: cualquier dato de aplicación puede ser un track. El paquete secobj sella los objetos de un track para que un relay los reenvíe sin poder leer el payload, con un perfil de Kolo de draft-ietf-moq-secure-objects-01. Los paquetes de Go son kolomoq y secobj.

Todos los pasos

Un relay comparte una suscripción

Por muchos suscriptores que pidan un track, el publicador escribe cada objeto una sola vez. El relay lee los objetos que reenvía, salvo que estén sellados, y guarda los grupos más recientes en su caché.

  1. El publicador se conecta al relay y anuncia un namespace con PUBLISH_NAMESPACE. Config.Authorize puede rechazarlo.
  2. Un suscriptor envía SUBSCRIBE para un track de ese namespace. El relay abre un solo SUBSCRIBE hacia el publicador.
  3. Más suscriptores piden el mismo track. Se unen a la suscripción hacia el publicador que ya está abierta, así que el publicador sigue escribiendo cada objeto una sola vez.
  4. El publicador escribe objetos en el relay, que reenvía cada uno a todos los suscriptores y guarda en su caché los grupos más recientes del track (16 grupos y 32 MiB por defecto).
  5. Un suscriptor que llega tarde lee los grupos en caché del relay, con JoinCurrentGroup o un FETCH. La suscripción hacia el publicador termina cuando se va el último suscriptor.

Instalación

go get github.com/ciranda-dev/kolo-moq

Para fijar esta versión, ejecuta go get github.com/ciranda-dev/kolo-moq@v0.1.0. Es solo Go, sin cgo y sin nada que instalar, así que compila con CGO_ENABLED=0. Necesita Go 1.26 o más reciente. Los dos paquetes están en el mismo módulo.

Inicio rápido

Un publicador y un suscriptor se encuentran a través de un relay, todo en 127.0.0.1. El relay escucha y atiende a cada peer que se conecta. El publicador se conecta a él y anuncia el namespace demo, el suscriptor se conecta al mismo relay y se suscribe al track chat, y el publicador escribe un grupo de tres objetos y cierra el track.

main.go
// Command quickstart publishes a track to a relay and subscribes to it through the relay, all on 127.0.0.1.
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	koloid "github.com/ciranda-dev/kolo-id"
	kolomoq "github.com/ciranda-dev/kolo-moq"
	kolosecure "github.com/ciranda-dev/kolo-secure"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	relayID, pubID, subID := must(koloid.Generate()), must(koloid.Generate()), must(koloid.Generate())

	// The relay listens and serves every peer that connects.
	relay := must(kolomoq.NewRelay(nil))
	ln := must(kolosecure.Listen(ctx, "127.0.0.1:0", relayID, nil))
	defer ln.Close()
	go func() {
		for {
			conn, err := ln.Accept(ctx)
			if err != nil {
				return
			}
			relay.NewServer(ctx, conn)
		}
	}()
	dial := func(id *koloid.Identity, cfg *kolomoq.Config) *kolomoq.Session {
		conn := must(kolosecure.Dial(ctx, ln.Addr().String(), id, relayID.PublicKey(), nil))
		return must(kolomoq.NewClient(ctx, conn, cfg))
	}

	// The publisher dials the relay and announces the namespace "demo".
	origin := must(kolomoq.NewOrigin(nil))
	pub := dial(pubID, &kolomoq.Config{Origin: origin})
	defer pub.Close()
	ns := kolomoq.Namespace{"demo"}
	must(pub.PublishNamespace(ctx, ns))
	track := must(origin.CreateTrack(ns, "chat", nil))

	// The subscriber dials the same relay and subscribes to the track.
	sess := dial(subID, nil)
	defer sess.Close()
	sub := must(sess.Subscribe(ctx, ns, "chat", nil))

	// The publisher writes one group of three objects, then ends the track.
	group := must(track.NewGroup())
	for i := range 3 {
		must(group.WriteObject([]byte(fmt.Sprintf("hello %d", i))))
	}
	track.Close()

	for obj, err := sub.ReadObject(ctx); err != io.EOF; obj, err = sub.ReadObject(ctx) {
		if err != nil {
			log.Fatal(err)
		}
		if obj.Status == kolomoq.StatusNormal {
			fmt.Printf("group %d object %d: %s\n", obj.Group, obj.ID, obj.Payload)
		}
	}
}

func must[T any](v T, err error) T {
	if err != nil {
		log.Fatal(err)
	}
	return v
}

Imprime:

Texto
group 0 object 0: hello 0
group 0 object 1: hello 1
group 0 object 2: hello 2

El repositorio también trae examples/publisher y examples/subscriber, que ejecutan los dos lados como programas separados y reciben la dirección y un archivo de clave de identidad como flags, y examples/basic, que conecta a los dos directamente, sin relay.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete kolomoq · github.com/ciranda-dev/kolo-moq · v0.1.0

Package kolomoq runs MoQ Transport (draft-ietf-moq-transport-22) sessions over authenticated Kolo connections: publish tracks of groups and objects, subscribe to them, fetch cached groups and relay tracks to many subscribers.

Each control stream starts with the version preface "moqt-22"; objects travel only on subgroup and fetch streams, never in datagrams.

Experimental: the API may change before v1.0.0.

Constantes

const DefaultPriority = 128

DefaultPriority is the draft's default publisher and subscriber priority. Lower numbers are more urgent.

const KeyNamespaceField = "kolo-keys"

KeyNamespaceField is the reserved first namespace field of key tracks: PublishNamespace refuses it, namespace answers never list it, and a Relay refuses every request under it.

const NewGroupRequestInterval = time.Second

NewGroupRequestInterval is the least time between two requests for a new group on one subscription, and the most often a publisher signals one for one track, whatever the number of subscriptions.

Variables

var (
	// ErrInvalidConfig means a Config, OriginConfig or TrackOptions field is out of range.
	ErrInvalidConfig = errors.New("kolomoq: invalid config")
	// ErrInvalidName means a namespace or track name breaks the draft or configured limits.
	ErrInvalidName = errors.New("kolomoq: invalid namespace or track name")
	// ErrInvalidProperty means a property's Type parity does not match its value, or its bytes are too long.
	ErrInvalidProperty = errors.New("kolomoq: invalid property")
	// ErrClosed means this side closed the session, subscription, fetch, track or group.
	ErrClosed = errors.New("kolomoq: closed")
	// ErrGoingAway means a GOAWAY was received, so no new request is sent, or this side already sent one, so GoAway is not repeated.
	ErrGoingAway = errors.New("kolomoq: session is going away")
	// ErrVersion means the peer's control stream did not start with the moqt-22 preface.
	ErrVersion = errors.New("kolomoq: peer speaks another MoQ Transport version")
	// ErrProtocol means the peer broke the draft; the session is closed.
	ErrProtocol = errors.New("kolomoq: protocol violation")
	// ErrTimeout means the setup or a request took longer than its configured timeout.
	ErrTimeout = errors.New("kolomoq: timeout")
	// ErrNewGroupTooSoon means RequestNewGroup was called less than NewGroupRequestInterval after the last request on the subscription.
	ErrNewGroupTooSoon = errors.New("kolomoq: new group requested too soon")
	// ErrTrackExists means the origin already has a track with this name.
	ErrTrackExists = errors.New("kolomoq: track exists")
	// ErrTooManyTracks means the origin holds MaxTracks tracks.
	ErrTooManyTracks = errors.New("kolomoq: too many tracks")
	// ErrObjectTooLarge means an object is larger than MaxObjectSize.
	ErrObjectTooLarge = errors.New("kolomoq: object too large")
	// ErrMalformedTrack means the publisher sent objects that break the draft's track rules.
	ErrMalformedTrack = errors.New("kolomoq: malformed track")
	// ErrTooManyNamespaces means a namespace subscription announced more than MaxNamespaces namespaces.
	ErrTooManyNamespaces = errors.New("kolomoq: too many namespaces")
	// ErrRequestCanceled means the peer reset a request stream; the error wraps the stream code.
	ErrRequestCanceled = errors.New("kolomoq: request canceled by peer")
	// ErrUnsupportedProperty means a track carries a mandatory track property (types 0x4000 to 0x7FFF) this side does not understand.
	ErrUnsupportedProperty = errors.New("kolomoq: unsupported mandatory track property")
)

Tipos

type Config

type Config struct {
	// Origin holds the tracks this side publishes. Nil means requests for tracks are answered DOES_NOT_EXIST.
	Origin *Origin
	// Authorize decides each request from the peer: a non-nil error refuses it with UNAUTHORIZED.
	// Nil allows every request; the peer is already authenticated by its kolo-id key.
	Authorize func(peer ed25519.PublicKey, kind RequestKind, ns Namespace, track string) error

	// SetupTimeout bounds the exchange of version prefaces and SETUP. Default 10s, from 1s to 10m.
	SetupTimeout time.Duration
	// RequestTimeout bounds the wait for a response, for the first message of a request stream and for a data stream header, the wait for the data stream of a fetch after FETCH_OK, and the time a data stream the peer does not read may stay blocked before it is reset. Default 10s, from 1s to 10m.
	RequestTimeout time.Duration
	// MaxRequests caps the requests the peer may have open at once; more are reset. Default 1000, from 1 to 1000000.
	MaxRequests int
	// MaxSubscriptions caps the peer's open subscriptions; more are refused with EXCESSIVE_LOAD. Default 1000, from 1 to 1000000.
	MaxSubscriptions int
	// MaxObjectSize caps an object payload received from the peer, in bytes. Default 16 MiB, from 1 KiB to 1 GiB.
	MaxObjectSize int
	// MaxControlMessageSize caps a control message from the peer, in bytes. Default and maximum 65535 (the draft's 16-bit length), from 8192.
	MaxControlMessageSize int
	// MaxNamespaceFields caps the fields of a namespace in a request. Default and maximum 32 (the draft limit), from 1.
	MaxNamespaceFields int
	// MaxNameLength caps a namespace plus track name in a request, in bytes. Default and maximum 4096 (the draft limit), from 1.
	MaxNameLength int
	// MaxBufferedGroups caps the groups queued for one subscription, on either side. Default 64, from 1 to 1000000.
	MaxBufferedGroups int
	// MaxBufferedBytes caps the payload bytes queued for one subscription, on either side. Default 32 MiB or MaxObjectSize if larger, from MaxObjectSize to 64 GiB.
	MaxBufferedBytes int64
	// MaxNamespaces caps the namespaces one namespace subscription tracks, on either side. Default 1000, from 1 to 1000000.
	MaxNamespaces int
	// MaxFetchBytes caps the bytes of cached objects held at once for the peer's FETCHes and fills, and in a relay the objects it buffers for the peer's forwarded FETCHes. A FETCH beyond it is refused with EXCESSIVE_LOAD, a fill is skipped and a forwarded FETCH is reset. Default MaxBufferedBytes, from MaxObjectSize to 64 GiB.
	MaxFetchBytes int64
	// contains filtered or unexported fields
}

Config sets the behavior and limits of a Session. A zero field takes its default.

type Conn

type Conn interface {
	RemotePublicKey() ed25519.PublicKey
	OpenStream(ctx context.Context) (*kolotransport.Stream, error)
	AcceptStream(ctx context.Context) (*kolotransport.Stream, error)
	OpenUniStream(ctx context.Context) (*kolotransport.SendStream, error)
	AcceptUniStream(ctx context.Context) (*kolotransport.ReceiveStream, error)
	Context() context.Context
	Close() error
	CloseWithError(code uint64, msg string) error
}

Conn is an authenticated Kolo connection; *kolosecure.Conn and *kolorelay.Conn satisfy it. A Session owns its Conn: it is the only caller of AcceptStream and AcceptUniStream, and closes the Conn when the session ends.

type DoneCode

type DoneCode uint64

DoneCode is a PUBLISH_DONE status code (draft section 12.4).

const (
	DoneInternalError  DoneCode = 0x0
	DoneUnauthorized   DoneCode = 0x1
	DoneTrackEnded     DoneCode = 0x2
	DoneGoingAway      DoneCode = 0x4
	DoneTooFarBehind   DoneCode = 0x5
	DoneExpired        DoneCode = 0x6
	DoneUpdateFailed   DoneCode = 0x8
	DoneExcessiveLoad  DoneCode = 0x9
	DoneMalformedTrack DoneCode = 0x12
)

PUBLISH_DONE status codes.

func (DoneCode) String
func (c DoneCode) String() string

String returns the draft name of the code, or its hex value if unknown.

type Fetch

type Fetch struct {
	// contains filtered or unexported fields
}

Fetch receives the cached objects of a track that a FETCH asked for.

func (Fetch) Close
func (f *Fetch) Close() error

Close cancels the fetch.

func (Fetch) End
func (f *Fetch) End() Location

End returns the last location the fetch covers, from FETCH_OK.

func (Fetch) EndOfTrack
func (f *Fetch) EndOfTrack() bool

EndOfTrack reports whether End is the last object of the track.

func (Fetch) Properties
func (f *Fetch) Properties() []Property

Properties returns a copy of the track properties from FETCH_OK.

func (Fetch) ReadObject
func (f *Fetch) ReadObject(ctx context.Context) (Object, error)

ReadObject returns the next object; io.EOF after the last one. Calls must not overlap.

type FetchOptions

type FetchOptions struct {
	// RecentGroups, when above zero, fetches the newest RecentGroups groups up to the Largest Object; 1 is the current group.
	RecentGroups uint64
	// Start is the first location of an absolute range, used when RecentGroups is zero.
	Start Location
	// End is the last location of the range, inclusive; nil means up to the Largest Object.
	End *Location
	// Priority is the subscriber priority, 0 (most urgent) to 255.
	Priority uint8
	// GroupOrder is the order groups are sent in. Default OrderAscending.
	GroupOrder GroupOrder
}

FetchOptions selects the objects a Fetch asks for. A nil *FetchOptions fetches the current group; in a non-nil one, Priority is used as is.

type GroupOrder

type GroupOrder uint8

GroupOrder is the order groups of a track are sent in.

const (
	OrderDefault    GroupOrder = 0
	OrderAscending  GroupOrder = 1
	OrderDescending GroupOrder = 2
)

Group orders; OrderDefault means the publisher's preference.

type GroupWriter

type GroupWriter struct {
	// contains filtered or unexported fields
}

GroupWriter writes the objects of one group, numbered from 0.

func (GroupWriter) Close
func (g *GroupWriter) Close() error

Close ends the group with an End of Group object.

func (GroupWriter) ID
func (g *GroupWriter) ID() uint64

ID returns the group ID.

func (GroupWriter) Priority
func (g *GroupWriter) Priority() uint8

Priority returns the publisher priority of the group's track.

func (GroupWriter) WriteObject
func (g *GroupWriter) WriteObject(payload []byte, props ...Property) (uint64, error)

WriteObject publishes the next object of the group and returns its ID. The payload and properties are copied.

func (GroupWriter) WriteObjectFunc
func (g *GroupWriter) WriteObjectFunc(build func(id uint64) ([]byte, []Property, error)) (uint64, error)

WriteObjectFunc publishes the next object of the group with the payload and properties that build returns for its Object ID, holding the group for the whole call. If build or the checks of its result fail, no ID is used. build must not call methods of this track's writers.

type Join

type Join int

Join is where a subscription starts.

const (
	// JoinNextObject delivers objects published from now on.
	JoinNextObject Join = iota
	// JoinCurrentGroup also delivers the current group's earlier objects
	// from the publisher's cache, on a fill fetch stream.
	JoinCurrentGroup
	// JoinNextGroup starts at the next group.
	JoinNextGroup
)

Join points (draft section 3.5).

type Location

type Location struct {
	Group, Object uint64
}

Location is a Group and Object pair.

func (Location) Less
func (l Location) Less(m Location) bool

Less reports whether l comes before m.

type Namespace

type Namespace []string

Namespace is a Track Namespace: 0 to 32 non-empty fields.

func (Namespace) HasPrefix
func (n Namespace) HasPrefix(p Namespace) bool

HasPrefix reports whether p is a prefix of n, field by field.

type NamespaceEvent

type NamespaceEvent struct {
	Namespace Namespace
	Active    bool
}

NamespaceEvent reports a namespace the peer starts (Active) or stops publishing.

type NamespaceSubscription

type NamespaceSubscription struct {
	// contains filtered or unexported fields
}

NamespaceSubscription receives the namespaces the peer publishes under a prefix.

func (NamespaceSubscription) Close
func (n *NamespaceSubscription) Close() error

Close ends the namespace subscription.

func (NamespaceSubscription) Next
func (n *NamespaceSubscription) Next(ctx context.Context) (NamespaceEvent, error)

Next returns the next change. When the peer ends the subscription it returns io.EOF; every namespace reported active is then gone. Calls must not overlap.

type Object

type Object struct {
	Group      uint64
	Subgroup   uint64
	ID         uint64
	Priority   uint8
	Status     ObjectStatus
	Properties []Property
	Payload    []byte
}

Object is one object of a track.

type ObjectStatus

type ObjectStatus uint64

ObjectStatus tells a normal object from an end marker.

const (
	StatusNormal     ObjectStatus = wire.StatusNormal
	StatusEndOfGroup ObjectStatus = wire.StatusEndOfGroup
	StatusEndOfTrack ObjectStatus = wire.StatusEndOfTrack
)

Object statuses (draft section 11.1.1).

type Origin

type Origin struct {
	// contains filtered or unexported fields
}

Origin holds the tracks one side publishes. Many sessions can serve the same Origin: each subscriber gets its own queue, so a slow one never blocks the writer or the others. Its methods are safe for concurrent use.

func NewOrigin
func NewOrigin(cfg *OriginConfig) (*Origin, error)

NewOrigin returns an empty Origin.

func (Origin) CreateTrack
func (o *Origin) CreateTrack(ns Namespace, name string, opts *TrackOptions) (*TrackWriter, error)

CreateTrack adds a track to the origin and returns its writer.

type OriginConfig

type OriginConfig struct {
	// MaxTracks caps the open tracks. Default 1000, from 1 to 1000000.
	MaxTracks int
	// MaxObjectSize caps an object payload, in bytes. Default 16 MiB, from 1 KiB to 1 GiB.
	MaxObjectSize int
}

OriginConfig sets the limits of an Origin. A zero field takes its default.

type Property

type Property struct {
	Type  uint64
	Value uint64
	Bytes []byte
}

Property is an object or track property: an even Type carries Value, an odd Type carries Bytes (at most 65535 of them).

type PublishDoneError

type PublishDoneError struct {
	Code   DoneCode
	Reason string
}

PublishDoneError means the publisher ended a subscription with a status other than TRACK_ENDED. Reason is sanitized peer text, as in RequestError.

func (PublishDoneError) Error
func (e *PublishDoneError) Error() string

Error names the status code and leaves out the peer text.

type PublishedNamespace

type PublishedNamespace struct {
	// contains filtered or unexported fields
}

PublishedNamespace is a namespace this side announced with PUBLISH_NAMESPACE.

func (PublishedNamespace) Close
func (p *PublishedNamespace) Close() error

Close withdraws the namespace.

func (PublishedNamespace) Done
func (p *PublishedNamespace) Done() <-chan struct{}

Done is closed when the peer revoked the namespace or the session ended.

type Relay

type Relay struct {
	// contains filtered or unexported fields
}

Relay forwards tracks from publishers to many subscribers. Publishers announce namespaces with PUBLISH_NAMESPACE; a SUBSCRIBE for a track under such a namespace opens one upstream subscription to the publisher, shared by every subscriber of the track and cached for FETCH and late joiners. The upstream subscription ends when the last subscriber leaves; when the publisher ends the track or goes away, subscribers get PUBLISH_DONE.

func NewRelay
func NewRelay(cfg *RelayConfig) (*Relay, error)

NewRelay returns a Relay with no sessions.

func (Relay) NewClient
func (r *Relay) NewClient(ctx context.Context, conn Conn) (*Session, error)

NewClient starts a relay session as the MoQT client on a Conn this side dialed, as the package-level NewClient.

func (Relay) NewServer
func (r *Relay) NewServer(ctx context.Context, conn Conn) (*Session, error)

NewServer starts a relay session as the MoQT server on a Conn this side accepted, as the package-level NewServer.

type RelayConfig

type RelayConfig struct {
	// Session configures every session of the relay; its Origin must be nil.
	// Its Authorize hook decides PUBLISH_NAMESPACE from publishers and every
	// request from subscribers.
	Session Config
	// MaxTracks caps the tracks relayed at once. Default 1000, from 1 to 1000000.
	MaxTracks int
	// MaxSessionTracks caps the relayed tracks that one session's SUBSCRIBEs opened and that are still relayed; more are refused with EXCESSIVE_LOAD. Default MaxTracks / 10 (at least 1), from 1 to MaxTracks.
	MaxSessionTracks int
	// MaxSessionFetches caps the FETCHes of one session the relay forwards to publishers at once; more are refused with EXCESSIVE_LOAD. Default 16, from 1 to 1000000.
	MaxSessionFetches int
	// CacheGroups and CacheBytes bound the cache of each relayed track, as in TrackOptions. Defaults 16 groups and 32 MiB.
	CacheGroups int
	CacheBytes  int64
	// Resume lets a publisher come back after its connection is lost. When a session ends because the connection
	// failed or the peer called Suspend, not because a side closed it, its announcements are held, so subscribers do
	// not see the publisher leave. While held, no other peer may announce the namespace or one under it, and no
	// request under it goes to another peer. A new session of the same peer that announces the namespace takes over
	// and closes the older one if it still runs. A hold ends when Resume is over or the session closes cleanly. Zero,
	// the default, withdraws the announcements with the session. From 1s to 1h.
	Resume time.Duration
	// MaxResumeHeld caps the announcements held at once for sessions that ended. A session whose announcements do not
	// fit loses them with the session, as without Resume, so a flood of short sessions cannot push out the holds of
	// others. Default 10000, ten times the default MaxRequests, from 1 to 1000000. It counts only with Resume.
	MaxResumeHeld int
	// MaxPeerResumeHeld caps the announcements held for one peer key, so one key cannot fill MaxResumeHeld. Default
	// the Session's MaxRequests, the most announcements one session can have, or MaxResumeHeld if that is lower;
	// from 1 to MaxResumeHeld. It counts only with Resume.
	MaxPeerResumeHeld int
}

RelayConfig sets a Relay. A zero field takes its default.

type RequestCode

type RequestCode uint64

RequestCode is a REQUEST_ERROR code (draft section 12.3).

const (
	ReqInternalError        RequestCode = 0x0
	ReqUnauthorized         RequestCode = 0x1
	ReqTimeout              RequestCode = 0x2
	ReqNotSupported         RequestCode = 0x3
	ReqMalformedAuthToken   RequestCode = 0x4
	ReqExpiredAuthToken     RequestCode = 0x5
	ReqGoingAway            RequestCode = 0x6
	ReqExcessiveLoad        RequestCode = 0x9
	ReqDoesNotExist         RequestCode = 0x10
	ReqInvalidRange         RequestCode = 0x11
	ReqMalformedTrack       RequestCode = 0x12
	ReqUninterested         RequestCode = 0x20
	ReqPrefixOverlap        RequestCode = 0x30
	ReqNamespaceTooLarge    RequestCode = 0x31
	ReqUnsupportedExtension RequestCode = 0x33
	ReqRedirect             RequestCode = 0x34
	ReqConflictingFilters   RequestCode = 0x35
	ReqInvalidFilter        RequestCode = 0x36
)

REQUEST_ERROR codes.

func (RequestCode) String
func (c RequestCode) String() string

String returns the draft name of the code, or its hex value if unknown.

type RequestError

type RequestError struct {
	Code RequestCode
	// Retry reports whether the peer allows a retry, after RetryAfter.
	Retry      bool
	RetryAfter time.Duration
	Reason     string
}

RequestError is a REQUEST_ERROR from the peer. Reason is the peer's text (at most 1024 bytes on the wire) with bytes outside printable ASCII escaped; it is not part of Error().

func (RequestError) Error
func (e *RequestError) Error() string

Error names the refusal code and leaves out the peer text.

type RequestKind

type RequestKind int

RequestKind is the kind of request the Authorize hook decides on.

const (
	KindSubscribe RequestKind = iota + 1
	KindFetch
	KindTrackStatus
	KindPublishNamespace
	KindSubscribeNamespace
)

Request kinds.

func (RequestKind) String
func (k RequestKind) String() string

String returns the draft message name of the kind.

type RoomPolicy

type RoomPolicy struct {
	Room   Namespace
	Member func(peer ed25519.PublicKey) bool
}

RoomPolicy authorizes requests for a relay serving rooms: a peer publishes only Room+{hex(peer)} and, if Member allows it, reads under Room. Everything else is refused. A nil Member admits no reader.

func (RoomPolicy) Authorize
func (p RoomPolicy) Authorize(peer ed25519.PublicKey, kind RequestKind, ns Namespace, track string) error

Authorize decides one request as Config.Authorize does; a peer's field is the lowercase hex of its 32-byte key.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is a MoQ Transport session over one Conn. It owns the Conn: it is the only caller of AcceptStream and AcceptUniStream and closes the Conn when the session ends. Its methods are safe for concurrent use.

func NewClient
func NewClient(ctx context.Context, conn Conn, cfg *Config) (*Session, error)

NewClient starts a session as the MoQT client, on a Conn this side dialed. It returns once both SETUP messages are exchanged.

func NewServer
func NewServer(ctx context.Context, conn Conn, cfg *Config) (*Session, error)

NewServer starts a session as the MoQT server, on a Conn this side accepted. It returns once both SETUP messages are exchanged.

func (Session) Close
func (s *Session) Close() error

Close ends the session with NO_ERROR and waits for its goroutines. Calls in progress return ErrClosed.

func (Session) Done
func (s *Session) Done() <-chan struct{}

Done is closed when the session has ended.

func (Session) Err
func (s *Session) Err() error

Err returns why the session ended, or nil while it runs: ErrClosed after Close, a *SessionError for a termination code, or a wrapped kolo-transport error when the connection failed.

func (Session) Fetch
func (s *Session) Fetch(ctx context.Context, ns Namespace, track string, opts *FetchOptions) (*Fetch, error)

Fetch asks the peer for cached objects and returns once the peer accepted (FETCH_OK) or refused (*RequestError, INVALID_RANGE when nothing is cached in the range).

func (Session) GoAway
func (s *Session) GoAway(ctx context.Context, timeout time.Duration) error

GoAway sends GOAWAY, refuses new requests with GOING_AWAY, and closes the session with NO_ERROR once the peer has no request open, or with GOAWAY_TIMEOUT after timeout (at least 1ms). It returns nil once it has closed the session either way; Err tells which. A second call returns ErrGoingAway, and a session that had already ended returns its error.

func (Session) GoingAway
func (s *Session) GoingAway() <-chan struct{}

GoingAway is closed when the peer sent GOAWAY: open a new session and move the subscriptions there.

func (Session) PeerImplementation
func (s *Session) PeerImplementation() string

PeerImplementation returns the peer's MOQT_IMPLEMENTATION, cut to 1024 bytes, then with bytes outside printable ASCII escaped.

func (Session) PeerNamespaces
func (s *Session) PeerNamespaces() []Namespace

PeerNamespaces returns the namespaces the peer has published to this side with PUBLISH_NAMESPACE and not withdrawn.

func (Session) PublishNamespace
func (s *Session) PublishNamespace(ctx context.Context, ns Namespace) (*PublishedNamespace, error)

PublishNamespace tells the peer this side has tracks under ns, and returns once the peer accepted it or refused it (*RequestError).

func (Session) RemotePublicKey
func (s *Session) RemotePublicKey() ed25519.PublicKey

RemotePublicKey returns a copy of the peer's kolo-id public key.

func (Session) Stats
func (s *Session) Stats() SessionStats

Stats returns counters of groups this side stopped sending, how far behind its sending is, and the transport's numbers of the connection.

func (Session) Subscribe
func (s *Session) Subscribe(ctx context.Context, ns Namespace, track string, opts *SubscribeOptions) (*Subscription, error)

Subscribe asks the peer for a track and returns once the peer accepted (SUBSCRIBE_OK) or refused (*RequestError).

func (Session) SubscribeNamespace
func (s *Session) SubscribeNamespace(ctx context.Context, prefix Namespace) (*NamespaceSubscription, error)

SubscribeNamespace asks the peer for the namespaces under prefix and their changes, and returns once the peer accepted or refused (*RequestError).

func (Session) Suspend
func (s *Session) Suspend() error

Suspend ends the session and closes its connection with CodeSuspend, to tell a Relay with Resume that this peer means to come back: the relay keeps the peer's announcements as it does for a lost connection. Close, which ends with CodeNoError, withdraws them at once.

func (Session) TrackStatus
func (s *Session) TrackStatus(ctx context.Context, ns Namespace, track string) (*TrackStatus, error)

TrackStatus asks the peer for the Largest Object and properties of a track without subscribing.

type SessionCode

type SessionCode uint64

SessionCode is a session termination code (draft section 12.2).

const (
	CodeNoError                 SessionCode = 0x0
	CodeInternalError           SessionCode = 0x1
	CodeUnauthorized            SessionCode = 0x2
	CodeProtocolViolation       SessionCode = 0x3
	CodeInvalidRequestID        SessionCode = 0x4
	CodeDuplicateTrackAlias     SessionCode = 0x5
	CodeKeyValueFormatting      SessionCode = 0x6
	CodeInvalidPath             SessionCode = 0x8
	CodeMalformedPath           SessionCode = 0x9
	CodeGoAwayTimeout           SessionCode = 0x10
	CodeControlMessageTimeout   SessionCode = 0x11
	CodeDataStreamTimeout       SessionCode = 0x12
	CodeAuthTokenCacheOverflow  SessionCode = 0x13
	CodeDuplicateAuthTokenAlias SessionCode = 0x14
	CodeMalformedAuthToken      SessionCode = 0x16
	CodeUnknownAuthTokenAlias   SessionCode = 0x17
	CodeExpiredAuthToken        SessionCode = 0x18
	CodeInvalidAuthority        SessionCode = 0x19
	CodeMalformedAuthority      SessionCode = 0x1A
	CodeTooManyRequestUpdates   SessionCode = 0x1B
	// CodeSuspend is kolo-moq's own code, outside the draft's: Suspend closes a session with it.
	CodeSuspend SessionCode = 0x100
)

Session termination codes.

func (SessionCode) String
func (c SessionCode) String() string

String returns the draft name of the code, or its hex value if unknown.

type SessionError

type SessionError struct {
	Code   SessionCode
	Remote bool
	// contains filtered or unexported fields
}

SessionError means the session ended with a MoQT termination code. Remote reports whether the peer chose the code.

func (SessionError) Error
func (e *SessionError) Error() string

Error says who closed the session and with which code.

func (SessionError) Unwrap
func (e *SessionError) Unwrap() error

Unwrap returns the sentinel behind a local close (ErrProtocol, ErrVersion, ErrTimeout), if any.

type SessionStats

type SessionStats struct {
	// SentBytes counts the bytes of data streams handed to the transport, which takes them as fast as the path lets
	// it: while QueueDelay is above zero, its change over time is the rate the path carries.
	SentBytes uint64
	// QueuedBytes is the payload waiting in subscribers' queues, not yet handed to the transport.
	QueuedBytes int64
	// QueueDelay is how long the oldest object still being sent or waiting has been held, across the subscribers of
	// this session. It is zero when nothing waits; it grows while the path carries less than is published.
	QueueDelay time.Duration
	// ResetGroups counts subgroup streams reset because a subscriber's queue exceeded MaxBufferedGroups or MaxBufferedBytes, or because the subscriber stopped reading the stream for RequestTimeout.
	ResetGroups uint64
	// ExpiredGroups counts subgroup streams reset with DELIVERY_TIMEOUT.
	ExpiredGroups uint64
	// Transport is the transport's statistics of the connection this session runs on: round-trip times, losses, the
	// congestion window, the congestion controller and the path (see kolotransport.ConnStats). It is the zero value
	// when the session's Conn has no Stats method, as a *kolorelay.Conn has none, and once the connection has ended.
	Transport kolotransport.ConnStats
}

SessionStats counts what this side sent and the groups it stopped sending, and says how far behind its sending is.

type SubscribeOptions

type SubscribeOptions struct {
	// Priority is the subscriber priority, 0 (most urgent) to 255; nil options give DefaultPriority.
	Priority uint8
	// GroupOrder overrides the publisher's group order.
	GroupOrder GroupOrder
	// Join is where the subscription starts.
	Join Join
	// Paused subscribes without receiving objects until Update resumes.
	Paused bool
	// SubgroupDeliveryTimeout and ObjectDeliveryTimeout ask the publisher to drop late groups; the smaller of its and these values applies. Zero means none.
	SubgroupDeliveryTimeout time.Duration
	ObjectDeliveryTimeout   time.Duration
}

SubscribeOptions sets a subscription. A nil *SubscribeOptions takes every default; in a non-nil one, Priority is used as is.

type Subscription

type Subscription struct {
	// contains filtered or unexported fields
}

Subscription receives the objects of one track. ReadObject is safe for concurrent use with the other methods.

func (Subscription) Close
func (sub *Subscription) Close() error

Close unsubscribes; queued objects are dropped and ReadObject returns ErrClosed.

func (Subscription) Dropped
func (sub *Subscription) Dropped() uint64

Dropped returns how many groups this side dropped because the reader fell more than MaxBufferedGroups or MaxBufferedBytes behind.

func (Subscription) Largest
func (sub *Subscription) Largest() (Location, bool)

Largest returns the Largest Object the publisher last reported.

func (Subscription) Properties
func (sub *Subscription) Properties() []Property

Properties returns a copy of the track properties from SUBSCRIBE_OK.

func (Subscription) ReadObject
func (sub *Subscription) ReadObject(ctx context.Context) (Object, error)

ReadObject returns the next object, in arrival order. After the publisher ends the track it returns io.EOF; after another PUBLISH_DONE, a *PublishDoneError; after Close, ErrClosed.

func (Subscription) RequestNewGroup
func (sub *Subscription) RequestNewGroup(ctx context.Context) error

RequestNewGroup asks the publisher to start a new group, so a subscriber that lost a group or just joined does not wait for the next one: for a video track the publisher sends a key frame. The publisher ignores the request when a newer group exists. At most one request goes out every NewGroupRequestInterval; a sooner call returns ErrNewGroupTooSoon and sends nothing. A refused update ends the subscription, as with Update.

func (Subscription) Update
func (sub *Subscription) Update(ctx context.Context, u SubscriptionUpdate) error

Update changes the subscriber priority and pauses or resumes delivery, waiting for the publisher's answer. A refused update ends the subscription.

type SubscriptionUpdate

type SubscriptionUpdate struct {
	Priority uint8
	Paused   bool
}

SubscriptionUpdate is the new state Update asks for.

type TrackOptions

type TrackOptions struct {
	// Priority is the publisher priority, 0 (most urgent) to 255; nil options give DefaultPriority.
	Priority uint8
	// GroupOrder is the publisher's preferred group order. Default OrderAscending.
	GroupOrder GroupOrder
	// SubgroupDeliveryTimeout resets a group's stream that is not fully sent this long after the group ended. Zero means none; millisecond precision, rounded up.
	SubgroupDeliveryTimeout time.Duration
	// ObjectDeliveryTimeout resets a group's stream when an object waited this long to be sent. Zero means none; millisecond precision, rounded up.
	ObjectDeliveryTimeout time.Duration
	// CacheGroups caps the newest groups kept for FETCH and late joiners. Default 16, from 1 to 1000000.
	CacheGroups int
	// CacheBytes caps the payload bytes kept, in bytes. Default 32 MiB, from 1 KiB to 64 GiB.
	CacheBytes int64
	// Properties are extra track properties sent to subscribers; types 0x02, 0x06, 0x0E and 0x22 are set from the fields above.
	Properties []Property
	// Readers, if non-nil, are the only peers that may SUBSCRIBE to, FETCH or ask TRACK_STATUS of the track, whatever Config.Authorize decides; others get DOES_NOT_EXIST, also through a relay. An empty non-nil slice admits nobody. Each key must be 32 bytes.
	Readers []ed25519.PublicKey
}

TrackOptions sets how a track is published. A nil *TrackOptions takes every default; in a non-nil one, Priority is used as is.

type TrackStatus

type TrackStatus struct {
	Largest    Location
	HasLargest bool
	Properties []Property
}

TrackStatus is the publisher's view of a track (TRACK_STATUS_OK).

type TrackWriter

type TrackWriter struct {
	// contains filtered or unexported fields
}

TrackWriter publishes the groups of one track. Its methods are safe for concurrent use.

func (TrackWriter) Close
func (w *TrackWriter) Close() error

Close ends the track: the open group ends with an End of Track object, subscribers get PUBLISH_DONE TRACK_ENDED once their queues are sent, and the track leaves the origin.

func (TrackWriter) NewGroup
func (w *TrackWriter) NewGroup() (*GroupWriter, error)

NewGroup ends the open group, if any, and starts the next one; group IDs start at 0 and increase by one.

func (TrackWriter) NewGroupRequests
func (w *TrackWriter) NewGroupRequests() <-chan struct{}

NewGroupRequests returns a channel that receives when a subscriber asks for a new group with RequestNewGroup and no newer group exists. The application then calls NewGroup and writes a group that a late subscriber can start from: for video, one that begins with a key frame. Requests merge while one is pending, and the track signals at most once every NewGroupRequestInterval, however many subscriptions ask.

func (TrackWriter) Subscribers
func (w *TrackWriter) Subscribers() int

Subscribers returns the number of subscriptions the track has now, over all sessions.

Paquete secobj

github.com/ciranda-dev/kolo-moq/secobj

Package secobj protects MoQ objects end to end through relays with the Kolo profile of MoQ Secure Objects (draft-ietf-moq-secure-objects-01).

One cipher suite is used: AES_128_GCM_SHA256_128 (0x0004). The key and salt of a track come from HKDF-SHA256 over a 16-byte base key, the Key ID and the serialized full track name. The nonce is the salt XOR the 64-bit Group ID and 32-bit Object ID, so an Object ID is below 2^32. The AAD is the Group ID, the Object ID, the publisher priority and the Immutable Properties bytes.

A protected object carries one visible property: Immutable Properties (0x0B) holding one Key ID property of type PropertyKeyID (0x78). Its payload is the AEAD output of the payload length, the payload and, when there are private properties, the marker 00 0A, a length and the properties. Every encoding is draft-ietf-moq-transport-22's, so objects do not interoperate with other Secure Objects implementations.

Relays still see namespaces, track names, Group and Object IDs, priority, Key IDs, sizes and timing, object status and track properties. Status and track properties are not authenticated. Go's AES-GCM is constant time only in its assembly for amd64 and arm64 CPUs with AES instructions, ppc64x and s390x; on 386, arm, riscv64, loong64, mips, wasm, and amd64 or arm64 CPUs without AES instructions, it is generic code that is not constant time.

A Sender gives its key for one media namespace to each member over a key track that only that member may read; a Keyring receives keys only from the peer that KeyringConfig.Authorize names as the namespace owner; each reader of a track opens objects through its own Opener, which keeps its own replay window.

Keys are never written to disk. Base keys and salts are overwritten when replaced, removed or closed; AES key schedules and key messages in key track caches and transport buffers are only released, and Go does not guarantee that no copy remains.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// PropertyKeyID is the type of the Key ID property inside Immutable Properties.
	PropertyKeyID = 0x78
	// PropertyEncryptedList is the type that marks the Encrypted Properties List inside the plaintext.
	PropertyEncryptedList = 0x0A
)

Property types of the profile.

Variables

var (
	// ErrNoKey means no key is held for the object's Key ID.
	ErrNoKey = errors.New("kolomoq: secobj: no key for this key ID")
	// ErrKeyRetired means the object's key was erased.
	ErrKeyRetired = errors.New("kolomoq: secobj: key retired")
	// ErrAuthentication means the object failed AEAD authentication.
	ErrAuthentication = errors.New("kolomoq: secobj: authentication failed")
	// ErrMalformed means a Key ID property or a decrypted plaintext breaks the profile's encoding.
	ErrMalformed = errors.New("kolomoq: secobj: malformed object")
	// ErrNotProtected means the object carries no Immutable Properties, so it was not sealed.
	ErrNotProtected = errors.New("kolomoq: secobj: object not protected")
	// ErrReplay means the object was opened before or falls outside the replay window.
	ErrReplay = errors.New("kolomoq: secobj: replayed object")
	// ErrWrongSession means a session that neither owns a protected namespace nor is a listed relay carries it.
	ErrWrongSession = errors.New("kolomoq: secobj: session may not carry this namespace")
	// ErrObjectID means an Object ID of 2^32 or more, or a (Group ID, Object ID) not after the last one sealed under the key.
	ErrObjectID = errors.New("kolomoq: secobj: object ID not allowed")
	// ErrKeyMessage means a key message breaks the profile's encoding.
	ErrKeyMessage = errors.New("kolomoq: secobj: malformed key message")
	// ErrUnauthorized means a key message came from a peer that may not give keys for its namespace.
	ErrUnauthorized = errors.New("kolomoq: secobj: unauthorized key message")
	// ErrInvalidConfig means a configuration field is out of range.
	ErrInvalidConfig = errors.New("kolomoq: secobj: invalid config")
	// ErrTooManySenders means a Keyring already holds keys for MaxSenders namespaces.
	ErrTooManySenders = errors.New("kolomoq: secobj: too many senders")
)

Funciones

func KeyNamespace
func KeyNamespace(ns kolomoq.Namespace) kolomoq.Namespace

KeyNamespace returns the namespace of the key tracks of the media namespace ns.

func KeyTrack
func KeyTrack(member ed25519.PublicKey) string

KeyTrack returns the name of the key track for member: the lowercase hex of its public key.

Tipos

type Keyring
type Keyring struct {
	// contains filtered or unexported fields
}

Keyring holds the keys of the senders a participant receives, per media namespace: the current key and the one it replaced. Objects are opened through an Opener per reader, each with its own replay window. Make one with NewKeyring. Its methods are safe for concurrent use; it prints redacted with fmt.

func NewKeyring
func NewKeyring(cfg KeyringConfig) (*Keyring, error)

NewKeyring returns an empty Keyring.

func (Keyring) Changed
func (k *Keyring) Changed() <-chan struct{}

Changed returns a channel that is closed the next time a key is installed.

func (Keyring) Format
func (k *Keyring) Format(f fmt.State, _ rune)

Format prints no key material.

func (Keyring) MayCarry
func (k *Keyring) MayCarry(s *kolomoq.Session, ns kolomoq.Namespace) error

MayCarry reports whether s may carry the protected namespace ns: its peer owns ns or is a listed relay. Otherwise it returns ErrWrongSession.

func (Keyring) Opener
func (k *Keyring) Opener(s *kolomoq.Session, ns kolomoq.Namespace, track string) (*Opener, error)

Opener returns an Opener for track under ns read on s. It fails with ErrWrongSession unless MayCarry(s, ns) is nil, so a member cannot serve another member's namespace on its own session.

func (Keyring) Receive
func (k *Keyring) Receive(ctx context.Context, s *kolomoq.Session, self ed25519.PublicKey, ns kolomoq.Namespace) error

Receive installs the keys that the peer of s gives for ns on the key track of self, until ctx ends, s ends, the peer ends the track (nil) or Remove(ns) is called. The peer is s.RemotePublicKey(); Receive fails with ErrUnauthorized unless Authorize says it owns ns. Until the peer makes self a member, the subscription is refused and Receive returns that error. Key messages that break the rules are counted in Stats and skipped.

func (Keyring) Remove
func (k *Keyring) Remove(ns kolomoq.Namespace)

Remove erases the keys of ns and ends its Receive calls.

func (Keyring) Stats
func (k *Keyring) Stats() KeyringStats

Stats returns the key message counters.

type KeyringConfig
type KeyringConfig struct {
	// Authorize reports whether peer owns ns and may give its key. Required.
	Authorize func(peer ed25519.PublicKey, ns kolomoq.Namespace) error
	// Relays are the relay identities a protected watch may use besides a namespace's owner.
	Relays []ed25519.PublicKey
	// Retain is how long a replaced key still opens objects after the first object under its successor. Default 450ms, at most 1m.
	Retain time.Duration
	// RetainMax is how long a replaced key opens objects at most after its successor arrived, even if no object under the successor opens. Default Retain plus 400ms, from Retain to 2m.
	RetainMax time.Duration
	// MaxSenders caps the namespaces with keys. Default 64, from 1 to 1024.
	MaxSenders int
	// MaxKeyRate caps key messages per namespace per second; more are dropped. Default 64, from 1 to 1024.
	MaxKeyRate int
	// ReplayGroups and ReplayObjects bound the replay window per track. Defaults 64 and 8192, from 1 to 1000000.
	ReplayGroups  int
	ReplayObjects int
}

KeyringConfig sets a Keyring. A zero field takes its default.

type KeyringStats
type KeyringStats struct {
	// Rejected counts malformed key messages, ones naming another namespace and ones that change the key of a Key ID.
	Rejected uint64
	// Dropped counts key messages over MaxKeyRate.
	Dropped uint64
}

KeyringStats counts the key messages a Keyring did not install.

type Opener
type Opener struct {
	// contains filtered or unexported fields
}

Opener opens the objects of one track of a protected namespace for one reader, such as one subscription, with the reader's own replay window: each Opener opens an object at most once, whatever other Openers of the same Keyring opened. Its methods are safe for concurrent use.

func (Opener) Open
func (o *Opener) Open(obj kolomoq.Object) ([]byte, []kolomoq.Property, error)

Open authenticates and decrypts an object with its sender's key and records it in the replay window. It fails with ErrNoKey for a Key ID newer than the keys held, ErrKeyRetired for an older one, and ErrReplay for an object this Opener opened before or one outside its window.

type Sender
type Sender struct {
	// contains filtered or unexported fields
}

Sender holds one sender's key for one media namespace and gives it to each member on the member's key track. Make one with NewSender. Its methods are safe for concurrent use; it prints redacted with fmt.

func NewSender
func NewSender(origin *kolomoq.Origin, ns kolomoq.Namespace, cfg *SenderConfig) (*Sender, error)

NewSender returns a Sender for the media namespace ns with a random instance ID and a random key of Key ID 0, and no members. Its key tracks are published on origin.

func (Sender) Changed
func (s *Sender) Changed() <-chan struct{}

Changed returns a channel that is closed the next time the key changes.

func (Sender) Close
func (s *Sender) Close() error

Close closes the key tracks and erases the keys. Later calls fail with kolomoq.ErrClosed.

func (Sender) Format
func (s *Sender) Format(f fmt.State, _ rune)

Format prints no key material.

func (Sender) KeyID
func (s *Sender) KeyID() uint64

KeyID returns the Key ID of the current key.

func (Sender) Members
func (s *Sender) Members() []ed25519.PublicKey

Members returns the members that receive the key, in ascending order.

func (Sender) Namespace
func (s *Sender) Namespace() kolomoq.Namespace

Namespace returns the media namespace.

func (Sender) Rotate
func (s *Sender) Rotate() error

Rotate draws a new key, gives it to every member, then makes it current.

func (Sender) Seal
func (s *Sender) Seal(track string, group, object uint64, priority uint8, payload []byte, private []kolomoq.Property) ([]byte, []kolomoq.Property, error)

Seal protects one object of track under the current key and returns its payload and properties. A (group, object) not after the last one sealed for the track is refused. The Sender rotates first when the track is one more than MaxTracks or its key reached the usage limit.

func (Sender) SetMembers
func (s *Sender) SetMembers(members []ed25519.PublicKey) error

SetMembers sets who receives the key. When the set changes, the Sender rotates: the new key goes to every member's key track before it is used, and a removed member's track is closed. On error the members and the key do not change.

func (Sender) Write
func (s *Sender) Write(g *kolomoq.GroupWriter, track string, payload []byte, private ...kolomoq.Property) (uint64, error)

Write seals the next object of g, a group of track, under the track's priority inside GroupWriter.WriteObjectFunc and publishes it. Objects of one track must be written in increasing (Group ID, Object ID) order: one that is not means the track was re-created, so the Sender rotates before sealing, and a rotation per object soon goes over the receivers' MaxKeyRate.

type SenderConfig
type SenderConfig struct {
	// MaxTracks caps the tracks sealed under one key; one more rotates. Default 1024, from 1 to 1000000.
	MaxTracks int
}

SenderConfig sets a Sender. A zero field takes its default.

type Suite
type Suite uint16

Suite is an SFrame cipher suite identifier (RFC 9605 section 8.1).

const AES128GCMSHA256 Suite = 0x0004

AES128GCMSHA256 is AES_128_GCM_SHA256_128, the only suite of the profile.

Conviene saber

Sesiones

  • NewClient(ctx, conn, cfg) y NewServer(ctx, conn, cfg) intercambian el preámbulo de versión y SETUP dentro de Config.SetupTimeout y devuelven un *Session. conn es cualquier kolomoq.Conn; *kolosecure.Conn y *kolorelay.Conn la cumplen. El lado que inició la conexión ejecuta NewClient, y el que la aceptó, NewServer.
  • La sesión es dueña de la conexión: es la única que llama a AcceptStream y AcceptUniStream, y la cierra cuando termina. Close termina la sesión con NO_ERROR y espera a sus goroutines. Done y Err informan del final: ErrClosed, un *SessionError con el código de terminación, o un error de kolo-transport envuelto.
  • Cada suscripción usa un stream bidireccional y un stream unidireccional por cada grupo en vuelo. Sube el MaxIncomingStreams de kolo-transport (16 por defecto) hasta las suscripciones que esperes.
  • Config.Origin guarda los tracks que publica este lado. Sin él, las peticiones de track se responden DOES_NOT_EXIST.
  • Config.Authorize(peer, kind, namespace, track) decide cada petición del peer (SUBSCRIBE, FETCH, TRACK_STATUS, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE) según la clave de kolo-id del peer. Un error la rechaza con UNAUTHORIZED. Un SUBSCRIBE que también pide objetos en caché necesita además KindFetch. Nil lo permite todo, porque el peer ya está autenticado.
  • GoAway(ctx, timeout) envía GOAWAY, rechaza las peticiones nuevas con GOING_AWAY y cierra la sesión cuando el peer no tiene ninguna petición abierta, o con GOAWAY_TIMEOUT pasado timeout. Una segunda llamada devuelve ErrGoingAway. GoingAway() se cierra cuando el peer envió GOAWAY.
  • Stats cuenta los grupos que este lado reinició por suscriptores lentos o por streams que el peer dejó de leer (ResetGroups), y los grupos que llegaron a un timeout de entrega (ExpiredGroups).
  • SessionStats también dice cuánto se queda atrás el envío: SentBytes entregados al transporte, QueuedBytes esperando en las colas de los suscriptores y QueueDelay, la edad del objeto más antiguo sin enviar. Un publicador cuyo QueueDelay crece publica más de lo que lleva su camino, y bajar entonces su bitrate evita que sus grupos caduquen. SessionStats.Transport es el ConnStats de kolo-transport de la conexión de la sesión (tiempos de ida y vuelta, pérdidas, CongestionWindow, BytesInFlight, el controlador de congestión y los cambios de camino), así que con un QueueDelay que crece dice si el camino es lento (SmoothedRTT muy por encima de MinRTT, PacketsLost en aumento) o si el emisor no está limitado por la red (BytesInFlight muy por debajo de CongestionWindow). Viene de un método opcional Stats() kolotransport.ConnStats del Conn, que tiene *kolosecure.Conn, y es el valor cero con un Conn sin él, como un *kolorelay.Conn, y después de que la conexión termina.
  • Session.Suspend termina la sesión con CodeSuspend, un código propio de kolo-moq, para que un relay al que se dio RelayConfig.Resume conserve los anuncios del peer (mira Relay).
  • Session.RemotePublicKey devuelve una copia de la clave de kolo-id del peer, así que quien la llama no puede cambiar la identidad que ven las comprobaciones de Readers de la sesión.

Publicar

  • NewOrigin(cfg) guarda tracks y puede atender muchas sesiones. CreateTrack(ns, name, opts) devuelve un *TrackWriter. TrackOptions fija la prioridad del publicador, el orden de los grupos, los timeouts de entrega, propiedades extra del track y la caché.
  • TrackWriter.NewGroup cierra el grupo abierto y empieza el siguiente, con IDs desde 0. GroupWriter.WriteObject(payload, props...) publica el siguiente objeto y devuelve su ID. GroupWriter.Close cierra el grupo y TrackWriter.Close cierra el track: los suscriptores reciben PUBLISH_DONE TRACK_ENDED y el track sale del origin. Subscribers cuenta las suscripciones actuales.
  • Las escrituras nunca bloquean. Cada suscriptor tiene su propia cola. Cuando una cola tiene más de MaxBufferedGroups subgrupos abiertos o MaxBufferedBytes bytes, el stream del grupo más antiguo se reinicia con EXCESSIVE_LOAD solo para ese suscriptor.
  • Un TrackWriter escribe un subgrupo por grupo, el subgrupo 0. Cada grupo termina con un objeto End of Group, y el track con End of Track.
  • GroupWriter.WriteObjectFunc(build) publica el siguiente objeto con el payload y las propiedades que build devuelve para su Object ID, mientras el grupo está retenido, así que un payload que depende del ID, como uno sellado, no puede quedar emparejado con el ID de otro objeto. GroupWriter.Priority devuelve la prioridad del publicador del track del grupo.
  • TrackOptions.Readers limita un track a las claves públicas de kolo-id indicadas: un SUBSCRIBE, FETCH o TRACK_STATUS de cualquier otro peer recibe DOES_NOT_EXIST, decida lo que decida Config.Authorize, también si es nil. Un relay se suscribe a un publicador como un peer más, así que un relay que no figura en la lista no puede leer el track.
  • Los timeouts de entrega se leen de las propiedades de un objeto tanto en el nivel superior como, según exige el draft, dentro de sus Immutable Properties.
  • TrackWriter.NewGroupRequests es un canal de capacidad 1 que nunca bloquea la sesión. Se dispara cuando un suscriptor pide un grupo nuevo (mira Suscribirse): la aplicación llama entonces a NewGroup y empieza el grupo con lo que necesita quien se une, en vídeo un fotograma clave. Una petición cuyo valor no supera el mayor grupo del track se responde y se ignora, las peticiones se funden mientras hay una pendiente, y el track avisa como mucho una vez cada NewGroupRequestInterval (1 s), pidan las suscripciones que pidan: una petición dentro del intervalo se descarta. Un suscriptor que repite la petición, o que abre muchas suscripciones, no puede hacer que el publicador corte grupos más a menudo, así que una aplicación que responde a cada aviso con un fotograma clave envía como mucho uno por segundo para el track.

Prioridades

Los objetos se entregan al transporte de uno en uno por sesión, el más urgente primero: prioridad del suscriptor, luego prioridad del publicador, luego orden de grupos, luego subgrupo. Los números menores son más urgentes, y el valor por defecto es 128 (DefaultPriority). Subscription.Update cambia la prioridad del suscriptor mientras la suscripción corre. Cada suscripción o fetch tiene su propia cola de envío, y las colas de igual prioridad se turnan, así que una suscripción con IDs de grupo altos no deja sin turno a otra.

Suscribirse

  • Session.Subscribe(ctx, ns, track, opts) devuelve un *Subscription cuando el peer aceptó, o un *RequestError. SubscribeOptions fija la prioridad del suscriptor, el orden de los grupos, Join, Paused y los timeouts de entrega. Join es JoinNextObject, JoinCurrentGroup, que recibe los objetos anteriores del grupo actual desde la caché del publicador, o JoinNextGroup.
  • ReadObject(ctx) devuelve los objetos en orden de llegada con sus IDs de grupo, subgrupo y objeto, prioridad, estado y propiedades. Devuelve io.EOF cuando el publicador cerró el track, y un *PublishDoneError tras cualquier otro PUBLISH_DONE. Los grupos viajan en streams separados, así que un grupo posterior puede llegar antes que uno anterior. Un lector que se atrasa más de MaxBufferedGroups grupos o MaxBufferedBytes pierde los grupos más antiguos.
  • Update(ctx, SubscriptionUpdate{Priority, Paused}) cambia la prioridad y pausa o reanuda. Close cancela la suscripción.
  • Después de PUBLISH_DONE, una suscripción que no tiene ningún stream abierto pero sí menos streams de los que anunció el publicador espera a los que faltan solo el tiempo de su mayor timeout de entrega, cuando hay uno, en lugar de al menos RequestTimeout.
  • Subscription.RequestNewGroup(ctx) pide al publicador un grupo nuevo, para un suscriptor que perdió un grupo o acaba de unirse a un track de vídeo y no quiere esperar al siguiente. Sale como mucho una petición cada NewGroupRequestInterval (1 s) por suscripción, y una llamada más temprana devuelve ErrNewGroupTooSoon.

Caché y fetch

Cada track guarda los CacheGroups grupos más recientes dentro de CacheBytes. Quien llega tarde los lee con JoinCurrentGroup, y Session.Fetch(ctx, ns, track, opts) los pide directamente: los RecentGroups grupos más recientes, o un rango absoluto. Fetch.ReadObject los devuelve en orden y io.EOF al final. Session.TrackStatus devuelve el Largest Object y las propiedades del track sin suscribirse. Un FETCH sobre objetos que la caché ya descartó recibe un marcador End of Unknown Range en lugar de un falso "no existe".

Namespaces

Session.PublishNamespace(ctx, ns) anuncia un namespace, y PublishedNamespace.Close lo retira. Session.PeerNamespaces enumera lo que anunció el peer. Session.SubscribeNamespace(ctx, prefix) devuelve un *NamespaceSubscription cuyo Next informa de los namespaces que el peer empieza o deja de publicar bajo el prefijo. El primer campo de namespace kolo-keys (KeyNamespaceField) está reservado para los tracks de claves: PublishNamespace lo rechaza con ErrInvalidName, un PUBLISH_NAMESPACE de un peer bajo él recibe UNAUTHORIZED, y una respuesta a SUBSCRIBE_NAMESPACE nunca lo lista.

Relay

  • NewRelay(cfg) devuelve un *Relay, y Relay.NewServer y Relay.NewClient inician sus sesiones. Los publicadores anuncian namespaces con PUBLISH_NAMESPACE, que decide Config.Authorize. Un peer no puede anunciar un namespace igual a uno que anunció otro peer, ni uno que cuelgue de él.
  • Un SUBSCRIBE a un track de un namespace anunciado abre una sola suscripción hacia el publicador con el namespace coincidente más largo. Todos los suscriptores la comparten, y sus objetos se guardan en caché (CacheGroups, CacheBytes) para quienes llegan tarde y para FETCH. La suscripción hacia el publicador termina cuando se va el último suscriptor.
  • Cuando el publicador cierra el track, los suscriptores reciben su estado PUBLISH_DONE. Cuando termina la sesión del publicador, reciben GOING_AWAY solo si se envió o se recibió un GOAWAY en esa sesión, e INTERNAL_ERROR si se cerró, se perdió o se rompió sin uno. MALFORMED_TRACK significa que el relay encontró el track mal formado. Un FETCH o un TRACK_STATUS de un track que el relay no tiene se reenvía al publicador.
  • RelayConfig.MaxTracks limita los tracks reenviados a la vez y MaxSessionTracks los que abrió una sola sesión, para que un suscriptor no pueda usar todas las plazas. Un SUBSCRIBE que pase de cualquiera de los dos recibe EXCESSIVE_LOAD. MaxSessionFetches limita los FETCH de una sesión reenviados a la vez a los publicadores.
  • Un relay comprueba las reglas de track mal formado que su caché puede ver: un objeto repetido que difiere, otra prioridad dentro de un subgrupo y objetos después del final de un subgrupo, un grupo o un track. No guarda en caché el objeto que rompe una regla, termina las suscripciones descendentes con MALFORMED_TRACK y cancela la suscripción hacia el publicador.
  • RoomPolicy{Room, Member}.Authorize es un Authorize para un relay de salas. Bajo Room, un peer solo puede anunciar Room más el hex en minúsculas de su propia clave pública como un campo más, y SUBSCRIBE, FETCH, TRACK_STATUS y SUBSCRIBE_NAMESPACE se permiten solo si Member devuelve true. Un Member nil no admite a nadie. Todo lo demás, incluida cualquier petición fuera de Room, se rechaza con UNAUTHORIZED.
  • Un relay rechaza con UNAUTHORIZED toda petición bajo kolo-keys, así que los tracks de claves nunca pasan por él.
  • Un track reenviado sale del relay en cuanto llega su objeto End of Track o su PUBLISH_DONE. El siguiente SUBSCRIBE, FETCH o TRACK_STATUS por su nombre va al publicador, así que un track que el publicador cerró y volvió a crear con el mismo nombre se sirve como el nuevo, mientras los suscriptores del track cerrado todavía reciben sus últimos objetos y su final. Un track cerrado cuenta para MaxTracks y MaxSessionTracks hasta que termina su suscripción hacia el publicador o se va su último suscriptor. Un SUBSCRIBE que llega al relay antes de cualquiera de las dos señales de fin todavía se une al track cerrado y recibe su final, porque un nombre de track no distingue dos tracks: un suscriptor que sabe de uno más nuevo se suscribe otra vez.
  • Cuando la suscripción hacia el publicador de un track termina antes de que el relay entregue el track a los suscriptores que lo esperaban, estos reciben el track, sus objetos y su final, en lugar de INTERNAL_ERROR.
  • RelayConfig.Resume (desactivado por defecto, de 1 s a 1 h) permite que un publicador vuelva tras perder su conexión. Una sesión que termina porque la conexión agotó el tiempo o falló, o porque el peer llamó a Session.Suspend, conserva sus anuncios durante Resume, así que los suscriptores del namespace no ven salir al publicador. Una sesión cerrada por cualquiera de los lados los retira al momento. Cuando una sesión nueva del mismo peer anuncia el mismo namespace, toma el relevo: la sesión anterior de ese peer, si aún funciona, se cierra y sus tracks reenviados terminan, así que los suscriptores se suscriben de nuevo y llegan a la sesión nueva. Un anuncio retenido queda reservado para su peer: ningún otro peer puede anunciar su namespace ni uno debajo de él (UNAUTHORIZED), y una petición de un track bajo él nunca se encamina a otro peer, aunque haya anunciado un namespace más amplio, así que recibe DOES_NOT_EXIST hasta que el publicador vuelve o termina Resume. La retención acaba cuando el peer anuncia de nuevo el namespace, cuando esa sesión posterior se cierra limpiamente o cuando termina Resume. El relay guarda solo el namespace y la clave del peer de un anuncio retenido, no la sesión terminada, y retiene como mucho MaxResumeHeld anuncios, MaxPeerResumeHeld por clave de peer; uno que no cabe se retira con su sesión.
  • Un relay pasa una petición de grupo nuevo de un track reenviado al publicador por su suscripción hacia él, como mucho una a la vez y una por segundo.

Objetos protegidos

El paquete secobj es el perfil de Kolo de MoQ Secure Objects, draft-ietf-moq-secure-objects-01. Sella los objetos de un track para que un relay los reenvíe sin poder leer el payload. Sus objetos usan las codificaciones de draft-ietf-moq-transport-22, así que no interoperan con otras implementaciones de Secure Objects.

Todos los pasos

Objetos sellados antes del relay

La clave llega a cada miembro por su propia sesión, nunca por el relay. El relay transporta y guarda en caché objetos sellados. Sin la clave del Key ID de un objeto, un miembro no puede abrirlo.

  1. El emisor entrega su clave a cada miembro en un track de claves que solo ese miembro puede leer, por su sesión directa. Un relay rechaza el namespace kolo-keys, así que la clave nunca pasa por él.
  2. Sender.Write sella cada objeto. El payload y las propiedades privadas se cifran, y el Group ID, el Object ID, la prioridad y el Key ID se autentican.
  3. El relay recibe el objeto sellado. Ve el namespace, el nombre del track, los IDs, la prioridad, el Key ID, el tamaño y los tiempos, no el payload.
  4. El relay reenvía el objeto y lo guarda en su caché, como hace con cualquier otro.
  5. El Opener del miembro abre el objeto con la clave de su Key ID. Sin clave devuelve ErrNoKey, y un objeto que falla la autenticación devuelve ErrAuthentication.

Qué se protege:

  • El payload y las propiedades privadas de cada objeto, con AES-128-GCM (AES128GCMSHA256, la única suite). La clave y la sal de un track salen de HKDF-SHA256 sobre una clave base de 16 bytes, el Key ID y el nombre completo del track.
  • El Group ID, el Object ID, la prioridad del publicador y las Immutable Properties se autentican. La única propiedad visible es el Key ID, dentro de las Immutable Properties (PropertyKeyID, 0x78). El nonce contiene un Object ID de 32 bits, así que un Object ID debe ser menor que 2^32 (ErrObjectID).

Qué sigue viendo y qué puede hacer un relay:

  • Ve el namespace, el nombre del track, los Group ID y Object ID, la prioridad, el Key ID, los tamaños y los tiempos, el estado del objeto y las propiedades del track. El estado del objeto y las propiedades del track no están autenticados.
  • Puede descartar, retrasar, reordenar o retener objetos y terminar tracks. Un objeto cuyo payload, IDs, prioridad o Key ID cambie falla la autenticación en el receptor.

Qué recibe un participante sin las claves:

  • Nada que pueda abrir. Opener.Open devuelve ErrNoKey para un Key ID más nuevo que las claves que tiene, ErrKeyRetired para uno más antiguo, ErrAuthentication para un objeto que falla la autenticación, ErrNotProtected para un objeto sin Immutable Properties y ErrReplay para uno que ya abrió.
  • Keyring.Receive se rechaza hasta que el dueño del namespace hace miembro al participante, y devuelve ese error.
  • Keyring.Opener(session, ns, track) falla con ErrWrongSession salvo que el peer de la sesión sea el dueño de ns o un relay incluido en KeyringConfig.Relays, así que un miembro no puede servir los tracks de otro miembro en su propia sesión.

Manejo de las claves, tal como lo ofrece el paquete:

  • NewSender(origin, ns, cfg) crea un Sender para el namespace de medios ns, con un ID de instancia aleatorio, una clave aleatoria de 16 bytes con Key ID 0 y sin miembros. SetMembers(members) entrega la clave a cada miembro en su propio track de claves, KeyNamespace(ns) y KeyTrack(member) (el hex en minúsculas de su clave), que solo ese miembro puede leer, y cierra el track de un miembro retirado. Cuando el conjunto cambia, el Sender rota: la clave nueva llega al track de claves de cada miembro antes de usarse. Tu aplicación decide quiénes son los miembros.
  • El Sender también rota para un track creado de nuevo, al pasar de SenderConfig.MaxTracks y a las 2^24 unidades de 16 KiB de texto plano por clave de track. Rotate fuerza una rotación, Changed se cierra con cada clave nueva y KeyID devuelve el Key ID actual.
  • Write(g, track, payload, private...) sella el siguiente objeto de un grupo con la prioridad de su track, dentro de WriteObjectFunc, y lo publica. Seal devuelve el payload y las propiedades sellados sin publicar. Escribe los objetos de cada track en orden creciente de (Group ID, Object ID): un objeto fuera de orden significa un track creado de nuevo, así que el Sender rota, y una rotación por objeto supera pronto el MaxKeyRate de los receptores.
  • Las claves viajan solo por tracks de claves, que solo su miembro puede leer, por la sesión entre el emisor y ese miembro. Un relay rechaza el campo de namespace reservado kolo-keys, así que nunca pasan por él.
  • NewKeyring(cfg) crea el lado receptor. KeyringConfig.Authorize(peer, ns) es obligatorio y dice qué peer es dueño de qué namespace. Receive(ctx, session, self, ns) toma las claves que el peer de la sesión entrega para ns en el track de claves de self, y solo si Authorize dice que ese peer es dueño de ns.
  • Un Keyring guarda la clave actual y la que reemplazó. La clave reemplazada abre objetos durante Retain (450 ms) después del primer objeto bajo su sucesora, y durante RetainMax como máximo después de que llegó su sucesora, así que un miembro retirado que la conservó no puede usarla mucho tiempo aunque un relay retenga los objetos más nuevos.
  • Cada lector de un track, como una suscripción, abre los objetos con su propio Opener, con su propia ventana de repeticiones, así que varios lectores pueden compartir un Keyring. MayCarry, Changed, Remove(ns), que borra las claves de un namespace, y Stats, que cuenta los mensajes de clave Rejected y Dropped, lo completan.
  • Las claves nunca se escriben en disco y se imprimen ocultas. Las claves base y las sales se sobrescriben al reemplazarlas, quitarlas o cerrar. Los key schedules de AES y los mensajes de clave que quedan en cachés de tracks de claves y en buffers del transporte se liberan, no se sobrescriben, y Go no garantiza que no quede ninguna copia en memoria.

Qué no ofrece el paquete:

  • Una lista de miembros. La aplicación entrega a SetMembers los participantes que autoriza.
  • Una firma por emisor. Cada miembro tiene la clave de cada emisor, así que un miembro que controla el relay, o que se coluda con su operador, puede crear objetos que parecen venir de otro miembro. Con un relay honesto con RoomPolicy, y en una sesión directa, un miembro no puede.
  • Secreto hacia adelante dentro de una generación de clave, ni recuperación tras un compromiso. Quien tenga la clave de un emisor lee los objetos de ese emisor.
  • AES-GCM en tiempo constante en toda CPU. El AES-GCM de Go es de tiempo constante solo en su ensamblador para CPUs amd64 y arm64 con instrucciones AES, ppc64x y s390x. En 386, arm, riscv64, loong64, mips, wasm, y en CPUs amd64 o arm64 sin instrucciones AES, es código genérico que no es de tiempo constante.

kolo-media usa secobj para los broadcasts protegidos y trae un programa completo.

Límites

Un campo en cero toma el valor por defecto, y un valor fuera de rango devuelve ErrInvalidConfig. Las tablas completas están en Límites.

  • SetupTimeout y RequestTimeout, 10 s cada uno, de 1 s a 10 min.
  • MaxRequests y MaxSubscriptions, 1000 cada uno. Las que superan ese número se rechazan con EXCESSIVE_LOAD.
  • MaxObjectSize, 16 MiB, de 1 KiB a 1 GiB, para un payload recibido del peer. OriginConfig.MaxObjectSize es el mismo límite para un payload escrito en el origin.
  • MaxBufferedGroups, 64, y MaxBufferedBytes, 32 MiB o MaxObjectSize si es mayor, por suscripción en ambos lados.
  • MaxFetchBytes, igual que MaxBufferedBytes: los objetos en caché que se retienen a la vez para los FETCH y los rellenos del peer.
  • TrackOptions.CacheGroups, 16, y CacheBytes, 32 MiB, por track. RelayConfig tiene los mismos dos para cada track reenviado.
  • RelayConfig.MaxTracks, 1000, MaxSessionTracks, la décima parte, y MaxSessionFetches, 16.
  • RelayConfig.Resume, desactivado por defecto, de 1 s a 1 h. RelayConfig.MaxResumeHeld, 10000, de 1 a 1000000: anuncios retenidos a la vez para sesiones terminadas. RelayConfig.MaxPeerResumeHeld, el MaxRequests de la sesión (1000) o MaxResumeHeld si es menor: anuncios retenidos para una clave de peer.
  • Un track avisa en TrackWriter.NewGroupRequests como mucho una vez cada NewGroupRequestInterval (1 s), sea cual sea el número de suscripciones.
  • Cada objeto cuenta su payload, 48 bytes por propiedad y 64 bytes para MaxBufferedBytes y la caché, así que los objetos vacíos no son gratis. Un payload de más de 64 KiB se lee a medida que llega, así que un peer que anuncia un objeto grande y no envía nada no reserva memoria.
  • secobj: KeyringConfig.Retain, 450 ms, y RetainMax, Retain más 400 ms; MaxSenders, 64; MaxKeyRate, 64 mensajes de clave por segundo y namespace; ReplayGroups, 64, y ReplayObjects, 8192, por Opener; y SenderConfig.MaxTracks, 1024. Una clave de track sella como máximo 2^24 unidades de 16 KiB de texto plano, y después el Sender rota. Los rangos están en Límites.

Seguridad

  • Una frase de motivo de un peer se guarda en Reason, de 1024 bytes como máximo y escapada, y nunca va en Error(). PeerImplementation se recorta a 1024 bytes y se escapa.
  • Cada decodificador tiene un fuzz target. Los mensajes de control de más de 65535 bytes se rechazan, no se recortan.
  • Un stream que no avanza durante RequestTimeout se reinicia, así que un peer que deja de leer no frena a los demás. Un relay lee de una vez un FETCH reenviado en un búfer acotado y lo reinicia cuando el suscriptor se atrasa demasiado.
  • Las revisiones de seguridad y de Go encontraron problemas que están corregidos con tests.

Estándares

kolo-moq implementa draft-ietf-moq-transport-22 solo sobre streams, porque las conexiones Kolo son QUIC con ALPN kolo/0 y no tienen datagramas. Cada stream de control empieza con el preámbulo moqt-22. Un peer cuyo stream de control empieza de otra forma se cierra con PROTOCOL_VIOLATION, y la sesión devuelve ErrVersion.

  • Implementado: SETUP, GOAWAY, SUBSCRIBE, REQUEST_UPDATE, FETCH, TRACK_STATUS, PUBLISH_DONE, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE, prioridades del suscriptor y del publicador, orden de grupos, timeouts de entrega y las reglas de la sección 12.1 que una caché de relay puede comprobar.
  • Respondido con NOT_SUPPORTED: PUBLISH, SUBSCRIBE_TRACKS y las actualizaciones de prefijo de namespace. Los filtros de rango reciben INVALID_FILTER.
  • No hecho: el relay se suscribe a un solo publicador por track, no a todos los que coinciden, como pide la sección 7.6, y RENDEZVOUS_TIMEOUT no se respeta. NEW_GROUP_REQUEST sí se respeta en REQUEST_UPDATE: Subscription.RequestNewGroup lo envía y TrackWriter.NewGroupRequests avisa al publicador. Un suscriptor que no es un relay comprueba solo las reglas de track mal formado que muestra un único objeto.
  • El draft 22 es un borrador en movimiento, así que un draft posterior será un cambio incompatible.

Estado

  • Hecho: sesiones, publicar, suscribirse, fetch, namespaces, relay, prioridades y timeouts de entrega, e interoperabilidad con una segunda implementación del draft 22 en ambos sentidos.
  • Hecho: el paquete secobj para objetos protegidos de extremo a extremo a través de relays, los tracks de claves, TrackOptions.Readers y RoomPolicy.
  • Probada en macOS (arm64): go test, go test -race y la suite de interoperabilidad pasan. En Linux y Windows pasa go vet y los tests no se ejecutaron.
  • Experimental. La API puede cambiar antes de v1.0.0.

Errores

ErrorMensaje
ErrClosedkolomoq: closed
ErrGoingAwaykolomoq: session is going away
ErrInvalidConfigkolomoq: invalid config
ErrInvalidNamekolomoq: invalid namespace or track name
ErrInvalidPropertykolomoq: invalid property
ErrMalformedTrackkolomoq: malformed track
ErrNewGroupTooSoonkolomoq: new group requested too soon
ErrObjectTooLargekolomoq: object too large
ErrProtocolkolomoq: protocol violation
ErrRequestCanceledkolomoq: request canceled by peer
ErrTimeoutkolomoq: timeout
ErrTooManyNamespaceskolomoq: too many namespaces
ErrTooManyTrackskolomoq: too many tracks
ErrTrackExistskolomoq: track exists
ErrUnsupportedPropertykolomoq: unsupported mandatory track property
ErrVersionkolomoq: peer speaks another MoQ Transport version
secobj.ErrAuthenticationkolomoq: secobj: authentication failed
secobj.ErrInvalidConfigkolomoq: secobj: invalid config
secobj.ErrKeyMessagekolomoq: secobj: malformed key message
secobj.ErrKeyRetiredkolomoq: secobj: key retired
secobj.ErrMalformedkolomoq: secobj: malformed object
secobj.ErrNoKeykolomoq: secobj: no key for this key ID
secobj.ErrNotProtectedkolomoq: secobj: object not protected
secobj.ErrObjectIDkolomoq: secobj: object ID not allowed
secobj.ErrReplaykolomoq: secobj: replayed object
secobj.ErrTooManySenderskolomoq: secobj: too many senders
secobj.ErrUnauthorizedkolomoq: secobj: unauthorized key message
secobj.ErrWrongSessionkolomoq: secobj: session may not carry this namespace

Comprueba los errores centinela con errors.Is. *SessionError, *RequestError y *PublishDoneError llevan el código del draft (SessionCode, RequestCode, DoneCode), y errors.As los lee. Los errores de las peticiones, de Fetch.ReadObject, de Update y de GoAway empiezan por kolomoq: y envuelven su causa. Los errores de secobj empiezan con kolomoq: secobj:.

Referencias