asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Debug HTTP server for runtime inspection.
//!
//! Provides a lightweight HTTP server that serves a debug dashboard and
//! runtime snapshot data. The server runs in a background thread using
//! `std::net::TcpListener` — no async runtime required.
//!
//! ubs:ignore — synchronous debug server; TcpStreams are short-lived
//! (one request/response cycle) and close-on-drop is acceptable here.
//!
//! # Endpoints
//!
//! - `GET /debug` — HTML dashboard with auto-refresh
//! - `GET /debug/snapshot` — Current runtime snapshot as JSON
//! - `GET /debug/trace` — Recent trace events as JSON
//! - `GET /debug/ws` — WebSocket endpoint (upgrade + one-shot JSON push)
//!
//! # Example
//!
//! ```ignore
//! use asupersync::web::debug::{DebugServer, DebugServerConfig};
//! use asupersync::runtime::RuntimeSnapshot;
//! use parking_lot::Mutex;
//! use std::sync::Arc;
//!
//! let state = Arc::new(Mutex::new(runtime_state));
//! let st = Arc::clone(&state);
//! let server = DebugServer::new(
//!     9999,
//!     Arc::new(move || st.lock().snapshot()),
//! );
//! server.start().expect("failed to start debug server");
//! println!("Dashboard: {}", server.url());
//! ```

use std::io::{BufRead, BufReader, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;

use crate::runtime::RuntimeSnapshot;
use crate::tracing_compat::info;
use base64::Engine as _;
use sha1::{Digest, Sha1};

/// Function that produces a runtime snapshot on demand.
pub type SnapshotFn = Arc<dyn Fn() -> RuntimeSnapshot + Send + Sync>;

/// Configuration for the debug server.
#[derive(Debug, Clone)]
pub struct DebugServerConfig {
    /// Whether to print the URL on startup.
    pub print_url: bool,
    /// Bind address (default: `127.0.0.1`).
    pub bind_addr: String,
    /// Auto-refresh interval for the dashboard in seconds.
    pub refresh_interval_secs: u32,
    /// Maximum number of concurrent connections.
    pub max_connections: usize,
}

impl Default for DebugServerConfig {
    fn default() -> Self {
        Self {
            print_url: true,
            bind_addr: "127.0.0.1".to_string(),
            refresh_interval_secs: 2,
            max_connections: 16,
        }
    }
}

/// Debug HTTP server handle.
///
/// Serves a debug dashboard and JSON endpoints for runtime inspection.
/// The server runs in a background thread and stops when this handle
/// is dropped.
pub struct DebugServer {
    port: u16,
    snapshot_fn: SnapshotFn,
    config: DebugServerConfig,
    running: Arc<AtomicBool>,
    local_addr: Option<SocketAddr>,
}

impl DebugServer {
    /// Creates a new debug server on the given port.
    #[must_use]
    pub fn new(port: u16, snapshot_fn: SnapshotFn) -> Self {
        Self {
            port,
            snapshot_fn,
            config: DebugServerConfig::default(),
            running: Arc::new(AtomicBool::new(false)),
            local_addr: None,
        }
    }

    /// Creates a new debug server with custom configuration.
    #[must_use]
    pub fn with_config(port: u16, snapshot_fn: SnapshotFn, config: DebugServerConfig) -> Self {
        Self {
            port,
            snapshot_fn,
            config,
            running: Arc::new(AtomicBool::new(false)),
            local_addr: None,
        }
    }

    /// Returns the dashboard URL.
    #[must_use]
    pub fn url(&self) -> String {
        let addr = self.local_addr.map_or_else(
            || format!("{}:{}", self.config.bind_addr, self.port),
            |a| a.to_string(),
        );
        format!(
            "http://{addr}/debug?refresh={}",
            self.config.refresh_interval_secs.saturating_mul(1000)
        )
    }

    /// Returns whether the server is running.
    #[must_use]
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::Relaxed)
    }

    /// Starts the debug server in a background thread.
    ///
    /// # Errors
    ///
    /// Returns an error if the TCP listener cannot bind.
    pub fn start(&mut self) -> std::io::Result<()> {
        let bind = format!("{}:{}", self.config.bind_addr, self.port);
        let listener = TcpListener::bind(&bind)?;
        listener.set_nonblocking(true)?;

        let local_addr = listener.local_addr()?;
        self.local_addr = Some(local_addr);
        self.running.store(true, Ordering::Relaxed);

        if self.config.print_url {
            info!(url = %self.url(), "debug dashboard started");
        }

        let snapshot_fn = Arc::clone(&self.snapshot_fn);
        let running = Arc::clone(&self.running);
        let active_connections = Arc::new(AtomicUsize::new(0));
        let max_connections = self.config.max_connections;

        thread::Builder::new()
            .name("asupersync-debug-server".to_string())
            .spawn(move || {
                serve_loop(
                    &listener,
                    &snapshot_fn,
                    &running,
                    max_connections,
                    &active_connections,
                );
            })?;

        Ok(())
    }

    /// Stops the debug server.
    pub fn stop(&self) {
        self.running.store(false, Ordering::Relaxed);
    }
}

impl Drop for DebugServer {
    fn drop(&mut self) {
        self.stop();
    }
}

// =========================================================================
// HTTP server loop
// =========================================================================

fn serve_loop(
    listener: &TcpListener,
    snapshot_fn: &SnapshotFn,
    running: &AtomicBool,
    max_connections: usize,
    active_connections: &Arc<AtomicUsize>,
) {
    while running.load(Ordering::Relaxed) {
        match listener.accept() {
            Ok((mut stream, _peer)) => {
                // Atomically increment-then-check to prevent TOCTOU race
                // where multiple threads pass the limit check simultaneously.
                let prev = active_connections.fetch_add(1, Ordering::Relaxed);
                if prev >= max_connections {
                    active_connections.fetch_sub(1, Ordering::Relaxed);
                    let _ = write_response(&mut stream, 503, "text/plain", b"Debug server busy");
                    let _ = stream.shutdown(Shutdown::Both);
                    continue;
                }

                let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
                let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
                let snapshot_fn = Arc::clone(snapshot_fn);
                let active_connections_for_thread = Arc::clone(active_connections);

                if thread::Builder::new()
                    .name("asupersync-debug-connection".to_string())
                    .spawn(move || {
                        let _active_connection =
                            ActiveConnectionGuard::new(Arc::clone(&active_connections_for_thread));
                        let _ = panic::catch_unwind(AssertUnwindSafe(|| {
                            handle_connection(stream, &snapshot_fn);
                        }));
                    })
                    .is_err()
                {
                    active_connections.fetch_sub(1, Ordering::Relaxed);
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                // Nonblocking accept lets stop() terminate promptly even with no traffic.
                thread::sleep(std::time::Duration::from_millis(25));
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => {
                if !running.load(Ordering::Relaxed) {
                    break;
                }
                thread::sleep(std::time::Duration::from_millis(25));
            }
        }
    }
}

struct ActiveConnectionGuard {
    active_connections: Arc<AtomicUsize>,
}

impl ActiveConnectionGuard {
    fn new(active_connections: Arc<AtomicUsize>) -> Self {
        Self { active_connections }
    }
}

impl Drop for ActiveConnectionGuard {
    fn drop(&mut self) {
        self.active_connections.fetch_sub(1, Ordering::Relaxed);
    }
}

fn handle_connection(mut stream: TcpStream, snapshot_fn: &SnapshotFn) {
    let mut reader = if let Ok(read_half) = stream.try_clone() {
        BufReader::new(read_half)
    } else {
        let _ = stream.shutdown(Shutdown::Both);
        return;
    };
    let mut request_line = String::new();
    if reader.read_line(&mut request_line).is_err() {
        let _ = stream.shutdown(Shutdown::Both);
        return;
    }

    // Parse method and path from the request line.
    let parts: Vec<&str> = request_line.split_whitespace().collect();
    if parts.len() < 2 {
        let _ = stream.shutdown(Shutdown::Both);
        return;
    }
    let method = parts[0];
    let request_target = parts[1];
    let path = request_target
        .split_once('?')
        .map_or(request_target, |(path, _query)| path);
    let headers = read_headers(&mut reader);

    // Only handle GET requests.
    if method != "GET" {
        let _ = write_response(&mut stream, 405, "text/plain", b"Method Not Allowed");
        let _ = stream.shutdown(Shutdown::Both);
        return;
    }

    match path {
        "/debug" | "/debug/" => {
            let _ = write_response(
                &mut stream,
                200,
                "text/html; charset=utf-8",
                DASHBOARD_HTML.as_bytes(),
            );
        }
        "/debug/snapshot" => {
            let snapshot = snapshot_fn();
            match serde_json::to_string_pretty(&snapshot) {
                Ok(json) => {
                    let _ = write_response(&mut stream, 200, "application/json", json.as_bytes());
                }
                Err(e) => {
                    let body = format!("{{\"error\":\"{e}\"}}");
                    let _ = write_response(&mut stream, 500, "application/json", body.as_bytes());
                }
            }
        }
        "/debug/trace" => {
            let snapshot = snapshot_fn();
            match serde_json::to_string_pretty(&snapshot.recent_events) {
                Ok(json) => {
                    let _ = write_response(&mut stream, 200, "application/json", json.as_bytes());
                }
                Err(e) => {
                    let body = format!("{{\"error\":\"{e}\"}}");
                    let _ = write_response(&mut stream, 500, "application/json", body.as_bytes());
                }
            }
        }
        "/debug/ws" => {
            if let Err(err) = handle_websocket(&mut stream, &headers, snapshot_fn) {
                let body = format!("{{\"error\":\"websocket upgrade failed: {err}\"}}");
                let _ = write_response(&mut stream, 400, "application/json", body.as_bytes());
            }
        }
        _ => {
            let _ = write_response(&mut stream, 404, "text/plain", b"Not Found");
        }
    }

    let _ = stream.shutdown(Shutdown::Both);
}

fn read_headers<R: BufRead>(reader: &mut R) -> Vec<(String, String)> {
    let mut headers = Vec::with_capacity(16);
    loop {
        let mut line = String::new();
        match reader.read_line(&mut line) {
            Ok(0) | Err(_) => break,
            Ok(_) => {
                let trimmed = line.trim_end_matches(['\r', '\n']);
                if trimmed.is_empty() {
                    break;
                }
                if let Some((key, value)) = trimmed.split_once(':') {
                    headers.push((key.trim().to_ascii_lowercase(), value.trim().to_string()));
                }
            }
        }
    }
    headers
}

fn header_value<'a>(headers: &'a [(String, String)], key: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(k, _)| k == key)
        .map(|(_, v)| v.as_str())
}

fn websocket_accept_key(client_key: &str) -> String {
    let mut hasher = Sha1::new();
    hasher.update(client_key.as_bytes());
    hasher.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
    let digest = hasher.finalize();
    base64::engine::general_purpose::STANDARD.encode(digest)
}

fn write_ws_text_frame(stream: &mut TcpStream, payload: &[u8]) -> std::io::Result<()> {
    let len = payload.len();
    let mut header = [0u8; 10];
    header[0] = 0x81; // FIN + text

    let header_len = if len < 126 {
        header[1] = len as u8;
        2
    } else if u16::try_from(len).is_ok() {
        header[1] = 126;
        header[2..4].copy_from_slice(&(len as u16).to_be_bytes());
        4
    } else {
        header[1] = 127;
        header[2..10].copy_from_slice(&(len as u64).to_be_bytes());
        10
    };

    stream.write_all(&header[..header_len])?;
    stream.write_all(payload)?;
    Ok(())
}

fn handle_websocket(
    stream: &mut TcpStream,
    headers: &[(String, String)],
    snapshot_fn: &SnapshotFn,
) -> std::io::Result<()> {
    let upgrade = header_value(headers, "upgrade").unwrap_or_default();
    let connection = header_value(headers, "connection").unwrap_or_default();
    let key = header_value(headers, "sec-websocket-key")
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "missing key"))?;
    let version = header_value(headers, "sec-websocket-version").unwrap_or_default();

    if !upgrade.eq_ignore_ascii_case("websocket")
        || !connection
            .split(',')
            .any(|part| part.trim().eq_ignore_ascii_case("upgrade"))
    {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "missing websocket upgrade headers",
        ));
    }
    if version != "13" {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "unsupported websocket version",
        ));
    }

    let accept = websocket_accept_key(key.trim());
    write!(
        stream,
        "HTTP/1.1 101 Switching Protocols\r\n\
         Upgrade: websocket\r\n\
         Connection: Upgrade\r\n\
         Sec-WebSocket-Accept: {accept}\r\n\
         \r\n"
    )?;

    let snapshot = snapshot_fn();
    let payload = serde_json::to_vec(&snapshot).map_err(std::io::Error::other)?;
    write_ws_text_frame(stream, &payload)?;
    // Normal closure after one push keeps this debug endpoint lightweight.
    stream.write_all(&[0x88, 0x00])?;
    stream.flush()
}

fn write_response(
    stream: &mut TcpStream,
    status: u16,
    content_type: &str,
    body: &[u8],
) -> std::io::Result<()> {
    let status_text = match status {
        200 => "OK",
        400 => "Bad Request",
        404 => "Not Found",
        405 => "Method Not Allowed",
        500 => "Internal Server Error",
        503 => "Service Unavailable",
        501 => "Not Implemented",
        _ => "Unknown",
    };

    write!(
        stream,
        "HTTP/1.1 {status} {status_text}\r\n\
         Content-Type: {content_type}\r\n\
         Content-Length: {}\r\n\
         Connection: close\r\n\
         Access-Control-Allow-Origin: *\r\n\
         \r\n",
        body.len(),
    )?;
    stream.write_all(body)?;
    stream.flush()
}

// =========================================================================
// Dashboard HTML — loaded from assets/dashboard.html at compile time.
// The HTML is self-contained (CSS/JS inlined, no external deps) and handles
// both live mode (polling /debug/snapshot) and file mode (post-mortem).
// Refresh interval is configured via ?refresh=<ms> URL parameter.
// =========================================================================

const DASHBOARD_HTML: &str = include_str!("../../assets/dashboard.html");

// =========================================================================
// Tests
// =========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Read;

    fn test_snapshot() -> RuntimeSnapshot {
        RuntimeSnapshot {
            timestamp: 12345,
            regions: vec![],
            tasks: vec![],
            obligations: vec![],
            recent_events: vec![],
        }
    }

    #[test]
    fn server_starts_and_serves_snapshot() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0, // OS-assigned port
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                ..Default::default()
            },
        );
        server.start().expect("server should start");
        assert!(server.is_running());

        let url = server.url();
        assert!(url.contains("/debug"));

        // Fetch snapshot endpoint.
        let addr = server.local_addr.unwrap();
        let mut stream = TcpStream::connect(addr).unwrap();
        write!(
            stream,
            "GET /debug/snapshot HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(response.contains("200 OK"));
        // serde_json pretty-printing adds spaces: "timestamp": 12345
        assert!(response.contains("12345"));
        assert!(response.contains("timestamp"));

        server.stop();
    }

    #[test]
    fn server_serves_dashboard_html() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        let mut stream = TcpStream::connect(addr).unwrap();
        write!(stream, "GET /debug HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(response.contains("200 OK"));
        assert!(response.contains("Asupersync Debug Dashboard"));

        server.stop();
    }

    #[test]
    fn server_serves_dashboard_html_with_refresh_query() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                refresh_interval_secs: 7,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        let mut stream = TcpStream::connect(addr).unwrap();
        write!(
            stream,
            "GET /debug?refresh=7000 HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(response.contains("200 OK"));
        assert!(response.contains("Asupersync Debug Dashboard"));

        server.stop();
    }

    #[test]
    fn server_returns_404_for_unknown_path() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        let mut stream = TcpStream::connect(addr).unwrap();
        write!(
            stream,
            "GET /nonexistent HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(response.contains("404"));

        server.stop();
    }

    #[test]
    fn server_returns_trace_json() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        let mut stream = TcpStream::connect(addr).unwrap();
        write!(
            stream,
            "GET /debug/trace HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(response.contains("200 OK"));
        assert!(response.contains("[]")); // empty events list

        server.stop();
    }

    #[test]
    fn websocket_upgrade_and_frame_push() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        let mut stream = TcpStream::connect(addr).unwrap();
        write!(
            stream,
            "GET /debug/ws HTTP/1.1\r\n\
             Host: localhost\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n\
             Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
             Sec-WebSocket-Version: 13\r\n\
             \r\n"
        )
        .unwrap();
        stream.flush().unwrap();

        let mut buf = Vec::new();
        let n = stream.read_to_end(&mut buf).unwrap();
        let resp = &buf[..n];
        let text = String::from_utf8_lossy(resp);
        assert!(text.contains("101 Switching Protocols"), "response: {text}");
        assert!(text.contains("Sec-WebSocket-Accept"), "response: {text}");
        let header_end = resp
            .windows(4)
            .position(|w| w == b"\r\n\r\n")
            .expect("websocket header terminator should exist");
        assert!(
            n > header_end + 4 + 2,
            "expected frame bytes after websocket upgrade"
        );

        server.stop();
    }

    #[test]
    fn stop_eventually_closes_listener() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        server.stop();

        let mut listener_closed = false;
        for _ in 0..20 {
            if TcpStream::connect(addr).is_err() {
                listener_closed = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }

        assert!(
            listener_closed,
            "listener should close shortly after stop()"
        );
    }

    #[test]
    fn default_config_values() {
        let config = DebugServerConfig::default();
        assert!(config.print_url);
        assert_eq!(config.bind_addr, "127.0.0.1");
        assert_eq!(config.refresh_interval_secs, 2);
        assert_eq!(config.max_connections, 16);
    }

    #[test]
    fn url_includes_configured_refresh_query() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                refresh_interval_secs: 7,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let url = server.url();
        assert!(url.contains("/debug?refresh=7000"), "url was {url}");

        server.stop();
    }

    #[test]
    fn server_rejects_connections_over_limit() {
        let snapshot_fn: SnapshotFn = Arc::new(test_snapshot);
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                max_connections: 1,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();
        let first_stream = TcpStream::connect(addr).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));

        let mut second_stream = TcpStream::connect(addr).unwrap();
        write!(
            second_stream,
            "GET /debug HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        second_stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&second_stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(
            response.contains("503 Service Unavailable"),
            "response: {response}"
        );

        drop(first_stream);
        server.stop();
    }

    #[test]
    fn panicking_snapshot_request_does_not_leak_connection_slots() {
        let panicked_once = Arc::new(AtomicBool::new(false));
        let panicked_once_clone = Arc::clone(&panicked_once);
        let snapshot_fn: SnapshotFn = Arc::new(move || {
            assert!(
                panicked_once_clone.swap(true, Ordering::SeqCst),
                "snapshot boom"
            );
            test_snapshot()
        });
        let mut server = DebugServer::with_config(
            0,
            snapshot_fn,
            DebugServerConfig {
                print_url: false,
                max_connections: 1,
                ..Default::default()
            },
        );
        server.start().unwrap();

        let addr = server.local_addr.unwrap();

        let mut first_stream = TcpStream::connect(addr).unwrap();
        write!(
            first_stream,
            "GET /debug/snapshot HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        first_stream.flush().unwrap();
        let mut first_response = Vec::new();
        let _ = first_stream.read_to_end(&mut first_response);

        std::thread::sleep(std::time::Duration::from_millis(50));

        let mut second_stream = TcpStream::connect(addr).unwrap();
        write!(
            second_stream,
            "GET /debug HTTP/1.1\r\nHost: localhost\r\n\r\n"
        )
        .unwrap();
        second_stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&second_stream);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => response.push_str(&line),
            }
        }

        assert!(
            response.contains("200 OK"),
            "server should recover after a panicking request; response: {response}"
        );
        assert!(
            !response.contains("503 Service Unavailable"),
            "panicking request must not leak a connection slot"
        );

        server.stop();
    }

    #[test]
    fn dashboard_html_content() {
        assert!(DASHBOARD_HTML.contains("Asupersync Debug Dashboard"));
        assert!(DASHBOARD_HTML.contains("/debug/snapshot"));
        assert!(DASHBOARD_HTML.contains("CONFIG"));
    }

    #[test]
    fn debug_server_config_debug_clone() {
        let c = DebugServerConfig::default();
        let dbg = format!("{c:?}");
        assert!(dbg.contains("DebugServerConfig"));
        assert!(dbg.contains("127.0.0.1"));

        let c2 = c;
        assert_eq!(c2.bind_addr, "127.0.0.1");
        assert_eq!(c2.max_connections, 16);
        assert_eq!(c2.refresh_interval_secs, 2);
        assert!(c2.print_url);
    }
}