numcodecs_wasm_host/
wit.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::sync::OnceLock;

use semver::Version;
use wasm_component_layer::{InterfaceIdentifier, PackageIdentifier, PackageName, Value};

use crate::error::{CodecError, RuntimeError};

/// WebAssembly Interface Type (WIT) interfaces for `numcodecs`
#[non_exhaustive]
pub struct NumcodecsWitInterfaces {
    /// The `numcodecs:abc/codec` interface
    pub codec: InterfaceIdentifier,
}

impl NumcodecsWitInterfaces {
    /// Get the once-computed interfaces
    #[must_use]
    pub fn get() -> &'static Self {
        static NUMCODECS_WIT_INTERFACES: OnceLock<NumcodecsWitInterfaces> = OnceLock::new();

        NUMCODECS_WIT_INTERFACES.get_or_init(|| Self {
            codec: InterfaceIdentifier::new(
                PackageIdentifier::new(
                    PackageName::new("numcodecs", "abc"),
                    Some(Version::new(0, 1, 1)),
                ),
                "codec",
            ),
        })
    }
}

pub fn guest_error_from_wasm(err: Option<&Value>) -> Result<CodecError, RuntimeError> {
    let Some(Value::Record(record)) = err else {
        return Err(RuntimeError::from(anyhow::anyhow!(
            "unexpected err value {err:?}"
        )));
    };

    let Some(Value::String(message)) = record.field("message") else {
        return Err(RuntimeError::from(anyhow::anyhow!(
            "numcodecs:abc/codec::error is missing the `message` field"
        )));
    };

    let Some(Value::List(chain)) = record.field("chain") else {
        return Err(RuntimeError::from(anyhow::anyhow!(
            "numcodecs:abc/codec::error is missing the `chain` field"
        )));
    };

    let Ok(chain) = chain
        .iter()
        .map(|msg| match msg {
            Value::String(msg) => Ok(msg),
            _ => Err(()),
        })
        .collect::<Result<Vec<_>, _>>()
    else {
        return Err(RuntimeError::from(anyhow::anyhow!(
            "numcodecs:abc/codec::error chain contains unexpected non-string values: {chain:?}"
        )));
    };

    Ok(CodecError::new(message, chain))
}