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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use serde::{Deserialize, Serialize};
use std::io::Cursor;

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DeployResult {
    pub valid: Result<String, String>,
    #[serde(default)]
    pub vols: Vec<ContainerVolume>,
    #[serde(default)]
    pub start_mode: StartMode,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ContainerVolume {
    pub name: String,
    pub path: String,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum StartMode {
    Empty,
    Blocking,
}

impl Default for StartMode {
    fn default() -> Self {
        StartMode::Empty
    }
}

impl DeployResult {
    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> anyhow::Result<DeployResult> {
        let b: &[u8] = bytes.as_ref();
        if b.is_empty() {
            log::warn!("empty descriptor");
            let vols = if cfg!(feature = "compat-deployment") {
                vec![ContainerVolume {
                    name: ".".to_string(),
                    path: "".to_string(),
                }]
            } else {
                Default::default()
            };

            return Ok(DeployResult {
                valid: Ok(Default::default()),
                vols,
                start_mode: Default::default(),
            });
        }
        if let Some(idx) = b.iter().position(|&ch| ch == b'{') {
            let b = &b[idx..];
            Ok(serde_json::from_reader(Cursor::new(b))?)
        } else {
            let text = String::from_utf8_lossy(b);
            anyhow::bail!("invalid deploy response: {}", text);
        }
    }
}

#[cfg(test)]
mod test {
    use super::DeployResult;

    fn parse_bytes<T: AsRef<[u8]>>(b: T) -> DeployResult {
        let result = DeployResult::from_bytes(b).unwrap();
        eprintln!("result={:?}", result);
        result
    }

    #[test]
    fn test_wasi_deploy() {
        parse_bytes(
            r#"{
            "valid": {"Ok": "success"}
        }"#,
        );
        parse_bytes(
            r#"{
            "valid": {"Err": "bad image format"}
        }"#,
        );
        parse_bytes(
            r#"{
            "valid": {"Ok": "success"},
            "vols": [
                {"name": "vol-9a0c1c4a", "path": "/in"},
                {"name": "vol-a68672e0", "path": "/out"}
            ]
        }"#,
        );
    }
}