use crate::constants::{ErrorCode, QueryFormat, REPE_VERSION};
use crate::header::Header;
use crate::message::{
Message, MessageView, create_error_response_like, create_error_response_unstamped_view,
};
use crate::peer::CallContext;
use crate::server::{HandlerErased, Router};
use std::sync::Arc;
pub(crate) enum RouteOutcome<'a> {
Dispatch {
handler: Arc<dyn HandlerErased>,
notify: bool,
path: &'a str,
},
Reject {
notify: bool,
code: ErrorCode,
message: String,
},
}
pub(crate) fn route<'a>(router: &Router, header: &Header, query: &'a [u8]) -> RouteOutcome<'a> {
let notify = header.notify == 1;
if header.version != REPE_VERSION {
return RouteOutcome::Reject {
notify,
code: ErrorCode::VersionMismatch,
message: format!("Unsupported REPE version {}", header.version),
};
}
let qf = QueryFormat::try_from(header.query_format).unwrap_or(QueryFormat::RawBinary);
let path = match qf {
QueryFormat::JsonPointer => match std::str::from_utf8(query) {
Ok(path) => path,
Err(_) => {
return RouteOutcome::Reject {
notify,
code: ErrorCode::InvalidQuery,
message: "Query must be valid UTF-8".to_string(),
};
}
},
_ => {
return RouteOutcome::Reject {
notify,
code: ErrorCode::InvalidQuery,
message: "Raw binary queries are not supported by this server".to_string(),
};
}
};
match router.get(path) {
Some(handler) => RouteOutcome::Dispatch {
handler,
notify,
path,
},
None => RouteOutcome::Reject {
notify,
code: ErrorCode::MethodNotFound,
message: format!("Method not found: {path}"),
},
}
}
pub(crate) fn route_request_view(router: &Router, view: &MessageView) -> Option<Message> {
match route(router, &view.header, view.query) {
RouteOutcome::Dispatch {
handler,
notify,
path,
} => {
let ctx = CallContext::detached(path);
dispatch_view(handler.as_ref(), view, &ctx, notify)
}
RouteOutcome::Reject {
notify,
code,
message,
} => (!notify).then(|| create_error_response_unstamped_view(view, code, message)),
}
}
pub(crate) fn write_view_response<W: std::io::Write>(
w: &mut W,
response: &Message,
query: &[u8],
) -> Result<(), crate::error::RepeError> {
let echo = crate::message::response_echo_query(response, query);
crate::io::write_message_streaming(w, response.header, echo, response.body.len() as u64, |w| {
w.write_all(&response.body)
})
}
pub(crate) fn dispatch_view(
handler: &dyn HandlerErased,
view: &MessageView,
ctx: &CallContext,
notify: bool,
) -> Option<Message> {
if notify {
let _ = handler.handle_view(view, ctx);
return None;
}
Some(match handler.handle_view(view, ctx) {
Ok(message) => message,
Err(err) => {
create_error_response_unstamped_view(view, err.to_error_code(), err.to_string())
}
})
}
#[cfg_attr(not(feature = "websocket"), allow(dead_code))]
pub(crate) fn dispatch(
handler: &dyn HandlerErased,
req: &Message,
ctx: &CallContext,
notify: bool,
) -> Option<Message> {
if notify {
let _ = handler.handle_with_ctx(req, ctx);
return None;
}
Some(match handler.handle_with_ctx(req, ctx) {
Ok(message) => message,
Err(err) => create_error_response_like(req, err.to_error_code(), err.to_string()),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{HEADER_SIZE, QueryFormat};
use crate::io::write_message_streaming;
use crate::server::Router;
use serde_json::json;
use std::io::Write;
fn request_bytes(path: &str, body: serde_json::Value) -> Vec<u8> {
Message::builder()
.id(7)
.query_str(path)
.query_format(QueryFormat::JsonPointer)
.body_json(&body)
.unwrap()
.build()
.to_vec()
}
#[test]
fn view_dispatch_returns_query_less_response_framed_with_borrowed_query() {
let router = Router::new().with_json("/echo", |v: serde_json::Value| Ok(v));
let wire = request_bytes("/echo", json!({"x": 1}));
let view = MessageView::from_slice(&wire).unwrap();
let resp = route_request_view(&router, &view).expect("response");
assert!(
resp.query.is_empty(),
"view dispatch leaves the query for the writer"
);
let mut out = Vec::new();
write_message_streaming(
&mut out,
resp.header,
view.query,
resp.body.len() as u64,
|w| w.write_all(&resp.body),
)
.unwrap();
let framed = Message::from_slice(&out).unwrap();
assert_eq!(framed.query, view.query);
assert_eq!(framed.header.id, 7);
assert_eq!(
framed.header.length,
HEADER_SIZE as u64 + framed.header.query_length + framed.header.body_length
);
let echoed: serde_json::Value = framed.json_body().unwrap();
assert_eq!(echoed, json!({"x": 1}));
}
#[test]
fn view_dispatch_unknown_method_is_query_less_error() {
let router = Router::new();
let wire = request_bytes("/missing", json!({}));
let view = MessageView::from_slice(&wire).unwrap();
let resp = route_request_view(&router, &view).expect("error response");
assert!(resp.query.is_empty());
assert_ne!(resp.header.ec, 0, "method-not-found is an error response");
}
}