-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.rs
124 lines (112 loc) · 3.65 KB
/
main.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
#![forbid(unsafe_code)]
//! An example of how to run a webserver
use std::{
convert::Infallible,
time::{Duration, SystemTime},
};
use axum::{
extract::{
ws::{Message, WebSocket},
Path, WebSocketUpgrade,
},
response::IntoResponse,
routing::get,
Router,
};
use futures::{
stream::{SplitSink, SplitStream},
SinkExt, StreamExt,
};
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use tokio::time::sleep;
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
const APP_NAME: &str = "reverse_proxy";
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
enum AccessPolicy {
Admin,
Operator,
Viewer,
Anonymous,
}
async fn whoami(Path(policy): Path<AccessPolicy>) -> impl IntoResponse {
match policy {
AccessPolicy::Admin => "admin",
AccessPolicy::Operator => "operator",
AccessPolicy::Viewer => "viewer",
AccessPolicy::Anonymous => "anonymous",
}
}
async fn ws(ws: WebSocketUpgrade) -> impl IntoResponse {
ws.on_upgrade(|s| async {
let (sender, receiver) = s.split();
tokio::select!(
Err(e) = publish_time(sender) => error!("Closing websocket because {e:?}"),
_ = discard_inbound(receiver) => {},
);
})
}
async fn publish_time(
mut stream: SplitSink<WebSocket, Message>,
) -> Result<Infallible, axum::Error> {
loop {
// Unwrap is OK `now` is always after `UNIX_EPOCH` on well-configured systems.
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
stream.send(Message::Text(format!("{now}"))).await?;
sleep(Duration::from_secs(1)).await
}
}
async fn discard_inbound(mut stream: SplitStream<WebSocket>) {
while let Some(msg) = stream.next().await {
match msg {
Ok(Message::Text(msg)) => warn!("Discarding inbound text {msg}"),
Ok(Message::Binary(_)) => warn!("Discarding inbound binary"),
Ok(Message::Ping(_)) => {}
Ok(Message::Pong(_)) => {}
Ok(Message::Close(msg)) => info!("Client is closing the connection {msg:?}"),
Err(e) => {
warn!("Failed to discard inbound because {e}");
break;
}
}
}
}
fn new_app() -> Router {
let app = Router::new()
.route(
&format!("/local/{APP_NAME}/api/:policy/whoami"),
get(whoami),
)
.route(&format!("/local/{APP_NAME}/api/:policy/ws"), get(ws));
// No Axis devices are x86_64, so as long as this continues to be the case this will not be
// erroneously included. However, even though the SDK only supports x86_64 hosts, this app
// does not depend on the C APIs and could be built without the SDK. If that is done one a
// host other than x86_64 this will be erroneously excluded.
// TODO: Find a more robust configuration
#[cfg(target_arch = "x86_64")]
let app = {
use tower_http::services::ServeDir;
app.nest_service(
&format!("/local/{APP_NAME}"),
ServeDir::new(format!("apps/{APP_NAME}/html")),
)
};
app.layer(
TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::new().include_headers(true)),
)
}
#[tokio::main]
async fn main() {
acap_logging::init_logger();
let app = new_app();
// Unwrap is OK because if we cannot start the web server then there is nothing useful the app
// can do, so exiting is appropriate.
let listener = tokio::net::TcpListener::bind("127.0.0.1:2001")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}