1
use std::sync::{Arc, Mutex};
2
use std::time::{Duration, Instant};
3

            
4
use nomiscript::{Compiler, Error as NomiError, Expr, Program, Reader, SymbolTable, Value};
5
use scripting::runtime::{EngineError, EngineOpts, ModuleCache, build_engine};
6
use thiserror::Error;
7
use tracing::debug;
8
use wasmtime::Engine;
9

            
10
use crate::ctx::{EpochBumper, InterruptHandle, ScriptCtx};
11
use crate::envelope::{
12
    EnvelopeError, Frame, Request, RequestId, Response, ResponsePayload, format_response,
13
    read_frame, with_notices,
14
};
15

            
16
mod data;
17
pub(crate) mod failure;
18
pub(crate) mod payload;
19
mod unit;
20

            
21
pub use data::SessionData;
22
use failure::record_eval;
23
pub(crate) use failure::{EvalFailure, rejected};
24

            
25
const 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`.
36
pub 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.
60
const 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)]
67
pub struct EvalOutcome {
68
    pub output: String,
69
    pub payload: ResponsePayload,
70
}
71

            
72
#[derive(Debug, Error)]
73
pub 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

            
80
impl Session {
81
60152
    pub fn new(ctx: ScriptCtx) -> Result<Self, SessionError> {
82
60152
        let engine = build_engine(EngineOpts::baseline().with_fuel())?;
83
60152
        let host_fns = crate::natives::all_compiler_specs();
84
60152
        let mut symbols = SymbolTable::with_builtins();
85
60152
        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
60152
        crate::host_prelude::load(&mut symbols).map_err(SessionError::Prelude)?;
90
60152
        Ok(Self {
91
60152
            ctx,
92
60152
            engine,
93
60152
            compiler: Compiler::with_host_fns(host_fns),
94
60152
            cache: ModuleCache::new(),
95
60152
            symbols,
96
60152
            interrupt: InterruptHandle::new(),
97
60152
            interrupt_ack: 0,
98
60152
            output: Arc::new(Mutex::new(String::new())),
99
60152
            notices: Arc::default(),
100
60152
            status_check_after: None,
101
60152
        })
102
60152
    }
103

            
104
    #[must_use]
105
1120
    pub fn ctx(&self) -> &ScriptCtx {
106
1120
        &self.ctx
107
1120
    }
108

            
109
    #[must_use]
110
12410
    pub fn interrupt_handle(&self) -> InterruptHandle {
111
12410
        self.interrupt.clone()
112
12410
    }
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
4
    pub fn completions(&self, prefix: &str) -> Vec<String> {
124
4
        let needle = prefix.to_ascii_uppercase();
125
4
        let mut names: Vec<String> = self
126
4
            .symbols
127
4
            .iter()
128
977
            .map(|(name, _)| name.as_str())
129
977
            .filter(|name| {
130
977
                !name.starts_with('$') && !name.starts_with("__") && !name.starts_with("(SETF")
131
977
            })
132
977
            .filter(|name| name.starts_with(&needle))
133
4
            .map(str::to_owned)
134
            .collect();
135
4
        names.sort_unstable();
136
4
        names.dedup();
137
4
        names
138
4
    }
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
12403
    pub fn epoch_bumper(&self) -> EpochBumper {
147
12403
        EpochBumper::new(self.engine.clone())
148
12403
    }
149

            
150
    /// Number of compiled wasm modules currently cached.
151
1120
    pub fn cache_size(&self) -> Result<usize, EngineError> {
152
1120
        self.cache.len()
153
1120
    }
154

            
155
154733
    pub async fn handle_form(&mut self, frame: &str) -> String {
156
4531
        match read_frame(frame) {
157
            Ok(Frame::Request {
158
                id,
159
                stream: 0,
160
                form,
161
4515
            }) => self.reply_to(0, id, form).await,
162
2
            Ok(Frame::Request { id, stream, .. }) => rejected(0, EvalFailure::Unmuxed(id, stream)),
163
            Ok(Frame::Interrupt(_) | Frame::Close(_)) => {
164
1
                rejected(0, EvalFailure::Envelope(EnvelopeError::Unsupported))
165
            }
166
13
            Err(err) => rejected(0, EvalFailure::Envelope(err)),
167
        }
168
4531
    }
169

            
170
    /// The one request entry: evaluates `form` and formats the reply on `stream`.
171
231626
    pub(crate) async fn reply_to(&mut self, stream: u32, id: RequestId, form: &str) -> String {
172
231626
        self.take_notices();
173
231626
        let start = Instant::now();
174
231626
        let result = self.evaluate_frame(id, form).await;
175
230985
        record_eval(&result, start.elapsed());
176
230985
        let response = result.unwrap_or_else(EvalFailure::into_response);
177
230985
        with_notices(
178
230985
            format_response(&Response { stream, ..response }),
179
230985
            &self.take_notices(),
180
230985
        )
181
230985
    }
182

            
183
464013
    fn take_notices(&self) -> Vec<String> {
184
464013
        self.notices
185
464013
            .lock()
186
464013
            .map(|mut notices| std::mem::take(&mut *notices))
187
            .unwrap_or_default()
188
464013
    }
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
701
    pub async fn handle_request(&mut self, source: &str) -> EvalOutcome {
196
701
        if let Ok(mut buf) = self.output.lock() {
197
701
            buf.clear();
198
        }
199
701
        self.take_notices();
200
701
        let payload = match self.eval_source(source).await {
201
511
            Ok(value) => ResponsePayload::Value(value),
202
190
            Err(err) => err.into_response().payload,
203
        };
204
701
        let mut output = self
205
701
            .output
206
701
            .lock()
207
701
            .map(|buf| buf.clone())
208
            .unwrap_or_default();
209
701
        for notice in self.take_notices() {
210
            output.push_str(&format!("; {notice}\n"));
211
        }
212
701
        EvalOutcome { output, payload }
213
701
    }
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
701
    async fn eval_source(&mut self, source: &str) -> Result<Value, EvalFailure> {
222
701
        match read_one(&RequestId::Int(0), source)? {
223
700
            Some(form) => self.eval_one_form(form).await,
224
            None => Ok(Value::Nil),
225
        }
226
701
    }
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
4
    pub async fn handle_file(&mut self, path: &str) -> EvalOutcome {
234
4
        if let Ok(mut buf) = self.output.lock() {
235
4
            buf.clear();
236
        }
237
4
        let payload = match self.load_path(path).await {
238
1
            Ok(summary) => ResponsePayload::Value(Value::String(summary)),
239
3
            Err(err) => err.into_response().payload,
240
        };
241
4
        let output = self
242
4
            .output
243
4
            .lock()
244
4
            .map(|buf| buf.clone())
245
            .unwrap_or_default();
246
4
        EvalOutcome { output, payload }
247
4
    }
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
13403
    fn ack_interrupt(&mut self, observed: u64) {
260
13403
        if observed > self.interrupt_ack {
261
1455
            self.interrupt_ack = observed;
262
11948
        }
263
13403
    }
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
462366
    fn check_interrupt(&mut self, id: &RequestId) -> Option<EvalFailure> {
270
462366
        let observed = self.interrupt.generation();
271
462366
        (observed > self.interrupt_ack).then(|| {
272
1130
            self.ack_interrupt(observed);
273
1130
            EvalFailure::Interrupted(id.clone())
274
1130
        })
275
462366
    }
276

            
277
4
    async fn load_path(&mut self, path: &str) -> Result<String, EvalFailure> {
278
4
        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
4
        if let Some(err) = self.check_interrupt(&id) {
283
1
            return Err(err);
284
3
        }
285
3
        let source = std::fs::read_to_string(path).map_err(|err| {
286
1
            EvalFailure::Eval(
287
1
                id.clone(),
288
1
                NomiError::Compile(format!("cannot read {path}: {err}")),
289
1
            )
290
1
        })?;
291
2
        if let Some(err) = self.check_interrupt(&id) {
292
            return Err(err);
293
2
        }
294
2
        let program = Reader::parse(&source).map_err(|err| EvalFailure::Eval(id.clone(), err))?;
295
2
        let count = program.exprs.len();
296
2
        for form in program.exprs {
297
4
            self.run(&Request {
298
4
                id: id.clone(),
299
4
                form,
300
4
            })
301
4
            .await?;
302
        }
303
1
        Ok(format!("loaded {path} ({count} forms)"))
304
4
    }
305

            
306
    /// Evaluates a single already-parsed form (mREPL input). The interrupt
307
    /// pre-start check lives in `run`.
308
700
    async fn eval_one_form(&mut self, form: Expr) -> Result<Value, EvalFailure> {
309
700
        self.run(&Request {
310
700
            id: RequestId::Int(0),
311
700
            form,
312
700
        })
313
700
        .await
314
700
    }
315

            
316
231626
    async fn evaluate_frame(&mut self, id: RequestId, form: &str) -> Result<Response, EvalFailure> {
317
231626
        let form = read_one(&id, form)?.ok_or_else(|| {
318
1
            EvalFailure::Eval(id.clone(), NomiError::Compile("expected a form".into()))
319
1
        })?;
320
231619
        let request = Request { id, form };
321
231619
        let value = self.run(&request).await?;
322
215806
        Ok(Response {
323
215806
            stream: 0,
324
215806
            id: request.id,
325
215806
            payload: ResponsePayload::Value(value),
326
215806
        })
327
230985
    }
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
4161
    pub fn guarded(ctx: ScriptCtx) -> Result<Self, SessionError> {
340
4161
        let mut session = Self::new(ctx)?;
341
4161
        session.status_check_after = Some(Instant::now());
342
4161
        Ok(session)
343
4161
    }
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
232323
    async fn check_account(&mut self, id: &RequestId) -> Result<(), EvalFailure> {
348
232323
        let Some(due) = self.status_check_after else {
349
197602
            return Ok(());
350
        };
351
34721
        if Instant::now() < due {
352
31040
            return Ok(());
353
3681
        }
354
        let refusal =
355
3681
            refusal_or_closed(server::command::user::account_refusal(self.ctx.user_id).await);
356

            
357
3681
        match refusal {
358
            None => {
359
3520
                self.status_check_after = Some(Instant::now() + STATUS_RECHECK);
360
3520
                Ok(())
361
            }
362
161
            Some(reason) => Err(EvalFailure::Refused(id.clone(), reason)),
363
        }
364
232323
    }
365

            
366
232323
    async fn run(&mut self, request: &Request) -> Result<Value, EvalFailure> {
367
232323
        debug!(user_id = %self.ctx.user_id, "evaluating form");
368
232323
        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
232162
        if let Some(err) = self.check_interrupt(&request.id) {
372
168
            return Err(err);
373
231994
        }
374
231994
        let program = Program::new(vec![request.form.clone()]);
375
231994
        let compiled = self
376
231994
            .compiler
377
231994
            .compile_eval_with_type(&program, &mut self.symbols)
378
1797
            .map_err(|err| EvalFailure::Eval(request.id.clone(), err))?;
379
230197
        self.run_compiled(&request.id, compiled).await
380
231682
    }
381
}
382

            
383
/// The single form in `source`, or `None` when it holds none.
384
232327
fn read_one(id: &RequestId, source: &str) -> Result<Option<Expr>, EvalFailure> {
385
232327
    let program = Reader::parse(source).map_err(|err| EvalFailure::Eval(id.clone(), err))?;
386
232322
    let mut exprs = program.exprs;
387
232322
    match exprs.len() {
388
232320
        0 | 1 => Ok(exprs.pop()),
389
2
        _ => Err(EvalFailure::Eval(
390
2
            id.clone(),
391
2
            NomiError::Compile("expected a single form".to_string()),
392
2
        )),
393
    }
394
232327
}
395

            
396
/// Fails closed: an unreadable directory is not evidence of health.
397
/// An unavailable directory is already logged where the connection was refused.
398
3684
fn refusal_or_closed(
399
3684
    checked: Result<Option<server::command::user::Refusal>, server::command::CmdError>,
400
3684
) -> Option<server::command::user::Refusal> {
401
3684
    checked.unwrap_or_else(|err| {
402
2
        if !err.is_unavailable() {
403
1
            tracing::error!("account status check failed, refusing: {err:?}");
404
1
        }
405
2
        Some(server::command::user::Refusal::Quarantined)
406
2
    })
407
3684
}
408

            
409
#[cfg(test)]
410
mod tests;