perspective_js/
client.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
13use std::error::Error;
14use std::future::Future;
15use std::sync::Arc;
16
17use derivative::Derivative;
18use futures::channel::oneshot;
19use js_sys::{Function, Uint8Array};
20#[cfg(doc)]
21use perspective_client::SystemInfo;
22use perspective_client::{
23    ClientError, ReconnectCallback, Session, TableData, TableInitOptions, asyncfn,
24};
25use wasm_bindgen::prelude::*;
26use wasm_bindgen_derive::TryFromJsValue;
27use wasm_bindgen_futures::{JsFuture, future_to_promise};
28
29pub use crate::table::*;
30use crate::utils::{ApiError, ApiResult, JsValueSerdeExt, LocalPollLoop};
31use crate::{TableDataExt, apierror};
32
33#[wasm_bindgen]
34extern "C" {
35    #[derive(Clone)]
36    #[wasm_bindgen(typescript_type = "TableInitOptions")]
37    pub type JsTableInitOptions;
38}
39
40#[wasm_bindgen]
41#[derive(Clone)]
42pub struct ProxySession(perspective_client::ProxySession);
43
44#[wasm_bindgen]
45impl ProxySession {
46    #[wasm_bindgen(constructor)]
47    pub fn new(client: &Client, on_response: &Function) -> Self {
48        let poll_loop = LocalPollLoop::new({
49            let on_response = on_response.clone();
50            move |msg: Vec<u8>| {
51                let msg = Uint8Array::from(&msg[..]);
52                on_response.call1(&JsValue::UNDEFINED, &JsValue::from(msg))?;
53                Ok(JsValue::null())
54            }
55        });
56        // NB: This swallows any errors raised by the inner callback
57        let on_response = Box::new(move |msg: &[u8]| {
58            wasm_bindgen_futures::spawn_local(poll_loop.poll(msg.to_vec()));
59            Ok(())
60        });
61        Self(perspective_client::ProxySession::new(
62            client.client.clone(),
63            on_response,
64        ))
65    }
66
67    #[wasm_bindgen]
68    pub async fn handle_request(&self, value: JsValue) -> ApiResult<()> {
69        let uint8array = Uint8Array::new(&value);
70        let slice = uint8array.to_vec();
71        self.0.handle_request(&slice).await?;
72        Ok(())
73    }
74
75    pub async fn close(self) {
76        self.0.close().await;
77    }
78}
79
80/// An instance of a [`Client`] is a connection to a single
81/// `perspective_server::Server`, whether locally in-memory or remote over some
82/// transport like a WebSocket.
83///
84/// The browser and node.js libraries both support the `websocket(url)`
85/// constructor, which connects to a remote `perspective_server::Server`
86/// instance over a WebSocket transport.
87///
88/// In the browser, the `worker()` constructor creates a new Web Worker
89/// `perspective_server::Server` and returns a [`Client`] connected to it.
90///
91/// In node.js, a pre-instantied [`Client`] connected synhronously to a global
92/// singleton `perspective_server::Server` is the default module export.
93///
94/// # JavaScript Examples
95///
96/// Create a Web Worker `perspective_server::Server` in the browser and return a
97/// [`Client`] instance connected for it:
98///
99/// ```javascript
100/// import perspective from "@finos/perspective";
101/// const client = await perspective.worker();
102/// ```
103///
104/// Create a WebSocket connection to a remote `perspective_server::Server`:
105///
106/// ```javascript
107/// import perspective from "@finos/perspective";
108/// const client = await perspective.websocket("ws://locahost:8080/ws");
109/// ```
110///
111/// Access the synchronous client in node.js:
112///
113/// ```javascript
114/// import { default as client } from "@finos/perspective";
115/// ```
116#[wasm_bindgen]
117#[derive(TryFromJsValue, Clone)]
118pub struct Client {
119    pub(crate) close: Option<Function>,
120    pub(crate) client: perspective_client::Client,
121}
122
123impl PartialEq for Client {
124    fn eq(&self, other: &Self) -> bool {
125        self.client.get_name() == other.client.get_name()
126    }
127}
128
129/// A wrapper around [`js_sys::Function`] to ease async integration for the
130/// `reconnect` argument of [`Client::on_error`] callback.
131#[derive(Derivative)]
132#[derivative(Clone(bound = ""))]
133struct JsReconnect<I>(Arc<dyn Fn(I) -> js_sys::Promise>);
134
135unsafe impl<I> Send for JsReconnect<I> {}
136unsafe impl<I> Sync for JsReconnect<I> {}
137
138impl<I> JsReconnect<I> {
139    fn run(&self, args: I) -> js_sys::Promise {
140        self.0(args)
141    }
142
143    fn run_all(
144        &self,
145        args: I,
146    ) -> impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>>
147    + Send
148    + Sync
149    + 'static
150    + use<I> {
151        let (sender, receiver) = oneshot::channel::<Result<(), Box<dyn Error + Send + Sync>>>();
152        let p = self.0(args);
153        let _ = future_to_promise(async move {
154            let result = JsFuture::from(p)
155                .await
156                .map(|_| ())
157                .map_err(|x| format!("{x:?}").into());
158
159            sender.send(result).unwrap();
160            Ok(JsValue::UNDEFINED)
161        });
162
163        async move { receiver.await.unwrap() }
164    }
165}
166
167impl<F, I> From<F> for JsReconnect<I>
168where
169    F: Fn(I) -> js_sys::Promise + 'static,
170{
171    fn from(value: F) -> Self {
172        JsReconnect(Arc::new(value))
173    }
174}
175
176impl Client {
177    pub fn get_client(&self) -> &'_ perspective_client::Client {
178        &self.client
179    }
180}
181
182#[wasm_bindgen]
183impl Client {
184    #[wasm_bindgen(constructor)]
185    pub fn new(send_request: Function, close: Option<Function>) -> ApiResult<Self> {
186        let send_request = JsReconnect::from(move |mut v: Vec<u8>| {
187            let buff2 = unsafe { js_sys::Uint8Array::view_mut_raw(v.as_mut_ptr(), v.len()) };
188            send_request
189                .call1(&JsValue::UNDEFINED, &buff2)
190                .unwrap()
191                .unchecked_into::<js_sys::Promise>()
192        });
193
194        let client = perspective_client::Client::new_with_callback(None, move |msg| {
195            send_request.run_all(msg)
196        })?;
197
198        Ok(Client { close, client })
199    }
200
201    #[wasm_bindgen]
202    pub fn new_proxy_session(&self, on_response: &Function) -> ProxySession {
203        ProxySession::new(self, on_response)
204    }
205
206    #[wasm_bindgen]
207    pub async fn init(&self) -> ApiResult<()> {
208        self.client.clone().init().await?;
209        Ok(())
210    }
211
212    #[wasm_bindgen]
213    pub async fn handle_response(&self, value: &JsValue) -> ApiResult<()> {
214        let uint8array = Uint8Array::new(value);
215        let slice = uint8array.to_vec();
216        self.client.handle_response(&slice).await?;
217        Ok(())
218    }
219
220    #[wasm_bindgen]
221    pub async fn handle_error(&self, error: String, reconnect: Option<Function>) -> ApiResult<()> {
222        self.client
223            .handle_error(
224                ClientError::Unknown(error),
225                reconnect.map(|reconnect| {
226                    let reconnect =
227                        JsReconnect::from(move |()| match reconnect.call0(&JsValue::UNDEFINED) {
228                            Ok(x) => x.unchecked_into::<js_sys::Promise>(),
229                            Err(e) => {
230                                // This error may occur when _invoking_ the function
231                                tracing::warn!("{:?}", e);
232                                js_sys::Promise::reject(&format!("C {e:?}").into())
233                            },
234                        });
235
236                    asyncfn!(reconnect, async move || {
237                        if let Err(e) = JsFuture::from(reconnect.run(())).await {
238                            if let Some(e) = e.dyn_ref::<js_sys::Object>() {
239                                Err(ClientError::Unknown(e.to_string().as_string().unwrap()))
240                            } else {
241                                Err(ClientError::Unknown(e.as_string().unwrap()))
242                            }
243                        } else {
244                            Ok(())
245                        }
246                    })
247                }),
248            )
249            .await?;
250
251        Ok(())
252    }
253
254    #[wasm_bindgen]
255    pub async fn on_error(&self, callback: Function) -> ApiResult<u32> {
256        let callback = JsReconnect::from(
257            move |(message, reconnect): (ClientError, Option<ReconnectCallback>)| {
258                let cl: Closure<dyn Fn() -> js_sys::Promise> = Closure::new(move || {
259                    let reconnect = reconnect.clone();
260                    future_to_promise(async move {
261                        if let Some(f) = reconnect {
262                            f().await.map_err(|e| JsValue::from(format!("A {e}")))?;
263                        }
264
265                        Ok(JsValue::UNDEFINED)
266                    })
267                });
268
269                if let Err(e) = callback.call2(
270                    &JsValue::UNDEFINED,
271                    &JsValue::from(apierror!(ClientError(message))),
272                    &cl.into_js_value(),
273                ) {
274                    tracing::warn!("{:?}", e);
275                }
276
277                js_sys::Promise::resolve(&JsValue::UNDEFINED)
278            },
279        );
280
281        let poll_loop = LocalPollLoop::new_async(move |x| JsFuture::from(callback.run(x)));
282        let id = self
283            .client
284            .on_error(asyncfn!(poll_loop, async move |message, reconnect| {
285                poll_loop.poll((message, reconnect)).await;
286                Ok(())
287            }))
288            .await?;
289
290        Ok(id)
291    }
292
293    /// Creates a new [`Table`] from either a _schema_ or _data_.
294    ///
295    /// The [`Client::table`] factory function can be initialized with either a
296    /// _schema_ (see [`Table::schema`]), or data in one of these formats:
297    ///
298    /// - Apache Arrow
299    /// - CSV
300    /// - JSON row-oriented
301    /// - JSON column-oriented
302    /// - NDJSON
303    ///
304    /// When instantiated with _data_, the schema is inferred from this data.
305    /// While this is convenient, inferrence is sometimes imperfect e.g.
306    /// when the input is empty, null or ambiguous. For these cases,
307    /// [`Client::table`] can first be instantiated with a explicit schema.
308    ///
309    /// When instantiated with a _schema_, the resulting [`Table`] is empty but
310    /// with known column names and column types. When subsqeuently
311    /// populated with [`Table::update`], these columns will be _coerced_ to
312    /// the schema's type. This behavior can be useful when
313    /// [`Client::table`]'s column type inferences doesn't work.
314    ///
315    /// The resulting [`Table`] is _virtual_, and invoking its methods
316    /// dispatches events to the `perspective_server::Server` this
317    /// [`Client`] connects to, where the data is stored and all calculation
318    /// occurs.
319    ///
320    /// # Arguments
321    ///
322    /// - `arg` - Either _schema_ or initialization _data_.
323    /// - `options` - Optional configuration which provides one of:
324    ///     - `limit` - The max number of rows the resulting [`Table`] can
325    ///       store.
326    ///     - `index` - The column name to use as an _index_ column. If this
327    ///       `Table` is being instantiated by _data_, this column name must be
328    ///       present in the data.
329    ///     - `name` - The name of the table. This will be generated if it is
330    ///       not provided.
331    ///     - `format` - The explicit format of the input data, can be one of
332    ///       `"json"`, `"columns"`, `"csv"` or `"arrow"`. This overrides
333    ///       language-specific type dispatch behavior, which allows stringified
334    ///       and byte array alternative inputs.
335    ///
336    /// # JavaScript Examples
337    ///
338    /// Load a CSV from a `string`:
339    ///
340    /// ```javascript
341    /// const table = await client.table("x,y\n1,2\n3,4");
342    /// ```
343    ///
344    /// Load an Arrow from an `ArrayBuffer`:
345    ///
346    /// ```javascript
347    /// import * as fs from "node:fs/promises";
348    /// const table2 = await client.table(await fs.readFile("superstore.arrow"));
349    /// ```
350    ///
351    /// Load a CSV from a `UInt8Array` (the default for this type is Arrow)
352    /// using a format override:
353    ///
354    /// ```javascript
355    /// const enc = new TextEncoder();
356    /// const table = await client.table(enc.encode("x,y\n1,2\n3,4"), {
357    ///     format: "csv",
358    /// });
359    /// ```
360    ///
361    /// Create a table with an `index`:
362    ///
363    /// ```javascript
364    /// const table = await client.table(data, { index: "Row ID" });
365    /// ```
366    #[wasm_bindgen]
367    pub async fn table(
368        &self,
369        value: &JsTableInitData,
370        options: Option<JsTableInitOptions>,
371    ) -> ApiResult<Table> {
372        let options = options
373            .into_serde_ext::<Option<TableInitOptions>>()?
374            .unwrap_or_default();
375
376        let args = TableData::from_js_value(value, options.format)?;
377        Ok(Table(self.client.table(args, options).await?))
378    }
379
380    /// Terminates this [`Client`], cleaning up any [`crate::View`] handles the
381    /// [`Client`] has open as well as its callbacks.
382    #[wasm_bindgen]
383    pub fn terminate(&self) -> ApiResult<JsValue> {
384        if let Some(f) = self.close.clone() {
385            Ok(f.call0(&JsValue::UNDEFINED)?)
386        } else {
387            Err(ApiError::new("Client type cannot be terminated"))
388        }
389    }
390
391    /// Opens a [`Table`] that is hosted on the `perspective_server::Server`
392    /// that is connected to this [`Client`].
393    ///
394    /// The `name` property of [`TableInitOptions`] is used to identify each
395    /// [`Table`]. [`Table`] `name`s can be looked up for each [`Client`]
396    /// via [`Client::get_hosted_table_names`].
397    ///
398    /// # JavaScript Examples
399    ///
400    /// Get a virtual [`Table`] named "table_one" from this [`Client`]
401    ///
402    /// ```javascript
403    /// const tables = await client.open_table("table_one");
404    /// ```
405    #[wasm_bindgen]
406    pub async fn open_table(&self, entity_id: String) -> ApiResult<Table> {
407        Ok(Table(self.client.open_table(entity_id).await?))
408    }
409
410    /// Retrieves the names of all tables that this client has access to.
411    ///
412    /// `name` is a string identifier unique to the [`Table`] (per [`Client`]),
413    /// which can be used in conjunction with [`Client::open_table`] to get
414    /// a [`Table`] instance without the use of [`Client::table`]
415    /// constructor directly (e.g., one created by another [`Client`]).
416    ///
417    /// # JavaScript Examples
418    ///
419    /// ```javascript
420    /// const tables = await client.get_hosted_table_names();
421    /// ```
422    #[wasm_bindgen]
423    pub async fn get_hosted_table_names(&self) -> ApiResult<JsValue> {
424        Ok(JsValue::from_serde_ext(
425            &self.client.get_hosted_table_names().await?,
426        )?)
427    }
428
429    /// Register a callback which is invoked whenever [`Client::table`] (on this
430    /// [`Client`]) or [`Table::delete`] (on a [`Table`] belinging to this
431    /// [`Client`]) are called.
432    #[wasm_bindgen]
433    pub async fn on_hosted_tables_update(&self, on_update_js: Function) -> ApiResult<u32> {
434        let poll_loop = LocalPollLoop::new(move |_| on_update_js.call0(&JsValue::UNDEFINED));
435        let on_update = Box::new(move || poll_loop.poll(()));
436        let id = self.client.on_hosted_tables_update(on_update).await?;
437        Ok(id)
438    }
439
440    /// Remove a callback previously registered via
441    /// `Client::on_hosted_tables_update`.
442    #[wasm_bindgen]
443    pub async fn remove_hosted_tables_update(&self, update_id: u32) -> ApiResult<()> {
444        self.client.remove_hosted_tables_update(update_id).await?;
445        Ok(())
446    }
447
448    /// Provides the [`SystemInfo`] struct, implementation-specific metadata
449    /// about the [`perspective_server::Server`] runtime such as Memory and
450    /// CPU usage.
451    ///
452    /// For WebAssembly servers, this method includes the WebAssembly heap size.
453    ///
454    /// # JavaScript Examples
455    ///
456    /// ```javascript
457    /// const info = await client.system_info();
458    /// ```
459    #[wasm_bindgen]
460    pub async fn system_info(&self) -> ApiResult<JsValue> {
461        let info = self.client.system_info().await?;
462        Ok(JsValue::from_serde_ext(&info)?)
463    }
464}