1#![allow(clippy::result_large_err)]
21
22use crate::policy::Policy;
23use indexmap::IndexMap;
24use lex_bytecode::vm::Vm;
25use lex_bytecode::{Program, Value};
26use std::net::TcpListener;
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::sync::mpsc;
29use std::sync::{Arc, Mutex};
30use std::thread;
31use std::time::Duration;
32
33struct Conn {
35 room: String,
36 outbound: mpsc::Sender<String>,
40}
41
42#[derive(Default)]
44pub struct ChatRegistry {
45 conns: Mutex<IndexMap<u64, Conn>>,
46}
47
48impl ChatRegistry {
49 fn register(&self, room: String, outbound: mpsc::Sender<String>) -> u64 {
50 static NEXT_ID: AtomicU64 = AtomicU64::new(1);
51 let id = NEXT_ID.fetch_add(1, Ordering::SeqCst);
52 self.conns.lock().unwrap().insert(id, Conn { room, outbound });
53 id
54 }
55 fn unregister(&self, id: u64) {
56 self.conns.lock().unwrap().shift_remove(&id);
57 }
58 fn broadcast(&self, room: &str, body: &str) {
59 let conns = self.conns.lock().unwrap();
60 for c in conns.values() {
61 if c.room == room {
62 let _ = c.outbound.send(body.to_string());
63 }
64 }
65 }
66 fn send_to(&self, id: u64, body: &str) -> bool {
67 if let Some(c) = self.conns.lock().unwrap().get(&id) {
68 let _ = c.outbound.send(body.to_string());
69 true
70 } else {
71 false
72 }
73 }
74}
75
76pub fn chat_broadcast(reg: &Arc<ChatRegistry>, room: &str, body: &str) {
79 reg.broadcast(room, body);
80}
81
82pub fn chat_send(reg: &Arc<ChatRegistry>, conn_id: u64, body: &str) -> bool {
83 reg.send_to(conn_id, body)
84}
85
86pub fn serve_ws(
89 port: u16,
90 handler_name: String,
91 program: Arc<Program>,
92 policy: Policy,
93 registry: Arc<ChatRegistry>,
94) -> Result<Value, String> {
95 let listener = TcpListener::bind(("127.0.0.1", port))
96 .map_err(|e| format!("net.serve_ws bind {port}: {e}"))?;
97 eprintln!("net.serve_ws: listening on ws://127.0.0.1:{port}");
98 for stream in listener.incoming() {
99 let stream = match stream {
100 Ok(s) => s,
101 Err(e) => { eprintln!("net.serve_ws accept: {e}"); continue; }
102 };
103 let program = Arc::clone(&program);
104 let policy = policy.clone();
105 let handler_name = handler_name.clone();
106 let registry = Arc::clone(®istry);
107 thread::spawn(move || {
108 if let Err(e) = handle_connection(stream, program, policy, handler_name, registry) {
109 eprintln!("net.serve_ws connection error: {e}");
110 }
111 });
112 }
113 Ok(Value::Unit)
114}
115
116fn handle_connection(
117 stream: std::net::TcpStream,
118 program: Arc<Program>,
119 policy: Policy,
120 handler_name: String,
121 registry: Arc<ChatRegistry>,
122) -> Result<(), String> {
123 use tungstenite::{accept_hdr, handshake::server::{Request, Response}};
124
125 let mut path = String::new();
127 let path_ref = &mut path;
128 let mut ws = accept_hdr(stream, |req: &Request, resp: Response| {
129 *path_ref = req.uri().path().to_string();
130 Ok(resp)
131 }).map_err(|e| format!("ws handshake: {e}"))?;
132
133 let room = path.trim_start_matches('/').to_string();
134
135 let (tx, rx) = mpsc::channel::<String>();
138 let conn_id = registry.register(room.clone(), tx);
139
140 let _ = ws.get_mut().set_read_timeout(Some(Duration::from_millis(50)));
144
145 let result = run_loop(&mut ws, &rx, conn_id, &room, &program, &policy, &handler_name, ®istry);
146 registry.unregister(conn_id);
147 let _ = ws.close(None);
148 result
149}
150
151#[allow(clippy::too_many_arguments)]
152fn run_loop(
153 ws: &mut tungstenite::WebSocket<std::net::TcpStream>,
154 rx: &mpsc::Receiver<String>,
155 conn_id: u64,
156 room: &str,
157 program: &Arc<Program>,
158 policy: &Policy,
159 handler_name: &str,
160 registry: &Arc<ChatRegistry>,
161) -> Result<(), String> {
162 use tungstenite::Message;
163 use std::io::ErrorKind;
164 loop {
165 match ws.read() {
167 Ok(Message::Text(body)) => {
168 let ev = build_ws_event(conn_id, room, &body);
169 let handler = crate::handler::DefaultHandler::new(policy.clone())
170 .with_program(Arc::clone(program))
171 .with_chat_registry(Arc::clone(registry));
172 let mut vm = Vm::with_handler(program, Box::new(handler));
173 if let Err(e) = vm.call(handler_name, vec![ev]) {
174 eprintln!("on_message {conn_id}: {e}");
175 }
176 }
177 Ok(Message::Binary(_)) => { }
178 Ok(Message::Close(_)) | Err(tungstenite::Error::ConnectionClosed) => break,
179 Ok(_) => {} Err(tungstenite::Error::Io(ref e)) if e.kind() == ErrorKind::WouldBlock
181 || e.kind() == ErrorKind::TimedOut => {}
182 Err(e) => return Err(format!("ws read: {e}")),
183 }
184 loop {
186 match rx.try_recv() {
187 Ok(msg) => {
188 if let Err(e) = ws.send(Message::Text(msg.into())) {
189 return Err(format!("ws send: {e}"));
190 }
191 }
192 Err(mpsc::TryRecvError::Empty) => break,
193 Err(mpsc::TryRecvError::Disconnected) => return Ok(()),
194 }
195 }
196 }
197 Ok(())
198}
199
200fn build_ws_event(conn_id: u64, room: &str, body: &str) -> Value {
201 let mut rec = IndexMap::new();
202 rec.insert("body".into(), Value::Str(body.to_string()));
203 rec.insert("conn_id".into(), Value::Int(conn_id as i64));
204 rec.insert("room".into(), Value::Str(room.to_string()));
205 Value::Record(rec)
206}
207
208fn build_ws_conn(conn_id: u64, path: &str, subprotocol: &str) -> Value {
212 let mut rec = IndexMap::new();
213 rec.insert("id".into(), Value::Str(conn_id.to_string()));
214 rec.insert("path".into(), Value::Str(path.to_string()));
215 rec.insert("subprotocol".into(), Value::Str(subprotocol.to_string()));
216 Value::Record(rec)
217}
218
219fn build_ws_message_text(body: &str) -> Value {
221 Value::Variant { name: "WsText".into(), args: vec![Value::Str(body.to_string())] }
222}
223
224fn build_ws_message_close() -> Value {
225 Value::Variant { name: "WsClose".into(), args: vec![] }
226}
227
228fn build_ws_message_ping() -> Value {
229 Value::Variant { name: "WsPing".into(), args: vec![] }
230}
231
232fn apply_ws_action(
234 action: &Value,
235 ws: &mut tungstenite::WebSocket<std::net::TcpStream>,
236) -> Result<(), String> {
237 use tungstenite::Message;
238 match action {
239 Value::Variant { name, args } if name == "WsSend" => {
240 let text = match args.first() {
241 Some(Value::Str(s)) => s.clone(),
242 _ => return Err("WsSend payload must be Str".into()),
243 };
244 ws.send(Message::Text(text.into()))
245 .map_err(|e| format!("ws send: {e}"))
246 }
247 Value::Variant { name, args } if name == "WsSendBinary" => {
248 let bytes: Vec<u8> = match args.first() {
249 Some(Value::List(elems)) => elems
250 .iter()
251 .map(|v| match v {
252 Value::Int(n) => Ok(*n as u8),
253 _ => Err("WsSendBinary payload must be List[Int]".into()),
254 })
255 .collect::<Result<Vec<_>, String>>()?,
256 _ => return Err("WsSendBinary payload must be List[Int]".into()),
257 };
258 ws.send(Message::Binary(bytes.into()))
259 .map_err(|e| format!("ws send binary: {e}"))
260 }
261 Value::Variant { name, .. } if name == "WsNoOp" => Ok(()),
262 other => Err(format!("unexpected WsAction: {other:?}")),
263 }
264}
265
266pub fn serve_ws_fn(
268 port: u16,
269 subprotocol: String,
270 closure: Value,
271 program: Arc<Program>,
272 policy: Policy,
273 registry: Arc<ChatRegistry>,
274) -> Result<Value, String> {
275 let listener = TcpListener::bind(("127.0.0.1", port))
276 .map_err(|e| format!("net.serve_ws_fn bind {port}: {e}"))?;
277 eprintln!("net.serve_ws_fn: listening on ws://127.0.0.1:{port}");
278 for stream in listener.incoming() {
279 let stream = match stream {
280 Ok(s) => s,
281 Err(e) => { eprintln!("net.serve_ws_fn accept: {e}"); continue; }
282 };
283 let program = Arc::clone(&program);
284 let policy = policy.clone();
285 let closure = closure.clone();
286 let subprotocol = subprotocol.clone();
287 let registry = Arc::clone(®istry);
288 thread::spawn(move || {
289 if let Err(e) = handle_connection_fn(
290 stream, program, policy, closure, subprotocol, registry,
291 ) {
292 eprintln!("net.serve_ws_fn connection error: {e}");
293 }
294 });
295 }
296 Ok(Value::Unit)
297}
298
299fn handle_connection_fn(
300 stream: std::net::TcpStream,
301 program: Arc<Program>,
302 policy: Policy,
303 closure: Value,
304 subprotocol: String,
305 registry: Arc<ChatRegistry>,
306) -> Result<(), String> {
307 use tungstenite::{accept_hdr, handshake::server::{Request, Response}};
308
309 let mut path = String::new();
310 let path_ref = &mut path;
311 let mut ws = accept_hdr(stream, |req: &Request, resp: Response| {
312 *path_ref = req.uri().path().to_string();
313 Ok(resp)
314 }).map_err(|e| format!("ws handshake: {e}"))?;
315
316 let (tx, rx) = mpsc::channel::<String>();
317 let conn_id = registry.register(path.trim_start_matches('/').to_string(), tx);
318 let _ = ws.get_mut().set_read_timeout(Some(Duration::from_millis(50)));
319
320 let result = run_loop_fn(
321 &mut ws, &rx, conn_id, &path, &subprotocol,
322 &program, &policy, &closure, ®istry,
323 );
324 registry.unregister(conn_id);
325 let _ = ws.close(None);
326 result
327}
328
329#[allow(clippy::too_many_arguments)]
330fn run_loop_fn(
331 ws: &mut tungstenite::WebSocket<std::net::TcpStream>,
332 rx: &mpsc::Receiver<String>,
333 conn_id: u64,
334 path: &str,
335 subprotocol: &str,
336 program: &Arc<Program>,
337 policy: &Policy,
338 closure: &Value,
339 registry: &Arc<ChatRegistry>,
340) -> Result<(), String> {
341 use tungstenite::Message;
342 use std::io::ErrorKind;
343
344 let ws_conn = build_ws_conn(conn_id, path, subprotocol);
345
346 loop {
347 let ws_msg = match ws.read() {
348 Ok(Message::Text(body)) => Some(build_ws_message_text(&body)),
349 Ok(Message::Binary(_)) => None,
350 Ok(Message::Ping(_)) => Some(build_ws_message_ping()),
351 Ok(Message::Close(_)) | Err(tungstenite::Error::ConnectionClosed) => {
352 let handler = crate::handler::DefaultHandler::new(policy.clone())
354 .with_program(Arc::clone(program))
355 .with_chat_registry(Arc::clone(registry));
356 let mut vm = Vm::with_handler(program, Box::new(handler));
357 let _ = vm.invoke_closure_value(
358 closure.clone(),
359 vec![ws_conn.clone(), build_ws_message_close()],
360 );
361 break;
362 }
363 Ok(_) => None, Err(tungstenite::Error::Io(ref e))
365 if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => None,
366 Err(e) => return Err(format!("ws read: {e}")),
367 };
368
369 if let Some(msg) = ws_msg {
370 let handler = crate::handler::DefaultHandler::new(policy.clone())
371 .with_program(Arc::clone(program))
372 .with_chat_registry(Arc::clone(registry));
373 let mut vm = Vm::with_handler(program, Box::new(handler));
374 match vm.invoke_closure_value(closure.clone(), vec![ws_conn.clone(), msg]) {
375 Ok(action) => {
376 if let Err(e) = apply_ws_action(&action, ws) {
377 eprintln!("ws action {conn_id}: {e}");
378 }
379 }
380 Err(e) => eprintln!("ws handler {conn_id}: {e}"),
381 }
382 }
383
384 loop {
386 match rx.try_recv() {
387 Ok(msg) => {
388 if let Err(e) = ws.send(Message::Text(msg.into())) {
389 return Err(format!("ws send: {e}"));
390 }
391 }
392 Err(mpsc::TryRecvError::Empty) => break,
393 Err(mpsc::TryRecvError::Disconnected) => return Ok(()),
394 }
395 }
396 }
397 Ok(())
398}