Documentation
¶
Overview ¶
Package session implements the ZMTP per-peer state machine. Each Session wraps a single transport.Conn with two goroutines: the reader drives the greeting and security handshake, then moves wire frames to the pipe; the writer puts the handshake frames, then the pipe's messages, on the wire. The optional heartbeat is a self-rearming timer, not a goroutine. Raw mode (Config.Raw, for STREAM) keeps the two goroutines but skips ZMTP.
The session consumes its collaborators through their contracts (zmtp.FrameCodec, security.Mech, transport.Conn), so it can be tested with fakes for each.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SocketTypesCompatible ¶
SocketTypesCompatible reports whether two ZMTP Socket-Type values form a valid pairing per ZMTP 3.1. Inproc wiring, which has no handshake, uses it directly.
Types ¶
type Config ¶
type Config struct {
Conn transport.Conn
Mech security.Mech
Codec zmtp.FrameCodec
HeartbeatInterval time.Duration
HeartbeatTimeout time.Duration
HandshakeTimeout time.Duration
SendHWM int
RecvHWM int
// MaxMessageSize caps the total decoded payload, in bytes, of one
// logical inbound message — the sum of all frame lengths accumulated
// while FlagMore is set. The frame codec enforces only a per-frame
// cap, so without this a peer could stream an endless MORE chain and
// OOM the receiver. When the cap is exceeded the session tears down
// with an error wrapping zmqerr.ErrMalformedFrame. 0 means unlimited.
// The root socket layer wires its option through this field.
MaxMessageSize int64
// RecvBufferPool reads inbound frames larger than the reader's scratch
// into pooled buffers and delivers them as lent messages that return
// the buffers on their final Release (gozmq.WithRecvBufferPool). It
// applies only to identity-framed mechanisms (NULL, PLAIN), whose
// decoded frame is the buffer itself.
RecvBufferPool bool
// SubscriptionCommands turns inbound ZMTP SUBSCRIBE/CANCEL commands
// into 0x01/0x00-prefixed messages on the pipe. Set it only for
// PUB/XPUB; every other socket type drops the commands.
SubscriptionCommands bool
// Raw carries bytes with no ZMTP at all (STREAM): no greeting,
// handshake or heartbeat, each conn.Read is one single-frame inbound
// message, and each outbound message is one body frame written
// verbatim, an empty one closing the conn. Mech, Codec and the
// ZMTP-only fields are ignored. The mode is fixed at New, so the ZMTP
// loops carry no per-message branch for it.
Raw bool
// OnReady runs on the reader goroutine once the handshake succeeds,
// with the engine-facing pipe end, before any inbound frame is read.
// An error (the engine refused the pipe) tears the session down
// unattached. nil accepts every pipe.
OnReady func(*pipe.End) error
// OnClosed runs exactly once, on the last session goroutine to exit,
// after the conn is closed and before Done closes. err is the
// handshake failure, nil once the handshake succeeded; attached
// reports whether OnReady accepted the pipe.
//
// Callbacks must never call Stop: it waits for the goroutine running
// them.
OnClosed func(err error, attached bool)
// Logger is the destination for non-fatal diagnostics (heartbeat
// timeout reasons, malformed-frame events). When nil, slog.Default()
// is used.
Logger *slog.Logger
// Now returns a monotonic nanosecond timestamp used to stamp inbound
// frames and measure heartbeat idle time. When nil it defaults to the
// package monoNow (runtime monotonic clock). Tests inject a fake clock
// here to drive heartbeat-timeout behavior deterministically without
// real elapsed time.
Now func() int64
}
Config bundles the inputs to New. Conn is required, and Mech and Codec unless Raw is set. New applies no defaults to the timeout and heartbeat values; the socket layer supplies production ones. Zero HandshakeTimeout means no handshake deadline, zero HeartbeatInterval no heartbeats, zero MaxMessageSize no inbound size cap; a zero HeartbeatTimeout does not disable the liveness check, it means three times the interval.
type ReconnectConfig ¶
type ReconnectConfig struct {
// Dial opens a new Conn to the remote endpoint. Respects ctx
// cancellation. Called once per reconnect attempt.
Dial func(ctx context.Context) (transport.Conn, error)
// Start runs a connection over conn, taking ownership of it (closing
// it on error). An error is treated like a dial failure: the loop
// backs off and retries.
Start func(conn transport.Conn) (Runner, error)
// InitialBackoff is the base delay between reconnect attempts. Also
// the value the schedule resets to after a successful attach.
InitialBackoff time.Duration
// MaxBackoff caps the exponential schedule. Zero means no cap —
// doubling continues unbounded (subject to the context's lifetime).
MaxBackoff time.Duration
// JitterFraction is the symmetric randomness applied to each delay,
// e.g. 0.2 → ±20%. Zero disables jitter.
JitterFraction float64
// OnRetry fires once per backoff cycle, immediately before the
// loop sleeps. attempt counts 1-based consecutive failures since
// the last successful attach; it resets to 1 after success.
// backoff is the sleep duration about to be applied (pre-jitter).
OnRetry func(attempt int, backoff time.Duration)
// Logger sinks diagnostic events. nil defaults to slog.Default().
Logger *slog.Logger
}
ReconnectConfig bundles the inputs to StartReconnector. Dial and Start are required; zero durations are interpreted as documented.
type Reconnector ¶
type Reconnector struct {
// contains filtered or unexported fields
}
Reconnector runs the dial loop in a dedicated goroutine. Create one with StartReconnector; tear it down with Stop.
func StartReconnector ¶
func StartReconnector(parent context.Context, cfg ReconnectConfig) *Reconnector
StartReconnector launches the dial loop in a new goroutine. The loop runs until parent is cancelled or Stop is called.
func (*Reconnector) Quiesce ¶
func (r *Reconnector) Quiesce()
Quiesce flips a flag so that when the current connection ends, loop() does not dial a new one. The current connection keeps running. Idempotent.
func (*Reconnector) Stop ¶
func (r *Reconnector) Stop() error
Stop cancels the loop, which stops any live Runner, and blocks until the loop has exited. It returns the live Runner's Stop error, if any. Safe to call more than once.
type Runner ¶
type Runner interface {
// Done closes when the connection has fully ended.
Done() <-chan struct{}
// Stop tears the connection down and waits for Done.
Stop() error
// Attached reports whether the connection reached the engine, which
// resets the backoff schedule.
Attached() bool
}
Runner is the Reconnector's view of a started connection; *Session implements it.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session owns the ZMTP state machine for a single peer connection: it drives greeting, handshake, heartbeats, and the traffic phase. It sits between a transport.Conn (bytes) and a pipe (messages).
Exactly two goroutines run per session. The reader performs the handshake, calls OnReady, then moves wire frames to the pipe. The writer writes the handshake frames, then moves pipe messages to the wire. The last of the two to exit closes the conn, calls OnClosed and closes done.
func New ¶
New constructs a Session around cfg.Conn; Start runs it. New lets the caller register the session (for Close) before any callback can fire.
The Session owns cfg.Conn once started: it closes it on teardown. The caller retains ownership of cfg.Mech and cfg.Codec, which are assumed to be safe for the session's use until Done closes.
func (*Session) Done ¶
func (s *Session) Done() <-chan struct{}
Done returns a channel closed once both session goroutines have exited and OnClosed has returned.
func (*Session) Drain ¶
func (s *Session) Drain() <-chan struct{}
Drain makes the writer flush the messages still queued and exit without closing the conn, so in-flight writes complete; the returned channel closes once it has. Call engine.Close first so nothing new is queued, wait on the channel, then call Stop. Idempotent.