aboutsummaryrefslogtreecommitdiffstats
path: root/includes/libs/filebackend/FileBackendStore.php
blob: 6af79d1c0138ba141e77c1a77700449605154e36 (plain) (blame)
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
<?php
/**
 * Base class for all backends using particular storage medium.
 *
 * 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
 * @ingroup FileBackend
 */

use Wikimedia\AtEase\AtEase;
use Wikimedia\Timestamp\ConvertibleTimestamp;

/**
 * @brief Base class for all backends using particular storage medium.
 *
 * This class defines the methods as abstract that subclasses must implement.
 * Outside callers should *not* use functions with "Internal" in the name.
 *
 * The FileBackend operations are implemented using basic functions
 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
 * This class is also responsible for path resolution and sanitization.
 *
 * @stable to extend
 * @ingroup FileBackend
 * @since 1.19
 */
abstract class FileBackendStore extends FileBackend {
	/** @var WANObjectCache */
	protected $memCache;
	/** @var BagOStuff */
	protected $srvCache;
	/** @var MapCacheLRU Map of paths to small (RAM/disk) cache items */
	protected $cheapCache;
	/** @var MapCacheLRU Map of paths to large (RAM/disk) cache items */
	protected $expensiveCache;

	/** @var array<string,array> Map of container names to sharding config */
	protected $shardViaHashLevels = [];

	/** @var callable|null Method to get the MIME type of files */
	protected $mimeCallback;

	protected $maxFileSize = 32 * 1024 * 1024 * 1024; // integer bytes (32GiB)

	protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
	protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
	protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"

	/** @var false Idiom for "no result due to missing file" (since 1.34) */
	protected const RES_ABSENT = false;
	/** @var null Idiom for "no result due to I/O errors" (since 1.34) */
	protected const RES_ERROR = null;

	/** @var string File does not exist according to a normal stat query */
	protected const ABSENT_NORMAL = 'FNE-N';
	/** @var string File does not exist according to a "latest"-mode stat query */
	protected const ABSENT_LATEST = 'FNE-L';

	/**
	 * @see FileBackend::__construct()
	 * Additional $config params include:
	 *   - srvCache     : BagOStuff cache to APC or the like.
	 *   - wanCache     : WANObjectCache object to use for persistent caching.
	 *   - mimeCallback : Callback that takes (storage path, content, file system path) and
	 *                    returns the MIME type of the file or 'unknown/unknown'. The file
	 *                    system path parameter should be used if the content one is null.
	 *
	 * @stable to call
	 *
	 * @param array $config
	 */
	public function __construct( array $config ) {
		parent::__construct( $config );
		$this->mimeCallback = $config['mimeCallback'] ?? null;
		$this->srvCache = new EmptyBagOStuff(); // disabled by default
		$this->memCache = WANObjectCache::newEmpty(); // disabled by default
		$this->cheapCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
		$this->expensiveCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
	}

	/**
	 * Get the maximum allowable file size given backend
	 * medium restrictions and basic performance constraints.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * @return int Bytes
	 */
	final public function maxFileSizeInternal() {
		return min( $this->maxFileSize, PHP_INT_MAX );
	}

	/**
	 * Check if a file can be created or changed at a given storage path in the backend
	 *
	 * FS backends should check that the parent directory exists, files can be written
	 * under it, and that any file already there is both readable and writable.
	 * Backends using key/value stores should check if the container exists.
	 *
	 * @param string $storagePath
	 * @return bool
	 */
	abstract public function isPathUsableInternal( $storagePath );

	/**
	 * Create a file in the backend with the given contents.
	 * This will overwrite any file that exists at the destination.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * $params include:
	 *   - content     : the raw file contents
	 *   - dst         : destination storage path
	 *   - headers     : HTTP header name/value map
	 *   - async       : StatusValue will be returned immediately if supported.
	 *                   If the StatusValue is OK, then its value field will be
	 *                   set to a FileBackendStoreOpHandle object.
	 *   - dstExists   : Whether a file exists at the destination (optimization).
	 *                   Callers can use "false" if no existing file is being changed.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function createInternal( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
			$status = $this->newStatus( 'backend-fail-maxsize',
				$params['dst'], $this->maxFileSizeInternal() );
		} else {
			$status = $this->doCreateInternal( $params );
			$this->clearCache( [ $params['dst'] ] );
			if ( $params['dstExists'] ?? true ) {
				$this->deleteFileCache( $params['dst'] ); // persistent cache
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::createInternal()
	 * @param array $params
	 * @return StatusValue
	 */
	abstract protected function doCreateInternal( array $params );

	/**
	 * Store a file into the backend from a file on disk.
	 * This will overwrite any file that exists at the destination.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * $params include:
	 *   - src         : source path on disk
	 *   - dst         : destination storage path
	 *   - headers     : HTTP header name/value map
	 *   - async       : StatusValue will be returned immediately if supported.
	 *                   If the StatusValue is OK, then its value field will be
	 *                   set to a FileBackendStoreOpHandle object.
	 *   - dstExists   : Whether a file exists at the destination (optimization).
	 *                   Callers can use "false" if no existing file is being changed.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function storeInternal( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
			$status = $this->newStatus( 'backend-fail-maxsize',
				$params['dst'], $this->maxFileSizeInternal() );
		} else {
			$status = $this->doStoreInternal( $params );
			$this->clearCache( [ $params['dst'] ] );
			if ( $params['dstExists'] ?? true ) {
				$this->deleteFileCache( $params['dst'] ); // persistent cache
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::storeInternal()
	 * @param array $params
	 * @return StatusValue
	 */
	abstract protected function doStoreInternal( array $params );

	/**
	 * Copy a file from one storage path to another in the backend.
	 * This will overwrite any file that exists at the destination.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * $params include:
	 *   - src                 : source storage path
	 *   - dst                 : destination storage path
	 *   - ignoreMissingSource : do nothing if the source file does not exist
	 *   - headers             : HTTP header name/value map
	 *   - async               : StatusValue will be returned immediately if supported.
	 *                           If the StatusValue is OK, then its value field will be
	 *                           set to a FileBackendStoreOpHandle object.
	 *   - dstExists           : Whether a file exists at the destination (optimization).
	 *                           Callers can use "false" if no existing file is being changed.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function copyInternal( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$status = $this->doCopyInternal( $params );
		$this->clearCache( [ $params['dst'] ] );
		if ( $params['dstExists'] ?? true ) {
			$this->deleteFileCache( $params['dst'] ); // persistent cache
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::copyInternal()
	 * @param array $params
	 * @return StatusValue
	 */
	abstract protected function doCopyInternal( array $params );

	/**
	 * Delete a file at the storage path.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * $params include:
	 *   - src                 : source storage path
	 *   - ignoreMissingSource : do nothing if the source file does not exist
	 *   - async               : StatusValue will be returned immediately if supported.
	 *                           If the StatusValue is OK, then its value field will be
	 *                           set to a FileBackendStoreOpHandle object.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function deleteInternal( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$status = $this->doDeleteInternal( $params );
		$this->clearCache( [ $params['src'] ] );
		$this->deleteFileCache( $params['src'] ); // persistent cache
		return $status;
	}

	/**
	 * @see FileBackendStore::deleteInternal()
	 * @param array $params
	 * @return StatusValue
	 */
	abstract protected function doDeleteInternal( array $params );

	/**
	 * Move a file from one storage path to another in the backend.
	 * This will overwrite any file that exists at the destination.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * $params include:
	 *   - src                 : source storage path
	 *   - dst                 : destination storage path
	 *   - ignoreMissingSource : do nothing if the source file does not exist
	 *   - headers             : HTTP header name/value map
	 *   - async               : StatusValue will be returned immediately if supported.
	 *                           If the StatusValue is OK, then its value field will be
	 *                           set to a FileBackendStoreOpHandle object.
	 *   - dstExists           : Whether a file exists at the destination (optimization).
	 *                           Callers can use "false" if no existing file is being changed.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function moveInternal( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$status = $this->doMoveInternal( $params );
		$this->clearCache( [ $params['src'], $params['dst'] ] );
		$this->deleteFileCache( $params['src'] ); // persistent cache
		if ( $params['dstExists'] ?? true ) {
			$this->deleteFileCache( $params['dst'] ); // persistent cache
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::moveInternal()
	 * @param array $params
	 * @return StatusValue
	 */
	abstract protected function doMoveInternal( array $params );

	/**
	 * Alter metadata for a file at the storage path.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * $params include:
	 *   - src           : source storage path
	 *   - headers       : HTTP header name/value map
	 *   - async         : StatusValue will be returned immediately if supported.
	 *                     If the StatusValue is OK, then its value field will be
	 *                     set to a FileBackendStoreOpHandle object.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function describeInternal( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		if ( count( $params['headers'] ) ) {
			$status = $this->doDescribeInternal( $params );
			$this->clearCache( [ $params['src'] ] );
			$this->deleteFileCache( $params['src'] ); // persistent cache
		} else {
			$status = $this->newStatus(); // nothing to do
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::describeInternal()
	 * @stable to override
	 * @param array $params
	 * @return StatusValue
	 */
	protected function doDescribeInternal( array $params ) {
		return $this->newStatus();
	}

	/**
	 * No-op file operation that does nothing.
	 * Do not call this function from places outside FileBackend and FileOp.
	 *
	 * @param array $params
	 * @return StatusValue
	 */
	final public function nullInternal( array $params ) {
		return $this->newStatus();
	}

	final public function concatenate( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		// Try to lock the source files for the scope of this function
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
		if ( $status->isOK() ) {
			// Actually do the file concatenation...
			$start_time = microtime( true );
			$status->merge( $this->doConcatenate( $params ) );
			$sec = microtime( true ) - $start_time;
			if ( !$status->isOK() ) {
				$this->logger->error( static::class . "-{$this->name}" .
					" failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::concatenate()
	 * @stable to override
	 * @param array $params
	 * @return StatusValue
	 */
	protected function doConcatenate( array $params ) {
		$status = $this->newStatus();
		$tmpPath = $params['dst'];
		unset( $params['latest'] );

		// Check that the specified temp file is valid...
		AtEase::suppressWarnings();
		$ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
		AtEase::restoreWarnings();
		if ( !$ok ) { // not present or not empty
			$status->fatal( 'backend-fail-opentemp', $tmpPath );

			return $status;
		}

		// Get local FS versions of the chunks needed for the concatenation...
		$fsFiles = $this->getLocalReferenceMulti( $params );
		foreach ( $fsFiles as $path => &$fsFile ) {
			if ( !$fsFile ) { // chunk failed to download?
				$fsFile = $this->getLocalReference( [ 'src' => $path ] );
				if ( !$fsFile ) { // retry failed?
					$status->fatal(
						$fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
						$path
					);

					return $status;
				}
			}
		}
		unset( $fsFile ); // unset reference so we can reuse $fsFile

		// Get a handle for the destination temp file
		$tmpHandle = fopen( $tmpPath, 'ab' );
		if ( $tmpHandle === false ) {
			$status->fatal( 'backend-fail-opentemp', $tmpPath );

			return $status;
		}

		// Build up the temp file using the source chunks (in order)...
		foreach ( $fsFiles as $virtualSource => $fsFile ) {
			// Get a handle to the local FS version
			$sourceHandle = fopen( $fsFile->getPath(), 'rb' );
			if ( $sourceHandle === false ) {
				fclose( $tmpHandle );
				$status->fatal( 'backend-fail-read', $virtualSource );

				return $status;
			}
			// Append chunk to file (pass chunk size to avoid magic quotes)
			if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
				fclose( $sourceHandle );
				fclose( $tmpHandle );
				$status->fatal( 'backend-fail-writetemp', $tmpPath );

				return $status;
			}
			fclose( $sourceHandle );
		}
		if ( !fclose( $tmpHandle ) ) {
			$status->fatal( 'backend-fail-closetemp', $tmpPath );

			return $status;
		}

		clearstatcache(); // temp file changed

		return $status;
	}

	/**
	 * @inheritDoc
	 */
	final protected function doPrepare( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			$status->fatal( 'backend-fail-invalidpath', $params['dir'] );

			return $status; // invalid storage path
		}

		if ( $shard !== null ) { // confined to a single container/shard
			$status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
		} else { // directory is on several shards
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
			foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
				$status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::doPrepare()
	 * @stable to override
	 * @param string $container
	 * @param string $dir
	 * @param array $params
	 * @return StatusValue Good status without value for success, fatal otherwise.
	 */
	protected function doPrepareInternal( $container, $dir, array $params ) {
		return $this->newStatus();
	}

	final protected function doSecure( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			$status->fatal( 'backend-fail-invalidpath', $params['dir'] );

			return $status; // invalid storage path
		}

		if ( $shard !== null ) { // confined to a single container/shard
			$status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
		} else { // directory is on several shards
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
			foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
				$status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::doSecure()
	 * @stable to override
	 * @param string $container
	 * @param string $dir
	 * @param array $params
	 * @return StatusValue Good status without value for success, fatal otherwise.
	 */
	protected function doSecureInternal( $container, $dir, array $params ) {
		return $this->newStatus();
	}

	final protected function doPublish( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			$status->fatal( 'backend-fail-invalidpath', $params['dir'] );

			return $status; // invalid storage path
		}

		if ( $shard !== null ) { // confined to a single container/shard
			$status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
		} else { // directory is on several shards
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
			foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
				$status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::doPublish()
	 * @stable to override
	 * @param string $container
	 * @param string $dir
	 * @param array $params
	 * @return StatusValue
	 */
	protected function doPublishInternal( $container, $dir, array $params ) {
		return $this->newStatus();
	}

	final protected function doClean( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		// Recursive: first delete all empty subdirs recursively
		if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
			$subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
			if ( $subDirsRel !== null ) { // no errors
				foreach ( $subDirsRel as $subDirRel ) {
					$subDir = $params['dir'] . "/{$subDirRel}"; // full path
					$status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
				}
				unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
			}
		}

		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			$status->fatal( 'backend-fail-invalidpath', $params['dir'] );

			return $status; // invalid storage path
		}

		// Attempt to lock this directory...
		$filesLockEx = [ $params['dir'] ];
		/** @noinspection PhpUnusedLocalVariableInspection */
		$scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
		if ( !$status->isOK() ) {
			return $status; // abort
		}

		if ( $shard !== null ) { // confined to a single container/shard
			$status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
			$this->deleteContainerCache( $fullCont ); // purge cache
		} else { // directory is on several shards
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
			foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
				$status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
				$this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
			}
		}

		return $status;
	}

	/**
	 * @see FileBackendStore::doClean()
	 * @stable to override
	 * @param string $container
	 * @param string $dir
	 * @param array $params
	 * @return StatusValue
	 */
	protected function doCleanInternal( $container, $dir, array $params ) {
		return $this->newStatus();
	}

	final public function fileExists( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$stat = $this->getFileStat( $params );
		if ( is_array( $stat ) ) {
			return true;
		}

		return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
	}

	final public function getFileTimestamp( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$stat = $this->getFileStat( $params );
		if ( is_array( $stat ) ) {
			return $stat['mtime'];
		}

		return self::TIMESTAMP_FAIL; // all failure cases
	}

	final public function getFileSize( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$stat = $this->getFileStat( $params );
		if ( is_array( $stat ) ) {
			return $stat['size'];
		}

		return self::SIZE_FAIL; // all failure cases
	}

	final public function getFileStat( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$path = self::normalizeStoragePath( $params['src'] );
		if ( $path === null ) {
			return self::STAT_ERROR; // invalid storage path
		}

		// Whether to bypass cache except for process cache entries loaded directly from
		// high consistency backend queries (caller handles any cache flushing and locking)
		$latest = !empty( $params['latest'] );
		// Whether to ignore cache entries missing the SHA-1 field for existing files
		$requireSHA1 = !empty( $params['requireSHA1'] );

		$stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
		// Load the persistent stat cache into process cache if needed
		if ( !$latest ) {
			if (
				// File stat is not in process cache
				$stat === null ||
				// Key/value store backends might opportunistically set file stat process
				// cache entries from object listings that do not include the SHA-1. In that
				// case, loading the persistent stat cache will likely yield the SHA-1.
				( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
			) {
				$this->primeFileCache( [ $path ] );
				// Get any newly process-cached entry
				$stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
			}
		}

		if ( is_array( $stat ) ) {
			if (
				( !$latest || !empty( $stat['latest'] ) ) &&
				( !$requireSHA1 || isset( $stat['sha1'] ) )
			) {
				return $stat;
			}
		} elseif ( $stat === self::ABSENT_LATEST ) {
			return self::STAT_ABSENT;
		} elseif ( $stat === self::ABSENT_NORMAL ) {
			if ( !$latest ) {
				return self::STAT_ABSENT;
			}
		}

		// Load the file stat from the backend and update caches
		$stat = $this->doGetFileStat( $params );
		$this->ingestFreshFileStats( [ $path => $stat ], $latest );

		if ( is_array( $stat ) ) {
			return $stat;
		}

		return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
	}

	/**
	 * Ingest file stat entries that just came from querying the backend (not cache)
	 *
	 * @param array<string,array|false|null> $stats Map of storage path => {@see doGetFileStat} result
	 * @param bool $latest Whether doGetFileStat()/doGetFileStatMulti() had the 'latest' flag
	 * @return bool Whether all files have non-error stat replies
	 */
	final protected function ingestFreshFileStats( array $stats, $latest ) {
		$success = true;

		foreach ( $stats as $path => $stat ) {
			if ( is_array( $stat ) ) {
				// Strongly consistent backends might automatically set this flag
				$stat['latest'] ??= $latest;

				$this->cheapCache->setField( $path, 'stat', $stat );
				if ( isset( $stat['sha1'] ) ) {
					// Some backends store the SHA-1 hash as metadata
					$this->cheapCache->setField(
						$path,
						'sha1',
						[ 'hash' => $stat['sha1'], 'latest' => $latest ]
					);
				}
				if ( isset( $stat['xattr'] ) ) {
					// Some backends store custom headers/metadata
					$stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
					$this->cheapCache->setField(
						$path,
						'xattr',
						[ 'map' => $stat['xattr'], 'latest' => $latest ]
					);
				}
				// Update persistent cache (@TODO: set all entries in one batch)
				$this->setFileCache( $path, $stat );
			} elseif ( $stat === self::RES_ABSENT ) {
				$this->cheapCache->setField(
					$path,
					'stat',
					$latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
				);
				$this->cheapCache->setField(
					$path,
					'xattr',
					[ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
				);
				$this->cheapCache->setField(
					$path,
					'sha1',
					[ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
				);
				$this->logger->debug(
					__METHOD__ . ': File {path} does not exist',
					[ 'path' => $path ]
				);
			} else {
				$success = false;
				$this->logger->error(
					__METHOD__ . ': Could not stat file {path}',
					[ 'path' => $path ]
				);
			}
		}

		return $success;
	}

	/**
	 * @see FileBackendStore::getFileStat()
	 * @param array $params
	 * @return array|false|null
	 */
	abstract protected function doGetFileStat( array $params );

	public function getFileContentsMulti( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$params = $this->setConcurrencyFlags( $params );
		$contents = $this->doGetFileContentsMulti( $params );
		foreach ( $contents as $path => $content ) {
			if ( !is_string( $content ) ) {
				$contents[$path] = self::CONTENT_FAIL; // used for all failure cases
			}
		}

		return $contents;
	}

	/**
	 * @see FileBackendStore::getFileContentsMulti()
	 * @stable to override
	 * @param array $params
	 * @return string[]|bool[]|null[] Map of (path => string, false (missing), or null (error))
	 */
	protected function doGetFileContentsMulti( array $params ) {
		$contents = [];
		foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
			if ( $fsFile instanceof FSFile ) {
				AtEase::suppressWarnings();
				$content = file_get_contents( $fsFile->getPath() );
				AtEase::restoreWarnings();
				$contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
			} else {
				// self::RES_ERROR or self::RES_ABSENT
				$contents[$path] = $fsFile;
			}
		}

		return $contents;
	}

	final public function getFileXAttributes( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$path = self::normalizeStoragePath( $params['src'] );
		if ( $path === null ) {
			return self::XATTRS_FAIL; // invalid storage path
		}
		$latest = !empty( $params['latest'] ); // use latest data?
		if ( $this->cheapCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
			$stat = $this->cheapCache->getField( $path, 'xattr' );
			// If we want the latest data, check that this cached
			// value was in fact fetched with the latest available data.
			if ( !$latest || $stat['latest'] ) {
				return $stat['map'];
			}
		}
		$fields = $this->doGetFileXAttributes( $params );
		if ( is_array( $fields ) ) {
			$fields = self::normalizeXAttributes( $fields );
			$this->cheapCache->setField(
				$path,
				'xattr',
				[ 'map' => $fields, 'latest' => $latest ]
			);
		} elseif ( $fields === self::RES_ABSENT ) {
			$this->cheapCache->setField(
				$path,
				'xattr',
				[ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
			);
		} else {
			$fields = self::XATTRS_FAIL; // used for all failure cases
		}

		return $fields;
	}

	/**
	 * @see FileBackendStore::getFileXAttributes()
	 * @stable to override
	 * @param array $params
	 * @return array[][]|false|null Attributes, false (missing file), or null (error)
	 */
	protected function doGetFileXAttributes( array $params ) {
		return [ 'headers' => [], 'metadata' => [] ]; // not supported
	}

	final public function getFileSha1Base36( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$path = self::normalizeStoragePath( $params['src'] );
		if ( $path === null ) {
			return self::SHA1_FAIL; // invalid storage path
		}
		$latest = !empty( $params['latest'] ); // use latest data?
		if ( $this->cheapCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
			$stat = $this->cheapCache->getField( $path, 'sha1' );
			// If we want the latest data, check that this cached
			// value was in fact fetched with the latest available data.
			if ( !$latest || $stat['latest'] ) {
				return $stat['hash'];
			}
		}
		$sha1 = $this->doGetFileSha1Base36( $params );
		if ( is_string( $sha1 ) ) {
			$this->cheapCache->setField(
				$path,
				'sha1',
				[ 'hash' => $sha1, 'latest' => $latest ]
			);
		} elseif ( $sha1 === self::RES_ABSENT ) {
			$this->cheapCache->setField(
				$path,
				'sha1',
				[ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
			);
		} else {
			$sha1 = self::SHA1_FAIL; // used for all failure cases
		}

		return $sha1;
	}

	/**
	 * @see FileBackendStore::getFileSha1Base36()
	 * @stable to override
	 * @param array $params
	 * @return bool|string|null SHA1, false (missing file), or null (error)
	 */
	protected function doGetFileSha1Base36( array $params ) {
		$fsFile = $this->getLocalReference( $params );
		if ( $fsFile instanceof FSFile ) {
			$sha1 = $fsFile->getSha1Base36();

			return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
		}

		return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
	}

	final public function getFileProps( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$fsFile = $this->getLocalReference( $params );

		return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
	}

	final public function getLocalReferenceMulti( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$params = $this->setConcurrencyFlags( $params );

		$fsFiles = []; // (path => FSFile)
		$latest = !empty( $params['latest'] ); // use latest data?
		// Reuse any files already in process cache...
		foreach ( $params['srcs'] as $src ) {
			$path = self::normalizeStoragePath( $src );
			if ( $path === null ) {
				$fsFiles[$src] = self::RES_ERROR; // invalid storage path
			} elseif ( $this->expensiveCache->hasField( $path, 'localRef' ) ) {
				$val = $this->expensiveCache->getField( $path, 'localRef' );
				// If we want the latest data, check that this cached
				// value was in fact fetched with the latest available data.
				if ( !$latest || $val['latest'] ) {
					$fsFiles[$src] = $val['object'];
				}
			}
		}
		// Fetch local references of any remaining files...
		$params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
		foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
			if ( $fsFile instanceof FSFile ) {
				$fsFiles[$path] = $fsFile;
				$this->expensiveCache->setField(
					$path,
					'localRef',
					[ 'object' => $fsFile, 'latest' => $latest ]
				);
			} else {
				// self::RES_ERROR or self::RES_ABSENT
				$fsFiles[$path] = $fsFile;
			}
		}

		return $fsFiles;
	}

	/**
	 * @see FileBackendStore::getLocalReferenceMulti()
	 * @stable to override
	 * @param array $params
	 * @return string[]|bool[]|null[] Map of (path => FSFile, false (missing), or null (error))
	 */
	protected function doGetLocalReferenceMulti( array $params ) {
		return $this->doGetLocalCopyMulti( $params );
	}

	final public function getLocalCopyMulti( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$params = $this->setConcurrencyFlags( $params );

		return $this->doGetLocalCopyMulti( $params );
	}

	/**
	 * @see FileBackendStore::getLocalCopyMulti()
	 * @param array $params
	 * @return string[]|bool[]|null[] Map of (path => TempFSFile, false (missing), or null (error))
	 */
	abstract protected function doGetLocalCopyMulti( array $params );

	/**
	 * @see FileBackend::getFileHttpUrl()
	 * @stable to override
	 * @param array $params
	 * @return string|null
	 */
	public function getFileHttpUrl( array $params ) {
		return self::TEMPURL_ERROR; // not supported
	}

	final public function streamFile( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		// Always set some fields for subclass convenience
		$params['options'] ??= [];
		$params['headers'] ??= [];

		// Don't stream it out as text/html if there was a PHP error
		if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
			print "Headers already sent, terminating.\n";
			$status->fatal( 'backend-fail-stream', $params['src'] );
			return $status;
		}

		$status->merge( $this->doStreamFile( $params ) );

		return $status;
	}

	/**
	 * @see FileBackendStore::streamFile()
	 * @stable to override
	 * @param array $params
	 * @return StatusValue
	 */
	protected function doStreamFile( array $params ) {
		$status = $this->newStatus();

		$flags = 0;
		$flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
		$flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;

		$fsFile = $this->getLocalReference( $params );
		if ( $fsFile ) {
			$streamer = new HTTPFileStreamer(
				$fsFile->getPath(),
				[
					'obResetFunc' => $this->obResetFunc,
					'streamMimeFunc' => $this->streamMimeFunc
				]
			);
			$res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
		} else {
			$res = false;
			HTTPFileStreamer::send404Message( $params['src'], $flags );
		}

		if ( !$res ) {
			$status->fatal( 'backend-fail-stream', $params['src'] );
		}

		return $status;
	}

	final public function directoryExists( array $params ) {
		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			return self::EXISTENCE_ERROR; // invalid storage path
		}
		if ( $shard !== null ) { // confined to a single container/shard
			return $this->doDirectoryExists( $fullCont, $dir, $params );
		} else { // directory is on several shards
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
			$res = false; // response
			foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
				$exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
				if ( $exists === true ) {
					$res = true;
					break; // found one!
				} elseif ( $exists === self::RES_ERROR ) {
					$res = self::EXISTENCE_ERROR;
				}
			}

			return $res;
		}
	}

	/**
	 * @see FileBackendStore::directoryExists()
	 *
	 * @param string $container Resolved container name
	 * @param string $dir Resolved path relative to container
	 * @param array $params
	 * @return bool|null
	 */
	abstract protected function doDirectoryExists( $container, $dir, array $params );

	final public function getDirectoryList( array $params ) {
		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			return self::EXISTENCE_ERROR; // invalid storage path
		}
		if ( $shard !== null ) {
			// File listing is confined to a single container/shard
			return $this->getDirectoryListInternal( $fullCont, $dir, $params );
		} else {
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			// File listing spans multiple containers/shards
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );

			return new FileBackendStoreShardDirIterator( $this,
				$fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
		}
	}

	/**
	 * Do not call this function from places outside FileBackend
	 *
	 * @see FileBackendStore::getDirectoryList()
	 *
	 * @param string $container Resolved container name
	 * @param string $dir Resolved path relative to container
	 * @param array $params
	 * @return Traversable|array|null Iterable list or null (error)
	 */
	abstract public function getDirectoryListInternal( $container, $dir, array $params );

	final public function getFileList( array $params ) {
		[ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
		if ( $dir === null ) {
			return self::LIST_ERROR; // invalid storage path
		}
		if ( $shard !== null ) {
			// File listing is confined to a single container/shard
			return $this->getFileListInternal( $fullCont, $dir, $params );
		} else {
			$this->logger->debug( __METHOD__ . ": iterating over all container shards." );
			// File listing spans multiple containers/shards
			[ , $shortCont, ] = self::splitStoragePath( $params['dir'] );

			return new FileBackendStoreShardFileIterator( $this,
				$fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
		}
	}

	/**
	 * Do not call this function from places outside FileBackend
	 *
	 * @see FileBackendStore::getFileList()
	 *
	 * @param string $container Resolved container name
	 * @param string $dir Resolved path relative to container
	 * @param array $params
	 * @return Traversable|string[]|null Iterable list or null (error)
	 */
	abstract public function getFileListInternal( $container, $dir, array $params );

	/**
	 * Return a list of FileOp objects from a list of operations.
	 * Do not call this function from places outside FileBackend.
	 *
	 * The result must have the same number of items as the input.
	 * An exception is thrown if an unsupported operation is requested.
	 *
	 * @param array[] $ops Same format as doOperations()
	 * @return FileOp[]
	 * @throws FileBackendError
	 */
	final public function getOperationsInternal( array $ops ) {
		$supportedOps = [
			'store' => StoreFileOp::class,
			'copy' => CopyFileOp::class,
			'move' => MoveFileOp::class,
			'delete' => DeleteFileOp::class,
			'create' => CreateFileOp::class,
			'describe' => DescribeFileOp::class,
			'null' => NullFileOp::class
		];

		$performOps = []; // array of FileOp objects
		// Build up ordered array of FileOps...
		foreach ( $ops as $operation ) {
			$opName = $operation['op'];
			if ( isset( $supportedOps[$opName] ) ) {
				$class = $supportedOps[$opName];
				// Get params for this operation
				$params = $operation;
				// Append the FileOp class
				$performOps[] = new $class( $this, $params, $this->logger );
			} else {
				throw new FileBackendError( "Operation '$opName' is not supported." );
			}
		}

		return $performOps;
	}

	/**
	 * Get a list of storage paths to lock for a list of operations
	 * Returns an array with LockManager::LOCK_UW (shared locks) and
	 * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
	 * to a list of storage paths to be locked. All returned paths are
	 * normalized.
	 *
	 * @param FileOp[] $performOps List of FileOp objects
	 * @return string[][] (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
	 */
	final public function getPathsToLockForOpsInternal( array $performOps ) {
		// Build up a list of files to lock...
		$paths = [ 'sh' => [], 'ex' => [] ];
		foreach ( $performOps as $fileOp ) {
			$paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
			$paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
		}
		// Optimization: if doing an EX lock anyway, don't also set an SH one
		$paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
		// Get a shared lock on the parent directory of each path changed
		$paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );

		return [
			LockManager::LOCK_UW => $paths['sh'],
			LockManager::LOCK_EX => $paths['ex']
		];
	}

	public function getScopedLocksForOps( array $ops, StatusValue $status ) {
		$paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );

		return $this->getScopedFileLocks( $paths, 'mixed', $status );
	}

	final protected function doOperationsInternal( array $ops, array $opts ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		// Fix up custom header name/value pairs
		$ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
		// Build up a list of FileOps and involved paths
		$fileOps = $this->getOperationsInternal( $ops );
		$pathsUsed = [];
		foreach ( $fileOps as $fileOp ) {
			$pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
		}

		// Acquire any locks as needed for the scope of this function
		if ( empty( $opts['nonLocking'] ) ) {
			$pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
			/** @noinspection PhpUnusedLocalVariableInspection */
			$scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
			if ( !$status->isOK() ) {
				return $status; // abort
			}
		}

		// Clear any file cache entries (after locks acquired)
		if ( empty( $opts['preserveCache'] ) ) {
			$this->clearCache( $pathsUsed );
		}

		// Enlarge the cache to fit the stat entries of these files
		$this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );

		// Load from the persistent container caches
		$this->primeContainerCache( $pathsUsed );
		// Get the latest stat info for all the files (having locked them)
		$ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );

		if ( $ok ) {
			// Actually attempt the operation batch...
			$opts = $this->setConcurrencyFlags( $opts );
			$subStatus = FileOpBatch::attempt( $fileOps, $opts );
		} else {
			// If we could not even stat some files, then bail out
			$subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
			foreach ( $ops as $i => $op ) { // mark each op as failed
				$subStatus->success[$i] = false;
				++$subStatus->failCount;
			}
			$this->logger->error( static::class . "-{$this->name} " .
				" stat failure; aborted operations: " . FormatJson::encode( $ops ) );
		}

		// Merge errors into StatusValue fields
		$status->merge( $subStatus );
		$status->success = $subStatus->success; // not done in merge()

		// Shrink the stat cache back to normal size
		$this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );

		return $status;
	}

	final protected function doQuickOperationsInternal( array $ops, array $opts ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
		$status = $this->newStatus();

		// Fix up custom header name/value pairs
		$ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
		// Build up a list of FileOps and involved paths
		$fileOps = $this->getOperationsInternal( $ops );
		$pathsUsed = [];
		foreach ( $fileOps as $fileOp ) {
			$pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
		}

		// Clear any file cache entries for involved paths
		$this->clearCache( $pathsUsed );

		// Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
		$async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
		$maxConcurrency = $this->concurrency; // throttle
		/** @var StatusValue[] $statuses */
		$statuses = []; // array of (index => StatusValue)
		/** @var FileBackendStoreOpHandle[] $batch */
		$batch = [];
		foreach ( $fileOps as $index => $fileOp ) {
			$subStatus = $async
				? $fileOp->attemptAsyncQuick()
				: $fileOp->attemptQuick();
			if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
				if ( count( $batch ) >= $maxConcurrency ) {
					// Execute this batch. Don't queue any more ops since they contain
					// open filehandles which are a limited resource (T230245).
					$statuses += $this->executeOpHandlesInternal( $batch );
					$batch = [];
				}
				$batch[$index] = $subStatus->value; // keep index
			} else { // error or completed
				$statuses[$index] = $subStatus; // keep index
			}
		}
		if ( count( $batch ) ) {
			$statuses += $this->executeOpHandlesInternal( $batch );
		}
		// Marshall and merge all the responses...
		foreach ( $statuses as $index => $subStatus ) {
			$status->merge( $subStatus );
			if ( $subStatus->isOK() ) {
				$status->success[$index] = true;
				++$status->successCount;
			} else {
				$status->success[$index] = false;
				++$status->failCount;
			}
		}

		$this->clearCache( $pathsUsed );

		return $status;
	}

	/**
	 * Execute a list of FileBackendStoreOpHandle handles in parallel.
	 * The resulting StatusValue object fields will correspond
	 * to the order in which the handles where given.
	 *
	 * @param FileBackendStoreOpHandle[] $fileOpHandles
	 * @return StatusValue[] Map of StatusValue objects
	 * @throws FileBackendError
	 */
	final public function executeOpHandlesInternal( array $fileOpHandles ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		foreach ( $fileOpHandles as $fileOpHandle ) {
			if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
				throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
			} elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
				throw new InvalidArgumentException( "Expected handle for this file backend." );
			}
		}

		$statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
		foreach ( $fileOpHandles as $fileOpHandle ) {
			$fileOpHandle->closeResources();
		}

		return $statuses;
	}

	/**
	 * @see FileBackendStore::executeOpHandlesInternal()
	 * @stable to override
	 *
	 * @param FileBackendStoreOpHandle[] $fileOpHandles
	 *
	 * @throws FileBackendError
	 * @return StatusValue[] List of corresponding StatusValue objects
	 */
	protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
		if ( count( $fileOpHandles ) ) {
			throw new FileBackendError( "Backend does not support asynchronous operations." );
		}

		return [];
	}

	/**
	 * Normalize and filter HTTP headers from a file operation
	 *
	 * This normalizes and strips long HTTP headers from a file operation.
	 * Most headers are just numbers, but some are allowed to be long.
	 * This function is useful for cleaning up headers and avoiding backend
	 * specific errors, especially in the middle of batch file operations.
	 *
	 * @param array $op Same format as doOperation()
	 * @return array
	 */
	protected function sanitizeOpHeaders( array $op ) {
		static $longs = [ 'content-disposition' ];

		if ( isset( $op['headers'] ) ) { // op sets HTTP headers
			$newHeaders = [];
			foreach ( $op['headers'] as $name => $value ) {
				$name = strtolower( $name );
				$maxHVLen = in_array( $name, $longs ) ? INF : 255;
				if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
					$this->logger->error( "Header '{header}' is too long.", [
						'filebackend' => $this->name,
						'header' => "$name: $value",
					] );
				} else {
					$newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
				}
			}
			$op['headers'] = $newHeaders;
		}

		return $op;
	}

	final public function preloadCache( array $paths ) {
		$fullConts = []; // full container names
		foreach ( $paths as $path ) {
			[ $fullCont, , ] = $this->resolveStoragePath( $path );
			$fullConts[] = $fullCont;
		}
		// Load from the persistent file and container caches
		$this->primeContainerCache( $fullConts );
		$this->primeFileCache( $paths );
	}

	final public function clearCache( array $paths = null ) {
		if ( is_array( $paths ) ) {
			$paths = array_map( [ FileBackend::class, 'normalizeStoragePath' ], $paths );
			$paths = array_filter( $paths, 'strlen' ); // remove nulls
		}
		if ( $paths === null ) {
			$this->cheapCache->clear();
			$this->expensiveCache->clear();
		} else {
			foreach ( $paths as $path ) {
				$this->cheapCache->clear( $path );
				$this->expensiveCache->clear( $path );
			}
		}
		$this->doClearCache( $paths );
	}

	/**
	 * Clears any additional stat caches for storage paths
	 * @stable to override
	 *
	 * @see FileBackend::clearCache()
	 *
	 * @param string[]|null $paths Storage paths (optional)
	 */
	protected function doClearCache( array $paths = null ) {
	}

	final public function preloadFileStat( array $params ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
		$stats = $this->doGetFileStatMulti( $params );
		if ( $stats === null ) {
			return true; // not supported
		}

		// Whether this queried the backend in high consistency mode
		$latest = !empty( $params['latest'] );

		return $this->ingestFreshFileStats( $stats, $latest );
	}

	/**
	 * Get file stat information (concurrently if possible) for several files
	 * @stable to override
	 *
	 * @see FileBackend::getFileStat()
	 *
	 * @param array $params Parameters include:
	 *   - srcs        : list of source storage paths
	 *   - latest      : use the latest available data
	 * @return array<string,array|false|null>|null Null if not supported. Otherwise a map of storage
	 *  path to attribute map, false (missing file), or null (I/O error).
	 * @since 1.23
	 */
	protected function doGetFileStatMulti( array $params ) {
		return null; // not supported
	}

	/**
	 * Is this a key/value store where directories are just virtual?
	 * Virtual directories exists in so much as files exists that are
	 * prefixed with the directory path followed by a forward slash.
	 *
	 * @return bool
	 */
	abstract protected function directoriesAreVirtual();

	/**
	 * Check if a short container name is valid
	 *
	 * This checks for length and illegal characters.
	 * This may disallow certain characters that can appear
	 * in the prefix used to make the full container name.
	 *
	 * @param string $container
	 * @return bool
	 */
	final protected static function isValidShortContainerName( $container ) {
		// Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
		// might be used by subclasses. Reserve the dot character.
		// The only way dots end up in containers (e.g. resolveStoragePath)
		// is due to the wikiId container prefix or the above suffixes.
		return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
	}

	/**
	 * Check if a full container name is valid
	 *
	 * This checks for length and illegal characters.
	 * Limiting the characters makes migrations to other stores easier.
	 *
	 * @param string $container
	 * @return bool
	 */
	final protected static function isValidContainerName( $container ) {
		// This accounts for NTFS, Swift, and Ceph restrictions
		// and disallows directory separators or traversal characters.
		// Note that matching strings URL encode to the same string;
		// in Swift/Ceph, the length restriction is *after* URL encoding.
		return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
	}

	/**
	 * Splits a storage path into an internal container name,
	 * an internal relative file name, and a container shard suffix.
	 * Any shard suffix is already appended to the internal container name.
	 * This also checks that the storage path is valid and within this backend.
	 *
	 * If the container is sharded but a suffix could not be determined,
	 * this means that the path can only refer to a directory and can only
	 * be scanned by looking in all the container shards.
	 *
	 * @param string $storagePath
	 * @return array (container, path, container suffix) or (null, null, null) if invalid
	 */
	final protected function resolveStoragePath( $storagePath ) {
		[ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
		if ( $backend === $this->name ) { // must be for this backend
			$relPath = self::normalizeContainerPath( $relPath );
			if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
				// Get shard for the normalized path if this container is sharded
				$cShard = $this->getContainerShard( $shortCont, $relPath );
				// Validate and sanitize the relative path (backend-specific)
				$relPath = $this->resolveContainerPath( $shortCont, $relPath );
				if ( $relPath !== null ) {
					// Prepend any domain ID prefix to the container name
					$container = $this->fullContainerName( $shortCont );
					if ( self::isValidContainerName( $container ) ) {
						// Validate and sanitize the container name (backend-specific)
						$container = $this->resolveContainerName( "{$container}{$cShard}" );
						if ( $container !== null ) {
							return [ $container, $relPath, $cShard ];
						}
					}
				}
			}
		}

		return [ null, null, null ];
	}

	/**
	 * Like resolveStoragePath() except null values are returned if
	 * the container is sharded and the shard could not be determined
	 * or if the path ends with '/'. The latter case is illegal for FS
	 * backends and can confuse listings for object store backends.
	 *
	 * This function is used when resolving paths that must be valid
	 * locations for files. Directory and listing functions should
	 * generally just use resolveStoragePath() instead.
	 *
	 * @see FileBackendStore::resolveStoragePath()
	 *
	 * @param string $storagePath
	 * @return array (container, path) or (null, null) if invalid
	 */
	final protected function resolveStoragePathReal( $storagePath ) {
		[ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
		if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
			return [ $container, $relPath ];
		}

		return [ null, null ];
	}

	/**
	 * Get the container name shard suffix for a given path.
	 * Any empty suffix means the container is not sharded.
	 *
	 * @param string $container Container name
	 * @param string $relPath Storage path relative to the container
	 * @return string|null Returns null if shard could not be determined
	 */
	final protected function getContainerShard( $container, $relPath ) {
		[ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
		if ( $levels == 1 || $levels == 2 ) {
			// Hash characters are either base 16 or 36
			$char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
			// Get a regex that represents the shard portion of paths.
			// The concatenation of the captures gives us the shard.
			if ( $levels === 1 ) { // 16 or 36 shards per container
				$hashDirRegex = '(' . $char . ')';
			} else { // 256 or 1296 shards per container
				if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
					$hashDirRegex = $char . '/(' . $char . '{2})';
				} else { // short hash dir format (e.g. "a/b/c")
					$hashDirRegex = '(' . $char . ')/(' . $char . ')';
				}
			}
			// Allow certain directories to be above the hash dirs so as
			// to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
			// They must be 2+ chars to avoid any hash directory ambiguity.
			$m = [];
			if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
				return '.' . implode( '', array_slice( $m, 1 ) );
			}

			return null; // failed to match
		}

		return ''; // no sharding
	}

	/**
	 * Check if a storage path maps to a single shard.
	 * Container dirs like "a", where the container shards on "x/xy",
	 * can reside on several shards. Such paths are tricky to handle.
	 *
	 * @param string $storagePath
	 * @return bool
	 */
	final public function isSingleShardPathInternal( $storagePath ) {
		[ , , $shard ] = $this->resolveStoragePath( $storagePath );

		return ( $shard !== null );
	}

	/**
	 * Get the sharding config for a container.
	 * If greater than 0, then all file storage paths within
	 * the container are required to be hashed accordingly.
	 *
	 * @param string $container
	 * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
	 */
	final protected function getContainerHashLevels( $container ) {
		if ( isset( $this->shardViaHashLevels[$container] ) ) {
			$config = $this->shardViaHashLevels[$container];
			$hashLevels = (int)$config['levels'];
			if ( $hashLevels == 1 || $hashLevels == 2 ) {
				$hashBase = (int)$config['base'];
				if ( $hashBase == 16 || $hashBase == 36 ) {
					return [ $hashLevels, $hashBase, $config['repeat'] ];
				}
			}
		}

		return [ 0, 0, false ]; // no sharding
	}

	/**
	 * Get a list of full container shard suffixes for a container
	 *
	 * @param string $container
	 * @return array
	 */
	final protected function getContainerSuffixes( $container ) {
		$shards = [];
		[ $digits, $base ] = $this->getContainerHashLevels( $container );
		if ( $digits > 0 ) {
			$numShards = $base ** $digits;
			for ( $index = 0; $index < $numShards; $index++ ) {
				$shards[] = '.' . Wikimedia\base_convert( (string)$index, 10, $base, $digits );
			}
		}

		return $shards;
	}

	/**
	 * Get the full container name, including the domain ID prefix
	 *
	 * @param string $container
	 * @return string
	 */
	final protected function fullContainerName( $container ) {
		if ( $this->domainId != '' ) {
			return "{$this->domainId}-$container";
		} else {
			return $container;
		}
	}

	/**
	 * Resolve a container name, checking if it's allowed by the backend.
	 * This is intended for internal use, such as encoding illegal chars.
	 * Subclasses can override this to be more restrictive.
	 * @stable to override
	 *
	 * @param string $container
	 * @return string|null
	 */
	protected function resolveContainerName( $container ) {
		return $container;
	}

	/**
	 * Resolve a relative storage path, checking if it's allowed by the backend.
	 * This is intended for internal use, such as encoding illegal chars or perhaps
	 * getting absolute paths (e.g. FS based backends). Note that the relative path
	 * may be the empty string (e.g. the path is simply to the container).
	 * @stable to override
	 *
	 * @param string $container Container name
	 * @param string $relStoragePath Storage path relative to the container
	 * @return string|null Path or null if not valid
	 */
	protected function resolveContainerPath( $container, $relStoragePath ) {
		return $relStoragePath;
	}

	/**
	 * Get the cache key for a container
	 *
	 * @param string $container Resolved container name
	 * @return string
	 */
	private function containerCacheKey( $container ) {
		return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
	}

	/**
	 * Set the cached info for a container
	 *
	 * @param string $container Resolved container name
	 * @param array $val Information to cache
	 */
	final protected function setContainerCache( $container, array $val ) {
		if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
			$this->logger->warning( "Unable to set stat cache for container {container}.",
				[ 'filebackend' => $this->name, 'container' => $container ]
			);
		}
	}

	/**
	 * Delete the cached info for a container.
	 * The cache key is salted for a while to prevent race conditions.
	 *
	 * @param string $container Resolved container name
	 */
	final protected function deleteContainerCache( $container ) {
		if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
			$this->logger->warning( "Unable to delete stat cache for container {container}.",
				[ 'filebackend' => $this->name, 'container' => $container ]
			);
		}
	}

	/**
	 * Do a batch lookup from cache for container stats for all containers
	 * used in a list of container names or storage paths objects.
	 * This loads the persistent cache values into the process cache.
	 *
	 * @param array $items
	 */
	final protected function primeContainerCache( array $items ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$paths = []; // list of storage paths
		$contNames = []; // (cache key => resolved container name)
		// Get all the paths/containers from the items...
		foreach ( $items as $item ) {
			if ( self::isStoragePath( $item ) ) {
				$paths[] = $item;
			} elseif ( is_string( $item ) ) { // full container name
				$contNames[$this->containerCacheKey( $item )] = $item;
			}
		}
		// Get all the corresponding cache keys for paths...
		foreach ( $paths as $path ) {
			[ $fullCont, , ] = $this->resolveStoragePath( $path );
			if ( $fullCont !== null ) { // valid path for this backend
				$contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
			}
		}

		$contInfo = []; // (resolved container name => cache value)
		// Get all cache entries for these container cache keys...
		$values = $this->memCache->getMulti( array_keys( $contNames ) );
		foreach ( $values as $cacheKey => $val ) {
			$contInfo[$contNames[$cacheKey]] = $val;
		}

		// Populate the container process cache for the backend...
		$this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
	}

	/**
	 * Fill the backend-specific process cache given an array of
	 * resolved container names and their corresponding cached info.
	 * Only containers that actually exist should appear in the map.
	 * @stable to override
	 *
	 * @param array $containerInfo Map of resolved container names to cached info
	 */
	protected function doPrimeContainerCache( array $containerInfo ) {
	}

	/**
	 * Get the cache key for a file path
	 *
	 * @param string $path Normalized storage path
	 * @return string
	 */
	private function fileCacheKey( $path ) {
		return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
	}

	/**
	 * Set the cached stat info for a file path.
	 * Negatives (404s) are not cached. By not caching negatives, we can skip cache
	 * salting for the case when a file is created at a path were there was none before.
	 *
	 * @param string $path Storage path
	 * @param array $val Stat information to cache
	 */
	final protected function setFileCache( $path, array $val ) {
		$path = FileBackend::normalizeStoragePath( $path );
		if ( $path === null ) {
			return; // invalid storage path
		}
		$mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
		$ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
		$key = $this->fileCacheKey( $path );
		// Set the cache unless it is currently salted.
		if ( !$this->memCache->set( $key, $val, $ttl ) ) {
			$this->logger->warning( "Unable to set stat cache for file {path}.",
				[ 'filebackend' => $this->name, 'path' => $path ]
			);
		}
	}

	/**
	 * Delete the cached stat info for a file path.
	 * The cache key is salted for a while to prevent race conditions.
	 * Since negatives (404s) are not cached, this does not need to be called when
	 * a file is created at a path were there was none before.
	 *
	 * @param string $path Storage path
	 */
	final protected function deleteFileCache( $path ) {
		$path = FileBackend::normalizeStoragePath( $path );
		if ( $path === null ) {
			return; // invalid storage path
		}
		if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
			$this->logger->warning( "Unable to delete stat cache for file {path}.",
				[ 'filebackend' => $this->name, 'path' => $path ]
			);
		}
	}

	/**
	 * Do a batch lookup from cache for file stats for all paths
	 * used in a list of storage paths or FileOp objects.
	 * This loads the persistent cache values into the process cache.
	 *
	 * @param array $items List of storage paths
	 */
	final protected function primeFileCache( array $items ) {
		/** @noinspection PhpUnusedLocalVariableInspection */
		$ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );

		$paths = []; // list of storage paths
		$pathNames = []; // (cache key => storage path)
		// Get all the paths/containers from the items...
		foreach ( $items as $item ) {
			if ( self::isStoragePath( $item ) ) {
				$path = FileBackend::normalizeStoragePath( $item );
				if ( $path !== null ) {
					$paths[] = $path;
				}
			}
		}
		// Get all the corresponding cache keys for paths...
		foreach ( $paths as $path ) {
			[ , $rel, ] = $this->resolveStoragePath( $path );
			if ( $rel !== null ) { // valid path for this backend
				$pathNames[$this->fileCacheKey( $path )] = $path;
			}
		}
		// Get all cache entries for these file cache keys.
		// Note that negatives are not cached by getFileStat()/preloadFileStat().
		$values = $this->memCache->getMulti( array_keys( $pathNames ) );
		// Load all of the results into process cache...
		foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
			$path = $pathNames[$cacheKey];
			// This flag only applies to stat info loaded directly
			// from a high consistency backend query to the process cache
			unset( $stat['latest'] );

			$this->cheapCache->setField( $path, 'stat', $stat );
			if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
				// Some backends store SHA-1 as metadata
				$this->cheapCache->setField(
					$path,
					'sha1',
					[ 'hash' => $stat['sha1'], 'latest' => false ]
				);
			}
			if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
				// Some backends store custom headers/metadata
				$stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
				$this->cheapCache->setField(
					$path,
					'xattr',
					[ 'map' => $stat['xattr'], 'latest' => false ]
				);
			}
		}
	}

	/**
	 * Normalize file headers/metadata to the FileBackend::getFileXAttributes() format
	 *
	 * @param array $xattr
	 * @return array
	 * @since 1.22
	 */
	final protected static function normalizeXAttributes( array $xattr ) {
		$newXAttr = [ 'headers' => [], 'metadata' => [] ];

		foreach ( $xattr['headers'] as $name => $value ) {
			$newXAttr['headers'][strtolower( $name )] = $value;
		}

		foreach ( $xattr['metadata'] as $name => $value ) {
			$newXAttr['metadata'][strtolower( $name )] = $value;
		}

		return $newXAttr;
	}

	/**
	 * Set the 'concurrency' option from a list of operation options
	 *
	 * @param array $opts Map of operation options
	 * @return array
	 */
	final protected function setConcurrencyFlags( array $opts ) {
		$opts['concurrency'] = 1; // off
		if ( $this->parallelize === 'implicit' ) {
			if ( $opts['parallelize'] ?? true ) {
				$opts['concurrency'] = $this->concurrency;
			}
		} elseif ( $this->parallelize === 'explicit' ) {
			if ( !empty( $opts['parallelize'] ) ) {
				$opts['concurrency'] = $this->concurrency;
			}
		}

		return $opts;
	}

	/**
	 * Get the content type to use in HEAD/GET requests for a file
	 * @stable to override
	 *
	 * @param string $storagePath
	 * @param string|null $content File data
	 * @param string|null $fsPath File system path
	 * @return string MIME type
	 */
	protected function getContentType( $storagePath, $content, $fsPath ) {
		if ( $this->mimeCallback ) {
			return call_user_func_array( $this->mimeCallback, func_get_args() );
		}

		$mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
		return $mime ?: 'unknown/unknown';
	}
}