rustorb-rtps 0.2.0

DDSI-RTPS wire protocol (messages, discovery, writers and readers) for rustorb-dds
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! A shared memory transport for participants of rustorb-dds on the same
//! host (feature `shm`).
//!
//! Each participant has a receive segment: a file in a shared memory
//! directory (`/dev/shm` on Linux, else the temporary directory), mapped
//! by every process that sends to it, holding a ring buffer of RTPS
//! messages; and a UDP socket on the loopback interface, whose port the
//! segment gives, that senders ring after writing. Senders take turns through a
//! lock in the segment. A message that does not fit is dropped, like a
//! datagram lost on the way: the reliable protocol repairs it.
//!
//! The participant announces its segment with locators of the vendor
//! kind [`Locator::KIND_SHM`] (the address holds the host and the segment,
//! the port tells metatraffic from user traffic), besides its UDP ones.
//! Other implementations ignore them. A sender uses a peer's shared memory
//! locator when the host is its own and it can open the segment; else the
//! peer's UDP locators ([`ShmTransport::select`]).

use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io;
use std::net::{Ipv4Addr, SocketAddr, UdpSocket};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use memmap2::MmapMut;

use crate::udp::{Channel, Datagram};
use crate::{GuidPrefix, Locator};

/// The port of a shared memory locator for metatraffic.
pub const PORT_METATRAFFIC: u32 = 1;
/// The port of a shared memory locator for user traffic.
pub const PORT_USER: u32 = 2;

/// "RSHM" and the layout version.
const MAGIC: u64 = 0x5253_484d_0000_0001;
/// The header: magic, capacity, lock, head, tail and the port of the
/// receiver's bell, each on its own word.
const HEADER: usize = 64;
const OFF_MAGIC: usize = 0;
const OFF_CAPACITY: usize = 8;
const OFF_LOCK: usize = 16;
const OFF_HEAD: usize = 24;
const OFF_TAIL: usize = 32;
const OFF_BELL: usize = 40;
/// A record: its length and port, then the message, padded to 8.
const RECORD_HEADER: usize = 8;
/// The length that marks the rest of the buffer as unused.
const WRAP: u32 = u32::MAX;
/// How often the receive thread looks at the stop flag.
const POLL: Duration = Duration::from_millis(100);
/// How long a sender waits for the lock before it takes it from a holder
/// that is gone.
const LOCK_PATIENCE: Duration = Duration::from_millis(500);

/// How the transport is set up.
#[derive(Clone, Debug)]
pub struct ShmConfig {
    /// The directory of the segments: `/dev/shm` where it exists, else
    /// the temporary directory.
    pub directory: PathBuf,
    /// The size of the receive buffer, in octets (default 4 MiB). A
    /// message larger than a quarter of it cannot be sent this way.
    pub capacity: usize,
}

impl Default for ShmConfig {
    fn default() -> Self {
        let shm = Path::new("/dev/shm");
        ShmConfig {
            directory: if shm.is_dir() {
                shm.to_path_buf()
            } else {
                std::env::temp_dir()
            },
            capacity: 4 << 20,
        }
    }
}

/// An identifier of this host: from the machine id where there is one,
/// else from the host name. Shared memory is tried only with peers of
/// the same one.
fn host_id() -> [u8; 8] {
    let text = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
        .iter()
        .find_map(|p| std::fs::read_to_string(p).ok())
        .or_else(|| std::fs::read_to_string("/proc/sys/kernel/hostname").ok())
        .or_else(|| std::env::var("HOSTNAME").ok())
        .or_else(|| std::env::var("COMPUTERNAME").ok())
        .unwrap_or_default();
    fnv(text.trim().as_bytes()).to_be_bytes()
}

/// FNV-1a, 64 bits.
fn fnv(b: &[u8]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for x in b {
        h ^= u64::from(*x);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

fn segment_path(dir: &Path, segment: u64) -> PathBuf {
    dir.join(format!("rustorb-dds-{segment:016x}"))
}

/// A mapped segment.
struct Segment {
    map: MmapMut,
    capacity: usize,
}

// SAFETY: the shared words are accessed through atomics, the data under
// the lock (writers) or below `head` (the reader).
unsafe impl Send for Segment {}
unsafe impl Sync for Segment {}

impl Segment {
    fn create(path: &Path, capacity: usize, bell: u16) -> io::Result<Segment> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(path)?;
        file.set_len((HEADER + capacity) as u64)?;
        let s = Segment::map(&file, capacity)?;
        s.word(OFF_CAPACITY)
            .store(capacity as u64, Ordering::Relaxed);
        s.word(OFF_BELL).store(u64::from(bell), Ordering::Relaxed);
        s.word(OFF_MAGIC).store(MAGIC, Ordering::Release);
        Ok(s)
    }

    fn open(path: &Path) -> io::Result<Segment> {
        let file = OpenOptions::new().read(true).write(true).open(path)?;
        let len = file.metadata()?.len() as usize;
        if len < HEADER {
            return Err(io::Error::new(io::ErrorKind::InvalidData, "not a segment"));
        }
        let s = Segment::map(&file, len - HEADER)?;
        if s.word(OFF_MAGIC).load(Ordering::Acquire) != MAGIC
            || s.word(OFF_CAPACITY).load(Ordering::Relaxed) != (len - HEADER) as u64
        {
            return Err(io::Error::new(io::ErrorKind::InvalidData, "not a segment"));
        }
        Ok(s)
    }

    fn map(file: &File, capacity: usize) -> io::Result<Segment> {
        // SAFETY: the file is a segment of this transport; other
        // processes change it only through the protocol below.
        let map = unsafe { MmapMut::map_mut(file) }?;
        Ok(Segment { map, capacity })
    }

    fn word(&self, off: usize) -> &AtomicU64 {
        // SAFETY: the mapping is page aligned and HEADER long at least;
        // off is a multiple of 8 below HEADER.
        unsafe { &*(self.map.as_ptr().add(off) as *const AtomicU64) }
    }

    /// The receiver's bell.
    fn bell(&self) -> SocketAddr {
        let port = self.word(OFF_BELL).load(Ordering::Relaxed) as u16;
        SocketAddr::from((Ipv4Addr::LOCALHOST, port))
    }

    fn lock_word(&self) -> &AtomicU32 {
        // SAFETY: as in `word`.
        unsafe { &*(self.map.as_ptr().add(OFF_LOCK) as *const AtomicU32) }
    }

    fn data(&self) -> *mut u8 {
        // SAFETY: HEADER is within the mapping.
        unsafe { self.map.as_ptr().add(HEADER) as *mut u8 }
    }

    /// Takes the writers' lock; false if it cannot.
    fn lock(&self) -> bool {
        let me = std::process::id().max(1);
        let lock = self.lock_word();
        let start = Instant::now();
        let mut spins = 0u32;
        loop {
            let held = lock.load(Ordering::Relaxed);
            if held == 0 {
                if lock
                    .compare_exchange(0, me, Ordering::Acquire, Ordering::Relaxed)
                    .is_ok()
                {
                    return true;
                }
            } else if start.elapsed() > LOCK_PATIENCE {
                // A holder that is gone left it: on Linux, one with no
                // /proc/<pid>; elsewhere, one that kept it far longer
                // than a copy takes.
                let gone = if Path::new("/proc/self").exists() {
                    !Path::new(&format!("/proc/{held}")).exists()
                } else {
                    start.elapsed() > 4 * LOCK_PATIENCE
                };
                if gone
                    && lock
                        .compare_exchange(held, me, Ordering::Acquire, Ordering::Relaxed)
                        .is_ok()
                {
                    return true;
                }
                if start.elapsed() > 8 * LOCK_PATIENCE {
                    return false;
                }
            }
            spins += 1;
            if spins < 64 {
                std::hint::spin_loop();
            } else {
                std::thread::yield_now();
            }
        }
    }

    fn unlock(&self) {
        self.lock_word().store(0, Ordering::Release);
    }

    /// Puts a message in the ring; false if there is no room.
    fn push(&self, port: u32, data: &[u8]) -> bool {
        let need = RECORD_HEADER + data.len().next_multiple_of(8);
        if need > self.capacity / 4 || !self.lock() {
            return false;
        }
        let head = self.word(OFF_HEAD).load(Ordering::Relaxed);
        let tail = self.word(OFF_TAIL).load(Ordering::Acquire);
        let cap = self.capacity as u64;
        let at = (head % cap) as usize;
        let to_end = self.capacity - at;
        let skip = if to_end < need { to_end } else { 0 };
        if (head - tail) as usize + skip + need > self.capacity {
            self.unlock();
            return false;
        }
        let p = self.data();
        // SAFETY: [at, at + to_end) and [0, need) are within the buffer,
        // free (below tail + capacity), and only this writer, holding the
        // lock, writes there.
        unsafe {
            let mut at = at;
            if skip > 0 {
                std::ptr::copy_nonoverlapping(WRAP.to_ne_bytes().as_ptr(), p.add(at), 4);
                at = 0;
            }
            let len = data.len() as u32;
            std::ptr::copy_nonoverlapping(len.to_ne_bytes().as_ptr(), p.add(at), 4);
            std::ptr::copy_nonoverlapping(port.to_ne_bytes().as_ptr(), p.add(at + 4), 4);
            std::ptr::copy_nonoverlapping(data.as_ptr(), p.add(at + RECORD_HEADER), data.len());
        }
        self.word(OFF_HEAD)
            .store(head + (skip + need) as u64, Ordering::Release);
        self.unlock();
        true
    }

    /// Takes the messages in the ring, with their ports.
    fn drain(&self, mut f: impl FnMut(u32, Vec<u8>)) {
        let head = self.word(OFF_HEAD).load(Ordering::Acquire);
        let mut tail = self.word(OFF_TAIL).load(Ordering::Relaxed);
        let cap = self.capacity as u64;
        let p = self.data();
        while tail < head {
            let at = (tail % cap) as usize;
            let mut w = [0u8; 4];
            // SAFETY: records below head are complete (Release/Acquire on
            // head) and nobody writes them until tail passes them.
            unsafe { std::ptr::copy_nonoverlapping(p.add(at), w.as_mut_ptr(), 4) };
            let len = u32::from_ne_bytes(w);
            if len == WRAP {
                tail += (self.capacity - at) as u64;
                continue;
            }
            let mut port = [0u8; 4];
            let mut data = vec![0u8; len as usize];
            // SAFETY: as above.
            unsafe {
                std::ptr::copy_nonoverlapping(p.add(at + 4), port.as_mut_ptr(), 4);
                std::ptr::copy_nonoverlapping(
                    p.add(at + RECORD_HEADER),
                    data.as_mut_ptr(),
                    data.len(),
                );
            }
            tail += (RECORD_HEADER + (len as usize).next_multiple_of(8)) as u64;
            f(u32::from_ne_bytes(port), data);
        }
        self.word(OFF_TAIL).store(tail, Ordering::Release);
    }
}

/// A peer's segment, opened on first use.
struct Peer {
    segment: Segment,
}

/// The shared memory transport of one participant.
pub struct ShmTransport {
    host: [u8; 8],
    segment_id: u64,
    directory: PathBuf,
    path: PathBuf,
    /// Peers by segment; `None` for one that could not be opened.
    peers: Mutex<HashMap<u64, Option<Arc<Peer>>>>,
    /// The pools of the samples sent by reference to this participant.
    pools: Arc<Pools>,
    /// Rings the peers' bells.
    bell: UdpSocket,
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

impl std::fmt::Debug for ShmTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ShmTransport")
            .field("segment", &self.path)
            .finish()
    }
}

impl ShmTransport {
    /// Creates the receive segment and socket of the participant `prefix`
    /// and starts receiving: the messages go to `tx`, as datagrams of the
    /// unicast channels.
    pub fn open(
        config: &ShmConfig,
        prefix: GuidPrefix,
        tx: mpsc::Sender<Datagram>,
    ) -> io::Result<ShmTransport> {
        let segment_id = fnv(&prefix.0) ^ u64::from(std::process::id());
        let path = segment_path(&config.directory, segment_id);
        let _ = std::fs::remove_file(&path);
        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
        socket.set_read_timeout(Some(POLL))?;
        let port = socket.local_addr()?.port();
        let segment = Arc::new(Segment::create(&path, config.capacity, port)?);
        let bell = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
        bell.set_nonblocking(true)?;
        let stop = Arc::new(AtomicBool::new(false));
        let thread = {
            let stop = stop.clone();
            std::thread::Builder::new()
                .name("rtps-shm".into())
                .spawn(move || receive_loop(&segment, &socket, &stop, &tx))?
        };
        Ok(ShmTransport {
            host: host_id(),
            segment_id,
            directory: config.directory.clone(),
            path,
            peers: Mutex::new(HashMap::new()),
            pools: Arc::new(Pools::new(&config.directory)),
            bell,
            stop,
            thread: Some(thread),
        })
    }

    fn locator(&self, port: u32) -> Locator {
        let mut address = [0u8; 16];
        address[..8].copy_from_slice(&self.host);
        address[8..].copy_from_slice(&self.segment_id.to_be_bytes());
        Locator {
            kind: Locator::KIND_SHM,
            port,
            address,
        }
    }

    /// The locator of the metatraffic.
    pub fn metatraffic_locator(&self) -> Locator {
        self.locator(PORT_METATRAFFIC)
    }

    /// The locator of the user traffic.
    pub fn user_locator(&self) -> Locator {
        self.locator(PORT_USER)
    }

    /// The peer behind a shared memory locator of this host, opened.
    fn peer(&self, l: &Locator) -> Option<Arc<Peer>> {
        if l.kind != Locator::KIND_SHM || l.address[..8] != self.host {
            return None;
        }
        let id = u64::from_be_bytes(l.address[8..].try_into().ok()?);
        let mut peers = self.peers.lock().ok()?;
        peers
            .entry(id)
            .or_insert_with(|| {
                Segment::open(&segment_path(&self.directory, id))
                    .ok()
                    .map(|segment| Arc::new(Peer { segment }))
            })
            .clone()
    }

    /// Of a peer's locators, those to send to: its shared memory ones if
    /// one of them can be used, else the others.
    pub fn select<'a>(&self, locators: &'a [Locator]) -> Vec<&'a Locator> {
        let shm: Vec<&Locator> = locators.iter().filter(|l| self.peer(l).is_some()).collect();
        if shm.is_empty() {
            locators
                .iter()
                .filter(|l| l.kind != Locator::KIND_SHM)
                .collect()
        } else {
            shm
        }
    }

    /// Whether one of a peer's locators can be sent to by shared memory.
    pub fn reaches(&self, locators: &[Locator]) -> bool {
        locators.iter().any(|l| self.peer(l).is_some())
    }

    /// A pool of `slots` samples of up to `slot_size` octets, for a
    /// writer to lend samples from.
    pub fn create_pool(&self, slots: u32, slot_size: usize) -> io::Result<Arc<Pool>> {
        Pool::create(&self.directory, slots, slot_size)
    }

    /// The pools of the samples that writers of this host send to this
    /// participant by reference (see [`PoolLoan::reference`]).
    pub fn pools(&self) -> Arc<Pools> {
        self.pools.clone()
    }

    /// Sends one message to a shared memory locator. Fails with
    /// [`io::ErrorKind::WouldBlock`] when the peer's buffer is full and
    /// [`io::ErrorKind::Unsupported`] for a locator it cannot use.
    pub fn send(&self, data: &[u8], to: &Locator) -> io::Result<()> {
        let peer = self.peer(to).ok_or_else(|| {
            io::Error::new(io::ErrorKind::Unsupported, "no such shared memory peer")
        })?;
        if !peer.segment.push(to.port, data) {
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "the shared memory buffer is full",
            ));
        }
        match self.bell.send_to(&[0], peer.segment.bell()) {
            Ok(_) => Ok(()),
            // The peer is busy or its socket is full: it drains the ring
            // at its next wake-up anyway.
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(()),
            Err(e) => {
                // The peer is gone: forget it, so that the next send
                // opens it again or falls back.
                if let Ok(mut peers) = self.peers.lock() {
                    peers.retain(|_, p| !p.as_ref().is_some_and(|p| Arc::ptr_eq(p, &peer)));
                }
                Err(e)
            }
        }
    }
}

impl Drop for ShmTransport {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
        // On Windows this fails while a peer still maps the file; the
        // next participant with the same id removes it.
        let _ = std::fs::remove_file(&self.path);
    }
}

fn receive_loop(
    segment: &Segment,
    socket: &UdpSocket,
    stop: &AtomicBool,
    tx: &mpsc::Sender<Datagram>,
) {
    let mut buf = [0u8; 64];
    let source = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
    while !stop.load(Ordering::Relaxed) {
        // A ring, or the poll interval, wakes it; then it drains the
        // buffer, which may hold more than one message per ring.
        let _ = socket.recv(&mut buf);
        let mut closed = false;
        segment.drain(|port, data| {
            let channel = if port == PORT_METATRAFFIC {
                Channel::DiscoveryUnicast
            } else {
                Channel::UserUnicast
            };
            if tx
                .send(Datagram {
                    channel,
                    source,
                    data,
                })
                .is_err()
            {
                closed = true;
            }
        });
        if closed {
            return;
        }
    }
}

/// "RPOL" and the layout version of a [`Pool`].
const POOL_MAGIC: u64 = 0x5250_4f4c_0000_0001;
/// The header of a pool: magic, slots, slot size, then the control words
/// of each slot.
const POOL_HEADER: usize = 64;
/// The control of a slot: its state (generation in the high 32 bits,
/// references in the low 32) and the length of its payload.
const SLOT_CONTROL: usize = 16;
/// Where a payload starts in its slot (whose alignment is 64): 4 octets
/// in, so that what follows its 4-octet encapsulation header is aligned
/// to 8.
const PAYLOAD_OFFSET: usize = 4;

fn pool_path(dir: &Path, id: u64) -> PathBuf {
    dir.join(format!("rustorb-dds-pool-{id:016x}"))
}

/// A pool of samples in shared memory, made by a writer for the samples
/// it loans (zero-copy): fixed-size slots that the writer fills and the
/// readers of this host map and read in place. A slot is reused once no
/// one holds a reference to it: the writer, while the sample is in its
/// history, and each reader, while it has the sample.
///
/// Each slot has a generation, changed each time the writer takes it, so
/// that a reference to an older sample of the slot is not taken for the
/// new one.
pub struct Pool {
    map: MmapMut,
    id: u64,
    slots: u32,
    slot_size: usize,
    data: usize,
    /// The file, removed when the writer's pool goes; `None` in readers.
    path: Option<PathBuf>,
}

// SAFETY: the control words are atomics; a slot's data is written only by
// the writer while it holds the slot alone, and read after it is
// published.
unsafe impl Send for Pool {}
unsafe impl Sync for Pool {}

impl std::fmt::Debug for Pool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Pool")
            .field("id", &format_args!("{:016x}", self.id))
            .field("slots", &self.slots)
            .field("slot_size", &self.slot_size)
            .finish()
    }
}

impl Pool {
    /// Makes a pool of `slots` slots for payloads of up to `slot_size`
    /// octets (rounded up, see [`Self::slot_size`]) in `dir`.
    pub fn create(dir: &Path, slots: u32, slot_size: usize) -> io::Result<Arc<Pool>> {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos() as u64);
        let id = fnv(&[
            u64::from(std::process::id()).to_le_bytes(),
            nanos.to_le_bytes(),
            NEXT.fetch_add(1, Ordering::Relaxed).to_le_bytes(),
        ]
        .concat());
        let slot_size = (slot_size.max(8) + PAYLOAD_OFFSET).next_multiple_of(64);
        let data = (POOL_HEADER + slots as usize * SLOT_CONTROL).next_multiple_of(64);
        let path = pool_path(dir, id);
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(&path)?;
        file.set_len((data + slots as usize * slot_size) as u64)?;
        // SAFETY: a new file of this process; others change it only
        // through the protocol of this type.
        let map = unsafe { MmapMut::map_mut(&file) }?;
        let pool = Pool {
            map,
            id,
            slots,
            slot_size,
            data,
            path: Some(path),
        };
        pool.word(8).store(u64::from(slots), Ordering::Relaxed);
        pool.word(16).store(slot_size as u64, Ordering::Relaxed);
        pool.word(0).store(POOL_MAGIC, Ordering::Release);
        Ok(Arc::new(pool))
    }

    /// Maps the pool `id` of `dir`, made by a writer of this host.
    pub fn open(dir: &Path, id: u64) -> io::Result<Arc<Pool>> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(pool_path(dir, id))?;
        let len = file.metadata()?.len() as usize;
        let bad = || io::Error::new(io::ErrorKind::InvalidData, "not a pool");
        if len < POOL_HEADER {
            return Err(bad());
        }
        // SAFETY: as in `create`.
        let map = unsafe { MmapMut::map_mut(&file) }?;
        let word = |off: usize| {
            // SAFETY: page aligned, and off < POOL_HEADER <= len.
            unsafe { &*(map.as_ptr().add(off) as *const AtomicU64) }
        };
        if word(0).load(Ordering::Acquire) != POOL_MAGIC {
            return Err(bad());
        }
        let slots = word(8).load(Ordering::Relaxed) as u32;
        let slot_size = word(16).load(Ordering::Relaxed) as usize;
        let data = (POOL_HEADER + slots as usize * SLOT_CONTROL).next_multiple_of(64);
        if slot_size < 64
            || !slot_size.is_multiple_of(64)
            || (slots as usize)
                .checked_mul(slot_size)
                .and_then(|n| n.checked_add(data))
                != Some(len)
        {
            return Err(bad());
        }
        Ok(Arc::new(Pool {
            map,
            id,
            slots,
            slot_size,
            data,
            path: None,
        }))
    }

    /// Its id, which references name it by.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// The largest payload a slot holds.
    pub fn slot_size(&self) -> usize {
        self.slot_size - PAYLOAD_OFFSET
    }

    /// The number of slots.
    pub fn slots(&self) -> u32 {
        self.slots
    }

    fn word(&self, off: usize) -> &AtomicU64 {
        // SAFETY: the mapping is page aligned; off is a multiple of 8
        // within the header and the slot controls.
        unsafe { &*(self.map.as_ptr().add(off) as *const AtomicU64) }
    }

    fn state(&self, i: u32) -> &AtomicU64 {
        self.word(POOL_HEADER + i as usize * SLOT_CONTROL)
    }

    fn len_word(&self, i: u32) -> &AtomicU64 {
        self.word(POOL_HEADER + i as usize * SLOT_CONTROL + 8)
    }

    /// The payload of slot `i`.
    fn slot_ptr(&self, i: u32) -> *mut u8 {
        // SAFETY: slot i is within the mapping.
        unsafe {
            self.map
                .as_ptr()
                .add(self.data + i as usize * self.slot_size + PAYLOAD_OFFSET)
                as *mut u8
        }
    }

    /// Takes a free slot for the writer; `None` if every slot is held. It
    /// holds zeros the first time, then the sample it held last.
    pub fn acquire(self: &Arc<Self>) -> Option<PoolSlot> {
        for i in 0..self.slots {
            let s = self.state(i);
            let v = s.load(Ordering::Acquire);
            if v & 0xffff_ffff != 0 {
                continue;
            }
            let generation = ((v >> 32) as u32).wrapping_add(1);
            if s.compare_exchange(
                v,
                (u64::from(generation) << 32) | 1,
                Ordering::AcqRel,
                Ordering::Relaxed,
            )
            .is_ok()
            {
                return Some(PoolSlot(PoolLoan {
                    pool: self.clone(),
                    index: i,
                    generation,
                }));
            }
        }
        None
    }

    /// How many slots are held.
    pub fn held(&self) -> usize {
        (0..self.slots)
            .filter(|i| self.state(*i).load(Ordering::Relaxed) & 0xffff_ffff != 0)
            .count()
    }

    /// Takes a reference to slot `index` if it still holds the sample of
    /// `generation`.
    fn retain(self: &Arc<Self>, index: u32, generation: u32) -> Option<PoolLoan> {
        if index >= self.slots {
            return None;
        }
        let s = self.state(index);
        let mut v = s.load(Ordering::Acquire);
        loop {
            if (v >> 32) as u32 != generation || v & 0xffff_ffff == 0 {
                return None;
            }
            match s.compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire) {
                Ok(_) => {
                    return Some(PoolLoan {
                        pool: self.clone(),
                        index,
                        generation,
                    });
                }
                Err(now) => v = now,
            }
        }
    }
}

impl Drop for Pool {
    fn drop(&mut self) {
        // Readers that still map it keep their mapping.
        if let Some(p) = &self.path {
            let _ = std::fs::remove_file(p);
        }
    }
}

/// A slot the writer holds alone, to fill before it publishes it.
#[derive(Debug)]
pub struct PoolSlot(PoolLoan);

impl PoolSlot {
    /// The slot, to write the payload in: its address is 4 past a
    /// multiple of 64, so that octet 4 on is aligned to 8.
    pub fn bytes_mut(&mut self) -> &mut [u8] {
        let p = &self.0.pool;
        // SAFETY: the slot is held by this writer alone until published.
        unsafe { std::slice::from_raw_parts_mut(p.slot_ptr(self.0.index), p.slot_size()) }
    }

    /// The slot, as [`Self::bytes_mut`].
    pub fn bytes(&self) -> &[u8] {
        let p = &self.0.pool;
        // SAFETY: as in `bytes_mut`.
        unsafe { std::slice::from_raw_parts(p.slot_ptr(self.0.index), p.slot_size()) }
    }

    /// Publishes the first `len` octets of the slot: from then on it is
    /// only read.
    pub fn publish(self, len: usize) -> PoolLoan {
        let len = len.min(self.0.pool.slot_size());
        self.0
            .pool
            .len_word(self.0.index)
            .store(len as u64, Ordering::Release);
        self.0
    }
}

/// A reference to a published sample of a [`Pool`]: the slot is not
/// reused while one is alive. Cloning takes another reference.
#[derive(Debug)]
pub struct PoolLoan {
    pool: Arc<Pool>,
    index: u32,
    generation: u32,
}

/// The encapsulation identifier of a payload that is a reference to a
/// sample in a pool, not the sample: a vendor value, sent only to
/// participants of rustorb-dds on this host.
pub const REFERENCE_ENCAPSULATION: [u8; 2] = [0x52, 0x44];

impl PoolLoan {
    /// The payload.
    pub fn bytes(&self) -> &[u8] {
        let len = (self.pool.len_word(self.index).load(Ordering::Acquire) as usize)
            .min(self.pool.slot_size());
        // SAFETY: published, so no longer written while referenced.
        unsafe { std::slice::from_raw_parts(self.pool.slot_ptr(self.index), len) }
    }

    /// The payload that refers to this sample: [`REFERENCE_ENCAPSULATION`]
    /// and two octets of options, then the pool id, the slot and its
    /// generation (little endian).
    pub fn reference(&self) -> Vec<u8> {
        let mut b = Vec::with_capacity(20);
        b.extend_from_slice(&REFERENCE_ENCAPSULATION);
        b.extend_from_slice(&[0, 0]);
        b.extend_from_slice(&self.pool.id.to_le_bytes());
        b.extend_from_slice(&self.index.to_le_bytes());
        b.extend_from_slice(&self.generation.to_le_bytes());
        b
    }
}

impl Clone for PoolLoan {
    fn clone(&self) -> Self {
        self.pool.state(self.index).fetch_add(1, Ordering::AcqRel);
        PoolLoan {
            pool: self.pool.clone(),
            index: self.index,
            generation: self.generation,
        }
    }
}

impl Drop for PoolLoan {
    fn drop(&mut self) {
        self.pool.state(self.index).fetch_sub(1, Ordering::AcqRel);
    }
}

/// Whether a payload is a reference to a pooled sample.
pub fn is_reference(payload: &[u8]) -> bool {
    payload.len() == 20 && payload[..2] == REFERENCE_ENCAPSULATION
}

/// The pools of other writers that a reader opened, by id: each is kept
/// mapped while its file exists.
#[derive(Debug)]
pub struct Pools {
    directory: PathBuf,
    open: Mutex<HashMap<u64, Arc<Pool>>>,
}

impl Pools {
    /// The pools of directory `directory`.
    pub fn new(directory: &Path) -> Pools {
        Pools {
            directory: directory.to_path_buf(),
            open: Mutex::new(HashMap::new()),
        }
    }

    /// The sample a reference payload names: `None` if its pool cannot
    /// be opened or its slot holds another sample by now.
    pub fn resolve(&self, reference: &[u8]) -> Option<PoolLoan> {
        if !is_reference(reference) {
            return None;
        }
        let id = u64::from_le_bytes(reference[4..12].try_into().ok()?);
        let index = u32::from_le_bytes(reference[12..16].try_into().ok()?);
        let generation = u32::from_le_bytes(reference[16..20].try_into().ok()?);
        let pool = {
            let mut pools = self.open.lock().ok()?;
            match pools.get(&id) {
                Some(p) => p.clone(),
                None => {
                    // The pools of writers that are gone.
                    let dir = &self.directory;
                    pools.retain(|id, _| pool_path(dir, *id).exists());
                    let p = Pool::open(dir, id).ok()?;
                    pools.insert(id, p.clone());
                    p
                }
            }
        };
        pool.retain(index, generation)
    }
}

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

    fn config() -> ShmConfig {
        ShmConfig {
            capacity: 4096,
            ..ShmConfig::default()
        }
    }

    fn prefix(n: u8) -> GuidPrefix {
        GuidPrefix([n; 12])
    }

    #[test]
    fn messages_go_through_in_order() {
        let (tx_a, _rx_a) = mpsc::channel();
        let (tx_b, rx_b) = mpsc::channel();
        let a = ShmTransport::open(&config(), prefix(1), tx_a).unwrap();
        let b = ShmTransport::open(&config(), prefix(2), tx_b).unwrap();
        let to = b.user_locator();
        assert_eq!(a.select(std::slice::from_ref(&to)), vec![&to]);
        // Enough messages to wrap around the ring several times, each
        // waiting for room.
        let mut got = Vec::new();
        for i in 0..200u32 {
            let msg = vec![i as u8; 1 + (i as usize * 7) % 900];
            let deadline = Instant::now() + Duration::from_secs(5);
            while a.send(&msg, &to).is_err() {
                assert!(Instant::now() < deadline);
                while let Ok(d) = rx_b.try_recv() {
                    got.push(d);
                }
                std::thread::sleep(Duration::from_millis(1));
            }
        }
        let deadline = Instant::now() + Duration::from_secs(5);
        while got.len() < 200 && Instant::now() < deadline {
            if let Ok(d) = rx_b.recv_timeout(Duration::from_millis(50)) {
                got.push(d);
            }
        }
        assert_eq!(got.len(), 200);
        for (i, d) in got.iter().enumerate() {
            assert_eq!(d.channel, Channel::UserUnicast);
            assert_eq!(d.data, vec![i as u8; 1 + (i * 7) % 900]);
        }
        let meta = b.metatraffic_locator();
        a.send(b"hello", &meta).unwrap();
        let d = rx_b.recv_timeout(Duration::from_secs(5)).unwrap();
        assert_eq!(
            (d.channel, &d.data[..]),
            (Channel::DiscoveryUnicast, &b"hello"[..])
        );
    }

    #[test]
    fn other_hosts_and_gone_peers_use_udp() {
        let (tx, _rx) = mpsc::channel();
        let a = ShmTransport::open(&config(), prefix(3), tx).unwrap();
        let udp = Locator::udpv4("127.0.0.1:7411".parse().unwrap());
        let mut elsewhere = a.user_locator();
        elsewhere.address[0] ^= 0xff;
        let mut gone = a.user_locator();
        gone.address[15] ^= 0xff;
        assert_eq!(a.select(&[elsewhere, udp]), vec![&udp]);
        assert_eq!(a.select(&[gone, udp]), vec![&udp]);
        assert!(a.send(b"x", &gone).is_err());
        // Too large for the ring: not sent this way.
        let (tx_b, _rx_b) = mpsc::channel();
        let b = ShmTransport::open(&config(), prefix(4), tx_b).unwrap();
        assert!(a.send(&[0u8; 2048], &b.user_locator()).is_err());
    }

    #[test]
    fn pooled_samples_are_shared_until_released() {
        let dir = ShmConfig::default().directory;
        let pool = Pool::create(&dir, 2, 100).unwrap();
        assert_eq!(pool.slot_size(), 124);
        let mut a = pool.acquire().unwrap();
        a.bytes_mut()[..5].copy_from_slice(b"hello");
        let a = a.publish(5);
        assert_eq!(a.bytes(), b"hello");
        let r = a.reference();
        assert!(is_reference(&r));
        // A reader maps it and holds the sample after the writer lets go.
        let pools = Pools::new(&dir);
        let got = pools.resolve(&r).unwrap();
        assert_eq!(got.bytes(), b"hello");
        let b = pool.acquire().unwrap();
        assert!(pool.acquire().is_none(), "two slots held");
        drop(a);
        assert!(pool.acquire().is_none(), "the reader holds the first");
        drop(got);
        // The slot is reused, with another generation: the old reference
        // no longer resolves.
        let c = pool.acquire().unwrap().publish(1);
        assert!(pools.resolve(&r).is_none());
        assert!(pools.resolve(&c.reference()).is_some());
        drop((b, c));
        assert_eq!(pool.held(), 0);
        let path = pool_path(&dir, pool.id());
        assert!(path.exists());
        drop(pool);
        assert!(!path.exists());
        assert!(pools.resolve(&r).is_none());
    }

    #[test]
    fn dropping_removes_the_files() {
        let (tx, _rx) = mpsc::channel();
        let a = ShmTransport::open(&config(), prefix(5), tx).unwrap();
        let seg = a.path.clone();
        assert!(seg.exists());
        drop(a);
        assert!(!seg.exists());
    }
}