use crate::error::{LineError, ParseError};
use crate::message::Message;
use alloc::string::ToString;
use serde_json::Value;
const MESSAGE_TAGS: [&str; 12] = [
"insert",
"update",
"delete",
"bootstrap-insert",
"bootstrap-start",
"bootstrap-complete",
"table-create",
"table-alter",
"table-drop",
"database-create",
"database-alter",
"database-drop",
];
fn classify(json_error: serde_json::Error, tag: Option<&str>) -> ParseError {
match tag {
Some(tag) if !MESSAGE_TAGS.contains(&tag) => {
ParseError::UnknownMessageType(tag.to_string())
}
_ => ParseError::Json(json_error),
}
}
fn peek_tag(value: &Value) -> Option<&str> {
value.get("type")?.as_str()
}
pub fn parse(json: &str) -> Result<Message, ParseError> {
match serde_json::from_str(json) {
Ok(message) => Ok(message),
Err(e) => Err(match serde_json::from_str::<Value>(json) {
Ok(value) => classify(e, peek_tag(&value)),
Err(_) => ParseError::Json(e),
}),
}
}
pub fn parse_slice(json: &[u8]) -> Result<Message, ParseError> {
match serde_json::from_slice(json) {
Ok(message) => Ok(message),
Err(e) => Err(match serde_json::from_slice::<Value>(json) {
Ok(value) => classify(e, peek_tag(&value)),
Err(_) => ParseError::Json(e),
}),
}
}
pub fn parse_lines(json: &str) -> impl Iterator<Item = Result<Message, LineError>> + '_ {
json.lines()
.enumerate()
.filter(|(_, line)| !line.trim().is_empty())
.map(|(index, line)| {
parse(line).map_err(|source| LineError {
line: index + 1,
source,
})
})
}
#[cfg(test)]
mod tests {
use super::{MESSAGE_TAGS, ParseError, parse};
use alloc::format;
#[test]
fn message_tags_match_the_variants() {
for tag in MESSAGE_TAGS {
let json = format!(r#"{{"type":"{tag}"}}"#);
match parse(&json) {
Err(ParseError::Json(_)) => {}
Err(ParseError::UnknownMessageType(unknown)) => {
panic!("`{unknown}` is in MESSAGE_TAGS but is not a Message variant")
}
Ok(message) => panic!("`{tag}` parsed with no fields at all: {message:?}"),
}
}
}
#[test]
fn a_tag_outside_the_array_is_unknown() {
let error = parse(r#"{"type":"table-rename"}"#).expect_err("must not parse");
assert!(matches!(error, ParseError::UnknownMessageType(_)));
}
}