1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
pub mod activity;
pub mod build;
pub mod cache_backend;
pub mod callbacks;
pub mod chunk_sink;
pub mod defaults;
pub mod make_dio;
pub mod memory_cache;
pub mod redb_cache;
use std::ops::Range;
use std::sync::Arc;
use tokio::runtime::Handle;
use std::future::Future;
use vantage_core::Result;
use crate::dio::Dio;
use crate::error::LensBuildError;
use crate::ops::{ChangeEvent, QueryDescriptor, WriteOp};
pub use activity::{Activity, ActivitySignal};
pub use cache_backend::{CacheBackend, CacheStatus, CacheTable};
pub use callbacks::{
DioCallback, DioEventCallback, DioListPageCallback, DioLoadChunkCallback,
DioLoadDetailCallback, DioQueryCallback, DioTotalProviderCallback, DioWriteCallback,
LensCallbacks, boxed_dio_callback, boxed_dio_event_callback, boxed_dio_query_callback,
boxed_dio_write_callback, boxed_list_page_callback, boxed_load_chunk_callback,
boxed_load_detail_callback, boxed_total_provider_callback,
};
pub use chunk_sink::{ChunkRow, ChunkSink, SceneryChunkTarget};
pub use defaults::LensDefaults;
pub use memory_cache::{MemoryCache, MemoryCacheTable};
pub use redb_cache::{RedbCache, RedbCacheTable};
/// Long-lived shared infrastructure for caching, callbacks, and refresh.
///
/// Built once via [`LensBuilder`] and shared across every Dio produced by
/// [`make_dio`](Lens::make_dio). After construction the Lens is immutable.
pub struct Lens {
pub(crate) cache_source: Arc<dyn CacheBackend>,
pub(crate) callbacks: Arc<LensCallbacks>,
pub(crate) defaults: LensDefaults,
pub(crate) runtime: Handle,
/// App-activity signal driving adaptive refresh cadence. Shared with the UI
/// (cloned), so flipping it re-paces every Dio's refresh loop at once.
pub(crate) activity: ActivitySignal,
}
impl Lens {
/// Start building a Lens. Equivalent to [`LensBuilder::new`].
#[allow(clippy::new_ret_no_self)]
pub fn new() -> LensBuilder {
LensBuilder::new()
}
pub(crate) fn cache_source(&self) -> &Arc<dyn CacheBackend> {
&self.cache_source
}
pub(crate) fn callbacks(&self) -> &Arc<LensCallbacks> {
&self.callbacks
}
pub fn defaults(&self) -> &LensDefaults {
&self.defaults
}
pub(crate) fn runtime(&self) -> &Handle {
&self.runtime
}
}
/// Configuration surface used to assemble a [`Lens`].
///
/// Setters are chainable; `.build()` validates required state and returns
/// a `Lens`. Stage 1 holds the shape only — the validation and dispatch
/// machinery lands in later stages.
pub struct LensBuilder {
pub(crate) cache_source: Option<Arc<dyn CacheBackend>>,
pub(crate) deferred_cache_error: Option<LensBuildError>,
pub(crate) on_start: Option<DioCallback>,
pub(crate) on_refresh: Option<DioCallback>,
pub(crate) on_write: Option<DioWriteCallback>,
pub(crate) on_event: Option<DioEventCallback>,
pub(crate) on_query: Option<DioQueryCallback>,
pub(crate) total_provider: Option<DioTotalProviderCallback>,
pub(crate) on_load_chunk: Option<DioLoadChunkCallback>,
pub(crate) on_list_page: Option<DioListPageCallback>,
pub(crate) on_load_detail: Option<DioLoadDetailCallback>,
pub(crate) augmentations: Vec<crate::augment::Augmentation>,
pub(crate) catalog: Option<std::sync::Arc<vantage_vista_factory::VistaCatalog>>,
pub(crate) defaults: LensDefaults,
pub(crate) runtime: Option<Handle>,
pub(crate) activity: ActivitySignal,
}
impl Default for LensBuilder {
fn default() -> Self {
Self::new()
}
}
impl LensBuilder {
pub fn new() -> Self {
Self {
cache_source: None,
deferred_cache_error: None,
on_start: None,
on_refresh: None,
on_write: None,
on_event: None,
on_query: None,
total_provider: None,
on_load_chunk: None,
on_list_page: None,
on_load_detail: None,
augmentations: Vec::new(),
catalog: None,
defaults: LensDefaults::default(),
runtime: None,
activity: ActivitySignal::new(),
}
}
/// Share an app-activity signal so this Lens's refresh loops adapt their
/// cadence (active → fast, standby → slow, offline → paused). Pass the same
/// cloned handle to every Lens and update it from the UI.
pub fn activity_signal(mut self, signal: ActivitySignal) -> Self {
self.activity = signal;
self
}
/// The slower refresh interval used while the app is on
/// [`Standby`](Activity::Standby). Falls back to the active
/// [`refresh_every`](Self::refresh_every) interval when unset.
pub fn standby_refresh_every(mut self, interval: std::time::Duration) -> Self {
self.defaults.standby_refresh_interval = Some(interval);
self
}
/// Provide the cache backend explicitly. Use this when [`cache_at`](Self::cache_at)
/// is not flexible enough (e.g. wrapping a remote object store).
pub fn cache_source(mut self, source: Arc<dyn CacheBackend>) -> Self {
self.cache_source = Some(source);
self
}
/// Convenience: cache to a redb file at `path`. Each Dio under the
/// resulting Lens claims a named table within that file. Errors
/// from opening redb propagate at [`build`](Self::build) time —
/// the constructor is fallible but stored eagerly so `.build()`
/// can decide what to do.
pub fn cache_at(self, path: impl Into<std::path::PathBuf>) -> Self {
let path = path.into();
match RedbCache::open(&path) {
Ok(cache) => self.cache_source(Arc::new(cache)),
Err(e) => Self {
deferred_cache_error: Some(LensBuildError::Other(e)),
..self
},
}
}
/// Convenience: cache to a process-local in-memory store. No file, no
/// persistence — handy for tests and ephemeral Dios. Mirrors
/// [`cache_at`](Self::cache_at)'s per-Dio-named-table + status semantics.
pub fn cache_in_memory(self) -> Self {
self.cache_source(Arc::new(MemoryCache::new()))
}
/// Register the `on_start` callback. Fires once when a Dio is built
/// via [`Lens::make_dio`]; by default `make_dio` awaits it.
///
/// The canonical shape is `|dio| { let dio = dio.clone(); async
/// move { ... } }` — cloning Dio inside the closure produces a
/// `'static` future without lifetime gymnastics.
pub fn on_start<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_start = Some(boxed_dio_callback(f));
self
}
/// Register the `on_refresh` callback. Fires on the configured
/// [`refresh_every`](Self::refresh_every) interval and on manual
/// `dio.refresh().await`.
pub fn on_refresh<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_refresh = Some(boxed_dio_callback(f));
self
}
/// Register the `on_write` callback. Fires for every WriteOp the
/// Dio's write queue receives. When not registered, the worker
/// applies the op directly to `dio.master()`.
pub fn on_write<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio, WriteOp) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_write = Some(boxed_dio_write_callback(f));
self
}
/// Register the `on_event` callback. Fires when an upstream
/// [`ChangeEvent`] arrives (e.g. from a SurrealDB LIVE stream).
pub fn on_event<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio, ChangeEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_event = Some(boxed_dio_event_callback(f));
self
}
/// Register the `on_query` callback. Stage 5b will wire this up;
/// stage 3 only stores the registration.
pub fn on_query<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio, QueryDescriptor) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_query = Some(boxed_dio_query_callback(f));
self
}
/// Register the `total_provider` callback. Fires once per
/// [`TableScenery`](crate::scenery::TableScenery) open; the result
/// drives `row_count()` and `estimated_total()` for that scenery's
/// lifetime. Absent → `row_count` falls back to the cached map
/// size (v1 behaviour).
pub fn total_provider<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<usize>> + Send + 'static,
{
self.total_provider = Some(callbacks::boxed_total_provider_callback(f));
self
}
/// Register the `on_load_chunk` callback. The Scenery calls this
/// from `set_viewport` / `request_load_more` when the requested
/// range is not fully cached. The callback fetches the rows from
/// the master (or any other source) and streams them back via
/// [`ChunkSink::push`]. Absent → viewport calls only emit
/// `ViewportChanged` and never load.
pub fn on_load_chunk<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio, Range<usize>, ChunkSink) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_load_chunk = Some(callbacks::boxed_load_chunk_callback(f));
self
}
/// Register the two-pass **list pass**. The Scenery calls this to fetch one
/// page of cheap/list rows for its query variant (conditions + sort +
/// `offset`/`limit` arrive via the [`QueryDescriptor`]). Returned rows are
/// written to the detail table as `Incomplete` and their ids appended to
/// the per-query index. A page shorter than `limit` ends paging.
///
/// Pairs with [`on_load_detail`](Self::on_load_detail); registering
/// `on_load_detail` is what engages two-pass loading.
pub fn on_list_page<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio, QueryDescriptor) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Vec<(String, vantage_types::Record<ciborium::Value>)>>>
+ Send
+ 'static,
{
self.on_list_page = Some(callbacks::boxed_list_page_callback(f));
self
}
/// Register the two-pass **detail pass**. The Scenery calls this once per
/// visible `Incomplete` row to fetch its expensive columns; the returned
/// record is merged into the detail table as `Complete` and the row flips
/// to `Fresh`. **Registering this callback opts the Dio into two-pass
/// loading** — without it, sceneries use the legacy single-pass path.
pub fn on_load_detail<F, Fut>(mut self, f: F) -> Self
where
F: for<'a> Fn(&'a Dio, String) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<vantage_types::Record<ciborium::Value>>> + Send + 'static,
{
self.on_load_detail = Some(callbacks::boxed_load_detail_callback(f));
self
}
pub fn refresh_every(mut self, interval: std::time::Duration) -> Self {
self.defaults.refresh_interval = Some(interval);
self
}
pub fn cache_ttl(mut self, ttl: std::time::Duration) -> Self {
self.defaults.cache_ttl = Some(ttl);
self
}
pub fn write_queue_capacity(mut self, cap: usize) -> Self {
self.defaults.write_queue_capacity = cap;
self
}
pub fn on_start_blocking(mut self, blocking: bool) -> Self {
self.defaults.on_start_blocking = blocking;
self
}
/// Override the `refresh_on_open` default for sceneries opened
/// from any Dio of this Lens.
pub fn refresh_on_open(mut self, enabled: bool) -> Self {
self.defaults.refresh_on_open = enabled;
self
}
/// Override the viewport-debounce window.
pub fn viewport_debounce(mut self, window: std::time::Duration) -> Self {
self.defaults.viewport_debounce = window;
self
}
pub fn runtime(mut self, handle: Handle) -> Self {
self.runtime = Some(handle);
self
}
/// Provide the cross-persistence [`VistaCatalog`](vantage_vista_factory::VistaCatalog)
/// used to resolve augmentation `table:` names into base detail Vistas.
/// Required whenever [`augment`](Self::augment) is used.
pub fn catalog(mut self, catalog: std::sync::Arc<vantage_vista_factory::VistaCatalog>) -> Self {
self.catalog = Some(catalog);
self
}
/// Register augmentations — detail sources merged onto each master row.
///
/// Registering at least one engages two-pass loading: the master is listed
/// cheaply, then each visible row is augmented one at a time from its detail
/// source (the same Vista or a different backend, resolved via the
/// [`catalog`](Self::catalog)). [`build`](Self::build) synthesizes the list
/// and detail passes unless explicit `on_list_page`/`on_load_detail`
/// callbacks were supplied.
///
/// Lower [`AugmentSpec`](crate::augment::AugmentSpec)s with
/// [`lower_augment`](crate::augment::lower_augment) first.
pub fn augment(mut self, augmentations: Vec<crate::augment::Augmentation>) -> Self {
self.augmentations = augmentations;
self
}
}