This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 124
/
server.rs
283 lines (241 loc) · 8.21 KB
/
server.rs
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use crate::route_guide::Feature;
use crate::route_guide::Point;
use crate::route_guide::Rectangle;
use crate::route_guide::RouteNote;
use crate::route_guide::RouteSummary;
use crate::route_guide_grpc::RouteGuide;
use futures::stream::StreamExt;
use grpc::Metadata;
use grpc::ServerRequest;
use grpc::ServerRequestSingle;
use grpc::ServerResponseSink;
use grpc::ServerResponseUnarySink;
use json::JsonValue;
use std::collections::HashMap;
use std::f64;
use std::fs;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Instant;
// https://github.com/grpc/grpc-go/blob/master/examples/route_guide/server/server.go
#[derive(Default)]
pub struct RouteGuideImpl {
saved_features: Arc<Vec<Feature>>,
route_notes: Arc<Mutex<HashMap<String, Vec<RouteNote>>>>,
}
impl RouteGuideImpl {
pub fn new_and_load_db() -> RouteGuideImpl {
RouteGuideImpl {
saved_features: Arc::new(load_features(Path::new(ROUTE_GUIDE_DB_PATH))),
route_notes: Default::default(),
}
}
}
impl RouteGuide for RouteGuideImpl {
fn get_feature(
&self,
req: ServerRequestSingle<Point>,
resp: ServerResponseUnarySink<Feature>,
) -> grpc::Result<()> {
for feature in &*self.saved_features {
if feature.get_location() == &req.message {
return resp.finish(feature.clone());
}
}
resp.finish(Feature {
location: Some(req.message).into(),
..Default::default()
})
}
fn list_features(
&self,
mut req: ServerRequestSingle<Rectangle>,
mut resp: ServerResponseSink<Feature>,
) -> grpc::Result<()> {
let loop_handle = req.loop_handle();
let req = req.take_message();
let saved_features = self.saved_features.clone();
loop_handle.spawn(async move {
for feature in &saved_features[..] {
if in_range(feature.get_location(), &req) {
resp.ready().await?;
resp.send_data(feature.clone())?;
}
}
resp.send_trailers(Metadata::new())
});
Ok(())
}
fn record_route(
&self,
req: ServerRequest<Point>,
resp: ServerResponseUnarySink<RouteSummary>,
) -> grpc::Result<()> {
let start_time = Instant::now();
let saved_features = self.saved_features.clone();
let loop_handle = req.loop_handle();
let mut stream = req.into_stream();
loop_handle.spawn(async move {
struct State {
point_count: u32,
feature_count: u32,
distance: u32,
last_point: Option<Point>,
}
let mut state = State {
point_count: 0,
feature_count: 0,
distance: 0,
last_point: None,
};
while let Some(point) = stream.next().await {
let point = point?;
state.point_count += 1;
for feature in &saved_features[..] {
if feature.get_location() == &point {
state.feature_count += 1;
}
}
if let Some(last_point) = &state.last_point {
state.distance += calc_distance(last_point, &point);
}
state.last_point = Some(point);
}
resp.finish(RouteSummary {
point_count: state.point_count as i32,
feature_count: state.feature_count as i32,
distance: state.distance as i32,
elapsed_time: start_time.elapsed().as_secs() as i32,
..Default::default()
})
});
Ok(())
}
fn route_chat(
&self,
req: ServerRequest<RouteNote>,
mut resp: ServerResponseSink<RouteNote>,
) -> grpc::Result<()> {
let route_notes_map = self.route_notes.clone();
let loop_handle = req.loop_handle();
let mut req = req.into_stream();
loop_handle.spawn(async move {
loop {
// Wait until resp is writable
resp.ready().await?;
match req.next().await {
Some(note) => {
let note = note?;
let key = serialize(note.get_location());
let mut route_notes_map = route_notes_map.lock().unwrap();
let route_notes = route_notes_map.entry(key).or_insert(Vec::new());
route_notes.push(note);
for note in route_notes {
resp.send_data(note.clone())?;
}
}
None => {
return resp.send_trailers(Metadata::new());
}
}
}
});
Ok(())
}
}
fn in_range(point: &Point, rect: &Rectangle) -> bool {
let left = f64::min(
rect.get_lo().longitude as f64,
rect.get_hi().longitude as f64,
);
let right = f64::max(
rect.get_lo().longitude as f64,
rect.get_hi().longitude as f64,
);
let top = f64::max(rect.get_lo().latitude as f64, rect.get_hi().latitude as f64);
let bottom = f64::min(rect.get_lo().latitude as f64, rect.get_hi().latitude as f64);
point.longitude as f64 >= left
&& point.longitude as f64 <= right
&& point.latitude as f64 >= bottom
&& point.latitude as f64 <= top
}
fn to_radians(num: f64) -> f64 {
num * f64::consts::PI / 180.
}
fn calc_distance(p1: &Point, p2: &Point) -> u32 {
let cord_factor: f64 = 1e7;
let r = 6371000.; // earth radius in metres
let lat1 = to_radians(p1.latitude as f64 / cord_factor);
let lat2 = to_radians(p2.latitude as f64 / cord_factor);
let lng1 = to_radians(p1.longitude as f64 / cord_factor);
let lng2 = to_radians(p2.longitude as f64 / cord_factor);
let dlat = lat2 - lat1;
let dlng = lng2 - lng1;
let a = f64::sin(dlat / 2.) * f64::sin(dlat / 2.)
+ f64::cos(lat1) * f64::cos(lat2) * f64::sin(dlng / 2.) * f64::sin(dlng / 2.);
let c = 2. * f64::atan2(f64::sqrt(a), f64::sqrt(1. - a));
let distance = r * c;
distance as u32
}
fn serialize(point: &Point) -> String {
format!("{} {}", point.latitude, point.longitude)
}
const ROUTE_GUIDE_DB_PATH: &str = "testdata/route_guide_db.json";
fn load_features(path: &Path) -> Vec<Feature> {
let mut file = fs::File::open(path).expect("open");
let mut s = String::new();
file.read_to_string(&mut s).expect("read");
// TODO: use protobuf mapper when new version is released
let json_value = json::parse(&s).expect("parse json");
let array = match json_value {
JsonValue::Array(array) => array,
_ => panic!(),
};
array
.into_iter()
.map(|item| {
let object = match item {
JsonValue::Object(object) => object,
_ => panic!(),
};
let location = match object.get("location").expect("location") {
JsonValue::Object(object) => object,
_ => panic!(),
};
Feature {
name: object
.get("name")
.expect("name")
.as_str()
.expect("unwrap")
.to_owned(),
location: Some(Point {
latitude: location
.get("latitude")
.expect("latitude")
.as_i32()
.unwrap(),
longitude: location
.get("longitude")
.expect("longitude")
.as_i32()
.unwrap(),
..Default::default()
})
.into(),
..Default::default()
}
})
.collect()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_load_features() {
let features = load_features(Path::new(ROUTE_GUIDE_DB_PATH));
assert!(features.len() > 0);
}
}