1
use std::cell::RefCell;
2
use std::sync::{Arc, Mutex};
3

            
4
use crate::ctx::ScriptCtx;
5

            
6
/// Wasmtime Store data type for the rpc eval channel. Carries the
7
/// per-session user context (`ScriptCtx`) so native fns reach
8
/// `caller.data().ctx().user_id` directly. The legacy
9
/// `EvalContext` capture-protocol companion field retired alongside
10
/// the capture imports in P4 A6.c — `nomi-eval` now returns its
11
/// final value via the function's `(ref null any)` return slot.
12
///
13
/// Native fns are async (`Linker::func_wrap_async`) — they `.await`
14
/// `server::command::*` futures directly on whatever runtime drives the
15
/// surrounding `Session::handle_form` call. No owned runtime, no
16
/// `spawn_blocking`, no thread-local pool concerns.
17
pub struct SessionData {
18
    ctx: ScriptCtx,
19
    /// Per-request stdout sink. `env.log` (PRINT/DISPLAY/NEWLINE) appends here so
20
    /// the mREPL (`nms --slynk-port`) can surface script output as
21
    /// `:write-string` separately from the final value. Shared with the owning
22
    /// `Session`, which drains it per request. The non-mrepl paths (sshd / the
23
    /// rpc text REPL) ignore it; `env.log` still tees to `tracing` for them.
24
    output: Arc<Mutex<String>>,
25
    /// Render-only draft accumulator. `Some` only on the restricted template
26
    /// render path ([`crate::template`]); the draft natives mutate it and the
27
    /// render entry point reads it back via `store.into_data()`. `None` on the
28
    /// normal eval channel, where the draft natives are not even linked.
29
    draft: Option<RefCell<crate::draft::TransactionDraft>>,
30
    /// Per-request notices: warnings a native gives alongside success. The
31
    /// wire carries them as the response's `:notices`.
32
    notices: Arc<Mutex<Vec<String>>>,
33
}
34

            
35
impl SessionData {
36
230200
    pub(crate) fn new(ctx: ScriptCtx, output: Arc<Mutex<String>>) -> Self {
37
230200
        Self {
38
230200
            ctx,
39
230200
            output,
40
230200
            draft: None,
41
230200
            notices: Arc::default(),
42
230200
        }
43
230200
    }
44

            
45
    /// Collect notices into `notices`, shared with the owning `Session`.
46
    #[must_use]
47
230198
    pub(crate) fn with_notices(mut self, notices: Arc<Mutex<Vec<String>>>) -> Self {
48
230198
        self.notices = notices;
49
230198
        self
50
230198
    }
51

            
52
    /// Adds a notice to the current request's reply. A poisoned lock drops it.
53
1604
    pub fn push_notice(&self, notice: String) {
54
1604
        if let Ok(mut notices) = self.notices.lock() {
55
1604
            notices.push(notice);
56
        }
57
1604
    }
58

            
59
    /// Builds session data with a draft accumulator armed — the render path's
60
    /// constructor. Draft natives require `draft` to be `Some`.
61
6611
    pub(crate) fn for_render(ctx: ScriptCtx, output: Arc<Mutex<String>>) -> Self {
62
6611
        Self {
63
6611
            ctx,
64
6611
            output,
65
6611
            draft: Some(RefCell::new(crate::draft::TransactionDraft::new())),
66
6611
            notices: Arc::default(),
67
6611
        }
68
6611
    }
69

            
70
    #[must_use]
71
215727
    pub fn ctx(&self) -> &ScriptCtx {
72
215727
        &self.ctx
73
215727
    }
74

            
75
    /// Mutates the draft accumulator if armed (render path). Returns an error
76
    /// on the normal eval path where no draft is present — a draft native
77
    /// reaching a non-render Store is a wiring bug, surfaced as a trap.
78
29370
    pub fn with_draft<F>(&self, f: F) -> wasmtime::Result<()>
79
29370
    where
80
29370
        F: FnOnce(&mut crate::draft::TransactionDraft),
81
    {
82
29370
        let cell = self
83
29370
            .draft
84
29370
            .as_ref()
85
            .ok_or_else(|| wasmtime::Error::msg("draft native invoked outside render mode"))?;
86
29370
        f(&mut cell.borrow_mut());
87
29370
        Ok(())
88
29370
    }
89

            
90
    /// Consumes the accumulated draft, if any. Called after a render run via
91
    /// `store.into_data()`.
92
    #[must_use]
93
5784
    pub fn into_draft(self) -> Option<crate::draft::TransactionDraft> {
94
5784
        self.draft.map(RefCell::into_inner)
95
5784
    }
96

            
97
    /// Appends a script-output line to the per-request buffer. Called by the
98
    /// `env.log` host fn. A poisoned lock is swallowed (output capture is
99
    /// best-effort telemetry, never a reason to fail an eval).
100
93
    pub fn push_output(&self, msg: &str) {
101
93
        if let Ok(mut buf) = self.output.lock() {
102
93
            buf.push_str(msg);
103
        }
104
93
    }
105
}