Lines
77.92 %
Functions
42.31 %
Branches
100 %
//! Running a compiled unit (plan 0014 PERSIST): a unit that never reaches its
//! call puts back every slot it wrote.
use std::sync::Arc;
use nomiscript::{Value, WasmType};
use scripting::runtime::{
EngineError, UnitEnd, carry_globals, carry_not_run, decode_eval_result, resolve_type_handles,
};
use wasmtime::{AnyRef, Func, Instance, Linker, Rooted, Store, Val};
use super::failure::runtime_failure;
use super::{EPOCH_DEADLINE_TICKS, EvalFailure, Session, SessionData};
use crate::envelope::RequestId;
/// Fuel between yields to the scheduler, so a running eval cannot hold its
/// Tokio worker and starve the tasks that read interrupts.
const YIELD_FUEL: u64 = 1_000_000;
impl Session {
/// Instantiates a compiled unit, unless an interrupt arrived during its
/// compile or link (the epoch bump only cancels a running call).
async fn start(
&mut self,
id: &RequestId,
bytes: &[u8],
) -> Result<(Store<SessionData>, Instance, Func), EvalFailure> {
let module = self
.cache
.get_or_compile(&self.engine, bytes)
.map_err(|err| EvalFailure::Engine(id.clone(), err))?;
let mut linker: Linker<SessionData> = Linker::new(&self.engine);
crate::natives::link(&mut linker).map_err(|err| {
EvalFailure::Engine(id.clone(), EngineError::Instantiate(err.to_string()))
})?;
let mut store: Store<SessionData> = Store::new(
&self.engine,
SessionData::new(self.ctx.clone(), Arc::clone(&self.output))
.with_notices(Arc::clone(&self.notices)),
);
store
.set_fuel(self.ctx.limits.fuel)
.map_err(|err| EvalFailure::Engine(id.clone(), EngineError::Fuel(err.to_string())))?;
store.set_epoch_deadline(EPOCH_DEADLINE_TICKS);
.fuel_async_yield_interval(Some(YIELD_FUEL))
let instance = linker
.instantiate_async(&mut store, &module)
.await
.map_err(|err| runtime_failure(id, &err))?;
let func = instance.get_func(&mut store, "nomi-eval").ok_or_else(|| {
EvalFailure::Engine(id.clone(), EngineError::MissingExport("nomi-eval".into()))
match self.check_interrupt(id) {
Some(err) => Err(err),
None => Ok((store, instance, func)),
}
/// Runs a compiled unit; one that never reaches its call puts back every
/// slot it wrote.
pub(super) async fn run_compiled(
(bytes, result_ty): (Vec<u8>, Option<WasmType>),
) -> Result<Value, EvalFailure> {
let (mut store, instance, func) = match self.start(id, &bytes).await {
Ok(started) => started,
Err(err) => {
carry_not_run(&mut self.symbols);
return Err(err);
let mut results = [Val::AnyRef(None)];
let call_result = func.call_async(&mut store, &[], &mut results).await;
// The reader bumps the epoch AND signals the interrupt together on
// `(:emacs-interrupt)`. If a C-g arrived during THIS call it cancelled it
// (epoch trap → `call_result` is `Err`); attribute it to this request so
// it can't also abort the next one. We ack only on the error path, so a
// C-g just after a clean success stays pending for the next form. This
// covers every terminal exit uniformly (epoch cancel, the
// out-of-fuel/runtime-trap-wins-the-race case) with no per-exit cleanup.
//
// Attribution cutoff (deliberate): the ack snapshot is taken AFTER the
// call returns, so a C-g landing in the sub-µs window between the call
// returning `Err` and this load is attributed to THIS (failing) form,
// not the next one. That is correct REPL semantics — at that instant the
// failing form is still the in-flight request (its error hasn't reached
// the client), so the user can't yet have meant the C-g for a later
// form. A C-g pressed after the error is surfaced necessarily arrives
// after `run` returns, advancing the generation again, and the next
// form's pre-start `check_interrupt` catches it. The exact instant of
// call return is unobservable, so this boundary is irreducible, not a
// lost interrupt.
if call_result.is_err() {
let observed = self.interrupt.generation();
self.ack_interrupt(observed);
let end = call_result
.as_ref()
.err()
.map_or(UnitEnd::Returned, UnitEnd::of_failure);
carry_globals(&mut store, &instance, &mut self.symbols, end);
call_result.map_err(|err| runtime_failure(id, &err))?;
let any: Option<Rooted<AnyRef>> = match &results[0] {
Val::AnyRef(a) => *a,
_ => {
return Err(EvalFailure::Engine(
id.clone(),
EngineError::Trap("nomi-eval did not return anyref".into()),
));
let handles = resolve_type_handles(&mut store, &instance).map_err(|err| {
EvalFailure::Engine(
EngineError::Trap(format!("resolving anyref type handles: {err}")),
)
let captured = decode_eval_result(&mut store, any, result_ty, &handles).map_err(|err| {
EngineError::Trap(format!("decoding nomi-eval result: {err}")),
Ok(Value::from(captured))