Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/md/how_to/javascript/viewer.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ The viewer provides an interactive side panel with:
- **Copy** - copy the current view to the clipboard.
- **Reset** - restore the viewer to its default configuration.

Clicking the status icon opens the workspace panel on the left, which lists
each loaded `Client`'s tables, shows the element's `WorkspaceConfig` as
editable JSON, and hosts the agent chat. It floats over the panels by default
and can be pinned alongside them. A `Client` whose connection is lost, or
whose panels have failed, shows its error there with a Reconnect button when
it can be recovered.

## Methods

A `<perspective-viewer>` hosts one or more _panels_. Methods which address a
Expand Down Expand Up @@ -185,6 +192,7 @@ for charts and text for the datagrid.
| `resize(options?)` | Redraw, optionally at a `{dimensions: {width, height}}` size hint |
| `setAutoSize(bool)` / `setAutoPause(bool)` / `setThrottle(ms)` | Render policy |
| `toggleConfig(force?)` | Toggle the settings sidebar |
| `toggleWorkspaceConfig(force?)` | Toggle the workspace panel |
| `toggleColumnSettings(...)` | Toggle the column settings sidebar |
| `resetThemes(themes?)` | Re-detect or explicitly set available themes |
| `restyleElement()` | Re-read CSS and repaint |
Expand Down
2 changes: 1 addition & 1 deletion docs/src/data/projects/dashboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ export const DASHBOARD_PROJECTS: Project[] = [
workspace: multiPanel(ORDER_FLOW, {
depth: market("Depth Timeseries", "Vaporwave"),
heat: market("Heatmap", "Solarized Dark"),
closed: market("Closed Orders", "Solarized Light"),
closed: market("Closed Orders", "Solarized"),
}),
},
{
Expand Down
9 changes: 7 additions & 2 deletions examples/esbuild-example/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ const req = fetch(arrow);
const viewer = document.createElement("perspective-viewer");
document.body.append(viewer);
const worker = await perspective.worker();
const worker2 = await perspective.worker();
const resp = await req;
const buffer = await resp.arrayBuffer();
const table = worker.table(buffer);
viewer.load(table);
await worker.table(buffer, { name: "superstore1" });
await worker2.table(buffer, { name: "superstore2" });
viewer.load(worker);
viewer.load(worker2);

window.TEST = worker2;
9 changes: 7 additions & 2 deletions packages/viewer-datagrid/src/ts/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export function query_commands(

/**
* Whether `location` is in the app's scopes, asked with an empty frame so no
* schema call runs.
* schema call runs; `false` when the host throws.
*/
export function is_command_scope(
plugin: DatagridPluginElement,
Expand All @@ -116,7 +116,12 @@ export function is_command_scope(
data: {},
};

return viewer.queryCommands(plugin, location, frame, []) !== undefined;
try {
return viewer.queryCommands(plugin, location, frame, []) !== undefined;
} catch (error) {
console.error(`Failed to query "${location}" command scope`, error);
return false;
}
}

function command_button(
Expand Down
34 changes: 18 additions & 16 deletions packages/viewer-datagrid/test/js/plugin_config_options.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,22 +374,24 @@ test.describe("Datagrid plugin_config text and row options", () => {
await viewer.flush();
});

const wrapped = await page.evaluate(async () => {
const datagrid = document.querySelector(
"perspective-viewer-datagrid",
) as any;

const rows = [
...datagrid.regular_table.querySelectorAll("tbody tr"),
].slice(0, 3);

return rows.map(
(tr: Element) =>
tr.children[0].querySelector(".psp-wrap") !== null,
);
});

expect(wrapped).toEqual([true, true, true]);
await expect
.poll(() =>
page.evaluate(async () => {
const datagrid = document.querySelector(
"perspective-viewer-datagrid",
) as any;

const rows = [
...datagrid.regular_table.querySelectorAll("tbody tr"),
].slice(0, 3);

return rows.map(
(tr: Element) =>
tr.children[0].querySelector(".psp-wrap") !== null,
);
}),
)
.toEqual([true, true, true]);
});

test("double-clicking a narrowed column's handle unboxes it and restores auto width", async ({
Expand Down
172 changes: 160 additions & 12 deletions rust/perspective-client/src/rust/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,13 +244,31 @@ impl ReconnectCallback {
}
}

/// Whether a [`Client`] can currently reach its `Server`.
#[derive(Clone)]
pub enum Connection {
Open,
Lost {
error: ClientError,
reconnect: Option<ReconnectCallback>,
},
}

impl Connection {
/// Whether requests can be sent.
pub fn is_open(&self) -> bool {
matches!(self, Self::Open)
}
}

/// An instance of a [`Client`] is a connection to a single
/// `perspective_server::Server`, whether locally in-memory or remote over some
/// transport like a WebSocket.
#[derive(Clone)]
pub struct Client {
name: Arc<String>,
features: Arc<Mutex<Option<Features>>>,
connection: Arc<std::sync::RwLock<Connection>>,
send: SendCallback,
id_gen: IDGen,
subscriptions_errors: Subscriptions<OnErrorCallback>,
Expand Down Expand Up @@ -290,6 +308,7 @@ impl Client {
Ok(Client {
name: Arc::new(name),
features: Arc::default(),
connection: Arc::new(std::sync::RwLock::new(Connection::Open)),
id_gen: IDGen::default(),
send,
subscriptions: Subscriptions::default(),
Expand All @@ -315,6 +334,28 @@ impl Client {
self.name.as_str()
}

/// Whether this [`Client`] can currently reach its `Server`, and the error
/// and reconnect function of the loss when it cannot.
pub fn connection(&self) -> Connection {
self.connection
.read()
.unwrap_or_else(|x| x.into_inner())
.clone()
}

fn set_connection(&self, connection: Connection) -> Connection {
let mut guard = self.connection.write().unwrap_or_else(|x| x.into_inner());

std::mem::replace(&mut *guard, connection)
}

fn check_open(&self) -> ClientResult<()> {
match self.connection() {
Connection::Open => Ok(()),
Connection::Lost { error, .. } => Err(ClientError::TransportError(error.to_string())),
}
}

/// Handle a message from the external message queue.
/// [`Client::handle_response`] is part of the low-level message-handling
/// API necessary to implement new transports for a [`Client`]
Expand Down Expand Up @@ -351,7 +392,8 @@ impl Client {
Ok(false)
}

/// Handle an exception from the underlying transport.
/// Handle an exception from the underlying transport, after which every
/// request is rejected until `reconnect` succeeds.
pub async fn handle_error<T, U>(
&self,
message: ClientError,
Expand All @@ -361,20 +403,38 @@ impl Client {
T: Fn() -> U + Clone + Send + Sync + 'static,
U: Future<Output = ClientResult<()>>,
{
let reconnect = reconnect.map(|f| {
let connection = Arc::downgrade(&self.connection);
ReconnectCallback(Arc::new(move || {
clone!(f, connection);
Box::pin(async move {
f().await?;
if let Some(connection) = connection.upgrade() {
*connection.write().unwrap_or_else(|x| x.into_inner()) = Connection::Open;
}

Ok(())
}) as LocalBoxFuture<'static, _>
}))
});

let previous = self.set_connection(Connection::Lost {
error: message.clone(),
reconnect: reconnect.clone(),
});

if !previous.is_open() {
return Ok(());
}

let subs = self.subscriptions_errors.read().await;
let tasks = join_all(subs.values().map(|callback| {
callback(
message.clone(),
reconnect.clone().map(move |f| {
ReconnectCallback(Arc::new(move || {
clone!(f);
Box::pin(async move { Ok(f().await?) }) as LocalBoxFuture<'static, _>
}))
}),
)
}));
let tasks = join_all(
subs.values()
.map(|callback| callback(message.clone(), reconnect.clone())),
);

tasks.await.into_iter().collect::<Result<(), _>>()?;
drop(subs);
self.close_and_error_subscriptions(&message).await
}

Expand Down Expand Up @@ -444,6 +504,7 @@ impl Client {
msg: &Request,
on_update: Box<dyn FnOnce(Response) -> ClientResult<()> + Send + Sync + 'static>,
) -> ClientResult<()> {
self.check_open()?;
self.subscriptions_once
.write()
.await
Expand All @@ -463,6 +524,7 @@ impl Client {
T: Fn(Response) -> U + Send + Sync + 'static,
U: Future<Output = Result<(), ClientError>> + Send + 'static,
{
self.check_open()?;
self.subscriptions
.write()
.await
Expand Down Expand Up @@ -939,3 +1001,89 @@ impl Client {
}
}
}

#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};

use futures::executor::block_on;

use super::*;

fn counting_client() -> (Client, Arc<AtomicUsize>) {
let sent = Arc::new(AtomicUsize::new(0));
let client = Client::new_with_callback(None, {
clone!(sent);
move |_| {
sent.fetch_add(1, Ordering::SeqCst);
async { Ok(()) }
}
})
.unwrap();

(client, sent)
}

fn request(client: &Client) -> ClientResult<()> {
let msg = Request {
msg_id: client.gen_id(),
entity_id: "".to_owned(),
client_req: Some(ClientReq::GetFeaturesReq(GetFeaturesReq {})),
};

block_on(client.subscribe_once(&msg, Box::new(|_| Ok(()))))
}

#[test]
fn test_lost_client_rejects_without_sending() {
let (client, sent) = counting_client();
let reconnect = || async { Ok::<(), ClientError>(()) };
block_on(client.handle_error(ClientError::Unknown("closed".to_owned()), Some(reconnect)))
.unwrap();

assert!(!client.connection().is_open());
assert!(block_on(client.get_hosted_table_names()).is_err());
assert_eq!(sent.load(Ordering::SeqCst), 0);
}

#[test]
fn test_reconnect_reopens_client() {
let (client, sent) = counting_client();
let reconnect = || async { Ok::<(), ClientError>(()) };
block_on(client.handle_error(ClientError::Unknown("closed".to_owned()), Some(reconnect)))
.unwrap();

let Connection::Lost {
reconnect: Some(reconnect),
..
} = client.connection()
else {
panic!("Expected a reconnectable lost connection");
};

block_on(reconnect()).unwrap();
assert!(client.connection().is_open());
request(&client).unwrap();
assert_eq!(sent.load(Ordering::SeqCst), 1);
}

#[test]
fn test_on_error_fires_once_per_loss() {
let (client, _) = counting_client();
let fired = Arc::new(AtomicUsize::new(0));
block_on(client.on_error({
clone!(fired);
move |_, _| {
fired.fetch_add(1, Ordering::SeqCst);
async { Ok::<(), ClientError>(()) }
}
}))
.unwrap();

let none = None::<fn() -> futures::future::Ready<ClientResult<()>>>;
block_on(client.handle_error(ClientError::Unknown("a".to_owned()), none)).unwrap();
block_on(client.handle_error(ClientError::Unknown("b".to_owned()), none)).unwrap();
assert_eq!(fired.load(Ordering::SeqCst), 1);
assert!(request(&client).is_err());
}
}
4 changes: 3 additions & 1 deletion rust/perspective-client/src/rust/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ pub mod proto;

pub mod utils;

pub use crate::client::{Client, ClientHandler, Features, ReconnectCallback, SystemInfo};
pub use crate::client::{
Client, ClientHandler, Connection, Features, ReconnectCallback, SystemInfo,
};
use crate::proto::HostedTable;
pub use crate::proto::JoinType;
pub use crate::session::{ProxySession, Session};
Expand Down
1 change: 1 addition & 0 deletions rust/perspective-js/src/ts/perspective.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ export async function worker(worker: Promise<MessagePort>) {
async () => {
console.debug("Closing WebWorker");
port.close();
await client.handle_error("Worker terminated");
},
);

Expand Down
12 changes: 12 additions & 0 deletions rust/perspective-js/src/ts/wasm/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export async function worker(
async () => {
console.debug("Closing WebWorker");
close();
await client.handle_error("Worker terminated");
},
);

Expand All @@ -113,6 +114,17 @@ export async function worker(
client.handle_response(json.data);
};

port.onmessageerror = () => {
client.handle_error("Worker message error");
};

if (!(webworker instanceof MessagePort)) {
webworker.onerror = (event: Event) => {
const msg = (event as ErrorEvent).message || "Worker error";
client.handle_error(msg);
};
}

return client;
}

Expand Down
Loading
Loading