Skip to main content

qualia_core_db/net/peer/fabric/
connect.rs

1//! `connect(peer, purpose, protection, budget)` — the application surface.
2
3use super::carrier::PathClass;
4use super::intent::{ConnectionIntent, PeerId, ProtectionPolicy, Purpose};
5use super::kernel::{FabricError, FabricState, Kernel, KernelEffect, KernelEvent};
6use super::lease::RelayLease;
7use super::receipt::{OpReceipt, ReceiptStatus};
8use super::session::SessionReady;
9use crate::net::peer::runtime::ResourceBudget;
10
11pub const MAX_RECEIPTS: usize = 8;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct ConnectHandle {
15    pub peer: PeerId,
16    pub state: FabricState,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum DriveOutcome {
21    Establishing,
22    Live,
23    Queued,
24    Denied,
25    Closed,
26}
27
28#[derive(Debug, Clone, Copy)]
29pub struct Fabric {
30    pub kernel: Kernel,
31    receipts: [Option<OpReceipt>; MAX_RECEIPTS],
32    receipt_len: usize,
33    session: Option<SessionReady>,
34}
35
36impl Fabric {
37    /// Creates a default `Fabric`.
38    pub const fn new() -> Self {
39        Self {
40            kernel: Kernel::new(),
41            receipts: [None; MAX_RECEIPTS],
42            receipt_len: 0,
43            session: None,
44        }
45    }
46
47    /// Active session, or `None`.
48    pub fn session(&self) -> Option<SessionReady> {
49        self.session
50    }
51
52    /// Queues a payload for the session.
53    pub fn enqueue(
54        &mut self,
55        op_id: u64,
56        digest: [u8; 32],
57        peer: PeerId,
58        expiry_unix: u32,
59    ) -> Result<usize, FabricError> {
60        if self.receipt_len >= MAX_RECEIPTS {
61            return Err(FabricError::Capacity);
62        }
63        let r = OpReceipt::queued(
64            op_id,
65            digest,
66            peer,
67            self.kernel.grant_generation,
68            expiry_unix,
69        );
70        self.receipts[self.receipt_len] = Some(r);
71        let i = self.receipt_len;
72        self.receipt_len += 1;
73        Ok(i)
74    }
75
76    /// Replays queued payloads after reconnect.
77    pub fn replay(
78        &self,
79        index: usize,
80        op_id: u64,
81        digest: &[u8; 32],
82        now_unix: u32,
83    ) -> Result<ReceiptStatus, FabricError> {
84        let r = self.receipts[index].ok_or(FabricError::Illegal)?;
85        Ok(r.replay(
86            op_id,
87            digest,
88            self.kernel.grant_live,
89            self.kernel.grant_generation,
90            now_unix,
91        ))
92    }
93}
94
95/// Admit an intent. Isolated profiles queue immediately and never probe.
96pub fn connect(
97    fabric: &mut Fabric,
98    peer: PeerId,
99    purpose: Purpose,
100    protection: ProtectionPolicy,
101    budget: ResourceBudget,
102    now_ms: u64,
103    deadline_ms: u64,
104) -> Result<ConnectHandle, FabricError> {
105    let intent = ConnectionIntent::new(peer, purpose, protection, budget, now_ms, deadline_ms);
106    fabric.kernel.admit(intent, now_ms)?;
107    fabric.kernel.step(KernelEvent::IntentAdmitted, now_ms);
108    if matches!(
109        protection.disclosure,
110        crate::net::peer::connectivity::policy::Disclosure::Isolated
111    ) {
112        fabric.kernel.step(KernelEvent::Deadline, now_ms);
113        return Ok(ConnectHandle {
114            peer,
115            state: FabricState::OfflineQueued,
116        });
117    }
118    Ok(ConnectHandle {
119        peer,
120        state: fabric.kernel.state,
121    })
122}
123
124/// Drives the fabric state machine on a `KernelEvent`.
125pub fn drive(fabric: &mut Fabric, event: KernelEvent, now_ms: u64) -> DriveOutcome {
126    let effect = fabric.kernel.step(event, now_ms);
127    match effect {
128        KernelEffect::Deny => DriveOutcome::Denied,
129        KernelEffect::QueueOffline | KernelEffect::Close => DriveOutcome::Queued,
130        KernelEffect::AdmitSession => DriveOutcome::Live,
131        KernelEffect::Probe {
132            class: PathClass::Offline,
133        } => DriveOutcome::Queued,
134        _ => match fabric.kernel.state {
135            FabricState::SessionLive => DriveOutcome::Live,
136            FabricState::Closed => DriveOutcome::Closed,
137            FabricState::OfflineQueued => DriveOutcome::Queued,
138            _ => DriveOutcome::Establishing,
139        },
140    }
141}
142
143/// Binds a relay `lease`, extending connectivity.
144pub fn bind_lease(fabric: &mut Fabric, lease: &RelayLease, now_ms: u64) -> Result<(), FabricError> {
145    if !lease.live(now_ms) {
146        return Err(FabricError::LeaseDead);
147    }
148    let _ = fabric.kernel.step(KernelEvent::LeaseLive, now_ms);
149    Ok(())
150}
151
152/// Admits a new session into the fabric.
153pub fn admit_session(
154    fabric: &mut Fabric,
155    path: super::evidence::PathEvidence,
156    now_ms: u64,
157) -> Result<SessionReady, FabricError> {
158    let peer = fabric.kernel.intent().ok_or(FabricError::Illegal)?.peer;
159    let _ = fabric
160        .kernel
161        .step(KernelEvent::SessionAuthenticated, now_ms);
162    let ready = SessionReady::try_new(&fabric.kernel, peer, path)?;
163    fabric.session = Some(ready);
164    Ok(ready)
165}
166
167#[cfg(not(target_arch = "wasm32"))]
168mod native {
169    use super::*;
170    use crate::net::peer::fabric::contact::ContactDescriptor;
171    use crate::net::peer::fabric::evidence::PathEvidence;
172    use crate::net::peer::fabric::lease::RelayLease;
173    use crate::net::peer::fabric::relay::{decode_payload, encode, BoundUdpRelay};
174    use crate::q_hash;
175    use std::net::UdpSocket;
176    use std::time::Duration;
177
178    /// Two loopback clients, each outbound-only to a bound relay. Not Internet MASQUE.
179    pub fn local_bound_udp_exchange(
180        protection: ProtectionPolicy,
181        payload: &[u8],
182        now_ms: u64,
183        lease_bytes: u64,
184        lease_expiry_ms: u64,
185    ) -> Result<(Fabric, Fabric, usize), FabricError> {
186        let a_id = [0xAAu8; 32];
187        let b_id = [0xBBu8; 32];
188        let budget = ResourceBudget {
189            bytes: 8192,
190            work: 8,
191            io: 8,
192        };
193        let mut fa = Fabric::new();
194        let mut fb = Fabric::new();
195        connect(
196            &mut fa,
197            b_id,
198            Purpose::ordinary(),
199            protection,
200            budget,
201            now_ms,
202            now_ms.saturating_add(10_000),
203        )?;
204        connect(
205            &mut fb,
206            a_id,
207            Purpose::ordinary(),
208            protection,
209            budget,
210            now_ms,
211            now_ms.saturating_add(10_000),
212        )?;
213        let desc = ContactDescriptor::mailbox(b_id, 2, 2_000_000_000);
214        fa.kernel.note_contact(&desc);
215        fb.kernel.note_contact(&desc);
216        drive(
217            &mut fa,
218            KernelEvent::Descriptor {
219                stale: false,
220                expired: false,
221                direct_locator: false,
222            },
223            now_ms,
224        );
225        drive(
226            &mut fb,
227            KernelEvent::Descriptor {
228                stale: false,
229                expired: false,
230                direct_locator: false,
231            },
232            now_ms,
233        );
234        let export = matches!(
235            protection.disclosure,
236            crate::net::peer::connectivity::policy::Disclosure::DirectPermitted
237        );
238        let lease = RelayLease::grant(
239            42,
240            q_hash("q42:relay/local-loopback"),
241            a_id,
242            b_id,
243            lease_bytes,
244            lease_expiry_ms,
245            fa.kernel.generation,
246            export,
247        );
248        bind_lease(&mut fa, &lease, now_ms)?;
249        bind_lease(&mut fb, &lease, now_ms)?;
250        let mut relay = BoundUdpRelay::bind(lease)?;
251        let relay_addr = relay.addr()?;
252        let sa = UdpSocket::bind("127.0.0.1:0").map_err(|_| FabricError::Capacity)?;
253        let sb = UdpSocket::bind("127.0.0.1:0").map_err(|_| FabricError::Capacity)?;
254        sa.set_read_timeout(Some(Duration::from_millis(400)))
255            .map_err(|_| FabricError::Capacity)?;
256        sb.set_read_timeout(Some(Duration::from_millis(400)))
257            .map_err(|_| FabricError::Capacity)?;
258        let mut pkt = [0u8; 32 + 1152];
259        let n = encode(&relay.lease, &a_id, payload, &mut pkt)?;
260        sa.send_to(&pkt[..n], relay_addr)
261            .map_err(|_| FabricError::Capacity)?;
262        // First datagram registers A; B is unknown yet. Send a hello from B so both ends exist.
263        let hello_n = encode(&relay.lease, &b_id, b"hi", &mut pkt)?;
264        sb.send_to(&pkt[..hello_n], relay_addr)
265            .map_err(|_| FabricError::Capacity)?;
266        let _ = relay.forward_once(now_ms)?;
267        let _ = relay.forward_once(now_ms)?;
268        // Re-send payload now that both endpoints are known.
269        let n = encode(&relay.lease, &a_id, payload, &mut pkt)?;
270        sa.send_to(&pkt[..n], relay_addr)
271            .map_err(|_| FabricError::Capacity)?;
272        let forwarded = relay.forward_once(now_ms)?;
273        let mut rx = [0u8; 32 + 1152];
274        let (got, _) = sb.recv_from(&mut rx).map_err(|_| FabricError::Capacity)?;
275        let body = decode_payload(&rx[..got])?;
276        if body != payload {
277            return Err(FabricError::Illegal);
278        }
279        let path = PathEvidence::from_witness(relay.witness(now_ms));
280        drive(
281            &mut fa,
282            KernelEvent::PathValidated {
283                class: PathClass::Relayed,
284            },
285            now_ms,
286        );
287        drive(
288            &mut fb,
289            KernelEvent::PathValidated {
290                class: PathClass::Relayed,
291            },
292            now_ms,
293        );
294        admit_session(&mut fa, path, now_ms)?;
295        admit_session(&mut fb, path, now_ms)?;
296        if export {
297            // Direct remains eligible to rank, but this local proof does not dial peer IPs.
298            let _ = export;
299        }
300        Ok((fa, fb, forwarded))
301    }
302}
303
304#[cfg(not(target_arch = "wasm32"))]
305pub use native::local_bound_udp_exchange;
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate::net::peer::connectivity::policy::Disclosure;
311
312    #[test]
313    fn isolated_connect_queues_without_session() {
314        let mut f = Fabric::new();
315        let h = connect(
316            &mut f,
317            [1u8; 32],
318            Purpose::ordinary(),
319            ProtectionPolicy::ISOLATED,
320            ResourceBudget {
321                bytes: 128,
322                work: 1,
323                io: 1,
324            },
325            0,
326            5_000,
327        )
328        .unwrap();
329        assert_eq!(h.state, FabricState::OfflineQueued);
330        assert!(f.session().is_none());
331    }
332
333    #[cfg(not(target_arch = "wasm32"))]
334    #[test]
335    fn local_bound_udp_delivers_and_admits_session() {
336        let (fa, _fb, n) =
337            local_bound_udp_exchange(ProtectionPolicy::RELAY_ONLY, b"q-fabric", 10, 4096, 10_000)
338                .unwrap();
339        assert!(n >= b"q-fabric".len());
340        let s = fa.session().unwrap();
341        assert_eq!(s.path.class, PathClass::Relayed);
342        assert!(s.path.validated());
343        assert_eq!(fa.kernel.direct_probe_count, 0);
344        assert_eq!(
345            fa.kernel.intent().unwrap().protection.disclosure,
346            Disclosure::ApprovedRelaysOnly
347        );
348    }
349}