Documentation
¶
Overview ¶
Package socket holds the per-pattern Engine implementations that back the public gozmq Socket types. Each ZMTP 3.1 socket pattern — PAIR, PUSH, PULL, PUB, SUB, XPUB, XSUB, REQ, REP, DEALER, ROUTER, STREAM — is realised by its own engine in this package.
Engine contract ¶
The per-pattern engines implement Engine. That interface binds a narrow lifecycle (AttachPipe, DetachPipe, Close) to a two-method dispatch surface (Send, Recv). Pipes are handed to the engine by the session layer post-handshake; the engine owns all routing, subscription, and FSM state associated with those pipes. Close unblocks any pending Send/Recv with zmqerr.ErrSocketClosed and detaches every pipe.
Error sentinels are stable: engines surface zmqerr.ErrSocketClosed after Close, zmqerr.ErrFSMViolation for patterns that disallow a direction (e.g. PUSH.Recv, SUB.Send) or a mis-ordered FSM step (REQ/REP), and zmqerr.ErrRouteUnknown on ROUTER with the mandatory option set.
Reusable primitives ¶
Two primitives (in sibling files loadbalancer.go and fairqueue.go) are shared across engines so each pattern can stay focused on its policy:
- LoadBalancer — round-robin outbound dispatcher over the attached pipe set, rotating past peers at HWM and blocking only when every peer is full. Used by PUSH and DEALER. (REQ does its own round-robin with sticky-peer semantics via the shared pipeRing helper, not LoadBalancer.)
- FairQueue — fair-queued inbound multiplexer that receivers read round-robin across the attached pipes, with no goroutines. Used by PULL, DEALER, REP, ROUTER, STREAM, SUB, and XSUB.
Both depend only on *pipe.End so engine-specific logic (identity prefixing, subscription filtering, FSM state, sticky peer selection) stays in the per-engine files rather than leaking into the primitive.
A third shared primitive, SubTree, is a refcounted byte-prefix trie used by PUB/XPUB (one per peer) and SUB/XSUB (one per socket) for subscription matching.
Thread-safety model ¶
Engines must be fully goroutine-safe: there is no external serialization. The public Socket invokes Send/Recv/AttachPipe/ DetachPipe/Close without holding any lock, application goroutines may call Send and Recv concurrently, and the session layer drives AttachPipe/DetachPipe from its own goroutines. Every engine therefore guards its own state — with its mutex, atomics, or by delegating to the goroutine-safe primitives. Engines spawn no goroutines of their own.
LoadBalancer, FairQueue, and SubTree are themselves goroutine-safe so tests and future patterns can use them directly.
Message references ¶
Every *msg.Msg queued on a pipe carries one reference (a no-op for plain memory; see msg's "Lent frames"), owned by whoever holds the message. Send takes over m's reference when it returns nil — handing m to one pipe, or releasing it once a derived message, a fan-out copy or a drop has replaced it — and leaves it with the caller on error. Recv hands the caller one reference. An engine that rewrites an envelope derives the new message from the old one (msg.Msg.Derive) and releases the old one; it never modifies a message it was given. Messages an engine discards (filter misses, stale replies, drops) are released.
Ownership model ¶
Each engine owns the per-peer bookkeeping for every pipe it has been handed: subscription trees, routing identity tables, sticky peer state, FSM bits, reply envelopes. It does not own the pipes themselves — the session layer creates and closes those, and calls AttachPipe/DetachPipe to let the engine react. The Socket owns the engine and is responsible for calling Close exactly once.
Index ¶
- Constants
- func NewSubEngine() (Engine, *SubEngine)
- func NewXSubEngine() (Engine, *SubEngine)
- type Engine
- func NewDealerEngine() Engine
- func NewPairEngine() Engine
- func NewPubEngine() Engine
- func NewPullEngine() Engine
- func NewPushEngine() Engine
- func NewRepEngine() Engine
- func NewReqEngine() Engine
- func NewRouterEngine(mandatory bool) Engine
- func NewStreamEngine() Engine
- func NewXPubEngineV(verbose bool) Engine
- type FairQueue
- func (fq *FairQueue) Attach(p *pipe.End) error
- func (fq *FairQueue) CanRecv() bool
- func (fq *FairQueue) Close() error
- func (fq *FairQueue) Detach(p *pipe.End) error
- func (fq *FairQueue) Pending() bool
- func (fq *FairQueue) QueueDepth() uint64
- func (fq *FairQueue) Recv(ctx context.Context) (*msg.Msg, error)
- func (fq *FairQueue) RecvWithSource(ctx context.Context) (*msg.Msg, *pipe.End, error)
- func (fq *FairQueue) Recvd() uint64
- func (fq *FairQueue) TryRecvWithSource() (m *msg.Msg, p *pipe.End, ok bool)
- type LoadBalancer
- type Metrics
- type SubEngine
- func (e *SubEngine) AttachPipe(p *pipe.End) error
- func (e *SubEngine) CanRecvNow() bool
- func (e *SubEngine) CanSendNow() bool
- func (e *SubEngine) Close() error
- func (e *SubEngine) DetachPipe(p *pipe.End) error
- func (g SubEngine) Gates() (in, out chan struct{})
- func (e *SubEngine) Metrics() Metrics
- func (e *SubEngine) Recv(ctx context.Context) (*msg.Msg, error)
- func (e *SubEngine) Send(ctx context.Context, m *msg.Msg) error
- func (e *SubEngine) Subscribe(prefix []byte) error
- func (e *SubEngine) Unsubscribe(prefix []byte) error
- type SubTree
Constants ¶
const ( SubscribeByte byte = 0x01 UnsubscribeByte byte = 0x00 )
Synthetic subscription message format: a single-frame message whose first byte is SubscribeByte (0x01) or UnsubscribeByte (0x00), followed by the subscription prefix bytes. This is the same on-wire shape libzmq XPUB surfaces to its application and the same shape XSUB accepts from its application; we reuse it internally to carry subscription commands between the session reader and the PUB/XPUB engine without extending *pipe.End.
See internal/session/reader.go (handleCommand) for how incoming ZMTP SUBSCRIBE/CANCEL commands are converted to synthetic messages on the inbound pipe.
Variables ¶
This section is empty.
Functions ¶
func NewSubEngine ¶
NewSubEngine returns a new SUB socket engine and a handle for driving subscriptions.
func NewXSubEngine ¶
NewXSubEngine returns a new XSUB socket engine.
XSUB behaves like SUB on the inbound path (fair-queue across all attached peers + local subscription filter), but the subscription list is driven by the application sending synthetic single-frame subscribe/unsubscribe messages through Send rather than via explicit Subscribe/Unsubscribe API calls — matching libzmq's XSUB contract. The expected outbound wire shape is one frame whose first byte is 0x01 (SUBSCRIBE) or 0x00 (CANCEL) followed by the prefix bytes; any other message shape yields zmqerr.ErrFSMViolation. Inbound SUBSCRIBE/CANCEL commands from peers are dropped by the session (only PUB/XPUB consume them), as in libzmq; data frames reach Recv unchanged.
Implementation: the same *SubEngine as NewSubEngine, with the surfacing flag set; Send is re-targeted to interpret the outbound message as a subscription command. Subscribe/Unsubscribe remain callable on the returned *SubEngine for tests that want to drive the filter via the API path rather than through synthetic wire messages.
Types ¶
type Engine ¶
type Engine interface {
// AttachPipe registers a new peer pipe (post-handshake). Engines with
// subscription state (SUB, XPUB) may push pending SUBSCRIBE commands
// into the pipe at attach time.
AttachPipe(p *pipe.End) error
// DetachPipe is called by the socket layer when a peer disconnects.
// Engines must stop dispatching to p; any in-flight state (e.g. a
// ROUTER's outstanding reply envelope) is resolved per pattern policy.
DetachPipe(p *pipe.End) error
// Send is the engine-level SendMsg entry. Pattern-specific:
// PUSH: load-balance
// PUB: fanout filtered by subscription
// ROUTER: route by leading identity frame
// REQ: fail with ErrFSMViolation unless Recv was the last call
Send(ctx context.Context, m *msg.Msg) error
// Recv is the engine-level RecvMsg entry. Pattern-specific:
// PULL: fair-queue across pipes
// SUB: fair-queue with subscription filter
// ROUTER: prepend peer identity frame
// REP: fail with ErrFSMViolation unless Send was the last call
Recv(ctx context.Context) (*msg.Msg, error)
// Close releases engine state, unblocks pending Send/Recv with
// ErrSocketClosed, and detaches all pipes.
Close() error
// Metrics returns a point-in-time snapshot of the engine's counters
// and the current inbound queue-depth gauge. Safe to call from any
// goroutine, including concurrently with Send/Recv.
Metrics() Metrics
// Gates returns the engine's two readiness gates (see gates), stable
// for its lifetime: in is armed when a Recv may have stopped blocking,
// out when a Send may have. The Poller parks on them and re-checks
// with CanRecvNow/CanSendNow, which answer false for a direction the
// engine lacks.
Gates() (in, out chan struct{})
// CanRecvNow is a non-consuming level check: true iff a Recv would
// not block on inbound queue emptiness right now. A false answer also
// registers a wake-up: the pipes it found empty are marked idle, so
// the next message arms the in-gate. Always false for send-only
// engines.
CanRecvNow() bool
// CanSendNow is a non-consuming level check: true iff a Send would
// not block on peer-set emptiness right now. HWM blocking is not
// surfaced, as in libzmq where POLLOUT means "a peer exists", not
// "the next message is guaranteed to land instantly". Always false
// for recv-only engines.
CanSendNow() bool
}
Engine encapsulates the per-type policy (REQ lock-step, PUB fanout, DEALER round-robin, etc.) on top of a set of pipes. One engine per Socket; the public gozmq.Socket is a thin front for an Engine.
func NewDealerEngine ¶
func NewDealerEngine() Engine
NewDealerEngine returns a new DEALER socket engine.
DEALER is an asynchronous request/reply peer — the symmetric counterpart to ROUTER, but without identity bookkeeping. It composes the two shared primitives:
- Send load-balances outbound messages round-robin across attached peer pipes (reusing LoadBalancer; an HWM-full peer is rotated past, blocking only when every peer is full).
- Recv fair-queues inbound messages across attached peer pipes (reusing FairQueue).
DEALER does not mangle identity envelopes or enforce a lock-step FSM: Send and Recv may interleave freely from multiple goroutines. Any REQ-style empty-delimiter framing required by a downstream ROUTER/REP peer is the application's responsibility.
Thread-safe: Send, Recv, AttachPipe, DetachPipe, and Close are goroutine-safe via the underlying primitives.
func NewPullEngine ¶
func NewPullEngine() Engine
NewPullEngine returns a new PULL socket engine.
PULL is recv-only. Inbound messages are fair-queued across the attached peer pipes by a FairQueue, which Recv reads round-robin. Recv blocks until some peer has a message, ctx cancels, or the engine closes. Send always returns zmqerr.ErrFSMViolation (wrapped); PULL has no outbound path.
func NewPushEngine ¶
func NewPushEngine() Engine
NewPushEngine returns a new PUSH socket engine.
PUSH is send-only. Outbound messages are dispatched round-robin across the attached peer pipes using a shared LoadBalancer; a peer at HWM is rotated past (libzmq lb_t parity), and Send blocks only when EVERY attached peer is full — until one drains, ctx cancels, or the engine closes. Recv always returns zmqerr.ErrFSMViolation (wrapped); PUSH has no inbound path.
func NewRouterEngine ¶
NewRouterEngine returns a new ROUTER socket engine. If mandatory is true, Send returns zmqerr.ErrRouteUnknown when the leading identity frame does not match an attached peer; otherwise such sends are silently dropped.
func NewStreamEngine ¶
func NewStreamEngine() Engine
NewStreamEngine returns a new STREAM socket engine.
Pipe boundary contract:
- Each inbound pipe Msg carries one body frame: the raw chunk read from the wire.
- Each outbound pipe Msg carries one body frame: the bytes to write verbatim. An empty body means "close the conn" (STREAM half-close).
- The pipe's PeerIdentity may be empty; the engine synthesizes one.
func NewXPubEngineV ¶
NewXPubEngineV returns a new XPUB socket engine. When verbose is true every SUBSCRIBE/CANCEL command observed on any attached peer is forwarded to the application via Recv. When verbose is false the engine applies libzmq-style deduplication: only the first SUBSCRIBE and the last CANCEL for each distinct prefix, across the set of attached peers, surfaces to the application. Duplicate SUBSCRIBEs from the same peer, and SUBSCRIBEs for a prefix already tracked by another peer, are applied to the routing tables silently.
libzmq default is verbose=false (dedup enabled); callers that want to observe every subscriber churn event must opt in with verbose=true. Mirrors the semantics of ZMQ_XPUB_VERBOSE on a classic libzmq XPUB.
type FairQueue ¶
type FairQueue struct {
// contains filtered or unexported fields
}
FairQueue is a fair-queued inbound multiplexer over a dynamic set of *pipe.End values, after libzmq's fq_t. It runs no goroutines: receivers read the pipes themselves.
The attached pipes live in entries, whose first nActive elements are the active ones, which may hold a message. A receiver walks them round-robin from cur under mu. It deactivates a pipe it finds empty, after marking the pipe idle (pipe.End.RecvOrIdle), so the next message sent to that pipe runs the pipe's notification, which reactivates it and arms gate. That keeps the invariant a parked receiver relies on: every attached pipe is active, or idle, or has a notification in flight that will reactivate it.
While exactly one pipe is attached, single publishes it and Recv blocks in that pipe directly without taking mu, which is what a single-peer socket costs anyway. Every change of single wakes gen, whose generation single was published with: that aborts receivers blocked in the old pipe and wakes receivers parked on gate, and both re-evaluate.
func NewFairQueue ¶
func NewFairQueue(gate chan struct{}) *FairQueue
NewFairQueue returns an empty FairQueue that arms gate, a cap-1 channel, whenever a message may have become receivable.
func (*FairQueue) Attach ¶
Attach registers p. Idempotent. Returns zmqerr.ErrSocketClosed (wrapped) after Close.
func (*FairQueue) CanRecv ¶
CanRecv reports whether a Recv would find a message right now. A false answer leaves every pipe idle, so the next message arms the gate: a Poller may park on it after this.
func (*FairQueue) Close ¶
Close releases the FairQueue and unblocks pending Recv with zmqerr.ErrSocketClosed. The pipes are left open (their owners close them). Idempotent.
func (*FairQueue) Detach ¶
Detach removes p. A pipe that has already closed with messages queued stays until a receiver drains it to EOF: the peer delivered them before leaving, and libzmq keeps them receivable.
func (*FairQueue) Pending ¶
Pending reports, without locking, whether a message may be queued. A false answer is exact until the next message arrives.
func (*FairQueue) QueueDepth ¶
QueueDepth reports the number of messages queued in the attached pipes.
func (*FairQueue) Recv ¶
Recv blocks until a message arrives from any attached pipe, ctx cancels, or Close is called. Returns zmqerr.ErrSocketClosed (wrapped) on close.
func (*FairQueue) RecvWithSource ¶
RecvWithSource blocks like Recv and additionally reports the pipe from which the message was received. ROUTER uses this to stamp the leading peer-identity frame onto each inbound message; REP uses it to capture the delimiter envelope for the next Send.
func (*FairQueue) TryRecvWithSource ¶
TryRecvWithSource is RecvWithSource without blocking: ok is false when no message is queued (the pipes are then idle, so the next one sets Pending and arms the gate) or the queue is closed.
type LoadBalancer ¶
type LoadBalancer struct {
// contains filtered or unexported fields
}
LoadBalancer is a round-robin outbound dispatcher across a dynamic set of *pipe.End values. It is goroutine-safe: Attach, Detach, Send, and Close may be called concurrently from any goroutine.
Send tries the peer at the round-robin cursor first and advances the cursor on success. A peer whose pipe is at HWM is skipped: Send rotates through the remaining peers and only blocks when EVERY attached peer is full (until one drains, the peer set changes, ctx cancels, or the LoadBalancer closes). This matches libzmq's lb_t semantics, where a full pipe is deactivated and the sender moves on, backpressuring only when no active pipe remains.
If a peer disappears mid-send (its pipe closed), the cursor advances past it and Send retries with the next peer. This keeps load-balancing liveness in the presence of churn.
func NewLoadBalancer ¶
func NewLoadBalancer(gate chan struct{}) *LoadBalancer
NewLoadBalancer returns an empty LoadBalancer that arms gate, a cap-1 channel, whenever a peer attaches.
func (*LoadBalancer) Attach ¶
func (lb *LoadBalancer) Attach(p *pipe.End) error
Attach registers p with the dispatcher. Idempotent: re-attaching an already-tracked pipe is a no-op. Returns zmqerr.ErrSocketClosed (wrapped) after Close.
func (*LoadBalancer) Close ¶
func (lb *LoadBalancer) Close() error
Close releases the LoadBalancer. Subsequent Attach returns zmqerr.ErrSocketClosed; pending Send unblocks with the same. Idempotent.
func (*LoadBalancer) Detach ¶
func (lb *LoadBalancer) Detach(p *pipe.End) error
Detach removes p from the dispatcher. No-op if p was never attached. Adjusts the cursor so round-robin continues sensibly.
func (*LoadBalancer) HasPeers ¶
func (lb *LoadBalancer) HasPeers() bool
HasPeers reports whether at least one peer is attached. Used by the Poller for the immediate non-blocking PollOut check.
func (*LoadBalancer) Send ¶
Send dispatches m to the first peer with room, starting at the round-robin cursor, and advances the cursor past the winner. When every attached peer is at HWM, Send blocks on the cursor peer until it drains, the peer set changes, ctx cancels, or Close is called.
Returns zmqerr.ErrSocketClosed (wrapped) after Close, ctx.Err() on cancellation, or the underlying Pipe.Send error.
func (*LoadBalancer) Sent ¶
func (lb *LoadBalancer) Sent() uint64
Sent reports the number of messages this LoadBalancer has successfully dispatched. Safe to call concurrently with Send.
type Metrics ¶
Metrics is a point-in-time snapshot of per-engine counters and gauges; the root package copies it into the public SocketMetrics. Counters (Sent, Recv, Dropped) are monotonically increasing; QueueDepth is the number of messages queued in the engine's inbound pipes when sampled (zero for send-only patterns).
Dropped covers messages the engine refuses to deliver after the caller's Send returned successfully (PUB fanout at HWM, a ROUTER route miss); send-side errors returned to the caller are not counted.
type SubEngine ¶
type SubEngine struct {
// contains filtered or unexported fields
}
SubEngine implements Engine for the SUB socket type and also exposes subscription control to the public gozmq layer.
SUB fair-queues inbound messages across all attached peer pipes using a shared FairQueue and applies the local subscription filter after Recv: a message whose topic frame (first frame) does not match any subscription is discarded and the engine loops for the next one.
The local subscription list is refcounted: duplicate Subscribe calls require a matching number of Unsubscribe calls before the prefix is actually removed from the filter. Every net change (first Subscribe for a prefix, final Unsubscribe) is forwarded as a ZMTP SUBSCRIBE or CANCEL command to every attached peer via a synthetic single-frame message on the pipe's outbound side (leading byte 0x01 / 0x00 + prefix). Forwarding is best-effort — a brief per-peer deadline avoids blocking the subscriber against a congested PUB. New peers attached after Subscribe replay the current subscription list.
Send on a plain SUB returns zmqerr.ErrFSMViolation (wrapped); XSUB (see xsub.go) overrides Send to treat the message as a subscription command from the application.
NewSubEngine returns both the opaque Engine (plumbed into the Socket layer) and a *SubEngine handle the public gozmq package uses to implement WithSubscribe and dynamic Subscribe/Unsubscribe calls. Internally the two returned values point to the same object — the split keeps subscription controls out of the Engine interface.
func (*SubEngine) AttachPipe ¶
AttachPipe registers p. Every current subscription is replayed to the new peer as a synthetic SUBSCRIBE message so the peer's PUB engine (or XPUB) sees the same filter state an existing peer does.
func (*SubEngine) CanRecvNow ¶
CanRecvNow reports the FairQueue's level. A queued message the filter then drops is at worst a spurious wake (PUB peers filter upstream, so it is rare).
func (*SubEngine) CanSendNow ¶
CanSendNow reports whether XSUB can take a subscription command; SUB never can.
func (SubEngine) Gates ¶
func (g SubEngine) Gates() (in, out chan struct{})
Gates implements Engine.
func (*SubEngine) Metrics ¶
Metrics reports the SUB/XSUB engine's counters. recv counts user- visible Recv returns (filter-matched messages). QueueDepth samples the FairQueue.
func (*SubEngine) Recv ¶
Recv fair-queues across attached pipes and applies the local subscription filter. Messages whose topic frame (first frame) is not matched by any local subscription are discarded and Recv loops. The payload is never sniffed: data beginning with 0x00/0x01 is ordinary data (the session drops upstream SUBSCRIBE/CANCEL commands for SUB/XSUB, as libzmq does).
func (*SubEngine) Send ¶
Send on a SUB socket is an FSM violation. XSUB overrides this to treat the message as a subscription command.
func (*SubEngine) Subscribe ¶
Subscribe adds prefix to the local filter and forwards a SUBSCRIBE to every attached peer. Duplicate Subscribe calls are refcounted: an equal number of Unsubscribe calls removes the filter.
func (*SubEngine) Unsubscribe ¶
Unsubscribe decrements prefix's refcount and, on the final decrement, forwards a CANCEL to every attached peer.
type SubTree ¶
type SubTree struct {
// contains filtered or unexported fields
}
SubTree is a reference-counted byte-prefix radix tree used by PUB/XPUB to track subscriptions for a single peer, and by SUB/XSUB to match incoming messages against the local subscription list.
Operations:
- Add(prefix) — insert prefix, incrementing its refcount.
- Remove(prefix) — decrement the refcount; drop the prefix when it hits zero; return whether the prefix was fully removed.
- Match(topic) — report whether any stored prefix is a prefix of topic.
libzmq semantics:
- Add and Remove are reference counted: two Add("foo") calls require two Remove("foo") calls before the prefix disappears from the tree.
- Match returns true if ANY prefix in the tree is a prefix of the candidate topic. The empty prefix ([]byte{}) matches every topic.
- Add/Remove/Match are all goroutine-safe.
Implementation: a node-per-byte trie with per-node child maps so memory stays proportional to stored subscriptions (subscription trees are usually sparse away from the root). Match runs in O(L) in the topic length with no allocation.
func (*SubTree) Add ¶
Add inserts prefix into the tree with refcount +1. A duplicate Add bumps the refcount at the terminal node.
func (*SubTree) Match ¶
Match reports whether any subscription prefix in the tree is a prefix of topic. The empty prefix ([]byte{}) is considered a prefix of every topic, so a tree containing only "" matches everything.
The Size accessor (number of distinct prefixes) is test-only and lives in subtree_test.go; production code never reads the size field.