Skip to main content

weida/
listener.rs

1//! Listener, bindings and the endpoint namespace.
2//!
3//! A Listener is one externally reachable messaging namespace, not one socket
4//! (master doc §3): several bindings may serve the same set of endpoints.
5
6use std::collections::hash_map::Entry;
7use std::collections::{HashMap, HashSet};
8use std::io;
9use std::net::SocketAddr;
10use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
11use std::sync::{Arc, Mutex, PoisonError, RwLock, Weak};
12use std::time::{Duration, Instant};
13
14use quinn::VarInt;
15use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, watch};
16use weida_core::{EndpointAddr, Error, Fingerprint, Limits, RELAY_PATH, validate_endpoint_path};
17use weida_protocol::codes;
18use weida_protocol::header::GuaranteeSet;
19
20use crate::config::{ClientTls, ServerTls};
21use crate::conn::ConnCtx;
22use crate::endpoint::{
23    BusMember, BusState, Endpoint, PairState, Paired, PubState, Publisher, PullState, Puller,
24    RepState, Replier, RespondState, Respondent,
25};
26use crate::handoff::{self, Handoff, HandoverSocket};
27use crate::inproc;
28use crate::network::{AddrLease, BoundSocket};
29use crate::pubsub::SubRegistry;
30use crate::relay::{RegisterAttach, Relay, RelaySocket};
31use crate::runtime::{Exec, RuntimeInner, Shared};
32use crate::stream::{Acceptor, Incoming, Peer};
33use crate::tls;
34use crate::transfer::{IncomingRequest, IncomingTransfer};
35use crate::transport::{Link, QuicLink};
36
37/// What a registered endpoint path does with an inbound transfer.
38pub(crate) enum Route {
39    /// A replier: inbound exchanges become [`IncomingRequest`]s.
40    Request(mpsc::Sender<IncomingRequest>),
41    /// A puller or subscriber: inbound one-way transfers are queued as-is.
42    Transfer(mpsc::Sender<IncomingTransfer>),
43    /// A raw L0 acceptor: both stream kinds are queued, tagged.
44    Raw(mpsc::Sender<Incoming>),
45    /// A publisher. Nothing inbound is accepted on this path; the entry exists
46    /// so the path is claimed exclusively and so SUBSCRIBE can be answered for
47    /// a path that really is served here.
48    Pub,
49    /// A paired endpoint: one-way transfers in both directions, from exactly
50    /// **one** peer ([`PairOwner`]).
51    Pair {
52        /// Where an accepted transfer goes.
53        queue: mpsc::Sender<IncomingTransfer>,
54        /// The one connection this endpoint talks to.
55        owner: Arc<PairOwner>,
56    },
57    /// A radio. Like a publisher it accepts nothing inbound; its SUBSCRIBE
58    /// frames are dish joins, kept in the hub
59    /// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §4.6).
60    Radio(Arc<crate::radio::RadioHub>),
61    /// A dish: inbound segments are checked against the newest delivered on
62    /// their topic and queued without ever blocking the connection.
63    Dish(crate::radio::DishRoute),
64}
65
66/// The single peer of a paired endpoint, and the claim on it.
67///
68/// `id` is `0` until a connection takes the endpoint, then that connection's
69/// `stable_id` **plus one** — `0` is the sentinel, so a stable id of zero
70/// cannot masquerade as "unclaimed". A stream from any other connection is
71/// refused with `LIMIT_EXCEEDED` and the connection survives: ZeroMQ's PAIR
72/// drops the newcomer silently, and refusing while saying so is this
73/// repository's rule for a capacity decision
74/// ([decisions/0005](../../../docs/decisions/0005-refusal-race.md)).
75///
76/// The connection is held **weakly**. A bound endpoint lives in the
77/// listener's namespace and every connection holds that namespace, so a
78/// strong handle here would be a cycle: the connection would keep itself
79/// alive through the route that names it. A peer that went away upgrades to
80/// `None`, which is exactly what the sending side needs to know.
81///
82/// **The claim is released when its holder dies.** A pair whose peer
83/// restarts, or whose connection went past the idle timeout, is claimable
84/// again: holding the endpoint against a connection that no longer exists
85/// would make one peer's shutdown permanent, which is neither ZeroMQ's
86/// behaviour nor nanomsg's and is not what "one peer at a time" means. The
87/// release happens inside [`PairOwner::claim`] rather than in a destructor
88/// because the holder is exactly what a newcomer's claim has to compare
89/// itself against.
90pub(crate) struct PairOwner {
91    id: AtomicU64,
92    conn: watch::Sender<Option<Weak<ConnCtx>>>,
93}
94
95impl PairOwner {
96    pub(crate) fn new() -> PairOwner {
97        PairOwner {
98            id: AtomicU64::new(0),
99            conn: watch::channel(None).0,
100        }
101    }
102
103    /// Claims this endpoint for `conn`, or reports that another peer holds it.
104    ///
105    /// The loop runs at most twice: either the claim is free, or a dead
106    /// holder is released and the retry takes it, or a live holder refuses
107    /// it. Two newcomers racing a dead holder both see it gone, exactly one
108    /// wins the `0 -> id` exchange, and the loser refuses against the
109    /// winner.
110    pub(crate) fn claim(&self, conn: &Arc<ConnCtx>) -> bool {
111        let id = conn.conn.stable_id() as u64 + 1;
112        loop {
113            match self
114                .id
115                .compare_exchange(0, id, Ordering::AcqRel, Ordering::Acquire)
116            {
117                Ok(_) => {
118                    self.conn.send_replace(Some(Arc::downgrade(conn)));
119                    return true;
120                }
121                // The same connection again: every stream after the first.
122                Err(held) if held == id => return true,
123                Err(held) => {
124                    if self.holder_is_live() {
125                        return false;
126                    }
127                    // Dropping the id back to the sentinel is what makes the
128                    // endpoint claimable; the watch value goes with it so a
129                    // sender waiting in `peer` waits for the next peer
130                    // instead of reading a dead one.
131                    if self
132                        .id
133                        .compare_exchange(held, 0, Ordering::AcqRel, Ordering::Acquire)
134                        .is_ok()
135                    {
136                        self.conn.send_replace(None);
137                    }
138                }
139            }
140        }
141    }
142
143    /// Is the connection that holds this endpoint still usable?
144    ///
145    /// A dropped `ConnCtx` fails to upgrade; a *closed* one may still be
146    /// upgradable, because a pool or a drain can outlive the connection it
147    /// holds, and a closed connection can carry nothing for this pair.
148    fn holder_is_live(&self) -> bool {
149        let held = self.conn.borrow().clone();
150        held.and_then(|weak| weak.upgrade())
151            .is_some_and(|ctx| ctx.conn.close_reason().is_none())
152    }
153
154    /// The peer, once one has claimed the endpoint and while it is alive.
155    pub(crate) async fn peer(&self) -> Result<Arc<ConnCtx>, Error> {
156        let mut rx = self.conn.subscribe();
157        loop {
158            if let Some(weak) = rx.borrow_and_update().clone() {
159                return weak.upgrade().ok_or(Error::NotConnected);
160            }
161            rx.changed().await.map_err(|_| Error::NotConnected)?;
162        }
163    }
164}
165
166/// Connection, then path, then the filters held: [`Namespace`]'s record of
167/// raw consumers.
168type ConsumerFilters = HashMap<usize, HashMap<Arc<str>, HashSet<String>>>;
169
170/// Endpoint path to accept-queue map.
171///
172/// A plain `RwLock<HashMap>`, not an async lock: lookup is a hash and a channel
173/// clone, and the guard is never held across an `await`.
174pub(crate) struct Namespace {
175    routes: RwLock<HashMap<Arc<str>, Route>>,
176    /// Which filters each connection holds on which raw paths: connection,
177    /// then path, then the set of filters.
178    ///
179    /// Only L2 consumers appear here: a Pub/Sub subscription is the
180    /// [`SubRegistry`]'s business, and a queue's is this table's, because the
181    /// thing that must happen when the connection closes is different — a
182    /// publisher forgets a subscriber, a queue is *told*, so it can requeue
183    /// what that consumer owed (0018 §4.7). The set holds **filters**, not
184    /// paths, because a connection may hold several on one path and the path
185    /// is only forgotten with the last of them; it is also what makes a
186    /// reservation against `max_subscriptions` exist exactly once per filter
187    /// held. Bounded by the same `max_subscriptions` count the registry
188    /// enforces.
189    consumers: RwLock<ConsumerFilters>,
190}
191
192impl Namespace {
193    pub(crate) fn new() -> Namespace {
194        Namespace {
195            routes: RwLock::new(HashMap::new()),
196            consumers: RwLock::new(HashMap::new()),
197        }
198    }
199
200    /// Looks a path up. The path is compared byte for byte: it is an opaque
201    /// identifier, so there is no splitting, prefix matching or wildcarding
202    /// (master doc §4, §81 rule 5).
203    ///
204    /// Returns a clone of the route's sender rather than a guard, so the lock
205    /// is never held across an `await`.
206    pub(crate) fn lookup(&self, path: &str) -> Option<Route> {
207        self.routes
208            .read()
209            .expect("namespace lock poisoned")
210            .get(path)
211            .map(Route::clone_sender)
212    }
213
214    pub(crate) fn register(&self, path: &str, route: Route) -> Result<(), Error> {
215        let mut routes = self.routes.write().expect("namespace lock poisoned");
216        match routes.entry(Arc::from(path)) {
217            Entry::Occupied(_) => Err(Error::AlreadyRegistered),
218            Entry::Vacant(slot) => {
219                slot.insert(route);
220                Ok(())
221            }
222        }
223    }
224
225    /// Releases a path so the same endpoint can be registered again.
226    ///
227    /// Used by subscriber teardown: a `Sub` claims its path on the pooled
228    /// client connection and must give it back, or a later `Sub` on the same
229    /// connection would fail with [`Error::AlreadyRegistered`] forever.
230    pub(crate) fn unregister(&self, path: &str) {
231        self.routes
232            .write()
233            .expect("namespace lock poisoned")
234            .remove(path);
235    }
236
237    /// Records that `conn_id` consumes on `path` with `filter`.
238    ///
239    /// `false` when it already did: the caller then has nothing to count and
240    /// nothing to announce.
241    pub(crate) fn note_consumer(&self, conn_id: usize, path: &str, filter: &str) -> bool {
242        let mut consumers = self.consumers.write().expect("namespace lock poisoned");
243        let paths = consumers.entry(conn_id).or_default();
244        match paths.get_mut(path) {
245            Some(filters) if filters.contains(filter) => false,
246            Some(filters) => filters.insert(filter.to_owned()),
247            None => {
248                paths.insert(Arc::from(path), HashSet::from([filter.to_owned()]));
249                true
250            }
251        }
252    }
253
254    /// Forgets one filter `conn_id` held on `path`; `false` when it held no
255    /// such filter. The last filter of a path takes the path with it and the
256    /// last path takes the connection, so nothing is left behind.
257    pub(crate) fn forget_consumer(&self, conn_id: usize, path: &str, filter: &str) -> bool {
258        let mut consumers = self.consumers.write().expect("namespace lock poisoned");
259        let Some(paths) = consumers.get_mut(&conn_id) else {
260            return false;
261        };
262        let Some(filters) = paths.get_mut(path) else {
263            return false;
264        };
265        let held = filters.remove(filter);
266        if filters.is_empty() {
267            paths.remove(path);
268        }
269        if paths.is_empty() {
270            consumers.remove(&conn_id);
271        }
272        held
273    }
274
275    /// Takes every path `conn_id` still consumes on, with the route serving
276    /// it.
277    ///
278    /// Called once, when the connection closes: the entry is removed, so a
279    /// queue is told exactly once that a consumer is gone, and told so for
280    /// **every** path with a filter still held, however many filters the
281    /// connection withdrew along the way.
282    pub(crate) fn take_consumer_routes(&self, conn_id: usize) -> Vec<(Arc<str>, Route)> {
283        let taken = self
284            .consumers
285            .write()
286            .expect("namespace lock poisoned")
287            .remove(&conn_id);
288        let Some(paths) = taken else {
289            return Vec::new();
290        };
291        let routes = self.routes.read().expect("namespace lock poisoned");
292        paths
293            .into_keys()
294            .filter_map(|path| {
295                let route = routes.get(&path)?.clone_sender();
296                Some((path, route))
297            })
298            .collect()
299    }
300}
301
302impl Route {
303    fn clone_sender(&self) -> Route {
304        match self {
305            Route::Request(tx) => Route::Request(tx.clone()),
306            Route::Transfer(tx) => Route::Transfer(tx.clone()),
307            Route::Raw(tx) => Route::Raw(tx.clone()),
308            Route::Pair { queue, owner } => Route::Pair {
309                queue: queue.clone(),
310                owner: Arc::clone(owner),
311            },
312            Route::Pub => Route::Pub,
313            Route::Radio(hub) => Route::Radio(Arc::clone(hub)),
314            Route::Dish(route) => Route::Dish(route.clone()),
315        }
316    }
317}
318
319pub(crate) struct ListenerInner {
320    pub(crate) runtime: Arc<RuntimeInner>,
321    pub(crate) namespace: Arc<Namespace>,
322    pub(crate) subs: Arc<SubRegistry>,
323}
324
325/// One externally reachable messaging namespace.
326///
327/// A Listener is a namespace, not a socket and not a transport: it owns the
328/// endpoint routing table and nothing else (master doc §3). Credentials belong
329/// to the individual bindings, because they are transport-specific — a QUIC
330/// binding needs a certificate and key, a future in-process or adapter binding
331/// needs neither — and because two interfaces of one service may legitimately
332/// present different certificates.
333#[derive(Clone)]
334pub struct Listener {
335    inner: Arc<ListenerInner>,
336}
337
338impl Listener {
339    pub(crate) fn new(runtime: Arc<RuntimeInner>) -> Listener {
340        // A binding cannot tell the tiers apart — nothing on the wire
341        // distinguishes them (`docs/PROTOCOL.md` §2.5) — so it serves every
342        // accepted connection on the bulk profile, which is the one that must
343        // tolerate payload.
344        let limits = runtime.config.limits;
345        let ordering = runtime.config.guarantees.ordering;
346        Listener {
347            inner: Arc::new(ListenerInner {
348                runtime,
349                namespace: Arc::new(Namespace::new()),
350                subs: Arc::new(SubRegistry::new(limits, ordering)),
351            }),
352        }
353    }
354
355    /// Adds a native QUIC binding with its own server identity.
356    ///
357    /// `tls` may be a bare [`crate::Identity`] — the binding then accepts
358    /// anonymous peers — or a [`ServerTls`] that also requires clients to
359    /// present an identity it trusts. The material is loaded and validated
360    /// here, so a misconfigured certificate fails before the socket serves
361    /// anything. Pass port `0` to let the OS choose; read it back with
362    /// [`Binding::local_addr`].
363    ///
364    /// Several bindings may serve the same Listener, each with its own
365    /// identity: the endpoints they expose are the same, the identities they
366    /// present need not be.
367    pub async fn bind_quic(
368        &self,
369        addr: SocketAddr,
370        tls: impl Into<ServerTls>,
371    ) -> Result<Binding, Error> {
372        let server_config = tls::server_config(&tls.into(), &self.inner.runtime.config.limits)?;
373        let socket = self
374            .inner
375            .runtime
376            .config
377            .network
378            .bind_server(addr, &self.inner.runtime.exec)?;
379        self.serve_quic(socket, server_config)
380    }
381
382    /// Adds a native QUIC binding on a socket that is already bound.
383    ///
384    /// For a process that received its socket rather than binding it: from
385    /// its predecessor over `SCM_RIGHTS` after [`Binding::hand_over`], or
386    /// through socket activation. Otherwise it is exactly
387    /// [`Listener::bind_quic`].
388    ///
389    /// The socket is taken as it is: weida neither binds it nor sets options
390    /// on it, and [`Binding::local_addr`] reports the address it is bound to.
391    /// The socket is an OS socket, so a binding made here is never on a
392    /// simulated network.
393    ///
394    /// A predecessor that called `hand_over` no longer reads the socket, so
395    /// the successor may serve it at once; it calls [`Binding::take_over`]
396    /// once its endpoints are registered.
397    pub async fn bind_quic_socket(
398        &self,
399        socket: std::net::UdpSocket,
400        tls: impl Into<ServerTls>,
401    ) -> Result<Binding, Error> {
402        let server_config = tls::server_config(&tls.into(), &self.inner.runtime.config.limits)?;
403        self.serve_quic(
404            BoundSocket::os(socket, &self.inner.runtime.exec)?,
405            server_config,
406        )
407    }
408
409    /// Serves this Listener's endpoints through a relay, for a peer that can
410    /// only dial out ([`crate::Relay`], `docs/PROTOCOL.md` §9.6).
411    ///
412    /// Dials `relay`, a `weida://[relay-key@]host[:port]/.weida/relay`
413    /// address, on `via`'s terms and registers there under the key `via`
414    /// presents, which therefore needs an identity. A dialler reaches the
415    /// endpoints as `weida+relay://<key>@[relay-key@]host[:port]/path`, with
416    /// QUIC and TLS end to end: `tls` is this side's server identity and
417    /// client trust, exactly as for [`Listener::bind_quic`], and every
418    /// endpoint sees the dialler's own key, not the relay's.
419    ///
420    /// The registration is kept as a dialled address is: a lost relay is
421    /// redialled and registered again under the runtime's
422    /// [`crate::ReconnectPolicy`], reported on [`Binding::relay_events`]. The
423    /// first registration's failure is returned, and nothing is served then:
424    /// [`Error::Rejected`] where the relay refused it.
425    pub async fn bind_relay(
426        &self,
427        relay: &str,
428        via: impl Into<ClientTls>,
429        tls: impl Into<ServerTls>,
430    ) -> Result<Binding, Error> {
431        let runtime = &self.inner.runtime;
432        let server_config = tls::server_config(&tls.into(), &runtime.config.limits)?;
433        if EndpointAddr::parse(relay)?.path != RELAY_PATH {
434            return Err(Error::InvalidAddress(format!(
435                "a relay serves on {RELAY_PATH}: {relay:?}"
436            )));
437        }
438        let socket = Arc::new(RelaySocket::new());
439        let peer = Peer::with_attach(
440            Arc::clone(runtime),
441            Arc::new(via.into()),
442            Some(Arc::new(RegisterAttach::new(&socket))),
443        );
444        peer.connect(relay).await?;
445        socket.set_peer(peer);
446        let served = BoundSocket::relay(Arc::clone(&socket), &runtime.exec)
447            .and_then(|bound| self.serve_quic(bound, server_config));
448        match served {
449            Ok(mut binding) => {
450                binding.relay = Some(socket);
451                Ok(binding)
452            }
453            Err(e) => {
454                socket.release();
455                Err(e)
456            }
457        }
458    }
459
460    /// Serves this Listener's endpoints over QUIC on `socket`.
461    fn serve_quic(
462        &self,
463        socket: BoundSocket,
464        server_config: quinn::ServerConfig,
465    ) -> Result<Binding, Error> {
466        let exec = self.inner.runtime.exec.clone();
467        let BoundSocket {
468            inner,
469            runtime,
470            lease,
471        } = socket;
472
473        // Inside the runtime context: `quinn` spawns the endpoint's driver
474        // as it is constructed, and the calling thread may have no reactor.
475        let (endpoint, socket) = {
476            let _guard = exec.enter();
477            let socket = Arc::new(HandoverSocket::new(inner));
478            let endpoint = quinn::Endpoint::new_with_abstract_socket(
479                quinn::EndpointConfig::default(),
480                Some(server_config),
481                Arc::clone(&socket) as Arc<dyn quinn::AsyncUdpSocket>,
482                runtime,
483            )
484            .map_err(Error::Io)?;
485            (endpoint, socket)
486        };
487        let local_addr = endpoint.local_addr().map_err(Error::Io)?;
488        let served = Arc::new(ServedEndpoint::new(endpoint, lease));
489        self.inner.runtime.track_endpoint(Arc::clone(&served));
490
491        let peers = Arc::new(PeerConns::default());
492        let open = Arc::new(OpenConns::default());
493        exec.spawn(accept_connections(
494            Arc::clone(&served),
495            Arc::clone(&self.inner),
496            Arc::clone(&peers),
497            Arc::clone(&open),
498        ));
499
500        tracing::info!(%local_addr, "quic binding listening");
501        Ok(Binding {
502            served,
503            local_addr,
504            peers,
505            socket,
506            open,
507            close_timeout: self.inner.runtime.config.shutdown_timeout,
508            exec,
509            relay: None,
510        })
511    }
512
513    /// Binds this Listener's endpoints on an in-process bus.
514    ///
515    /// The counterpart of [`Listener::bind_quic`] for the transport that has
516    /// no socket: `weida+inproc://<bus>/<path>` reaches the same endpoints
517    /// from the same process, with the same frames, the same HELLO and the
518    /// same negotiation, and without TLS or credentials
519    /// (`docs/PROTOCOL.md` §2.1,
520    /// [decisions/0010](../../../docs/decisions/0010-local-transport.md)
521    /// §4.1). The bus name is at most 256 bytes and unique within the
522    /// process; binding a name twice fails with
523    /// [`Error::AlreadyRegistered`].
524    pub fn bind_inproc(&self, bus: &str) -> Result<LocalBinding, Error> {
525        let incoming = inproc::bind(bus)?;
526        let exec = self.inner.runtime.exec.clone();
527        exec.spawn(accept_local(
528            incoming,
529            Arc::clone(&self.inner.namespace),
530            Arc::clone(&self.inner.subs),
531            self.inner.runtime.config.limits,
532            exec.clone(),
533            self.inner.runtime.config.guarantees,
534            self.inner.runtime.shared(),
535        ));
536        tracing::info!(bus, "inproc binding listening");
537        Ok(LocalBinding {
538            bus: bus.to_owned(),
539        })
540    }
541
542    /// Binds this Listener's endpoints on an `AF_UNIX` socket.
543    ///
544    /// `SOCK_STREAM` on a filesystem path, no TLS and no credentials of our
545    /// own: the peer is proved by the kernel instead
546    /// ([decisions/0010](../../../docs/decisions/0010-local-transport.md)
547    /// §4.4, §4.5). A live listener on the path is refused
548    /// ([`ErrorKind::AddrInUse`](std::io::ErrorKind::AddrInUse)); a socket
549    /// file a crash left behind is replaced. The socket is bound in a private
550    /// `0700` directory next to `path`, given mode `0600` there rather than
551    /// inheriting `umask`, and renamed into place, so it is never visible with
552    /// another mode. **The directory is still what makes that safe**:
553    /// whoever can write it can rename over the node afterwards
554    /// (`docs/research/ipc.md` §1.2, §7), so `path` MUST live in a directory
555    /// this process owns and no other user may write.
556    ///
557    /// Connections are grouped into peers by
558    /// [decision 0012](../../../docs/decisions/0012-local-connection-grouping.md):
559    /// the first connection is the peer, further ones carry its group token
560    /// and are admitted only if the kernel credentials match.
561    #[cfg(unix)]
562    pub fn bind_unix(&self, path: impl AsRef<std::path::Path>) -> Result<UnixBinding, Error> {
563        let path = path.as_ref();
564        let exec = self.inner.runtime.exec.clone();
565        #[cfg(feature = "test-util")]
566        if let Some(net) = self.inner.runtime.config.network.sim_net() {
567            let crate::sim::LocalListener { incoming, lease } = net.bind_local(path)?;
568            let (serve, requests) = self.local_accept(|link| Link::Unix(Box::new(link)));
569            exec.spawn(accept_sim_unix(incoming, requests, serve));
570            tracing::info!(path = %path.display(), "simulated unix binding listening");
571            return Ok(UnixBinding {
572                inner: UnixBound::Sim(lease),
573            });
574        }
575        let (binding, listener) = {
576            // Inside the runtime context: tokio registers the socket with the
577            // reactor as it is constructed, and the calling thread may have
578            // no reactor of its own.
579            let _guard = exec.enter();
580            // The bind hygiene — the `sun_path` budget, the socket-type
581            // check, the live-listener probe, the private-directory bind
582            // and rename, and the explicit mode — is `weida-runtime`'s,
583            // because `ipc://` on any protocol needs the same answers
584            // [0010 §4.5].
585            weida_runtime::BoundUnixSocket::bind(path)?
586        };
587        let (serve, requests) = self.local_accept(|link| Link::Unix(Box::new(link)));
588        exec.spawn(accept_unix(listener, requests, serve));
589        tracing::info!(path = %path.display(), "unix binding listening");
590        Ok(UnixBinding {
591            inner: UnixBound::Os(binding),
592        })
593    }
594
595    /// Binds a Windows named pipe, `\\.\pipe\<name>`, and serves it.
596    ///
597    /// The pipe is created with an owner-only descriptor, for local clients
598    /// only, and only if the name does not exist yet — the three answers a
599    /// pipe needs where a socket file needs a private directory
600    /// ([decisions/0010](../../../docs/decisions/0010-local-transport.md)
601    /// §4.5). Connections are grouped into peers exactly as on `AF_UNIX`
602    /// ([decision 0012](../../../docs/decisions/0012-local-connection-grouping.md)).
603    #[cfg(windows)]
604    pub fn bind_pipe(&self, name: &str) -> Result<PipeBinding, Error> {
605        let addr = weida_core::PipeAddr::parse(&format!("{}://{name}/", weida_core::SCHEME_PIPE))?;
606        let exec = self.inner.runtime.exec.clone();
607        let (binding, first) = {
608            // Inside the runtime context, for the same reason as on unix.
609            let _guard = exec.enter();
610            weida_runtime::BoundPipe::bind(addr.os_path())?
611        };
612        let name = addr.name.clone();
613        let (stop_tx, stop_rx) = tokio::sync::oneshot::channel();
614        let (serve, requests) = self.local_accept(|link| Link::Pipe(Box::new(link)));
615        exec.spawn(accept_pipe(binding, first, stop_rx, requests, serve));
616        tracing::info!(pipe = %name, "pipe binding listening");
617        Ok(PipeBinding {
618            name,
619            _stop: stop_tx,
620        })
621    }
622
623    /// What every accepted connection of a grouped local transport is
624    /// served with, and the requests of its links' accept barrier, which the
625    /// accept loop answers.
626    #[cfg(any(unix, windows))]
627    fn local_accept<S: crate::grouped::Stream>(
628        &self,
629        link: fn(crate::grouped::Grouped<S>) -> Link,
630    ) -> (LocalAccept<S>, crate::grouped::BarrierRequests) {
631        let max_connections = self.inner.runtime.config.max_connections;
632        let (barrier, requests) = crate::grouped::AcceptBarrier::new();
633        let serve = LocalAccept {
634            groups: Arc::new(crate::grouped::Groups::new(Arc::clone(&barrier))),
635            barrier,
636            namespace: Arc::clone(&self.inner.namespace),
637            subs: Arc::clone(&self.inner.subs),
638            limits: self.inner.runtime.config.limits,
639            exec: self.inner.runtime.exec.clone(),
640            guarantees: self.inner.runtime.config.guarantees,
641            shared: self.inner.runtime.shared(),
642            link,
643            // tokio panics above `Semaphore::MAX_PERMITS`.
644            admitted: Arc::new(Semaphore::new(max_connections.min(Semaphore::MAX_PERMITS))),
645            departing: Arc::new(Semaphore::new(
646                max_connections.clamp(1, Semaphore::MAX_PERMITS),
647            )),
648            refusals: Arc::new(LogThrottle::new(REFUSAL_LOG_INTERVAL)),
649        };
650        (serve, requests)
651    }
652
653    /// Registers a replier for `path`.
654    ///
655    /// The path must be a valid endpoint path and must not already be
656    /// registered on this listener.
657    pub fn replier(&self, path: &str) -> Result<Replier, Error> {
658        validate_endpoint_path(path)?;
659        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
660        self.inner.namespace.register(path, Route::Request(tx))?;
661        Ok(Endpoint::from_state(RepState::new(path, rx)))
662    }
663
664    /// Registers a puller for `path`.
665    ///
666    /// Pull binds and Push connects, mirroring Rep/Req. The path must be a
667    /// valid endpoint path and must not already be registered on this
668    /// listener, whatever pattern claimed it.
669    pub fn puller(&self, path: &str) -> Result<Puller, Error> {
670        validate_endpoint_path(path)?;
671        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
672        self.inner.namespace.register(path, Route::Transfer(tx))?;
673        Ok(Endpoint::from_state(PullState::new(path, rx)))
674    }
675
676    /// Registers a publisher for `path`.
677    ///
678    /// Pub binds and Sub connects. Nothing inbound is accepted on the path —
679    /// the registration claims it exclusively — and subscriptions that arrived
680    /// before this call are already recorded, so a publisher created after its
681    /// subscribers still reaches them.
682    pub fn publisher(&self, path: &str) -> Result<Publisher, Error> {
683        validate_endpoint_path(path)?;
684        self.inner.namespace.register(path, Route::Pub)?;
685        Ok(Endpoint::from_state(PubState::new(
686            path,
687            Arc::clone(&self.inner.subs),
688            self.inner.runtime.config.limits.subscriber_buffer_bytes,
689        )))
690    }
691
692    /// Registers a radio for `path`
693    /// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §4.6).
694    ///
695    /// RADIO binds and DISH connects. Nothing inbound is accepted on the
696    /// path; a dish's join is a SUBSCRIBE and lands in the radio. Every
697    /// segment goes to the dishes joined when it opens, and each copy is
698    /// dropped rather than waited for: by its successor, by the dish's
699    /// `max_age`, or by the dish's byte budget.
700    pub fn radio(&self, path: &str) -> Result<crate::Radio, Error> {
701        validate_endpoint_path(path)?;
702        let hub = Arc::new(crate::radio::RadioHub::new(
703            path,
704            self.inner.runtime.config.limits,
705        ));
706        self.inner
707            .namespace
708            .register(path, Route::Radio(Arc::clone(&hub)))?;
709        Ok(Endpoint::from_state(crate::radio::RadioState::new(
710            hub,
711            Arc::clone(&self.inner.namespace),
712        )))
713    }
714
715    /// Registers a raw L0 acceptor for `path`.
716    ///
717    /// Below the patterns: an acceptor takes both stream kinds on one path and
718    /// hands them over tagged ([`crate::Incoming`]), leaving the shape of the
719    /// conversation to the application. The path is claimed exactly like a
720    /// replier's or a puller's.
721    pub fn acceptor(&self, path: &str) -> Result<Acceptor, Error> {
722        validate_endpoint_path(path)?;
723        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
724        self.inner.namespace.register(path, Route::Raw(tx))?;
725        Ok(Acceptor::new(path, rx))
726    }
727
728    /// Serves a relay on this Listener: hidden peers register through
729    /// [`Listener::bind_relay`], and diallers reach them through
730    /// `weida+relay://` addresses ([`Relay`], `docs/PROTOCOL.md` §9.6).
731    ///
732    /// Claims [`RELAY_PATH`] on every binding of this Listener, so a second
733    /// call fails with [`Error::AlreadyRegistered`]. Each registration and
734    /// each tunnel waits at [`Relay::accept`] for the application to admit
735    /// or refuse it.
736    pub fn relay(&self) -> Result<Relay, Error> {
737        Relay::serve_on(&self.inner)
738    }
739
740    /// Registers a bound paired endpoint for `path`.
741    ///
742    /// PAIR is one connection and one peer, carrying one-way transfers in
743    /// both directions ([ARCHITECTURE.md](../../../docs/ARCHITECTURE.md)
744    /// §6b). It adds **no wire vocabulary**: a paired endpoint talks to a
745    /// bare [`crate::Peer`] or [`Acceptor`] on the same path, which is the
746    /// test that proves the pattern layer is API and nothing else.
747    ///
748    /// The one-peer rule is enforced at dispatch: the first connection to
749    /// send here claims the endpoint, and a stream from any other is refused
750    /// with `LIMIT_EXCEEDED` while **the first keeps working**.
751    pub fn pair(&self, path: &str) -> Result<Paired, Error> {
752        validate_endpoint_path(path)?;
753        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
754        let owner = Arc::new(PairOwner::new());
755        self.inner.namespace.register(
756            path,
757            Route::Pair {
758                queue: tx,
759                owner: Arc::clone(&owner),
760            },
761        )?;
762        Ok(Endpoint::from_state(PairState::bound(path, owner, rx)))
763    }
764
765    /// Registers a respondent for `path`.
766    ///
767    /// A survey question is an exchange, so a respondent's route is
768    /// **byte-for-byte a replier's**: the same request route, the same accept
769    /// queue, the same backpressure. What makes it a survey is entirely on
770    /// the asking side — the fan-out and the deadline — so this pattern adds
771    /// no routing and no wire vocabulary.
772    pub fn respondent(&self, path: &str) -> Result<Respondent, Error> {
773        validate_endpoint_path(path)?;
774        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
775        self.inner.namespace.register(path, Route::Request(tx))?;
776        Ok(Endpoint::from_state(RespondState::new(path, rx)))
777    }
778
779    /// Registers a SWARM seeder for `path`
780    /// ([decisions/0040](../../../docs/decisions/0040-swarm-pattern.md),
781    /// [decisions/0041](../../../docs/decisions/0041-swarm-sessions.md)).
782    ///
783    /// A session, and a version-1 ask, is an exchange, so the route is a
784    /// replier's, byte for byte. What a seeder adds is above it: each
785    /// session's open (or ask) is read under `Limits::header_timeout_ms` and
786    /// decoded before the application sees it, at most
787    /// [`crate::MAX_PENDING_SESSIONS`] at once, and every answer is checked
788    /// for shape before it is sent.
789    #[cfg(feature = "swarm")]
790    pub fn seeder(&self, path: &str) -> Result<crate::Seeder, Error> {
791        validate_endpoint_path(path)?;
792        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
793        self.inner.namespace.register(path, Route::Request(tx))?;
794        Ok(Endpoint::from_state(crate::swarm::SeedState::new(
795            path,
796            rx,
797            &self.inner.runtime,
798        )))
799    }
800
801    /// Registers a bus member on `path` that dials the others on `tls`'s
802    /// terms.
803    ///
804    /// The **only** factory that takes both a path and dialling terms,
805    /// because a bus member is the one role that is bound and dialling at
806    /// once ([ARCHITECTURE.md](../../../docs/ARCHITECTURE.md) §6b): it
807    /// accepts on its own path with a puller's route and reaches the others
808    /// with [`crate::BusMember::connect`].
809    pub fn bus(&self, path: &str, tls: impl Into<ClientTls>) -> Result<BusMember, Error> {
810        validate_endpoint_path(path)?;
811        let (tx, rx) = mpsc::channel(self.inner.runtime.config.endpoint_queue);
812        self.inner.namespace.register(path, Route::Transfer(tx))?;
813        Ok(Endpoint::from_state(BusState::new(
814            path,
815            Arc::clone(&self.inner.runtime),
816            Arc::new(tls.into()),
817            rx,
818            self.inner.runtime.config.endpoint_queue,
819            self.inner.runtime.config.limits.subscriber_buffer_bytes,
820        )))
821    }
822}
823
824impl std::fmt::Debug for Listener {
825    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826        f.debug_struct("Listener").finish_non_exhaustive()
827    }
828}
829
830/// A QUIC binding's endpoint as both of its closers hold it: [`Binding::close`]
831/// and [`Binding::hand_over`], and the runtime's close.
832pub(crate) struct ServedEndpoint {
833    endpoint: quinn::Endpoint,
834    /// Frees the binding's address once it closed.
835    lease: AddrLease,
836    /// Set before the endpoint is closed. `quinn` still hands out an `Incoming`
837    /// that queued before the close, and accepts it without closing the
838    /// connection that makes, so the accept loop checks this as well.
839    closed: AtomicBool,
840}
841
842impl ServedEndpoint {
843    fn new(endpoint: quinn::Endpoint, lease: AddrLease) -> ServedEndpoint {
844        ServedEndpoint {
845            endpoint,
846            lease,
847            closed: AtomicBool::new(false),
848        }
849    }
850
851    /// Closes every connection with `code` and `reason` and stops admitting:
852    /// the flag is set before `quinn`'s close takes the endpoint's lock, which
853    /// an accept takes too, so a connection inserted after the close sees it.
854    pub(crate) fn close(&self, code: VarInt, reason: &[u8]) {
855        self.closed.store(true, Ordering::Release);
856        self.endpoint.close(code, reason);
857    }
858
859    fn is_closed(&self) -> bool {
860        self.closed.load(Ordering::Acquire)
861    }
862
863    pub(crate) async fn wait_idle(&self) {
864        self.endpoint.wait_idle().await;
865    }
866
867    pub(crate) fn release(&self) {
868        self.lease.release();
869    }
870
871    /// The duplicate a handover passes on; `None` on a simulated network, or
872    /// once the binding closed.
873    fn take_handed(&self) -> Option<std::net::UdpSocket> {
874        self.lease.take_handed()
875    }
876}
877
878/// One concrete transport binding of a [`Listener`].
879pub struct Binding {
880    served: Arc<ServedEndpoint>,
881    local_addr: SocketAddr,
882    peers: Arc<PeerConns>,
883    /// The decorator under the endpoint, which `hand_over` makes hold.
884    socket: Arc<HandoverSocket>,
885    open: Arc<OpenConns>,
886    exec: Exec,
887    close_timeout: Duration,
888    /// The registration a relayed binding serves through.
889    relay: Option<Arc<RelaySocket>>,
890}
891
892impl std::fmt::Debug for Binding {
893    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
894        f.debug_struct("Binding")
895            .field("local_addr", &self.local_addr)
896            .finish_non_exhaustive()
897    }
898}
899
900impl Binding {
901    /// The address actually bound, with the port resolved.
902    pub fn local_addr(&self) -> SocketAddr {
903        self.local_addr
904    }
905
906    /// The events of a relayed binding's connection to its relay: lost,
907    /// redialled and registered again, given up. `None` for every other
908    /// binding.
909    pub fn relay_events(&self) -> Option<crate::PeerEvents> {
910        self.relay.as_ref().and_then(|socket| socket.events())
911    }
912
913    /// Stops accepting and closes this binding's connections with
914    /// `SHUTDOWN`, then waits for the socket to go idle for at most
915    /// [`RuntimeConfig::shutdown_timeout`](crate::RuntimeConfig::shutdown_timeout).
916    ///
917    /// When it returns, the binding's port is free to bind again: the OS
918    /// socket is closed, even where the application or weida still holds a
919    /// handle on one of its connections, which from then on sends and
920    /// receives nothing.
921    pub async fn close(&self) {
922        self.served
923            .close(VarInt::from_u32(codes::SHUTDOWN as u32), b"binding closed");
924        if self
925            .exec
926            .within(self.close_timeout, self.served.wait_idle())
927            .await
928            .is_none()
929        {
930            tracing::debug!(
931                timeout_ms = self.close_timeout.as_millis(),
932                "timeout reached before the binding's socket went idle"
933            );
934        }
935        self.served.release();
936    }
937
938    /// Hands this binding's socket over to a successor process, which tells
939    /// the clients to redial once it serves
940    /// ([decisions/0039](../../../docs/decisions/0039-handover-says-when.md)).
941    ///
942    /// From the call on, this process neither reads nor sends on the socket.
943    /// The successor may serve it, through [`Listener::bind_quic_socket`], as
944    /// soon as `hand_over` returns, and this process may keep its runtime as
945    /// long as it likes.
946    ///
947    /// Every connection is closed with `RESTARTING`, but the close packets
948    /// are held in the [`Handoff`] and not sent. Clients learn of the restart
949    /// only when the successor calls [`Binding::take_over`]: they see
950    /// [`LossCause::PeerRestarting`](crate::LossCause::PeerRestarting) and
951    /// redial at once, whatever their
952    /// [`stop_on_peer_closed`](crate::ReconnectPolicy::stop_on_peer_closed)
953    /// says, into a binding that already reads.
954    ///
955    /// The wait for the closes is bounded by
956    /// [`RuntimeConfig::shutdown_timeout`](crate::RuntimeConfig::shutdown_timeout),
957    /// and a connection still in its handshake is not waited for. If the
958    /// successor never calls `take_over`, or a datagram is lost, a client
959    /// notices through [`Limits::idle_timeout`] and redials on its normal
960    /// schedule.
961    ///
962    /// # Panics
963    ///
964    /// On a binding on a simulated network or a relay, which has no OS socket
965    /// to hand over, or on a binding already closed by [`Binding::close`] or
966    /// [`Runtime::shutdown`](crate::Runtime::shutdown).
967    pub async fn hand_over(self) -> Handoff {
968        let handed = self.served.take_handed().expect(
969            "Binding::hand_over needs an open OS socket; a closed binding, or one on a simulated network or a relay, has none",
970        );
971        self.socket.hold();
972        let pending: Vec<quinn::Connection> = self
973            .open
974            .snapshot()
975            .into_iter()
976            .filter(|conn| conn.close_reason().is_none())
977            .collect();
978        self.served.close(
979            VarInt::from_u32(codes::RESTARTING as u32),
980            b"server restarting",
981        );
982        // The endpoint's close reaches each connection as an event its driver
983        // applies, and the same driver poll then passes the close packet to
984        // the socket, all under the lock `closed()` takes to read the reason.
985        // A connection that was open above and is now closed has therefore
986        // handed its close to the held socket.
987        let all_held = self
988            .exec
989            .within(self.close_timeout, async {
990                for conn in &pending {
991                    conn.closed().await;
992                }
993            })
994            .await
995            .is_some();
996        if !all_held {
997            tracing::debug!(
998                timeout_ms = self.close_timeout.as_millis(),
999                "timeout reached before every close was held"
1000            );
1001        }
1002        let held = self.socket.release();
1003        tracing::info!(
1004            local_addr = %self.local_addr,
1005            connections = pending.len(),
1006            datagrams = held.len(),
1007            "binding handed over"
1008        );
1009        Handoff {
1010            socket: handed,
1011            local_addr: self.local_addr,
1012            held,
1013        }
1014    }
1015
1016    /// Sends the close packets a predecessor held in its [`Handoff`], so its
1017    /// clients redial into this binding
1018    /// ([decisions/0039](../../../docs/decisions/0039-handover-says-when.md)).
1019    ///
1020    /// `held` is the second half of [`Handoff::into_parts`]. Call this after
1021    /// the Listener's endpoints the clients use are registered: a client
1022    /// redials within one round trip, and a path not yet registered refuses
1023    /// it. Each datagram is sent once; the return value is how many were.
1024    ///
1025    /// **The bytes must reach this process over a channel as trusted as the
1026    /// one that carries the socket descriptor.** Whoever can write them makes
1027    /// this binding send up to the decoder's cap of datagrams from its port,
1028    /// to destinations of their choosing within what the decoder accepts.
1029    ///
1030    /// # Errors
1031    ///
1032    /// [`Error::Io`] of kind `InvalidData` for bytes that are not a handoff,
1033    /// and of kind `InvalidInput` for a handoff of a socket bound to another
1034    /// address than this binding's.
1035    pub async fn take_over(&self, held: &[u8]) -> Result<usize, Error> {
1036        let (from, datagrams) = handoff::decode(held)?;
1037        if from != self.local_addr {
1038            return Err(Error::Io(io::Error::new(
1039                io::ErrorKind::InvalidInput,
1040                format!(
1041                    "handoff for {from} offered to a binding on {}",
1042                    self.local_addr
1043                ),
1044            )));
1045        }
1046        let mut sent = 0;
1047        for datagram in &datagrams {
1048            match self.socket.send_raw(datagram).await {
1049                Ok(()) => sent += 1,
1050                Err(e) => tracing::debug!(
1051                    destination = %datagram.destination,
1052                    error = %e,
1053                    "handed-over datagram not sent"
1054                ),
1055            }
1056        }
1057        tracing::info!(local_addr = %self.local_addr, sent, "binding took over");
1058        Ok(sent)
1059    }
1060
1061    /// Closes every live connection this binding holds from `peer`, with
1062    /// `REJECTED` and the reason `disconnected by the application`, and
1063    /// returns how many it closed
1064    /// ([decisions/0035](../../../docs/decisions/0035-keys-proved-not-judged.md)
1065    /// §4.4).
1066    ///
1067    /// **Not a ban.** The dialler sees
1068    /// [`LossCause::PeerClosed`](crate::LossCause::PeerClosed) and redials
1069    /// under its own [`ReconnectPolicy`](crate::ReconnectPolicy); keeping a
1070    /// peer out is refusing its arrivals and joins. An anonymous client
1071    /// cannot be named, so it cannot be disconnected here.
1072    pub fn disconnect(&self, peer: Fingerprint) -> usize {
1073        self.peers.disconnect(&peer)
1074    }
1075}
1076
1077/// One in-process binding: a bus name and nothing else.
1078///
1079/// No socket, no TLS and no credentials — there is nothing to configure and
1080/// nobody to prove ([decisions/0010](../../../docs/decisions/0010-local-transport.md)
1081/// §4.1, §4.4). Dropping it unregisters the bus, after which a dial to that
1082/// name fails as a dial to a closed port does.
1083#[derive(Debug)]
1084pub struct LocalBinding {
1085    bus: String,
1086}
1087
1088impl LocalBinding {
1089    /// The bus this binding answers on.
1090    pub fn bus(&self) -> &str {
1091        &self.bus
1092    }
1093}
1094
1095impl Drop for LocalBinding {
1096    fn drop(&mut self) {
1097        inproc::unbind(&self.bus);
1098    }
1099}
1100
1101/// One `AF_UNIX` binding: the socket file, removed when this drops; or, under
1102/// `Network::sim`, the simulated path, freed when this drops.
1103#[cfg(unix)]
1104#[derive(Debug)]
1105pub struct UnixBinding {
1106    inner: UnixBound,
1107}
1108
1109#[cfg(unix)]
1110#[derive(Debug)]
1111enum UnixBound {
1112    Os(weida_runtime::BoundUnixSocket),
1113    #[cfg(feature = "test-util")]
1114    Sim(crate::sim::LocalLease),
1115}
1116
1117#[cfg(unix)]
1118impl UnixBinding {
1119    /// The socket path actually bound.
1120    pub fn path(&self) -> &std::path::Path {
1121        match &self.inner {
1122            UnixBound::Os(socket) => socket.path(),
1123            #[cfg(feature = "test-util")]
1124            UnixBound::Sim(lease) => lease.path(),
1125        }
1126    }
1127}
1128
1129/// One named-pipe binding: the pipe name, released when this drops.
1130#[cfg(windows)]
1131#[derive(Debug)]
1132pub struct PipeBinding {
1133    name: String,
1134    /// Dropping it ends the accept loop, and with it the last listening
1135    /// instance, which is what releases the name.
1136    _stop: tokio::sync::oneshot::Sender<()>,
1137}
1138
1139#[cfg(windows)]
1140impl PipeBinding {
1141    /// The pipe name bound, without the `\\.\pipe\` prefix.
1142    pub fn name(&self) -> &str {
1143        &self.name
1144    }
1145}
1146
1147/// How long a local accept loop waits after a failed `accept` before it asks
1148/// again. Descriptor or memory exhaustion passes, and a loop that spun on it
1149/// would only make it worse.
1150#[cfg(any(unix, windows))]
1151const ACCEPT_RETRY: Duration = Duration::from_millis(100);
1152
1153/// What one accepted local connection is served with.
1154#[cfg(any(unix, windows))]
1155struct LocalAccept<S: crate::grouped::Stream> {
1156    groups: Arc<crate::grouped::Groups<S>>,
1157    /// The barrier the groups' closing links wait on: every connection this
1158    /// binding accepts holds a ticket of it until it is admitted.
1159    barrier: Arc<crate::grouped::AcceptBarrier>,
1160    namespace: Arc<Namespace>,
1161    subs: Arc<SubRegistry>,
1162    limits: Limits,
1163    exec: Exec,
1164    guarantees: GuaranteeSet,
1165    shared: Arc<Shared>,
1166    /// Which `Link` variant a peer over this stream is.
1167    link: fn(crate::grouped::Grouped<S>) -> Link,
1168    /// The places `RuntimeConfig::max_connections` hands out: one per live
1169    /// local connection, taken before it is accepted and kept for as long as
1170    /// it lives (a control connection for the life of its peer, a transfer or
1171    /// parked connection until its last half is gone). What a hostile or buggy
1172    /// local process can make a binding hold is this count, not the
1173    /// descriptor limit of the whole process.
1174    admitted: Arc<Semaphore>,
1175    /// How many closed connections may wait, as a task of their own, for a
1176    /// queue to take the notice that their consumer is gone ([`depart`]).
1177    departing: Arc<Semaphore>,
1178    /// One record a second for everything an accept loop turns away or trips
1179    /// over, so a flood is not a flood of log lines.
1180    refusals: Arc<LogThrottle>,
1181}
1182
1183#[cfg(any(unix, windows))]
1184impl<S: crate::grouped::Stream> LocalAccept<S> {
1185    fn clone_for(&self) -> LocalAccept<S> {
1186        LocalAccept {
1187            groups: Arc::clone(&self.groups),
1188            barrier: Arc::clone(&self.barrier),
1189            namespace: Arc::clone(&self.namespace),
1190            subs: Arc::clone(&self.subs),
1191            limits: self.limits,
1192            exec: self.exec.clone(),
1193            guarantees: self.guarantees,
1194            shared: Arc::clone(&self.shared),
1195            link: self.link,
1196            admitted: Arc::clone(&self.admitted),
1197            departing: Arc::clone(&self.departing),
1198            refusals: Arc::clone(&self.refusals),
1199        }
1200    }
1201
1202    /// Hands one accepted connection to a task of its own, numbered for the
1203    /// barrier before the accept loop takes the next one.
1204    fn spawn(&self, stream: S, place: OwnedSemaphorePermit) {
1205        let ticket = self.barrier.ticket();
1206        self.exec
1207            .spawn(self.clone_for().serve(stream, place, ticket));
1208    }
1209
1210    /// Serves one accepted connection: a control connection becomes a
1211    /// peer, a transfer or reverse connection joins the peer its token
1212    /// names ([decisions/0012](../../../docs/decisions/0012-local-connection-grouping.md)
1213    /// §4.1, §4.2, §4.4). `ticket` is held until the connection is admitted
1214    /// or turned away.
1215    async fn serve(self, stream: S, place: OwnedSemaphorePermit, ticket: crate::grouped::Ticket) {
1216        use crate::grouped::{
1217            Accepted, accept_control, admit_reverse, admit_transfer, read_accepted,
1218        };
1219        // The preamble is the peer's to send, and a socket that never sends
1220        // one would hold a place and a descriptor for ever.
1221        let deadline = Duration::from_millis(self.limits.hello_timeout_ms);
1222        let accepted = match self.exec.within(deadline, read_accepted(stream)).await {
1223            Some(Ok(accepted)) => accepted,
1224            Some(Err(e)) => {
1225                tracing::debug!(error = %e, "local connection preamble rejected");
1226                return;
1227            }
1228            None => {
1229                tracing::debug!("local connection sent no preamble in time");
1230                return;
1231            }
1232        };
1233        match accepted {
1234            Accepted::Control(stream, principal) => {
1235                // Not a transfer anyone's link waits for.
1236                drop(ticket);
1237                // A control connection is a peer, and keeps its place until
1238                // its link closes; the group holds it, so a peer that went
1239                // can spend it on the connections it sent before it went.
1240                let link = match accept_control(
1241                    stream,
1242                    principal,
1243                    Arc::clone(&self.groups),
1244                    self.limits.max_local_streams,
1245                    self.limits.max_parked_reverse,
1246                    self.exec.clone(),
1247                    Some(place),
1248                )
1249                .await
1250                {
1251                    Ok(link) => link,
1252                    Err(e) => {
1253                        tracing::debug!(error = %e, "local control connection failed");
1254                        return;
1255                    }
1256                };
1257                let ctx = ConnCtx::spawn(
1258                    (self.link)(link),
1259                    self.limits,
1260                    self.namespace,
1261                    Some(Arc::clone(&self.subs)),
1262                    self.exec,
1263                    self.guarantees,
1264                    self.shared,
1265                );
1266                let conn_id = ctx.conn.stable_id();
1267                let reason = ctx.conn.closed().await;
1268                self.subs.remove_connection(conn_id);
1269                let departure = crate::conn::take_departure(&ctx);
1270                tracing::debug!(%reason, "local connection closed");
1271                depart(departure, &self.departing, move || drop(ctx)).await;
1272            }
1273            Accepted::Transfer(token, stream, principal) => {
1274                // The connection keeps its place until both of its halves are
1275                // gone. The token names the group and the kernel says who is
1276                // asking; an unbound connection is dispatched nowhere
1277                // [0012 §4.2].
1278                if !admit_transfer(&self.groups, &token, &principal, stream, place)
1279                    && let Some(held_back) = self.refusals.pass()
1280                {
1281                    tracing::warn!(
1282                        held_back,
1283                        "local transfer connection refused: unknown or mismatched group"
1284                    );
1285                }
1286            }
1287            Accepted::Reverse(token, stream, principal) => {
1288                // A connection parked for fan-out, under the same admission
1289                // rule and the two bounds of [0012 §4.4]; it keeps its place
1290                // while it is parked.
1291                if !admit_reverse(&self.groups, &token, &principal, stream, place) {
1292                    tracing::debug!(
1293                        "local reverse connection not parked: unknown group or pool full"
1294                    );
1295                }
1296            }
1297        }
1298    }
1299}
1300
1301/// Accepts `AF_UNIX` connections and serves each one.
1302///
1303/// A place is taken before the next connection is accepted. Past
1304/// `max_connections` live connections the surplus waits in the kernel's queue,
1305/// and a dialler's `connect` fails visibly once that is full, instead of the
1306/// connection being accepted and closed with its payload already written: a
1307/// sender that outruns a slow consumer loses nothing.
1308///
1309/// A barrier request ([`crate::grouped::AcceptBarrier`]) is answered after
1310/// the queue is empty: every connection a dialler's `connect` already
1311/// returned for is accepted and numbered first.
1312#[cfg(unix)]
1313async fn accept_unix(
1314    listener: tokio::net::UnixListener,
1315    mut requests: crate::grouped::BarrierRequests,
1316    serve: LocalAccept<crate::unix::UnixLocal>,
1317) {
1318    loop {
1319        tokio::select! {
1320            Some(request) = requests.recv() => drain_unix_queue(&listener, &serve, request, None),
1321            place = Arc::clone(&serve.admitted).acquire_owned() => {
1322                // The semaphore is never closed, so this only fails if it were.
1323                let Ok(place) = place else { return };
1324                tokio::select! {
1325                    accepted = listener.accept() => match accepted {
1326                        Ok((stream, _)) => take_unix(&serve, stream, place),
1327                        Err(e) => {
1328                            // Descriptor or memory exhaustion passes, and a
1329                            // socket that died before it was accepted concerns
1330                            // nobody but its peer: neither ends the binding,
1331                            // which would stay dead after the cause was gone.
1332                            if let Some(held_back) = serve.refusals.pass() {
1333                                tracing::warn!(error = %e, held_back, "accepting a unix connection failed; retrying");
1334                            }
1335                            serve.exec.sleep(ACCEPT_RETRY).await;
1336                        }
1337                    },
1338                    Some(request) = requests.recv() => {
1339                        drain_unix_queue(&listener, &serve, request, Some(place));
1340                    }
1341                }
1342            }
1343        }
1344    }
1345}
1346
1347/// Answers a barrier request: accepts every connection waiting in the
1348/// kernel's queue now, with the place the loop held, the one the request
1349/// brought and any free one ([`crate::grouped::AcceptBarrier`]), and stops
1350/// once the queue is empty or no place is left.
1351///
1352/// The queue is asked with `accept(2)` itself, not through the reactor:
1353/// the reactor's readiness can lag the queue, which is the very lag the
1354/// barrier exists for, and an empty answer from it would not mean an empty
1355/// queue.
1356#[cfg(unix)]
1357fn drain_unix_queue(
1358    listener: &tokio::net::UnixListener,
1359    serve: &LocalAccept<crate::unix::UnixLocal>,
1360    mut request: crate::grouped::BarrierRequest,
1361    mut held: Option<OwnedSemaphorePermit>,
1362) {
1363    use std::os::fd::AsFd;
1364    // The same listening socket, non-blocking like the original: an empty
1365    // queue answers `WouldBlock`.
1366    let queue = match listener.as_fd().try_clone_to_owned() {
1367        Ok(fd) => Some(std::os::unix::net::UnixListener::from(fd)),
1368        Err(e) => {
1369            tracing::debug!(error = %e, "the unix accept queue could not be read");
1370            None
1371        }
1372    };
1373    if let Some(queue) = queue {
1374        while let Some(place) = held.take().or_else(|| request.next_place(&serve.admitted)) {
1375            let stream = queue.accept().and_then(|(stream, _)| {
1376                stream.set_nonblocking(true)?;
1377                let _guard = serve.exec.enter();
1378                tokio::net::UnixStream::from_std(stream)
1379            });
1380            match stream {
1381                Ok(stream) => take_unix(serve, stream, place),
1382                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
1383                Err(e) => {
1384                    tracing::debug!(error = %e, "accepting a queued unix connection failed");
1385                    break;
1386                }
1387            }
1388        }
1389    }
1390    let _ = request.answer.send(serve.barrier.last());
1391}
1392
1393/// Serves one accepted unix connection under the drain rule.
1394#[cfg(unix)]
1395fn take_unix(
1396    serve: &LocalAccept<crate::unix::UnixLocal>,
1397    stream: tokio::net::UnixStream,
1398    place: OwnedSemaphorePermit,
1399) {
1400    if serve.shared.drain.is_draining() {
1401        // Admission stopped: the same rule as on every other binding
1402        // (`docs/decisions/0009-drain.md` §4.5).
1403        return;
1404    }
1405    // The accepted socket carries the runtime its halves write their
1406    // end-of-payload marker on, exactly as a pipe instance does.
1407    serve.spawn(
1408        crate::unix::UnixLocal::accepted(stream, serve.exec.clone()),
1409        place,
1410    );
1411}
1412
1413/// [`accept_unix`] for a binding on a simulated network: the same place
1414/// before each accept, the same drain rule and the same barrier, over the
1415/// connections the `SimNet` hands this path, whose channel is the queue.
1416/// Ends once the binding is dropped and no dial is still on its way in.
1417#[cfg(all(unix, feature = "test-util"))]
1418async fn accept_sim_unix(
1419    mut incoming: tokio::sync::mpsc::Receiver<tokio::io::DuplexStream>,
1420    mut requests: crate::grouped::BarrierRequests,
1421    serve: LocalAccept<crate::unix::UnixLocal>,
1422) {
1423    let take = |stream, place| {
1424        if !serve.shared.drain.is_draining() {
1425            serve.spawn(
1426                crate::unix::UnixLocal::accepted_sim(stream, serve.exec.clone()),
1427                place,
1428            );
1429        }
1430    };
1431    let drain = |incoming: &mut tokio::sync::mpsc::Receiver<tokio::io::DuplexStream>,
1432                 mut request: crate::grouped::BarrierRequest,
1433                 mut held: Option<OwnedSemaphorePermit>| {
1434        while let Some(place) = held.take().or_else(|| request.next_place(&serve.admitted)) {
1435            match incoming.try_recv() {
1436                Ok(stream) => take(stream, place),
1437                Err(_) => break,
1438            }
1439        }
1440        let _ = request.answer.send(serve.barrier.last());
1441    };
1442    loop {
1443        tokio::select! {
1444            Some(request) = requests.recv() => drain(&mut incoming, request, None),
1445            place = Arc::clone(&serve.admitted).acquire_owned() => {
1446                // The semaphore is never closed, so this only fails if it were.
1447                let Ok(place) = place else { return };
1448                tokio::select! {
1449                    stream = incoming.recv() => {
1450                        let Some(stream) = stream else { return };
1451                        take(stream, place);
1452                    }
1453                    Some(request) = requests.recv() => drain(&mut incoming, request, Some(place)),
1454                }
1455            }
1456        }
1457    }
1458}
1459
1460/// Pipe instances a binding keeps listening at once, each holding a place.
1461///
1462/// A pipe instance is one connection, and a client that finds none
1463/// listening retries on the timer, which Windows rounds to its 15.6 ms tick:
1464/// with one listening instance every waiting client wakes on the same tick
1465/// and one of them gets in, about 64 connections a second however many
1466/// wait. Every listening instance is one more client per tick. libuv keeps
1467/// four; weida opens a connection per transfer, so it keeps more.
1468#[cfg(windows)]
1469const PIPE_LISTENING: usize = 16;
1470
1471/// One pipe instance waiting for a client, with the place it holds. The
1472/// server is shared with the pending connect, so a barrier can ask the
1473/// instance itself whether a client is on it.
1474#[cfg(windows)]
1475struct PipeListening {
1476    server: Arc<tokio::net::windows::named_pipe::NamedPipeServer>,
1477    connect: std::pin::Pin<Box<dyn Future<Output = (OwnedSemaphorePermit, io::Result<()>)> + Send>>,
1478}
1479
1480/// What a completed listen hands on: the instance, its place, how the
1481/// connect ended.
1482#[cfg(windows)]
1483type PipeAccepted = (
1484    tokio::net::windows::named_pipe::NamedPipeServer,
1485    OwnedSemaphorePermit,
1486    io::Result<()>,
1487);
1488
1489#[cfg(windows)]
1490fn pipe_listen(
1491    server: tokio::net::windows::named_pipe::NamedPipeServer,
1492    place: OwnedSemaphorePermit,
1493) -> PipeListening {
1494    let server = Arc::new(server);
1495    let connecting = Arc::clone(&server);
1496    PipeListening {
1497        server,
1498        connect: Box::pin(async move {
1499            let connected = connecting.connect().await;
1500            (place, connected)
1501        }),
1502    }
1503}
1504
1505#[cfg(windows)]
1506impl PipeListening {
1507    /// The instance and its place once `connect` resolved to `out`: the
1508    /// connect future has let go of its share of the server by then.
1509    fn accepted(self, out: (OwnedSemaphorePermit, io::Result<()>)) -> Option<PipeAccepted> {
1510        let PipeListening { server, connect } = self;
1511        drop(connect);
1512        let (place, connected) = out;
1513        Arc::try_unwrap(server)
1514            .ok()
1515            .map(|server| (server, place, connected))
1516    }
1517}
1518
1519/// The first of `listening` a client connected to, taken out of the set.
1520/// Never resolves while the set is empty.
1521#[cfg(windows)]
1522async fn pipe_connected(listening: &mut Vec<PipeListening>) -> Option<PipeAccepted> {
1523    std::future::poll_fn(|cx| {
1524        for i in 0..listening.len() {
1525            if let std::task::Poll::Ready(out) = listening[i].connect.as_mut().poll(cx) {
1526                return std::task::Poll::Ready(listening.swap_remove(i).accepted(out));
1527            }
1528        }
1529        std::task::Poll::Pending
1530    })
1531    .await
1532}
1533
1534/// Accepts named-pipe connections and serves each one.
1535///
1536/// Up to [`PIPE_LISTENING`] instances listen at once, and each takes a place
1537/// before it listens, for the reason `accept_unix` gives: the surplus waits
1538/// on the pipe, which a client sees as busy, instead of being accepted and
1539/// dropped. One more instance, `spare`, exists whenever none listens, so
1540/// that the pipe never has no instance at all: a client that finds every
1541/// instance taken sees the pipe busy rather than absent, and absent reads
1542/// as the peer gone (`docs/research/ipc.md` §3.1). A client may connect to
1543/// the spare before it holds a place; it is accepted with the next place.
1544///
1545/// A barrier request ([`crate::grouped::AcceptBarrier`]) is answered once
1546/// every instance a client is on has been taken, the spare included. The
1547/// instance itself is asked (`GetNamedPipeClientProcessId` answers only with
1548/// a client on it), not the completion of its connect, which the reactor may
1549/// not have seen yet: a client's `CreateFile` returns only once it holds an
1550/// instance, so those are all the connections a dialler can have written to.
1551#[cfg(windows)]
1552async fn accept_pipe(
1553    binding: weida_runtime::BoundPipe,
1554    first: tokio::net::windows::named_pipe::NamedPipeServer,
1555    mut stop: tokio::sync::oneshot::Receiver<()>,
1556    mut requests: crate::grouped::BarrierRequests,
1557    serve: LocalAccept<crate::pipe::PipeStream>,
1558) {
1559    let mut spare = Some(first);
1560    let mut listening: Vec<PipeListening> = Vec::with_capacity(PIPE_LISTENING);
1561    loop {
1562        // The pipe always has an instance: made before the last listening
1563        // one is served, and a failure to make it is waited out.
1564        while spare.is_none() && listening.is_empty() {
1565            match binding.next_instance() {
1566                Ok(next) => spare = Some(next),
1567                Err(e) => {
1568                    if let Some(held_back) = serve.refusals.pass() {
1569                        tracing::warn!(error = %e, held_back, "pipe instance not created; retrying");
1570                    }
1571                    tokio::select! {
1572                        () = serve.exec.sleep(ACCEPT_RETRY) => {}
1573                        _ = &mut stop => return,
1574                    }
1575                }
1576            }
1577        }
1578        tokio::select! {
1579            Some(request) = requests.recv() => {
1580                drain_pipe_instances(&binding, &mut spare, &mut listening, &serve, request).await;
1581            }
1582            place = Arc::clone(&serve.admitted).acquire_owned(),
1583                if listening.len() < PIPE_LISTENING =>
1584            {
1585                // The semaphore is never closed, so this only fails if it were.
1586                let Ok(place) = place else { return };
1587                let server = match spare.take() {
1588                    Some(spare) => spare,
1589                    None => match binding.next_instance() {
1590                        Ok(next) => next,
1591                        Err(e) => {
1592                            if let Some(held_back) = serve.refusals.pass() {
1593                                tracing::warn!(error = %e, held_back, "pipe instance not created; retrying");
1594                            }
1595                            tokio::select! {
1596                                () = serve.exec.sleep(ACCEPT_RETRY) => {}
1597                                _ = &mut stop => return,
1598                            }
1599                            continue;
1600                        }
1601                    },
1602                };
1603                listening.push(pipe_listen(server, place));
1604            }
1605            accepted = pipe_connected(&mut listening), if !listening.is_empty() => {
1606                let Some((accepted, place, connected)) = accepted else { continue };
1607                if let Err(e) = connected {
1608                    // A failed connect leaves this instance in no state to be
1609                    // trusted: it is dropped with its place, and the place is
1610                    // taken again for a fresh instance after a pause.
1611                    if let Some(held_back) = serve.refusals.pass() {
1612                        tracing::warn!(error = %e, held_back, "pipe accept failed; retrying");
1613                    }
1614                    drop((accepted, place));
1615                    tokio::select! {
1616                        () = serve.exec.sleep(ACCEPT_RETRY) => {}
1617                        _ = &mut stop => return,
1618                    }
1619                    continue;
1620                }
1621                if listening.is_empty() && spare.is_none() {
1622                    // Before the accepted instance is served, for the rule
1623                    // above; a failure here is retried at the top of the loop.
1624                    spare = binding.next_instance().ok();
1625                }
1626                if serve.shared.drain.is_draining() {
1627                    // Admission stopped: the accepted instance is dropped,
1628                    // which disconnects the client.
1629                    continue;
1630                }
1631                serve.spawn(
1632                    crate::pipe::PipeStream::accepted(accepted, serve.exec.clone()),
1633                    place,
1634                );
1635            }
1636            _ = &mut stop => {
1637                tracing::debug!("pipe binding dropped; accept loop ending");
1638                return;
1639            }
1640        }
1641    }
1642}
1643
1644/// Answers a barrier request on a pipe binding: takes every instance a
1645/// client is on now, the spare with the place the request brought or a
1646/// free one, each listening one once its connect completes (which it does,
1647/// because the client is there), and leaves the rest listening. Keeps the
1648/// rule that the pipe always has an instance.
1649#[cfg(windows)]
1650async fn drain_pipe_instances(
1651    binding: &weida_runtime::BoundPipe,
1652    spare: &mut Option<tokio::net::windows::named_pipe::NamedPipeServer>,
1653    listening: &mut Vec<PipeListening>,
1654    serve: &LocalAccept<crate::pipe::PipeStream>,
1655    mut request: crate::grouped::BarrierRequest,
1656) {
1657    let has_client = |server: &tokio::net::windows::named_pipe::NamedPipeServer| {
1658        weida_runtime::client_principal(server).is_ok()
1659    };
1660    if spare.as_ref().is_some_and(has_client)
1661        && let Some(place) = request.next_place(&serve.admitted)
1662        && let Some(server) = spare.take()
1663    {
1664        listening.push(pipe_listen(server, place));
1665    }
1666    let mut ready = Vec::new();
1667    let mut i = 0;
1668    while i < listening.len() {
1669        if !has_client(listening[i].server.as_ref()) {
1670            i += 1;
1671            continue;
1672        }
1673        let mut taken = listening.swap_remove(i);
1674        let out = taken.connect.as_mut().await;
1675        ready.extend(taken.accepted(out));
1676    }
1677    if listening.is_empty() && spare.is_none() {
1678        *spare = binding.next_instance().ok();
1679    }
1680    for (accepted, place, connected) in ready {
1681        if let Err(e) = connected {
1682            tracing::debug!(error = %e, "a connected pipe instance failed");
1683            continue;
1684        }
1685        if serve.shared.drain.is_draining() {
1686            continue;
1687        }
1688        serve.spawn(
1689            crate::pipe::PipeStream::accepted(accepted, serve.exec.clone()),
1690            place,
1691        );
1692    }
1693    let _ = request.answer.send(serve.barrier.last());
1694}
1695
1696/// Accepts in-process connections until the bus is unbound.
1697async fn accept_local(
1698    mut incoming: mpsc::UnboundedReceiver<inproc::LocalConn>,
1699    namespace: Arc<Namespace>,
1700    subs: Arc<SubRegistry>,
1701    limits: Limits,
1702    exec: Exec,
1703    guarantees: GuaranteeSet,
1704    shared: Arc<Shared>,
1705) {
1706    while let Some(conn) = incoming.recv().await {
1707        if shared.drain.is_draining() {
1708            // Admission stopped: the same rule as on a QUIC binding
1709            // (`docs/decisions/0009-drain.md` §4.5).
1710            conn.close(codes::SHUTDOWN, "runtime draining");
1711            continue;
1712        }
1713        let namespace = Arc::clone(&namespace);
1714        let subs = Arc::clone(&subs);
1715        let exec_for_conn = exec.clone();
1716        let shared = Arc::clone(&shared);
1717        exec.spawn(async move {
1718            let ctx = ConnCtx::spawn(
1719                Link::Local(conn),
1720                limits,
1721                namespace,
1722                Some(Arc::clone(&subs)),
1723                exec_for_conn,
1724                guarantees,
1725                shared,
1726            );
1727            let conn_id = ctx.conn.stable_id();
1728            let reason = ctx.conn.closed().await;
1729            subs.remove_connection(conn_id);
1730            let departure = crate::conn::take_departure(&ctx);
1731            tracing::debug!(%reason, "local connection closed");
1732            drop(ctx);
1733            departure.announce().await;
1734        });
1735    }
1736}
1737
1738/// Live connections per proved peer identity, for `max_connections_per_peer`
1739/// and [`Binding::disconnect`].
1740///
1741/// Keyed by the fingerprint a peer proved in the handshake, because that is
1742/// the only thing that binds two connections into one peer
1743/// (`docs/decisions/0008-session-identity.md` §4.2). A connection that proved
1744/// nothing is not counted here at all: two anonymous connections cannot be
1745/// shown to be one peer, so counting them together would refuse strangers for
1746/// each other's traffic. They remain bounded by `max_connections`.
1747///
1748/// The table holds the connection handles rather than a count, so a binding
1749/// can close one peer's connections; it is bounded by `max_connections`, as
1750/// the count was.
1751#[derive(Default)]
1752struct PeerConns(std::sync::Mutex<HashMap<Fingerprint, Vec<quinn::Connection>>>);
1753
1754impl PeerConns {
1755    /// Records one more connection for `peer` and reports whether it fits.
1756    ///
1757    /// The entry is taken before the connection is served and released when
1758    /// it closes, so what is bounded is *live* connections rather than dials
1759    /// over time.
1760    fn admit(&self, peer: Option<Fingerprint>, conn: &quinn::Connection, max: usize) -> bool {
1761        let Some(peer) = peer else {
1762            return true;
1763        };
1764        let mut conns = self.0.lock().expect("peer table poisoned");
1765        let held = conns.entry(peer).or_default();
1766        if held.len() >= max {
1767            return false;
1768        }
1769        held.push(conn.clone());
1770        true
1771    }
1772
1773    fn release(&self, peer: Option<Fingerprint>, conn_id: usize) {
1774        let Some(peer) = peer else {
1775            return;
1776        };
1777        let mut conns = self.0.lock().expect("peer table poisoned");
1778        if let Some(held) = conns.get_mut(&peer) {
1779            held.retain(|c| c.stable_id() != conn_id);
1780            // The table is keyed by remote input, so an entry that holds
1781            // nothing is removed rather than left behind.
1782            if held.is_empty() {
1783                conns.remove(&peer);
1784            }
1785        }
1786    }
1787
1788    /// Closes every live connection of `peer`; entries leave through
1789    /// [`PeerConns::release`] as each accept task sees its connection close.
1790    fn disconnect(&self, peer: &Fingerprint) -> usize {
1791        let held = self
1792            .0
1793            .lock()
1794            .expect("peer table poisoned")
1795            .get(peer)
1796            .cloned()
1797            .unwrap_or_default();
1798        for conn in &held {
1799            conn.close(
1800                VarInt::from_u32(codes::REJECTED as u32),
1801                b"disconnected by the application",
1802            );
1803        }
1804        held.len()
1805    }
1806}
1807
1808impl std::fmt::Debug for PeerConns {
1809    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1810        let peers = self.0.lock().map_or(0, |conns| conns.len());
1811        f.debug_struct("PeerConns").field("peers", &peers).finish()
1812    }
1813}
1814
1815/// Every handshaken connection of a binding, anonymous ones included, so
1816/// [`Binding::hand_over`] can wait for each one's close.
1817///
1818/// [`PeerConns`] cannot serve here: it holds proved peers only. Keyed by
1819/// `stable_id()` and bounded by `max_connections`.
1820#[derive(Default)]
1821struct OpenConns(std::sync::Mutex<HashMap<usize, quinn::Connection>>);
1822
1823impl OpenConns {
1824    fn insert(&self, conn: &quinn::Connection) {
1825        self.0
1826            .lock()
1827            .expect("open connections poisoned")
1828            .insert(conn.stable_id(), conn.clone());
1829    }
1830
1831    fn remove(&self, conn_id: usize) {
1832        self.0
1833            .lock()
1834            .expect("open connections poisoned")
1835            .remove(&conn_id);
1836    }
1837
1838    fn snapshot(&self) -> Vec<quinn::Connection> {
1839        self.0
1840            .lock()
1841            .expect("open connections poisoned")
1842            .values()
1843            .cloned()
1844            .collect()
1845    }
1846}
1847
1848/// How often a refusal is let through to the log.
1849const REFUSAL_LOG_INTERVAL: Duration = Duration::from_secs(1);
1850
1851/// Lets one log record through per interval and counts the ones it held back,
1852/// so a flood of refusals is one line a second and not one per packet.
1853struct LogThrottle {
1854    every: Duration,
1855    state: Mutex<ThrottleState>,
1856}
1857
1858struct ThrottleState {
1859    next: Option<Instant>,
1860    held_back: u64,
1861}
1862
1863impl LogThrottle {
1864    fn new(every: Duration) -> LogThrottle {
1865        LogThrottle {
1866            every,
1867            state: Mutex::new(ThrottleState {
1868                next: None,
1869                held_back: 0,
1870            }),
1871        }
1872    }
1873
1874    /// `Some(n)` when the caller should log now, `n` being how many records
1875    /// were held back since the last one that passed.
1876    fn pass(&self) -> Option<u64> {
1877        self.pass_at(Instant::now())
1878    }
1879
1880    fn pass_at(&self, now: Instant) -> Option<u64> {
1881        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
1882        match state.next {
1883            Some(next) if now < next => {
1884                state.held_back += 1;
1885                None
1886            }
1887            _ => {
1888                state.next = Some(now + self.every);
1889                Some(std::mem::take(&mut state.held_back))
1890            }
1891        }
1892    }
1893}
1894
1895/// One unit of a shared count, given back when this drops, however the task
1896/// that holds it ends.
1897struct Counted(Arc<AtomicUsize>);
1898
1899impl Counted {
1900    fn take(counter: &Arc<AtomicUsize>) -> Counted {
1901        counter.fetch_add(1, Ordering::Relaxed);
1902        Counted(Arc::clone(counter))
1903    }
1904}
1905
1906impl Drop for Counted {
1907    fn drop(&mut self) {
1908        self.0.fetch_sub(1, Ordering::Relaxed);
1909    }
1910}
1911
1912/// Tells the queues a closed connection consumed on that it is gone, and runs
1913/// `release`, which gives back everything that counted the connection.
1914///
1915/// A queue that is full and unread makes the telling wait for as long as its
1916/// application likes. A connection that waited holding everything it is
1917/// counted against would stay in every table that limits live ones: its share
1918/// of `max_connections`, its peer's share of `max_connections_per_peer`, a
1919/// local place. So `release` runs first, and what waits is a [`Departure`],
1920/// which holds the queues and an id and nothing of the connection.
1921///
1922/// `departing` bounds how many of those waits there are, to `max_connections`.
1923/// Past it the connection keeps what counts it until its queues have taken
1924/// the notice, which bounds the tasks at twice what the binding admits and
1925/// still loses no notice: a queue owes something for what it handed that
1926/// consumer, and has to be told.
1927async fn depart(
1928    departure: crate::conn::Departure,
1929    departing: &Arc<Semaphore>,
1930    release: impl FnOnce() + Send,
1931) {
1932    if departure.is_empty() {
1933        release();
1934        return;
1935    }
1936    match Arc::clone(departing).try_acquire_owned() {
1937        Ok(_wait) => {
1938            release();
1939            departure.announce().await;
1940        }
1941        Err(_) => {
1942            departure.announce().await;
1943            release();
1944        }
1945    }
1946}
1947
1948/// Accepts connections until the endpoint is closed.
1949///
1950/// Everything it needs is already on the listener it serves: the namespace to
1951/// route into, the subscription registry, and the runtime whose configuration
1952/// decides the limits and whose executor runs the connections. Holding the
1953/// listener for as long as a binding accepts is the honest lifetime — a
1954/// binding without its namespace serves nothing.
1955///
1956/// **What an Initial costs is decided before it is accepted.** Accepting one
1957/// builds the connection's state and runs the server half of the TLS
1958/// handshake for a source that has not proved the address it wrote, so every
1959/// refusal below is made on the `Incoming` itself and builds nothing: a
1960/// binding at `max_connections` or `max_handshakes` refuses
1961/// (`CONNECTION_REFUSED`), and above `retry_above_handshakes` an Initial from
1962/// an unvalidated address is answered with a stateless Retry, so a flood from
1963/// spoofed sources allocates nothing and a real dialler pays one round trip.
1964async fn accept_connections(
1965    served: Arc<ServedEndpoint>,
1966    listener: Arc<ListenerInner>,
1967    peers: Arc<PeerConns>,
1968    open: Arc<OpenConns>,
1969) {
1970    let config = &listener.runtime.config;
1971    let limits = config.limits;
1972    let max_connections = config.max_connections;
1973    let max_connections_per_peer = config.max_connections_per_peer;
1974    let max_handshakes = config.max_handshakes;
1975    let retry_above = config.retry_above_handshakes;
1976    let guarantees = config.guarantees;
1977    let exec = listener.runtime.exec.clone();
1978    let shared = listener.runtime.shared();
1979    let namespace = Arc::clone(&listener.namespace);
1980    let subs = Arc::clone(&listener.subs);
1981    let live = Arc::new(AtomicUsize::new(0));
1982    let handshaking = Arc::new(AtomicUsize::new(0));
1983    let refusals = Arc::new(LogThrottle::new(REFUSAL_LOG_INTERVAL));
1984    let departing = Arc::new(Semaphore::new(
1985        max_connections.clamp(1, Semaphore::MAX_PERMITS),
1986    ));
1987    while let Some(incoming) = served.endpoint.accept().await {
1988        // A draining runtime or a closed binding admits nothing new: the
1989        // handshake is refused outright rather than accepted and then closed
1990        // (`docs/decisions/0009-drain.md` §4.5).
1991        if shared.drain.is_draining() || served.is_closed() {
1992            incoming.refuse();
1993            continue;
1994        }
1995        if live.load(Ordering::Relaxed) >= max_connections {
1996            if let Some(held_back) = refusals.pass() {
1997                tracing::warn!(
1998                    max = max_connections,
1999                    held_back,
2000                    "connection limit reached; refusing"
2001                );
2002            }
2003            incoming.refuse();
2004            continue;
2005        }
2006        let in_progress = handshaking.load(Ordering::Relaxed);
2007        if in_progress >= max_handshakes {
2008            if let Some(held_back) = refusals.pass() {
2009                tracing::warn!(
2010                    max = max_handshakes,
2011                    held_back,
2012                    "handshake limit reached; refusing"
2013                );
2014            }
2015            incoming.refuse();
2016            continue;
2017        }
2018        if in_progress >= retry_above && !incoming.remote_address_validated() {
2019            // An address that has not been validated may always be asked to
2020            // prove itself, so the Retry cannot be refused; an Initial handed
2021            // back anyway is turned away rather than accepted unvalidated.
2022            if let Err(unretried) = incoming.retry() {
2023                unretried.into_incoming().refuse();
2024            }
2025            continue;
2026        }
2027
2028        let namespace = Arc::clone(&namespace);
2029        let subs = Arc::clone(&subs);
2030        let live = Counted::take(&live);
2031        let handshake = Counted::take(&handshaking);
2032        let exec_for_conn = exec.clone();
2033        let shared = Arc::clone(&shared);
2034        let peers = Arc::clone(&peers);
2035        let open = Arc::clone(&open);
2036        let refusals = Arc::clone(&refusals);
2037        let departing = Arc::clone(&departing);
2038        let served = Arc::clone(&served);
2039        exec.spawn(async move {
2040            let connecting = match incoming.accept() {
2041                Ok(connecting) => connecting,
2042                Err(e) => {
2043                    tracing::debug!(error = %e, "handshake failed");
2044                    return; // `handshake` and `live` drop with the task
2045                }
2046            };
2047            // An `Incoming` taken before the close is accepted after it without
2048            // the close reaching the connection; dropping the handshake closes it.
2049            if served.is_closed() {
2050                tracing::debug!("binding closed during the handshake; connection dropped");
2051                return;
2052            }
2053            let connected = connecting.await;
2054            drop(handshake);
2055            match connected {
2056                Ok(conn) => {
2057                    open.insert(&conn);
2058                    let remote = conn.remote_address();
2059                    // `quinn`'s own id: it keys the two tables below, which
2060                    // hold a handle on the connection and so keep the id from
2061                    // being handed out again. Everything that outlives the
2062                    // connection keys on the link's serial instead.
2063                    let quic_id = conn.stable_id();
2064                    // The per-peer ceiling can only be applied here: the
2065                    // identity exists once the handshake is complete, and one
2066                    // peer now holds one connection per endpoint path it
2067                    // dials, so the path count it chooses would otherwise be
2068                    // the only bound
2069                    // (`docs/decisions/0002-control-and-bulk-separation.md` §7).
2070                    let peer = crate::tls::peer_fingerprint(&conn);
2071                    if !peers.admit(peer, &conn, max_connections_per_peer) {
2072                        if let Some(held_back) = refusals.pass() {
2073                            tracing::warn!(
2074                                %remote,
2075                                max = max_connections_per_peer,
2076                                held_back,
2077                                "per-peer connection limit reached; refusing"
2078                            );
2079                        }
2080                        conn.close(
2081                            VarInt::from_u32(codes::LIMIT_EXCEEDED as u32),
2082                            b"per-peer connection limit reached",
2083                        );
2084                        open.remove(quic_id);
2085                    } else {
2086                        tracing::debug!(%remote, "connection accepted");
2087                        // The handle must outlive the connection: it owns the
2088                        // actor's control channel.
2089                        let ctx = ConnCtx::spawn(
2090                            Link::Quic(QuicLink::new(conn.clone())),
2091                            limits,
2092                            namespace,
2093                            Some(Arc::clone(&subs)),
2094                            exec_for_conn,
2095                            guarantees,
2096                            shared,
2097                        );
2098                        let serial = ctx.conn.stable_id();
2099                        let reason = conn.closed().await;
2100                        // A peer that goes away takes its subscriptions with
2101                        // it; otherwise connection churn would grow the
2102                        // registry.
2103                        subs.remove_connection(serial);
2104                        let departure = crate::conn::take_departure(&ctx);
2105                        tracing::debug!(%remote, %reason, "connection closed");
2106                        depart(departure, &departing, move || {
2107                            peers.release(peer, quic_id);
2108                            open.remove(quic_id);
2109                            drop((ctx, conn, live));
2110                        })
2111                        .await;
2112                    }
2113                }
2114                Err(e) => tracing::debug!(error = %e, "handshake failed"),
2115            }
2116        });
2117    }
2118    tracing::debug!("binding stopped accepting");
2119}
2120
2121#[cfg(test)]
2122mod tests {
2123    use super::*;
2124
2125    #[tokio::test]
2126    async fn namespace_rejects_duplicate_paths() {
2127        let ns = Namespace::new();
2128        let (tx, _rx) = mpsc::channel(1);
2129        ns.register("/a", Route::Request(tx.clone())).unwrap();
2130        assert!(matches!(
2131            ns.register("/a", Route::Request(tx.clone())),
2132            Err(Error::AlreadyRegistered)
2133        ));
2134        // The pattern behind the path is irrelevant: a path is claimed once.
2135        assert!(matches!(
2136            ns.register("/a", Route::Pub),
2137            Err(Error::AlreadyRegistered)
2138        ));
2139        ns.register("/b", Route::Request(tx)).unwrap();
2140    }
2141
2142    #[tokio::test]
2143    async fn namespace_lookup_is_exact() {
2144        let ns = Namespace::new();
2145        let (tx, _rx) = mpsc::channel(1);
2146        ns.register("/jobs/a", Route::Request(tx)).unwrap();
2147        assert!(ns.lookup("/jobs/a").is_some());
2148        // No prefix matching, no wildcards, no trailing-slash equivalence.
2149        assert!(ns.lookup("/jobs").is_none());
2150        assert!(ns.lookup("/jobs/a/").is_none());
2151        assert!(ns.lookup("/jobs/*").is_none());
2152        assert!(ns.lookup("/JOBS/A").is_none());
2153    }
2154
2155    #[tokio::test]
2156    async fn unregistering_releases_the_path() {
2157        let ns = Namespace::new();
2158        let (tx, _rx) = mpsc::channel(1);
2159        ns.register("/s", Route::Transfer(tx)).unwrap();
2160        ns.unregister("/s");
2161        assert!(ns.lookup("/s").is_none());
2162        // Unregistering an unknown path is not an error.
2163        ns.unregister("/s");
2164        ns.register("/s", Route::Pub).unwrap();
2165    }
2166}
2167
2168#[cfg(test)]
2169mod accept_tests {
2170    use super::*;
2171
2172    /// A flood of refusals is one log record per interval, and the record
2173    /// says how many were held back.
2174    #[test]
2175    fn a_log_throttle_passes_one_record_per_interval_and_counts_the_rest() {
2176        let throttle = LogThrottle::new(Duration::from_secs(1));
2177        let start = Instant::now();
2178        assert_eq!(throttle.pass_at(start), Some(0));
2179        for _ in 0..5 {
2180            assert_eq!(throttle.pass_at(start + Duration::from_millis(500)), None);
2181        }
2182        assert_eq!(
2183            throttle.pass_at(start + Duration::from_millis(1500)),
2184            Some(5)
2185        );
2186        assert_eq!(throttle.pass_at(start + Duration::from_millis(1600)), None);
2187    }
2188
2189    /// A raw consumer is recorded per filter: a repeat is not a new
2190    /// subscription, a filter the connection never held frees nothing, and the
2191    /// path stays reportable until its last filter goes.
2192    #[test]
2193    fn a_consumer_is_recorded_per_filter_and_reported_with_its_last_path() {
2194        let ns = Namespace::new();
2195        assert!(ns.note_consumer(7, "/q", "a"));
2196        assert!(!ns.note_consumer(7, "/q", "a"));
2197        assert!(ns.note_consumer(7, "/q", "b"));
2198        assert!(!ns.forget_consumer(7, "/q", "never"));
2199        assert!(ns.forget_consumer(7, "/q", "a"));
2200        assert!(!ns.forget_consumer(7, "/q", "a"));
2201
2202        let (tx, _rx) = mpsc::channel(1);
2203        ns.register("/q", Route::Raw(tx)).expect("register");
2204        // "b" is still held, so closing the connection reports the path.
2205        assert_eq!(ns.take_consumer_routes(7).len(), 1);
2206        assert!(ns.take_consumer_routes(7).is_empty());
2207    }
2208}