numcodecs_wasm_host_reproducible/
codec.rs1use std::num::Wrapping;
2use std::sync::{Arc, Mutex};
3
4use numcodecs::{
5 AnyArray, AnyArrayView, AnyArrayViewMut, AnyCowArray, Codec, DynCodec, DynCodecType,
6};
7use numcodecs_registry::{EmptyRegistry, Registry};
8use numcodecs_wasm_host::{CodecError, RuntimeError, WasmCodec, WasmCodecComponent};
9use schemars::Schema;
10use serde::Serializer;
11use wasm_component_layer::{AsContextMut, Component, Instance, Linker, Store, TypedFunc};
12use wasm_runtime_layer::{Engine, backend::WasmEngine};
13
14use crate::transform::instcnt::PerfWitInterfaces;
15use crate::transform::transform_wasm_component;
16use crate::{engine::ReproducibleEngine, logging, stdio};
17
18#[derive(Debug, thiserror::Error)]
19pub enum ReproducibleWasmCodecError {
21 #[error("{codec_id} codec's lock was poisoned")]
23 Poisoned {
24 codec_id: Arc<str>,
26 },
27 #[error("{codec_id} codec's WebAssembly runtime raised an error")]
29 Runtime {
30 codec_id: Arc<str>,
32 source: RuntimeError,
34 },
35 #[error("{codec_id} codec's implementation raised an error")]
37 Codec {
38 codec_id: Arc<str>,
40 source: CodecError,
42 },
43}
44
45pub struct ReproducibleWasmCodec<E: WasmEngine>
51where
52 Store<(), ReproducibleEngine<E>>: Send,
53{
54 store: Mutex<Store<(), ReproducibleEngine<E>>>,
55 instance: Instance,
56 codec: WasmCodec,
57 ty: ReproducibleWasmCodecType<E>,
58 instruction_counter: TypedFunc<(), u64>,
59}
60
61impl<E: WasmEngine> ReproducibleWasmCodec<E>
62where
63 Store<(), ReproducibleEngine<E>>: Send,
64{
65 pub fn try_clone(&self) -> Result<Self, serde_json::Error> {
75 let mut config = self.get_config(serde_json::value::Serializer)?;
76
77 if let Some(config) = config.as_object_mut() {
78 config.remove("id");
79 }
80
81 let codec: Self = self.ty.codec_from_config(config)?;
82
83 Ok(codec)
84 }
85
86 pub fn try_drop(mut self) -> Result<(), ReproducibleWasmCodecError> {
97 let store = self
99 .store
100 .get_mut()
101 .map_err(|_| ReproducibleWasmCodecError::Poisoned {
102 codec_id: self.ty.codec_id.clone(),
103 })?;
104
105 let result = self.codec.try_drop(&mut *store).map_err(|source| {
106 ReproducibleWasmCodecError::Runtime {
107 codec_id: self.ty.codec_id.clone(),
108 source,
109 }
110 });
111 let results = try_drop_instance(store, &self.instance, &self.ty.codec_id);
112
113 result.and(results)
114 }
115
116 #[expect(clippy::significant_drop_tightening)]
117 pub fn instruction_counter(&self) -> Result<Wrapping<u64>, ReproducibleWasmCodecError> {
128 let mut store = self
129 .store
130 .lock()
131 .map_err(|_| ReproducibleWasmCodecError::Poisoned {
132 codec_id: self.ty.codec_id.clone(),
133 })?;
134
135 let cnt = self
136 .instruction_counter
137 .call(store.as_context_mut(), ())
138 .map_err(|err| ReproducibleWasmCodecError::Runtime {
139 codec_id: self.ty.codec_id.clone(),
140 source: RuntimeError::from(err),
141 })?;
142
143 Ok(Wrapping(cnt))
144 }
145}
146
147impl<E: WasmEngine> Clone for ReproducibleWasmCodec<E>
148where
149 Store<(), ReproducibleEngine<E>>: Send,
150{
151 fn clone(&self) -> Self {
152 #[expect(clippy::expect_used)]
153 self.try_clone()
154 .expect("cloning a wasm codec should not fail")
155 }
156}
157
158impl<E: WasmEngine> Drop for ReproducibleWasmCodec<E>
159where
160 Store<(), ReproducibleEngine<E>>: Send,
161{
162 fn drop(&mut self) {
163 let Ok(store) = self.store.get_mut() else {
165 return;
166 };
167
168 let result = self.codec.try_drop(&mut *store);
169 std::mem::drop(result);
170
171 let results = self.instance.drop(store);
172 std::mem::drop(results);
173 }
174}
175
176impl<E: WasmEngine> Codec for ReproducibleWasmCodec<E>
177where
178 Store<(), ReproducibleEngine<E>>: Send,
179{
180 type Error = ReproducibleWasmCodecError;
181
182 #[expect(clippy::significant_drop_tightening)]
183 fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
184 let mut store = self
185 .store
186 .lock()
187 .map_err(|_| ReproducibleWasmCodecError::Poisoned {
188 codec_id: self.ty.codec_id.clone(),
189 })?;
190
191 let encoded = self
192 .codec
193 .encode(store.as_context_mut(), data)
194 .map_err(|err| ReproducibleWasmCodecError::Runtime {
195 codec_id: self.ty.codec_id.clone(),
196 source: err,
197 })?
198 .map_err(|err| ReproducibleWasmCodecError::Codec {
199 codec_id: self.ty.codec_id.clone(),
200 source: err,
201 })?;
202
203 Ok(encoded)
204 }
205
206 #[expect(clippy::significant_drop_tightening)]
207 fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
208 let mut store = self
209 .store
210 .lock()
211 .map_err(|_| ReproducibleWasmCodecError::Poisoned {
212 codec_id: self.ty.codec_id.clone(),
213 })?;
214
215 let decoded = self
216 .codec
217 .decode(store.as_context_mut(), encoded)
218 .map_err(|err| ReproducibleWasmCodecError::Runtime {
219 codec_id: self.ty.codec_id.clone(),
220 source: err,
221 })?
222 .map_err(|err| ReproducibleWasmCodecError::Codec {
223 codec_id: self.ty.codec_id.clone(),
224 source: err,
225 })?;
226
227 Ok(decoded)
228 }
229
230 #[expect(clippy::significant_drop_tightening)]
231 fn decode_into(
232 &self,
233 encoded: AnyArrayView,
234 decoded: AnyArrayViewMut,
235 ) -> Result<(), Self::Error> {
236 let mut store = self
237 .store
238 .lock()
239 .map_err(|_| ReproducibleWasmCodecError::Poisoned {
240 codec_id: self.ty.codec_id.clone(),
241 })?;
242
243 self.codec
244 .decode_into(store.as_context_mut(), encoded, decoded)
245 .map_err(|err| ReproducibleWasmCodecError::Runtime {
246 codec_id: self.ty.codec_id.clone(),
247 source: err,
248 })?
249 .map_err(|err| ReproducibleWasmCodecError::Codec {
250 codec_id: self.ty.codec_id.clone(),
251 source: err,
252 })?;
253
254 Ok(())
255 }
256}
257
258impl<E: WasmEngine> DynCodec for ReproducibleWasmCodec<E>
259where
260 Store<(), ReproducibleEngine<E>>: Send,
261{
262 type Type = ReproducibleWasmCodecType<E>;
263
264 fn ty(&self) -> Self::Type {
265 ReproducibleWasmCodecType {
266 codec_id: self.ty.codec_id.clone(),
267 codec_config_schema: self.ty.codec_config_schema.clone(),
268 component: self.ty.component.clone(),
269 component_instantiater: self.ty.component_instantiater.clone(),
270 }
271 }
272
273 fn get_config<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
274 let mut store = self
275 .store
276 .lock()
277 .map_err(|_| ReproducibleWasmCodecError::Poisoned {
278 codec_id: self.ty.codec_id.clone(),
279 })
280 .map_err(serde::ser::Error::custom)?;
281
282 self.codec.get_config(store.as_context_mut(), serializer)
283 }
284}
285
286pub struct ReproducibleWasmCodecType<E: WasmEngine>
288where
289 Store<(), ReproducibleEngine<E>>: Send,
290{
291 pub(super) codec_id: Arc<str>,
292 pub(super) codec_config_schema: Arc<Schema>,
293 pub(super) component: Component,
294 #[expect(clippy::type_complexity)]
295 pub(super) component_instantiater: Arc<
296 dyn Send
297 + Sync
298 + Fn(
299 &Component,
300 &str,
301 ) -> Result<
302 (
303 Store<(), ReproducibleEngine<E>>,
304 Instance,
305 WasmCodecComponent,
306 ),
307 ReproducibleWasmCodecError,
308 >,
309 >,
310}
311
312impl<E: WasmEngine> ReproducibleWasmCodecType<E>
313where
314 Store<(), ReproducibleEngine<E>>: Send,
315{
316 pub fn new(
324 engine: E,
325 wasm_component: impl Into<Vec<u8>>,
326 ) -> Result<Self, ReproducibleWasmCodecError>
327 where
328 E: Send + Sync,
329 Store<(), ReproducibleEngine<E>>: Send + Sync,
330 {
331 Self::new_with_registry(engine, wasm_component, EmptyRegistry)
332 }
333
334 pub fn new_with_registry(
343 engine: E,
344 wasm_component: impl Into<Vec<u8>>,
345 registry: impl Registry,
346 ) -> Result<Self, ReproducibleWasmCodecError>
347 where
348 E: Send + Sync,
349 Store<(), ReproducibleEngine<E>>: Send + Sync,
350 {
351 let wasm_component = transform_wasm_component(wasm_component).map_err(|err| {
352 ReproducibleWasmCodecError::Runtime {
353 codec_id: Arc::from("<unknown>"),
354 source: RuntimeError::from(err),
355 }
356 })?;
357
358 let engine = Engine::new(ReproducibleEngine::new(engine));
359 let component = Component::new(&engine, &wasm_component).map_err(|err| {
360 ReproducibleWasmCodecError::Runtime {
361 codec_id: Arc::from("<unknown>"),
362 source: RuntimeError::from(err),
363 }
364 })?;
365
366 let registry = Arc::new(registry);
367
368 let component_instantiater = Arc::new(move |component: &Component, codec_id: &str| {
369 let mut store = Store::new(&engine, ());
370
371 let mut linker = Linker::default();
372 stdio::add_to_linker(&mut linker, &mut store).map_err(|err| {
373 ReproducibleWasmCodecError::Runtime {
374 codec_id: Arc::from(codec_id),
375 source: RuntimeError::from(err),
376 }
377 })?;
378 logging::add_to_linker(&mut linker, &mut store).map_err(|err| {
379 ReproducibleWasmCodecError::Runtime {
380 codec_id: Arc::from(codec_id),
381 source: RuntimeError::from(err),
382 }
383 })?;
384 numcodecs_wasm_host::add_registry_to_linker(&mut linker, &mut store, registry.clone())
385 .map_err(|err| ReproducibleWasmCodecError::Runtime {
386 codec_id: Arc::from(codec_id),
387 source: RuntimeError::from(err),
388 })?;
389
390 let instance = linker.instantiate(&mut store, component).map_err(|err| {
391 ReproducibleWasmCodecError::Runtime {
392 codec_id: Arc::from(codec_id),
393 source: RuntimeError::from(err),
394 }
395 })?;
396
397 let component =
398 WasmCodecComponent::new(&mut store, instance.clone()).map_err(|source| {
399 ReproducibleWasmCodecError::Runtime {
400 codec_id: Arc::from(codec_id),
401 source,
402 }
403 })?;
404
405 Ok((store, instance, component))
406 });
407
408 let (codec_id, codec_config_schema) = {
409 let (mut store, instance, ty): (_, _, WasmCodecComponent) =
410 (component_instantiater)(&component, "<unknown>")?;
411
412 let codec_id = Arc::from(ty.codec_id());
413 let codec_config_schema = Arc::from(ty.codec_config_schema().clone());
414
415 try_drop_instance(&mut store, &instance, &codec_id)?;
416
417 (codec_id, codec_config_schema)
418 };
419
420 Ok(Self {
421 codec_id,
422 codec_config_schema,
423 component,
424 component_instantiater,
425 })
426 }
427}
428
429impl<E: WasmEngine> DynCodecType for ReproducibleWasmCodecType<E>
430where
431 Store<(), ReproducibleEngine<E>>: Send,
432{
433 type Codec = ReproducibleWasmCodec<E>;
434
435 fn codec_id(&self) -> &str {
436 &self.codec_id
437 }
438
439 fn codec_from_config<'de, D: serde::Deserializer<'de>>(
440 &self,
441 config: D,
442 ) -> Result<Self::Codec, D::Error> {
443 let (mut store, instance, component) =
444 (self.component_instantiater)(&self.component, &self.codec_id)
445 .map_err(serde::de::Error::custom)?;
446 let codec = component.codec_from_config(store.as_context_mut(), config)?;
447
448 let PerfWitInterfaces {
449 perf: perf_interface,
450 instruction_counter,
451 } = PerfWitInterfaces::get();
452 let Some(perf_interface) = instance.exports().instance(perf_interface) else {
453 return Err(serde::de::Error::custom(
454 "WASM component does not contain an interface to read the instruction counter",
455 ));
456 };
457 let Some(instruction_counter) = perf_interface.func(instruction_counter) else {
458 return Err(serde::de::Error::custom(
459 "WASM component interface does not contain a function to read the instruction counter",
460 ));
461 };
462 let instruction_counter = instruction_counter.typed().map_err(|err| {
463 serde::de::Error::custom(format!(
464 "WASM component instruction counter function has the wrong signature: {err}"
465 ))
466 })?;
467
468 Ok(ReproducibleWasmCodec {
469 store: Mutex::new(store),
470 instance,
471 codec,
472 ty: Self {
473 codec_id: self.codec_id.clone(),
474 codec_config_schema: self.codec_config_schema.clone(),
475 component: self.component.clone(),
476 component_instantiater: self.component_instantiater.clone(),
477 },
478 instruction_counter,
479 })
480 }
481
482 fn codec_config_schema(&self) -> Schema {
483 (*self.codec_config_schema).clone()
484 }
485}
486
487fn try_drop_instance<T, E: WasmEngine>(
488 store: &mut Store<T, E>,
489 instance: &Instance,
490 codec_id: &str,
491) -> Result<(), ReproducibleWasmCodecError> {
492 let mut errors = instance
493 .drop(store)
494 .map_err(|err| ReproducibleWasmCodecError::Runtime {
495 codec_id: Arc::from(codec_id),
496 source: RuntimeError::from(err),
497 })?;
498
499 let Some(mut err) = errors.pop() else {
500 return Ok(());
501 };
502
503 if !errors.is_empty() {
504 err = err.context(format!("showing one of {} errors", errors.len() + 1));
505 }
506
507 Err(ReproducibleWasmCodecError::Runtime {
508 codec_id: Arc::from(codec_id),
509 source: RuntimeError::from(
510 err.context("dropping instance and all of its resources failed"),
511 ),
512 })
513}