Skip to main content

rpc/
session.rs

1use std::sync::{Arc, Mutex};
2use std::time::{Duration, Instant};
3
4use nomiscript::{Compiler, Error as NomiError, Expr, Program, Reader, SymbolTable, Value};
5use scripting::runtime::{EngineError, EngineOpts, ModuleCache, build_engine};
6use thiserror::Error;
7use tracing::debug;
8use wasmtime::Engine;
9
10use crate::ctx::{EpochBumper, InterruptHandle, ScriptCtx};
11use crate::envelope::{
12    EnvelopeError, Frame, Request, RequestId, Response, ResponsePayload, format_response,
13    read_frame, with_notices,
14};
15
16mod data;
17pub(crate) mod failure;
18pub(crate) mod payload;
19mod unit;
20
21pub use data::SessionData;
22use failure::record_eval;
23pub(crate) use failure::{EvalFailure, rejected};
24
25const EPOCH_DEADLINE_TICKS: u64 = 1;
26
27/// Per-channel evaluator. Owns mutable state across forms (defun-defined symbols
28/// persist between requests in the same session via `SymbolTable`; the wasm
29/// `ModuleCache` reuses compilations of structurally identical forms) and an
30/// interrupt handle that cooperatively short-circuits the next form on demand.
31///
32/// Eval pipeline: `nomiscript::Compiler::compile_with_mode(Eval)` emits a
33/// module exporting `nomi-eval`; the form's final value rides the function's
34/// `(ref null any)` return slot and the host walks it into an `EvalValue`
35/// via `decode_eval_result`.
36pub struct Session {
37    ctx: ScriptCtx,
38    engine: Engine,
39    compiler: Compiler,
40    cache: ModuleCache,
41    symbols: SymbolTable,
42    interrupt: InterruptHandle,
43    /// Watermark of the highest interrupt generation already attributed to a
44    /// finished request (see [`Session::check_interrupt`] / [`Session::ack_interrupt`]).
45    /// A `C-g` counts only while `interrupt.generation() > interrupt_ack`. One
46    /// signal aborts exactly one request: the running one, or the next one when
47    /// nothing is running (design rule 4).
48    interrupt_ack: u64,
49    /// Shared with each per-request `SessionData` so `env.log` output lands
50    /// where [`Session::handle_request`] can drain it.
51    output: Arc<Mutex<String>>,
52    /// Shared with each per-request `SessionData`; drained into each reply.
53    notices: Arc<Mutex<Vec<String>>>,
54    /// `None` on an unguarded session; otherwise when the account status may
55    /// next go unchecked until. See [`Session::guarded`].
56    status_check_after: Option<Instant>,
57}
58
59/// The same 30s as the tenant pool's `QUARANTINE_RECHECK`, kept in step by hand.
60const STATUS_RECHECK: Duration = Duration::from_secs(30);
61
62/// A structured eval result: the captured script output plus the typed
63/// value/error payload. The SLYNK mREPL maps `output` → `:write-string` and
64/// `payload` → `:write-values` / `:evaluation-aborted`. `handle_form` (the text
65/// wire path) does not use this — it formats the payload alone.
66#[derive(Debug, Clone, PartialEq)]
67pub struct EvalOutcome {
68    pub output: String,
69    pub payload: ResponsePayload,
70}
71
72#[derive(Debug, Error)]
73pub enum SessionError {
74    #[error("engine init failed: {0}")]
75    Engine(#[from] EngineError),
76    #[error("host prelude failed to load: {0}")]
77    Prelude(nomiscript::Error),
78}
79
80impl Session {
81    pub fn new(ctx: ScriptCtx) -> Result<Self, SessionError> {
82        let engine = build_engine(EngineOpts::baseline().with_fuel())?;
83        let host_fns = crate::natives::all_compiler_specs();
84        let mut symbols = SymbolTable::with_builtins();
85        symbols.register_host_fns(&host_fns);
86        // Host-dependent prelude (ADR-0029): loaded only here, after the RPC
87        // host fns it calls are registered. The universal prelude already rode
88        // in via `with_builtins`.
89        crate::host_prelude::load(&mut symbols).map_err(SessionError::Prelude)?;
90        Ok(Self {
91            ctx,
92            engine,
93            compiler: Compiler::with_host_fns(host_fns),
94            cache: ModuleCache::new(),
95            symbols,
96            interrupt: InterruptHandle::new(),
97            interrupt_ack: 0,
98            output: Arc::new(Mutex::new(String::new())),
99            notices: Arc::default(),
100            status_check_after: None,
101        })
102    }
103
104    #[must_use]
105    pub fn ctx(&self) -> &ScriptCtx {
106        &self.ctx
107    }
108
109    #[must_use]
110    pub fn interrupt_handle(&self) -> InterruptHandle {
111        self.interrupt.clone()
112    }
113
114    /// Symbol names completing `prefix`, sorted and deduplicated, for the SLYNK
115    /// completion rex (`M-x sly-complete-symbol` / mREPL TAB). The reader folds
116    /// symbols with `make_ascii_uppercase` at read time, so the match uppercases
117    /// the prefix the SAME way (ASCII-only — matching the reader, not full
118    /// Unicode) and returns the canonical name (it re-reads identically). Skips
119    /// `(SETF …)` setf-place names and compiler-internal `$…` / `__…` symbols —
120    /// none are head symbols a user types. An empty `prefix` lists every
121    /// completable symbol.
122    #[must_use]
123    pub fn completions(&self, prefix: &str) -> Vec<String> {
124        let needle = prefix.to_ascii_uppercase();
125        let mut names: Vec<String> = self
126            .symbols
127            .iter()
128            .map(|(name, _)| name.as_str())
129            .filter(|name| {
130                !name.starts_with('$') && !name.starts_with("__") && !name.starts_with("(SETF")
131            })
132            .filter(|name| name.starts_with(&needle))
133            .map(str::to_owned)
134            .collect();
135        names.sort_unstable();
136        names.dedup();
137        names
138    }
139
140    /// Cooperative cancel handle for an in-flight `nomi-eval`. Clone
141    /// and hand to the transport layer: when the client sends a
142    /// cancel signal (e.g. emacs `C-g`), call `.bump()` and the
143    /// awaiting evaluation traps with `EngineError::EpochInterrupt`,
144    /// surfacing on the wire as `(:error (:code interrupted ...))`.
145    #[must_use]
146    pub fn epoch_bumper(&self) -> EpochBumper {
147        EpochBumper::new(self.engine.clone())
148    }
149
150    /// Number of compiled wasm modules currently cached.
151    pub fn cache_size(&self) -> Result<usize, EngineError> {
152        self.cache.len()
153    }
154
155    pub async fn handle_form(&mut self, frame: &str) -> String {
156        match read_frame(frame) {
157            Ok(Frame::Request {
158                id,
159                stream: 0,
160                form,
161            }) => self.reply_to(0, id, form).await,
162            Ok(Frame::Request { id, stream, .. }) => rejected(0, EvalFailure::Unmuxed(id, stream)),
163            Ok(Frame::Interrupt(_) | Frame::Close(_)) => {
164                rejected(0, EvalFailure::Envelope(EnvelopeError::Unsupported))
165            }
166            Err(err) => rejected(0, EvalFailure::Envelope(err)),
167        }
168    }
169
170    /// The one request entry: evaluates `form` and formats the reply on `stream`.
171    pub(crate) async fn reply_to(&mut self, stream: u32, id: RequestId, form: &str) -> String {
172        self.take_notices();
173        let start = Instant::now();
174        let result = self.evaluate_frame(id, form).await;
175        record_eval(&result, start.elapsed());
176        let response = result.unwrap_or_else(EvalFailure::into_response);
177        with_notices(
178            format_response(&Response { stream, ..response }),
179            &self.take_notices(),
180        )
181    }
182
183    fn take_notices(&self) -> Vec<String> {
184        self.notices
185            .lock()
186            .map(|mut notices| std::mem::take(&mut *notices))
187            .unwrap_or_default()
188    }
189
190    /// Structured eval of a single bare `form` (not an envelope frame): clears
191    /// the output buffer, runs the form, and returns the captured script output
192    /// alongside the typed value/error payload. The SLYNK mREPL uses this so it
193    /// can render `:write-string` (output) and `:write-values` /
194    /// `:evaluation-aborted` (payload) separately. `handle_form` is unchanged.
195    pub async fn handle_request(&mut self, source: &str) -> EvalOutcome {
196        if let Ok(mut buf) = self.output.lock() {
197            buf.clear();
198        }
199        self.take_notices();
200        let payload = match self.eval_source(source).await {
201            Ok(value) => ResponsePayload::Value(value),
202            Err(err) => err.into_response().payload,
203        };
204        let mut output = self
205            .output
206            .lock()
207            .map(|buf| buf.clone())
208            .unwrap_or_default();
209        for notice in self.take_notices() {
210            output.push_str(&format!("; {notice}\n"));
211        }
212        EvalOutcome { output, payload }
213    }
214
215    /// Parses `source` to a single top-level form and evaluates it. Unlike
216    /// `handle_form`, the source is parsed to an AST directly (NOT interpolated
217    /// into an envelope string), so plist-shaped input can't hijack the
218    /// envelope: `1 :form (+ 2 3)` is rejected as "more than one form", not
219    /// silently re-read as a `(:id 1 :form …)` plist. The fixed `RequestId::Int(0)`
220    /// is unused downstream — the SLYNK layer tracks its own channel ids.
221    async fn eval_source(&mut self, source: &str) -> Result<Value, EvalFailure> {
222        match read_one(&RequestId::Int(0), source)? {
223            Some(form) => self.eval_one_form(form).await,
224            None => Ok(Value::Nil),
225        }
226    }
227
228    /// Reads `path`, evaluates every top-level form in source order (state —
229    /// `defun`s etc. — accumulates across forms, like the sshd channel), and
230    /// returns a short summary. Powers SLY's `M-x sly-load-file`
231    /// (`slynk:load-file`). Captured output across all forms is returned for the
232    /// caller to surface; a failing form aborts the load at that point.
233    pub async fn handle_file(&mut self, path: &str) -> EvalOutcome {
234        if let Ok(mut buf) = self.output.lock() {
235            buf.clear();
236        }
237        let payload = match self.load_path(path).await {
238            Ok(summary) => ResponsePayload::Value(Value::String(summary)),
239            Err(err) => err.into_response().payload,
240        };
241        let output = self
242            .output
243            .lock()
244            .map(|buf| buf.clone())
245            .unwrap_or_default();
246        EvalOutcome { output, payload }
247    }
248
249    /// Attributes all interrupts up to `observed` to the current request, so
250    /// they aren't counted again. Crucially the caller passes the SAME
251    /// generation it used to decide an interrupt is pending — never a fresh
252    /// reload — so a `C-g` that lands strictly after that observation point is
253    /// NOT folded into this request; it stays pending for the next form. The
254    /// guard keeps the watermark monotonic.
255    ///
256    /// Coalescing is intended: several `C-g`s observed together (generation
257    /// jumped by >1) cancel the one in-flight form, they do not pre-arm
258    /// cancellation of distinct future forms — that is the REPL `C-g` contract.
259    fn ack_interrupt(&mut self, observed: u64) {
260        if observed > self.interrupt_ack {
261            self.interrupt_ack = observed;
262        }
263    }
264
265    /// If an interrupt is pending, ack it (using the one generation snapshot
266    /// that decided it) and yield the interrupted error; otherwise `None`. The
267    /// single checkpoint used everywhere a form can abort on a `C-g` before the
268    /// Wasm call.
269    fn check_interrupt(&mut self, id: &RequestId) -> Option<EvalFailure> {
270        let observed = self.interrupt.generation();
271        (observed > self.interrupt_ack).then(|| {
272            self.ack_interrupt(observed);
273            EvalFailure::Interrupted(id.clone())
274        })
275    }
276
277    async fn load_path(&mut self, path: &str) -> Result<String, EvalFailure> {
278        let id = RequestId::Int(0);
279        // The synchronous file read + parse aren't covered by `run`'s checks, so
280        // guard them explicitly; a `C-g` during a later form is caught by that
281        // form's `run`, and the failing form aborts the whole load via `?`.
282        if let Some(err) = self.check_interrupt(&id) {
283            return Err(err);
284        }
285        let source = std::fs::read_to_string(path).map_err(|err| {
286            EvalFailure::Eval(
287                id.clone(),
288                NomiError::Compile(format!("cannot read {path}: {err}")),
289            )
290        })?;
291        if let Some(err) = self.check_interrupt(&id) {
292            return Err(err);
293        }
294        let program = Reader::parse(&source).map_err(|err| EvalFailure::Eval(id.clone(), err))?;
295        let count = program.exprs.len();
296        for form in program.exprs {
297            self.run(&Request {
298                id: id.clone(),
299                form,
300            })
301            .await?;
302        }
303        Ok(format!("loaded {path} ({count} forms)"))
304    }
305
306    /// Evaluates a single already-parsed form (mREPL input). The interrupt
307    /// pre-start check lives in `run`.
308    async fn eval_one_form(&mut self, form: Expr) -> Result<Value, EvalFailure> {
309        self.run(&Request {
310            id: RequestId::Int(0),
311            form,
312        })
313        .await
314    }
315
316    async fn evaluate_frame(&mut self, id: RequestId, form: &str) -> Result<Response, EvalFailure> {
317        let form = read_one(&id, form)?.ok_or_else(|| {
318            EvalFailure::Eval(id.clone(), NomiError::Compile("expected a form".into()))
319        })?;
320        let request = Request { id, form };
321        let value = self.run(&request).await?;
322        Ok(Response {
323            stream: 0,
324            id: request.id,
325            payload: ResponsePayload::Value(value),
326        })
327    }
328
329    /// A session for a remote user, re-checking per form that the account may
330    /// still be served.
331    ///
332    /// The daemon's `refuse_if_withheld` runs only when a channel is *opened*
333    /// and most natives never touch the tenant pool, so without this an open SSH
334    /// session outlives a disable indefinitely. [`Session::new`] stays unguarded
335    /// for the local CLI and for tests, whose users have no directory row.
336    ///
337    /// # Errors
338    /// As [`Session::new`].
339    pub fn guarded(ctx: ScriptCtx) -> Result<Self, SessionError> {
340        let mut session = Self::new(ctx)?;
341        session.status_check_after = Some(Instant::now());
342        Ok(session)
343    }
344
345    /// Bounded by [`STATUS_RECHECK`] rather than read per form: this is the hot
346    /// eval path and the global pool's budget is 5.
347    async fn check_account(&mut self, id: &RequestId) -> Result<(), EvalFailure> {
348        let Some(due) = self.status_check_after else {
349            return Ok(());
350        };
351        if Instant::now() < due {
352            return Ok(());
353        }
354        let refusal =
355            refusal_or_closed(server::command::user::account_refusal(self.ctx.user_id).await);
356
357        match refusal {
358            None => {
359                self.status_check_after = Some(Instant::now() + STATUS_RECHECK);
360                Ok(())
361            }
362            Some(reason) => Err(EvalFailure::Refused(id.clone(), reason)),
363        }
364    }
365
366    async fn run(&mut self, request: &Request) -> Result<Value, EvalFailure> {
367        debug!(user_id = %self.ctx.user_id, "evaluating form");
368        self.check_account(&request.id).await?;
369        // A `C-g` that landed before this form started (pre-armed, or during an
370        // earlier form of a load) aborts here.
371        if let Some(err) = self.check_interrupt(&request.id) {
372            return Err(err);
373        }
374        let program = Program::new(vec![request.form.clone()]);
375        let compiled = self
376            .compiler
377            .compile_eval_with_type(&program, &mut self.symbols)
378            .map_err(|err| EvalFailure::Eval(request.id.clone(), err))?;
379        self.run_compiled(&request.id, compiled).await
380    }
381}
382
383/// The single form in `source`, or `None` when it holds none.
384fn read_one(id: &RequestId, source: &str) -> Result<Option<Expr>, EvalFailure> {
385    let program = Reader::parse(source).map_err(|err| EvalFailure::Eval(id.clone(), err))?;
386    let mut exprs = program.exprs;
387    match exprs.len() {
388        0 | 1 => Ok(exprs.pop()),
389        _ => Err(EvalFailure::Eval(
390            id.clone(),
391            NomiError::Compile("expected a single form".to_string()),
392        )),
393    }
394}
395
396/// Fails closed: an unreadable directory is not evidence of health.
397/// An unavailable directory is already logged where the connection was refused.
398fn refusal_or_closed(
399    checked: Result<Option<server::command::user::Refusal>, server::command::CmdError>,
400) -> Option<server::command::user::Refusal> {
401    checked.unwrap_or_else(|err| {
402        if !err.is_unavailable() {
403            tracing::error!("account status check failed, refusing: {err:?}");
404        }
405        Some(server::command::user::Refusal::Quarantined)
406    })
407}
408
409#[cfg(test)]
410mod tests;