-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
day19.rs
128 lines (113 loc) · 3.21 KB
/
day19.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
use axum::{
extract::{
ws::{WebSocket, WebSocketUpgrade},
Path, State,
},
response::IntoResponse,
routing::{get, post},
Router,
};
use futures::{SinkExt, StreamExt};
use std::{
collections::HashMap,
sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex,
},
};
use tokio::{spawn, sync::broadcast::Sender};
#[derive(Clone, serde::Serialize)]
struct Message {
user: String,
message: String,
}
#[derive(Clone)]
struct Day19State {
view_count: Arc<AtomicU64>,
sockets: Arc<Mutex<HashMap<u64, Sender<Message>>>>,
}
pub(crate) fn router() -> Router {
Router::new()
.route("/19/ws/ping", get(ping_handler))
.route("/19/reset", post(reset))
.route("/19/views", get(views))
.route("/19/ws/room/:id/user/:user", get(room_handler))
.with_state(Day19State {
view_count: Arc::new(AtomicU64::new(0)),
sockets: Arc::new(Mutex::new(HashMap::new())),
})
}
async fn ping_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
ws.on_upgrade(ping)
}
async fn ping(mut ws: WebSocket) {
let mut served = false;
while let Some(Ok(msg)) = ws.recv().await {
if let Ok(msg) = msg.to_text() {
match msg {
"serve" => served = true,
"ping" if served => {
let _ = ws.send("pong".into()).await;
}
_ => {}
}
}
}
}
async fn reset(State(state): State<Day19State>) {
state.view_count.store(0, Ordering::Relaxed);
}
async fn views(State(state): State<Day19State>) -> impl IntoResponse {
state.view_count.load(Ordering::Relaxed).to_string()
}
async fn room_handler(
ws: WebSocketUpgrade,
Path((id, user)): Path<(u64, String)>,
State(state): State<Day19State>,
) -> impl IntoResponse {
ws.on_upgrade(move |s| room(s, id, user, state))
}
#[derive(serde::Deserialize)]
struct WsMsg {
message: String,
}
async fn room(ws: WebSocket, id: u64, user: String, state: Day19State) {
let send = {
let Ok(mut map) = state.sockets.lock() else {
return;
};
if let Some(ch) = map.get(&id) {
ch.clone()
} else {
let ch = Sender::new(128);
map.insert(id, ch.clone());
ch
}
};
let (mut ws_send, mut ws_recv) = ws.split();
let mut recv = send.subscribe();
let recv_task = spawn(async move {
while let Ok(message) = recv.recv().await {
if let Ok(message) = serde_json::to_string(&message) {
if ws_send.send(message.into()).await.is_ok() {
state.view_count.fetch_add(1, Ordering::Relaxed);
} else {
return;
}
}
}
});
while let Some(Ok(msg)) = ws_recv.next().await {
if let Ok(msg) = msg.into_text() {
if let Ok(WsMsg { message }) = serde_json::from_str::<WsMsg>(&msg) {
if message.len() <= 128 {
let _ = send.send(Message {
user: user.clone(),
message,
});
}
}
}
}
recv_task.abort();
}