//! RFC 010 c6b — the handshake on the accept/connect path. //! //! Per D8 (re-amended): the c5 machines are driven by **straight-line code //! on the path**, not by an actor. The dial side runs [`Initiator`]; the //! acceptor loop runs [`Responder`]. A connection actor is spawned only //! *after* a successful handshake ([`spawn_established`]); every reject, //! protocol failure, timeout, and tie-break loss is resolved right here, //! on the path, by closing — no actor ever exists for a connection that //! didn't establish. //! //! Buffer trap (binding): the path reader and the steady-state actor share //! ONE [`FramedConn`]. Its decode buffer may hold read-ahead past the //! handshake frames, so the *whole* `FramedConn` travels into //! [`spawn_established`] — never a fresh codec over the same socket. //! //! Layering: [`dial_handshake`] and [`accept_handshake`] are the bare path //! steps — IO on a `FramedConn`, no manager, no actors — testable over the //! loopback transport on plain threads. [`dial`] and [`spawn_acceptor`] are //! the manager-integrated layer (actor context required): they keep the //! [`manager`](crate::cluster::manager)'s dial-intent set honest and spawn //! the connection actor on success. use std::io; use std::time::{Duration, Instant}; use crate::channel::{channel, Receiver, Selectable, Sender}; use crate::cluster::conn::spawn_established; use crate::cluster::envelope::{Frame, RejectReason}; use crate::cluster::handshake::{ HelloCtx, Initiator, InitiatorOutcome, Local, Peer, Responder, ResponderOutcome, }; use crate::cluster::manager::{Call, Reply, MANAGER}; use crate::cluster::transport::{FramedConn, Listener, RecvError, SendError, Transport}; use crate::gen_server; use crate::pid::Pid; use crate::scheduler::{self, spawn}; /// How long either side waits for the peer's handshake frame before giving /// up and closing. Enforced on the path via [`FramedConn::recv_deadline`], /// so a peer that connects and goes silent cannot wedge the acceptor. pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5); /// Why a handshake did not establish. In every case the connection has /// already been closed on the path by the time this is returned. #[derive(Debug)] pub enum HandshakeError { /// A `HelloReject` travelled — sent by us (accept side) or received by /// us (dial side). Rejected(RejectReason), /// Accept side only: the inbound dial lost the simultaneous-connect /// tie-break (D7) and was closed silently, no frame sent. TieBreakLoss, /// The peer spoke a valid frame that is wrong here (non-`Hello` first /// frame; non-response to our `Hello`), or an undecodable byte stream. Protocol, /// EOF before the handshake resolved. On the dial side this is also /// what losing the tie-break looks like: the peer closes silently. Closed, /// [`HANDSHAKE_TIMEOUT`] (or the caller's deadline) passed first. TimedOut, /// The transport failed mid-handshake. Transport(io::Error), } fn from_send(e: SendError) -> HandshakeError { match e { // Handshake frames are small and self-made; an encode failure is a // protocol-level impossibility, not a transport fault. SendError::Encode(_) => HandshakeError::Protocol, SendError::Io(e) => HandshakeError::Transport(e), } } fn from_recv(e: RecvError) -> HandshakeError { match e { RecvError::Corrupt(_) => HandshakeError::Protocol, RecvError::TruncatedByPeer => HandshakeError::Closed, RecvError::Io(e) => HandshakeError::Transport(e), RecvError::TimedOut => HandshakeError::TimedOut, } } /// Dial-side path step: send our `Hello`, interpret the one response. On /// `Ok` the connection is established and `framed` is live (with any /// read-ahead intact in its buffer); on `Err` the connection is closed. pub fn dial_handshake( framed: &mut FramedConn, local: &Local, deadline: Instant, ) -> Result { let (initiator, hello) = Initiator::new(local); if let Err(e) = framed.send(&hello) { framed.close(); return Err(from_send(e)); } let outcome = match framed.recv_deadline(deadline) { Ok(Some(frame)) => initiator.on_frame(frame), Ok(None) => { framed.close(); return Err(HandshakeError::Closed); } Err(e) => { framed.close(); return Err(from_recv(e)); } }; match outcome { InitiatorOutcome::Established(peer) => Ok(peer), InitiatorOutcome::Rejected(reason) => { framed.close(); Err(HandshakeError::Rejected(reason)) } InitiatorOutcome::Failed(_) => { framed.close(); Err(HandshakeError::Protocol) } } } /// Accept-side path step: read the first frame, judge it, answer or close. /// /// `ctx_for` supplies the [`HelloCtx`] for the *offered* name — knowledge /// only the frame reveals, which is why it is a callback and not a value /// (the integrated acceptor asks the manager; loopback tests fabricate). /// It is not called when the first frame is not a `Hello`. /// /// On `Ok` the ack has been sent and `framed` is live (read-ahead intact); /// on `Err` any owed reject has been sent and the connection is closed. pub fn accept_handshake( framed: &mut FramedConn, local: Local, ctx_for: impl FnOnce(&str) -> HelloCtx, deadline: Instant, ) -> Result { let frame = match framed.recv_deadline(deadline) { Ok(Some(frame)) => frame, Ok(None) => { framed.close(); return Err(HandshakeError::Closed); } Err(e) => { framed.close(); return Err(from_recv(e)); } }; let ctx = match &frame { Frame::Hello { node_name, .. } => ctx_for(node_name), _ => HelloCtx::default(), }; match Responder::new(local).on_frame(frame, ctx) { ResponderOutcome::Accepted { reply, peer } => { if let Err(e) = framed.send(&reply) { framed.close(); return Err(from_send(e)); } Ok(peer) } ResponderOutcome::Rejected { reply, reason } => { // Best effort: the reject is the cross-version compatibility // anchor, but if the write fails the peer sees a bare close, // which it must survive anyway. let _ = framed.send(&reply); framed.close(); Err(HandshakeError::Rejected(reason)) } ResponderOutcome::TieBreakLoss => { // D7: close silently — the peer computes the same verdict. framed.close(); Err(HandshakeError::TieBreakLoss) } ResponderOutcome::Failed(_) => { framed.close(); Err(HandshakeError::Protocol) } } } // --------------------------------------------------------------------------- // Manager-integrated layer // --------------------------------------------------------------------------- /// Why an integrated [`dial`] did not produce a connection. #[derive(Debug)] pub enum DialError { /// Another dial to this peer name is already in flight. AlreadyDialing, /// The manager is not running (or answered nonsense). ManagerUnavailable, /// The transport could not connect. Connect(io::Error), /// Connected, but the handshake did not establish. Handshake(HandshakeError), /// The peer at `addr` established, but answered as a different name /// than the one we dialed — the tie-break bookkeeping (keyed by the /// dialed name) would be unsound, so the connection is closed. PeerNameMismatch { expected: String, got: String }, /// The handshake established, but the manager refused the registration: /// a connection to this peer already exists. The loser has been closed. Duplicate, } /// Dial `peer_name` at `addr` and run the handshake, keeping the manager's /// dial-intent set honest around it: the intent is registered *before* /// connecting (so a crossing inbound `Hello` sees it) and cleared the /// moment the handshake resolves, before the connection actor is spawned. /// Must run inside an actor. Retrying is the caller's business (c7's dial /// loop); a lost tie-break surfaces as `Handshake(Closed)` — the peer's /// accepted connection is already on its way. pub fn dial( transport: &dyn Transport, addr: &str, peer_name: &str, local: &Local, ) -> Result { let me = scheduler::self_pid(); match gen_server::call( MANAGER, Call::DialBegin { name: peer_name.to_string(), pid: me, }, ) { Ok(Reply::DialBegan(true)) => {} Ok(Reply::DialBegan(false)) => return Err(DialError::AlreadyDialing), _ => return Err(DialError::ManagerUnavailable), } let result = connect_and_shake(transport, addr, local); // Cleared immediately on outcome — a stale intent during the established // window would corrupt later tie-breaks. Synchronous (a call): the // intent is provably gone before anything else happens. let _ = gen_server::call( MANAGER, Call::DialEnd { name: peer_name.to_string(), }, ); let (mut framed, peer) = result?; if peer.node_name != peer_name { framed.close(); return Err(DialError::PeerNameMismatch { expected: peer_name.to_string(), got: peer.node_name, }); } spawn_established(framed, peer).map_err(|_| DialError::Duplicate) } fn connect_and_shake( transport: &dyn Transport, addr: &str, local: &Local, ) -> Result<(FramedConn, Peer), DialError> { let conn = transport.dial(addr).map_err(DialError::Connect)?; let mut framed = FramedConn::new(conn); let deadline = Instant::now() + HANDSHAKE_TIMEOUT; let peer = dial_handshake(&mut framed, local, deadline).map_err(DialError::Handshake)?; Ok((framed, peer)) } /// A running acceptor. [`shutdown`](AcceptorHandle::shutdown) (or dropping /// the last handle) stops the accept loop only: connections it established /// belong to the [`manager`](crate::cluster::manager) and keep running, to /// be torn down through the table (`Disconnect`, a peer close, or manager /// shutdown). pub struct AcceptorHandle { cmd_tx: Sender<()>, addr: String, } impl AcceptorHandle { /// Ask the acceptor to stop. Idempotent; a no-op if it already has. pub fn shutdown(&self) { let _ = self.cmd_tx.send(()); } /// The concrete bound address, dialable as-is. pub fn local_addr(&self) -> &str { &self.addr } } /// Spawn the acceptor actor over a bound listener. Each inbound connection /// is handshaken **inline in the loop** (a deliberate serialization: the /// per-frame deadline bounds how long any one peer can hold the line, and /// nothing concurrent exists to be starved before c7). The listener must be /// fd-backed ([`Listener::readable_arm`]); the loopback listener is not, /// and its acceptor exits immediately — loopback handshakes are driven /// synchronously through the path fns instead, per D8. pub fn spawn_acceptor(listener: Box, local: Local) -> AcceptorHandle { let addr = listener.local_addr(); let (cmd_tx, cmd_rx) = channel(); spawn(move || accept_loop(listener, local, cmd_rx)); AcceptorHandle { cmd_tx, addr } } fn accept_loop(mut listener: Box, local: Local, cmd_rx: Receiver<()>) { loop { let Some(arm) = listener.readable_arm() else { return; }; let arms: [&dyn Selectable; 2] = [&cmd_rx, &arm]; match crate::channel::try_select(&arms) { Ok(0) => match cmd_rx.try_recv() { Ok(Some(())) => return, Ok(None) => continue, // spurious wake Err(_) => return, // all handles dropped }, Ok(_) => { // The listener is readable: accept completes without parking. let conn = match listener.accept() { Ok(conn) => conn, Err(_) => return, // listener itself is broken }; handle_inbound(FramedConn::new(conn), &local); } Err(_) => return, // fd arm failed to register: listener is gone } } } /// Run the accept-side handshake for one inbound connection, asking the /// manager for the [`HelloCtx`], and hand the established connection to the /// manager. Every failure was already resolved on the path (reject sent / /// closed, or the registration refused and the actor stopped), so there is /// nothing for the acceptor to carry forward. fn handle_inbound(mut framed: FramedConn, local: &Local) { let deadline = Instant::now() + HANDSHAKE_TIMEOUT; let ctx_for = |name: &str| match gen_server::call( MANAGER, Call::HelloCtx { peer_name: name.to_string(), }, ) { Ok(Reply::HelloCtx(ctx)) => ctx, // Manager unreachable: nobody could register this connection anyway, // so claim the name taken and reject rather than accept an orphan. _ => HelloCtx { name_claimed: true, dialing_this_peer: false, }, }; if let Ok(peer) = accept_handshake(&mut framed, local.clone(), ctx_for, deadline) { let _ = spawn_established(framed, peer); } }