Skip to main content

rustorb_rtps/
typelookup.rs

1//! The built-in endpoints of the TypeLookup service (DDS-XTypes 1.3
2//! clause 7.6.3.3), with which participants ask each other for the
3//! TypeObjects of the types their endpoints announce.
4//!
5//! [`TypeLookup`] holds the four endpoints of a participant, without
6//! doing any I/O, like [`crate::sedp::Sedp`]. As a server it answers the
7//! requests addressed to it from a [`TypeRegistry`]: getTypes with the
8//! TypeObjects it has, getTypeDependencies with the types those depend
9//! on. As a client it sends requests ([`TypeLookup::request`]) and hands
10//! back the replies ([`TypeLookupReplied`]); what to do with them is the
11//! caller's.
12//!
13//! Requests and replies go to every matched reader, as the endpoints have
14//! no key: a server answers only the requests that name its instance
15//! (7.6.3.3.4), and a client matches a reply to its request by the
16//! request's identity. Some implementations put another identity in their
17//! replies; a reply that matches no request is then taken for the oldest
18//! request of the same operation to the participant that wrote it.
19
20use std::collections::HashSet;
21use std::time::Instant;
22
23use rustorb_xtypes::registry::TypeRegistry;
24use rustorb_xtypes::typelookup::{
25    GetTypeDependenciesOut, GetTypesOut, REMOTE_EX_OK, REMOTE_EX_UNKNOWN_OPERATION, ReplyHeader,
26    RequestHeader, SampleIdentity, TypeLookupCall, TypeLookupReply, TypeLookupRequest,
27    TypeLookupReturn, instance_name,
28};
29
30use crate::receiver::receive;
31use crate::reliable::{
32    MatchedReader, Outgoing, ReaderConfig, ReliableReader, ReliableWriter, WriterConfig,
33};
34use crate::spdp::ParticipantData;
35use crate::submessage::{PayloadKind, SerializedPayload, Submessage};
36use crate::types::{BuiltinEndpointSet, EntityId, Guid, GuidPrefix, VendorId};
37
38/// A reply to one of our requests.
39#[derive(Clone, Debug, PartialEq)]
40pub struct TypeLookupReplied {
41    /// The participant that replied.
42    pub server: GuidPrefix,
43    /// The request it answers, when it is known.
44    pub call: Option<TypeLookupCall>,
45    /// The reply.
46    pub reply: TypeLookupReply,
47}
48
49#[derive(Debug)]
50struct Pending {
51    id: SampleIdentity,
52    server: GuidPrefix,
53    call: TypeLookupCall,
54}
55
56fn same_operation(a: &TypeLookupCall, b: &TypeLookupReturn) -> bool {
57    matches!(
58        (a, b),
59        (TypeLookupCall::GetTypes(_), TypeLookupReturn::GetTypes(_))
60            | (
61                TypeLookupCall::GetTypeDependencies(_),
62                TypeLookupReturn::GetTypeDependencies(_)
63            )
64    )
65}
66
67/// The TypeLookup service endpoints of one participant.
68#[derive(Debug)]
69pub struct TypeLookup {
70    prefix: GuidPrefix,
71    /// Our instance name, which requests to us carry.
72    instance_name: String,
73    request_writer: ReliableWriter,
74    request_reader: ReliableReader,
75    reply_writer: ReliableWriter,
76    reply_reader: ReliableReader,
77    /// Our requests not answered yet, oldest first.
78    pending: Vec<Pending>,
79}
80
81impl TypeLookup {
82    /// The bits of `availableBuiltinEndpoints` for the endpoints provided
83    /// here (DDS-XTypes 1.3 Table 62).
84    pub const BUILTIN_ENDPOINTS: u32 = BuiltinEndpointSet::TYPE_LOOKUP_REQUEST_WRITER
85        | BuiltinEndpointSet::TYPE_LOOKUP_REQUEST_READER
86        | BuiltinEndpointSet::TYPE_LOOKUP_REPLY_WRITER
87        | BuiltinEndpointSet::TYPE_LOOKUP_REPLY_READER;
88
89    /// The endpoints of the participant `prefix`. They are RELIABLE,
90    /// KEEP_ALL and VOLATILE (7.6.3.3.3).
91    pub fn new(
92        prefix: GuidPrefix,
93        vendor_id: VendorId,
94        writer: WriterConfig,
95        reader: ReaderConfig,
96    ) -> Self {
97        let guid = |e| Guid::new(prefix, e);
98        TypeLookup {
99            prefix,
100            instance_name: instance_name(&guid(EntityId::PARTICIPANT).to_bytes()),
101            request_writer: ReliableWriter::new(
102                guid(EntityId::TL_SVC_REQ_WRITER),
103                vendor_id,
104                writer.clone(),
105            ),
106            request_reader: ReliableReader::new(
107                guid(EntityId::TL_SVC_REQ_READER),
108                vendor_id,
109                reader.clone(),
110            ),
111            reply_writer: ReliableWriter::new(
112                guid(EntityId::TL_SVC_REPLY_WRITER),
113                vendor_id,
114                writer,
115            ),
116            reply_reader: ReliableReader::new(
117                guid(EntityId::TL_SVC_REPLY_READER),
118                vendor_id,
119                reader,
120            ),
121            pending: Vec::new(),
122        }
123    }
124
125    /// Whether the participant `p` serves TypeLookup requests: it has the
126    /// request reader and the reply writer.
127    pub fn is_server(p: &ParticipantData) -> bool {
128        p.available_builtin_endpoints.contains(
129            BuiltinEndpointSet::TYPE_LOOKUP_REQUEST_READER
130                | BuiltinEndpointSet::TYPE_LOOKUP_REPLY_WRITER,
131        )
132    }
133
134    /// Connects with the endpoints of a discovered participant, as far
135    /// as its `availableBuiltinEndpoints` says it has them. The local
136    /// participant is ignored.
137    pub fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
138        if p.guid_prefix == self.prefix {
139            return;
140        }
141        let set = p.available_builtin_endpoints;
142        let uc = p.metatraffic_unicast_locators.clone();
143        let mc = p.metatraffic_multicast_locators.clone();
144        let reader = |uc: &Vec<_>, mc: &Vec<_>| MatchedReader {
145            unicast: uc.clone(),
146            multicast: mc.clone(),
147            reliable: true,
148            history: false,
149        };
150        let guid = |e| Guid::new(p.guid_prefix, e);
151        if set.contains(BuiltinEndpointSet::TYPE_LOOKUP_REQUEST_READER) {
152            self.request_writer
153                .add_matched_reader(guid(EntityId::TL_SVC_REQ_READER), reader(&uc, &mc));
154        }
155        if set.contains(BuiltinEndpointSet::TYPE_LOOKUP_REPLY_READER) {
156            self.reply_writer
157                .add_matched_reader(guid(EntityId::TL_SVC_REPLY_READER), reader(&uc, &mc));
158        }
159        if set.contains(BuiltinEndpointSet::TYPE_LOOKUP_REQUEST_WRITER) {
160            self.request_reader.add_writer(
161                guid(EntityId::TL_SVC_REQ_WRITER),
162                uc.clone(),
163                mc.clone(),
164                now,
165            );
166        }
167        if set.contains(BuiltinEndpointSet::TYPE_LOOKUP_REPLY_WRITER) {
168            self.reply_reader
169                .add_writer(guid(EntityId::TL_SVC_REPLY_WRITER), uc, mc, now);
170        }
171    }
172
173    /// Disconnects from a participant that is gone, and forgets the
174    /// requests made to it.
175    pub fn remove_participant(&mut self, prefix: &GuidPrefix) {
176        self.request_writer.remove_readers_of(prefix);
177        self.reply_writer.remove_readers_of(prefix);
178        self.request_reader.remove_writers_of(prefix);
179        self.reply_reader.remove_writers_of(prefix);
180        self.pending.retain(|p| &p.server != prefix);
181    }
182
183    /// Sends `call` to the participant `server`. It goes at the next
184    /// [`Self::poll`]; the reply comes from [`Self::handle_message`].
185    pub fn request(&mut self, server: GuidPrefix, call: TypeLookupCall) -> SampleIdentity {
186        let id = SampleIdentity {
187            writer_guid: self.request_writer.guid().to_bytes(),
188            sequence_number: self.request_writer.last_sn().0 + 1,
189        };
190        let request = TypeLookupRequest {
191            header: RequestHeader {
192                request_id: id,
193                instance_name: instance_name(&Guid::new(server, EntityId::PARTICIPANT).to_bytes()),
194            },
195            data: call.clone(),
196        };
197        if let Ok(bytes) = request.to_payload() {
198            let sn = self.request_writer.add_change(
199                None,
200                Some(SerializedPayload {
201                    kind: PayloadKind::Data,
202                    bytes,
203                }),
204            );
205            debug_assert_eq!(sn.0, id.sequence_number);
206            self.pending.push(Pending { id, server, call });
207        }
208        id
209    }
210
211    /// Whether a getTypes request for `id` is waiting for its reply.
212    pub fn is_requested(&self, id: &rustorb_xtypes::type_object::TypeIdentifier) -> bool {
213        self.pending.iter().any(|p| match &p.call {
214            TypeLookupCall::GetTypes(c) => c.type_ids.contains(id),
215            _ => false,
216        })
217    }
218
219    /// The number of requests not answered yet.
220    pub fn pending(&self) -> usize {
221        self.pending.len()
222    }
223
224    /// Processes one received RTPS message: answers the requests to this
225    /// participant from `registry`, and returns the replies to ours.
226    pub fn handle_message(
227        &mut self,
228        bytes: &[u8],
229        now: Instant,
230        registry: &TypeRegistry,
231    ) -> Vec<TypeLookupReplied> {
232        let mut out = Vec::new();
233        let Some((_, received)) = receive(bytes, self.prefix) else {
234            return out;
235        };
236        for r in received {
237            let src = r.source_prefix;
238            let (requests, replies) = match r.submessage {
239                Submessage::Data(d) => {
240                    let w = Guid::new(src, d.writer_id);
241                    match d.writer_id {
242                        EntityId::TL_SVC_REQ_WRITER => {
243                            (self.request_reader.handle_data(w, &d, r.timestamp), vec![])
244                        }
245                        EntityId::TL_SVC_REPLY_WRITER => {
246                            (vec![], self.reply_reader.handle_data(w, &d, r.timestamp))
247                        }
248                        _ => continue,
249                    }
250                }
251                Submessage::DataFrag(d) => {
252                    let w = Guid::new(src, d.writer_id);
253                    match d.writer_id {
254                        EntityId::TL_SVC_REQ_WRITER => (
255                            self.request_reader.handle_data_frag(w, &d, r.timestamp),
256                            vec![],
257                        ),
258                        EntityId::TL_SVC_REPLY_WRITER => (
259                            vec![],
260                            self.reply_reader.handle_data_frag(w, &d, r.timestamp),
261                        ),
262                        _ => continue,
263                    }
264                }
265                Submessage::Gap(g) => {
266                    let w = Guid::new(src, g.writer_id);
267                    match g.writer_id {
268                        EntityId::TL_SVC_REQ_WRITER => {
269                            (self.request_reader.handle_gap(w, &g), vec![])
270                        }
271                        EntityId::TL_SVC_REPLY_WRITER => {
272                            (vec![], self.reply_reader.handle_gap(w, &g))
273                        }
274                        _ => continue,
275                    }
276                }
277                Submessage::Heartbeat(h) => {
278                    let w = Guid::new(src, h.writer_id);
279                    match h.writer_id {
280                        EntityId::TL_SVC_REQ_WRITER => {
281                            (self.request_reader.handle_heartbeat(w, &h, now), vec![])
282                        }
283                        EntityId::TL_SVC_REPLY_WRITER => {
284                            (vec![], self.reply_reader.handle_heartbeat(w, &h, now))
285                        }
286                        _ => continue,
287                    }
288                }
289                Submessage::HeartbeatFrag(h) => {
290                    let w = Guid::new(src, h.writer_id);
291                    match h.writer_id {
292                        EntityId::TL_SVC_REQ_WRITER => {
293                            self.request_reader.handle_heartbeat_frag(w, &h, now)
294                        }
295                        EntityId::TL_SVC_REPLY_WRITER => {
296                            self.reply_reader.handle_heartbeat_frag(w, &h, now)
297                        }
298                        _ => {}
299                    }
300                    continue;
301                }
302                Submessage::AckNack(a) => {
303                    let reader = Guid::new(src, a.reader_id);
304                    match a.writer_id {
305                        EntityId::TL_SVC_REQ_WRITER => {
306                            self.request_writer.handle_acknack(reader, &a, now)
307                        }
308                        EntityId::TL_SVC_REPLY_WRITER => {
309                            self.reply_writer.handle_acknack(reader, &a, now)
310                        }
311                        _ => {}
312                    }
313                    continue;
314                }
315                Submessage::NackFrag(n) => {
316                    let reader = Guid::new(src, n.reader_id);
317                    match n.writer_id {
318                        EntityId::TL_SVC_REQ_WRITER => {
319                            self.request_writer.handle_nackfrag(reader, &n, now)
320                        }
321                        EntityId::TL_SVC_REPLY_WRITER => {
322                            self.reply_writer.handle_nackfrag(reader, &n, now)
323                        }
324                        _ => {}
325                    }
326                    continue;
327                }
328                _ => continue,
329            };
330            for c in requests {
331                let Some(p) = c.payload.filter(|p| p.kind == PayloadKind::Data) else {
332                    continue;
333                };
334                if let Ok(request) = TypeLookupRequest::from_payload(&p.bytes) {
335                    self.serve(request, registry);
336                }
337            }
338            for c in replies {
339                let Some(p) = c.payload.filter(|p| p.kind == PayloadKind::Data) else {
340                    continue;
341                };
342                if let Ok(reply) = TypeLookupReply::from_payload(&p.bytes) {
343                    out.extend(self.replied(c.writer.prefix, reply));
344                }
345            }
346        }
347        out
348    }
349
350    /// Answers a request, if it is to us.
351    fn serve(&mut self, request: TypeLookupRequest, registry: &TypeRegistry) {
352        if request.header.instance_name != self.instance_name {
353            return;
354        }
355        let (remote_ex, data) =
356            match request.data {
357                TypeLookupCall::GetTypes(call) => {
358                    // The types of a strongly connected component go together,
359                    // all or none (7.6.3.3.4.2), even when one is asked for
360                    // alone.
361                    let mut seen = HashSet::new();
362                    let types =
363                        call.type_ids
364                            .iter()
365                            .flat_map(|id| {
366                                if id.scc_identifier().is_some() {
367                                    registry.component(id).unwrap_or_default()
368                                } else {
369                                    registry
370                                .get(id)
371                                .map(|o| rustorb_xtypes::type_object::TypeIdentifierTypeObjectPair {
372                                    type_identifier: id.clone(),
373                                    type_object: o.clone(),
374                                })
375                                .into_iter()
376                                .collect()
377                                }
378                            })
379                            .filter(|p| seen.insert(p.type_identifier.clone()))
380                            .collect();
381                    (
382                        REMOTE_EX_OK,
383                        TypeLookupReturn::GetTypes(Ok(GetTypesOut {
384                            types,
385                            complete_to_minimal: Vec::new(),
386                        })),
387                    )
388                }
389                TypeLookupCall::GetTypeDependencies(call) => {
390                    // All of them at once: no continuation point.
391                    let asked: HashSet<_> = call.type_ids.iter().collect();
392                    let mut seen = HashSet::new();
393                    let dependent_typeids = call
394                        .type_ids
395                        .iter()
396                        .flat_map(|id| registry.dependencies(id).unwrap_or_default())
397                        .filter(|id| !asked.contains(id) && seen.insert(id.clone()))
398                        .filter_map(|id| registry.with_size(&id))
399                        .collect();
400                    (
401                        REMOTE_EX_OK,
402                        TypeLookupReturn::GetTypeDependencies(Ok(GetTypeDependenciesOut {
403                            dependent_typeids,
404                            continuation_point: None,
405                        })),
406                    )
407                }
408                TypeLookupCall::Unknown(d) => {
409                    (REMOTE_EX_UNKNOWN_OPERATION, TypeLookupReturn::Unknown(d))
410                }
411            };
412        let reply = TypeLookupReply {
413            header: ReplyHeader {
414                related_request_id: request.header.request_id,
415                remote_ex,
416            },
417            data,
418        };
419        if let Ok(bytes) = reply.to_payload() {
420            self.reply_writer.add_change(
421                None,
422                Some(SerializedPayload {
423                    kind: PayloadKind::Data,
424                    bytes,
425                }),
426            );
427        }
428    }
429
430    /// Matches a reply from `server` with one of our requests.
431    fn replied(&mut self, server: GuidPrefix, reply: TypeLookupReply) -> Option<TypeLookupReplied> {
432        let id = reply.header.related_request_id;
433        let at = match self.pending.iter().position(|p| p.id == id) {
434            Some(at) => Some(at),
435            // A reply to another participant's request.
436            None if id.writer_guid[..12] == self.prefix.0 => return None,
437            None => self
438                .pending
439                .iter()
440                .position(|p| p.server == server && same_operation(&p.call, &reply.data)),
441        };
442        let call = at.map(|at| self.pending.remove(at).call);
443        if call.is_none() && server == self.prefix {
444            return None;
445        }
446        Some(TypeLookupReplied {
447            server,
448            call,
449            reply,
450        })
451    }
452
453    /// The datagrams due at `now`.
454    pub fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
455        // VOLATILE: what every reader has is no longer needed.
456        self.request_writer.remove_acknowledged();
457        self.reply_writer.remove_acknowledged();
458        let mut out = self.request_writer.poll(now);
459        out.extend(self.reply_writer.poll(now));
460        out.extend(self.request_reader.poll(now));
461        out.extend(self.reply_reader.poll(now));
462        out
463    }
464
465    /// When [`Self::poll`] next has something to do, if no message comes
466    /// in before.
467    pub fn next_deadline(&self) -> Option<Instant> {
468        [
469            self.request_writer.next_deadline(),
470            self.reply_writer.next_deadline(),
471            self.request_reader.next_deadline(),
472            self.reply_reader.next_deadline(),
473        ]
474        .into_iter()
475        .flatten()
476        .min()
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use crate::types::Locator;
484    use rustorb_xtypes::type_object::TypeIdentifier;
485    use rustorb_xtypes::typelookup::{GetTypeDependenciesIn, GetTypesIn};
486    use rustorb_xtypes::types::*;
487
488    fn prefix(n: u8) -> GuidPrefix {
489        GuidPrefix([n; 12])
490    }
491
492    fn participant(n: u8) -> ParticipantData {
493        let mut p = ParticipantData::new(prefix(n), VendorId::UNKNOWN);
494        p.available_builtin_endpoints.0 |= TypeLookup::BUILTIN_ENDPOINTS;
495        p.metatraffic_unicast_locators = vec![Locator::udpv4(std::net::SocketAddrV4::new(
496            std::net::Ipv4Addr::LOCALHOST,
497            7400 + n as u16,
498        ))];
499        p
500    }
501
502    fn tl(n: u8) -> TypeLookup {
503        TypeLookup::new(
504            prefix(n),
505            VendorId::UNKNOWN,
506            WriterConfig::default(),
507            ReaderConfig::default(),
508        )
509    }
510
511    /// Delivers everything due between the two until both are quiet.
512    fn pump(
513        a: &mut TypeLookup,
514        ra: &TypeRegistry,
515        b: &mut TypeLookup,
516        rb: &TypeRegistry,
517        t: Instant,
518    ) -> (Vec<TypeLookupReplied>, Vec<TypeLookupReplied>) {
519        let (mut got_a, mut got_b) = (Vec::new(), Vec::new());
520        for _ in 0..10 {
521            let out_a = a.poll(t);
522            let out_b = b.poll(t);
523            if out_a.is_empty() && out_b.is_empty() {
524                break;
525            }
526            for o in out_a {
527                got_b.extend(b.handle_message(&o.bytes, t, rb));
528            }
529            for o in out_b {
530                got_a.extend(a.handle_message(&o.bytes, t, ra));
531            }
532        }
533        (got_a, got_b)
534    }
535
536    fn nested() -> TypeObjects {
537        let inner: Type = StructType {
538            name: "M::Inner".into(),
539            members: vec![StructMember::new("x", 0, Type::Primitive(Primitive::Int32))],
540            ..Default::default()
541        }
542        .into();
543        let outer: Type = StructType {
544            name: "M::Outer".into(),
545            members: vec![StructMember::new("i", 0, inner)],
546            ..Default::default()
547        }
548        .into();
549        TypeObjects::new(&outer).unwrap()
550    }
551
552    #[test]
553    fn types_and_dependencies_are_served() {
554        let t = Instant::now();
555        let objects = nested();
556        let mut server_types = TypeRegistry::new();
557        server_types.add_type(&objects);
558        let client_types = TypeRegistry::new();
559        let (mut a, mut b) = (tl(1), tl(2));
560        a.add_participant(&participant(2), t);
561        b.add_participant(&participant(1), t);
562
563        let root = objects.minimal_id().clone();
564        let inner = objects.information.minimal.dependent_typeids[0].clone();
565        a.request(
566            prefix(2),
567            TypeLookupCall::GetTypeDependencies(GetTypeDependenciesIn {
568                type_ids: vec![root.clone()],
569                continuation_point: None,
570            }),
571        );
572        let unknown = TypeIdentifier::Minimal([9; 14]);
573        a.request(
574            prefix(2),
575            TypeLookupCall::GetTypes(GetTypesIn {
576                type_ids: vec![root.clone(), unknown],
577            }),
578        );
579        assert_eq!(a.pending(), 2);
580        let (got, other) = pump(&mut a, &client_types, &mut b, &server_types, t);
581        assert!(other.is_empty());
582        assert_eq!(got.len(), 2);
583        assert_eq!(a.pending(), 0);
584        let TypeLookupReturn::GetTypeDependencies(Ok(deps)) = &got[0].reply.data else {
585            panic!("{:?}", got[0]);
586        };
587        assert_eq!(deps.dependent_typeids, [inner]);
588        assert!(matches!(
589            got[0].call,
590            Some(TypeLookupCall::GetTypeDependencies(_))
591        ));
592        let TypeLookupReturn::GetTypes(Ok(types)) = &got[1].reply.data else {
593            panic!("{:?}", got[1]);
594        };
595        // The unknown one is left out.
596        assert_eq!(types.types.len(), 1);
597        assert_eq!(types.types[0].type_identifier, root);
598        assert_eq!(got[1].server, prefix(2));
599
600        // Requests to another participant are not answered.
601        let mut c = tl(3);
602        c.add_participant(&participant(1), t);
603        a.add_participant(&participant(3), t);
604        a.request(
605            prefix(4),
606            TypeLookupCall::GetTypes(GetTypesIn {
607                type_ids: vec![root],
608            }),
609        );
610        let (got, _) = pump(&mut a, &client_types, &mut c, &server_types, t);
611        assert!(got.is_empty());
612        assert_eq!(a.pending(), 1);
613        a.remove_participant(&prefix(4));
614        assert_eq!(a.pending(), 0);
615    }
616
617    #[test]
618    fn replies_with_another_identity_are_matched_by_operation() {
619        let mut a = tl(1);
620        let call = TypeLookupCall::GetTypes(GetTypesIn {
621            type_ids: vec![TypeIdentifier::Minimal([1; 14])],
622        });
623        a.request(prefix(2), call.clone());
624        let reply = |guid: [u8; 16]| TypeLookupReply {
625            header: ReplyHeader {
626                related_request_id: SampleIdentity {
627                    writer_guid: guid,
628                    sequence_number: 1,
629                },
630                remote_ex: REMOTE_EX_OK,
631            },
632            data: TypeLookupReturn::GetTypes(Ok(GetTypesOut::default())),
633        };
634        // From a participant we did not ask: handed on, with no request.
635        assert!(
636            a.replied(prefix(3), reply([7; 16]))
637                .is_some_and(|r| r.call.is_none())
638        );
639        // As Cyclone DDS 0.10.4 answers: its own reply writer as the
640        // identity.
641        let cyclone = Guid::new(prefix(2), EntityId::TL_SVC_REPLY_WRITER).to_bytes();
642        let got = a.replied(prefix(2), reply(cyclone)).unwrap();
643        assert_eq!(got.call, Some(call));
644        assert_eq!(a.pending(), 0);
645        // A late reply to a request of ours that was answered already.
646        let ours = Guid::new(prefix(1), EntityId::TL_SVC_REQ_WRITER).to_bytes();
647        assert!(a.replied(prefix(2), reply(ours)).is_none());
648    }
649}