perspective_client/utils/
mod.rs1mod clone;
16mod logging;
17mod rand_sequence;
18
19#[cfg(feature = "talc-allocator")]
20mod talc_allocator;
21
22#[cfg(test)]
23mod tests;
24
25use std::sync::Arc;
26use std::time::SystemTimeError;
27
28use rand::prelude::*;
29use rand::rngs::StdRng;
30#[cfg(feature = "talc-allocator")]
31pub(crate) use talc_allocator::get_used;
32use thiserror::*;
33
34use crate::proto;
35use crate::utils::rand_sequence::RandomSequence;
36
37#[derive(Clone, Error, Debug)]
38pub enum ClientError {
39 #[error("View not found")]
40 ViewNotFound,
41
42 #[error("Abort(): {0}")]
43 Internal(String),
44
45 #[error("Transport error: {0}")]
46 TransportError(String),
47
48 #[error("Client not yet initialized")]
49 NotInitialized,
50
51 #[error("Unknown error: {0}")]
52 Unknown(String),
53
54 #[error("Unwrapped option")]
55 Option,
56
57 #[error("Bad string")]
58 Utf8(#[from] std::str::Utf8Error),
59
60 #[error("Undecipherable server message {0:?}")]
61 DecodeError(#[from] prost::DecodeError),
62
63 #[error("Response aborted")]
64 ResponseAborted,
65
66 #[error("Unexpected response {0:?}")]
67 ResponseFailed(Box<proto::response::ClientResp>),
68
69 #[error("Not yet implemented {0:?}")]
70 NotImplemented(&'static str),
71
72 #[error("Can't use both `limit` and `index` arguments")]
73 BadTableOptions,
74
75 #[error("External error: {0}")]
76 ExternalError(Arc<Box<dyn std::error::Error + Send + Sync>>),
77
78 #[error("Undecipherable proto message")]
79 ProtoError(#[from] prost::EncodeError),
80
81 #[error("Duplicate name {0}")]
82 DuplicateNameError(String),
83
84 #[error("{0}")]
85 TimeError(#[from] SystemTimeError),
86
87 #[error("{0}")]
88 TypedArrayError(String),
89}
90
91pub type ClientResult<T> = Result<T, ClientError>;
92
93impl From<Box<dyn std::error::Error + Send + Sync>> for ClientError {
94 fn from(value: Box<dyn std::error::Error + Send + Sync>) -> Self {
95 ClientError::ExternalError(Arc::new(value))
96 }
97}
98
99impl<'a, A> From<std::sync::PoisonError<std::sync::MutexGuard<'a, A>>> for ClientError {
100 fn from(_: std::sync::PoisonError<std::sync::MutexGuard<'a, A>>) -> Self {
101 ClientError::Internal("Lock Error".to_owned())
102 }
103}
104
105impl From<Option<proto::response::ClientResp>> for ClientError {
106 fn from(value: Option<proto::response::ClientResp>) -> Self {
107 match value {
108 Some(proto::response::ClientResp::ServerError(x)) => match x.status_code() {
109 proto::StatusCode::ServerError => ClientError::Internal(x.message),
110 proto::StatusCode::ViewNotFound => ClientError::ViewNotFound,
111 proto::StatusCode::TransportError => ClientError::TransportError(x.message),
112 },
113 Some(x) => ClientError::ResponseFailed(Box::new(x)),
114 None => ClientError::ResponseAborted,
115 }
116 }
117}
118
119impl From<proto::response::ClientResp> for ClientError {
120 fn from(value: proto::response::ClientResp) -> Self {
121 match value {
122 proto::response::ClientResp::ServerError(x) => match x.status_code() {
123 proto::StatusCode::ServerError => ClientError::Internal(x.message),
124 proto::StatusCode::ViewNotFound => ClientError::ViewNotFound,
125 proto::StatusCode::TransportError => ClientError::TransportError(x.message),
126 },
127 x => ClientError::ResponseFailed(Box::new(x)),
128 }
129 }
130}
131
132pub trait PerspectiveResultExt {
133 fn unwrap_or_log(&self);
134}
135
136impl<T, E> PerspectiveResultExt for Result<T, E>
137where
138 E: std::error::Error,
139{
140 fn unwrap_or_log(&self) {
141 if let Err(e) = self {
142 tracing::warn!("{}", e);
143 }
144 }
145}
146
147#[derive(Clone)]
149pub struct IDGen(Arc<std::sync::Mutex<RandomSequence>>);
150
151impl Default for IDGen {
152 fn default() -> Self {
153 Self(Arc::new(std::sync::Mutex::new(Self::new_seq())))
154 }
155}
156
157impl IDGen {
158 fn new_seq() -> RandomSequence {
159 let mut rng = rand::rngs::ThreadRng::default();
160 let config = RandomSequence::new(rng.next_u32(), rng.next_u32());
161 config.into_iter()
162 }
163
164 pub fn next(&self) -> u32 {
165 let mut idgen = self.0.lock().unwrap();
166 if let Some(x) = idgen.next() {
167 x
168 } else {
169 *idgen = Self::new_seq();
170 idgen.next().unwrap()
171 }
172 }
173}
174
175const SIZE: usize = 21;
176
177const CHARACTERS: [char; 52] = [
178 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
179 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
180 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
181];
182
183pub fn randid() -> String {
185 let mask = CHARACTERS.len().next_power_of_two() - 1;
186 let step: usize = 8 * SIZE / 5;
187 let mut id = String::with_capacity(SIZE);
188 loop {
189 let mut rng = rand::rngs::ThreadRng::default();
190 let mut random = StdRng::from_rng(&mut rng);
191 let mut bytes: Vec<u8> = vec![0; step];
192 random.fill(&mut bytes[..]);
193 for &byte in &bytes {
194 let byte = byte as usize & mask;
195 if CHARACTERS.len() > byte {
196 id.push(CHARACTERS[byte]);
197 if id.len() == SIZE {
198 return id;
199 }
200 }
201 }
202 }
203}