unb-server 2.0.0

unb inbound server: Node, request/subscribe handlers, catalog, relay orchestration, accept
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
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use unb_client::{Endpoint, EndpointSet};
use unb_runtime::WsError;

use crate::connection::{ConnectError, PeerConnection};
use crate::node::{Node, PeerLink};
use crate::session::{CandidateFailure, CandidateOutcome, CandidateSession};

/// Supplies a transport for one already-ordered endpoint candidate.
///
/// This specialist hook lets platform bindings retain the server's connection
/// lifecycle while constructing transports in their native runtime.
#[doc(hidden)]
pub trait EndpointDialer: Send + Sync {
    fn supports(&self, kind: unb_client::TransportKind) -> bool;

    fn dial(
        &self,
        endpoint: Endpoint,
    ) -> Pin<Box<dyn Future<Output = Result<unb_runtime::Pipe, WsError>> + Send + 'static>>;
}

pub(crate) struct ReconnectCandidate {
    pub(crate) identity: unb_core::NodeIdentity,
    pub(crate) selected: PeerLink,
    pub(crate) candidate_wire: Arc<unb_runtime::Wire>,
}

impl Node {
    /// Eagerly dial, verify the peer, and synchronize its routes.
    ///
    /// The returned logical connection is retained by the node and automatically
    /// maintains an unintentionally lost selected session.
    pub async fn connect(
        self: &Arc<Self>,
        endpoints: impl Into<EndpointSet>,
    ) -> Result<PeerConnection, ConnectError> {
        self.connect_using(endpoints.into(), None, None).await
    }

    #[cfg(feature = "hosting")]
    pub(crate) async fn connect_expected(
        self: &Arc<Self>,
        endpoints: impl Into<EndpointSet>,
        expected_peer: &str,
    ) -> Result<PeerConnection, ConnectError> {
        self.connect_using(endpoints.into(), None, Some(expected_peer))
            .await
    }

    /// Connect using a platform-owned transport constructor.
    ///
    /// Endpoint ordering, establishment, identity verification, route sync,
    /// logical-handle convergence, and reconnect coordination remain owned by
    /// the server. Only construction of each candidate transport is delegated.
    #[doc(hidden)]
    pub async fn connect_with_dialer(
        self: &Arc<Self>,
        endpoints: impl Into<EndpointSet>,
        dialer: Arc<dyn EndpointDialer>,
    ) -> Result<PeerConnection, ConnectError> {
        self.connect_using(endpoints.into(), Some(dialer), None)
            .await
    }

    async fn connect_using(
        self: &Arc<Self>,
        set: EndpointSet,
        dialer: Option<Arc<dyn EndpointDialer>>,
        expected_peer: Option<&str>,
    ) -> Result<PeerConnection, ConnectError> {
        let key = set.cache_key();
        let ordered = self
            .dial_policy
            .ordered_candidates(&key, &set)
            .into_iter()
            .filter(|endpoint| {
                dialer
                    .as_ref()
                    .is_none_or(|dialer| dialer.supports(endpoint.kind))
            })
            .collect::<Vec<_>>();
        if ordered.is_empty() {
            return Err(ConnectError::NoSupportedEndpoint);
        }
        let mut last_error = ConnectError::NoSupportedEndpoint;
        for endpoint in ordered {
            match self
                .try_candidate(&endpoint, expected_peer, dialer.as_ref())
                .await
            {
                Ok((candidate, outcome)) => {
                    let identity = match outcome {
                        CandidateOutcome::Promoted(identity)
                        | CandidateOutcome::Duplicate(identity) => identity,
                    };
                    let Some(link) = self.peer(&identity.node_id).await else {
                        candidate.wire.shutdown();
                        let _ = candidate.cleaned.await;
                        last_error = ConnectError::Establishment {
                            message: format!(
                                "verified peer {:?} has no selected live session",
                                identity.node_id
                            ),
                        };
                        continue;
                    };
                    if n0_future::time::timeout(
                        crate::session::ROUTE_SYNC_TIMEOUT,
                        self.wait_for_selected_route(&identity.node_id, &link.session_id),
                    )
                    .await
                    .is_err()
                    {
                        candidate.wire.shutdown();
                        let _ = candidate.cleaned.await;
                        last_error = ConnectError::Establishment {
                            message: format!(
                                "verified peer {:?} did not publish its synchronized node route",
                                identity.node_id
                            ),
                        };
                        continue;
                    }
                    let connection = {
                        let mut connections = self
                            .connections
                            .write()
                            .unwrap_or_else(|poisoned| poisoned.into_inner());
                        if let Some(connection) = connections
                            .get(&identity.node_id)
                            .filter(|connection| !connection.is_terminal())
                            .cloned()
                        {
                            if connection.bind(
                                identity.clone(),
                                link.session_id.clone(),
                                link.wire.clone(),
                            ) {
                                connection.replace_endpoints(set.clone());
                                connection.replace_dialer(dialer.clone());
                                connection
                            } else {
                                let connection = PeerConnection::new(
                                    Arc::downgrade(self),
                                    identity.clone(),
                                    set.clone(),
                                    link.session_id.clone(),
                                    link.wire.clone(),
                                    dialer.clone(),
                                );
                                connections.insert(identity.node_id, connection.clone());
                                connection
                            }
                        } else {
                            let connection = PeerConnection::new(
                                Arc::downgrade(self),
                                identity.clone(),
                                set.clone(),
                                link.session_id.clone(),
                                link.wire.clone(),
                                dialer.clone(),
                            );
                            connections.insert(identity.node_id, connection.clone());
                            connection
                        }
                    };
                    self.dial_policy.record_winner(&key, endpoint.kind);
                    return Ok(connection);
                }
                Err(error) => last_error = error,
            }
        }
        Err(last_error)
    }

    async fn wait_for_selected_route(&self, peer: &str, session_id: &str) {
        let mut changes = self.route_changes();
        loop {
            let selected_session = self.peer(peer).await.map(|selected| selected.session_id);
            let direct_route = matches!(
                self.snapshot.load().node_core.resolve(peer),
                unb_core::Resolution::Route(next_hop) if next_hop == peer
            );
            if selected_session.as_deref() == Some(session_id) && direct_route {
                return;
            }
            if changes.changed().await.is_err() {
                return;
            }
        }
    }

    /// Wait until a directly linked peer is both selectable and routable.
    ///
    /// A link's transport handshake can finish before its first route snapshot
    /// is applied. `link` promises immediate request readiness, so it must wait
    /// for this local publication rather than merely for the handshake ACK.
    async fn wait_for_direct_peer_route(&self, peer: &str) {
        let mut changes = self.route_changes();
        loop {
            let selected = self.peer(peer).await.is_some();
            let direct_route = matches!(
                self.snapshot.load().node_core.resolve(peer),
                unb_core::Resolution::Route(next_hop) if next_hop == peer
            );
            if selected && direct_route {
                return;
            }
            if changes.changed().await.is_err() {
                return;
            }
        }
    }

    async fn try_candidate(
        self: &Arc<Self>,
        endpoint: &Endpoint,
        expected_peer: Option<&str>,
        dialer: Option<&Arc<dyn EndpointDialer>>,
    ) -> Result<(CandidateSession, CandidateOutcome), ConnectError> {
        let deadline = self.dial_policy.attempt_timeout();
        let candidate_dial = async {
            match dialer {
                Some(dialer) => dialer.dial(endpoint.clone()).await,
                None => self.dial_policy.dial_candidate(endpoint).await,
            }
        };
        let pipe = match n0_future::time::timeout(deadline, candidate_dial).await {
            Ok(Ok(pipe)) => pipe,
            Ok(Err(error)) => {
                return Err(ConnectError::Dial {
                    transport: endpoint.kind,
                    message: error.to_string(),
                })
            }
            Err(_) => {
                return Err(ConnectError::DialTimedOut {
                    transport: endpoint.kind,
                })
            }
        };
        let candidate = self.establish(pipe, expected_peer.map(str::to_owned)).await;
        let outcome = candidate.observed_outcome().await;
        match outcome {
            Ok(outcome) => Ok((candidate, outcome)),
            Err(failure) => {
                candidate.wire.shutdown();
                let _ = candidate.cleaned.await;
                Err(match (expected_peer, failure) {
                    (
                        Some(expected),
                        CandidateFailure::Retired {
                            reason: unb_core::RetirementReason::UnexpectedPeer,
                            identity,
                        },
                    ) => ConnectError::IdentityMismatch {
                        expected: expected.to_string(),
                        actual: identity.map(|identity| identity.node_id),
                    },
                    (_, CandidateFailure::Session(error)) => ConnectError::Establishment {
                        message: error.to_string(),
                    },
                    (_, CandidateFailure::Retired { reason, .. }) => ConnectError::Establishment {
                        message: format!("session retired during establishment: {reason:?}"),
                    },
                    (_, CandidateFailure::MissingIdentity) => ConnectError::Establishment {
                        message: "session completed without an admitted identity".into(),
                    },
                })
            }
        }
    }

    pub(crate) async fn reconnect_peer(
        self: &Arc<Self>,
        peer: &str,
        set: &EndpointSet,
        dialer: Option<Arc<dyn EndpointDialer>>,
    ) -> Result<ReconnectCandidate, ConnectError> {
        let key = set.cache_key();
        let ordered = self
            .dial_policy
            .ordered_candidates(&key, set)
            .into_iter()
            .filter(|endpoint| {
                dialer
                    .as_ref()
                    .is_none_or(|dialer| dialer.supports(endpoint.kind))
            })
            .collect::<Vec<_>>();
        if ordered.is_empty() {
            return Err(ConnectError::NoSupportedEndpoint);
        }
        let mut last_error = ConnectError::NoSupportedEndpoint;
        for endpoint in ordered {
            match self
                .try_candidate(&endpoint, Some(peer), dialer.as_ref())
                .await
            {
                Ok((candidate, outcome)) => {
                    let identity = match outcome {
                        CandidateOutcome::Promoted(identity)
                        | CandidateOutcome::Duplicate(identity) => identity,
                    };
                    let Some(selected) = self.peer(&identity.node_id).await else {
                        candidate.wire.shutdown();
                        let _ = candidate.cleaned.await;
                        last_error = ConnectError::Establishment {
                            message: format!(
                                "verified peer {:?} has no selected live session",
                                identity.node_id
                            ),
                        };
                        continue;
                    };
                    if n0_future::time::timeout(
                        crate::session::ROUTE_SYNC_TIMEOUT,
                        self.wait_for_selected_route(&identity.node_id, &selected.session_id),
                    )
                    .await
                    .is_err()
                    {
                        candidate.wire.shutdown();
                        let _ = candidate.cleaned.await;
                        last_error = ConnectError::Establishment {
                            message: format!(
                                "verified peer {:?} did not publish its synchronized node route",
                                identity.node_id
                            ),
                        };
                        continue;
                    }
                    let Some(selected) = self.peer(&identity.node_id).await else {
                        candidate.wire.shutdown();
                        let _ = candidate.cleaned.await;
                        last_error = ConnectError::Establishment {
                            message: format!(
                                "verified peer {:?} lost its selected session after route synchronization",
                                identity.node_id
                            ),
                        };
                        continue;
                    };
                    self.dial_policy.record_winner(&key, endpoint.kind);
                    return Ok(ReconnectCandidate {
                        identity,
                        selected,
                        candidate_wire: candidate.wire,
                    });
                }
                Err(error) => last_error = error,
            }
        }
        Err(last_error)
    }

    pub async fn link(self: &Arc<Self>, other: &Arc<Node>) -> Result<(), WsError> {
        if Arc::ptr_eq(self, other) || self.identity.node_id == other.identity.node_id {
            return Err(WsError::Connect("a node cannot link to itself".into()));
        }
        let (dial_side, accept_side) = unb_client::pair();
        let left = self
            .establish(dial_side, Some(other.identity.node_id.clone()))
            .await;
        let right = other
            .establish(accept_side, Some(self.identity.node_id.clone()))
            .await;
        let result = match tokio::join!(
            left.outcome(&other.identity.node_id),
            right.outcome(&self.identity.node_id)
        ) {
            (Ok(CandidateOutcome::Promoted(_)), Ok(CandidateOutcome::Promoted(_))) => {
                n0_future::time::timeout(crate::session::ROUTE_SYNC_TIMEOUT, async {
                    tokio::join!(left.wire.routes_acked(), right.wire.routes_acked());
                    tokio::join!(
                        self.wait_for_direct_peer_route(&other.identity.node_id),
                        other.wait_for_direct_peer_route(&self.identity.node_id),
                    );
                })
                .await
                .map_err(|_| {
                    WsError::Connect(
                        "linked peers did not publish their synchronized node routes".into(),
                    )
                })
            }
            (Err(error), _) | (_, Err(error)) => Err(error),
            _ => Err(WsError::Connect("link closed during establishment".into())),
        };
        if result.is_err() {
            left.wire.shutdown();
            right.wire.shutdown();
            let _ = tokio::join!(left.cleaned, right.cleaned);
        }
        result
    }

    /// Attach one caller-provided outbound transport without imposing an expected peer name.
    /// Browser bindings use this after JavaScript completes the platform dial.
    pub async fn connect_transport_unchecked(
        self: &Arc<Self>,
        transport: unb_runtime::Pipe,
    ) -> Result<(), WsError> {
        let candidate = self.establish(transport, None).await;
        match candidate.outcome("candidate").await {
            Ok(CandidateOutcome::Promoted(_) | CandidateOutcome::Duplicate(_)) => {
                let _ = n0_future::time::timeout(
                    crate::session::ROUTE_SYNC_TIMEOUT,
                    candidate.wire.routes_acked(),
                )
                .await;
                Ok(())
            }
            Err(error) => {
                candidate.wire.shutdown();
                let _ = candidate.cleaned.await;
                Err(error)
            }
        }
    }
}