-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmessage_receiver.rs
127 lines (103 loc) · 4.03 KB
/
message_receiver.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
use std::{
sync::{mpsc, Arc},
thread,
time::Duration,
};
use futures::{future, stream::Stream, sync::oneshot, Future};
use hyper::{service::service_fn, Body, Method, Request, Response, Server, StatusCode};
use serde::Deserialize;
type HyperResponse = Box<dyn Future<Item = Response<Body>, Error = hyper::Error> + Send>;
#[derive(Debug, Clone)]
pub enum Message {
Start,
Stop,
Messages(Vec<RobloxMessage>),
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
pub enum RobloxMessage {
Output { level: OutputLevel, body: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum OutputLevel {
Print,
Info,
Warning,
Error,
}
#[derive(Debug)]
pub struct MessageReceiverOptions {
pub port: u16,
pub server_id: String,
}
pub struct MessageReceiver {
shutdown_tx: oneshot::Sender<()>,
message_rx: mpsc::Receiver<Message>,
}
impl MessageReceiver {
pub fn start(options: MessageReceiverOptions) -> MessageReceiver {
let (message_tx, message_rx) = mpsc::channel();
let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
let server_id = Arc::new(options.server_id.clone());
thread::spawn(move || {
let service = move || {
let server_id = server_id.clone();
let message_tx = message_tx.clone();
service_fn(move |request: Request<Body>| -> HyperResponse {
let server_id = server_id.clone();
let message_tx = message_tx.clone();
let mut response = Response::new(Body::empty());
log::debug!("Request: {} {}", request.method(), request.uri().path());
match (request.method(), request.uri().path()) {
(&Method::GET, "/") => {
*response.body_mut() = Body::from(server_id.as_str().to_owned());
}
(&Method::POST, "/start") => {
message_tx.send(Message::Start).unwrap();
*response.body_mut() = Body::from("Started");
}
(&Method::POST, "/stop") => {
message_tx.send(Message::Stop).unwrap();
*response.body_mut() = Body::from("Finished");
}
(&Method::POST, "/messages") => {
let message_tx = message_tx.clone();
let future = request.into_body().concat2().map(move |chunk| {
let source = chunk.to_vec();
let messages: Vec<RobloxMessage> = serde_json::from_slice(&source)
.expect("Failed deserializing message from Roblox Studio");
message_tx.send(Message::Messages(messages)).unwrap();
*response.body_mut() = Body::from("Got it!");
response
});
return Box::new(future);
}
_ => {
*response.status_mut() = StatusCode::NOT_FOUND;
}
}
Box::new(future::ok(response))
})
};
let addr = ([127, 0, 0, 1], options.port).into();
let server = Server::bind(&addr)
.serve(service)
.with_graceful_shutdown(shutdown_rx)
.map_err(|e| eprintln!("server error: {}", e));
hyper::rt::run(server);
});
MessageReceiver {
shutdown_tx,
message_rx,
}
}
pub fn recv(&self) -> Message {
self.message_rx.recv().unwrap()
}
pub fn recv_timeout(&self, timeout: Duration) -> Option<Message> {
self.message_rx.recv_timeout(timeout).ok()
}
pub fn stop(self) {
let _dont_care = self.shutdown_tx.send(());
}
}