1
//! Running a compiled unit (plan 0014 PERSIST): a unit that never reaches its
2
//! call puts back every slot it wrote.
3

            
4
use std::sync::Arc;
5

            
6
use nomiscript::{Value, WasmType};
7
use scripting::runtime::{
8
    EngineError, UnitEnd, carry_globals, carry_not_run, decode_eval_result, resolve_type_handles,
9
};
10
use wasmtime::{AnyRef, Func, Instance, Linker, Rooted, Store, Val};
11

            
12
use super::failure::runtime_failure;
13
use super::{EPOCH_DEADLINE_TICKS, EvalFailure, Session, SessionData};
14
use crate::envelope::RequestId;
15

            
16
/// Fuel between yields to the scheduler, so a running eval cannot hold its
17
/// Tokio worker and starve the tasks that read interrupts.
18
const YIELD_FUEL: u64 = 1_000_000;
19

            
20
impl Session {
21
    /// Instantiates a compiled unit, unless an interrupt arrived during its
22
    /// compile or link (the epoch bump only cancels a running call).
23
230198
    async fn start(
24
230198
        &mut self,
25
230198
        id: &RequestId,
26
230198
        bytes: &[u8],
27
230198
    ) -> Result<(Store<SessionData>, Instance, Func), EvalFailure> {
28
230198
        let module = self
29
230198
            .cache
30
230198
            .get_or_compile(&self.engine, bytes)
31
            .map_err(|err| EvalFailure::Engine(id.clone(), err))?;
32
230198
        let mut linker: Linker<SessionData> = Linker::new(&self.engine);
33
230198
        crate::natives::link(&mut linker).map_err(|err| {
34
            EvalFailure::Engine(id.clone(), EngineError::Instantiate(err.to_string()))
35
        })?;
36
230198
        let mut store: Store<SessionData> = Store::new(
37
230198
            &self.engine,
38
230198
            SessionData::new(self.ctx.clone(), Arc::clone(&self.output))
39
230198
                .with_notices(Arc::clone(&self.notices)),
40
230198
        );
41
230198
        store
42
230198
            .set_fuel(self.ctx.limits.fuel)
43
            .map_err(|err| EvalFailure::Engine(id.clone(), EngineError::Fuel(err.to_string())))?;
44
230198
        store.set_epoch_deadline(EPOCH_DEADLINE_TICKS);
45
230198
        store
46
230198
            .fuel_async_yield_interval(Some(YIELD_FUEL))
47
            .map_err(|err| EvalFailure::Engine(id.clone(), EngineError::Fuel(err.to_string())))?;
48
230198
        let instance = linker
49
230198
            .instantiate_async(&mut store, &module)
50
230198
            .await
51
            .map_err(|err| runtime_failure(id, &err))?;
52
230198
        let func = instance.get_func(&mut store, "nomi-eval").ok_or_else(|| {
53
            EvalFailure::Engine(id.clone(), EngineError::MissingExport("nomi-eval".into()))
54
        })?;
55
230198
        match self.check_interrupt(id) {
56
961
            Some(err) => Err(err),
57
229237
            None => Ok((store, instance, func)),
58
        }
59
230198
    }
60

            
61
    /// Runs a compiled unit; one that never reaches its call puts back every
62
    /// slot it wrote.
63
230198
    pub(super) async fn run_compiled(
64
230198
        &mut self,
65
230198
        id: &RequestId,
66
230198
        (bytes, result_ty): (Vec<u8>, Option<WasmType>),
67
230198
    ) -> Result<Value, EvalFailure> {
68
230198
        let (mut store, instance, func) = match self.start(id, &bytes).await {
69
229237
            Ok(started) => started,
70
            Err(err) => {
71
961
                carry_not_run(&mut self.symbols);
72
961
                return Err(err);
73
            }
74
        };
75
229237
        let mut results = [Val::AnyRef(None)];
76
229237
        let call_result = func.call_async(&mut store, &[], &mut results).await;
77
        // The reader bumps the epoch AND signals the interrupt together on
78
        // `(:emacs-interrupt)`. If a C-g arrived during THIS call it cancelled it
79
        // (epoch trap → `call_result` is `Err`); attribute it to this request so
80
        // it can't also abort the next one. We ack only on the error path, so a
81
        // C-g just after a clean success stays pending for the next form. This
82
        // covers every terminal exit uniformly (epoch cancel, the
83
        // out-of-fuel/runtime-trap-wins-the-race case) with no per-exit cleanup.
84
        //
85
        // Attribution cutoff (deliberate): the ack snapshot is taken AFTER the
86
        // call returns, so a C-g landing in the sub-µs window between the call
87
        // returning `Err` and this load is attributed to THIS (failing) form,
88
        // not the next one. That is correct REPL semantics — at that instant the
89
        // failing form is still the in-flight request (its error hasn't reached
90
        // the client), so the user can't yet have meant the C-g for a later
91
        // form. A C-g pressed after the error is surfaced necessarily arrives
92
        // after `run` returns, advancing the generation again, and the next
93
        // form's pre-start `check_interrupt` catches it. The exact instant of
94
        // call return is unobservable, so this boundary is irreducible, not a
95
        // lost interrupt.
96
228596
        if call_result.is_err() {
97
12273
            let observed = self.interrupt.generation();
98
12273
            self.ack_interrupt(observed);
99
216323
        }
100
228596
        let end = call_result
101
228596
            .as_ref()
102
228596
            .err()
103
228596
            .map_or(UnitEnd::Returned, UnitEnd::of_failure);
104
228596
        carry_globals(&mut store, &instance, &mut self.symbols, end);
105
228596
        call_result.map_err(|err| runtime_failure(id, &err))?;
106

            
107
216323
        let any: Option<Rooted<AnyRef>> = match &results[0] {
108
216323
            Val::AnyRef(a) => *a,
109
            _ => {
110
                return Err(EvalFailure::Engine(
111
                    id.clone(),
112
                    EngineError::Trap("nomi-eval did not return anyref".into()),
113
                ));
114
            }
115
        };
116
216323
        let handles = resolve_type_handles(&mut store, &instance).map_err(|err| {
117
            EvalFailure::Engine(
118
                id.clone(),
119
                EngineError::Trap(format!("resolving anyref type handles: {err}")),
120
            )
121
        })?;
122
216323
        let captured = decode_eval_result(&mut store, any, result_ty, &handles).map_err(|err| {
123
3
            EvalFailure::Engine(
124
3
                id.clone(),
125
3
                EngineError::Trap(format!("decoding nomi-eval result: {err}")),
126
3
            )
127
3
        })?;
128
216320
        Ok(Value::from(captured))
129
229557
    }
130
}