File: LoadBalancer.php

package info (click to toggle)
mediawiki 1%3A1.39.13-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 320,416 kB
  • sloc: php: 815,516; javascript: 601,264; sql: 11,218; python: 4,863; xml: 3,080; sh: 990; ruby: 82; makefile: 78
file content (2529 lines) | stat: -rw-r--r-- 85,146 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
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */
namespace Wikimedia\Rdbms;

use ArrayUtils;
use BagOStuff;
use EmptyBagOStuff;
use InvalidArgumentException;
use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
use LogicException;
use NullStatsdDataFactory;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RuntimeException;
use Throwable;
use UnexpectedValueException;
use WANObjectCache;
use Wikimedia\RequestTimeout\CriticalSectionProvider;
use Wikimedia\ScopedCallback;

/**
 * @see ILoadBalancer
 * @ingroup Database
 */
class LoadBalancer implements ILoadBalancerForOwner {
	/** @var ILoadMonitor */
	private $loadMonitor;
	/** @var CriticalSectionProvider|null */
	private $csProvider;
	/** @var callable|null Callback to run before the first connection attempt */
	private $chronologyCallback;
	/** @var BagOStuff */
	private $srvCache;
	/** @var WANObjectCache */
	private $wanCache;
	/** @var DatabaseFactory */
	private $databaseFactory;
	/**
	 * @var callable|null An optional callback that returns a ScopedCallback instance,
	 * meant to profile the actual query execution in {@see Database::doQuery}
	 */
	private $profiler;
	/** @var TransactionProfiler */
	private $trxProfiler;
	/** @var StatsdDataFactoryInterface */
	private $statsd;
	/** @var LoggerInterface */
	private $connLogger;
	/** @var LoggerInterface */
	private $queryLogger;
	/** @var LoggerInterface */
	private $replLogger;
	/** @var LoggerInterface */
	private $perfLogger;
	/** @var callable Exception logger */
	private $errorLogger;
	/** @var callable Deprecation logger */
	private $deprecationLogger;

	/** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
	private $localDomain;

	/** @var IDatabase[][][] Map of (pool category => server index => domain => Database) */
	private $conns;

	/** @var string|null The name of the DB cluster */
	private $clusterName;
	/** @var array[] Map of (server index => server config array) */
	private $servers;
	/** @var array[] Map of (group => server index => weight) */
	private $groupLoads;
	/** @var int Seconds to spend waiting on replica DB lag to resolve */
	private $waitTimeout;
	/** @var array The LoadMonitor configuration */
	private $loadMonitorConfig;
	/** @var int */
	private $maxLag;
	/** @var string|null Default query group to use with getConnection() */
	private $defaultGroup;

	/** @var bool Whether this PHP instance is for a CLI script */
	private $cliMode;
	/** @var string Agent name for query profiling */
	private $agent;

	/** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
	private $tableAliases = [];
	/** @var string[] Map of (index alias => index) */
	private $indexAliases = [];
	/** @var DatabaseDomain[]|string[] Map of (domain alias => DB domain) */
	private $domainAliases = [];
	/** @var callable[] Map of (name => callable) */
	private $trxRecurringCallbacks = [];
	/** @var bool[] Map of (domain => whether to use "temp tables only" mode) */
	private $tempTablesOnlyMode = [];

	/** @var string|false Explicit DBO_TRX transaction round active or false if none */
	private $trxRoundId = false;
	/** @var string Stage of the current transaction round in the transaction round life-cycle */
	private $trxRoundStage = self::ROUND_CURSORY;
	/** @var Database Connection handle that caused a problem */
	private $errorConnection;
	/** @var int[] The group replica server indexes keyed by group */
	private $readIndexByGroup = [];
	/** @var DBPrimaryPos|false Replication sync position or false if not set */
	private $waitForPos;
	/** @var bool Whether the generic reader fell back to a lagged replica DB */
	private $laggedReplicaMode = false;
	/** @var string The last DB selection or connection error */
	private $lastError = 'Unknown error';
	/** @var string|false Reason this instance is read-only or false if not */
	private $readOnlyReason = false;
	/** @var int Total number of new connections ever made with this instance */
	private $connectionCounter = 0;
	/** @var bool */
	private $disabled = false;
	/** @var bool Whether the session consistency callback already executed */
	private $chronologyCallbackTriggered = false;

	/** @var DatabaseDomain[] Map of (domain ID => domain instance) */
	private $nonLocalDomainCache = [];

	/**
	 * @var int Modification counter for invalidating connections held by
	 *      DBConnRef instances. This is bumped by reconfigure().
	 */
	private $modcount = 0;

	private const INFO_SERVER_INDEX = 'serverIndex';
	private const INFO_AUTOCOMMIT_ONLY = 'autoCommitOnly';
	private const INFO_FORIEGN = 'foreign';
	private const INFO_FOREIGN_REF_COUNT = 'foreignPoolRefCount';

	/**
	 * Default 'maxLag' when unspecified
	 * @internal Only for use within LoadBalancer/LoadMonitor
	 */
	public const MAX_LAG_DEFAULT = 6;

	/** Warn when this many connection are held */
	private const CONN_HELD_WARN_THRESHOLD = 10;

	/** Default 'waitTimeout' when unspecified */
	private const MAX_WAIT_DEFAULT = 10;
	/** Seconds to cache primary DB server read-only status */
	private const TTL_CACHE_READONLY = 5;

	private const KEY_LOCAL = 'local';
	private const KEY_FOREIGN_FREE = 'foreignFree';
	private const KEY_FOREIGN_INUSE = 'foreignInUse';

	private const KEY_LOCAL_NOROUND = 'localAutoCommit';
	private const KEY_FOREIGN_FREE_NOROUND = 'foreignFreeAutoCommit';
	private const KEY_FOREIGN_INUSE_NOROUND = 'foreignInUseAutoCommit';

	private const KEY_LOCAL_DOMAIN = '__local__';

	/** Transaction round, explicit or implicit, has not finished writing */
	private const ROUND_CURSORY = 'cursory';
	/** Transaction round writes are complete and ready for pre-commit checks */
	private const ROUND_FINALIZED = 'finalized';
	/** Transaction round passed final pre-commit checks */
	private const ROUND_APPROVED = 'approved';
	/** Transaction round was committed and post-commit callbacks must be run */
	private const ROUND_COMMIT_CALLBACKS = 'commit-callbacks';
	/** Transaction round was rolled back and post-rollback callbacks must be run */
	private const ROUND_ROLLBACK_CALLBACKS = 'rollback-callbacks';
	/** Transaction round encountered an error */
	private const ROUND_ERROR = 'error';

	/** @var int Idiom for getExistingReaderIndex() meaning "no index selected" */
	private const READER_INDEX_NONE = -1;

	public function __construct( array $params ) {
		$this->configure( $params );

		$this->conns = self::newTrackedConnectionsArray();
	}

	/**
	 * @param array $params A database configuration array, see $wgLBFactoryConf.
	 *
	 * @return void
	 */
	protected function configure( array $params ): void {
		if ( !isset( $params['servers'] ) || !count( $params['servers'] ) ) {
			throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
		}

		$localDomain = isset( $params['localDomain'] )
			? DatabaseDomain::newFromId( $params['localDomain'] )
			: DatabaseDomain::newUnspecified();
		$this->setLocalDomain( $localDomain );

		$this->maxLag = $params['maxLag'] ?? self::MAX_LAG_DEFAULT;

		$listKey = -1;
		$this->servers = [];
		$this->groupLoads = [ self::GROUP_GENERIC => [] ];
		foreach ( $params['servers'] as $i => $server ) {
			if ( ++$listKey !== $i ) {
				throw new UnexpectedValueException( 'List expected for "servers" parameter' );
			}
			$this->servers[ $i ] = $server;
			foreach ( ( $server['groupLoads'] ?? [] ) as $group => $ratio ) {
				$this->groupLoads[ $group ][ $i ] = $ratio;
			}
			$this->groupLoads[ self::GROUP_GENERIC ][ $i ] = $server['load'];
		}

		$this->waitTimeout = $params['waitTimeout'] ?? self::MAX_WAIT_DEFAULT;

		if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
			$this->readOnlyReason = $params['readOnlyReason'];
		}

		$this->loadMonitorConfig = $params['loadMonitor'] ?? [ 'class' => 'LoadMonitorNull' ];
		$this->loadMonitorConfig += [ 'lagWarnThreshold' => $this->maxLag ];

		$this->srvCache = $params['srvCache'] ?? new EmptyBagOStuff();
		$this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
		$this->databaseFactory = $params['databaseFactory'] ?? new DatabaseFactory();
		$this->errorLogger = $params['errorLogger'] ?? static function ( Throwable $e ) {
				trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
		};
		$this->deprecationLogger = $params['deprecationLogger'] ?? static function ( $msg ) {
				trigger_error( $msg, E_USER_DEPRECATED );
		};
		$this->replLogger = $params['replLogger'] ?? new NullLogger();
		$this->connLogger = $params['connLogger'] ?? new NullLogger();
		$this->queryLogger = $params['queryLogger'] ?? new NullLogger();
		$this->perfLogger = $params['perfLogger'] ?? new NullLogger();

		$this->clusterName = $params['clusterName'] ?? null;
		$this->profiler = $params['profiler'] ?? null;
		$this->trxProfiler = $params['trxProfiler'] ?? new TransactionProfiler();
		$this->statsd = $params['statsdDataFactory'] ?? new NullStatsdDataFactory();

		$this->csProvider = $params['criticalSectionProvider'] ?? null;

		$this->cliMode = $params['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
		$this->agent = $params['agent'] ?? '';

		if ( isset( $params['chronologyCallback'] ) ) {
			$this->chronologyCallback = $params['chronologyCallback'];
		}

		if ( isset( $params['roundStage'] ) ) {
			if ( $params['roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) {
				$this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
			} elseif ( $params['roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) {
				$this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
			}
		}

		$group = $params['defaultGroup'] ?? self::GROUP_GENERIC;
		$this->defaultGroup = isset( $this->groupLoads[ $group ] ) ? $group : self::GROUP_GENERIC;
	}

	private static function newTrackedConnectionsArray() {
		return [
			// Connection were transaction rounds may be applied
			self::KEY_LOCAL => [],
			self::KEY_FOREIGN_INUSE => [],
			self::KEY_FOREIGN_FREE => [],
			// Auto-committing counterpart connections that ignore transaction rounds
			self::KEY_LOCAL_NOROUND => [],
			self::KEY_FOREIGN_INUSE_NOROUND => [],
			self::KEY_FOREIGN_FREE_NOROUND => []
		];
	}

	public function getClusterName(): string {
		if ( $this->clusterName !== null ) {
			$name = $this->clusterName;
		} else {
			// Fallback to the current primary name if not specified
			$name = $this->getServerName( $this->getWriterIndex() );
		}

		return $name;
	}

	public function getLocalDomainID(): string {
		return $this->localDomain->getId();
	}

	public function resolveDomainID( $domain ): string {
		return $this->resolveDomainInstance( $domain )->getId();
	}

	/**
	 * @param DatabaseDomain|string|false $domain
	 * @return DatabaseDomain
	 */
	final protected function resolveDomainInstance( $domain ): DatabaseDomain {
		if ( $domain instanceof DatabaseDomain ) {
			return $domain; // already a domain instance
		} elseif ( $domain === false || $domain === $this->localDomain->getId() ) {
			return $this->localDomain;
		} elseif ( isset( $this->domainAliases[$domain] ) ) {
			$this->domainAliases[$domain] =
				DatabaseDomain::newFromId( $this->domainAliases[$domain] );

			return $this->domainAliases[$domain];
		}

		$cachedDomain = $this->nonLocalDomainCache[$domain] ?? null;
		if ( $cachedDomain === null ) {
			$cachedDomain = DatabaseDomain::newFromId( $domain );
			$this->nonLocalDomainCache = [ $domain => $cachedDomain ];
		}

		return $cachedDomain;
	}

	/**
	 * Resolve $groups into a list of query groups defining as having database servers
	 *
	 * @param string[]|string|false $groups Query group(s) in preference order, [], or false
	 * @param int $i Specific server index or DB_PRIMARY/DB_REPLICA
	 * @return string[] Non-empty group list in preference order with the default group appended
	 */
	private function resolveGroups( $groups, $i ) {
		// If a specific replica server was specified, then $groups makes no sense
		if ( $i > 0 && $groups !== [] && $groups !== false ) {
			$list = implode( ', ', (array)$groups );
			throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
		}

		if ( $groups === [] || $groups === false || $groups === $this->defaultGroup ) {
			$resolvedGroups = [ $this->defaultGroup ]; // common case
		} elseif ( is_string( $groups ) && isset( $this->groupLoads[$groups] ) ) {
			$resolvedGroups = [ $groups, $this->defaultGroup ];
		} elseif ( is_array( $groups ) ) {
			$resolvedGroups = $groups;
			if ( !in_array( $this->defaultGroup, $resolvedGroups ) ) {
				$resolvedGroups[] = $this->defaultGroup;
			}
		} else {
			$resolvedGroups = [ $this->defaultGroup ];
		}

		return $resolvedGroups;
	}

	/**
	 * @param int $flags Bitfield of class CONN_* constants
	 * @param int $i Specific server index or DB_PRIMARY/DB_REPLICA
	 * @param string $domain Database domain
	 * @return int Sanitized bitfield
	 */
	private function sanitizeConnectionFlags( $flags, $i, $domain ) {
		// Whether an outside caller is explicitly requesting the primary database server
		if ( $i === self::DB_PRIMARY || $i === $this->getWriterIndex() ) {
			$flags |= self::CONN_INTENT_WRITABLE;
		}

		if ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) {
			// Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
			// resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
			// during larger transactions. This is useful for avoiding lock contention.

			// Primary DB server attributes (should match those of the replica DB servers)
			$attributes = $this->getServerAttributes( $this->getWriterIndex() );
			if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) {
				// The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
				// to use separate connections would just cause self-deadlocks. Note that
				// REPEATABLE-READ staleness is not an issue since DB-level locking means
				// that transactions are Strict Serializable anyway.
				$flags &= ~self::CONN_TRX_AUTOCOMMIT;
				$type = $this->getServerType( $this->getWriterIndex() );
				$this->connLogger->info( __METHOD__ . ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
			} elseif ( isset( $this->tempTablesOnlyMode[$domain] ) ) {
				// T202116: integration tests are active and queries should be all be using
				// temporary clone tables (via prefix). Such tables are not visible across
				// different connections nor can there be REPEATABLE-READ snapshot staleness,
				// so use the same connection for everything.
				$flags &= ~self::CONN_TRX_AUTOCOMMIT;
			}
		}

		return $flags;
	}

	/**
	 * @param IDatabase $conn
	 * @param int $flags
	 * @throws DBUnexpectedError
	 */
	private function enforceConnectionFlags( IDatabase $conn, $flags ) {
		if ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) {
			if ( $conn->trxLevel() ) {
				throw new DBUnexpectedError(
					$conn,
					'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
				);
			}

			$conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
		}
	}

	/**
	 * Get a LoadMonitor instance
	 *
	 * @return ILoadMonitor
	 */
	private function getLoadMonitor() {
		if ( !isset( $this->loadMonitor ) ) {
			$compat = [
				'LoadMonitor' => LoadMonitor::class,
				'LoadMonitorNull' => LoadMonitorNull::class,
				'LoadMonitorMySQL' => LoadMonitorMySQL::class,
			];

			$class = $this->loadMonitorConfig['class'];
			if ( isset( $compat[$class] ) ) {
				$class = $compat[$class];
			}

			$this->loadMonitor = new $class(
				$this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
			$this->loadMonitor->setLogger( $this->replLogger );
			$this->loadMonitor->setStatsdDataFactory( $this->statsd );
		}

		return $this->loadMonitor;
	}

	/**
	 * @param array $loads
	 * @param string $domain Resolved DB domain
	 * @param int|float $maxLag Restrict the maximum allowed lag to this many seconds, or INF for no max
	 * @return int|string|false
	 */
	private function getRandomNonLagged( array $loads, string $domain, $maxLag = INF ) {
		$lags = $this->getLagTimes( $domain );

		# Unset excessively lagged servers
		foreach ( $lags as $i => $lag ) {
			if ( $i !== $this->getWriterIndex() ) {
				# How much lag this server nominally is allowed to have
				$maxServerLag = $this->servers[$i]['max lag'] ?? $this->maxLag; // default
				# Constrain that further by $maxLag argument
				$maxServerLag = min( $maxServerLag, $maxLag );

				$srvName = $this->getServerName( $i );
				if ( $lag === false && !is_infinite( $maxServerLag ) ) {
					$this->replLogger->debug(
						__METHOD__ . ": server {db_server} is not replicating?",
						[ 'db_server' => $srvName ]
					);
					unset( $loads[$i] );
				} elseif ( $lag > $maxServerLag ) {
					$this->replLogger->debug(
						__METHOD__ .
							": server {db_server} has {lag} seconds of lag (>= {maxlag})",
						[ 'db_server' => $srvName, 'lag' => $lag, 'maxlag' => $maxServerLag ]
					);
					unset( $loads[$i] );
				}
			}
		}

		# Find out if all the replica DBs with non-zero load are lagged
		$sum = 0;
		foreach ( $loads as $load ) {
			$sum += $load;
		}
		if ( $sum == 0 ) {
			# No appropriate DB servers except maybe the primary and some replica DBs with zero load
			# Do NOT use the primary DB
			# Instead, this function will return false, triggering read-only mode,
			# and a lagged replica DB will be used instead.
			return false;
		}

		if ( count( $loads ) == 0 ) {
			return false;
		}

		# Return a random representative of the remainder
		return ArrayUtils::pickRandom( $loads );
	}

	/**
	 * Get the server index to use for a specified server index and query group list
	 *
	 * @param int $i Specific server index or DB_PRIMARY/DB_REPLICA
	 * @param string[] $groups Non-empty query group list in preference order
	 * @param string|false $domain
	 * @return int A specific server index (replica DBs are checked for connectivity)
	 */
	private function getConnectionIndex( $i, array $groups, $domain ) {
		if ( $i === self::DB_PRIMARY ) {
			$i = $this->getWriterIndex();
		} elseif ( $i === self::DB_REPLICA ) {
			foreach ( $groups as $group ) {
				$groupIndex = $this->getReaderIndex( $group, $domain );
				if ( $groupIndex !== false ) {
					$i = $groupIndex; // group connection succeeded
					break;
				}
			}
		} elseif ( !isset( $this->servers[$i] ) ) {
			throw new UnexpectedValueException( "Invalid server index index #$i" );
		}

		if ( $i === self::DB_REPLICA ) {
			$this->lastError = 'Unknown error'; // set here in case of worse failure
			$this->lastError = 'No working replica DB server: ' . $this->lastError;
			$this->reportConnectionError();
		}

		return $i;
	}

	public function getReaderIndex( $group = false, $domain = false ) {
		$domain = $this->resolveDomainID( $domain );
		$group = is_string( $group ) ? $group : self::GROUP_GENERIC;

		if ( $this->getServerCount() == 1 ) {
			// Skip the load balancing if there's only one server
			return $this->getWriterIndex();
		}

		$index = $this->getExistingReaderIndex( $group );
		if ( $index !== self::READER_INDEX_NONE ) {
			// A reader index was already selected and "waitForPos" was handled
			return $index;
		}

		// Use the server weight array for this load group
		if ( isset( $this->groupLoads[$group] ) ) {
			$loads = $this->groupLoads[$group];
		} else {
			$this->connLogger->info( __METHOD__ . ": no loads for group $group" );

			return false;
		}

		// Scale the configured load ratios according to each server's load and state
		$this->getLoadMonitor()->scaleLoads( $loads, $domain );

		// Pick a server to use, accounting for weights, load, lag, and "waitForPos"
		$this->lazyLoadReplicationPositions(); // optimizes server candidate selection
		[ $i, $laggedReplicaMode ] = $this->pickReaderIndex( $loads, $domain );
		if ( $i === false ) {
			// DB connection unsuccessful
			return false;
		}

		// If data seen by queries is expected to reflect the transactions committed as of
		// or after a given replication position then wait for the DB to apply those changes
		if ( $this->waitForPos && $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
			// Data will be outdated compared to what was expected
			$laggedReplicaMode = true;
		}

		// Cache the reader index for future DB_REPLICA handles
		$this->setExistingReaderIndex( $group, $i );
		// Record whether the generic reader index is in "lagged replica DB" mode
		if ( $group === self::GROUP_GENERIC && $laggedReplicaMode ) {
			$this->laggedReplicaMode = true;
			$this->replLogger->debug( __METHOD__ . ": setting lagged replica mode" );
		}

		$serverName = $this->getServerName( $i );
		$this->connLogger->debug( __METHOD__ . ": using server $serverName for group '$group'" );

		return $i;
	}

	/**
	 * Get the server index chosen by the load balancer for use with the given query group
	 *
	 * @param string $group Query group; use false for the generic group
	 * @return int Server index or LoadBalancer::READER_INDEX_NONE if none was chosen
	 */
	protected function getExistingReaderIndex( $group ) {
		return $this->readIndexByGroup[$group] ?? self::READER_INDEX_NONE;
	}

	/**
	 * Set the server index chosen by the load balancer for use with the given query group
	 *
	 * @param string $group Query group; use false for the generic group
	 * @param int $index The index of a specific server
	 */
	private function setExistingReaderIndex( $group, $index ) {
		if ( $index < 0 ) {
			throw new UnexpectedValueException( "Cannot set a negative read server index" );
		}
		$this->readIndexByGroup[$group] = $index;
	}

	/**
	 * Pick a server that is reachable, preferably non-lagged, and return its server index
	 *
	 * This will leave the server connection open within the pool for reuse
	 *
	 * @param array $loads List of server weights
	 * @param string $domain Resolved DB domain
	 * @return array (reader index, lagged replica mode) or (false, false) on failure
	 */
	private function pickReaderIndex( array $loads, string $domain ) {
		if ( $loads === [] ) {
			throw new InvalidArgumentException( "Server configuration array is empty" );
		}

		/** @var int|false $i Index of selected server */
		$i = false;
		/** @var bool $laggedReplicaMode Whether server is considered lagged */
		$laggedReplicaMode = false;

		// Quickly look through the available servers for a server that meets criteria...
		$currentLoads = $loads;
		while ( count( $currentLoads ) ) {
			if ( $laggedReplicaMode ) {
				$i = ArrayUtils::pickRandom( $currentLoads );
			} else {
				$i = false;
				if ( $this->waitForPos && $this->waitForPos->asOfTime() ) {
					$this->replLogger->debug( __METHOD__ . ": replication positions detected" );
					// "chronologyCallback" sets "waitForPos" for session consistency.
					// This triggers doWait() after connect, so it's especially good to
					// avoid lagged servers so as to avoid excessive delay in that method.
					$ago = microtime( true ) - $this->waitForPos->asOfTime();
					// Aim for <= 1 second of waiting (being too picky can backfire)
					$i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
				}
				if ( $i === false ) {
					// Any server with less lag than it's 'max lag' param is preferable
					$i = $this->getRandomNonLagged( $currentLoads, $domain );
				}
				if ( $i === false && count( $currentLoads ) ) {
					// All replica DBs lagged. Switch to read-only mode
					$this->replLogger->error(
						__METHOD__ . ": all replica DBs lagged. Switch to read-only mode",
						[ 'db_domain' => $domain ]
					);
					$i = ArrayUtils::pickRandom( $currentLoads );
					$laggedReplicaMode = true;
				}
			}

			if ( $i === false ) {
				// pickRandom() returned false.
				// This is permanent and means the configuration or the load monitor
				// wants us to return false.
				$this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );

				return [ false, false ];
			}

			$serverName = $this->getServerName( $i );
			$this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );

			// Get a connection to this server without triggering complementary connections
			// to other servers (due to things like lag or read-only checks). We want to avoid
			// the risk of overhead and recursion here.
			$conn = $this->getServerConnection( $i, $domain, self::CONN_SILENCE_ERRORS );
			if ( !$conn ) {
				$this->connLogger->warning(
					__METHOD__ . ": failed connecting to $i/{db_domain}",
					[ 'db_domain' => $domain ]
				);
				unset( $currentLoads[$i] ); // avoid this server next iteration
				$i = false;
				continue;
			}

			// Decrement reference counter, we are finished with this connection.
			// It will be incremented for the caller later.
			if ( !$this->localDomain->equals( $domain ) ) {
				$this->reuseConnectionInternal( $conn );
			}

			// Return this server
			break;
		}

		// If all servers were down, quit now
		if ( $currentLoads === [] ) {
			$this->connLogger->error(
				__METHOD__ . ": all servers down",
				[ 'db_domain' => $domain ]
			);
		}

		return [ $i, $laggedReplicaMode ];
	}

	public function waitFor( $pos ) {
		$oldPos = $this->waitForPos;
		try {
			$this->waitForPos = $pos;

			$genericIndex = $this->getExistingReaderIndex( self::GROUP_GENERIC );
			// If a generic reader connection was already established, then wait now.
			// Otherwise, wait until a connection is established in getReaderIndex().
			if ( $genericIndex > $this->getWriterIndex() && !$this->doWait( $genericIndex ) ) {
				$this->laggedReplicaMode = true;
				$this->replLogger->debug( __METHOD__ . ": setting lagged replica mode" );
			}
		} finally {
			// Restore the older position if it was higher since this is used for lag-protection
			$this->setWaitForPositionIfHigher( $oldPos );
		}
	}

	public function waitForAll( $pos, $timeout = null ) {
		$timeout = $timeout ?: $this->waitTimeout;

		$oldPos = $this->waitForPos;
		try {
			$this->waitForPos = $pos;

			$ok = true;
			foreach ( $this->getStreamingReplicaIndexes() as $i ) {
				if ( $this->serverHasLoadInAnyGroup( $i ) ) {
					$start = microtime( true );
					$ok = $this->doWait( $i, $timeout ) && $ok;
					$timeout -= intval( microtime( true ) - $start );
					if ( $timeout <= 0 ) {
						break; // timeout reached
					}
				}
			}

			return $ok;
		} finally {
			// Restore the old position; this is used for throttling, not lag-protection
			$this->waitForPos = $oldPos;
		}
	}

	/**
	 * @param int $i Specific server index
	 * @return bool
	 */
	private function serverHasLoadInAnyGroup( $i ) {
		foreach ( $this->groupLoads as $loadsByIndex ) {
			if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * @param DBPrimaryPos|false $pos
	 */
	private function setWaitForPositionIfHigher( $pos ) {
		if ( !$pos ) {
			return;
		}

		if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) {
			$this->waitForPos = $pos;
		}
	}

	public function getAnyOpenConnection( $i, $flags = 0 ) {
		$i = ( $i === self::DB_PRIMARY ) ? $this->getWriterIndex() : $i;
		// Connection handles required to be in auto-commit mode use a separate connection
		// pool since the main pool is effected by implicit and explicit transaction rounds
		$autoCommitOnly = self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT );

		$conn = false;
		foreach ( $this->conns as $type => $connsByServer ) {
			if ( $i === self::DB_REPLICA ) {
				// Consider all existing connections to any server
				$applicableConnsByServer = $connsByServer;
			} else {
				// Consider all existing connections to a specific server
				$applicableConnsByServer = isset( $connsByServer[$i] )
					? [ $i => $connsByServer[$i] ]
					: [];
			}

			$conn = $this->pickAnyOpenConnection( $applicableConnsByServer, $autoCommitOnly );
			if ( $conn ) {
				$this->connLogger->debug( __METHOD__ . ": found '$type' connection to #$i." );
				break;
			}
		}

		if ( $conn ) {
			$this->enforceConnectionFlags( $conn, $flags );
		}

		return $conn;
	}

	/**
	 * @param Database[][] $connsByServer Map of (server index => array of DB handles)
	 * @param bool $autoCommitOnly Whether to only look for auto-commit connections
	 * @return IDatabase|false An appropriate open connection or false if none found
	 */
	private function pickAnyOpenConnection( array $connsByServer, $autoCommitOnly ) {
		foreach ( $connsByServer as $i => $conns ) {
			foreach ( $conns as $conn ) {
				if ( !$conn->isOpen() ) {
					$this->connLogger->warning(
						__METHOD__ .
						": pooled DB handle for {db_server} (#$i) has no open connection.",
						$this->getConnLogContext( $conn )
					);

					continue; // some sort of error occurred?
				}

				if ( $autoCommitOnly ) {
					// Only accept CONN_TRX_AUTOCOMMIT connections
					if ( !$conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
						// Connection is aware of transaction rounds
						continue;
					}

					if ( $conn->trxLevel() ) {
						// Some sort of bug left a transaction open
						$this->connLogger->warning(
							__METHOD__ .
							": pooled DB handle for {db_server} (#$i) has a pending transaction.",
							$this->getConnLogContext( $conn )
						);

						continue;
					}
				}

				return $conn;
			}
		}

		return false;
	}

	/**
	 * Wait for a given replica DB to catch up to the primary DB pos stored in "waitForPos"
	 *
	 * @param int $index Specific server index
	 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
	 * @return bool
	 */
	private function doWait( $index, $timeout = null ) {
		$timeout = max( 1, intval( $timeout ?: $this->waitTimeout ) );

		// Check if we already know that the DB has reached this point
		$srvName = $this->getServerName( $index );
		$key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $srvName, 'v1' );
		/** @var DBPrimaryPos $knownReachedPos */
		$knownReachedPos = $this->srvCache->get( $key );
		if (
			$knownReachedPos instanceof DBPrimaryPos &&
			$knownReachedPos->hasReached( $this->waitForPos )
		) {
			$this->replLogger->debug(
				__METHOD__ .
				": replica DB {db_server} known to be caught up (pos >= $knownReachedPos).",
				[ 'db_server' => $srvName ]
			);

			return true;
		}

		$close = false; // close the connection afterwards
		$flags = self::CONN_SILENCE_ERRORS;
		// Check if there is an existing connection that can be used
		$conn = $this->getAnyOpenConnection( $index, $flags );
		if ( !$conn ) {
			// Get a connection to this server without triggering complementary connections
			// to other servers (due to things like lag or read-only checks). We want to avoid
			// the risk of overhead and recursion here.
			$conn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
			if ( !$conn ) {
				$this->replLogger->warning(
					__METHOD__ . ': failed to connect to {db_server}',
					[ 'db_server' => $srvName ]
				);

				return false;
			}
			// Avoid connection spam in waitForAll() when connections
			// are made just for the sake of doing this lag check.
			$close = true;
		}

		$this->replLogger->info(
			__METHOD__ .
			': waiting for replica DB {db_server} to catch up...',
			$this->getConnLogContext( $conn )
		);

		$result = $conn->primaryPosWait( $this->waitForPos, $timeout );

		$ok = ( $result !== null && $result != -1 );
		if ( $ok ) {
			// Remember that the DB reached this point
			$this->srvCache->set( $key, $this->waitForPos, BagOStuff::TTL_DAY );
		}

		if ( $close ) {
			$this->closeConnection( $conn );
		}

		return $ok;
	}

	public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
		return $this->getConnectionRef( $i, $groups, $domain, $flags );
	}

	public function getConnectionInternal( $i, $groups = [], $domain = false, $flags = 0 ): IDatabase {
		$domain = $this->resolveDomainID( $domain );
		$groups = $this->resolveGroups( $groups, $i );
		$flags = $this->sanitizeConnectionFlags( $flags, $i, $domain );
		// If given DB_PRIMARY/DB_REPLICA, resolve it to a specific server index. Resolving
		// DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
		// connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
		// The use of getServerConnection() instead of getConnection() avoids infinite loops.
		$serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
		// Get an open connection to that server (might trigger a new connection)
		$conn = $this->getServerConnection( $serverIndex, $domain, $flags );
		// Set primary DB handles as read-only if there is high replication lag
		if (
			$conn &&
			$serverIndex === $this->getWriterIndex() &&
			$this->getLaggedReplicaMode( $domain ) &&
			!is_string( $conn->getLBInfo( $conn::LB_READ_ONLY_REASON ) )
		) {
			$genericIndex = $this->getExistingReaderIndex( self::GROUP_GENERIC );
			$reason = ( $genericIndex !== self::READER_INDEX_NONE )
				? 'The database is read-only until replication lag decreases.'
				: 'The database is read-only until replica database servers becomes reachable.';
			$conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $reason );
		}

		return $conn;
	}

	public function getServerConnection( $i, $domain, $flags = 0 ) {
		// Number of connections made before getting the server index and handle
		$priorConnectionsMade = $this->connectionCounter;
		// Get an open connection to this server (might trigger a new connection)
		$conn = $this->localDomain->equals( $domain )
			? $this->getLocalConnection( $i, $flags )
			: $this->getForeignConnection( $i, $domain, $flags );
		// Throw an error or otherwise bail out if the connection attempt failed
		if ( !( $conn instanceof IDatabase ) ) {
			if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
				$this->reportConnectionError();
			}

			return false;
		}

		// Profile any new connections caused by this method
		if ( $this->connectionCounter > $priorConnectionsMade ) {
			$this->trxProfiler->recordConnection(
				$conn->getServerName(),
				$conn->getDBname(),
				self::fieldHasBit( $flags, self::CONN_INTENT_WRITABLE )
			);
		}

		if ( !$conn->isOpen() ) {
			$this->errorConnection = $conn;
			// Connection was made but later unrecoverably lost for some reason.
			// Do not return a handle that will just throw exceptions on use, but
			// let the calling code, e.g. getReaderIndex(), try another server.
			if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
				$this->reportConnectionError();
			}
			return false;
		}

		// Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
		$this->enforceConnectionFlags( $conn, $flags );
		// Set primary DB handles as read-only if the load balancer is configured as read-only
		// or the primary database server is running in server-side read-only mode. Note that
		// replica DB handles are always read-only via Database::assertIsWritablePrimary().
		// Read-only mode due to replication lag is *avoided* here to avoid recursion.
		if ( $i === $this->getWriterIndex() ) {
			if ( $this->readOnlyReason !== false ) {
				$readOnlyReason = $this->readOnlyReason;
			} elseif ( $this->isPrimaryConnectionReadOnly( $conn, $flags ) ) {
				$readOnlyReason = 'The primary database server is running in read-only mode.';
			} else {
				$readOnlyReason = false;
			}
			$conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $readOnlyReason );
		}

		return $conn;
	}

	public function reuseConnection( IDatabase $conn ) {
		// no-op
	}

	public function reuseConnectionInternal( IDatabase $conn ) {
		$serverIndex = $conn->getLBInfo( self::INFO_SERVER_INDEX );
		$refCount = $conn->getLBInfo( self::INFO_FOREIGN_REF_COUNT );
		if ( $serverIndex === null || $refCount === null ) {
			return; // non-foreign connection; no domain-use tracking to update
		} elseif ( $conn instanceof DBConnRef ) {
			// DBConnRef already handles calling reuseConnection() and only passes the live
			// Database instance to this method. Any caller passing in a DBConnRef is broken.
			$this->connLogger->error(
				__METHOD__ . ": got DBConnRef instance",
				[ 'db_domain' => $conn->getDomainID(), 'exception' => new RuntimeException() ]
			);

			return;
		}

		if ( $this->disabled ) {
			return; // DBConnRef handle probably survived longer than the LoadBalancer
		}

		if ( $conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
			$connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
			$connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
		} else {
			$connFreeKey = self::KEY_FOREIGN_FREE;
			$connInUseKey = self::KEY_FOREIGN_INUSE;
		}

		$domain = $conn->getDomainID();
		$existingDomainConn = $this->conns[$connInUseKey][$serverIndex][$domain] ?? null;
		if ( !$existingDomainConn ) {
			throw new InvalidArgumentException(
				"Connection $serverIndex/$domain not found; it may have already been freed" );
		} elseif ( $existingDomainConn !== $conn ) {
			throw new InvalidArgumentException(
				"Connection $serverIndex/$domain mismatched; it may have already been freed" );
		}

		$existingDomainConn->setLBInfo( self::INFO_FOREIGN_REF_COUNT, --$refCount );
		if ( $refCount <= 0 ) {
			$this->conns[$connFreeKey][$serverIndex][$domain] = $existingDomainConn;
			unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
			if ( !$this->conns[$connInUseKey][$serverIndex] ) {
				unset( $this->conns[$connInUseKey][$serverIndex] ); // clean up
			}
			$this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
		} else {
			$this->connLogger->debug( __METHOD__ .
				": reference count for $serverIndex/$domain reduced to $refCount" );
		}
	}

	public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ): IDatabase {
		if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
			throw new UnexpectedValueException(
				__METHOD__ . ' got CONN_SILENCE_ERRORS; connection is already deferred'
			);
		}

		$domain = $this->resolveDomainID( $domain );
		$role = $this->getRoleFromIndex( $i );

		return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role, $this->modcount );
	}

	public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ): IDatabase {
		wfDeprecated( __METHOD__, '1.38 Use ::getConnectionRef' );
		return $this->getConnectionRef( $i, $groups, $domain, $flags );
	}

	public function getMaintenanceConnectionRef(
		$i,
		$groups = [],
		$domain = false,
		$flags = 0
	): DBConnRef {
		if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
			throw new UnexpectedValueException(
				__METHOD__ . ' CONN_SILENCE_ERRORS is not supported'
			);
		}

		$domain = $this->resolveDomainID( $domain );
		$role = $this->getRoleFromIndex( $i );

		return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role, $this->modcount );
	}

	/**
	 * @param int $i Server index or DB_PRIMARY/DB_REPLICA
	 * @return int One of DB_PRIMARY/DB_REPLICA
	 */
	private function getRoleFromIndex( $i ) {
		return ( $i === self::DB_PRIMARY || $i === $this->getWriterIndex() )
			? self::DB_PRIMARY
			: self::DB_REPLICA;
	}

	/**
	 * Open a connection to a local DB, or return one if it is already open.
	 *
	 * On error, returns false, and the connection which caused the
	 * error will be available via $this->errorConnection.
	 *
	 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
	 *
	 * @param int $i Specific server index
	 * @param int $flags Class CONN_* constant bitfield
	 * @return Database
	 * @throws InvalidArgumentException When the server index is invalid
	 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
	 */
	private function getLocalConnection( $i, $flags = 0 ) {
		$autoCommit = self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT );
		// Connection handles required to be in auto-commit mode use a separate connection
		// pool since the main pool is effected by implicit and explicit transaction rounds
		$connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;

		if ( isset( $this->conns[$connKey][$i][self::KEY_LOCAL_DOMAIN] ) ) {
			$conn = $this->conns[$connKey][$i][self::KEY_LOCAL_DOMAIN];
			$this->connLogger->debug( __METHOD__ . ": reused a connection for $connKey/$i" );
		} else {
			$conn = $this->reallyOpenConnection(
				$i,
				$this->localDomain,
				[ self::INFO_AUTOCOMMIT_ONLY => $autoCommit ]
			);
			if ( $conn->isOpen() ) {
				$this->connLogger->debug( __METHOD__ . ": opened new connection for $connKey/$i" );
				$this->conns[$connKey][$i][self::KEY_LOCAL_DOMAIN] = $conn;
			} else {
				$this->connLogger->warning( __METHOD__ . ": connection error for $connKey/$i" );
				$this->errorConnection = $conn;
				$conn = false;
			}
		}

		// Check to make sure that the right domain is selected
		if (
			$conn instanceof IDatabase &&
			!$this->localDomain->isCompatible( $conn->getDomainID() )
		) {
			throw new UnexpectedValueException(
				"Got connection to '{$conn->getDomainID()}', " .
				"but expected local domain ('{$this->localDomain}')"
			);
		}

		return $conn;
	}

	/**
	 * Open a connection to a foreign DB, or return one if it is already open.
	 *
	 * Increments a reference count on the returned connection which locks the
	 * connection to the requested domain. This reference count can be
	 * decremented by calling reuseConnection().
	 *
	 * If a connection is open to the appropriate server already, but with the wrong
	 * database, it will be switched to the right database and returned, as long as
	 * it has been freed first with reuseConnection().
	 *
	 * On error, returns false, and the connection which caused the
	 * error will be available via $this->errorConnection.
	 *
	 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
	 *
	 * @param int $i Specific server index
	 * @param string $domain Domain ID to open
	 * @param int $flags Class CONN_* constant bitfield
	 * @return Database|false Returns false on connection error
	 * @throws DBError When database selection fails
	 * @throws InvalidArgumentException When the server index is invalid
	 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
	 */
	private function getForeignConnection( $i, $domain, $flags = 0 ) {
		$domainInstance = DatabaseDomain::newFromId( $domain );
		$autoCommit = self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT );
		// Connection handles required to be in auto-commit mode use a separate connection
		// pool since the main pool is effected by implicit and explicit transaction rounds
		if ( $autoCommit ) {
			$connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
			$connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
		} else {
			$connFreeKey = self::KEY_FOREIGN_FREE;
			$connInUseKey = self::KEY_FOREIGN_INUSE;
		}

		/** @var Database $conn */
		$conn = null;

		if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
			// Reuse an in-use connection for the same domain
			$conn = $this->conns[$connInUseKey][$i][$domain];
			$this->connLogger->debug( __METHOD__ . ": reusing connection $connInUseKey/$i/$domain" );
		} elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
			// Reuse a free connection for the same domain
			$conn = $this->conns[$connFreeKey][$i][$domain];
			unset( $this->conns[$connFreeKey][$i][$domain] );
			$this->conns[$connInUseKey][$i][$domain] = $conn;
			$this->connLogger->debug( __METHOD__ . ": reusing free connection $connInUseKey/$i/$domain" );
		} elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
			// Reuse a free connection from another domain if possible
			foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $oldConn ) {
				if ( $domainInstance->getDatabase() !== null ) {
					// Check if changing the database will require a new connection.
					// In that case, leave the connection handle alone and keep looking.
					// This prevents connections from being closed mid-transaction and can
					// also avoid overhead if the same database will later be requested.
					if (
						$oldConn->databasesAreIndependent() &&
						$oldConn->getDBname() !== $domainInstance->getDatabase()
					) {
						continue;
					}
					// Select the new database, schema, and prefix
					$conn = $oldConn;
					$conn->selectDomain( $domainInstance );
				} else {
					// Stay on the current database, but update the schema/prefix
					$conn = $oldConn;
					$conn->dbSchema( $domainInstance->getSchema() );
					$conn->tablePrefix( $domainInstance->getTablePrefix() );
				}
				unset( $this->conns[$connFreeKey][$i][$oldDomain] );
				// Note that if $domain is an empty string, getDomainID() might not match it
				$this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
				$this->connLogger->debug( __METHOD__ .
					": reusing free connection from $oldDomain for $domain" );
				break;
			}
		}

		if ( !$conn ) {
			$conn = $this->reallyOpenConnection(
				$i,
				$domainInstance,
				[
					self::INFO_AUTOCOMMIT_ONLY => $autoCommit,
					self::INFO_FORIEGN => true,
					self::INFO_FOREIGN_REF_COUNT => 0
				]
			);
			if ( $conn->isOpen() ) {
				// Note that if $domain is an empty string, getDomainID() might not match it
				$this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
				$this->connLogger->debug( __METHOD__ . ": opened new connection for $connInUseKey/$i/$domain" );
			} else {
				$this->connLogger->warning(
					__METHOD__ . ": connection error for $connInUseKey/$i/{db_domain}",
					[ 'db_domain' => $domain ]
				);
				$this->errorConnection = $conn;
				$conn = false;
			}
		}

		if ( $conn instanceof IDatabase ) {
			// Check to make sure that the right domain is selected
			if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
				throw new UnexpectedValueException(
					"Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
			}
			// Increment reference count
			$refCount = $conn->getLBInfo( self::INFO_FOREIGN_REF_COUNT );
			$conn->setLBInfo( self::INFO_FOREIGN_REF_COUNT, $refCount + 1 );
		}

		return $conn;
	}

	public function getServerAttributes( $i ) {
		return $this->databaseFactory->attributesFromType(
			$this->getServerType( $i ),
			$this->servers[$i]['driver'] ?? null
		);
	}

	/**
	 * Test if the specified index represents an open connection
	 *
	 * @param int $index Server index
	 * @return bool
	 */
	private function isOpen( $index ) {
		return (bool)$this->getAnyOpenConnection( $index );
	}

	/**
	 * Open a new network connection to a server (uncached)
	 *
	 * Returns a Database object whether or not the connection was successful.
	 *
	 * @param int $i Specific server index
	 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
	 * @param array $lbInfo Additional information for setLBInfo()
	 * @return IDatabase
	 * @throws DBAccessError
	 * @throws InvalidArgumentException
	 */
	protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo ) {
		if ( $this->disabled ) {
			throw new DBAccessError();
		}

		$server = $this->getServerInfoStrict( $i );

		$conn = $this->databaseFactory->create(
			$server['type'],
			array_merge( $server, [
				// Basic replication role information
				'topologyRole' => $this->getTopologyRole( $i, $server ),
				// Use the database specified in $domain (null means "none or entrypoint DB");
				// fallback to the $server default if the RDBMs is an embedded library using a
				// file on disk since there would be nothing to access to without a DB/file name.
				'dbname' => $this->getServerAttributes( $i )[Database::ATTR_DB_IS_FILE]
					? ( $domain->getDatabase() ?? $server['dbname'] ?? null )
					: $domain->getDatabase(),
				// Override the $server default schema with that of $domain if specified
				'schema' => $domain->getSchema() ?? $server['schema'] ?? null,
				// Use the table prefix specified in $domain
				'tablePrefix' => $domain->getTablePrefix(),
				// Participate in transaction rounds if $server does not specify otherwise
				'flags' => $this->initConnFlags( $server['flags'] ?? IDatabase::DBO_DEFAULT ),
				// Inject the PHP execution mode and the agent string
				'cliMode' => $this->cliMode,
				'agent' => $this->agent,
				// Inject object and callback dependencies
				'topologicalPrimaryConnRef' => $this->getConnectionRef(
					self::DB_PRIMARY,
					[],
					$domain->getId()
				),
				'srvCache' => $this->srvCache,
				'connLogger' => $this->connLogger,
				'queryLogger' => $this->queryLogger,
				'replLogger' => $this->replLogger,
				'errorLogger' => $this->errorLogger,
				'deprecationLogger' => $this->deprecationLogger,
				'profiler' => $this->profiler,
				'trxProfiler' => $this->trxProfiler,
				'criticalSectionProvider' => $this->csProvider
			] ),
			Database::NEW_UNCONNECTED
		);
		// Attach load balancer information to the handle
		$conn->setLBInfo( [ self::INFO_SERVER_INDEX => $i ] + $lbInfo );
		// Set alternative table/index names before any queries can be issued
		$conn->setTableAliases( $this->tableAliases );
		$conn->setIndexAliases( $this->indexAliases );
		// Account for any active transaction round and listeners
		if ( $i === $this->getWriterIndex() ) {
			if ( $this->trxRoundId !== false ) {
				$this->applyTransactionRoundFlags( $conn );
			}
			foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
				$conn->setTransactionListener( $name, $callback );
			}
		}

		// Make the connection handle live
		try {
			$conn->initConnection();
			++$this->connectionCounter;
		} catch ( DBConnectionError $e ) {
			// ignore; let the DB handle the logging
		}

		// Try to maintain session consistency for clients that trigger write transactions
		// in a request or script and then return soon after in another request or script.
		// This requires cooperation with ChronologyProtector and the application wiring.
		if ( $conn->isOpen() ) {
			$this->lazyLoadReplicationPositions();
		}

		// Log when many connection are made during a single request/script
		$count = $this->getCurrentConnectionCount();
		if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) {
			$this->perfLogger->warning(
				__METHOD__ . ": {connections}+ connections made (primary={primarydb})",
				$this->getConnLogContext(
					$conn,
					[
						'connections' => $count,
						'primarydb' => $this->getPrimaryServerName(),
						'db_domain' => $domain->getId()
					]
				)
			);
		}

		return $conn;
	}

	/**
	 * @param int $i Specific server index
	 * @param array $server Server config map
	 * @return string IDatabase::ROLE_* constant
	 */
	private function getTopologyRole( $i, array $server ) {
		if ( !empty( $server['is static'] ) ) {
			return IDatabase::ROLE_STATIC_CLONE;
		}

		return ( $i === $this->getWriterIndex() )
			? IDatabase::ROLE_STREAMING_MASTER
			: IDatabase::ROLE_STREAMING_REPLICA;
	}

	/**
	 * @see IDatabase::DBO_DEFAULT
	 * @param int $flags Bit field of IDatabase::DBO_* constants from configuration
	 * @return int Bit field of IDatabase::DBO_* constants to use with Database::factory()
	 */
	private function initConnFlags( $flags ) {
		if ( self::fieldHasBit( $flags, IDatabase::DBO_DEFAULT ) ) {
			if ( $this->cliMode ) {
				$flags &= ~IDatabase::DBO_TRX;
			} else {
				$flags |= IDatabase::DBO_TRX;
			}
		}

		return $flags;
	}

	/**
	 * Make sure that any "waitForPos" positions are loaded and available to doWait()
	 */
	private function lazyLoadReplicationPositions() {
		if ( !$this->chronologyCallbackTriggered && $this->chronologyCallback ) {
			$this->chronologyCallbackTriggered = true;
			( $this->chronologyCallback )( $this ); // generally calls waitFor()
			$this->connLogger->debug( __METHOD__ . ': executed chronology callback.' );
		}
	}

	/**
	 * @throws DBConnectionError
	 * @return never
	 */
	private function reportConnectionError() {
		$conn = $this->errorConnection; // the connection which caused the error
		$context = [
			'method' => __METHOD__,
			'last_error' => $this->lastError,
		];

		if ( $conn instanceof IDatabase ) {
			$srvName = $conn->getServerName();
			$this->connLogger->warning(
				__METHOD__ . ": connection error: {last_error} ({db_server})",
				$this->getConnLogContext( $conn, $context )
			);
			$error = $conn->lastError() ?: $this->lastError;
			throw new DBConnectionError( $conn, "{$error} ($srvName)" );
		} else {
			// No last connection, probably due to all servers being too busy
			$this->connLogger->error(
				__METHOD__ .
				": LB failure with no last connection. Connection error: {last_error}",
				$context
			);

			// If all servers were busy, "lastError" will contain something sensible
			throw new DBConnectionError( null, $this->lastError );
		}
	}

	public function getWriterIndex() {
		return 0;
	}

	/**
	 * Returns true if the specified index is a valid server index
	 *
	 * @param int $i
	 * @return bool
	 * @deprecated Since 1.34
	 */
	public function haveIndex( $i ) {
		return array_key_exists( $i, $this->servers );
	}

	/**
	 * Returns true if the specified index is valid and has non-zero load
	 *
	 * @param int $i
	 * @return bool
	 * @deprecated Since 1.34
	 */
	public function isNonZeroLoad( $i ) {
		return ( isset( $this->servers[$i] ) && $this->groupLoads[self::GROUP_GENERIC][$i] > 0 );
	}

	public function getServerCount() {
		return count( $this->servers );
	}

	public function hasReplicaServers() {
		return ( $this->getServerCount() > 1 );
	}

	/**
	 * @return int[] List of replica server indexes
	 */
	private function getStreamingReplicaIndexes() {
		$indexes = [];
		foreach ( $this->servers as $i => $server ) {
			if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
				$indexes[] = $i;
			}
		}

		return $indexes;
	}

	public function hasStreamingReplicaServers() {
		return (bool)$this->getStreamingReplicaIndexes();
	}

	public function getServerName( $i ): string {
		$name = $this->servers[$i]['serverName'] ?? ( $this->servers[$i]['host'] ?? '' );

		return ( $name !== '' ) ? $name : 'localhost';
	}

	public function getServerInfo( $i ) {
		return $this->servers[$i] ?? false;
	}

	public function getServerType( $i ) {
		return $this->servers[$i]['type'] ?? 'unknown';
	}

	public function getPrimaryPos() {
		$index = $this->getWriterIndex();

		$conn = $this->getAnyOpenConnection( $index );
		if ( $conn ) {
			return $conn->getPrimaryPos();
		}

		$conn = $this->getConnectionInternal( $index, self::CONN_SILENCE_ERRORS );
		// @phan-suppress-next-line PhanRedundantCondition
		if ( !$conn ) {
			$this->reportConnectionError();
		}

		try {
			return $conn->getPrimaryPos();
		} finally {
			$this->closeConnection( $conn );
		}
	}

	public function getReplicaResumePos() {
		// Get the position of any existing primary DB server connection
		$primaryConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
		if ( $primaryConn ) {
			return $primaryConn->getPrimaryPos();
		}

		// Get the highest position of any existing replica server connection
		$highestPos = false;
		foreach ( $this->getStreamingReplicaIndexes() as $i ) {
			$conn = $this->getAnyOpenConnection( $i );
			$pos = $conn ? $conn->getReplicaPos() : false;
			if ( !$pos ) {
				continue; // no open connection or could not get position
			}

			$highestPos = $highestPos ?: $pos;
			if ( $pos->hasReached( $highestPos ) ) {
				$highestPos = $pos;
			}
		}

		return $highestPos;
	}

	/**
	 * Apply updated configuration.
	 *
	 * This invalidates any open connections. However, existing connections may continue to be
	 * used while they are in an active transaction. In that case, the old connection will be
	 * discarded on the first operation after the transaction is complete. The next operation
	 * will use a new connection based on the new configuration.
	 *
	 * @internal for use by LBFactory::reconfigure()
	 *
	 * @see DBConnRef::ensureConnection()
	 * @see LBFactory::reconfigure()
	 *
	 * @param array $params A database configuration array, see $wgLBFactoryConf.
	 *
	 * @return void
	 */
	public function reconfigure( array $params ) {
		// NOTE: We could close all connection here, but some may be in the middle of
		//       a transaction. So instead, we leave it to DBConnRef to close the
		//       connection when it detects that the modcount has changed and no
		//       transaction is open.

		$this->configure( $params );

		// Bump modification counter to invalidate the connections held by DBConnRef
		// instances. This will cause the next call to a method on the DBConnRef
		// to get a new connection from getConnectionInternal()
		$this->modcount++;
	}

	public function disable( $fname = __METHOD__ ) {
		$this->closeAll( $fname );
		$this->disabled = true;
	}

	public function closeAll( $fname = __METHOD__ ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();
		foreach ( $this->getOpenConnections() as $conn ) {
			$srvName = $conn->getServerName();
			$conn->close( $fname );
		}

		$this->conns = self::newTrackedConnectionsArray();
	}

	public function closeConnection( IDatabase $conn ) {
		if ( $conn instanceof DBConnRef ) {
			// Avoid calling close() but still leaving the handle in the pool
			throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
		}

		$serverIndex = $conn->getLBInfo( self::INFO_SERVER_INDEX );
		if ( $serverIndex === null ) {
			throw new RuntimeException( 'Database handle is missing server index' );
		}

		$srvName = $this->getServerName( $serverIndex );
		$domain = $conn->getDomainID();

		$found = false;
		foreach ( $this->conns as $type => $connsByServer ) {
			$key = array_search( $conn, $connsByServer[$serverIndex] ?? [], true );
			if ( $key !== false ) {
				$found = true;
				unset( $this->conns[$type][$serverIndex][$key] );
			}
		}

		if ( !$found ) {
			$this->connLogger->warning(
				__METHOD__ .
				": got orphaned connection to database $serverIndex/$domain at '$srvName'."
			);
		}

		$this->connLogger->debug(
			__METHOD__ .
			": closing connection to database $serverIndex/$domain at '$srvName'."
		);

		$conn->close( __METHOD__ );
	}

	public function commitAll( $fname = __METHOD__ ) {
		$this->commitPrimaryChanges( $fname );
		$this->flushPrimarySnapshots( $fname );
		$this->flushReplicaSnapshots( $fname );
	}

	public function finalizePrimaryChanges( $fname = __METHOD__ ) {
		$this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
		// Loop until callbacks stop adding callbacks on other connections
		$total = 0;
		do {
			$count = 0; // callbacks execution attempts
			foreach ( $this->getOpenPrimaryConnections() as $conn ) {
				// Run any pre-commit callbacks while leaving the post-commit ones suppressed.
				// Any error should cause all (peer) transactions to be rolled back together.
				$count += $conn->runOnTransactionPreCommitCallbacks();
			}
			$total += $count;
		} while ( $count > 0 );
		// Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->setTrxEndCallbackSuppression( true );
		}
		$this->trxRoundStage = self::ROUND_FINALIZED;

		return $total;
	}

	public function approvePrimaryChanges( array $options, $fname = __METHOD__ ) {
		$this->assertTransactionRoundStage( self::ROUND_FINALIZED );
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		$limit = $options['maxWriteDuration'] ?? 0;

		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			// Any atomic sections should have been closed by now and there definitely should
			// not be any open transactions started by begin() from callers outside Database.
			if ( $conn->explicitTrxActive() ) {
				throw new DBTransactionError(
					$conn,
					"Explicit transaction still active; a caller might have failed to call " .
					"endAtomic() or cancelAtomic()."
				);
			}
			// Assert that the time to replicate the transaction will be reasonable.
			// If this fails, then all DB transactions will be rollback back together.
			$time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
			if ( $limit > 0 ) {
				if ( $time > $limit ) {
					$humanTimeSec = round( $time, 3 );
					throw new DBTransactionSizeError(
						$conn,
						"Transaction spent {time}s in writes, exceeding the {$limit}s limit",
						// Message parameters for: transaction-duration-limit-exceeded
						[ $time, $limit ],
						null,
						[ 'time' => $humanTimeSec ]
					);
				} elseif ( $time > 0 ) {
					$timeMs = $time * 1000;
					$humanTimeMs = $timeMs > 1 ? round( $timeMs ) : round( $timeMs, 3 );
					$this->perfLogger->debug(
						"Transaction spent {time_ms}ms in writes, under the {$limit}s limit",
						[ 'time_ms' => $humanTimeMs ]
					);
				}
			}
			// If a connection sits idle for too long it might be dropped, causing transaction
			// writes and session locks to be lost. Ping all the server connections before making
			// any attempt to commit the transactions belonging to the active transaction round.
			if ( $conn->writesOrCallbacksPending() || $conn->sessionLocksPending() ) {
				if ( !$conn->ping() ) {
					throw new DBTransactionError(
						$conn,
						"Pre-commit ping failed on server {$conn->getServerName()}"
					);
				}
			}
		}
		$this->trxRoundStage = self::ROUND_APPROVED;
	}

	public function beginPrimaryChanges( $fname = __METHOD__ ) {
		if ( $this->trxRoundId !== false ) {
			throw new DBTransactionError(
				null,
				"Transaction round '{$this->trxRoundId}' already started"
			);
		}
		$this->assertTransactionRoundStage( self::ROUND_CURSORY );
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		// Clear any empty transactions (no writes/callbacks) from the implicit round
		$this->flushPrimarySnapshots( $fname );

		$this->trxRoundId = $fname;
		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
		// Mark applicable handles as participating in this explicit transaction round.
		// For each of these handles, any writes and callbacks will be tied to a single
		// transaction. The (peer) handles will reject begin()/commit() calls unless they
		// are part of an en masse commit or an en masse rollback.
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$this->applyTransactionRoundFlags( $conn );
		}
		$this->trxRoundStage = self::ROUND_CURSORY;
	}

	public function commitPrimaryChanges( $fname = __METHOD__ ) {
		$this->assertTransactionRoundStage( self::ROUND_APPROVED );
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		$failures = [];

		$restore = ( $this->trxRoundId !== false );
		$this->trxRoundId = false;
		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
		// Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
		// Note that callbacks should already be suppressed due to finalizePrimaryChanges().
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			try {
				$conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
			} catch ( DBError $e ) {
				( $this->errorLogger )( $e );
				$failures[] = "{$conn->getServerName()}: {$e->getMessage()}";
			}
		}
		if ( $failures ) {
			throw new DBTransactionError(
				null,
				"Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
			);
		}
		if ( $restore ) {
			// Unmark handles as participating in this explicit transaction round
			foreach ( $this->getOpenPrimaryConnections() as $conn ) {
				$this->undoTransactionRoundFlags( $conn );
			}
		}
		$this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
	}

	public function runPrimaryTransactionIdleCallbacks( $fname = __METHOD__ ) {
		if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
			$type = IDatabase::TRIGGER_COMMIT;
		} elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
			$type = IDatabase::TRIGGER_ROLLBACK;
		} else {
			throw new DBTransactionError(
				null,
				"Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
			);
		}
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		$oldStage = $this->trxRoundStage;
		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise

		// Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->setTrxEndCallbackSuppression( false );
		}

		$errors = [];
		$fname = __METHOD__;
		// Loop until callbacks stop adding callbacks on other connections
		do {
			// Run any pending callbacks for each connection...
			$count = 0; // callback execution attempts
			foreach ( $this->getOpenPrimaryConnections() as $conn ) {
				if ( $conn->trxLevel() ) {
					continue; // retry in the next iteration, after commit() is called
				}
				$count += $conn->runOnTransactionIdleCallbacks( $type, $errors );
			}
			// Clear out any active transactions left over from callbacks...
			foreach ( $this->getOpenPrimaryConnections() as $conn ) {
				if ( $conn->writesPending() ) {
					// A callback from another handle wrote to this one and DBO_TRX is set
					$this->queryLogger->warning( $fname . ": found writes pending." );
					$fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
					$this->queryLogger->warning(
						"$fname: found writes pending ($fnames).",
						$this->getConnLogContext(
							$conn,
							[ 'exception' => new RuntimeException() ]
						)
					);
				} elseif ( $conn->trxLevel() ) {
					// A callback from another handle read from this one and DBO_TRX is set,
					// which can easily happen if there is only one DB (no replicas)
					$this->queryLogger->debug( "$fname: found empty transaction." );
				}
				try {
					$conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
				} catch ( DBError $ex ) {
					$errors[] = $ex;
				}
			}
		} while ( $count > 0 );

		$this->trxRoundStage = $oldStage;

		return $errors ? $errors[0] : null;
	}

	public function runPrimaryTransactionListenerCallbacks( $fname = __METHOD__ ) {
		if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
			$type = IDatabase::TRIGGER_COMMIT;
		} elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
			$type = IDatabase::TRIGGER_ROLLBACK;
		} else {
			throw new DBTransactionError(
				null,
				"Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
			);
		}
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		$errors = [];
		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->runTransactionListenerCallbacks( $type, $errors );
		}
		$this->trxRoundStage = self::ROUND_CURSORY;

		return $errors ? $errors[0] : null;
	}

	public function rollbackPrimaryChanges( $fname = __METHOD__ ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scope = ScopedCallback::newScopedIgnoreUserAbort();

		$restore = ( $this->trxRoundId !== false );
		$this->trxRoundId = false;
		$this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
		}
		if ( $restore ) {
			// Unmark handles as participating in this explicit transaction round
			foreach ( $this->getOpenPrimaryConnections() as $conn ) {
				$this->undoTransactionRoundFlags( $conn );
			}
		}
		$this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
	}

	public function flushPrimarySessions( $fname = __METHOD__ ) {
		$this->assertTransactionRoundStage( [ self::ROUND_CURSORY ] );
		if ( $this->hasPrimaryChanges() ) {
			// Any transaction should have been rolled back beforehand
			throw new DBTransactionError( null, "Cannot reset session while writes are pending" );
		}

		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->flushSession( $fname, $conn::FLUSHING_ALL_PEERS );
		}
	}

	/**
	 * @param string|string[] $stage
	 * @throws DBTransactionError
	 */
	private function assertTransactionRoundStage( $stage ) {
		$stages = (array)$stage;

		if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
			$stageList = implode(
				'/',
				array_map( static function ( $v ) {
					return "'$v'";
				}, $stages )
			);
			throw new DBTransactionError(
				null,
				"Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
			);
		}
	}

	/**
	 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
	 *
	 * Some servers may have neither flag enabled, meaning that they opt out of such
	 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
	 * when a DB server is used for something like simple key/value storage.
	 *
	 * @param Database $conn
	 */
	private function applyTransactionRoundFlags( Database $conn ) {
		if ( $conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
			return; // transaction rounds do not apply to these connections
		}

		if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
			// DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
			// Force DBO_TRX even in CLI mode since a commit round is expected soon.
			$conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
		}

		if ( $conn->getFlag( $conn::DBO_TRX ) ) {
			$conn->setLBInfo( $conn::LB_TRX_ROUND_ID, $this->trxRoundId );
		}
	}

	/**
	 * @param Database $conn
	 */
	private function undoTransactionRoundFlags( Database $conn ) {
		if ( $conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
			return; // transaction rounds do not apply to these connections
		}

		if ( $conn->getFlag( $conn::DBO_TRX ) ) {
			$conn->setLBInfo( $conn::LB_TRX_ROUND_ID, null ); // remove the round ID
		}

		if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
			$conn->restoreFlags( $conn::RESTORE_PRIOR );
		}
	}

	public function flushReplicaSnapshots( $fname = __METHOD__ ) {
		foreach ( $this->getOpenReplicaConnections() as $conn ) {
			$conn->flushSnapshot( $fname );
		}
	}

	public function flushPrimarySnapshots( $fname = __METHOD__ ) {
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->flushSnapshot( $fname );
		}
	}

	/**
	 * @return string
	 * @since 1.32
	 */
	public function getTransactionRoundStage() {
		return $this->trxRoundStage;
	}

	public function hasPrimaryConnection() {
		return $this->isOpen( $this->getWriterIndex() );
	}

	public function hasPrimaryChanges() {
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			if ( $conn->writesOrCallbacksPending() ) {
				return true;
			}
		}

		return false;
	}

	public function lastPrimaryChangeTimestamp() {
		$lastTime = false;
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$lastTime = max( $lastTime, $conn->lastDoneWrites() );
		}

		return $lastTime;
	}

	public function hasOrMadeRecentPrimaryChanges( $age = null ) {
		$age = $age ?? $this->waitTimeout;

		return ( $this->hasPrimaryChanges()
			|| $this->lastPrimaryChangeTimestamp() > microtime( true ) - $age );
	}

	public function pendingPrimaryChangeCallers() {
		$fnames = [];
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
		}

		return $fnames;
	}

	public function explicitTrxActive() {
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			if ( $conn->explicitTrxActive() ) {
				return true;
			}
		}
		return false;
	}

	public function getLaggedReplicaMode( $domain = false ) {
		$domain = $this->resolveDomainID( $domain );

		if ( $this->laggedReplicaMode ) {
			// Stay in lagged replica mode once it is observed on any domain
			return true;
		}

		if ( $this->hasStreamingReplicaServers() ) {
			// This will set "laggedReplicaMode" as needed
			$this->getReaderIndex( self::GROUP_GENERIC, $domain );
		}

		return $this->laggedReplicaMode;
	}

	public function laggedReplicaUsed() {
		return $this->laggedReplicaMode;
	}

	public function getReadOnlyReason( $domain = false ) {
		$domainInstance = DatabaseDomain::newFromId( $this->resolveDomainID( $domain ) );

		if ( $this->readOnlyReason !== false ) {
			return $this->readOnlyReason;
		} elseif ( $this->isPrimaryRunningReadOnly( $domainInstance ) ) {
			return 'The primary database server is running in read-only mode.';
		} elseif ( $this->getLaggedReplicaMode( $domain ) ) {
			$genericIndex = $this->getExistingReaderIndex( self::GROUP_GENERIC );

			return ( $genericIndex !== self::READER_INDEX_NONE )
				? 'The database is read-only until replication lag decreases.'
				: 'The database is read-only until a replica database server becomes reachable.';
		}

		return false;
	}

	/**
	 * @note This method suppresses DBError exceptions in order to avoid severe downtime
	 * @param IDatabase $conn Primary connection
	 * @param int $flags Bitfield of class CONN_* constants
	 * @return bool Whether the entire server or currently selected DB/schema is read-only
	 */
	private function isPrimaryConnectionReadOnly( IDatabase $conn, $flags = 0 ) {
		// Note that table prefixes are not related to server-side read-only mode
		$key = $this->srvCache->makeGlobalKey(
			'rdbms-server-readonly',
			$conn->getServerName(),
			(string)$conn->getDBname(),
			(string)$conn->dbSchema()
		);

		if ( self::fieldHasBit( $flags, self::CONN_REFRESH_READ_ONLY ) ) {
			// Refresh the local server cache. This is useful when the caller is
			// currently in the process of updating a corresponding WANCache key.
			try {
				$readOnly = (int)$conn->serverIsReadOnly();
			} catch ( DBError $e ) {
				$readOnly = 0;
			}
			$this->srvCache->set( $key, $readOnly, BagOStuff::TTL_PROC_SHORT );
		} else {
			$readOnly = $this->srvCache->getWithSetCallback(
				$key,
				BagOStuff::TTL_PROC_SHORT,
				static function () use ( $conn ) {
					try {
						$readOnly = (int)$conn->serverIsReadOnly();
					} catch ( DBError $e ) {
						$readOnly = 0;
					}

					return $readOnly;
				}
			);
		}

		return (bool)$readOnly;
	}

	/**
	 * @note This method suppresses DBError exceptions in order to avoid severe downtime
	 * @param DatabaseDomain $domain
	 * @return bool Whether the entire primary DB server or the local domain DB is read-only
	 */
	private function isPrimaryRunningReadOnly( DatabaseDomain $domain ) {
		// Context will often be HTTP GET/HEAD; heavily cache the results
		return (bool)$this->wanCache->getWithSetCallback(
			// Note that table prefixes are not related to server-side read-only mode
			$this->wanCache->makeGlobalKey(
				'rdbms-server-readonly',
				$this->getPrimaryServerName(),
				$domain->getDatabase(),
				(string)$domain->getSchema()
			),
			self::TTL_CACHE_READONLY,
			function () use ( $domain ) {
				$scope = $this->trxProfiler->silenceForScope();

				$index = $this->getWriterIndex();
				// Refresh the local server cache as well. This is done in order to avoid
				// backfilling the WANCache with data that is already significantly stale
				$flags = self::CONN_SILENCE_ERRORS | self::CONN_REFRESH_READ_ONLY;
				$conn = $this->getServerConnection( $index, $domain->getId(), $flags );
				if ( $conn ) {
					try {
						$readOnly = (int)$this->isPrimaryConnectionReadOnly( $conn );
					} catch ( DBError $e ) {
						$readOnly = 0;
					}
					$this->reuseConnectionInternal( $conn );
				} else {
					$readOnly = 0;
				}

				ScopedCallback::consume( $scope );

				return $readOnly;
			},
			[
				'busyValue' => 0,
				'pcTTL' => WANObjectCache::TTL_PROC_LONG
			]
		);
	}

	public function pingAll() {
		$success = true;
		foreach ( $this->getOpenConnections() as $conn ) {
			if ( !$conn->ping() ) {
				$success = false;
			}
		}

		return $success;
	}

	public function forEachOpenConnection( $callback, array $params = [] ) {
		wfDeprecated( __METHOD__, '1.39' );
		foreach ( $this->getOpenConnections() as $conn ) {
			$callback( $conn, ...$params );
		}
	}

	public function forEachOpenPrimaryConnection( $callback, array $params = [] ) {
		wfDeprecated( __METHOD__, '1.39' );
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$callback( $conn, ...$params );
		}
	}

	/**
	 * Get all open connections
	 * @return \Generator|Database[]
	 */
	private function getOpenConnections() {
		foreach ( $this->conns as $connsByServer ) {
			foreach ( $connsByServer as $serverConns ) {
				foreach ( $serverConns as $conn ) {
					yield $conn;
				}
			}
		}
	}

	/**
	 * Get all open primary connections
	 * @return \Generator|Database[]
	 */
	private function getOpenPrimaryConnections() {
		$primaryIndex = $this->getWriterIndex();
		foreach ( $this->conns as $connsByServer ) {
			if ( isset( $connsByServer[$primaryIndex] ) ) {
				/** @var IDatabase $conn */
				foreach ( $connsByServer[$primaryIndex] as $conn ) {
					yield $conn;
				}
			}
		}
	}

	/**
	 * Get open replica connections
	 * @return \Generator|Database[]
	 */
	private function getOpenReplicaConnections() {
		foreach ( $this->conns as $connsByServer ) {
			foreach ( $connsByServer as $i => $serverConns ) {
				if ( $i === $this->getWriterIndex() ) {
					continue; // skip primary DB
				}
				foreach ( $serverConns as $conn ) {
					yield $conn;
				}
			}
		}
	}

	/**
	 * @return int
	 */
	private function getCurrentConnectionCount() {
		$count = 0;
		foreach ( $this->conns as $connsByServer ) {
			foreach ( $connsByServer as $serverConns ) {
				$count += count( $serverConns );
			}
		}

		return $count;
	}

	public function getMaxLag( $domain = false ) {
		$domain = $this->resolveDomainID( $domain );

		$host = '';
		$maxLag = -1;
		$maxIndex = 0;

		if ( $this->hasReplicaServers() ) {
			$lagTimes = $this->getLagTimes( $domain );
			foreach ( $lagTimes as $i => $lag ) {
				if ( $this->groupLoads[self::GROUP_GENERIC][$i] > 0 && $lag > $maxLag ) {
					$maxLag = $lag;
					$host = $this->getServerInfoStrict( $i, 'host' );
					$maxIndex = $i;
				}
			}
		}

		return [ $host, $maxLag, $maxIndex ];
	}

	public function getLagTimes( $domain = false ) {
		$domain = $this->resolveDomainID( $domain );

		if ( !$this->hasReplicaServers() ) {
			return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
		}

		$knownLagTimes = []; // map of (server index => 0 seconds)
		$indexesWithLag = [];
		foreach ( $this->servers as $i => $server ) {
			if ( empty( $server['is static'] ) ) {
				$indexesWithLag[] = $i; // DB server might have replication lag
			} else {
				$knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
			}
		}

		return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
	}

	public function waitForPrimaryPos( IDatabase $conn, $pos = false, $timeout = null ) {
		$timeout = max( 1, $timeout ?: $this->waitTimeout );

		if ( $conn->getLBInfo( self::INFO_SERVER_INDEX ) === $this->getWriterIndex() ) {
			return true; // not a replica DB server
		}

		if ( !$pos ) {
			// Get the current primary DB position, opening a connection only if needed
			$this->replLogger->debug( __METHOD__ . ': no position passed; using current' );
			$index = $this->getWriterIndex();
			$flags = self::CONN_SILENCE_ERRORS;
			$primaryConn = $this->getAnyOpenConnection( $index, $flags );
			if ( $primaryConn ) {
				$pos = $primaryConn->getPrimaryPos();
			} else {
				$primaryConn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
				if ( !$primaryConn ) {
					throw new DBReplicationWaitError(
						null,
						"Could not obtain a primary database connection to get the position"
					);
				}
				$pos = $primaryConn->getPrimaryPos();
				$this->closeConnection( $primaryConn );
			}
		}

		if ( $pos instanceof DBPrimaryPos ) {
			$this->replLogger->debug( __METHOD__ . ': waiting' );
			$result = $conn->primaryPosWait( $pos, $timeout );
			$ok = ( $result !== null && $result != -1 );
			if ( $ok ) {
				$this->replLogger->debug( __METHOD__ . ': done waiting (success)' );
			} else {
				$this->replLogger->debug( __METHOD__ . ': done waiting (failure)' );
			}
		} else {
			$ok = false; // something is misconfigured
			$this->replLogger->error(
				__METHOD__ . ': could not get primary pos for {db_server}',
				$this->getConnLogContext( $conn, [ 'exception' => new RuntimeException() ] )
			);
		}

		return $ok;
	}

	public function setTransactionListener( $name, callable $callback = null ) {
		if ( $callback ) {
			$this->trxRecurringCallbacks[$name] = $callback;
		} else {
			unset( $this->trxRecurringCallbacks[$name] );
		}
		foreach ( $this->getOpenPrimaryConnections() as $conn ) {
			$conn->setTransactionListener( $name, $callback );
		}
	}

	public function setTableAliases( array $aliases ) {
		$this->tableAliases = $aliases;
	}

	public function setIndexAliases( array $aliases ) {
		$this->indexAliases = $aliases;
	}

	public function setDomainAliases( array $aliases ) {
		$this->domainAliases = $aliases;
	}

	public function setLocalDomainPrefix( $prefix ) {
		// Find connections to explicit foreign domains still marked as in-use...
		$domainsInUse = [];
		foreach ( $this->getOpenConnections() as $conn ) {
			// Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
			// Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
			if ( $conn->getLBInfo( self::INFO_FOREIGN_REF_COUNT ) > 0 ) {
				$domainsInUse[] = $conn->getDomainID();
			}
		}

		// Do not switch connections to explicit foreign domains unless marked as safe
		if ( $domainsInUse ) {
			$domains = implode( ', ', $domainsInUse );
			throw new DBUnexpectedError( null,
				"Foreign domain connections are still in use ($domains)" );
		}

		$this->setLocalDomain( new DatabaseDomain(
			$this->localDomain->getDatabase(),
			$this->localDomain->getSchema(),
			$prefix
		) );

		// Update the prefix for all local connections...
		foreach ( $this->getOpenConnections() as $conn ) {
			if ( !$conn->getLBInfo( self::INFO_FORIEGN ) ) {
				$conn->tablePrefix( $prefix );
			}
		}
	}

	public function redefineLocalDomain( $domain ) {
		$this->closeAll( __METHOD__ );

		$this->setLocalDomain( DatabaseDomain::newFromId( $domain ) );
	}

	public function setTempTablesOnlyMode( $value, $domain ) {
		$old = $this->tempTablesOnlyMode[$domain] ?? false;
		if ( $value ) {
			$this->tempTablesOnlyMode[$domain] = true;
		} else {
			unset( $this->tempTablesOnlyMode[$domain] );
		}

		return $old;
	}

	/**
	 * @param DatabaseDomain $domain
	 */
	private function setLocalDomain( DatabaseDomain $domain ) {
		$this->localDomain = $domain;
	}

	/**
	 * @param int $i Server index
	 * @param string|null $field Server index field [optional]
	 * @return array|mixed
	 * @throws InvalidArgumentException
	 */
	private function getServerInfoStrict( $i, $field = null ) {
		if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
			throw new InvalidArgumentException( "No server with index '$i'" );
		}

		if ( $field !== null ) {
			if ( !array_key_exists( $field, $this->servers[$i] ) ) {
				throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
			}

			return $this->servers[$i][$field];
		}

		return $this->servers[$i];
	}

	/**
	 * @return string Name of the primary DB server of the relevant DB cluster (e.g. "db1052")
	 */
	private function getPrimaryServerName() {
		return $this->getServerName( $this->getWriterIndex() );
	}

	/**
	 * @param int $flags A bitfield of flags
	 * @param int $bit Bit flag constant
	 * @return bool Whether the bit field has the specified bit flag set
	 */
	private function fieldHasBit( int $flags, int $bit ) {
		return ( ( $flags & $bit ) === $bit );
	}

	/**
	 * Create a log context to pass to PSR-3 logger functions.
	 *
	 * @param IDatabase $conn
	 * @param array $extras Additional data to add to context
	 * @return array
	 */
	protected function getConnLogContext( IDatabase $conn, array $extras = [] ) {
		return array_merge(
			[
				'db_server' => $conn->getServerName(),
				'db_domain' => $conn->getDomainID()
			],
			$extras
		);
	}

}

/**
 * @deprecated since 1.29
 */
class_alias( LoadBalancer::class, 'LoadBalancer' );