Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
68.19% covered (warning)
68.19%
476 / 698
47.44% covered (danger)
47.44%
37 / 78
CRAP
0.00% covered (danger)
0.00%
0 / 1
FileBackendStore
68.29% covered (warning)
68.29%
476 / 697
47.44% covered (danger)
47.44%
37 / 78
2722.90
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 maxFileSizeInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isPathUsableInternal
n/a
0 / 0
n/a
0 / 0
0
 createInternal
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 doCreateInternal
n/a
0 / 0
n/a
0 / 0
0
 storeInternal
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 doStoreInternal
n/a
0 / 0
n/a
0 / 0
0
 copyInternal
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 doCopyInternal
n/a
0 / 0
n/a
0 / 0
0
 deleteInternal
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 doDeleteInternal
n/a
0 / 0
n/a
0 / 0
0
 moveInternal
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 doMoveInternal
n/a
0 / 0
n/a
0 / 0
0
 describeInternal
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 doDescribeInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 nullInternal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 concatenate
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 doConcatenate
53.85% covered (warning)
53.85%
21 / 39
0.00% covered (danger)
0.00%
0 / 1
26.16
 doPrepare
66.67% covered (warning)
66.67%
8 / 12
0.00% covered (danger)
0.00%
0 / 1
4.59
 doPrepareInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doSecure
50.00% covered (danger)
50.00%
6 / 12
0.00% covered (danger)
0.00%
0 / 1
6.00
 doSecureInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doPublish
50.00% covered (danger)
50.00%
6 / 12
0.00% covered (danger)
0.00%
0 / 1
6.00
 doPublishInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doClean
68.00% covered (warning)
68.00%
17 / 25
0.00% covered (danger)
0.00%
0 / 1
11.65
 doCleanInternal
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 fileExists
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getFileTimestamp
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getFileSize
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getFileStat
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
17
 ingestFreshFileStats
75.56% covered (warning)
75.56%
34 / 45
0.00% covered (danger)
0.00%
0 / 1
7.72
 doGetFileStat
n/a
0 / 0
n/a
0 / 0
0
 getFileContentsMulti
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 doGetFileContentsMulti
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 getFileXAttributes
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
56
 doGetFileXAttributes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getFileSha1Base36
65.22% covered (warning)
65.22%
15 / 23
0.00% covered (danger)
0.00%
0 / 1
9.06
 doGetFileSha1Base36
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 getFileProps
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 getLocalReferenceMulti
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
8
 doGetLocalReferenceMulti
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLocalCopyMulti
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 doGetLocalCopyMulti
n/a
0 / 0
n/a
0 / 0
0
 getFileHttpUrl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addShellboxInputFile
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
3.10
 streamFile
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
4.59
 doStreamFile
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
5
 directoryExists
25.00% covered (danger)
25.00%
4 / 16
0.00% covered (danger)
0.00%
0 / 1
21.19
 doDirectoryExists
n/a
0 / 0
n/a
0 / 0
0
 getDirectoryList
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
4.54
 getDirectoryListInternal
n/a
0 / 0
n/a
0 / 0
0
 getFileList
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
3.79
 getFileListInternal
n/a
0 / 0
n/a
0 / 0
0
 getOperationsInternal
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
3.00
 getPathsToLockForOpsInternal
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 getScopedLocksForOps
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 doOperationsInternal
75.00% covered (warning)
75.00%
24 / 32
0.00% covered (danger)
0.00%
0 / 1
7.77
 doQuickOperationsInternal
75.00% covered (warning)
75.00%
24 / 32
0.00% covered (danger)
0.00%
0 / 1
11.56
 executeOpHandlesInternal
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
9.29
 doExecuteOpHandlesInternal
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 sanitizeOpHeaders
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 preloadCache
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 clearCache
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
4.13
 doClearCache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 preloadFileStat
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 doGetFileStatMulti
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 directoriesAreVirtual
n/a
0 / 0
n/a
0 / 0
0
 isValidShortContainerName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isValidContainerName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolveStoragePath
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
8
 resolveStoragePathReal
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getContainerShard
23.08% covered (danger)
23.08%
3 / 13
0.00% covered (danger)
0.00%
0 / 1
29.30
 isSingleShardPathInternal
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getContainerHashLevels
25.00% covered (danger)
25.00%
2 / 8
0.00% covered (danger)
0.00%
0 / 1
21.19
 getContainerSuffixes
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 fullContainerName
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 resolveContainerName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolveContainerPath
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 containerCacheKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setContainerCache
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 deleteContainerCache
25.00% covered (danger)
25.00%
1 / 4
0.00% covered (danger)
0.00%
0 / 1
3.69
 primeContainerCache
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
7.01
 doPrimeContainerCache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 fileCacheKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setFileCache
42.86% covered (danger)
42.86%
3 / 7
0.00% covered (danger)
0.00%
0 / 1
4.68
 deleteFileCache
42.86% covered (danger)
42.86%
3 / 7
0.00% covered (danger)
0.00%
0 / 1
4.68
 primeFileCache
44.83% covered (danger)
44.83%
13 / 29
0.00% covered (danger)
0.00%
0 / 1
31.32
 normalizeXAttributes
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 setConcurrencyFlags
50.00% covered (danger)
50.00%
4 / 8
0.00% covered (danger)
0.00%
0 / 1
8.12
 getContentType
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Base class for all backends using particular storage medium.
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 * @ingroup FileBackend
8 */
9
10namespace Wikimedia\FileBackend;
11
12use InvalidArgumentException;
13use Shellbox\Command\BoxedCommand;
14use StatusValue;
15use Traversable;
16use Wikimedia\FileBackend\FileIteration\FileBackendStoreShardDirIterator;
17use Wikimedia\FileBackend\FileIteration\FileBackendStoreShardFileIterator;
18use Wikimedia\FileBackend\FileOpHandle\FileBackendStoreOpHandle;
19use Wikimedia\FileBackend\FileOps\CopyFileOp;
20use Wikimedia\FileBackend\FileOps\CreateFileOp;
21use Wikimedia\FileBackend\FileOps\DeleteFileOp;
22use Wikimedia\FileBackend\FileOps\DescribeFileOp;
23use Wikimedia\FileBackend\FileOps\FileOp;
24use Wikimedia\FileBackend\FileOps\MoveFileOp;
25use Wikimedia\FileBackend\FileOps\NullFileOp;
26use Wikimedia\FileBackend\FileOps\StoreFileOp;
27use Wikimedia\FileBackend\FSFile\FSFile;
28use Wikimedia\Http\HttpHeader;
29use Wikimedia\LockManager\LockManager;
30use Wikimedia\ObjectCache\BagOStuff;
31use Wikimedia\ObjectCache\EmptyBagOStuff;
32use Wikimedia\ObjectCache\MapCacheLRU;
33use Wikimedia\ObjectCache\WANObjectCache;
34
35/**
36 * @brief Base class for all backends using particular storage medium.
37 *
38 * This class defines the methods as abstract that subclasses must implement.
39 * Outside callers should *not* use functions with "Internal" in the name.
40 *
41 * The FileBackend operations are implemented using basic functions
42 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
43 * This class is also responsible for path resolution and sanitization.
44 *
45 * @stable to extend
46 * @ingroup FileBackend
47 * @since 1.19
48 */
49abstract class FileBackendStore extends FileBackend {
50    /** Persistent cache accessible to all relevant datacenters */
51    protected WANObjectCache $wanCache;
52    /** Persistent local server/host cache (e.g. APCu) */
53    protected BagOStuff $srvCache;
54    /** LRU map of file paths to small (RAM/disk) cache items */
55    protected MapCacheLRU $procFileStatCache;
56    /** @deprecated Since 1.47 */
57    protected MapCacheLRU $cheapCache;
58    /** LRU map of file paths to large (RAM/disk) cache items */
59    protected MapCacheLRU $procFileDataCache;
60    /** @deprecated Since 1.47 */
61    protected MapCacheLRU $expensiveCache;
62
63    /** Cache used for persistent file/container stat entries */
64    protected WANObjectCache $wanStatCache;
65    /** @deprecated Since 1.47 */
66    protected $memCache;
67
68    /** @var array<string,array> Map of container names to sharding config */
69    protected $shardViaHashLevels = [];
70
71    /** @var callable|null Method to get the MIME type of files */
72    protected $mimeCallback;
73
74    /** @var int Size in bytes, defaults to 32 GiB */
75    protected $maxFileSize = 32 * 1024 * 1024 * 1024;
76
77    protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
78    protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
79    protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
80
81    /** @var false Idiom for "no result due to missing file" (since 1.34) */
82    protected const RES_ABSENT = false;
83    /** @var null Idiom for "no result due to I/O errors" (since 1.34) */
84    protected const RES_ERROR = null;
85
86    /** @var string File does not exist according to a normal stat query */
87    protected const ABSENT_NORMAL = 'FNE-N';
88    /** @var string File does not exist according to a "latest"-mode stat query */
89    protected const ABSENT_LATEST = 'FNE-L';
90
91    /**
92     * @see FileBackend::__construct()
93     * Additional $config params include:
94     *   - srvCache     : BagOStuff object to use for server-local persistent caching.
95     *   - wanCache     : WANObjectCache object to use for server-shared persistent caching.
96     *   - mimeCallback : Callback that takes (storage path, content, file system path) and
97     *                    returns the MIME type of the file or 'unknown/unknown'. The file
98     *                    system path parameter should be used if the content one is null.
99     *
100     * @stable to call
101     *
102     * @param array $config
103     */
104    public function __construct( array $config ) {
105        parent::__construct( $config );
106        $this->mimeCallback = $config['mimeCallback'] ?? null;
107        $this->srvCache = $config['srvCache'] ?? new EmptyBagOStuff();
108        $this->wanCache = $config['wanCache'] ?? WANObjectCache::newEmpty();
109        $this->wanStatCache = WANObjectCache::newEmpty(); // disabled by default
110        $this->memCache =& $this->wanStatCache; // compatibility alias
111        $this->procFileStatCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
112        $this->cheapCache =& $this->procFileStatCache; // compatability alias
113        $this->procFileDataCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
114        $this->expensiveCache =& $this->procFileDataCache; // compatability alias
115    }
116
117    /**
118     * Get the maximum allowable file size given backend
119     * medium restrictions and basic performance constraints.
120     * Do not call this function from places outside FileBackend and FileOp.
121     *
122     * @return int Bytes
123     */
124    final public function maxFileSizeInternal() {
125        return min( $this->maxFileSize, PHP_INT_MAX );
126    }
127
128    /**
129     * Check if a file can be created or changed at a given storage path in the backend
130     *
131     * This quickly checks to see if the path is already prepared for use to store files.
132     * FS backends should check that the parent directory exists and that files can be written
133     * to it for the current system user. Backends using key/value stores should check if the
134     * container exists and that objects can be written to it for the configured account/user.
135     *
136     * @param string $storagePath
137     * @return bool
138     */
139    abstract public function isPathUsableInternal( $storagePath );
140
141    /**
142     * Create a file in the backend with the given contents.
143     * This will overwrite any file that exists at the destination.
144     * Do not call this function from places outside FileBackend and FileOp.
145     *
146     * $params include:
147     *   - content     : the raw file contents
148     *   - dst         : destination storage path
149     *   - headers     : HTTP header name/value map
150     *   - async       : StatusValue will be returned immediately if supported.
151     *                   If the StatusValue is OK, then its value field will be
152     *                   set to a FileBackendStoreOpHandle object.
153     *   - dstExists   : Whether a file exists at the destination (optimization).
154     *                   Callers can use "false" if no existing file is being changed.
155     *
156     * @param array $params
157     * @return StatusValue
158     */
159    final public function createInternal( array $params ) {
160        if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
161            $status = $this->newStatus( 'backend-fail-maxsize',
162                $params['dst'], $this->maxFileSizeInternal() );
163        } else {
164            $status = $this->doCreateInternal( $params );
165            $this->clearCache( [ $params['dst'] ] );
166            if ( $params['dstExists'] ?? true ) {
167                $this->deleteFileCache( $params['dst'] ); // persistent cache
168            }
169        }
170
171        return $status;
172    }
173
174    /**
175     * @see FileBackendStore::createInternal()
176     * @param array $params
177     * @return StatusValue
178     */
179    abstract protected function doCreateInternal( array $params );
180
181    /**
182     * Store a file into the backend from a file on disk.
183     * This will overwrite any file that exists at the destination.
184     * Do not call this function from places outside FileBackend and FileOp.
185     *
186     * $params include:
187     *   - src         : source path on disk
188     *   - dst         : destination storage path
189     *   - headers     : HTTP header name/value map
190     *   - async       : StatusValue will be returned immediately if supported.
191     *                   If the StatusValue is OK, then its value field will be
192     *                   set to a FileBackendStoreOpHandle object.
193     *   - dstExists   : Whether a file exists at the destination (optimization).
194     *                   Callers can use "false" if no existing file is being changed.
195     *
196     * @param array $params
197     * @return StatusValue
198     */
199    final public function storeInternal( array $params ) {
200        if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
201            $status = $this->newStatus( 'backend-fail-maxsize',
202                $params['dst'], $this->maxFileSizeInternal() );
203        } else {
204            $status = $this->doStoreInternal( $params );
205            $this->clearCache( [ $params['dst'] ] );
206            if ( $params['dstExists'] ?? true ) {
207                $this->deleteFileCache( $params['dst'] ); // persistent cache
208            }
209        }
210
211        return $status;
212    }
213
214    /**
215     * @see FileBackendStore::storeInternal()
216     * @param array $params
217     * @return StatusValue
218     */
219    abstract protected function doStoreInternal( array $params );
220
221    /**
222     * Copy a file from one storage path to another in the backend.
223     * This will overwrite any file that exists at the destination.
224     * Do not call this function from places outside FileBackend and FileOp.
225     *
226     * $params include:
227     *   - src                 : source storage path
228     *   - dst                 : destination storage path
229     *   - ignoreMissingSource : do nothing if the source file does not exist
230     *   - headers             : HTTP header name/value map
231     *   - async               : StatusValue will be returned immediately if supported.
232     *                           If the StatusValue is OK, then its value field will be
233     *                           set to a FileBackendStoreOpHandle object.
234     *   - dstExists           : Whether a file exists at the destination (optimization).
235     *                           Callers can use "false" if no existing file is being changed.
236     *
237     * @param array $params
238     * @return StatusValue
239     */
240    final public function copyInternal( array $params ) {
241        $status = $this->doCopyInternal( $params );
242        $this->clearCache( [ $params['dst'] ] );
243        if ( $params['dstExists'] ?? true ) {
244            $this->deleteFileCache( $params['dst'] ); // persistent cache
245        }
246
247        return $status;
248    }
249
250    /**
251     * @see FileBackendStore::copyInternal()
252     * @param array $params
253     * @return StatusValue
254     */
255    abstract protected function doCopyInternal( array $params );
256
257    /**
258     * Delete a file at the storage path.
259     * Do not call this function from places outside FileBackend and FileOp.
260     *
261     * $params include:
262     *   - src                 : source storage path
263     *   - ignoreMissingSource : do nothing if the source file does not exist
264     *   - async               : StatusValue will be returned immediately if supported.
265     *                           If the StatusValue is OK, then its value field will be
266     *                           set to a FileBackendStoreOpHandle object.
267     *
268     * @param array $params
269     * @return StatusValue
270     */
271    final public function deleteInternal( array $params ) {
272        $status = $this->doDeleteInternal( $params );
273        $this->clearCache( [ $params['src'] ] );
274        $this->deleteFileCache( $params['src'] ); // persistent cache
275        return $status;
276    }
277
278    /**
279     * @see FileBackendStore::deleteInternal()
280     * @param array $params
281     * @return StatusValue
282     */
283    abstract protected function doDeleteInternal( array $params );
284
285    /**
286     * Move a file from one storage path to another in the backend.
287     * This will overwrite any file that exists at the destination.
288     * Do not call this function from places outside FileBackend and FileOp.
289     *
290     * $params include:
291     *   - src                 : source storage path
292     *   - dst                 : destination storage path
293     *   - ignoreMissingSource : do nothing if the source file does not exist
294     *   - headers             : HTTP header name/value map
295     *   - async               : StatusValue will be returned immediately if supported.
296     *                           If the StatusValue is OK, then its value field will be
297     *                           set to a FileBackendStoreOpHandle object.
298     *   - dstExists           : Whether a file exists at the destination (optimization).
299     *                           Callers can use "false" if no existing file is being changed.
300     *
301     * @param array $params
302     * @return StatusValue
303     */
304    final public function moveInternal( array $params ) {
305        $status = $this->doMoveInternal( $params );
306        $this->clearCache( [ $params['src'], $params['dst'] ] );
307        $this->deleteFileCache( $params['src'] ); // persistent cache
308        if ( $params['dstExists'] ?? true ) {
309            $this->deleteFileCache( $params['dst'] ); // persistent cache
310        }
311
312        return $status;
313    }
314
315    /**
316     * @see FileBackendStore::moveInternal()
317     * @param array $params
318     * @return StatusValue
319     */
320    abstract protected function doMoveInternal( array $params );
321
322    /**
323     * Alter metadata for a file at the storage path.
324     * Do not call this function from places outside FileBackend and FileOp.
325     *
326     * $params include:
327     *   - src           : source storage path
328     *   - headers       : HTTP header name/value map
329     *   - async         : StatusValue will be returned immediately if supported.
330     *                     If the StatusValue is OK, then its value field will be
331     *                     set to a FileBackendStoreOpHandle object.
332     *
333     * @param array $params
334     * @return StatusValue
335     */
336    final public function describeInternal( array $params ) {
337        if ( count( $params['headers'] ) ) {
338            $status = $this->doDescribeInternal( $params );
339            $this->clearCache( [ $params['src'] ] );
340            $this->deleteFileCache( $params['src'] ); // persistent cache
341        } else {
342            $status = $this->newStatus(); // nothing to do
343        }
344
345        return $status;
346    }
347
348    /**
349     * @see FileBackendStore::describeInternal()
350     * @stable to override
351     * @param array $params
352     * @return StatusValue
353     */
354    protected function doDescribeInternal( array $params ) {
355        return $this->newStatus();
356    }
357
358    /**
359     * No-op file operation that does nothing.
360     * Do not call this function from places outside FileBackend and FileOp.
361     *
362     * @param array $params
363     * @return StatusValue
364     */
365    final public function nullInternal( array $params ) {
366        return $this->newStatus();
367    }
368
369    /** @inheritDoc */
370    final public function concatenate( array $params ) {
371        $status = $this->newStatus();
372        // Try to lock the source files for the scope of this function
373        /** @noinspection PhpUnusedLocalVariableInspection */
374        $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
375        if ( $status->isOK() ) {
376            // Actually do the file concatenation...
377            $hrStart = hrtime( true );
378            $status->merge( $this->doConcatenate( $params ) );
379            $sec = ( hrtime( true ) - $hrStart ) / 1e9;
380            if ( !$status->isOK() ) {
381                $this->logger->error( static::class . "-{$this->name}" .
382                    " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
383            }
384        }
385
386        return $status;
387    }
388
389    /**
390     * @see FileBackendStore::concatenate()
391     * @stable to override
392     * @param array $params
393     * @return StatusValue
394     */
395    protected function doConcatenate( array $params ) {
396        $status = $this->newStatus();
397        $tmpPath = $params['dst'];
398        unset( $params['latest'] );
399
400        // Check that the specified temp file is valid...
401        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
402        $ok = ( @is_file( $tmpPath ) && @filesize( $tmpPath ) == 0 );
403        if ( !$ok ) { // not present or not empty
404            $status->fatal( 'backend-fail-opentemp', $tmpPath );
405
406            return $status;
407        }
408
409        // Get local FS versions of the chunks needed for the concatenation...
410        $fsFiles = $this->getLocalReferenceMulti( $params );
411        foreach ( $fsFiles as $path => &$fsFile ) {
412            if ( !$fsFile ) { // chunk failed to download?
413                $fsFile = $this->getLocalReference( [ 'src' => $path ] );
414                if ( !$fsFile ) { // retry failed?
415                    $status->fatal(
416                        $fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
417                        $path
418                    );
419
420                    return $status;
421                }
422            }
423        }
424        unset( $fsFile ); // unset reference so we can reuse $fsFile
425
426        // Get a handle for the destination temp file
427        $tmpHandle = fopen( $tmpPath, 'ab' );
428        if ( $tmpHandle === false ) {
429            $status->fatal( 'backend-fail-opentemp', $tmpPath );
430
431            return $status;
432        }
433
434        // Build up the temp file using the source chunks (in order)...
435        foreach ( $fsFiles as $virtualSource => $fsFile ) {
436            // Get a handle to the local FS version
437            $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
438            if ( $sourceHandle === false ) {
439                fclose( $tmpHandle );
440                $status->fatal( 'backend-fail-read', $virtualSource );
441
442                return $status;
443            }
444            // Append chunk to file (pass chunk size to avoid magic quotes)
445            if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
446                fclose( $sourceHandle );
447                fclose( $tmpHandle );
448                $status->fatal( 'backend-fail-writetemp', $tmpPath );
449
450                return $status;
451            }
452            fclose( $sourceHandle );
453        }
454        if ( !fclose( $tmpHandle ) ) {
455            $status->fatal( 'backend-fail-closetemp', $tmpPath );
456
457            return $status;
458        }
459
460        clearstatcache(); // temp file changed
461
462        return $status;
463    }
464
465    /**
466     * @inheritDoc
467     */
468    final protected function doPrepare( array $params ) {
469        $status = $this->newStatus();
470
471        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
472        if ( $dir === null ) {
473            $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
474
475            return $status; // invalid storage path
476        }
477
478        if ( $shard !== null ) { // confined to a single container/shard
479            $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
480        } else { // directory is on several shards
481            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
482            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
483            foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
484                $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
485            }
486        }
487
488        return $status;
489    }
490
491    /**
492     * @see FileBackendStore::doPrepare()
493     * @stable to override
494     * @param string $fullCont
495     * @param string $dirRel
496     * @param array $params
497     * @return StatusValue Good status without value for success, fatal otherwise.
498     */
499    protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
500        return $this->newStatus();
501    }
502
503    /** @inheritDoc */
504    final protected function doSecure( array $params ) {
505        $status = $this->newStatus();
506
507        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
508        if ( $dir === null ) {
509            $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
510
511            return $status; // invalid storage path
512        }
513
514        if ( $shard !== null ) { // confined to a single container/shard
515            $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
516        } else { // directory is on several shards
517            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
518            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
519            foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
520                $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
521            }
522        }
523
524        return $status;
525    }
526
527    /**
528     * @see FileBackendStore::doSecure()
529     * @stable to override
530     * @param string $fullCont
531     * @param string $dirRel
532     * @param array $params
533     * @return StatusValue Good status without value for success, fatal otherwise.
534     */
535    protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
536        return $this->newStatus();
537    }
538
539    /** @inheritDoc */
540    final protected function doPublish( array $params ) {
541        $status = $this->newStatus();
542
543        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
544        if ( $dir === null ) {
545            $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
546
547            return $status; // invalid storage path
548        }
549
550        if ( $shard !== null ) { // confined to a single container/shard
551            $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
552        } else { // directory is on several shards
553            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
554            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
555            foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
556                $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
557            }
558        }
559
560        return $status;
561    }
562
563    /**
564     * @see FileBackendStore::doPublish()
565     * @stable to override
566     * @param string $fullCont
567     * @param string $dirRel
568     * @param array $params
569     * @return StatusValue
570     */
571    protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
572        return $this->newStatus();
573    }
574
575    /** @inheritDoc */
576    final protected function doClean( array $params ) {
577        $status = $this->newStatus();
578
579        // Recursive: first delete all empty subdirs recursively
580        if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
581            $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
582            if ( $subDirsRel !== null ) { // no errors
583                foreach ( $subDirsRel as $subDirRel ) {
584                    $subDir = $params['dir'] . "/{$subDirRel}"; // full path
585                    $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
586                }
587                unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
588            }
589        }
590
591        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
592        if ( $dir === null ) {
593            $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
594
595            return $status; // invalid storage path
596        }
597
598        // Attempt to lock this directory...
599        $filesLockEx = [ $params['dir'] ];
600        /** @noinspection PhpUnusedLocalVariableInspection */
601        $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
602        if ( !$status->isOK() ) {
603            return $status; // abort
604        }
605
606        if ( $shard !== null ) { // confined to a single container/shard
607            $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
608            $this->deleteContainerCache( $fullCont ); // purge cache
609        } else { // directory is on several shards
610            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
611            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
612            foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
613                $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
614                $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
615            }
616        }
617
618        return $status;
619    }
620
621    /**
622     * @see FileBackendStore::doClean()
623     * @stable to override
624     * @param string $fullCont
625     * @param string $dirRel
626     * @param array $params
627     * @return StatusValue
628     */
629    protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
630        return $this->newStatus();
631    }
632
633    /** @inheritDoc */
634    final public function fileExists( array $params ) {
635        $stat = $this->getFileStat( $params );
636        if ( is_array( $stat ) ) {
637            return true;
638        }
639
640        return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
641    }
642
643    /** @inheritDoc */
644    final public function getFileTimestamp( array $params ) {
645        $stat = $this->getFileStat( $params );
646        if ( is_array( $stat ) ) {
647            return $stat['mtime'];
648        }
649
650        return self::TIMESTAMP_FAIL; // all failure cases
651    }
652
653    /** @inheritDoc */
654    final public function getFileSize( array $params ) {
655        $stat = $this->getFileStat( $params );
656        if ( is_array( $stat ) ) {
657            return $stat['size'];
658        }
659
660        return self::SIZE_FAIL; // all failure cases
661    }
662
663    /** @inheritDoc */
664    final public function getFileStat( array $params ) {
665        $path = self::normalizeStoragePath( $params['src'] );
666        if ( $path === null ) {
667            return self::STAT_ERROR; // invalid storage path
668        }
669
670        // Whether to bypass cache except for process cache entries loaded directly from
671        // high consistency backend queries (caller handles any cache flushing and locking)
672        $latest = !empty( $params['latest'] );
673        // Whether to ignore cache entries missing the SHA-1 field for existing files
674        $requireSHA1 = !empty( $params['requireSHA1'] );
675
676        $stat = $this->procFileStatCache->getField( $path, 'stat', self::CACHE_TTL );
677        // Load the persistent stat cache into process cache if needed
678        if ( !$latest ) {
679            if (
680                // File stat is not in process cache
681                $stat === null ||
682                // Key/value store backends might opportunistically set file stat process
683                // cache entries from object listings that do not include the SHA-1. In that
684                // case, loading the persistent stat cache will likely yield the SHA-1.
685                ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
686            ) {
687                $this->primeFileCache( [ $path ] );
688                // Get any newly process-cached entry
689                $stat = $this->procFileStatCache->getField( $path, 'stat', self::CACHE_TTL );
690            }
691        }
692
693        if ( is_array( $stat ) ) {
694            if (
695                ( !$latest || !empty( $stat['latest'] ) ) &&
696                ( !$requireSHA1 || isset( $stat['sha1'] ) )
697            ) {
698                return $stat;
699            }
700        } elseif ( $stat === self::ABSENT_LATEST ) {
701            return self::STAT_ABSENT;
702        } elseif ( $stat === self::ABSENT_NORMAL ) {
703            if ( !$latest ) {
704                return self::STAT_ABSENT;
705            }
706        }
707
708        // Load the file stat from the backend and update caches
709        $stat = $this->doGetFileStat( $params );
710        $this->ingestFreshFileStats( [ $path => $stat ], $latest );
711
712        if ( is_array( $stat ) ) {
713            return $stat;
714        }
715
716        return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
717    }
718
719    /**
720     * Ingest file stat entries that just came from querying the backend (not cache)
721     *
722     * @param array<string,array|false|null> $stats Map of storage path => {@see doGetFileStat} result
723     * @param bool $latest Whether doGetFileStat()/doGetFileStatMulti() had the 'latest' flag
724     * @return bool Whether all files have non-error stat replies
725     */
726    final protected function ingestFreshFileStats( array $stats, $latest ) {
727        $success = true;
728
729        foreach ( $stats as $path => $stat ) {
730            if ( is_array( $stat ) ) {
731                // Strongly consistent backends might automatically set this flag
732                $stat['latest'] ??= $latest;
733
734                $this->procFileStatCache->setField( $path, 'stat', $stat );
735                if ( isset( $stat['sha1'] ) ) {
736                    // Some backends store the SHA-1 hash as metadata
737                    $this->procFileStatCache->setField(
738                        $path,
739                        'sha1',
740                        [ 'hash' => $stat['sha1'], 'latest' => $latest ]
741                    );
742                }
743                if ( isset( $stat['xattr'] ) ) {
744                    // Some backends store custom headers/metadata
745                    $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
746                    $this->procFileStatCache->setField(
747                        $path,
748                        'xattr',
749                        [ 'map' => $stat['xattr'], 'latest' => $latest ]
750                    );
751                }
752                // Update persistent cache (@TODO: set all entries in one batch)
753                $this->setFileCache( $path, $stat );
754            } elseif ( $stat === self::RES_ABSENT ) {
755                $this->procFileStatCache->setField(
756                    $path,
757                    'stat',
758                    $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
759                );
760                $this->procFileStatCache->setField(
761                    $path,
762                    'xattr',
763                    [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
764                );
765                $this->procFileStatCache->setField(
766                    $path,
767                    'sha1',
768                    [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
769                );
770                $this->logger->debug(
771                    __METHOD__ . ': File {path} does not exist',
772                    [ 'path' => $path ]
773                );
774            } else {
775                $success = false;
776                $this->logger->error(
777                    __METHOD__ . ': Could not stat file {path}',
778                    [ 'path' => $path ]
779                );
780            }
781        }
782
783        return $success;
784    }
785
786    /**
787     * @see FileBackendStore::getFileStat()
788     * @param array $params
789     * @return array|false|null
790     */
791    abstract protected function doGetFileStat( array $params );
792
793    /** @inheritDoc */
794    public function getFileContentsMulti( array $params ) {
795        $params = $this->setConcurrencyFlags( $params );
796        $contents = $this->doGetFileContentsMulti( $params );
797        foreach ( $contents as $path => $content ) {
798            if ( !is_string( $content ) ) {
799                $contents[$path] = self::CONTENT_FAIL; // used for all failure cases
800            }
801        }
802
803        return $contents;
804    }
805
806    /**
807     * @see FileBackendStore::getFileContentsMulti()
808     * @stable to override
809     * @param array $params
810     * @return string[]|bool[]|null[] Map of (path => string, false (missing), or null (error))
811     */
812    protected function doGetFileContentsMulti( array $params ) {
813        $contents = [];
814        foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
815            if ( $fsFile instanceof FSFile ) {
816                // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
817                $content = @file_get_contents( $fsFile->getPath() );
818                $contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
819            } else {
820                // self::RES_ERROR or self::RES_ABSENT
821                $contents[$path] = $fsFile;
822            }
823        }
824
825        return $contents;
826    }
827
828    /** @inheritDoc */
829    final public function getFileXAttributes( array $params ) {
830        $path = self::normalizeStoragePath( $params['src'] );
831        if ( $path === null ) {
832            return self::XATTRS_FAIL; // invalid storage path
833        }
834        $latest = !empty( $params['latest'] ); // use latest data?
835        if ( $this->procFileStatCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
836            $stat = $this->procFileStatCache->getField( $path, 'xattr' );
837            // If we want the latest data, check that this cached
838            // value was in fact fetched with the latest available data.
839            if ( !$latest || $stat['latest'] ) {
840                return $stat['map'];
841            }
842        }
843        $fields = $this->doGetFileXAttributes( $params );
844        if ( is_array( $fields ) ) {
845            $fields = self::normalizeXAttributes( $fields );
846            $this->procFileStatCache->setField(
847                $path,
848                'xattr',
849                [ 'map' => $fields, 'latest' => $latest ]
850            );
851        } elseif ( $fields === self::RES_ABSENT ) {
852            $this->procFileStatCache->setField(
853                $path,
854                'xattr',
855                [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
856            );
857        } else {
858            $fields = self::XATTRS_FAIL; // used for all failure cases
859        }
860
861        return $fields;
862    }
863
864    /**
865     * @see FileBackendStore::getFileXAttributes()
866     * @stable to override
867     * @param array $params
868     * @return array[][]|false|null Attributes, false (missing file), or null (error)
869     */
870    protected function doGetFileXAttributes( array $params ) {
871        return [ 'headers' => [], 'metadata' => [] ]; // not supported
872    }
873
874    /** @inheritDoc */
875    final public function getFileSha1Base36( array $params ) {
876        $path = self::normalizeStoragePath( $params['src'] );
877        if ( $path === null ) {
878            return self::SHA1_FAIL; // invalid storage path
879        }
880        $latest = !empty( $params['latest'] ); // use latest data?
881        if ( $this->procFileStatCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
882            $stat = $this->procFileStatCache->getField( $path, 'sha1' );
883            // If we want the latest data, check that this cached
884            // value was in fact fetched with the latest available data.
885            if ( !$latest || $stat['latest'] ) {
886                return $stat['hash'];
887            }
888        }
889        $sha1 = $this->doGetFileSha1Base36( $params );
890        if ( is_string( $sha1 ) ) {
891            $this->procFileStatCache->setField(
892                $path,
893                'sha1',
894                [ 'hash' => $sha1, 'latest' => $latest ]
895            );
896        } elseif ( $sha1 === self::RES_ABSENT ) {
897            $this->procFileStatCache->setField(
898                $path,
899                'sha1',
900                [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
901            );
902        } else {
903            $sha1 = self::SHA1_FAIL; // used for all failure cases
904        }
905
906        return $sha1;
907    }
908
909    /**
910     * @see FileBackendStore::getFileSha1Base36()
911     * @stable to override
912     * @param array $params
913     * @return bool|string|null SHA1, false (missing file), or null (error)
914     */
915    protected function doGetFileSha1Base36( array $params ) {
916        $fsFile = $this->getLocalReference( $params );
917        if ( $fsFile instanceof FSFile ) {
918            $sha1 = $fsFile->getSha1Base36();
919
920            return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
921        }
922
923        return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
924    }
925
926    /** @inheritDoc */
927    final public function getFileProps( array $params ) {
928        $fsFile = $this->getLocalReference( $params );
929
930        return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
931    }
932
933    /** @inheritDoc */
934    final public function getLocalReferenceMulti( array $params ) {
935        $params = $this->setConcurrencyFlags( $params );
936
937        $fsFiles = []; // (path => FSFile)
938        $latest = !empty( $params['latest'] ); // use latest data?
939        // Reuse any files already in process cache...
940        foreach ( $params['srcs'] as $src ) {
941            $path = self::normalizeStoragePath( $src );
942            if ( $path === null ) {
943                $fsFiles[$src] = self::RES_ERROR; // invalid storage path
944            } elseif ( $this->procFileDataCache->hasField( $path, 'localRef' ) ) {
945                $val = $this->procFileDataCache->getField( $path, 'localRef' );
946                // If we want the latest data, check that this cached
947                // value was in fact fetched with the latest available data.
948                if ( !$latest || $val['latest'] ) {
949                    $fsFiles[$src] = $val['object'];
950                }
951            }
952        }
953        // Fetch local references of any remaining files...
954        $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
955        foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
956            $fsFiles[$path] = $fsFile;
957            if ( $fsFile instanceof FSFile ) {
958                $this->procFileDataCache->setField(
959                    $path,
960                    'localRef',
961                    [ 'object' => $fsFile, 'latest' => $latest ]
962                );
963            }
964        }
965
966        return $fsFiles;
967    }
968
969    /**
970     * @see FileBackendStore::getLocalReferenceMulti()
971     * @stable to override
972     * @param array $params
973     * @return string[]|bool[]|null[] Map of (path => FSFile, false (missing), or null (error))
974     */
975    protected function doGetLocalReferenceMulti( array $params ) {
976        return $this->doGetLocalCopyMulti( $params );
977    }
978
979    /** @inheritDoc */
980    final public function getLocalCopyMulti( array $params ) {
981        $params = $this->setConcurrencyFlags( $params );
982
983        return $this->doGetLocalCopyMulti( $params );
984    }
985
986    /**
987     * @see FileBackendStore::getLocalCopyMulti()
988     * @param array $params
989     * @return string[]|bool[]|null[] Map of (path => TempFSFile, false (missing), or null (error))
990     */
991    abstract protected function doGetLocalCopyMulti( array $params );
992
993    /**
994     * @see FileBackend::getFileHttpUrl()
995     * @stable to override
996     * @param array $params
997     * @return string|null
998     */
999    public function getFileHttpUrl( array $params ) {
1000        return self::TEMPURL_ERROR; // not supported
1001    }
1002
1003    /** @inheritDoc */
1004    public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1005        array $params
1006    ) {
1007        $ref = $this->getLocalReference( [ 'src' => $params['src'] ] );
1008        if ( $ref === false ) {
1009            return $this->newStatus( 'backend-fail-notexists', $params['src'] );
1010        } elseif ( $ref === null ) {
1011            return $this->newStatus( 'backend-fail-read', $params['src'] );
1012        } else {
1013            $file = $command->newInputFileFromFile( $ref->getPath() )
1014                ->userData( __CLASS__, $ref );
1015            $command->inputFile( $boxedName, $file );
1016            return $this->newStatus();
1017        }
1018    }
1019
1020    /** @inheritDoc */
1021    final public function streamFile( array $params ) {
1022        $status = $this->newStatus();
1023
1024        // Always set some fields for subclass convenience
1025        $params['options'] ??= [];
1026        $params['headers'] ??= [];
1027
1028        // Don't stream it out as text/html if there was a PHP error
1029        if ( ( empty( $params['headless'] ) || $params['headers'] ) && HttpHeader::headersSent() ) {
1030            print "Headers already sent, terminating.\n";
1031            $status->fatal( 'backend-fail-stream', $params['src'] );
1032            return $status;
1033        }
1034
1035        $status->merge( $this->doStreamFile( $params ) );
1036
1037        return $status;
1038    }
1039
1040    /**
1041     * @see FileBackendStore::streamFile()
1042     * @stable to override
1043     * @param array $params
1044     * @return StatusValue
1045     */
1046    protected function doStreamFile( array $params ) {
1047        $status = $this->newStatus();
1048
1049        $flags = 0;
1050        $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1051        $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
1052
1053        $fsFile = $this->getLocalReference( $params );
1054        if ( $fsFile ) {
1055            $streamer = new HTTPFileStreamer(
1056                $fsFile->getPath(),
1057                $this->getStreamerOptions()
1058            );
1059            $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1060        } else {
1061            $res = false;
1062            HTTPFileStreamer::send404Message( $params['src'], $flags );
1063        }
1064
1065        if ( !$res ) {
1066            $status->fatal( 'backend-fail-stream', $params['src'] );
1067        }
1068
1069        return $status;
1070    }
1071
1072    /** @inheritDoc */
1073    final public function directoryExists( array $params ) {
1074        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1075        if ( $dir === null ) {
1076            return self::EXISTENCE_ERROR; // invalid storage path
1077        }
1078        if ( $shard !== null ) { // confined to a single container/shard
1079            return $this->doDirectoryExists( $fullCont, $dir, $params );
1080        } else { // directory is on several shards
1081            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1082            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1083            $res = false; // response
1084            foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1085                $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1086                if ( $exists === true ) {
1087                    $res = true;
1088                    break; // found one!
1089                } elseif ( $exists === self::RES_ERROR ) {
1090                    $res = self::EXISTENCE_ERROR;
1091                }
1092            }
1093
1094            return $res;
1095        }
1096    }
1097
1098    /**
1099     * @see FileBackendStore::directoryExists()
1100     *
1101     * @param string $fullCont Resolved container name
1102     * @param string $dirRel Resolved path relative to container
1103     * @param array $params
1104     * @return bool|null
1105     */
1106    abstract protected function doDirectoryExists( $fullCont, $dirRel, array $params );
1107
1108    /** @inheritDoc */
1109    final public function getDirectoryList( array $params ) {
1110        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1111        if ( $dir === null ) {
1112            return self::EXISTENCE_ERROR; // invalid storage path
1113        }
1114        if ( $shard !== null ) {
1115            // File listing is confined to a single container/shard
1116            return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1117        } else {
1118            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1119            // File listing spans multiple containers/shards
1120            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1121
1122            return new FileBackendStoreShardDirIterator( $this,
1123                $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1124        }
1125    }
1126
1127    /**
1128     * Do not call this function from places outside FileBackend
1129     *
1130     * @see FileBackendStore::getDirectoryList()
1131     *
1132     * @param string $fullCont Resolved container name
1133     * @param string $dirRel Resolved path relative to container
1134     * @param array $params
1135     * @return Traversable|array|null Iterable list or null (error)
1136     */
1137    abstract public function getDirectoryListInternal( $fullCont, $dirRel, array $params );
1138
1139    /** @inheritDoc */
1140    final public function getFileList( array $params ) {
1141        [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1142        if ( $dir === null ) {
1143            return self::LIST_ERROR; // invalid storage path
1144        }
1145        if ( $shard !== null ) {
1146            // File listing is confined to a single container/shard
1147            return $this->getFileListInternal( $fullCont, $dir, $params );
1148        } else {
1149            $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1150            // File listing spans multiple containers/shards
1151            [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1152
1153            return new FileBackendStoreShardFileIterator( $this,
1154                $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1155        }
1156    }
1157
1158    /**
1159     * Do not call this function from places outside FileBackend
1160     *
1161     * @see FileBackendStore::getFileList()
1162     *
1163     * @param string $fullCont Resolved container name
1164     * @param string $dirRel Resolved path relative to container
1165     * @param array $params
1166     * @return Traversable|string[]|null Iterable list or null (error)
1167     */
1168    abstract public function getFileListInternal( $fullCont, $dirRel, array $params );
1169
1170    /**
1171     * Return a list of FileOp objects from a list of operations.
1172     * Do not call this function from places outside FileBackend.
1173     *
1174     * The result must have the same number of items as the input.
1175     * An exception is thrown if an unsupported operation is requested.
1176     *
1177     * @param array[] $ops Same format as doOperations()
1178     * @return FileOp[]
1179     * @throws FileBackendError
1180     */
1181    final public function getOperationsInternal( array $ops ) {
1182        $supportedOps = [
1183            'store' => StoreFileOp::class,
1184            'copy' => CopyFileOp::class,
1185            'move' => MoveFileOp::class,
1186            'delete' => DeleteFileOp::class,
1187            'create' => CreateFileOp::class,
1188            'describe' => DescribeFileOp::class,
1189            'null' => NullFileOp::class
1190        ];
1191
1192        $performOps = []; // array of FileOp objects
1193        // Build up ordered array of FileOps...
1194        foreach ( $ops as $operation ) {
1195            $opName = $operation['op'];
1196            if ( isset( $supportedOps[$opName] ) ) {
1197                $class = $supportedOps[$opName];
1198                // Get params for this operation
1199                $params = $operation;
1200                // Append the FileOp class
1201                $performOps[] = new $class( $this, $params, $this->logger );
1202            } else {
1203                throw new FileBackendError( "Operation '$opName' is not supported." );
1204            }
1205        }
1206
1207        return $performOps;
1208    }
1209
1210    /**
1211     * Get a list of storage paths to lock for a list of operations
1212     * Returns an array with LockManager::LOCK_UW (shared locks) and
1213     * LockManager::LOCK_EX (exclusive locks) keys, each corresponding
1214     * to a list of storage paths to be locked. All returned paths are
1215     * normalized.
1216     *
1217     * @param FileOp[] $performOps List of FileOp objects
1218     * @return string[][] (LockManager::LOCK_UW => path list, LockManager::LOCK_EX => path list)
1219     */
1220    final public function getPathsToLockForOpsInternal( array $performOps ) {
1221        // Build up a list of files to lock...
1222        $paths = [ 'sh' => [], 'ex' => [] ];
1223        foreach ( $performOps as $fileOp ) {
1224            $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1225            $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1226        }
1227        // Optimization: if doing an EX lock anyway, don't also set an SH one
1228        $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1229        // Get a shared lock on the parent directory of each path changed
1230        $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1231
1232        return [
1233            LockManager::LOCK_UW => $paths['sh'],
1234            LockManager::LOCK_EX => $paths['ex']
1235        ];
1236    }
1237
1238    /** @inheritDoc */
1239    public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1240        $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1241
1242        return $this->getScopedFileLocks( $paths, 'mixed', $status );
1243    }
1244
1245    /** @inheritDoc */
1246    final protected function doOperationsInternal( array $ops, array $opts ) {
1247        $status = $this->newStatus();
1248
1249        // Fix up custom header name/value pairs
1250        $ops = array_map( $this->sanitizeOpHeaders( ... ), $ops );
1251        // Build up a list of FileOps and involved paths
1252        $fileOps = $this->getOperationsInternal( $ops );
1253        $pathsUsed = [];
1254        foreach ( $fileOps as $fileOp ) {
1255            $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1256        }
1257
1258        // Acquire any locks as needed for the scope of this function
1259        if ( empty( $opts['nonLocking'] ) ) {
1260            $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1261            /** @noinspection PhpUnusedLocalVariableInspection */
1262            $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1263            if ( !$status->isOK() ) {
1264                return $status; // abort
1265            }
1266        }
1267
1268        // Clear any file cache entries (after locks acquired)
1269        if ( empty( $opts['preserveCache'] ) ) {
1270            $this->clearCache( $pathsUsed );
1271        }
1272
1273        // Enlarge the cache to fit the stat entries of these files
1274        $this->procFileStatCache->setMaxSize(
1275            max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE )
1276        );
1277
1278        // Load from the persistent container caches
1279        $this->primeContainerCache( $pathsUsed );
1280        // Get the latest stat info for all the files (having locked them)
1281        $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1282
1283        if ( $ok ) {
1284            // Actually attempt the operation batch...
1285            $opts = $this->setConcurrencyFlags( $opts );
1286            $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1287        } else {
1288            // If we could not even stat some files, then bail out
1289            $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1290            foreach ( $ops as $i => $op ) { // mark each op as failed
1291                $subStatus->success[$i] = false;
1292                ++$subStatus->failCount;
1293            }
1294            $this->logger->error( static::class . "-{$this->name} stat failure",
1295                [ 'aborted_operations' => $ops ]
1296            );
1297        }
1298
1299        // Merge errors into StatusValue fields
1300        $status->merge( $subStatus );
1301        $status->success = $subStatus->success; // not done in merge()
1302
1303        // Shrink the stat cache back to normal size
1304        $this->procFileStatCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1305
1306        return $status;
1307    }
1308
1309    /** @inheritDoc */
1310    final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1311        $status = $this->newStatus();
1312
1313        // Fix up custom header name/value pairs
1314        $ops = array_map( $this->sanitizeOpHeaders( ... ), $ops );
1315        // Build up a list of FileOps and involved paths
1316        $fileOps = $this->getOperationsInternal( $ops );
1317        $pathsUsed = [];
1318        foreach ( $fileOps as $fileOp ) {
1319            $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1320        }
1321
1322        // Clear any file cache entries for involved paths
1323        $this->clearCache( $pathsUsed );
1324
1325        // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1326        $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1327        $maxConcurrency = $this->concurrency; // throttle
1328        /** @var StatusValue[] $statuses */
1329        $statuses = []; // array of (index => StatusValue)
1330        /** @var FileBackendStoreOpHandle[] $batch */
1331        $batch = [];
1332        foreach ( $fileOps as $index => $fileOp ) {
1333            $subStatus = $async
1334                ? $fileOp->attemptAsyncQuick()
1335                : $fileOp->attemptQuick();
1336            if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1337                if ( count( $batch ) >= $maxConcurrency ) {
1338                    // Execute this batch. Don't queue any more ops since they contain
1339                    // open filehandles which are a limited resource (T230245).
1340                    $statuses += $this->executeOpHandlesInternal( $batch );
1341                    $batch = [];
1342                }
1343                $batch[$index] = $subStatus->value; // keep index
1344            } else { // error or completed
1345                $statuses[$index] = $subStatus; // keep index
1346            }
1347        }
1348        if ( count( $batch ) ) {
1349            $statuses += $this->executeOpHandlesInternal( $batch );
1350        }
1351        // Marshall and merge all the responses...
1352        foreach ( $statuses as $index => $subStatus ) {
1353            $status->merge( $subStatus );
1354            if ( $subStatus->isOK() ) {
1355                $status->success[$index] = true;
1356                ++$status->successCount;
1357            } else {
1358                $status->success[$index] = false;
1359                ++$status->failCount;
1360            }
1361        }
1362
1363        $this->clearCache( $pathsUsed );
1364
1365        return $status;
1366    }
1367
1368    /**
1369     * Execute a list of FileBackendStoreOpHandle handles in parallel.
1370     * The resulting StatusValue object fields will correspond
1371     * to the order in which the handles where given.
1372     *
1373     * @param FileBackendStoreOpHandle[] $fileOpHandles
1374     * @return StatusValue[] Map of StatusValue objects
1375     * @throws FileBackendError
1376     */
1377    final public function executeOpHandlesInternal( array $fileOpHandles ) {
1378        foreach ( $fileOpHandles as $fileOpHandle ) {
1379            if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1380                throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1381            } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1382                throw new InvalidArgumentException( "Expected handle for this file backend." );
1383            }
1384        }
1385
1386        $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1387        foreach ( $fileOpHandles as $fileOpHandle ) {
1388            $fileOpHandle->closeResources();
1389        }
1390
1391        return $statuses;
1392    }
1393
1394    /**
1395     * @see FileBackendStore::executeOpHandlesInternal()
1396     * @stable to override
1397     *
1398     * @param FileBackendStoreOpHandle[] $fileOpHandles
1399     *
1400     * @throws FileBackendError
1401     * @return StatusValue[] List of corresponding StatusValue objects
1402     */
1403    protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1404        if ( count( $fileOpHandles ) ) {
1405            throw new FileBackendError( "Backend does not support asynchronous operations." );
1406        }
1407
1408        return [];
1409    }
1410
1411    /**
1412     * Normalize and filter HTTP headers from a file operation
1413     *
1414     * This normalizes and strips long HTTP headers from a file operation.
1415     * Most headers are just numbers, but some are allowed to be long.
1416     * This function is useful for cleaning up headers and avoiding backend
1417     * specific errors, especially in the middle of batch file operations.
1418     *
1419     * @param array $op Same format as doOperation()
1420     * @return array
1421     */
1422    protected function sanitizeOpHeaders( array $op ) {
1423        static $longs = [ 'content-disposition' ];
1424
1425        if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1426            $newHeaders = [];
1427            foreach ( $op['headers'] as $name => $value ) {
1428                $name = strtolower( $name );
1429                $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1430                if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1431                    $this->logger->error( "Header '{header}' is too long.", [
1432                        'filebackend' => $this->name,
1433                        'header' => "$name: $value",
1434                    ] );
1435                } else {
1436                    $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1437                }
1438            }
1439            $op['headers'] = $newHeaders;
1440        }
1441
1442        return $op;
1443    }
1444
1445    final public function preloadCache( array $paths ) {
1446        $fullConts = []; // full container names
1447        foreach ( $paths as $path ) {
1448            [ $fullCont, , ] = $this->resolveStoragePath( $path );
1449            $fullConts[] = $fullCont;
1450        }
1451        // Load from the persistent file and container caches
1452        $this->primeContainerCache( $fullConts );
1453        $this->primeFileCache( $paths );
1454    }
1455
1456    final public function clearCache( ?array $paths = null ) {
1457        if ( is_array( $paths ) ) {
1458            $paths = array_map( FileBackend::normalizeStoragePath( ... ), $paths );
1459            $paths = array_filter( $paths, 'strlen' ); // remove nulls
1460        }
1461        if ( $paths === null ) {
1462            $this->procFileStatCache->clear();
1463            $this->procFileDataCache->clear();
1464        } else {
1465            foreach ( $paths as $path ) {
1466                $this->procFileStatCache->clear( $path );
1467                $this->procFileDataCache->clear( $path );
1468            }
1469        }
1470        $this->doClearCache( $paths );
1471    }
1472
1473    /**
1474     * Clears any additional stat caches for storage paths
1475     * @stable to override
1476     *
1477     * @see FileBackend::clearCache()
1478     *
1479     * @param string[]|null $paths Storage paths (optional)
1480     */
1481    protected function doClearCache( ?array $paths = null ) {
1482    }
1483
1484    /** @inheritDoc */
1485    final public function preloadFileStat( array $params ) {
1486        $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1487        $stats = $this->doGetFileStatMulti( $params );
1488        if ( $stats === null ) {
1489            return true; // not supported
1490        }
1491
1492        // Whether this queried the backend in high consistency mode
1493        $latest = !empty( $params['latest'] );
1494
1495        return $this->ingestFreshFileStats( $stats, $latest );
1496    }
1497
1498    /**
1499     * Get file stat information (concurrently if possible) for several files
1500     * @stable to override
1501     *
1502     * @see FileBackend::getFileStat()
1503     *
1504     * @param array $params Parameters include:
1505     *   - srcs        : list of source storage paths
1506     *   - latest      : use the latest available data
1507     * @return array<string,array|false|null>|null Null if not supported. Otherwise a map of storage
1508     *  path to attribute map, false (missing file), or null (I/O error).
1509     * @since 1.23
1510     */
1511    protected function doGetFileStatMulti( array $params ) {
1512        return null; // not supported
1513    }
1514
1515    /**
1516     * Whether this a key/value store where directories are merely virtual
1517     *
1518     * Virtual directories exists in so much as files exists that are
1519     * prefixed with the directory path followed by a forward slash.
1520     *
1521     * @return bool
1522     */
1523    abstract protected function directoriesAreVirtual();
1524
1525    /**
1526     * Check if a short container name is valid
1527     *
1528     * This checks for length and illegal characters.
1529     * This may disallow certain characters that can appear
1530     * in the prefix used to make the full container name.
1531     *
1532     * @param string $container
1533     * @return bool
1534     */
1535    final protected static function isValidShortContainerName( $container ) {
1536        // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1537        // might be used by subclasses. Reserve the dot character.
1538        // The only way dots end up in containers (e.g. resolveStoragePath)
1539        // is due to the wikiId container prefix or the above suffixes.
1540        return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1541    }
1542
1543    /**
1544     * Check if a full container name is valid
1545     *
1546     * This checks for length and illegal characters.
1547     * Limiting the characters makes migrations to other stores easier.
1548     *
1549     * @param string $container
1550     * @return bool
1551     */
1552    final protected static function isValidContainerName( $container ) {
1553        // This accounts for NTFS, Swift, and Ceph restrictions
1554        // and disallows directory separators or traversal characters.
1555        // Note that matching strings URL encode to the same string;
1556        // in Swift/Ceph, the length restriction is *after* URL encoding.
1557        return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1558    }
1559
1560    /**
1561     * Splits a storage path into an internal container name,
1562     * an internal relative file name, and a container shard suffix.
1563     * Any shard suffix is already appended to the internal container name.
1564     * This also checks that the storage path is valid and within this backend.
1565     *
1566     * If the container is sharded but a suffix could not be determined,
1567     * this means that the path can only refer to a directory and can only
1568     * be scanned by looking in all the container shards.
1569     *
1570     * @param string $storagePath
1571     * @return array (container, path, container suffix) or (null, null, null) if invalid
1572     */
1573    final protected function resolveStoragePath( $storagePath ) {
1574        [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1575        if ( $backend === $this->name && $relPath !== null ) { // must be for this backend
1576            $relPath = self::normalizeContainerPath( $relPath );
1577            if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1578                // Get shard for the normalized path if this container is sharded
1579                $cShard = $this->getContainerShard( $shortCont, $relPath );
1580                // Validate and sanitize the relative path (backend-specific)
1581                $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1582                if ( $relPath !== null ) {
1583                    // Prepend any domain ID prefix to the container name
1584                    $container = $this->fullContainerName( $shortCont );
1585                    if ( self::isValidContainerName( $container ) ) {
1586                        // Validate and sanitize the container name (backend-specific)
1587                        $container = $this->resolveContainerName( "{$container}{$cShard}" );
1588                        if ( $container !== null ) {
1589                            return [ $container, $relPath, $cShard ];
1590                        }
1591                    }
1592                }
1593            }
1594        }
1595
1596        return [ null, null, null ];
1597    }
1598
1599    /**
1600     * Like resolveStoragePath() except null values are returned if
1601     * the container is sharded and the shard could not be determined
1602     * or if the path ends with '/'. The latter case is illegal for FS
1603     * backends and can confuse listings for object store backends.
1604     *
1605     * This function is used when resolving paths that must be valid
1606     * locations for files. Directory and listing functions should
1607     * generally just use resolveStoragePath() instead.
1608     *
1609     * @see FileBackendStore::resolveStoragePath()
1610     *
1611     * @param string $storagePath
1612     * @return array (container, path) or (null, null) if invalid
1613     */
1614    final protected function resolveStoragePathReal( $storagePath ) {
1615        [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1616        if ( $cShard !== null && !str_ends_with( $relPath, '/' ) ) {
1617            return [ $container, $relPath ];
1618        }
1619
1620        return [ null, null ];
1621    }
1622
1623    /**
1624     * Get the container name shard suffix for a given path.
1625     * Any empty suffix means the container is not sharded.
1626     *
1627     * @param string $container Container name
1628     * @param string $relPath Storage path relative to the container
1629     * @return string|null Returns null if shard could not be determined
1630     */
1631    final protected function getContainerShard( $container, $relPath ) {
1632        [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1633        if ( $levels == 1 || $levels == 2 ) {
1634            // Hash characters are either base 16 or 36
1635            $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1636            // Get a regex that represents the shard portion of paths.
1637            // The concatenation of the captures gives us the shard.
1638            if ( $levels === 1 ) { // 16 or 36 shards per container
1639                $hashDirRegex = '(' . $char . ')';
1640            } else { // 256 or 1296 shards per container
1641                if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1642                    $hashDirRegex = $char . '/(' . $char . '{2})';
1643                } else { // short hash dir format (e.g. "a/b/c")
1644                    $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1645                }
1646            }
1647            // Allow certain directories to be above the hash dirs so as
1648            // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1649            // They must be 2+ chars to avoid any hash directory ambiguity.
1650            $m = [];
1651            if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1652                return '.' . implode( '', array_slice( $m, 1 ) );
1653            }
1654
1655            return null; // failed to match
1656        }
1657
1658        return ''; // no sharding
1659    }
1660
1661    /**
1662     * Check if a storage path maps to a single shard.
1663     * Container dirs like "a", where the container shards on "x/xy",
1664     * can reside on several shards. Such paths are tricky to handle.
1665     *
1666     * @param string $storagePath
1667     * @return bool
1668     */
1669    final public function isSingleShardPathInternal( $storagePath ) {
1670        [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1671
1672        return ( $shard !== null );
1673    }
1674
1675    /**
1676     * Get the sharding config for a container.
1677     * If greater than 0, then all file storage paths within
1678     * the container are required to be hashed accordingly.
1679     *
1680     * @param string $container
1681     * @return array (integer levels, integer base, repeat flag) or (0, 0, false)
1682     */
1683    final protected function getContainerHashLevels( $container ) {
1684        if ( isset( $this->shardViaHashLevels[$container] ) ) {
1685            $config = $this->shardViaHashLevels[$container];
1686            $hashLevels = (int)$config['levels'];
1687            if ( $hashLevels == 1 || $hashLevels == 2 ) {
1688                $hashBase = (int)$config['base'];
1689                if ( $hashBase == 16 || $hashBase == 36 ) {
1690                    return [ $hashLevels, $hashBase, $config['repeat'] ];
1691                }
1692            }
1693        }
1694
1695        return [ 0, 0, false ]; // no sharding
1696    }
1697
1698    /**
1699     * Get a list of full container shard suffixes for a container
1700     *
1701     * @param string $container
1702     * @return array
1703     */
1704    final protected function getContainerSuffixes( $container ) {
1705        $shards = [];
1706        [ $digits, $base ] = $this->getContainerHashLevels( $container );
1707        if ( $digits > 0 ) {
1708            $numShards = $base ** $digits;
1709            for ( $index = 0; $index < $numShards; $index++ ) {
1710                $shards[] = '.' . \Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1711            }
1712        }
1713
1714        return $shards;
1715    }
1716
1717    /**
1718     * Get the full container name, including the domain ID prefix
1719     *
1720     * @param string $container
1721     * @return string
1722     */
1723    final protected function fullContainerName( $container ) {
1724        if ( $this->domainId != '' ) {
1725            return "{$this->domainId}-$container";
1726        } else {
1727            return $container;
1728        }
1729    }
1730
1731    /**
1732     * Resolve a container name, checking if it's allowed by the backend.
1733     * This is intended for internal use, such as encoding illegal chars.
1734     * Subclasses can override this to be more restrictive.
1735     * @stable to override
1736     *
1737     * @param string $container
1738     * @return string|null
1739     */
1740    protected function resolveContainerName( $container ) {
1741        return $container;
1742    }
1743
1744    /**
1745     * Resolve a relative storage path, checking if it's allowed by the backend.
1746     * This is intended for internal use, such as encoding illegal chars or perhaps
1747     * getting absolute paths (e.g. FS based backends). Note that the relative path
1748     * may be the empty string (e.g. the path is simply to the container).
1749     * @stable to override
1750     *
1751     * @param string $container Container name
1752     * @param string $relStoragePath Storage path relative to the container
1753     * @return string|null Path or null if not valid
1754     */
1755    protected function resolveContainerPath( $container, $relStoragePath ) {
1756        return $relStoragePath;
1757    }
1758
1759    /**
1760     * Get the cache key for a container
1761     *
1762     * @param string $container Resolved container name
1763     * @return string
1764     */
1765    private function containerCacheKey( $container ) {
1766        return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1767    }
1768
1769    /**
1770     * Set the cached info for a container
1771     *
1772     * @param string $container Resolved container name
1773     * @param array $val Information to cache
1774     */
1775    final protected function setContainerCache( $container, array $val ) {
1776        if ( !$this->wanStatCache->set(
1777            $this->containerCacheKey( $container ),
1778            $val,
1779            14 * 86400
1780        ) ) {
1781            $this->logger->warning( "Unable to set stat cache for container {container}.",
1782                [ 'filebackend' => $this->name, 'container' => $container ]
1783            );
1784        }
1785    }
1786
1787    /**
1788     * Delete the cached info for a container.
1789     * The cache key is salted for a while to prevent race conditions.
1790     *
1791     * @param string $container Resolved container name
1792     */
1793    final protected function deleteContainerCache( $container ) {
1794        if ( !$this->wanStatCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1795            $this->logger->warning( "Unable to delete stat cache for container {container}.",
1796                [ 'filebackend' => $this->name, 'container' => $container ]
1797            );
1798        }
1799    }
1800
1801    /**
1802     * Do a batch lookup from cache for container stats for all containers
1803     * used in a list of container names or storage paths objects.
1804     * This loads the persistent cache values into the process cache.
1805     */
1806    final protected function primeContainerCache( array $items ) {
1807        $paths = []; // list of storage paths
1808        $contNames = []; // (cache key => resolved container name)
1809        // Get all the paths/containers from the items...
1810        foreach ( $items as $item ) {
1811            if ( self::isStoragePath( $item ) ) {
1812                $paths[] = $item;
1813            } elseif ( is_string( $item ) ) { // full container name
1814                $contNames[$this->containerCacheKey( $item )] = $item;
1815            }
1816        }
1817        // Get all the corresponding cache keys for paths...
1818        foreach ( $paths as $path ) {
1819            [ $fullCont, , ] = $this->resolveStoragePath( $path );
1820            if ( $fullCont !== null ) { // valid path for this backend
1821                $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1822            }
1823        }
1824
1825        $contInfo = []; // (resolved container name => cache value)
1826        // Get all cache entries for these container cache keys...
1827        $values = $this->wanStatCache->getMulti( array_keys( $contNames ) );
1828        foreach ( $values as $cacheKey => $val ) {
1829            $contInfo[$contNames[$cacheKey]] = $val;
1830        }
1831
1832        // Populate the container process cache for the backend...
1833        $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1834    }
1835
1836    /**
1837     * Fill the backend-specific process cache given an array of
1838     * resolved container names and their corresponding cached info.
1839     * Only containers that actually exist should appear in the map.
1840     * @stable to override
1841     *
1842     * @param array $containerInfo Map of resolved container names to cached info
1843     */
1844    protected function doPrimeContainerCache( array $containerInfo ) {
1845    }
1846
1847    /**
1848     * Get the cache key for a file path
1849     *
1850     * @param string $path Normalized storage path
1851     * @return string
1852     */
1853    private function fileCacheKey( $path ) {
1854        return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1855    }
1856
1857    /**
1858     * Set the cached stat info for a file path.
1859     * Negatives (404s) are not cached. By not caching negatives, we can skip cache
1860     * salting for the case when a file is created at a path were there was none before.
1861     *
1862     * @param string $path Storage path
1863     * @param array $val Stat information to cache
1864     */
1865    final protected function setFileCache( $path, array $val ) {
1866        $path = FileBackend::normalizeStoragePath( $path );
1867        if ( $path === null ) {
1868            return; // invalid storage path
1869        }
1870        // Set the cache unless it is currently salted.
1871        if ( !$this->wanStatCache->set( $this->fileCacheKey( $path ), $val, 7 * 86400 ) ) {
1872            $this->logger->warning( "Unable to set stat cache for file {path}.",
1873                [ 'filebackend' => $this->name, 'path' => $path ]
1874            );
1875        }
1876    }
1877
1878    /**
1879     * Delete the cached stat info for a file path.
1880     * The cache key is salted for a while to prevent race conditions.
1881     * Since negatives (404s) are not cached, this does not need to be called when
1882     * a file is created at a path were there was none before.
1883     *
1884     * @param string $path Storage path
1885     */
1886    final protected function deleteFileCache( $path ) {
1887        $path = FileBackend::normalizeStoragePath( $path );
1888        if ( $path === null ) {
1889            return; // invalid storage path
1890        }
1891        if ( !$this->wanStatCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1892            $this->logger->warning( "Unable to delete stat cache for file {path}.",
1893                [ 'filebackend' => $this->name, 'path' => $path ]
1894            );
1895        }
1896    }
1897
1898    /**
1899     * Do a batch lookup from cache for file stats for all paths
1900     * used in a list of storage paths or FileOp objects.
1901     * This loads the persistent cache values into the process cache.
1902     *
1903     * @param array $items List of storage paths
1904     */
1905    final protected function primeFileCache( array $items ) {
1906        $paths = []; // list of storage paths
1907        $pathNames = []; // (cache key => storage path)
1908        // Get all the paths/containers from the items...
1909        foreach ( $items as $item ) {
1910            if ( self::isStoragePath( $item ) ) {
1911                $path = FileBackend::normalizeStoragePath( $item );
1912                if </