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
- func CheckListen(l Listen, token string) error
- func DecodeRequest(frame []byte) (Request, *Error)
- func Encode(v any) ([]byte, error)
- func MustEncode(v any) []byte
- func ParseUint64(b []byte) (uint64, error)
- func RequireToken(token string, h http.Handler) http.Handler
- type Conn
- func (c *Conn) Close()
- func (c *Conn) Done() <-chan struct{}
- func (c *Conn) Flush(ctx context.Context) error
- func (c *Conn) OutboxLen() int
- func (c *Conn) Queued() bool
- func (c *Conn) Received()
- func (c *Conn) SendCoalescable(key string, build func() []byte)
- func (c *Conn) SendOrdered(frame []byte, isDroppable bool)
- func (c *Conn) SendReliable(frame []byte)
- type ConnOptions
- type Error
- type ErrorCode
- type Event
- type Listen
- type Meter
- type Metrics
- type Request
- type Result
- type Socket
- type Uint64
Constants ¶
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.
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.
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).
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 ¶
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 ¶
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 ¶
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 ¶
MustEncode is Encode for values that always encode (the server's own types); it panics otherwise.
func ParseUint64 ¶
ParseUint64 parses a JSON integer literal as an unsigned 64-bit number.
func RequireToken ¶
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) 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 ¶
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 ¶
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 ¶
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 (*Error) WithReason ¶
WithReason returns e with Reason 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 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 ¶
ParseListen parses "unix:/path" or a TCP address ("127.0.0.1:5580", ":5580", "[::1]:5580"); empty is DefaultListen.
func (Listen) Loopback ¶
Loopback reports whether the listener is reachable from this host only: a Unix socket, or a TCP address on a loopback IP or "localhost".
type Meter ¶
type Meter struct {
// contains filtered or unexported fields
}
Meter aggregates the gauges of every Conn of a server; nil Metrics discards.
type Metrics ¶
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 ¶
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).
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 ¶
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. |