Documentation
¶
Overview ¶
Package relay drives the binary's outbound long-lived connection to the relay: opens the WSS via internal/transport and exposes inbound frames as protocol.RoutingEnvelope values via Frames(). The binary↔relay leg is content-blind — the relay registers the binary's server-id from the x-pyrycode-server request header and claims the slot on WS upgrade, so the conn is treated as established the moment the upgrade completes; there is no relay-originated hello/hello_ack handshake on this leg. It does NOT dispatch on envelope types, validate device tokens, or interpret application-level error payloads — those concerns layer above this package in a future ticket (supervisor wiring + per-message handlers).
The single source of truth for the headers and close codes is docs/protocol-mobile.md (§ Authentication, § Connection lifecycle, § Worked example). When that document changes, this package changes.
Index ¶
- Constants
- Variables
- type ActiveConn
- type AuthOutcome
- type Config
- type Connection
- type InnerFrameV2Decoded
- type Interrupter
- type ModalDismissal
- type ModalResolver
- type QueueRemover
- type ScreenSnapshotter
- type V2Session
- type V2SessionConfig
- type V2SessionManager
- func (m *V2SessionManager) ActiveConnIDs(ctx context.Context) []string
- func (m *V2SessionManager) ActiveConns(ctx context.Context) []ActiveConn
- func (m *V2SessionManager) ArmModalTimeout(ctx context.Context, modalID string)
- func (m *V2SessionManager) Push(ctx context.Context, connID string, env protocol.Envelope) error
- func (m *V2SessionManager) Rekey(ctx context.Context, connID string) error
- func (m *V2SessionManager) Run(ctx context.Context) error
- func (m *V2SessionManager) SetReplaySource(ring *eventring.Ring, currentConv func() string)
- type V2SessionState
Constants ¶
const ( // StatusProtocolMismatch is the WS close code the binary asks the // relay to apply when a phone sends an inner frame that violates the // v2 inner-frame shape, the state machine, or the discriminator // table. Wire spec: docs/protocol-mobile.md § Error codes, close-code // row 4421. StatusProtocolMismatch websocket.StatusCode = 4421 // StatusHandshakeFailure is the WS close code the binary asks the // relay to apply when the Noise_IK handshake fails before // CipherStates exist (e.g. MAC failure on IK message 1, wrong static // pubkey). No AEAD-sealed error envelope can be sent — the close // code is the only signal. Wire spec: docs/protocol-mobile.md // § Error codes, close-code row 4426. StatusHandshakeFailure websocket.StatusCode = 4426 )
Mobile Protocol v2 close codes (docs/protocol-mobile.md § Error codes). 4401 (StatusUnauthorized) lives in auth.go and is reused unchanged.
const MsgInvalidToken = "device token not recognised; re-pair via pyry pair on the binary"
MsgInvalidToken is the fixed user-facing message emitted in the auth.invalid_token error payload (docs/protocol-mobile.md § Error codes). Defined as an exported const so future integration tests can pin it without re-typing the spec sentence.
StatusUnauthorized is the WS close code the relay sends when the binary rejects a phone's device token (docs/protocol-mobile.md § Error codes, close-code row 4401). Typed locally so callers don't import the websocket package for the value; parallel to statusServerIDConflict in connection.go.
Variables ¶
var ( // ErrServerIDConflict is the terminal error returned by Wait when // the relay refused our claim with WS close 4409. Another binary is // currently holding the same server-id and the relay's 30-second // grace window has not elapsed. Operator escalation: another pyry is // already running for this server-id, or a stale connection on the // relay side has not yet been reaped. ErrServerIDConflict = errors.New("relay: server-id conflict (close 4409)") // ErrInvalidConfig is returned by Connect on missing required fields. ErrInvalidConfig = errors.New("relay: invalid config") )
Sentinel errors. Callers distinguish fatal vs. retryable via errors.Is.
var ErrConnNotFound = fmt.Errorf("relay: conn not found: %w", control.ErrConnNotFound)
ErrConnNotFound is returned by (*V2SessionManager).Rekey when connID is not currently registered in the manager's sessions map. Wraps control.ErrConnNotFound so the control dispatcher's errors.Is(err, control.ErrConnNotFound) check in handleRekey continues to map to ErrCodeConnNotFound on the wire without further plumbing.
var ErrMalformedHelloFrame = errors.New("relay: malformed hello frame")
ErrMalformedHelloFrame is returned by AuthenticateFirstFrame when the inner envelope inside env.Frame cannot be JSON-decoded. The relay-conn caller maps this to its existing protocol.malformed handling; this package does not synthesize an error envelope for it (the malformed- frame response shape is owned by a sibling ticket).
var ErrSessionNotOpen = errors.New("relay: session not open")
ErrSessionNotOpen is returned by (*V2SessionManager).Rekey when the named session exists but is not eligible for a manual rekey — either not in V2StateOpen (still handshaking, or already torn down), or already awaiting a rekey reply from a prior emit. The control dispatcher surfaces this verbatim through Response.Error with no ErrorCode (slice A defines no wire code for this state yet).
Functions ¶
This section is empty.
Types ¶
type ActiveConn ¶ added in v0.15.0
ActiveConn is one open v2 session in the capability-aware enumeration: its routing conn-id and the negotiated interactive-capability decision recorded at handshake. It holds only non-secret routing/decision data — never a *V2Session, CipherState, key, or plaintext — so the snapshot is safe to hand to a consumer goroutine. The downstream structured-stream fan-out selects interactive vs non-interactive conns on the Interactive flag.
type AuthOutcome ¶
type AuthOutcome struct {
Response protocol.RoutingEnvelope
CloseConn bool
// Device is the matched *devices.Device snapshot on the accept path.
// Nil on reject and on the ErrMalformedHelloFrame early return. The
// dispatcher carries this forward into the per-conn Auth slot so
// downstream verb handlers can read the authenticated device without
// re-validating the token (see #318 / docs/protocol-mobile.md §
// Authentication).
Device *devices.Device
}
AuthOutcome is the structured result of AuthenticateFirstFrame. The relay-conn caller forwards Response back through the binary→relay leg and, when CloseConn is true, asks the relay to close the phone WS with StatusUnauthorized after the Response has been written.
CloseConn carries the protocol-level intent (close-because-auth-failed) rather than the wire code itself; the close code is fixed at 4401 by spec and lives on the StatusUnauthorized constant.
func AuthenticateFirstFrame ¶
func AuthenticateFirstFrame( env protocol.RoutingEnvelope, token string, reg *devices.Registry, serverID string, logger *slog.Logger, ) (AuthOutcome, error)
AuthenticateFirstFrame is the per-connection token-validation predicate for the phone→relay→binary auth phase (docs/protocol-mobile.md § Authentication). It is invoked exactly once per phone conn — on the binary's receipt of the first frame for a given conn_id — and returns the routing envelope the binary should send back plus the close-or-keep signal the relay-conn layer will act on.
The function is carrier-agnostic with respect to how token reached the binary: it never parses WS headers, never reads env.Frame's payload for a token field, and never inspects a hello payload. The relay-conn ticket that wires this handler into phone traffic picks one of (a) extended routing envelope, (b) synthesized connection_opened control frame, or (c) amended hello payload, and forwards the extracted token here unchanged.
Two-state semantics: reg.Validate returns (Device, bool). A true result means the device row exists and was just bumped (the predicate already handled LastSeenAt under reg.mu — the handler does not call any further mutator). A false result means either never-paired or the row was removed via reg.Remove; both produce the same auth.invalid_token outcome per docs/protocol-mobile.md § Error codes line 535 ("Same UX as invalid_token"). The CodeAuthTokenRevoked constant is reserved for a future tombstone primitive and is NOT emitted by this handler.
SECURITY: token is never logged, never wrapped into any returned error, and never echoed to the phone. The matched device's name IS logged on accept but is NOT logged on reject (preventing name-enumeration probes from binary logs).
type Config ¶
type Config struct {
ServerID identity.ServerID
RelayURL string
BinaryVersion string
Logger *slog.Logger
// AllowInsecureScheme, when true, lets RelayURL use plain ws:// in
// addition to wss://. Test-only seam so e2e suites can point pyry at
// an httptest-hosted fakerelay over plaintext. Production callers
// leave this false; cmd/pyry flips it only when the operator sets
// PYRY_ALLOW_INSECURE_RELAY=1.
AllowInsecureScheme bool
}
Config carries the static configuration for a Connection. The caller resolves ServerID via internal/identity.LoadOrCreate before constructing Config — the relay package never touches the on-disk store, keeping the net package free of pairing / storage concerns.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection runs the binary↔relay leg of the wire protocol. Lifecycle is tied to the context passed to Connect; cancellation closes the WS cleanly. Wait blocks until the lifecycle terminates; the returned error is the terminal classification (ErrServerIDConflict for fatal 4409, ctx.Err for graceful shutdown, or a wrapped transport error for unexpected halts).
func Connect ¶
func Connect(ctx context.Context, cfg Config) (*Connection, error)
Connect builds the transport, starts the lifecycle goroutine, and returns immediately. The connection is not yet Ready — observe Frames to consume post-handshake inbound frames, or call Wait to block on terminal classification. The caller is responsible for invoking Close during shutdown to release resources; ctx cancellation also drains the lifecycle.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close requests a clean shutdown. Idempotent. After Close, Frames drains and closes; Wait returns.
func (*Connection) CloseConn ¶
func (c *Connection) CloseConn(connID string, code uint16) error
CloseConn asks the relay to close the named phone conn with the given WS close code. Builds a close-only routing envelope (no Frame) with CloseCode set and forwards via the transport. Returns transport.ErrNotConnected when the underlying WS is currently dropped or transport.ErrDisconnected if the live conn drops while Send is blocked (caller decides whether to retry; transport reconnect runs asynchronously). Wire mechanism: docs/protocol-mobile.md § Routing envelope (CloseCode).
CloseConn does NOT block on the relay's close-frame being delivered to the phone — the request is fire-and-forget at this layer. The per-conn close ack is implicit (no more inbound frames will arrive for connID).
The dispatcher's auth-reject path does NOT call CloseConn; instead it publishes one routing envelope carrying both Frame and CloseCode so the error envelope and the close are atomic on the wire. CloseConn is the explicit surface for callers that want close-without-payload (none today; reserved for the idle/inactivity sweep hinted at in #307).
func (*Connection) Frames ¶
func (c *Connection) Frames() <-chan protocol.RoutingEnvelope
Frames returns the channel of inbound frames. The channel closes when the lifecycle terminates. Frames are delivered in the order the underlying conn produces them; reconnects are transparent — frames resume on the new conn directly.
func (*Connection) Send ¶
func (c *Connection) Send(env protocol.RoutingEnvelope) error
Send marshals env to JSON and forwards it to the relay over the current transport conn. Returns transport.ErrDisconnected if the underlying conn is currently dropped (caller decides whether to retry or drop the frame); transport reconnect happens asynchronously, so a frame sent while disconnected is lost — that's consistent with the protocol's connection-lifecycle expectations (docs/protocol-mobile.md § Connection lifecycle).
func (*Connection) Wait ¶
func (c *Connection) Wait() error
Wait blocks until the lifecycle terminates and returns the terminal classification: ErrServerIDConflict (fatal), ctx.Err (graceful shutdown), or a wrapped transport error.
type InnerFrameV2Decoded ¶ added in v0.14.0
InnerFrameV2Decoded is the post-validation form of an InnerFrameV2: Type matches one of the discriminator constants and Data has been base64-decoded with the size cap enforced.
type Interrupter ¶ added in v0.15.0
type Interrupter interface{ SendEsc() error }
Interrupter delivers a single Esc to the supervised claude — the remote equivalent of a local Esc, claude's own interrupt. *supervisor.Supervisor satisfies it via SendEsc (#726), so the supervisor needs no new method. Declared here (consumer side), beside ScreenSnapshotter, so internal/relay imports neither internal/supervisor nor tui-driver. Named for its relay-domain role (matching ScreenSnapshotter.ScreenSnapshot / ModalResolver.Resolve*), even though the method keeps the sealed surface's name. SendEsc is safe to call from any goroutine — it is the same seam ResolveCancel / ResolveTimeout use.
type ModalDismissal ¶ added in v0.15.0
type ModalDismissal struct {
Outcome string // e.g. "cancelled" (cancel); #717 uses the answered option_id
Source string // closed set {remote, local, timeout}; cancel ⇒ "remote"
}
ModalDismissal is the wire outcome+source the manager broadcasts after a resolver consumes an outstanding modal. The manager already holds modal_id (from the inbound control payload), so it is not repeated here.
type ModalResolver ¶ added in v0.15.0
type ModalResolver interface {
// ResolveCancel consumes modalID (registry Resolve), routes a cancel/ESC
// keystroke, audits outcome=cancelled, and returns the dismissal to
// broadcast with ok=true. An unknown/already-resolved id ⇒ (zero, false):
// no keystroke, no audit, no dismissal.
ResolveCancel(modalID string, dev *devices.Device) (ModalDismissal, bool)
// ResolveAnswer resolves an inbound modal_answer. In this slice it is a
// deferred no-op — always (zero, false): no keystroke, no mutation, no
// audit. #717 fills the gated answer arm; the manager code is already
// general (broadcasts on ok=true) so #717 changes only the impl.
ResolveAnswer(modalID, optionID, answerToken string, dev *devices.Device) (ModalDismissal, bool)
// ResolveTimeout safe-denies an unanswered modal whose deny-on-timeout
// window elapsed (#725): it consumes modalID (registry Resolve), routes the
// fail-closed deny keystroke (ESC), audits outcome=denied_timeout /
// source=timeout with an empty device (a timeout has no answering device),
// and returns the dismissal to broadcast with ok=true. An unknown or
// already-resolved id (an answer/cancel won the race) ⇒ (zero, false): no
// keystroke, no audit, no broadcast — the AC-2 loser path. Takes no device
// (unlike ResolveCancel/ResolveAnswer): the safe-deny is unconditional, so
// there is nothing to gate.
ResolveTimeout(modalID string) (ModalDismissal, bool)
}
ModalResolver resolves an inbound modal control frame against the daemon's outstanding-modal state. Declared here (consumer side), beside ScreenSnapshotter, so internal/relay imports neither internal/supervisor nor cmd/pyry; the cmd/pyry resolver satisfies it. *devices.Device crosses the seam (the per-conn s.device); internal/relay already imports internal/devices, so no new import. Both methods run on the manager's single Run dispatch goroutine.
type QueueRemover ¶ added in v0.15.0
QueueRemover drops a not-yet-drained queued message from a conversation's inbound backlog by id (#723). *msgqueue.Queue satisfies it. Declared here, in the consumer, beside Interrupter / ModalResolver, so internal/relay imports neither internal/msgqueue nor cmd/pyry (CODING-STYLE: define interfaces where they are consumed). Returns true iff a message was removed; an unknown or foreign conversationID, an unknown or already-delivered id, or the in-flight (draining) head is a safe no-op (false). The conversationID arg IS the mutation scope: Remove(A,…) provably never touches conversation B's backlog.
type ScreenSnapshotter ¶ added in v0.15.0
ScreenSnapshotter renders the daemon's live claude screen to plain text: text is the rendered screen, live is false (and text "") when no claude child is attached. *supervisor.Supervisor satisfies it. Declared here, in the consumer, so internal/relay depends on neither internal/supervisor nor tui-driver (CODING-STYLE: define interfaces where they are consumed).
type V2Session ¶ added in v0.14.0
type V2Session struct {
// contains filtered or unexported fields
}
V2Session is the per-conn_id state held by V2SessionManager. Mutation is serialised by the manager's single dispatch goroutine (the loop is the lock); there is no mutex because flynn/noise's CipherStates are not safe for concurrent use and the manager guarantees a single writer per conn_id. The re-key responder (handleRekeyInit) atomically swaps s.send / s.recv in a single tuple assignment on this same goroutine; old *CipherState pointers are dropped from the struct and reclaimed by GC. No explicit Wipe() of the key bytes is exposed — the single-owner-goroutine invariant means no code path reads the old state after the swap, which is the practical zeroisation property.
func (*V2Session) State ¶ added in v0.14.0
func (s *V2Session) State() V2SessionState
State returns the externally-observable state. Called from the same goroutine that mutates today; a cross-goroutine reader (e.g. a broadcast layer added in a later slice) would need atomic.Int32 or a small mutex — tracked in spec § Open questions.
type V2SessionConfig ¶ added in v0.14.0
type V2SessionConfig struct {
// Frames is the inbound RoutingEnvelope stream from a relay.Connection
// (or an in-memory channel in tests). Run consumes until Frames
// closes or ctx is done.
Frames <-chan protocol.RoutingEnvelope
// Outbound forwards a single binary→relay RoutingEnvelope. Production
// wiring passes (*relay.Connection).Send. Non-nil errors are logged
// at debug and dropped — the relay leg's reconnect handles recovery
// (mirrors v1's cmd/pyry/relay.go forwarder posture).
Outbound func(protocol.RoutingEnvelope) error
// StaticPriv is the binary's 32-byte X25519 static private key.
StaticPriv []byte
// Devices is the token-validation predicate for hello.Token.
Devices *devices.Registry
// ServerID is surfaced into the hello_ack early-data payload.
ServerID string
// Logger receives lifecycle and reject events. Token, key bytes,
// payload bytes, AEAD ciphertext, and base64 forms thereof MUST NOT
// appear in any logged field.
Logger *slog.Logger
// Handlers is the application-layer envelope-type → handler table
// used for v2 open-state dispatch. Optional: nil or empty map means
// no app handlers are registered, and every open-state envelope falls
// through to a sealed protocol.unsupported reply via dispatch.Route.
// Mirror v1's internal/dispatch.Dispatcher.Register registration
// shape — production wires Handlers via the daemon, same handlers as
// v1.
//
// SECURITY: handlers run on the manager's single dispatch goroutine
// (same goroutine that mutates s.send / s.recv). Handlers MUST be
// synchronous and MUST NOT spawn long-lived background goroutines
// that retain a reference to the *dispatch.Conn passed in — the
// conn's outbound channel is per-frame and is drained before
// dispatchAppFrame returns; sends from a forked goroutine after that
// drain are silently lost (the channel is leaked but bounded by its
// capacity, and reclaimed by GC).
Handlers map[string]dispatch.Handler
// Snapshotter renders the live claude screen for an inbound
// request_snapshot (ADR 025 § Safe degradation). Optional: when nil,
// request_snapshot yields a server.binary_offline error reply — the
// snapshot feature is simply unavailable, not a crash.
Snapshotter ScreenSnapshotter
// KnownConversation reports whether conversationID names a conversation
// this daemon hosts. request_snapshot rejects an unknown/foreign id with
// conversation.not_found before any render (AC #4). Optional: when nil,
// every request_snapshot is rejected as not-found. Production wires it to
// a conversations.Registry membership check.
KnownConversation func(conversationID string) bool
// ModalResolver resolves inbound modal_answer / modal_cancel control
// frames. Optional: when nil, both are inert no-ops (the modal bridge is
// simply unwired — foreground, or pre-#708 before the producer is live).
// Production wires the cmd/pyry resolver.
ModalResolver ModalResolver
// Interrupter routes an inbound interactive `interrupt` control frame to
// the supervised claude as one Esc (#707). Optional: nil ⇒ interrupt is
// inert (no Esc) — the foreground / unwired case. Production wires
// *supervisor.Supervisor.
Interrupter Interrupter
// QueueRemover drops a queued message named by an inbound dequeue_message
// control frame (#723). Optional: nil ⇒ dequeue_message is inert (foreground
// / unwired). Production wires *msgqueue.Queue.
QueueRemover QueueRemover
}
V2SessionConfig parameterises V2SessionManager. The handshake/transport fields are required; NewV2SessionManager validates and panics or errors on missing required values per the documentation below. Handlers, Snapshotter, and KnownConversation are optional — their per-field docs describe the nil behaviour.
SECURITY: StaticPriv is the binary's 32-byte X25519 static private key. It MUST NOT be logged, wrapped into an error message, or emitted on any wire surface. internal/keys and internal/noise document the same contract for the same bytes; this struct extends the contract to the manager's holding site.
type V2SessionManager ¶ added in v0.14.0
type V2SessionManager struct {
// contains filtered or unexported fields
}
V2SessionManager owns the per-conn_id v2 state machine. Construct with NewV2SessionManager; drive with Run. The manager is single-shot — Run returns when Frames closes or ctx is done, and the manager must not be reused.
Concurrency: Run is the only goroutine the manager owns. sessions is mutated exclusively by Run; no lock. This is intentionally simpler than internal/dispatch.Dispatcher (which spins one goroutine per conn_id); v2 in this slice runs no application handlers, every frame processes synchronously (~100µs Noise call or sub-µs JSON decode), so single-goroutine fan-in is correct and obviously safe. The re-key responder's CipherState swap (s.send, s.recv = newSend, newRecv) inherits this property: a single tuple assignment on this goroutine cannot be observed half-applied by any other code path, so the spec's atomic-switchover requirement is structural.
func NewV2SessionManager ¶ added in v0.14.0
func NewV2SessionManager(cfg V2SessionConfig) (*V2SessionManager, error)
NewV2SessionManager validates cfg and returns a ready manager. Panics on missing Frames or Logger (matching internal/dispatch.New style for programmer errors). Returns an error on missing Outbound, missing Devices, missing ServerID, or wrong-length StaticPriv.
func (*V2SessionManager) ActiveConnIDs ¶ added in v0.14.0
func (m *V2SessionManager) ActiveConnIDs(ctx context.Context) []string
ActiveConnIDs returns a snapshot of the conn IDs of every session currently in V2StateOpen — the authenticated, token-validated sessions to which Push may deliver. It is a thin projection over ActiveConns (dropping the interactive flag) preserved for the capability-agnostic #589 fan-out consumer; its signature and observable contract (unordered set, nil on ctx cancellation, non-nil-empty on an empty manager) are unchanged.
Production wire-up of *V2SessionManager into the cmd/pyry daemon for server-initiated fan-out lands in a separate ticket (#572); until then this method is reachable only from internal/relay tests.
func (*V2SessionManager) ActiveConns ¶ added in v0.15.0
func (m *V2SessionManager) ActiveConns(ctx context.Context) []ActiveConn
ActiveConns returns a snapshot of every session currently in V2StateOpen — the authenticated, token-validated sessions to which Push may deliver — each paired with its negotiated interactive flag. The result is an unordered set (Go's randomized map-iteration order); a caller that needs a stable order must sort it.
Safe to call from any goroutine other than the dispatch goroutine: the request is funneled onto Run via m.snapshot so m.sessions is never read concurrently with an in-flight handshake transition, dispatchAppFrame reply, re-key swap, or closeWith teardown. It is the enumeration half of the server-initiated fan-out primitive — a consumer calls this, then Push on each conn-id, fanning interactive events only to conns with Interactive set. It is the capability-aware v2 analog of v1's dispatch.Dispatcher.ActiveConns().
Sessions still handshaking (V2StateAwaitingInit) or handshake-complete-but- token-unvalidated (V2StateHandshakeComplete) are excluded — the same V2StateOpen security gate forwardEnvelope enforces, so the negotiated flag of an un-authenticated peer is never observable. A torn-down session (deleted from the map by closeWith) cannot appear.
Returns nil on caller ctx cancellation, or when Run has already exited (Frames closed, no receiver on m.snapshot) and the caller's ctx then fires — both equivalent to "no open sessions" for the broadcast consumer, which fans out to nobody this round and re-enumerates on the next turn. nil and an empty non-nil slice are interchangeable (both len 0); a snapshot has no failure the caller can act on, so no error is returned.
func (*V2SessionManager) ArmModalTimeout ¶ added in v0.15.0
func (m *V2SessionManager) ArmModalTimeout(ctx context.Context, modalID string)
ArmModalTimeout arms the daemon-side deny-on-timeout for a surfaced modal (#725). The surfacer calls it (off the Run goroutine) immediately after reg.Record; the time.AfterFunc callback runs on a fresh runtime goroutine and funnels modalID onto m.modalTimeout so the Run goroutine fires the safe-deny under the single-owner invariant (mirrors armRekeyTimer's callback shape). ctx is the surfacer's ctx (the daemon ctx in production, since cmd/pyry runs the surfacer and Run under the same ctx); its Done arm releases a fired-but- undelivered callback on shutdown, so no goroutine outlives Run.
The *time.Timer is deliberately discarded — never stored, never Stopped. The registry's one-shot Resolve is the idempotency gate: a timer that fires after an answer/cancel already consumed the modal simply runs handleModalTimeout → ResolveTimeout → Resolve-miss → no-op. Tracking timers to Stop them on resolve would need a map[modalID]*time.Timer mutated by both the surfacer (arm) and Run (cancel) — new cross-goroutine state and a new lock — for zero correctness gain (see § Concurrency in the spec). An un-fired AfterFunc holds only a heap entry, not a parked goroutine, so leaving it un-Stopped leaks nothing.
func (*V2SessionManager) Push ¶ added in v0.14.0
Push enqueues env onto the addressed session's bounded push buffer and returns immediately — it NEVER blocks on the relay/send path. The Run goroutine drains the buffer on its own schedule (drainOnce), sealing each envelope under s.send in order; so a slow or stalled relay can never wedge the calling producer/dispatch goroutine (the ADR-025 open-risk guard, decisions/025 line 220). Safe to call from any goroutine: Push touches only m.queues (under pushMu) — never s.send, m.sessions, or Outbound.
connID names a specific connected phone. The caller owns env entirely (Type, ID, TS, Payload); Push performs no envelope validation — it is a transport primitive.
Under pressure (queue at capacity) the event-class-aware drop policy runs pre-seal (pushQueue.enqueue): an assistant_delta evicts the oldest queued delta (drop-oldest); a control event is admitted by evicting a droppable delta and is never itself dropped. A drop is not an error — Push returns nil and debug-logs the running count + the dropped class (env.Type only; never payload bytes).
Returns ErrConnNotFound (wraps control.ErrConnNotFound) when no queue exists for connID — i.e. the session never reached V2StateOpen, was never seen, or has been torn down (closeWith deletes the queue). This collapses the former "session not open" case into ErrConnNotFound: a not-open conn has no queue. The V2StateOpen security gate is preserved on the drain side — forwardEnvelope re-checks s.state before sealing, so a buffered push to a conn that closed or de-authed before drain is dropped there, never delivered to an un-authenticated peer. Returns ctx.Err() only when ctx is already cancelled at entry (preserves the emitter's ctx-teardown branch). Both production callers (#632 emitter, #589 coarse bridge) only debug-log the error, so the collapse is invisible to them.
func (*V2SessionManager) Rekey ¶ added in v0.14.0
func (m *V2SessionManager) Rekey(ctx context.Context, connID string) error
func (*V2SessionManager) Run ¶ added in v0.14.0
func (m *V2SessionManager) Run(ctx context.Context) error
Run drives the state machine until Frames closes or ctx is cancelled. Returns ctx.Err() on cancellation, nil on Frames close. Every per-conn session is released on return; no goroutines outlive Run.
runCtx is a derived-cancel context so per-session timer-callback goroutines (spawned by armRekeyTimer / armRekeyReplyTimer via time.AfterFunc) unblock cleanly when Run exits. The callbacks select on (m.wake, runCtx.Done) so a fired-but-undelivered wake completes via the ctx branch on shutdown and leaves no goroutine behind.
func (*V2SessionManager) SetReplaySource ¶ added in v0.15.0
func (m *V2SessionManager) SetReplaySource(ring *eventring.Ring, currentConv func() string)
SetReplaySource publishes the mid-turn-reconnect replay source to the manager (#647). It is called once during relay wiring, AFTER the interactive emitter (which owns the eventring) is constructed: the emitter and manager have a circular dependency (the emitter takes the manager as its broadcaster; the replay path needs the emitter-owned ring), so the ring does not exist when NewV2SessionManager runs — a construction-time V2SessionConfig field is not buildable without the constructor cascade #646 avoided. A late-bound setter is the seam that breaks the cycle. ring is the emitter's per-conversation event ring; currentConv resolves the conversation a reconnecting conn replays for (the supervisor's #312 cursor).
Stored under pushMu (the existing leaf lock, taken alone): this write happens off the Run goroutine during wiring, and replayMissed reads them on the Run goroutine at reconnect — much later, after a full network handshake. A nil ring or cursor leaves replay disabled. Idempotent by construction (the wiring calls it once).
type V2SessionState ¶ added in v0.14.0
type V2SessionState int
V2SessionState is the externally-observable lifecycle state of a per-conn V2Session. The handshakeComplete substate is distinct from open even though both can be set inside the same noise_init handler: the field exists so the gating test pins the "handler chain unreachable from handshakeComplete" invariant deterministically (AC #1 / #4).
const ( V2StateAwaitingInit V2SessionState = iota V2StateHandshakeComplete V2StateOpen V2StateClosed )