Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
157 lines (143 loc) · 6.19 KB
/
Copy pathlib.rs
File metadata and controls
157 lines (143 loc) · 6.19 KB
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
//! Routing calls for the HTTP service and the phone's native provider. Both answer through `respond`.
#[cfg(feature = "http")]
mod http;
pub mod native;
#[cfg(feature = "http")]
pub use http::{app, MAX_WORKERS};
use planner_router::{
data::{RoutingData, Selection},
directory::Files,
shape::LineRequest,
Control, Error, Request, Router,
};
use serde_json::{json, Value};
use std::{
panic::{catch_unwind, AssertUnwindSafe},
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
pub type Engine = Router<Selection<Files>>;
/// The request body limit of every call.
const BODY_LIMIT: usize = 64 * 1024;
/// Cooperative deadlines. A shape request routes parts of its line many times.
const ROUTE_DEADLINE: Duration = Duration::from_secs(15);
const SHAPE_DEADLINE: Duration = Duration::from_secs(30);
/// Answers one call, `route` or `shape`, with an HTTP status and a JSON body. The call stops
/// when `cancelled` is set or at its deadline. A panic answers `internal` and rebuilds `router`.
pub fn respond(router: &mut Engine, call: &str, body: &[u8], cancelled: &AtomicBool) -> (u16, Vec<u8>) {
if !known(call) {
return encode(not_found(call));
}
let started = Instant::now();
let deadline = if call == "shape" { SHAPE_DEADLINE } else { ROUTE_DEADLINE };
let stop = || cancelled.load(Ordering::Relaxed) || started.elapsed() > deadline;
let control = Control { cancelled: &stop, ..Control::default() };
let invalid = || Error::InvalidRequest(format!("Expected a {call} request with valid JSON fields"));
let result = catch_unwind(AssertUnwindSafe(|| {
if body.len() > BODY_LIMIT {
return Err(too_large());
}
if call == "route" {
let request: Request = serde_json::from_slice(body).map_err(|_| invalid())?;
router.route(&request, &control).map(|route| planner_router::answer::answer(&route))
} else {
let request: LineRequest = serde_json::from_slice(body).map_err(|_| invalid())?;
planner_router::shape::answer(router, &request, control)
}
}));
encode(match result {
Ok(Ok(answer)) => (200, answer),
Ok(Err(error)) => error_body(error),
Err(_) => {
// The panic can leave the router's caches half updated. A fork shares only complete data.
let budget = router.package().memory_budget();
*router = Router::new(router.package().fork(), budget);
internal(&format!("A {call} call panicked; its router was rebuilt"))
}
})
}
/// The calls that `respond` answers.
pub(crate) fn known(call: &str) -> bool {
matches!(call, "route" | "shape")
}
pub(crate) fn encode((status, value): (u16, Value)) -> (u16, Vec<u8>) {
(status, serde_json::to_vec(&value).expect("JSON value serializes"))
}
pub(crate) fn not_found(call: &str) -> (u16, Value) {
(404, json!({ "code": "not_found", "message": format!("Unknown call {call:?}. Use route or shape.") }))
}
pub(crate) fn too_large() -> Error {
Error::InvalidRequest(format!("Use a request body of at most {} KiB", BODY_LIMIT / 1024))
}
/// A failure of the service itself, not of the request or the data. The cause goes to the log.
pub(crate) fn internal(cause: &str) -> (u16, Value) {
eprintln!("{cause}");
(500, json!({ "code": "internal", "message": "The routing service failed. Try again." }))
}
/// No worker became free in time, or a worker had no memory for the request at that moment.
pub(crate) fn busy() -> (u16, Value) {
(503, json!({ "code": "busy", "message": "Routing is busy. Try again shortly." }))
}
pub(crate) fn error_body(error: Error) -> (u16, Value) {
let at = match error {
Error::NoSnap(point) => Some(("point", point)),
Error::NoPath(leg) => Some(("leg", leg)),
_ => None,
};
let (status, code, message) = match error {
Error::InvalidRequest(message) => (400, "invalid_request", message),
Error::MissingRegion(_) => {
(422, "missing_region", "The installed region does not cover these points or is incomplete.".into())
}
Error::NoSnap(index) => (
422,
"no_snap",
format!("No accessible road within {} km of point {}.", planner_router::snap::REACH_M / 1000.0, index + 1),
),
Error::NoPath(_) => (422, "no_path", "No legal route connects these points in this region.".into()),
Error::Cancelled => (408, "cancelled", "The routing request was cancelled or timed out.".into()),
Error::Limit => {
(422, "limit", "This route exceeds the limits of the route service. Plan it in shorter parts.".into())
}
Error::Memory => return busy(),
Error::LineTooLong => (
422,
"line_too_long",
format!(
"Use a line of at most {} km and {} points.",
planner_router::shape::MAX_LINE_M / 1000.0,
planner_router::shape::MAX_LINE_POINTS
),
),
Error::NotReproducible => {
(422, "line_not_reproducible", "No plan within the shaping limits follows this line on roads.".into())
}
Error::InvalidData(cause) => {
eprintln!("Routing data failed validation: {cause}");
(500, "invalid_data", "Routing data failed validation.".into())
}
};
let mut body = json!({ "code": code, "message": message });
if let Some((field, index)) = at {
body[field] = index.into();
}
(status, body)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_fixed_limit_answers_422_and_a_lack_of_memory_answers_busy() {
let (status, body) = error_body(Error::Limit);
assert_eq!((status, body["code"].as_str()), (422, Some("limit")));
assert_eq!(error_body(Error::Memory), busy());
assert_eq!(busy().0, 503);
}
#[test]
fn a_missing_road_names_its_point_and_a_missing_path_its_leg() {
let (_, snap) = error_body(Error::NoSnap(3));
let (_, path) = error_body(Error::NoPath(2));
assert_eq!((snap["code"].as_str(), snap["point"].as_u64()), (Some("no_snap"), Some(3)));
assert_eq!((path["code"].as_str(), path["leg"].as_u64()), (Some("no_path"), Some(2)));
}
}