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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use jsonschema::JSONSchema;
use serde::{Deserialize, Serialize};
use thiserror::Error;

// This file is supposed to be auto-generated via rust/build.rs
pub mod schema_types {
    include!(concat!(env!("OUT_DIR"), "/schema_types.rs"));
}

include!(concat!(env!("OUT_DIR"), "/embedded_data.rs"));

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SchemaType {
    #[serde(rename = "json")]
    Json,
    #[serde(rename = "msgpack")]
    Msgpack,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum CompatibilityMode {
    #[serde(rename = "none")]
    None,
    #[serde(rename = "backward")]
    Backward,
}

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SchemaError {
    #[error("Topic not found")]
    TopicNotFound,
    #[error("Invalid version")]
    InvalidVersion,
    #[error("Invalid type")]
    InvalidType,
    #[error("Invalid schema")]
    InvalidSchema,
    // FIXME(swatinem): maybe a dedicated `ValidationError` would be nice which
    // carries a JSON error as well as the exact Schema error.
    #[error("Invalid message")]
    InvalidMessage,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct TopicSchema {
    version: u16,
    #[serde(rename = "type")]
    schema_type: SchemaType,
    compatibility_mode: CompatibilityMode,
    resource: String,
    examples: Vec<String>,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct TopicData {
    topic: String,
    schemas: Vec<TopicSchema>,
}

fn find_entry<'s, T>(slice: &'s [(&str, T)], key: &str) -> Option<&'s T> {
    let idx = slice.binary_search_by_key(&key, |&(name, _)| name).ok()?;
    Some(&slice.get(idx)?.1)
}

impl TopicData {
    fn load(topic: &str) -> Result<Self, SchemaError> {
        let topic_data = find_entry(TOPICS, topic).ok_or(SchemaError::TopicNotFound)?;
        serde_yaml::from_str(topic_data).map_err(|_| SchemaError::TopicNotFound)
    }
}

#[derive(Debug)]
pub struct Schema {
    pub version: u16,
    pub schema_type: SchemaType,
    pub compatibility_mode: CompatibilityMode,
    schema: &'static str,
    compiled_json_schema: JSONSchema,
    examples: &'static [Example],
}

impl PartialEq for Schema {
    fn eq(&self, other: &Self) -> bool {
        self.version == other.version
            && self.schema_type == other.schema_type
            && self.compatibility_mode == other.compatibility_mode
            && self.schema == other.schema
    }
}

impl Schema {
    pub fn validate_json(&self, input: &[u8]) -> Result<serde_json::Value, SchemaError> {
        let message = serde_json::from_slice(input).map_err(|_| SchemaError::InvalidMessage)?;

        if self.compiled_json_schema.is_valid(&message) {
            Ok(message)
        } else {
            Err(SchemaError::InvalidMessage)
        }
    }

    /// Returns the raw JSON Schema definition.
    pub fn raw_schema(&self) -> &str {
        self.schema
    }

    /// Returns a list of examples for this schema.
    pub fn examples(&self) -> &[Example] {
        self.examples
    }
}

#[derive(Debug)]
pub struct Example {
    name: &'static str,
    payload: &'static [u8],
}

impl Example {
    pub fn name(&self) -> &str {
        self.name
    }

    pub fn payload(&self) -> &[u8] {
        self.payload
    }
}

fn get_topic_schema(topic: &str, version: Option<u16>) -> Result<TopicSchema, SchemaError> {
    let mut topic_data = TopicData::load(topic)?;
    topic_data.schemas.sort_by_key(|x| x.version);

    let schema_metadata = if let Some(version) = version {
        topic_data
            .schemas
            .into_iter()
            .find(|x| x.version == version)
            .ok_or(SchemaError::TopicNotFound)?
    } else {
        topic_data
            .schemas
            .pop()
            .ok_or(SchemaError::InvalidVersion)?
    };

    Ok(schema_metadata)
}

/// Returns the schema for a topic. If `version` is passed, return the schema for
/// the specified version, otherwise the latest version is returned.
///
/// Only JSON schemas are currently supported.
///
/// # Errors
///
/// Will return `Err` if `topic` or `version` is not found or if schema data is invalid.
pub fn get_schema(topic: &str, version: Option<u16>) -> Result<Schema, SchemaError> {
    let schema_metadata = get_topic_schema(topic, version)?;

    let schema =
        find_entry(SCHEMAS, &schema_metadata.resource).ok_or(SchemaError::InvalidSchema)?;

    let s = serde_json::from_str(schema).map_err(|_| SchemaError::InvalidSchema)?;
    let compiled_json_schema = JSONSchema::compile(&s).map_err(|_| SchemaError::InvalidSchema)?;

    // FIXME(swatinem): This assumes that there is only a single `examples` entry in the definition.
    // If we would want to support multiple, we would have to either merge those in code generation,
    // or rather use a `fn examples() -> impl Iterator`.
    let examples = schema_metadata
        .examples
        .first()
        .and_then(|example| find_entry(EXAMPLES, example))
        .copied()
        .unwrap_or_default();

    Ok(Schema {
        version: schema_metadata.version,
        schema_type: schema_metadata.schema_type,
        compatibility_mode: schema_metadata.compatibility_mode,
        schema,
        compiled_json_schema,
        examples,
    })
}

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

    #[test]
    fn test_get_schema() {
        assert!(matches!(
            get_schema("asdf", None),
            Err(SchemaError::TopicNotFound)
        ));

        // Json topic
        let schema = get_schema("snuba-queries", None).unwrap();
        assert_eq!(schema.version, 1);
        assert_eq!(schema.schema_type, SchemaType::Json);

        // Msgpack topic
        let schema = get_schema("ingest-events", None).unwrap();
        assert_eq!(schema.version, 1);
        assert_eq!(schema.schema_type, SchemaType::Msgpack);

        // Did not error
        get_schema("snuba-queries", Some(1)).unwrap();
        get_schema("transactions", Some(1)).unwrap();
    }

    #[test]
    fn test_validate() {
        let schema = get_schema("snuba-queries", None).unwrap();

        let examples = schema.examples();
        assert!(!examples.is_empty());
        for example in examples {
            schema.validate_json(example.payload()).unwrap();
        }

        assert!(matches!(
            schema.validate_json(b"{}"),
            Err(SchemaError::InvalidMessage)
        ));
    }
}