@perspective-dev/client 5.2.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,7 @@
10
10
  // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
11
  // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
12
 
13
+ use std::cell::RefCell;
13
14
  use std::future::Future;
14
15
  use std::pin::Pin;
15
16
 
@@ -25,13 +26,64 @@ use wasm_bindgen_futures::{JsFuture, future_to_promise};
25
26
 
26
27
  use super::errors::*;
27
28
 
29
+ #[wasm_bindgen]
30
+ extern "C" {
31
+ /// A DevTools task handle from `console.createTask` — Chrome's Async
32
+ /// Stack Tagging API. Bound manually, as `js_sys` does not expose it.
33
+ type JsConsoleTask;
34
+
35
+ #[wasm_bindgen(method, catch)]
36
+ fn run(this: &JsConsoleTask, f: &js_sys::Function) -> Result<JsValue, JsValue>;
37
+ }
38
+
39
+ #[wasm_bindgen]
40
+ extern "C" {
41
+ #[wasm_bindgen(variadic, js_namespace = console , js_name = createTask, catch)]
42
+ pub fn createTask(name: JsValue) -> Result<JsValue, JsValue>;
43
+ }
44
+
45
+ /// Create a DevTools task, or `None` where the API is unavailable (it is
46
+ /// Chrome-only).
47
+ fn create_task(name: &str) -> Option<JsConsoleTask> {
48
+ thread_local! {
49
+ static CREATE_TASK: Option<(JsValue, js_sys::Function)> = (|| {
50
+ let global = js_sys::global();
51
+ let console = js_sys::Reflect::get(&global, &"console".into()).ok()?;
52
+ let create = js_sys::Reflect::get(&console, &"createTask".into()).ok()?;
53
+ Some((console, create.dyn_into().ok()?))
54
+ })();
55
+ }
56
+
57
+ CREATE_TASK.with(|x| {
58
+ let (console, create) = x.as_ref()?;
59
+ Some(create.call1(console, &name.into()).ok()?.unchecked_into())
60
+ })
61
+ }
62
+
63
+ thread_local! {
64
+ /// Scoped poll thunks for [`TRAMPOLINE`], a stack because tagged polls
65
+ /// nest (an `ApiFuture` awaiting another `ApiFuture`).
66
+ static POLL_STACK: RefCell<Vec<*mut (dyn FnMut() + 'static)>> = RefCell::new(Vec::new());
67
+
68
+ /// The single reusable JS closure handed to [`JsConsoleTask::run`].
69
+ static TRAMPOLINE: Closure<dyn Fn()> = Closure::new(|| {
70
+ let thunk = POLL_STACK.with(|x| x.borrow().last().copied());
71
+ if let Some(thunk) = thunk {
72
+ unsafe { (*thunk)() }
73
+ }
74
+ });
75
+ }
76
+
28
77
  /// A newtype wrapper for a `Future` trait object which supports being
29
78
  /// marshalled to a `JsPromise`.
30
79
  ///
31
80
  /// This avoids implementing an API which requires type casting to
32
81
  /// and from `JsValue` and the associated loss of type safety.
33
82
  #[must_use]
34
- pub struct ApiFuture<T>(Pin<Box<dyn Future<Output = ApiResult<T>>>>)
83
+ pub struct ApiFuture<T>(
84
+ Pin<Box<dyn Future<Output = ApiResult<T>>>>,
85
+ Option<JsConsoleTask>,
86
+ )
35
87
  where
36
88
  Result<T, JsValue>: IntoJsResult + 'static;
37
89
 
@@ -44,13 +96,17 @@ where
44
96
  /// `Promise`, either explicitly or implcitly (when exposed via
45
97
  /// `wasm_bindgen`).
46
98
  pub fn new<U: Future<Output = ApiResult<T>> + 'static>(x: U) -> Self {
47
- Self(Box::pin(x))
99
+ Self::new_named("perspective", x)
100
+ }
101
+
102
+ /// [`Self::new`] with an explicit DevTools task label, shown at the async
103
+ /// gap in tagged stack traces.
104
+ pub fn new_named<U: Future<Output = ApiResult<T>> + 'static>(name: &str, x: U) -> Self {
105
+ Self(Box::pin(x), create_task(name))
48
106
  }
49
107
 
50
108
  pub fn new_throttled<U: Future<Output = ApiResult<T>> + 'static>(x: U) -> ApiFuture<()> {
51
- ApiFuture::<()>(Box::pin(
52
- async move { x.await.ignore_view_delete().map(|_| ()) },
53
- ))
109
+ ApiFuture::<()>::new(async move { x.await.ignore_view_delete().map(|_| ()) })
54
110
  }
55
111
  }
56
112
 
@@ -65,6 +121,11 @@ where
65
121
  drop(js_sys::Promise::from(Self::new(x)))
66
122
  }
67
123
 
124
+ /// [`Self::spawn`] with an explicit DevTools task label.
125
+ pub fn spawn_named<U: Future<Output = ApiResult<T>> + 'static>(name: &str, x: U) {
126
+ drop(js_sys::Promise::from(Self::new_named(name, x)))
127
+ }
128
+
68
129
  pub fn spawn_throttled<U: Future<Output = ApiResult<T>> + 'static>(x: U) {
69
130
  drop(js_sys::Promise::from(Self::new_throttled(x)))
70
131
  }
@@ -94,7 +155,8 @@ where
94
155
  Result<T, JsValue>: IntoJsResult + 'static,
95
156
  {
96
157
  fn from(fut: ApiFuture<T>) -> Self {
97
- future_to_promise(async move { Ok(fut.0.await?).into_js_result() })
158
+ // Await `fut` NOT `fut.0` or the stack frame is lost in Chrome.
159
+ future_to_promise(async move { Ok(fut.await?).into_js_result() })
98
160
  }
99
161
  }
100
162
 
@@ -145,8 +207,33 @@ where
145
207
  self: Pin<&mut Self>,
146
208
  cx: &mut std::task::Context<'_>,
147
209
  ) -> std::task::Poll<Self::Output> {
148
- let mut fut = unsafe { self.map_unchecked_mut(|s| &mut s.0) };
149
- fut.as_mut().poll(cx)
210
+ // SAFETY: structural projection only — neither field is moved, and
211
+ // the inner future stays behind its own `Pin<Box<_>>`.
212
+ let Self(inner, task) = unsafe { self.get_unchecked_mut() };
213
+ let Some(task) = task else {
214
+ return inner.as_mut().poll(cx);
215
+ };
216
+
217
+ let mut result = None;
218
+ let mut thunk = || result = Some(inner.as_mut().poll(cx));
219
+
220
+ // SAFETY: the lifetime is erased for storage only. The entry is
221
+ // pushed and popped within this scope, and `run` invokes the
222
+ // trampoline synchronously, so the pointer never outlives `thunk`.
223
+ let short: *mut (dyn FnMut() + '_) = &mut thunk;
224
+ let long: *mut (dyn FnMut() + 'static) = unsafe { std::mem::transmute(short) };
225
+ POLL_STACK.with(|x| x.borrow_mut().push(long));
226
+ let _ = TRAMPOLINE.with(|x| task.run(x.as_ref().unchecked_ref()));
227
+ POLL_STACK.with(|x| x.borrow_mut().pop());
228
+
229
+ #[allow(clippy::drop_non_drop)]
230
+ drop(thunk);
231
+
232
+ match result {
233
+ Some(result) => result,
234
+ // `run` threw without invoking the trampoline.
235
+ None => inner.as_mut().poll(cx),
236
+ }
150
237
  }
151
238
  }
152
239
 
@@ -359,7 +359,18 @@ export class ClickhouseHandler implements perspective.VirtualServerHandler {
359
359
  viewId: string,
360
360
  config: ViewConfigUpdate,
361
361
  ) {
362
- const query = this.sqlBuilder.tableMakeView(tableId, viewId, config);
362
+ // Window order keys need column types for `range` frame emission.
363
+ const schema = Object.keys(config.windows ?? {}).length
364
+ ? await this.tableSchema(tableId)
365
+ : undefined;
366
+
367
+ const query = this.sqlBuilder.tableMakeView(
368
+ tableId,
369
+ viewId,
370
+ config,
371
+ schema,
372
+ );
373
+
363
374
  await runQuery(this.db, query, { execute: true });
364
375
  }
365
376
 
@@ -371,7 +371,18 @@ export class DuckDBHandler implements perspective.VirtualServerHandler {
371
371
  viewId: string,
372
372
  config: ViewConfigUpdate,
373
373
  ) {
374
- const query = this.sqlBuilder.tableMakeView(tableId, viewId, config);
374
+ // Window order keys need column types for `range` frame emission.
375
+ const schema = Object.keys(config.windows ?? {}).length
376
+ ? await this.tableSchema(tableId)
377
+ : undefined;
378
+
379
+ const query = this.sqlBuilder.tableMakeView(
380
+ tableId,
381
+ viewId,
382
+ config,
383
+ schema,
384
+ );
385
+
375
386
  await runQuery(this.db, query);
376
387
  }
377
388