dispatch

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT Imports: 10 Imported by: 0 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 dispatch demultiplexes inbound binary↔relay frames by RoutingEnvelope.ConnID and routes each frame through a handler table. The package is carrier-agnostic: it takes a generic <-chan protocol.RoutingEnvelope as its input and exposes its outbound frames on a channel the caller forwards to the relay. Wiring lives in cmd/pyry; this package imports internal/protocol only.

The handler table is empty until downstream verb slices register routes. Frames whose Envelope.Type has no registered handler fall through to a protocol.unsupported error reply; encrypted or otherwise non-v1 frames are refused via the protocol.IsV1Compatible check and map to protocol.unsupported / protocol.unknown_type. Malformed inner frames map to protocol.malformed.

Concurrency model: Run is a single demux goroutine that fans frames out to one goroutine per active conn_id. Per-conn goroutines read their inputs serially (preserving arrival order within a conn) and publish replies on a shared outbound channel that the caller drains. Bounded backpressure: a slow outbound consumer pauses per-conn goroutines, which is the intended flow control.

Security / operational notes (per the spec's Security review, #307):

  • Inbound frame size cap is inherited from internal/transport's WS read path. The dispatcher does not re-enforce; verb slices likewise rely on the transport cap rather than per-handler limits.
  • Head-of-line blocking on the demux: with an empty handler table no handler runs, so a slow handler cannot stall the demux today. Once verb slices register a long-running handler (e.g. an LLM-touching route), revisit and consider per-conn goroutine offload.
  • Log policy: dispatcher diagnostics carry conn_id, envelope type, envelope id, and the decode-error class — never the raw frame payload. Verb slices crossing this code path (message bodies, push tokens) must keep the same posture.
  • Wire-side error envelopes carry only the Code* string plus a static descriptive Message. No decode-error text, stack info, or anything derived from untrusted input is echoed back.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Frames is the inbound RoutingEnvelope stream the dispatcher demuxes.
	// Required. The dispatcher exits when this channel closes.
	Frames <-chan protocol.RoutingEnvelope

	// OutboundBuffer is the buffer size for the dispatcher's outbound
	// channel. Defaults to 32 when zero. Bounded backpressure on a slow
	// consumer pauses per-conn goroutines, which is the desired flow
	// control.
	OutboundBuffer int

	// Logger is required. Used for WARN/DEBUG diagnostics; no info-level
	// lifecycle logging at this layer (the daemon-side wiring logs that).
	//
	// SECURITY: the dispatcher never logs RoutingEnvelope.Token at any
	// level; the gate closure passed via FirstFrame must honor the same
	// rule (the token is plaintext credential material).
	Logger *slog.Logger

	// FirstFrame, if non-nil, is invoked on the FIRST inbound frame for
	// every new conn_id, before normal handler-table dispatch. The
	// dispatcher uses the returned outcome to either (a) forward
	// Response and continue dispatching subsequent frames on this conn
	// normally, (b) forward Response with CloseCode set and stop the
	// per-conn goroutine, or (c) fall through to the malformed-frame
	// error path. Nil disables the gate (every frame goes straight to
	// the handler table — the pre-#308 behavior preserved for tests).
	//
	// CloseCode on inbound frames is ignored: it is a binary→relay-only
	// signal. The gate runs on the inner Frame regardless of any
	// CloseCode the relay-side attacker may have injected on the wire.
	FirstFrame FirstFrameGate
}

Config configures a Dispatcher.

type Conn

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

Conn is the per-conn_id state exposed to handlers. It owns the monotonic outbound id counter and the conn's outbound send seam.

func NewTestConn

func NewTestConn(id string, outbound chan<- protocol.RoutingEnvelope, auth *devices.Device) *Conn

NewTestConn constructs a *Conn for verb-handler test fixtures. Test fixtures only — do not call from production code. The dispatcher is the sole production Conn factory (see routeConn). The constructor exists so handler tests in sibling packages can drive a real Conn against a caller-supplied outbound channel and a synthesised auth snapshot, without depending on a full Dispatcher.

The returned Conn has nextID at zero, so the first NextID() call returns 1 (matching the gate-disabled production path). Tests that want to simulate the post-hello_ack state — where id=1 has been consumed by AuthenticateFirstFrame's reply and the next handler- originated reply lands at id=2 — should call c.NextID() once before invoking the handler.

func (*Conn) Auth

func (c *Conn) Auth() *devices.Device

Auth returns the authenticated device snapshot for this conn, or nil if the first-frame gate has not yet accepted on this conn (the gate-disabled test path, a pre-accept frame, or a reject/Err path where the slot was never populated). Verb handlers MUST nil-check the result before dereferencing.

func (*Conn) ConnID

func (c *Conn) ConnID() string

ConnID returns the relay-assigned conn_id this Conn dispatches for.

func (*Conn) NextID

func (c *Conn) NextID() uint64

NextID returns the next monotonic outbound envelope id for this conn. Starts at 1 on the first call. Concurrent-safe even though the per-conn goroutine is the only writer today — atomic is cheap insurance for future fan-out inside a handler.

func (*Conn) Reply

func (c *Conn) Reply(ctx context.Context, req protocol.Envelope, respType string, payload json.RawMessage) error

Reply builds a response envelope keyed by NextID with InReplyTo set to req.ID and TS set to time.Now().UTC(), then Send's it. This is the load-bearing helper for the per-conn "in_reply_to matches request id" invariant.

func (*Conn) Send

func (c *Conn) Send(ctx context.Context, env protocol.Envelope) error

Send wraps env in a RoutingEnvelope addressed to this conn and pushes it onto the dispatcher's outbound channel. Blocks on backpressure; returns ctx.Err if ctx is cancelled while blocked. Caller is responsible for env.ID and env.TS — use Reply for the request/response convenience path.

type Dispatcher

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

Dispatcher demultiplexes frames by conn_id and routes each through the handler table.

func New

func New(cfg Config) *Dispatcher

New constructs a Dispatcher. Panics if cfg.Frames or cfg.Logger is nil (programmer error; mirrors transport.New).

func (*Dispatcher) ActiveConns

func (d *Dispatcher) ActiveConns() []*Conn

ActiveConns returns a snapshot of currently-active conns eligible for server-initiated outbound (broadcast). The returned slice excludes:

  • conns marked closed (gate-reject path; routeConn drops further frames for them)
  • conns whose first-frame gate has not yet RETURNED on the accept-and-continue path — i.e. connState.gateCompleted == false. "Completed" means runGate's `_ = c.NextID()` advance has executed, so the per-conn id counter has moved past the hello_ack's literal id=1 and a broadcast call to c.NextID() will return id >= 2.

The gate-completed filter is load-bearing: relay.AuthenticateFirstFrame emits hello_ack with literal ID=1, not via c.NextID(); runGate publishes that response onto d.outbound and THEN calls `_ = c.NextID()` so the next binary-originated frame on this conn gets id=2. A broadcast that races the gate would call c.NextID() first, claim id=1 for its message envelope, and collide with hello_ack on the wire (two envelopes both stamped id=1). Filtering on gateCompleted — set ONLY after runGate has returned on the accept path — closes that race deterministically.

The slice is fresh; callers may retain it. The returned *Conn pointers remain safe to call Send on — a conn that closes between snapshot and Send is handled by the demux's existing closed-conn drop in routeConn.

Concurrency: holds d.mu briefly to copy the conns map under the same lock that guards both closed-flag and gateCompleted mutation; no new lock order.

func (*Dispatcher) Outbound

func (d *Dispatcher) Outbound() <-chan protocol.RoutingEnvelope

Outbound returns the channel of binary→relay frames produced by handlers (and dispatcher-synthesised error replies). Closes after Run returns; callers can range over it.

func (*Dispatcher) Register

func (d *Dispatcher) Register(envType string, h Handler)

Register installs a handler for envType. Must be called before Run; panics if Run has already started (the handlers map is otherwise lock-free in the read path, so late registration would be a data race). Also panics on duplicate registration (programmer error; downstream verb slices register one route apiece).

func (*Dispatcher) Run

func (d *Dispatcher) Run(ctx context.Context) error

Run blocks until cfg.Frames closes or ctx is done. Returns nil for Frames-close (normal lifecycle end) and ctx.Err() for cancellation. On return, every per-conn goroutine has exited and Outbound is closed.

Run flips started before reading from Frames, locking the handlers map against further Register calls.

type FirstFrameGate

type FirstFrameGate func(ctx context.Context, env protocol.RoutingEnvelope) FirstFrameOutcome

FirstFrameGate is the per-conn first-frame interceptor. Called exactly once per conn_id, on the per-conn goroutine, with the inbound envelope. Returns the response envelope the dispatcher should forward plus a close-or-keep decision.

SECURITY: implementations MUST NOT log env.Token at any level. The token is plaintext credential material; only AuthenticateFirstFrame is allowed to consume it.

type FirstFrameOutcome

type FirstFrameOutcome struct {
	// Response is the routing envelope to forward to the relay. The
	// dispatcher publishes Response verbatim (its ConnID is expected
	// to match the incoming env.ConnID; the gate owns ID/InReplyTo/TS
	// construction). Required when Err is nil.
	Response protocol.RoutingEnvelope

	// CloseConn, when true, causes the dispatcher to set
	// Response.CloseCode = Code before publishing, and to stop the
	// per-conn goroutine after Response is sent.
	CloseConn bool

	// Code is the WS close code (4401 for auth.invalid_token).
	// Required when CloseConn is true; ignored otherwise.
	Code uint16

	// Err signals a gate-level failure (e.g. the inbound frame was
	// malformed JSON). The dispatcher falls through to its existing
	// protocol.malformed refusal path (no in_reply_to) and does NOT
	// publish Response. The first-frame status is still consumed so a
	// buggy phone cannot retry into the gate forever; subsequent frames
	// flow through the regular handler table.
	Err error

	// Device is the matched device snapshot from the gate. Populated iff
	// Err == nil && !CloseConn (the accept-and-continue branch). The
	// dispatcher MUST NOT propagate Device on the Err or CloseConn
	// branches; even a misbehaving gate that supplies it there leaves
	// Conn.Auth() nil.
	Device *devices.Device
}

FirstFrameOutcome carries the gate's verdict back to the dispatcher.

type Handler

type Handler func(ctx context.Context, c *Conn, env protocol.Envelope) error

Handler processes a single inbound envelope on a phone conn. Returning a non-nil error is logged at WARN and otherwise ignored in v1 (no close-conn semantics yet — the auth-gate slice (#308) introduces that surface). Handlers reply by calling Conn.Reply or Conn.Send; the dispatcher does not synthesize a response from a handler return value.

Jump to

Keyboard shortcuts

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