qrusty 0.25.2

A trusty priority queue server built with Rust
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
// tests/ws_tests.rs
//
// Integration tests for the WebSocket API (WS-0001 through WS-0016, WS-0020 through WS-0026).
// Each test spins up an in-process server bound to a random OS-assigned port,
// then connects via tokio-tungstenite so we exercise the full Axum WS stack.

use futures_util::{SinkExt, StreamExt};
use qrusty::{api::ApiServer, storage::Storage};
use reqwest::Client;
use serde_json::{json, Value};
use std::sync::Arc;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio::time::{timeout, Duration};
use tokio_tungstenite::{connect_async, tungstenite::Message as TungsteniteMessage};

// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------

/// Start a throwaway server; returns (ws_base, http_base, TempDir).
/// The TempDir must be kept alive for the duration of the test.
async fn start_test_server() -> (String, String, TempDir) {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path().to_str().unwrap()).unwrap());
    let api = ApiServer::new(storage);
    let router = api
        .router()
        .layer(tower_http::cors::CorsLayer::permissive());
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    tokio::spawn(async move {
        axum::serve(listener, router).await.unwrap();
    });
    (
        format!("ws://127.0.0.1:{}", port),
        format!("http://127.0.0.1:{}", port),
        temp_dir,
    )
}

type WsStream =
    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;

async fn ws_connect(ws_base: &str) -> WsStream {
    let url = format!("{}/ws", ws_base);
    let (ws, _) = connect_async(&url).await.unwrap();
    ws
}

async fn send(ws: &mut WsStream, frame: Value) {
    ws.send(TungsteniteMessage::Text(frame.to_string().into()))
        .await
        .unwrap();
}

/// Receive the next text frame and parse as JSON, skipping Ping/Pong frames.
/// Panics if nothing arrives within 5 seconds.
async fn recv(ws: &mut WsStream) -> Value {
    timeout(Duration::from_secs(5), async {
        loop {
            let msg = ws.next().await.expect("stream ended").expect("ws error");
            match msg {
                TungsteniteMessage::Text(t) => {
                    return serde_json::from_str(&t).expect("bad JSON");
                }
                TungsteniteMessage::Ping(_) | TungsteniteMessage::Pong(_) => continue,
                other => panic!("expected text frame, got {:?}", other),
            }
        }
    })
    .await
    .expect("recv timeout")
}

/// Create a queue via the HTTP API.
async fn http_create_queue(http_base: &str, name: &str) {
    Client::new()
        .post(format!("{}/create-queue", http_base))
        .json(&json!({"name": name, "config": {"ordering": "MaxFirst"}}))
        .send()
        .await
        .unwrap()
        .error_for_status()
        .unwrap();
}

/// Publish a message via the HTTP API; returns the assigned id.
async fn http_publish(http_base: &str, queue: &str, payload: &str) -> String {
    let resp = Client::new()
        .post(format!("{}/publish", http_base))
        .json(&json!({"queue": queue, "priority": 0, "payload": payload}))
        .send()
        .await
        .unwrap()
        .error_for_status()
        .unwrap();
    let body: Value = resp.json().await.unwrap();
    body["id"].as_str().unwrap().to_string()
}

// ---------------------------------------------------------------------------
// WS-0001 – connection upgrade
// ---------------------------------------------------------------------------

// Verifies: WS-0001, SYS-0010
#[tokio::test]
async fn test_ws_connection_upgrade() {
    let (ws_base, _http, _dir) = start_test_server().await;
    // Should connect without error.
    let mut ws = ws_connect(&ws_base).await;
    ws.close(None).await.unwrap();
}

// ---------------------------------------------------------------------------
// WS-0002 – framing: binary frames rejected with 1003
// ---------------------------------------------------------------------------

// Verifies: WS-0002
#[tokio::test]
async fn test_ws_binary_frame_rejected_with_1003() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    ws.send(TungsteniteMessage::Binary(b"raw bytes".to_vec().into()))
        .await
        .unwrap();

    let msg = timeout(Duration::from_secs(2), ws.next())
        .await
        .expect("timeout waiting for close")
        .expect("stream ended")
        .expect("ws error");

    match msg {
        TungsteniteMessage::Close(Some(frame)) => {
            assert_eq!(
                frame.code,
                tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::Unsupported
            );
        }
        other => panic!("expected close frame, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// WS-0002 – framing: invalid JSON rejected with 1007
// ---------------------------------------------------------------------------

// Verifies: WS-0002
#[tokio::test]
async fn test_ws_invalid_json_rejected_with_1007() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    ws.send(TungsteniteMessage::Text("{not valid json".into()))
        .await
        .unwrap();

    let msg = timeout(Duration::from_secs(2), ws.next())
        .await
        .expect("timeout waiting for close")
        .expect("stream ended")
        .expect("ws error");

    match msg {
        TungsteniteMessage::Close(Some(frame)) => {
            assert_eq!(
                frame.code,
                tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::Invalid
            );
        }
        other => panic!("expected close frame, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// WS-0003 / WS-0004 – req_id is echoed in ok response
// ---------------------------------------------------------------------------

// Verifies: WS-0003, WS-0004
#[tokio::test]
async fn test_ws_req_id_echoed_in_ok() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "echo-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({
            "type": "publish",
            "queue": "echo-q",
            "payload": "hello",
            "req_id": "my-request-42"
        }),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert_eq!(resp["req_id"], "my-request-42");
    assert!(resp["id"].is_string());
}

// ---------------------------------------------------------------------------
// WS-0003 / WS-0004 – response omits req_id when not provided
// ---------------------------------------------------------------------------

// Verifies: WS-0003, WS-0004
#[tokio::test]
async fn test_ws_no_req_id_omitted_in_response() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "no-rid-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "publish", "queue": "no-rid-q", "payload": "x"}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert!(resp.get("req_id").is_none(), "req_id should be absent");
}

// ---------------------------------------------------------------------------
// WS-0005 – error frame on unknown type keeps connection open
// ---------------------------------------------------------------------------

// Verifies: WS-0005
#[tokio::test]
async fn test_ws_unknown_type_returns_error_frame_and_stays_open() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "totally-unknown", "req_id": "r1"})).await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "r1");
    assert!(resp["code"].is_string());
    assert!(resp["message"].is_string());

    // Connection must still be usable.
    send(&mut ws, json!({"type": "totally-unknown"})).await;
    let resp2 = recv(&mut ws).await;
    assert_eq!(resp2["type"], "error");
}

// ---------------------------------------------------------------------------
// WS-0006 – publish success
// ---------------------------------------------------------------------------

// Verifies: WS-0006
#[tokio::test]
async fn test_ws_publish_success() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "pub-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "publish", "queue": "pub-q", "payload": "world", "priority": 5}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert!(resp["id"].is_string(), "response should include message id");
}

// ---------------------------------------------------------------------------
// WS-0006 – publish to non-existent queue → error frame, no close
// ---------------------------------------------------------------------------

// Verifies: WS-0006
#[tokio::test]
async fn test_ws_publish_nonexistent_queue_error() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "publish", "queue": "ghost-q", "payload": "x", "req_id": "r99"}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "r99");
    assert!(resp["code"].is_string());

    // Connection must still be alive.
    send(&mut ws, json!({"type": "totally-unknown"})).await;
    let still_open = recv(&mut ws).await;
    assert_eq!(still_open["type"], "error");
}

// ---------------------------------------------------------------------------
// WS-0007 / WS-0008 – subscribe then receive delivery frame
// ---------------------------------------------------------------------------

// Verifies: WS-0007, WS-0008
#[tokio::test]
async fn test_ws_subscribe_and_deliver() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "sub-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Subscribe.
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "sub-q", "req_id": "sub1"}),
    )
    .await;
    let sub_resp = recv(&mut ws).await;
    assert_eq!(sub_resp["type"], "ok");
    assert_eq!(sub_resp["req_id"], "sub1");

    // Publish a message so the poller picks it up.
    http_publish(&http_base, "sub-q", "hello-ws").await;

    // Wait for the delivery frame (poller may take up to ~100ms).
    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let frame = recv(&mut ws).await;
            if frame["type"] == "deliver" {
                return frame;
            }
        }
    })
    .await
    .expect("did not receive delivery frame in time");

    assert_eq!(delivery["type"], "deliver");
    assert_eq!(delivery["queue"], "sub-q");
    assert_eq!(delivery["payload"], "hello-ws");
    assert!(delivery["id"].is_string());
    assert!(delivery["priority"].is_number());
    assert!(delivery["created_at"].is_string());
    // Delivery frames must NOT carry req_id (WS-0008).
    assert!(
        delivery.get("req_id").is_none(),
        "delivery frame must not include req_id"
    );
}

// ---------------------------------------------------------------------------
// WS-0007 – subscribe to missing queue → error frame
// ---------------------------------------------------------------------------

// Verifies: WS-0007
#[tokio::test]
async fn test_ws_subscribe_nonexistent_queue_error() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "no-such-q", "req_id": "s1"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "s1");
}

// ---------------------------------------------------------------------------
// WS-0009 – unsubscribe stops delivery
// ---------------------------------------------------------------------------

// Verifies: WS-0009
#[tokio::test]
async fn test_ws_unsubscribe_stops_delivery() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "unsub-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe", "queue": "unsub-q"})).await;
    let _ = recv(&mut ws).await; // ok

    send(
        &mut ws,
        json!({"type": "unsubscribe", "queue": "unsub-q", "req_id": "u1"}),
    )
    .await;
    let unsub_resp = recv(&mut ws).await;
    assert_eq!(unsub_resp["type"], "ok");
    assert_eq!(unsub_resp["req_id"], "u1");

    // Publish; should NOT receive a delivery frame since we unsubscribed.
    http_publish(&http_base, "unsub-q", "should-not-arrive").await;

    let no_delivery = timeout(Duration::from_millis(400), ws.next()).await;
    // Expect a timeout (None), meaning nothing arrived.
    assert!(
        no_delivery.is_err(),
        "should not have received a frame after unsubscribe"
    );
}

// ---------------------------------------------------------------------------
// WS-0010 – multi-queue subscriptions on one connection
// ---------------------------------------------------------------------------

// Verifies: WS-0010
#[tokio::test]
async fn test_ws_multi_queue_subscribe() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "mq-alpha").await;
    http_create_queue(&http_base, "mq-beta").await;
    let mut ws = ws_connect(&ws_base).await;

    // Subscribe to both queues.
    send(&mut ws, json!({"type": "subscribe", "queue": "mq-alpha"})).await;
    let _ = recv(&mut ws).await; // ok
    send(&mut ws, json!({"type": "subscribe", "queue": "mq-beta"})).await;
    let _ = recv(&mut ws).await; // ok

    // Publish to each queue.
    http_publish(&http_base, "mq-alpha", "from-alpha").await;
    http_publish(&http_base, "mq-beta", "from-beta").await;

    // Collect two delivery frames (order may vary).
    let mut queues_seen = std::collections::HashSet::new();
    for _ in 0..2 {
        let frame = timeout(Duration::from_secs(3), async {
            loop {
                let f = recv(&mut ws).await;
                if f["type"] == "deliver" {
                    return f;
                }
            }
        })
        .await
        .expect("timeout waiting for delivery");
        queues_seen.insert(frame["queue"].as_str().unwrap().to_string());
    }

    assert!(
        queues_seen.contains("mq-alpha"),
        "missing mq-alpha delivery"
    );
    assert!(queues_seen.contains("mq-beta"), "missing mq-beta delivery");
}

// ---------------------------------------------------------------------------
// WS-0011 – ack removes message
// ---------------------------------------------------------------------------

// Verifies: WS-0011
#[tokio::test]
async fn test_ws_ack_removes_message() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "ack-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe", "queue": "ack-q"})).await;
    let _ = recv(&mut ws).await; // ok

    http_publish(&http_base, "ack-q", "ack-me").await;

    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .unwrap();

    let msg_id = delivery["id"].as_str().unwrap().to_string();

    send(
        &mut ws,
        json!({"type": "ack", "queue": "ack-q", "id": msg_id, "req_id": "a1"}),
    )
    .await;

    let ack_resp = recv(&mut ws).await;
    assert_eq!(ack_resp["type"], "ok");
    assert_eq!(ack_resp["req_id"], "a1");

    // Queue should now be empty.
    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/ack-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(stats["total"], 0, "message should be gone after ack");
}

// ---------------------------------------------------------------------------
// WS-0012 – nack unlocks message
// ---------------------------------------------------------------------------

// Verifies: WS-0012
#[tokio::test]
async fn test_ws_nack_unlocks_message() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "nack-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe", "queue": "nack-q"})).await;
    let _ = recv(&mut ws).await; // ok

    http_publish(&http_base, "nack-q", "nack-me").await;

    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .unwrap();

    let msg_id = delivery["id"].as_str().unwrap().to_string();

    send(
        &mut ws,
        json!({"type": "nack", "queue": "nack-q", "id": msg_id, "req_id": "n1"}),
    )
    .await;

    // The subscriber is still active, so the server may re-deliver the
    // nacked message before (or instead of) the nack `ok` response.
    // Loop until we see the `ok` for req_id "n1", discarding any
    // interleaved `deliver` frames.
    let nack_resp = loop {
        let f = recv(&mut ws).await;
        if f["type"] == "ok" {
            break f;
        }
        assert_eq!(f["type"], "deliver", "unexpected frame: {f}");
    };
    assert_eq!(nack_resp["req_id"], "n1");

    // Unsubscribe so the server won't immediately re-deliver the nacked
    // message (which would lock it again and make "available" == 0).
    send(
        &mut ws,
        json!({"type": "unsubscribe", "queue": "nack-q", "req_id": "u1"}),
    )
    .await;
    // Drain until we see the unsubscribe ok (discarding any deliver frames).
    loop {
        let f = recv(&mut ws).await;
        if f["type"] == "ok" && f["req_id"] == "u1" {
            break;
        }
    }

    // Message should be unlocked (available).
    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/nack-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert!(
        stats["available"].as_u64().unwrap_or(0) > 0,
        "message should be back in the queue after nack"
    );
}

// ---------------------------------------------------------------------------
// WS-0013 – batch-ack
// ---------------------------------------------------------------------------

// Verifies: WS-0013
#[tokio::test]
async fn test_ws_batch_ack() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "batch-ack-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Publish two messages.
    http_publish(&http_base, "batch-ack-q", "m1").await;
    http_publish(&http_base, "batch-ack-q", "m2").await;

    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "batch-ack-q"}),
    )
    .await;
    let _ = recv(&mut ws).await; // ok

    // Collect two delivery frames.
    let mut ids = vec![];
    for _ in 0..2 {
        let f = timeout(Duration::from_secs(3), async {
            loop {
                let f = recv(&mut ws).await;
                if f["type"] == "deliver" {
                    return f;
                }
            }
        })
        .await
        .unwrap();
        ids.push(f["id"].as_str().unwrap().to_string());
    }

    send(
        &mut ws,
        json!({"type": "batch-ack", "queue": "batch-ack-q", "ids": ids, "req_id": "ba1"}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert_eq!(resp["req_id"], "ba1");
    assert_eq!(resp["acked"], 2, "both messages should be acked");
}

// ---------------------------------------------------------------------------
// WS-0014 – batch-nack
// ---------------------------------------------------------------------------

// Verifies: WS-0014
#[tokio::test]
async fn test_ws_batch_nack() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "batch-nack-q").await;
    let mut ws = ws_connect(&ws_base).await;

    http_publish(&http_base, "batch-nack-q", "n1").await;
    http_publish(&http_base, "batch-nack-q", "n2").await;

    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "batch-nack-q"}),
    )
    .await;
    let _ = recv(&mut ws).await; // ok

    let mut ids = vec![];
    for _ in 0..2 {
        let f = timeout(Duration::from_secs(3), async {
            loop {
                let f = recv(&mut ws).await;
                if f["type"] == "deliver" {
                    return f;
                }
            }
        })
        .await
        .unwrap();
        ids.push(f["id"].as_str().unwrap().to_string());
    }

    send(
        &mut ws,
        json!({"type": "batch-nack", "queue": "batch-nack-q", "ids": ids, "req_id": "bn1"}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert_eq!(resp["req_id"], "bn1");
    // unlocked + dropped = total messages nacked
    let unlocked = resp["unlocked"].as_u64().unwrap_or(0);
    let dropped = resp["dropped"].as_u64().unwrap_or(0);
    assert_eq!(
        unlocked + dropped,
        2,
        "all messages should be accounted for"
    );
}

// ---------------------------------------------------------------------------
// WS-0016 – connection close releases subscriptions (no crash)
// ---------------------------------------------------------------------------

// Verifies: WS-0016
#[tokio::test]
async fn test_ws_connection_close_releases_subscriptions() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "close-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe", "queue": "close-q"})).await;
    let _ = recv(&mut ws).await; // ok

    // Explicitly close.
    ws.close(None).await.unwrap();

    // Brief pause so the server task can clean up.
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Server should still be healthy (didn't crash).
    let status = Client::new()
        .get(format!("{}/health", http_base))
        .send()
        .await
        .unwrap()
        .status();
    assert_eq!(status, 200);
}

// ---------------------------------------------------------------------------
// WS-0005 – error frame echoes req_id
// ---------------------------------------------------------------------------

// Verifies: WS-0005
#[tokio::test]
async fn test_ws_error_frame_echoes_req_id() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "nonexistent-q", "req_id": "err-123"}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "err-123");
    assert!(resp["code"].is_string());
    assert!(resp["message"].is_string());
}

// ---------------------------------------------------------------------------
// WS-0006 – publish missing required field → error frame
// ---------------------------------------------------------------------------

// Verifies: WS-0006
#[tokio::test]
async fn test_ws_publish_missing_queue_field() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    // No "queue" field in the publish frame.
    send(&mut ws, json!({"type": "publish", "payload": "oops"})).await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
}

// ---------------------------------------------------------------------------
// WS-0020 – renew extends the message lock
// ---------------------------------------------------------------------------

// Verifies: WS-0020
#[tokio::test]
async fn test_ws_renew_extends_lock() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "renew-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe", "queue": "renew-q"})).await;
    let _ = recv(&mut ws).await; // ok

    http_publish(&http_base, "renew-q", "renew-me").await;

    // Wait for delivery to get the locked message id.
    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .expect("did not receive delivery frame in time");

    let msg_id = delivery["id"].as_str().unwrap().to_string();

    // Renew the lock – should succeed with "ok".
    send(
        &mut ws,
        json!({"type": "renew", "queue": "renew-q", "id": msg_id, "req_id": "rn1"}),
    )
    .await;

    let renew_resp = recv(&mut ws).await;
    assert_eq!(renew_resp["type"], "ok");
    assert_eq!(renew_resp["req_id"], "rn1");

    // Connection must still be open.
    send(
        &mut ws,
        json!({"type": "ack", "queue": "renew-q", "id": msg_id}),
    )
    .await;
    let ack_resp = recv(&mut ws).await;
    assert_eq!(ack_resp["type"], "ok");
}

// Verifies: WS-0020
#[tokio::test]
async fn test_ws_renew_not_locked_returns_error() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "renew-err-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Publish a message but do not subscribe – message is unlocked.
    let msg_id = http_publish(&http_base, "renew-err-q", "not-locked").await;

    // Attempt renew on a message this connection doesn't hold a lock on.
    send(
        &mut ws,
        json!({"type": "renew", "queue": "renew-err-q", "id": msg_id, "req_id": "rn2"}),
    )
    .await;

    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["code"], "not_locked");
    assert_eq!(resp["req_id"], "rn2");

    // Connection must remain open after the error.
    send(&mut ws, json!({"type": "totally-unknown"})).await;
    let still_open = recv(&mut ws).await;
    assert_eq!(still_open["type"], "error");
}

// WS publish and ack operations must update the shared rate counters so that
// /queue-stats reports non-zero publish_rate_per_sec and ack_rate_per_sec.
// Verifies: WS-0021
#[tokio::test]
async fn test_ws_operations_update_rate_counters() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "rate-ws").await;

    // First /queue-stats call establishes the baseline snapshot (all zeros).
    let _: Value = Client::new()
        .get(format!("{}/queue-stats/rate-ws", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();

    let mut ws = ws_connect(&ws_base).await;

    // Publish 3 messages via the WebSocket API.
    for i in 0..3u64 {
        send(
            &mut ws,
            json!({"type": "publish", "queue": "rate-ws", "priority": i, "payload": format!("msg-{}", i)}),
        )
        .await;
        let resp = recv(&mut ws).await;
        assert_eq!(resp["type"], "ok", "publish frame {i} failed: {resp}");
    }

    // Subscribe so the server starts delivering.
    send(&mut ws, json!({"type": "subscribe", "queue": "rate-ws"})).await;
    let sub_resp = recv(&mut ws).await;
    assert_eq!(sub_resp["type"], "ok");

    // Receive all 3 deliveries and ack each one.
    // After sending an ack the next frame may be another delivery (subscriber
    // is racing), so we loop until we see the "ok" ack response.
    let mut pending_acks = 0u32;
    let mut acked = 0u32;
    let total = 3u32;

    while acked < total {
        let f = timeout(Duration::from_secs(5), recv(&mut ws))
            .await
            .expect("timed out waiting for deliver/ok frame");

        match f["type"].as_str().unwrap_or("") {
            "deliver" => {
                let msg_id = f["id"].as_str().unwrap().to_owned();
                send(
                    &mut ws,
                    json!({"type": "ack", "queue": "rate-ws", "id": msg_id}),
                )
                .await;
                pending_acks += 1;
            }
            "ok" => {
                assert!(pending_acks > 0, "unexpected ok with no pending acks");
                pending_acks -= 1;
                acked += 1;
            }
            other => panic!("unexpected frame type: {other} — {f}"),
        }
    }

    // Poll until the background sampler (1 Hz) picks up the activity.
    // Rates are stored in the metrics ring-buffer; the sampler fires within
    // ~1 second of seeding the baseline on first activity.
    let deadline = std::time::Instant::now() + Duration::from_secs(3);
    let mut pub_rate = 0.0f64;
    let mut ack_rate = 0.0f64;
    while std::time::Instant::now() < deadline {
        let stats: Value = Client::new()
            .get(format!("{}/queue-stats/rate-ws", http_base))
            .send()
            .await
            .unwrap()
            .json()
            .await
            .unwrap();
        pub_rate = stats["publish_rate_per_sec"].as_f64().unwrap_or(0.0);
        ack_rate = stats["ack_rate_per_sec"].as_f64().unwrap_or(0.0);
        if pub_rate > 0.0 && ack_rate > 0.0 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    assert!(
        pub_rate > 0.0,
        "publish_rate_per_sec must be non-zero after WS publishes; got {pub_rate}"
    );
    assert!(
        ack_rate > 0.0,
        "ack_rate_per_sec must be non-zero after WS acks; got {ack_rate}"
    );
}

// ---------------------------------------------------------------------------
// WS-0024 – no_reply suppresses server response
// ---------------------------------------------------------------------------

// Verifies: WS-0024
#[tokio::test]
async fn test_ws_no_reply_suppresses_response() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "noreply-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Publish a message so we have something to ack.
    http_publish(&http_base, "noreply-q", "msg").await;

    // Subscribe, consume the ok and then wait for the delivery.
    send(&mut ws, json!({"type": "subscribe", "queue": "noreply-q"})).await;
    let _ = recv(&mut ws).await; // subscribe ok

    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .unwrap();
    let msg_id = delivery["id"].as_str().unwrap().to_string();

    // Unsubscribe first so no redelivery frames arrive.
    send(
        &mut ws,
        json!({"type": "unsubscribe", "queue": "noreply-q"}),
    )
    .await;
    let _ = recv(&mut ws).await; // unsubscribe ok

    // Ack with no_reply: true — server should NOT send a response.
    send(
        &mut ws,
        json!({
            "type": "ack",
            "queue": "noreply-q",
            "id": msg_id,
            "no_reply": true
        }),
    )
    .await;

    // Send a probe frame; its response should be the NEXT frame we receive
    // (i.e. no ack response appeared between the ack send and the probe).
    send(
        &mut ws,
        json!({"type": "totally-unknown", "req_id": "probe"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(
        resp["req_id"], "probe",
        "no_reply ack should not produce a response; got: {resp}"
    );

    // Verify the ack was actually processed.
    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/noreply-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(
        stats["total"], 0,
        "message should be acked despite no_reply"
    );
}

// ---------------------------------------------------------------------------
// WS-0023 – credit-based flow control
// ---------------------------------------------------------------------------

// Verifies: WS-0023
#[tokio::test]
async fn test_ws_credit_flow_control() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "credit-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Publish 5 messages.
    for i in 0..5 {
        http_publish(&http_base, "credit-q", &format!("msg-{}", i)).await;
    }

    // Subscribe with credits=2.
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "credit-q", "credits": 2, "req_id": "sub1"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert_eq!(resp["req_id"], "sub1");

    // Should receive exactly 2 deliveries.
    for _ in 0..2 {
        let f = timeout(Duration::from_secs(3), async {
            loop {
                let f = recv(&mut ws).await;
                if f["type"] == "deliver" {
                    return f;
                }
            }
        })
        .await
        .expect("expected delivery");
        assert_eq!(f["queue"], "credit-q");
    }

    // Should NOT receive a 3rd delivery within a reasonable time.
    let no_more = timeout(Duration::from_millis(500), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await;
    assert!(
        no_more.is_err(),
        "should not receive more than 2 deliveries"
    );

    // Replenish 2 credits.
    send(
        &mut ws,
        json!({"type": "credit", "queue": "credit-q", "credits": 2, "req_id": "cr1"}),
    )
    .await;
    let cr_resp = recv(&mut ws).await;
    assert_eq!(cr_resp["type"], "ok");
    assert_eq!(cr_resp["req_id"], "cr1");

    // Should now receive 2 more deliveries.
    for _ in 0..2 {
        let f = timeout(Duration::from_secs(3), async {
            loop {
                let f = recv(&mut ws).await;
                if f["type"] == "deliver" {
                    return f;
                }
            }
        })
        .await
        .expect("expected delivery after credit replenishment");
        assert_eq!(f["queue"], "credit-q");
    }
}

// Verifies: WS-0023
#[tokio::test]
async fn test_ws_subscribe_without_credits_is_unlimited() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "unlim-q").await;
    let mut ws = ws_connect(&ws_base).await;

    for i in 0..5 {
        http_publish(&http_base, "unlim-q", &format!("msg-{}", i)).await;
    }

    // Subscribe without credits field — unlimited delivery.
    send(&mut ws, json!({"type": "subscribe", "queue": "unlim-q"})).await;
    let _ = recv(&mut ws).await; // ok

    // Should receive all 5.
    for _ in 0..5 {
        let f = timeout(Duration::from_secs(5), async {
            loop {
                let f = recv(&mut ws).await;
                if f["type"] == "deliver" {
                    return f;
                }
            }
        })
        .await
        .expect("expected delivery");
        assert_eq!(f["queue"], "unlim-q");
    }
}

// Verifies: WS-0023
#[tokio::test]
async fn test_ws_credit_on_unsubscribed_queue_returns_error() {
    let (ws_base, _http_base, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "credit", "queue": "no-such-sub", "credits": 5, "req_id": "c1"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["code"], "not_subscribed");
}

// ---------------------------------------------------------------------------
// WS-0025 – public send_frame via WsSession
// ---------------------------------------------------------------------------

// Verifies: WS-0025
#[tokio::test]
async fn test_ws_session_send_frame_public() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "sf-q").await;
    let session = qrusty_client::ws::WsSession::connect(&format!(
        "ws://127.0.0.1:{}",
        extract_port(&ws_base)
    ))
    .await
    .unwrap();

    // send_frame is public and should succeed (fire-and-forget publish).
    session
        .send_frame(json!({
            "type": "publish",
            "queue": "sf-q",
            "payload": "raw-frame",
            "priority": 0,
        }))
        .await
        .unwrap();

    // Give the server a moment to process.
    tokio::time::sleep(Duration::from_millis(200)).await;

    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/sf-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(
        stats["total"], 1,
        "send_frame should have published a message"
    );

    session.close().await.unwrap();
}

// ---------------------------------------------------------------------------
// WS-0026 – request timeout via WsSession
// ---------------------------------------------------------------------------

// Verifies: WS-0026
#[tokio::test]
async fn test_ws_session_request_timeout() {
    // Spin up a raw TCP listener that accepts the WS handshake but never
    // sends any application-level response.  This guarantees a timeout.
    use tokio_tungstenite::accept_async;

    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();

    tokio::spawn(async move {
        if let Ok((stream, _)) = listener.accept().await {
            // Complete the WebSocket handshake, then hold the connection.
            let _ws = accept_async(stream).await;
            tokio::time::sleep(Duration::from_secs(600)).await;
        }
    });

    let session = qrusty_client::ws::WsSession::connect_with_timeout(
        &format!("ws://127.0.0.1:{}", port),
        Duration::from_millis(100),
    )
    .await
    .unwrap();

    let result = session.publish("any-q", "hello", None).await;
    assert!(
        matches!(
            result,
            Err(qrusty_client::error::QrustyClientError::RequestTimeout(_))
        ),
        "expected RequestTimeout, got: {:?}",
        result,
    );
}

// ---------------------------------------------------------------------------
// WS-0024 – ack_noreply / nack_noreply via WsSession
// ---------------------------------------------------------------------------

// Verifies: WS-0024
#[tokio::test]
async fn test_ws_session_ack_noreply() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "noreply-client-q").await;

    let session = qrusty_client::ws::WsSession::connect(&format!(
        "ws://127.0.0.1:{}",
        extract_port(&ws_base)
    ))
    .await
    .unwrap();

    session
        .publish("noreply-client-q", "msg", None)
        .await
        .unwrap();
    let mut rx = session.subscribe("noreply-client-q").await.unwrap();

    let msg = tokio::time::timeout(Duration::from_secs(3), rx.recv())
        .await
        .expect("delivery timeout")
        .expect("channel closed")
        .expect("delivery error");

    // ack_noreply should return immediately.
    session.ack_noreply(&msg.queue, &msg.id).await.unwrap();

    tokio::time::sleep(Duration::from_millis(200)).await;

    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/noreply-client-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(stats["total"], 0, "message should be acked via ack_noreply");
}

// ---------------------------------------------------------------------------
// WS-0017 – qrusty_client WsSession full public-API surface
// ---------------------------------------------------------------------------

// Exercises every WsSession method the requirement enumerates against a live
// server: connect, publish (returns id), subscribe (yields DeliveredMessage),
// ack, nack, batch_ack, batch_nack, unsubscribe, close — plus the
// DeliveredMessage struct fields.  Each call returning Ok witnesses that the
// method exists with the specified signature and round-trips correctly.
// Verifies: WS-0017
#[tokio::test]
async fn test_ws_session_full_api_round_trip() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "wsapi-q").await;

    let session = qrusty_client::ws::WsSession::connect(&format!(
        "ws://127.0.0.1:{}",
        extract_port(&ws_base)
    ))
    .await
    .unwrap();

    // publish returns the assigned message id.
    for i in 0..4 {
        let id = session
            .publish("wsapi-q", &format!("payload-{i}"), None)
            .await
            .unwrap();
        assert!(!id.is_empty(), "publish must return a non-empty message id");
    }

    // subscribe yields DeliveredMessage values; receiving locks each message.
    let mut rx = session.subscribe("wsapi-q").await.unwrap();
    let mut delivered = Vec::new();
    for _ in 0..4 {
        let msg = tokio::time::timeout(Duration::from_secs(5), rx.recv())
            .await
            .expect("delivery timeout")
            .expect("subscription channel closed")
            .expect("delivery error");
        delivered.push(msg);
    }

    // DeliveredMessage exposes queue / id / payload / priority / created_at.
    let first = &delivered[0];
    assert_eq!(first.queue, "wsapi-q");
    assert!(!first.id.is_empty());
    assert!(first.payload.starts_with("payload-"));
    let _ = &first.priority;
    let _ = &first.created_at;

    // Single ack and single nack.
    session
        .ack(&delivered[0].queue, &delivered[0].id)
        .await
        .unwrap();
    session
        .nack(&delivered[1].queue, &delivered[1].id)
        .await
        .unwrap();

    // batch_ack returns the count acked.
    let acked = session
        .batch_ack("wsapi-q", &[delivered[2].id.as_str()])
        .await
        .unwrap();
    assert_eq!(acked, 1, "batch_ack should ack the one locked message");

    // batch_nack returns (unlocked, dropped).
    let (unlocked, _dropped) = session
        .batch_nack("wsapi-q", &[delivered[3].id.as_str()])
        .await
        .unwrap();
    assert_eq!(
        unlocked, 1,
        "batch_nack should unlock the one locked message"
    );

    // unsubscribe and close complete the API surface.
    session.unsubscribe("wsapi-q").await.unwrap();
    session.close().await.unwrap();
}

// ---------------------------------------------------------------------------
// WS-0023 – WsSession credit API
// ---------------------------------------------------------------------------

// Verifies: WS-0023
#[tokio::test]
async fn test_ws_session_credit_flow_control() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "credit-session-q").await;

    let session = qrusty_client::ws::WsSession::connect(&format!(
        "ws://127.0.0.1:{}",
        extract_port(&ws_base)
    ))
    .await
    .unwrap();

    for i in 0..4 {
        session
            .publish("credit-session-q", &format!("msg-{}", i), None)
            .await
            .unwrap();
    }

    let mut rx = session
        .subscribe_with_credits("credit-session-q", Some(2))
        .await
        .unwrap();

    // Should receive 2.
    for _ in 0..2 {
        let msg = tokio::time::timeout(Duration::from_secs(3), rx.recv())
            .await
            .expect("delivery timeout")
            .expect("channel closed")
            .expect("delivery error");
        session.ack_noreply(&msg.queue, &msg.id).await.unwrap();
    }

    // Third should not arrive.
    let no_more = tokio::time::timeout(Duration::from_millis(500), rx.recv()).await;
    assert!(
        no_more.is_err(),
        "should not receive more than 2 deliveries"
    );

    // Grant 2 more credits.
    session.grant_credits("credit-session-q", 2).await.unwrap();

    // Should receive 2 more.
    for _ in 0..2 {
        let msg = tokio::time::timeout(Duration::from_secs(3), rx.recv())
            .await
            .expect("delivery timeout after credit grant")
            .expect("channel closed")
            .expect("delivery error");
        session.ack_noreply(&msg.queue, &msg.id).await.unwrap();
    }
}

// ---------------------------------------------------------------------------
// WS-0015 – server-side ping timeout closes with 1001
// ---------------------------------------------------------------------------

/// Perform a bare WebSocket handshake over a raw TCP stream and return it.
/// The caller controls all subsequent reads/writes — no auto-pong.
async fn raw_ws_upgrade(addr: &str) -> tokio::net::TcpStream {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
    let req = format!(
        "GET /ws HTTP/1.1\r\nHost: {addr}\r\nUpgrade: websocket\r\n\
         Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
         Sec-WebSocket-Version: 13\r\n\r\n"
    );
    stream.write_all(req.as_bytes()).await.unwrap();

    // Drain HTTP response headers.
    let mut buf = Vec::new();
    let mut b = [0u8; 1];
    loop {
        stream.read_exact(&mut b).await.unwrap();
        buf.push(b[0]);
        if buf.ends_with(b"\r\n\r\n") {
            break;
        }
    }
    let headers = String::from_utf8_lossy(&buf);
    assert!(
        headers.contains("101"),
        "expected 101 Switching Protocols, got: {headers}"
    );
    stream
}

/// Read one unmasked WebSocket frame and return `(opcode, payload)`.
async fn read_raw_ws_frame(stream: &mut tokio::net::TcpStream) -> (u8, Vec<u8>) {
    use tokio::io::AsyncReadExt;
    let mut hdr = [0u8; 2];
    stream.read_exact(&mut hdr).await.unwrap();
    let opcode = hdr[0] & 0x0F;
    let len_byte = (hdr[1] & 0x7F) as usize;
    let payload_len = match len_byte {
        126 => {
            let mut e = [0u8; 2];
            stream.read_exact(&mut e).await.unwrap();
            u16::from_be_bytes(e) as usize
        }
        127 => {
            let mut e = [0u8; 8];
            stream.read_exact(&mut e).await.unwrap();
            u64::from_be_bytes(e) as usize
        }
        n => n,
    };
    let mut payload = vec![0u8; payload_len];
    if payload_len > 0 {
        stream.read_exact(&mut payload).await.unwrap();
    }
    (opcode, payload)
}

// Verifies: WS-0015
#[tokio::test]
async fn test_ws_ping_timeout_closes_with_1001() {
    // Use very short intervals so the test completes quickly.
    // Safety: these env vars are only read inside handle_connection() at
    // connection setup time; no other concurrent test uses them.
    #[allow(deprecated)]
    unsafe {
        std::env::set_var("WS_PING_INTERVAL_SECS", "1");
        std::env::set_var("WS_PING_TIMEOUT_SECS", "1");
    }

    let (ws_base, _http_base, _dir) = start_test_server().await;
    // Strip "ws://" prefix to get "host:port".
    let addr = ws_base.trim_start_matches("ws://");
    let mut stream = raw_ws_upgrade(addr).await;

    // Read frames without sending any pongs.  The server tracks last_pong
    // from connection time.  After ping_iv elapses with no pong received,
    // on the next tick (ping_iv + ping_to later) it closes with 1001 (AWAY).
    // With intervals of 1 s each that should happen by ~3 s; allow 8 s total.
    let close_code = tokio::time::timeout(Duration::from_secs(8), async {
        loop {
            let (opcode, payload) = read_raw_ws_frame(&mut stream).await;
            match opcode {
                0x8 => {
                    // Close frame — extract 2-byte status code.
                    return if payload.len() >= 2 {
                        u16::from_be_bytes([payload[0], payload[1]])
                    } else {
                        0u16
                    };
                }
                0x9 => {} // Ping — intentionally not responded to
                _ => {}   // other frames
            }
        }
    })
    .await
    .expect("timed out: server did not send Close within 8 s");

    assert_eq!(close_code, 1001, "expected close code 1001 (Going Away)");

    #[allow(deprecated)]
    unsafe {
        std::env::remove_var("WS_PING_INTERVAL_SECS");
        std::env::remove_var("WS_PING_TIMEOUT_SECS");
    }
}

// ---------------------------------------------------------------------------
// Helpers for WsSession integration tests
// ---------------------------------------------------------------------------

/// Extract the port from a base URL like "ws://127.0.0.1:12345".
fn extract_port(base: &str) -> u16 {
    base.rsplit(':').next().unwrap().parse().unwrap()
}

// ---------------------------------------------------------------------------
// Additional coverage tests
// ---------------------------------------------------------------------------

/// Start a server that has a LogBuffer attached (for subscribe-logs tests).
async fn start_test_server_with_logs() -> (String, String, qrusty::log_buffer::LogBuffer, TempDir) {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path().to_str().unwrap()).unwrap());
    let log_buffer = qrusty::log_buffer::LogBuffer::new();
    let api = ApiServer::new(storage).with_log_buffer(log_buffer.clone());
    let router = api
        .router()
        .layer(tower_http::cors::CorsLayer::permissive());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    tokio::spawn(async move {
        axum::serve(listener, router).await.unwrap();
    });
    (
        format!("ws://127.0.0.1:{}", port),
        format!("http://127.0.0.1:{}", port),
        log_buffer,
        temp_dir,
    )
}

// Verifies: WS-0022
#[tokio::test]
async fn test_ws_subscribe_logs_delivers_live_entries() {
    let (ws_base, _http, log_buffer, _dir) = start_test_server_with_logs().await;
    let mut ws = ws_connect(&ws_base).await;

    // Push a history entry before subscribing so the history path is exercised.
    log_buffer.push_sync("INFO", "history-entry");

    send(&mut ws, json!({"type": "subscribe-logs", "req_id": "sl1"})).await;
    let resp = recv(&mut ws).await;
    assert_eq!(
        resp["type"], "ok",
        "subscribe-logs should return ok: {resp}"
    );

    // The history entry should arrive as a log frame immediately after subscribe.
    let log_frame = timeout(Duration::from_secs(2), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "log" {
                return f;
            }
        }
    })
    .await
    .expect("expected log frame from history");

    assert_eq!(log_frame["type"], "log");
    assert!(log_frame["message"].is_string());
    assert!(log_frame["timestamp"].is_string());
    assert!(log_frame["level"].is_string());

    // Push a live entry and verify it is forwarded too.
    log_buffer.push_sync("WARN", "live-entry");
    let live_frame = timeout(Duration::from_secs(2), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "log" && f["message"] == "live-entry" {
                return f;
            }
        }
    })
    .await
    .expect("expected live log frame");
    assert_eq!(live_frame["level"], "WARN");
}

// Regression: large history must not deadlock the WS main loop.
//
// Before the fix, handle_subscribe_logs performed the history replay inline
// via log_tx.send(entry).await. log_tx has capacity 256; the main select!
// loop drains log_rx from a different branch that cannot fire while
// handle_subscribe_logs is awaiting. With history > 256 entries, entry #256
// blocked forever and no log frames reached the client. This is what caused
// the UI Logs tab to appear "connected" but show nothing after navigating
// away and back.
//
// Verifies: WS-0022
#[tokio::test]
async fn test_ws_subscribe_logs_with_large_history_does_not_deadlock() {
    let (ws_base, _http, log_buffer, _dir) = start_test_server_with_logs().await;
    let mut ws = ws_connect(&ws_base).await;

    // Push well past log_tx capacity (256) — up to HISTORY_CAPACITY=1000.
    for i in 0..500 {
        log_buffer.push_sync("INFO", format!("hist-{i}"));
    }

    send(
        &mut ws,
        json!({"type": "subscribe-logs", "req_id": "sl-big"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");

    // We should be able to receive all 500 history entries without timing out.
    // Use a generous timeout because draining + serializing 500 frames takes
    // a moment, but far less than the 5 seconds we allow.
    let first = b"hist-0".to_vec();
    let last = b"hist-499".to_vec();
    let mut saw_first = false;
    let mut saw_last = false;
    timeout(Duration::from_secs(5), async {
        while !(saw_first && saw_last) {
            let f = recv(&mut ws).await;
            if f["type"] != "log" {
                continue;
            }
            let msg = f["message"].as_str().unwrap_or("");
            if msg.as_bytes() == first.as_slice() {
                saw_first = true;
            }
            if msg.as_bytes() == last.as_slice() {
                saw_last = true;
            }
        }
    })
    .await
    .expect("history replay stalled — handle_subscribe_logs deadlocked");

    // A fresh live event should still be forwarded after the bulk replay.
    log_buffer.push_sync("WARN", "after-large-history");
    timeout(Duration::from_secs(2), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "log" && f["message"] == "after-large-history" {
                return;
            }
        }
    })
    .await
    .expect("live entry after large-history replay did not arrive");
}

// Verifies: WS-0022
#[tokio::test]
async fn test_ws_unsubscribe_logs_stops_delivery() {
    let (ws_base, _http, log_buffer, _dir) = start_test_server_with_logs().await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe-logs"})).await;
    let _ = recv(&mut ws).await; // ok

    send(
        &mut ws,
        json!({"type": "unsubscribe-logs", "req_id": "ul1"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "ok");
    assert_eq!(resp["req_id"], "ul1");

    // Push a log entry after unsubscribing — should NOT arrive.
    log_buffer.push_sync("INFO", "after-unsub");
    let no_log = timeout(Duration::from_millis(300), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "log" {
                return f;
            }
        }
    })
    .await;
    assert!(
        no_log.is_err(),
        "should not receive log frames after unsubscribe"
    );
}

// Verifies: WS-0007
#[tokio::test]
async fn test_ws_subscribe_same_queue_twice_is_ok() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "dup-sub-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // First subscribe
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "dup-sub-q", "req_id": "s1"}),
    )
    .await;
    let r1 = recv(&mut ws).await;
    assert_eq!(r1["type"], "ok");

    // Second subscribe to the same queue — silently ignored, still returns ok.
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "dup-sub-q", "req_id": "s2"}),
    )
    .await;
    let r2 = recv(&mut ws).await;
    assert_eq!(r2["type"], "ok", "duplicate subscribe should be idempotent");
    assert_eq!(r2["req_id"], "s2");
}

// Verifies: WS-0006
#[tokio::test]
async fn test_ws_publish_missing_payload_field() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "miss-payload-q").await;
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "publish", "queue": "miss-payload-q", "req_id": "r1"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "r1");
}

// Verifies: WS-0007
#[tokio::test]
async fn test_ws_subscribe_missing_queue_field() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"type": "subscribe", "req_id": "r2"})).await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "r2");
}

// Covers the dispatch "missing 'type' field" path.
#[tokio::test]
async fn test_ws_frame_missing_type_field_returns_error() {
    let (ws_base, _http, _dir) = start_test_server().await;
    let mut ws = ws_connect(&ws_base).await;

    send(&mut ws, json!({"req_id": "r3"})).await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "r3");
    assert_eq!(resp["code"], "invalid_request");
}

// Verifies that subscribe-logs returns an error when no log buffer is configured.
#[tokio::test]
async fn test_ws_subscribe_logs_without_buffer_returns_error() {
    let (ws_base, _http, _dir) = start_test_server().await; // no log buffer
    let mut ws = ws_connect(&ws_base).await;

    send(
        &mut ws,
        json!({"type": "subscribe-logs", "req_id": "sl-err"}),
    )
    .await;
    let resp = recv(&mut ws).await;
    assert_eq!(resp["type"], "error");
    assert_eq!(resp["req_id"], "sl-err");
}

// ---------------------------------------------------------------------------
// WS-0007 / WS-0020 – lock_timeout_secs on subscribe and renew
// ---------------------------------------------------------------------------

/// Subscribe with a custom lock_timeout_secs (120s).  Verify the delivered
/// message has a lock expiry far beyond the default 30 seconds, proving
/// the lock_timeout_secs was honoured.
// Verifies: WS-0007
#[tokio::test]
async fn test_ws_subscribe_with_lock_timeout_secs() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "long-lock-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Subscribe with a 120-second lock.
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "long-lock-q", "lock_timeout_secs": 120}),
    )
    .await;
    let sub_resp = recv(&mut ws).await;
    assert_eq!(sub_resp["type"], "ok");

    http_publish(&http_base, "long-lock-q", "long-lock-payload").await;

    // Receive delivery.
    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .expect("did not receive delivery frame in time");

    let msg_id = delivery["id"].as_str().unwrap().to_string();

    // The message should be locked with a timeout well beyond 30s.
    // Consume the same queue via HTTP to inspect the locked_until field.
    // Since the message is already locked, HTTP consume should return no
    // message (the only message is locked).
    let consume_resp: Value = Client::new()
        .post(format!("{}/consume/long-lock-q", http_base))
        .json(&json!({"consumer_id": "probe", "timeout_seconds": 5}))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    // No message available — confirming the only message is locked.
    assert!(
        consume_resp.get("id").is_none(),
        "message should be locked and not consumable by another consumer"
    );

    // Stats should show locked=1.
    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/long-lock-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(
        stats["locked"], 1,
        "message should be locked after delivery"
    );

    // Ack to clean up.
    send(
        &mut ws,
        json!({"type": "ack", "queue": "long-lock-q", "id": msg_id}),
    )
    .await;
    let ack_resp = recv(&mut ws).await;
    assert_eq!(ack_resp["type"], "ok");
}

/// Subscribe with default lock, then renew with a custom lock_timeout_secs.
/// The renewed lock should use the specified timeout, not the default 30s.
// Verifies: WS-0020
#[tokio::test]
async fn test_ws_renew_with_lock_timeout_secs() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "renew-timeout-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Subscribe with default lock.
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "renew-timeout-q"}),
    )
    .await;
    let _ = recv(&mut ws).await; // ok

    http_publish(&http_base, "renew-timeout-q", "renew-timeout-payload").await;

    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .expect("did not receive delivery frame in time");

    let msg_id = delivery["id"].as_str().unwrap().to_string();

    // Renew with a custom timeout (120 seconds).
    send(
        &mut ws,
        json!({
            "type": "renew",
            "queue": "renew-timeout-q",
            "id": msg_id,
            "lock_timeout_secs": 120,
            "req_id": "rn-timeout"
        }),
    )
    .await;
    let renew_resp = recv(&mut ws).await;
    assert_eq!(renew_resp["type"], "ok");
    assert_eq!(renew_resp["req_id"], "rn-timeout");

    // Message should still be locked (renewed for 120s).
    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/renew-timeout-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(
        stats["locked"], 1,
        "message should still be locked after renew with 120s timeout"
    );

    // Ack the message to clean up.
    send(
        &mut ws,
        json!({"type": "ack", "queue": "renew-timeout-q", "id": msg_id}),
    )
    .await;
    let ack_resp = recv(&mut ws).await;
    assert_eq!(ack_resp["type"], "ok");
}

/// Subscribe without lock_timeout_secs should use the default (30s).
/// Verify backward compatibility.
// Verifies: WS-0007
#[tokio::test]
async fn test_ws_subscribe_default_lock_timeout() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "default-lock-q").await;
    let mut ws = ws_connect(&ws_base).await;

    // Subscribe without lock_timeout_secs.
    send(
        &mut ws,
        json!({"type": "subscribe", "queue": "default-lock-q"}),
    )
    .await;
    let sub_resp = recv(&mut ws).await;
    assert_eq!(sub_resp["type"], "ok");

    http_publish(&http_base, "default-lock-q", "default-lock-payload").await;

    let delivery = timeout(Duration::from_secs(3), async {
        loop {
            let f = recv(&mut ws).await;
            if f["type"] == "deliver" {
                return f;
            }
        }
    })
    .await
    .expect("did not receive delivery frame in time");

    let msg_id = delivery["id"].as_str().unwrap();

    // Message should be locked.
    let stats: Value = Client::new()
        .get(format!("{}/queue-stats/default-lock-q", http_base))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(stats["locked"], 1);

    // Ack to clean up.
    send(
        &mut ws,
        json!({"type": "ack", "queue": "default-lock-q", "id": msg_id}),
    )
    .await;
    let _ = recv(&mut ws).await;
}

// ---------------------------------------------------------------------------
// WS-0027 – outbound write path decoupled from the inbound receive loop
// ---------------------------------------------------------------------------

/// The inbound receive loop must keep processing client frames while the
/// outbound write path is busy delivering a large backlog. We subscribe to a
/// "sink" queue and give it several hundred deliveries — enough to keep the
/// server's sender task continuously busy — then, *concurrently*, send inbound
/// `publish` frames to a *second* queue and confirm they take effect.
///
/// A background reader keeps our end of the socket serviced so the connection
/// stays alive and server pings are answered; the delivery frames themselves
/// are discarded, which WS-0027 explicitly permits under back-pressure. The
/// probe effect is observed over HTTP — never via an outbound WS frame — so the
/// assertion is deterministic regardless of delivery timing or drops.
///
/// (The narrower "outbound channel full ⇒ frame dropped, inbound still served"
/// path is a unit-level concern of the 512-slot channel; filling it here would
/// require ~512 durable publishes, so this integration test targets the
/// inbound/outbound *decoupling* instead.)
///
/// Verifies: WS-0027
#[tokio::test]
async fn test_ws_outbound_backpressure_does_not_stall_inbound() {
    let (ws_base, http_base, _dir) = start_test_server().await;
    http_create_queue(&http_base, "bp-sink").await;
    http_create_queue(&http_base, "bp-probe").await;

    let ws = ws_connect(&ws_base).await;
    let (mut ws_tx, mut ws_rx) = ws.split();

    let subscribe = json!({"type": "subscribe", "queue": "bp-sink"}).to_string();
    ws_tx
        .send(TungsteniteMessage::Text(subscribe.into()))
        .await
        .unwrap();

    // Keep the socket serviced (so the connection stays alive and pings are
    // answered) while the server delivers the backlog; drop the delivery frames.
    let drainer = tokio::spawn(async move { while let Some(Ok(_)) = ws_rx.next().await {} });

    // Hand the server a large outbound backlog to deliver.
    for i in 0..500 {
        http_publish(&http_base, "bp-sink", &format!("flood-{i}")).await;
    }

    // Inbound must still be processed while all that outbound work is in flight.
    const PROBE_COUNT: u64 = 10;
    for i in 0..PROBE_COUNT {
        let frame =
            json!({"type": "publish", "queue": "bp-probe", "payload": format!("probe-{i}")})
                .to_string();
        ws_tx
            .send(TungsteniteMessage::Text(frame.into()))
            .await
            .unwrap();
    }

    // Observe the side effect over HTTP, independent of the WS outbound path.
    let client = Client::new();
    let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
    let mut total = 0u64;
    while tokio::time::Instant::now() < deadline {
        let stats: Value = client
            .get(format!("{}/queue-stats/bp-probe", http_base))
            .send()
            .await
            .unwrap()
            .json()
            .await
            .unwrap();
        total = stats["total"].as_u64().unwrap_or(0);
        if total >= PROBE_COUNT {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert_eq!(
        total, PROBE_COUNT,
        "inbound WS publishes must be processed while the outbound path is busy"
    );

    drainer.abort();
    let _ = ws_tx.close().await;
}