quarb_session/daemon.rs
1//! The daemon-backed executor: reuse `qua`'s resident session.
2//!
3//! Rather than reimplement the socket, spawn, keying, TTL, and
4//! security machinery, [`DaemonExecutor`] shells out to
5//! `qua --resident`, which materializes the source once in a
6//! background process keyed by the target set and answers later
7//! queries from the standing arbor. `quai` sends the combined query
8//! text (its macro table prepended) and wraps the rendered lines as
9//! [`Cell`]s.
10//!
11//! The win is a *shared, persistent* hot arbor: it survives `quai`
12//! exiting and can be shared with other clients (a Jupyter kernel).
13//! For a single session over a RAM-sized source the in-process
14//! [`LocalExecutor`](crate::LocalExecutor) is faster (no IPC); the
15//! daemon earns its keep on expensive sources reused across runs.
16
17use crate::{Cell, Executor};
18use anyhow::{Context, Result, bail};
19use std::path::PathBuf;
20use std::process::Command;
21
22pub struct DaemonExecutor {
23 /// The `qua` binary to drive.
24 qua: PathBuf,
25 /// The source paths (the resident session's identity).
26 paths: Vec<PathBuf>,
27 /// A pinned `--now` (reproducible; also keys the session). Omitted
28 /// so the daemon reads the clock per query — which keeps the
29 /// session reusable across `quai` restarts.
30 pinned_now: Option<String>,
31 /// Semantics flags forwarded verbatim (`--allow-shell`, …).
32 flags: Vec<String>,
33}
34
35impl DaemonExecutor {
36 pub fn new(
37 paths: Vec<PathBuf>,
38 pinned_now: Option<String>,
39 allow_shell: bool,
40 hidden: bool,
41 no_ignore: bool,
42 descend: bool,
43 cache: bool,
44 ) -> Result<Self> {
45 let qua = resolve_qua();
46 let mut flags = Vec::new();
47 if allow_shell {
48 flags.push("--allow-shell".to_string());
49 }
50 if hidden {
51 flags.push("--hidden".to_string());
52 }
53 if no_ignore {
54 flags.push("--no-ignore".to_string());
55 }
56 if descend {
57 flags.push("--descend".to_string());
58 }
59 // Cache and daemon are layers, not alternatives: the resident
60 // arbor's cold start reads parsed ASTs from the on-disk cache,
61 // and populates it as it materializes.
62 if cache {
63 flags.push("--cache".to_string());
64 }
65 Ok(Self {
66 qua,
67 paths,
68 pinned_now,
69 flags,
70 })
71 }
72}
73
74/// Prefer a `qua` sitting beside the running binary (installed as a
75/// pair); otherwise rely on `PATH`.
76fn resolve_qua() -> PathBuf {
77 if let Ok(exe) = std::env::current_exe()
78 && let Some(dir) = exe.parent()
79 {
80 for name in ["qua", "qua.exe"] {
81 let sib = dir.join(name);
82 if sib.exists() {
83 return sib;
84 }
85 }
86 }
87 PathBuf::from("qua")
88}
89
90impl DaemonExecutor {
91 /// Invoke `qua`: `resident` hits the standing arbor (`&N`), while
92 /// a one-shot (not resident) re-materializes the source live
93 /// (`&N!`). Results are opaque rendered lines across this boundary
94 /// (typed values are a later protocol upgrade for Jupyter).
95 fn invoke(&self, resident: bool, query: &str) -> Result<Vec<Cell>> {
96 let mut cmd = Command::new(&self.qua);
97 if resident {
98 cmd.arg("--resident");
99 }
100 if let Some(iso) = &self.pinned_now {
101 cmd.arg("--now").arg(iso);
102 }
103 for f in &self.flags {
104 cmd.arg(f);
105 }
106 cmd.arg(query);
107 for p in &self.paths {
108 cmd.arg(p);
109 }
110 let out = cmd.output().with_context(|| {
111 format!(
112 "invoking '{}' (is qua installed and on PATH?)",
113 self.qua.display()
114 )
115 })?;
116 if !out.status.success() {
117 bail!("{}", String::from_utf8_lossy(&out.stderr).trim());
118 }
119 Ok(String::from_utf8_lossy(&out.stdout)
120 .lines()
121 .map(|l| Cell::Node(l.to_string()))
122 .collect())
123 }
124}
125
126impl Executor for DaemonExecutor {
127 fn run(&self, query: &str) -> Result<Vec<Cell>> {
128 self.invoke(true, query)
129 }
130
131 fn run_fresh(&self, query: &str) -> Result<Vec<Cell>> {
132 // A one-shot qua re-reads the source, bypassing the (fixed)
133 // resident arbor — a genuinely live reading.
134 self.invoke(false, query)
135 }
136}