12use InvalidArgumentException;
13use Shellbox\Command\BoxedCommand;
33use Wikimedia\Timestamp\ConvertibleTimestamp;
34use Wikimedia\Timestamp\TimestampFormat as TS;
79 protected const RES_ABSENT =
false;
81 protected const RES_ERROR =
null;
84 protected const ABSENT_NORMAL =
'FNE-N';
86 protected const ABSENT_LATEST =
'FNE-L';
102 parent::__construct( $config );
103 $this->mimeCallback = $config[
'mimeCallback'] ??
null;
105 $this->wanCache = $config[
'wanCache'] ?? WANObjectCache::newEmpty();
106 $this->wanStatCache = WANObjectCache::newEmpty();
108 $this->cheapCache =
new MapCacheLRU( self::CACHE_CHEAP_SIZE );
109 $this->expensiveCache =
new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
120 return min( $this->maxFileSize, PHP_INT_MAX );
158 $status = $this->
newStatus(
'backend-fail-maxsize',
163 if ( $params[
'dstExists'] ??
true ) {
201 $status = $this->
newStatus(
'backend-fail-maxsize',
206 if ( $params[
'dstExists'] ??
true ) {
246 if ( $params[
'dstExists'] ??
true ) {
315 $this->
clearCache( [ $params[
'src'], $params[
'dst'] ] );
317 if ( $params[
'dstExists'] ??
true ) {
349 if ( count( $params[
'headers'] ) ) {
389 $scopeLockS = $this->
getScopedFileLocks( $params[
'srcs'], LockManager::LOCK_UW, $status );
390 if ( $status->isOK() ) {
392 $hrStart = hrtime(
true );
394 $sec = ( hrtime(
true ) - $hrStart ) / 1e9;
395 if ( !$status->isOK() ) {
396 $this->logger->error( static::class .
"-{$this->name}" .
397 " failed to concatenate " . count( $params[
'srcs'] ) .
" file(s) [$sec sec]" );
412 $tmpPath = $params[
'dst'];
413 unset( $params[
'latest'] );
417 $ok = ( @is_file( $tmpPath ) && @filesize( $tmpPath ) == 0 );
419 $status->fatal(
'backend-fail-opentemp', $tmpPath );
426 foreach ( $fsFiles as
$path => &$fsFile ) {
431 $fsFile === self::RES_ERROR ?
'backend-fail-read' :
'backend-fail-notexists',
442 $tmpHandle = fopen( $tmpPath,
'ab' );
443 if ( $tmpHandle ===
false ) {
444 $status->fatal(
'backend-fail-opentemp', $tmpPath );
450 foreach ( $fsFiles as $virtualSource => $fsFile ) {
452 $sourceHandle = fopen( $fsFile->getPath(),
'rb' );
453 if ( $sourceHandle ===
false ) {
454 fclose( $tmpHandle );
455 $status->fatal(
'backend-fail-read', $virtualSource );
460 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
461 fclose( $sourceHandle );
462 fclose( $tmpHandle );
463 $status->fatal(
'backend-fail-writetemp', $tmpPath );
467 fclose( $sourceHandle );
469 if ( !fclose( $tmpHandle ) ) {
470 $status->fatal(
'backend-fail-closetemp', $tmpPath );
489 if ( $dir ===
null ) {
490 $status->fatal(
'backend-fail-invalidpath', $params[
'dir'] );
495 if ( $shard !==
null ) {
498 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
501 $status->merge( $this->
doPrepareInternal(
"{$fullCont}{$suffix}", $dir, $params ) );
521 final protected function doSecure( array $params ) {
527 if ( $dir ===
null ) {
528 $status->fatal(
'backend-fail-invalidpath', $params[
'dir'] );
533 if ( $shard !==
null ) {
536 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
539 $status->merge( $this->
doSecureInternal(
"{$fullCont}{$suffix}", $dir, $params ) );
565 if ( $dir ===
null ) {
566 $status->fatal(
'backend-fail-invalidpath', $params[
'dir'] );
571 if ( $shard !==
null ) {
574 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
577 $status->merge( $this->
doPublishInternal(
"{$fullCont}{$suffix}", $dir, $params ) );
597 final protected function doClean( array $params ) {
605 if ( $subDirsRel !==
null ) {
606 foreach ( $subDirsRel as $subDirRel ) {
607 $subDir = $params[
'dir'] .
"/{$subDirRel}";
608 $status->merge( $this->
doClean( [
'dir' => $subDir ] + $params ) );
610 unset( $subDirsRel );
615 if ( $dir ===
null ) {
616 $status->fatal(
'backend-fail-invalidpath', $params[
'dir'] );
622 $filesLockEx = [ $params[
'dir'] ];
624 $scopedLockE = $this->
getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
625 if ( !$status->isOK() ) {
629 if ( $shard !==
null ) {
633 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
636 $status->merge( $this->
doCleanInternal(
"{$fullCont}{$suffix}", $dir, $params ) );
662 if ( is_array( $stat ) ) {
666 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
675 if ( is_array( $stat ) ) {
676 return $stat[
'mtime'];
679 return self::TIMESTAMP_FAIL;
688 if ( is_array( $stat ) ) {
689 return $stat[
'size'];
692 return self::SIZE_FAIL;
701 if (
$path ===
null ) {
702 return self::STAT_ERROR;
707 $latest = !empty( $params[
'latest'] );
709 $requireSHA1 = !empty( $params[
'requireSHA1'] );
711 $stat = $this->cheapCache->getField(
$path,
'stat', self::CACHE_TTL );
720 ( $requireSHA1 && is_array( $stat ) && !isset( $stat[
'sha1'] ) )
724 $stat = $this->cheapCache->getField(
$path,
'stat', self::CACHE_TTL );
728 if ( is_array( $stat ) ) {
730 ( !$latest || !empty( $stat[
'latest'] ) ) &&
731 ( !$requireSHA1 || isset( $stat[
'sha1'] ) )
735 } elseif ( $stat === self::ABSENT_LATEST ) {
736 return self::STAT_ABSENT;
737 } elseif ( $stat === self::ABSENT_NORMAL ) {
739 return self::STAT_ABSENT;
747 if ( is_array( $stat ) ) {
751 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
764 foreach ( $stats as
$path => $stat ) {
765 if ( is_array( $stat ) ) {
767 $stat[
'latest'] ??= $latest;
769 $this->cheapCache->setField(
$path,
'stat', $stat );
770 if ( isset( $stat[
'sha1'] ) ) {
772 $this->cheapCache->setField(
775 [
'hash' => $stat[
'sha1'],
'latest' => $latest ]
778 if ( isset( $stat[
'xattr'] ) ) {
781 $this->cheapCache->setField(
784 [
'map' => $stat[
'xattr'],
'latest' => $latest ]
789 } elseif ( $stat === self::RES_ABSENT ) {
790 $this->cheapCache->setField(
793 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
795 $this->cheapCache->setField(
798 [
'map' => self::XATTRS_FAIL,
'latest' => $latest ]
800 $this->cheapCache->setField(
803 [
'hash' => self::SHA1_FAIL,
'latest' => $latest ]
805 $this->logger->debug(
806 __METHOD__ .
': File {path} does not exist',
811 $this->logger->error(
812 __METHOD__ .
': Could not stat file {path}',
835 foreach ( $contents as
$path => $content ) {
836 if ( !is_string( $content ) ) {
837 $contents[
$path] = self::CONTENT_FAIL;
853 if ( $fsFile instanceof
FSFile ) {
855 $content = @file_get_contents( $fsFile->getPath() );
856 $contents[
$path] = is_string( $content ) ? $content : self::RES_ERROR;
859 $contents[
$path] = $fsFile;
872 if (
$path ===
null ) {
873 return self::XATTRS_FAIL;
875 $latest = !empty( $params[
'latest'] );
876 if ( $this->cheapCache->hasField(
$path,
'xattr', self::CACHE_TTL ) ) {
877 $stat = $this->cheapCache->getField(
$path,
'xattr' );
880 if ( !$latest || $stat[
'latest'] ) {
885 if ( is_array( $fields ) ) {
887 $this->cheapCache->setField(
890 [
'map' => $fields,
'latest' => $latest ]
892 } elseif ( $fields === self::RES_ABSENT ) {
893 $this->cheapCache->setField(
896 [
'map' => self::XATTRS_FAIL,
'latest' => $latest ]
899 $fields = self::XATTRS_FAIL;
912 return [
'headers' => [],
'metadata' => [] ];
921 if (
$path ===
null ) {
922 return self::SHA1_FAIL;
924 $latest = !empty( $params[
'latest'] );
925 if ( $this->cheapCache->hasField(
$path,
'sha1', self::CACHE_TTL ) ) {
926 $stat = $this->cheapCache->getField(
$path,
'sha1' );
929 if ( !$latest || $stat[
'latest'] ) {
930 return $stat[
'hash'];
934 if ( is_string( $sha1 ) ) {
935 $this->cheapCache->setField(
938 [
'hash' => $sha1,
'latest' => $latest ]
940 } elseif ( $sha1 === self::RES_ABSENT ) {
941 $this->cheapCache->setField(
944 [
'hash' => self::SHA1_FAIL,
'latest' => $latest ]
947 $sha1 = self::SHA1_FAIL;
961 if ( $fsFile instanceof
FSFile ) {
962 $sha1 = $fsFile->getSha1Base36();
964 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
967 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
977 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
988 $latest = !empty( $params[
'latest'] );
990 foreach ( $params[
'srcs'] as $src ) {
992 if (
$path ===
null ) {
993 $fsFiles[$src] = self::RES_ERROR;
994 } elseif ( $this->expensiveCache->hasField(
$path,
'localRef' ) ) {
995 $val = $this->expensiveCache->getField(
$path,
'localRef' );
998 if ( !$latest || $val[
'latest'] ) {
999 $fsFiles[$src] = $val[
'object'];
1004 $params[
'srcs'] = array_diff( $params[
'srcs'], array_keys( $fsFiles ) );
1006 $fsFiles[
$path] = $fsFile;
1007 if ( $fsFile instanceof
FSFile ) {
1008 $this->expensiveCache->setField(
1011 [
'object' => $fsFile,
'latest' => $latest ]
1053 return self::TEMPURL_ERROR;
1061 if ( $ref ===
false ) {
1062 return $this->
newStatus(
'backend-fail-notexists', $params[
'src'] );
1063 } elseif ( $ref ===
null ) {
1064 return $this->
newStatus(
'backend-fail-read', $params[
'src'] );
1066 $file = $command->newInputFileFromFile( $ref->getPath() )
1067 ->userData( __CLASS__, $ref );
1068 $command->inputFile( $boxedName, $file );
1080 $params[
'options'] ??= [];
1081 $params[
'headers'] ??= [];
1084 if ( ( empty( $params[
'headless'] ) || $params[
'headers'] ) && headers_sent() ) {
1085 print
"Headers already sent, terminating.\n";
1086 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1112 $this->getStreamerOptions()
1114 $res = $streamer->stream( $params[
'headers'],
true, $params[
'options'], $flags );
1121 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1130 if ( $dir ===
null ) {
1131 return self::EXISTENCE_ERROR;
1133 if ( $shard !==
null ) {
1136 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
1141 if ( $exists ===
true ) {
1144 } elseif ( $exists === self::RES_ERROR ) {
1145 $res = self::EXISTENCE_ERROR;
1166 if ( $dir ===
null ) {
1167 return self::EXISTENCE_ERROR;
1169 if ( $shard !==
null ) {
1173 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
1197 if ( $dir ===
null ) {
1198 return self::LIST_ERROR;
1200 if ( $shard !==
null ) {
1204 $this->logger->debug( __METHOD__ .
": iterating over all container shards." );
1238 'store' => StoreFileOp::class,
1239 'copy' => CopyFileOp::class,
1240 'move' => MoveFileOp::class,
1241 'delete' => DeleteFileOp::class,
1242 'create' => CreateFileOp::class,
1243 'describe' => DescribeFileOp::class,
1244 'null' => NullFileOp::class
1249 foreach ( $ops as $operation ) {
1250 $opName = $operation[
'op'];
1251 if ( isset( $supportedOps[$opName] ) ) {
1252 $class = $supportedOps[$opName];
1254 $params = $operation;
1256 $performOps[] =
new $class( $this, $params, $this->logger );
1277 $paths = [
'sh' => [],
'ex' => [] ];
1278 foreach ( $performOps as $fileOp ) {
1279 $paths[
'sh'] = array_merge( $paths[
'sh'], $fileOp->storagePathsRead() );
1280 $paths[
'ex'] = array_merge( $paths[
'ex'], $fileOp->storagePathsChanged() );
1283 $paths[
'sh'] = array_diff( $paths[
'sh'], $paths[
'ex'] );
1285 $paths[
'sh'] = array_merge( $paths[
'sh'], array_map(
'dirname', $paths[
'ex'] ) );
1288 LockManager::LOCK_UW => $paths[
'sh'],
1289 LockManager::LOCK_EX => $paths[
'ex']
1311 foreach ( $fileOps as $fileOp ) {
1312 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1316 if ( empty( $opts[
'nonLocking'] ) ) {
1320 if ( !$status->isOK() ) {
1326 if ( empty( $opts[
'preserveCache'] ) ) {
1331 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1336 $ok = $this->
preloadFileStat( [
'srcs' => $pathsUsed,
'latest' =>
true ] );
1344 $subStatus = $this->
newStatus(
'backend-fail-internal', $this->name );
1345 foreach ( $ops as $i => $op ) {
1346 $subStatus->success[$i] =
false;
1347 ++$subStatus->failCount;
1349 $this->logger->error( static::class .
"-{$this->name} stat failure",
1350 [
'aborted_operations' => $ops ]
1355 $status->merge( $subStatus );
1356 $status->success = $subStatus->success;
1359 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1375 foreach ( $fileOps as $fileOp ) {
1376 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1383 $async = ( $this->parallelize ===
'implicit' && count( $ops ) > 1 );
1389 foreach ( $fileOps as $index => $fileOp ) {
1391 ? $fileOp->attemptAsyncQuick()
1392 : $fileOp->attemptQuick();
1394 if ( count( $batch ) >= $maxConcurrency ) {
1400 $batch[$index] = $subStatus->value;
1402 $statuses[$index] = $subStatus;
1405 if ( count( $batch ) ) {
1409 foreach ( $statuses as $index => $subStatus ) {
1410 $status->merge( $subStatus );
1411 if ( $subStatus->isOK() ) {
1412 $status->success[$index] =
true;
1413 ++$status->successCount;
1415 $status->success[$index] =
false;
1416 ++$status->failCount;
1438 foreach ( $fileOpHandles as $fileOpHandle ) {
1440 throw new InvalidArgumentException(
"Expected FileBackendStoreOpHandle object." );
1441 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1442 throw new InvalidArgumentException(
"Expected handle for this file backend." );
1447 foreach ( $fileOpHandles as $fileOpHandle ) {
1448 $fileOpHandle->closeResources();
1464 if ( count( $fileOpHandles ) ) {
1465 throw new FileBackendError(
"Backend does not support asynchronous operations." );
1483 static $longs = [
'content-disposition' ];
1485 if ( isset( $op[
'headers'] ) ) {
1487 foreach ( $op[
'headers'] as
$name => $value ) {
1489 $maxHVLen = in_array(
$name, $longs ) ? INF : 255;
1490 if ( strlen(
$name ) > 255 || strlen( $value ) > $maxHVLen ) {
1491 $this->logger->error(
"Header '{header}' is too long.", [
1492 'filebackend' => $this->name,
1493 'header' =>
"$name: $value",
1496 $newHeaders[
$name] = strlen( $value ) ? $value :
'';
1499 $op[
'headers'] = $newHeaders;
1507 foreach ( $paths as
$path ) {
1509 $fullConts[] = $fullCont;
1517 if ( is_array( $paths ) ) {
1519 $paths = array_filter( $paths,
'strlen' );
1521 if ( $paths ===
null ) {
1522 $this->cheapCache->clear();
1523 $this->expensiveCache->clear();
1525 foreach ( $paths as
$path ) {
1526 $this->cheapCache->clear(
$path );
1527 $this->expensiveCache->clear(
$path );
1549 $params[
'concurrency'] = ( $this->parallelize !==
'off' ) ? $this->concurrency : 1;
1551 if ( $stats ===
null ) {
1556 $latest = !empty( $params[
'latest'] );
1619 return (
bool)preg_match(
'/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1637 if ( $backend === $this->name && $relPath !==
null ) {
1639 if ( $relPath !==
null && self::isValidShortContainerName( $shortCont ) ) {
1644 if ( $relPath !==
null ) {
1647 if ( self::isValidContainerName( $container ) ) {
1650 if ( $container !==
null ) {
1651 return [ $container, $relPath, $cShard ];
1658 return [
null,
null, null ];
1678 if ( $cShard !==
null && !str_ends_with( $relPath,
'/' ) ) {
1679 return [ $container, $relPath ];
1682 return [
null, null ];
1695 if ( $levels == 1 || $levels == 2 ) {
1697 $char = ( $base == 36 ) ?
'[0-9a-z]' :
'[0-9a-f]';
1700 if ( $levels === 1 ) {
1701 $hashDirRegex =
'(' . $char .
')';
1704 $hashDirRegex = $char .
'/(' . $char .
'{2})';
1706 $hashDirRegex =
'(' . $char .
')/(' . $char .
')';
1713 if ( preg_match(
"!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1714 return '.' . implode(
'', array_slice( $m, 1 ) );
1734 return ( $shard !==
null );
1746 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1747 $config = $this->shardViaHashLevels[$container];
1748 $hashLevels = (int)$config[
'levels'];
1749 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1750 $hashBase = (int)$config[
'base'];
1751 if ( $hashBase == 16 || $hashBase == 36 ) {
1752 return [ $hashLevels, $hashBase, $config[
'repeat'] ];
1757 return [ 0, 0, false ];
1769 if ( $digits > 0 ) {
1770 $numShards = $base ** $digits;
1771 for ( $index = 0; $index < $numShards; $index++ ) {
1772 $shards[] =
'.' . \Wikimedia\base_convert( (
string)$index, 10, $base, $digits );
1786 if ( $this->domainId !=
'' ) {
1787 return "{$this->domainId}-$container";
1818 return $relStoragePath;
1827 private function containerCacheKey( $container ) {
1828 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1838 if ( !$this->wanStatCache->set(
1839 $this->containerCacheKey( $container ),
1843 $this->logger->warning(
"Unable to set stat cache for container {container}.",
1844 [
'filebackend' => $this->name,
'container' => $container ]
1856 if ( !$this->wanStatCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1857 $this->logger->warning(
"Unable to delete stat cache for container {container}.",
1858 [
'filebackend' => $this->name,
'container' => $container ]
1875 foreach ( $items as $item ) {
1876 if ( self::isStoragePath( $item ) ) {
1878 } elseif ( is_string( $item ) ) {
1879 $contNames[$this->containerCacheKey( $item )] = $item;
1883 foreach ( $paths as
$path ) {
1885 if ( $fullCont !==
null ) {
1886 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1892 $values = $this->wanStatCache->getMulti( array_keys( $contNames ) );
1893 foreach ( $values as $cacheKey => $val ) {
1894 $contInfo[$contNames[$cacheKey]] = $val;
1918 private function fileCacheKey(
$path ) {
1919 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1(
$path );
1932 if (
$path ===
null ) {
1935 $mtime = (int)ConvertibleTimestamp::convert( TS::UNIX, $val[
'mtime'] );
1936 $ttl = $this->wanStatCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1938 if ( !$this->wanStatCache->set( $this->fileCacheKey(
$path ), $val, $ttl ) ) {
1939 $this->logger->warning(
"Unable to set stat cache for file {path}.",
1940 [
'filebackend' => $this->name,
'path' =>
$path ]
1955 if (
$path ===
null ) {
1958 if ( !$this->wanStatCache->delete( $this->fileCacheKey(
$path ), 300 ) ) {
1959 $this->logger->warning(
"Unable to delete stat cache for file {path}.",
1960 [
'filebackend' => $this->name,
'path' =>
$path ]
1979 foreach ( $items as $item ) {
1980 if ( self::isStoragePath( $item ) ) {
1982 if (
$path !==
null ) {
1988 foreach ( $paths as
$path ) {
1990 if ( $rel !==
null ) {
1991 $pathNames[$this->fileCacheKey(
$path )] =
$path;
1996 $values = $this->wanStatCache->getMulti( array_keys( $pathNames ) );
1998 foreach ( array_filter( $values,
'is_array' ) as $cacheKey => $stat ) {
1999 $path = $pathNames[$cacheKey];
2002 unset( $stat[
'latest'] );
2004 $this->cheapCache->setField(
$path,
'stat', $stat );
2005 if ( isset( $stat[
'sha1'] ) && strlen( $stat[
'sha1'] ) == 31 ) {
2007 $this->cheapCache->setField(
2010 [
'hash' => $stat[
'sha1'],
'latest' =>
false ]
2013 if ( isset( $stat[
'xattr'] ) && is_array( $stat[
'xattr'] ) ) {
2016 $this->cheapCache->setField(
2019 [
'map' => $stat[
'xattr'],
'latest' =>
false ]
2033 $newXAttr = [
'headers' => [],
'metadata' => [] ];
2035 foreach ( $xattr[
'headers'] as
$name => $value ) {
2036 $newXAttr[
'headers'][strtolower(
$name )] = $value;
2039 foreach ( $xattr[
'metadata'] as
$name => $value ) {
2040 $newXAttr[
'metadata'][strtolower(
$name )] = $value;
2053 $opts[
'concurrency'] = 1;
2054 if ( $this->parallelize ===
'implicit' ) {
2055 if ( $opts[
'parallelize'] ??
true ) {
2058 } elseif ( $this->parallelize ===
'explicit' ) {
2059 if ( !empty( $opts[
'parallelize'] ) ) {
2077 if ( $this->mimeCallback ) {
2078 return ( $this->mimeCallback )( $storagePath, $content, $fsPath );
2081 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) :
false;
2082 return $mime ?:
'unknown/unknown';
2087class_alias( FileBackendStore::class,
'FileBackendStore' );
Generic operation result class Has warning/error list, boolean status and arbitrary value.