pinch-points 0.9.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
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
//! The listener and a game, end to end over real sockets: a test client
//! registers, plays, drops, comes back, and misbehaves on purpose.

use super::connstr::Key;
use super::game::{self, GameSpec, Seat, Sinks};
use super::listener::{Admission, Config, Event, Invite, Listener};
use super::protocol::Clock;
use crate::sim::{Board, BotLevel, CapPolicy, CrabKind, Direction, Handedness, TileKind};
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::mpsc::Receiver;
use std::time::Duration;

/// A bot written for the tests: a socket and a line reader.
struct Client {
    stream: TcpStream,
    reader: BufReader<TcpStream>,
}

impl Client {
    fn connect(addr: SocketAddr) -> Client {
        let stream = TcpStream::connect(addr).expect("connect");
        stream.set_nodelay(true).expect("nodelay");
        stream
            .set_read_timeout(Some(Duration::from_secs(20)))
            .expect("timeout");
        let reader = BufReader::new(stream.try_clone().expect("clone"));
        Client { stream, reader }
    }

    /// Write a message. A listener may already have closed a connection
    /// it refused, so a failed write is the test's to notice by what
    /// comes back, not a panic here.
    fn send(&mut self, msg: &Value) {
        let _ = writeln!(self.stream, "{msg}");
    }

    fn raw(&mut self, line: &str) {
        writeln!(self.stream, "{line}").expect("write");
    }

    /// The next message that is not a ping (pings are answered).
    fn next(&mut self) -> Option<Value> {
        loop {
            let mut line = String::new();
            if self.reader.read_line(&mut line).ok()? == 0 {
                return None;
            }
            let msg: Value = serde_json::from_str(&line).expect("the listener writes JSON");
            if msg["type"] == "ping" {
                let id = msg["id"].clone();
                self.send(&json!({"type": "pong", "id": id}));
                continue;
            }
            return Some(msg);
        }
    }

    fn register(addr: SocketAddr, name: &str, key: Option<&Key>) -> (Client, Value) {
        let mut client = Client::connect(addr);
        let mut msg = json!({"type": "register", "protocol": 1, "name": name, "version": "t"});
        if let Some(key) = key {
            msg["key"] = json!(key.to_string());
        }
        client.send(&msg);
        let answer = client.next().expect("an answer");
        (client, answer)
    }
}

fn listen(admission: Admission) -> (Listener, Receiver<Event>) {
    Listener::bind(
        SocketAddr::from(([127, 0, 0, 1], 0)),
        Config::new(admission),
    )
    .expect("bind")
}

fn invite(key: &Key, uses: Option<u32>) -> Invite {
    Invite {
        key: key.clone(),
        uses,
        owner: None,
        slot: None,
    }
}

/// A short round on a small beach: a crab walking straight at seat 0's
/// castle, and seat 1 across the way.
fn little_beach(ticks: u32) -> Board {
    let mut board = Board::new(12, 3, 9);
    board.set_tile(11, 1, TileKind::Castle(0));
    board.set_tile(0, 1, TileKind::Castle(1));
    // Two tiles from home and too far from seat 1 for the AI to reach for.
    board.spawn_crab(9, 1, Direction::Right, Handedness::Left, CrabKind::Giant);
    board.rules_mut().round_length = Some(ticks);
    board.set_signpost_rule(3, CapPolicy::Evict);
    board
}

fn spec(board: Board, seats: Vec<Seat>, deadline_ms: u32) -> GameSpec {
    spec_on(board, seats, deadline_ms, false)
}

fn spec_on(board: Board, seats: Vec<Seat>, deadline_ms: u32, live: bool) -> GameSpec {
    GameSpec {
        game: 7,
        replay_id: "t-g7".into(),
        board,
        names: seats
            .iter()
            .enumerate()
            .map(|(i, _)| format!("seat{i}"))
            .collect(),
        seats,
        clock: Clock {
            live,
            deadline_ms,
            input_delay: 0,
        },
        fair_cursor: false,
        forfeit_after: Duration::from_millis(300),
        ready_within: Duration::from_secs(5),
    }
}

fn play(listener: &Listener, spec: GameSpec) -> (game::GameResult, String) {
    let mut log = Vec::new();
    let mut console = |_: String| {};
    let result = {
        let mut sinks = Sinks {
            log: &mut log,
            trace: None,
            feed: None,
            console: &mut console,
            echo_notes: false,
        };
        game::play(listener, spec, &mut sinks)
    };
    (result, String::from_utf8(log).expect("utf8"))
}

#[test]
fn a_bot_registers_plays_and_is_told_how_it_went() {
    let key = Key::draw();
    let (listener, events) = listen(Admission::Keys(vec![invite(&key, Some(1))]));
    let addr = listener.local_addr();
    let (mut bot, answer) = Client::register(addr, "Plucky", Some(&key));
    assert_eq!(answer["type"], "registered");
    assert!(answer["token"].as_str().is_some_and(|t| t.len() >= 20));
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let player = std::thread::spawn(move || {
        let mut ticks = 0;
        let mut refused = None;
        while let Some(msg) = bot.next() {
            match msg["type"].as_str() {
                Some("hello") => {
                    assert_eq!(msg["seat"], 0);
                    assert_eq!(msg["kinds"], json!(["bot", "ai"]));
                    bot.send(&json!({"type": "ready", "game": msg["game"]}));
                }
                Some("tick") => {
                    ticks += 1;
                    let t = msg["tick"].clone();
                    if refused.is_none() && msg["you"]["last"]["accepted"] == false {
                        refused = Some(msg["you"]["last"]["reason"].clone());
                    }
                    // First a placement on a castle, which is refused, then
                    // nothing.
                    let act = if t == 0 {
                        json!({"game": 7, "tick": t, "act": "place", "x": 0, "y": 1, "dir": "up", "note": "hi"})
                    } else {
                        json!({"game": 7, "tick": t, "act": "none"})
                    };
                    bot.send(&act);
                }
                Some("end") => return (ticks, refused, msg),
                _ => {}
            }
        }
        panic!("the connection closed before the end");
    });
    let (result, log) = play(
        &listener,
        spec(
            little_beach(120),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            1000,
        ),
    );
    let (ticks, refused, end) = player.join().expect("player");
    assert_eq!(ticks, 120, "one tick message per tick of the round");
    assert_eq!(refused, Some(json!("castle")));
    assert_eq!(result.seats[0].rejected, 1);
    assert_eq!(result.seats[0].banked, 1, "the giant walked home");
    assert_eq!(end["scores"][0], 10);
    assert_eq!(end["placing"], 1);
    assert_eq!(end["replay"], "t-g7");
    assert!(log.contains("note: hi"), "{log}");
    assert!(log.contains("refused: castle"), "{log}");
    assert_eq!(result.replay.inputs.len(), 120);
}

#[test]
fn a_second_bot_on_a_single_use_key_is_turned_away() {
    let key = Key::draw();
    let (listener, _events) = listen(Admission::Keys(vec![invite(&key, Some(1))]));
    let addr = listener.local_addr();
    let (_first, answer) = Client::register(addr, "One", Some(&key));
    assert_eq!(answer["type"], "registered");
    let (_second, answer) = Client::register(addr, "Two", Some(&key));
    assert_eq!(answer["type"], "error");
    assert_eq!(answer["fatal"], true);
}

#[test]
fn a_taken_name_does_not_spend_the_key() {
    let key = Key::draw();
    let (listener, _events) = listen(Admission::Keys(vec![invite(&key, Some(2))]));
    let addr = listener.local_addr();
    let (_a, answer) = Client::register(addr, "Same", Some(&key));
    assert_eq!(answer["type"], "registered");
    let (_b, answer) = Client::register(addr, "same", Some(&key));
    assert_eq!(
        answer["type"], "error",
        "names are unique, whatever the case"
    );
    let (_c, answer) = Client::register(addr, "Other", Some(&key));
    assert_eq!(
        answer["type"], "registered",
        "the refused one did not use the key up"
    );
}

#[test]
fn three_wrong_keys_turn_the_address_away_and_not_the_key() {
    let key = Key::draw();
    let (listener, _events) = listen(Admission::Keys(vec![invite(&key, None)]));
    let addr = listener.local_addr();
    for _ in 0..3 {
        let (_c, answer) = Client::register(addr, "Guess", Some(&Key::draw()));
        assert_eq!(answer["type"], "error");
    }
    // The right key from the same address is refused for now...
    let (_c, answer) = Client::register(addr, "Honest", Some(&key));
    assert_eq!(answer["type"], "error");
    assert!(
        answer["message"]
            .as_str()
            .is_some_and(|m| m.contains("minute"))
    );
}

#[test]
fn a_protocol_this_build_does_not_speak_is_refused_by_number() {
    let (listener, _events) = listen(Admission::Open);
    let mut client = Client::connect(listener.local_addr());
    client.send(&json!({"type": "register", "protocol": 3, "name": "Future"}));
    let answer = client.next().expect("answer");
    assert_eq!(answer["type"], "error");
    assert!(
        answer["message"]
            .as_str()
            .is_some_and(|m| m.contains("protocol 1 to 2"))
    );
}

#[test]
fn a_line_too_long_closes_the_connection() {
    let (listener, _events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Wordy", None);
    let long = format!("{{\"note\": \"{}\"}}", "x".repeat(70 * 1024));
    // The listener may close before the whole line is written.
    let _ = writeln!(bot.stream, "{long}");
    let mut saw_error = false;
    while let Some(msg) = bot.next() {
        saw_error |= msg["type"] == "error" && msg["fatal"] == true;
    }
    assert!(saw_error);
}

#[test]
fn a_bot_that_comes_back_with_its_token_plays_on() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let (mut bot, answer) = Client::register(addr, "Phoenix", None);
    let token = answer["token"].as_str().expect("token").to_string();
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let player = std::thread::spawn(move || {
        // Play a few ticks, hang up, and come back with the token.
        let mut seen = 0;
        while let Some(msg) = bot.next() {
            if msg["type"] == "hello" {
                bot.send(&json!({"type": "ready", "game": msg["game"]}));
            }
            if msg["type"] == "tick" {
                seen += 1;
                bot.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"}));
                if seen == 5 {
                    break;
                }
            }
        }
        drop(bot);
        std::thread::sleep(Duration::from_millis(100));
        let mut back = Client::connect(addr);
        back.send(&json!({"type": "register", "protocol": 1, "token": token}));
        let answer = back.next().expect("registered again");
        assert_eq!(answer["type"], "registered");
        assert_eq!(answer["name"], "Phoenix");
        let hello = back.next().expect("hello again");
        assert_eq!(hello["type"], "hello");
        assert_eq!(hello["resumed"], true);
        let mut after = 0;
        while let Some(msg) = back.next() {
            if msg["type"] == "tick" {
                after += 1;
                back.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"}));
            }
            if msg["type"] == "end" {
                return after;
            }
        }
        panic!("no end");
    });
    // On the live clock: in fast-forward a table whose only bot has gone
    // has nobody to wait for, and runs to the tide before it is back.
    let (result, log) = play(
        &listener,
        spec_on(
            little_beach(150),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            33,
            true,
        ),
    );
    let after = player.join().expect("player");
    assert!(
        after > 100,
        "it played on after coming back ({after} ticks)"
    );
    assert!(!result.seats[0].forfeit);
    assert!(
        log.contains("connection dropped") && log.contains("reconnected"),
        "{log}"
    );
}

#[test]
fn a_bot_that_never_comes_forfeits_and_places_last() {
    let (listener, events) = listen(Admission::Open);
    let (bot, _) = Client::register(listener.local_addr(), "Ghost", None);
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    drop(bot);
    while listener.connected(id) {
        std::thread::sleep(Duration::from_millis(5));
    }
    let mut board = little_beach(60);
    // The ghost's castle would bank the giant on its own.
    board.set_score(1, 0);
    let (result, _) = play(
        &listener,
        spec(board, vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)], 50),
    );
    assert!(result.seats[0].forfeit);
    assert_eq!(result.seats[0].placing, 2);
    assert_eq!(result.seats[1].placing, 1);
}

#[test]
fn a_lookahead_is_answered_off_the_game_and_a_replay_fetched_after_it() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let (mut bot, _) = Client::register(addr, "Seer", None);
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let player = std::thread::spawn(move || {
        let mut lookahead = None;
        while let Some(msg) = bot.next() {
            match msg["type"].as_str() {
                Some("hello") => bot.send(&json!({"type": "ready", "game": 7})),
                Some("tick") if msg["tick"] == 0 => {
                    bot.send(&json!({"type": "simulate", "game": 7, "ticks": 100, "plan": []}));
                    let answer = bot.next().expect("simulated");
                    lookahead = Some(answer);
                    bot.send(&json!({"game": 7, "tick": 0, "act": "none"}));
                }
                Some("tick") => bot.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"})),
                Some("end") => {
                    bot.send(&json!({"type": "replay", "id": "t-g7"}));
                    let replay = bot.next().expect("replay");
                    return (lookahead, replay);
                }
                _ => {}
            }
        }
        panic!("no end");
    });
    play(
        &listener,
        spec(
            little_beach(80),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            1000,
        ),
    );
    let (lookahead, replay) = player.join().expect("player");
    let lookahead = lookahead.expect("a lookahead");
    assert_eq!(lookahead["type"], "simulated");
    assert_eq!(lookahead["ticks"], 80, "it stops where the round does");
    assert!(
        lookahead["events"]
            .as_array()
            .is_some_and(|e| e.iter().any(|e| e["what"] == "banked" && e["owner"] == 0)),
        "{lookahead}"
    );
    assert_eq!(replay["type"], "replay");
    let text = replay["text"].as_str().expect("text");
    let parsed = crate::sim::Replay::parse(text).expect("a replay this build reads");
    assert_eq!(parsed.inputs.len(), 80);
    assert_eq!(parsed.names[0], "seat0");
    assert_eq!(parsed.kinds[0], crate::sim::SeatKind::Bot);
}

#[test]
fn a_slow_bot_is_late_but_never_buried_under_ticks() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Sloth", None);
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let player = std::thread::spawn(move || {
        let mut ticks = 0;
        while let Some(msg) = bot.next() {
            match msg["type"].as_str() {
                Some("hello") => bot.send(&json!({"type": "ready", "game": 7})),
                Some("tick") => {
                    ticks += 1;
                    std::thread::sleep(Duration::from_millis(12));
                    bot.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"}));
                }
                Some("end") => return ticks,
                _ => {}
            }
        }
        panic!("no end");
    });
    let (result, _) = play(
        &listener,
        spec(
            little_beach(90),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            5,
        ),
    );
    let ticks = player.join().expect("player");
    let seat = &result.seats[0];
    assert!(seat.late > 0, "a 12 ms bot on a 5 ms deadline is late");
    assert!(
        ticks < 60,
        "and is not sent ticks it has not caught up with ({ticks})"
    );
    assert_eq!(seat.sent as usize, ticks);
}

#[test]
fn garbage_counts_as_none_and_is_logged() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Babbler", None);
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let player = std::thread::spawn(move || {
        while let Some(msg) = bot.next() {
            match msg["type"].as_str() {
                Some("hello") => bot.send(&json!({"type": "ready", "game": 7})),
                Some("tick") if msg["tick"] == 3 => bot.raw("{this is not json"),
                Some("tick") if msg["tick"] == 4 => {
                    bot.send(&json!({"game": 7, "tick": 4, "act": "teleport", "x": 1, "y": 1}));
                }
                Some("tick") => bot.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"})),
                Some("end") => return,
                _ => {}
            }
        }
    });
    let (result, log) = play(
        &listener,
        spec(
            little_beach(10),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            1000,
        ),
    );
    player.join().expect("player");
    assert!(log.contains("garbled"), "{log}");
    assert!(log.contains("teleport"), "{log}");
    assert_eq!(result.seats[0].rejected, 0);
}

#[test]
fn a_per_author_key_names_the_owner_and_one_owner_enters_once() {
    let shared = Key::draw();
    let ana = Key::draw();
    let mut config = Config::new(Admission::Keys(vec![invite(&shared, None)]));
    config.per_owner = Some(1);
    let (listener, events) =
        Listener::bind(SocketAddr::from(([127, 0, 0, 1], 0)), config).expect("bind");
    listener.invite(Invite {
        key: ana.clone(),
        uses: None,
        owner: Some("Ana".into()),
        slot: None,
    });
    let addr = listener.local_addr();
    // Whatever it claims, a bot on Ana's key is Ana's.
    let mut client = Client::connect(addr);
    client.send(&json!({
        "type": "register", "protocol": 1, "name": "Sly", "owner": "Somebody Else",
        "key": ana.to_string(),
    }));
    assert_eq!(client.next().expect("answer")["type"], "registered");
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let info = listener.bot(id).expect("info");
    assert_eq!(info.owner.as_deref(), Some("Ana"));
    assert!(!info.owner_declared);
    // A second bot declaring Ana on the shared key is one too many.
    let mut second = Client::connect(addr);
    second.send(&json!({
        "type": "register", "protocol": 1, "name": "Sly2", "owner": "ana",
        "key": shared.to_string(),
    }));
    let answer = second.next().expect("answer");
    assert_eq!(answer["type"], "error", "{answer}");
}

#[test]
fn a_closed_listener_lets_its_port_and_its_bots_go() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let (mut bot, _) = Client::register(addr, "Leaving", None);
    let Ok(Event::Registered(_)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    listener.close();
    // The bot hears the end of its connection.
    while bot.next().is_some() {}
    // And the port is free to take again.
    let mut again = None;
    for _ in 0..250 {
        if let Ok(socket) = std::net::TcpListener::bind(addr) {
            again = Some(socket);
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(again.is_some(), "the port was never let go");
}

fn registered(events: &Receiver<Event>) -> usize {
    loop {
        match events.recv_timeout(Duration::from_secs(5)) {
            Ok(Event::Registered(id)) => return id,
            Ok(_) => {}
            Err(_) => panic!("no registration event"),
        }
    }
}

/// A request that draws an error must not pay for itself. Each answer is a
/// line sent, and lines sent are what earn a bot the right to send more: if
/// an error earned it too, a bot could ask for errors forever.
#[test]
fn an_answer_to_a_bad_request_earns_nothing() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Drum", None);
    let id = registered(&events);
    // One at a time, each answer read before the next is asked: no flood,
    // only a bot that keeps asking for the same error.
    for _ in 0..300 {
        bot.send(&json!({"type": "register", "protocol": 1, "name": "Drum"}));
        assert_eq!(bot.next().expect("an answer")["type"], "error");
    }
    // Time refills an allowance up to the burst and no further; only lines
    // that earn can lift it past that.
    assert!(
        listener.allowance(id) <= Listener::BURST,
        "300 errors earned the bot {} lines",
        listener.allowance(id)
    );
}

/// And a bot that asks for nothing but errors, as fast as it can, is let
/// go: told it is flooding, or, on a machine too busy to write the errors
/// out as fast as they are asked for, dropped for not reading them.
#[test]
fn a_flood_of_requests_answered_with_errors_is_let_go() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Drum", None);
    let id = registered(&events);
    let again = json!({"type": "register", "protocol": 1, "name": "Drum"}).to_string();
    // Far more than the burst, written while the answers are read. A flood
    // is that many refusals within a sliding window, so a reader slowed
    // down by a busy machine, let a line through every 20 ms, trips it all
    // the same.
    let mut flood = bot.stream.try_clone().expect("a second handle");
    let writer = std::thread::spawn(move || {
        for _ in 0..20_000 {
            if writeln!(flood, "{again}").is_err() {
                break;
            }
        }
    });
    while let Some(msg) = bot.next() {
        if msg["type"] == "error" && msg["fatal"] == true {
            assert_eq!(msg["message"], "flooding", "{msg}");
            break;
        }
    }
    drop(bot);
    let _ = writer.join();
    let gone = (0..250).any(|_| {
        std::thread::sleep(Duration::from_millis(20));
        !listener.connected(id)
    });
    assert!(gone, "a flood and still welcome");
}

/// Wrong keys from an address lock its keys out, not its tokens: a bot
/// coming back with its own token is let in, and a stale token is no
/// strike against anyone sharing the address (behind a cup's proxy, say).
#[test]
fn a_locked_out_address_still_takes_a_bot_back_by_its_token() {
    let key = Key::draw();
    let (listener, events) = listen(Admission::Keys(vec![invite(&key, None)]));
    let addr = listener.local_addr();
    let (keeper, answer) = Client::register(addr, "Keeper", Some(&key));
    let token = answer["token"].as_str().expect("token").to_string();
    let id = registered(&events);
    // Three stale tokens cost nobody anything.
    for _ in 0..3 {
        let mut stale = Client::connect(addr);
        stale.send(&json!({"type": "register", "protocol": 1, "token": "0".repeat(26)}));
        assert_eq!(stale.next().expect("answer")["type"], "error");
    }
    let (_other, answer) = Client::register(addr, "Other", Some(&key));
    assert_eq!(answer["type"], "registered", "{answer}");
    // Three wrong keys lock the address's keys out...
    for _ in 0..3 {
        let (_c, answer) = Client::register(addr, "Guess", Some(&Key::draw()));
        assert_eq!(answer["type"], "error");
    }
    let (_c, answer) = Client::register(addr, "Late", Some(&key));
    assert_eq!(answer["type"], "error", "the keys are locked out");
    // ...and not the bot that drops and comes back with its token.
    drop(keeper);
    while listener.connected(id) {
        std::thread::sleep(Duration::from_millis(5));
    }
    let mut back = Client::connect(addr);
    back.send(&json!({"type": "register", "protocol": 1, "token": token}));
    let answer = back.next().expect("answer");
    assert_eq!(answer["type"], "registered", "{answer}");
}

/// Connections that never register are capped, so a few hundred silent
/// ones cannot use up the machine; one over the cap is told so at once,
/// and the places come back as they go.
#[test]
fn silent_connections_are_capped_and_told_so_at_once() {
    let (listener, _events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let mut silent: Vec<Client> = Vec::new();
    for _ in 0..8 {
        silent.push(Client::connect(addr));
    }
    // Each has been taken in before the next is tried.
    std::thread::sleep(Duration::from_millis(200));
    let started = std::time::Instant::now();
    let mut over = Client::connect(addr);
    let answer = over.next().expect("an answer");
    assert_eq!(answer["type"], "error");
    assert!(
        started.elapsed() < Duration::from_secs(3),
        "told after {:?}",
        started.elapsed()
    );
    drop(silent);
    std::thread::sleep(Duration::from_millis(200));
    let (_bot, answer) = Client::register(addr, "Patient", None);
    assert_eq!(answer["type"], "registered", "{answer}");
}

/// A lookahead runs off the game's lock: the game publishes its board
/// through it every tick, and must never wait out somebody's 600 ticks of
/// thinking to do so.
#[test]
fn a_lookahead_does_not_hold_the_game_up() {
    use super::listener::{View, lock};
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Thinker", None);
    let id = registered(&events);
    let link = listener.open_game(7, vec![(id, 0)]);
    let board = crate::sim::classic_arena(false, 2);
    let ticks = 3000;
    let alone = std::time::Instant::now();
    super::lookahead::run(&board, 0, ticks, &[]);
    let alone = alone.elapsed();
    *lock(&link.view) = Some(View {
        board,
        cursors: vec![None, None],
        budget: vec![ticks, ticks],
    });
    let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let thinker = {
        let done = std::sync::Arc::clone(&done);
        std::thread::spawn(move || {
            bot.send(&json!({"type": "simulate", "game": 7, "ticks": ticks, "plan": []}));
            let answer = bot.next().expect("simulated");
            done.store(true, std::sync::atomic::Ordering::SeqCst);
            answer
        })
    };
    let mut longest = Duration::ZERO;
    while !done.load(std::sync::atomic::Ordering::SeqCst) {
        let asked = std::time::Instant::now();
        drop(lock(&link.view));
        longest = longest.max(asked.elapsed());
        std::thread::sleep(Duration::from_millis(1));
    }
    let answer = thinker.join().expect("thinker");
    assert_eq!(answer["type"], "simulated", "{answer}");
    assert!(
        longest < alone / 2,
        "the game waited {longest:?} for a lookahead that takes {alone:?}"
    );
}

/// A bot that asks for replays and never reads them is dropped once a
/// couple of megabytes are waiting for it, not after hundreds of them.
#[test]
fn a_bot_that_asks_for_replays_and_never_reads_is_dropped() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Hoarder", None);
    let id = registered(&events);
    listener.keep_replay("big".into(), vec![id], "x".repeat(200 * 1024));
    let ask = json!({"type": "replay", "id": "big"}).to_string();
    for _ in 0..150 {
        if writeln!(bot.stream, "{ask}").is_err() {
            break;
        }
    }
    // How soon is not the point, and is slow under load: every answer is a
    // 200 KB string written out as JSON in a debug build. Six suites side
    // by side took longer than five seconds to fill the queue.
    let deadline = std::time::Instant::now() + Duration::from_secs(60);
    let mut dropped = false;
    while let Some(left) = deadline.checked_duration_since(std::time::Instant::now())
        && let Ok(event) = events.recv_timeout(left)
    {
        if matches!(event, Event::Dropped(gone) if gone == id) {
            dropped = true;
            break;
        }
    }
    assert!(
        dropped,
        "30 MB asked for and never read, and still connected"
    );
}

/// A `simulate` the listener cannot read is answered with an error and is
/// no answer to the tick: the bot's reply after it is its move.
#[test]
fn a_garbled_lookahead_is_an_error_and_not_the_move() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Fumble", None);
    let id = registered(&events);
    let player = std::thread::spawn(move || {
        let mut after = None;
        while let Some(msg) = bot.next() {
            match msg["type"].as_str() {
                Some("hello") => bot.send(&json!({"type": "ready", "game": 7})),
                Some("tick") if msg["tick"] == 0 => {
                    bot.send(&json!({
                        "type": "simulate", "game": 7, "ticks": 10,
                        "plan": [{"at": 0, "act": "place", "x": 9, "y": 1}],
                    }));
                    after = bot.next();
                    bot.send(&json!({"game": 7, "tick": 0, "act": "place", "x": 9, "y": 0, "dir": "down"}));
                }
                Some("tick") => bot.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"})),
                Some("end") => return after,
                _ => {}
            }
        }
        panic!("no end");
    });
    let (result, _) = play(
        &listener,
        spec(
            little_beach(10),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            1000,
        ),
    );
    let after = player.join().expect("player").expect("an answer");
    assert_eq!(after["type"], "error", "{after}");
    assert_eq!(after["game"], 7, "{after}");
    let placed = result.replay.inputs.first().map(|actions| actions[0]);
    assert!(
        matches!(
            placed,
            Some(crate::sim::PlayerAction::Place { x: 9, y: 0, .. })
        ),
        "{placed:?}"
    );
}

/// Wait for the listener to say bot `id` went.
fn dropped(events: &Receiver<Event>, id: usize) {
    loop {
        match events.recv_timeout(Duration::from_secs(5)) {
            Ok(Event::Dropped(gone)) if gone == id => return,
            Ok(_) => {}
            Err(_) => panic!("bot {id} was never reported gone"),
        }
    }
}

/// A bot that dropped and restarted, its token gone with the rest of its
/// memory, takes its own chair back on the key and the name it came in
/// on: not refused for a spent key or a taken name, and never a strike
/// against its address, however often it comes back. Somebody else with
/// the key, under another name, does not get the chair. It comes back
/// with a new token, and the old one lets nobody in.
#[test]
fn a_dropped_bot_restarted_without_its_token_takes_its_chair_back() {
    let slot_key = Key::draw();
    let shared_key = Key::draw();
    let (listener, events) = listen(Admission::Keys(vec![
        Invite {
            key: slot_key.clone(),
            uses: Some(1),
            owner: None,
            slot: Some(0),
        },
        Invite {
            key: shared_key.clone(),
            uses: Some(1),
            owner: None,
            slot: Some(1),
        },
    ]));
    let addr = listener.local_addr();
    for (name, key) in [("Greedy", &slot_key), ("Second", &shared_key)] {
        let (bot, answer) = Client::register(addr, name, Some(key));
        assert_eq!(answer["type"], "registered", "{answer}");
        let mut token = answer["token"].clone();
        let id = registered(&events);
        let mut bot = Some(bot);
        // More times than the strikes that lock an address out.
        for _ in 0..4 {
            drop(bot.take());
            dropped(&events, id);
            let (back, answer) = Client::register(addr, name, Some(key));
            assert_eq!(answer["type"], "registered", "{name}: {answer}");
            assert_eq!(answer["resumed"], true, "{answer}");
            assert_ne!(answer["token"], token, "a new token: {answer}");
            token = answer["token"].clone();
            bot = Some(back);
        }
        // Sat in, the chair is not up for grabs.
        let (_twin, answer) = Client::register(addr, name, Some(key));
        assert_eq!(answer["type"], "error", "{answer}");
        // Empty, it is not anybody's who holds the key.
        drop(bot.take());
        dropped(&events, id);
        let (_other, answer) = Client::register(addr, "Other", Some(key));
        assert_eq!(answer["type"], "error", "{answer}");
    }
}

/// A key every entrant holds, like a cup's invite, takes no chair back by
/// name: bot names are public, so with it a rival could sit down in a
/// dropped bot's chair, be handed its token, and throw its games. That
/// bot comes back by its token.
#[test]
fn a_shared_key_does_not_take_another_bots_chair() {
    let shared = Key::draw();
    // A cup's invite, and an arena's `--key` for two seats.
    for uses in [None, Some(2)] {
        let (listener, events) = listen(Admission::Keys(vec![invite(&shared, uses)]));
        let addr = listener.local_addr();
        let (bot, answer) = Client::register(addr, "Victim", Some(&shared));
        assert_eq!(answer["type"], "registered", "{answer}");
        let token = answer["token"].as_str().expect("token").to_string();
        let id = registered(&events);
        drop(bot);
        dropped(&events, id);
        let (_rival, answer) = Client::register(addr, "Victim", Some(&shared));
        assert_eq!(answer["type"], "error", "not the victim's chair: {answer}");
        let mut back = Client::connect(addr);
        back.send(&json!({"type": "register", "protocol": 1, "token": token}));
        let answer = back.next().expect("an answer");
        assert_eq!(answer["resumed"], true, "its token still works: {answer}");
    }
}

/// A bot the host lets go, asked to leave or told it has no seat, is gone
/// for good and said to be: its going is reported, its token lands
/// nowhere, and its name is free for the same bot started anew.
#[test]
fn a_bot_let_go_by_the_host_frees_its_name() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    for dismissed in [false, true] {
        let (mut bot, answer) = Client::register(addr, "Shown Out", None);
        assert_eq!(answer["type"], "registered", "{answer}");
        let token = answer["token"].as_str().expect("token").to_string();
        let id = registered(&events);
        if dismissed {
            listener.dismiss(id, "no seat for you");
        } else {
            listener.disconnect(id);
        }
        dropped(&events, id);
        let mut told = None;
        while let Some(msg) = bot.next() {
            if msg["type"] == "error" {
                told = Some(msg);
            }
        }
        if dismissed {
            let told = told.expect("told why");
            assert_eq!(told["message"], "no seat for you", "{told}");
            assert_eq!(told["fatal"], true, "{told}");
        }
        let mut back = Client::connect(addr);
        back.send(&json!({"type": "register", "protocol": 1, "token": token}));
        let answer = back.next().expect("an answer");
        assert_eq!(answer["type"], "error", "the token lands nowhere: {answer}");
        assert_eq!(answer["fatal"], true, "{answer}");
        // The name is free again, for the next round of the loop too.
        let (anew, answer) = Client::register(addr, "Shown Out", None);
        assert_eq!(answer["type"], "registered", "the name is free: {answer}");
        let again = registered(&events);
        drop(anew);
        listener.disconnect(again);
        dropped(&events, again);
    }
}

/// A flood that lets a message through now and then, steady rather than
/// all at once, is let go as surely as a burst: what is dropped adds up,
/// whatever gets through between.
#[test]
fn a_steady_flood_is_let_go_too() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Drip", None);
    let id = registered(&events);
    let again = json!({"type": "register", "protocol": 1, "name": "Drip"}).to_string();
    let mut flood = bot.stream.try_clone().expect("a second handle");
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    // About a thousand a second: far under what a burst of refusals in a
    // row would need, and far over what the clock refills.
    let writer = {
        let stop = std::sync::Arc::clone(&stop);
        std::thread::spawn(move || {
            let until = std::time::Instant::now() + Duration::from_secs(15);
            while !stop.load(std::sync::atomic::Ordering::SeqCst)
                && std::time::Instant::now() < until
            {
                if writeln!(flood, "{again}").is_err() {
                    return;
                }
                std::thread::sleep(Duration::from_millis(1));
            }
        })
    };
    let mut flooding = false;
    while let Some(msg) = bot.next() {
        if msg["type"] == "error" && msg["fatal"] == true {
            assert_eq!(msg["message"], "flooding", "{msg}");
            flooding = true;
            break;
        }
    }
    stop.store(true, std::sync::atomic::Ordering::SeqCst);
    drop(bot);
    let _ = writer.join();
    assert!(flooding, "a steady flood and never told");
    let gone = (0..250).any(|_| {
        std::thread::sleep(Duration::from_millis(20));
        !listener.connected(id)
    });
    assert!(gone, "a steady flood and still welcome");
}

/// With bots counted per owner, one that declares no owner is counted
/// under its address: leaving the owner out is no way round the cap.
#[test]
fn an_undeclared_owner_counts_as_its_address() {
    let mut config = Config::new(Admission::Open);
    config.per_owner = Some(1);
    let (listener, _events) =
        Listener::bind(SocketAddr::from(([127, 0, 0, 1], 0)), config).expect("bind");
    let addr = listener.local_addr();
    let (_first, answer) = Client::register(addr, "Anon", None);
    assert_eq!(answer["type"], "registered", "{answer}");
    let (_second, answer) = Client::register(addr, "Anon Again", None);
    assert_eq!(answer["type"], "error", "{answer}");
    assert!(
        answer["message"]
            .as_str()
            .is_some_and(|m| m.contains("owner")),
        "it says what to do: {answer}"
    );
    // One that says whose it is counts as that owner's.
    let mut declared = Client::connect(addr);
    declared.send(&json!({"type": "register", "protocol": 1, "name": "Bea's", "owner": "Bea"}));
    let answer = declared.next().expect("an answer");
    assert_eq!(answer["type"], "registered", "{answer}");
}

/// A bot that forfeited one game for never coming is not waited for
/// again: the next game forfeits its seat at once, rather than a cup
/// standing still for the whole timeout game after game. Coming back
/// puts an end to it.
#[test]
fn a_bot_that_never_came_is_not_waited_for_twice() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let (bot, answer) = Client::register(addr, "Truant", None);
    let token = answer["token"].as_str().expect("token").to_string();
    let id = registered(&events);
    drop(bot);
    while listener.connected(id) {
        std::thread::sleep(Duration::from_millis(5));
    }
    let wait = Duration::from_secs(1);
    let game = |listener: &Listener| {
        let mut spec = spec(
            little_beach(30),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            50,
        );
        spec.forfeit_after = wait;
        let started = std::time::Instant::now();
        let (result, _) = play(listener, spec);
        assert!(result.seats[0].forfeit);
        started.elapsed()
    };
    let first = game(&listener);
    assert!(first >= wait, "the first game waits for it ({first:?})");
    assert!(listener.absent(id));
    let second = game(&listener);
    assert!(second < wait / 2, "the second does not ({second:?})");
    let mut back = Client::connect(addr);
    back.send(&json!({"type": "register", "protocol": 1, "token": token}));
    assert_eq!(back.next().expect("an answer")["type"], "registered");
    assert!(!listener.absent(id), "back, and waited for again");
}

/// A bot that reconnects with its token before the first tick, while its
/// old connection is still open, is heard only coming back (the old
/// connection's going is never reported), and is greeted on the new one.
#[test]
fn a_bot_back_on_a_new_connection_before_the_first_tick_is_greeted_there() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let (mut first, answer) = Client::register(addr, "Twice", None);
    let token = answer["token"].as_str().expect("token").to_string();
    let id = registered(&events);
    let player = std::thread::spawn(move || {
        let hello = first.next().expect("hello");
        assert_eq!(hello["type"], "hello");
        // Not answered here: the bot comes in again with the first still open.
        let mut second = Client::connect(addr);
        second.send(&json!({"type": "register", "protocol": 1, "token": token}));
        assert_eq!(second.next().expect("an answer")["type"], "registered");
        let hello = second.next().expect("hello on the new connection");
        assert_eq!(hello["type"], "hello", "{hello}");
        second.send(&json!({"type": "ready", "game": hello["game"]}));
        let mut ticks = 0;
        while let Some(msg) = second.next() {
            if msg["type"] == "tick" {
                ticks += 1;
                second.send(&json!({"game": 7, "tick": msg["tick"], "act": "none"}));
            }
            if msg["type"] == "end" {
                break;
            }
        }
        drop(first);
        ticks
    });
    let mut spec = spec(
        little_beach(30),
        vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
        50,
    );
    spec.ready_within = Duration::from_secs(3);
    let (result, log) = play(&listener, spec);
    let ticks = player.join().expect("player");
    assert!(!result.seats[0].forfeit, "{log}");
    assert!(ticks > 0, "it played on the new connection");
}

/// A game already waiting for a bot that is away keeps waiting the whole
/// timeout when another game, played beside it, forfeits that bot for
/// never coming: only the games that start after that forfeit skip it.
#[test]
fn a_forfeit_elsewhere_does_not_cut_short_a_wait_already_begun() {
    let (listener, events) = listen(Admission::Open);
    let (bot, _) = Client::register(listener.local_addr(), "Away", None);
    let id = registered(&events);
    drop(bot);
    while listener.connected(id) {
        std::thread::sleep(Duration::from_millis(5));
    }
    let wait = Duration::from_secs(1);
    let mut spec = spec(
        little_beach(30),
        vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
        50,
    );
    spec.forfeit_after = wait;
    let took = std::thread::scope(|scope| {
        let game = scope.spawn(|| {
            let started = std::time::Instant::now();
            let (result, _) = play(&listener, spec);
            assert!(result.seats[0].forfeit);
            started.elapsed()
        });
        std::thread::sleep(Duration::from_millis(150));
        // Another game gives up on it meanwhile.
        listener.mark_absent(id);
        game.join().expect("game")
    });
    assert!(took >= wait, "the wait was cut short ({took:?})");
}

/// A bot that comes during the wait for the first tick and goes again
/// came: it forfeits for leaving, and later games still wait for it.
#[test]
fn a_bot_that_came_and_went_before_the_first_tick_is_not_marked_absent() {
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let (bot, answer) = Client::register(addr, "Flicker", None);
    let token = answer["token"].as_str().expect("token").to_string();
    let id = registered(&events);
    drop(bot);
    while listener.connected(id) {
        std::thread::sleep(Duration::from_millis(5));
    }
    let player = std::thread::spawn(move || {
        std::thread::sleep(Duration::from_millis(100));
        let mut back = Client::connect(addr);
        back.send(&json!({"type": "register", "protocol": 1, "token": token}));
        assert_eq!(back.next().expect("an answer")["type"], "registered");
        assert_eq!(back.next().expect("hello")["type"], "hello");
        // And gone, without a word.
    });
    let mut spec = spec(
        little_beach(30),
        vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
        50,
    );
    spec.forfeit_after = Duration::from_millis(500);
    let (result, log) = play(&listener, spec);
    player.join().expect("player");
    assert!(result.seats[0].forfeit);
    assert!(!log.contains("forfeit, never came"), "{log}");
    assert!(log.contains("left before the first tick"), "{log}");
    assert!(!listener.absent(id), "it came, so it is waited for again");
}

/// Under the fair cursor a bot's walk still under way when it drops does
/// not land: its seat idles from the moment the connection went.
#[test]
fn a_dropped_bots_walk_does_not_land_under_the_fair_cursor() {
    let (listener, events) = listen(Admission::Open);
    let (mut bot, _) = Client::register(listener.local_addr(), "Walker", None);
    let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
        panic!("no registration event");
    };
    let player = std::thread::spawn(move || {
        while let Some(msg) = bot.next() {
            if msg["type"] == "hello" {
                bot.send(&json!({"type": "ready", "game": msg["game"]}));
            }
            if msg["type"] == "tick" {
                // A post across the beach from its castle, a long walk
                // away, and gone before the hand gets there.
                bot.send(&json!({
                    "game": 7, "tick": msg["tick"], "act": "place", "x": 1, "y": 0, "dir": "down",
                }));
                return;
            }
        }
    });
    let mut spec = spec(
        little_beach(90),
        vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
        1000,
    );
    spec.fair_cursor = true;
    let (result, log) = play(&listener, spec);
    player.join().expect("player");
    assert!(log.contains("connection dropped"), "{log}");
    assert!(
        result
            .replay
            .inputs
            .iter()
            .all(|tick| tick[0] == crate::sim::PlayerAction::None),
        "the walk landed after the bot was gone"
    );
}

/// A LAN socket closed and opened again on the same port takes its first
/// bot: the stopped address is forgotten, not read as this loop's
/// wake-up.
#[test]
fn a_port_listened_on_again_takes_its_first_bot() {
    let (listener, _events) = listen(Admission::Open);
    let lan = listener
        .also_listen(SocketAddr::from(([127, 0, 0, 1], 0)))
        .expect("listen");
    listener.stop_listening(lan);
    // The old socket closes once its loop has woken and ended.
    let mut again = None;
    for _ in 0..200 {
        if let Ok(addr) = listener.also_listen(lan) {
            again = Some(addr);
            break;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    let again = again.expect("the port free again");
    assert_eq!(again, lan);
    let (_bot, answer) = Client::register(again, "First", None);
    assert_eq!(answer["type"], "registered", "{answer}");
}

/// A rival on the shared key declaring an invited owner's name takes none
/// of that owner's places: it is refused once the name is bound, and
/// counted apart if it declared it before.
#[test]
fn a_declared_owner_takes_none_of_an_invited_owners_places() {
    let shared = Key::draw();
    let alice = Key::draw();
    let mut config = Config::new(Admission::Keys(vec![invite(&shared, None)]));
    config.per_owner = Some(1);
    let (listener, _events) =
        Listener::bind(SocketAddr::from(([127, 0, 0, 1], 0)), config).expect("bind");
    let addr = listener.local_addr();
    let declare = |name: &str| {
        let mut client = Client::connect(addr);
        client.send(&json!({
            "type": "register", "protocol": 1, "name": name, "owner": "alice",
            "key": shared.to_string(),
        }));
        let answer = client.next().expect("answer");
        (client, answer)
    };
    // Before Alice is invited, a rival declares her name.
    let (_rival, answer) = declare("Rival");
    assert_eq!(answer["type"], "registered", "{answer}");
    listener.invite(Invite {
        key: alice.clone(),
        uses: None,
        owner: Some("Alice".into()),
        slot: None,
    });
    // Once she is, nobody else may.
    let (_late, answer) = declare("Late Rival");
    assert_eq!(answer["type"], "error", "{answer}");
    // And her own bot still gets in.
    let (_own, answer) = Client::register(addr, "Alice's", Some(&alice));
    assert_eq!(answer["type"], "registered", "{answer}");
    // The cup's draw counts them as two owners too: a two-seat table of
    // the rival and Alice is not one owner facing herself.
    let owners: Vec<Option<String>> = listener
        .bots()
        .iter()
        .map(|b| Some(b.owner_key()))
        .collect();
    assert_eq!(owners.len(), 2);
    assert_ne!(owners[0], owners[1]);
    assert!(super::draw::draw(&owners, 2, 1, 1, 7).is_ok());
}

/// A bot that drops and comes back with its token between two commits
/// does not have the reply it held on the old connection acted on: its
/// seat idled from the moment the connection went.
#[test]
fn a_reply_held_across_a_drop_and_a_return_is_not_acted_on() {
    use super::listener::GameMsg;
    use super::protocol::{Act, Reply};
    use super::seat::{BotDriver, Journal};
    use std::time::Instant;
    let mut bot = BotDriver::new(
        super::listener::BotId::default(),
        0,
        "Hopper".into(),
        true,
        Duration::from_millis(100),
    );
    let mut log = Vec::new();
    let mut console = |_: String| {};
    let mut journal = Journal {
        log: &mut log,
        console: &mut console,
        echo_notes: false,
        game: 7,
    };
    bot.take(GameMsg::Ready { seat: 0 }, 0, &mut journal);
    let now = Instant::now();
    bot.sent(3, now);
    let place = Act::Place {
        x: 1,
        y: 0,
        dir: Direction::Down,
    };
    let reply = Reply {
        game: 7,
        tick: 3,
        act: place,
        wait: 0,
        note: None,
        garbled: None,
    };
    bot.take(
        GameMsg::Reply {
            seat: 0,
            reply,
            at: now,
        },
        3,
        &mut journal,
    );
    bot.take(GameMsg::Dropped { seat: 0 }, 4, &mut journal);
    bot.take(GameMsg::Back { seat: 0, serial: 2 }, 4, &mut journal);
    assert!(bot.playing(), "it is back and ready");
    assert_eq!(bot.order(&mut journal), Act::None);
}

/// A coordinate is any byte to the protocol, so a placement can be aimed
/// far off the beach. The sim refuses it, as it refuses a castle, and the
/// bot hears why: nothing on the way may look for a post on a tile that is
/// not there.
#[test]
fn a_placement_far_off_the_beach_is_refused_and_not_a_crash() {
    for fair in [false, true] {
        let (listener, events) = listen(Admission::Open);
        let (mut bot, _) = Client::register(listener.local_addr(), "Wanderer", None);
        let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
            panic!("no registration event");
        };
        let player = std::thread::spawn(move || {
            let mut refused = None;
            while let Some(msg) = bot.next() {
                match msg["type"].as_str() {
                    Some("hello") => bot.send(&json!({"type": "ready", "game": 7})),
                    Some("tick") => {
                        let t = msg["tick"].clone();
                        if refused.is_none() && msg["you"]["last"]["accepted"] == false {
                            refused = Some(msg["you"]["last"]["reason"].clone());
                        }
                        bot.send(&json!({
                            "game": 7, "tick": t, "act": "place", "x": 200, "y": 200, "dir": "up",
                        }));
                    }
                    Some("end") => return refused,
                    _ => {}
                }
            }
            panic!("the connection closed before the end");
        });
        let mut spec = spec(
            little_beach(40),
            vec![Seat::Bot(id), Seat::Ai(BotLevel::Easy)],
            1000,
        );
        spec.fair_cursor = fair;
        let (result, _) = play(&listener, spec);
        let refused = player.join().expect("player");
        // Under the fair cursor the hand walks to the edge and the order
        // is refused there, as it is at once without the rule.
        assert_eq!(refused, Some(json!("off_board")), "fair cursor: {fair}");
        assert_eq!(result.replay.inputs.len(), 40, "the round played out");
    }
}

/// A bot registered with protocol 2 is sent each tick as what changed, and
/// holds, diff by diff, the board a protocol 1 bot at the same table is
/// sent whole: compared tick by tick, everything but the seat's own
/// `you`. It is sent a whole tick first, every `FULL_EVERY` ticks after,
/// and next whenever it asks with `resync`, which is how it recovers from
/// a diff it lost.
#[test]
fn a_protocol_2_bot_holds_by_diffs_what_a_protocol_1_bot_is_sent_whole() {
    use super::protocol::{FULL_EVERY, apply_delta};
    const TICKS: u32 = 400;
    let (listener, events) = listen(Admission::Open);
    let addr = listener.local_addr();
    let registered = |events: &Receiver<Event>| {
        let Ok(Event::Registered(id)) = events.recv_timeout(Duration::from_secs(5)) else {
            panic!("no registration event");
        };
        id
    };
    let (mut whole, _) = Client::register(addr, "Whole", None);
    let whole_id = registered(&events);
    let mut diffing = Client::connect(addr);
    diffing.send(&json!({"type": "register", "protocol": 2, "name": "Diffing"}));
    assert_eq!(diffing.next().expect("answer")["type"], "registered");
    let diffing_id = registered(&events);
    // Seat 0 is sent every tick whole, and places a post now and then so
    // the posts come and go.
    let whole_player = std::thread::spawn(move || {
        let mut seen = Vec::new();
        let mut sand = Vec::new();
        while let Some(msg) = whole.next() {
            match msg["type"].as_str() {
                Some("hello") => {
                    for (y, row) in msg["board"]["tiles"]
                        .as_array()
                        .expect("tiles")
                        .iter()
                        .enumerate()
                    {
                        for (x, c) in row.as_str().expect("row").chars().enumerate() {
                            if c == '.' {
                                sand.push((x, y));
                            }
                        }
                    }
                    whole.send(&json!({"type": "ready", "game": 7}));
                }
                Some("tick") => {
                    let t = msg["tick"].as_u64().expect("tick");
                    assert!(msg.get("base").is_none(), "protocol 1 is sent no diff");
                    let mut reply = json!({"game": 7, "tick": t, "act": "none"});
                    if t % 9 == 0 {
                        let (x, y) = sand[(t as usize * 7) % sand.len()];
                        reply = json!({"game": 7, "tick": t, "act": "place", "x": x, "y": y, "dir": "up"});
                    }
                    whole.send(&reply);
                    seen.push(msg);
                }
                Some("end") => return seen,
                _ => {}
            }
        }
        panic!("the connection closed before the end");
    });
    // Seat 1 applies every diff, but asks for a whole tick at 40, and
    // drops the diff for 100 as a bot that misread it would.
    let diffing_player = std::thread::spawn(move || {
        let mut held: Option<Value> = None;
        let mut seen = Vec::new();
        let mut whole_at = Vec::new();
        let mut refused = Vec::new();
        while let Some(msg) = diffing.next() {
            match msg["type"].as_str() {
                Some("hello") => diffing.send(&json!({"type": "ready", "game": 7})),
                Some("tick") => {
                    let t = msg["tick"].as_u64().expect("tick");
                    if msg.get("base").is_none() {
                        whole_at.push(t);
                    }
                    let lost = match (t == 100, apply_delta(held.as_ref(), &msg)) {
                        (true, _) => false,
                        (false, Some(state)) => {
                            seen.push(state.clone());
                            held = Some(state);
                            false
                        }
                        (false, None) => {
                            refused.push(t);
                            true
                        }
                    };
                    // Asked before this tick's act goes: the game deals
                    // the next tick the moment both acts are in, and a
                    // `resync` sent after the act raced it, the next tick
                    // shaped as a diff when it lost.
                    if lost || t == 40 {
                        diffing.send(&json!({"type": "resync", "game": 7}));
                    }
                    diffing.send(&json!({"game": 7, "tick": t, "act": "none"}));
                }
                Some("end") => return (seen, whole_at, refused),
                _ => {}
            }
        }
        panic!("the connection closed before the end");
    });
    let mut board = crate::sim::generate_arena(7, 2, 12, 9);
    crate::sim::set_versus_rules(&mut board, 240);
    board.rules_mut().round_length = Some(TICKS);
    let (result, _) = play(
        &listener,
        spec(
            board,
            vec![Seat::Bot(whole_id), Seat::Bot(diffing_id)],
            1000,
        ),
    );
    let sent_whole = whole_player.join().expect("whole");
    let (held, whole_at, refused) = diffing_player.join().expect("diffing");
    assert_eq!(result.replay.inputs.len(), TICKS as usize);
    // The tick after the one it asked at, the tick after the diff it
    // could not apply, and the first and every `FULL_EVERY` between.
    assert_eq!(refused, vec![101], "the diff after the one it dropped");
    assert!(whole_at.starts_with(&[0, 41, 102]), "whole at {whole_at:?}");
    assert!(
        whole_at.contains(&(102 + FULL_EVERY)),
        "whole at {whole_at:?}"
    );
    let mut compared = 0;
    for state in &held {
        let t = &state["tick"];
        let sent = sent_whole
            .iter()
            .find(|s| &s["tick"] == t)
            .expect("both seats are sent every tick");
        for (field, value) in sent.as_object().expect("a tick") {
            if field == "you" {
                continue;
            }
            let mut a = value.clone();
            let mut b = state[field].clone();
            for list in [&mut a, &mut b] {
                if let Some(entries) = list.as_array_mut() {
                    entries.sort_by_key(|e| e.to_string());
                }
            }
            assert_eq!(a, b, "{field} at tick {t}");
        }
        compared += 1;
    }
    assert_eq!(compared, TICKS as usize - 2, "all but 100 and 101");
    assert!(
        sent_whole
            .iter()
            .any(|s| !s["signposts"].as_array().expect("posts").is_empty()),
        "posts stood"
    );
}