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 unique 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 ///
303 /// When instantiated with _data_, the schema is inferred from this data.
304 /// While this is convenient, inferrence is sometimes imperfect e.g.
305 /// when the input is empty, null or ambiguous. For these cases,
306 /// [`Client::table`] can first be instantiated with a explicit schema.
307 ///
308 /// When instantiated with a _schema_, the resulting [`Table`] is empty but
309 /// with known column names and column types. When subsqeuently
310 /// populated with [`Table::update`], these columns will be _coerced_ to
311 /// the schema's type. This behavior can be useful when
312 /// [`Client::table`]'s column type inferences doesn't work.
313 ///
314 /// The resulting [`Table`] is _virtual_, and invoking its methods
315 /// dispatches events to the `perspective_server::Server` this
316 /// [`Client`] connects to, where the data is stored and all calculation
317 /// occurs.
318 ///
319 /// # Arguments
320 ///
321 /// - `arg` - Either _schema_ or initialization _data_.
322 /// - `options` - Optional configuration which provides one of:
323 /// - `limit` - The max number of rows the resulting [`Table`] can
324 /// store.
325 /// - `index` - The column name to use as an _index_ column. If this
326 /// `Table` is being instantiated by _data_, this column name must be
327 /// present in the data.
328 /// - `name` - The name of the table. This will be generated if it is
329 /// not provided.
330 /// - `format` - The explicit format of the input data, can be one of
331 /// `"json"`, `"columns"`, `"csv"` or `"arrow"`. This overrides
332 /// language-specific type dispatch behavior, which allows stringified
333 /// and byte array alternative inputs.
334 ///
335 /// # JavaScript Examples
336 ///
337 /// Load a CSV from a `string`:
338 ///
339 /// ```javascript
340 /// const table = await client.table("x,y\n1,2\n3,4");
341 /// ```
342 ///
343 /// Load an Arrow from an `ArrayBuffer`:
344 ///
345 /// ```javascript
346 /// import * as fs from "node:fs/promises";
347 /// const table2 = await client.table(await fs.readFile("superstore.arrow"));
348 /// ```
349 ///
350 /// Load a CSV from a `UInt8Array` (the default for this type is Arrow)
351 /// using a format override:
352 ///
353 /// ```javascript
354 /// const enc = new TextEncoder();
355 /// const table = await client.table(enc.encode("x,y\n1,2\n3,4"), {
356 /// format: "csv",
357 /// });
358 /// ```
359 ///
360 /// Create a table with an `index`:
361 ///
362 /// ```javascript
363 /// const table = await client.table(data, { index: "Row ID" });
364 /// ```
365 #[wasm_bindgen]
366 pub async fn table(
367 &self,
368 value: &JsTableInitData,
369 options: Option<JsTableInitOptions>,
370 ) -> ApiResult<Table> {
371 let options = options
372 .into_serde_ext::<Option<TableInitOptions>>()?
373 .unwrap_or_default();
374
375 let args = TableData::from_js_value(value, options.format)?;
376 Ok(Table(self.client.table(args, options).await?))
377 }
378
379 /// Terminates this [`Client`], cleaning up any [`crate::View`] handles the
380 /// [`Client`] has open as well as its callbacks.
381 #[wasm_bindgen]
382 pub fn terminate(&self) -> ApiResult<JsValue> {
383 if let Some(f) = self.close.clone() {
384 Ok(f.call0(&JsValue::UNDEFINED)?)
385 } else {
386 Err(ApiError::new("Client type cannot be terminated"))
387 }
388 }
389
390 /// Opens a [`Table`] that is hosted on the `perspective_server::Server`
391 /// that is connected to this [`Client`].
392 ///
393 /// The `name` property of [`TableInitOptions`] is used to identify each
394 /// [`Table`]. [`Table`] `name`s can be looked up for each [`Client`]
395 /// via [`Client::get_hosted_table_names`].
396 ///
397 /// # JavaScript Examples
398 ///
399 /// Get a virtual [`Table`] named "table_one" from this [`Client`]
400 ///
401 /// ```javascript
402 /// const tables = await client.open_table("table_one");
403 /// ```
404 #[wasm_bindgen]
405 pub async fn open_table(&self, entity_id: String) -> ApiResult<Table> {
406 Ok(Table(self.client.open_table(entity_id).await?))
407 }
408
409 /// Retrieves the names of all tables that this client has access to.
410 ///
411 /// `name` is a string identifier unique to the [`Table`] (per [`Client`]),
412 /// which can be used in conjunction with [`Client::open_table`] to get
413 /// a [`Table`] instance without the use of [`Client::table`]
414 /// constructor directly (e.g., one created by another [`Client`]).
415 ///
416 /// # JavaScript Examples
417 ///
418 /// ```javascript
419 /// const tables = await client.get_hosted_table_names();
420 /// ```
421 #[wasm_bindgen]
422 pub async fn get_hosted_table_names(&self) -> ApiResult<JsValue> {
423 Ok(JsValue::from_serde_ext(
424 &self.client.get_hosted_table_names().await?,
425 )?)
426 }
427
428 /// Register a callback which is invoked whenever [`Client::table`] (on this
429 /// [`Client`]) or [`Table::delete`] (on a [`Table`] belinging to this
430 /// [`Client`]) are called.
431 #[wasm_bindgen]
432 pub async fn on_hosted_tables_update(&self, on_update_js: Function) -> ApiResult<u32> {
433 let poll_loop = LocalPollLoop::new(move |_| on_update_js.call0(&JsValue::UNDEFINED));
434 let on_update = Box::new(move || poll_loop.poll(()));
435 let id = self.client.on_hosted_tables_update(on_update).await?;
436 Ok(id)
437 }
438
439 /// Remove a callback previously registered via
440 /// `Client::on_hosted_tables_update`.
441 #[wasm_bindgen]
442 pub async fn remove_hosted_tables_update(&self, update_id: u32) -> ApiResult<()> {
443 self.client.remove_hosted_tables_update(update_id).await?;
444 Ok(())
445 }
446
447 /// Provides the [`SystemInfo`] struct, implementation-specific metadata
448 /// about the [`perspective_server::Server`] runtime such as Memory and
449 /// CPU usage.
450 ///
451 /// For WebAssembly servers, this method includes the WebAssembly heap size.
452 ///
453 /// # JavaScript Examples
454 ///
455 /// ```javascript
456 /// const info = await client.system_info();
457 /// ```
458 #[wasm_bindgen]
459 pub async fn system_info(&self) -> ApiResult<JsValue> {
460 let info = self.client.system_info().await?;
461 Ok(JsValue::from_serde_ext(&info)?)
462 }
463}