Debian Codegraph @

third_party/rust/warp/examples/sse_chat.rs

raw
1 use futures_util::{Stream, StreamExt};
2 use std::collections::HashMap;
3 use std::sync::{
4 atomic::{AtomicUsize, Ordering},
5 Arc, Mutex,
6 };
7 use tokio::sync::mpsc;
8 use tokio_stream::wrappers::UnboundedReceiverStream;
9 use warp::{sse::Event, Filter};
10
11 #[tokio::main]
12 async fn main() {
13 pretty_env_logger::init();
14
15 // Keep track of all connected users, key is usize, value
16 // is an event stream sender.
17 let users = Arc::new(Mutex::new(HashMap::new()));
18 // Turn our "state" into a new Filter...
19 let users = warp::any().map(move || users.clone());
20
21 // POST /chat -> send message
22 let chat_send = warp::path("chat")
23 .and(warp::post())
24 .and(warp::path::param::<usize>())
25 .and(warp::body::content_length_limit(500))
26 .and(
27 warp::body::bytes().and_then(|body: bytes::Bytes| async move {
28 std::str::from_utf8(&body)
29 .map(String::from)
30 .map_err(|_e| warp::reject::custom(NotUtf8))
31 }),
32 )
33 .and(users.clone())
34 .map(|my_id, msg, users| {
35 user_message(my_id, msg, &users);
36 warp::reply()
37 });
38
39 // GET /chat -> messages stream
40 let chat_recv = warp::path("chat").and(warp::get()).and(users).map(|users| {
41 // reply using server-sent events
42 let stream = user_connected(users);
43 warp::sse::reply(warp::sse::keep_alive().stream(stream))
44 });
45
46 // GET / -> index html
47 let index = warp::path::end().map(|| {
48 warp::http::Response::builder()
49 .header("content-type", "text/html; charset=utf-8")
50 .body(INDEX_HTML)
51 });
52
53 let routes = index.or(chat_recv).or(chat_send);
54
55 warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
56 }
57
58 /// Our global unique user id counter.
59 static NEXT_USER_ID: AtomicUsize = AtomicUsize::new(1);
60
61 /// Message variants.
62 #[derive(Debug)]
63 enum Message {
64 UserId(usize),
65 Reply(String),
66 }
67
68 #[derive(Debug)]
69 struct NotUtf8;
70 impl warp::reject::Reject for NotUtf8 {}
71
72 /// Our state of currently connected users.
73 ///
74 /// - Key is their id
75 /// - Value is a sender of `Message`
76 type Users = Arc<Mutex<HashMap<usize, mpsc::UnboundedSender<Message>>>>;
77
78 fn user_connected(users: Users) -> impl Stream<Item = Result<Event, warp::Error>> + Send + 'static {
79 // Use a counter to assign a new unique ID for this user.
80 let my_id = NEXT_USER_ID.fetch_add(1, Ordering::Relaxed);
81
82 eprintln!("new chat user: {}", my_id);
83
84 // Use an unbounded channel to handle buffering and flushing of messages
85 // to the event source...
86 let (tx, rx) = mpsc::unbounded_channel();
87 let rx = UnboundedReceiverStream::new(rx);
88
89 tx.send(Message::UserId(my_id))
90 // rx is right above, so this cannot fail
91 .unwrap();
92
93 // Save the sender in our list of connected users.
94 users.lock().unwrap().insert(my_id, tx);
95
96 // Convert messages into Server-Sent Events and return resulting stream.
97 rx.map(|msg| match msg {
98 Message::UserId(my_id) => Ok(Event::default().event("user").data(my_id.to_string())),
99 Message::Reply(reply) => Ok(Event::default().data(reply)),
100 })
101 }
102
103 fn user_message(my_id: usize, msg: String, users: &Users) {
104 let new_msg = format!("<User#{}>: {}", my_id, msg);
105
106 // New message from this user, send it to everyone else (except same uid)...
107 //
108 // We use `retain` instead of a for loop so that we can reap any user that
109 // appears to have disconnected.
110 users.lock().unwrap().retain(|uid, tx| {
111 if my_id == *uid {
112 // don't send to same user, but do retain
113 true
114 } else {
115 // If not `is_ok`, the SSE stream is gone, and so don't retain
116 tx.send(Message::Reply(new_msg.clone())).is_ok()
117 }
118 });
119 }
120
121 static INDEX_HTML: &str = r#"
122 <!DOCTYPE html>
123 <html>
124 <head>
125 <title>Warp Chat</title>
126 </head>
127 <body>
128 <h1>warp chat</h1>
129 <div id="chat">
130 <p><em>Connecting...</em></p>
131 </div>
132 <input type="text" id="text" />
133 <button type="button" id="send">Send</button>
134 <script type="text/javascript">
135 var uri = 'http://' + location.host + '/chat';
136 var sse = new EventSource(uri);
137 function message(data) {
138 var line = document.createElement('p');
139 line.innerText = data;
140 chat.appendChild(line);
141 }
142 sse.onopen = function() {
143 chat.innerHTML = "<p><em>Connected!</em></p>";
144 }
145 var user_id;
146 sse.addEventListener("user", function(msg) {
147 user_id = msg.data;
148 });
149 sse.onmessage = function(msg) {
150 message(msg.data);
151 };
152 send.onclick = function() {
153 var msg = text.value;
154 var xhr = new XMLHttpRequest();
155 xhr.open("POST", uri + '/' + user_id, true);
156 xhr.send(msg);
157 text.value = '';
158 message('<You>: ' + msg);
159 };
160 </script>
161 </body>
162 </html>
163 "#;