cch23-validator 22.0.1

Validate solutions to challenges from Shuttle's Christmas Code Hunt 2023
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
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
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
pub mod args;

use std::{ops::Deref, sync::Arc};

use base64::{engine::general_purpose, Engine};
use futures_util::{
    stream::{SplitSink, SplitStream},
    SinkExt, StreamExt,
};
use reqwest::{
    header::{HeaderValue, CONTENT_TYPE},
    multipart::{Form, Part},
    redirect::Policy,
    StatusCode,
};
use tokio::{
    net::TcpStream,
    sync::mpsc::Sender,
    time::{sleep, Duration},
};
use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream};
use tracing::info;
use uuid::Uuid;

pub const SUPPORTED_CHALLENGES: &[i32] =
    &[-1, 1, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22];
pub const SUBMISSION_TIMEOUT: u64 = 60;

#[derive(Debug)]
pub enum SubmissionState {
    Waiting,
    Running,
    Done,
    Error,
}
impl std::fmt::Display for SubmissionState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

#[derive(Debug)]
pub enum SubmissionUpdate {
    /// State update
    State(SubmissionState),
    /// bool is true if this task was the last core task, int is amount of bonus points
    TaskCompleted(bool, i32),
    /// Append line to log
    LogLine(String),
    /// Save changes to db
    Save,
}
impl From<SubmissionState> for SubmissionUpdate {
    fn from(value: SubmissionState) -> Self {
        Self::State(value)
    }
}
impl From<(bool, i32)> for SubmissionUpdate {
    fn from((b, i): (bool, i32)) -> Self {
        Self::TaskCompleted(b, i)
    }
}
impl From<String> for SubmissionUpdate {
    fn from(value: String) -> Self {
        Self::LogLine(value)
    }
}

pub async fn run(url: String, id: Uuid, number: i32, tx: Sender<SubmissionUpdate>) {
    info!(%id, %url, %number, "Starting submission");

    tx.send(SubmissionState::Running.into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    tokio::select! {
        _ = validate(url.as_str(), number, tx.clone()) => (),
        _ = sleep(Duration::from_secs(SUBMISSION_TIMEOUT)) => {
            // if the validation task timed out
            info!(%id, %url, %number, "Submission timed out");
            tx.send("Timed out".to_owned().into()).await.unwrap();
            tx.send(SubmissionState::Done.into()).await.unwrap();
            tx.send(SubmissionUpdate::Save).await.unwrap();
        },
    };
    info!(%id, %url, %number, "Completed submission");
}

/// Task number and Test number in the current challenge
type TaskTest = (i32, i32);
/// If failure, return tuple with task number and test number that failed
type ValidateResult = std::result::Result<(), TaskTest>;

pub async fn validate(url: &str, number: i32, tx: Sender<SubmissionUpdate>) {
    if !SUPPORTED_CHALLENGES.contains(&number) {
        tx.send(
            format!("Validating Challenge {number} is not supported yet! Check for updates.")
                .into(),
        )
        .await
        .unwrap();
        return;
    }
    let txc = tx.clone();
    if let Err((task, test)) = match number {
        -1 => validate_minus1(url, txc).await,
        1 => validate_1(url, txc).await,
        4 => validate_4(url, txc).await,
        5 => validate_5(url, txc).await,
        6 => validate_6(url, txc).await,
        7 => validate_7(url, txc).await,
        8 => validate_8(url, txc).await,
        11 => validate_11(url, txc).await,
        12 => validate_12(url, txc).await,
        13 => validate_13(url, txc).await,
        14 => validate_14(url, txc).await,
        15 => validate_15(url, txc).await,
        18 => validate_18(url, txc).await,
        19 => validate_19(url, txc).await,
        20 => validate_20(url, txc).await,
        21 => validate_21(url, txc).await,
        22 => validate_22(url, txc).await,
        _ => unreachable!(),
    } {
        info!(%url, %number, %task, %test, "Submission failed");
        tx.send(format!("Task {task}: test #{test} failed 🟥").into())
            .await
            .unwrap();
    }
    tx.send(SubmissionState::Done.into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();
}

pub fn make_url(pn: Option<&str>) -> String {
    match pn {
        Some(pn) => format!("https://{pn}.shuttleapp.rs"),
        None => "http://localhost:8000".to_owned(),
    }
}

fn new_client() -> reqwest::Client {
    reqwest::ClientBuilder::new()
        .http1_only()
        .connect_timeout(Duration::from_secs(3))
        .redirect(Policy::limited(3))
        .referer(false)
        .timeout(Duration::from_secs(60))
        .build()
        .unwrap()
}

async fn validate_minus1(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1: respond 200
    test = (1, 1);
    let url = &format!("{}/", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2: respond 500
    test = (2, 1);
    let url = &format!("{}/-1/error", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::INTERNAL_SERVER_ERROR {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 0).into()).await.unwrap();

    Ok(())
}

async fn validate_1(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1: basic formula
    test = (1, 1);
    let url = &format!("{}/1/2/3", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "1" {
        return Err(test);
    }
    test = (1, 2);
    let url = &format!("{}/1/12/16", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "21952" {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2: multiple and zero and negative numbers
    test = (2, 1);
    let url = &format!("{}/1/3/5/7/9", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "512" {
        return Err(test);
    }
    test = (2, 2);
    let url = &format!("{}/1/0/0/0", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "0" {
        return Err(test);
    }
    test = (2, 3);
    let url = &format!("{}/1/-3/1", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "-64" {
        return Err(test);
    }
    test = (2, 4);
    let url = &format!("{}/1/3/5/7/9/2/13/12/16/18", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "729" {
        return Err(test);
    }
    tx.send((false, 100).into()).await.unwrap();

    Ok(())
}

async fn validate_4(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/4/strength", base_url);
    let res = client
        .post(url)
        .json(&serde_json::json!([
            {
              "name": "Zeus",
              "strength": 8
            },
            {
              "name": "Oner",
              "strength": 6
            },
            {
              "name": "Faker",
              "strength": 7
            },
            {
              "name": "Gumayusi",
              "strength": 6
            },
            {
              "name": "Keria",
              "strength": 6
            }
        ]))
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "33" {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!("{}/4/contest", base_url);
    let res = client
        .post(url)
        .json(&serde_json::json!([
        {
            "name": "Zeus",
            "strength": 8,
            "speed": 51.2,
            "height": 81,
            "antler_width": 31,
            "snow_magic_power": 311,
            "favorite_food": "pizza",
            "cAnD13s_3ATeN-yesT3rdAy": 4
        },
        {
            "name": "Oner",
            "strength": 6,
            "speed": 41.3,
            "height": 51,
            "antler_width": 30,
            "snow_magic_power": 321,
            "favorite_food": "burger",
            "cAnD13s_3ATeN-yesT3rdAy": 1
        },
        {
            "name": "Faker",
            "strength": 7,
            "speed": 50,
            "height": 50,
            "antler_width": 37,
            "snow_magic_power": 6667,
            "favorite_food": "broccoli",
            "cAnD13s_3ATeN-yesT3rdAy": 1
        },
        {
            "name": "Gumayusi",
            "strength": 6,
            "speed": 60.1,
            "height": 50,
            "antler_width": 34,
            "snow_magic_power": 2323,
            "favorite_food": "pizza",
            "cAnD13s_3ATeN-yesT3rdAy": 1
        },
        {
            "name": "Keria",
            "strength": 6,
            "speed": 48.2,
            "height": 65,
            "antler_width": 33,
            "snow_magic_power": 5014,
            "favorite_food": "wok",
            "cAnD13s_3ATeN-yesT3rdAy": 5
        }
        ]))
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "fastest":"Speeding past the finish line with a strength of 6 is Gumayusi",
            "tallest":"Zeus is standing tall with his 31 cm wide antlers",
            "magician":"Faker could blast you away with a snow magic power of 6667",
            "consumer":"Keria ate lots of candies, but also some wok"
        })
    {
        return Err(test);
    }
    tx.send((false, 150).into()).await.unwrap();

    Ok(())
}

async fn validate_5(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    // TASK 1
    let t = JSONTester::new(format!("{}/5?offset=0&limit=8", base_url));
    t.test(
        (1, 1),
        &serde_json::json!(["Ava", "Caleb", "Mia", "Owen", "Lily", "Ethan", "Zoe", "Nolan"]),
        StatusCode::OK,
        &serde_json::json!(["Ava", "Caleb", "Mia", "Owen", "Lily", "Ethan", "Zoe", "Nolan"]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?offset=10&limit=4", base_url));
    t.test(
        (1, 2),
        &serde_json::json!([
            "Ava", "Caleb", "Mia", "Owen", "Lily", "Ethan", "Zoe", "Nolan", "Harper", "Lucas",
            "Stella", "Mason", "Olivia", "Wyatt", "Isabella", "Logan",
        ]),
        StatusCode::OK,
        &serde_json::json!(["Stella", "Mason", "Olivia", "Wyatt"]),
    )
    .await?;
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    let t = JSONTester::new(format!("{}/5?offset=0&limit=5", base_url));
    t.test(
        (2, 1),
        &serde_json::json!([]),
        StatusCode::OK,
        &serde_json::json!([]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5", base_url));
    t.test(
        (2, 2),
        &serde_json::json!(["Alice", "Bob", "Charlie", "David"]),
        StatusCode::OK,
        &serde_json::json!(["Alice", "Bob", "Charlie", "David"]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?offset=2", base_url));
    t.test(
        (2, 3),
        &serde_json::json!(["Alice", "Bob", "Charlie", "David"]),
        StatusCode::OK,
        &serde_json::json!(["Charlie", "David"]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?offset=2&limit=0", base_url));
    t.test(
        (2, 4),
        &serde_json::json!(["Alice", "Bob", "Charlie", "David"]),
        StatusCode::OK,
        &serde_json::json!([]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?split=6", base_url));
    t.test(
        (2, 5),
        &serde_json::json!([
            "Alice", "Bob", "Charlie", "David", "Eva", "Frank", "Grace", "Hank", "Ivy", "Jack",
            "Katie", "Liam", "Mia", "Nathan", "Olivia", "Paul", "Quinn", "Rachel", "Samuel",
            "Tara", "Aria", "Jackson"
        ]),
        StatusCode::OK,
        &serde_json::json!([
            ["Alice", "Bob", "Charlie", "David", "Eva", "Frank"],
            ["Grace", "Hank", "Ivy", "Jack", "Katie", "Liam"],
            ["Mia", "Nathan", "Olivia", "Paul", "Quinn", "Rachel"],
            ["Samuel", "Tara", "Aria", "Jackson"]
        ]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?offset=2&limit=4&split=1", base_url));
    t.test(
        (2, 6),
        &serde_json::json!([
            "Alice", "Bob", "Charlie", "David", "Alice", "Bob", "Charlie", "David"
        ]),
        StatusCode::OK,
        &serde_json::json!([["Charlie"], ["David"], ["Alice"], ["Bob"],]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?limit=0", base_url));
    t.test(
        (2, 7),
        &serde_json::json!(["Alice", "Bob", "Charlie", "David"]),
        StatusCode::OK,
        &serde_json::json!([]),
    )
    .await?;
    let t = JSONTester::new(format!("{}/5?offset=0&limit=0", base_url));
    t.test(
        (2, 8),
        &serde_json::json!(["Alice", "Bob", "Charlie", "David"]),
        StatusCode::OK,
        &serde_json::json!([]),
    )
    .await?;
    tx.send((false, 150).into()).await.unwrap();

    Ok(())
}

async fn validate_6(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    let url = &format!("{}/6", base_url);
    // TASK 1: elf
    test = (1, 1);
    let res = client
        .post(url)
        .body("elf elf elf")
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json["elf"] != serde_json::Value::Number(3.into()) {
        return Err(test);
    }
    test = (1, 2);
    let res = client
        .post(url)
        .body("In the quirky town of Elf stood an enchanting shop named 'The Elf & Shelf.' Managed by Wally, a mischievous elf with a knack for crafting exquisite shelves, the shop was a bustling hub of elf after elf who wanter to see their dear elf in Belfast.")
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json["elf"] != serde_json::Value::Number(6.into()) {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2: more strings
    test = (2, 1);
    let res = client
        .post(url)
        .body("elf elf elf on a shelf")
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "elf":4,
            "elf on a shelf":1,
            "shelf with no elf on it":0
        })
    {
        return Err(test);
    }
    test = (2, 2);
    let res = client
        .post(url)
        .body("In Belfast I heard an elf on a shelf on a shelf on a ")
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "elf":4,
            "elf on a shelf":2,
            "shelf with no elf on it":0
        })
    {
        return Err(test);
    }
    test = (2, 3);
    let res = client
        .post(url)
        .body("Somewhere in Belfast under a shelf store but above the shelf realm there's an elf on a shelf on a shelf on a shelf on a elf on a shelf on a shelf on a shelf on a shelf on a elf on a elf on a elf on a shelf on a ")
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "elf":16,
            "elf on a shelf":8,
            "shelf with no elf on it":2
        })
    {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 200).into()).await.unwrap();

    Ok(())
}

async fn validate_7(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/7/decode", base_url);
    let data = serde_json::json!({
        "recipe": {
            "flour": 4,
            "sugar": 3,
            "butter": 3,
            "baking powder": 1,
            "raisins": 50
        },
    });
    let b64 = general_purpose::STANDARD.encode(serde_json::to_vec(&data).unwrap());
    let res = client
        .get(url)
        .header("Cookie", format!("recipe={b64}"))
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != data {
        return Err(test);
    }
    test = (1, 2);
    let data = serde_json::json!({
        "recipe": {
            "peanuts": 26,
            "dough": 37,
            "extra salt": 1,
            "raisins": 50
        },
    });
    let b64 = general_purpose::STANDARD.encode(serde_json::to_vec(&data).unwrap());
    let res = client
        .get(url)
        .header("Cookie", format!("recipe={b64}"))
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != data {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    let url = &format!("{}/7/bake", base_url);
    let test_bake = |test: (i32, i32), i: serde_json::Value, o: serde_json::Value| async move {
        let client = new_client();
        let b64 = general_purpose::STANDARD.encode(serde_json::to_vec(&i).unwrap());
        let res = client
            .get(url)
            .header("Cookie", format!("recipe={b64}"))
            .send()
            .await
            .map_err(|_| test)?;
        let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
        if json != o {
            return Err(test);
        }
        Ok(())
    };
    test = (2, 1);
    test_bake(
        test,
        serde_json::json!({
            "recipe": {
                "flour": 35,
                "sugar": 56,
                "butter": 3,
                "baking powder": 1001,
                "chocolate chips": 55
            },
            "pantry": {
                "flour": 4045,
                "sugar": 9606,
                "butter": 99, // will land at 0
                "baking powder": 8655432,
                "chocolate chips": 4587
            }
        }),
        serde_json::json!({
            "cookies": 33,
            "pantry": {
                "flour": 2890,
                "sugar": 7758,
                "butter": 0,
                "baking powder": 8622399,
                "chocolate chips": 2772
            }
        }),
    )
    .await?;
    test = (2, 2);
    test_bake(
        test,
        serde_json::json!({
            "recipe": {
                "flour": 35,
                "sugar": 56,
                "butter": 3,
                "baking powder": 1001,
                "chocolate chips": 55
            },
            "pantry": {
                "flour": 4045,
                "sugar": 7606,
                "butter": 100,
                "baking powder": 865543211516164409i64,
                "chocolate chips": 4587
            }
        }),
        serde_json::json!({
            "cookies": 33,
            "pantry": {
                "flour": 2890,
                "sugar": 5758,
                "butter": 1,
                "baking powder": 865543211516131376i64,
                "chocolate chips": 2772
            }
        }),
    )
    .await?;
    // TASK 2 DONE
    tx.send((false, 120).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 3
    test = (3, 1);
    test_bake(
        test,
        serde_json::json!({
            "recipe": {
                "chicken": 1,
            },
            "pantry": {
                "chicken": 0,
            }
        }),
        serde_json::json!({
            "cookies": 0,
            "pantry": {
                "chicken": 0,
            }
        }),
    )
    .await?;
    test = (3, 2);
    test_bake(
        test,
        serde_json::json!({
            "recipe": {
                "cocoa bean": 1,
                "chicken": 0,
            },
            "pantry": {
                "cocoa bean": 5,
                "corn": 5,
                "cucumber": 0,
            }
        }),
        serde_json::json!({
            "cookies": 5,
            "pantry": {
                "cocoa bean": 0,
                "corn": 5,
                "cucumber": 0,
            }
        }),
    )
    .await?;
    test = (3, 3);
    test_bake(
        test,
        serde_json::json!({
            "recipe": {
                "cocoa bean": 1,
                "chicken": 0,
            },
            "pantry": {
                "cocoa bean": 5,
                "chicken": 0,
            }
        }),
        serde_json::json!({
            "cookies": 5,
            "pantry": {
                "cocoa bean": 0,
                "chicken": 0,
            }
        }),
    )
    .await?;
    test = (3, 4);
    test_bake(
        test,
        serde_json::json!({
            "recipe": {
                "cocoa bean": 1,
                "chicken": 0,
            },
            "pantry": {
                "cocoa bean": 5,
            }
        }),
        serde_json::json!({
            "cookies": 5,
            "pantry": {
                "cocoa bean": 0,
            }
        }),
    )
    .await?;
    // TASK 3 DONE
    tx.send((false, 100).into()).await.unwrap();

    Ok(())
}

async fn validate_8(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    let tol = 0.001f64;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/8/weight/225", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    let num: f64 = text.parse().map_err(|_| test)?;
    if !(num.is_finite() && (num - 16f64).abs() < tol) {
        return Err(test);
    }
    test = (1, 2);
    let url = &format!("{}/8/weight/393", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    let num: f64 = text.parse().map_err(|_| test)?;
    if !(num.is_finite() && (num - 5.2f64).abs() < tol) {
        return Err(test);
    }
    test = (1, 3);
    let url = &format!("{}/8/weight/92", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    let num: f64 = text.parse().map_err(|_| test)?;
    if !(num.is_finite() && (num - 0.1f64).abs() < tol) {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!("{}/8/drop/383", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    let num: f64 = text.parse().map_err(|_| test)?;
    if !(num.is_finite() && (num - 13316.953480432378f64).abs() < tol) {
        return Err(test);
    }
    test = (2, 2);
    let url = &format!("{}/8/drop/16", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    let num: f64 = text.parse().map_err(|_| test)?;
    if !(num.is_finite() && (num - 25.23212238397714f64).abs() < tol) {
        return Err(test);
    }
    test = (2, 3);
    let url = &format!("{}/8/drop/143", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    let num: f64 = text.parse().map_err(|_| test)?;
    if !(num.is_finite() && (num - 6448.2090536830465f64).abs() < tol) {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 160).into()).await.unwrap();

    Ok(())
}

async fn validate_11(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/11/assets/decoration.png", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let headers = res.headers();
    if !headers
        .get("content-type")
        .is_some_and(|v| v == "image/png")
    {
        return Err(test);
    }
    if !headers.get("content-length").is_some_and(|v| v == "787297") {
        return Err(test);
    }
    let bytes = res.bytes().await.map_err(|_| test)?;
    const EXPECTED: &[u8] = include_bytes!("../assets/decoration.png");
    if bytes.to_vec().as_slice() != EXPECTED {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!("{}/11/red_pixels", base_url);
    let form = Form::new().part(
        "image",
        Part::bytes(include_bytes!("../assets/decoration2.png").as_slice())
            .file_name("decoration2.png")
            .mime_str("image/png")
            .unwrap(),
    );
    let res = client
        .post(url)
        .multipart(form)
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "152107" {
        return Err(test);
    }
    test = (2, 2);
    let form = Form::new().part(
        "image",
        Part::bytes(include_bytes!("../assets/decoration3.png").as_slice())
            .file_name("decoration3.png")
            .mime_str("image/png")
            .unwrap(),
    );
    let res = client
        .post(url)
        .multipart(form.into())
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "40263" {
        return Err(test);
    }
    test = (2, 3);
    let form = Form::new().part(
        "image",
        Part::bytes(include_bytes!("../assets/decoration4.png").as_slice())
            .file_name("decoration4.png")
            .mime_str("image/png")
            .unwrap(),
    );
    let res = client
        .post(url)
        .multipart(form.into())
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "86869" {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 200).into()).await.unwrap();

    Ok(())
}

async fn validate_12(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/12/save/cch23", base_url);
    let res = client.post(url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    sleep(Duration::from_secs(2)).await;
    let url = &format!("{}/12/load/cch23", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "2" {
        return Err(test);
    }
    sleep(Duration::from_secs(2)).await;
    let url = &format!("{}/12/load/cch23", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "4" {
        return Err(test);
    }
    test = (1, 2);
    let url = &format!("{}/12/save/alpha", base_url);
    let res = client.post(url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    sleep(Duration::from_secs(2)).await;
    let url = &format!("{}/12/save/omega", base_url);
    let res = client.post(url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    sleep(Duration::from_secs(2)).await;
    let url = &format!("{}/12/load/alpha", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "4" {
        return Err(test);
    }
    let url = &format!("{}/12/save/alpha", base_url);
    let res = client.post(url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    sleep(Duration::from_secs(1)).await;
    let url = &format!("{}/12/load/omega", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "3" {
        return Err(test);
    }
    let url = &format!("{}/12/load/alpha", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "1" {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!("{}/12/ulids", base_url);
    let res = client
        .post(url)
        .json(&serde_json::json!([
            "01BJQ0E1C3Z56ABCD0E11HYX4M",
            "01BJQ0E1C3Z56ABCD0E11HYX5N",
            "01BJQ0E1C3Z56ABCD0E11HYX6Q",
            "01BJQ0E1C3Z56ABCD0E11HYX7R",
            "01BJQ0E1C3Z56ABCD0E11HYX8P"
        ]))
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!([
            "015cae07-0583-f94c-a5b1-a070431f7516",
            "015cae07-0583-f94c-a5b1-a070431f74f8",
            "015cae07-0583-f94c-a5b1-a070431f74d7",
            "015cae07-0583-f94c-a5b1-a070431f74b5",
            "015cae07-0583-f94c-a5b1-a070431f7494"
        ])
    {
        return Err(test);
    }
    test = (2, 2);
    let res = client
        .post(url)
        .json(&serde_json::json!([]))
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != serde_json::json!([]) {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 100).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 3
    test = (3, 1);
    let ids = serde_json::json!([
        "00WEGGF0G0J5HEYXS3D7RWZGV8",
        "76EP4G39R8JD1N8AQNYDVJBRCF",
        "018CJ7KMG0051CDCS3B7BFJ3AK",
        "00Y986KPG0AMGB78RD45E9109K",
        "010451HTG0NYWMPWCEXG6AJ8F2",
        "01HH9SJEG0KY16H81S3N1BMXM4",
        "01HH9SJEG0P9M22Z9VGHH9C8CX",
        "017F8YY0G0NQA16HHC2QT5JD6X",
        "03QCPC7P003V1NND3B3QJW72QJ"
    ]);
    let url = &format!("{}/12/ulids/5", base_url);
    let res = client.post(url).json(&ids).send().await.map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "christmas eve": 3,
            "weekday": 1,
            "in the future": 2,
            "LSB is 1": 5
        })
    {
        return Err(test);
    }
    test = (3, 2);
    let url = &format!("{}/12/ulids/0", base_url);
    let res = client.post(url).json(&ids).send().await.map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "christmas eve": 3,
            "weekday": 0,
            "in the future": 2,
            "LSB is 1": 5
        })
    {
        return Err(test);
    }
    test = (3, 3);
    let url = &format!("{}/12/ulids/2", base_url);
    let res = client
        .post(url)
        .json(&serde_json::json!(["04BJK8N300BAMR9SQQWPWHVYKZ"]))
        .send()
        .await
        .map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json
        != serde_json::json!({
            "christmas eve": 1,
            "weekday": 1,
            "in the future": 1,
            "LSB is 1": 1
        })
    {
        return Err(test);
    }
    // TASK 3 DONE
    tx.send((false, 200).into()).await.unwrap();

    Ok(())
}

async fn validate_13(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/13/sql", base_url);
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "20231213" {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((false, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let reset_url = &format!("{}/13/reset", base_url);
    let order_url = &format!("{}/13/orders", base_url);
    let total_url = &format!("{}/13/orders/total", base_url);
    let res = client.post(reset_url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    let res = client
        .post(order_url)
        .json(&serde_json::json!([
            {"id":1,"region_id":2,"gift_name":"Toy Train","quantity":5},
            {"id":2,"region_id":2,"gift_name":"Doll","quantity":8},
            {"id":3,"region_id":3,"gift_name":"Action Figure","quantity":12},
            {"id":4,"region_id":4,"gift_name":"Board Game","quantity":10},
            {"id":5,"region_id":2,"gift_name":"Teddy Bear","quantity":6},
            {"id":6,"region_id":3,"gift_name":"Toy Train","quantity":3},
        ]))
        .send()
        .await
        .map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    let res = client.get(total_url).send().await.map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != serde_json::json!({"total": 44}) {
        return Err(test);
    }
    test = (2, 2);
    let res = client
        .post(order_url)
        .json(&serde_json::json!([
            {"id":123,"region_id":6,"gift_name":"Unknown","quantity":333},
        ]))
        .send()
        .await
        .map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    let res = client.get(total_url).send().await.map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != serde_json::json!({"total": 377}) {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 3
    test = (3, 1);
    let popular_url = &format!("{}/13/orders/popular", base_url);
    let res = client.post(reset_url).send().await.map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    let res = client.get(popular_url).send().await.map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != serde_json::json!({"popular": null}) {
        return Err(test);
    }
    test = (3, 2);
    let res = client
        .post(order_url)
        .json(&serde_json::json!([
            {"id":1,"region_id":2,"gift_name":"Lego Rocket","quantity":12},
            {"id":2,"region_id":2,"gift_name":"Action Figure","quantity":18},
            {"id":3,"region_id":5,"gift_name":"Toy Train","quantity":19},
            {"id":4,"region_id":5,"gift_name":"Lego Rocket","quantity":12},
            {"id":5,"region_id":4,"gift_name":"Toy Train","quantity":15},
            {"id":6,"region_id":2,"gift_name":"Toy Train","quantity":7},
            {"id":7,"region_id":3,"gift_name":"Toy Train","quantity":19},
            {"id":8,"region_id":4,"gift_name":"Action Figure","quantity":8},
            {"id":9,"region_id":2,"gift_name":"Toy Axe","quantity":15},
            {"id":10,"region_id":4,"gift_name":"Toy Axe","quantity":1},
            {"id":11,"region_id":2,"gift_name":"Toy Train","quantity":17},
            {"id":12,"region_id":4,"gift_name":"Toy Train","quantity":5},
            {"id":13,"region_id":4,"gift_name":"Sweater","quantity":20},
            {"id":14,"region_id":4,"gift_name":"Action Figure","quantity":7},
            {"id":15,"region_id":2,"gift_name":"Toy Train","quantity":16},
            {"id":16,"region_id":3,"gift_name":"Action Figure","quantity":12},
            {"id":17,"region_id":4,"gift_name":"Toy Axe","quantity":2},
            {"id":18,"region_id":3,"gift_name":"Toy Train","quantity":9},
            {"id":19,"region_id":2,"gift_name":"Sweater","quantity":9},
            {"id":20,"region_id":5,"gift_name":"Toy Train","quantity":9},
            {"id":21,"region_id":4,"gift_name":"Action Figure","quantity":11},
            {"id":22,"region_id":3,"gift_name":"Toy Train","quantity":7},
            {"id":23,"region_id":2,"gift_name":"Action Figure","quantity":5},
            {"id":24,"region_id":4,"gift_name":"Action Figure","quantity":17},
            {"id":25,"region_id":5,"gift_name":"Lego Rocket","quantity":6},
            {"id":26,"region_id":2,"gift_name":"Sweater","quantity":5},
            {"id":27,"region_id":5,"gift_name":"Toy Train","quantity":4},
            {"id":28,"region_id":4,"gift_name":"Lego Rocket","quantity":8},
            {"id":29,"region_id":2,"gift_name":"Toy Train","quantity":3},
            {"id":30,"region_id":4,"gift_name":"Toy Axe","quantity":20},
            {"id":31,"region_id":2,"gift_name":"Action Figure","quantity":5},
            {"id":32,"region_id":2,"gift_name":"Lego Rocket","quantity":10},
            {"id":33,"region_id":5,"gift_name":"Toy Train","quantity":4},
            {"id":34,"region_id":2,"gift_name":"Toy Axe","quantity":14},
            {"id":35,"region_id":3,"gift_name":"Action Figure","quantity":18},
            {"id":36,"region_id":5,"gift_name":"Toy Axe","quantity":10},
            {"id":37,"region_id":4,"gift_name":"Lego Rocket","quantity":6},
            {"id":38,"region_id":4,"gift_name":"Action Figure","quantity":16},
            {"id":39,"region_id":4,"gift_name":"Toy Axe","quantity":15},
            {"id":40,"region_id":5,"gift_name":"Lego Rocket","quantity":15},
            {"id":41,"region_id":5,"gift_name":"Action Figure","quantity":7},
            {"id":42,"region_id":3,"gift_name":"Action Figure","quantity":16},
            {"id":43,"region_id":3,"gift_name":"Toy Train","quantity":8},
            {"id":44,"region_id":4,"gift_name":"Action Figure","quantity":13},
            {"id":45,"region_id":3,"gift_name":"Lego Rocket","quantity":12},
            {"id":46,"region_id":3,"gift_name":"Toy Train","quantity":1},
            {"id":47,"region_id":2,"gift_name":"Toy Train","quantity":11},
            {"id":48,"region_id":5,"gift_name":"Action Figure","quantity":1},
            {"id":49,"region_id":4,"gift_name":"Toy Train","quantity":13},
            {"id":50,"region_id":5,"gift_name":"Action Figure","quantity":16},
            {"id":51,"region_id":4,"gift_name":"Toy Axe","quantity":19},
            {"id":52,"region_id":2,"gift_name":"Toy Train","quantity":14},
            {"id":53,"region_id":3,"gift_name":"Action Figure","quantity":16},
        ]))
        .send()
        .await
        .map_err(|_| test)?;
    if res.status() != StatusCode::OK {
        return Err(test);
    }
    let res = client.get(popular_url).send().await.map_err(|_| test)?;
    let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
    if json != serde_json::json!({"popular": "Action Figure"}) {
        return Err(test);
    }
    // TASK 3 DONE
    tx.send((false, 100).into()).await.unwrap();

    Ok(())
}

async fn validate_14(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/14/unsafe", base_url);
    let res = client
        .post(url)
        .json(&serde_json::json!({"content": "Bing Chilling 🥶🍦"}))
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text
        != "\
<html>
  <head>
    <title>CCH23 Day 14</title>
  </head>
  <body>
    Bing Chilling 🥶🍦
  </body>
</html>"
    {
        return Err(test);
    }
    test = (1, 2);
    let res = client
        .post(url)
        .json(&serde_json::json!({"content": r#"<script>alert("XSS Attack Success!")</script>"#}))
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text
        != "\
<html>
  <head>
    <title>CCH23 Day 14</title>
  </head>
  <body>
    <script>alert(\"XSS Attack Success!\")</script>
  </body>
</html>"
    {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!("{}/14/safe", base_url);
    let res = client
        .post(url)
        .json(&serde_json::json!({"content": r#"<script>alert("XSS Attack Failed!")</script>"#}))
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text
        != "\
<html>
  <head>
    <title>CCH23 Day 14</title>
  </head>
  <body>
    &lt;script&gt;alert(&quot;XSS Attack Failed!&quot;)&lt;/script&gt;
  </body>
</html>"
    {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 100).into()).await.unwrap();

    Ok(())
}

struct JSONTester {
    client: reqwest::Client,
    url: String,
}

impl JSONTester {
    fn new(url: String) -> Self {
        Self {
            client: new_client(),
            url,
        }
    }
    async fn test(
        &self,
        test: TaskTest,
        i: &serde_json::Value,
        code: StatusCode,
        o: &serde_json::Value,
    ) -> ValidateResult {
        let res = self
            .client
            .post(&self.url)
            .json(i)
            .send()
            .await
            .map_err(|_| test)?;
        if res.status() != code {
            return Err(test);
        }
        let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
        if json != *o {
            return Err(test);
        }
        Ok(())
    }
}

async fn validate_15(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    // TASK 1
    let t = JSONTester::new(format!("{}/15/nice", base_url));
    t.test(
        (1, 1),
        &serde_json::json!({"input": "hello there"}),
        StatusCode::OK,
        &serde_json::json!({"result": "nice"}),
    )
    .await?;
    t.test(
        (1, 2),
        &serde_json::json!({"input": "he77o there"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty"}),
    )
    .await?;
    t.test(
        (1, 3),
        &serde_json::json!({"input": "hello"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty"}),
    )
    .await?;
    t.test(
        (1, 4),
        &serde_json::json!({"input": "hello xylophone"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty"}),
    )
    .await?;
    t.test(
        (1, 5),
        &serde_json::json!({"input": "password"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty"}),
    )
    .await?;
    let test = (1, 6);
    let res = new_client()
        .post(format!("{}/15/nice", base_url))
        .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
        .body("WooooOOOooOOOoooOO 👻")
        .send()
        .await
        .map_err(|_| test)?;
    if res.status() != StatusCode::BAD_REQUEST {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    let t = JSONTester::new(format!("{}/15/game", base_url));
    t.test(
        (2, 1),
        &serde_json::json!({"input": "mario"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "8 chars"}),
    )
    .await?;
    t.test(
        (2, 2),
        &serde_json::json!({"input": "mariobro"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "more types of chars"}),
    )
    .await?;
    t.test(
        (2, 3),
        &serde_json::json!({"input": "EEEEEEEEEEE"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "more types of chars"}),
    )
    .await?;
    t.test(
        (2, 4),
        &serde_json::json!({"input": "E3E3E3E3E3E"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "more types of chars"}),
    )
    .await?;
    t.test(
        (2, 5),
        &serde_json::json!({"input": "e3E3e#eE#ee3#EeE3"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "55555"}),
    )
    .await?;
    t.test(
        (2, 6),
        &serde_json::json!({"input": "Password12345"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "math is hard"}),
    )
    .await?;
    t.test(
        (2, 7),
        &serde_json::json!({"input": "2 00 2 3 OOgaBooga"}),
        StatusCode::BAD_REQUEST,
        &serde_json::json!({"result": "naughty", "reason": "math is hard"}),
    )
    .await?;
    t.test(
        (2, 8),
        &serde_json::json!({"input": "2+2/2-8*8 = 1-2000 OOgaBooga"}),
        StatusCode::NOT_ACCEPTABLE,
        &serde_json::json!({"result": "naughty", "reason": "not joyful enough"}),
    )
    .await?;
    t.test(
        (2, 9),
        &serde_json::json!({"input": "2000.23.A yoyoj"}),
        StatusCode::NOT_ACCEPTABLE,
        &serde_json::json!({"result": "naughty", "reason": "not joyful enough"}),
    )
    .await?;
    t.test(
        (2, 10),
        &serde_json::json!({"input": "2000.23.A joy joy"}),
        StatusCode::NOT_ACCEPTABLE,
        &serde_json::json!({"result": "naughty", "reason": "not joyful enough"}),
    )
    .await?;
    t.test(
        (2, 11),
        &serde_json::json!({"input": "2000.23.A joyo"}),
        StatusCode::NOT_ACCEPTABLE,
        &serde_json::json!({"result": "naughty", "reason": "not joyful enough"}),
    )
    .await?;
    t.test(
        (2, 12),
        &serde_json::json!({"input": "2000.23.A j  ;)  o  ;)  y "}),
        StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS,
        &serde_json::json!({"result": "naughty", "reason": "illegal: no sandwich"}),
    )
    .await?;
    t.test(
        (2, 13),
        &serde_json::json!({"input": "2020.3.A j  ;)  o  ;)  y"}),
        StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS,
        &serde_json::json!({"result": "naughty", "reason": "illegal: no sandwich"}),
    )
    .await?;
    t.test(
        (2, 14),
        &serde_json::json!({"input": "2000.23.A j  ;)  o  ;)  y AzA"}),
        StatusCode::RANGE_NOT_SATISFIABLE,
        &serde_json::json!({"result": "naughty", "reason": "outranged"}),
    )
    .await?;
    t.test(
        (2, 15),
        &serde_json::json!({"input": "2000.23.A j  ;)  o  ;)  y⥿ AzA"}),
        StatusCode::RANGE_NOT_SATISFIABLE,
        &serde_json::json!({"result": "naughty", "reason": "outranged"}),
    )
    .await?;
    t.test(
        (2, 16),
        &serde_json::json!({"input": "2000.23.A j  ;)  o  ;)  y ⦄AzA"}),
        StatusCode::UPGRADE_REQUIRED,
        &serde_json::json!({"result": "naughty", "reason": "😳"}),
    )
    .await?;
    t.test(
        (2, 17),
        &serde_json::json!({"input": "2000.23.A j  🥶  o  🍦  y ⦄AzA"}),
        StatusCode::IM_A_TEAPOT,
        &serde_json::json!({"result": "naughty", "reason": "not a coffee brewer"}),
    )
    .await?;
    t.test(
        (2, 18),
        &serde_json::json!({"input": "2000.23.A j ⦖⦖⦖⦖⦖⦖⦖⦖ 🥶  o  🍦  y ⦄AzA"}),
        StatusCode::OK,
        &serde_json::json!({"result": "nice", "reason": "that's a nice password"}),
    )
    .await?;
    // TASK 2 DONE
    tx.send((false, 400).into()).await.unwrap();

    Ok(())
}

struct RegionGiftTester {
    client: reqwest::Client,
    reset_url: String,
    regions_url: String,
    orders_url: String,
    final_url: String,
}

impl RegionGiftTester {
    async fn test(
        &self,
        test: TaskTest,
        i1: &serde_json::Value,
        i2: &serde_json::Value,
        o: &serde_json::Value,
    ) -> ValidateResult {
        let res = self
            .client
            .post(&self.reset_url)
            .send()
            .await
            .map_err(|_| test)?;
        if res.status() != StatusCode::OK {
            return Err(test);
        }
        let res = self
            .client
            .post(&self.regions_url)
            .json(i1)
            .send()
            .await
            .map_err(|_| test)?;
        if res.status() != StatusCode::OK {
            return Err(test);
        }
        let res = self
            .client
            .post(&self.orders_url)
            .json(i2)
            .send()
            .await
            .map_err(|_| test)?;
        if res.status() != StatusCode::OK {
            return Err(test);
        }
        let res = self
            .client
            .get(&self.final_url)
            .send()
            .await
            .map_err(|_| test)?;
        if res.status() != StatusCode::OK {
            return Err(test);
        }
        let json = res.json::<serde_json::Value>().await.map_err(|_| test)?;
        if json != *o {
            return Err(test);
        }
        Ok(())
    }
}

async fn validate_18(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    // TASK 1
    let t = RegionGiftTester {
        client: new_client(),
        reset_url: format!("{}/18/reset", base_url),
        regions_url: format!("{}/18/regions", base_url),
        orders_url: format!("{}/18/orders", base_url),
        final_url: format!("{}/18/regions/total", base_url),
    };
    t.test(
        (1, 1),
        &serde_json::json!([{"id":1,"name":"North Pole"}]),
        &serde_json::json!([]),
        &serde_json::json!([]),
    )
    .await?;
    t.test(
        (1, 2),
        &serde_json::json!([]),
        &serde_json::json!([{"id":1,"region_id":2,"gift_name":"Board Game","quantity":5}]),
        &serde_json::json!([]),
    )
    .await?;
    t.test(
        (1, 3),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([{"id":1,"region_id":1,"gift_name":"A","quantity":1}]),
        &serde_json::json!([{"region":"A","total":1}]),
    )
    .await?;
    t.test(
        (1, 4),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([
            {"id":1,"region_id":1,"gift_name":"A","quantity":1},
            {"id":2,"region_id":1,"gift_name":"A","quantity":1},
            {"id":3,"region_id":1,"gift_name":"A","quantity":1}
        ]),
        &serde_json::json!([{"region":"A","total":3}]),
    )
    .await?;
    t.test(
        (1, 5),
        &serde_json::json!([
            {"id":1,"name":"A"},
            {"id":2,"name":"B"}
        ]),
        &serde_json::json!([
            {"id":1,"region_id":1,"gift_name":"A","quantity":1},
            {"id":2,"region_id":1,"gift_name":"A","quantity":1},
            {"id":3,"region_id":2,"gift_name":"B","quantity":1}
        ]),
        &serde_json::json!([
            {"region":"A","total":2},
            {"region":"B","total":1}
        ]),
    )
    .await?;
    t.test(
        (1, 6),
        &serde_json::json!([
            {"id":1,"name":"A"},
            {"id":2,"name":"B"}
        ]),
        &serde_json::json!([
            {"id":1,"region_id":1,"gift_name":"A","quantity":1},
            {"id":2,"region_id":1,"gift_name":"A","quantity":1},
            {"id":3,"region_id":3,"gift_name":"C","quantity":1}
        ]),
        &serde_json::json!([{"region":"A","total":2}]),
    )
    .await?;
    t.test(
        (1, 7),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([{"id":1,"region_id":1,"gift_name":"A","quantity":555555555}]),
        &serde_json::json!([{"region":"A","total":555555555}]),
    )
    .await?;
    t.test(
        (1, 8),
        &serde_json::json!([{"id":-1,"name":"A"}]),
        &serde_json::json!([
            {"id":-1,"region_id":-1,"gift_name":"A","quantity":-1},
            {"id":0,"region_id":-1,"gift_name":"A","quantity":1}
        ]),
        &serde_json::json!([{"region":"A","total":0}]),
    )
    .await?;
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    let t = RegionGiftTester {
        client: new_client(),
        reset_url: format!("{}/18/reset", base_url),
        regions_url: format!("{}/18/regions", base_url),
        orders_url: format!("{}/18/orders", base_url),
        final_url: format!("{}/18/regions/top_list/2", base_url),
    };
    t.test(
        (2, 1),
        &serde_json::json!([]),
        &serde_json::json!([]),
        &serde_json::json!([]),
    )
    .await?;
    t.test(
        (2, 2),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([]),
        &serde_json::json!([{"region":"A","top_gifts":[]}]),
    )
    .await?;
    t.test(
        (2, 3),
        &serde_json::json!([]),
        &serde_json::json!([{"id":1,"region_id":2,"gift_name":"B","quantity":5}]),
        &serde_json::json!([]),
    )
    .await?;
    t.test(
        (2, 4),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([{"id":1,"region_id":2,"gift_name":"B","quantity":5}]),
        &serde_json::json!([{"region":"A","top_gifts":[]}]),
    )
    .await?;
    t.test(
        (2, 5),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([
            {"id":1,"region_id":1,"gift_name":"B","quantity":10},
            {"id":2,"region_id":1,"gift_name":"A","quantity":5},
            {"id":3,"region_id":1,"gift_name":"A","quantity":5},
            {"id":4,"region_id":1,"gift_name":"C","quantity":9}
        ]),
        &serde_json::json!([{"region":"A","top_gifts":["A","B"]}]),
    )
    .await?;
    let regions = serde_json::json!([
        {"id":1,"name":"North Pole"},
        {"id":2,"name":"Europe"},
        {"id":3,"name":"North America"},
        {"id":4,"name":"South America"},
        {"id":5,"name":"Africa"},
        {"id":6,"name":"Asia"},
        {"id":7,"name":"Oceania"}
    ]);
    t.test(
        (2, 6),
        &regions,
        &serde_json::json!([
            {"id":1,"region_id":2,"gift_name":"Toy Train","quantity":5},
            {"id":2,"region_id":2,"gift_name":"Toy Train","quantity":3},
            {"id":3,"region_id":2,"gift_name":"Doll","quantity":8},
            {"id":4,"region_id":3,"gift_name":"Toy Train","quantity":3},
            {"id":5,"region_id":2,"gift_name":"Teddy Bear","quantity":6},
            {"id":6,"region_id":3,"gift_name":"Action Figure","quantity":12},
            {"id":7,"region_id":4,"gift_name":"Board Game","quantity":10},
            {"id":8,"region_id":3,"gift_name":"Teddy Bear","quantity":1},
            {"id":9,"region_id":3,"gift_name":"Teddy Bear","quantity":2}
        ]),
        &serde_json::json!([
            {"region":"Africa","top_gifts":[]},
            {"region":"Asia","top_gifts":[]},
            {"region":"Europe","top_gifts":["Doll","Toy Train"]},
            {"region":"North America","top_gifts":["Action Figure","Teddy Bear"]},
            {"region":"North Pole","top_gifts":[]},
            {"region":"Oceania","top_gifts":[]},
            {"region":"South America","top_gifts":["Board Game"]},
        ]),
    )
    .await?;
    let t = RegionGiftTester {
        client: new_client(),
        reset_url: format!("{}/18/reset", base_url),
        regions_url: format!("{}/18/regions", base_url),
        orders_url: format!("{}/18/orders", base_url),
        final_url: format!("{}/18/regions/top_list/3", base_url),
    };
    t.test(
        (2, 7),
        &regions,
        &serde_json::json!([
            {"id":1,"region_id":2,"gift_name":"Toy Train","quantity":5},
            {"id":2,"region_id":2,"gift_name":"Toy Train","quantity":3},
            {"id":3,"region_id":2,"gift_name":"Doll","quantity":8},
            {"id":4,"region_id":3,"gift_name":"Toy Train","quantity":3},
            {"id":5,"region_id":2,"gift_name":"Teddy Bear","quantity":6},
            {"id":6,"region_id":3,"gift_name":"Action Figure","quantity":12},
            {"id":7,"region_id":4,"gift_name":"Board Game","quantity":10},
            {"id":8,"region_id":3,"gift_name":"Teddy Bear","quantity":1},
            {"id":9,"region_id":3,"gift_name":"Teddy Bear","quantity":2}
        ]),
        &serde_json::json!([
            {"region":"Africa","top_gifts":[]},
            {"region":"Asia","top_gifts":[]},
            {"region":"Europe","top_gifts":["Doll","Toy Train","Teddy Bear"]},
            {"region":"North America","top_gifts":["Action Figure","Teddy Bear","Toy Train"]},
            {"region":"North Pole","top_gifts":[]},
            {"region":"Oceania","top_gifts":[]},
            {"region":"South America","top_gifts":["Board Game"]},
        ]),
    )
    .await?;
    let t = RegionGiftTester {
        client: new_client(),
        reset_url: format!("{}/18/reset", base_url),
        regions_url: format!("{}/18/regions", base_url),
        orders_url: format!("{}/18/orders", base_url),
        final_url: format!("{}/18/regions/top_list/0", base_url),
    };
    t.test(
        (2, 8),
        &serde_json::json!([{"id":1,"name":"A"}]),
        &serde_json::json!([{"id":1,"region_id":1,"gift_name":"A","quantity":555555555}]),
        &serde_json::json!([{"region":"A","top_gifts":[]}]),
    )
    .await?;
    // TASK 2 DONE
    tx.send((false, 600).into()).await.unwrap();

    Ok(())
}

struct WS {
    test: TaskTest,
    w: SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
    r: SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
}

impl WS {
    async fn new(test: TaskTest, url: String) -> Result<Self, TaskTest> {
        let (s, _) = tokio_tungstenite::connect_async(url)
            .await
            .map_err(|_| test)?;
        let (w, r) = s.split();

        Ok(Self { test, w, r })
    }

    async fn send(&mut self, msg: impl Into<String>) -> ValidateResult {
        self.w
            .send(Message::Text(msg.into()))
            .await
            .map_err(|_| self.test)
    }

    async fn send_tweet(&mut self, msg: impl Into<String>) -> ValidateResult {
        self.send(serde_json::to_string(&serde_json::json!({"message": msg.into()})).unwrap())
            .await
    }

    async fn recv(&mut self) -> Result<String, TaskTest> {
        let Some(Ok(Message::Text(text))) = self.r.next().await else {
            return Err(self.test);
        };

        Ok(text)
    }

    async fn recv_str(&mut self, exp: &str) -> ValidateResult {
        let text = self.recv().await?;
        if text != exp {
            return Err(self.test);
        }

        Ok(())
    }

    async fn recv_json(&mut self, exp: &serde_json::Value) -> ValidateResult {
        let text = self.recv().await?;
        let json = serde_json::from_str::<serde_json::Value>(&text).map_err(|_| self.test)?;
        if &json != exp {
            return Err(self.test);
        }

        Ok(())
    }

    async fn close(mut self) -> ValidateResult {
        self.w.close().await.map_err(|_| self.test)?;

        Ok(())
    }
}

async fn validate_19(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let mut test: TaskTest;
    let ws_base_url = format!(
        "ws{}",
        base_url
            .strip_prefix("http")
            .expect("url to begin with http")
    );
    // TASK 1
    test = (1, 1);
    let mut ws = WS::new(test, format!("{}/19/ws/ping", ws_base_url)).await?;
    ws.send("ping").await?;
    tokio::select! {
        _ = ws.recv() => {
            return Err(test);
        },
        _ = sleep(Duration::from_secs(1)) => (),
    };
    ws.send("serve").await?;
    ws.send("ping").await?;
    ws.recv_str("pong").await?;
    test = (1, 2);
    ws.test = test;
    ws.send("ding").await?;
    tokio::select! {
        _ = ws.recv() => {
            return Err(test);
        },
        _ = sleep(Duration::from_secs(1)) => (),
    };
    test = (1, 3);
    ws.test = test;
    ws.send("ping").await?;
    ws.send("ping").await?;
    ws.recv_str("pong").await?;
    ws.recv_str("pong").await?;
    tokio::select! {
        _ = ws.recv() => {
            return Err(test);
        },
        _ = sleep(Duration::from_millis(500)) => (),
    };
    ws.close().await?;
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    let reset_url = &format!("{}/19/reset", base_url);
    let reset = || async move {
        let client = new_client();
        let res = client.post(reset_url).send().await.map_err(|_| ())?;
        if res.status() != StatusCode::OK {
            return Err(());
        }
        Ok(())
    };
    let views_url = &format!("{}/19/views", base_url);
    let ensure_views = |v: u32| async move {
        let client = new_client();
        let res = client.get(views_url).send().await.map_err(|_| ())?;
        let text = res.text().await.map_err(|_| ())?;
        if text != v.to_string() {
            return Err(());
        }
        Ok(())
    };

    test = (2, 1);
    reset().await.map_err(|_| test)?;
    ensure_views(0).await.map_err(|_| test)?;

    test = (2, 2);
    let mut elon = WS::new(test, format!("{}/19/ws/room/1/user/elonmusk", ws_base_url)).await?;
    let s = "Next I'm buying Coca-Cola to put the cocaine back in";
    elon.send_tweet(s).await?;
    elon.recv_json(&serde_json::json!({"user": "elonmusk", "message": s}))
        .await?;
    ensure_views(1).await.map_err(|_| test)?;

    test = (2, 3);
    let s = "I've concocted a whimsical idea to bring a bit of the ol' history back to life by attempting to put the cocaine back in Coca-Cola, rekindling the rebellious spirit of its original formulation";
    elon.send_tweet(s).await?;
    tokio::select! {
        _ = elon.recv() => {
            return Err(test);
        },
        _ = sleep(Duration::from_secs(1)) => (),
    };
    ensure_views(1).await.map_err(|_| test)?;
    elon.close().await?;
    sleep(Duration::from_millis(10)).await;

    test = (2, 4);
    reset().await.map_err(|_| test)?;
    ensure_views(0).await.map_err(|_| test)?;
    let mut a1 = WS::new(test, format!("{}/19/ws/room/44/user/annifrid", ws_base_url)).await?;
    let mut b1 = WS::new(test, format!("{}/19/ws/room/55/user/bjorn", ws_base_url)).await?;
    let mut b2 = WS::new(test, format!("{}/19/ws/room/55/user/benny", ws_base_url)).await?;
    let mut a2 = WS::new(test, format!("{}/19/ws/room/44/user/agnetha", ws_base_url)).await?;
    let l1 = "thank you for the music";
    let l2 = "the songs i'm singing";
    let l3 = "thanks for all";
    let l4 = "the joy they're bringing";
    let l5 = "who can live without it";
    let l6 = "i ask in all honesty";
    let x1 = "uhhhhhhhh?";
    let x2 = "wazzaaaaa?";
    a1.send_tweet(l1).await?;
    sleep(Duration::from_millis(10)).await;
    a2.send_tweet(l2).await?;
    sleep(Duration::from_millis(10)).await;
    a1.send_tweet(l3).await?;
    sleep(Duration::from_millis(10)).await;
    b1.send_tweet(x1).await?;
    sleep(Duration::from_millis(10)).await;
    a2.send_tweet(l4).await?;
    sleep(Duration::from_millis(10)).await;
    a1.send_tweet(l5).await?;
    sleep(Duration::from_millis(10)).await;
    a1.recv_json(&serde_json::json!({"user": "annifrid", "message": l1}))
        .await?;
    a2.recv_json(&serde_json::json!({"user": "annifrid", "message": l1}))
        .await?;
    a1.recv_json(&serde_json::json!({"user": "agnetha", "message": l2}))
        .await?;
    a2.recv_json(&serde_json::json!({"user": "agnetha", "message": l2}))
        .await?;
    a1.recv_json(&serde_json::json!({"user": "annifrid", "message": l3}))
        .await?;
    a2.recv_json(&serde_json::json!({"user": "annifrid", "message": l3}))
        .await?;
    a1.recv_json(&serde_json::json!({"user": "agnetha", "message": l4}))
        .await?;
    a2.recv_json(&serde_json::json!({"user": "agnetha", "message": l4}))
        .await?;
    a1.recv_json(&serde_json::json!({"user": "annifrid", "message": l5}))
        .await?;
    a2.recv_json(&serde_json::json!({"user": "annifrid", "message": l5}))
        .await?;
    sleep(Duration::from_millis(10)).await;
    ensure_views(12).await.map_err(|_| test)?;

    test = (2, 5);
    a1.close().await?;
    a2.send_tweet(l6).await?;
    a2.recv_json(&serde_json::json!({"user": "agnetha", "message": l6}))
        .await?;
    sleep(Duration::from_millis(10)).await;
    ensure_views(13).await.map_err(|_| test)?;

    test = (2, 6);
    let mut a1 = WS::new(test, format!("{}/19/ws/room/55/user/annifrid", ws_base_url)).await?;
    tokio::select! {
        _ = a1.recv() => {
            return Err(test);
        },
        _ = sleep(Duration::from_secs(1)) => (),
    };
    b1.recv_json(&serde_json::json!({"user": "bjorn", "message": x1}))
        .await?;
    b2.recv_json(&serde_json::json!({"user": "bjorn", "message": x1}))
        .await?;
    a1.send_tweet(x2).await?;
    sleep(Duration::from_millis(10)).await;
    b1.close().await?;
    a1.send_tweet(x2).await?;
    b2.recv_json(&serde_json::json!({"user": "annifrid", "message": x2}))
        .await?;
    b2.recv_json(&serde_json::json!({"user": "annifrid", "message": x2}))
        .await?;
    a1.recv_json(&serde_json::json!({"user": "annifrid", "message": x2}))
        .await?;
    a1.recv_json(&serde_json::json!({"user": "annifrid", "message": x2}))
        .await?;
    sleep(Duration::from_millis(10)).await;
    ensure_views(18).await.map_err(|_| test)?;

    test = (2, 7);
    reset().await.map_err(|_| test)?;
    ensure_views(0).await.map_err(|_| test)?;
    // generated with https://github.com/orhun/godsays
    let phrases = Arc::new([
        "you're nuts lift Greek to me cheerful don't mention it I made it that way quit it",
        "just lovely left field king of mars threads do it insane its trivial obviously",
        "not that theres anything wrong surprise surprise you'll see ba ha no you cant off the record Jesus",
        "you don't like it employer joke small talk that's all folks Varoom yikes",
        "Russia grumble failure to communicate Greece enough let me count the ways nut job",
        "don't push it Han shot first Is that so big fish Jedi mind trick you never know game changer",
        "on occassion that's no fun if and only if no more tears cracks me up it was nothing whiner",
        "Wow piety figuratively figuratively you're no fun hot air astrophysics",
        "astounding duck the shoe relax you think you could do better is it just me or What are you doing Dave Bam",
        "to infinity and beyond basket case no more let me count the ways one more time that's for me to know NOT",
        "What I want relax what planet are you from not that theres anything wrong What I want phasors on stun walking",
        "ice cream this might end badly thank you very much I'm not sure catastrophe beam me up food",
        "nope wazz up with that grumble awesome yuck are you sure recipe",
        "I'll let you know FBI wishful thinking jobs what's up Heaven Ghost",
        "take the day off repeat after me scum let's roll I'll ask nicely stuff duck the shoe",
        "not a chance in hell nut job nope heathen air head basically why do I put up with this",
        "chill out I'm not sure sad no news is good news news to me biggot whatcha talkin' 'bout",
        "well obviously That's gonna leave a mark if anything can go wrong debt play exports rose colored glasses",
        "not in my wildest dreams game changer Zzzzzzzz do over how could you look on the brightside You da man",
        "Ivy league oh no a likely story you're lucky face palm what luck I'll think about it",
        "game over homo segway gluttony pwned China test pilot",
        "after a break strip you owe me fight humongous God never happy",
        "take the day off bizarre on occassion just between us I'll think about it application I veto that",
        "spending look out enough is it just me or jealousy debt that's much better",
        "I didn't do it gross Han shot first I had a crazy dream tree hugger LOL music",
        "I have an idea chill you're nuts glorious CIA astrophysics king nun",
        "no more tears left field Ivy league break some woopass on you go ahead make my day don't push it middle class",
        "bizarre fer sure now that I think about it I'll be back in a galaxy far far away holy grail you couldnt navigate yer way circleK",
        "honesty holy grail failure is not an option hi let me count the ways Oh really are you deaf",
        "Isn't that special my precious it'd take a miracle the enquirer hobnob job handyman",
        "dance oh my chill If had my druthers evolution you know a better God could it be   Satan",
        "I'm in suspense Heaven joking experts you owe me That's gonna leave a mark spoiled brat",
        "delicious you should be so lucky basket case chess you couldnt navigate yer way circleK smack some sense into you Yawn",
        "I could swear game changer what would Jesus do just between us news to me Ghost charity",
        "climate I donno threads food What I want roses are red you're so screwed",
        "my precious Okilydokily energy dignity atrocious quit it when hell freezes over",
        "I give up Watch this now you tell me courage love relax you do it",
        "I could swear delightful Catastrophic Success bad why is it King Midas happy",
        "I'll think about it it's hopeless well I never stoked air head I'll ask nicely end",
        "you don't like it You fix it got the life imports rip off computers I don't care",
        "now that I think about it rich I'll let you know humongous let's roll ahh thats much better no way dude",
        "atrocious Hicc up ghastly don't worry hello I could be wrong heathen",
        "chill out ouch fool you couldnt navigate yer way circleK I'm done earnest threads",
        "energy ba ha ghetto I'm the boss boink King Midas you better not",
        "spoiled brat overflow after a break don't push it fabulous chill you don't like it",
        "don't worry other Russia wonderbread ohh thank you endure how high",
        "ridiculous What are you doing Dave crash and burn manufacturing chill gosh thank you very much",
        "how do I put this astronomical I had a crazy dream umm If had my druthers Varoom are you deaf",
        "Han shot first car tiffanies fool Shalom who are you to judge charged",
        "take your pick atheist don't even think about it I was just thinking you talkin' to me conservative scorning",
        "daunting quit it SupremerCourt enough how hard could it be lighten up how could you",
        "it's hopeless you hoser horrendous climate talk to my lawyer enough not that theres anything wrong",
        "I was sleeping nasty do you get a cookie foul job I m prettier than this man praise",
        "glorious Catastrophic Success far out man I don't care soap opera unsung hero hang in there",
        "a screw loose glorious not a chance in hell Greece rum bitty di vice are you feeling lucky",
        "King Midas catastrophe far out man you better not Yes you are vengeful Catastrophic Success",
        "thats right unemployment ouch you know a better God fun atheist joy",
        "'kay I don't care no more patience happy happy joy joy cowardice don't have a cow",
        "relax do I have to hard working happy happy joy joy ouch huh just lovely",
        "ahh thats much better courage China furious its trivial obviously straighten up what would Jesus do",
        "evolution SupremerCourt joy glorious exports hard working Oh Hell No",
        "Boo do not disturb radio smurfs reverse engineer biggot I don't care",
        "courage This is confusing Yawn ahh thats much better you talkin' to me I'm busy Terry",
        "Pullin the dragons tail don't mention it adultery what's up talk to my lawyer try again That's my favorite",
        "praise that's for me to know mission from God incoming endure You get what you pray for charity",
        "Pullin the dragons tail chill out do you get a cookie overflow You fix it what luck just lovely",
        "catastrophe let me count the ways Jesus food I forgot busybody so he sess",
        "what would Jesus do courage now you tell me can you hear me now Shhh rip off okay",
        "not too shabby food That's gonna leave a mark Yawn Ivy league sess me you're so screwed",
        "bye I am not amused unemployment figuratively really gambling look on the brightside",
        "umm what now bring it on petty Hicc up boink hobnob Varoom",
        "the quit ouch quite high mucky muck by the way study",
        "silly human poor I got your back handyman don't have a cow but of course I could swear",
        "One finger salute overflow won't you be my neighbor just lovely industrious Mars place",
        "oops an Irishman is forced to talk to God come and get me bye absolutely failure is not an option do you get a cookie",
        "not the sharpest knife in the drawer what's it to you the enquirer CIA 'kay do you have a problem run away",
        "who's to say zoot what a mess you talkin' to me laziness because I said so okay",
        "one more time ROFLMAO enough said frown happy happy joy joy Zzzzzzzz slumin",
        "nasty who are you to judge application are you insane how about that figuratively eh",
        "rubbish try again the wot courage I hate when that happens thats just wrong",
        "bye hey Mikey he likes it boink geek yep what a nightmare oh no",
        "praying the enquirer no you cant let's see fake nut job failure to communicate",
        "yuck 'kay are you feeling lucky high mucky muck refreshing love not the sharpest knife in the drawer",
        "if and only if unsung hero I'll ask nicely you're nuts pride wrath Zzzzzzzz",
        "shucks NeilDeGrasseTyson courage absolutely charity failure is not an option one more time",
        "by the way industrious boss epic fail oh oh Pope BRB",
        "I'm God and you're not my precious food duck the shoe special case where's the love in a perfect world",
        "adultery I'm impressed break some woopass on you wishful thinking sloth yikes This cant be william wallace",
        "you think I'm joking I donno fer sure computers it figures phasors on stun courage",
        "smurfs I didn't do it kick back catastrophe bickering church That's my favorite",
        "I veto that how could you God is not mocked okay rubbish harder than it looks voodoo",
        "caution Okilydokily really segway outrageous cosmetics thats right",
        "potentially look buddy holy grail joyful honestly pride look buddy",
        "pwned what luck repent lighten up BBC are you sure astrophysics",
        "by the way joy yeah birds naughty blessing whazza matter for you",
        "what's it to you grumble ha Hicc up huh endure money",
        "left field not the sharpest knife in the drawer patience crazy debt because I said so I made it that way",
        "strip wastoid red fang hang in there It grieves me you are my sunshine you'll see",
        "how could you frown you're in big trouble king of mars thats just wrong that's your opinion what planet are you from",
        "you think I'm joking I forgot Greek to me wonderful jobs spunky catastrophe",
        "Okilydokily Give me praise Shhh how high umm what now epic fail mine",
        "quite Wow Shhh driving wot exorbitant Church",
        "whatcha talkin' 'bout chaos look buddy husband good pow Shalom",
        "joking don't have a cow so let it be written you should be so lucky taxes wonderbread spirit",
        "radio dean scream slumin big fish begs the question unemployment red fang",
        "radio Is that your final answer how goes it where's the love unsung hero yep fool",
        "yeah ghetto pardon the french happy middle class what a mess Isn't that special",
        "incoming you better not husband hope driving Watch this thank you very much",
        "I didn't see that sex won't you be my neighbor What take your pick naughty delicious",
        "you're in big trouble hypocrite won't you be my neighbor not in kansas anymore angel joy look on the brightside",
        "money freak joyful bizarre ahh go ahead make my day HolySpirit",
        "Han shot first awesome CIA what's up king of mars what's the plan do you like it",
        "woot ridiculous in a perfect world in other words It's nice being God I was just thinking joker",
        "lying depressing gluttony thank you very much think you could do better charity rip off",
        "how come You da man gosh chaos what a mess frown vengeance",
        "when hell freezes over resume theft I had a crazy dream dude such a scoffer not good Wow",
        "in a perfect world rose colored glasses quite That's gonna leave a mark slumin That's my favorite I have an idea",
        "you don't say I'm not sure what a nightmare well I never be quiet bird fortitude when hell freezes over",
        "scum you're in big trouble you see the light I'm bored who are you to judge because I said so by the way",
        "nevada cheerful vermin threads boss Yes you are I planned that",
        "high mucky muck Isn't that special what a mess mine pet energy that's your opinion",
        "et tu who's to say tattle tale oh my I'm good you good you owe me yuck",
        "praying patience genius I'm in suspense how high Venus I didn't do it",
        "Terry the Mom rum bitty di do it Zap I veto that",
        "hotel I got your back on the otherhand not good chess chill out talk to my lawyer",
        "in a perfect world I'm on a roll Yawn rubbish boss hold on a minute sports",
        "Varoom it'd take a miracle ohh thank you naughty Terry make my day outrageous",
        "atrocious Icarus hate piety one small step phasors on stun take your pick",
        "whazza matter for you not a chance in hell ridiculous whoop there it is little fish hilarious close your eyes",
        "you'll see yep this might end badly news to me red fang that's for me to know you're nuts",
        "what part of God do you not understand what's it to you laziness I donno ha whale beam me up",
        "sess me yep joy hurts my head chaos be happy okay",
        "how about that Pullin the dragons tail prosperity mocking refreshing StephenHawking my bad",
        "boss quite beep beep study dang it population basket case",
        "hobnob no you cant employee jealousy one of the secret words are REMOTE lift uh huh are you deaf",
        "bickering skills thats laughable theres no place like home king of mars repeat after me go ahead make my day",
        "music you should be so lucky in theory no more tears do you know what time it is Angel it's hopeless",
        "couldnt possibly bad ol puddytat husband anger yep atheist et tu",
        "FBI energy lust well I never dance I'm the boss manufacturing",
        "think you could do better gluttony Shalom I didn't see that voodoo Han shot first how could you",
        "virtue experts just between us drama like like vengeance charity",
        "incredibly don't have a cow got the life Russia rufus! basically Is that so",
        "I planned that white trash failure to communicate check this out virtue crash and burn let's see",
        "check this out sloth news to me but of course NOT do it shucks",
        "It grieves me you're no fun cursing rufus! sess me rose colored glasses Church",
        "dance bizarre these cans are defective frown Knock you upside the head no more tears I am not amused",
        "manufacturing adjusted for inflation application Jedi mind trick do I have to praise Venus",
        "I'll let you know you're not all there are you I'm impressed talk to my lawyer abnormal This cant be william wallace frown",
        "Putin This cant be william wallace California rum bitty di end begs the question look buddy",
        "shist Greece failure to communicate you'll see rich left field Mom",
        "thats right you're wonderful you never know really that's your opinion what's up ice cream",
        "class  class  shutup tree hugger news to me just between us ROFLMAO not good not",
        "do it smile You fix it services liberal study I'm God and you're not",
        "chump change I'm feeling nice today thats just wrong you're fired it figures God smack Oy",
        "One finger salute ba ha won't you be my neighbor bring it on don't mention it talk to my lawyer exorbitant",
        "phasors on stun ohh thank you Yes you are how goes it nut job come and get me I got your back",
        "tattle tale you shouldn't have you're wonderful perfect Give me praise I veto that Is that so",
        "fabulous stuff pride Pope You know ordinarily ho ho ho",
        "ouch CIA study application phasors on stun not a chance in hell I'm not sure",
        "energy Isn't that special piety unsung hero guilty downer you owe me",
        "now you tell me no more hypocrite food one small step bad ol puddytat you're not all there are you",
        "depressing Ivy league I was just thinking umm I can't believe it ipod angel",
        "WooHoo place in theory strip African hello a flag on that play",
        "slumin grumble here now I'll get right on it frown If had my druthers over the top",
        "doh naughty joy NeilDeGrasseTyson sports nut job now you tell me",
        "commanded lust Yes you are don't worry recipe nope evolution",
        "manufacturing because I said so pride straighten up I'm on a roll quit it evolution",
        "Mom a likely story I'm off today Is that so don't mention it surprise surprise grumble",
        "arrogant won't you be my neighbor exports act yep Terry I have an idea",
        "reverse engineer I could be wrong news to me nope employee love foul",
        "conservative thank you very much commanded I'll let you know let me count the ways funny theres no place like home",
        "handyman yeah You get what you pray for whale gambling delightful sloth",
        "I'll think about it in theory awful Mom what a mess radio rum bitty di",
        "holy grail glam fortitude have fun depressing who are you to judge take your pick",
        "incoming in a galaxy far far away blessing spirit Pullin the dragons tail computers red fang",
        "beam me up Mom money boss fake prosperity scorning",
        "umm what now one more time nevada completely what's the plan rum bitty di no news is good news",
        "okay exorbitant hopefully mocking is it just me or I pity the fool that's your opinion",
        "because I said so kick back wot vote it's my world Pope charged",
        "money wazz up with that in other words I'm God who the hell are you tattle tale you're lucky don't count on it",
        "small talk genius lying here now mocking other smart",
        "you're lucky smurfs no way dude tree hugger abnormal You da man it's my world",
        "couldn't be better sloth look buddy we ve already got one holy grail take the day off ehheh that's all folks",
        "don't worry relax baffling whoop there it is phasors on stun lighten up I hate when that happens",
        "yeah illogical astrophysics not good busybody bye funny",
        "I hate when that happens food fancy it'd take a miracle shist pick me pick me sloth",
        "check this out wonderful ba ha Moses It's nice being God I don't care abnormal",
        "ipod here now one small step Ivy league that's your opinion you think I'm joking programming",
        "super computer happy GarryKasparov I be like smile God after a break",
        "Oh really it'd take a miracle nut job you owe me Pope holy grail dude such a scoffer",
        "genius humility California holier than thou persistence Isn't that special absetively posilutely",
        "desert break some woopass on you rufus! super computer stuff I'm thrilled the",
        "yep not too shabby voodoo you should be so lucky You da man boss Knock you upside the head",
        "joyful boss you're fired yada yada yada close your eyes look out you'll see",
        "Varoom food don't have a cow run away got the life You know stuff",
        "play is it just me or tiffanies vermin God is not mocked bad what luck",
        "by the way hotel pow study courage I can't believe it I pity the fool",
        "failure is not an option how hard could it be ridiculous what do you want nerd bring it on Dad",
        "spirit king of mars I'm off today threads oh oh what's the plan so he sess",
        "are you feeling lucky do not disturb here now bring it on Bam Dad red fang",
    ]);
    let mut joins = tokio::task::JoinSet::<ValidateResult>::new();
    let mut tasks = vec![];
    let views_url = Arc::new(views_url.clone());
    for i in 0..20 {
        let u = ws_base_url.clone();
        let ps = phrases.clone();
        let views_url = views_url.clone();
        let mut user = WS::new(test, format!("{}/19/ws/room/1/user/{}", u, i)).await?;
        tasks.push(async move {
            for (ii, p) in ps.iter().enumerate() {
                user.send_tweet(*p).await?;
                sleep(Duration::from_millis(1)).await;
                if i == 0 && ii == 100 {
                    let client = new_client();
                    client
                        .get(views_url.deref())
                        .send()
                        .await
                        .map_err(|_| test)?;
                }
            }
            sleep(Duration::from_secs(2)).await;
            user.close().await?;

            Ok(())
        });
    }
    for t in tasks.into_iter() {
        joins.spawn(t);
    }
    while let Some(Ok(r)) = joins.join_next().await {
        r?;
    }
    sleep(Duration::from_millis(100)).await;
    ensure_views(80000).await.map_err(|_| test)?;
    // TASK 2 DONE
    tx.send((false, 500).into()).await.unwrap();

    Ok(())
}

async fn validate_20(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!("{}/20/archive_files", base_url);
    let res = client
        .post(url)
        .body(include_bytes!("../assets/northpole20231220.tar").to_vec())
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "6" {
        return Err(test);
    }
    test = (1, 2);
    let url = &format!("{}/20/archive_files_size", base_url);
    let res = client
        .post(url)
        .body(include_bytes!("../assets/northpole20231220.tar").to_vec())
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "1196282" {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!("{}/20/cookie", base_url);
    let res = client
        .post(url)
        .body(include_bytes!("../assets/cookiejar.tar").to_vec())
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Grinch 71dfab551a1958b35b7436c54b7455dcec99a12c" {
        return Err(test);
    }
    test = (2, 2);
    let url = &format!("{}/20/cookie", base_url);
    let res = client
        .post(url)
        .body(include_bytes!("../assets/lottery.tar").to_vec())
        .send()
        .await
        .map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "elf-27221 6342c1dbdb560f0d5dcaac7566fca51454866664" {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 350).into()).await.unwrap();

    Ok(())
}

async fn validate_21(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    let client = new_client();
    let mut test: TaskTest;
    // TASK 1
    test = (1, 1);
    let url = &format!(
        "{}/21/coords/0100111110010011000110011001010101011111000010100011110001011011",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "83°39'54.324''N 30°37'40.584''W" {
        return Err(test);
    }
    test = (1, 2);
    let url = &format!(
        "{}/21/coords/0010000111110000011111100000111010111100000100111101111011000101",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "18°54'55.944''S 47°31'17.976''E" {
        return Err(test);
    }
    test = (1, 3);
    let url = &format!(
        "{}/21/coords/0101110100010001110001111100100111000111100010111100111101110001",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "51°26'57.804''N 99°28'33.204''E" {
        return Err(test);
    }
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    test = (2, 1);
    let url = &format!(
        "{}/21/country/0010000111110000011111100000111010111100000100111101111011000101",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Madagascar" {
        return Err(test);
    }
    test = (2, 2);
    let url = &format!(
        "{}/21/country/0011001000100010100010110001110100000111000010111000100000010101",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Brunei" {
        return Err(test);
    }
    test = (2, 3);
    let url = &format!(
        "{}/21/country/1001010011001110010011100110001000100110100111001001000100110001",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Brazil" {
        return Err(test);
    }
    test = (2, 4);
    let url = &format!(
        "{}/21/country/0101110100010001110001111100100111000111100010111100111101110001",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Mongolia" {
        return Err(test);
    }
    test = (2, 5);
    let url = &format!(
        "{}/21/country/0011100111101001000010001100001100111111101001100110000010101011",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Nepal" {
        return Err(test);
    }
    test = (2, 6);
    let url = &format!(
        "{}/21/country/0100011111000110101110101100011001101001111111001011000011101111",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Belgium" {
        return Err(test);
    }
    test = (2, 7);
    let url = &format!(
        "{}/21/country/0100111100110010101001010001010100100110110000100100101011011111",
        base_url
    );
    let res = client.get(url).send().await.map_err(|_| test)?;
    let text = res.text().await.map_err(|_| test)?;
    if text != "Iceland" {
        return Err(test);
    }
    // TASK 2 DONE
    tx.send((false, 300).into()).await.unwrap();

    Ok(())
}

struct TextTester {
    client: reqwest::Client,
    url: String,
}

impl TextTester {
    fn new(url: String) -> Self {
        Self {
            client: new_client(),
            url,
        }
    }
    async fn test(&self, test: TaskTest, i: &str, code: StatusCode, o: &str) -> ValidateResult {
        let res = self
            .client
            .post(&self.url)
            .body(i.to_owned())
            .send()
            .await
            .map_err(|_| test)?;
        if res.status() != code {
            return Err(test);
        }
        let text = res.text().await.map_err(|_| test)?;
        if text != o {
            return Err(test);
        }
        Ok(())
    }
}

async fn validate_22(base_url: &str, tx: Sender<SubmissionUpdate>) -> ValidateResult {
    // TASK 1
    let t = TextTester::new(format!("{}/22/integers", base_url));
    t.test(
        (1, 1),
        "\
1
",
        StatusCode::OK,
        "🎁".repeat(1).as_str(),
    )
    .await?;
    t.test(
        (1, 2),
        "\
1
1
2
2
3
3
4
",
        StatusCode::OK,
        "🎁".repeat(4).as_str(),
    )
    .await?;
    t.test(
        (1, 3),
        "\
1
3
1
2
4
2
3
",
        StatusCode::OK,
        "🎁".repeat(4).as_str(),
    )
    .await?;
    t.test(
        (1, 4),
        "\
11111111111111111111
555555555555555
33333333
68
555555555555555
33333333
4444
11111111111111111111
4444
",
        StatusCode::OK,
        "🎁".repeat(68).as_str(),
    )
    .await?;
    t.test(
        (1, 5),
        include_str!("../assets/numbers.txt"),
        StatusCode::OK,
        "🎁".repeat(120003).as_str(),
    )
    .await?;
    // TASK 1 DONE
    tx.send((true, 0).into()).await.unwrap();
    tx.send(SubmissionUpdate::Save).await.unwrap();

    // TASK 2
    let t = TextTester::new(format!("{}/22/rocket", base_url));
    t.test(
        (2, 1),
        "\
2
0 0 0
0 0 1
1
0 1
",
        StatusCode::OK,
        "1 1.000",
    )
    .await?;
    t.test(
        (2, 2),
        "\
5
0 1 0
-2 2 3
3 -3 -5
1 1 5
4 3 5
4
0 1
2 4
3 4
1 2
",
        StatusCode::OK,
        "3 26.123",
    )
    .await?;
    t.test(
        (2, 3),
        "\
5
0 1 0
-2 2 3
3 -3 -5
1 1 5
4 3 5
5
0 1
1 3
3 4
0 2
2 4
",
        StatusCode::OK,
        "2 18.776",
    )
    .await?;
    t.test(
        (2, 4),
        "\
5
0 1 0
-2 2 3
3 -3 -5
1 1 5
4 3 5
1
0 4
",
        StatusCode::OK,
        "1 6.708",
    )
    .await?;
    t.test(
        (2, 5),
        "\
5
0 1 0
-2 2 3
3 -3 -5
1 1 5
4 3 5
5
0 4
0 1
1 2
2 0
0 3
",
        StatusCode::OK,
        "1 6.708",
    )
    .await?;
    t.test(
        (2, 6),
        "\
21
570 -435 923
672 -762 -218
707 16 640
311 902 47
-963 -399 -773
788 532 -704
703 475 -145
-303 -394 -369
699 -640 952
-341 -221 743
740 -146 544
-424 655 179
-630 161 690
789 -848 -517
-14 -893 551
-48 815 962
528 552 -96
337 983 165
-565 459 -90
81 -476 301
-685 -319 698
24
0 2
2 4
4 6
6 10
10 17
17 20
20 18
18 11
11 7
7 5
5 3
3 0
0 1
1 12
12 13
13 19
19 20
20 16
16 14
14 15
15 9
9 8
8 6
11 16
",
        StatusCode::OK,
        "5 7167.055",
    )
    .await?;
    t.test(
        (2, 7),
        "\
75
570 -435 923
672 -762 -218
707 16 640
311 902 47
-963 -399 -773
788 532 -704
703 475 -145
-303 -394 -369
699 -640 952
-341 -221 743
740 -146 544
-424 655 179
-630 161 690
789 -848 -517
-14 -893 551
-48 815 962
528 552 -96
337 983 165
-565 459 -90
81 -476 301
-685 -319 698
-264 96 361
796 94 402
983 763 -953
711 -221 -866
-578 128 -178
-464 117 304
426 -433 -961
-626 -779 -596
-117 -88 349
880 -286 -527
941 -451 177
627 -832 286
593 370 -436
609 431 -681
-549 -690 447
957 849 -162
189 290 -485
-914 -447 -61
367 731 825
-177 432 -675
-926 -811 198
-379 345 831
-669 -134 804
956 380 -427
213 -954 -357
-806 -663 583
7 -460 374
-384 -797 -404
-793 -333 196
402 175 329
703 9 -926
599 559 -844
64 343 885
-865 -49 -373
-728 880 -164
830 528 -394
931 -782 -365
661 -528 931
-764 34 -289
442 298 983
-899 382 -967
662 361 -85
775 98 -519
202 335 60
474 823 -677
-708 41 127
-974 718 81
443 -526 -945
-279 778 -271
896 26 -902
-977 -233 837
151 -22 -454
824 -472 471
702 871 -244
73
0 1
0 2
0 4
0 5
0 7
1 10
10 11
11 25
12 13
13 27
14 29
15 30
16 17
17 35
18 36
19 6
2 3
20 22
21 19
22 40
23 60
24 42
25 26
26 43
27 28
28 45
29 47
3 12
30 31
31 68
32 50
34 16
35 52
36 54
37 38
38 57
39 21
4 14
40 59
41 23
42 61
43 44
44 63
45 64
46 65
47 46
49 32
49 68
5 15
50 33
51 34
52 70
54 73
55 37
56 74
57 56
58 39
59 58
6 18
63 62
65 66
66 67
67 48
69 51
7 20
70 71
71 72
72 53
73 55
8 1
8 9
9 23
9 24
",
        StatusCode::OK,
        "20 27826.439",
    )
    .await?;
    t.test(
        (2, 8),
        "\
70
788 532 -704
703 475 -145
-303 -394 -369
699 -640 952
-341 -221 743
740 -146 544
-424 655 179
-630 161 690
789 -848 -517
-14 -893 551
-48 815 962
528 552 -96
337 983 165
-565 459 -90
81 -476 301
-685 -319 698
-264 96 361
796 94 402
983 763 -953
711 -221 -866
-578 128 -178
-464 117 304
426 -433 -961
-626 -779 -596
-117 -88 349
880 -286 -527
941 -451 177
627 -832 286
593 370 -436
609 431 -681
-549 -690 447
957 849 -162
189 290 -485
-914 -447 -61
367 731 825
-177 432 -675
-926 -811 198
-379 345 831
-669 -134 804
956 380 -427
213 -954 -357
-806 -663 583
7 -460 374
-384 -797 -404
-793 -333 196
402 175 329
703 9 -926
599 559 -844
64 343 885
-865 -49 -373
-728 880 -164
830 528 -394
931 -782 -365
661 -528 931
-764 34 -289
442 298 983
-899 382 -967
662 361 -85
775 98 -519
202 335 60
474 823 -677
-708 41 127
-974 718 81
443 -526 -945
-279 778 -271
896 26 -902
-977 -233 837
151 -22 -454
824 -472 471
702 871 -244
70
0 10
0 2
0 3
1 22
10 21
11 1
12 11
13 27
14 15
15 4
16 31
17 33
18 19
19 7
2 12
20 53
21 37
22 39
23 40
24 23
25 24
26 25
27 26
27 6
28 14
29 30
3 13
30 46
30 69
31 47
33 18
33 48
34 33
35 34
37 20
38 55
39 56
39 57
4 16
40 59
41 60
42 62
43 63
44 28
44 65
45 29
46 68
47 32
48 49
49 50
5 17
50 51
51 35
53 36
55 54
56 38
57 58
59 41
6 5
60 61
61 42
62 43
63 64
64 44
65 45
67 66
68 67
7 9
8 0
9 8
",
        StatusCode::OK,
        "23 34029.320",
    )
    .await?;
    // TASK 2 DONE
    tx.send((false, 600).into()).await.unwrap();

    Ok(())
}