Skip to main content

rustorb_dds/rpc/
mod.rs

1//! Requests and replies over DDS (DDS-RPC 1.0): a [`Requester`] sends
2//! requests on a request topic and gets the replies to them on a reply
3//! topic; a [`Replier`] takes the requests and answers each one.
4//!
5//! A reply names the request it answers with its related sample identity
6//! (`PID_RELATED_SAMPLE_IDENTITY`, sent in-line, DDS-RPC 1.0, 7.8.2): the
7//! writer and sequence number of the request, as in the Enhanced Service
8//! Mapping (7.4.3), so the request and reply types are the user's own, with
9//! no header. The topics are `<service>_Request` and `<service>_Reply`
10//! (7.4.1), or names given in [`RpcConfig`].
11//!
12//! A request also names, as its related sample identity, the requester's
13//! reply reader (with `SEQUENCENUMBER_UNKNOWN`), and a replier answers a
14//! request that names one with that reader and the request's sequence
15//! number: ROS 2's rmw_fastrtps_cpp does both (seen in captures), so its
16//! clients and services work with these. Others ignore the identity of a
17//! request (7.8.2 gives it to replies).
18//!
19//! Each side announces its writer and reader as a pair through discovery,
20//! with `PID_RELATED_ENTITY_GUID` (7.6.2.1), and holds back what would
21//! go astray while the other side's pair is half discovered (7.6.2.2): a
22//! [`Replier`] does not hand out the requests of a requester until it has
23//! matched that requester's reply reader, and
24//! [`Requester::wait_for_service`] waits for a replier both of whose
25//! endpoints are matched. A remote endpoint that does not announce a
26//! related entity is paired with those of the same participant.
27//!
28//! ROS 2's rmw_cyclonedds_cpp puts a header in the payload instead,
29//! between the encapsulation and the body (seen in captures): the client's
30//! 8-octet id and a 64-bit sequence number of its own, in the byte order of
31//! the encapsulation, which the service sends back at the head of the
32//! reply. With the endpoints of a participant of Cyclone DDS (vendor
33//! 0x0110), a [`Requester`] and a [`Replier`] write and read that header.
34//! Its services answer only a client whose reply reader they have matched,
35//! known by `clientid= ...;` in the USER_DATA of the client's writer and
36//! reader, which a [`Requester`] announces.
37//!
38//! A [`Replier`] sends each reply only to the reply reader of the
39//! requester that asked, when it knows which (the reader the request
40//! names, or the one paired with the request's writer): the others are
41//! sent a GAP for it, so that a requester does not get the replies to
42//! the others (7.2.1).
43//!
44//! The topics may have aliases (`PID_TOPIC_ALIASES`, 7.4.3), set in
45//! [`RpcConfig`]: an endpoint matches those of a topic named by an alias
46//! of its own or whose alias is its topic, as a service of a derived
47//! interface does with the clients of its bases.
48//!
49//! [`Requester::basic`] and [`Replier::basic`] make them for the Basic
50//! Service Mapping (7.5.1.1), whose request and reply types start with a
51//! [`RequestHeader`] and a [`ReplyHeader`] ([`BasicRequest`],
52//! [`BasicReply`]): the requester writes the identity of each request in
53//! its header, the replier copies it to the reply's, and the requester
54//! reads it there. The requester reads the replies through a content
55//! filtered topic that passes only those to its requests (7.2.1).
56
57use std::collections::HashMap;
58use std::sync::Mutex;
59use std::time::{Duration, Instant};
60
61use rustorb_rtps::{EntityId, Guid, GuidPrefix, SampleIdentity, SequenceNumber, VendorId};
62use rustorb_typesupport::TopicType;
63use rustorb_xtypes::types::DescribeType;
64
65use crate::participant::Shared;
66use crate::publisher::{DataWriter, WriteParams};
67use crate::qos::{DataReaderQos, DataWriterQos, History, Reliability};
68use crate::subscriber::DataReader;
69use crate::topic::TopicDescription;
70use crate::{DomainParticipant, Error, Result, SampleInfo, Topic};
71
72/// The common types of the Basic Service Mapping (DDS-RPC 1.0,
73/// 7.5.1.1.1), as `rustorb-idl -brust -Wbdds_only -Wbxtypes` writes them
74/// from `DdsRpc.idl`: the modules `dds` and `dds::rpc`. Generated code
75/// refers to them with `-Wbextern=dds=::rustorb_dds::rpc::idl::dds`.
76#[allow(missing_docs, clippy::all)]
77#[rustfmt::skip]
78#[path = "dds_rpc.rs"]
79pub mod idl;
80
81pub use idl::dds::rpc::{RemoteExceptionCodeT as RemoteExceptionCode, ReplyHeader, RequestHeader};
82
83impl From<SampleIdentity> for idl::dds::SampleIdentity {
84    fn from(id: SampleIdentity) -> Self {
85        let g = id.writer_guid;
86        let sn = id.sequence_number.0;
87        idl::dds::SampleIdentity {
88            writer_guid: idl::dds::GuidT {
89                guid_prefix: g.prefix.0,
90                entity_id: idl::dds::EntityIdT {
91                    entity_key: g.entity_id.entity_key,
92                    entity_kind: g.entity_id.entity_kind,
93                },
94            },
95            sequence_number: idl::dds::SequenceNumberT {
96                high: (sn >> 32) as i32,
97                low: sn as u32,
98            },
99        }
100    }
101}
102
103impl From<idl::dds::SampleIdentity> for SampleIdentity {
104    fn from(id: idl::dds::SampleIdentity) -> Self {
105        let g = id.writer_guid;
106        let sn = id.sequence_number;
107        SampleIdentity {
108            writer_guid: Guid::new(
109                GuidPrefix(g.guid_prefix),
110                EntityId {
111                    entity_key: g.entity_id.entity_key,
112                    entity_kind: g.entity_id.entity_kind,
113                },
114            ),
115            sequence_number: SequenceNumber((i64::from(sn.high) << 32) | i64::from(sn.low)),
116        }
117    }
118}
119
120/// What the code of the DDS services that `rustorb-idl -brust
121/// -Wbdds_only` writes needs (the function-call style of DDS-RPC 1.0):
122/// generated code refers to it and does not compile against a runtime
123/// without it.
124pub const GENERATED_CODE_VERSION_1: () = ();
125
126/// Why a call of the function-call style failed (DDS-RPC 1.0, 7.5.2,
127/// 7.11.1.3): an exception the operation raises (`E`), a remote exception
128/// code the service sent, or a local error.
129#[derive(Debug)]
130pub enum RpcError<E> {
131    /// An exception of the operation.
132    Exception(E),
133    /// A remote exception code other than `REMOTE_EX_OK`: the operation is
134    /// not known or not implemented, an argument was not valid, ...
135    Remote(RemoteExceptionCode),
136    /// A reply that answers nothing the call can take.
137    InvalidReply,
138    /// A local error, such as [`Error::Timeout`] when no reply came.
139    Dds(Error),
140}
141
142impl<E> RpcError<E> {
143    /// The remote exception code a service sends for this error:
144    /// `REMOTE_EX_UNKNOWN_EXCEPTION` for all but a [`RpcError::Remote`].
145    pub fn remote_code(&self) -> RemoteExceptionCode {
146        match self {
147            RpcError::Remote(code) => *code,
148            _ => RemoteExceptionCode::RemoteExUnknownException,
149        }
150    }
151}
152
153impl<E> From<Error> for RpcError<E> {
154    fn from(e: Error) -> Self {
155        RpcError::Dds(e)
156    }
157}
158
159impl<E: std::fmt::Debug> std::fmt::Display for RpcError<E> {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        match self {
162            RpcError::Exception(e) => write!(f, "exception {e:?}"),
163            RpcError::Remote(code) => write!(f, "remote exception {code:?}"),
164            RpcError::InvalidReply => f.write_str("a reply that is not valid"),
165            RpcError::Dds(e) => write!(f, "{e}"),
166        }
167    }
168}
169
170impl<E: std::fmt::Debug> std::error::Error for RpcError<E> {}
171
172/// A request type of the Basic Service Mapping: a struct with a member
173/// `header` of type [`RequestHeader`] (DDS-RPC 1.0, 7.3.1.4, 7.5.1.1.6).
174pub trait BasicRequest {
175    /// The header.
176    fn header(&self) -> &RequestHeader;
177    /// The header, to change.
178    fn header_mut(&mut self) -> &mut RequestHeader;
179}
180
181/// A reply type of the Basic Service Mapping: a struct with a member
182/// `header` of type [`ReplyHeader`] (DDS-RPC 1.0, 7.3.1.4, 7.5.1.1.7).
183pub trait BasicReply {
184    /// The header.
185    fn header(&self) -> &ReplyHeader;
186    /// The header, to change.
187    fn header_mut(&mut self) -> &mut ReplyHeader;
188}
189
190/// The parts of a [`Requester`] of the Basic Service Mapping.
191struct RequesterBasic<Req, Rep> {
192    /// The request with this header.
193    with_header: fn(&Req, RequestHeader) -> Req,
194    /// The request a reply answers.
195    answers: fn(&Rep) -> SampleIdentity,
196    /// The instance name the requests carry.
197    instance_name: String,
198    /// Held while a request is written, so that the sequence number in its
199    /// header is the one it gets.
200    lock: Mutex<()>,
201}
202
203/// The parts of a [`Replier`] of the Basic Service Mapping.
204struct ReplierBasic<Req, Rep> {
205    /// The header of a request.
206    header: fn(&Req) -> RequestHeader,
207    /// The reply naming this request.
208    answering: fn(&Rep, SampleIdentity) -> Rep,
209}
210
211/// The filter that passes the replies of the Basic Service Mapping to the
212/// requests of the writer `writer`: on the GUID of the related request,
213/// octet by octet.
214fn reply_filter(writer: &Guid) -> (String, Vec<String>) {
215    let id = "header.relatedRequestId.writer_guid";
216    let mut terms: Vec<String> = (0..12)
217        .map(|i| format!("{id}.guidPrefix[{i}] = %{i}"))
218        .collect();
219    terms.extend((0..3).map(|i| format!("{id}.entityId.entityKey[{i}] = %{}", 12 + i)));
220    terms.push(format!("{id}.entityId.entityKind = %15"));
221    let e = &writer.entity_id;
222    let params = writer
223        .prefix
224        .0
225        .iter()
226        .chain(&e.entity_key)
227        .chain([&e.entity_kind])
228        .map(|b| b.to_string())
229        .collect();
230    (terms.join(" AND "), params)
231}
232
233/// The vendor of Cyclone DDS, whose ROS 2 services carry a header in the
234/// payload.
235const CYCLONE: VendorId = VendorId([0x01, 0x10]);
236
237/// The length of the encapsulation and of the in-payload header.
238const ENCAP: usize = 4;
239const HEADER: usize = 16;
240
241/// An in-payload header: the client id and the sequence number.
242type Header = ([u8; 8], i64);
243
244/// Whether the endpoint `guid` is of a participant of Cyclone DDS.
245fn is_cyclone(shared: &Shared, guid: &Guid) -> bool {
246    shared.vendor_of(&guid.prefix) == Some(CYCLONE)
247}
248
249/// Whether a payload's encapsulation is little-endian.
250fn little_endian(payload: &[u8]) -> bool {
251    payload.get(1).is_some_and(|b| b & 1 == 1)
252}
253
254/// Puts the header (`client`, `seq`) after the encapsulation of `payload`.
255fn insert_header(mut payload: Vec<u8>, client: [u8; 8], seq: i64) -> Vec<u8> {
256    let mut header = [0u8; HEADER];
257    header[..8].copy_from_slice(&client);
258    header[8..].copy_from_slice(&if little_endian(&payload) {
259        seq.to_le_bytes()
260    } else {
261        seq.to_be_bytes()
262    });
263    let at = ENCAP.min(payload.len());
264    payload.splice(at..at, header);
265    payload
266}
267
268/// Takes the header out of `payload`: the client id and the sequence
269/// number, and the payload left.
270fn strip_header(payload: &[u8]) -> Option<([u8; 8], i64, Vec<u8>)> {
271    if payload.len() < ENCAP + HEADER {
272        return None;
273    }
274    let h = &payload[ENCAP..ENCAP + HEADER];
275    let client: [u8; 8] = h[..8].try_into().ok()?;
276    let seq: [u8; 8] = h[8..].try_into().ok()?;
277    let seq = if little_endian(payload) {
278        i64::from_le_bytes(seq)
279    } else {
280        i64::from_be_bytes(seq)
281    };
282    let mut rest = payload[..ENCAP].to_vec();
283    rest.extend_from_slice(&payload[ENCAP + HEADER..]);
284    Some((client, seq, rest))
285}
286
287/// Takes the samples of `reader`, deserialized, with the header of those
288/// written by a participant of Cyclone DDS taken out of the payload.
289fn take_with_headers<T>(reader: &DataReader<T>) -> Vec<(T, SampleInfo, Option<Header>)> {
290    let shared = &reader.shared;
291    reader
292        .take_raw()
293        .into_iter()
294        .filter_map(|(payload, info)| {
295            let payload = payload?;
296            if is_cyclone(shared, &info.writer) {
297                let (client, seq, rest) = strip_header(&payload)?;
298                Some((reader.decode_raw(&rest)?, info, Some((client, seq))))
299            } else {
300                Some((reader.decode_raw(&payload)?, info, None))
301            }
302        })
303        .collect()
304}
305
306/// How a [`Requester`] or [`Replier`] is made.
307#[derive(Clone, Debug)]
308pub struct RpcConfig {
309    /// The topic of the requests.
310    pub request_topic: String,
311    /// The topic of the replies.
312    pub reply_topic: String,
313    /// The service instance name a replier announces
314    /// (`PID_SERVICE_INSTANCE_NAME`, DDS-RPC 1.0, 7.6.2.1); a requester
315    /// announces none.
316    pub service_instance_name: Option<String>,
317    /// The QoS of the writer (of requests for a requester, of replies for
318    /// a replier).
319    pub writer_qos: DataWriterQos,
320    /// The QoS of the reader.
321    pub reader_qos: DataReaderQos,
322    /// The aliases of the request topic (`PID_TOPIC_ALIASES`, DDS-RPC
323    /// 1.0, 7.4.3): those a service of a derived interface announces for
324    /// its bases. Empty by default.
325    pub request_topic_aliases: Vec<String>,
326    /// The aliases of the reply topic.
327    pub reply_topic_aliases: Vec<String>,
328}
329
330impl RpcConfig {
331    /// The topics `<service>_Request` and `<service>_Reply` (DDS-RPC
332    /// 1.0, 7.4.1), RELIABLE and KEEP_ALL on both sides.
333    pub fn new(service: &str) -> Self {
334        RpcConfig::with_topics(&format!("{service}_Request"), &format!("{service}_Reply"))
335    }
336
337    /// The topics given, RELIABLE and KEEP_ALL on both sides.
338    pub fn with_topics(request_topic: &str, reply_topic: &str) -> Self {
339        RpcConfig {
340            request_topic: request_topic.to_string(),
341            reply_topic: reply_topic.to_string(),
342            service_instance_name: None,
343            writer_qos: DataWriterQos {
344                reliability: Reliability::reliable(),
345                history: History::KeepAll,
346                ..DataWriterQos::default()
347            },
348            reader_qos: DataReaderQos {
349                reliability: Reliability::reliable(),
350                history: History::KeepAll,
351                ..DataReaderQos::default()
352            },
353            request_topic_aliases: Vec::new(),
354            reply_topic_aliases: Vec::new(),
355        }
356    }
357}
358
359/// Whether the remote endpoints `a` and `b` are announced as a pair: one
360/// names the other as its related entity or, when neither names any, they
361/// are of the same participant.
362fn paired(shared: &Shared, a: &Guid, b: &Guid) -> bool {
363    let rel = |g: &Guid| shared.endpoint_data(g).and_then(|d| d.related_entity_guid);
364    match (rel(a), rel(b)) {
365        (None, None) => a.prefix == b.prefix,
366        (ra, rb) => ra == Some(*b) || rb == Some(*a),
367    }
368}
369
370/// Announces `writer` and `reader` as a pair (DDS-RPC 1.0, 7.6.2.1).
371fn pair<A, B>(
372    writer: &DataWriter<A>,
373    reader: &DataReader<B>,
374    instance_name: Option<&String>,
375) -> Result<()> {
376    let (w, r) = (writer.guid, reader.guid);
377    writer.shared.update_endpoint(&w, |d| {
378        d.related_entity_guid = Some(r);
379        d.service_instance_name = instance_name.cloned();
380    })?;
381    reader.shared.update_endpoint(&r, |d| {
382        d.related_entity_guid = Some(w);
383        d.service_instance_name = instance_name.cloned();
384    })
385}
386
387/// Puts `clientid= <octets>;` at the head of the USER_DATA of a
388/// requester's writer and reader, the octets being the writer's GUID in
389/// hexadecimal, separated by dots: a service of rmw_cyclonedds_cpp
390/// answers a request only when it has matched a reader with the
391/// `clientid` of the request's writer (seen in captures, where its own
392/// clients announce one).
393fn announce_client_id<A, B>(writer: &DataWriter<A>, reader: &DataReader<B>) -> Result<()> {
394    let g = writer.guid;
395    let e = &g.entity_id;
396    let octets: Vec<String> = g
397        .prefix
398        .0
399        .iter()
400        .chain(&e.entity_key)
401        .chain([&e.entity_kind])
402        .map(|b| format!("{b:x}"))
403        .collect();
404    let id = format!("clientid= {};", octets.join("."));
405    let add = |d: &mut rustorb_rtps::sedp::EndpointData| {
406        if !d.user_data.starts_with(b"clientid=") {
407            d.user_data.splice(0..0, id.bytes());
408        }
409    };
410    writer.shared.update_endpoint(&writer.guid, add)?;
411    reader.shared.update_endpoint(&reader.guid, add)
412}
413
414/// Waits, a little at a time, until `f` gives something or `timeout`
415/// passes.
416fn wait_until<R>(timeout: Duration, mut f: impl FnMut() -> Option<R>) -> Option<R> {
417    let deadline = Instant::now() + timeout;
418    loop {
419        if let Some(r) = f() {
420            return Some(r);
421        }
422        if Instant::now() >= deadline {
423            return None;
424        }
425        std::thread::sleep(Duration::from_millis(5));
426    }
427}
428
429/// The client side of a service: sends requests of type `Req` and gets
430/// the replies of type `Rep` to them (DDS-RPC 1.0, 7.8.1).
431pub struct Requester<Req, Rep> {
432    writer: DataWriter<Req>,
433    reader: DataReader<Rep>,
434    /// Replies taken from the reader and not yet given out, by the
435    /// request they answer.
436    replies: Mutex<HashMap<SampleIdentity, Vec<Rep>>>,
437    /// The client id of the in-payload header.
438    client_id: [u8; 8],
439    /// The last sequence number of the in-payload header, and the
440    /// requests sent with one by it.
441    headers: Mutex<(i64, HashMap<i64, SampleIdentity>)>,
442    /// For the Basic Service Mapping.
443    basic: Option<RequesterBasic<Req, Rep>>,
444}
445
446impl<Req, Rep> std::fmt::Debug for Requester<Req, Rep> {
447    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448        f.debug_struct("Requester")
449            .field("writer", &self.writer.guid)
450            .field("reader", &self.reader.guid)
451            .finish()
452    }
453}
454
455impl<Req: TopicType + 'static, Rep: TopicType + 'static> Requester<Req, Rep> {
456    /// A requester of the service `service`, on its default topics.
457    pub fn new(participant: &DomainParticipant, service: &str) -> Result<Self> {
458        Requester::with_config(participant, &RpcConfig::new(service))
459    }
460
461    /// A requester made as `config` says.
462    pub fn with_config(participant: &DomainParticipant, config: &RpcConfig) -> Result<Self> {
463        let request = participant.create_topic::<Req>(&config.request_topic)?;
464        let reply = participant.create_topic::<Rep>(&config.reply_topic)?;
465        Requester::with_topics(participant, &request, &reply, config)
466    }
467}
468
469impl<Req, Rep> Requester<Req, Rep>
470where
471    Req: TopicType + BasicRequest + Clone + 'static,
472    Rep: TopicType + DescribeType + BasicReply + 'static,
473{
474    /// A requester of the Basic Service Mapping (DDS-RPC 1.0, 7.5.1.1)
475    /// made as `config` says: it writes the identity of each request in
476    /// its header, with the `service_instance_name` of `config` (empty
477    /// when `None`) as the instance name, and takes the replies whose
478    /// header names one of its requests, through a content filtered topic
479    /// of the reply topic (7.2.1) that its reader announces.
480    pub fn basic(participant: &DomainParticipant, config: &RpcConfig) -> Result<Self> {
481        let request = participant.create_topic::<Req>(&config.request_topic)?;
482        let reply = participant.create_topic::<Rep>(&config.reply_topic)?;
483        participant.register_type::<Rep>()?;
484        let basic = RequesterBasic {
485            with_header: |r: &Req, h| {
486                let mut r = r.clone();
487                *r.header_mut() = h;
488                r
489            },
490            answers: |r: &Rep| r.header().related_request_id.into(),
491            instance_name: config.service_instance_name.clone().unwrap_or_default(),
492            lock: Mutex::new(()),
493        };
494        let writer = request_writer(participant, &request, config)?;
495        let (expression, parameters) = reply_filter(&writer.guid);
496        let g = writer.guid;
497        let name = format!(
498            "{}_{}",
499            reply.name(),
500            g.prefix
501                .0
502                .iter()
503                .chain(&g.entity_id.entity_key)
504                .chain([&g.entity_id.entity_kind])
505                .map(|b| format!("{b:02x}"))
506                .collect::<String>()
507        );
508        let filtered =
509            participant.create_contentfilteredtopic(&name, &reply, &expression, &parameters)?;
510        Requester::make(participant, writer, &filtered, config, Some(basic))
511    }
512}
513
514/// The request writer of a requester.
515fn request_writer<Req>(
516    participant: &DomainParticipant,
517    request: &Topic<Req>,
518    config: &RpcConfig,
519) -> Result<DataWriter<Req>> {
520    participant.create_publisher()?.create_datawriter_with(
521        request,
522        config.writer_qos.clone(),
523        |d| d.topic_aliases = config.request_topic_aliases.clone(),
524    )
525}
526
527impl<Req, Rep> Requester<Req, Rep> {
528    /// A requester on the topics given, of any sample type (such as
529    /// [`DynamicData`](crate::DynamicData)), with the QoS of `config` (its
530    /// topic names are not used).
531    pub fn with_topics(
532        participant: &DomainParticipant,
533        request: &Topic<Req>,
534        reply: &Topic<Rep>,
535        config: &RpcConfig,
536    ) -> Result<Self> {
537        let writer = request_writer(participant, request, config)?;
538        Requester::make(participant, writer, reply, config, None)
539    }
540
541    fn make(
542        participant: &DomainParticipant,
543        writer: DataWriter<Req>,
544        reply: &impl TopicDescription<Rep>,
545        config: &RpcConfig,
546        basic: Option<RequesterBasic<Req, Rep>>,
547    ) -> Result<Self> {
548        let reader = participant.create_subscriber()?.create_datareader_with(
549            reply,
550            config.reader_qos.clone(),
551            |d| d.topic_aliases = config.reply_topic_aliases.clone(),
552        )?;
553        pair(&writer, &reader, None)?;
554        announce_client_id(&writer, &reader)?;
555        // FNV-1a of the writer's GUID.
556        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
557        let e = &writer.guid.entity_id;
558        for b in writer
559            .guid
560            .prefix
561            .0
562            .iter()
563            .chain(&e.entity_key)
564            .chain([&e.entity_kind])
565        {
566            h = (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3);
567        }
568        Ok(Requester {
569            writer,
570            reader,
571            replies: Mutex::new(HashMap::new()),
572            client_id: h.to_be_bytes(),
573            headers: Mutex::new((0, HashMap::new())),
574            basic,
575        })
576    }
577
578    /// The writer of the requests.
579    pub fn request_datawriter(&self) -> &DataWriter<Req> {
580        &self.writer
581    }
582
583    /// The reader of the replies.
584    pub fn reply_datareader(&self) -> &DataReader<Rep> {
585        &self.reader
586    }
587
588    /// Whether a replier is matched: a request reader matched by the
589    /// request writer, and its reply writer matched by the reply reader
590    /// (DDS-RPC 1.0, 7.6.2.2.2).
591    pub fn is_service_matched(&self) -> bool {
592        let shared = &self.writer.shared;
593        let writers = self.reader.matched_publications();
594        self.writer.matched_subscriptions().iter().any(|r| {
595            writers.iter().any(|w| {
596                // Cyclone DDS drops a request that comes before it
597                // knows the reply reader with the request writer's
598                // clientid, so wait until it has acknowledged the
599                // latest announcements of both.
600                paired(shared, r, w)
601                    && (!is_cyclone(shared, w)
602                        || [self.writer.guid, self.reader.guid]
603                            .iter()
604                            .all(|g| shared.is_announced_to(g, &w.prefix)))
605            })
606        })
607    }
608
609    /// Waits until [`is_service_matched`](Self::is_service_matched), or
610    /// `timeout` passes; returns whether it is.
611    pub fn wait_for_service(&self, timeout: Duration) -> bool {
612        wait_until(timeout, || self.is_service_matched().then_some(())).is_some()
613    }
614
615    /// Sends a request; returns its identity, which its replies name.
616    ///
617    /// When a request reader of Cyclone DDS is matched, the request
618    /// carries the in-payload header too.
619    pub fn send_request(&self, request: &Req) -> Result<SampleIdentity> {
620        if let Some(b) = &self.basic {
621            let _held = b.lock.lock().map_err(|_| Error::PreconditionNotMet)?;
622            let last = self.writer.shared.last_sequence_number(&self.writer.guid)?;
623            let id = SampleIdentity {
624                writer_guid: self.writer.guid,
625                sequence_number: SequenceNumber(last.0 + 1),
626            };
627            let header = RequestHeader {
628                request_id: id.into(),
629                instance_name: b.instance_name.clone(),
630            };
631            self.writer
632                .write_w_params(&(b.with_header)(request, header), &WriteParams::default())?;
633            return Ok(id);
634        }
635        let params = WriteParams {
636            related_sample_identity: Some(SampleIdentity {
637                writer_guid: self.reader.guid,
638                sequence_number: SequenceNumber::UNKNOWN,
639            }),
640            ..WriteParams::default()
641        };
642        let shared = &self.writer.shared;
643        let cyclone = self
644            .writer
645            .matched_subscriptions()
646            .iter()
647            .any(|r| is_cyclone(shared, r));
648        if !cyclone {
649            return self.writer.write_w_params(request, &params);
650        }
651        let mut headers = self.headers.lock().map_err(|_| Error::PreconditionNotMet)?;
652        let seq = headers.0 + 1;
653        let id = self
654            .writer
655            .write_mapped(request, &params, |p| insert_header(p, self.client_id, seq))?;
656        headers.0 = seq;
657        headers.1.insert(seq, id);
658        Ok(id)
659    }
660
661    /// Moves the replies to this requester's requests from the reader to
662    /// `replies`; drops those to others.
663    fn collect(&self) -> Result<std::sync::MutexGuard<'_, HashMap<SampleIdentity, Vec<Rep>>>> {
664        let mut replies = self.replies.lock().map_err(|_| Error::PreconditionNotMet)?;
665        for (data, info, header) in take_with_headers(&self.reader) {
666            let id = match header {
667                // The reply's header names the request.
668                _ if self.basic.is_some() => self.basic.as_ref().map(|b| (b.answers)(&data)),
669                // The header names the request.
670                Some((client, seq)) => {
671                    if client != self.client_id {
672                        continue;
673                    }
674                    let mut headers = self.headers.lock().map_err(|_| Error::PreconditionNotMet)?;
675                    headers.1.remove(&seq)
676                }
677                None => info.related_sample_identity,
678            };
679            let Some(mut id) = id else {
680                continue;
681            };
682            // A reply names the request, or the reply reader with the
683            // request's sequence number.
684            if id.writer_guid == self.reader.guid {
685                id.writer_guid = self.writer.guid;
686            }
687            if id.writer_guid == self.writer.guid {
688                replies.entry(id).or_default().push(data);
689            }
690        }
691        Ok(replies)
692    }
693
694    /// Takes the replies come so far to the request `request`.
695    pub fn take_replies(&self, request: &SampleIdentity) -> Result<Vec<Rep>> {
696        Ok(self.collect()?.remove(request).unwrap_or_default())
697    }
698
699    /// Takes the replies come so far to any request of this requester,
700    /// with the request each answers.
701    pub fn take_all_replies(&self) -> Result<Vec<(SampleIdentity, Rep)>> {
702        let mut replies = self.collect()?;
703        let mut all: Vec<(SampleIdentity, Rep)> = replies
704            .drain()
705            .flat_map(|(id, v)| v.into_iter().map(move |r| (id, r)))
706            .collect();
707        all.sort_by_key(|(id, _)| id.sequence_number);
708        Ok(all)
709    }
710
711    /// Waits for a reply to `request` and takes it; fails with
712    /// [`Error::Timeout`] when `timeout` passes first.
713    pub fn receive_reply(&self, request: &SampleIdentity, timeout: Duration) -> Result<Rep> {
714        wait_until(timeout, || match self.collect() {
715            Ok(mut replies) => {
716                let v = replies.get_mut(request)?;
717                let r = v.remove(0);
718                if v.is_empty() {
719                    replies.remove(request);
720                }
721                Some(Ok(r))
722            }
723            Err(e) => Some(Err(e)),
724        })
725        .unwrap_or(Err(Error::Timeout))
726    }
727
728    /// Sends a request and waits for its first reply.
729    pub fn request(&self, request: &Req, timeout: Duration) -> Result<Rep> {
730        let id = self.send_request(request)?;
731        self.receive_reply(&id, timeout)
732    }
733}
734
735/// A request taken by a [`Replier`].
736#[derive(Clone, Debug, PartialEq)]
737pub struct Request<Req> {
738    /// The request.
739    pub data: Req,
740    /// What the reply names: the request's writer and sequence number,
741    /// or the reader the request named (as a ROS 2 client names its reply
742    /// reader) with the request's sequence number.
743    pub id: SampleIdentity,
744    /// The writer of the request.
745    pub writer: Guid,
746}
747
748/// The service side: takes requests of type `Req` and answers each with
749/// replies of type `Rep` (DDS-RPC 1.0, 7.8.1).
750pub struct Replier<Req, Rep> {
751    reader: DataReader<Req>,
752    writer: DataWriter<Rep>,
753    /// Requests of requesters whose reply reader is not yet matched,
754    /// held back (DDS-RPC 1.0, 7.6.2.2.1).
755    held: Mutex<Vec<Request<Req>>>,
756    /// The in-payload headers of the requests not yet answered, by the
757    /// identity a reply names.
758    headers: Mutex<HashMap<SampleIdentity, Header>>,
759    /// The service instance name.
760    instance_name: Option<String>,
761    /// For the Basic Service Mapping.
762    basic: Option<ReplierBasic<Req, Rep>>,
763}
764
765impl<Req, Rep> std::fmt::Debug for Replier<Req, Rep> {
766    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
767        f.debug_struct("Replier")
768            .field("reader", &self.reader.guid)
769            .field("writer", &self.writer.guid)
770            .finish()
771    }
772}
773
774impl<Req: TopicType + 'static, Rep: TopicType + 'static> Replier<Req, Rep> {
775    /// A replier of the service `service`, on its default topics.
776    pub fn new(participant: &DomainParticipant, service: &str) -> Result<Self> {
777        Replier::with_config(participant, &RpcConfig::new(service))
778    }
779
780    /// A replier made as `config` says.
781    pub fn with_config(participant: &DomainParticipant, config: &RpcConfig) -> Result<Self> {
782        let request = participant.create_topic::<Req>(&config.request_topic)?;
783        let reply = participant.create_topic::<Rep>(&config.reply_topic)?;
784        Replier::with_topics(participant, &request, &reply, config)
785    }
786}
787
788impl<Req, Rep> Replier<Req, Rep>
789where
790    Req: TopicType + BasicRequest + 'static,
791    Rep: TopicType + BasicReply + Clone + 'static,
792{
793    /// A replier of the Basic Service Mapping (DDS-RPC 1.0, 7.5.1.1)
794    /// made as `config` says: a request is known by the identity in its
795    /// header, which [`send_reply`](Self::send_reply) writes in the
796    /// header of the reply (its `remote_ex` is left as it is). With a
797    /// `service_instance_name`, it drops the requests for another
798    /// instance (a request with an empty instance name is for any).
799    pub fn basic(participant: &DomainParticipant, config: &RpcConfig) -> Result<Self> {
800        let request = participant.create_topic::<Req>(&config.request_topic)?;
801        let reply = participant.create_topic::<Rep>(&config.reply_topic)?;
802        let mut replier = Replier::with_topics(participant, &request, &reply, config)?;
803        replier.basic = Some(ReplierBasic {
804            header: |r: &Req| r.header().clone(),
805            answering: |r: &Rep, id| {
806                let mut r = r.clone();
807                r.header_mut().related_request_id = id.into();
808                r
809            },
810        });
811        Ok(replier)
812    }
813}
814
815impl<Req, Rep> Replier<Req, Rep> {
816    /// A replier on the topics given, of any sample type (such as
817    /// [`DynamicData`](crate::DynamicData)), with the QoS and the service
818    /// instance name of `config` (its topic names are not used).
819    pub fn with_topics(
820        participant: &DomainParticipant,
821        request: &Topic<Req>,
822        reply: &Topic<Rep>,
823        config: &RpcConfig,
824    ) -> Result<Self> {
825        let reader = participant.create_subscriber()?.create_datareader_with(
826            request,
827            config.reader_qos.clone(),
828            |d| d.topic_aliases = config.request_topic_aliases.clone(),
829        )?;
830        let writer = participant.create_publisher()?.create_datawriter_with(
831            reply,
832            config.writer_qos.clone(),
833            |d| d.topic_aliases = config.reply_topic_aliases.clone(),
834        )?;
835        pair(&writer, &reader, config.service_instance_name.as_ref())?;
836        Ok(Replier {
837            reader,
838            writer,
839            held: Mutex::new(Vec::new()),
840            headers: Mutex::new(HashMap::new()),
841            instance_name: config.service_instance_name.clone(),
842            basic: None,
843        })
844    }
845
846    /// The reader of the requests.
847    pub fn request_datareader(&self) -> &DataReader<Req> {
848        &self.reader
849    }
850
851    /// The writer of the replies.
852    pub fn reply_datawriter(&self) -> &DataWriter<Rep> {
853        &self.writer
854    }
855
856    /// Whether the reply writer has matched the reply reader of the
857    /// requester whose request writer is `writer`.
858    fn can_answer(&self, writer: &Guid) -> bool {
859        let shared = &self.writer.shared;
860        self.writer
861            .matched_subscriptions()
862            .iter()
863            .any(|r| paired(shared, writer, r))
864    }
865
866    /// The reply reader of the requester of `request`: the matched reader
867    /// it names, or the only matched reader paired with its writer.
868    fn reply_reader(&self, request: &SampleIdentity) -> Option<Guid> {
869        let shared = &self.writer.shared;
870        let matched = self.writer.matched_subscriptions();
871        let named = request.writer_guid;
872        if matched.contains(&named) {
873            return Some(named);
874        }
875        let mut paired_with = matched.into_iter().filter(|r| paired(shared, &named, r));
876        match (paired_with.next(), paired_with.next()) {
877            (Some(r), None) => Some(r),
878            _ => None,
879        }
880    }
881
882    /// Takes the requests come so far, in order of arrival, but those of
883    /// a requester whose reply reader is not yet matched: they stay until
884    /// it is.
885    pub fn take_requests(&self) -> Result<Vec<Request<Req>>> {
886        let mut held = self.held.lock().map_err(|_| Error::PreconditionNotMet)?;
887        for (data, info, header) in take_with_headers(&self.reader) {
888            if let Some(b) = &self.basic {
889                let h = (b.header)(&data);
890                if self
891                    .instance_name
892                    .as_ref()
893                    .is_some_and(|n| !h.instance_name.is_empty() && h.instance_name != *n)
894                {
895                    continue;
896                }
897                held.push(Request {
898                    data,
899                    id: h.request_id.into(),
900                    writer: info.writer,
901                });
902                continue;
903            }
904            let named = info
905                .related_sample_identity
906                .map(|id| id.writer_guid)
907                .filter(|g| *g != Guid::UNKNOWN);
908            let id = SampleIdentity {
909                writer_guid: named.unwrap_or(info.writer),
910                sequence_number: info.sequence_number,
911            };
912            if let Some(h) = header {
913                self.headers
914                    .lock()
915                    .map_err(|_| Error::PreconditionNotMet)?
916                    .insert(id, h);
917            }
918            held.push(Request {
919                data,
920                id,
921                writer: info.writer,
922            });
923        }
924        let mut ready = Vec::new();
925        let mut i = 0;
926        while i < held.len() {
927            if self.can_answer(&held[i].writer) {
928                ready.push(held.remove(i));
929            } else {
930                i += 1;
931            }
932        }
933        Ok(ready)
934    }
935
936    /// Waits for requests and takes them; an empty list when `timeout`
937    /// passes first.
938    pub fn receive_requests(&self, timeout: Duration) -> Result<Vec<Request<Req>>> {
939        wait_until(timeout, || match self.take_requests() {
940            Ok(v) if v.is_empty() => None,
941            r => Some(r),
942        })
943        .unwrap_or(Ok(Vec::new()))
944    }
945
946    /// Sends `reply` to the request `request`; with the request's
947    /// in-payload header at its head when it had one.
948    pub fn send_reply(&self, reply: &Rep, request: &SampleIdentity) -> Result<()> {
949        let params = WriteParams {
950            related_sample_identity: Some(*request),
951            directed_to: self.reply_reader(request),
952            ..WriteParams::default()
953        };
954        if let Some(b) = &self.basic {
955            return self
956                .writer
957                .write_w_params(&(b.answering)(reply, *request), &params)
958                .map(|_| ());
959        }
960        let header = self
961            .headers
962            .lock()
963            .map_err(|_| Error::PreconditionNotMet)?
964            .remove(request);
965        match header {
966            Some((client, seq)) => self
967                .writer
968                .write_mapped(reply, &params, |p| insert_header(p, client, seq)),
969            None => self.writer.write_w_params(reply, &params),
970        }
971        .map(|_| ())
972    }
973}
974
975#[cfg(test)]
976mod tests {
977    use super::*;
978
979    #[test]
980    fn in_payload_header() {
981        let client = [1, 2, 3, 4, 5, 6, 7, 8];
982        for encap in [[0, 1, 0, 0], [0, 0, 0, 0]] {
983            let mut payload = encap.to_vec();
984            payload.extend_from_slice(&[9, 9, 9, 9]);
985            let with = insert_header(payload.clone(), client, 42);
986            assert_eq!(with.len(), payload.len() + HEADER);
987            assert_eq!(&with[ENCAP..ENCAP + 8], &client);
988            let seq = if encap[1] == 1 {
989                42i64.to_le_bytes()
990            } else {
991                42i64.to_be_bytes()
992            };
993            assert_eq!(&with[ENCAP + 8..ENCAP + HEADER], &seq);
994            assert_eq!(strip_header(&with), Some((client, 42, payload)));
995        }
996        assert_eq!(strip_header(&[0, 1, 0, 0, 1, 2]), None);
997    }
998}