socket

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 16 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 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

This section is empty.

Variables

This section is empty.

Functions

func Arm added in v0.3.0

func Arm(gate chan struct{})

Arm puts the token in gate unless it is already there. The Poller uses it to re-arm the gates it reports.

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.

func NewPairEngine

func NewPairEngine() Engine

NewPairEngine returns a new PAIR socket engine.

func NewPubEngine

func NewPubEngine() Engine

NewPubEngine returns a new PUB socket engine.

func NewPullEngine

func NewPullEngine() Engine

NewPullEngine returns a new PULL socket engine.

func NewPushEngine

func NewPushEngine() Engine

NewPushEngine returns a new PUSH socket engine.

func NewRepEngine

func NewRepEngine() Engine

NewRepEngine returns a new REP socket engine.

func NewReqEngine

func NewReqEngine() Engine

NewReqEngine returns a new REQ socket engine.

func NewRouterEngine

func NewRouterEngine(mandatory bool) Engine

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 NewXPubEngine added in v0.3.0

func NewXPubEngine(verbose bool) Engine

NewXPubEngine 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

func (fq *FairQueue) Attach(p *pipe.End) error

Attach registers p. Idempotent. Returns zmqerr.ErrSocketClosed (wrapped) after Close.

func (*FairQueue) CanRecv

func (fq *FairQueue) CanRecv() bool

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

func (fq *FairQueue) Close() error

Close releases the FairQueue and unblocks pending Recv with zmqerr.ErrSocketClosed. The pipes are left open (their owners close them). Idempotent.

func (*FairQueue) Detach

func (fq *FairQueue) Detach(p *pipe.End) error

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

func (fq *FairQueue) Pending() bool

Pending reports, without locking, whether a message may be queued. A false answer is exact until the next message arrives.

func (*FairQueue) QueueDepth

func (fq *FairQueue) QueueDepth() uint64

QueueDepth reports the number of messages queued in the attached pipes.

func (*FairQueue) Recv

func (fq *FairQueue) Recv(ctx context.Context) (*msg.Msg, error)

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

func (fq *FairQueue) RecvWithSource(ctx context.Context) (*msg.Msg, *pipe.End, error)

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

func (fq *FairQueue) Recvd() uint64

Recvd reports the number of messages handed to receivers.

func (*FairQueue) TryRecvWithSource

func (fq *FairQueue) TryRecvWithSource() (m *msg.Msg, p *pipe.End, ok bool)

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

func (lb *LoadBalancer) Send(ctx context.Context, m *msg.Msg) error

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

type Metrics struct {
	Sent       uint64
	Recv       uint64
	Dropped    uint64
	QueueDepth uint64
}

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 NewXSubEngine) overrides Send to treat the message as a subscription command from the application.

*SubEngine implements Engine; the public gozmq package type-asserts it back to reach Subscribe and Unsubscribe, which stay out of the Engine interface.

func NewSubEngine

func NewSubEngine() *SubEngine

NewSubEngine returns a new SUB socket engine and a handle for driving subscriptions.

func NewXSubEngine

func NewXSubEngine() *SubEngine

NewXSubEngine returns a new XSUB socket engine: SUB whose subscription list is driven by the application sending the synthetic single-frame subscribe/unsubscribe messages (leading byte 0x01 / 0x00 + prefix) through Send, as in libzmq; any other shape is zmqerr.ErrFSMViolation. Subscribe/Unsubscribe work too (WithSubscribe uses them).

func (*SubEngine) AttachPipe

func (e *SubEngine) AttachPipe(p *pipe.End) error

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

func (e *SubEngine) CanRecvNow() bool

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

func (e *SubEngine) CanSendNow() bool

CanSendNow reports whether XSUB can take a subscription command; SUB never can.

func (*SubEngine) Close

func (e *SubEngine) Close() error

func (*SubEngine) DetachPipe

func (e *SubEngine) DetachPipe(p *pipe.End) error

func (SubEngine) Gates

func (g SubEngine) Gates() (in, out chan struct{})

Gates implements Engine.

func (*SubEngine) Metrics

func (e *SubEngine) Metrics() 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

func (e *SubEngine) Recv(ctx context.Context) (*msg.Msg, error)

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

func (e *SubEngine) Send(ctx context.Context, m *msg.Msg) error

Send on a SUB socket is an FSM violation. XSUB overrides this to treat the message as a subscription command.

func (*SubEngine) SetSubscription added in v0.4.0

func (e *SubEngine) SetSubscription(prefix []byte, on bool) error

SetSubscription is Subscribe (on) or Unsubscribe (!on) in one call.

func (*SubEngine) Subscribe

func (e *SubEngine) Subscribe(prefix []byte) error

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

func (e *SubEngine) Unsubscribe(prefix []byte) error

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 trie: PUB/XPUB keep one per peer with the peer's subscriptions, SUB/XSUB keep one with the local filter. It follows libzmq's semantics: Add and Remove are reference counted (two Add("foo") need two Remove("foo") before the prefix is gone), and Match reports whether any stored prefix is a prefix of the topic, the empty prefix matching every topic.

A PUB matches every peer's tree on every Send, so Match is the path that matters. The common case, a subscription to everything, is answered from an atomic flag without taking the lock; a selective tree is walked under the read lock. Writers hold the write lock and update in place, so a subscription change costs only the nodes it adds. Memory stays proportional to the stored prefixes: a node holds only the next-byte transitions that exist.

func NewSubTree

func NewSubTree() *SubTree

NewSubTree returns an empty SubTree.

func (*SubTree) Add

func (t *SubTree) Add(prefix []byte) (first bool)

Add inserts prefix with refcount +1 and reports whether it is new to the tree (the first Add for it since it was last removed).

func (*SubTree) Match

func (t *SubTree) Match(topic []byte) bool

Match reports whether any stored prefix is a prefix of topic.

func (*SubTree) Remove

func (t *SubTree) Remove(prefix []byte) (held, gone bool)

Remove decrements prefix's refcount. held reports whether the prefix was present (so a decrement happened), gone whether that dropped it from the tree. Removing an absent prefix is a no-op.

func (*SubTree) Walk added in v0.3.0

func (t *SubTree) Walk(fn func(prefix []byte, refs int))

Walk calls fn for every stored prefix with its refcount, in no particular order, under the read lock: fn must not call Add or Remove and must copy any prefix it keeps, since the slice is reused.

Jump to

Keyboard shortcuts

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