Skip to main content

zenoh_protocol/network/
request.rs

1//
2// Copyright (c) 2022 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13//
14use core::sync::atomic::AtomicU32;
15
16use zenoh_buffers::buffer::Buffer;
17
18use crate::{core::WireExpr, zenoh::RequestBody};
19
20/// The resolution of a RequestId
21pub type RequestId = u32;
22pub type AtomicRequestId = AtomicU32;
23
24pub mod flag {
25    pub const N: u8 = 1 << 5; // 0x20 Named         if N==1 then the key expr has name/suffix
26    pub const M: u8 = 1 << 6; // 0x40 Mapping       if M==1 then key expr mapping is the one declared by the sender, else it is the one declared by the receiver
27    pub const Z: u8 = 1 << 7; // 0x80 Extensions    if Z==1 then an extension will follow
28}
29
30/// # Request message
31///
32/// ```text
33/// Flags:
34/// - N: Named          if N==1 then the key expr has name/suffix
35/// - M: Mapping        if M==1 then key expr mapping is the one declared by the sender, else it is the one declared by the receiver
36/// - Z: Extension      if Z==1 then at least one extension is present
37///
38///  7 6 5 4 3 2 1 0
39/// +-+-+-+-+-+-+-+-+
40/// |Z|M|N| Request |
41/// +-+-+-+---------+
42/// ~ request_id:z32~  (*)
43/// +---------------+
44/// ~ key_scope:z16 ~
45/// +---------------+
46/// ~  key_suffix   ~  if N==1 -- <u8;z16>
47/// +---------------+
48/// ~   [req_exts]  ~  if Z==1
49/// +---------------+
50/// ~  RequestBody  ~  -- Payload
51/// +---------------+
52///
53/// (*) The resolution of the request id is negotiated during the session establishment.
54///     This implementation limits the resolution to 32bit.
55/// ```
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Request {
58    pub id: RequestId,
59    pub wire_expr: WireExpr<'static>,
60    pub ext_qos: ext::QoSType,
61    pub ext_tstamp: Option<ext::TimestampType>,
62    pub ext_nodeid: ext::NodeIdType,
63    pub ext_target: ext::QueryTarget,
64    pub ext_budget: Option<ext::BudgetType>,
65    pub ext_timeout: Option<ext::TimeoutType>,
66    pub payload: RequestBody,
67}
68
69pub mod ext {
70    use core::{num::NonZeroU32, time::Duration};
71
72    use serde::Deserialize;
73
74    use crate::{zextz64, zextzbuf};
75
76    pub type QoS = zextz64!(0x1, false);
77    pub type QoSType = crate::network::ext::QoSType<{ QoS::ID }>;
78
79    pub type Timestamp = zextzbuf!(0x2, false);
80    pub type TimestampType = crate::network::ext::TimestampType<{ Timestamp::ID }>;
81
82    pub type NodeId = zextz64!(0x3, true);
83    pub type NodeIdType = crate::network::ext::NodeIdType<{ NodeId::ID }>;
84
85    pub type Target = zextz64!(0x4, true);
86    // ```text
87    // - Target (0x03)
88    //  7 6 5 4 3 2 1 0
89    // +-+-+-+-+-+-+-+-+
90    // %     target    %
91    // +---------------+
92    // ```
93    // The `zenoh::queryable::Queryable`s that should be target of a `zenoh::Session::get()`.
94    #[repr(u8)]
95    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
96    pub enum QueryTarget {
97        /// Let Zenoh find the BestMatching queryable capabale of serving the query.
98        #[default]
99        BestMatching,
100        /// Deliver the query to all queryables matching the query's key expression.
101        All,
102        /// Deliver the query to all queryables matching the query's key expression that are declared as complete.
103        AllComplete,
104    }
105
106    impl QueryTarget {
107        pub const DEFAULT: Self = Self::BestMatching;
108
109        #[cfg(feature = "test")]
110        #[doc(hidden)]
111        pub fn rand() -> Self {
112            use rand::prelude::*;
113            let mut rng = rand::thread_rng();
114
115            *[
116                QueryTarget::All,
117                QueryTarget::AllComplete,
118                QueryTarget::BestMatching,
119            ]
120            .choose(&mut rng)
121            .unwrap()
122        }
123    }
124
125    // The maximum number of responses
126    pub type Budget = zextz64!(0x5, false);
127    pub type BudgetType = NonZeroU32;
128
129    // The timeout of the request
130    pub type Timeout = zextz64!(0x6, false);
131    pub type TimeoutType = Duration;
132}
133
134impl Request {
135    pub fn payload_size(&self) -> usize {
136        match &self.payload {
137            RequestBody::Query(q) => {
138                q.ext_body.as_ref().map_or(0, |b| b.payload.len())
139                    + q.ext_attachment.as_ref().map_or(0, |a| a.buffer.len())
140            }
141        }
142    }
143
144    #[cfg(feature = "test")]
145    #[doc(hidden)]
146    pub fn rand() -> Self {
147        use core::num::NonZeroU32;
148
149        use rand::Rng;
150
151        let mut rng = rand::thread_rng();
152        let wire_expr = WireExpr::rand();
153        let id: RequestId = rng.gen();
154        let payload = RequestBody::rand();
155        let ext_qos = ext::QoSType::rand();
156        let ext_tstamp = rng.gen_bool(0.5).then(ext::TimestampType::rand);
157        let ext_nodeid = ext::NodeIdType::rand();
158        let ext_target = ext::QueryTarget::rand();
159        let ext_budget = if rng.gen_bool(0.5) {
160            NonZeroU32::new(rng.gen())
161        } else {
162            None
163        };
164        let ext_timeout = if rng.gen_bool(0.5) {
165            Some(ext::TimeoutType::from_millis(rng.gen()))
166        } else {
167            None
168        };
169
170        Self {
171            wire_expr,
172            id,
173            payload,
174            ext_qos,
175            ext_tstamp,
176            ext_nodeid,
177            ext_target,
178            ext_budget,
179            ext_timeout,
180        }
181    }
182}