1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::AtomicU32;
use std::sync::Arc;

use async_lock::RwLock;
use futures::Future;
use nanoid::*;
use prost::Message;
use proto::make_table_data::Data;

use crate::proto::request::ClientReq;
use crate::proto::response::ClientResp;
use crate::proto::*;
use crate::table::SystemInfo;
use crate::utils::*;
use crate::view::View;
use crate::{proto, Table, TableInitOptions};

/// The possible formats of input data which [`Client::table`] and
/// [`Table::update`] may take as an argument. The latter method will not work
/// with [`TableData::View`] and [`TableData::Schema`] variants, and attempts to
/// call [`Table::update`] with these variants will error.
#[derive(Debug)]
pub enum TableData {
    Schema(Vec<(String, ColumnType)>),
    Csv(String),
    Arrow(Vec<u8>),
    JsonRows(String),
    JsonColumns(String),
    View(View),
}

impl From<TableData> for proto::make_table_data::Data {
    fn from(value: TableData) -> Self {
        match value {
            TableData::Csv(x) => make_table_data::Data::FromCsv(x),
            TableData::Arrow(x) => make_table_data::Data::FromArrow(x),
            TableData::JsonRows(x) => make_table_data::Data::FromRows(x),
            TableData::JsonColumns(x) => make_table_data::Data::FromCols(x),
            TableData::View(view) => make_table_data::Data::FromView(view.name),
            TableData::Schema(x) => make_table_data::Data::FromSchema(proto::Schema {
                schema: x
                    .into_iter()
                    .map(|(name, r#type)| KeyTypePair {
                        name,
                        r#type: r#type as i32,
                    })
                    .collect(),
            }),
        }
    }
}

type Subscriptions<C> = Arc<RwLock<HashMap<u32, C>>>;
type ManyCallback = Box<dyn Fn(ClientResp) -> Result<(), ClientError> + Send + Sync + 'static>;
type OnceCallback = Box<dyn FnOnce(ClientResp) -> Result<(), ClientError> + Send + Sync + 'static>;

type SendFuture = Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>;
type SendCallback = Arc<dyn Fn(&Client, &RequestEnvelope) -> SendFuture + Send + Sync + 'static>;

#[derive(Clone)]
#[doc = include_str!("../../docs/client.md")]
pub struct Client {
    send: SendCallback,
    id_gen: Arc<AtomicU32>,
    subscriptions_once: Subscriptions<OnceCallback>,
    subscriptions_many: Subscriptions<ManyCallback>,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("id_gen", &self.id_gen)
            .finish()
    }
}

fn encode(req: &RequestEnvelope) -> Vec<u8> {
    let mut bytes: Vec<u8> = Vec::new();
    req.encode(&mut bytes).unwrap();
    bytes
}

impl Client {
    /// Create a new client instance with a closure over an external message
    /// queue's `push()`.
    pub fn new<T>(send_handler: T) -> Self
    where
        T: Fn(&Client, &Vec<u8>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>
            + Send
            + Sync
            + 'static,
    {
        Client {
            id_gen: Arc::new(AtomicU32::new(1)),
            subscriptions_once: Arc::default(),
            subscriptions_many: Subscriptions::default(),
            send: Arc::new(move |client, msg| send_handler(client, &encode(msg))),
        }
    }

    /// Create a new client instance with a closure over an external message
    /// queue's `push()`.
    pub fn new_sync<T>(send_handler: T) -> Self
    where
        T: Fn(&Client, &Vec<u8>) + Send + Sync + 'static + Clone,
    {
        Client {
            id_gen: Arc::new(AtomicU32::new(1)),
            subscriptions_once: Arc::default(),
            subscriptions_many: Subscriptions::default(),
            send: Arc::new(move |client, msg| {
                let client = client.clone();
                let msg = msg.clone();
                let send_handler = send_handler.clone();
                Box::pin(async move {
                    send_handler(&client, &encode(&msg));
                })
            }),
        }
    }

    pub fn set_send_handler<T>(&mut self, send_handler: T)
    where
        T: Fn(&Client, &Vec<u8>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>
            + Send
            + Sync
            + 'static,
    {
        self.send = Arc::new(move |client, msg| send_handler(client, &encode(msg)))
    }

    /// Handle a message from the external message queue.
    pub fn receive(&self, msg: &Vec<u8>) -> Result<(), ClientError> {
        let msg = ResponseEnvelope::decode(msg.as_slice())?;
        // tracing::info!("RECV {:?}", msg);
        let payload = msg
            .payload
            .ok_or(ClientError::Option)?
            .client_resp
            .ok_or(ClientError::Option)?;

        let mut wr = self.subscriptions_once.try_write().unwrap();
        if let Some(handler) = (*wr).remove(&msg.msg_id) {
            handler(payload)?;
        } else if let Some(handler) = self.subscriptions_many.try_read().unwrap().get(&msg.msg_id) {
            handler(payload)?;
        } else {
            tracing::warn!("Received unsolicited server message");
        }

        Ok(())
    }

    #[doc = include_str!("../../docs/client/table.md")]
    pub async fn table(&self, input: TableData, options: TableInitOptions) -> ClientResult<Table> {
        let entity_id = match options.name.clone() {
            Some(x) => x.to_owned(),
            None => nanoid!(),
        };

        let msg = RequestEnvelope {
            msg_id: self.gen_id(),
            entity_id: entity_id.clone(),
            entity_type: EntityType::Table as i32,
            payload: Some(Request {
                client_req: Some(ClientReq::MakeTableReq(MakeTableReq {
                    data: Some(MakeTableData {
                        data: Some(input.into()),
                    }),
                    options: Some(options.clone().try_into()?),
                })),
            }),
        };

        let client = self.clone();
        match self.oneshot(&msg).await {
            ClientResp::MakeTableResp(_) => Ok(Table::new(entity_id, client, options)),
            resp => Err(resp.into()),
        }
    }

    #[doc = include_str!("../../docs/client/open_table.md")]
    pub async fn open_table(&self, entity_id: String) -> ClientResult<Table> {
        let names = self.get_hosted_table_names().await?;
        if names.contains(&entity_id) {
            let options = TableInitOptions::default();
            let client = self.clone();
            Ok(Table::new(entity_id, client, options))
        } else {
            Err(ClientError::Unknown("Unknown table".to_owned()))
        }
    }

    #[doc = include_str!("../../docs/client/get_hosted_table_names.md")]
    pub async fn get_hosted_table_names(&self) -> ClientResult<Vec<String>> {
        let msg = RequestEnvelope {
            msg_id: self.gen_id(),
            entity_id: "".to_owned(),
            entity_type: EntityType::Table as i32,
            payload: Some(Request {
                client_req: Some(ClientReq::GetHostedTablesReq(GetHostedTablesReq {})),
            }),
        };

        match self.oneshot(&msg).await {
            ClientResp::GetHostedTablesResp(GetHostedTablesResp { table_names }) => Ok(table_names),
            resp => Err(resp.into()),
        }
    }

    #[doc = include_str!("../../docs/client/system_info.md")]
    pub async fn system_info(&self) -> ClientResult<SystemInfo> {
        let msg = RequestEnvelope {
            msg_id: self.gen_id(),
            entity_id: "".to_string(),
            // TODO: We should rethink this field for system related requests
            entity_type: EntityType::Table as i32,
            payload: Some(Request {
                client_req: Some(ClientReq::ServerSystemInfoReq(ServerSystemInfoReq {})),
            }),
        };

        match self.oneshot(&msg).await {
            ClientResp::ServerSystemInfoResp(resp) => Ok(resp.into()),
            resp => Err(resp.into()),
        }
    }

    /// Generate a message ID unique to this client.
    pub(crate) fn gen_id(&self) -> u32 {
        self.id_gen
            .fetch_add(1, std::sync::atomic::Ordering::Acquire)
    }

    pub(crate) fn unsubscribe(&self, update_id: u32) -> ClientResult<()> {
        let callback = self
            .subscriptions_many
            .try_write()
            .unwrap()
            .remove(&update_id)
            .ok_or(ClientError::Unknown("remove_update".to_string()))?;

        drop(callback);
        Ok(())
    }

    /// Register a callback which is expected to respond exactly once.
    pub(crate) async fn subscribe_once(
        &self,
        msg: &RequestEnvelope,
        on_update: Box<dyn FnOnce(ClientResp) -> ClientResult<()> + Send + Sync + 'static>,
    ) {
        self.subscriptions_once
            .try_write()
            .unwrap()
            .insert(msg.msg_id, on_update);

        tracing::info!("SEND {}", msg);
        (self.send)(self, msg).await;
    }

    /// Register a callback which is expected to respond many times.
    pub(crate) async fn subscribe(
        &self,
        msg: &RequestEnvelope,
        on_update: Box<dyn Fn(ClientResp) -> ClientResult<()> + Send + Sync + 'static>,
    ) {
        self.subscriptions_many
            .try_write()
            .unwrap()
            .insert(msg.msg_id, on_update);

        tracing::info!("SEND {}", msg);
        (self.send)(self, msg).await;
    }

    /// Send a `ClientReq` and await both the successful completion of the
    /// `send`, _and_ the `ClientResp` which is returned.
    pub(crate) async fn oneshot(&self, msg: &RequestEnvelope) -> ClientResp {
        let (sender, receiver) = futures::channel::oneshot::channel::<ClientResp>();
        let callback = Box::new(move |msg| sender.send(msg).map_err(|x| x.into()));
        self.subscriptions_once
            .try_write()
            .unwrap()
            .insert(msg.msg_id, callback);

        tracing::info!("SEND {}", msg);
        (self.send)(self, msg).await;
        receiver.await.unwrap()
    }
}

fn replace(x: Data) -> Data {
    match x {
        Data::FromArrow(_) => Data::FromArrow("<< redacted >>".to_string().encode_to_vec()),
        Data::FromRows(_) => Data::FromRows("<< redacted >>".to_string()),
        Data::FromCols(_) => Data::FromCols("".to_string()),
        Data::FromCsv(_) => Data::FromCsv("".to_string()),
        x => x,
    }
}

/// `prost` generates `Debug` implementations that includes the `data` field,
/// which makes logs output unreadable. This `Display` implementation hides
/// fields that we don't want ot display in the logs.
impl std::fmt::Display for RequestEnvelope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut msg = self.clone();
        msg.payload = match msg.payload {
            Some(Request {
                client_req:
                    Some(request::ClientReq::MakeTableReq(MakeTableReq {
                        options,
                        data: Some(MakeTableData { data: Some(data) }),
                    })),
            }) => Some(Request {
                client_req: Some(request::ClientReq::MakeTableReq(MakeTableReq {
                    options,
                    data: Some(MakeTableData {
                        data: Some(replace(data)),
                    }),
                })),
            }),
            x => x,
        };

        write!(f, "{}", serde_json::to_string(&msg).unwrap())
    }
}