Skip to main content

rpc/
ctx.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicU64, Ordering};
3
4use uuid::Uuid;
5use wasmtime::Engine;
6
7use crate::lookup_log::{LookupKind, LookupLog};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct ScriptLimits {
11    pub fuel: u64,
12    pub max_memory_pages: u64,
13}
14
15impl Default for ScriptLimits {
16    fn default() -> Self {
17        Self {
18            fuel: 1_000_000,
19            max_memory_pages: 64,
20        }
21    }
22}
23
24#[derive(Debug, Clone)]
25pub struct ScriptCtx {
26    pub user_id: Uuid,
27    pub limits: ScriptLimits,
28    lookups: Option<LookupLog>,
29}
30
31impl ScriptCtx {
32    #[must_use]
33    pub fn new(user_id: Uuid) -> Self {
34        Self {
35            user_id,
36            limits: ScriptLimits::default(),
37            lookups: None,
38        }
39    }
40
41    #[must_use]
42    pub fn with_limits(mut self, limits: ScriptLimits) -> Self {
43        self.limits = limits;
44        self
45    }
46
47    /// Records every `get-account` / `get-commodity` argument into `log`.
48    #[must_use]
49    pub fn with_lookup_log(mut self, log: LookupLog) -> Self {
50        self.lookups = Some(log);
51        self
52    }
53
54    pub(crate) fn record_lookup(&self, kind: LookupKind, key: &str) {
55        if let Some(log) = &self.lookups {
56            log.record(kind, key);
57        }
58    }
59}
60
61/// Cooperative interrupt signal shared between the SLYNK reader task (which
62/// `interrupt()`s on `(:emacs-interrupt)`) and the eval task. Backed by a
63/// monotonic generation counter rather than a boolean latch: an interrupt
64/// increments the count. The session compares it with its ack watermark
65/// (the highest generation already charged to a request); a higher count
66/// interrupts the request that sees it, and acking it charges it there.
67///
68/// The generation design is deliberate (a prior boolean latch was racy): no
69/// flag is left set. An interrupt is charged to exactly one request, so once
70/// acked it never reaches a later one. An interrupt sent while nothing runs is
71/// charged to the next request (design rule 4).
72#[derive(Debug, Clone, Default)]
73pub struct InterruptHandle {
74    generation: Arc<AtomicU64>,
75}
76
77impl InterruptHandle {
78    pub(crate) fn new() -> Self {
79        Self::default()
80    }
81
82    /// Signals an interrupt by advancing the generation. Idempotent in effect:
83    /// any request whose baseline predates this call observes the interrupt.
84    pub fn interrupt(&self) {
85        self.generation.fetch_add(1, Ordering::SeqCst);
86    }
87
88    /// The current interrupt generation. The eval task keeps an "ack"
89    /// watermark of the highest generation already attributed to a finished
90    /// request; a new interrupt is one whose generation exceeds that watermark.
91    pub(crate) fn generation(&self) -> u64 {
92        self.generation.load(Ordering::SeqCst)
93    }
94}
95
96/// Cooperative cancel handle for an in-flight eval. Wraps a clone of
97/// the Session's [`wasmtime::Engine`]; the engine's epoch counter is
98/// shared internally so a `.bump()` from any task takes effect on the
99/// concurrent `func.call_async` running against the same engine.
100///
101/// Each Session sets `store.set_epoch_deadline(1)` before invoking
102/// `nomi-eval`, so one bump trips the deadline and the eval traps
103/// with `wasmtime::Trap::Interrupt` — surfaced upstream as
104/// `EngineError::EpochInterrupt` and on the wire as
105/// `(:error (:code interrupted ...))`.
106#[derive(Clone, Debug)]
107pub struct EpochBumper {
108    engine: Engine,
109}
110
111impl EpochBumper {
112    pub(crate) fn new(engine: Engine) -> Self {
113        Self { engine }
114    }
115
116    /// Increments the engine epoch. Returns immediately (no await).
117    /// Safe to call before, during, or after an eval; the next epoch
118    /// check inside any in-flight `call_async` traps.
119    pub fn bump(&self) {
120        self.engine.increment_epoch();
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn default_limits_are_non_zero() {
130        let limits = ScriptLimits::default();
131        assert!(limits.fuel > 0);
132        assert!(limits.max_memory_pages > 0);
133    }
134
135    #[test]
136    fn ctx_carries_user_id() {
137        let id = Uuid::new_v4();
138        let ctx = ScriptCtx::new(id);
139        assert_eq!(ctx.user_id, id);
140    }
141
142    #[test]
143    fn with_limits_overrides_default() {
144        let id = Uuid::new_v4();
145        let limits = ScriptLimits {
146            fuel: 42,
147            max_memory_pages: 7,
148        };
149        let ctx = ScriptCtx::new(id).with_limits(limits);
150        assert_eq!(ctx.limits, limits);
151    }
152
153    #[test]
154    fn interrupt_advances_generation_monotonically() {
155        let h = InterruptHandle::new();
156        let base = h.generation();
157        h.interrupt();
158        assert_eq!(h.generation(), base + 1);
159        h.interrupt();
160        assert_eq!(h.generation(), base + 2);
161    }
162
163    #[test]
164    fn interrupt_handle_clones_share_generation() {
165        let a = InterruptHandle::new();
166        let base = a.generation();
167        let b = a.clone();
168        b.interrupt();
169        assert!(a.generation() > base);
170    }
171}