weida 0.1.0-alpha.14

QUIC-native messaging framework: runtime, native QUIC transport, Req/Rep, Push/Pull, Pub/Sub, PAIR, SURVEY and BUS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Client connection pool.
//!
//! One QUIC endpoint per runtime and **one connection per dialled endpoint
//! path** ([decisions/0002](../../../docs/decisions/0002-control-and-bulk-separation.md)
//! §6.2). The path is part of the key, so a slow reader on one path cannot
//! stall a writer on another: they share no connection and therefore no
//! receive window, which is the only isolation QUIC actually gives
//! (`docs/PATTERNS.md` §1.3).
//!
//! The rest of the key is the authority as written, the trust configuration
//! and the fingerprint the address named, rather than the resolved address:
//! the TLS server name comes from the same string, so two spellings of one
//! address are genuinely different peers as far as authentication is
//! concerned.
//!
//! **The connections of one peer are bound together by the proved
//! fingerprint, and by nothing else**
//! ([decisions/0008](../../../docs/decisions/0008-session-identity.md) §4.2).
//! Dialling a second path is dialling the same peer, so the pool checks that
//! the peer that answers is the one that answered before and refuses the
//! connection otherwise — the load-balancer case, where two dials to one
//! authority reach two different servers.

use std::collections::HashMap;
use std::sync::Arc;

use quinn::VarInt;
use tokio::sync::Mutex;
use weida_core::{EndpointAddr, Error, Fingerprint, Limits, RelayAddr};
use weida_protocol::codes;

use crate::config::{ClientTls, Discovery, RuntimeConfig};
use crate::conn::{ConnCtx, ConnHandle, conn_error};
use crate::listener::Namespace;
use crate::runtime::{Exec, Shared};
use crate::tls;
use crate::transport::{Link, QuicLink};

/// The port a dial uses, and the refusal a `Single` runtime owes a portless
/// URL.
///
/// Separated out so the rule is testable without a socket: it is the whole of
/// [0020](../../../docs/decisions/0020-cluster-and-discovery.md) §4.2's client
/// half.
fn dial_port(written: Option<u16>, discovery: Discovery, host: &str) -> Result<u16, Error> {
    match (written, discovery) {
        (Some(port), _) => Ok(port),
        (None, Discovery::Aware) => Ok(weida_core::DEFAULT_PORT),
        (None, Discovery::Single) => Err(Error::InvalidAddress(format!(
            "{host} names no port, which means a set of nodes, and this runtime is \
             configured `Discovery::Single`: write the port, or allow discovery"
        ))),
    }
}

pub(crate) struct ClientPool {
    /// Shared with each connection's reaper, which holds it weakly.
    state: Arc<Mutex<PoolState>>,
    /// Handed to every connection this pool dials; owned by the runtime.
    shared: Arc<Shared>,
}

/// How a connection reaches its peer: directly, or through the relay whose
/// key the address named, if it named one.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Hop {
    Direct,
    Relay(Option<Fingerprint>),
}

/// Which **peer** a connection belongs to: authority, trust configuration,
/// the fingerprint the address named, and the hop. Two endpoints dialling
/// the same `host:port` on different terms are not the same peer — one was
/// authenticated on one set of terms, not both — and a peer reached through
/// a relay at `host:port` is not the relay.
type PeerKey = (String, u16, Arc<ClientTls>, Option<Fingerprint>, Hop);

/// Which **connection**: a peer plus the endpoint path it was dialled for.
type ConnKey = (PeerKey, String);

#[derive(Default)]
struct PoolState {
    endpoint: Option<quinn::Endpoint>,
    connections: HashMap<ConnKey, ConnHandle>,
}

impl ClientPool {
    pub(crate) fn new(shared: Arc<Shared>) -> ClientPool {
        ClientPool {
            state: Arc::new(Mutex::new(PoolState::default())),
            shared,
        }
    }

    /// Removes and returns the client endpoint, for shutdown.
    pub(crate) async fn take_endpoint(&self) -> Option<quinn::Endpoint> {
        let mut state = self.state.lock().await;
        state.connections.clear();
        state.endpoint.take()
    }

    /// Returns a live connection to `path` on `host:port`, authenticated on
    /// `tls`'s terms — and, when the address named one, as `expected` —
    /// dialling if necessary.
    ///
    /// One connection per path: two paths on one peer never share a
    /// connection, so neither can stall the other. The returned handle has
    /// completed the HELLO exchange, so callers never have to think about
    /// negotiation, and the peer it proved has been checked against the
    /// identity this peer proved on its other connections.
    ///
    /// A new connection is dialled with `limits`: the runtime's, or a
    /// swarm's with larger receive windows. They are not part of the key,
    /// because only a swarm dials a seeder's path, so one key is always
    /// dialled with the same limits.
    pub(crate) async fn connect(
        &self,
        config: &RuntimeConfig,
        limits: &Limits,
        exec: &Exec,
        addr: &EndpointAddr,
        tls: &Arc<ClientTls>,
    ) -> Result<ConnHandle, Error> {
        let EndpointAddr {
            host,
            port,
            path,
            peer: expected,
        } = addr;
        let (host, expected) = (host.as_str(), *expected);
        // A portless authority is a set (0020 §4.2); which port that set
        // listens on is not a guess but a constant, and whether a set is
        // allowed at all is the runtime's configuration.
        let written_port = *port;
        let port = dial_port(written_port, config.discovery, host)?;
        let peer: PeerKey = (
            host.to_owned(),
            port,
            Arc::clone(tls),
            expected,
            Hop::Direct,
        );
        let key: ConnKey = (peer.clone(), path.clone());
        // What the pool has to say is read under the lock and the lock is
        // then **released for the dial**. Holding it across name resolution,
        // the handshake attempts and the HELLO exchange — seconds of a
        // peer's choosing — serialized every dial in the process against
        // every other, and made `Runtime::close`, which takes this same
        // lock to retire the client endpoint, wait on a peer: 0009 §4.4
        // forbids exactly that.
        //
        // The cost of releasing it is that two dials for one key can both
        // build a connection. That race is settled below, where the loser
        // closes its own and returns the winner's, and it costs one extra
        // handshake rather than a lock that spans the network.
        let (endpoint, known) = {
            let mut state = self.state.lock().await;
            if let Some(existing) = state.connections.get(&key) {
                if existing.conn.close_reason().is_none() {
                    return Ok(ConnHandle::clone(existing));
                }
                state.connections.remove(&key);
            }
            // A connection whose key is never dialled again would otherwise
            // be retained forever, and with it its namespace, its dedup
            // window, its reorder hold and its driver task.
            state
                .connections
                .retain(|_, handle| handle.conn.close_reason().is_none());
            let endpoint = match &state.endpoint {
                Some(endpoint) => endpoint.clone(),
                None => {
                    let endpoint = config.network.bind_client(exec)?;
                    state.endpoint = Some(endpoint.clone());
                    endpoint
                }
            };
            (endpoint, state.peer_identity(&peer))
        };

        let (client_config, refused) = tls::client_config(tls, expected, limits)?;

        let addrs = config
            .resolver
            .resolve(exec, host, written_port, config.max_resolved_addresses)
            .await?;
        // Every address, in the resolver's order, until one answers. The first
        // is not necessarily reachable: `localhost` commonly resolves to `::1`
        // and `127.0.0.1`, and a server bound to one of them refuses the
        // other. The last error is what the caller sees when none answer,
        // because it is the one that describes the last thing tried.
        let mut last: Option<Error> = None;
        let mut established = None;
        for (index, addr) in addrs.iter().enumerate() {
            let is_last = index + 1 == addrs.len();
            tracing::debug!(%addr, host, is_last, "dialling");
            let connecting = {
                // Inside the runtime context: `quinn` reads its own runtime
                // out of the ambient reactor while it builds the attempt.
                let _guard = exec.enter();
                match endpoint.connect_with(client_config.clone(), *addr, host) {
                    Ok(connecting) => connecting,
                    Err(e) => {
                        last = Some(Error::Transport(format!("connect to {addr} failed: {e}")));
                        continue;
                    }
                }
            };
            // The handshake is driven *on* the runtime rather than by whoever
            // awaits `connect`: completing it spawns the connection driver,
            // and the caller's executor need not be tokio. Awaiting the join
            // handle needs nothing.
            let attempt = exec.spawn(connecting);
            // Every address but the last is bounded: an address that answers
            // nothing gives QUIC no refusal to observe, so an unbounded
            // attempt on an unreachable `::1` would reach `127.0.0.1` only
            // after a full handshake timeout. The last one keeps the whole
            // budget, which is also what an IP literal and a single-address
            // name get
            // (`RuntimeConfig::connect_attempt_timeout`, RFC 8305's
            // Connection Attempt Delay).
            let joined = if is_last {
                Some(attempt.await)
            } else {
                exec.within(config.connect_attempt_timeout, attempt).await
            };
            let handshake = match joined {
                Some(joined) => {
                    joined.map_err(|e| Error::Runtime(format!("dial task failed: {e}")))?
                }
                None => {
                    last = Some(Error::Transport(format!(
                        "connect to {addr} did not answer within {:?}",
                        config.connect_attempt_timeout
                    )));
                    continue;
                }
            };
            match handshake {
                Ok(conn) => {
                    established = Some(conn);
                    break;
                }
                Err(e) => {
                    // The verifier saw the peer before the handshake died:
                    // report who answered, so the operator can decide whether
                    // to pin it. A refusal is about *this* peer's key and is
                    // not retried against another address.
                    let refused = refused.lock().expect("refusal record poisoned").take();
                    if let Some(presented) = refused {
                        return Err(Error::Untrusted(presented));
                    }
                    last = Some(conn_error(e));
                }
            }
        }
        let conn = match established {
            Some(conn) => conn,
            None => {
                return Err(last.unwrap_or_else(|| {
                    Error::InvalidAddress(format!("{host}:{port} resolved to no addresses"))
                }));
            }
        };
        self.adopt(config, limits, exec, key, known, conn).await
    }

    /// Makes a dialled QUIC connection a pooled one: checks the identity it
    /// proved against this peer's live connections (`known`), runs the
    /// HELLO exchange, settles the race for `key`, and starts its reaper.
    async fn adopt(
        &self,
        config: &RuntimeConfig,
        limits: &Limits,
        exec: &Exec,
        key: ConnKey,
        known: Option<Option<Fingerprint>>,
        conn: quinn::Connection,
    ) -> Result<ConnHandle, Error> {
        // The connections of one peer are bound together by the proved
        // fingerprint and by nothing else (0008 §4.2). Dialling a second path
        // is dialling the same peer, so a connection that proved a different
        // identity than this peer's *live* connections is not this peer: it
        // is a second server behind one authority, and serving a transfer on
        // it would mean talking to somebody the caller never asked for.
        //
        // The comparison is against live connections rather than a remembered
        // fingerprint, because a peer is this peer only while a connection to
        // it lives: once the last one is gone, a replacement server with a new
        // key is a new peer and nothing should still be objecting to it.
        let presented = crate::tls::peer_fingerprint(&conn);
        if let Some(known) = known
            && known != presented
        {
            conn.close(
                VarInt::from_u32(codes::SHUTDOWN as u32),
                b"peer identity differs from this peer's other connections",
            );
            // `Untrusted` carries who answered, which is the fingerprint an
            // operator needs to decide whether to pin it. An anonymous answer
            // cannot be reported that way, and cannot be bound to anything
            // either.
            return Err(match presented {
                Some(fp) => Error::Untrusted(fp),
                None => Error::Tls(
                    "the peer that answered proved no identity, so it cannot be the peer this \
                     runtime is already connected to"
                        .into(),
                ),
            });
        }

        // A fresh namespace per client connection: a subscriber registers its
        // path here so fanned-out copies have somewhere to go. It is not the
        // listener's namespace — a client serves nothing on its own account.
        let handle = ConnCtx::spawn(
            Link::Quic(QuicLink::new(conn)),
            *limits,
            Arc::new(Namespace::new()),
            None,
            exec.clone(),
            config.guarantees,
            Arc::clone(&self.shared),
        );
        // The connection must be established before the caller can send
        // anything: a DATA frame ahead of our own HELLO would be parked by
        // the peer, and a version mismatch must fail `connect`, not the first
        // request.
        handle.established().await?;

        // The race the released lock allows, settled: whoever inserted first
        // owns the key, and this connection is closed rather than left open
        // for nobody. Both sides then hand their caller the same connection,
        // which is what a pool is for.
        let mut state = self.state.lock().await;
        let winner = state
            .connections
            .get(&key)
            .filter(|held| held.conn.close_reason().is_none())
            .map(ConnHandle::clone);
        if let Some(winner) = winner {
            handle
                .conn
                .close(codes::SHUTDOWN, "a concurrent dial won this pool key");
            return Ok(winner);
        }
        state
            .connections
            .insert(key.clone(), ConnHandle::clone(&handle));
        drop(state);
        exec.spawn(reap(
            Arc::downgrade(&self.state),
            key,
            Arc::downgrade(&handle),
            Arc::clone(&handle.conn),
            exec.clone(),
            limits.idle_timeout,
        ));
        Ok(handle)
    }

    /// Returns a live connection to `addr.path` on the peer whose key is
    /// `addr.target`, reached through the relay `addr.relay`
    /// (`docs/PROTOCOL.md` §9.6), dialling if necessary.
    ///
    /// The hop to the relay is an ordinary pooled connection, one per relay
    /// and terms; on it each relayed connection has a tunnel, and an inner
    /// `quinn` endpoint of its own runs QUIC and TLS end to end with the
    /// target through it. The tunnel ends when the inner connection closes.
    pub(crate) async fn connect_relayed(
        &self,
        config: &RuntimeConfig,
        limits: &Limits,
        exec: &Exec,
        addr: &RelayAddr,
        tls: &Arc<ClientTls>,
    ) -> Result<ConnHandle, Error> {
        let relay = &addr.relay;
        let port = dial_port(relay.port, config.discovery, &relay.host)?;
        let peer: PeerKey = (
            relay.host.clone(),
            port,
            Arc::clone(tls),
            Some(addr.target),
            Hop::Relay(relay.peer),
        );
        let key: ConnKey = (peer.clone(), addr.path.clone());
        let known = {
            let mut state = self.state.lock().await;
            if let Some(existing) = state.connections.get(&key) {
                if existing.conn.close_reason().is_none() {
                    return Ok(ConnHandle::clone(existing));
                }
                state.connections.remove(&key);
            }
            state.peer_identity(&peer)
        };

        let hop = self
            .connect(config, &config.limits, exec, relay, tls)
            .await?;
        let socket = crate::relay::open_tunnel(&hop, addr.target).await?;
        let tunnel = Arc::clone(&socket);
        let dialled = async {
            let endpoint = {
                let _guard = exec.enter();
                quinn::Endpoint::new_with_abstract_socket(
                    quinn::EndpointConfig::default(),
                    None,
                    socket as Arc<dyn quinn::AsyncUdpSocket>,
                    crate::network::quic_runtime()?,
                )
                .map_err(Error::Io)?
            };
            let (client_config, refused) = tls::client_config(tls, Some(addr.target), limits)?;
            let connecting = {
                let _guard = exec.enter();
                endpoint
                    .connect_with(client_config, crate::relay::tunnel_addr(0), &relay.host)
                    .map_err(|e| {
                        Error::Transport(format!("connect through the relay failed: {e}"))
                    })?
            };
            let handshake = exec
                .spawn(connecting)
                .await
                .map_err(|e| Error::Runtime(format!("dial task failed: {e}")))?;
            match handshake {
                Ok(conn) => Ok((endpoint, conn)),
                Err(e) => {
                    let refused = refused.lock().expect("refusal record poisoned").take();
                    Err(match refused {
                        Some(presented) => Error::Untrusted(presented),
                        None => conn_error(e),
                    })
                }
            }
        }
        .await;
        let (endpoint, conn) = match dialled {
            Ok(dialled) => dialled,
            Err(e) => {
                tunnel.end();
                return Err(e);
            }
        };
        // The tunnel is a use of the hop until the inner connection closes;
        // the endpoint lives exactly as long.
        let closed = conn.clone();
        exec.spawn(async move {
            closed.closed().await;
            tunnel.end();
            drop(endpoint);
        });
        self.adopt(config, limits, exec, key, known, conn).await
    }
}

/// How many looks a reaper takes per linger: an unused connection closes
/// between one linger and one linger plus this fraction of it after its last
/// user went.
const REAP_LOOKS: u32 = 8;

/// Closes the pooled connection `key` once nothing but the pool has held it
/// for `linger` (`Limits::idle_timeout`): no endpoint slot, no transfer, no
/// receipt, no stream ([B-383](../../../docs/BACKLOG.md), the owner's
/// option (b)). The linger keeps it for an endpoint created again right
/// away, as a redialling client does.
///
/// The pool's map holds one handle, so a strong count of one is "unused".
/// The count is read under the pool's lock, and every other handle is cloned
/// from one that already exists or from the map under that lock, so no
/// caller can take the connection between the look and the close. Nothing
/// the connection runs for itself holds a strong handle (accept loops,
/// HELLO deadline, path reports, the datagram reader): those are not uses.
async fn reap(
    state: std::sync::Weak<Mutex<PoolState>>,
    key: ConnKey,
    conn: std::sync::Weak<ConnCtx>,
    link: Arc<Link>,
    exec: Exec,
    linger: std::time::Duration,
) {
    let look = (linger / REAP_LOOKS).max(std::time::Duration::from_millis(1));
    let mut unused = std::time::Duration::ZERO;
    loop {
        tokio::select! {
            () = exec.sleep(look) => {}
            _ = link.closed() => return,
        }
        let Some(state) = state.upgrade() else { return };
        let mut state = state.lock().await;
        let Some(held) = state.connections.get(&key) else {
            return;
        };
        // The key may name a newer connection after this one closed.
        if !std::ptr::eq(Arc::as_ptr(held), conn.as_ptr()) {
            return;
        }
        if Arc::strong_count(held) > 1 {
            unused = std::time::Duration::ZERO;
            continue;
        }
        unused += look;
        if unused >= linger {
            let held = state.connections.remove(&key);
            drop(state);
            tracing::debug!(host = %key.0.0, path = %key.1, "closing an unused pooled connection");
            if let Some(held) = held {
                held.conn.close(codes::SHUTDOWN, "unused");
            }
            return;
        }
    }
}

impl PoolState {
    /// The identity this peer's live connections proved, if it has any.
    ///
    /// `Some(None)` is a peer whose live connections proved nothing at all
    /// and is a real answer, distinct from `None` — no live connection, so
    /// nothing to be consistent with.
    fn peer_identity(&self, peer: &PeerKey) -> Option<Option<Fingerprint>> {
        self.connections
            .iter()
            .find(|((p, _), handle)| p == peer && handle.conn.close_reason().is_none())
            // The pool is a QUIC structure, and what it compares is the key
            // the peer proved; a local principal never reaches it.
            .map(|(_, handle)| handle.peer.as_ref().and_then(|id| id.key()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Claim: a written port is used as written, a portless authority is the
    /// discovery form and dials `DEFAULT_PORT`, and a `Single` runtime
    /// **refuses** the portless form rather than resolving it — 0020 §4.2's
    /// client half.
    #[test]
    fn the_dial_port_follows_the_url_then_the_discovery_mode() {
        assert_eq!(
            dial_port(Some(9000), Discovery::Aware, "h").expect("written"),
            9000
        );
        assert_eq!(
            dial_port(Some(9000), Discovery::Single, "h").expect("written"),
            9000,
            "a written port is never overridden by the mode"
        );
        assert_eq!(
            dial_port(None, Discovery::Aware, "jobs.example").expect("discovered"),
            weida_core::DEFAULT_PORT
        );

        let refused = dial_port(None, Discovery::Single, "jobs.example")
            .expect_err("a set is not one endpoint");
        let message = refused.to_string();
        assert!(
            message.contains("jobs.example") && message.contains("Discovery::Single"),
            "the refusal names the host and the reason: {message}"
        );
    }
}