Request parsing generally works

This commit is contained in:
Greg Heartsfield 2021-11-24 13:33:38 -06:00
parent bba66a1bce
commit 5e9fca1aeb

View File

@ -1,4 +1,4 @@
use crate::error::{Error, Result}; use crate::error::Result;
use serde::{Deserialize, Deserializer, Serialize}; use serde::{Deserialize, Deserializer, Serialize};
//use serde_json::json; //use serde_json::json;
//use serde_json::Result; //use serde_json::Result;
@ -17,6 +17,7 @@ pub struct Subscription {
} }
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct ReqFilter { pub struct ReqFilter {
id: Option<String>, id: Option<String>,
author: Option<String>, author: Option<String>,
@ -34,26 +35,42 @@ impl<'de> Deserialize<'de> for Subscription {
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
let r: ReqCmd = Deserialize::deserialize(deserializer)?; let mut v: serde_json::Value = Deserialize::deserialize(deserializer)?;
let elems = r.cmds; // this shoud be a 3-or-more element array.
// ensure we have at least 3 fields // verify the first element is a String, REQ
if elems.len() < 3 { // get the subscription from the second element.
Err(serde::de::Error::custom("not enough fields")) // convert each of the remaining objects into filters
} else {
// divide into req/sub-id vector, and filter vector // check for array
let (header, filter_strs) = elems.split_at(2); let va = v
let req_cmd = header.get(0).unwrap(); .as_array_mut()
let sub_id = header.get(1).unwrap(); .ok_or(serde::de::Error::custom("not array"))?;
if req_cmd != "REQ" {
// check length
if va.len() < 3 {
return Err(serde::de::Error::custom("not enough fields"));
}
let mut i = va.into_iter();
// get command ("REQ") and ensure it is a string
let req_cmd_str: serde_json::Value = i.next().unwrap().take();
let req = req_cmd_str.as_str().ok_or(serde::de::Error::custom(
"first element of request was not a string",
))?;
if req != "REQ" {
return Err(serde::de::Error::custom("missing REQ command")); return Err(serde::de::Error::custom("missing REQ command"));
} }
// ensure sub id is a string
let sub_id_str: serde_json::Value = i.next().unwrap().take();
let sub_id = sub_id_str
.as_str()
.ok_or(serde::de::Error::custom("missing subscription id"))?;
let mut filters = vec![]; let mut filters = vec![];
for e in filter_strs.iter() { for fv in i {
let des_res = serde_json::from_str::<ReqFilter>(e); let f: ReqFilter = serde_json::from_value(fv.take())
match des_res { .map_err(|_| serde::de::Error::custom("could not parse filter"))?;
Ok(f) => filters.push(f), filters.push(f);
Err(_) => return Err(serde::de::Error::custom("could not parse filter")),
}
} }
Ok(Subscription { Ok(Subscription {
id: sub_id.to_owned(), id: sub_id.to_owned(),
@ -61,8 +78,6 @@ impl<'de> Deserialize<'de> for Subscription {
}) })
} }
} }
}
// impl Subscription { // impl Subscription {
// pub fn parse(json: &str) -> Result<Subscription> { // pub fn parse(json: &str) -> Result<Subscription> {
// use serde to parse the ReqCmd, and then extract elements // use serde to parse the ReqCmd, and then extract elements
@ -72,21 +87,20 @@ impl<'de> Deserialize<'de> for Subscription {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
// fn simple_req() -> Event {
// super::Event {
// id: 0,
// pubkey: 0,
// created_at: 0,
// kind: 0,
// tags: vec![],
// content: "".to_owned(),
// sig: 0,
// }
// }
#[test] #[test]
fn empty_request_parse() -> Result<()> { fn empty_request_parse() -> Result<()> {
let raw_json = "[\"REQ\",\"some-id\",\"{}\"]"; let raw_json = "[\"REQ\",\"some-id\",{}]";
let s: Subscription = serde_json::from_str(raw_json)?;
assert_eq!(s.id, "some-id");
assert_eq!(s.filters.len(), 1);
assert_eq!(s.filters.get(0).unwrap().author, None);
Ok(())
}
#[test]
fn multi_empty_request_parse() -> Result<()> {
let raw_json = r#"["REQ","some-id",{}]"#;
let s: Subscription = serde_json::from_str(raw_json)?; let s: Subscription = serde_json::from_str(raw_json)?;
assert_eq!(s.id, "some-id"); assert_eq!(s.id, "some-id");
assert_eq!(s.filters.len(), 1); assert_eq!(s.filters.len(), 1);
@ -109,16 +123,16 @@ mod tests {
#[test] #[test]
fn invalid_filter() { fn invalid_filter() {
// unrecognized field in filter // unrecognized field in filter
let raw_json = "[\"REQ\",\"some-id\",\"{\"foo\": 3}\"]"; let raw_json = "[\"REQ\",\"some-id\",{\"foo\": 3}]";
assert!(serde_json::from_str::<Subscription>(raw_json).is_err()); assert!(serde_json::from_str::<Subscription>(raw_json).is_err());
} }
// #[test] #[test]
// fn author_filter() -> Result<()> { fn author_filter() -> Result<()> {
// let raw_json = "[\"REQ\",\"some-id\",\"{\"author\": \"test-author-id\"}\"]"; let raw_json = "[\"REQ\",\"some-id\",{\"author\": \"test-author-id\"}]";
// let s: Subscription = serde_json::from_str(raw_json)?; let s: Subscription = serde_json::from_str(raw_json)?;
// assert_eq!(s.id, "some-id"); assert_eq!(s.id, "some-id");
// assert_eq!(s.filters.len(), 1); assert_eq!(s.filters.len(), 1);
// Ok(()) Ok(())
// } }
} }