zenoh_protocol/zenoh/query.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 alloc::{string::String, vec::Vec};
15
16use serde::Deserialize;
17
18use crate::common::ZExtUnknown;
19
20/// The kind of consolidation to apply to a query.
21#[repr(u8)]
22#[derive(Debug, Default, Clone, PartialEq, Eq, Copy, Deserialize)]
23pub enum ConsolidationMode {
24 /// Apply automatic consolidation based on queryable's preferences
25 #[default]
26 Auto,
27 /// No consolidation applied: multiple samples may be received for the same key-timestamp.
28 None,
29 /// Monotonic consolidation immediately forwards samples, except if one with an equal or more recent timestamp
30 /// has already been sent with the same key.
31 ///
32 /// This optimizes latency while potentially reducing bandwidth.
33 ///
34 /// Note that this doesn't cause re-ordering, but drops the samples for which a more recent timestamp has already
35 /// been observed with the same key.
36 Monotonic,
37 /// Holds back samples to only send the set of samples that had the highest timestamp for their key.
38 Latest,
39 // Remove the duplicates of any samples based on the their timestamp.
40 // Unique,
41}
42
43impl ConsolidationMode {
44 pub const DEFAULT: Self = Self::Auto;
45
46 #[cfg(feature = "test")]
47 pub fn rand() -> Self {
48 use rand::prelude::SliceRandom;
49 let mut rng = rand::thread_rng();
50
51 *[Self::None, Self::Monotonic, Self::Latest, Self::Auto]
52 .choose(&mut rng)
53 .unwrap()
54 }
55}
56
57/// # Query message
58///
59/// ```text
60/// Flags:
61/// - C: Consolidation if C==1 then consolidation is present
62/// - P: Parameters If P==1 then the parameters are present
63/// - Z: Extension If Z==1 then at least one extension is present
64///
65/// 7 6 5 4 3 2 1 0
66/// +-+-+-+-+-+-+-+-+
67/// |Z|P|C| QUERY |
68/// +-+-+-+---------+
69/// % consolidation % if C==1
70/// +---------------+
71/// ~ ps: <u8;z16> ~ if P==1
72/// +---------------+
73/// ~ [qry_exts] ~ if Z==1
74/// +---------------+
75/// ```
76pub mod flag {
77 pub const C: u8 = 1 << 5; // 0x20 Consolidation if C==1 then consolidation is present
78 pub const P: u8 = 1 << 6; // 0x40 Parameters if P==1 then the parameters are present
79 pub const Z: u8 = 1 << 7; // 0x80 Extensions if Z==1 then an extension will follow
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Query {
84 pub consolidation: ConsolidationMode,
85 pub parameters: String,
86 pub ext_sinfo: Option<ext::SourceInfoType>,
87 pub ext_body: Option<ext::QueryBodyType>,
88 pub ext_attachment: Option<ext::AttachmentType>,
89 pub ext_unknown: Vec<ZExtUnknown>,
90}
91
92pub mod ext {
93 use crate::{common::ZExtZBuf, zextzbuf};
94
95 /// # SourceInfo extension
96 /// Used to carry additional information about the source of data
97 pub type SourceInfo = zextzbuf!(0x1, false);
98 pub type SourceInfoType = crate::zenoh::ext::SourceInfoType<{ SourceInfo::ID }>;
99
100 /// # QueryBody extension
101 /// Used to carry a body attached to the query
102 /// Shared Memory extension is automatically defined by ValueType extension if
103 /// #[cfg(feature = "shared-memory")] is defined.
104 pub type QueryBodyType = crate::zenoh::ext::ValueType<{ ZExtZBuf::<0x03>::id(false) }, 0x04>;
105
106 /// # User attachment
107 pub type Attachment = zextzbuf!(0x5, false);
108 pub type AttachmentType = crate::zenoh::ext::AttachmentType<{ Attachment::ID }>;
109}
110
111impl Query {
112 #[cfg(feature = "test")]
113 pub fn rand() -> Self {
114 use rand::{
115 distributions::{Alphanumeric, DistString},
116 Rng,
117 };
118
119 use crate::common::iext;
120 let mut rng = rand::thread_rng();
121
122 const MIN: usize = 2;
123 const MAX: usize = 16;
124
125 let consolidation = ConsolidationMode::rand();
126 let parameters: String = if rng.gen_bool(0.5) {
127 let len = rng.gen_range(MIN..MAX);
128 Alphanumeric.sample_string(&mut rng, len)
129 } else {
130 String::new()
131 };
132 let ext_sinfo = rng.gen_bool(0.5).then_some(ext::SourceInfoType::rand());
133 let ext_body = rng.gen_bool(0.5).then_some(ext::QueryBodyType::rand());
134 let ext_attachment = rng.gen_bool(0.5).then_some(ext::AttachmentType::rand());
135 let mut ext_unknown = Vec::new();
136 for _ in 0..rng.gen_range(0..4) {
137 ext_unknown.push(ZExtUnknown::rand2(
138 iext::mid(ext::Attachment::ID) + 1,
139 false,
140 ));
141 }
142
143 Self {
144 consolidation,
145 parameters,
146 ext_sinfo,
147 ext_body,
148 ext_attachment,
149 ext_unknown,
150 }
151 }
152}