1
use std::sync::Arc;
2
use std::sync::atomic::{AtomicU64, Ordering};
3

            
4
use uuid::Uuid;
5
use wasmtime::Engine;
6

            
7
use crate::lookup_log::{LookupKind, LookupLog};
8

            
9
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10
pub struct ScriptLimits {
11
    pub fuel: u64,
12
    pub max_memory_pages: u64,
13
}
14

            
15
impl Default for ScriptLimits {
16
66424
    fn default() -> Self {
17
66424
        Self {
18
66424
            fuel: 1_000_000,
19
66424
            max_memory_pages: 64,
20
66424
        }
21
66424
    }
22
}
23

            
24
#[derive(Debug, Clone)]
25
pub struct ScriptCtx {
26
    pub user_id: Uuid,
27
    pub limits: ScriptLimits,
28
    lookups: Option<LookupLog>,
29
}
30

            
31
impl ScriptCtx {
32
    #[must_use]
33
63521
    pub fn new(user_id: Uuid) -> Self {
34
63521
        Self {
35
63521
            user_id,
36
63521
            limits: ScriptLimits::default(),
37
63521
            lookups: None,
38
63521
        }
39
63521
    }
40

            
41
    #[must_use]
42
3063
    pub fn with_limits(mut self, limits: ScriptLimits) -> Self {
43
3063
        self.limits = limits;
44
3063
        self
45
3063
    }
46

            
47
    /// Records every `get-account` / `get-commodity` argument into `log`.
48
    #[must_use]
49
6
    pub fn with_lookup_log(mut self, log: LookupLog) -> Self {
50
6
        self.lookups = Some(log);
51
6
        self
52
6
    }
53

            
54
29227
    pub(crate) fn record_lookup(&self, kind: LookupKind, key: &str) {
55
29227
        if let Some(log) = &self.lookups {
56
10
            log.record(kind, key);
57
29217
        }
58
29227
    }
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)]
73
pub struct InterruptHandle {
74
    generation: Arc<AtomicU64>,
75
}
76

            
77
impl InterruptHandle {
78
60154
    pub(crate) fn new() -> Self {
79
60154
        Self::default()
80
60154
    }
81

            
82
    /// Signals an interrupt by advancing the generation. Idempotent in effect:
83
    /// any request whose baseline predates this call observes the interrupt.
84
1624
    pub fn interrupt(&self) {
85
1624
        self.generation.fetch_add(1, Ordering::SeqCst);
86
1624
    }
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
474644
    pub(crate) fn generation(&self) -> u64 {
92
474644
        self.generation.load(Ordering::SeqCst)
93
474644
    }
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)]
107
pub struct EpochBumper {
108
    engine: Engine,
109
}
110

            
111
impl EpochBumper {
112
12403
    pub(crate) fn new(engine: Engine) -> Self {
113
12403
        Self { engine }
114
12403
    }
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
1625
    pub fn bump(&self) {
120
1625
        self.engine.increment_epoch();
121
1625
    }
122
}
123

            
124
#[cfg(test)]
125
mod tests {
126
    use super::*;
127

            
128
    #[test]
129
1
    fn default_limits_are_non_zero() {
130
1
        let limits = ScriptLimits::default();
131
1
        assert!(limits.fuel > 0);
132
1
        assert!(limits.max_memory_pages > 0);
133
1
    }
134

            
135
    #[test]
136
1
    fn ctx_carries_user_id() {
137
1
        let id = Uuid::new_v4();
138
1
        let ctx = ScriptCtx::new(id);
139
1
        assert_eq!(ctx.user_id, id);
140
1
    }
141

            
142
    #[test]
143
1
    fn with_limits_overrides_default() {
144
1
        let id = Uuid::new_v4();
145
1
        let limits = ScriptLimits {
146
1
            fuel: 42,
147
1
            max_memory_pages: 7,
148
1
        };
149
1
        let ctx = ScriptCtx::new(id).with_limits(limits);
150
1
        assert_eq!(ctx.limits, limits);
151
1
    }
152

            
153
    #[test]
154
1
    fn interrupt_advances_generation_monotonically() {
155
1
        let h = InterruptHandle::new();
156
1
        let base = h.generation();
157
1
        h.interrupt();
158
1
        assert_eq!(h.generation(), base + 1);
159
1
        h.interrupt();
160
1
        assert_eq!(h.generation(), base + 2);
161
1
    }
162

            
163
    #[test]
164
1
    fn interrupt_handle_clones_share_generation() {
165
1
        let a = InterruptHandle::new();
166
1
        let base = a.generation();
167
1
        let b = a.clone();
168
1
        b.interrupt();
169
1
        assert!(a.generation() > base);
170
1
    }
171
}