1use 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#[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
120pub const GENERATED_CODE_VERSION_1: () = ();
125
126#[derive(Debug)]
130pub enum RpcError<E> {
131 Exception(E),
133 Remote(RemoteExceptionCode),
136 InvalidReply,
138 Dds(Error),
140}
141
142impl<E> RpcError<E> {
143 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
172pub trait BasicRequest {
175 fn header(&self) -> &RequestHeader;
177 fn header_mut(&mut self) -> &mut RequestHeader;
179}
180
181pub trait BasicReply {
184 fn header(&self) -> &ReplyHeader;
186 fn header_mut(&mut self) -> &mut ReplyHeader;
188}
189
190struct RequesterBasic<Req, Rep> {
192 with_header: fn(&Req, RequestHeader) -> Req,
194 answers: fn(&Rep) -> SampleIdentity,
196 instance_name: String,
198 lock: Mutex<()>,
201}
202
203struct ReplierBasic<Req, Rep> {
205 header: fn(&Req) -> RequestHeader,
207 answering: fn(&Rep, SampleIdentity) -> Rep,
209}
210
211fn 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
233const CYCLONE: VendorId = VendorId([0x01, 0x10]);
236
237const ENCAP: usize = 4;
239const HEADER: usize = 16;
240
241type Header = ([u8; 8], i64);
243
244fn is_cyclone(shared: &Shared, guid: &Guid) -> bool {
246 shared.vendor_of(&guid.prefix) == Some(CYCLONE)
247}
248
249fn little_endian(payload: &[u8]) -> bool {
251 payload.get(1).is_some_and(|b| b & 1 == 1)
252}
253
254fn 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
268fn 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
287fn 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#[derive(Clone, Debug)]
308pub struct RpcConfig {
309 pub request_topic: String,
311 pub reply_topic: String,
313 pub service_instance_name: Option<String>,
317 pub writer_qos: DataWriterQos,
320 pub reader_qos: DataReaderQos,
322 pub request_topic_aliases: Vec<String>,
326 pub reply_topic_aliases: Vec<String>,
328}
329
330impl RpcConfig {
331 pub fn new(service: &str) -> Self {
334 RpcConfig::with_topics(&format!("{service}_Request"), &format!("{service}_Reply"))
335 }
336
337 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
359fn 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
370fn 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
387fn 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
414fn 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
429pub struct Requester<Req, Rep> {
432 writer: DataWriter<Req>,
433 reader: DataReader<Rep>,
434 replies: Mutex<HashMap<SampleIdentity, Vec<Rep>>>,
437 client_id: [u8; 8],
439 headers: Mutex<(i64, HashMap<i64, SampleIdentity>)>,
442 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 pub fn new(participant: &DomainParticipant, service: &str) -> Result<Self> {
458 Requester::with_config(participant, &RpcConfig::new(service))
459 }
460
461 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 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, ¶meters)?;
510 Requester::make(participant, writer, &filtered, config, Some(basic))
511 }
512}
513
514fn 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 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 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 pub fn request_datawriter(&self) -> &DataWriter<Req> {
580 &self.writer
581 }
582
583 pub fn reply_datareader(&self) -> &DataReader<Rep> {
585 &self.reader
586 }
587
588 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 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 pub fn wait_for_service(&self, timeout: Duration) -> bool {
612 wait_until(timeout, || self.is_service_matched().then_some(())).is_some()
613 }
614
615 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, ¶ms);
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, ¶ms, |p| insert_header(p, self.client_id, seq))?;
656 headers.0 = seq;
657 headers.1.insert(seq, id);
658 Ok(id)
659 }
660
661 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 _ if self.basic.is_some() => self.basic.as_ref().map(|b| (b.answers)(&data)),
669 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 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 pub fn take_replies(&self, request: &SampleIdentity) -> Result<Vec<Rep>> {
696 Ok(self.collect()?.remove(request).unwrap_or_default())
697 }
698
699 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 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 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#[derive(Clone, Debug, PartialEq)]
737pub struct Request<Req> {
738 pub data: Req,
740 pub id: SampleIdentity,
744 pub writer: Guid,
746}
747
748pub struct Replier<Req, Rep> {
751 reader: DataReader<Req>,
752 writer: DataWriter<Rep>,
753 held: Mutex<Vec<Request<Req>>>,
756 headers: Mutex<HashMap<SampleIdentity, Header>>,
759 instance_name: Option<String>,
761 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 pub fn new(participant: &DomainParticipant, service: &str) -> Result<Self> {
777 Replier::with_config(participant, &RpcConfig::new(service))
778 }
779
780 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 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 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 pub fn request_datareader(&self) -> &DataReader<Req> {
848 &self.reader
849 }
850
851 pub fn reply_datawriter(&self) -> &DataWriter<Rep> {
853 &self.writer
854 }
855
856 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 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 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 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 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), ¶ms)
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, ¶ms, |p| insert_header(p, client, seq)),
969 None => self.writer.write_w_params(reply, ¶ms),
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}