prns-runtime-tokio 0.3.4

Tokio host runtime for Personal Reticulum
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
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use prns_core::interfaces::{FrameSink, FrameSinkError, PacketPhyStats};
use rtrb::{Consumer, PopError, Producer, PushError, RingBuffer};
use tokio::sync::Notify;

pub fn tokio_grant_lane(slot_cap: usize, depth: usize) -> (TokioGrantProducer, TokioGrantConsumer) {
    let depth = depth.max(1);
    let (filled, filled_slots) = RingBuffer::new(depth);
    let (mut free_slots, free) = RingBuffer::new(depth);
    for _ in 0..depth {
        let _ = free_slots.push(HeapFrameSlot::empty(slot_cap));
    }
    let filled_ready = Arc::new(Notify::new());
    let free_ready = Arc::new(Notify::new());
    let announced = Arc::new(AtomicBool::new(false));
    (
        TokioGrantProducer {
            free,
            filled,
            granted: None,
            filled_ready: filled_ready.clone(),
            free_ready: free_ready.clone(),
            announced: announced.clone(),
        },
        TokioGrantConsumer {
            filled: filled_slots,
            free: free_slots,
            peeked: None,
            filled_ready,
            free_ready,
            announced,
        },
    )
}

pub struct HeapFrameSlot {
    pub len: usize,
    pub cap: usize,
    pub bytes: Vec<u8>,
    pub packet_phy: PacketPhyStats,
}

impl HeapFrameSlot {
    fn empty(cap: usize) -> Self {
        Self {
            len: 0,
            cap,
            bytes: Vec::new(),
            packet_phy: PacketPhyStats::default(),
        }
    }

    pub fn fill(&mut self, frame: &[u8]) {
        self.packet_phy = PacketPhyStats::default();
        if self.bytes.len() < frame.len() {
            self.bytes.clear();
            self.bytes.extend_from_slice(frame);
        } else {
            self.bytes[..frame.len()].copy_from_slice(frame);
        }
        self.len = frame.len();
    }

    pub fn frame(&self) -> &[u8] {
        &self.bytes[..self.len]
    }

    pub fn frame_mut(&mut self) -> &mut [u8] {
        let len = self.len;
        &mut self.bytes[..len]
    }
}

impl FrameSink for HeapFrameSlot {
    fn clear(&mut self) {
        self.bytes.clear();
        self.len = 0;
        self.packet_phy = PacketPhyStats::default();
    }

    fn frame_len(&self) -> usize {
        self.bytes.len()
    }

    fn free_capacity(&self) -> usize {
        self.cap.saturating_sub(self.bytes.len())
    }

    fn push(&mut self, byte: u8) -> Result<(), FrameSinkError> {
        if self.bytes.len() >= self.cap {
            return Err(FrameSinkError::Full);
        }
        self.bytes.push(byte);
        Ok(())
    }

    fn extend_from_slice(&mut self, run: &[u8]) -> Result<(), FrameSinkError> {
        if run.len() > self.cap.saturating_sub(self.bytes.len()) {
            return Err(FrameSinkError::Full);
        }
        self.bytes.extend_from_slice(run);
        Ok(())
    }
}

pub struct TokioGrantProducer {
    free: Consumer<HeapFrameSlot>,
    filled: Producer<HeapFrameSlot>,
    pub(super) granted: Option<HeapFrameSlot>,
    filled_ready: Arc<Notify>,
    free_ready: Arc<Notify>,
    announced: Arc<AtomicBool>,
}

impl TokioGrantProducer {
    pub fn try_grant(&mut self) -> Option<&mut HeapFrameSlot> {
        if self.granted.is_none() {
            self.granted = self.free.pop().ok();
        }
        self.granted.as_mut()
    }

    pub async fn grant(&mut self) -> &mut HeapFrameSlot {
        loop {
            if let Some(slot) = self.granted.take() {
                return self.granted.insert(slot);
            }
            match self.free.pop() {
                Ok(slot) => self.granted = Some(slot),
                Err(PopError::Empty) => self.free_ready.notified().await,
            }
        }
    }

    pub fn commit(&mut self) {
        if let Some(slot) = self.granted.take() {
            match self.filled.push(slot) {
                Ok(()) => self.filled_ready.notify_one(),
                Err(PushError::Full(_)) => {}
            }
        }
    }

    pub fn needs_announce(&self) -> bool {
        !self.announced.swap(true, Ordering::AcqRel)
    }
}

pub struct TokioGrantConsumer {
    filled: Consumer<HeapFrameSlot>,
    free: Producer<HeapFrameSlot>,
    peeked: Option<HeapFrameSlot>,
    filled_ready: Arc<Notify>,
    free_ready: Arc<Notify>,
    announced: Arc<AtomicBool>,
}

impl TokioGrantConsumer {
    pub fn try_peek(&mut self) -> Option<&mut HeapFrameSlot> {
        if self.peeked.is_none() {
            self.peeked = self.filled.pop().ok();
        }
        self.peeked.as_mut()
    }

    pub async fn peek(&mut self) -> &mut HeapFrameSlot {
        loop {
            if let Some(slot) = self.peeked.take() {
                return self.peeked.insert(slot);
            }
            match self.filled.pop() {
                Ok(slot) => self.peeked = Some(slot),
                Err(PopError::Empty) => self.filled_ready.notified().await,
            }
        }
    }

    pub fn release(&mut self) {
        if let Some(slot) = self.peeked.take() {
            match self.free.push(slot) {
                Ok(()) => self.free_ready.notify_one(),
                Err(PushError::Full(_)) => {}
            }
        }
    }

    pub fn acknowledge(&mut self) {
        self.announced.store(false, Ordering::Release);
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    #[test]
    fn depth_is_exact_and_frames_remain_fifo() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 3);

        for frame in [b"one".as_slice(), b"two".as_slice(), b"three".as_slice()] {
            producer.try_grant().expect("slot available").fill(frame);
            producer.commit();
        }
        assert!(producer.try_grant().is_none());

        for frame in [b"one".as_slice(), b"two".as_slice(), b"three".as_slice()] {
            assert_eq!(consumer.try_peek().expect("frame available").frame(), frame);
            consumer.release();
        }
        assert!(consumer.try_peek().is_none());
    }

    #[test]
    fn slot_storage_survives_a_complete_recycle() {
        let (mut producer, mut consumer) = tokio_grant_lane(512, 1);

        let slot = producer.try_grant().expect("slot available");
        slot.fill(&[0xA5; 384]);
        let allocation = slot.bytes.as_ptr();
        let capacity = slot.bytes.capacity();
        producer.commit();
        assert_eq!(
            consumer.try_peek().expect("frame available").bytes.as_ptr(),
            allocation
        );
        consumer.release();

        let recycled = producer.try_grant().expect("slot recycled");
        recycled.fill(b"small");
        assert_eq!(recycled.bytes.as_ptr(), allocation);
        assert_eq!(recycled.bytes.capacity(), capacity);
        assert_eq!(recycled.bytes.len(), 384);
        assert_eq!(recycled.frame(), b"small");
    }

    #[tokio::test]
    async fn commit_wakes_a_parked_consumer() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 1);

        let receive = async { consumer.peek().await.frame().to_vec() };
        let send = async {
            tokio::task::yield_now().await;
            producer.try_grant().expect("slot available").fill(b"ready");
            producer.commit();
        };
        let (frame, ()) = tokio::join!(receive, send);

        assert_eq!(frame, b"ready");
    }

    #[tokio::test]
    async fn release_wakes_a_parked_producer() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 1);
        producer.try_grant().expect("slot available").fill(b"full");
        producer.commit();

        let grant = async {
            producer.grant().await.fill(b"next");
        };
        let release = async {
            tokio::task::yield_now().await;
            assert_eq!(consumer.peek().await.frame(), b"full");
            consumer.release();
        };
        tokio::join!(grant, release);

        producer.commit();
        assert_eq!(consumer.peek().await.frame(), b"next");
    }

    #[tokio::test]
    async fn cancelled_parks_do_not_consume_or_strand_wakes() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 1);

        let consumer_resolved = tokio::select! {
            biased;
            _ = consumer.peek() => true,
            _ = tokio::task::yield_now() => false,
        };
        assert!(!consumer_resolved);
        producer
            .try_grant()
            .expect("slot available")
            .fill(b"after cancel");
        producer.commit();
        let frame = tokio::time::timeout(Duration::from_secs(1), consumer.peek())
            .await
            .expect("consumer wakes");
        assert_eq!(frame.frame(), b"after cancel");
        consumer.release();

        producer
            .try_grant()
            .expect("slot available")
            .fill(b"full again");
        producer.commit();
        let producer_resolved = tokio::select! {
            biased;
            _ = producer.grant() => true,
            _ = tokio::task::yield_now() => false,
        };
        assert!(!producer_resolved);
        consumer.peek().await;
        consumer.release();
        let slot = tokio::time::timeout(Duration::from_secs(1), producer.grant())
            .await
            .expect("producer wakes");
        slot.fill(b"after second cancel");
    }

    #[tokio::test]
    async fn exhausted_lane_parks_after_its_peer_is_dropped() {
        let (producer, mut consumer) = tokio_grant_lane(64, 1);
        drop(producer);
        assert!(
            tokio::time::timeout(Duration::from_millis(20), consumer.peek())
                .await
                .is_err()
        );

        let (mut producer, consumer) = tokio_grant_lane(64, 1);
        producer.try_grant().expect("slot available").fill(b"held");
        producer.commit();
        drop(consumer);
        assert!(
            tokio::time::timeout(Duration::from_millis(20), producer.grant())
                .await
                .is_err()
        );
    }

    #[test]
    fn commit_and_release_without_a_loan_are_noops() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 1);

        producer.commit();
        consumer.release();
        producer
            .try_grant()
            .expect("slot remains available")
            .fill(b"frame");
        producer.commit();
        assert_eq!(
            consumer.try_peek().expect("frame available").frame(),
            b"frame"
        );
    }

    #[tokio::test]
    async fn a_filled_grant_is_read_in_place_without_a_copy() {
        let (mut producer, mut consumer) = tokio_grant_lane(512, 2);

        let granted = producer.grant().await;
        granted.fill(b"the frame is written once");
        let written_at = granted.bytes.as_ptr() as usize;
        producer.commit();

        let received = consumer.peek().await;
        assert_eq!(received.frame(), b"the frame is written once");
        assert_eq!(
            received.bytes.as_ptr() as usize,
            written_at,
            "the consumer reads the very slot the producer filled",
        );
        received.frame_mut()[0] ^= 0x20;
        assert_eq!(&received.frame()[..3], b"The");
        consumer.release();
    }

    #[test]
    fn a_burst_earns_one_announcement_until_the_consumer_acknowledges() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 8);

        producer.try_grant().expect("lane grants").fill(b"one");
        producer.commit();
        assert!(producer.needs_announce(), "the first commit announces");

        producer.try_grant().expect("lane grants").fill(b"two");
        producer.commit();
        assert!(
            !producer.needs_announce(),
            "a burst behind an unconsumed announcement stays silent",
        );

        consumer.acknowledge();
        while consumer.try_peek().is_some() {
            consumer.release();
        }

        producer.try_grant().expect("lane grants").fill(b"three");
        producer.commit();
        assert!(
            producer.needs_announce(),
            "a commit after the acknowledge announces again",
        );
    }

    #[tokio::test]
    async fn a_full_lane_refuses_grants_until_the_consumer_releases() {
        let (mut producer, mut consumer) = tokio_grant_lane(64, 1);

        producer
            .try_grant()
            .expect("an empty lane grants")
            .fill(b"one");
        producer.commit();
        assert!(producer.try_grant().is_none(), "a depth-one lane is full");

        consumer.try_peek().expect("the committed frame is there");
        consumer.release();
        assert!(
            producer.try_grant().is_some(),
            "the release frees the slot for the next grant",
        );
    }
}