Lines
97.6 %
Functions
66.41 %
Branches
100 %
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use nomiscript::{Compiler, Error as NomiError, Expr, Program, Reader, SymbolTable, Value};
use scripting::runtime::{EngineError, EngineOpts, ModuleCache, build_engine};
use thiserror::Error;
use tracing::debug;
use wasmtime::Engine;
use crate::ctx::{EpochBumper, InterruptHandle, ScriptCtx};
use crate::envelope::{
EnvelopeError, Frame, Request, RequestId, Response, ResponsePayload, format_response,
read_frame, with_notices,
};
mod data;
pub(crate) mod failure;
pub(crate) mod payload;
mod unit;
pub use data::SessionData;
use failure::record_eval;
pub(crate) use failure::{EvalFailure, rejected};
const EPOCH_DEADLINE_TICKS: u64 = 1;
/// Per-channel evaluator. Owns mutable state across forms (defun-defined symbols
/// persist between requests in the same session via `SymbolTable`; the wasm
/// `ModuleCache` reuses compilations of structurally identical forms) and an
/// interrupt handle that cooperatively short-circuits the next form on demand.
///
/// Eval pipeline: `nomiscript::Compiler::compile_with_mode(Eval)` emits a
/// module exporting `nomi-eval`; the form's final value rides the function's
/// `(ref null any)` return slot and the host walks it into an `EvalValue`
/// via `decode_eval_result`.
pub struct Session {
ctx: ScriptCtx,
engine: Engine,
compiler: Compiler,
cache: ModuleCache,
symbols: SymbolTable,
interrupt: InterruptHandle,
/// Watermark of the highest interrupt generation already attributed to a
/// finished request (see [`Session::check_interrupt`] / [`Session::ack_interrupt`]).
/// A `C-g` counts only while `interrupt.generation() > interrupt_ack`. One
/// signal aborts exactly one request: the running one, or the next one when
/// nothing is running (design rule 4).
interrupt_ack: u64,
/// Shared with each per-request `SessionData` so `env.log` output lands
/// where [`Session::handle_request`] can drain it.
output: Arc<Mutex<String>>,
/// Shared with each per-request `SessionData`; drained into each reply.
notices: Arc<Mutex<Vec<String>>>,
/// `None` on an unguarded session; otherwise when the account status may
/// next go unchecked until. See [`Session::guarded`].
status_check_after: Option<Instant>,
}
/// The same 30s as the tenant pool's `QUARANTINE_RECHECK`, kept in step by hand.
const STATUS_RECHECK: Duration = Duration::from_secs(30);
/// A structured eval result: the captured script output plus the typed
/// value/error payload. The SLYNK mREPL maps `output` → `:write-string` and
/// `payload` → `:write-values` / `:evaluation-aborted`. `handle_form` (the text
/// wire path) does not use this — it formats the payload alone.
#[derive(Debug, Clone, PartialEq)]
pub struct EvalOutcome {
pub output: String,
pub payload: ResponsePayload,
#[derive(Debug, Error)]
pub enum SessionError {
#[error("engine init failed: {0}")]
Engine(#[from] EngineError),
#[error("host prelude failed to load: {0}")]
Prelude(nomiscript::Error),
impl Session {
pub fn new(ctx: ScriptCtx) -> Result<Self, SessionError> {
let engine = build_engine(EngineOpts::baseline().with_fuel())?;
let host_fns = crate::natives::all_compiler_specs();
let mut symbols = SymbolTable::with_builtins();
symbols.register_host_fns(&host_fns);
// Host-dependent prelude (ADR-0029): loaded only here, after the RPC
// host fns it calls are registered. The universal prelude already rode
// in via `with_builtins`.
crate::host_prelude::load(&mut symbols).map_err(SessionError::Prelude)?;
Ok(Self {
ctx,
engine,
compiler: Compiler::with_host_fns(host_fns),
cache: ModuleCache::new(),
symbols,
interrupt: InterruptHandle::new(),
interrupt_ack: 0,
output: Arc::new(Mutex::new(String::new())),
notices: Arc::default(),
status_check_after: None,
})
#[must_use]
pub fn ctx(&self) -> &ScriptCtx {
&self.ctx
pub fn interrupt_handle(&self) -> InterruptHandle {
self.interrupt.clone()
/// Symbol names completing `prefix`, sorted and deduplicated, for the SLYNK
/// completion rex (`M-x sly-complete-symbol` / mREPL TAB). The reader folds
/// symbols with `make_ascii_uppercase` at read time, so the match uppercases
/// the prefix the SAME way (ASCII-only — matching the reader, not full
/// Unicode) and returns the canonical name (it re-reads identically). Skips
/// `(SETF …)` setf-place names and compiler-internal `$…` / `__…` symbols —
/// none are head symbols a user types. An empty `prefix` lists every
/// completable symbol.
pub fn completions(&self, prefix: &str) -> Vec<String> {
let needle = prefix.to_ascii_uppercase();
let mut names: Vec<String> = self
.symbols
.iter()
.map(|(name, _)| name.as_str())
.filter(|name| {
!name.starts_with('$') && !name.starts_with("__") && !name.starts_with("(SETF")
.filter(|name| name.starts_with(&needle))
.map(str::to_owned)
.collect();
names.sort_unstable();
names.dedup();
names
/// Cooperative cancel handle for an in-flight `nomi-eval`. Clone
/// and hand to the transport layer: when the client sends a
/// cancel signal (e.g. emacs `C-g`), call `.bump()` and the
/// awaiting evaluation traps with `EngineError::EpochInterrupt`,
/// surfacing on the wire as `(:error (:code interrupted ...))`.
pub fn epoch_bumper(&self) -> EpochBumper {
EpochBumper::new(self.engine.clone())
/// Number of compiled wasm modules currently cached.
pub fn cache_size(&self) -> Result<usize, EngineError> {
self.cache.len()
pub async fn handle_form(&mut self, frame: &str) -> String {
match read_frame(frame) {
Ok(Frame::Request {
id,
stream: 0,
form,
}) => self.reply_to(0, id, form).await,
Ok(Frame::Request { id, stream, .. }) => rejected(0, EvalFailure::Unmuxed(id, stream)),
Ok(Frame::Interrupt(_) | Frame::Close(_)) => {
rejected(0, EvalFailure::Envelope(EnvelopeError::Unsupported))
Err(err) => rejected(0, EvalFailure::Envelope(err)),
/// The one request entry: evaluates `form` and formats the reply on `stream`.
pub(crate) async fn reply_to(&mut self, stream: u32, id: RequestId, form: &str) -> String {
self.take_notices();
let start = Instant::now();
let result = self.evaluate_frame(id, form).await;
record_eval(&result, start.elapsed());
let response = result.unwrap_or_else(EvalFailure::into_response);
with_notices(
format_response(&Response { stream, ..response }),
&self.take_notices(),
)
fn take_notices(&self) -> Vec<String> {
self.notices
.lock()
.map(|mut notices| std::mem::take(&mut *notices))
.unwrap_or_default()
/// Structured eval of a single bare `form` (not an envelope frame): clears
/// the output buffer, runs the form, and returns the captured script output
/// alongside the typed value/error payload. The SLYNK mREPL uses this so it
/// can render `:write-string` (output) and `:write-values` /
/// `:evaluation-aborted` (payload) separately. `handle_form` is unchanged.
pub async fn handle_request(&mut self, source: &str) -> EvalOutcome {
if let Ok(mut buf) = self.output.lock() {
buf.clear();
let payload = match self.eval_source(source).await {
Ok(value) => ResponsePayload::Value(value),
Err(err) => err.into_response().payload,
let mut output = self
.output
.map(|buf| buf.clone())
.unwrap_or_default();
for notice in self.take_notices() {
output.push_str(&format!("; {notice}\n"));
EvalOutcome { output, payload }
/// Parses `source` to a single top-level form and evaluates it. Unlike
/// `handle_form`, the source is parsed to an AST directly (NOT interpolated
/// into an envelope string), so plist-shaped input can't hijack the
/// envelope: `1 :form (+ 2 3)` is rejected as "more than one form", not
/// silently re-read as a `(:id 1 :form …)` plist. The fixed `RequestId::Int(0)`
/// is unused downstream — the SLYNK layer tracks its own channel ids.
async fn eval_source(&mut self, source: &str) -> Result<Value, EvalFailure> {
match read_one(&RequestId::Int(0), source)? {
Some(form) => self.eval_one_form(form).await,
None => Ok(Value::Nil),
/// Reads `path`, evaluates every top-level form in source order (state —
/// `defun`s etc. — accumulates across forms, like the sshd channel), and
/// returns a short summary. Powers SLY's `M-x sly-load-file`
/// (`slynk:load-file`). Captured output across all forms is returned for the
/// caller to surface; a failing form aborts the load at that point.
pub async fn handle_file(&mut self, path: &str) -> EvalOutcome {
let payload = match self.load_path(path).await {
Ok(summary) => ResponsePayload::Value(Value::String(summary)),
let output = self
/// Attributes all interrupts up to `observed` to the current request, so
/// they aren't counted again. Crucially the caller passes the SAME
/// generation it used to decide an interrupt is pending — never a fresh
/// reload — so a `C-g` that lands strictly after that observation point is
/// NOT folded into this request; it stays pending for the next form. The
/// guard keeps the watermark monotonic.
/// Coalescing is intended: several `C-g`s observed together (generation
/// jumped by >1) cancel the one in-flight form, they do not pre-arm
/// cancellation of distinct future forms — that is the REPL `C-g` contract.
fn ack_interrupt(&mut self, observed: u64) {
if observed > self.interrupt_ack {
self.interrupt_ack = observed;
/// If an interrupt is pending, ack it (using the one generation snapshot
/// that decided it) and yield the interrupted error; otherwise `None`. The
/// single checkpoint used everywhere a form can abort on a `C-g` before the
/// Wasm call.
fn check_interrupt(&mut self, id: &RequestId) -> Option<EvalFailure> {
let observed = self.interrupt.generation();
(observed > self.interrupt_ack).then(|| {
self.ack_interrupt(observed);
EvalFailure::Interrupted(id.clone())
async fn load_path(&mut self, path: &str) -> Result<String, EvalFailure> {
let id = RequestId::Int(0);
// The synchronous file read + parse aren't covered by `run`'s checks, so
// guard them explicitly; a `C-g` during a later form is caught by that
// form's `run`, and the failing form aborts the whole load via `?`.
if let Some(err) = self.check_interrupt(&id) {
return Err(err);
let source = std::fs::read_to_string(path).map_err(|err| {
EvalFailure::Eval(
id.clone(),
NomiError::Compile(format!("cannot read {path}: {err}")),
})?;
let program = Reader::parse(&source).map_err(|err| EvalFailure::Eval(id.clone(), err))?;
let count = program.exprs.len();
for form in program.exprs {
self.run(&Request {
id: id.clone(),
.await?;
Ok(format!("loaded {path} ({count} forms)"))
/// Evaluates a single already-parsed form (mREPL input). The interrupt
/// pre-start check lives in `run`.
async fn eval_one_form(&mut self, form: Expr) -> Result<Value, EvalFailure> {
id: RequestId::Int(0),
.await
async fn evaluate_frame(&mut self, id: RequestId, form: &str) -> Result<Response, EvalFailure> {
let form = read_one(&id, form)?.ok_or_else(|| {
EvalFailure::Eval(id.clone(), NomiError::Compile("expected a form".into()))
let request = Request { id, form };
let value = self.run(&request).await?;
Ok(Response {
id: request.id,
payload: ResponsePayload::Value(value),
/// A session for a remote user, re-checking per form that the account may
/// still be served.
/// The daemon's `refuse_if_withheld` runs only when a channel is *opened*
/// and most natives never touch the tenant pool, so without this an open SSH
/// session outlives a disable indefinitely. [`Session::new`] stays unguarded
/// for the local CLI and for tests, whose users have no directory row.
/// # Errors
/// As [`Session::new`].
pub fn guarded(ctx: ScriptCtx) -> Result<Self, SessionError> {
let mut session = Self::new(ctx)?;
session.status_check_after = Some(Instant::now());
Ok(session)
/// Bounded by [`STATUS_RECHECK`] rather than read per form: this is the hot
/// eval path and the global pool's budget is 5.
async fn check_account(&mut self, id: &RequestId) -> Result<(), EvalFailure> {
let Some(due) = self.status_check_after else {
return Ok(());
if Instant::now() < due {
let refusal =
refusal_or_closed(server::command::user::account_refusal(self.ctx.user_id).await);
match refusal {
None => {
self.status_check_after = Some(Instant::now() + STATUS_RECHECK);
Ok(())
Some(reason) => Err(EvalFailure::Refused(id.clone(), reason)),
async fn run(&mut self, request: &Request) -> Result<Value, EvalFailure> {
debug!(user_id = %self.ctx.user_id, "evaluating form");
self.check_account(&request.id).await?;
// A `C-g` that landed before this form started (pre-armed, or during an
// earlier form of a load) aborts here.
if let Some(err) = self.check_interrupt(&request.id) {
let program = Program::new(vec![request.form.clone()]);
let compiled = self
.compiler
.compile_eval_with_type(&program, &mut self.symbols)
.map_err(|err| EvalFailure::Eval(request.id.clone(), err))?;
self.run_compiled(&request.id, compiled).await
/// The single form in `source`, or `None` when it holds none.
fn read_one(id: &RequestId, source: &str) -> Result<Option<Expr>, EvalFailure> {
let program = Reader::parse(source).map_err(|err| EvalFailure::Eval(id.clone(), err))?;
let mut exprs = program.exprs;
match exprs.len() {
0 | 1 => Ok(exprs.pop()),
_ => Err(EvalFailure::Eval(
NomiError::Compile("expected a single form".to_string()),
)),
/// Fails closed: an unreadable directory is not evidence of health.
/// An unavailable directory is already logged where the connection was refused.
fn refusal_or_closed(
checked: Result<Option<server::command::user::Refusal>, server::command::CmdError>,
) -> Option<server::command::user::Refusal> {
checked.unwrap_or_else(|err| {
if !err.is_unavailable() {
tracing::error!("account status check failed, refusing: {err:?}");
Some(server::command::user::Refusal::Quarantined)
#[cfg(test)]
mod tests;