feat(cluster): RFC 010 c7b — discovery Strategy, static seeds, connector dial loop
Phase 2 gate: 3-node mesh under the subprocess harness, repeatable (10/10).
Strategy (ratified): push-based, spawned as its own actor by the connector —
it emits Discovery events into a channel whenever it learns something and
may run forever; the connector owns all retry/backoff state. StaticSeeds
announces its list once and exits. Discovery is #[non_exhaustive] and
additive-only (candidates announced, never withdrawn) so expiry can land
later without breaking strategies.
One-viable correction to the ratified Discovery shape, flagged: a candidate
is a (name, addr) PAIR, not a bare address. The dial path and the D7
tie-break are keyed by peer name (the dial intent must be registered before
connecting so a crossing inbound Hello sees it), so an anonymous dial would
reintroduce exactly the simultaneous-connect flap D7 exists to prevent.
Discovery mechanisms know names — that is what they discover.
Connector: plain select-loop actor (the c6 shape) folding cmd inbox,
discovery stream, membership stream, and the earliest retry deadline into
one wait. It tracks who is up by SUBSCRIBING TO MEMBERSHIP like any
consumer — first consumer of c7a's snapshot-then-stream surface, no
privileged channel into the manager. Backoff: 250ms doubling to a 5s cap
(the c6c class of one-viable constants), reset on node_up; node_down
schedules a prompt redial with a fresh sequence. A candidate bearing the
local name is parked (that seed is us); every other failure retries — in
particular NameTaken can be our own ghost at the peer, not yet reaped by
its liveness timer, so it must not park. Dials run inline in the loop, the
acceptor's deliberate serialization (each attempt bounded by the connect +
handshake deadlines).
cluster::start(Config {node_name, meta, listen_addr, strategy}) is now the
integrated node start: supervised manager + acceptor + connector. It
completes the node identity: build_hash = cluster::BUILD_HASH (first
consumer, closing the c6d loose end) and incarnation = self_incarnation()
— unix-epoch MILLIS truncated to u32, not seconds: a supervised
crash-and-restart inside one second is routine, and seconds would collide
the ghost with its successor. Cluster handle: local_addr()/local()/
shutdown(); drop stops acceptor+connector loops, manager subtree detaches
(same split as AcceptorHandle alone).
Roadmap-binding, asserted in review: no consumer touches the connection
table — Manager.conns and ConnEntry stay private; the only exposures are
Call::Peers (sorted names, pre-existing) and the membership surface.
tests/cluster_mesh.rs 2/0, 10/10 flake runs: (1) 3-node mesh forms; kill
one (SIGKILL via Drop, per the retractable-state trap: roles park forever)
=> node_down at both survivors; restart same name => new incarnation at
every observer, distinguishable from the ghost; (2) seed unreachable at
start (pre-reserved closed port; accepted micro steal-window, documented)
then arriving later => edge forms via the retry path. All cluster suites
regression-clean (envelope 15, handshake 11, transport 11, lifecycle 1,
liveness 3, connect 9, two_node 3, membership 4); clippy --lib green both
configs; fmt clean; default build compiles.
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
//! RFC 010 c7b — the connector: the dial loop that turns discovered
|
||||
//! candidates into a full mesh.
|
||||
//!
|
||||
//! A plain select-loop actor (the c6 shape). It spawns its [`Strategy`] as a
|
||||
//! child actor and receives [`Discovery`] events from it; it tracks which
|
||||
//! peers are up by **subscribing to membership like any other consumer** —
|
||||
//! no privileged channel into the manager, the same snapshot-then-stream
|
||||
//! surface c8 will use. One `select` folds the command inbox, the discovery
|
||||
//! stream, the membership stream, and the earliest retry deadline into a
|
||||
//! single wait.
|
||||
//!
|
||||
//! Per-candidate state: dial on arrival; on failure retry with capped
|
||||
//! exponential backoff ([`INITIAL_BACKOFF`] doubling to [`MAX_BACKOFF`]);
|
||||
//! on the peer's `node_up` stop dialing and reset the backoff; on its
|
||||
//! `node_down` resume immediately (a fresh sequence — the reconnect case is
|
||||
//! the one backoff exists to pace, but the *first* retry after a death
|
||||
//! should be prompt). A candidate bearing our own name is parked permanently
|
||||
//! — that seed is us. Every other failure retries: in particular a
|
||||
//! `NameTaken` reject can be our own ghost at the peer, not yet reaped by
|
||||
//! its liveness timer, so it must not park.
|
||||
//!
|
||||
//! Dials run **inline in the loop** — the same deliberate serialization as
|
||||
//! the acceptor (c6b): each attempt is bounded by the connect + handshake
|
||||
//! deadlines, and nothing concurrent exists to be starved. A wall of slow
|
||||
//! unreachable seeds would stretch the loop's latency; revisit if a real
|
||||
//! deployment ever hits that shape.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::channel::{channel, select, select_timeout, Receiver, Selectable, Sender};
|
||||
use crate::cluster::connect::dial;
|
||||
use crate::cluster::discovery::{Discovery, Strategy};
|
||||
use crate::cluster::handshake::Local;
|
||||
use crate::cluster::membership::{subscribe, NodeEvent};
|
||||
use crate::cluster::transport::Transport;
|
||||
use crate::pg::NodeId;
|
||||
use crate::scheduler::spawn;
|
||||
|
||||
/// First retry delay after a failed dial attempt.
|
||||
pub const INITIAL_BACKOFF: Duration = Duration::from_millis(250);
|
||||
/// Backoff ceiling: an unreachable seed is retried this often, forever.
|
||||
pub const MAX_BACKOFF: Duration = Duration::from_secs(5);
|
||||
|
||||
enum Cmd {
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// A running connector. `shutdown` (or dropping the last handle) stops the
|
||||
/// dial loop and its strategy only — established connections belong to the
|
||||
/// manager, exactly as with the acceptor.
|
||||
pub struct ConnectorHandle {
|
||||
cmd_tx: Sender<Cmd>,
|
||||
}
|
||||
|
||||
impl ConnectorHandle {
|
||||
/// Ask the connector to stop. Idempotent; a no-op if it already has.
|
||||
pub fn shutdown(&self) {
|
||||
let _ = self.cmd_tx.send(Cmd::Shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered `(name, addr)` and its dial state.
|
||||
struct Candidate {
|
||||
name: String,
|
||||
addr: String,
|
||||
/// This seed is the local node itself: never dialed.
|
||||
parked: bool,
|
||||
/// Delay to apply after the *next* failure.
|
||||
backoff: Duration,
|
||||
next_attempt: Instant,
|
||||
}
|
||||
|
||||
/// Spawn the connector actor. The strategy is spawned as its child; the
|
||||
/// membership subscription is taken inside the actor. Must be called from
|
||||
/// inside an actor (the same requirement as `dial`).
|
||||
pub fn spawn_connector(
|
||||
transport: Box<dyn Transport>,
|
||||
local: Local,
|
||||
strategy: Box<dyn Strategy>,
|
||||
) -> ConnectorHandle {
|
||||
let (cmd_tx, cmd_rx) = channel();
|
||||
spawn(move || run(transport, local, strategy, cmd_rx));
|
||||
ConnectorHandle { cmd_tx }
|
||||
}
|
||||
|
||||
fn run(
|
||||
transport: Box<dyn Transport>,
|
||||
local: Local,
|
||||
strategy: Box<dyn Strategy>,
|
||||
cmd_rx: Receiver<Cmd>,
|
||||
) {
|
||||
// Membership is the connector's source of truth for "who is up" — the
|
||||
// snapshot seeds `connected` before any candidate arrives.
|
||||
let Some(events) = subscribe() else {
|
||||
return; // no manager, no cluster to connect
|
||||
};
|
||||
let (disc_tx, disc_rx) = channel();
|
||||
spawn(move || strategy.run(disc_tx));
|
||||
|
||||
let mut cands: Vec<Candidate> = Vec::new();
|
||||
let mut connected: HashSet<String> = HashSet::new();
|
||||
let mut names: HashMap<NodeId, String> = HashMap::new(); // NodeDown carries only the id
|
||||
let mut strategy_done = false;
|
||||
|
||||
loop {
|
||||
// Drain every input, then act. Order does not matter: acting is
|
||||
// idempotent against the resulting state.
|
||||
match drain_cmd(&cmd_rx) {
|
||||
Drained::Stop => return,
|
||||
Drained::Open => {}
|
||||
}
|
||||
if !strategy_done {
|
||||
strategy_done = drain_discoveries(&disc_rx, &local, &mut cands);
|
||||
}
|
||||
match drain_events(&events.rx, &mut connected, &mut names, &mut cands) {
|
||||
Drained::Stop => return, // manager gone: the cluster is tearing down
|
||||
Drained::Open => {}
|
||||
}
|
||||
|
||||
// Dial everything due, inline (see the module docs on serialization).
|
||||
let now = Instant::now();
|
||||
for c in cands
|
||||
.iter_mut()
|
||||
.filter(|c| !c.parked && !connected.contains(&c.name) && c.next_attempt <= now)
|
||||
{
|
||||
// The outcome does not branch the bookkeeping: on success the
|
||||
// manager's node_up is on its way and flips `connected` (backing
|
||||
// off meanwhile keeps a racing re-attempt from spinning); every
|
||||
// failure retries — see the module docs.
|
||||
let _ = dial(&*transport, &c.addr, &c.name, &local);
|
||||
c.next_attempt = Instant::now() + c.backoff;
|
||||
c.backoff = (c.backoff * 2).min(MAX_BACKOFF);
|
||||
}
|
||||
|
||||
// Wait: until the earliest retry deadline among actionable
|
||||
// candidates, or indefinitely if none is pending.
|
||||
let deadline = cands
|
||||
.iter()
|
||||
.filter(|c| !c.parked && !connected.contains(&c.name))
|
||||
.map(|c| c.next_attempt)
|
||||
.min();
|
||||
let mut arms: Vec<&dyn Selectable> = vec![&cmd_rx, &events.rx];
|
||||
if !strategy_done {
|
||||
arms.push(&disc_rx);
|
||||
}
|
||||
match deadline {
|
||||
Some(d) => {
|
||||
let wait = d.saturating_duration_since(Instant::now());
|
||||
let _ = select_timeout(&arms, wait);
|
||||
}
|
||||
None => {
|
||||
let _ = select(&arms);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Drained {
|
||||
Open,
|
||||
Stop,
|
||||
}
|
||||
|
||||
fn drain_cmd(rx: &Receiver<Cmd>) -> Drained {
|
||||
match rx.try_recv() {
|
||||
Ok(Some(Cmd::Shutdown)) => Drained::Stop,
|
||||
Ok(None) => Drained::Open,
|
||||
Err(_) => Drained::Stop, // all handles dropped
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull every pending discovery into the candidate set (deduplicated by
|
||||
/// `(name, addr)`; a candidate bearing the local name is parked). Returns
|
||||
/// `true` once the strategy's channel closes — it has said all it will.
|
||||
fn drain_discoveries(rx: &Receiver<Discovery>, local: &Local, cands: &mut Vec<Candidate>) -> bool {
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
Ok(Some(Discovery::Candidate { name, addr })) => {
|
||||
if cands.iter().any(|c| c.name == name && c.addr == addr) {
|
||||
continue;
|
||||
}
|
||||
let parked = name == local.node_name;
|
||||
cands.push(Candidate {
|
||||
name,
|
||||
addr,
|
||||
parked,
|
||||
backoff: INITIAL_BACKOFF,
|
||||
next_attempt: Instant::now(),
|
||||
});
|
||||
}
|
||||
Ok(None) => return false,
|
||||
Err(_) => return true, // strategy done; its candidates live on here
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold pending membership events into `connected` (and the id→name map).
|
||||
/// `node_up` resets its candidates' backoff; `node_down` schedules a prompt
|
||||
/// redial with a fresh sequence.
|
||||
fn drain_events(
|
||||
rx: &Receiver<NodeEvent>,
|
||||
connected: &mut HashSet<String>,
|
||||
names: &mut HashMap<NodeId, String>,
|
||||
cands: &mut [Candidate],
|
||||
) -> Drained {
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
Ok(Some(NodeEvent::NodeUp(info))) => {
|
||||
names.insert(info.node, info.name.clone());
|
||||
for c in cands.iter_mut().filter(|c| c.name == info.name) {
|
||||
c.backoff = INITIAL_BACKOFF;
|
||||
}
|
||||
connected.insert(info.name);
|
||||
}
|
||||
Ok(Some(NodeEvent::NodeDown { node })) => {
|
||||
if let Some(name) = names.remove(&node) {
|
||||
connected.remove(&name);
|
||||
let now = Instant::now();
|
||||
for c in cands.iter_mut().filter(|c| c.name == name) {
|
||||
c.backoff = INITIAL_BACKOFF;
|
||||
c.next_attempt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => return Drained::Open,
|
||||
Err(_) => return Drained::Stop,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! RFC 010 c7b — peer discovery: the [`Strategy`] seam and the static-seeds
|
||||
//! implementation.
|
||||
//!
|
||||
//! A strategy is **push-based and runs as its own actor**: the
|
||||
//! [`connector`](crate::cluster::connector) spawns it with the sending end of
|
||||
//! a channel, and the strategy emits [`Discovery`] events whenever it learns
|
||||
//! something — once at startup for a static list, continuously for a future
|
||||
//! mDNS/DNS strategy — for as long as it cares to run. Returning ends the
|
||||
//! strategy actor; the candidates it pushed live on in the connector (the
|
||||
//! connector owns all retry/backoff state, so a strategy never re-announces).
|
||||
//!
|
||||
//! A candidate is a **`(node_name, addr)` pair**, not a bare address: the
|
||||
//! dial path and the D7 tie-break are keyed by peer *name* (the dial intent
|
||||
//! must be registered before connecting so a crossing inbound `Hello` sees
|
||||
//! it), so an anonymous dial would reintroduce exactly the
|
||||
//! simultaneous-connect flap D7 exists to prevent. Discovery mechanisms know
|
||||
//! names — that is what they discover.
|
||||
|
||||
use crate::channel::Sender;
|
||||
|
||||
/// A discovery event, as pushed by a [`Strategy`].
|
||||
///
|
||||
/// Additive-only for now (candidates are announced, never withdrawn);
|
||||
/// `#[non_exhaustive]` so expiry can land later without breaking strategies.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Discovery {
|
||||
/// A peer worth dialing: its claimed node name and a dialable address.
|
||||
Candidate { name: String, addr: String },
|
||||
}
|
||||
|
||||
/// A source of peers to dial. Implementations are spawned as actors by the
|
||||
/// connector — see the module docs for the contract.
|
||||
pub trait Strategy: Send + 'static {
|
||||
/// Run the strategy: push [`Discovery`] events into `out` as they are
|
||||
/// learned; return when done discovering (or when `out` reports closed —
|
||||
/// the connector is gone). Runs inside an actor, so blocking
|
||||
/// cooperatively is fine.
|
||||
fn run(self: Box<Self>, out: Sender<Discovery>);
|
||||
}
|
||||
|
||||
/// The static-seeds strategy: a fixed `(name, addr)` list, announced once.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct StaticSeeds {
|
||||
seeds: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl StaticSeeds {
|
||||
pub fn new(seeds: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>) -> Self {
|
||||
StaticSeeds {
|
||||
seeds: seeds
|
||||
.into_iter()
|
||||
.map(|(n, a)| (n.into(), a.into()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Strategy for StaticSeeds {
|
||||
fn run(self: Box<Self>, out: Sender<Discovery>) {
|
||||
for (name, addr) in self.seeds {
|
||||
if out.send(Discovery::Candidate { name, addr }).is_err() {
|
||||
return; // connector gone; nobody to discover for
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user