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 #[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#[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 pub fn interrupt(&self) {
85 self.generation.fetch_add(1, Ordering::SeqCst);
86 }
87
88 pub(crate) fn generation(&self) -> u64 {
92 self.generation.load(Ordering::SeqCst)
93 }
94}
95
96#[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 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}