protocol

package
v0.9.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package protocol is the wire of go-fabric-server: the envelope of every frame, the error codes, the schema numbers, the JSON codec and the per-connection send path with its backpressure model. It knows no Matter: the controller half (controllerapi) and the bridge half (bridgeapi, S2) fill the envelope.

The envelope is matterjs-server's (the python-matter-server contract, read map §1.1-1.6 at matterjs-server 0bd06f22): a request is {message_id, command, args}, a success {message_id, result}, a failure {message_id, error_code, details, status?, cluster_status?, reason?}, an event {event, data}. The server_info frame a connection receives first is the bare object, without an envelope.

Numbers: Go encodes uint64 as plain decimal digits, so 64-bit ids need no special serializer (matterjs-server's toBigIntAwareJson, packages/ws-client/src/json-utils.ts:21-52, does the same by hand); the decoder keeps every number as a json.Number and Uint64 parses an id from its literal, so an id above 2^53 never passes through a float.

Index

Constants

View Source
const (
	DefaultHighWater        = 1 << 20
	DefaultHighWaterCeiling = 50 << 20
	DefaultCapBase          = 1000
	DefaultCapPerNode       = 20
	DefaultWatchdog         = 5 * time.Minute
	DefaultKeepalive        = 30 * time.Second
	// MaxUnansweredPings is the number of keepalive pings in a row a peer
	// may leave without a pong or a message before it is terminated.
	MaxUnansweredPings = 3
)

Backpressure and keepalive defaults — matterjs-server's WebSocketConnection (packages/ws-controller/src/server/WebSocketConnection.ts:64-71 at 0bd06f22): DEFAULT_HIGH_WATER 1 MiB, DEFAULT_HIGH_WATER_CEILING 50 MiB, DEFAULT_CAP_BASE 1000, DEFAULT_CAP_PER_NODE 20, DEFAULT_WATCHDOG 5 min, DEFAULT_KEEPALIVE 30 s, MAX_UNANSWERED_PINGS 3.

View Source
const (
	// MetricConnections is the gauge of open connections.
	MetricConnections = "ws.connections"
	// MetricQueuedBytes is the gauge of bytes handed to the sockets and not
	// yet written, over every connection.
	MetricQueuedBytes = "ws.queued_bytes"
	// MetricDropped counts frames dropped under backpressure.
	MetricDropped = "ws.dropped"
	// MetricClosedOverflow counts connections closed by the send path: more
	// undroppable frames waiting than the cap, a stalled send, or
	// MaxUnansweredPings keepalive pings without a pong or a message.
	MetricClosedOverflow = "ws.closed_overflow"
)

The metric names of the send path.

View Source
const (
	SchemaVersion             = 14
	MinSupportedSchemaVersion = 11
)

Schema numbers of the controller half (/ws): the matterjs-server contract, packages/ws-controller/src/server/WebSocketControllerHandler.ts:114 (SCHEMA_VERSION = 14) and :119 (MIN_SUPPORTED_SCHEMA_VERSION = 11).

View Source
const (
	ReasonNotDiscovered       = "not-discovered"
	ReasonPasscodeMismatch    = "passcode-mismatch" //nolint:gosec // a reason name, not a credential
	ReasonInvalidPayload      = "invalid-payload"
	ReasonAttestationRejected = "attestation-rejected"
	ReasonTimeout             = "timeout"
	ReasonOther               = "other"
)

Commissioning failure reasons — the reason field of a NodeCommissionFailed error (docs/websockets_api.md:82-90 of matterjs-server; CommissionFailureReason, ws-client model.ts:1757).

Variables

This section is empty.

Functions

func CheckListen

func CheckListen(l Listen, token string) error

CheckListen enforces the authentication rule of the server: a TCP listener that is not loopback needs a token. It returns the error the daemon refuses to start with.

func DecodeRequest

func DecodeRequest(frame []byte) (Request, *Error)

DecodeRequest is the one request decoder. A frame that is not a JSON object, or whose message_id or command has the wrong type, fails with InvalidArguments; an absent or null args becomes {}, and an args that is not an object fails with InvalidArguments naming the command (docs/websockets_api.md:50-54). The failure carries the message id when the frame stated one.

func Encode

func Encode(v any) ([]byte, error)

Encode is the one encoder of the server: encoding/json without HTML escaping (JSON.stringify escapes nothing either), no trailing newline. uint64 values come out as plain decimal digits at full width, the form matterjs-server's toBigIntAwareJson writes (packages/ws-client/src/json-utils.ts:21-52).

func MustEncode

func MustEncode(v any) []byte

MustEncode is Encode for values that always encode (the server's own types); it panics otherwise.

func ParseUint64

func ParseUint64(b []byte) (uint64, error)

ParseUint64 parses a JSON integer literal as an unsigned 64-bit number.

func RequireToken

func RequireToken(token string, h http.Handler) http.Handler

RequireToken wraps h: with a token, a request must carry it as "Authorization: Bearer <token>" or as the query parameter token, else it is answered 401. An empty token lets every request through (a loopback or Unix-socket listener).

Types

type Conn

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

Conn is the per-connection send path — matterjs-server's WebSocketConnection (WebSocketConnection.ts:88-349) translated. In direct mode a frame goes to the socket at once, in emit order. When the bytes in flight (handed to the socket, not yet written: the Go form of ws.bufferedAmount) pass the high-water mark, the connection queues: ordered and coalescable frames wait in an outbox that drains while the bytes in flight stay below the mark, so a window of frames is in flight, not one; coalescable frames collapse latest-wins per key, keeping the first position, and are built only when sent; past the cap the oldest droppable frames are dropped, and more pinned (undroppable) frames than the cap close the connection, as does an in-flight write without progress for the watchdog interval. Reliable frames (responses, server_info, server_shutdown) always go to the socket at once. When the outbox and the socket drain, the connection returns to direct mode. A periodic ping keeps idle connections open through proxies and terminates a peer that stopped answering (#onKeepalive).

func NewConn

func NewConn(sock Socket, opts ConnOptions) *Conn

NewConn starts the send path over sock. Close (or a fatal condition) ends it; Conn.Done is closed then.

func (*Conn) Close

func (c *Conn) Close()

Close ends the send path; frames not yet written are discarded.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done is closed once the send path ended.

func (*Conn) Flush

func (c *Conn) Flush(ctx context.Context) error

Flush waits until every frame sent so far is written, or ctx ends.

func (*Conn) OutboxLen

func (c *Conn) OutboxLen() int

OutboxLen is the number of frames waiting in the outbox.

func (*Conn) Queued

func (c *Conn) Queued() bool

Queued reports whether the connection is in backpressure mode.

func (*Conn) Received added in v0.4.7

func (c *Conn) Received()

Received marks the peer alive: the reader calls it for every message, as a pong does (WebSocketConnection.ts:134-136, ws.on("message")).

func (*Conn) SendCoalescable

func (c *Conn) SendCoalescable(key string, build func() []byte)

SendCoalescable sends the frame build returns; under backpressure repeated sends with the same key collapse to the latest, at the first one's position, and build runs once, when the frame is sent. build may return nil to send nothing. It runs with the connection's lock held: it must not call back into the connection.

func (*Conn) SendOrdered

func (c *Conn) SendOrdered(frame []byte, isDroppable bool)

SendOrdered sends an event frame in order. Under backpressure a droppable frame (node_event, subscription_report) may be dropped oldest-first; an undroppable one (node_added, node_removed, endpoint_added, endpoint_removed, subscription_ended) never is.

func (*Conn) SendReliable

func (c *Conn) SendReliable(frame []byte)

SendReliable sends a frame that is never queued or dropped: a response, server_info, server_shutdown. Clients match responses by message id, so jumping the outbox is harmless (WebSocketConnection.ts sendReliable).

type ConnOptions

type ConnOptions struct {
	// ID tags the connection's log lines.
	ID string
	// HighWater is the in-flight byte count above which the connection
	// queues; it ratchets up to twice the largest frame sent, at most
	// HighWaterCeiling.
	HighWater, HighWaterCeiling int
	// CapBase and CapPerNode bound the outbox: max(CapBase, nodes ×
	// CapPerNode) entries.
	CapBase, CapPerNode int
	// Nodes returns the current node count for the cap.
	Nodes func() int
	// Watchdog closes the connection when an in-flight write makes no
	// progress for this long.
	Watchdog time.Duration
	// Keepalive is the interval between pings. Proxies on the path (a
	// remote access relay, an ingress) close connections that carry no
	// traffic, and browsers never ping on their own. A peer that leaves
	// MaxUnansweredPings pings in a row without a pong or a message
	// ([Conn.Received]) is terminated; a ping sent in queued mode resets the
	// count, because pongs wait behind the backlog
	// (WebSocketConnection.ts:44-50).
	Keepalive time.Duration
	// Meter receives the gauges and counters.
	Meter *Meter
	// Logger receives the mode changes; nil discards.
	Logger *slog.Logger
}

ConnOptions configures a Conn; zero values are the defaults.

type Error

type Error struct {
	MessageID     string    `json:"message_id"`
	ErrorCode     ErrorCode `json:"error_code"`
	Details       string    `json:"details"`
	Status        *int      `json:"status,omitempty"`
	ClusterStatus *int      `json:"cluster_status,omitempty"`
	Reason        *string   `json:"reason,omitempty"`
}

Error is a failure response; it is also the error a handler returns. Status and ClusterStatus carry a Matter status the device answered with, Reason why commissioning failed (docs/websockets_api.md:73-90).

func DecodeArgs

func DecodeArgs(command string, args json.RawMessage, dst any) *Error

DecodeArgs decodes a request's args into dst with numbers kept exact (json.Number for an interface field). Unknown keys are ignored, as python-matter-server ignores them (parse_arguments with strict=False, docs/websockets_api.md:2491-2497). A failure is InvalidArguments naming the command.

func Errorf

func Errorf(code ErrorCode, format string, args ...any) *Error

Errorf returns an *Error of code with a formatted Details.

func (*Error) Error

func (e *Error) Error() string

func (*Error) WithReason

func (e *Error) WithReason(reason string) *Error

WithReason returns e with Reason set.

func (*Error) WithStatus

func (e *Error) WithStatus(status int, cluster *int) *Error

WithStatus returns e with the Matter status (and the cluster status, when not nil) set.

type ErrorCode

type ErrorCode int

ErrorCode is the error_code of a failure — matterjs-server's ServerErrorCode (packages/ws-controller/src/types/WebSocketMessageTypes.ts:73-110), which keeps python-matter-server's numbers 0-11 and adds its own from 100.

const (
	UnknownError             ErrorCode = 0
	NodeCommissionFailed     ErrorCode = 1
	NodeInterviewFailed      ErrorCode = 2
	NodeNotReady             ErrorCode = 3
	NodeNotResolving         ErrorCode = 4
	NodeNotExists            ErrorCode = 5
	VersionMismatch          ErrorCode = 6
	SDKStackError            ErrorCode = 7
	InvalidArguments         ErrorCode = 8
	InvalidCommand           ErrorCode = 9
	UpdateCheckError         ErrorCode = 10
	UpdateError              ErrorCode = 11
	IcdMultiAdmin            ErrorCode = 100
	OtaUploadError           ErrorCode = 101
	CameraStreamIncompatible ErrorCode = 102
	CameraResourceExhausted  ErrorCode = 103
	CameraStreamInUse        ErrorCode = 104
	CameraNotSupported       ErrorCode = 105
	CameraPrivacyMode        ErrorCode = 106
)

The error codes, with matterjs-server's names.

const (
	// BridgeClientConnected refuses a second bridge client: the daemon's
	// node has one author.
	BridgeClientConnected ErrorCode = 200
)

The codes of the bridge half (/bridge) beyond matterjs-server's: our own protocol, numbered from 200 so they never meet a controller-half code.

type Event

type Event struct {
	Event string `json:"event"`
	Data  any    `json:"data"`
}

Event is a server push: {event, data} (docs/websockets_api.md:2002-2012).

type Listen

type Listen struct {
	// Network is "tcp" or "unix".
	Network string
	// Address is the TCP address or the socket path.
	Address string
}

Listen is a parsed --listen value.

func DefaultListen

func DefaultListen() Listen

DefaultListen is the listener when --listen is not given: the Unix socket fabric-server.sock in $XDG_RUNTIME_DIR, else in the temporary directory.

func ParseListen

func ParseListen(s string) (Listen, error)

ParseListen parses "unix:/path" or a TCP address ("127.0.0.1:5580", ":5580", "[::1]:5580"); empty is DefaultListen.

func (Listen) Loopback

func (l Listen) Loopback() bool

Loopback reports whether the listener is reachable from this host only: a Unix socket, or a TCP address on a loopback IP or "localhost".

func (Listen) Open

func (l Listen) Open(ctx context.Context) (net.Listener, error)

Open opens the listener; a stale Unix socket file is removed first.

func (Listen) String

func (l Listen) String() string

type Meter

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

Meter aggregates the gauges of every Conn of a server; nil Metrics discards.

func NewMeter

func NewMeter(m Metrics) *Meter

NewMeter returns a meter reporting to m (nil discards).

type Metrics

type Metrics interface {
	Counter(name string, delta int64)
	Gauge(name string, value int64)
}

Metrics is the counter/gauge sink of the send path; go-fabric's contract.Metrics satisfies it. The names are the Metric* constants.

type Request

type Request struct {
	MessageID string          `json:"message_id"`
	Command   string          `json:"command"`
	Args      json.RawMessage `json:"args,omitempty"`
}

Request is a client's command. Args is never nil after DecodeRequest: an absent or null args is the empty object (docs/websockets_api.md:50-54).

type Result

type Result struct {
	MessageID string `json:"message_id"`
	Result    any    `json:"result"`
}

Result is a success response. A nil Result encodes as "result": null, the answer of a command without a result (interview_node, remove_node).

type Socket

type Socket interface {
	Write(ctx context.Context, frame []byte) error
	Ping(ctx context.Context) error
	Abort(reason string)
}

Socket is the outgoing half of one WebSocket. Write blocks until the frame is written or ctx ends; Ping sends a ping and blocks until the pong arrived or ctx ends; Abort tears the connection down without a closing handshake (a half-open peer may never complete one).

func WebSocket

func WebSocket(c *websocket.Conn) Socket

WebSocket adapts a coder/websocket connection to the send path's Socket: text frames, Abort closes without a handshake.

type Uint64

type Uint64 uint64

Uint64 is an unsigned 64-bit id argument (node_id, fabric ids): a JSON integer literal of up to 20 digits, parsed from its text so it never passes through a float. A negative, fractional or exponent form, a string and an out-of-range number are refused — matterjs-server refuses a large node_id in exponent form for the same reason (docs/websockets_api.md:1833-1867, "Send a large node_id as an integer literal").

func (*Uint64) UnmarshalJSON

func (u *Uint64) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

Directories

Path Synopsis
Package schema is the data model of the protocol, generated from go-fabric's snapshot of the matter.js model (parity/schema.json, read through go-fabric's parity package): every cluster with its attributes, commands, events and datatypes, every device type, by id and by name.
Package schema is the data model of the protocol, generated from go-fabric's snapshot of the matter.js model (parity/schema.json, read through go-fabric's parity package): every cluster with its attributes, commands, events and datatypes, every device type, by id and by name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL