1use std::fmt;
8
9use graphrt_core::node::NodeContext;
10use graphrt_core::value::Value;
11
12use wasmi::{
13 Caller, Config, EnforcedLimits, Engine, Extern, Linker, Module, Store, StoreLimits, StoreLimitsBuilder, TrapCode,
14};
15
16use crate::abi::{ABI_VERSION, HOST_MODULE, unpack};
17use crate::error::WasmError;
18use crate::limits::WasmLimits;
19
20#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct LogLine {
23 pub level: u8,
24 pub message: String,
25}
26
27pub(crate) struct HostState {
29 limits: StoreLimits,
30 ctx: Option<NodeContext>,
31 message_bytes: usize,
32 max_logs: usize,
33 logs: Vec<LogLine>,
34 dropped_logs: usize,
35 max_events: usize,
36 events: usize,
37 max_stream_bytes: usize,
38 stream_bytes: usize,
39}
40
41pub(crate) const HOST_CALL_FUEL: u64 = 1_000;
45
46#[derive(Debug)]
48struct HostTrap(WasmError);
49
50impl fmt::Display for HostTrap {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 self.0.fmt(f)
53 }
54}
55
56impl wasmi::errors::HostError for HostTrap {}
57
58pub(crate) enum Call<'a> {
60 Describe,
61 Run(&'a [u8]),
62}
63
64pub(crate) struct CallOutput {
66 pub bytes: Vec<u8>,
67 pub logs: Vec<LogLine>,
68 pub dropped_logs: usize,
69}
70
71pub(crate) struct Compiled {
73 engine: Engine,
74 module: Module,
75 linker: Linker<HostState>,
76 limits: WasmLimits,
77}
78
79impl fmt::Debug for Compiled {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.debug_struct("Compiled").field("limits", &self.limits).finish_non_exhaustive()
82 }
83}
84
85impl Compiled {
86 pub(crate) fn new(bytes: &[u8], limits: WasmLimits) -> Result<Self, WasmError> {
88 if bytes.len() > limits.module_bytes {
89 return Err(WasmError::ModuleTooLarge { size: bytes.len(), limit: limits.module_bytes });
90 }
91 let mut config = Config::default();
92 config
93 .consume_fuel(true)
94 .enforced_limits(EnforcedLimits::strict())
95 .set_max_recursion_depth(limits.max_recursion_depth);
96 let engine = Engine::new(&config);
97 let module = Module::new(&engine, bytes).map_err(|e| WasmError::InvalidModule(e.to_string()))?;
98 for import in module.imports() {
99 if import.module() != HOST_MODULE || !matches!(import.name(), "log" | "chunk" | "progress") {
100 return Err(WasmError::InvalidModule(format!(
101 "unsupported import `{}::{}` (only `{HOST_MODULE}::log|chunk|progress` are provided)",
102 import.module(),
103 import.name()
104 )));
105 }
106 }
107 let linker = build_linker(&engine)?;
108 Ok(Self { engine, module, linker, limits })
109 }
110
111 pub(crate) fn limits(&self) -> &WasmLimits {
112 &self.limits
113 }
114
115 pub(crate) fn call(&self, call: Call<'_>, ctx: Option<NodeContext>) -> Result<CallOutput, WasmError> {
117 self.call_logged(call, ctx).map_err(|f| f.error)
118 }
119
120 pub(crate) fn call_logged(&self, call: Call<'_>, ctx: Option<NodeContext>) -> Result<CallOutput, CallFailure> {
123 let mut store = self.new_store(ctx).map_err(|error| CallFailure { error, logs: Vec::new() })?;
124 match self.call_in(&mut store, call) {
125 Ok(bytes) => {
126 let state = store.into_data();
127 Ok(CallOutput { bytes, logs: state.logs, dropped_logs: state.dropped_logs })
128 }
129 Err(error) => Err(CallFailure { error, logs: store.into_data().logs }),
130 }
131 }
132
133 fn new_store(&self, ctx: Option<NodeContext>) -> Result<Store<HostState>, WasmError> {
134 let limits = &self.limits;
135 let state = HostState {
136 limits: StoreLimitsBuilder::new()
137 .memory_size(limits.memory_bytes)
138 .memories(1)
139 .tables(8)
140 .table_elements(1_000_000)
141 .instances(1)
142 .trap_on_grow_failure(true)
143 .build(),
144 ctx,
145 message_bytes: limits.message_bytes,
146 max_logs: limits.max_logs,
147 logs: Vec::new(),
148 dropped_logs: 0,
149 max_events: limits.max_events,
150 events: 0,
151 max_stream_bytes: limits.max_stream_bytes,
152 stream_bytes: 0,
153 };
154 let mut store = Store::new(&self.engine, state);
155 store.limiter(|s| &mut s.limits);
156 store.set_fuel(limits.fuel).map_err(|e| WasmError::Internal(e.to_string()))?;
157 Ok(store)
158 }
159
160 fn call_in(&self, store: &mut Store<HostState>, call: Call<'_>) -> Result<Vec<u8>, WasmError> {
162 let limits = &self.limits;
163 let mut store = store;
164 let instance = self.linker.instantiate_and_start(&mut store, &self.module).map_err(|e| match map_trap(&e) {
165 Some(err) => err,
166 None => WasmError::Instantiate(e.to_string()),
167 })?;
168
169 let version = instance
170 .get_typed_func::<(), i32>(&store, "graphrt_abi_version")
171 .map_err(|_| WasmError::MissingExport("graphrt_abi_version: () -> i32".into()))?
172 .call(&mut store, ())
173 .map_err(|e| call_error(&e))?;
174 if version != ABI_VERSION {
175 return Err(WasmError::AbiVersion { found: version, supported: ABI_VERSION });
176 }
177 let memory = instance.get_memory(&store, "memory").ok_or_else(|| WasmError::MissingExport("memory".into()))?;
178
179 let packed = match call {
180 Call::Describe => instance
181 .get_typed_func::<(), i64>(&store, "graphrt_describe")
182 .map_err(|_| WasmError::MissingExport("graphrt_describe: () -> i64".into()))?
183 .call(&mut store, ())
184 .map_err(|e| call_error(&e))?,
185 Call::Run(input) => {
186 if input.len() > limits.input_bytes {
187 return Err(WasmError::TooLarge { what: "request", size: input.len(), limit: limits.input_bytes });
188 }
189 let len = i32::try_from(input.len()).map_err(|_| WasmError::TooLarge {
190 what: "request",
191 size: input.len(),
192 limit: limits.input_bytes,
193 })?;
194 let ptr = instance
195 .get_typed_func::<i32, i32>(&store, "graphrt_alloc")
196 .map_err(|_| WasmError::MissingExport("graphrt_alloc: (i32) -> i32".into()))?
197 .call(&mut store, len)
198 .map_err(|e| call_error(&e))?;
199 let offset = usize::try_from(as_u32(ptr)).map_err(|e| WasmError::Internal(e.to_string()))?;
200 memory
201 .write(&mut store, offset, input)
202 .map_err(|_| WasmError::OutOfBounds { ptr: as_u32(ptr), len: as_u32(len) })?;
203 instance
204 .get_typed_func::<(i32, i32), i64>(&store, "graphrt_run")
205 .map_err(|_| WasmError::MissingExport("graphrt_run: (i32, i32) -> i64".into()))?
206 .call(&mut store, (ptr, len))
207 .map_err(|e| call_error(&e))?
208 }
209 };
210
211 let (ptr, len) = unpack(packed);
212 let len_usize = usize::try_from(len).map_err(|e| WasmError::Internal(e.to_string()))?;
213 if len_usize > limits.output_bytes {
214 return Err(WasmError::TooLarge { what: "response", size: len_usize, limit: limits.output_bytes });
215 }
216 let start = usize::try_from(ptr).map_err(|e| WasmError::Internal(e.to_string()))?;
217 let bytes = start
218 .checked_add(len_usize)
219 .and_then(|end| memory.data(&store).get(start..end))
220 .ok_or(WasmError::OutOfBounds { ptr, len })?
221 .to_vec();
222 Ok(bytes)
223 }
224}
225
226pub(crate) struct CallFailure {
228 pub error: WasmError,
229 pub logs: Vec<LogLine>,
230}
231
232fn as_u32(v: i32) -> u32 {
233 u32::from_ne_bytes(v.to_ne_bytes())
234}
235
236fn call_error(e: &wasmi::Error) -> WasmError {
238 map_trap(e).unwrap_or_else(|| WasmError::Trap(e.to_string()))
239}
240
241fn map_trap(e: &wasmi::Error) -> Option<WasmError> {
242 if let Some(HostTrap(inner)) = e.downcast_ref::<HostTrap>() {
243 return Some(inner.clone());
244 }
245 match e.as_trap_code()? {
246 TrapCode::OutOfFuel => Some(WasmError::FuelExhausted),
247 TrapCode::GrowthOperationLimited => Some(WasmError::MemoryLimit),
248 other => Some(WasmError::Trap(other.to_string())),
249 }
250}
251
252fn host_trap(err: WasmError) -> wasmi::Error {
253 wasmi::Error::host(HostTrap(err))
254}
255
256fn read_guest(caller: &Caller<'_, HostState>, ptr: i32, len: i32, what: &'static str) -> Result<Vec<u8>, wasmi::Error> {
258 let (ptr, len) = (as_u32(ptr), as_u32(len));
259 let limit = caller.data().message_bytes;
260 let size = usize::try_from(len).map_err(|e| host_trap(WasmError::Internal(e.to_string())))?;
261 if size > limit {
262 return Err(host_trap(WasmError::TooLarge { what, size, limit }));
263 }
264 let memory = caller
265 .get_export("memory")
266 .and_then(Extern::into_memory)
267 .ok_or_else(|| host_trap(WasmError::MissingExport("memory".into())))?;
268 let start = usize::try_from(ptr).map_err(|e| host_trap(WasmError::Internal(e.to_string())))?;
269 start
270 .checked_add(size)
271 .and_then(|end| memory.data(caller).get(start..end))
272 .map(<[u8]>::to_vec)
273 .ok_or_else(|| host_trap(WasmError::OutOfBounds { ptr, len }))
274}
275
276fn read_text(caller: &Caller<'_, HostState>, ptr: i32, len: i32, what: &'static str) -> Result<String, wasmi::Error> {
277 let bytes = read_guest(caller, ptr, len, what)?;
278 String::from_utf8(bytes).map_err(|_| host_trap(WasmError::InvalidOutput(format!("{what} is not valid UTF-8"))))
279}
280
281fn charge(caller: &mut Caller<'_, HostState>, bytes: u64) -> Result<(), wasmi::Error> {
283 let cost = HOST_CALL_FUEL.saturating_add(bytes);
284 let fuel = caller.get_fuel().map_err(|e| host_trap(WasmError::Internal(e.to_string())))?;
285 if fuel < cost {
286 return Err(host_trap(WasmError::FuelExhausted));
287 }
288 caller.set_fuel(fuel - cost).map_err(|e| host_trap(WasmError::Internal(e.to_string())))
289}
290
291fn reserve_event(caller: &mut Caller<'_, HostState>, bytes: u64) -> Result<(), wasmi::Error> {
293 let state = caller.data_mut();
294 if state.events >= state.max_events {
295 return Err(host_trap(WasmError::TooLarge {
296 what: "streamed events",
297 size: state.events.saturating_add(1),
298 limit: state.max_events,
299 }));
300 }
301 let total = state.stream_bytes.saturating_add(usize::try_from(bytes).unwrap_or(usize::MAX));
302 if total > state.max_stream_bytes {
303 return Err(host_trap(WasmError::TooLarge {
304 what: "streamed bytes",
305 size: total,
306 limit: state.max_stream_bytes,
307 }));
308 }
309 state.events += 1;
310 state.stream_bytes = total;
311 Ok(())
312}
313
314fn len_of(len: i32) -> u64 {
315 u64::from(as_u32(len))
316}
317
318fn build_linker(engine: &Engine) -> Result<Linker<HostState>, WasmError> {
319 let link_err = |e: wasmi::errors::LinkerError| WasmError::Internal(e.to_string());
320 let mut linker = Linker::<HostState>::new(engine);
321 linker
322 .func_wrap(HOST_MODULE, "log", |mut caller: Caller<'_, HostState>, level: i32, ptr: i32, len: i32| {
323 let full = {
325 let state = caller.data();
326 state.logs.len() >= state.max_logs
327 };
328 if full {
329 charge(&mut caller, 0)?;
330 let state = caller.data_mut();
331 state.dropped_logs = state.dropped_logs.saturating_add(1);
332 return Ok(());
333 }
334 charge(&mut caller, len_of(len))?;
335 let message = read_text(&caller, ptr, len, "log line")?;
336 let level = u8::try_from(level.clamp(0, 4)).unwrap_or(2);
337 caller.data_mut().logs.push(LogLine { level, message });
338 Ok(())
339 })
340 .map_err(link_err)?;
341 linker
342 .func_wrap(
343 HOST_MODULE,
344 "chunk",
345 |mut caller: Caller<'_, HostState>, field_ptr: i32, field_len: i32, ptr: i32, len: i32| {
346 let bytes = len_of(field_len).saturating_add(len_of(len));
347 charge(&mut caller, bytes)?;
348 reserve_event(&mut caller, bytes)?;
349 let field = read_text(&caller, field_ptr, field_len, "chunk field")?;
350 let text = read_text(&caller, ptr, len, "chunk")?;
351 if let Some(ctx) = &caller.data().ctx {
352 ctx.chunk(&field, text);
353 }
354 Ok(())
355 },
356 )
357 .map_err(link_err)?;
358 linker
359 .func_wrap(
360 HOST_MODULE,
361 "progress",
362 |mut caller: Caller<'_, HostState>, name_ptr: i32, name_len: i32, ptr: i32, len: i32| {
363 let bytes = len_of(name_len).saturating_add(len_of(len));
364 charge(&mut caller, bytes)?;
365 reserve_event(&mut caller, bytes)?;
366 let name = read_text(&caller, name_ptr, name_len, "progress name")?;
367 let payload = read_text(&caller, ptr, len, "progress payload")?;
368 let data = match serde_json::from_str::<serde_json::Value>(&payload) {
369 Ok(json) => Value::from_json(json),
370 Err(_) => Value::from(payload),
371 };
372 if let Some(ctx) = &caller.data().ctx {
373 ctx.progress(&name, data);
374 }
375 Ok(())
376 },
377 )
378 .map_err(link_err)?;
379 Ok(linker)
380}