veilid-core 0.5.3

Core library used to create a Veilid node and operate it as part of an application
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
use crate::*;
use core::fmt;
use crypto::*;
use futures_util::stream::{FuturesUnordered, StreamExt};
use network_manager::*;
use routing_table::*;
use stop_token::future::FutureExt;

impl_veilid_log_facility!("receipt");

#[derive(Clone, Debug)]
pub enum ReceiptEvent {
    ReturnedOutOfBand,
    ReturnedInBand {
        inbound_noderef: FilteredNodeRef,
    },
    ReturnedSafety,
    ReturnedPrivate {
        #[expect(dead_code)]
        private_route: PublicKey,
    },
    Expired,
    Cancelled,
}

#[derive(Clone, Debug)]
pub(super) enum ReceiptReturned {
    OutOfBand,
    InBand { inbound_noderef: FilteredNodeRef },
    Safety,
    Private { private_route: PublicKey },
}

pub trait ReceiptCallback: Send + 'static {
    fn call(
        &self,
        event: ReceiptEvent,
        receipt: Receipt,
        returns_so_far: u32,
        expected_returns: u32,
    ) -> PinBoxFutureStatic<()>;
}
impl<F, T> ReceiptCallback for T
where
    T: Fn(ReceiptEvent, Receipt, u32, u32) -> F + Send + 'static,
    F: Future<Output = ()> + Send + 'static,
{
    fn call(
        &self,
        event: ReceiptEvent,
        receipt: Receipt,
        returns_so_far: u32,
        expected_returns: u32,
    ) -> PinBoxFutureStatic<()> {
        Box::pin(self(event, receipt, returns_so_far, expected_returns))
    }
}

type ReceiptCallbackType = Box<dyn ReceiptCallback>;
type ReceiptSingleShotType = SingleShotEventual<ReceiptEvent>;

enum ReceiptRecordCallbackType {
    Normal(ReceiptCallbackType),
    SingleShot(Option<ReceiptSingleShotType>),
}
impl fmt::Debug for ReceiptRecordCallbackType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ReceiptRecordCallbackType::{}",
            match self {
                Self::Normal(_) => "Normal".to_owned(),
                Self::SingleShot(_) => "SingleShot".to_owned(),
            }
        )
    }
}

#[derive(Debug)]
struct ReceiptRecord {
    expiration: Timestamp,
    receipt: Receipt,
    expected_returns: u32,
    returns_so_far: u32,
    receipt_callback: ReceiptRecordCallbackType,
}

impl ReceiptRecord {
    pub fn new(
        receipt: Receipt,
        expiration: Timestamp,
        expected_returns: u32,
        receipt_callback: impl ReceiptCallback,
    ) -> Self {
        Self {
            expiration,
            receipt,
            expected_returns,
            returns_so_far: 0u32,
            receipt_callback: ReceiptRecordCallbackType::Normal(Box::new(receipt_callback)),
        }
    }

    pub fn new_single_shot(
        receipt: Receipt,
        expiration: Timestamp,
        eventual: ReceiptSingleShotType,
    ) -> Self {
        Self {
            expiration,
            receipt,
            returns_so_far: 0u32,
            expected_returns: 1u32,
            receipt_callback: ReceiptRecordCallbackType::SingleShot(Some(eventual)),
        }
    }
}

/* XXX: may be useful for O(1) timestamp expiration
#[derive(Clone, Debug)]
struct ReceiptRecordTimestampSort {
    expiration: Timestamp,
    record: Arc<Mutex<ReceiptRecord>>,
}

impl PartialEq for ReceiptRecordTimestampSort {
    fn eq(&self, other: &ReceiptRecordTimestampSort) -> bool {
        self.expiration == other.expiration
    }
}
impl Eq for ReceiptRecordTimestampSort {}
impl Ord for ReceiptRecordTimestampSort {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.expiration.cmp(&other.expiration).reverse()
    }
}
impl PartialOrd for ReceiptRecordTimestampSort {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(&other))
    }
}
*/

///////////////////////////////////

struct ReceiptManagerInner {
    records_by_nonce: BTreeMap<Nonce, Arc<Mutex<ReceiptRecord>>>,
    next_oldest_ts: Option<Timestamp>,
    stop_source: Option<StopSource>,
    timeout_task: MustJoinSingleFuture<()>,
}

struct ReceiptManagerUnlockedInner {
    startup_lock: StartupLock,
}

#[derive(Clone)]
pub(super) struct ReceiptManager {
    registry: VeilidComponentRegistry,
    inner: Arc<Mutex<ReceiptManagerInner>>,
    unlocked_inner: Arc<ReceiptManagerUnlockedInner>,
}

impl_veilid_component_accessors!(ReceiptManager);

impl ReceiptManager {
    fn new_inner() -> ReceiptManagerInner {
        ReceiptManagerInner {
            records_by_nonce: BTreeMap::new(),
            next_oldest_ts: None,
            stop_source: None,
            timeout_task: MustJoinSingleFuture::new(),
        }
    }

    pub fn new(registry: VeilidComponentRegistry) -> Self {
        Self {
            registry,
            inner: Arc::new(Mutex::new(Self::new_inner())),
            unlocked_inner: Arc::new(ReceiptManagerUnlockedInner {
                startup_lock: StartupLock::new(),
            }),
        }
    }

    pub fn startup(&self) -> EyreResult<()> {
        let guard = self.unlocked_inner.startup_lock.startup()?;
        veilid_log!(self debug "startup receipt manager");

        let mut inner = self.inner.lock();
        inner.stop_source = Some(StopSource::new());

        guard.success();
        Ok(())
    }

    fn perform_callback(
        evt: ReceiptEvent,
        record_mut: &mut ReceiptRecord,
    ) -> Option<PinBoxFutureStatic<()>> {
        match &mut record_mut.receipt_callback {
            ReceiptRecordCallbackType::Normal(callback) => Some(callback.call(
                evt,
                record_mut.receipt.clone(),
                record_mut.returns_so_far,
                record_mut.expected_returns,
            )),
            ReceiptRecordCallbackType::SingleShot(eventual) => {
                // resolve this eventual with the receiptevent
                // don't need to wait for the instance to receive it
                // because this can only happen once
                if let Some(eventual) = eventual.take() {
                    eventual.resolve(evt);
                }
                None
            }
        }
    }

    #[cfg_attr(
        feature = "instrument",
        instrument(level = "trace", target = "receipt", skip_all, fields(__VEILID_LOG_KEY = self.log_key()))
    )]
    async fn timeout_task_routine(self, now: Timestamp, stop_token: StopToken) {
        // Go through all receipts and build a list of expired nonces
        let mut new_next_oldest_ts: Option<Timestamp> = None;
        let mut expired_records = Vec::new();
        {
            let mut inner = self.inner.lock();
            let mut expired_nonces = Vec::new();
            for (k, v) in &inner.records_by_nonce {
                let receipt_inner = v.lock();
                if receipt_inner.expiration <= now {
                    // Expire this receipt
                    expired_nonces.push(k.clone());
                } else if new_next_oldest_ts.is_none()
                    || receipt_inner.expiration < new_next_oldest_ts.unwrap_or_log()
                {
                    // Mark the next oldest timestamp we would need to take action on as we go through everything
                    new_next_oldest_ts = Some(receipt_inner.expiration);
                }
            }
            if expired_nonces.is_empty() {
                return;
            }
            // Now remove the expired receipts
            for e in expired_nonces {
                let expired_record = inner
                    .records_by_nonce
                    .remove(&e)
                    .expect_or_log("key should exist");
                expired_records.push(expired_record);
            }
            // Update the next oldest timestamp
            inner.next_oldest_ts = new_next_oldest_ts;
        }
        let mut callbacks = FuturesUnordered::new();
        for expired_record in expired_records {
            let mut expired_record_mut = expired_record.lock();
            if let Some(callback) =
                Self::perform_callback(ReceiptEvent::Expired, &mut expired_record_mut)
            {
                callbacks.push(callback.instrument(Span::current()))
            }
        }

        // Wait on all the multi-call callbacks
        loop {
            if let Ok(None) | Err(_) = callbacks.next().timeout_at(stop_token.clone()).await {
                break;
            }
        }
    }

    #[cfg_attr(
        feature = "instrument",
        instrument(
            level = "trace",
            target = "receipt",
            name = "ReceiptManager::tick",
            skip_all,
            err,
            fields(__VEILID_LOG_KEY = self.log_key())
        )
    )]
    pub async fn tick(&self) -> EyreResult<()> {
        let Ok(_guard) = self.unlocked_inner.startup_lock.enter() else {
            return Ok(());
        };

        let (next_oldest_ts, timeout_task, stop_token) = {
            let inner = self.inner.lock();
            let stop_token = match inner.stop_source.as_ref() {
                Some(ss) => ss.token(),
                None => {
                    // Do nothing if we're shutting down
                    return Ok(());
                }
            };
            (inner.next_oldest_ts, inner.timeout_task.clone(), stop_token)
        };
        let now = Timestamp::now_non_decreasing();
        // If we have at least one timestamp to expire, lets do it
        if let Some(next_oldest_ts) = next_oldest_ts {
            if now >= next_oldest_ts {
                // Single-spawn the timeout task routine
                let _ = timeout_task
                    .single_spawn("receipt timeout", || {
                        self.clone()
                            .timeout_task_routine(now, stop_token)
                            .instrument(trace_span!(parent: None, "receipt timeout task"))
                    })
                    .in_current_span()
                    .await;
            }
        }
        Ok(())
    }

    pub async fn cancel_tasks(&self) {
        // Stop all tasks
        let timeout_task = {
            let mut inner = self.inner.lock();
            // Drop the stop
            drop(inner.stop_source.take());
            inner.timeout_task.clone()
        };

        // Wait for everything to stop
        veilid_log!(self debug "waiting for timeout task to stop");
        if timeout_task.join().await.is_err() {
            panic!("joining timeout task failed");
        }
    }

    pub async fn shutdown(&self) {
        veilid_log!(self debug "starting receipt manager shutdown");
        let Ok(guard) = self.unlocked_inner.startup_lock.shutdown().await else {
            veilid_log!(self error "receipt manager is already shut down");
            return;
        };

        *self.inner.lock() = Self::new_inner();

        guard.success();
        veilid_log!(self debug "finished receipt manager shutdown");
    }

    #[cfg_attr(
        feature = "instrument",
        instrument(level = "trace", target = "receipt", skip_all, fields(__VEILID_LOG_KEY = self.log_key()))
    )]
    pub fn record_receipt(
        &self,
        receipt: Receipt,
        expiration: Timestamp,
        expected_returns: u32,
        callback: impl ReceiptCallback,
    ) {
        let Ok(_guard) = self.unlocked_inner.startup_lock.enter() else {
            veilid_log!(self debug "ignoring 'record_receipt' due to not started up");
            return;
        };
        let receipt_nonce = receipt.get_nonce();
        event!(target: "receipt", Level::DEBUG, "== New Multiple Receipt ({}) {} ", expected_returns, receipt_nonce.encode());
        let record = Arc::new(Mutex::new(ReceiptRecord::new(
            receipt,
            expiration,
            expected_returns,
            callback,
        )));
        let mut inner = self.inner.lock();
        inner.records_by_nonce.insert(receipt_nonce, record);

        Self::update_next_oldest_timestamp(&mut inner);
    }

    #[cfg_attr(
        feature = "instrument",
        instrument(level = "trace", target = "receipt", skip_all, fields(__VEILID_LOG_KEY = self.log_key()))
    )]
    pub fn record_single_shot_receipt(
        &self,
        receipt: Receipt,
        expiration: Timestamp,
        eventual: ReceiptSingleShotType,
    ) {
        let Ok(_guard) = self.unlocked_inner.startup_lock.enter() else {
            veilid_log!(self debug "ignoring 'record_single_shot_receipt' due to not started up");
            return;
        };
        let receipt_nonce = receipt.get_nonce();
        event!(target: "receipt", Level::DEBUG, "== New SingleShot Receipt {}", receipt_nonce.encode());

        let record = Arc::new(Mutex::new(ReceiptRecord::new_single_shot(
            receipt, expiration, eventual,
        )));
        let mut inner = self.inner.lock();
        inner.records_by_nonce.insert(receipt_nonce, record);

        Self::update_next_oldest_timestamp(&mut inner);
    }

    fn update_next_oldest_timestamp(inner: &mut ReceiptManagerInner) {
        // Update the next oldest timestamp
        let mut new_next_oldest_ts: Option<Timestamp> = None;
        for v in inner.records_by_nonce.values() {
            let receipt_inner = v.lock();
            if new_next_oldest_ts.is_none()
                || receipt_inner.expiration < new_next_oldest_ts.unwrap_or_log()
            {
                // Mark the next oldest timestamp we would need to take action on as we go through everything
                new_next_oldest_ts = Some(receipt_inner.expiration);
            }
        }

        inner.next_oldest_ts = new_next_oldest_ts;
    }

    #[expect(dead_code)]
    pub async fn cancel_receipt(&self, nonce: &Nonce) -> EyreResult<()> {
        event!(target: "receipt", Level::DEBUG, "== Cancel Receipt {}", nonce.encode());

        let _guard = self.unlocked_inner.startup_lock.enter()?;

        // Remove the record
        let record = {
            let mut inner = self.inner.lock();
            let record = match inner.records_by_nonce.remove(nonce) {
                Some(r) => r,
                None => {
                    bail!("receipt not recorded");
                }
            };
            Self::update_next_oldest_timestamp(&mut inner);
            record
        };

        // Generate a cancelled callback
        let callback_future = {
            let mut record_mut = record.lock();
            Self::perform_callback(ReceiptEvent::Cancelled, &mut record_mut)
        };

        // Issue the callback
        if let Some(callback_future) = callback_future {
            callback_future.await;
        }

        Ok(())
    }

    pub async fn handle_receipt(
        &self,
        receipt: Receipt,
        receipt_returned: ReceiptReturned,
    ) -> NetworkResult<()> {
        let Ok(_guard) = self.unlocked_inner.startup_lock.enter() else {
            return NetworkResult::service_unavailable("receipt manager not started");
        };

        let receipt_nonce = receipt.get_nonce();
        let extra_data = receipt.get_extra_data();

        event!(target: "receipt", Level::DEBUG, "<<== RECEIPT {} <- {}{}",
            receipt_nonce.encode(),
            match receipt_returned {
                ReceiptReturned::OutOfBand => "OutOfBand".to_owned(),
                ReceiptReturned::InBand { ref inbound_noderef } => format!("InBand({})", inbound_noderef),
                ReceiptReturned::Safety => "Safety".to_owned(),
                ReceiptReturned::Private { ref private_route } => format!("Private({})", private_route),
            },
            if extra_data.is_empty() {
                "".to_owned()
            } else {
                format!("[{} extra]", extra_data.len())
            }
        );

        // Increment return count
        let (callback_future, stop_token) = {
            // Look up the receipt record from the nonce
            let mut inner = self.inner.lock();
            let stop_token = match inner.stop_source.as_ref() {
                Some(ss) => ss.token(),
                None => {
                    // If we're stopping do nothing here
                    return NetworkResult::value(());
                }
            };
            let record = match inner.records_by_nonce.get(&receipt_nonce) {
                Some(r) => r.clone(),
                None => {
                    return NetworkResult::invalid_message("receipt not recorded");
                }
            };
            // Generate the callback future
            let mut record_mut = record.lock();
            record_mut.returns_so_far += 1;

            // Get the receipt event to return
            let receipt_event = match receipt_returned {
                ReceiptReturned::OutOfBand => ReceiptEvent::ReturnedOutOfBand,
                ReceiptReturned::Safety => ReceiptEvent::ReturnedSafety,
                ReceiptReturned::InBand { inbound_noderef } => {
                    ReceiptEvent::ReturnedInBand { inbound_noderef }
                }
                ReceiptReturned::Private { private_route } => {
                    ReceiptEvent::ReturnedPrivate { private_route }
                }
            };

            let callback_future = Self::perform_callback(receipt_event, &mut record_mut);

            // Remove the record if we're done
            if record_mut.returns_so_far == record_mut.expected_returns {
                inner.records_by_nonce.remove(&receipt_nonce);

                Self::update_next_oldest_timestamp(&mut inner);
            }
            (callback_future, stop_token)
        };

        // Issue the callback
        if let Some(callback_future) = callback_future {
            let _ = callback_future.timeout_at(stop_token).await;
        }

        NetworkResult::value(())
    }
}