Skip to main content

weida/
endpoint.rs

1//! L1: typed endpoints, one `Endpoint<P>` per messaging pattern.
2//!
3//! The pattern is a type parameter rather than a runtime mode flag, so a
4//! requester cannot be asked to accept and a replier cannot be asked to dial
5//! (master doc §3). The trait is sealed: patterns are part of the protocol.
6//!
7//! Everything here is a thin wrapper over the stream core ([`crate::stream`]):
8//! Req/Rep is one bidirectional stream per exchange, Push/Pull is a
9//! unidirectional stream per message with round-robin peer selection, Pub/Sub
10//! is the same stream with fan-out selection and publisher-side filtering. No
11//! pattern adds a guarantee QUIC does not already provide; the vocabulary of
12//! stored/replicated/processed belongs to a broker layer that does not exist
13//! yet (`docs/GUARANTEES.md`).
14
15use std::collections::HashSet;
16use std::pin::Pin;
17use std::sync::Arc;
18use std::time::{Duration, Instant};
19
20use bytes::Bytes;
21use tokio::sync::{Mutex, Semaphore, mpsc};
22use weida_core::{Error, TraceContext};
23use weida_protocol::{CreditHeader, FrameKind, SubscriptionHeader};
24
25use crate::config::ClientTls;
26use crate::conn::{ConnHandle, Ctl, check_header_len, write_control};
27use crate::listener::{PairOwner, Route};
28use crate::pubsub::{FanOut, SubRegistry};
29use crate::reconnect::PeerEvents;
30use crate::runtime::RuntimeInner;
31use crate::stream::{Attach, Peer};
32use crate::transfer::{
33    IncomingRequest, IncomingTransfer, OutgoingTransfer, ReplyStream, TransferMeta,
34};
35
36mod sealed {
37    pub trait Sealed {}
38}
39
40/// A messaging pattern.
41pub trait Pattern: sealed::Sealed {
42    /// Pattern-specific endpoint state.
43    type State;
44}
45
46/// The requesting side of Req/Rep.
47pub enum Req {}
48/// The replying side of Req/Rep.
49pub enum Rep {}
50/// The sending side of Push/Pull.
51pub enum Push {}
52/// The receiving side of Push/Pull.
53pub enum Pull {}
54/// The publishing side of Pub/Sub.
55pub enum Pub {}
56/// The subscribing side of Pub/Sub.
57pub enum Sub {}
58/// Either side of PAIR: one connection, one peer, both directions.
59pub enum Pair {}
60/// The asking side of SURVEY.
61pub enum Survey {}
62/// The answering side of SURVEY.
63pub enum Respond {}
64/// A member of a BUS.
65pub enum Bus {}
66/// The sending side of RADIO/DISH: lossy fan-out of segments
67/// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §4.6).
68pub enum Cast {}
69/// The receiving side of RADIO/DISH.
70pub enum Tune {}
71/// The bound side of SWARM: answers each fetch's orders about a blob from the
72/// application's storage ([decisions/0040](../../../docs/decisions/0040-swarm-pattern.md),
73/// [decisions/0041](../../../docs/decisions/0041-swarm-sessions.md)).
74#[cfg(feature = "swarm")]
75pub enum Seed {}
76/// The dialling side of SWARM: gathers one blob from every connected seeder.
77#[cfg(feature = "swarm")]
78pub enum Gather {}
79
80impl sealed::Sealed for Req {}
81impl Pattern for Req {
82    type State = ReqState;
83}
84
85impl sealed::Sealed for Rep {}
86impl Pattern for Rep {
87    type State = RepState;
88}
89
90impl sealed::Sealed for Push {}
91impl Pattern for Push {
92    type State = PushState;
93}
94
95impl sealed::Sealed for Pull {}
96impl Pattern for Pull {
97    type State = PullState;
98}
99
100impl sealed::Sealed for Pub {}
101impl Pattern for Pub {
102    type State = PubState;
103}
104
105impl sealed::Sealed for Sub {}
106impl Pattern for Sub {
107    type State = SubState;
108}
109
110impl sealed::Sealed for Pair {}
111impl Pattern for Pair {
112    type State = PairState;
113}
114
115impl sealed::Sealed for Survey {}
116impl Pattern for Survey {
117    type State = SurveyState;
118}
119
120impl sealed::Sealed for Respond {}
121impl Pattern for Respond {
122    type State = RespondState;
123}
124
125impl sealed::Sealed for Bus {}
126impl Pattern for Bus {
127    type State = BusState;
128}
129
130impl sealed::Sealed for Cast {}
131impl Pattern for Cast {
132    type State = crate::radio::RadioState;
133}
134
135impl sealed::Sealed for Tune {}
136impl Pattern for Tune {
137    type State = crate::radio::DishState;
138}
139
140#[cfg(feature = "swarm")]
141impl sealed::Sealed for Seed {}
142#[cfg(feature = "swarm")]
143impl Pattern for Seed {
144    type State = crate::swarm::SeedState;
145}
146
147#[cfg(feature = "swarm")]
148impl sealed::Sealed for Gather {}
149#[cfg(feature = "swarm")]
150impl Pattern for Gather {
151    type State = crate::swarm::GatherState;
152}
153
154/// A typed messaging endpoint.
155pub struct Endpoint<P: Pattern> {
156    state: P::State,
157}
158
159impl<P: Pattern> Endpoint<P> {
160    pub(crate) fn from_state(state: P::State) -> Endpoint<P> {
161        Endpoint { state }
162    }
163
164    /// The pattern's state, for patterns implemented outside this module.
165    pub(crate) fn state(&self) -> &P::State {
166        &self.state
167    }
168}
169
170/// The requesting half of Req/Rep.
171pub type Requester = Endpoint<Req>;
172/// The replying half of Req/Rep.
173pub type Replier = Endpoint<Rep>;
174/// The sending half of Push/Pull.
175pub type Pusher = Endpoint<Push>;
176/// The receiving half of Push/Pull.
177pub type Puller = Endpoint<Pull>;
178/// The publishing half of Pub/Sub.
179pub type Publisher = Endpoint<Pub>;
180/// The subscribing half of Pub/Sub.
181pub type Subscriber = Endpoint<Sub>;
182/// Either half of PAIR — the pattern is symmetric, so there is one role.
183pub type Paired = Endpoint<Pair>;
184/// One member of a BUS.
185pub type BusMember = Endpoint<Bus>;
186/// The sending half of RADIO/DISH: binds, and fans segments out to every
187/// dish whose filter matches, dropping rather than waiting.
188pub type Radio = Endpoint<Cast>;
189/// The receiving half of RADIO/DISH: connects, joins topics, and receives
190/// the newest segment of each.
191pub type Dish = Endpoint<Tune>;
192/// The bound half of SWARM: hands each fetch's session about a blob to the
193/// application, which answers its orders from its own storage.
194#[cfg(feature = "swarm")]
195pub type Seeder = Endpoint<Seed>;
196/// The dialling half of SWARM: connects to seeders and fetches a blob from
197/// all of them at once, verifying every piece against the root.
198#[cfg(feature = "swarm")]
199pub type Swarm = Endpoint<Gather>;
200
201/// State of a requester.
202pub struct ReqState {
203    peer: Peer,
204}
205/// The asking half of SURVEY.
206pub type Surveyor = Endpoint<Survey>;
207/// The answering half of SURVEY.
208pub type Respondent = Endpoint<Respond>;
209
210impl ReqState {
211    pub(crate) fn new(runtime: Arc<RuntimeInner>, tls: Arc<ClientTls>) -> ReqState {
212        ReqState {
213            peer: Peer::new(runtime, tls),
214        }
215    }
216}
217
218impl Requester {
219    /// Connects to `weida://host:port/path`.
220    ///
221    /// The address is kept: a lost connection is redialled by the runtime
222    /// under [`crate::RuntimeConfig::reconnect`], and [`Requester::events`]
223    /// reports it.
224    pub async fn connect(&self, url: &str) -> Result<(), Error> {
225        self.state.peer.connect(url).await
226    }
227
228    /// Forgets a dialled address; see [`Peer::disconnect`].
229    pub fn disconnect(&self, url: &str) -> bool {
230        self.state.peer.disconnect(url)
231    }
232
233    /// Number of connected peers.
234    pub fn peer_count(&self) -> usize {
235        self.state.peer.peer_count()
236    }
237
238    /// One record per live connection, labelled by the URL as dialled; see
239    /// [`Peer::connection_stats`].
240    pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
241        self.state.peer.connection_stats()
242    }
243
244    /// The event stream of this requester's addresses; see [`Peer::events`].
245    pub fn events(&self) -> PeerEvents {
246        self.state.peer.events()
247    }
248
249    /// Opens one exchange: a request stream and its reply half.
250    ///
251    /// Both halves belong to the same bidirectional QUIC stream, so no
252    /// correlation identifier is needed and none is sent.
253    pub async fn open(&self, meta: TransferMeta) -> Result<(OutgoingTransfer, ReplyStream), Error> {
254        self.state.peer.open_bi(meta).await
255    }
256
257    /// Sends `body` as one request and returns the reply stream.
258    ///
259    /// Convenience over [`Requester::open`] for small payloads; it never
260    /// materializes the reply. The delivery receipt is discarded: a reply is a
261    /// stronger answer than a transport acknowledgement, and waiting for both
262    /// would only add a round trip.
263    pub async fn request(&self, body: &[u8]) -> Result<IncomingTransfer, Error> {
264        self.request_with(TransferMeta::default(), body).await
265    }
266
267    /// Like [`Requester::request`], with explicit metadata.
268    pub async fn request_with(
269        &self,
270        meta: TransferMeta,
271        body: &[u8],
272    ) -> Result<IncomingTransfer, Error> {
273        let (mut transfer, reply) = self.open(meta).await?;
274        transfer.write_all(body).await?;
275        transfer.finish()?;
276        reply.recv().await
277    }
278}
279
280/// State of a replier.
281pub struct RepState {
282    path: Arc<str>,
283    /// An async mutex so `accept(&self)` needs no `&mut self`; contention is
284    /// between deliberate concurrent acceptors only.
285    queue: Mutex<mpsc::Receiver<IncomingRequest>>,
286}
287
288impl RepState {
289    pub(crate) fn new(path: &str, queue: mpsc::Receiver<IncomingRequest>) -> RepState {
290        RepState {
291            path: Arc::from(path),
292            queue: Mutex::new(queue),
293        }
294    }
295}
296
297impl Replier {
298    /// The endpoint path this replier serves.
299    pub fn path(&self) -> &str {
300        &self.state.path
301    }
302
303    /// Waits for the next request.
304    ///
305    /// Requests queue up to `Limits::endpoint_queue`; beyond that the sending
306    /// side blocks, which propagates backpressure to the peer through QUIC flow
307    /// control rather than growing an unbounded queue (master doc §50).
308    pub async fn accept(&self) -> Result<IncomingRequest, Error> {
309        let mut queue = self.state.queue.lock().await;
310        queue.recv().await.ok_or(Error::NotConnected)
311    }
312}
313
314// --- Push/Pull ------------------------------------------------------------
315
316/// State of a pusher.
317pub struct PushState {
318    peer: Peer,
319}
320
321impl PushState {
322    pub(crate) fn new(runtime: Arc<RuntimeInner>, tls: Arc<ClientTls>) -> PushState {
323        PushState {
324            peer: Peer::new(runtime, tls),
325        }
326    }
327}
328
329impl Pusher {
330    /// Connects to `weida://host:port/path`.
331    ///
332    /// The address is kept: a lost connection is redialled by the runtime
333    /// under [`crate::RuntimeConfig::reconnect`], and [`Pusher::events`]
334    /// reports it.
335    pub async fn connect(&self, url: &str) -> Result<(), Error> {
336        self.state.peer.connect(url).await
337    }
338
339    /// Forgets a dialled address; see [`Peer::disconnect`].
340    pub fn disconnect(&self, url: &str) -> bool {
341        self.state.peer.disconnect(url)
342    }
343
344    /// Number of connected peers.
345    pub fn peer_count(&self) -> usize {
346        self.state.peer.peer_count()
347    }
348
349    /// One record per live connection, labelled by the URL as dialled; see
350    /// [`Peer::connection_stats`].
351    pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
352        self.state.peer.connection_stats()
353    }
354
355    /// The event stream of this pusher's addresses; see [`Peer::events`].
356    pub fn events(&self) -> PeerEvents {
357        self.state.peer.events()
358    }
359
360    /// Bodies the outbox discarded; see [`Peer::dropped`].
361    pub fn dropped(&self) -> u64 {
362        self.state.peer.dropped()
363    }
364
365    /// Opens a one-way transfer to the next peer, round-robin.
366    ///
367    /// Use this rather than [`Pusher::send`] when the transport receipt
368    /// matters: [`OutgoingTransfer::finish`] hands back a
369    /// [`crate::Delivery`] that resolves once the peer's transport holds every
370    /// byte. The stream is the application's: with every peer down this
371    /// waits for the redial, and a stream on a connection that dies fails
372    /// with `ConnectionLost` and is not reopened by anyone but the caller.
373    pub async fn open(&self, meta: TransferMeta) -> Result<OutgoingTransfer, Error> {
374        self.state.peer.open(meta).await
375    }
376
377    /// Sends `body` as one message: the runtime owns it from this call.
378    ///
379    /// Pipeline semantics: the delivery receipt is discarded, so a push costs
380    /// no round trip and reports only failures the local side already knows
381    /// about. With a live peer the body is written at once; with none it is
382    /// held in the outbox and written once a peer is back, in order, and a
383    /// full outbox applies the configured backpressure ([`Peer::send`]).
384    /// Callers who want the receipt use [`Pusher::open`] and await
385    /// [`crate::Delivery::delivered`] themselves.
386    pub async fn send(&self, body: &[u8]) -> Result<(), Error> {
387        self.send_with(TransferMeta::default(), body).await
388    }
389
390    /// Like [`Pusher::send`], with explicit metadata.
391    pub async fn send_with(&self, meta: TransferMeta, body: &[u8]) -> Result<(), Error> {
392        self.state.peer.send(meta, body).await
393    }
394}
395
396/// State of a puller.
397pub struct PullState {
398    path: Arc<str>,
399    queue: Mutex<mpsc::Receiver<IncomingTransfer>>,
400}
401
402impl PullState {
403    pub(crate) fn new(path: &str, queue: mpsc::Receiver<IncomingTransfer>) -> PullState {
404        PullState {
405            path: Arc::from(path),
406            queue: Mutex::new(queue),
407        }
408    }
409}
410
411impl Puller {
412    /// The endpoint path this puller serves.
413    pub fn path(&self) -> &str {
414        &self.state.path
415    }
416
417    /// Waits for the next transfer.
418    ///
419    /// `recv`, not `accept`: a pulled transfer is a payload with metadata, not
420    /// a request that owes a reply. Backpressure works exactly as it does for a
421    /// replier — the queue is bounded by `Limits::endpoint_queue` and a full
422    /// queue stalls the sender through QUIC flow control.
423    pub async fn recv(&self) -> Result<IncomingTransfer, Error> {
424        let mut queue = self.state.queue.lock().await;
425        queue.recv().await.ok_or(Error::NotConnected)
426    }
427}
428
429// --- Pub/Sub --------------------------------------------------------------
430
431/// State of a publisher.
432pub struct PubState {
433    path: Arc<str>,
434    registry: Arc<SubRegistry>,
435    max_payload: usize,
436}
437
438impl PubState {
439    pub(crate) fn new(path: &str, registry: Arc<SubRegistry>, max_payload: usize) -> PubState {
440        PubState {
441            path: Arc::from(path),
442            registry,
443            max_payload,
444        }
445    }
446}
447
448impl Publisher {
449    /// The endpoint path this publisher serves.
450    pub fn path(&self) -> &str {
451        &self.state.path
452    }
453
454    /// Fans `payload` out to every subscriber whose filter is a prefix of
455    /// `topic`, and returns how many it was enqueued to.
456    ///
457    /// Synchronous and non-blocking: publishing never waits on a subscriber.
458    /// A subscriber whose byte budget is exhausted loses this message, which is
459    /// counted in [`Publisher::dropped`]. Zero subscribers is not an error —
460    /// a publisher with no audience is the normal startup state.
461    ///
462    /// Fails with [`Error::LimitExceeded`] when `payload` is larger than
463    /// `Limits::subscriber_buffer_bytes`: such a message could never be
464    /// enqueued for anyone, so reporting it beats silently dropping it for
465    /// every subscriber. It fails the same way for a `topic` above 256 bytes,
466    /// which a subscriber's decoder refuses by closing its connection.
467    ///
468    /// No `traceparent` is written unless one is propagated: see
469    /// [`Publisher::publish_with_trace`] and
470    /// [0028](../../../docs/decisions/0028-trace-propagation-is-the-callers.md).
471    pub fn publish(&self, topic: &str, payload: impl Into<Bytes>) -> Result<usize, Error> {
472        self.publish_inner(topic, payload.into(), None)
473    }
474
475    /// Like [`Publisher::publish`], propagating an existing trace context.
476    ///
477    /// The context comes from the caller — an inbound
478    /// [`crate::IncomingMeta::trace`], or [`crate::new_trace`] to start one.
479    pub fn publish_with_trace(
480        &self,
481        topic: &str,
482        payload: impl Into<Bytes>,
483        trace: TraceContext,
484    ) -> Result<usize, Error> {
485        self.publish_inner(topic, payload.into(), Some(trace))
486    }
487
488    fn publish_inner(
489        &self,
490        topic: &str,
491        payload: Bytes,
492        trace: Option<TraceContext>,
493    ) -> Result<usize, Error> {
494        if payload.len() > self.state.max_payload {
495            return Err(Error::LimitExceeded);
496        }
497        let want = u32::try_from(payload.len()).map_err(|_| Error::LimitExceeded)?;
498        self.state
499            .registry
500            .publish(&self.state.path, topic, payload, trace, want)
501    }
502
503    /// Opens a streamed publish: one stream per matched subscriber, written
504    /// chunk by chunk.
505    ///
506    /// This is the fan-out for a payload that is not in memory and need not
507    /// be — a video frame read from a capture device, a file, a response body
508    /// being forwarded
509    /// ([requirements/zeughaus-video.md](../../../docs/requirements/zeughaus-video.md)
510    /// request 1). [`Publisher::publish`] refuses a payload above
511    /// `Limits::subscriber_buffer_bytes` because such a message could not be
512    /// enqueued for anybody; here that limit applies to a **chunk**, so the
513    /// payload has no ceiling at all.
514    ///
515    /// The subscriber set is fixed at this call: a subscriber that arrives
516    /// while the payload is in flight would receive a fragment with no way to
517    /// know it, so it gets the next message instead. Zero subscribers is not
518    /// an error, exactly as for [`Publisher::publish`]. A `topic` above 256
519    /// bytes cannot be sent to anyone, since a subscriber's decoder refuses
520    /// it by closing its connection: the fan-out reaches nobody and refuses
521    /// every write with [`Error::LimitExceeded`].
522    ///
523    /// Every guarantee of [`Publisher::publish`] holds per subscriber rather
524    /// than per publish: see [`FanOut`].
525    pub fn open(&self, topic: &str) -> FanOut {
526        self.state.registry.open(&self.state.path, topic, None)
527    }
528
529    /// Like [`Publisher::open`], propagating an existing trace context.
530    pub fn open_with_trace(&self, topic: &str, trace: TraceContext) -> FanOut {
531        self.state
532            .registry
533            .open(&self.state.path, topic, Some(trace))
534    }
535
536    /// Connections currently subscribed to this publisher.
537    pub fn subscriber_count(&self) -> usize {
538        self.state.registry.subscriber_count(&self.state.path)
539    }
540
541    /// Filters registered on this publisher, summed over subscribers.
542    pub fn filter_count(&self) -> usize {
543        self.state.registry.filter_count(&self.state.path)
544    }
545
546    /// Messages dropped because a subscriber could not take them, summed
547    /// over topics and causes. "Something is being discarded"; for "which
548    /// signal is starving", see [`Publisher::drops`].
549    pub fn dropped(&self) -> u64 {
550        self.state.registry.dropped(&self.state.path)
551    }
552
553    /// What was dropped on `topic`, by cause, or `None` if nothing was.
554    ///
555    /// Maintained as the drops happen, so this is a lookup and not a scan.
556    /// The table holds at most `Limits::max_sequence_scopes` topics — the
557    /// same ceiling the sequencer's per-topic table has — and a topic beyond
558    /// it counts in [`Publisher::dropped`] only.
559    pub fn dropped_on(&self, topic: &str) -> Option<crate::TopicDrops> {
560        self.state.registry.dropped_on(&self.state.path, topic)
561    }
562
563    /// Every topic that lost a copy, with its counts by cause.
564    pub fn drops(&self) -> Vec<crate::TopicDrops> {
565        self.state.registry.drops(&self.state.path)
566    }
567}
568
569/// What a subscriber does on every connection it gets, first dial and
570/// redial alike: claim the path as its route, fill the reverse pool where
571/// the transport needs one, and send the filters it holds
572/// ([0031](../../../docs/decisions/0031-transparent-redial-and-the-sender-outbox.md)
573/// §4.6). The publisher kept nothing, so nothing else is restored.
574struct SubAttach {
575    filters: Arc<std::sync::Mutex<HashSet<String>>>,
576    queue_tx: mpsc::Sender<IncomingTransfer>,
577}
578
579impl Attach for SubAttach {
580    fn attach<'a>(
581        &'a self,
582        conn: &'a ConnHandle,
583        path: &'a str,
584    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'a>> {
585        Box::pin(async move {
586            if conn.conn.needs_reverse_pool() && conn.conn.park_reverse().await? == 0 {
587                return Err(Error::Unsupported);
588            }
589            conn.namespace
590                .register(path, Route::Transfer(self.queue_tx.clone()))?;
591            if conn.conn.needs_reverse_pool() {
592                let maintaining = Arc::clone(conn);
593                conn.exec
594                    .spawn(async move { maintaining.conn.maintain_reverse().await });
595            }
596            let filters: Vec<String> = self
597                .filters
598                .lock()
599                .expect("filter set poisoned")
600                .iter()
601                .cloned()
602                .collect();
603            for filter in filters {
604                send_subscription(conn, FrameKind::Subscribe, path, &filter, None, None).await?;
605            }
606            Ok(())
607        })
608    }
609}
610
611/// State of a subscriber.
612pub struct SubState {
613    peer: Peer,
614    /// Filters this subscriber wants, remembered so a peer connected — or
615    /// redialled — later receives the same subscriptions. Shared with the
616    /// attachment the peer runs on every connection.
617    filters: Arc<std::sync::Mutex<HashSet<String>>>,
618    queue: Mutex<mpsc::Receiver<IncomingTransfer>>,
619}
620
621impl SubState {
622    pub(crate) fn new(runtime: Arc<RuntimeInner>, tls: Arc<ClientTls>, depth: usize) -> SubState {
623        let (queue_tx, queue) = mpsc::channel(depth);
624        let filters = Arc::new(std::sync::Mutex::new(HashSet::new()));
625        let attach = SubAttach {
626            filters: Arc::clone(&filters),
627            queue_tx,
628        };
629        SubState {
630            peer: Peer::with_attach(runtime, tls, Some(Arc::new(attach))),
631            filters,
632            queue: Mutex::new(queue),
633        }
634    }
635}
636
637impl Subscriber {
638    /// Connects to `weida://host:port/path` and subscribes to every filter
639    /// registered so far.
640    ///
641    /// The subscriber registers `path` in the *client* connection's namespace:
642    /// fanned-out copies arrive as ordinary inbound one-way transfers, so the
643    /// dialling side needs a route for them. Two subscribers sharing a pooled
644    /// connection and claiming the same path therefore collide with
645    /// [`Error::AlreadyRegistered`]; fanning one subscription out to several
646    /// in-process consumers is the application's business, not the transport's.
647    ///
648    /// On a transport where the accepting side cannot open a stream back,
649    /// this is also where the reverse pool is filled: the subscriber parks
650    /// `Limits::max_parked_reverse` connections and keeps replacing them as
651    /// the publisher spends them
652    /// ([0012](../../../docs/decisions/0012-local-connection-grouping.md)
653    /// §4.4). A subscriber that parks nothing - because the limit is zero,
654    /// or because the peer refused every attempt - cannot receive fan-out at
655    /// all, and learns that here rather than by waiting forever.
656    ///
657    /// The address is kept: when the connection is lost the runtime redials
658    /// it and does all of the above again on the new connection, filters
659    /// included. What was published in between is gone — the publisher
660    /// keeps no subscription across connections — and
661    /// [`Subscriber::events`] says when the gap began and ended.
662    pub async fn connect(&self, url: &str) -> Result<(), Error> {
663        self.state.peer.connect(url).await
664    }
665
666    /// Forgets a dialled address; see [`Peer::disconnect`].
667    pub fn disconnect(&self, url: &str) -> bool {
668        self.state.peer.disconnect(url)
669    }
670
671    /// Number of connected peers.
672    pub fn peer_count(&self) -> usize {
673        self.state.peer.peer_count()
674    }
675
676    /// One record per live connection, labelled by the URL as dialled; see
677    /// [`Peer::connection_stats`].
678    pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
679        self.state.peer.connection_stats()
680    }
681
682    /// The event stream of this subscriber's addresses; see [`Peer::events`].
683    pub fn events(&self) -> PeerEvents {
684        self.state.peer.events()
685    }
686
687    /// Registers interest in every topic `filter` matches.
688    ///
689    /// The filter is a **segmented pattern** ([`PROTOCOL.md`] §6.4): segments
690    /// are split on `.`, `*` matches exactly one whole segment, a trailing
691    /// `#` matches zero or more segments and must be the last one, and every
692    /// other byte is literal — no escape character, no normalization, no case
693    /// folding. `""` receives everything, and so does `#`. A published topic
694    /// is never a pattern: `*` in a topic is an ordinary byte.
695    ///
696    /// So `sensors.*.temp` selects one segment in the middle, `sensors.#`
697    /// selects `sensors` and everything under it, and `sensors.temp` does
698    /// **not** select `sensors.temperature`.
699    ///
700    /// Subscribing twice to the same filter is idempotent. A filter that
701    /// violates the grammar fails here with [`Error::Protocol`] rather than
702    /// travelling to the publisher, which would answer it by closing the
703    /// connection.
704    ///
705    /// [`PROTOCOL.md`]: https://github.com/tuco86/weida/blob/main/docs/PROTOCOL.md
706    pub async fn subscribe(&self, filter: &str) -> Result<(), Error> {
707        weida_protocol::filter::validate(filter)?;
708        let fresh = self
709            .state
710            .filters
711            .lock()
712            .expect("filter set poisoned")
713            .insert(filter.to_owned());
714        if !fresh {
715            return Ok(());
716        }
717        self.broadcast(FrameKind::Subscribe, filter).await
718    }
719
720    /// Withdraws a filter. Unknown filters are ignored.
721    pub async fn unsubscribe(&self, filter: &str) -> Result<(), Error> {
722        let known = self
723            .state
724            .filters
725            .lock()
726            .expect("filter set poisoned")
727            .remove(filter);
728        if !known {
729            return Ok(());
730        }
731        self.broadcast(FrameKind::Unsubscribe, filter).await
732    }
733
734    /// Filters currently registered.
735    pub fn filter_count(&self) -> usize {
736        self.state
737            .filters
738            .lock()
739            .expect("filter set poisoned")
740            .len()
741    }
742
743    /// Waits for the next published message.
744    ///
745    /// The topic is on [`crate::IncomingMeta::topic`].
746    pub async fn recv(&self) -> Result<IncomingTransfer, Error> {
747        let mut queue = self.state.queue.lock().await;
748        queue.recv().await.ok_or(Error::NotConnected)
749    }
750
751    /// States how many messages this subscriber will accept in total on the
752    /// subscription `filter`, and sends it to every connected peer.
753    ///
754    /// This is the L2 credit of
755    /// [0003](https://github.com/tuco86/weida/blob/main/docs/decisions/0003-credit-unit.md)
756    /// §4.2, and it matters only where a **queue** serves the path: a
757    /// publisher fans a message out to every matching subscriber and consults
758    /// no credit, while a queue delivers to one consumer and delivers nothing
759    /// at all until that consumer has granted some.
760    ///
761    /// **The limit is absolute and cumulative**, counted from the
762    /// subscription's creation — not a delta and not a window — so a lost
763    /// grant costs nothing and a duplicated one changes nothing. A broker
764    /// keeps the **highest** limit it has seen for a subscription, which is
765    /// what makes a reordered grant harmless: every control frame rides its
766    /// own unidirectional stream, and QUIC does not order those against each
767    /// other.
768    ///
769    /// Two consequences worth stating, because they are the whole usage
770    /// pattern:
771    ///
772    /// - **An unmentioned subscription has a limit of zero**: a consumer that
773    ///   subscribes and grants nothing receives nothing. That is the only
774    ///   default that cannot surprise a consumer with a flood.
775    /// - **A standing limit cannot be lowered.** Monotone means what it
776    ///   says: a grant below the standing limit is ignored, so restating the
777    ///   count already delivered does *not* pause delivery — it changes
778    ///   nothing at all unless that count had already reached the limit.
779    ///   The only pause in v0 is the `0` a fresh subscription starts at, so
780    ///   a consumer that wants to stay in control grants in increments it is
781    ///   willing to receive rather than one large number it means to
782    ///   withdraw later. Lowering a limit would need a wire field that
783    ///   distinguishes a newer statement from an older one, which v0 does
784    ///   not have — and without it a "pause" could be undone by a delayed
785    ///   earlier grant.
786    pub async fn grant(&self, filter: &str, limit: u64) -> Result<(), Error> {
787        weida_protocol::filter::validate(filter)?;
788        for (conn, path) in self.state.peer.live_peers() {
789            let header = CreditHeader::new(path.as_ref(), filter, limit);
790            // Refused before anything is written: a header no peer would read,
791            // or one longer than the peer said it reads, makes it close the
792            // connection.
793            header.check().map_err(|_| Error::LimitExceeded)?;
794            let header = header.encode();
795            check_header_len(&conn, header.len())?;
796            write_control(&conn.conn, FrameKind::Credit, &header).await?;
797        }
798        Ok(())
799    }
800
801    async fn broadcast(&self, kind: FrameKind, filter: &str) -> Result<(), Error> {
802        for (conn, path) in self.state.peer.live_peers() {
803            send_subscription(&conn, kind, &path, filter, None, None).await?;
804        }
805        Ok(())
806    }
807}
808
809pub(crate) async fn send_subscription(
810    conn: &ConnHandle,
811    kind: FrameKind,
812    path: &str,
813    filter: &str,
814    max_age_ms: Option<u64>,
815    max_layer: Option<u8>,
816) -> Result<(), Error> {
817    let header = SubscriptionHeader {
818        max_age_ms,
819        max_layer,
820        ..SubscriptionHeader::new(path, filter)
821    };
822    // Refused before anything is written: a filter or path no peer would
823    // read, or a header longer than the peer said it reads, makes it close
824    // the connection, and a subscriber re-sends its filters on every redial.
825    header.check().map_err(|_| Error::LimitExceeded)?;
826    let header = header.encode();
827    check_header_len(conn, header.len())?;
828    write_control(&conn.conn, kind, &header).await
829}
830
831impl Drop for SubState {
832    fn drop(&mut self) {
833        // Best effort: tell each peer we are gone and release the path so the
834        // next subscriber on this pooled connection can claim it.
835        //
836        // The frames go through the connection actor with a non-blocking
837        // `notify`, not `tokio::spawn`: a destructor may run on a thread with
838        // no reactor, and panicking there aborts the process instead of
839        // unwinding. The publisher drops the subscription anyway once the
840        // connection closes, so a lost notification costs nothing.
841        let filters: Vec<String> = self
842            .filters
843            .lock()
844            .expect("filter set poisoned")
845            .iter()
846            .cloned()
847            .collect();
848        for (conn, path) in self.peer.live_peers() {
849            conn.namespace.unregister(&path);
850            for filter in &filters {
851                conn.notify(Ctl::SendUnsubscribe {
852                    path: Arc::clone(&path),
853                    filter: filter.clone(),
854                });
855            }
856        }
857    }
858}
859
860// --- PAIR -----------------------------------------------------------------
861
862/// State of a paired endpoint.
863///
864/// One type for both sides, because PAIR is symmetric: both send and receive
865/// with the same calls. What differs is only *how each side reaches its
866/// peer*, and that is the whole asymmetry of a bound endpoint in this
867/// library — a dialling side holds a [`Peer`], a bound side learns its peer
868/// when that peer first speaks, which is what [`PairOwner`] records.
869pub struct PairState {
870    /// The dialling side's peer. `None` on a bound pair.
871    peer: Option<Peer>,
872    /// The bound side's peer, once it has claimed the endpoint. `None` on a
873    /// dialling pair.
874    owner: Option<Arc<PairOwner>>,
875    /// The bound path; empty on a dialling pair, whose path is the one it
876    /// dialled and is already recorded in its [`Peer`].
877    path: Arc<str>,
878    queue: Mutex<mpsc::Receiver<IncomingTransfer>>,
879}
880
881/// What a dialling pair does on every connection it gets: claim the path as
882/// its route and fill the reverse pool where the transport needs one — on
883/// the redialled connection as on the first (0031 §4.6).
884struct PairAttach {
885    queue_tx: mpsc::Sender<IncomingTransfer>,
886}
887
888impl Attach for PairAttach {
889    fn attach<'a>(
890        &'a self,
891        conn: &'a ConnHandle,
892        path: &'a str,
893    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'a>> {
894        Box::pin(async move {
895            if conn.conn.needs_reverse_pool() && conn.conn.park_reverse().await? == 0 {
896                return Err(Error::Unsupported);
897            }
898            conn.namespace.register(
899                path,
900                Route::Pair {
901                    queue: self.queue_tx.clone(),
902                    owner: Arc::new(PairOwner::new()),
903                },
904            )?;
905            if conn.conn.needs_reverse_pool() {
906                let maintaining = ConnHandle::clone(conn);
907                conn.exec
908                    .spawn(async move { maintaining.conn.maintain_reverse().await });
909            }
910            Ok(())
911        })
912    }
913}
914
915impl PairState {
916    pub(crate) fn bound(
917        path: &str,
918        owner: Arc<PairOwner>,
919        queue: mpsc::Receiver<IncomingTransfer>,
920    ) -> PairState {
921        PairState {
922            peer: None,
923            owner: Some(owner),
924            path: Arc::from(path),
925            queue: Mutex::new(queue),
926        }
927    }
928
929    pub(crate) fn dialling(
930        runtime: Arc<RuntimeInner>,
931        tls: Arc<ClientTls>,
932        depth: usize,
933    ) -> PairState {
934        let (queue_tx, queue) = mpsc::channel(depth);
935        let attach = PairAttach { queue_tx };
936        PairState {
937            peer: Some(Peer::with_attach(runtime, tls, Some(Arc::new(attach)))),
938            owner: None,
939            path: Arc::from(""),
940            queue: Mutex::new(queue),
941        }
942    }
943}
944
945impl Paired {
946    /// The endpoint path this pair uses; empty on a dialling pair that has
947    /// not connected yet.
948    pub fn path(&self) -> &str {
949        &self.state.path
950    }
951
952    /// Connects to `weida://host:port/path`, once.
953    ///
954    /// A pair has **one** peer, so a second call is refused with
955    /// [`Error::LimitExceeded`] rather than quietly becoming a Push: two
956    /// peers on one endpoint would need a selection policy, and PAIR is the
957    /// pattern that has none. On a bound pair there is nothing to dial and
958    /// this is [`Error::Unsupported`].
959    ///
960    /// Like a subscriber, a dialling pair registers the path in the *client*
961    /// connection's namespace: the peer's transfers arrive as ordinary
962    /// inbound one-way transfers, so the dialling side needs a route for
963    /// them — and on a transport where the accepting side cannot open a
964    /// stream back, the reverse pool is filled here
965    /// ([0012](../../../docs/decisions/0012-local-connection-grouping.md)
966    /// §4.4).
967    pub async fn connect(&self, url: &str) -> Result<(), Error> {
968        let Some(peer) = self.state.peer.as_ref() else {
969            return Err(Error::Unsupported);
970        };
971        // One address, live or being redialled: a second one would be a
972        // second peer.
973        if peer.slot_count() > 0 {
974            return Err(Error::LimitExceeded);
975        }
976        peer.connect(url).await
977    }
978
979    /// Number of connected peers: `0` or `1`.
980    pub fn peer_count(&self) -> usize {
981        self.state.peer.as_ref().map_or(0, Peer::peer_count)
982    }
983
984    /// The dialling side's connection, labelled by the URL as dialled; see
985    /// [`Peer::connection_stats`]. Empty on a bound pair, which dialled
986    /// nothing.
987    pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
988        self.state
989            .peer
990            .as_ref()
991            .map_or_else(Vec::new, Peer::connection_stats)
992    }
993
994    /// The event stream of a dialling pair's address; see [`Peer::events`].
995    /// A bound pair dials nothing and reports nothing: `None`.
996    pub fn events(&self) -> Option<PeerEvents> {
997        self.state.peer.as_ref().map(Peer::events)
998    }
999
1000    /// Bodies a dialling pair's outbox discarded; see [`Peer::dropped`].
1001    pub fn dropped(&self) -> u64 {
1002        self.state.peer.as_ref().map_or(0, Peer::dropped)
1003    }
1004
1005    /// Opens one outgoing transfer to the peer.
1006    ///
1007    /// The two sides reach their peer differently and that is the pattern's
1008    /// only asymmetry. A dialling pair sends on the connection it opened. A
1009    /// **bound** pair sends on the connection its peer dialled — and it can
1010    /// only know which one that is once the peer has spoken, so the first
1011    /// send on a bound pair **waits for the peer to appear**. That is not a
1012    /// queue: nothing is buffered, and a bound pair with no peer has nobody
1013    /// to address rather than a backlog to flush.
1014    pub async fn open(&self, meta: TransferMeta) -> Result<OutgoingTransfer, Error> {
1015        if let Some(peer) = self.state.peer.as_ref() {
1016            return peer.open(meta).await;
1017        }
1018        let owner = self
1019            .state
1020            .owner
1021            .as_ref()
1022            .expect("a pair is either dialling or bound");
1023        let conn = owner.peer().await?;
1024        crate::stream::open_transfer_on(&conn, &self.state.path, &meta).await
1025    }
1026
1027    /// Sends `body` as one message.
1028    ///
1029    /// On a dialling pair the runtime owns the body from this call: written
1030    /// at once while the peer is live, held in the outbox and written after
1031    /// the redial otherwise ([`Peer::send`]). On a bound pair it is written
1032    /// once the peer has appeared, as [`Paired::open`] describes.
1033    pub async fn send(&self, body: &[u8]) -> Result<(), Error> {
1034        self.send_with(TransferMeta::default(), body).await
1035    }
1036
1037    /// Like [`Paired::send`], with explicit metadata.
1038    pub async fn send_with(&self, meta: TransferMeta, body: &[u8]) -> Result<(), Error> {
1039        if let Some(peer) = self.state.peer.as_ref() {
1040            return peer.send(meta, body).await;
1041        }
1042        let mut transfer = self.open(meta).await?;
1043        transfer.write_all(body).await?;
1044        transfer.finish()?;
1045        Ok(())
1046    }
1047
1048    /// Waits for the next transfer from the peer.
1049    pub async fn recv(&self) -> Result<IncomingTransfer, Error> {
1050        let mut queue = self.state.queue.lock().await;
1051        queue.recv().await.ok_or(Error::NotConnected)
1052    }
1053}
1054
1055impl Drop for PairState {
1056    /// Releases the dialled path on a pooled connection.
1057    ///
1058    /// A dialling pair registers its path in the *client* connection's
1059    /// namespace, and connections are pooled by authority, trust terms and
1060    /// path — so without this the next `Runtime::pair().connect()` to the
1061    /// same URL reuses the connection, finds the dead pair's route still
1062    /// there and fails with `LimitExceeded`. This is what
1063    /// [`SubState::drop`] does for a subscription, for the same reason.
1064    fn drop(&mut self) {
1065        let Some(peer) = self.peer.as_ref() else {
1066            return;
1067        };
1068        for (conn, path) in peer.live_peers() {
1069            conn.namespace.unregister(&path);
1070        }
1071    }
1072}
1073
1074// --- SURVEY ---------------------------------------------------------------
1075
1076/// State of a surveyor.
1077pub struct SurveyState {
1078    peer: Peer,
1079}
1080
1081impl SurveyState {
1082    pub(crate) fn new(runtime: Arc<RuntimeInner>, tls: Arc<ClientTls>) -> SurveyState {
1083        SurveyState {
1084            peer: Peer::new(runtime, tls),
1085        }
1086    }
1087}
1088
1089/// State of a respondent.
1090pub struct RespondState {
1091    path: Arc<str>,
1092    queue: Mutex<mpsc::Receiver<IncomingRequest>>,
1093}
1094
1095impl RespondState {
1096    pub(crate) fn new(path: &str, queue: mpsc::Receiver<IncomingRequest>) -> RespondState {
1097        RespondState {
1098            path: Arc::from(path),
1099            queue: Mutex::new(queue),
1100        }
1101    }
1102}
1103
1104impl Surveyor {
1105    /// Connects to `weida://host:port/path`.
1106    ///
1107    /// A surveyor addresses **every** connected respondent, so unlike a
1108    /// requester it accumulates peers on purpose: each `connect` adds one to
1109    /// the set a survey fans out over.
1110    pub async fn connect(&self, url: &str) -> Result<(), Error> {
1111        self.state.peer.connect(url).await
1112    }
1113
1114    /// Number of connected respondents.
1115    pub fn peer_count(&self) -> usize {
1116        self.state.peer.peer_count()
1117    }
1118
1119    /// One record per live connection, labelled by the URL as dialled; see
1120    /// [`Peer::connection_stats`].
1121    pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
1122        self.state.peer.connection_stats()
1123    }
1124
1125    /// Asks every connected respondent, and collects answers until
1126    /// `deadline`.
1127    ///
1128    /// One exchange per respondent, opened on the connection that respondent
1129    /// is on — not through the round-robin selection Req/Rep uses, which
1130    /// would ask exactly one. The deadline is the **caller's** and is not
1131    /// negotiated: nothing on the wire carries it, and a respondent never
1132    /// learns it.
1133    ///
1134    /// A survey with no respondents is not an error: it returns a
1135    /// [`SurveyRun`] whose first [`SurveyRun::next`] is `None`, because
1136    /// "nobody answered" is an answer.
1137    pub async fn survey(&self, body: &[u8], deadline: Duration) -> Result<SurveyRun, Error> {
1138        self.survey_with(TransferMeta::default(), body, deadline)
1139            .await
1140    }
1141
1142    /// Like [`Surveyor::survey`], with explicit metadata.
1143    pub async fn survey_with(
1144        &self,
1145        meta: TransferMeta,
1146        body: &[u8],
1147        deadline: Duration,
1148    ) -> Result<SurveyRun, Error> {
1149        let targets = self.state.peer.live_peers();
1150
1151        let exec = self.state.peer.exec().clone();
1152        let late = Arc::new(std::sync::atomic::AtomicU64::new(0));
1153        let expires = exec.now() + deadline;
1154        // One slot per respondent: every answer has somewhere to go, so a
1155        // reply is never late merely because the caller is slow to read.
1156        let (tx, rx) = mpsc::channel(targets.len().max(1));
1157        let mut respondents = 0usize;
1158        let mut collecting = Vec::with_capacity(targets.len());
1159
1160        for (conn, path) in targets {
1161            // The deadline bounds the **asking** too, not just the
1162            // collecting. Both of these awaits are the peer's to stall:
1163            // `open_exchange_on` waits on its stream budget and `write_all`
1164            // on its flow-control window, so without this one respondent
1165            // that accepts an exchange and stops reading would hold a
1166            // 100 ms survey open forever and every respondent after it
1167            // would never be asked at all.
1168            let remaining = expires.saturating_duration_since(exec.now());
1169            let asked = exec.within(remaining, ask(&conn, &path, &meta, body)).await;
1170            let Some(asked) = asked else {
1171                tracing::debug!(%path, "the survey deadline passed before this respondent was asked");
1172                break;
1173            };
1174            let reply = match asked {
1175                Ok(reply) => reply,
1176                // A respondent that cannot even be asked is not an answer
1177                // and not a failure of the survey: the others are still
1178                // being asked.
1179                Err(e) => {
1180                    tracing::debug!(error = %e, %path, "a respondent could not be asked");
1181                    continue;
1182                }
1183            };
1184            respondents += 1;
1185            let tx = tx.clone();
1186            let late = Arc::clone(&late);
1187            let collector_exec = exec.clone();
1188            collecting.push(exec.spawn(async move {
1189                let answer = reply.recv().await;
1190                // Counted rather than delivered, and counted **here** so the
1191                // number means "after the deadline" whatever the caller does
1192                // with its handle (`docs/GUARANTEES.md` §6).
1193                if collector_exec.now() >= expires || tx.send(answer).await.is_err() {
1194                    late.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1195                }
1196            }));
1197        }
1198        drop(tx);
1199
1200        Ok(SurveyRun {
1201            rx,
1202            exec,
1203            expires,
1204            late,
1205            respondents,
1206            collecting,
1207            done: false,
1208        })
1209    }
1210}
1211
1212/// Asks one respondent: the whole question, header to FIN.
1213///
1214/// Separate from the loop so the deadline can bound all three awaits
1215/// together — a question half-written when the deadline passes is abandoned
1216/// by dropping the transfer, which resets the stream and is exactly what a
1217/// respondent should see for a question nobody waits for any more.
1218async fn ask(
1219    conn: &ConnHandle,
1220    path: &str,
1221    meta: &TransferMeta,
1222    body: &[u8],
1223) -> Result<ReplyStream, Error> {
1224    let (mut request, reply) = crate::stream::open_exchange_on(conn, path, meta.clone()).await?;
1225    request.write_all(body).await?;
1226    request.finish()?;
1227    Ok(reply)
1228}
1229
1230/// One survey in progress: the answers, and what the deadline cost.
1231pub struct SurveyRun {
1232    rx: mpsc::Receiver<Result<IncomingTransfer, Error>>,
1233    exec: crate::runtime::Exec,
1234    expires: Instant,
1235    late: Arc<std::sync::atomic::AtomicU64>,
1236    respondents: usize,
1237    /// One collector per respondent, held so that dropping the run ends
1238    /// them: each owns a [`ReplyStream`], and therefore one of this side's
1239    /// bidirectional stream slots, until the answer arrives.
1240    collecting: Vec<tokio::task::JoinHandle<()>>,
1241    done: bool,
1242}
1243
1244impl SurveyRun {
1245    /// The next answer, or `None` once the deadline has passed or every
1246    /// respondent has answered.
1247    ///
1248    /// `max_bytes` caps the reply this call reads; nothing is buffered before
1249    /// the caller states a cap. A respondent that refused or died is one
1250    /// `Some(Err(_))` among the answers and ends nothing: the other
1251    /// respondents are independent exchanges.
1252    pub async fn next(&mut self, max_bytes: usize) -> Option<Result<Vec<u8>, Error>> {
1253        if self.done {
1254            return None;
1255        }
1256        // An answer already in hand is an answer. `within` selects without
1257        // bias, so at `remaining == 0` — a caller that reads after its own
1258        // deadline, which is the ordinary case — the deadline branch and a
1259        // ready `recv` are both ready and the choice is a coin flip. Taking
1260        // the buffer first is what keeps an answer that arrived in time from
1261        // being lost to that flip, silently and without being counted.
1262        match self.rx.try_recv() {
1263            Ok(Ok(transfer)) => return Some(transfer.collect(max_bytes).await),
1264            Ok(Err(e)) => return Some(Err(e)),
1265            Err(mpsc::error::TryRecvError::Disconnected) => {
1266                self.done = true;
1267                return None;
1268            }
1269            Err(mpsc::error::TryRecvError::Empty) => {}
1270        }
1271        let remaining = self.expires.saturating_duration_since(self.exec.now());
1272        match self.exec.within(remaining, self.rx.recv()).await {
1273            // The deadline. Anything that landed while this call was waiting
1274            // is counted here: its collector already succeeded in handing it
1275            // over, so it cannot count itself, and a dropped answer that
1276            // nothing counts is the one outcome `late` exists to prevent.
1277            None => {
1278                self.done = true;
1279                while self.rx.try_recv().is_ok() {
1280                    self.late.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1281                }
1282                None
1283            }
1284            // Every respondent has answered or failed.
1285            Some(None) => {
1286                self.done = true;
1287                None
1288            }
1289            Some(Some(Ok(transfer))) => Some(transfer.collect(max_bytes).await),
1290            Some(Some(Err(e))) => Some(Err(e)),
1291        }
1292    }
1293
1294    /// Answers that arrived after the deadline: dropped, and counted.
1295    pub fn late(&self) -> u64 {
1296        self.late.load(std::sync::atomic::Ordering::Relaxed)
1297    }
1298
1299    /// How many respondents were asked.
1300    pub fn respondents(&self) -> usize {
1301        self.respondents
1302    }
1303}
1304
1305impl Drop for SurveyRun {
1306    /// Ends the collectors with the run.
1307    ///
1308    /// A collector's first await is the answer, so a respondent that accepts
1309    /// a question and never answers would keep its task — and the
1310    /// bidirectional stream slot its [`ReplyStream`] holds — until the
1311    /// connection dies. Surveying such a respondent repeatedly would then
1312    /// exhaust this side's stream budget and the *next* survey would block
1313    /// in `open_bi`. Dropping the run is the caller saying it wants no more
1314    /// answers, so the streams go with it: each abort drops a `ReplyStream`,
1315    /// which resets that exchange.
1316    fn drop(&mut self) {
1317        for handle in &self.collecting {
1318            handle.abort();
1319        }
1320    }
1321}
1322
1323impl std::fmt::Debug for SurveyRun {
1324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1325        f.debug_struct("SurveyRun")
1326            .field("respondents", &self.respondents)
1327            .field("late", &self.late())
1328            .finish_non_exhaustive()
1329    }
1330}
1331
1332impl Respondent {
1333    /// The endpoint path this respondent serves.
1334    pub fn path(&self) -> &str {
1335        &self.state.path
1336    }
1337
1338    /// Waits for the next survey question.
1339    ///
1340    /// A question is an exchange, so this is a [`Replier::accept`] in every
1341    /// respect — the respondent needs no route of its own and no new wire
1342    /// vocabulary. What differs is only that the asker fans out and holds a
1343    /// deadline.
1344    pub async fn accept(&self) -> Result<IncomingRequest, Error> {
1345        let mut queue = self.state.queue.lock().await;
1346        queue.recv().await.ok_or(Error::NotConnected)
1347    }
1348}
1349
1350// --- BUS ------------------------------------------------------------------
1351
1352/// State of a bus member.
1353///
1354/// The one role in this library that is **bound and dialling at once**: a
1355/// member accepts on its own path and dials every other member. That is why
1356/// its factory takes both a path and dialling terms, and why nothing else
1357/// does.
1358pub struct BusState {
1359    peer: Peer,
1360    path: Arc<str>,
1361    queue: Mutex<mpsc::Receiver<IncomingTransfer>>,
1362    /// One writer per joined member, so a member that stops reading stalls
1363    /// **its own** queue rather than the sender's task. This is Pub/Sub's
1364    /// shape for the same reason: a fan-out that can be blocked by one slow
1365    /// peer is not a fan-out (`docs/GUARANTEES.md` §6).
1366    writers: std::sync::Mutex<Vec<BusWriter>>,
1367    /// Copies that never reached a member, by the same rule Pub/Sub uses:
1368    /// best effort per peer, counted rather than retried.
1369    dropped: Arc<std::sync::atomic::AtomicU64>,
1370    /// Messages one member's writer may hold.
1371    depth: usize,
1372    /// Bytes one member's writer may hold, `Limits::subscriber_buffer_bytes`.
1373    ///
1374    /// The message count alone bounds nothing: a bus send costs
1375    /// `depth × body.len()` per member and multiplies by the members, and
1376    /// `body.len()` is the application's number. This is the second
1377    /// dimension Pub/Sub already charges per subscriber, for the identical
1378    /// fan-out (`docs/INVARIANTS.md`).
1379    budget: usize,
1380}
1381
1382/// One joined member's writer queue.
1383struct BusWriter {
1384    tx: mpsc::Sender<BusMsg>,
1385    /// This member's share of the byte budget, returned by its writer once
1386    /// the bytes are on the wire.
1387    budget: Arc<Semaphore>,
1388}
1389
1390/// One message on its way to one member.
1391///
1392/// The payload is a `Bytes`: a bus send makes **one** copy of the body and
1393/// every member's queue holds a reference to it, which is what Pub/Sub does
1394/// with a published payload and for the same reason — a copy per member is
1395/// the one cost a fan-out must not pay per member.
1396struct BusMsg {
1397    meta: TransferMeta,
1398    body: Bytes,
1399}
1400
1401impl BusState {
1402    pub(crate) fn new(
1403        path: &str,
1404        runtime: Arc<RuntimeInner>,
1405        tls: Arc<ClientTls>,
1406        queue: mpsc::Receiver<IncomingTransfer>,
1407        depth: usize,
1408        budget: usize,
1409    ) -> BusState {
1410        BusState {
1411            peer: Peer::new(runtime, tls),
1412            path: Arc::from(path),
1413            queue: Mutex::new(queue),
1414            writers: std::sync::Mutex::new(Vec::new()),
1415            dropped: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1416            depth,
1417            budget,
1418        }
1419    }
1420}
1421
1422impl BusMember {
1423    /// The path this member accepts on.
1424    pub fn path(&self) -> &str {
1425        &self.state.path
1426    }
1427
1428    /// Joins another member.
1429    ///
1430    /// Joining is an ordinary connect and leaving an ordinary disconnect:
1431    /// there is no membership protocol, no election and nothing to
1432    /// synchronize, which is what keeps a bus a fan-out rather than a group.
1433    ///
1434    /// One writer task per member is started here, which is what makes a
1435    /// slow member cost its own copies rather than the sender's time.
1436    pub async fn connect(&self, url: &str) -> Result<(), Error> {
1437        let (conn, path) = self.state.peer.dial(url).await?;
1438        let (tx, rx) = mpsc::channel(self.state.depth);
1439        let budget = Arc::new(Semaphore::new(self.state.budget));
1440        conn.exec.spawn(bus_writer(
1441            conn.clone(),
1442            path,
1443            rx,
1444            Arc::clone(&budget),
1445            Arc::clone(&self.state.dropped),
1446        ));
1447        self.state
1448            .writers
1449            .lock()
1450            .expect("bus writers poisoned")
1451            .push(BusWriter { tx, budget });
1452        Ok(())
1453    }
1454
1455    /// Number of members this one has joined.
1456    pub fn peer_count(&self) -> usize {
1457        self.state.peer.peer_count()
1458    }
1459
1460    /// One record per member this one has dialled and is connected to,
1461    /// labelled by the URL as dialled; see [`Peer::connection_stats`].
1462    pub fn connection_stats(&self) -> Vec<crate::ConnectionStats> {
1463        self.state.peer.connection_stats()
1464    }
1465
1466    /// Sends `body` to every **other** member, returning how many it reached.
1467    ///
1468    /// A message never reaches the sender: structurally, because `send`
1469    /// writes to the peers this member dialled and a member does not dial
1470    /// itself. There is also **no relay** — a bus of *n* members is
1471    /// *n* × (*n* − 1) deliveries, and weida forwards on nobody's behalf,
1472    /// which is the trade nanomsg's BUS makes too.
1473    ///
1474    /// Fan-out is best effort per peer with the same counted drops as Pub/Sub
1475    /// ([`BusMember::dropped`]): one member that cannot take a copy costs
1476    /// that copy, not the send.
1477    pub async fn send(&self, body: &[u8]) -> Result<usize, Error> {
1478        self.send_with(TransferMeta::default(), body).await
1479    }
1480
1481    /// Like [`BusMember::send`], with explicit metadata.
1482    ///
1483    /// "Reached" means accepted for delivery to that member, which is what
1484    /// [`Publisher::publish`] counts too: the bytes are on their way, and a
1485    /// member whose writer queue is full — in messages or in bytes — loses
1486    /// **this** copy and is counted in [`BusMember::dropped`].
1487    ///
1488    /// Fails with [`Error::LimitExceeded`] for a body above
1489    /// `Limits::subscriber_buffer_bytes`, exactly as [`Publisher::publish`]
1490    /// does: such a message could never be enqueued for anybody, so
1491    /// reporting it beats dropping it for every member.
1492    pub async fn send_with(&self, meta: TransferMeta, body: &[u8]) -> Result<usize, Error> {
1493        if body.len() > self.state.budget {
1494            return Err(Error::LimitExceeded);
1495        }
1496        // One copy for the whole fan-out. Each member's queue then holds a
1497        // reference to it rather than a `Vec` of its own.
1498        let body = Bytes::copy_from_slice(body);
1499        let want = body.len() as u32;
1500        let mut reached = 0usize;
1501        let mut dropped = 0u64;
1502        {
1503            let mut writers = self.state.writers.lock().expect("bus writers poisoned");
1504            writers.retain(|writer| !writer.tx.is_closed());
1505            for writer in writers.iter() {
1506                let Ok(permit) = writer.budget.try_acquire_many(want) else {
1507                    dropped += 1;
1508                    continue;
1509                };
1510                let msg = BusMsg {
1511                    meta: meta.clone(),
1512                    body: body.clone(),
1513                };
1514                match writer.tx.try_send(msg) {
1515                    Ok(()) => {
1516                        // The writer returns the permits once the bytes are
1517                        // gone; dropping one here would return them while
1518                        // the copy is still queued.
1519                        permit.forget();
1520                        reached += 1;
1521                    }
1522                    Err(_) => dropped += 1,
1523                }
1524            }
1525        }
1526        if dropped > 0 {
1527            tracing::debug!(dropped, "a bus member could not take a copy");
1528            self.state
1529                .dropped
1530                .fetch_add(dropped, std::sync::atomic::Ordering::Relaxed);
1531        }
1532        Ok(reached)
1533    }
1534
1535    /// Waits for the next message from another member.
1536    pub async fn recv(&self) -> Result<IncomingTransfer, Error> {
1537        let mut queue = self.state.queue.lock().await;
1538        queue.recv().await.ok_or(Error::NotConnected)
1539    }
1540
1541    /// Copies that never reached a member.
1542    pub fn dropped(&self) -> u64 {
1543        self.state
1544            .dropped
1545            .load(std::sync::atomic::Ordering::Relaxed)
1546    }
1547}
1548
1549/// Serializes one member's copies, so a member that stops reading stalls only
1550/// its own queue.
1551///
1552/// A copy that fails on the wire is **counted here**, not silently lost: the
1553/// writer ends — which is what makes `send_with` prune this member on its
1554/// next call — and the copy it was carrying shows up in
1555/// [`BusMember::dropped`], exactly as Pub/Sub's writer counts a copy no
1556/// parked connection could take.
1557async fn bus_writer(
1558    conn: ConnHandle,
1559    path: Arc<str>,
1560    mut rx: mpsc::Receiver<BusMsg>,
1561    budget: Arc<Semaphore>,
1562    dropped: Arc<std::sync::atomic::AtomicU64>,
1563) {
1564    loop {
1565        let msg = tokio::select! {
1566            msg = rx.recv() => match msg {
1567                Some(msg) => msg,
1568                None => return,
1569            },
1570            // The sender holds this writer's channel for the life of the
1571            // endpoint, so the channel never closes on its own: without this
1572            // arm a member whose connection died would park here forever
1573            // holding an `Arc<ConnCtx>`, which is the same reason the
1574            // fan-out's writer watches its connection.
1575            _ = conn.conn.closed() => {
1576                dropped.fetch_add(rx.len() as u64, std::sync::atomic::Ordering::Relaxed);
1577                return;
1578            }
1579        };
1580        let len = msg.body.len();
1581        let outcome = send_one(&conn, &path, msg.meta, &msg.body).await;
1582        // Returned whatever happened: the copy is no longer queued, so the
1583        // bytes it held against this member are free either way.
1584        budget.add_permits(len);
1585        if let Err(e) = outcome {
1586            tracing::debug!(error = %e, %path, "a bus write failed; copy dropped");
1587            // This copy plus whatever was still queued for the member: a
1588            // member that died is dropped from the set without affecting the
1589            // others, and what it owed is counted rather than forgotten.
1590            dropped.fetch_add(1 + rx.len() as u64, std::sync::atomic::Ordering::Relaxed);
1591            return;
1592        }
1593    }
1594}
1595
1596/// Writes one whole one-way transfer on `conn`.
1597async fn send_one(
1598    conn: &ConnHandle,
1599    path: &str,
1600    meta: TransferMeta,
1601    body: &[u8],
1602) -> Result<(), Error> {
1603    let mut transfer = crate::stream::open_transfer_on(conn, path, &meta).await?;
1604    transfer.write_all(body).await?;
1605    transfer.finish()?;
1606    Ok(())
1607}