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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use super::{
    locality::CapabilityLocalityV1, CapabilityCpuV1, CapabilityFileSystemV1, CapabilityLoggingV1,
    CapabilityMemorySwapV1, CapabilityMemoryV1, CapabilityNetworkDnsV1, CapabilityNetworkGatewayV1,
    CapabilityNetworkV1, CapabilityPersistentMemoryV1, CapabilityWasiV1, CapabilityWebGatewayV1,
    Merge,
};

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, schemars::JsonSchema)]
pub enum CapabilityV1 {
    #[serde(rename = "cpu")]
    Cpu(CapabilityCpuV1),
    #[serde(rename = "fs")]
    FileSystem(CapabilityFileSystemV1),
    #[serde(rename = "memory_swap")]
    MemorySwap(CapabilityMemorySwapV1),
    #[serde(rename = "memory_persistent")]
    MemoryPersistent(CapabilityPersistentMemoryV1),
    #[serde(rename = "network")]
    Network(CapabilityNetworkV1),
    #[serde(rename = "network_dns")]
    NetworkDns(CapabilityNetworkDnsV1),
    #[serde(rename = "network_gateway")]
    NetworkGateway(CapabilityNetworkGatewayV1),
}

#[derive(Serialize, Deserialize, Default, PartialEq, Eq, Clone, Debug, schemars::JsonSchema)]
pub struct CapabilityMapV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wasi: Option<CapabilityWasiV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpu: Option<CapabilityCpuV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fs: Option<CapabilityFileSystemV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory: Option<CapabilityMemoryV1>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<CapabilityNetworkV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_dns: Option<CapabilityNetworkDnsV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_gateway: Option<CapabilityNetworkGatewayV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logging: Option<CapabilityLoggingV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locality: Option<CapabilityLocalityV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web_gateway: Option<CapabilityWebGatewayV1>,

    /// Additional unknown capabilities.
    #[serde(flatten)]
    pub other: HashMap<String, serde_json::Value>,
}

impl Merge for CapabilityMapV1 {
    fn merge_extend(self, other: &Self) -> Self {
        Self {
            wasi: self.wasi.merge_extend(&other.wasi),
            cpu: self.cpu.merge_extend(&other.cpu),
            fs: self.fs.merge_extend(&other.fs),
            memory: self.memory.merge_extend(&other.memory),
            network: self.network.merge_extend(&other.network),
            network_dns: self.network_dns.merge_extend(&other.network_dns),
            network_gateway: self.network_gateway.merge_extend(&other.network_gateway),
            logging: self.logging.merge_extend(&other.logging),
            locality: self.locality.merge_extend(&other.locality),
            web_gateway: self.web_gateway.merge_extend(&other.web_gateway),
            other: self.other,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::schema::{FsVolumeConfig, VolumeMountV1, VolumeSourceShared, VolumeSourceV1};

    use super::*;

    #[test]
    fn test_deser_validate_fs() {
        let raw = r#"
fs:
  volumes:
    - name: data
      source:
        shared:
          id: bf522f22-b5ff-42c4-9625-d1d9bf796b44
      mounts:
        - mount_path: /data
"#;

        let data = serde_yaml::from_str::<CapabilityMapV1>(raw).unwrap();
        assert_eq!(
            data,
            CapabilityMapV1 {
                fs: Some(CapabilityFileSystemV1 {
                    volumes: vec![FsVolumeConfig {
                        name: "data".to_string(),
                        source: VolumeSourceV1::Shared(VolumeSourceShared {
                            id: uuid::Uuid::parse_str("bf522f22-b5ff-42c4-9625-d1d9bf796b44")
                                .unwrap(),
                            size: None,
                        }),
                        mounts: vec![VolumeMountV1 {
                            mount_path: "/data".to_string(),
                            sub_path: None,
                            permissions: None,
                        }],
                    }],
                }),
                ..Default::default()
            }
        );

        let gen =
            schemars::gen::SchemaGenerator::new(schemars::gen::SchemaSettings::draft2019_09());

        let schema = gen.into_root_schema_for::<CapabilityMapV1>();
        let schema_value = serde_json::to_value(&schema).unwrap();

        let value = serde_json::to_value(&data).unwrap();
        let schema = Arc::new(jsonschema::JSONSchema::compile(&schema_value).unwrap());

        let res = schema.validate(&value);

        if let Err(errors) = res {
            for error in errors {
                println!("Validation error: {}", error);
            }
            panic!("Validation failed");
        }
    }
}