File: events.go

package info (click to toggle)
nats-server 2.10.27-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,332 kB
  • sloc: sh: 691; makefile: 3
file content (3183 lines) | stat: -rw-r--r-- 95,708 bytes parent folder | download
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
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
// Copyright 2018-2025 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package server

import (
	"bytes"
	"compress/gzip"
	"crypto/sha256"
	"crypto/x509"
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"net/http"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/klauspost/compress/s2"

	"github.com/nats-io/jwt/v2"
	"github.com/nats-io/nats-server/v2/server/certidp"
	"github.com/nats-io/nats-server/v2/server/pse"
)

const (
	accLookupReqTokens = 6
	accLookupReqSubj   = "$SYS.REQ.ACCOUNT.%s.CLAIMS.LOOKUP"
	accPackReqSubj     = "$SYS.REQ.CLAIMS.PACK"
	accListReqSubj     = "$SYS.REQ.CLAIMS.LIST"
	accClaimsReqSubj   = "$SYS.REQ.CLAIMS.UPDATE"
	accDeleteReqSubj   = "$SYS.REQ.CLAIMS.DELETE"

	connectEventSubj    = "$SYS.ACCOUNT.%s.CONNECT"
	disconnectEventSubj = "$SYS.ACCOUNT.%s.DISCONNECT"
	accDirectReqSubj    = "$SYS.REQ.ACCOUNT.%s.%s"
	accPingReqSubj      = "$SYS.REQ.ACCOUNT.PING.%s" // atm. only used for STATZ and CONNZ import from system account
	// kept for backward compatibility when using http resolver
	// this overlaps with the names for events but you'd have to have the operator private key in order to succeed.
	accUpdateEventSubjOld     = "$SYS.ACCOUNT.%s.CLAIMS.UPDATE"
	accUpdateEventSubjNew     = "$SYS.REQ.ACCOUNT.%s.CLAIMS.UPDATE"
	connsRespSubj             = "$SYS._INBOX_.%s"
	accConnsEventSubjNew      = "$SYS.ACCOUNT.%s.SERVER.CONNS"
	accConnsEventSubjOld      = "$SYS.SERVER.ACCOUNT.%s.CONNS" // kept for backward compatibility
	lameDuckEventSubj         = "$SYS.SERVER.%s.LAMEDUCK"
	shutdownEventSubj         = "$SYS.SERVER.%s.SHUTDOWN"
	clientKickReqSubj         = "$SYS.REQ.SERVER.%s.KICK"
	clientLDMReqSubj          = "$SYS.REQ.SERVER.%s.LDM"
	authErrorEventSubj        = "$SYS.SERVER.%s.CLIENT.AUTH.ERR"
	authErrorAccountEventSubj = "$SYS.ACCOUNT.CLIENT.AUTH.ERR"
	serverStatsSubj           = "$SYS.SERVER.%s.STATSZ"
	serverDirectReqSubj       = "$SYS.REQ.SERVER.%s.%s"
	serverPingReqSubj         = "$SYS.REQ.SERVER.PING.%s"
	serverStatsPingReqSubj    = "$SYS.REQ.SERVER.PING"             // use $SYS.REQ.SERVER.PING.STATSZ instead
	serverReloadReqSubj       = "$SYS.REQ.SERVER.%s.RELOAD"        // with server ID
	leafNodeConnectEventSubj  = "$SYS.ACCOUNT.%s.LEAFNODE.CONNECT" // for internal use only
	remoteLatencyEventSubj    = "$SYS.LATENCY.M2.%s"
	inboxRespSubj             = "$SYS._INBOX.%s.%s"

	// Used to return information to a user on bound account and user permissions.
	userDirectInfoSubj = "$SYS.REQ.USER.INFO"
	userDirectReqSubj  = "$SYS.REQ.USER.%s.INFO"

	// FIXME(dlc) - Should account scope, even with wc for now, but later on
	// we can then shard as needed.
	accNumSubsReqSubj = "$SYS.REQ.ACCOUNT.NSUBS"

	// These are for exported debug services. These are local to this server only.
	accSubsSubj = "$SYS.DEBUG.SUBSCRIBERS"

	shutdownEventTokens = 4
	serverSubjectIndex  = 2
	accUpdateTokensNew  = 6
	accUpdateTokensOld  = 5
	accUpdateAccIdxOld  = 2

	accReqTokens   = 5
	accReqAccIndex = 3

	ocspPeerRejectEventSubj           = "$SYS.SERVER.%s.OCSP.PEER.CONN.REJECT"
	ocspPeerChainlinkInvalidEventSubj = "$SYS.SERVER.%s.OCSP.PEER.LINK.INVALID"
)

// FIXME(dlc) - make configurable.
var eventsHBInterval = 30 * time.Second
var statsHBInterval = 10 * time.Second

// Default minimum wait time for sending statsz
const defaultStatszRateLimit = 1 * time.Second

// Variable version so we can set in tests.
var statszRateLimit = defaultStatszRateLimit

type sysMsgHandler func(sub *subscription, client *client, acc *Account, subject, reply string, hdr, msg []byte)

// Used if we have to queue things internally to avoid the route/gw path.
type inSysMsg struct {
	sub  *subscription
	c    *client
	acc  *Account
	subj string
	rply string
	hdr  []byte
	msg  []byte
	cb   sysMsgHandler
}

// Used to send and receive messages from inside the server.
type internal struct {
	account        *Account
	client         *client
	seq            uint64
	sid            int
	servers        map[string]*serverUpdate
	sweeper        *time.Timer
	stmr           *time.Timer
	replies        map[string]msgHandler
	sendq          *ipQueue[*pubMsg]
	recvq          *ipQueue[*inSysMsg]
	recvqp         *ipQueue[*inSysMsg] // For STATSZ/Pings
	resetCh        chan struct{}
	wg             sync.WaitGroup
	sq             *sendq
	orphMax        time.Duration
	chkOrph        time.Duration
	statsz         time.Duration
	cstatsz        time.Duration
	shash          string
	inboxPre       string
	remoteStatsSub *subscription
	lastStatsz     time.Time
}

// ServerStatsMsg is sent periodically with stats updates.
type ServerStatsMsg struct {
	Server ServerInfo  `json:"server"`
	Stats  ServerStats `json:"statsz"`
}

// ConnectEventMsg is sent when a new connection is made that is part of an account.
type ConnectEventMsg struct {
	TypedEvent
	Server ServerInfo `json:"server"`
	Client ClientInfo `json:"client"`
}

// ConnectEventMsgType is the schema type for ConnectEventMsg
const ConnectEventMsgType = "io.nats.server.advisory.v1.client_connect"

// DisconnectEventMsg is sent when a new connection previously defined from a
// ConnectEventMsg is closed.
type DisconnectEventMsg struct {
	TypedEvent
	Server   ServerInfo `json:"server"`
	Client   ClientInfo `json:"client"`
	Sent     DataStats  `json:"sent"`
	Received DataStats  `json:"received"`
	Reason   string     `json:"reason"`
}

// DisconnectEventMsgType is the schema type for DisconnectEventMsg
const DisconnectEventMsgType = "io.nats.server.advisory.v1.client_disconnect"

// OCSPPeerRejectEventMsg is sent when a peer TLS handshake is ultimately rejected due to OCSP invalidation.
// A "peer" can be an inbound client connection or a leaf connection to a remote server. Peer in event payload
// is always the peer's (TLS) leaf cert, which may or may be the invalid cert (See also OCSPPeerChainlinkInvalidEventMsg)
type OCSPPeerRejectEventMsg struct {
	TypedEvent
	Kind   string           `json:"kind"`
	Peer   certidp.CertInfo `json:"peer"`
	Server ServerInfo       `json:"server"`
	Reason string           `json:"reason"`
}

// OCSPPeerRejectEventMsgType is the schema type for OCSPPeerRejectEventMsg
const OCSPPeerRejectEventMsgType = "io.nats.server.advisory.v1.ocsp_peer_reject"

// OCSPPeerChainlinkInvalidEventMsg is sent when a certificate (link) in a valid TLS chain is found to be OCSP invalid
// during a peer TLS handshake. A "peer" can be an inbound client connection or a leaf connection to a remote server.
// Peer and Link may be the same if the invalid cert was the peer's leaf cert
type OCSPPeerChainlinkInvalidEventMsg struct {
	TypedEvent
	Link   certidp.CertInfo `json:"link"`
	Peer   certidp.CertInfo `json:"peer"`
	Server ServerInfo       `json:"server"`
	Reason string           `json:"reason"`
}

// OCSPPeerChainlinkInvalidEventMsgType is the schema type for OCSPPeerChainlinkInvalidEventMsg
const OCSPPeerChainlinkInvalidEventMsgType = "io.nats.server.advisory.v1.ocsp_peer_link_invalid"

// AccountNumConns is an event that will be sent from a server that is tracking
// a given account when the number of connections changes. It will also HB
// updates in the absence of any changes.
type AccountNumConns struct {
	TypedEvent
	Server ServerInfo `json:"server"`
	AccountStat
}

// AccountStat contains the data common between AccountNumConns and AccountStatz
type AccountStat struct {
	Account       string    `json:"acc"`
	Conns         int       `json:"conns"`
	LeafNodes     int       `json:"leafnodes"`
	TotalConns    int       `json:"total_conns"`
	NumSubs       uint32    `json:"num_subscriptions"`
	Sent          DataStats `json:"sent"`
	Received      DataStats `json:"received"`
	SlowConsumers int64     `json:"slow_consumers"`
}

const AccountNumConnsMsgType = "io.nats.server.advisory.v1.account_connections"

// accNumConnsReq is sent when we are starting to track an account for the first
// time. We will request others send info to us about their local state.
type accNumConnsReq struct {
	Server  ServerInfo `json:"server"`
	Account string     `json:"acc"`
}

// ServerID is basic static info for a server.
type ServerID struct {
	Name string `json:"name"`
	Host string `json:"host"`
	ID   string `json:"id"`
}

// Type for our server capabilities.
type ServerCapability uint64

// ServerInfo identifies remote servers.
type ServerInfo struct {
	Name    string   `json:"name"`
	Host    string   `json:"host"`
	ID      string   `json:"id"`
	Cluster string   `json:"cluster,omitempty"`
	Domain  string   `json:"domain,omitempty"`
	Version string   `json:"ver"`
	Tags    []string `json:"tags,omitempty"`
	// Whether JetStream is enabled (deprecated in favor of the `ServerCapability`).
	JetStream bool `json:"jetstream"`
	// Generic capability flags
	Flags ServerCapability `json:"flags"`
	// Sequence and Time from the remote server for this message.
	Seq  uint64    `json:"seq"`
	Time time.Time `json:"time"`
}

const (
	JetStreamEnabled     ServerCapability = 1 << iota // Server had JetStream enabled.
	BinaryStreamSnapshot                              // New stream snapshot capability.
)

// Set JetStream capability.
func (si *ServerInfo) SetJetStreamEnabled() {
	si.Flags |= JetStreamEnabled
	// Still set old version.
	si.JetStream = true
}

// JetStreamEnabled indicates whether or not we have JetStream enabled.
func (si *ServerInfo) JetStreamEnabled() bool {
	// Take into account old version.
	return si.Flags&JetStreamEnabled != 0 || si.JetStream
}

// Set binary stream snapshot capability.
func (si *ServerInfo) SetBinaryStreamSnapshot() {
	si.Flags |= BinaryStreamSnapshot
}

// JetStreamEnabled indicates whether or not we have binary stream snapshot capbilities.
func (si *ServerInfo) BinaryStreamSnapshot() bool {
	return si.Flags&BinaryStreamSnapshot != 0
}

// ClientInfo is detailed information about the client forming a connection.
type ClientInfo struct {
	Start      *time.Time    `json:"start,omitempty"`
	Host       string        `json:"host,omitempty"`
	ID         uint64        `json:"id,omitempty"`
	Account    string        `json:"acc,omitempty"`
	Service    string        `json:"svc,omitempty"`
	User       string        `json:"user,omitempty"`
	Name       string        `json:"name,omitempty"`
	Lang       string        `json:"lang,omitempty"`
	Version    string        `json:"ver,omitempty"`
	RTT        time.Duration `json:"rtt,omitempty"`
	Server     string        `json:"server,omitempty"`
	Cluster    string        `json:"cluster,omitempty"`
	Alternates []string      `json:"alts,omitempty"`
	Stop       *time.Time    `json:"stop,omitempty"`
	Jwt        string        `json:"jwt,omitempty"`
	IssuerKey  string        `json:"issuer_key,omitempty"`
	NameTag    string        `json:"name_tag,omitempty"`
	Tags       jwt.TagList   `json:"tags,omitempty"`
	Kind       string        `json:"kind,omitempty"`
	ClientType string        `json:"client_type,omitempty"`
	MQTTClient string        `json:"client_id,omitempty"` // This is the MQTT client ID
	Nonce      string        `json:"nonce,omitempty"`
}

// forAssignmentSnap returns the minimum amount of ClientInfo we need for assignment snapshots.
func (ci *ClientInfo) forAssignmentSnap() *ClientInfo {
	return &ClientInfo{
		Account: ci.Account,
		Service: ci.Service,
		Cluster: ci.Cluster,
	}
}

// forProposal returns the minimum amount of ClientInfo we need for assignment proposals.
func (ci *ClientInfo) forProposal() *ClientInfo {
	if ci == nil {
		return nil
	}
	cci := *ci
	cci.Jwt = _EMPTY_
	cci.IssuerKey = _EMPTY_
	return &cci
}

// forAdvisory returns the minimum amount of ClientInfo we need for JS advisory events.
func (ci *ClientInfo) forAdvisory() *ClientInfo {
	if ci == nil {
		return nil
	}
	cci := *ci
	cci.Jwt = _EMPTY_
	cci.Alternates = nil
	return &cci
}

// ServerStats hold various statistics that we will periodically send out.
type ServerStats struct {
	Start            time.Time      `json:"start"`
	Mem              int64          `json:"mem"`
	Cores            int            `json:"cores"`
	CPU              float64        `json:"cpu"`
	Connections      int            `json:"connections"`
	TotalConnections uint64         `json:"total_connections"`
	ActiveAccounts   int            `json:"active_accounts"`
	NumSubs          uint32         `json:"subscriptions"`
	Sent             DataStats      `json:"sent"`
	Received         DataStats      `json:"received"`
	SlowConsumers    int64          `json:"slow_consumers"`
	Routes           []*RouteStat   `json:"routes,omitempty"`
	Gateways         []*GatewayStat `json:"gateways,omitempty"`
	ActiveServers    int            `json:"active_servers,omitempty"`
	JetStream        *JetStreamVarz `json:"jetstream,omitempty"`
}

// RouteStat holds route statistics.
type RouteStat struct {
	ID       uint64    `json:"rid"`
	Name     string    `json:"name,omitempty"`
	Sent     DataStats `json:"sent"`
	Received DataStats `json:"received"`
	Pending  int       `json:"pending"`
}

// GatewayStat holds gateway statistics.
type GatewayStat struct {
	ID         uint64    `json:"gwid"`
	Name       string    `json:"name"`
	Sent       DataStats `json:"sent"`
	Received   DataStats `json:"received"`
	NumInbound int       `json:"inbound_connections"`
}

// DataStats reports how may msg and bytes. Applicable for both sent and received.
type DataStats struct {
	Msgs  int64 `json:"msgs"`
	Bytes int64 `json:"bytes"`
}

// Used for internally queueing up messages that the server wants to send.
type pubMsg struct {
	c    *client
	sub  string
	rply string
	si   *ServerInfo
	hdr  map[string]string
	msg  any
	oct  compressionType
	echo bool
	last bool
}

var pubMsgPool sync.Pool

func newPubMsg(c *client, sub, rply string, si *ServerInfo, hdr map[string]string,
	msg any, oct compressionType, echo, last bool) *pubMsg {

	var m *pubMsg
	pm := pubMsgPool.Get()
	if pm != nil {
		m = pm.(*pubMsg)
	} else {
		m = &pubMsg{}
	}
	// When getting something from a pool it is critical that all fields are
	// initialized. Doing this way guarantees that if someone adds a field to
	// the structure, the compiler will fail the build if this line is not updated.
	(*m) = pubMsg{c, sub, rply, si, hdr, msg, oct, echo, last}
	return m
}

func (pm *pubMsg) returnToPool() {
	if pm == nil {
		return
	}
	pm.c, pm.sub, pm.rply, pm.si, pm.hdr, pm.msg = nil, _EMPTY_, _EMPTY_, nil, nil, nil
	pubMsgPool.Put(pm)
}

// Used to track server updates.
type serverUpdate struct {
	seq   uint64
	ltime time.Time
}

// TypedEvent is a event or advisory sent by the server that has nats type hints
// typically used for events that might be consumed by 3rd party event systems
type TypedEvent struct {
	Type string    `json:"type"`
	ID   string    `json:"id"`
	Time time.Time `json:"timestamp"`
}

// internalReceiveLoop will be responsible for dispatching all messages that
// a server receives and needs to internally process, e.g. internal subs.
func (s *Server) internalReceiveLoop(recvq *ipQueue[*inSysMsg]) {
	for s.eventsRunning() {
		select {
		case <-recvq.ch:
			msgs := recvq.pop()
			for _, m := range msgs {
				if m.cb != nil {
					m.cb(m.sub, m.c, m.acc, m.subj, m.rply, m.hdr, m.msg)
				}
			}
			recvq.recycle(&msgs)
		case <-s.quitCh:
			return
		}
	}
}

// internalSendLoop will be responsible for serializing all messages that
// a server wants to send.
func (s *Server) internalSendLoop(wg *sync.WaitGroup) {
	defer wg.Done()

RESET:
	s.mu.RLock()
	if s.sys == nil || s.sys.sendq == nil {
		s.mu.RUnlock()
		return
	}
	sysc := s.sys.client
	resetCh := s.sys.resetCh
	sendq := s.sys.sendq
	id := s.info.ID
	host := s.info.Host
	servername := s.info.Name
	domain := s.info.Domain
	seqp := &s.sys.seq
	js := s.info.JetStream
	cluster := s.info.Cluster
	if s.gateway.enabled {
		cluster = s.getGatewayName()
	}
	s.mu.RUnlock()

	// Grab tags.
	tags := s.getOpts().Tags

	for s.eventsRunning() {
		select {
		case <-sendq.ch:
			msgs := sendq.pop()
			for _, pm := range msgs {
				if si := pm.si; si != nil {
					si.Name = servername
					si.Domain = domain
					si.Host = host
					si.Cluster = cluster
					si.ID = id
					si.Seq = atomic.AddUint64(seqp, 1)
					si.Version = VERSION
					si.Time = time.Now().UTC()
					si.Tags = tags
					if js {
						// New capability based flags.
						si.SetJetStreamEnabled()
						si.SetBinaryStreamSnapshot()
					}
				}
				var b []byte
				if pm.msg != nil {
					switch v := pm.msg.(type) {
					case string:
						b = []byte(v)
					case []byte:
						b = v
					default:
						b, _ = json.Marshal(pm.msg)
					}
				}
				// Setup our client. If the user wants to use a non-system account use our internal
				// account scoped here so that we are not changing out accounts for the system client.
				var c *client
				if pm.c != nil {
					c = pm.c
				} else {
					c = sysc
				}

				// Grab client lock.
				c.mu.Lock()

				// Prep internal structures needed to send message.
				c.pa.subject, c.pa.reply = []byte(pm.sub), []byte(pm.rply)
				c.pa.size, c.pa.szb = len(b), []byte(strconv.FormatInt(int64(len(b)), 10))
				c.pa.hdr, c.pa.hdb = -1, nil
				trace := c.trace

				// Now check for optional compression.
				var contentHeader string
				var bb bytes.Buffer

				if len(b) > 0 {
					switch pm.oct {
					case gzipCompression:
						zw := gzip.NewWriter(&bb)
						zw.Write(b)
						zw.Close()
						b = bb.Bytes()
						contentHeader = "gzip"
					case snappyCompression:
						sw := s2.NewWriter(&bb, s2.WriterSnappyCompat())
						sw.Write(b)
						sw.Close()
						b = bb.Bytes()
						contentHeader = "snappy"
					case unsupportedCompression:
						contentHeader = "identity"
					}
				}
				// Optional Echo
				replaceEcho := c.echo != pm.echo
				if replaceEcho {
					c.echo = !c.echo
				}
				c.mu.Unlock()

				// Add in NL
				b = append(b, _CRLF_...)

				// Check if we should set content-encoding
				if contentHeader != _EMPTY_ {
					b = c.setHeader(contentEncodingHeader, contentHeader, b)
				}

				// Optional header processing.
				if pm.hdr != nil {
					for k, v := range pm.hdr {
						b = c.setHeader(k, v, b)
					}
				}
				// Tracing
				if trace {
					c.traceInOp(fmt.Sprintf("PUB %s %s %d", c.pa.subject, c.pa.reply, c.pa.size), nil)
					c.traceMsg(b)
				}

				// Process like a normal inbound msg.
				c.processInboundClientMsg(b)

				// Put echo back if needed.
				if replaceEcho {
					c.mu.Lock()
					c.echo = !c.echo
					c.mu.Unlock()
				}

				// See if we are doing graceful shutdown.
				if !pm.last {
					c.flushClients(0) // Never spend time in place.
				} else {
					// For the Shutdown event, we need to send in place otherwise
					// there is a chance that the process will exit before the
					// writeLoop has a chance to send it.
					c.flushClients(time.Second)
					sendq.recycle(&msgs)
					return
				}
				pm.returnToPool()
			}
			sendq.recycle(&msgs)
		case <-resetCh:
			goto RESET
		case <-s.quitCh:
			return
		}
	}
}

// Will send a shutdown message for lame-duck. Unlike sendShutdownEvent, this will
// not close off the send queue or reply handler, as we may still have a workload
// that needs migrating off.
// Lock should be held.
func (s *Server) sendLDMShutdownEventLocked() {
	if s.sys == nil || s.sys.sendq == nil {
		return
	}
	subj := fmt.Sprintf(lameDuckEventSubj, s.info.ID)
	si := &ServerInfo{}
	s.sys.sendq.push(newPubMsg(nil, subj, _EMPTY_, si, nil, si, noCompression, false, true))
}

// Will send a shutdown message.
func (s *Server) sendShutdownEvent() {
	s.mu.Lock()
	if s.sys == nil || s.sys.sendq == nil {
		s.mu.Unlock()
		return
	}
	subj := fmt.Sprintf(shutdownEventSubj, s.info.ID)
	sendq := s.sys.sendq
	// Stop any more messages from queueing up.
	s.sys.sendq = nil
	// Unhook all msgHandlers. Normal client cleanup will deal with subs, etc.
	s.sys.replies = nil
	// Send to the internal queue and mark as last.
	si := &ServerInfo{}
	sendq.push(newPubMsg(nil, subj, _EMPTY_, si, nil, si, noCompression, false, true))
	s.mu.Unlock()
}

// Used to send an internal message to an arbitrary account.
func (s *Server) sendInternalAccountMsg(a *Account, subject string, msg any) error {
	return s.sendInternalAccountMsgWithReply(a, subject, _EMPTY_, nil, msg, false)
}

// Used to send an internal message with an optional reply to an arbitrary account.
func (s *Server) sendInternalAccountMsgWithReply(a *Account, subject, reply string, hdr map[string]string, msg any, echo bool) error {
	s.mu.RLock()
	if s.sys == nil || s.sys.sendq == nil {
		s.mu.RUnlock()
		if s.isShuttingDown() {
			// Skip in case this was called at the end phase during shut down
			// to avoid too many entries in the logs.
			return nil
		}
		return ErrNoSysAccount
	}
	c := s.sys.client
	// Replace our client with the account's internal client.
	if a != nil {
		a.mu.Lock()
		c = a.internalClient()
		a.mu.Unlock()
	}
	s.sys.sendq.push(newPubMsg(c, subject, reply, nil, hdr, msg, noCompression, echo, false))
	s.mu.RUnlock()
	return nil
}

// Send system style message to an account scope.
func (s *Server) sendInternalAccountSysMsg(a *Account, subj string, si *ServerInfo, msg interface{}) {
	s.mu.RLock()
	if s.sys == nil || s.sys.sendq == nil || a == nil {
		s.mu.RUnlock()
		return
	}
	sendq := s.sys.sendq
	s.mu.RUnlock()

	a.mu.Lock()
	c := a.internalClient()
	a.mu.Unlock()

	sendq.push(newPubMsg(c, subj, _EMPTY_, si, nil, msg, noCompression, false, false))
}

// This will queue up a message to be sent.
// Lock should not be held.
func (s *Server) sendInternalMsgLocked(subj, rply string, si *ServerInfo, msg any) {
	s.mu.RLock()
	s.sendInternalMsg(subj, rply, si, msg)
	s.mu.RUnlock()
}

// This will queue up a message to be sent.
// Assumes lock is held on entry.
func (s *Server) sendInternalMsg(subj, rply string, si *ServerInfo, msg any) {
	if s.sys == nil || s.sys.sendq == nil {
		return
	}
	s.sys.sendq.push(newPubMsg(nil, subj, rply, si, nil, msg, noCompression, false, false))
}

// Will send an api response.
func (s *Server) sendInternalResponse(subj string, response *ServerAPIResponse) {
	s.mu.RLock()
	if s.sys == nil || s.sys.sendq == nil {
		s.mu.RUnlock()
		return
	}
	s.sys.sendq.push(newPubMsg(nil, subj, _EMPTY_, response.Server, nil, response, response.compress, false, false))
	s.mu.RUnlock()
}

// Used to send internal messages from other system clients to avoid no echo issues.
func (c *client) sendInternalMsg(subj, rply string, si *ServerInfo, msg any) {
	if c == nil {
		return
	}
	s := c.srv
	if s == nil {
		return
	}
	s.mu.RLock()
	if s.sys == nil || s.sys.sendq == nil {
		s.mu.RUnlock()
		return
	}
	s.sys.sendq.push(newPubMsg(c, subj, rply, si, nil, msg, noCompression, false, false))
	s.mu.RUnlock()
}

// Locked version of checking if events system running. Also checks server.
func (s *Server) eventsRunning() bool {
	if s == nil {
		return false
	}
	s.mu.RLock()
	er := s.isRunning() && s.eventsEnabled()
	s.mu.RUnlock()
	return er
}

// EventsEnabled will report if the server has internal events enabled via
// a defined system account.
func (s *Server) EventsEnabled() bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.eventsEnabled()
}

// eventsEnabled will report if events are enabled.
// Lock should be held.
func (s *Server) eventsEnabled() bool {
	return s.sys != nil && s.sys.client != nil && s.sys.account != nil
}

// TrackedRemoteServers returns how many remote servers we are tracking
// from a system events perspective.
func (s *Server) TrackedRemoteServers() int {
	s.mu.RLock()
	defer s.mu.RUnlock()
	if !s.isRunning() || !s.eventsEnabled() {
		return -1
	}
	return len(s.sys.servers)
}

// Check for orphan servers who may have gone away without notification.
// This should be wrapChk() to setup common locking.
func (s *Server) checkRemoteServers() {
	now := time.Now()
	for sid, su := range s.sys.servers {
		if now.Sub(su.ltime) > s.sys.orphMax {
			s.Debugf("Detected orphan remote server: %q", sid)
			// Simulate it going away.
			s.processRemoteServerShutdown(sid)
		}
	}
	if s.sys.sweeper != nil {
		s.sys.sweeper.Reset(s.sys.chkOrph)
	}
}

// Grab RSS and PCPU
// Server lock will be held but released.
func (s *Server) updateServerUsage(v *ServerStats) {
	var vss int64
	pse.ProcUsage(&v.CPU, &v.Mem, &vss)
	v.Cores = runtime.NumCPU()
}

// Generate a route stat for our statz update.
func routeStat(r *client) *RouteStat {
	if r == nil {
		return nil
	}
	r.mu.Lock()
	// Note: *client.out[Msgs|Bytes] are not set using atomics,
	// unlike in[Msgs|Bytes].
	rs := &RouteStat{
		ID: r.cid,
		Sent: DataStats{
			Msgs:  r.outMsgs,
			Bytes: r.outBytes,
		},
		Received: DataStats{
			Msgs:  atomic.LoadInt64(&r.inMsgs),
			Bytes: atomic.LoadInt64(&r.inBytes),
		},
		Pending: int(r.out.pb),
	}
	if r.route != nil {
		rs.Name = r.route.remoteName
	}
	r.mu.Unlock()
	return rs
}

// Actual send method for statz updates.
// Lock should be held.
func (s *Server) sendStatsz(subj string) {
	var m ServerStatsMsg
	s.updateServerUsage(&m.Stats)

	if s.limitStatsz(subj) {
		return
	}

	s.mu.RLock()
	defer s.mu.RUnlock()

	// Check that we have a system account, etc.
	if s.sys == nil || s.sys.account == nil {
		return
	}

	shouldCheckInterest := func() bool {
		opts := s.getOpts()
		if opts.Cluster.Port != 0 || opts.Gateway.Port != 0 || opts.LeafNode.Port != 0 {
			return false
		}
		// If we are here we have no clustering or gateways and are not a leafnode hub.
		// Check for leafnode remotes that connect the system account.
		if len(opts.LeafNode.Remotes) > 0 {
			sysAcc := s.sys.account.GetName()
			for _, r := range opts.LeafNode.Remotes {
				if r.LocalAccount == sysAcc {
					return false
				}
			}
		}
		return true
	}

	// if we are running standalone, check for interest.
	if shouldCheckInterest() {
		// Check if we even have interest in this subject.
		sacc := s.sys.account
		rr := sacc.sl.Match(subj)
		totalSubs := len(rr.psubs) + len(rr.qsubs)
		if totalSubs == 0 {
			return
		} else if totalSubs == 1 && len(rr.psubs) == 1 {
			// For the broadcast subject we listen to that ourselves with no echo for remote updates.
			// If we are the only ones listening do not send either.
			if rr.psubs[0] == s.sys.remoteStatsSub {
				return
			}
		}
	}

	m.Stats.Start = s.start
	m.Stats.Connections = len(s.clients)
	m.Stats.TotalConnections = s.totalClients
	m.Stats.ActiveAccounts = int(atomic.LoadInt32(&s.activeAccounts))
	m.Stats.Received.Msgs = atomic.LoadInt64(&s.inMsgs)
	m.Stats.Received.Bytes = atomic.LoadInt64(&s.inBytes)
	m.Stats.Sent.Msgs = atomic.LoadInt64(&s.outMsgs)
	m.Stats.Sent.Bytes = atomic.LoadInt64(&s.outBytes)
	m.Stats.SlowConsumers = atomic.LoadInt64(&s.slowConsumers)
	m.Stats.NumSubs = s.numSubscriptions()
	// Routes
	s.forEachRoute(func(r *client) {
		m.Stats.Routes = append(m.Stats.Routes, routeStat(r))
	})
	// Gateways
	if s.gateway.enabled {
		gw := s.gateway
		gw.RLock()
		for name, c := range gw.out {
			gs := &GatewayStat{Name: name}
			c.mu.Lock()
			gs.ID = c.cid
			// Note that *client.out[Msgs|Bytes] are not set using atomic,
			// unlike the in[Msgs|bytes].
			gs.Sent = DataStats{
				Msgs:  c.outMsgs,
				Bytes: c.outBytes,
			}
			c.mu.Unlock()
			// Gather matching inbound connections
			gs.Received = DataStats{}
			for _, c := range gw.in {
				c.mu.Lock()
				if c.gw.name == name {
					gs.Received.Msgs += atomic.LoadInt64(&c.inMsgs)
					gs.Received.Bytes += atomic.LoadInt64(&c.inBytes)
					gs.NumInbound++
				}
				c.mu.Unlock()
			}
			m.Stats.Gateways = append(m.Stats.Gateways, gs)
		}
		gw.RUnlock()
	}
	// Active Servers
	m.Stats.ActiveServers = len(s.sys.servers) + 1

	// JetStream
	if js := s.js.Load(); js != nil {
		jStat := &JetStreamVarz{}
		s.mu.RUnlock()
		js.mu.RLock()
		c := js.config
		c.StoreDir = _EMPTY_
		jStat.Config = &c
		js.mu.RUnlock()
		jStat.Stats = js.usageStats()
		// Update our own usage since we do not echo so we will not hear ourselves.
		ourNode := getHash(s.serverName())
		if v, ok := s.nodeToInfo.Load(ourNode); ok && v != nil {
			ni := v.(nodeInfo)
			ni.stats = jStat.Stats
			ni.cfg = jStat.Config
			s.optsMu.RLock()
			ni.tags = copyStrings(s.opts.Tags)
			s.optsMu.RUnlock()
			s.nodeToInfo.Store(ourNode, ni)
		}
		// Metagroup info.
		if mg := js.getMetaGroup(); mg != nil {
			if mg.Leader() {
				if ci := s.raftNodeToClusterInfo(mg); ci != nil {
					jStat.Meta = &MetaClusterInfo{
						Name:     ci.Name,
						Leader:   ci.Leader,
						Peer:     getHash(ci.Leader),
						Replicas: ci.Replicas,
						Size:     mg.ClusterSize(),
					}
				}
			} else {
				// non leader only include a shortened version without peers
				leader := s.serverNameForNode(mg.GroupLeader())
				jStat.Meta = &MetaClusterInfo{
					Name:   mg.Group(),
					Leader: leader,
					Peer:   getHash(leader),
					Size:   mg.ClusterSize(),
				}
			}
			if ipq := s.jsAPIRoutedReqs; ipq != nil && jStat.Meta != nil {
				jStat.Meta.Pending = ipq.len()
			}
		}
		m.Stats.JetStream = jStat
		s.mu.RLock()
	}
	// Send message.
	s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
}

// Limit updates to the heartbeat interval, max one second by default.
func (s *Server) limitStatsz(subj string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()

	if s.sys == nil {
		return true
	}

	// Only limit the normal broadcast subject.
	if subj != fmt.Sprintf(serverStatsSubj, s.ID()) {
		return false
	}

	interval := statszRateLimit
	if s.sys.cstatsz < interval {
		interval = s.sys.cstatsz
	}
	if time.Since(s.sys.lastStatsz) < interval {
		// Reschedule heartbeat for the next interval.
		if s.sys.stmr != nil {
			s.sys.stmr.Reset(time.Until(s.sys.lastStatsz.Add(interval)))
		}
		return true
	}
	s.sys.lastStatsz = time.Now()
	return false
}

// Send out our statz update.
// This should be wrapChk() to setup common locking.
func (s *Server) heartbeatStatsz() {
	if s.sys.stmr != nil {
		// Increase after startup to our max.
		if s.sys.cstatsz < s.sys.statsz {
			s.sys.cstatsz *= 2
			if s.sys.cstatsz > s.sys.statsz {
				s.sys.cstatsz = s.sys.statsz
			}
		}
		s.sys.stmr.Reset(s.sys.cstatsz)
	}
	// Do in separate Go routine.
	go s.sendStatszUpdate()
}

// Reset statsz rate limit for the next broadcast.
// This should be wrapChk() to setup common locking.
func (s *Server) resetLastStatsz() {
	s.sys.lastStatsz = time.Time{}
}

func (s *Server) sendStatszUpdate() {
	s.sendStatsz(fmt.Sprintf(serverStatsSubj, s.ID()))
}

// This should be wrapChk() to setup common locking.
func (s *Server) startStatszTimer() {
	// We will start by sending out more of these and trail off to the statsz being the max.
	s.sys.cstatsz = 250 * time.Millisecond
	// Send out the first one quickly, we will slowly back off.
	s.sys.stmr = time.AfterFunc(s.sys.cstatsz, s.wrapChk(s.heartbeatStatsz))
}

// Start a ticker that will fire periodically and check for orphaned servers.
// This should be wrapChk() to setup common locking.
func (s *Server) startRemoteServerSweepTimer() {
	s.sys.sweeper = time.AfterFunc(s.sys.chkOrph, s.wrapChk(s.checkRemoteServers))
}

// Length of our system hash used for server targeted messages.
const sysHashLen = 8

// Computes a hash of 8 characters for the name.
func getHash(name string) string {
	return getHashSize(name, sysHashLen)
}

// Computes a hash for the given `name`. The result will be `size` characters long.
func getHashSize(name string, size int) string {
	sha := sha256.New()
	sha.Write([]byte(name))
	b := sha.Sum(nil)
	for i := 0; i < size; i++ {
		b[i] = digits[int(b[i]%base)]
	}
	return string(b[:size])
}

// Returns the node name for this server which is a hash of the server name.
func (s *Server) Node() string {
	s.mu.RLock()
	defer s.mu.RUnlock()
	if s.sys != nil {
		return s.sys.shash
	}
	return _EMPTY_
}

// This will setup our system wide tracking subs.
// For now we will setup one wildcard subscription to
// monitor all accounts for changes in number of connections.
// We can make this on a per account tracking basis if needed.
// Tradeoff is subscription and interest graph events vs connect and
// disconnect events, etc.
func (s *Server) initEventTracking() {
	// Capture sys in case we are shutdown while setting up.
	s.mu.RLock()
	sys := s.sys
	s.mu.RUnlock()

	if sys == nil || sys.client == nil || sys.account == nil {
		return
	}
	// Create a system hash which we use for other servers to target us specifically.
	sys.shash = getHash(s.info.Name)

	// This will be for all inbox responses.
	subject := fmt.Sprintf(inboxRespSubj, sys.shash, "*")
	if _, err := s.sysSubscribe(subject, s.inboxReply); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	sys.inboxPre = subject
	// This is for remote updates for connection accounting.
	subject = fmt.Sprintf(accConnsEventSubjOld, "*")
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteConnsUpdate)); err != nil {
		s.Errorf("Error setting up internal tracking for %s: %v", subject, err)
		return
	}
	// This will be for responses for account info that we send out.
	subject = fmt.Sprintf(connsRespSubj, s.info.ID)
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteConnsUpdate)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	// Listen for broad requests to respond with number of subscriptions for a given subject.
	if _, err := s.sysSubscribe(accNumSubsReqSubj, s.noInlineCallback(s.nsubsRequest)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	// Listen for statsz from others.
	subject = fmt.Sprintf(serverStatsSubj, "*")
	if sub, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteServerUpdate)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	} else {
		// Keep track of this one.
		sys.remoteStatsSub = sub
	}

	// Listen for all server shutdowns.
	subject = fmt.Sprintf(shutdownEventSubj, "*")
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteServerShutdown)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	// Listen for servers entering lame-duck mode.
	// NOTE: This currently is handled in the same way as a server shutdown, but has
	// a different subject in case we need to handle differently in future.
	subject = fmt.Sprintf(lameDuckEventSubj, "*")
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteServerShutdown)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	// Listen for account claims updates.
	subscribeToUpdate := true
	if s.accResolver != nil {
		subscribeToUpdate = !s.accResolver.IsTrackingUpdate()
	}
	if subscribeToUpdate {
		for _, sub := range []string{accUpdateEventSubjOld, accUpdateEventSubjNew} {
			if _, err := s.sysSubscribe(fmt.Sprintf(sub, "*"), s.noInlineCallback(s.accountClaimUpdate)); err != nil {
				s.Errorf("Error setting up internal tracking: %v", err)
				return
			}
		}
	}
	// Listen for ping messages that will be sent to all servers for statsz.
	// This subscription is kept for backwards compatibility. Got replaced by ...PING.STATZ from below
	if _, err := s.sysSubscribe(serverStatsPingReqSubj, s.noInlineCallbackStatsz(s.statszReq)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	monSrvc := map[string]sysMsgHandler{
		"IDZ":    s.idzReq,
		"STATSZ": s.statszReq,
		"VARZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &VarzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Varz(&optz.VarzOptions) })
		},
		"SUBSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &SubszEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Subsz(&optz.SubszOptions) })
		},
		"CONNZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &ConnzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Connz(&optz.ConnzOptions) })
		},
		"ROUTEZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &RoutezEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Routez(&optz.RoutezOptions) })
		},
		"GATEWAYZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &GatewayzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Gatewayz(&optz.GatewayzOptions) })
		},
		"LEAFZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &LeafzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Leafz(&optz.LeafzOptions) })
		},
		"ACCOUNTZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &AccountzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Accountz(&optz.AccountzOptions) })
		},
		"JSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &JszEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Jsz(&optz.JSzOptions) })
		},
		"HEALTHZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &HealthzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.healthz(&optz.HealthzOptions), nil })
		},
		"PROFILEZ": nil, // Special case, see below
		"EXPVARZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &ExpvarzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.expvarz(optz), nil })
		},
		"IPQUEUESZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &IpqueueszEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Ipqueuesz(&optz.IpqueueszOptions), nil })
		},
		"RAFTZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &RaftzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) { return s.Raftz(&optz.RaftzOptions), nil })
		},
	}
	profilez := func(_ *subscription, c *client, _ *Account, _, rply string, rmsg []byte) {
		hdr, msg := c.msgParts(rmsg)
		// Need to copy since we are passing those to the go routine below.
		hdr, msg = copyBytes(hdr), copyBytes(msg)
		// Execute in its own go routine because CPU profiling, for instance,
		// could take several seconds to complete.
		go func() {
			optz := &ProfilezEventOptions{}
			s.zReq(c, rply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				return s.profilez(&optz.ProfilezOptions), nil
			})
		}()
	}
	for name, req := range monSrvc {
		var h msgHandler
		switch name {
		case "PROFILEZ":
			h = profilez
		case "STATSZ":
			h = s.noInlineCallbackStatsz(req)
		default:
			h = s.noInlineCallback(req)
		}
		subject = fmt.Sprintf(serverDirectReqSubj, s.info.ID, name)
		if _, err := s.sysSubscribe(subject, h); err != nil {
			s.Errorf("Error setting up internal tracking: %v", err)
			return
		}
		subject = fmt.Sprintf(serverPingReqSubj, name)
		if _, err := s.sysSubscribe(subject, h); err != nil {
			s.Errorf("Error setting up internal tracking: %v", err)
			return
		}
	}
	extractAccount := func(subject string) (string, error) {
		if tk := strings.Split(subject, tsep); len(tk) != accReqTokens {
			return _EMPTY_, fmt.Errorf("subject %q is malformed", subject)
		} else {
			return tk[accReqAccIndex], nil
		}
	}
	monAccSrvc := map[string]sysMsgHandler{
		"SUBSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &SubszEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if acc, err := extractAccount(subject); err != nil {
					return nil, err
				} else {
					optz.SubszOptions.Subscriptions = true
					optz.SubszOptions.Account = acc
					return s.Subsz(&optz.SubszOptions)
				}
			})
		},
		"CONNZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &ConnzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if acc, err := extractAccount(subject); err != nil {
					return nil, err
				} else {
					optz.ConnzOptions.Account = acc
					return s.Connz(&optz.ConnzOptions)
				}
			})
		},
		"LEAFZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &LeafzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if acc, err := extractAccount(subject); err != nil {
					return nil, err
				} else {
					optz.LeafzOptions.Account = acc
					return s.Leafz(&optz.LeafzOptions)
				}
			})
		},
		"JSZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &JszEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if acc, err := extractAccount(subject); err != nil {
					return nil, err
				} else {
					optz.Account = acc
					return s.JszAccount(&optz.JSzOptions)
				}
			})
		},
		"INFO": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &AccInfoEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if acc, err := extractAccount(subject); err != nil {
					return nil, err
				} else {
					return s.accountInfo(acc)
				}
			})
		},
		// STATZ is essentially a duplicate of CONNS with an envelope identical to the others.
		// For historical reasons CONNS is the odd one out.
		// STATZ is also less heavy weight than INFO
		"STATZ": func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &AccountStatzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if acc, err := extractAccount(subject); err != nil {
					return nil, err
				} else if acc == "PING" { // Filter PING subject. Happens for server as well. But wildcards are not used
					return nil, errSkipZreq
				} else {
					optz.Accounts = []string{acc}
					if stz, err := s.AccountStatz(&optz.AccountStatzOptions); err != nil {
						return nil, err
					} else if len(stz.Accounts) == 0 && !optz.IncludeUnused {
						return nil, errSkipZreq
					} else {
						return stz, nil
					}
				}
			})
		},
		"CONNS": s.connsRequest,
	}
	for name, req := range monAccSrvc {
		if _, err := s.sysSubscribe(fmt.Sprintf(accDirectReqSubj, "*", name), s.noInlineCallback(req)); err != nil {
			s.Errorf("Error setting up internal tracking: %v", err)
			return
		}
	}

	// User info.
	// TODO(dlc) - Can be internal and not forwarded since bound server for the client connection
	// is only one that will answer. This breaks tests since we still forward on remote server connect.
	if _, err := s.sysSubscribe(fmt.Sprintf(userDirectReqSubj, "*"), s.userInfoReq); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}

	// For now only the STATZ subject has an account specific ping equivalent.
	if _, err := s.sysSubscribe(fmt.Sprintf(accPingReqSubj, "STATZ"),
		s.noInlineCallback(func(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
			optz := &AccountStatzEventOptions{}
			s.zReq(c, reply, hdr, msg, &optz.EventFilterOptions, optz, func() (any, error) {
				if stz, err := s.AccountStatz(&optz.AccountStatzOptions); err != nil {
					return nil, err
				} else if len(stz.Accounts) == 0 && !optz.IncludeUnused {
					return nil, errSkipZreq
				} else {
					return stz, nil
				}
			})
		})); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}

	// Listen for updates when leaf nodes connect for a given account. This will
	// force any gateway connections to move to `modeInterestOnly`
	subject = fmt.Sprintf(leafNodeConnectEventSubj, "*")
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.leafNodeConnected)); err != nil {
		s.Errorf("Error setting up internal tracking: %v", err)
		return
	}
	// For tracking remote latency measurements.
	subject = fmt.Sprintf(remoteLatencyEventSubj, sys.shash)
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.remoteLatencyUpdate)); err != nil {
		s.Errorf("Error setting up internal latency tracking: %v", err)
		return
	}
	// This is for simple debugging of number of subscribers that exist in the system.
	if _, err := s.sysSubscribeInternal(accSubsSubj, s.noInlineCallback(s.debugSubscribers)); err != nil {
		s.Errorf("Error setting up internal debug service for subscribers: %v", err)
		return
	}

	// Listen for requests to reload the server configuration.
	subject = fmt.Sprintf(serverReloadReqSubj, s.info.ID)
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.reloadConfig)); err != nil {
		s.Errorf("Error setting up server reload handler: %v", err)
		return
	}

	// Client connection kick
	subject = fmt.Sprintf(clientKickReqSubj, s.info.ID)
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.kickClient)); err != nil {
		s.Errorf("Error setting up client kick service: %v", err)
		return
	}
	// Client connection LDM
	subject = fmt.Sprintf(clientLDMReqSubj, s.info.ID)
	if _, err := s.sysSubscribe(subject, s.noInlineCallback(s.ldmClient)); err != nil {
		s.Errorf("Error setting up client LDM service: %v", err)
		return
	}
}

// UserInfo returns basic information to a user about bound account and user permissions.
// For account information they will need to ping that separately, and this allows security
// controls on each subsystem if desired, e.g. account info, jetstream account info, etc.
type UserInfo struct {
	UserID      string        `json:"user"`
	Account     string        `json:"account"`
	Permissions *Permissions  `json:"permissions,omitempty"`
	Expires     time.Duration `json:"expires,omitempty"`
}

// Process a user info request.
func (s *Server) userInfoReq(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
	if !s.EventsEnabled() || reply == _EMPTY_ {
		return
	}

	response := &ServerAPIResponse{Server: &ServerInfo{}}

	ci, _, _, _, err := s.getRequestInfo(c, msg)
	if err != nil {
		response.Error = &ApiError{Code: http.StatusBadRequest}
		s.sendInternalResponse(reply, response)
		return
	}

	response.Data = &UserInfo{
		UserID:      ci.User,
		Account:     ci.Account,
		Permissions: c.publicPermissions(),
		Expires:     c.claimExpiration(),
	}
	s.sendInternalResponse(reply, response)
}

// register existing accounts with any system exports.
func (s *Server) registerSystemImportsForExisting() {
	var accounts []*Account

	s.mu.RLock()
	if s.sys == nil {
		s.mu.RUnlock()
		return
	}
	sacc := s.sys.account
	s.accounts.Range(func(k, v any) bool {
		a := v.(*Account)
		if a != sacc {
			accounts = append(accounts, a)
		}
		return true
	})
	s.mu.RUnlock()

	for _, a := range accounts {
		s.registerSystemImports(a)
	}
}

// add all exports a system account will need
func (s *Server) addSystemAccountExports(sacc *Account) {
	if !s.EventsEnabled() {
		return
	}
	accConnzSubj := fmt.Sprintf(accDirectReqSubj, "*", "CONNZ")
	// prioritize not automatically added exports
	if !sacc.hasServiceExportMatching(accConnzSubj) {
		// pick export type that clamps importing account id into subject
		if err := sacc.addServiceExportWithResponseAndAccountPos(accConnzSubj, Streamed, nil, 4); err != nil {
			//if err := sacc.AddServiceExportWithResponse(accConnzSubj, Streamed, nil); err != nil {
			s.Errorf("Error adding system service export for %q: %v", accConnzSubj, err)
		}
	}
	// prioritize not automatically added exports
	accStatzSubj := fmt.Sprintf(accDirectReqSubj, "*", "STATZ")
	if !sacc.hasServiceExportMatching(accStatzSubj) {
		// pick export type that clamps importing account id into subject
		if err := sacc.addServiceExportWithResponseAndAccountPos(accStatzSubj, Streamed, nil, 4); err != nil {
			s.Errorf("Error adding system service export for %q: %v", accStatzSubj, err)
		}
	}
	// FIXME(dlc) - Old experiment, Remove?
	if !sacc.hasServiceExportMatching(accSubsSubj) {
		if err := sacc.AddServiceExport(accSubsSubj, nil); err != nil {
			s.Errorf("Error adding system service export for %q: %v", accSubsSubj, err)
		}
	}

	// User info export.
	userInfoSubj := fmt.Sprintf(userDirectReqSubj, "*")
	if !sacc.hasServiceExportMatching(userInfoSubj) {
		if err := sacc.AddServiceExport(userInfoSubj, nil); err != nil {
			s.Errorf("Error adding system service export for %q: %v", userInfoSubj, err)
		}
		mappedSubj := fmt.Sprintf(userDirectReqSubj, sacc.GetName())
		if err := sacc.AddServiceImport(sacc, userDirectInfoSubj, mappedSubj); err != nil {
			s.Errorf("Error setting up system service import %s: %v", mappedSubj, err)
		}
		// Make sure to share details.
		sacc.setServiceImportSharing(sacc, mappedSubj, false, true)
	}

	// Register any accounts that existed prior.
	s.registerSystemImportsForExisting()

	// in case of a mixed mode setup, enable js exports anyway
	if s.JetStreamEnabled() || !s.standAloneMode() {
		s.checkJetStreamExports()
	}
}

// accountClaimUpdate will receive claim updates for accounts.
func (s *Server) accountClaimUpdate(sub *subscription, c *client, _ *Account, subject, resp string, hdr, msg []byte) {
	if !s.EventsEnabled() {
		return
	}
	var pubKey string
	toks := strings.Split(subject, tsep)
	if len(toks) == accUpdateTokensNew {
		pubKey = toks[accReqAccIndex]
	} else if len(toks) == accUpdateTokensOld {
		pubKey = toks[accUpdateAccIdxOld]
	} else {
		s.Debugf("Received account claims update on bad subject %q", subject)
		return
	}
	if len(msg) == 0 {
		err := errors.New("request body is empty")
		respondToUpdate(s, resp, pubKey, "jwt update error", err)
	} else if claim, err := jwt.DecodeAccountClaims(string(msg)); err != nil {
		respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err)
	} else if claim.Subject != pubKey {
		err := errors.New("subject does not match jwt content")
		respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err)
	} else if v, ok := s.accounts.Load(pubKey); !ok {
		respondToUpdate(s, resp, pubKey, "jwt update skipped", nil)
	} else if err := s.updateAccountWithClaimJWT(v.(*Account), string(msg)); err != nil {
		respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err)
	} else {
		respondToUpdate(s, resp, pubKey, "jwt updated", nil)
	}
}

// processRemoteServerShutdown will update any affected accounts.
// Will update the remote count for clients.
// Lock assume held.
func (s *Server) processRemoteServerShutdown(sid string) {
	s.accounts.Range(func(k, v any) bool {
		v.(*Account).removeRemoteServer(sid)
		return true
	})
	// Update any state in nodeInfo.
	s.nodeToInfo.Range(func(k, v any) bool {
		ni := v.(nodeInfo)
		if ni.id == sid {
			ni.offline = true
			s.nodeToInfo.Store(k, ni)
			return false
		}
		return true
	})
	delete(s.sys.servers, sid)
}

func (s *Server) sameDomain(domain string) bool {
	return domain == _EMPTY_ || s.info.Domain == _EMPTY_ || domain == s.info.Domain
}

// remoteServerShutdown is called when we get an event from another server shutting down.
func (s *Server) remoteServerShutdown(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !s.eventsEnabled() {
		return
	}
	toks := strings.Split(subject, tsep)
	if len(toks) < shutdownEventTokens {
		s.Debugf("Received remote server shutdown on bad subject %q", subject)
		return
	}

	if len(msg) == 0 {
		s.Errorf("Remote server sent invalid (empty) shutdown message to %q", subject)
		return
	}

	// We have an optional serverInfo here, remove from nodeToX lookups.
	var si ServerInfo
	if err := json.Unmarshal(msg, &si); err != nil {
		s.Debugf("Received bad server info for remote server shutdown")
		return
	}

	// JetStream node updates if applicable.
	node := getHash(si.Name)
	if v, ok := s.nodeToInfo.Load(node); ok && v != nil {
		ni := v.(nodeInfo)
		ni.offline = true
		s.nodeToInfo.Store(node, ni)
	}

	sid := toks[serverSubjectIndex]
	if su := s.sys.servers[sid]; su != nil {
		s.processRemoteServerShutdown(sid)
	}
}

// remoteServerUpdate listens for statsz updates from other servers.
func (s *Server) remoteServerUpdate(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	var ssm ServerStatsMsg
	if len(msg) == 0 {
		s.Debugf("Received empty server info for remote server update")
		return
	} else if err := json.Unmarshal(msg, &ssm); err != nil {
		s.Debugf("Received bad server info for remote server update")
		return
	}
	si := ssm.Server

	// Should do normal updates before bailing if wrong domain.
	s.mu.Lock()
	if s.isRunning() && s.eventsEnabled() && ssm.Server.ID != s.info.ID {
		s.updateRemoteServer(&si)
	}
	s.mu.Unlock()

	// JetStream node updates.
	if !s.sameDomain(si.Domain) {
		return
	}

	var cfg *JetStreamConfig
	var stats *JetStreamStats

	if ssm.Stats.JetStream != nil {
		cfg = ssm.Stats.JetStream.Config
		stats = ssm.Stats.JetStream.Stats
	}

	node := getHash(si.Name)
	s.nodeToInfo.Store(node, nodeInfo{
		si.Name,
		si.Version,
		si.Cluster,
		si.Domain,
		si.ID,
		si.Tags,
		cfg,
		stats,
		false,
		si.JetStreamEnabled(),
		si.BinaryStreamSnapshot(),
	})
}

// updateRemoteServer is called when we have an update from a remote server.
// This allows us to track remote servers, respond to shutdown messages properly,
// make sure that messages are ordered, and allow us to prune dead servers.
// Lock should be held upon entry.
func (s *Server) updateRemoteServer(si *ServerInfo) {
	su := s.sys.servers[si.ID]
	if su == nil {
		s.sys.servers[si.ID] = &serverUpdate{si.Seq, time.Now()}
		s.processNewServer(si)
	} else {
		// Should always be going up.
		if si.Seq <= su.seq {
			s.Errorf("Received out of order remote server update from: %q", si.ID)
			return
		}
		su.seq = si.Seq
		su.ltime = time.Now()
	}
}

// processNewServer will hold any logic we want to use when we discover a new server.
// Lock should be held upon entry.
func (s *Server) processNewServer(si *ServerInfo) {
	// Right now we only check if we have leafnode servers and if so send another
	// connect update to make sure they switch this account to interest only mode.
	s.ensureGWsInterestOnlyForLeafNodes()

	// Add to our nodeToName
	if s.sameDomain(si.Domain) {
		node := getHash(si.Name)
		// Only update if non-existent
		if _, ok := s.nodeToInfo.Load(node); !ok {
			s.nodeToInfo.Store(node, nodeInfo{
				si.Name,
				si.Version,
				si.Cluster,
				si.Domain,
				si.ID,
				si.Tags,
				nil,
				nil,
				false,
				si.JetStreamEnabled(),
				si.BinaryStreamSnapshot(),
			})
		}
	}
	// Announce ourselves..
	// Do this in a separate Go routine.
	go s.sendStatszUpdate()
}

// If GW is enabled on this server and there are any leaf node connections,
// this function will send a LeafNode connect system event to the super cluster
// to ensure that the GWs are in interest-only mode for this account.
// Lock should be held upon entry.
// TODO(dlc) - this will cause this account to be loaded on all servers. Need a better
// way with GW2.
func (s *Server) ensureGWsInterestOnlyForLeafNodes() {
	if !s.gateway.enabled || len(s.leafs) == 0 {
		return
	}
	sent := make(map[*Account]bool, len(s.leafs))
	for _, c := range s.leafs {
		if !sent[c.acc] {
			s.sendLeafNodeConnectMsg(c.acc.Name)
			sent[c.acc] = true
		}
	}
}

// shutdownEventing will clean up all eventing state.
func (s *Server) shutdownEventing() {
	if !s.eventsRunning() {
		return
	}

	s.mu.Lock()
	clearTimer(&s.sys.sweeper)
	clearTimer(&s.sys.stmr)
	rc := s.sys.resetCh
	s.sys.resetCh = nil
	wg := &s.sys.wg
	s.mu.Unlock()

	// We will queue up a shutdown event and wait for the
	// internal send loop to exit.
	s.sendShutdownEvent()
	wg.Wait()

	s.mu.Lock()
	defer s.mu.Unlock()

	// Whip through all accounts.
	s.accounts.Range(func(k, v any) bool {
		v.(*Account).clearEventing()
		return true
	})
	// Turn everything off here.
	s.sys = nil
	// Make sure this is done after s.sys = nil, so that we don't
	// get sends to closed channels on badly-timed config reloads.
	close(rc)
}

// Request for our local connection count.
func (s *Server) connsRequest(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}
	tk := strings.Split(subject, tsep)
	if len(tk) != accReqTokens {
		s.sys.client.Errorf("Bad subject account connections request message")
		return
	}
	a := tk[accReqAccIndex]
	m := accNumConnsReq{Account: a}
	if len(msg) > 0 {
		if err := json.Unmarshal(msg, &m); err != nil {
			s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
			return
		}
	}
	if m.Account != a {
		s.sys.client.Errorf("Error unmarshalled account does not match subject")
		return
	}
	// Here we really only want to lookup the account if its local. We do not want to fetch this
	// account if we have no interest in it.
	var acc *Account
	if v, ok := s.accounts.Load(m.Account); ok {
		acc = v.(*Account)
	}
	if acc == nil {
		return
	}
	// We know this is a local connection.
	if nlc := acc.NumLocalConnections(); nlc > 0 {
		s.mu.Lock()
		s.sendAccConnsUpdate(acc, reply)
		s.mu.Unlock()
	}
}

// leafNodeConnected is an event we will receive when a leaf node for a given account connects.
func (s *Server) leafNodeConnected(sub *subscription, _ *client, _ *Account, subject, reply string, hdr, msg []byte) {
	m := accNumConnsReq{}
	if err := json.Unmarshal(msg, &m); err != nil {
		s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
		return
	}

	s.mu.RLock()
	na := m.Account == _EMPTY_ || !s.eventsEnabled() || !s.gateway.enabled
	s.mu.RUnlock()

	if na {
		return
	}

	if acc, _ := s.lookupAccount(m.Account); acc != nil {
		s.switchAccountToInterestMode(acc.Name)
	}
}

// Common filter options for system requests STATSZ VARZ SUBSZ CONNZ ROUTEZ GATEWAYZ LEAFZ
type EventFilterOptions struct {
	Name    string   `json:"server_name,omitempty"` // filter by server name
	Cluster string   `json:"cluster,omitempty"`     // filter by cluster name
	Host    string   `json:"host,omitempty"`        // filter by host name
	Tags    []string `json:"tags,omitempty"`        // filter by tags (must match all tags)
	Domain  string   `json:"domain,omitempty"`      // filter by JS domain
}

// StatszEventOptions are options passed to Statsz
type StatszEventOptions struct {
	// No actual options yet
	EventFilterOptions
}

// Options for account Info
type AccInfoEventOptions struct {
	// No actual options yet
	EventFilterOptions
}

// In the context of system events, ConnzEventOptions are options passed to Connz
type ConnzEventOptions struct {
	ConnzOptions
	EventFilterOptions
}

// In the context of system events, RoutezEventOptions are options passed to Routez
type RoutezEventOptions struct {
	RoutezOptions
	EventFilterOptions
}

// In the context of system events, SubzEventOptions are options passed to Subz
type SubszEventOptions struct {
	SubszOptions
	EventFilterOptions
}

// In the context of system events, VarzEventOptions are options passed to Varz
type VarzEventOptions struct {
	VarzOptions
	EventFilterOptions
}

// In the context of system events, GatewayzEventOptions are options passed to Gatewayz
type GatewayzEventOptions struct {
	GatewayzOptions
	EventFilterOptions
}

// In the context of system events, LeafzEventOptions are options passed to Leafz
type LeafzEventOptions struct {
	LeafzOptions
	EventFilterOptions
}

// In the context of system events, AccountzEventOptions are options passed to Accountz
type AccountzEventOptions struct {
	AccountzOptions
	EventFilterOptions
}

// In the context of system events, AccountzEventOptions are options passed to Accountz
type AccountStatzEventOptions struct {
	AccountStatzOptions
	EventFilterOptions
}

// In the context of system events, JszEventOptions are options passed to Jsz
type JszEventOptions struct {
	JSzOptions
	EventFilterOptions
}

// In the context of system events, HealthzEventOptions are options passed to Healthz
type HealthzEventOptions struct {
	HealthzOptions
	EventFilterOptions
}

// In the context of system events, ProfilezEventOptions are options passed to Profilez
type ProfilezEventOptions struct {
	ProfilezOptions
	EventFilterOptions
}

// In the context of system events, ExpvarzEventOptions are options passed to Expvarz
type ExpvarzEventOptions struct {
	EventFilterOptions
}

// In the context of system events, IpqueueszEventOptions are options passed to Ipqueuesz
type IpqueueszEventOptions struct {
	EventFilterOptions
	IpqueueszOptions
}

// In the context of system events, RaftzEventOptions are options passed to Raftz
type RaftzEventOptions struct {
	EventFilterOptions
	RaftzOptions
}

// returns true if the request does NOT apply to this server and can be ignored.
// DO NOT hold the server lock when
func (s *Server) filterRequest(fOpts *EventFilterOptions) bool {
	if fOpts.Name != _EMPTY_ && !strings.Contains(s.info.Name, fOpts.Name) {
		return true
	}
	if fOpts.Host != _EMPTY_ && !strings.Contains(s.info.Host, fOpts.Host) {
		return true
	}
	if fOpts.Cluster != _EMPTY_ {
		if !strings.Contains(s.ClusterName(), fOpts.Cluster) {
			return true
		}
	}
	if len(fOpts.Tags) > 0 {
		opts := s.getOpts()
		for _, t := range fOpts.Tags {
			if !opts.Tags.Contains(t) {
				return true
			}
		}
	}
	if fOpts.Domain != _EMPTY_ && s.getOpts().JetStreamDomain != fOpts.Domain {
		return true
	}
	return false
}

// Encoding support (compression)
type compressionType int8

const (
	noCompression = compressionType(iota)
	gzipCompression
	snappyCompression
	unsupportedCompression
)

// ServerAPIResponse is the response type for the server API like varz, connz etc.
type ServerAPIResponse struct {
	Server *ServerInfo `json:"server"`
	Data   any         `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`

	// Private to indicate compression if any.
	compress compressionType
}

// Specialized response types for unmarshalling. These structures are not
// used in the server code and only there for users of the Z endpoints to
// unmarshal the data without having to create these structs in their code

// ServerAPIConnzResponse is the response type connz
type ServerAPIConnzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Connz      `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPIRoutezResponse is the response type for routez
type ServerAPIRoutezResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Routez     `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPIGatewayzResponse is the response type for gatewayz
type ServerAPIGatewayzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Gatewayz   `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPIJszResponse is the response type for jsz
type ServerAPIJszResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *JSInfo     `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPIHealthzResponse is the response type for healthz
type ServerAPIHealthzResponse struct {
	Server *ServerInfo   `json:"server"`
	Data   *HealthStatus `json:"data,omitempty"`
	Error  *ApiError     `json:"error,omitempty"`
}

// ServerAPIVarzResponse is the response type for varz
type ServerAPIVarzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Varz       `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPISubszResponse is the response type for subsz
type ServerAPISubszResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Subsz      `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPILeafzResponse is the response type for leafz
type ServerAPILeafzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Leafz      `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPIAccountzResponse is the response type for accountz
type ServerAPIAccountzResponse struct {
	Server *ServerInfo `json:"server"`
	Data   *Accountz   `json:"data,omitempty"`
	Error  *ApiError   `json:"error,omitempty"`
}

// ServerAPIExpvarzResponse is the response type for expvarz
type ServerAPIExpvarzResponse struct {
	Server *ServerInfo    `json:"server"`
	Data   *ExpvarzStatus `json:"data,omitempty"`
	Error  *ApiError      `json:"error,omitempty"`
}

// ServerAPIpqueueszResponse is the response type for ipqueuesz
type ServerAPIpqueueszResponse struct {
	Server *ServerInfo      `json:"server"`
	Data   *IpqueueszStatus `json:"data,omitempty"`
	Error  *ApiError        `json:"error,omitempty"`
}

// ServerAPIRaftzResponse is the response type for raftz
type ServerAPIRaftzResponse struct {
	Server *ServerInfo  `json:"server"`
	Data   *RaftzStatus `json:"data,omitempty"`
	Error  *ApiError    `json:"error,omitempty"`
}

// statszReq is a request for us to respond with current statsz.
func (s *Server) statszReq(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.EventsEnabled() {
		return
	}

	// No reply is a signal that we should use our normal broadcast subject.
	if reply == _EMPTY_ {
		reply = fmt.Sprintf(serverStatsSubj, s.info.ID)
		s.wrapChk(s.resetLastStatsz)
	}

	opts := StatszEventOptions{}
	if len(msg) != 0 {
		if err := json.Unmarshal(msg, &opts); err != nil {
			response := &ServerAPIResponse{
				Server: &ServerInfo{},
				Error:  &ApiError{Code: http.StatusBadRequest, Description: err.Error()},
			}
			s.sendInternalMsgLocked(reply, _EMPTY_, response.Server, response)
			return
		} else if ignore := s.filterRequest(&opts.EventFilterOptions); ignore {
			return
		}
	}
	s.sendStatsz(reply)
}

// idzReq is for a request for basic static server info.
// Try to not hold the write lock or dynamically create data.
func (s *Server) idzReq(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	id := &ServerID{
		Name: s.info.Name,
		Host: s.info.Host,
		ID:   s.info.ID,
	}
	s.sendInternalMsg(reply, _EMPTY_, nil, &id)
}

var errSkipZreq = errors.New("filtered response")

const (
	acceptEncodingHeader  = "Accept-Encoding"
	contentEncodingHeader = "Content-Encoding"
)

// This is not as formal as it could be. We see if anything has s2 or snappy first, then gzip.
func getAcceptEncoding(hdr []byte) compressionType {
	ae := strings.ToLower(string(getHeader(acceptEncodingHeader, hdr)))
	if ae == _EMPTY_ {
		return noCompression
	}
	if strings.Contains(ae, "snappy") || strings.Contains(ae, "s2") {
		return snappyCompression
	}
	if strings.Contains(ae, "gzip") {
		return gzipCompression
	}
	return unsupportedCompression
}

func (s *Server) zReq(_ *client, reply string, hdr, msg []byte, fOpts *EventFilterOptions, optz any, respf func() (any, error)) {
	if !s.EventsEnabled() || reply == _EMPTY_ {
		return
	}
	response := &ServerAPIResponse{Server: &ServerInfo{}}
	var err error
	status := 0
	if len(msg) != 0 {
		if err = json.Unmarshal(msg, optz); err != nil {
			status = http.StatusBadRequest // status is only included on error, so record how far execution got
		} else if s.filterRequest(fOpts) {
			return
		}
	}
	if err == nil {
		response.Data, err = respf()
		if errors.Is(err, errSkipZreq) {
			return
		} else if err != nil {
			status = http.StatusInternalServerError
		}
	}
	if err != nil {
		response.Error = &ApiError{Code: status, Description: err.Error()}
	} else if len(hdr) > 0 {
		response.compress = getAcceptEncoding(hdr)
	}
	s.sendInternalResponse(reply, response)
}

// remoteConnsUpdate gets called when we receive a remote update from another server.
func (s *Server) remoteConnsUpdate(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}
	var m AccountNumConns
	if len(msg) == 0 {
		s.sys.client.Errorf("No message body provided")
		return
	} else if err := json.Unmarshal(msg, &m); err != nil {
		s.sys.client.Errorf("Error unmarshalling account connection event message: %v", err)
		return
	}

	// See if we have the account registered, if not drop it.
	// Make sure this does not force us to load this account here.
	var acc *Account
	if v, ok := s.accounts.Load(m.Account); ok {
		acc = v.(*Account)
	}
	// Silently ignore these if we do not have local interest in the account.
	if acc == nil {
		return
	}

	s.mu.Lock()

	// check again here if we have been shutdown.
	if !s.isRunning() || !s.eventsEnabled() {
		s.mu.Unlock()
		return
	}
	// Double check that this is not us, should never happen, so error if it does.
	if m.Server.ID == s.info.ID {
		s.sys.client.Errorf("Processing our own account connection event message: ignored")
		s.mu.Unlock()
		return
	}
	// If we are here we have interest in tracking this account. Update our accounting.
	clients := acc.updateRemoteServer(&m)
	s.updateRemoteServer(&m.Server)
	s.mu.Unlock()
	// Need to close clients outside of server lock
	for _, c := range clients {
		c.maxAccountConnExceeded()
	}
}

// This will import any system level exports.
func (s *Server) registerSystemImports(a *Account) {
	if a == nil || !s.EventsEnabled() {
		return
	}
	sacc := s.SystemAccount()
	if sacc == nil || sacc == a {
		return
	}
	// FIXME(dlc) - make a shared list between sys exports etc.

	importSrvc := func(subj, mappedSubj string) {
		if !a.serviceImportExists(subj) {
			if err := a.addServiceImportWithClaim(sacc, subj, mappedSubj, nil, true); err != nil {
				s.Errorf("Error setting up system service import %s -> %s for account: %v",
					subj, mappedSubj, err)
			}
		}
	}
	// Add in this to the account in 2 places.
	// "$SYS.REQ.SERVER.PING.CONNZ" and "$SYS.REQ.ACCOUNT.PING.CONNZ"
	mappedConnzSubj := fmt.Sprintf(accDirectReqSubj, a.Name, "CONNZ")
	importSrvc(fmt.Sprintf(accPingReqSubj, "CONNZ"), mappedConnzSubj)
	importSrvc(fmt.Sprintf(serverPingReqSubj, "CONNZ"), mappedConnzSubj)
	importSrvc(fmt.Sprintf(accPingReqSubj, "STATZ"), fmt.Sprintf(accDirectReqSubj, a.Name, "STATZ"))

	// This is for user's looking up their own info.
	mappedSubject := fmt.Sprintf(userDirectReqSubj, a.Name)
	importSrvc(userDirectInfoSubj, mappedSubject)
	// Make sure to share details.
	a.setServiceImportSharing(sacc, mappedSubject, false, true)
}

// Setup tracking for this account. This allows us to track global account activity.
// Lock should be held on entry.
func (s *Server) enableAccountTracking(a *Account) {
	if a == nil || !s.eventsEnabled() {
		return
	}

	// TODO(ik): Generate payload although message may not be sent.
	// May need to ensure we do so only if there is a known interest.
	// This can get complicated with gateways.

	subj := fmt.Sprintf(accDirectReqSubj, a.Name, "CONNS")
	reply := fmt.Sprintf(connsRespSubj, s.info.ID)
	m := accNumConnsReq{Account: a.Name}
	s.sendInternalMsg(subj, reply, &m.Server, &m)
}

// Event on leaf node connect.
// Lock should NOT be held on entry.
func (s *Server) sendLeafNodeConnect(a *Account) {
	s.mu.Lock()
	// If we are not in operator mode, or do not have any gateways defined, this should also be a no-op.
	if a == nil || !s.eventsEnabled() || !s.gateway.enabled {
		s.mu.Unlock()
		return
	}
	s.sendLeafNodeConnectMsg(a.Name)
	s.mu.Unlock()

	s.switchAccountToInterestMode(a.Name)
}

// Send the leafnode connect message.
// Lock should be held.
func (s *Server) sendLeafNodeConnectMsg(accName string) {
	subj := fmt.Sprintf(leafNodeConnectEventSubj, accName)
	m := accNumConnsReq{Account: accName}
	s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
}

// sendAccConnsUpdate is called to send out our information on the
// account's local connections.
// Lock should be held on entry.
func (s *Server) sendAccConnsUpdate(a *Account, subj ...string) {
	if !s.eventsEnabled() || a == nil {
		return
	}
	sendQ := s.sys.sendq
	if sendQ == nil {
		return
	}
	// Build event with account name and number of local clients and leafnodes.
	eid := s.nextEventID()
	a.mu.Lock()
	stat := a.statz()
	m := AccountNumConns{
		TypedEvent: TypedEvent{
			Type: AccountNumConnsMsgType,
			ID:   eid,
			Time: time.Now().UTC(),
		},
		AccountStat: *stat,
	}
	// Set timer to fire again unless we are at zero.
	if m.TotalConns == 0 {
		clearTimer(&a.ctmr)
	} else {
		// Check to see if we have an HB running and update.
		if a.ctmr == nil {
			a.ctmr = time.AfterFunc(eventsHBInterval, func() { s.accConnsUpdate(a) })
		} else {
			a.ctmr.Reset(eventsHBInterval)
		}
	}
	for _, sub := range subj {
		msg := newPubMsg(nil, sub, _EMPTY_, &m.Server, nil, &m, noCompression, false, false)
		sendQ.push(msg)
	}
	a.mu.Unlock()
}

// Lock should be held on entry.
func (a *Account) statz() *AccountStat {
	localConns := a.numLocalConnections()
	leafConns := a.numLocalLeafNodes()
	return &AccountStat{
		Account:    a.Name,
		Conns:      localConns,
		LeafNodes:  leafConns,
		TotalConns: localConns + leafConns,
		NumSubs:    a.sl.Count(),
		Received: DataStats{
			Msgs:  atomic.LoadInt64(&a.inMsgs),
			Bytes: atomic.LoadInt64(&a.inBytes),
		},
		Sent: DataStats{
			Msgs:  atomic.LoadInt64(&a.outMsgs),
			Bytes: atomic.LoadInt64(&a.outBytes),
		},
		SlowConsumers: atomic.LoadInt64(&a.slowConsumers),
	}
}

// accConnsUpdate is called whenever there is a change to the account's
// number of active connections, or during a heartbeat.
// We will not send for $G.
func (s *Server) accConnsUpdate(a *Account) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !s.eventsEnabled() || a == nil || a == s.gacc {
		return
	}
	s.sendAccConnsUpdate(a, fmt.Sprintf(accConnsEventSubjOld, a.Name), fmt.Sprintf(accConnsEventSubjNew, a.Name))
}

// server lock should be held
func (s *Server) nextEventID() string {
	return s.eventIds.Next()
}

// accountConnectEvent will send an account client connect event if there is interest.
// This is a billing event.
func (s *Server) accountConnectEvent(c *client) {
	s.mu.Lock()
	if !s.eventsEnabled() {
		s.mu.Unlock()
		return
	}
	gacc := s.gacc
	eid := s.nextEventID()
	s.mu.Unlock()

	c.mu.Lock()
	// Ignore global account activity
	if c.acc == nil || c.acc == gacc {
		c.mu.Unlock()
		return
	}

	m := ConnectEventMsg{
		TypedEvent: TypedEvent{
			Type: ConnectEventMsgType,
			ID:   eid,
			Time: time.Now().UTC(),
		},
		Client: ClientInfo{
			Start:      &c.start,
			Host:       c.host,
			ID:         c.cid,
			Account:    accForClient(c),
			User:       c.getRawAuthUser(),
			Name:       c.opts.Name,
			Lang:       c.opts.Lang,
			Version:    c.opts.Version,
			Jwt:        c.opts.JWT,
			IssuerKey:  issuerForClient(c),
			Tags:       c.tags,
			NameTag:    c.nameTag,
			Kind:       c.kindString(),
			ClientType: c.clientTypeString(),
			MQTTClient: c.getMQTTClientID(),
		},
	}
	subj := fmt.Sprintf(connectEventSubj, c.acc.Name)
	c.mu.Unlock()

	s.sendInternalMsgLocked(subj, _EMPTY_, &m.Server, &m)
}

// accountDisconnectEvent will send an account client disconnect event if there is interest.
// This is a billing event.
func (s *Server) accountDisconnectEvent(c *client, now time.Time, reason string) {
	s.mu.Lock()
	if !s.eventsEnabled() {
		s.mu.Unlock()
		return
	}
	gacc := s.gacc
	eid := s.nextEventID()
	s.mu.Unlock()

	c.mu.Lock()

	// Ignore global account activity
	if c.acc == nil || c.acc == gacc {
		c.mu.Unlock()
		return
	}

	m := DisconnectEventMsg{
		TypedEvent: TypedEvent{
			Type: DisconnectEventMsgType,
			ID:   eid,
			Time: now,
		},
		Client: ClientInfo{
			Start:      &c.start,
			Stop:       &now,
			Host:       c.host,
			ID:         c.cid,
			Account:    accForClient(c),
			User:       c.getRawAuthUser(),
			Name:       c.opts.Name,
			Lang:       c.opts.Lang,
			Version:    c.opts.Version,
			RTT:        c.getRTT(),
			Jwt:        c.opts.JWT,
			IssuerKey:  issuerForClient(c),
			Tags:       c.tags,
			NameTag:    c.nameTag,
			Kind:       c.kindString(),
			ClientType: c.clientTypeString(),
			MQTTClient: c.getMQTTClientID(),
		},
		Sent: DataStats{
			Msgs:  atomic.LoadInt64(&c.inMsgs),
			Bytes: atomic.LoadInt64(&c.inBytes),
		},
		Received: DataStats{
			Msgs:  c.outMsgs,
			Bytes: c.outBytes,
		},
		Reason: reason,
	}
	accName := c.acc.Name
	c.mu.Unlock()

	subj := fmt.Sprintf(disconnectEventSubj, accName)
	s.sendInternalMsgLocked(subj, _EMPTY_, &m.Server, &m)
}

// This is the system level event sent to the system account for operators.
func (s *Server) sendAuthErrorEvent(c *client) {
	s.mu.Lock()
	if !s.eventsEnabled() {
		s.mu.Unlock()
		return
	}
	eid := s.nextEventID()
	s.mu.Unlock()

	now := time.Now().UTC()
	c.mu.Lock()
	m := DisconnectEventMsg{
		TypedEvent: TypedEvent{
			Type: DisconnectEventMsgType,
			ID:   eid,
			Time: now,
		},
		Client: ClientInfo{
			Start:      &c.start,
			Stop:       &now,
			Host:       c.host,
			ID:         c.cid,
			Account:    accForClient(c),
			User:       c.getRawAuthUser(),
			Name:       c.opts.Name,
			Lang:       c.opts.Lang,
			Version:    c.opts.Version,
			RTT:        c.getRTT(),
			Jwt:        c.opts.JWT,
			IssuerKey:  issuerForClient(c),
			Tags:       c.tags,
			NameTag:    c.nameTag,
			Kind:       c.kindString(),
			ClientType: c.clientTypeString(),
			MQTTClient: c.getMQTTClientID(),
		},
		Sent: DataStats{
			Msgs:  c.inMsgs,
			Bytes: c.inBytes,
		},
		Received: DataStats{
			Msgs:  c.outMsgs,
			Bytes: c.outBytes,
		},
		Reason: AuthenticationViolation.String(),
	}
	c.mu.Unlock()

	s.mu.Lock()
	subj := fmt.Sprintf(authErrorEventSubj, s.info.ID)
	s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
	s.mu.Unlock()
}

// This is the account level event sent to the origin account for account owners.
func (s *Server) sendAccountAuthErrorEvent(c *client, acc *Account, reason string) {
	if acc == nil {
		return
	}
	s.mu.Lock()
	if !s.eventsEnabled() {
		s.mu.Unlock()
		return
	}
	eid := s.nextEventID()
	s.mu.Unlock()

	now := time.Now().UTC()
	c.mu.Lock()
	m := DisconnectEventMsg{
		TypedEvent: TypedEvent{
			Type: DisconnectEventMsgType,
			ID:   eid,
			Time: now,
		},
		Client: ClientInfo{
			Start:      &c.start,
			Stop:       &now,
			Host:       c.host,
			ID:         c.cid,
			Account:    acc.Name,
			User:       c.getRawAuthUser(),
			Name:       c.opts.Name,
			Lang:       c.opts.Lang,
			Version:    c.opts.Version,
			RTT:        c.getRTT(),
			Jwt:        c.opts.JWT,
			IssuerKey:  issuerForClient(c),
			Tags:       c.tags,
			NameTag:    c.nameTag,
			Kind:       c.kindString(),
			ClientType: c.clientTypeString(),
			MQTTClient: c.getMQTTClientID(),
		},
		Sent: DataStats{
			Msgs:  c.inMsgs,
			Bytes: c.inBytes,
		},
		Received: DataStats{
			Msgs:  c.outMsgs,
			Bytes: c.outBytes,
		},
		Reason: reason,
	}
	c.mu.Unlock()

	s.sendInternalAccountSysMsg(acc, authErrorAccountEventSubj, &m.Server, &m)
}

// Internal message callback.
// If the msg is needed past the callback it is required to be copied.
// rmsg contains header and the message. use client.msgParts(rmsg) to split them apart
type msgHandler func(sub *subscription, client *client, acc *Account, subject, reply string, rmsg []byte)

const (
	recvQMuxed  = 1
	recvQStatsz = 2
)

// Create a wrapped callback handler for the subscription that will move it to an
// internal recvQ for processing not inline with routes etc.
func (s *Server) noInlineCallback(cb sysMsgHandler) msgHandler {
	return s.noInlineCallbackRecvQSelect(cb, recvQMuxed)
}

// Create a wrapped callback handler for the subscription that will move it to an
// internal recvQ for Statsz/Pings for processing not inline with routes etc.
func (s *Server) noInlineCallbackStatsz(cb sysMsgHandler) msgHandler {
	return s.noInlineCallbackRecvQSelect(cb, recvQStatsz)
}

// Create a wrapped callback handler for the subscription that will move it to an
// internal IPQueue for processing not inline with routes etc.
func (s *Server) noInlineCallbackRecvQSelect(cb sysMsgHandler, recvQSelect int) msgHandler {
	s.mu.RLock()
	if !s.eventsEnabled() {
		s.mu.RUnlock()
		return nil
	}
	// Capture here for direct reference to avoid any unnecessary blocking inline with routes, gateways etc.
	var recvq *ipQueue[*inSysMsg]
	switch recvQSelect {
	case recvQStatsz:
		recvq = s.sys.recvqp
	default:
		recvq = s.sys.recvq
	}
	s.mu.RUnlock()

	return func(sub *subscription, c *client, acc *Account, subj, rply string, rmsg []byte) {
		// Need to copy and split here.
		hdr, msg := c.msgParts(rmsg)
		recvq.push(&inSysMsg{sub, c, acc, subj, rply, copyBytes(hdr), copyBytes(msg), cb})
	}
}

// Create an internal subscription. sysSubscribeQ for queue groups.
func (s *Server) sysSubscribe(subject string, cb msgHandler) (*subscription, error) {
	return s.systemSubscribe(subject, _EMPTY_, false, nil, cb)
}

// Create an internal subscription with queue
func (s *Server) sysSubscribeQ(subject, queue string, cb msgHandler) (*subscription, error) {
	return s.systemSubscribe(subject, queue, false, nil, cb)
}

// Create an internal subscription but do not forward interest.
func (s *Server) sysSubscribeInternal(subject string, cb msgHandler) (*subscription, error) {
	return s.systemSubscribe(subject, _EMPTY_, true, nil, cb)
}

func (s *Server) systemSubscribe(subject, queue string, internalOnly bool, c *client, cb msgHandler) (*subscription, error) {
	s.mu.Lock()
	if !s.eventsEnabled() {
		s.mu.Unlock()
		return nil, ErrNoSysAccount
	}
	if cb == nil {
		s.mu.Unlock()
		return nil, fmt.Errorf("undefined message handler")
	}
	if c == nil {
		c = s.sys.client
	}
	trace := c.trace
	s.sys.sid++
	sid := strconv.Itoa(s.sys.sid)
	s.mu.Unlock()

	// Now create the subscription
	if trace {
		c.traceInOp("SUB", []byte(subject+" "+queue+" "+sid))
	}

	var q []byte
	if queue != _EMPTY_ {
		q = []byte(queue)
	}

	// Now create the subscription
	return c.processSub([]byte(subject), q, []byte(sid), cb, internalOnly)
}

func (s *Server) sysUnsubscribe(sub *subscription) {
	if sub == nil {
		return
	}
	s.mu.RLock()
	if !s.eventsEnabled() {
		s.mu.RUnlock()
		return
	}
	c := sub.client
	s.mu.RUnlock()

	if c != nil {
		c.processUnsub(sub.sid)
	}
}

// This will generate the tracking subject for remote latency from the response subject.
func remoteLatencySubjectForResponse(subject []byte) string {
	if !isTrackedReply(subject) {
		return ""
	}
	toks := bytes.Split(subject, []byte(tsep))
	// FIXME(dlc) - Sprintf may become a performance concern at some point.
	return fmt.Sprintf(remoteLatencyEventSubj, toks[len(toks)-2])
}

// remoteLatencyUpdate is used to track remote latency measurements for tracking on exported services.
func (s *Server) remoteLatencyUpdate(sub *subscription, _ *client, _ *Account, subject, _ string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}
	var rl remoteLatency
	if err := json.Unmarshal(msg, &rl); err != nil {
		s.Errorf("Error unmarshalling remote latency measurement: %v", err)
		return
	}
	// Now we need to look up the responseServiceImport associated with this measurement.
	acc, err := s.LookupAccount(rl.Account)
	if err != nil {
		s.Warnf("Could not lookup account %q for latency measurement", rl.Account)
		return
	}
	// Now get the request id / reply. We need to see if we have a GW prefix and if so strip that off.
	reply := rl.ReqId
	if gwPrefix, old := isGWRoutedSubjectAndIsOldPrefix([]byte(reply)); gwPrefix {
		reply = string(getSubjectFromGWRoutedReply([]byte(reply), old))
	}
	acc.mu.RLock()
	si := acc.exports.responses[reply]
	if si == nil {
		acc.mu.RUnlock()
		return
	}
	lsub := si.latency.subject
	acc.mu.RUnlock()

	si.acc.mu.Lock()
	m1 := si.m1
	m2 := rl.M2

	// So we have not processed the response tracking measurement yet.
	if m1 == nil {
		// Store our value there for them to pick up.
		si.m1 = &m2
	}
	si.acc.mu.Unlock()

	if m1 == nil {
		return
	}

	// Calculate the correct latencies given M1 and M2.
	m1.merge(&m2)

	// Clear the requesting client since we send the result here.
	acc.mu.Lock()
	si.rc = nil
	acc.mu.Unlock()

	// Make sure we remove the entry here.
	acc.removeServiceImport(si.from)
	// Send the metrics
	s.sendInternalAccountMsg(acc, lsub, m1)
}

// This is used for all inbox replies so that we do not send supercluster wide interest
// updates for every request. Same trick used in modern NATS clients.
func (s *Server) inboxReply(sub *subscription, c *client, acc *Account, subject, reply string, msg []byte) {
	s.mu.RLock()
	if !s.eventsEnabled() || s.sys.replies == nil {
		s.mu.RUnlock()
		return
	}
	cb, ok := s.sys.replies[subject]
	s.mu.RUnlock()

	if ok && cb != nil {
		cb(sub, c, acc, subject, reply, msg)
	}
}

// Copied from go client.
// We could use serviceReply here instead to save some code.
// I prefer these semantics for the moment, when tracing you know what this is.
const (
	InboxPrefix        = "$SYS._INBOX."
	inboxPrefixLen     = len(InboxPrefix)
	respInboxPrefixLen = inboxPrefixLen + sysHashLen + 1
	replySuffixLen     = 8 // Gives us 62^8
)

// Creates an internal inbox used for replies that will be processed by the global wc handler.
func (s *Server) newRespInbox() string {
	var b [respInboxPrefixLen + replySuffixLen]byte
	pres := b[:respInboxPrefixLen]
	copy(pres, s.sys.inboxPre)
	rn := rand.Int63()
	for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
		b[i] = digits[l%base]
		l /= base
	}
	return string(b[:])
}

// accNumSubsReq is sent when we need to gather remote info on subs.
type accNumSubsReq struct {
	Account string `json:"acc"`
	Subject string `json:"subject"`
	Queue   []byte `json:"queue,omitempty"`
}

// helper function to total information from results to count subs.
func totalSubs(rr *SublistResult, qg []byte) (nsubs int32) {
	if rr == nil {
		return
	}
	checkSub := func(sub *subscription) {
		// TODO(dlc) - This could be smarter.
		if qg != nil && !bytes.Equal(qg, sub.queue) {
			return
		}
		if sub.client.kind == CLIENT || sub.client.isHubLeafNode() {
			nsubs++
		}
	}
	if qg == nil {
		for _, sub := range rr.psubs {
			checkSub(sub)
		}
	}
	for _, qsub := range rr.qsubs {
		for _, sub := range qsub {
			checkSub(sub)
		}
	}
	return
}

// Allows users of large systems to debug active subscribers for a given subject.
// Payload should be the subject of interest.
func (s *Server) debugSubscribers(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	// Even though this is an internal only subscription, meaning interest was not forwarded, we could
	// get one here from a GW in optimistic mode. Ignore for now.
	// FIXME(dlc) - Should we send no interest here back to the GW?
	if c.kind != CLIENT {
		return
	}

	var ci ClientInfo
	if len(hdr) > 0 {
		if err := json.Unmarshal(getHeader(ClientInfoHdr, hdr), &ci); err != nil {
			return
		}
	}

	var acc *Account
	if ci.Service != _EMPTY_ {
		acc, _ = s.LookupAccount(ci.Service)
	} else if ci.Account != _EMPTY_ {
		acc, _ = s.LookupAccount(ci.Account)
	} else {
		// Direct $SYS access.
		acc = c.acc
		if acc == nil {
			acc = s.SystemAccount()
		}
	}
	if acc == nil {
		return
	}

	// We could have a single subject or we could have a subject and a wildcard separated by whitespace.
	args := strings.Split(strings.TrimSpace(string(msg)), " ")
	if len(args) == 0 {
		s.sendInternalAccountMsg(acc, reply, 0)
		return
	}

	tsubj := args[0]
	var qgroup []byte
	if len(args) > 1 {
		qgroup = []byte(args[1])
	}

	var nsubs int32

	if subjectIsLiteral(tsubj) {
		// We will look up subscribers locally first then determine if we need to solicit other servers.
		rr := acc.sl.Match(tsubj)
		nsubs = totalSubs(rr, qgroup)
	} else {
		// We have a wildcard, so this is a bit slower path.
		var _subs [32]*subscription
		subs := _subs[:0]
		acc.sl.All(&subs)
		for _, sub := range subs {
			if subjectIsSubsetMatch(string(sub.subject), tsubj) {
				if qgroup != nil && !bytes.Equal(qgroup, sub.queue) {
					continue
				}
				if sub.client.kind == CLIENT || sub.client.isHubLeafNode() {
					nsubs++
				}
			}
		}
	}

	// We should have an idea of how many responses to expect from remote servers.
	var expected = acc.expectedRemoteResponses()

	// If we are only local, go ahead and return.
	if expected == 0 {
		s.sendInternalAccountMsg(nil, reply, nsubs)
		return
	}

	// We need to solicit from others.
	// To track status.
	responses := int32(0)
	done := make(chan (bool))

	s.mu.Lock()
	// Create direct reply inbox that we multiplex under the WC replies.
	replySubj := s.newRespInbox()
	// Store our handler.
	s.sys.replies[replySubj] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) {
		if n, err := strconv.Atoi(string(msg)); err == nil {
			atomic.AddInt32(&nsubs, int32(n))
		}
		if atomic.AddInt32(&responses, 1) >= expected {
			select {
			case done <- true:
			default:
			}
		}
	}
	// Send the request to the other servers.
	request := &accNumSubsReq{
		Account: acc.Name,
		Subject: tsubj,
		Queue:   qgroup,
	}
	s.sendInternalMsg(accNumSubsReqSubj, replySubj, nil, request)
	s.mu.Unlock()

	// FIXME(dlc) - We should rate limit here instead of blind Go routine.
	go func() {
		select {
		case <-done:
		case <-time.After(500 * time.Millisecond):
		}
		// Cleanup the WC entry.
		var sendResponse bool
		s.mu.Lock()
		if s.sys != nil && s.sys.replies != nil {
			delete(s.sys.replies, replySubj)
			sendResponse = true
		}
		s.mu.Unlock()
		if sendResponse {
			// Send the response.
			s.sendInternalAccountMsg(nil, reply, atomic.LoadInt32(&nsubs))
		}
	}()
}

// Request for our local subscription count. This will come from a remote origin server
// that received the initial request.
func (s *Server) nsubsRequest(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}
	m := accNumSubsReq{}
	if len(msg) == 0 {
		s.sys.client.Errorf("request requires a body")
		return
	} else if err := json.Unmarshal(msg, &m); err != nil {
		s.sys.client.Errorf("Error unmarshalling account nsubs request message: %v", err)
		return
	}
	// Grab account.
	acc, _ := s.lookupAccount(m.Account)
	if acc == nil || acc.numLocalAndLeafConnections() == 0 {
		return
	}
	// We will look up subscribers locally first then determine if we need to solicit other servers.
	var nsubs int32
	if subjectIsLiteral(m.Subject) {
		rr := acc.sl.Match(m.Subject)
		nsubs = totalSubs(rr, m.Queue)
	} else {
		// We have a wildcard, so this is a bit slower path.
		var _subs [32]*subscription
		subs := _subs[:0]
		acc.sl.All(&subs)
		for _, sub := range subs {
			if (sub.client.kind == CLIENT || sub.client.isHubLeafNode()) && subjectIsSubsetMatch(string(sub.subject), m.Subject) {
				if m.Queue != nil && !bytes.Equal(m.Queue, sub.queue) {
					continue
				}
				nsubs++
			}
		}
	}
	s.sendInternalMsgLocked(reply, _EMPTY_, nil, nsubs)
}

func (s *Server) reloadConfig(sub *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}

	optz := &EventFilterOptions{}
	s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) {
		// Reload the server config, as requested.
		return nil, s.Reload()
	})
}

type KickClientReq struct {
	CID uint64 `json:"cid"`
}

type LDMClientReq struct {
	CID uint64 `json:"cid"`
}

func (s *Server) kickClient(_ *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}

	var req KickClientReq
	if err := json.Unmarshal(msg, &req); err != nil {
		s.sys.client.Errorf("Error unmarshalling kick client request: %v", err)
		return
	}

	optz := &EventFilterOptions{}
	s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) {
		return nil, s.DisconnectClientByID(req.CID)
	})

}

func (s *Server) ldmClient(_ *subscription, c *client, _ *Account, subject, reply string, hdr, msg []byte) {
	if !s.eventsRunning() {
		return
	}

	var req LDMClientReq
	if err := json.Unmarshal(msg, &req); err != nil {
		s.sys.client.Errorf("Error unmarshalling kick client request: %v", err)
		return
	}

	optz := &EventFilterOptions{}
	s.zReq(c, reply, hdr, msg, optz, optz, func() (any, error) {
		return nil, s.LDMClientByID(req.CID)
	})
}

// Helper to grab account name for a client.
func accForClient(c *client) string {
	if c.acc != nil {
		return c.acc.Name
	}
	return "N/A"
}

// Helper to grab issuer for a client.
func issuerForClient(c *client) (issuerKey string) {
	if c == nil || c.user == nil {
		return
	}
	issuerKey = c.user.SigningKey
	if issuerKey == _EMPTY_ && c.user.Account != nil {
		issuerKey = c.user.Account.Name
	}
	return
}

// Helper to clear timers.
func clearTimer(tp **time.Timer) {
	if t := *tp; t != nil {
		t.Stop()
		*tp = nil
	}
}

// Helper function to wrap functions with common test
// to lock server and return if events not enabled.
func (s *Server) wrapChk(f func()) func() {
	return func() {
		s.mu.Lock()
		if !s.eventsEnabled() {
			s.mu.Unlock()
			return
		}
		f()
		s.mu.Unlock()
	}
}

// sendOCSPPeerRejectEvent sends a system level event to system account when a peer connection is
// rejected due to OCSP invalid status of its trust chain(s).
func (s *Server) sendOCSPPeerRejectEvent(kind string, peer *x509.Certificate, reason string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !s.eventsEnabled() {
		return
	}
	if peer == nil {
		s.Errorf(certidp.ErrPeerEmptyNoEvent)
		return
	}
	eid := s.nextEventID()
	now := time.Now().UTC()
	m := OCSPPeerRejectEventMsg{
		TypedEvent: TypedEvent{
			Type: OCSPPeerRejectEventMsgType,
			ID:   eid,
			Time: now,
		},
		Kind: kind,
		Peer: certidp.CertInfo{
			Subject:     certidp.GetSubjectDNForm(peer),
			Issuer:      certidp.GetIssuerDNForm(peer),
			Fingerprint: certidp.GenerateFingerprint(peer),
			Raw:         peer.Raw,
		},
		Reason: reason,
	}
	subj := fmt.Sprintf(ocspPeerRejectEventSubj, s.info.ID)
	s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
}

// sendOCSPPeerChainlinkInvalidEvent sends a system level event to system account when a link in a peer's trust chain
// is OCSP invalid.
func (s *Server) sendOCSPPeerChainlinkInvalidEvent(peer *x509.Certificate, link *x509.Certificate, reason string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !s.eventsEnabled() {
		return
	}
	if peer == nil || link == nil {
		s.Errorf(certidp.ErrPeerEmptyNoEvent)
		return
	}
	eid := s.nextEventID()
	now := time.Now().UTC()
	m := OCSPPeerChainlinkInvalidEventMsg{
		TypedEvent: TypedEvent{
			Type: OCSPPeerChainlinkInvalidEventMsgType,
			ID:   eid,
			Time: now,
		},
		Link: certidp.CertInfo{
			Subject:     certidp.GetSubjectDNForm(link),
			Issuer:      certidp.GetIssuerDNForm(link),
			Fingerprint: certidp.GenerateFingerprint(link),
			Raw:         link.Raw,
		},
		Peer: certidp.CertInfo{
			Subject:     certidp.GetSubjectDNForm(peer),
			Issuer:      certidp.GetIssuerDNForm(peer),
			Fingerprint: certidp.GenerateFingerprint(peer),
			Raw:         peer.Raw,
		},
		Reason: reason,
	}
	subj := fmt.Sprintf(ocspPeerChainlinkInvalidEventSubj, s.info.ID)
	s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
}