Rust Iron Web Framework gives some phantom error

152 Views Asked by At

I am using iron. Most of time like 99.* % all is good. But sometimes I get error like Error was: ErrorImpl { code: EofWhileParsingString/List/Object, line: 1, column: 8186 } or InvalidUnicodeCodePoint. I am printing request in log and when i try that request every thing goes well. I also have server written in Golang receiving same request and they never have parsing or json to MyStruct conversion problem.Please note Code would not compile as it is, missing imports, error::from and structure definition. Can not provide reproducible request logs as it only happens when serving lots on concurrent request but if single request is taken it works fine. I have tried serde_json::from_reader, bodyparser crate and all have same issue.

extern crate serde;
extern crate serde_json;
extern crate iron;
use self::iron;
use self::iron::prelude::*;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MyStruct {

}
struct ResponseTime;
impl typemap::Key for ResponseTime {
    type Value = u64;
}

#[derive(Debug)]
struct RequestBody;
impl typemap::Key for RequestBody {
    type Value = RefCell<Vec<u8>>;
}

impl BeforeMiddleware for ResponseTime {
    fn before(&self, req: &mut Request) -> IronResult<()> {
        req.extensions.insert::<RequestBody>(RefCell::new(Vec::new()));
        req.extensions.insert::<ResponseTime>(precise_time_ns());
        Ok(())
    }
}

impl AfterMiddleware for ResponseTime {
    fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
         Ok(res)
    }
    fn catch(&self, req : &mut Request, err : IronError) -> IronResult<Response> {
        let ref byte_req = *req.extensions.get::<RequestBody>()
                        .unwrap()
                        .borrow();
        //just to make sure uft8 is not causing some issue. 
        let payload  = unsafe {
            str::from_utf8_unchecked(&byte_req)
        };
        //but when i send request body all comes good
        error!("Error {} for Body {}", err, payload);
        Err(err)
    }
}


fn iron_handler(req : &mut Request) -> Result<Response, CustomError>{
    let mut buffer = req.extensions.get::<server::RequestBody>()
                        .unwrap()
                        .borrow_mut();
    req.body.read_to_end(&mut buffer)?;
    // not seeing InvalidUnicodeCodePoint after this. 
    let payload = String::from_utf8_lossy(&buffer);
    //some request throw error
    let my_struct_obj : MyStruct = serde_json::from_str(&payload)?;
    Ok(Response::with((iron::status::Ok, "Final Response")))
}

Need help to figure out how to identify problem. Intent of posting here is to see if someone had same issue or can see obvious problem with this. Appreciate everyone'e time do not expect to build and run with examples as can not provide them because of privacy.

0

There are 0 best solutions below