Skip to main content

quarb_session/
doc.rs

1//! Opening a source into a queryable adapter, and running queries
2//! against it.
3//!
4//! `AstAdapter` is object-safe, but each adapter's *render* method
5//! (`pointer` / `locator` / `path`) is an inherent method, not on the
6//! trait — so, as the Python bindings do, we hold one of a fixed set
7//! of adapter families in an enum and dispatch render (and the
8//! `WithNow`/`AllowShell` query wrap) by variant.
9//!
10//! The text-format variants always compile (they are wasm-safe); the
11//! native fleet (filesystem, git, SQLite, archives, spreadsheets,
12//! source code, mounts) is gated behind the `native` feature, as is
13//! the filesystem `open`/`mount` dispatch. The wasm build drives
14//! everything through [`Doc::parse`].
15
16use anyhow::{Context, Result, bail};
17use quarb::{AllowShell, NodeId, QueryResult, WithNow};
18
19#[cfg(feature = "native")]
20use std::path::Path;
21use std::rc::Rc;
22
23/// Options that shape how native sources open (unused on wasm, which
24/// only parses text).
25#[derive(Clone, Default)]
26pub struct Options {
27    pub hidden: bool,
28    pub respect_ignore: bool,
29    pub descend: bool,
30    /// Declared references, `(field, container)` pairs — the parsed
31    /// `--refs` document, consumed by the SQLite mounts.
32    pub refs: Rc<Vec<(String, String)>>,
33}
34
35/// A materialized source: one variant per adapter family. JSON-model
36/// formats (json/yaml/toml) render node results as pointers, the rest
37/// as locators.
38pub enum Doc {
39    Json(quarb_json::JsonAdapter),
40    Csv(quarb_csv::CsvAdapter),
41    Xml(quarb_xml::XmlAdapter),
42    Html(quarb_html::HtmlAdapter),
43    Sqlite(quarb_sqlite::SqliteAdapter),
44    #[cfg(feature = "native")]
45    Fs(quarb_fs::FsAdapter),
46    #[cfg(feature = "native")]
47    FsDeep(quarb_compose::ComposeAdapter<quarb_fs::FsAdapter>),
48    #[cfg(feature = "native")]
49    Git(quarb_git::GitAdapter),
50    #[cfg(feature = "native")]
51    Archive(quarb_compose::ComposeAdapter<quarb_archive::ArchiveAdapter>),
52    #[cfg(feature = "native")]
53    Xlsx(quarb_xlsx::XlsxAdapter),
54    #[cfg(feature = "native")]
55    Code(quarb_code::CodeAdapter),
56    Mount(quarb_mount::MountAdapter),
57    /// Any adapter behind the object-safe trait, with its locator
58    /// renderer — the carrier for scheme targets opened through
59    /// qua's dispatch (`gcl:`, `kafka:`, `neo4j://`, …).
60    Boxed(Dyn, Box<dyn Fn(NodeId) -> String>),
61}
62
63/// A boxed adapter as an adapter — plain delegation (the
64/// quarb-py `Dyn` pattern).
65pub struct Dyn(pub Box<dyn quarb::AstAdapter>);
66
67impl quarb::AstAdapter for Dyn {
68    fn root(&self) -> NodeId {
69        self.0.root()
70    }
71    fn children(&self, node: NodeId) -> Vec<NodeId> {
72        self.0.children(node)
73    }
74    fn name(&self, node: NodeId) -> Option<String> {
75        self.0.name(node)
76    }
77    fn parent(&self, node: NodeId) -> Option<NodeId> {
78        self.0.parent(node)
79    }
80    fn traits(&self, node: NodeId) -> Vec<String> {
81        self.0.traits(node)
82    }
83    fn property(&self, node: NodeId, name: &str) -> Option<quarb::Value> {
84        self.0.property(node, name)
85    }
86    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
87        self.0.children_named(node, name)
88    }
89    fn default_value(&self, node: NodeId) -> Option<quarb::Value> {
90        self.0.default_value(node)
91    }
92    fn metadata(&self, node: NodeId, key: &str) -> Option<quarb::Value> {
93        self.0.metadata(node, key)
94    }
95    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
96        self.0.links(node)
97    }
98    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
99        self.0.backlinks(node)
100    }
101    fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
102        self.0.resolve(node, property, hint)
103    }
104    fn link_property(
105        &self,
106        source: NodeId,
107        label: &str,
108        target: NodeId,
109        name: &str,
110    ) -> Option<quarb::Value> {
111        self.0.link_property(source, label, target, name)
112    }
113    fn quantifier_bound(&self) -> usize {
114        self.0.quantifier_bound()
115    }
116    fn invocation_instant(&self) -> Option<(i64, u32)> {
117        self.0.invocation_instant()
118    }
119    fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
120        self.0.unit_scale(expr)
121    }
122}
123
124impl Doc {
125    /// The kaiv door: the adapter is Rc-shared between the Doc and
126    /// its locator renderer (the `Shared` pattern qua's scheme
127    /// mounts use), riding the Boxed variant.
128    fn boxed_kaiv(a: quarb_kaiv::KaivAdapter) -> Doc {
129        let a = std::rc::Rc::new(a);
130        let r = a.clone();
131        Doc::Boxed(
132            Dyn(Box::new(quarb_mount::Shared(a))),
133            Box::new(move |n| r.locator(n)),
134        )
135    }
136
137    /// Parse a text document by format name — the wasm entry point,
138    /// and the text tail of the native `open`. Formats: json, yaml,
139    /// toml, csv, tsv, xml, html, markdown, jsonl/ndjson, kaiv/daiv.
140    pub fn parse(input: &str, format: &str) -> Result<Doc> {
141        match format {
142            // kaiv rides the Boxed door (no dedicated variant): the
143            // offline resolver — a browser mount has no filesystem
144            // or registry, so `.!units`/`.!types` imports beyond the
145            // embedded core fail with kaiv's own pointed error.
146            "kaiv" => {
147                let a = quarb_kaiv::KaivAdapter::parse_kaiv(input)
148                    .map_err(|e| anyhow::anyhow!("parsing kaiv: {e}"))?;
149                return Ok(Self::boxed_kaiv(a));
150            }
151            "daiv" => {
152                let a = quarb_kaiv::KaivAdapter::parse_daiv(input)
153                    .map_err(|e| anyhow::anyhow!("parsing daiv: {e}"))?;
154                return Ok(Self::boxed_kaiv(a));
155            }
156            "json" => quarb_json::JsonAdapter::parse(input)
157                .map(Doc::Json)
158                .context("parsing JSON"),
159            "jsonl" | "ndjson" => quarb_json::JsonAdapter::parse_lines(input)
160                .map(Doc::Json)
161                .context("parsing JSONL"),
162            "yaml" | "yml" => quarb_yaml::parse(input).map(Doc::Json).context("parsing YAML"),
163            "toml" => quarb_toml::parse(input).map(Doc::Json).context("parsing TOML"),
164            "csv" => quarb_csv::CsvAdapter::parse_with_delimiter(input, b',')
165                .map(Doc::Csv)
166                .context("parsing CSV"),
167            "tsv" => quarb_csv::CsvAdapter::parse_with_delimiter(input, b'\t')
168                .map(Doc::Csv)
169                .context("parsing TSV"),
170            "xml" => quarb_xml::XmlAdapter::parse(input)
171                .map(Doc::Xml)
172                .context("parsing XML"),
173            "html" => Ok(Doc::Html(quarb_html::HtmlAdapter::parse(input))),
174            "markdown" | "md" => Ok(Doc::Html(quarb_markdown::parse(input))),
175            other => bail!("unknown format: {other}"),
176        }
177    }
178
179    /// Run one query against this source with the session's invocation
180    /// instant and shell permission. The query text carries any macro
181    /// definitions inline (the session prepends its table), which
182    /// `quarb::run` expands.
183    /// The concrete adapter behind this `Doc`, as `&dyn` — the base a
184    /// `--model` enrichment layer wraps (one match, so the model
185    /// paths avoid duplicating the variant arms).
186    #[cfg(feature = "native")]
187    fn base_dyn(&self) -> &dyn quarb::AstAdapter {
188        match self {
189            Doc::Json(a) => a,
190            Doc::Csv(a) => a,
191            Doc::Xml(a) => a,
192            Doc::Html(a) => a,
193            Doc::Sqlite(a) => a,
194            Doc::Fs(a) => a,
195            Doc::FsDeep(a) => a,
196            Doc::Git(a) => a,
197            Doc::Archive(a) => a,
198            Doc::Xlsx(a) => a,
199            Doc::Code(a) => a,
200            Doc::Mount(a) => a,
201            Doc::Boxed(a, _) => &*a.0,
202        }
203    }
204
205    /// Run against a `--model`-enriched view of this source: the
206    /// derived containers, references, and edges the model declares,
207    /// over this `Doc`'s base. `now` binds `now()` for the base and
208    /// its constructor queries alike.
209    #[cfg(feature = "native")]
210    pub fn run_modeled(
211        &self,
212        query: &str,
213        now: (i64, u32),
214        allow_shell: bool,
215        model: &quarb_model::Model,
216    ) -> quarb::Result<QueryResult> {
217        let (secs, nanos) = now;
218        let base = quarb_model::Borrowed(self.base_dyn());
219        let nowed = WithNow {
220            inner: &base,
221            secs,
222            nanos,
223        };
224        let enriched = quarb_model::ModelAdapter::new(nowed, model.clone());
225        if allow_shell {
226            quarb::run(query, &AllowShell { inner: &enriched })
227        } else {
228            quarb::run(query, &enriched)
229        }
230    }
231
232    /// Render a node from a model-enriched run: `/container/value`
233    /// for derived nodes, the base's own renderer otherwise.
234    #[cfg(feature = "native")]
235    pub fn render_modeled(&self, node: NodeId, model: &quarb_model::Model) -> String {
236        let enriched =
237            quarb_model::ModelAdapter::new(quarb_model::Borrowed(self.base_dyn()), model.clone());
238        enriched.locator(node, |bn| self.render(bn))
239    }
240
241    pub fn run(&self, query: &str, now: (i64, u32), allow_shell: bool) -> quarb::Result<QueryResult> {
242        let (secs, nanos) = now;
243        macro_rules! go {
244            ($a:expr) => {{
245                let nowed = WithNow {
246                    inner: $a,
247                    secs,
248                    nanos,
249                };
250                if allow_shell {
251                    quarb::run(query, &AllowShell { inner: &nowed })
252                } else {
253                    quarb::run(query, &nowed)
254                }
255            }};
256        }
257        match self {
258            Doc::Json(a) => go!(a),
259            Doc::Csv(a) => go!(a),
260            Doc::Xml(a) => go!(a),
261            Doc::Html(a) => go!(a),
262            Doc::Sqlite(a) => go!(a),
263            #[cfg(feature = "native")]
264            Doc::Fs(a) => go!(a),
265            #[cfg(feature = "native")]
266            Doc::FsDeep(a) => go!(a),
267            #[cfg(feature = "native")]
268            Doc::Git(a) => go!(a),
269            #[cfg(feature = "native")]
270            Doc::Archive(a) => go!(a),
271            #[cfg(feature = "native")]
272            Doc::Xlsx(a) => go!(a),
273            #[cfg(feature = "native")]
274            Doc::Code(a) => go!(a),
275            Doc::Mount(a) => go!(a),
276            Doc::Boxed(a, _) => go!(a),
277        }
278    }
279
280    /// Render a node result as its source-appropriate locator.
281    pub fn render(&self, node: NodeId) -> String {
282        match self {
283            Doc::Json(a) => a.pointer(node),
284            Doc::Csv(a) => a.locator(node),
285            Doc::Xml(a) => a.locator(node),
286            Doc::Html(a) => a.locator(node),
287            Doc::Sqlite(a) => a.locator(node),
288            #[cfg(feature = "native")]
289            Doc::Fs(a) => a.path(node).display().to_string(),
290            #[cfg(feature = "native")]
291            Doc::FsDeep(a) => a.locator(node, |o| a.outer().path(o).display().to_string()),
292            #[cfg(feature = "native")]
293            Doc::Git(a) => a.locator(node),
294            #[cfg(feature = "native")]
295            Doc::Archive(a) => a.locator(node, |o| a.outer().locator(o)),
296            #[cfg(feature = "native")]
297            Doc::Xlsx(a) => a.locator(node),
298            #[cfg(feature = "native")]
299            Doc::Code(a) => a.locator(node),
300            Doc::Mount(a) => generic_locator(a, node),
301            Doc::Boxed(_, render) => render(node),
302        }
303    }
304
305    /// Open a SQLite database from its file bytes — a `.db` that
306    /// never touched a filesystem (the browser's uploaded files).
307    pub fn sqlite_bytes(bytes: &[u8]) -> Result<Doc> {
308        Ok(Doc::Sqlite(
309            quarb_sqlite::SqliteAdapter::from_bytes(bytes)
310                .map_err(|e| anyhow::anyhow!("{e}"))
311                .context("opening SQLite bytes")?,
312        ))
313    }
314
315    /// Mount already-built documents as named children of one root —
316    /// the general wasm-safe mount, for callers that assembled their
317    /// `Doc`s from text or bytes rather than paths.
318    pub fn mount_docs(parts: Vec<(String, Doc)>) -> Result<Doc> {
319        let mut mounts: Vec<quarb_mount::Mount> = Vec::new();
320        for (name, doc) in parts {
321            if mounts.iter().any(|m| m.name == name) {
322                bail!("two sources mount as '{name}'; give each a distinct name");
323            }
324            mounts.push(quarb_mount::Mount {
325                name,
326                adapter: doc.into_boxed()?,
327            });
328        }
329        Ok(Doc::Mount(quarb_mount::MountAdapter::new(mounts)))
330    }
331
332    /// Mount several already-parsed text documents as named children
333    /// of one root — [`Doc::mount_docs`] over [`Doc::parse`], for
334    /// callers that hold text (the browser playground's paste
335    /// boxes). `parts` is `(name, format, text)`.
336    pub fn mount_texts(parts: &[(String, String, String)]) -> Result<Doc> {
337        let mut docs: Vec<(String, Doc)> = Vec::new();
338        for (name, format, text) in parts {
339            let doc = Doc::parse(text, format)
340                .with_context(|| format!("parsing '{name}' as {format}"))?;
341            docs.push((name.clone(), doc));
342        }
343        Doc::mount_docs(docs)
344    }
345
346    /// Box this source as a shared adapter — a mount child.
347    fn into_boxed(self) -> Result<Box<dyn quarb::AstAdapter>> {
348        use quarb_mount::Shared;
349        Ok(match self {
350            Doc::Json(a) => Box::new(Shared(Rc::new(a))),
351            Doc::Csv(a) => Box::new(Shared(Rc::new(a))),
352            Doc::Xml(a) => Box::new(Shared(Rc::new(a))),
353            Doc::Html(a) => Box::new(Shared(Rc::new(a))),
354            Doc::Sqlite(a) => Box::new(Shared(Rc::new(a))),
355            #[cfg(feature = "native")]
356            Doc::Fs(a) => Box::new(Shared(Rc::new(a))),
357            #[cfg(feature = "native")]
358            Doc::FsDeep(a) => Box::new(Shared(Rc::new(a))),
359            #[cfg(feature = "native")]
360            Doc::Git(a) => Box::new(Shared(Rc::new(a))),
361            #[cfg(feature = "native")]
362            Doc::Archive(a) => Box::new(Shared(Rc::new(a))),
363            #[cfg(feature = "native")]
364            Doc::Xlsx(a) => Box::new(Shared(Rc::new(a))),
365            #[cfg(feature = "native")]
366            Doc::Code(a) => Box::new(Shared(Rc::new(a))),
367            Doc::Mount(_) => bail!("cannot nest a mount inside a mount"),
368            Doc::Boxed(a, _) => a.0,
369        })
370    }
371}
372
373// ---------------------------------------------------------------------
374// Native-only: filesystem/db/git dispatch and multi-source mounts.
375// ---------------------------------------------------------------------
376
377#[cfg(feature = "native")]
378impl Doc {
379    /// Open one path as a local source. Directories are filesystem
380    /// trees (`--descend` grafts parseable leaves); `git:PATH` opens a
381    /// repository; binary kinds (SQLite, spreadsheets, archives) and
382    /// source files dispatch by extension/magic; everything else is a
383    /// text document parsed by extension or content sniff.
384    pub fn open(path: &Path, opts: &Options) -> Result<Doc> {
385        if path.is_dir() {
386            let fsopts = quarb_fs::FsOptions {
387                hidden: opts.hidden,
388                respect_ignore: opts.respect_ignore,
389            };
390            let fs = quarb_fs::FsAdapter::with_options(path, fsopts)
391                .with_context(|| format!("opening directory {}", path.display()))?;
392            return Ok(if opts.descend {
393                Doc::FsDeep(quarb_compose::ComposeAdapter::with_source_paths(
394                    fs,
395                    |fs, n| Some(fs.path(n)),
396                ))
397            } else {
398                Doc::Fs(fs)
399            });
400        }
401
402        let s = path.to_string_lossy();
403        if let Some(repo) = s.strip_prefix("git:") {
404            let a =
405                quarb_git::GitAdapter::open(Path::new(repo)).context("opening git repository")?;
406            return Ok(Doc::Git(a));
407        }
408
409        let ext = path
410            .extension()
411            .and_then(|e| e.to_str())
412            .map(|e| e.to_ascii_lowercase());
413
414        if let Some(e) = &ext
415            && quarb_code::supported(e)
416        {
417            let a = quarb_code::CodeAdapter::open(path).context("parsing source file")?;
418            return Ok(Doc::Code(a));
419        }
420        if matches!(ext.as_deref(), Some("xlsx" | "xls" | "ods")) {
421            let a = quarb_xlsx::XlsxAdapter::open(path).context("opening workbook")?;
422            return Ok(Doc::Xlsx(a));
423        }
424        if is_sqlite(path) {
425            let a = quarb_sqlite::SqliteAdapter::open_with_refs(path, &opts.refs)
426                .context("opening SQLite database")?;
427            return Ok(Doc::Sqlite(a));
428        }
429        if is_archive(path) {
430            let a = quarb_archive::ArchiveAdapter::open(path).context("opening archive")?;
431            return Ok(Doc::Archive(quarb_compose::ComposeAdapter::new(a)));
432        }
433
434        // Text documents.
435        let text = std::fs::read_to_string(path)
436            .with_context(|| format!("reading {}", path.display()))?;
437        let text = text
438            .strip_prefix('\u{feff}')
439            .map(str::to_owned)
440            .unwrap_or(text);
441        match ext.as_deref() {
442            Some("csv") => Doc::parse(&text, "csv"),
443            Some("tsv") => Doc::parse(&text, "tsv"),
444            Some("yaml" | "yml") => Doc::parse(&text, "yaml"),
445            Some("toml") => Doc::parse(&text, "toml"),
446            Some("md" | "markdown") => Doc::parse(&text, "markdown"),
447            Some("jsonl" | "ndjson") => Doc::parse(&text, "jsonl"),
448            _ => {
449                if is_xml(path, &text) {
450                    Doc::parse(&text, "xml")
451                } else if is_html(path, &text) {
452                    Doc::parse(&text, "html")
453                } else {
454                    Doc::parse(&text, "json")
455                }
456            }
457        }
458    }
459
460    /// Open several sources as named children of one root (file stem =
461    /// mount name), so a single query — including a `<=>` join — spans
462    /// them all.
463    pub fn mount(paths: &[std::path::PathBuf], opts: &Options) -> Result<Doc> {
464        let specs: Vec<crate::MountSpec> = paths
465            .iter()
466            .map(|p| crate::MountSpec {
467                name: None,
468                path: p.clone(),
469            })
470            .collect();
471        Doc::mount_specs(&specs, opts)
472    }
473
474    /// [`Doc::mount`] with optional explicit mount names
475    /// (`NAME=TARGET`); an unnamed spec mounts under its file stem.
476    pub fn mount_specs(specs: &[crate::MountSpec], opts: &Options) -> Result<Doc> {
477        let mut mounts: Vec<quarb_mount::Mount> = Vec::new();
478        for (i, spec) in specs.iter().enumerate() {
479            let name = spec.name.clone().unwrap_or_else(|| {
480                spec.path
481                    .file_stem()
482                    .map(|s| s.to_string_lossy().into_owned())
483                    .unwrap_or_else(|| format!("doc{i}"))
484            });
485            if mounts.iter().any(|m| m.name == name) {
486                bail!(
487                    "input '{}' mounts as '{name}', colliding with an earlier input of the \
488                     same name; give each a distinct basename (or a NAME=TARGET alias)",
489                    spec.path.display()
490                );
491            }
492            let adapter = Doc::open(&spec.path, opts)?.into_boxed()?;
493            mounts.push(quarb_mount::Mount { name, adapter });
494        }
495        Ok(Doc::Mount(quarb_mount::MountAdapter::new(mounts)))
496    }
497
498}
499
500/// A name-path locator built from the adapter trait alone
501/// (`parent`/`name`) — used for a mount, whose per-source render
502/// functions we do not keep.
503fn generic_locator<A: quarb::AstAdapter>(a: &A, node: NodeId) -> String {
504    let mut parts = Vec::new();
505    let mut cur = Some(node);
506    while let Some(n) = cur {
507        if let Some(nm) = a.name(n) {
508            parts.push(nm);
509        }
510        cur = a.parent(n);
511    }
512    parts.reverse();
513    format!("/{}", parts.join("/"))
514}
515
516/// Whether a file is a SQLite database — by extension, or the 16-byte
517/// header magic.
518#[cfg(feature = "native")]
519fn is_sqlite(path: &Path) -> bool {
520    if path
521        .extension()
522        .and_then(|e| e.to_str())
523        .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "db" | "sqlite" | "sqlite3"))
524    {
525        return true;
526    }
527    use std::io::Read as _;
528    let mut buf = [0u8; 16];
529    std::fs::File::open(path)
530        .and_then(|mut f| f.read_exact(&mut buf))
531        .is_ok()
532        && &buf == b"SQLite format 3\0"
533}
534
535/// Whether a file is an archive — by extension, or zip/gzip magic.
536#[cfg(feature = "native")]
537fn is_archive(path: &Path) -> bool {
538    if path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
539        matches!(
540            e.to_ascii_lowercase().as_str(),
541            "zip" | "tar" | "gz" | "tgz" | "jar" | "war" | "docx" | "pptx" | "odt" | "odp"
542        )
543    }) {
544        return true;
545    }
546    use std::io::Read as _;
547    let mut buf = [0u8; 2];
548    std::fs::File::open(path)
549        .and_then(|mut f| f.read_exact(&mut buf))
550        .is_ok()
551        && (&buf == b"PK" || buf == [0x1f, 0x8b])
552}
553
554/// Whether to parse as XML: an `.xml`/`.svg`/`.xhtml` name, or a
555/// `<?xml` prolog.
556#[cfg(feature = "native")]
557fn is_xml(path: &Path, text: &str) -> bool {
558    path.extension()
559        .and_then(|e| e.to_str())
560        .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "xml" | "svg" | "xhtml"))
561        || text.trim_start().starts_with("<?xml")
562}
563
564/// Whether to parse as HTML: an `.html`/`.htm` name, or content that
565/// starts with `<`.
566#[cfg(feature = "native")]
567fn is_html(path: &Path, text: &str) -> bool {
568    path.extension()
569        .and_then(|e| e.to_str())
570        .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "html" | "htm"))
571        || text.trim_start().starts_with('<')
572}