rpc/session/data.rs
1use std::cell::RefCell;
2use std::sync::{Arc, Mutex};
3
4use 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.
17pub 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
35impl SessionData {
36 pub(crate) fn new(ctx: ScriptCtx, output: Arc<Mutex<String>>) -> Self {
37 Self {
38 ctx,
39 output,
40 draft: None,
41 notices: Arc::default(),
42 }
43 }
44
45 /// Collect notices into `notices`, shared with the owning `Session`.
46 #[must_use]
47 pub(crate) fn with_notices(mut self, notices: Arc<Mutex<Vec<String>>>) -> Self {
48 self.notices = notices;
49 self
50 }
51
52 /// Adds a notice to the current request's reply. A poisoned lock drops it.
53 pub fn push_notice(&self, notice: String) {
54 if let Ok(mut notices) = self.notices.lock() {
55 notices.push(notice);
56 }
57 }
58
59 /// Builds session data with a draft accumulator armed — the render path's
60 /// constructor. Draft natives require `draft` to be `Some`.
61 pub(crate) fn for_render(ctx: ScriptCtx, output: Arc<Mutex<String>>) -> Self {
62 Self {
63 ctx,
64 output,
65 draft: Some(RefCell::new(crate::draft::TransactionDraft::new())),
66 notices: Arc::default(),
67 }
68 }
69
70 #[must_use]
71 pub fn ctx(&self) -> &ScriptCtx {
72 &self.ctx
73 }
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 pub fn with_draft<F>(&self, f: F) -> wasmtime::Result<()>
79 where
80 F: FnOnce(&mut crate::draft::TransactionDraft),
81 {
82 let cell = self
83 .draft
84 .as_ref()
85 .ok_or_else(|| wasmtime::Error::msg("draft native invoked outside render mode"))?;
86 f(&mut cell.borrow_mut());
87 Ok(())
88 }
89
90 /// Consumes the accumulated draft, if any. Called after a render run via
91 /// `store.into_data()`.
92 #[must_use]
93 pub fn into_draft(self) -> Option<crate::draft::TransactionDraft> {
94 self.draft.map(RefCell::into_inner)
95 }
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 pub fn push_output(&self, msg: &str) {
101 if let Ok(mut buf) = self.output.lock() {
102 buf.push_str(msg);
103 }
104 }
105}