1use std::collections::HashMap;
17use std::time::Instant;
18
19use crate::error::DecodeError;
20use crate::parameter::{Parameter, ParameterList};
21use crate::pl::{PL_CDR_BE, PL_CDR_LE, pid};
22use crate::receiver::receive;
23use crate::reliable::{
24 MatchedReader, Outgoing, ReaderConfig, ReliableReader, ReliableWriter, WriterConfig,
25};
26use crate::spdp::ParticipantData;
27use crate::submessage::{PayloadKind, SerializedPayload, Submessage};
28use crate::types::{BuiltinEndpointSet, EntityId, Guid, GuidPrefix, SequenceNumber, VendorId};
29use crate::wire::Endianness;
30
31pub mod kind {
33 pub const UNKNOWN: [u8; 4] = [0, 0, 0, 0];
35 pub const AUTOMATIC_LIVELINESS_UPDATE: [u8; 4] = [0, 0, 0, 1];
37 pub const MANUAL_LIVELINESS_UPDATE: [u8; 4] = [0, 0, 0, 2];
39}
40
41pub const BEST_EFFORT_PARTICIPANT_MESSAGE_DATA_READER: u32 = 1 << 0;
44
45const CDR_BE: [u8; 2] = [0x00, 0x00];
47const CDR_LE: [u8; 2] = [0x00, 0x01];
48
49#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct ParticipantMessage {
52 pub participant: GuidPrefix,
54 pub kind: [u8; 4],
56 pub data: Vec<u8>,
58}
59
60impl ParticipantMessage {
61 pub fn to_payload(&self, endianness: Endianness) -> Vec<u8> {
64 let mut b = Vec::with_capacity(4 + 20 + self.data.len());
65 b.extend_from_slice(match endianness {
66 Endianness::Big => &CDR_BE,
67 Endianness::Little => &CDR_LE,
68 });
69 b.extend_from_slice(&[0, 0]);
70 b.extend_from_slice(&self.participant.0);
71 b.extend_from_slice(&self.kind);
72 let n = self.data.len() as u32;
73 b.extend_from_slice(&match endianness {
74 Endianness::Big => n.to_be_bytes(),
75 Endianness::Little => n.to_le_bytes(),
76 });
77 b.extend_from_slice(&self.data);
78 b
79 }
80
81 pub fn from_payload(bytes: &[u8]) -> Result<Self, DecodeError> {
83 if bytes.len() < 4 + 20 {
84 return Err(DecodeError::UnexpectedEnd);
85 }
86 let big = match [bytes[0], bytes[1]] {
89 CDR_BE | PL_CDR_BE => true,
90 CDR_LE | PL_CDR_LE => false,
91 other => return Err(DecodeError::UnknownRepresentation(other)),
92 };
93 let body = &bytes[4..];
94 let participant = GuidPrefix(body[..12].try_into().expect("12 octets"));
95 let kind = body[12..16].try_into().expect("4 octets");
96 let len: [u8; 4] = body[16..20].try_into().expect("4 octets");
97 let len = if big {
98 u32::from_be_bytes(len)
99 } else {
100 u32::from_le_bytes(len)
101 } as usize;
102 let data = body
103 .get(20..20 + len)
104 .ok_or(DecodeError::UnexpectedEnd)?
105 .to_vec();
106 Ok(ParticipantMessage {
107 participant,
108 kind,
109 data,
110 })
111 }
112
113 pub fn key_hash(&self) -> [u8; 16] {
116 let mut h = [0u8; 16];
117 h[..12].copy_from_slice(&self.participant.0);
118 h[12..].copy_from_slice(&self.kind);
119 h
120 }
121}
122
123#[derive(Clone, Debug, PartialEq, Eq)]
125pub struct LivelinessAsserted {
126 pub participant: GuidPrefix,
128 pub kind: [u8; 4],
130}
131
132#[derive(Debug)]
134pub struct Wlp {
135 prefix: GuidPrefix,
136 ids: (EntityId, EntityId),
138 bits: (u32, u32),
139 writer: ReliableWriter,
140 reader: ReliableReader,
141 last: HashMap<[u8; 4], SequenceNumber>,
143}
144
145impl Wlp {
146 pub const BUILTIN_ENDPOINTS: u32 = BuiltinEndpointSet::PARTICIPANT_MESSAGE_DATA_WRITER
149 | BuiltinEndpointSet::PARTICIPANT_MESSAGE_DATA_READER;
150
151 pub const BUILTIN_ENDPOINTS_SECURE: u32 = BuiltinEndpointSet::PARTICIPANT_MESSAGE_SECURE_WRITER
153 | BuiltinEndpointSet::PARTICIPANT_MESSAGE_SECURE_READER;
154
155 pub fn new(
157 prefix: GuidPrefix,
158 vendor_id: VendorId,
159 writer: WriterConfig,
160 reader: ReaderConfig,
161 ) -> Self {
162 Self::with_ids(
163 prefix,
164 vendor_id,
165 writer,
166 reader,
167 (
168 EntityId::P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER,
169 EntityId::P2P_BUILTIN_PARTICIPANT_MESSAGE_READER,
170 ),
171 (
172 BuiltinEndpointSet::PARTICIPANT_MESSAGE_DATA_WRITER,
173 BuiltinEndpointSet::PARTICIPANT_MESSAGE_DATA_READER,
174 ),
175 )
176 }
177
178 pub fn new_secure(
182 prefix: GuidPrefix,
183 vendor_id: VendorId,
184 writer: WriterConfig,
185 reader: ReaderConfig,
186 ) -> Self {
187 Self::with_ids(
188 prefix,
189 vendor_id,
190 writer,
191 reader,
192 (
193 EntityId::P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_WRITER,
194 EntityId::P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_READER,
195 ),
196 (
197 BuiltinEndpointSet::PARTICIPANT_MESSAGE_SECURE_WRITER,
198 BuiltinEndpointSet::PARTICIPANT_MESSAGE_SECURE_READER,
199 ),
200 )
201 }
202
203 fn with_ids(
204 prefix: GuidPrefix,
205 vendor_id: VendorId,
206 writer: WriterConfig,
207 reader: ReaderConfig,
208 ids: (EntityId, EntityId),
209 bits: (u32, u32),
210 ) -> Self {
211 Wlp {
212 prefix,
213 ids,
214 bits,
215 writer: ReliableWriter::new(Guid::new(prefix, ids.0), vendor_id, writer),
216 reader: ReliableReader::new(Guid::new(prefix, ids.1), vendor_id, reader),
217 last: HashMap::new(),
218 }
219 }
220
221 pub fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
226 if p.guid_prefix == self.prefix {
227 return;
228 }
229 let set = p.available_builtin_endpoints;
230 let uc = p.metatraffic_unicast_locators.clone();
231 let mc = p.metatraffic_multicast_locators.clone();
232 if set.contains(self.bits.1) {
233 let best_effort = p
234 .builtin_endpoint_qos
235 .is_some_and(|q| q & BEST_EFFORT_PARTICIPANT_MESSAGE_DATA_READER != 0);
236 self.writer.add_matched_reader(
237 Guid::new(p.guid_prefix, self.ids.1),
238 MatchedReader {
239 unicast: uc.clone(),
240 multicast: mc.clone(),
241 reliable: !best_effort,
242 history: true,
243 },
244 );
245 }
246 if set.contains(self.bits.0) {
247 self.reader
248 .add_writer(Guid::new(p.guid_prefix, self.ids.0), uc, mc, now);
249 }
250 }
251
252 pub fn remove_participant(&mut self, prefix: &GuidPrefix) {
254 self.writer.remove_readers_of(prefix);
255 self.reader.remove_writers_of(prefix);
256 }
257
258 pub fn assert_liveliness(&mut self, kind: [u8; 4]) {
261 let m = ParticipantMessage {
262 participant: self.prefix,
263 kind,
264 data: Vec::new(),
265 };
266 let mut qos = ParameterList::new();
267 qos.push(Parameter::new(pid::KEY_HASH, m.key_hash()));
268 let sn = self.writer.add_change(
269 Some(qos),
270 Some(SerializedPayload {
271 kind: PayloadKind::Data,
272 bytes: m.to_payload(Endianness::NATIVE).into(),
273 }),
274 );
275 if let Some(old) = self.last.insert(kind, sn) {
276 self.writer.remove_change(old);
277 }
278 }
279
280 pub fn handle_message(&mut self, bytes: &[u8], now: Instant) -> Vec<LivelinessAsserted> {
283 let mut out = Vec::new();
284 let Some((_, received)) = receive(bytes, self.prefix) else {
285 return out;
286 };
287 let w = self.ids.0;
288 for r in received {
289 let src = r.source_prefix;
290 let changes = match r.submessage {
291 Submessage::Data(d) if d.writer_id == w => {
292 self.reader
293 .handle_data(Guid::new(src, d.writer_id), &d, r.timestamp)
294 }
295 Submessage::DataFrag(d) if d.writer_id == w => {
296 self.reader
297 .handle_data_frag(Guid::new(src, d.writer_id), &d, r.timestamp)
298 }
299 Submessage::Gap(g) if g.writer_id == w => {
300 self.reader.handle_gap(Guid::new(src, g.writer_id), &g)
301 }
302 Submessage::Heartbeat(h) if h.writer_id == w => {
303 self.reader
304 .handle_heartbeat(Guid::new(src, h.writer_id), &h, now)
305 }
306 Submessage::HeartbeatFrag(h) if h.writer_id == w => {
307 self.reader
308 .handle_heartbeat_frag(Guid::new(src, h.writer_id), &h, now);
309 Vec::new()
310 }
311 Submessage::AckNack(a) if a.writer_id == w => {
312 self.writer
313 .handle_acknack(Guid::new(src, a.reader_id), &a, now);
314 Vec::new()
315 }
316 Submessage::NackFrag(n) if n.writer_id == w => {
317 self.writer
318 .handle_nackfrag(Guid::new(src, n.reader_id), &n, now);
319 Vec::new()
320 }
321 _ => Vec::new(),
322 };
323 for c in changes {
324 let Some(p) = c.payload.filter(|p| p.kind == PayloadKind::Data) else {
325 continue;
326 };
327 if let Ok(m) = ParticipantMessage::from_payload(&p.bytes) {
330 out.push(LivelinessAsserted {
331 participant: c.writer.prefix,
332 kind: m.kind,
333 });
334 }
335 }
336 }
337 out
338 }
339
340 pub fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
342 let mut out = self.writer.poll(now);
343 out.extend(self.reader.poll(now));
344 out
345 }
346
347 pub fn next_deadline(&self) -> Option<Instant> {
350 [self.writer.next_deadline(), self.reader.next_deadline()]
351 .into_iter()
352 .flatten()
353 .min()
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use crate::types::Locator;
361 use std::time::Duration;
362
363 fn prefix(n: u8) -> GuidPrefix {
364 GuidPrefix([n; 12])
365 }
366
367 fn participant(n: u8) -> ParticipantData {
368 let mut p = ParticipantData::new(prefix(n), VendorId::UNKNOWN);
369 p.available_builtin_endpoints.0 |= Wlp::BUILTIN_ENDPOINTS;
370 p.metatraffic_unicast_locators = vec![Locator::udpv4(std::net::SocketAddrV4::new(
371 std::net::Ipv4Addr::LOCALHOST,
372 7400 + n as u16,
373 ))];
374 p
375 }
376
377 fn wlp(n: u8) -> Wlp {
378 Wlp::new(
379 prefix(n),
380 VendorId::UNKNOWN,
381 WriterConfig::default(),
382 ReaderConfig::default(),
383 )
384 }
385
386 #[test]
387 fn payload_round_trip() {
388 let m = ParticipantMessage {
389 participant: prefix(3),
390 kind: kind::MANUAL_LIVELINESS_UPDATE,
391 data: vec![1, 2, 3],
392 };
393 for e in [Endianness::Big, Endianness::Little] {
394 let b = m.to_payload(e);
395 assert_eq!(b.len(), 4 + 12 + 4 + 4 + 3);
397 assert_eq!(ParticipantMessage::from_payload(&b).unwrap(), m);
398 }
399 let b = m.to_payload(Endianness::Big);
400 assert_eq!(&b[..4], &[0, 0, 0, 0]);
401 assert_eq!(&b[16..24], &[0, 0, 0, 2, 0, 0, 0, 3]);
402 assert!(ParticipantMessage::from_payload(&b[..20]).is_err());
403 let mut fast = m.to_payload(Endianness::Little);
405 fast[1] = 0x03;
406 assert_eq!(ParticipantMessage::from_payload(&fast).unwrap(), m);
407 assert_eq!(&m.key_hash()[12..], &[0, 0, 0, 2]);
408 }
409
410 fn pump(
412 a: &mut Wlp,
413 b: &mut Wlp,
414 t: Instant,
415 ) -> (Vec<LivelinessAsserted>, Vec<LivelinessAsserted>) {
416 let (mut got_a, mut got_b) = (Vec::new(), Vec::new());
417 for _ in 0..10 {
418 let out_a = a.poll(t);
419 let out_b = b.poll(t);
420 if out_a.is_empty() && out_b.is_empty() {
421 break;
422 }
423 for o in out_a {
424 got_b.extend(b.handle_message(&o.bytes, t));
425 }
426 for o in out_b {
427 got_a.extend(a.handle_message(&o.bytes, t));
428 }
429 }
430 (got_a, got_b)
431 }
432
433 #[test]
434 fn assertions_reach_the_other_participant() {
435 let t = Instant::now();
436 let mut a = wlp(1);
437 let mut b = wlp(2);
438 a.assert_liveliness(kind::AUTOMATIC_LIVELINESS_UPDATE);
440 a.add_participant(&participant(2), t);
441 b.add_participant(&participant(1), t);
442 let (_, got) = pump(&mut a, &mut b, t);
443 assert_eq!(
444 got,
445 [LivelinessAsserted {
446 participant: prefix(1),
447 kind: kind::AUTOMATIC_LIVELINESS_UPDATE,
448 }]
449 );
450 a.assert_liveliness(kind::MANUAL_LIVELINESS_UPDATE);
451 a.assert_liveliness(kind::AUTOMATIC_LIVELINESS_UPDATE);
452 let (_, got) = pump(&mut a, &mut b, t + Duration::from_millis(10));
453 let kinds: Vec<[u8; 4]> = got.iter().map(|g| g.kind).collect();
454 assert_eq!(
455 kinds,
456 [
457 kind::MANUAL_LIVELINESS_UPDATE,
458 kind::AUTOMATIC_LIVELINESS_UPDATE
459 ]
460 );
461 assert_eq!(a.writer.len(), 2);
463 a.remove_participant(&prefix(2));
465 a.assert_liveliness(kind::AUTOMATIC_LIVELINESS_UPDATE);
466 assert!(a.poll(t + Duration::from_millis(20)).is_empty());
467 }
468
469 #[test]
470 fn best_effort_readers_are_served_once() {
471 let t = Instant::now();
472 let mut a = wlp(1);
473 let mut p = participant(2);
474 p.available_builtin_endpoints =
476 BuiltinEndpointSet(BuiltinEndpointSet::PARTICIPANT_MESSAGE_DATA_READER);
477 p.builtin_endpoint_qos = Some(BEST_EFFORT_PARTICIPANT_MESSAGE_DATA_READER);
478 a.add_participant(&p, t);
479 a.assert_liveliness(kind::AUTOMATIC_LIVELINESS_UPDATE);
480 assert_eq!(a.poll(t).len(), 1);
481 assert!(a.poll(t + Duration::from_secs(5)).is_empty());
483 }
484}