kolo docsbeta

kolo-moq

Publique, assine e repasse tracks ao vivo por conexões Kolo, com MoQ Transport draft 22. Um relay compartilha uma assinatura para o publicador entre muitos assinantes, e o pacote secobj sela os objetos para que um relay os repasse sem lê-los.

Nesta página

A kolo-moq implementa o MoQ Transport, draft-ietf-moq-transport-22, sobre uma conexão que a kolo-secure ou a kolo-relay já autenticou. Um publicador escreve tracks formados por grupos de objetos. Os assinantes recebem um track ao vivo, ou pedem grupos em cache com um fetch, e um relay distribui um track para muitos assinantes. Ela não sabe nada de mídia: qualquer dado de aplicação pode ser um track. O pacote secobj sela os objetos de um track para que um relay os repasse sem conseguir ler o payload, com um perfil da Kolo do draft-ietf-moq-secure-objects-01. Os pacotes Go são kolomoq e secobj.

Todos os passos

Um relay compartilha uma assinatura

Por mais assinantes que peçam um track, o publicador escreve cada objeto uma só vez. O relay lê os objetos que repassa, a menos que estejam selados, e guarda os grupos mais recentes no cache.

  1. O publicador se conecta ao relay e anuncia um namespace com PUBLISH_NAMESPACE. O Config.Authorize pode recusá-lo.
  2. Um assinante envia SUBSCRIBE para um track desse namespace. O relay abre um único SUBSCRIBE para o publicador.
  3. Mais assinantes pedem o mesmo track. Eles entram na assinatura para o publicador que já está aberta, então o publicador continua escrevendo cada objeto uma só vez.
  4. O publicador escreve objetos no relay, que repassa cada um a todos os assinantes e guarda no cache os grupos mais recentes do track (16 grupos e 32 MiB por padrão).
  5. Um assinante que chega tarde lê os grupos em cache do relay, com JoinCurrentGroup ou um FETCH. A assinatura para o publicador termina quando o último assinante sai.

Instalação

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

Para fixar esta versão, rode go get github.com/ciranda-dev/kolo-moq@v0.1.0. Ela é só Go, sem cgo e sem nada para instalar, então compila com CGO_ENABLED=0. Precisa do Go 1.26 ou mais novo. Os dois pacotes estão no mesmo módulo.

Início rápido

Um publicador e um assinante se encontram por meio de um relay, tudo em 127.0.0.1. O relay escuta e atende todo peer que se conecta. O publicador se conecta a ele e anuncia o namespace demo, o assinante se conecta ao mesmo relay e assina o track chat, e o publicador escreve um grupo de três objetos e encerra o 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
}

Ele imprime:

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

O repositório também traz examples/publisher e examples/subscriber, que rodam os dois lados como programas separados e recebem o endereço e um arquivo de chave de identidade como flags, e examples/basic, que conecta os dois diretamente, sem relay.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote 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.

Variáveis

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.

Pacote 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.

Variáveis

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")
)

Funções

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.

Bom saber

Sessões

  • NewClient(ctx, conn, cfg) e NewServer(ctx, conn, cfg) trocam o preâmbulo de versão e o SETUP dentro de Config.SetupTimeout e devolvem um *Session. conn é qualquer kolomoq.Conn; *kolosecure.Conn e *kolorelay.Conn a satisfazem. O lado que iniciou a conexão roda NewClient, e o que a aceitou, NewServer.
  • A sessão é dona da conexão: é a única que chama AcceptStream e AcceptUniStream, e a fecha quando termina. Close encerra a sessão com NO_ERROR e espera as suas goroutines. Done e Err informam o fim: ErrClosed, um *SessionError com o código de encerramento, ou um erro da kolo-transport embrulhado.
  • Cada assinatura usa um stream bidirecional e um stream unidirecional por grupo em andamento. Aumente o MaxIncomingStreams da kolo-transport (16 por padrão) até as assinaturas que você espera.
  • Config.Origin guarda os tracks que este lado publica. Sem ele, os pedidos de track são respondidos com DOES_NOT_EXIST.
  • Config.Authorize(peer, kind, namespace, track) decide cada pedido do peer (SUBSCRIBE, FETCH, TRACK_STATUS, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE) pela chave da kolo-id do peer. Um erro o recusa com UNAUTHORIZED. Um SUBSCRIBE que também pede objetos em cache precisa também de KindFetch. Nil permite tudo, porque o peer já está autenticado.
  • GoAway(ctx, timeout) envia GOAWAY, recusa os pedidos novos com GOING_AWAY e fecha a sessão quando o peer não tem nenhum pedido aberto, ou com GOAWAY_TIMEOUT depois de timeout. Uma segunda chamada devolve ErrGoingAway. GoingAway() é fechado quando o peer enviou GOAWAY.
  • Stats conta os grupos que este lado reiniciou por assinantes lentos ou por streams que o peer parou de ler (ResetGroups), e os grupos que atingiram um timeout de entrega (ExpiredGroups).
  • SessionStats também diz o quanto o envio fica para trás: SentBytes entregues ao transporte, QueuedBytes esperando nas filas dos assinantes e QueueDelay, a idade do objeto mais antigo ainda não enviado. Um publicador cujo QueueDelay cresce publica mais do que o seu caminho carrega, e baixar então o bitrate evita que os grupos dele expirem. SessionStats.Transport é o ConnStats da kolo-transport da conexão da sessão (tempos de ida e volta, perdas, CongestionWindow, BytesInFlight, o controlador de congestionamento e as mudanças de caminho), então com um QueueDelay que cresce ele diz se o caminho está lento (SmoothedRTT bem acima de MinRTT, PacketsLost subindo) ou se quem envia não está limitado pela rede (BytesInFlight bem abaixo de CongestionWindow). Ele vem de um método opcional Stats() kolotransport.ConnStats do Conn, que o *kolosecure.Conn tem, e é o valor zero para um Conn sem ele, como um *kolorelay.Conn, e depois que a conexão termina.
  • Session.Suspend encerra a sessão com CodeSuspend, um código próprio da kolo-moq, para que um relay que recebeu RelayConfig.Resume guarde os anúncios do peer (veja Relay).
  • Session.RemotePublicKey devolve uma cópia da chave kolo-id do peer, então quem a chama não consegue mudar a identidade que as verificações de Readers da sessão enxergam.

Publicar

  • NewOrigin(cfg) guarda tracks e pode atender muitas sessões. CreateTrack(ns, name, opts) devolve um *TrackWriter. TrackOptions define a prioridade do publicador, a ordem dos grupos, os timeouts de entrega, propriedades extras do track e o cache.
  • TrackWriter.NewGroup encerra o grupo aberto e começa o próximo, com IDs a partir de 0. GroupWriter.WriteObject(payload, props...) publica o próximo objeto e devolve o ID dele. GroupWriter.Close encerra o grupo e TrackWriter.Close encerra o track: os assinantes recebem PUBLISH_DONE TRACK_ENDED e o track sai do origin. Subscribers conta as assinaturas atuais.
  • As escritas nunca bloqueiam. Cada assinante tem a sua própria fila. Quando uma fila tem mais de MaxBufferedGroups subgrupos abertos ou MaxBufferedBytes bytes, o stream do grupo mais antigo é reiniciado com EXCESSIVE_LOAD só para aquele assinante.
  • Um TrackWriter escreve um subgrupo por grupo, o subgrupo 0. Cada grupo termina com um objeto End of Group, e o track com End of Track.
  • GroupWriter.WriteObjectFunc(build) publica o próximo objeto com o payload e as propriedades que build devolve para o seu Object ID, enquanto o grupo está retido, então um payload que depende do ID, como um selado, não pode ser pareado com o ID de outro objeto. GroupWriter.Priority devolve a prioridade do publicador do track do grupo.
  • TrackOptions.Readers limita um track às chaves públicas kolo-id listadas: um SUBSCRIBE, FETCH ou TRACK_STATUS de qualquer outro peer recebe DOES_NOT_EXIST, seja qual for a decisão do Config.Authorize, também quando ele é nil. Um relay assina um publicador como um peer próprio, então um relay que não está na lista não consegue ler o track.
  • Os timeouts de entrega são lidos das propriedades de um objeto tanto no nível superior quanto, como o draft exige, dentro das suas Immutable Properties.
  • TrackWriter.NewGroupRequests é um canal de capacidade 1 que nunca bloqueia a sessão. Ele dispara quando um assinante pede um grupo novo (veja Assinar): a aplicação então chama NewGroup e começa o grupo com o que quem entra precisa, em vídeo um quadro chave. Uma requisição cujo valor não passa do maior grupo do track é respondida e ignorada, as requisições se fundem enquanto há uma pendente, e o track avisa no máximo uma vez a cada NewGroupRequestInterval (1 s), não importa quantas assinaturas peçam: uma requisição dentro do intervalo é descartada. Um assinante que repete a requisição, ou que abre muitas assinaturas, não consegue fazer o publicador cortar grupos com mais frequência, então uma aplicação que responde a cada aviso com um quadro chave envia no máximo um por segundo para o track.

Prioridades

Os objetos são entregues ao transporte um de cada vez por sessão, o mais urgente primeiro: prioridade do assinante, depois prioridade do publicador, depois ordem dos grupos, depois subgrupo. Números menores são mais urgentes, e o padrão é 128 (DefaultPriority). Subscription.Update muda a prioridade do assinante enquanto a assinatura roda. Cada assinatura ou fetch tem a sua própria fila de envio, e as filas de mesma prioridade se revezam, então uma assinatura com IDs de grupo altos não deixa outra sem vez.

Assinar

  • Session.Subscribe(ctx, ns, track, opts) devolve um *Subscription quando o peer aceitou, ou um *RequestError. SubscribeOptions define a prioridade do assinante, a ordem dos grupos, Join, Paused e os timeouts de entrega. Join é JoinNextObject, JoinCurrentGroup, que recebe os objetos anteriores do grupo atual a partir do cache do publicador, ou JoinNextGroup.
  • ReadObject(ctx) devolve os objetos na ordem de chegada com os IDs de grupo, subgrupo e objeto, prioridade, estado e propriedades. Devolve io.EOF quando o publicador encerrou o track, e um *PublishDoneError depois de qualquer outro PUBLISH_DONE. Os grupos viajam em streams separados, então um grupo posterior pode chegar antes de um anterior. Um leitor que fica mais de MaxBufferedGroups grupos ou MaxBufferedBytes para trás perde os grupos mais antigos.
  • Update(ctx, SubscriptionUpdate{Priority, Paused}) muda a prioridade e pausa ou retoma. Close cancela a assinatura.
  • Depois do PUBLISH_DONE, uma assinatura que não tem nenhum stream aberto mas tem menos streams do que o publicador anunciou espera pelos que faltam só o tempo do seu maior timeout de entrega, quando há um, em vez de pelo menos RequestTimeout.
  • Subscription.RequestNewGroup(ctx) pede ao publicador um grupo novo, para um assinante que perdeu um grupo ou acabou de entrar em um track de vídeo e não quer esperar o próximo. No máximo uma requisição sai a cada NewGroupRequestInterval (1 s) por assinatura, e uma chamada mais cedo retorna ErrNewGroupTooSoon.

Cache e fetch

Cada track guarda os CacheGroups grupos mais recentes dentro de CacheBytes. Quem chega tarde os lê com JoinCurrentGroup, e Session.Fetch(ctx, ns, track, opts) os pede diretamente: os RecentGroups grupos mais recentes, ou um intervalo absoluto. Fetch.ReadObject os devolve em ordem e io.EOF no fim. Session.TrackStatus devolve o Largest Object e as propriedades do track sem assinar. Um FETCH sobre objetos que o cache já descartou recebe um marcador End of Unknown Range em vez de um falso "não existe".

Namespaces

Session.PublishNamespace(ctx, ns) anuncia um namespace, e PublishedNamespace.Close o retira. Session.PeerNamespaces lista o que o peer anunciou. Session.SubscribeNamespace(ctx, prefix) devolve um *NamespaceSubscription cujo Next informa os namespaces que o peer começa ou deixa de publicar sob o prefixo. O primeiro campo de namespace kolo-keys (KeyNamespaceField) é reservado para os tracks de chaves: PublishNamespace o recusa com ErrInvalidName, um PUBLISH_NAMESPACE de um peer sob ele recebe UNAUTHORIZED, e uma resposta a SUBSCRIBE_NAMESPACE nunca o lista.

Relay

  • NewRelay(cfg) devolve um *Relay, e Relay.NewServer e Relay.NewClient iniciam as sessões dele. Os publicadores anunciam namespaces com PUBLISH_NAMESPACE, o que o Config.Authorize decide. Um peer não pode anunciar um namespace igual a um que outro peer anunciou, nem um que fique abaixo dele.
  • Um SUBSCRIBE a um track de um namespace anunciado abre uma única assinatura para o publicador com o namespace correspondente mais longo. Todos os assinantes a compartilham, e os objetos dela ficam em cache (CacheGroups, CacheBytes) para quem chega tarde e para o FETCH. A assinatura para o publicador termina quando o último assinante sai.
  • Quando o publicador encerra o track, os assinantes recebem o estado PUBLISH_DONE dele. Quando a sessão do publicador termina, eles recebem GOING_AWAY só se um GOAWAY foi enviado ou recebido nessa sessão, e INTERNAL_ERROR se ela foi fechada, perdida ou quebrada sem um. MALFORMED_TRACK significa que o relay achou o track malformado. Um FETCH ou um TRACK_STATUS de um track que o relay não tem é repassado ao publicador.
  • RelayConfig.MaxTracks limita os tracks repassados ao mesmo tempo e MaxSessionTracks os que uma única sessão abriu, para que um assinante não ocupe todas as vagas. Um SUBSCRIBE além de qualquer um dos dois recebe EXCESSIVE_LOAD. MaxSessionFetches limita os FETCH de uma sessão repassados aos publicadores ao mesmo tempo.
  • Um relay confere as regras de track malformado que o cache dele consegue ver: um objeto repetido que difere, outra prioridade dentro de um subgrupo e objetos depois do fim de um subgrupo, de um grupo ou de um track. Ele não guarda no cache o objeto que quebra uma regra, encerra as assinaturas dos assinantes com MALFORMED_TRACK e cancela a assinatura para o publicador.
  • RoomPolicy{Room, Member}.Authorize é um Authorize para um relay de salas. Sob Room, um peer só pode anunciar Room mais o hex em minúsculas da sua própria chave pública como mais um campo, e SUBSCRIBE, FETCH, TRACK_STATUS e SUBSCRIBE_NAMESPACE só são permitidos se Member devolver true. Um Member nil não admite ninguém. Todo o resto, inclusive qualquer pedido fora de Room, é recusado com UNAUTHORIZED.
  • Um relay recusa com UNAUTHORIZED todo pedido sob kolo-keys, então os tracks de chaves nunca passam por ele.
  • Um track repassado sai do relay assim que chega o seu objeto End of Track ou o seu PUBLISH_DONE. O próximo SUBSCRIBE, FETCH ou TRACK_STATUS pelo seu nome vai ao publicador, então um track que o publicador encerrou e criou de novo com o mesmo nome é servido como o novo, enquanto os assinantes do track encerrado ainda recebem os seus últimos objetos e o seu fim. Um track encerrado conta para MaxTracks e MaxSessionTracks até a sua assinatura para o publicador terminar ou o seu último assinante sair. Um SUBSCRIBE que chega ao relay antes de qualquer um dos dois sinais de fim ainda entra no track encerrado e recebe o seu fim, porque o nome de um track não distingue dois tracks: um assinante que sabe de um mais novo assina de novo.
  • Quando a assinatura para o publicador de um track termina antes de o relay entregar o track aos assinantes que o esperavam, eles recebem o track, os seus objetos e o seu fim, em vez de INTERNAL_ERROR.
  • RelayConfig.Resume (desligado por padrão, de 1 s a 1 h) deixa um publicador voltar depois de perder a conexão. Uma sessão que termina porque a conexão estourou o tempo ou falhou, ou porque o peer chamou Session.Suspend, guarda os anúncios por Resume, então os assinantes do namespace não veem o publicador sair. Uma sessão fechada por qualquer dos lados os retira na hora. Quando uma sessão nova do mesmo peer anuncia o mesmo namespace, ela assume: a sessão anterior desse peer, se ainda roda, é fechada e os tracks repassados dela terminam, então os assinantes assinam de novo e chegam à sessão nova. Um anúncio retido fica reservado para o peer dele: nenhum outro peer pode anunciar o namespace dele nem um abaixo dele (UNAUTHORIZED), e uma requisição de um track abaixo dele nunca é encaminhada a outro peer, mesmo um que anunciou um namespace mais amplo, então ela recebe DOES_NOT_EXIST até o publicador voltar ou o Resume acabar. A retenção termina quando o peer anuncia o namespace de novo, quando essa sessão posterior fecha de forma limpa ou quando o Resume acaba. O relay guarda só o namespace e a chave do peer de um anúncio retido, não a sessão encerrada, e retém no máximo MaxResumeHeld anúncios, MaxPeerResumeHeld por chave de peer; um que não cabe é retirado com a sessão dele.
  • Um relay repassa uma requisição de grupo novo de um track repassado ao publicador pela sua assinatura para ele, no máximo uma de cada vez e uma por segundo.

Objetos protegidos

O pacote secobj é o perfil da Kolo do MoQ Secure Objects, draft-ietf-moq-secure-objects-01. Ele sela os objetos de um track para que um relay os repasse sem conseguir ler o payload. Os objetos dele usam as codificações do draft-ietf-moq-transport-22, então não interoperam com outras implementações de Secure Objects.

Todos os passos

Objetos selados antes do relay

A chave chega a cada membro pela sua própria sessão, nunca pelo relay. O relay transporta e guarda em cache objetos selados. Sem a chave do Key ID de um objeto, um membro não consegue abri-lo.

  1. O remetente entrega a sua chave a cada membro em um track de chaves que só esse membro pode ler, pela sessão direta. Um relay recusa o namespace kolo-keys, então a chave nunca passa por ele.
  2. Sender.Write sela cada objeto. O payload e as propriedades privadas são cifrados, e o Group ID, o Object ID, a prioridade e o Key ID são autenticados.
  3. O relay recebe o objeto selado. Ele vê o namespace, o nome do track, os IDs, a prioridade, o Key ID, o tamanho e os tempos, não o payload.
  4. O relay repassa o objeto e o guarda no cache, como faz com qualquer outro.
  5. O Opener do membro abre o objeto com a chave do seu Key ID. Sem a chave ele devolve ErrNoKey, e um objeto que falha na autenticação devolve ErrAuthentication.

O que é protegido:

  • O payload e as propriedades privadas de cada objeto, com AES-128-GCM (AES128GCMSHA256, a única suíte). A chave e o sal de um track vêm de HKDF-SHA256 sobre uma chave base de 16 bytes, o Key ID e o nome completo do track.
  • O Group ID, o Object ID, a prioridade do publicador e as Immutable Properties são autenticados. A única propriedade visível é o Key ID, dentro das Immutable Properties (PropertyKeyID, 0x78). O nonce contém um Object ID de 32 bits, então um Object ID precisa ser menor que 2^32 (ErrObjectID).

O que um relay ainda vê e pode fazer:

  • Ele vê o namespace, o nome do track, os Group ID e Object ID, a prioridade, o Key ID, os tamanhos e os tempos, o estado do objeto e as propriedades do track. O estado do objeto e as propriedades do track não são autenticados.
  • Ele pode descartar, atrasar, reordenar ou reter objetos e encerrar tracks. Um objeto cujo payload, IDs, prioridade ou Key ID ele altere falha na autenticação no receptor.

O que um participante sem as chaves recebe:

  • Nada que consiga abrir. Opener.Open devolve ErrNoKey para um Key ID mais novo que as chaves que ele tem, ErrKeyRetired para um mais antigo, ErrAuthentication para um objeto que falha na autenticação, ErrNotProtected para um objeto sem Immutable Properties e ErrReplay para um que ele já abriu.
  • Keyring.Receive é recusado até que o dono do namespace torne o participante um membro, e devolve esse erro.
  • Keyring.Opener(session, ns, track) falha com ErrWrongSession a menos que o peer da sessão seja o dono de ns ou um relay listado em KeyringConfig.Relays, então um membro não consegue servir os tracks de outro membro na sua própria sessão.

Como o pacote trata as chaves:

  • NewSender(origin, ns, cfg) cria um Sender para o namespace de mídia ns, com um ID de instância aleatório, uma chave aleatória de 16 bytes com Key ID 0 e nenhum membro. SetMembers(members) entrega a chave a cada membro no seu próprio track de chaves, KeyNamespace(ns) e KeyTrack(member) (o hex em minúsculas da chave dele), que só esse membro pode ler, e fecha o track de um membro removido. Quando o conjunto muda, o Sender faz a rotação: a chave nova chega ao track de chaves de cada membro antes de ser usada. A sua aplicação decide quem são os membros.
  • O Sender também faz a rotação para um track criado de novo, ao passar de SenderConfig.MaxTracks e em 2^24 unidades de 16 KiB de texto claro por chave de track. Rotate força uma rotação, Changed é fechado a cada chave nova e KeyID devolve o Key ID atual.
  • Write(g, track, payload, private...) sela o próximo objeto de um grupo com a prioridade do seu track, dentro de WriteObjectFunc, e o publica. Seal devolve o payload e as propriedades selados sem publicar. Escreva os objetos de cada track em ordem crescente de (Group ID, Object ID): um objeto fora de ordem significa um track criado de novo, então o Sender faz a rotação, e uma rotação por objeto logo passa do MaxKeyRate dos receptores.
  • As chaves viajam só por tracks de chaves, que só o seu membro pode ler, pela sessão entre o remetente e esse membro. Um relay recusa o campo de namespace reservado kolo-keys, então elas nunca passam por ele.
  • NewKeyring(cfg) cria o lado receptor. KeyringConfig.Authorize(peer, ns) é obrigatório e diz qual peer é dono de qual namespace. Receive(ctx, session, self, ns) pega as chaves que o peer da sessão entrega para ns no track de chaves de self, e só se o Authorize disser que esse peer é dono de ns.
  • Um Keyring guarda a chave atual e a que ela substituiu. A chave substituída abre objetos por Retain (450 ms) depois do primeiro objeto sob a sucessora, e por RetainMax no máximo depois que a sucessora chegou, então um membro removido que a guardou não consegue usá-la por muito tempo mesmo que um relay retenha os objetos mais novos.
  • Cada leitor de um track, como uma assinatura, abre os objetos pelo seu próprio Opener, com a sua própria janela de repetições, então vários leitores podem compartilhar um Keyring. MayCarry, Changed, Remove(ns), que apaga as chaves de um namespace, e Stats, que conta as mensagens de chave Rejected e Dropped, completam o conjunto.
  • As chaves nunca são gravadas em disco e são impressas ocultas. As chaves base e os sais são sobrescritos quando substituídos, removidos ou fechados. Os key schedules do AES e as mensagens de chave guardadas em caches de tracks de chaves e em buffers do transporte são liberados, não sobrescritos, e o Go não garante que nenhuma cópia fique na memória.

O que o pacote não oferece:

  • Uma lista de membros. A aplicação entrega ao SetMembers os participantes que autoriza.
  • Uma assinatura por remetente. Todo membro tem a chave de cada remetente, então um membro que controla o relay, ou que se alia ao operador dele, pode criar objetos que parecem vir de outro membro. Por um relay honesto com RoomPolicy, e em uma sessão direta, um membro não consegue.
  • Sigilo futuro dentro de uma geração de chave, nem recuperação depois de um comprometimento. Quem tem a chave de um remetente lê os objetos desse remetente.
  • AES-GCM em tempo constante em toda CPU. O AES-GCM do Go é de tempo constante só no seu assembly para CPUs amd64 e arm64 com instruções AES, ppc64x e s390x. Em 386, arm, riscv64, loong64, mips, wasm, e em CPUs amd64 ou arm64 sem instruções AES, ele é código genérico que não é de tempo constante.

A kolo-media usa o secobj nos broadcasts protegidos e traz um programa completo.

Limites

Um campo em zero assume o padrão, e um valor fora da faixa devolve ErrInvalidConfig. As tabelas completas estão em Limites.

  • SetupTimeout e RequestTimeout, 10 s cada um, de 1 s a 10 min.
  • MaxRequests e MaxSubscriptions, 1000 cada um. Os que passam desse número são recusados com EXCESSIVE_LOAD.
  • MaxObjectSize, 16 MiB, de 1 KiB a 1 GiB, para um payload recebido do peer. OriginConfig.MaxObjectSize é o mesmo limite para um payload escrito no origin.
  • MaxBufferedGroups, 64, e MaxBufferedBytes, 32 MiB ou MaxObjectSize se for maior, por assinatura nos dois lados.
  • MaxFetchBytes, igual a MaxBufferedBytes: os objetos em cache retidos ao mesmo tempo para os FETCH e os preenchimentos do peer.
  • TrackOptions.CacheGroups, 16, e CacheBytes, 32 MiB, por track. RelayConfig tem os mesmos dois para cada track repassado.
  • RelayConfig.MaxTracks, 1000, MaxSessionTracks, um décimo disso, e MaxSessionFetches, 16.
  • RelayConfig.Resume, desligado por padrão, de 1 s a 1 h. RelayConfig.MaxResumeHeld, 10000, de 1 a 1000000: anúncios retidos ao mesmo tempo para sessões encerradas. RelayConfig.MaxPeerResumeHeld, o MaxRequests da sessão (1000) ou MaxResumeHeld se for menor: anúncios retidos para uma chave de peer.
  • Um track avisa em TrackWriter.NewGroupRequests no máximo uma vez a cada NewGroupRequestInterval (1 s), seja qual for o número de assinaturas.
  • Cada objeto conta o payload, 48 bytes por propriedade e 64 bytes para o MaxBufferedBytes e o cache, então objetos vazios não saem de graça. Um payload de mais de 64 KiB é lido conforme chega, então um peer que anuncia um objeto grande e não envia nada não reserva memória.
  • secobj: KeyringConfig.Retain, 450 ms, e RetainMax, Retain mais 400 ms; MaxSenders, 64; MaxKeyRate, 64 mensagens de chave por segundo e namespace; ReplayGroups, 64, e ReplayObjects, 8192, por Opener; e SenderConfig.MaxTracks, 1024. Uma chave de track sela no máximo 2^24 unidades de 16 KiB de texto claro, e depois o Sender faz a rotação. As faixas estão em Limites.

Segurança

  • Uma frase de motivo de um peer é guardada em Reason, com no máximo 1024 bytes e escapada, e nunca vai em Error(). PeerImplementation é cortada em 1024 bytes e escapada.
  • Todo decodificador tem um fuzz target. Mensagens de controle de mais de 65535 bytes são recusadas, não cortadas.
  • Um stream que não avança por RequestTimeout é reiniciado, então um peer que para de ler não atrasa os outros. Um relay lê de uma vez um FETCH repassado para um buffer limitado e o reinicia quando o assinante fica muito para trás.
  • As revisões de segurança e de Go encontraram problemas que estão corrigidos com testes.

Padrões

A kolo-moq implementa o draft-ietf-moq-transport-22 só sobre streams, porque as conexões Kolo são QUIC com ALPN kolo/0 e não têm datagramas. Cada stream de controle começa com o preâmbulo moqt-22. Um peer cujo stream de controle começa de outra forma é fechado com PROTOCOL_VIOLATION, e a sessão devolve ErrVersion.

  • Implementado: SETUP, GOAWAY, SUBSCRIBE, REQUEST_UPDATE, FETCH, TRACK_STATUS, PUBLISH_DONE, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE, prioridades do assinante e do publicador, ordem dos grupos, timeouts de entrega e as regras da seção 12.1 que um cache de relay consegue conferir.
  • Respondido com NOT_SUPPORTED: PUBLISH, SUBSCRIBE_TRACKS e as atualizações de prefixo de namespace. Os filtros de intervalo recebem INVALID_FILTER.
  • Não feito: o relay assina um único publicador por track, não todos os que correspondem, como pede a seção 7.6, e o RENDEZVOUS_TIMEOUT não é respeitado. O NEW_GROUP_REQUEST é respeitado no REQUEST_UPDATE: Subscription.RequestNewGroup o envia e TrackWriter.NewGroupRequests avisa o publicador. Um assinante que não é um relay confere só as regras de track malformado que um único objeto mostra.
  • O draft 22 é um rascunho em movimento, então um draft posterior será uma mudança incompatível.

Estado

  • Feito: sessões, publicar, assinar, fetch, namespaces, relay, prioridades e timeouts de entrega, e interoperabilidade com uma segunda implementação do draft 22 nos dois sentidos.
  • Feito: o pacote secobj para objetos protegidos de ponta a ponta através de relays, os tracks de chaves, TrackOptions.Readers e RoomPolicy.
  • Testada no macOS (arm64): go test, go test -race e a suíte de interoperabilidade passam. No Linux e no Windows o go vet passa e os testes não foram executados.
  • Experimental. A API pode mudar antes da v1.0.0.

Erros

ErroMensagem
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

Teste os erros sentinela com errors.Is. *SessionError, *RequestError e *PublishDoneError trazem o código do draft (SessionCode, RequestCode, DoneCode), e errors.As os lê. Os erros dos pedidos, de Fetch.ReadObject, de Update e de GoAway começam com kolomoq: e embrulham a causa. Os erros do secobj começam com kolomoq: secobj:.

Referências