Skip to main content

perspective_client/utils/
mod.rs

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