Skip to main content

perspective_client/
view.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::collections::HashMap;
14use std::ops::Deref;
15use std::str::FromStr;
16use std::sync::Arc;
17
18use futures::Future;
19use prost::bytes::Bytes;
20use serde::{Deserialize, Serialize};
21use ts_rs::TS;
22
23use self::view_on_update_req::Mode;
24use crate::assert_view_api;
25use crate::client::Client;
26use crate::proto::request::ClientReq;
27use crate::proto::response::ClientResp;
28use crate::proto::*;
29#[cfg(doc)]
30use crate::table::Table;
31use crate::typed_array::{TypedArrayColumn, TypedArrayWindow, decode_typed_arrays};
32pub use crate::utils::*;
33
34/// Options for [`View::on_update`].
35#[derive(Default, Debug, Deserialize, TS)]
36pub struct OnUpdateOptions {
37    pub mode: Option<OnUpdateMode>,
38}
39
40/// The update mode for [`View::on_update`].
41///
42/// `Row` mode calculates and provides the update batch new rows/columns as an
43/// Apache Arrow to the callback provided to [`View::on_update`]. This allows
44/// incremental updates if your callbakc can read this format, but should be
45/// disabled otherwise.
46#[derive(Default, Debug, Deserialize, TS)]
47pub enum OnUpdateMode {
48    #[default]
49    #[serde(rename = "row")]
50    Row,
51}
52
53impl FromStr for OnUpdateMode {
54    type Err = ClientError;
55
56    fn from_str(s: &str) -> Result<Self, Self::Err> {
57        if s == "row" {
58            Ok(OnUpdateMode::Row)
59        } else {
60            Err(ClientError::Option)
61        }
62    }
63}
64
65#[derive(Clone, Debug, Default, Deserialize, Serialize, TS, PartialEq)]
66pub struct ColumnWindow {
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub start_col: Option<f32>,
69
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub end_col: Option<f32>,
72}
73
74/// Options for serializing a window of data from a [`View`].
75///
76/// Some fields of [`ViewWindow`] are only applicable to specific methods of
77/// [`View`].
78#[derive(Clone, Debug, Default, Deserialize, Serialize, TS, PartialEq)]
79pub struct ViewWindow {
80    #[ts(optional)]
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub start_row: Option<f64>,
83
84    #[ts(optional)]
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub start_col: Option<f64>,
87
88    #[ts(optional)]
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub end_row: Option<f64>,
91
92    #[ts(optional)]
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub end_col: Option<f64>,
95
96    #[ts(optional)]
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub id: Option<bool>,
99
100    #[ts(optional)]
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub index: Option<bool>,
103
104    /// Only impacts [`View::to_csv`]
105    #[ts(optional)]
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub formatted: Option<bool>,
108
109    /// Arrow IPC body compression for [`View::to_arrow`], `"lz4"` or `"zstd"`
110    /// (uncompressed when omitted).
111    #[ts(optional)]
112    #[ts(type = "\"lz4\" | \"zstd\"")]
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub compression: Option<String>,
115
116    /// When `true`, [`View::to_arrow`] names `group_by` key columns
117    /// `__ROW_PATH_N__` and never qualifies an aggregate, instead of the
118    /// human-readable names a key column and its aggregate would otherwise
119    /// take.
120    #[ts(optional)]
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub machine_column_names: Option<bool>,
123}
124
125impl From<ViewWindow> for ViewPort {
126    fn from(window: ViewWindow) -> Self {
127        ViewPort {
128            start_row: window.start_row.map(|x| x.floor() as u32),
129            start_col: window.start_col.map(|x| x.floor() as u32),
130            end_row: window.end_row.map(|x| x.ceil() as u32),
131            end_col: window.end_col.map(|x| x.ceil() as u32),
132            machine_column_names: window.machine_column_names,
133        }
134    }
135}
136
137impl From<ViewPort> for ViewWindow {
138    fn from(window: ViewPort) -> Self {
139        ViewWindow {
140            start_row: window.start_row.map(|x| x as f64),
141            start_col: window.start_col.map(|x| x as f64),
142            end_row: window.end_row.map(|x| x as f64),
143            end_col: window.end_col.map(|x| x as f64),
144            machine_column_names: window.machine_column_names,
145            ..ViewWindow::default()
146        }
147    }
148}
149
150/// Rows updated and port ID corresponding to an update batch, provided to the
151/// callback argument to [`View::on_update`] with the "rows" mode.
152#[derive(TS)]
153pub struct OnUpdateData(crate::proto::ViewOnUpdateResp);
154
155impl Deref for OnUpdateData {
156    type Target = crate::proto::ViewOnUpdateResp;
157
158    fn deref(&self) -> &Self::Target {
159        &self.0
160    }
161}
162
163/// The rule under which the rows reported by [`View::on_remove`] left the
164/// [`View`].
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, TS)]
166#[serde(rename_all = "lowercase")]
167pub enum RemoveCause {
168    Key,
169    Group,
170    Filter,
171}
172
173impl RemoveCause {
174    /// This cause as its lowercase name.
175    pub fn as_str(&self) -> &'static str {
176        match self {
177            RemoveCause::Key => "key",
178            RemoveCause::Group => "group",
179            RemoveCause::Filter => "filter",
180        }
181    }
182}
183
184impl From<view_on_remove_resp::Cause> for RemoveCause {
185    fn from(cause: view_on_remove_resp::Cause) -> Self {
186        match cause {
187            view_on_remove_resp::Cause::Key => RemoveCause::Key,
188            view_on_remove_resp::Cause::Group => RemoveCause::Group,
189            view_on_remove_resp::Cause::Filter => RemoveCause::Filter,
190        }
191    }
192}
193
194/// The keys of rows which left a [`View`], the port ID and the [`RemoveCause`]
195/// they left under, provided to the callback argument to [`View::on_remove`].
196#[derive(Clone, Debug, Serialize, TS)]
197pub struct OnRemoveData {
198    pub port_id: u32,
199    #[ts(type = "Uint8Array | undefined")]
200    #[serde(with = "serde_bytes")]
201    pub indices: Option<Vec<u8>>,
202    pub cause: RemoveCause,
203}
204
205impl From<ViewOnRemoveResp> for OnRemoveData {
206    fn from(resp: ViewOnRemoveResp) -> Self {
207        OnRemoveData {
208            port_id: resp.port_id,
209            cause: resp.cause().into(),
210            indices: resp.indices,
211        }
212    }
213}
214/// The [`View`] struct is Perspective's query and serialization interface. It
215/// represents a query on the `Table`'s dataset and is always created from an
216/// existing `Table` instance via the [`Table::view`] method.
217///
218/// [`View`]s are immutable with respect to the arguments provided to the
219/// [`Table::view`] method; to change these parameters, you must create a new
220/// [`View`] on the same [`Table`]. However, each [`View`] is _live_ with
221/// respect to the [`Table`]'s data, and will (within a conflation window)
222/// update with the latest state as its parent [`Table`] updates, including
223/// incrementally recalculating all aggregates, pivots, filters, etc. [`View`]
224/// query parameters are composable, in that each parameter works independently
225/// _and_ in conjunction with each other, and there is no limit to the number of
226/// pivots, filters, etc. which can be applied.
227///
228/// To construct a [`View`], call the [`Table::view`] factory method. A
229/// [`Table`] can have as many [`View`]s associated with it as you need -
230/// Perspective conserves memory by relying on a single [`Table`] to power
231/// multiple [`View`]s concurrently.
232///
233/// # Examples
234///
235/// ```no_run
236/// # use perspective_client::{Client, TableData, TableInitOptions, UpdateData, ViewWindow};
237/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
238/// # let client: Client = todo!();
239/// let opts = TableInitOptions::default();
240/// let data = TableData::Update(UpdateData::Csv("x,y\n1,2\n3,4".into()));
241/// let table = client.table(data, opts).await?;
242///
243/// let view = table.view(None).await?;
244/// let arrow = view.to_arrow(ViewWindow::default()).await?;
245/// view.delete().await?;
246/// # Ok(()) }
247/// ```
248///
249/// ```no_run
250/// # use std::collections::HashMap;
251/// # use perspective_client::Table;
252/// # use perspective_client::config::*;
253/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
254/// # let table: Table = todo!();
255/// let view = table
256///     .view(Some(ViewConfigUpdate {
257///         columns: Some(vec![Some("Sales".into())]),
258///         aggregates: Some(HashMap::from_iter(vec![("Sales".into(), "sum".into())])),
259///         group_by: Some(vec!["Region".into(), "Country".into()]),
260///         filter: Some(vec![Filter::new("Category", "in", &[
261///             "Furniture",
262///             "Technology",
263///         ])]),
264///         ..ViewConfigUpdate::default()
265///     }))
266///     .await?;
267/// # Ok(()) }
268/// ```
269///
270///  Group By
271///
272/// ```no_run
273/// # use perspective_client::Table;
274/// # use perspective_client::config::*;
275/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
276/// # let table: Table = todo!();
277/// let view = table
278///     .view(Some(ViewConfigUpdate {
279///         group_by: Some(vec!["a".into(), "c".into()]),
280///         ..ViewConfigUpdate::default()
281///     }))
282///     .await?;
283/// # Ok(()) }
284/// ```
285///
286/// Split By
287///
288/// ```no_run
289/// # use perspective_client::Table;
290/// # use perspective_client::config::*;
291/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
292/// # let table: Table = todo!();
293/// let view = table
294///     .view(Some(ViewConfigUpdate {
295///         split_by: Some(vec!["a".into(), "c".into()]),
296///         ..ViewConfigUpdate::default()
297///     }))
298///     .await?;
299/// # Ok(()) }
300/// ```
301///
302/// In Javascript, a [`Table`] can be constructed on a [`Table::view`] instance,
303/// which will return a new [`Table`] based on the [`Table::view`]'s dataset,
304/// and all future updates that affect the [`Table::view`] will be forwarded to
305/// the new [`Table`]. This is particularly useful for implementing a
306/// [Client/Server Replicated](server.md#clientserver-replicated) design, by
307/// serializing the `View` to an arrow and setting up an `on_update` callback.
308///
309/// ```no_run
310/// # use perspective_client::{Client, TableData, TableInitOptions, UpdateData, UpdateOptions};
311/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
312/// # let client: Client = todo!();
313/// let opts = TableInitOptions::default();
314/// let data = TableData::Update(UpdateData::Csv("x,y\n1,2\n3,4".into()));
315/// let table = client.table(data, opts.clone()).await?;
316/// let view = table.view(None).await?;
317/// let table2 = client.table(TableData::View(view), opts).await?;
318/// let more = UpdateData::Csv("x,y\n5,6".into());
319/// table.update(more, UpdateOptions::default()).await?;
320/// # Ok(()) }
321/// ```
322#[derive(Clone, Debug)]
323pub struct View {
324    pub name: String,
325    client: Client,
326    pub(crate) source: Option<ViewSource>,
327}
328
329/// The options of the [`Table`] a [`View`] was created from, as known to the
330/// [`Client`] which created it; a [`View`] opened by name alone has no source.
331#[derive(Clone, Debug)]
332pub(crate) struct ViewSource {
333    pub options: crate::table::TableOptions,
334}
335
336assert_view_api!(View);
337
338impl View {
339    pub(crate) fn client(&self) -> &Client {
340        &self.client
341    }
342
343    pub fn new(name: String, client: Client) -> Self {
344        View {
345            name,
346            client,
347            source: None,
348        }
349    }
350
351    pub(crate) fn new_with_source(name: String, client: Client, source: ViewSource) -> Self {
352        View {
353            name,
354            client,
355            source: Some(source),
356        }
357    }
358
359    fn client_message(&self, req: ClientReq) -> Request {
360        crate::proto::Request {
361            msg_id: self.client.gen_id(),
362            entity_id: self.name.clone(),
363            client_req: Some(req),
364        }
365    }
366
367    /// Returns this [`View`]'s column header area for `window`, transposed as
368    /// `area[level][column]`.
369    ///
370    /// A column path shows the columns that a given cell belongs to after
371    /// pivots are applied. The area is rectangular with one level per
372    /// `split_by` plus one: a column's split values occupy the leading levels
373    /// and its name always occupies the last, so a subtotal or grand total
374    /// under `split_rollup_mode: "rollup"` reads [`Scalar::Null`] at the levels
375    /// it does not pivot on. Values keep their column's type - a `datetime`
376    /// split value is epoch milliseconds, not text - so formatting them is the
377    /// caller's choice.
378    ///
379    /// `window` slices the *column* axis; the number of levels does not depend
380    /// on it.
381    pub async fn column_paths(
382        &self,
383        window: ColumnWindow,
384    ) -> ClientResult<Vec<Vec<crate::config::Scalar>>> {
385        let msg = self.client_message(ClientReq::ViewColumnPathsReq(ViewColumnPathsReq {
386            start_col: window.start_col.map(|x| x as u32),
387            end_col: window.end_col.map(|x| x as u32),
388        }));
389
390        match self.client.oneshot(&msg).await? {
391            ClientResp::ViewColumnPathsResp(ViewColumnPathsResp { area }) => Ok(area
392                .into_iter()
393                .map(|level| {
394                    level
395                        .values
396                        .into_iter()
397                        .map(crate::config::Scalar::from)
398                        .collect()
399                })
400                .collect()),
401            resp => Err(resp.into()),
402        }
403    }
404
405    /// Returns this [`View`]'s _dimensions_, row and column count, as well as
406    /// those of the [`crate::Table`] from which it was derived.
407    ///
408    /// - `num_table_rows` - The number of rows in the underlying
409    ///   [`crate::Table`].
410    /// - `num_table_columns` - The number of columns in the underlying
411    ///   [`crate::Table`] (including the `index` column if this
412    ///   [`crate::Table`] was constructed with one).
413    /// - `num_view_rows` - The number of rows in this [`View`]. If this
414    ///   [`View`] has a `group_by` clause, `num_view_rows` will also include
415    ///   aggregated rows.
416    /// - `num_view_columns` - The number of columns in this [`View`]. If this
417    ///   [`View`] has a `split_by` clause, `num_view_columns` will include all
418    ///   _column paths_, e.g. the number of `columns` clause times the number
419    ///   of `split_by` groups.
420    pub async fn dimensions(&self) -> ClientResult<ViewDimensionsResp> {
421        let msg = self.client_message(ClientReq::ViewDimensionsReq(ViewDimensionsReq {}));
422        match self.client.oneshot(&msg).await? {
423            ClientResp::ViewDimensionsResp(resp) => Ok(resp),
424            resp => Err(resp.into()),
425        }
426    }
427
428    /// The expression schema of this [`View`], which contains only the
429    /// expressions created on this [`View`]. See [`View::schema`] for
430    /// details.
431    pub async fn expression_schema(&self) -> ClientResult<HashMap<String, ColumnType>> {
432        if self.client.get_features().await?.expressions {
433            let msg = self.client_message(ClientReq::ViewExpressionSchemaReq(
434                ViewExpressionSchemaReq {},
435            ));
436            match self.client.oneshot(&msg).await? {
437                ClientResp::ViewExpressionSchemaResp(ViewExpressionSchemaResp { schema }) => {
438                    Ok(schema
439                        .into_iter()
440                        .map(|(x, y)| (x, ColumnType::try_from(y).unwrap()))
441                        .collect())
442                },
443                resp => Err(resp.into()),
444            }
445        } else {
446            Ok([].into_iter().collect())
447        }
448    }
449
450    /// A copy of the [`ViewConfig`] object passed to the [`Table::view`] method
451    /// which created this [`View`].
452    pub async fn get_config(&self) -> ClientResult<crate::config::ViewConfig> {
453        let msg = self.client_message(ClientReq::ViewGetConfigReq(ViewGetConfigReq {}));
454        match self.client.oneshot(&msg).await? {
455            ClientResp::ViewGetConfigResp(ViewGetConfigResp {
456                config: Some(config),
457            }) => Ok(config.into()),
458            resp => Err(resp.into()),
459        }
460    }
461
462    /// The number of aggregated rows in this [`View`]. This is affected by the
463    /// "group_by" configuration parameter supplied to this view's contructor.
464    ///
465    /// # Returns
466    ///
467    /// The number of aggregated rows.
468    pub async fn num_rows(&self) -> ClientResult<u32> {
469        Ok(self.dimensions().await?.num_view_rows)
470    }
471
472    /// The schema of this [`View`].
473    ///
474    /// The [`View`] schema differs from the `schema` returned by
475    /// [`Table::schema`]; it may have different column names due to
476    /// `expressions` or `columns` configs, or it maye have _different
477    /// column types_ due to the application og `group_by` and `aggregates`
478    /// config. You can think of [`Table::schema`] as the _input_ schema and
479    /// [`View::schema`] as the _output_ schema of a Perspective pipeline.
480    pub async fn schema(&self) -> ClientResult<HashMap<String, ColumnType>> {
481        let msg = self.client_message(ClientReq::ViewSchemaReq(ViewSchemaReq {}));
482        match self.client.oneshot(&msg).await? {
483            ClientResp::ViewSchemaResp(ViewSchemaResp { schema }) => Ok(schema
484                .into_iter()
485                .map(|(x, y)| (x, ColumnType::try_from(y).unwrap()))
486                .collect()),
487            resp => Err(resp.into()),
488        }
489    }
490
491    /// Serializes a [`View`] to the Apache Arrow data format, with IPC body
492    /// compression per [`ViewWindow::compression`].
493    pub async fn to_arrow(&self, window: ViewWindow) -> ClientResult<Bytes> {
494        let msg = self.client_message(ClientReq::ViewToArrowReq(ViewToArrowReq {
495            viewport: Some(window.clone().into()),
496            compression: window.compression,
497        }));
498
499        match self.client.oneshot(&msg).await? {
500            ClientResp::ViewToArrowResp(ViewToArrowResp { arrow }) => Ok(arrow.into()),
501            resp => Err(resp.into()),
502        }
503    }
504
505    /// Serializes a [`View`] to one flat numeric array per column, per the
506    /// options in [`TypedArrayWindow`].
507    pub async fn to_typed_arrays(
508        &self,
509        window: TypedArrayWindow,
510    ) -> ClientResult<Vec<TypedArrayColumn>> {
511        let TypedArrayWindow {
512            mut view_window,
513            float32,
514        } = window;
515
516        view_window.machine_column_names = Some(true);
517        let arrow = self.to_arrow(view_window).await?;
518        decode_typed_arrays(&arrow, float32)
519    }
520
521    /// Serializes this [`View`] to a string of JSON data. Useful if you want to
522    /// save additional round trip serialize/deserialize cycles.    
523    pub async fn to_columns_string(&self, window: ViewWindow) -> ClientResult<String> {
524        let msg = self.client_message(ClientReq::ViewToColumnsStringReq(ViewToColumnsStringReq {
525            viewport: Some(window.clone().into()),
526            id: window.id,
527            index: window.index,
528            formatted: window.formatted,
529        }));
530
531        match self.client.oneshot(&msg).await? {
532            ClientResp::ViewToColumnsStringResp(ViewToColumnsStringResp { json_string }) => {
533                Ok(json_string)
534            },
535            resp => Err(resp.into()),
536        }
537    }
538
539    /// Render this `View` as a JSON string.
540    pub async fn to_json_string(&self, window: ViewWindow) -> ClientResult<String> {
541        let viewport = ViewPort::from(window.clone());
542        let msg = self.client_message(ClientReq::ViewToRowsStringReq(ViewToRowsStringReq {
543            viewport: Some(viewport),
544            id: window.id,
545            index: window.index,
546            formatted: window.formatted,
547        }));
548
549        match self.client.oneshot(&msg).await? {
550            ClientResp::ViewToRowsStringResp(ViewToRowsStringResp { json_string }) => {
551                Ok(json_string)
552            },
553            resp => Err(resp.into()),
554        }
555    }
556
557    /// Renders this [`View`] as an [NDJSON](https://github.com/ndjson/ndjson-spec)
558    /// formatted [`String`].
559    pub async fn to_ndjson(&self, window: ViewWindow) -> ClientResult<String> {
560        let viewport = ViewPort::from(window.clone());
561        let msg = self.client_message(ClientReq::ViewToNdjsonStringReq(ViewToNdjsonStringReq {
562            viewport: Some(viewport),
563            id: window.id,
564            index: window.index,
565            formatted: window.formatted,
566        }));
567
568        match self.client.oneshot(&msg).await? {
569            ClientResp::ViewToNdjsonStringResp(ViewToNdjsonStringResp { ndjson_string }) => {
570                Ok(ndjson_string)
571            },
572            resp => Err(resp.into()),
573        }
574    }
575
576    /// Serializes this [`View`] to CSV data in a standard format.
577    pub async fn to_csv(&self, window: ViewWindow) -> ClientResult<String> {
578        let msg = self.client_message(ClientReq::ViewToCsvReq(ViewToCsvReq {
579            viewport: Some(window.into()),
580        }));
581
582        match self.client.oneshot(&msg).await? {
583            ClientResp::ViewToCsvResp(ViewToCsvResp { csv }) => Ok(csv),
584            resp => Err(resp.into()),
585        }
586    }
587
588    /// Delete this [`View`] and clean up all resources associated with it.
589    /// [`View`] objects do not stop consuming resources or processing
590    /// updates when they are garbage collected - you must call this method
591    /// to reclaim these.
592    pub async fn delete(&self) -> ClientResult<()> {
593        let msg = self.client_message(ClientReq::ViewDeleteReq(ViewDeleteReq {}));
594        match self.client.oneshot(&msg).await? {
595            ClientResp::ViewDeleteResp(_) => Ok(()),
596            resp => Err(resp.into()),
597        }
598    }
599
600    /// Calculates the [min, max] of the leaf nodes of a column `column_name`.
601    ///
602    /// # Returns
603    ///
604    /// A tuple of [min, max], whose types are column and aggregate dependent.
605    pub async fn get_min_max(
606        &self,
607        column_name: String,
608    ) -> ClientResult<(crate::config::Scalar, crate::config::Scalar)> {
609        let msg = self.client_message(ClientReq::ViewGetMinMaxReq(ViewGetMinMaxReq {
610            column_name,
611        }));
612
613        match self.client.oneshot(&msg).await? {
614            ClientResp::ViewGetMinMaxResp(ViewGetMinMaxResp { min, max }) => {
615                let min = min.map(crate::config::Scalar::from).unwrap_or_default();
616                let max = max.map(crate::config::Scalar::from).unwrap_or_default();
617                Ok((min, max))
618            },
619            resp => Err(resp.into()),
620        }
621    }
622
623    /// Register a callback with this [`View`]. Whenever the view's underlying
624    /// table emits an update, this callback will be invoked with an object
625    /// containing `port_id`, indicating which port the update fired on,
626    /// `reset`, which is `true` when the step began with [`Table::clear`] or
627    /// [`Table::replace`] so `delta` is relative to an empty table, and
628    /// optionally `delta`, which is the new data that was updated for each
629    /// cell or each row.
630    ///
631    /// # Arguments
632    ///
633    /// - `on_update` - A callback function invoked on update, which receives an
634    ///   object with three keys: `port_id`, indicating which port the update
635    ///   was triggered on, `reset`, and `delta`, whose value is dependent on
636    ///   the mode parameter.
637    /// - `options` - If this is provided as `OnUpdateOptions { mode:
638    ///   Some(OnUpdateMode::Row) }`, then `delta` is an Arrow of the updated
639    ///   rows. Otherwise `delta` will be [`Option::None`].
640    pub async fn on_update<T, U>(&self, on_update: T, options: OnUpdateOptions) -> ClientResult<u32>
641    where
642        T: Fn(OnUpdateData) -> U + Send + Sync + 'static,
643        U: Future<Output = ()> + Send + 'static,
644    {
645        let on_update = Arc::new(on_update);
646        let callback = move |resp: Response| {
647            let on_update = on_update.clone();
648            async move {
649                match resp.client_resp {
650                    Some(ClientResp::ViewOnUpdateResp(resp)) => {
651                        on_update(OnUpdateData(resp)).await;
652                        Ok(())
653                    },
654                    resp => Err(resp.into()),
655                }
656            }
657        };
658
659        let msg = self.client_message(ClientReq::ViewOnUpdateReq(ViewOnUpdateReq {
660            mode: options.mode.map(|OnUpdateMode::Row| Mode::Row as i32),
661        }));
662
663        self.client.subscribe(&msg, callback).await?;
664        Ok(msg.msg_id)
665    }
666
667    /// Unregister a previously registered update callback with this [`View`].
668    ///
669    /// # Arguments
670    ///
671    /// - `id` - A callback `id` as returned by a recipricol call to
672    ///   [`View::on_update`].
673    ///
674    /// # Examples
675    ///
676    /// ```no_run
677    /// # use perspective_client::{OnUpdateOptions, View};
678    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
679    /// # let view: View = todo!();
680    /// let callback = |_| async { print!("Updated!") };
681    /// let cid = view.on_update(callback, OnUpdateOptions::default()).await?;
682    /// view.remove_update(cid).await?;
683    /// # Ok(()) }
684    /// ```
685    pub async fn remove_update(&self, update_id: u32) -> ClientResult<()> {
686        let msg = self.client_message(ClientReq::ViewRemoveOnUpdateReq(ViewRemoveOnUpdateReq {
687            id: update_id,
688        }));
689
690        self.client.unsubscribe(update_id).await?;
691        match self.client.oneshot(&msg).await? {
692            ClientResp::ViewRemoveOnUpdateResp(_) => Ok(()),
693            resp => Err(resp.into()),
694        }
695    }
696
697    /// Register a callback which is invoked whenever rows leave this [`View`],
698    /// with their keys as an Apache Arrow of one column per key column named
699    /// after it and the [`RemoveCause`] they left under.
700    ///
701    /// For a [`View`] without `group_by` the keys are the `index` columns of
702    /// the [`Table`], which must have one: [`RemoveCause::Key`] when
703    /// [`Table::remove`] removed them ([`Table::replace`] reports the keys it
704    /// does not re-supply and [`Table::clear`] every key) and
705    /// [`RemoveCause::Filter`] when [`Table::update`] moved them outside the
706    /// [`View`]'s `filter`. For a [`View`] with `group_by` the keys are the
707    /// `group_by` columns of each group which no longer has any rows,
708    /// [`RemoveCause::Group`], `null` below the group's depth. It fires once
709    /// per cause per update step.
710    ///
711    /// # Examples
712    ///
713    /// ```no_run
714    /// # use perspective_client::{View, OnRemoveData};
715    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
716    /// # let view: View = todo!();
717    /// let callback = |removed: OnRemoveData| async move { println!("{:?}", removed.port_id) };
718    /// let cid = view.on_remove(callback).await?;
719    /// view.remove_remove(cid).await?;
720    /// # Ok(()) }
721    /// ```
722    pub async fn on_remove<T, U>(&self, on_remove: T) -> ClientResult<u32>
723    where
724        T: Fn(OnRemoveData) -> U + Send + Sync + 'static,
725        U: Future<Output = ()> + Send + 'static,
726    {
727        let on_remove = Arc::new(on_remove);
728        let callback = move |resp: Response| {
729            let on_remove = on_remove.clone();
730            async move {
731                match resp.client_resp {
732                    Some(ClientResp::ViewOnRemoveResp(resp)) => {
733                        on_remove(OnRemoveData::from(resp)).await;
734                        Ok(())
735                    },
736                    resp => Err(resp.into()),
737                }
738            }
739        };
740
741        let msg = self.client_message(ClientReq::ViewOnRemoveReq(ViewOnRemoveReq {}));
742        self.client.subscribe(&msg, callback).await?;
743        Ok(msg.msg_id)
744    }
745
746    /// Unregister a previously registered [`View::on_remove`] callback.
747    ///
748    /// # Arguments
749    ///
750    /// - `callback_id` - A callback `id` as returned by a reciprocal call to
751    ///   [`View::on_remove`].
752    pub async fn remove_remove(&self, callback_id: u32) -> ClientResult<()> {
753        let msg = self.client_message(ClientReq::ViewRemoveOnRemoveReq(ViewRemoveOnRemoveReq {
754            id: callback_id,
755        }));
756
757        self.client.unsubscribe(callback_id).await?;
758        match self.client.oneshot(&msg).await? {
759            ClientResp::ViewRemoveOnRemoveResp(_) => Ok(()),
760            resp => Err(resp.into()),
761        }
762    }
763
764    /// Register a callback with this [`View`]. Whenever the [`View`] is
765    /// deleted, this callback will be invoked.
766    pub async fn on_delete(
767        &self,
768        on_delete: Box<dyn Fn() + Send + Sync + 'static>,
769    ) -> ClientResult<u32> {
770        let callback = move |resp: Response| match resp.client_resp.unwrap() {
771            ClientResp::ViewOnDeleteResp(_) => {
772                on_delete();
773                Ok(())
774            },
775            resp => Err(resp.into()),
776        };
777
778        let msg = self.client_message(ClientReq::ViewOnDeleteReq(ViewOnDeleteReq {}));
779        self.client.subscribe_once(&msg, Box::new(callback)).await?;
780        Ok(msg.msg_id)
781    }
782
783    /// Unregister a previously registered [`View::on_delete`] callback.
784    pub async fn remove_delete(&self, callback_id: u32) -> ClientResult<()> {
785        let msg = self.client_message(ClientReq::ViewRemoveDeleteReq(ViewRemoveDeleteReq {
786            id: callback_id,
787        }));
788
789        match self.client.oneshot(&msg).await? {
790            ClientResp::ViewRemoveDeleteResp(ViewRemoveDeleteResp {}) => Ok(()),
791            resp => Err(resp.into()),
792        }
793    }
794
795    /// Collapses the `group_by` row at `row_index`.
796    pub async fn collapse(&self, row_index: u32) -> ClientResult<u32> {
797        let msg = self.client_message(ClientReq::ViewCollapseReq(ViewCollapseReq { row_index }));
798        match self.client.oneshot(&msg).await? {
799            ClientResp::ViewCollapseResp(ViewCollapseResp { num_changed }) => Ok(num_changed),
800            resp => Err(resp.into()),
801        }
802    }
803
804    /// Expand the `group_by` row at `row_index`.
805    pub async fn expand(&self, row_index: u32) -> ClientResult<u32> {
806        let msg = self.client_message(ClientReq::ViewExpandReq(ViewExpandReq { row_index }));
807        match self.client.oneshot(&msg).await? {
808            ClientResp::ViewExpandResp(ViewExpandResp { num_changed }) => Ok(num_changed),
809            resp => Err(resp.into()),
810        }
811    }
812
813    /// Set expansion `depth` of the `group_by` tree.
814    pub async fn set_depth(&self, depth: u32) -> ClientResult<()> {
815        let msg = self.client_message(ClientReq::ViewSetDepthReq(ViewSetDepthReq { depth }));
816        match self.client.oneshot(&msg).await? {
817            ClientResp::ViewSetDepthResp(_) => Ok(()),
818            resp => Err(resp.into()),
819        }
820    }
821}