From 995640c647cc8a49f0e86cb7a6280672a827b1e7 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Thu, 19 Nov 2026 11:02:54 -0600 Subject: [PATCH] feat: bulk delete on S3 and Azure filesystems - rm() of a directory or pattern uses DeleteObjects / Blob Batch - bulk_delete option turns it off - azure-sdk: BlobServiceInterface::deleteBlobs() - fix Shared Key signature for a zero Content-Length - fix Azure rm() hiding a refused delete - cache adapter clears with one rm() --- .../bridges/filesystem-async-aws-bridge.md | 19 ++ .../bridges/filesystem-azure-bridge.md | 19 ++ .../bridges/symfony-filesystem-bundle.md | 2 + documentation/upgrading.md | 6 + .../Bridge/AsyncAWS/AsyncAWSS3Filesystem.php | 101 +++++---- .../Filesystem/Bridge/AsyncAWS/Options.php | 21 +- .../AsyncAWS/Tests/Mother/S3ClientMother.php | 90 +++++++++ .../Tests/Unit/AsyncAWSS3FilesystemTest.php | 108 ++++++++++ .../AsyncAWS/Tests/Unit/OptionsTest.php | 2 + .../Bridge/Azure/AzureBlobFilesystem.php | 115 ++++++++--- .../Flow/Filesystem/Bridge/Azure/Options.php | 21 +- .../Tests/Double/InMemoryBlobService.php | 3 + .../Tests/Double/RecordingBlobService.php | 9 + .../Azure/Tests/Mother/BlobServiceMother.php | 53 ++++- .../Tests/Unit/AzureBlobFilesystemTest.php | 191 ++++++++++++++++++ .../Bridge/Azure/Tests/Unit/OptionsTest.php | 4 +- .../Factory/AsyncAwsS3FilesystemFactory.php | 10 +- .../Factory/AzureBlobFilesystemFactory.php | 10 +- .../Tests/Double/StubBlobService.php | 3 + .../AsyncAwsS3FilesystemFactoryTest.php | 26 +++ .../AzureBlobFilesystemFactoryTest.php | 23 +++ .../FlowFilesystemCacheAdapter.php | 10 +- .../Unit/FlowFilesystemCacheAdapterTest.php | 42 ++++ .../AuthorizationFactory/SharedKeyFactory.php | 3 +- .../src/Flow/Azure/SDK/BlobService.php | 160 +++++++++++++++ .../DeleteBlobs/DeleteBlobsOptions.php | 101 +++++++++ .../Flow/Azure/SDK/BlobServiceInterface.php | 13 ++ .../Azure/SDK/Exception/AzureException.php | 1 + .../SDK/Tests/Context/BlobServiceContext.php | 23 +++ .../SharedKeyFactoryTest.php | 17 ++ .../Azure/SDK/Tests/Unit/BlobServiceTest.php | 105 ++++++++++ 31 files changed, 1226 insertions(+), 85 deletions(-) create mode 100644 src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService/DeleteBlobs/DeleteBlobsOptions.php diff --git a/documentation/components/bridges/filesystem-async-aws-bridge.md b/documentation/components/bridges/filesystem-async-aws-bridge.md index 4e00123d50..d3b79083c1 100644 --- a/documentation/components/bridges/filesystem-async-aws-bridge.md +++ b/documentation/components/bridges/filesystem-async-aws-bridge.md @@ -91,3 +91,22 @@ The limits are part of the filesystem description, so a worker process builds th `mv()` sends one `CopyObject` up to `copy_part_size` (default 256 MiB, 5 MiB to 5 GB). Above it, `mv()` copies the object in ranged parts of that size. The source is deleted only after the copy succeeded. A move above `copy_part_size` does not carry object tags. + +## Deletes + +```php +use function Flow\Filesystem\DSL\path; + +$s3->rm(path('aws-s3://data')); // 1 DeleteObjects request per 1,000 keys +$s3->rm(path('aws-s3://data/*.parquet')); // the same for a pattern +$s3->rm(path('aws-s3://data/a.csv')); // HeadObject, then 1 DeleteObject + +// a refused key: the current request finishes, no further request is sent +// Flow\Filesystem\Exception\RuntimeException: +// 3 of 1000 paths were not removed, the first is aws-s3://data/part-7.parquet: AccessDenied + +// 1 DeleteObject request per key +$s3 = aws_s3_filesystem($bucket, $client, aws_s3_filesystem_options()->withBulkDelete(false)); +``` + +Turn bulk delete off for an S3-compatible store that has no `DeleteObjects`. diff --git a/documentation/components/bridges/filesystem-azure-bridge.md b/documentation/components/bridges/filesystem-azure-bridge.md index e7943ecf59..ece91cf74b 100644 --- a/documentation/components/bridges/filesystem-azure-bridge.md +++ b/documentation/components/bridges/filesystem-azure-bridge.md @@ -110,6 +110,25 @@ copies ranged blocks with Put Block From URL and commits them with one Put Block headers and the metadata of the source. The source is deleted only after the copy succeeded. Blob tags are not carried. The source is signed with a SAS, so the service must use Shared Key authorization. +### rm() + +```php +rm(path('azure-blob://data')); // 1 Blob Batch request per 256 blobs +$azure->rm(path('azure-blob://data/*.parquet')); // the same for a pattern +$azure->rm(path('azure-blob://data/a.csv')); // 1 Delete Blob request + +// a refused blob: the current batch finishes, no further batch is sent +// Flow\Filesystem\Exception\RuntimeException: +// 3 of 256 paths were not removed, the first is azure-blob://data/part-7.parquet: AuthorizationFailure + +// 1 Delete Blob request per blob +$azure = azure_filesystem($blobService, azure_filesystem_options()->withBulkDelete(false)); +``` + ## Usage with Flow To use the Azure Blob filesystem with Flow, give it to the source or sink that reads or writes the diff --git a/documentation/components/bridges/symfony-filesystem-bundle.md b/documentation/components/bridges/symfony-filesystem-bundle.md index 6cf05bde1c..5bbb1511d4 100644 --- a/documentation/components/bridges/symfony-filesystem-bundle.md +++ b/documentation/components/bridges/symfony-filesystem-bundle.md @@ -328,6 +328,7 @@ flow_filesystem: max_retries: 1 options: block_size: 6291456 + bulk_delete: true # false: 1 DeleteObject per key, for stores without DeleteObjects copy_part_size: 268435456 # mv() above this size copies in ranged parts ``` @@ -385,6 +386,7 @@ flow_filesystem: max_retries: 1 options: block_size: 4194304 + bulk_delete: true # false: 1 Delete Blob per blob instead of Blob Batch copy_part_size: 268435456 # mv() above this size copies in ranged blocks list_blob_max_results: 100 ``` diff --git a/documentation/upgrading.md b/documentation/upgrading.md index b7d066734a..6d9cec5d8e 100644 --- a/documentation/upgrading.md +++ b/documentation/upgrading.md @@ -293,6 +293,12 @@ PHP engine. | `RustBackend::allocatedBytes()` adds `Flow\Arrow\allocated_bytes()` | it counts the bytes of `flow_php` only, which hold the Parquet bytes of the `flow_php` engine. `Flow\Arrow\allocated_bytes()` stays for the bytes of `arrow` | | `FLOW_ARROW_ABI` 2 | 3: build `arrow` from the release of `flow-php/parquet` | +### 24) `flow-php/azure-sdk` - `BlobServiceInterface` deletes blobs in one batch + +| Before | After | +|------------------------|--------------------------------------------------------------------------------------------------------| +| `BlobServiceInterface` | also `deleteBlobs(array $blobs, DeleteBlobsOptions $options = new DeleteBlobsOptions()): void` | + --- ## Upgrading from 0.46.x to 0.47.x diff --git a/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/AsyncAWSS3Filesystem.php b/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/AsyncAWSS3Filesystem.php index b791d41c83..d4822b4633 100644 --- a/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/AsyncAWSS3Filesystem.php +++ b/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/AsyncAWSS3Filesystem.php @@ -19,6 +19,8 @@ use Generator; use SensitiveParameter; +use function array_map; +use function count; use function Flow\Filesystem\DSL\path; use function Flow\Types\DSL\type_array; use function Flow\Types\DSL\type_string; @@ -35,6 +37,8 @@ */ final readonly class AsyncAWSS3Filesystem implements Filesystem { + private const int DELETE_OBJECTS_LIMIT = 1000; + public function __construct( private Mount $mount, private string $bucket, @@ -276,20 +280,7 @@ public function rm(Path $path, bool $recursive = true): bool $this->mount->supports($path) || throw new InvalidSchemeException($path->protocol(), $this->mount->protocol); if ($path->isPattern()) { - $deletedCount = 0; - - foreach ($this->list($path) as $fileStatus) { - $this->client - ->client() - ->deleteObject([ - 'Bucket' => $this->bucket, - 'Key' => ltrim($fileStatus->path->path(), '/'), - ]); - - $deletedCount++; - } - - return (bool) $deletedCount; + return $this->deleteListed($path); } try { @@ -301,11 +292,7 @@ public function rm(Path $path, bool $recursive = true): bool ]); $headObject->resolve(); } catch (NoSuchKeyException) { - /** - * Since AzureS3 doesn't have a concept of folders, before we check if the intention is not to delete - * entire path, like for example aws-s3://nested/folder we need to first add / at the end, to accidentally - * not delete files that would also match the prefix, like: aws-s3://nested/folder_but_file.txt. - */ + // the trailing slash keeps "folder" from matching "folder_but_file.txt" $folderPath = path(trim($path->uri(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $path->options()); if (!$recursive) { @@ -316,19 +303,7 @@ public function rm(Path $path, bool $recursive = true): bool } } - $deletedCount = 0; - - foreach ($this->list($folderPath) as $fileStatus) { - $this->client - ->client() - ->deleteObject([ - 'Bucket' => $this->bucket, - 'Key' => ltrim($fileStatus->path->path(), '/'), - ]); - $deletedCount++; - } - - return (bool) $deletedCount; + return $this->deleteListed($folderPath); } $this->client @@ -365,11 +340,7 @@ public function status(Path $path): ?FileStatus return new FileStatus($path, true, $headObject->getContentLength(), $headObject->getLastModified()); } catch (NoSuchKeyException) { - /** - * Since S3 doesn't have a concept of folders, before we check if the intention is not to delete - * entire path, like for example aws-s3://nested/folder we need to first add / at the end, to accidentally - * not match files that would also match the prefix, like: aws-s3://nested/folder_but_file.txt. - */ + // the trailing slash keeps "folder" from matching "folder_but_file.txt" $folderPath = path(trim($path->uri(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $path->options()); foreach ($this->list($folderPath) as $fileStatus) { @@ -408,4 +379,60 @@ public function writeTo(Path $path): DestinationStream $this->options->partSize(), ); } + + private function deleteListed(Path $path): bool + { + $keys = []; + $deleted = false; + + foreach ($this->list($path) as $fileStatus) { + $key = ltrim($fileStatus->path->path(), DIRECTORY_SEPARATOR); + $deleted = true; + + if (!$this->options->bulkDelete()) { + $this->client->client()->deleteObject(['Bucket' => $this->bucket, 'Key' => $key]); + + continue; + } + + $keys[] = $key; + + if (count($keys) === self::DELETE_OBJECTS_LIMIT) { + $this->deleteObjects($path, $keys); + $keys = []; + } + } + + if ($keys !== []) { + $this->deleteObjects($path, $keys); + } + + return $deleted; + } + + /** + * @param non-empty-list $keys + */ + private function deleteObjects(Path $listed, array $keys): void + { + $errors = $this->client + ->client() + ->deleteObjects([ + 'Bucket' => $this->bucket, + 'Delete' => ['Objects' => array_map(static fn(string $key): array => ['Key' => $key], $keys)], + ]) + ->getErrors(); + + if ($errors === []) { + return; + } + + throw new RuntimeException(sprintf( + '%d of %d paths were not removed, the first is %s: %s', + count($errors), + count($keys), + path($listed->protocol() . '://' . DIRECTORY_SEPARATOR . $errors[0]->getKey(), $listed->options())->uri(), + $errors[0]->getCode(), + )); + } } diff --git a/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/Options.php b/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/Options.php index 33f31a1e67..f07cc75466 100644 --- a/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/Options.php +++ b/src/bridge/filesystem/async-aws/src/Flow/Filesystem/Bridge/AsyncAWS/Options.php @@ -19,13 +19,15 @@ use function sprintf; /** - * @type S3Options = array{block_location: string, block_permissions: null|PermissionsShape, copy_part_size: int, file_fast_path: bool, part_size: int} + * @type S3Options = array{block_location: string, block_permissions: null|PermissionsShape, bulk_delete: bool, copy_part_size: int, file_fast_path: bool, part_size: int} * @import-type PermissionsShape from Permissions */ final class Options { private BlockFactory $blockFactory; + private bool $bulkDelete = true; + private int $copyPartSize = 256 * 1024 * 1024; private bool $fileFastPath = true; @@ -46,6 +48,11 @@ public function blockFactory(): BlockFactory return $this->blockFactory; } + public function bulkDelete(): bool + { + return $this->bulkDelete; + } + public function copyPartSize(): int { return $this->copyPartSize; @@ -75,12 +82,13 @@ public static function fromArray(array $data): self !is_string($data['block_location'] ?? null) || !array_key_exists('block_permissions', $data) || $data['block_permissions'] !== null && !is_array($data['block_permissions']) + || !is_bool($data['bulk_delete'] ?? null) || !is_int($data['copy_part_size'] ?? null) || !is_bool($data['file_fast_path'] ?? null) || !is_int($data['part_size'] ?? null) ) { throw new InvalidArgumentException( - 'AsyncAWS options must hold block_location (string), block_permissions (null or array), copy_part_size (int), file_fast_path (bool) and part_size (int)', + 'AsyncAWS options must hold block_location (string), block_permissions (null or array), bulk_delete (bool), copy_part_size (int), file_fast_path (bool) and part_size (int)', ); } @@ -91,6 +99,7 @@ public static function fromArray(array $data): self $data['block_permissions'] === null ? null : Permissions::fromArray($data['block_permissions']), ), ) + ->withBulkDelete($data['bulk_delete']) ->withCopyPartSize($data['copy_part_size']) ->withFileFastPath($data['file_fast_path']) ->withBlockSize($data['part_size']); @@ -108,6 +117,7 @@ public function normalize(): ?array return [ 'block_location' => $this->blockFactory->blockLocation(), 'block_permissions' => $this->blockFactory->permissions()?->normalize(), + 'bulk_delete' => $this->bulkDelete, 'copy_part_size' => $this->copyPartSize, 'file_fast_path' => $this->fileFastPath, 'part_size' => $this->partSize, @@ -137,6 +147,13 @@ public function withBlockSize(int $bytes): self return $this; } + public function withBulkDelete(bool $enabled = true): self + { + $this->bulkDelete = $enabled; + + return $this; + } + public function withCopyPartSize(int $bytes): self { if ($bytes < (5 * 1024 * 1024) || $bytes > 5_000_000_000) { diff --git a/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Mother/S3ClientMother.php b/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Mother/S3ClientMother.php index af13ef24b0..9446c9f83d 100644 --- a/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Mother/S3ClientMother.php +++ b/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Mother/S3ClientMother.php @@ -10,6 +10,10 @@ use Symfony\Component\HttpClient\Response\MockResponse; use function array_key_exists; +use function count; +use function explode; +use function htmlspecialchars; +use function implode; use function in_array; use function ltrim; use function max; @@ -25,6 +29,7 @@ use function substr; use function trim; +use const ENT_XML1; use const PHP_URL_PATH; use const PHP_URL_QUERY; @@ -32,6 +37,46 @@ final class S3ClientMother { public const string ERROR_XML = 'InternalErrorWe encountered an internal error.r'; + /** + * @param array, 2?: string}> $answers "Operation" answers every such request, "Operation#n" its n-th request only + * @param list $calls receives "Operation" per request: HeadObject, ListObjectsV2, DeleteObject, DeleteObjects + */ + public static function answering(array $answers, array &$calls): S3Client + { + /** @var array $counts */ + $counts = []; + + return new S3Client( + ['region' => 'eu-west-1', 'accessKeyId' => 'k', 'accessKeySecret' => 's', 'endpoint' => 'http://s3.test'], + null, + new MockHttpClient(static function (string $method, string $url) use ( + $answers, + &$calls, + &$counts, + ): MockResponse { + $query = []; + parse_str((string) parse_url($url, PHP_URL_QUERY), $query); + + $name = match (true) { + $method === 'HEAD' => 'HeadObject', + $method === 'GET' && ($query['list-type'] ?? null) === '2' => 'ListObjectsV2', + $method === 'DELETE' => 'DeleteObject', + $method === 'POST' && array_key_exists('delete', $query) => 'DeleteObjects', + default => 'Unexpected ' . $method . ' ' . $url, + }; + $counts[$name] = ($counts[$name] ?? 0) + 1; + $calls[] = $name; + + $answer = $answers[$name . '#' . $counts[$name]] ?? $answers[$name] ?? [500, [], '']; + + return new MockResponse($answer[2] ?? '', [ + 'http_code' => $answer[0], + 'response_headers' => $answer[1], + ]); + }), + ); + } + /** * @param list $calls receives "Operation key range" per request, e.g. "UploadPartCopy dst.bin bytes=0-5242879" */ @@ -212,6 +257,51 @@ public static function copyingWithStatusOn(int $sourceSize, string $operation, i ); } + public static function deleteResult(string ...$failedKeyCodes): string + { + $errors = []; + + foreach ($failedKeyCodes as $failedKeyCode) { + [$key, $code] = explode(':', $failedKeyCode, 2); + $errors[] = + '' + . htmlspecialchars($key, ENT_XML1) + . '' + . $code + . '' + . $code + . ''; + } + + return ( + '' + . implode('', $errors) + . '' + ); + } + + public static function listing(string ...$keys): string + { + $contents = []; + + foreach ($keys as $key) { + $contents[] = + '' + . htmlspecialchars($key, ENT_XML1) + . '' + . '2026-11-18T12:00:00.000Z1'; + } + + return ( + '' + . 'bucket' + . count($keys) + . 'false' + . implode('', $contents) + . '' + ); + } + public static function serving(string $content): S3Client { return new S3Client( diff --git a/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/AsyncAWSS3FilesystemTest.php b/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/AsyncAWSS3FilesystemTest.php index a89d8f08fa..fe8dd2079d 100644 --- a/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/AsyncAWSS3FilesystemTest.php +++ b/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/AsyncAWSS3FilesystemTest.php @@ -15,11 +15,13 @@ use Flow\Types\Exception\InvalidArgumentException; use PHPUnit\Framework\TestCase; +use function array_map; use function end; use function Flow\Filesystem\Bridge\AsyncAWS\DSL\aws_s3_filesystem; use function Flow\Filesystem\Bridge\AsyncAWS\DSL\aws_s3_filesystem_options; use function Flow\Filesystem\DSL\path; use function iterator_to_array; +use function range; final class AsyncAWSS3FilesystemTest extends TestCase { @@ -288,4 +290,110 @@ public function test_mv_aborts_when_complete_answers_error_xml(): void static::assertContains('AbortMultipartUpload dst', $calls); static::assertNotContains('DeleteObject src', $calls); } + + public function test_rm_of_a_directory_sends_one_delete_objects(): void + { + $calls = []; + + static::assertTrue(aws_s3_filesystem('bucket', S3ClientMother::answering([ + 'HeadObject' => [404, []], + 'ListObjectsV2' => [200, [], S3ClientMother::listing('dir/a.txt', 'dir/b.txt', 'dir/c.txt')], + 'DeleteObject' => [204, []], + 'DeleteObjects' => [200, [], S3ClientMother::deleteResult()], + ], $calls))->rm(path('aws-s3://dir'))); + + static::assertSame(['HeadObject', 'ListObjectsV2', 'DeleteObjects'], $calls); + } + + public function test_rm_without_bulk_delete_sends_one_delete_object_per_key(): void + { + $calls = []; + + static::assertTrue(aws_s3_filesystem( + 'bucket', + S3ClientMother::answering([ + 'HeadObject' => [404, []], + 'ListObjectsV2' => [200, [], S3ClientMother::listing('dir/a.txt', 'dir/b.txt', 'dir/c.txt')], + 'DeleteObject' => [204, []], + 'DeleteObjects' => [200, [], S3ClientMother::deleteResult()], + ], $calls), + aws_s3_filesystem_options()->withBulkDelete(false), + )->rm(path('aws-s3://dir'))); + + static::assertSame(['HeadObject', 'ListObjectsV2', 'DeleteObject', 'DeleteObject', 'DeleteObject'], $calls); + } + + public function test_rm_of_a_pattern_sends_one_delete_objects_per_1000_keys(): void + { + $calls = []; + + static::assertTrue(aws_s3_filesystem('bucket', S3ClientMother::answering([ + 'ListObjectsV2' => [ + 200, + [], + S3ClientMother::listing(...array_map( + static fn(int $index): string => "dir/{$index}.csv", + range(0, 1000), + )), + ], + 'DeleteObject' => [204, []], + 'DeleteObjects' => [200, [], S3ClientMother::deleteResult()], + ], $calls))->rm(path('aws-s3://dir/*.csv'))); + + static::assertSame(['ListObjectsV2', 'DeleteObjects', 'DeleteObjects'], $calls); + } + + public function test_rm_of_a_non_empty_directory_without_recursion_sends_no_delete(): void + { + $calls = []; + + try { + aws_s3_filesystem('bucket', S3ClientMother::answering([ + 'HeadObject' => [404, []], + 'ListObjectsV2' => [200, [], S3ClientMother::listing('dir/a.txt')], + ], $calls))->rm(path('aws-s3://dir'), recursive: false); + + static::fail('rm() of a non-empty directory without recursion must throw'); + } catch (RuntimeException $exception) { + static::assertSame('Directory aws-s3://dir was not removed: it is not empty', $exception->getMessage()); + } + + static::assertSame(['HeadObject', 'ListObjectsV2'], $calls); + } + + public function test_rm_of_refused_keys_throws_before_the_next_delete_objects(): void + { + $calls = []; + + try { + aws_s3_filesystem('bucket', S3ClientMother::answering([ + 'ListObjectsV2' => [ + 200, + [], + S3ClientMother::listing(...array_map( + static fn(int $index): string => "dir/{$index}.csv", + range(0, 1000), + )), + ], + 'DeleteObjects' => [ + 200, + [], + S3ClientMother::deleteResult( + 'dir/7.csv:AccessDenied', + 'dir/8.csv:AccessDenied', + 'dir/9.csv:AccessDenied', + ), + ], + ], $calls))->rm(path('aws-s3://dir/*.csv')); + + static::fail('rm() of refused keys must throw'); + } catch (RuntimeException $exception) { + static::assertSame( + '3 of 1000 paths were not removed, the first is aws-s3://dir/7.csv: AccessDenied', + $exception->getMessage(), + ); + } + + static::assertSame(['ListObjectsV2', 'DeleteObjects'], $calls); + } } diff --git a/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/OptionsTest.php b/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/OptionsTest.php index ec1f72ce94..14fb7c33a6 100644 --- a/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/OptionsTest.php +++ b/src/bridge/filesystem/async-aws/tests/Flow/Filesystem/Bridge/AsyncAWS/Tests/Unit/OptionsTest.php @@ -32,6 +32,7 @@ public function test_normalize_round_trips(): void { $options = (new Options()) ->withFileFastPath(false) + ->withBulkDelete(false) ->withBlockSize(6 * 1024 * 1024) ->withCopyPartSize(6 * 1024 * 1024); @@ -41,6 +42,7 @@ public function test_normalize_round_trips(): void [ 'block_location' => sys_get_temp_dir(), 'block_permissions' => null, + 'bulk_delete' => false, 'copy_part_size' => 6 * 1024 * 1024, 'file_fast_path' => false, 'part_size' => 6 * 1024 * 1024, diff --git a/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/AzureBlobFilesystem.php b/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/AzureBlobFilesystem.php index 2fffcd8d3f..f7f252f73c 100644 --- a/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/AzureBlobFilesystem.php +++ b/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/AzureBlobFilesystem.php @@ -4,11 +4,11 @@ namespace Flow\Filesystem\Bridge\Azure; -use Exception; use Flow\Azure\SDK\BlobService\BlockBlob\Block; use Flow\Azure\SDK\BlobService\BlockBlob\BlockList; use Flow\Azure\SDK\BlobService\BlockBlob\BlockState; use Flow\Azure\SDK\BlobService\PutBlockBlobBlockList\PutBlockBlobBlockListOptions; +use Flow\Azure\SDK\Exception\AzureException; use Flow\Filesystem\DestinationStream; use Flow\Filesystem\Exception\InvalidSchemeException; use Flow\Filesystem\Exception\RuntimeException; @@ -24,6 +24,7 @@ use function bin2hex; use function ceil; +use function count; use function Flow\Filesystem\DSL\path; use function Flow\Types\DSL\type_array; use function Flow\Types\DSL\type_string; @@ -31,8 +32,10 @@ use function max; use function min; use function random_bytes; +use function rawurldecode; use function sprintf; use function str_ends_with; +use function strlen; use function trim; /** @@ -47,6 +50,8 @@ private const int AZURE_MAX_BLOCKS = 50_000; + private const int BLOB_BATCH_LIMIT = 256; + public function __construct( private Mount $mount, private BlobServiceSource $blobService, @@ -250,41 +255,27 @@ public function rm(Path $path, bool $recursive = true): bool $this->mount->supports($path) || throw new InvalidSchemeException($path->protocol(), $this->mount->protocol); if ($path->isPattern()) { - $deletedCount = 0; - - foreach ($this->list($path) as $fileStatus) { - $this->blobService->blobService()->deleteBlob($fileStatus->path->path()); - $deletedCount++; - } - - return (bool) $deletedCount; + return $this->deleteListed($path); } try { - $this->blobService->blobService()->deleteBlob($path->path()); + $this->blobService->blobService()->deleteBlob(ltrim($path->path(), DIRECTORY_SEPARATOR)); return true; - } catch (Exception) { - /** - * Since AzureBlobStorage doesn't have a concept of folders, before we check if the intention is not to delete - * entire path, like for example azure-blob://nested/folder we need to first add / at the end, to accidentally - * not delete files that would also match the prefix, like: azure-blob://nested/folder_but_file.txt. - */ - $folderPath = path(trim($path->uri(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $path->options()); - - if (!$recursive && $this->list($folderPath)->valid()) { - throw new RuntimeException("Directory {$path->uri()} was not removed: it is not empty"); + } catch (AzureException $exception) { + if ($exception->response->getStatusCode() !== 404) { + throw $exception; } + } - $deletedCount = 0; - - foreach ($this->list($folderPath) as $fileStatus) { - $this->blobService->blobService()->deleteBlob($fileStatus->path->path()); - $deletedCount++; - } + // the trailing slash keeps "folder" from matching "folder_but_file.txt" + $folderPath = path(trim($path->uri(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $path->options()); - return (bool) $deletedCount; + if (!$recursive && $this->list($folderPath)->valid()) { + throw new RuntimeException("Directory {$path->uri()} was not removed: it is not empty"); } + + return $this->deleteListed($folderPath); } public function status(Path $path): ?FileStatus @@ -305,11 +296,7 @@ public function status(Path $path): ?FileStatus ->getBlobProperties(ltrim($path->path(), DIRECTORY_SEPARATOR)); if ($blobProperties === null) { - /** - * Since AzureBlobStorage doesn't have a concept of folders, before we check if the intention is not to delete - * entire path, like for example azure-blob://nested/folder we need to first add / at the end, to accidentally - * not match files that would also match the prefix, like: azure-blob://nested/folder_but_file.txt. - */ + // the trailing slash keeps "folder" from matching "folder_but_file.txt" $folderPath = path(trim($path->uri(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $path->options()); foreach ($this->list($folderPath) as $fileStatus) { @@ -349,4 +336,68 @@ public function writeTo(Path $path): DestinationStream $this->options->blockSize(), ); } + + /** + * @param non-empty-list $blobs + */ + private function deleteBlobs(Path $listed, array $blobs): void + { + try { + $this->blobService->blobService()->deleteBlobs($blobs); + } catch (AzureException $exception) { + $requestPath = rawurldecode($exception->request->getUri()->getPath()); + $failedBlob = ''; + + foreach ($blobs as $blob) { + if (strlen($blob) > strlen($failedBlob) && str_ends_with($requestPath, '/' . $blob)) { + $failedBlob = $blob; + } + } + + if ($failedBlob === '') { + throw $exception; + } + + throw new RuntimeException( + sprintf( + '%d of %d paths were not removed, the first is %s: %s', + $exception->failedRequests, + count($blobs), + path($listed->protocol() . '://' . DIRECTORY_SEPARATOR . $failedBlob, $listed->options())->uri(), + $exception->response->getHeaderLine('x-ms-error-code'), + ), + previous: $exception, + ); + } + } + + private function deleteListed(Path $path): bool + { + $blobs = []; + $deleted = false; + + foreach ($this->list($path) as $fileStatus) { + $blob = ltrim($fileStatus->path->path(), DIRECTORY_SEPARATOR); + $deleted = true; + + if (!$this->options->bulkDelete()) { + $this->blobService->blobService()->deleteBlob($blob); + + continue; + } + + $blobs[] = $blob; + + if (count($blobs) === self::BLOB_BATCH_LIMIT) { + $this->deleteBlobs($path, $blobs); + $blobs = []; + } + } + + if ($blobs !== []) { + $this->deleteBlobs($path, $blobs); + } + + return $deleted; + } } diff --git a/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/Options.php b/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/Options.php index e405885065..55de9bc978 100644 --- a/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/Options.php +++ b/src/bridge/filesystem/azure/src/Flow/Filesystem/Bridge/Azure/Options.php @@ -25,7 +25,7 @@ use function sprintf; /** - * @type AzureOptions = array{block_location: string, block_permissions: null|PermissionsShape, block_size: int, copy_part_size: int, file_fast_path: bool, list_blob_include: null|list, list_blob_max_results: null|int, list_blob_show_only: null|string, tmp_dir: PathData} + * @type AzureOptions = array{block_location: string, block_permissions: null|PermissionsShape, block_size: int, bulk_delete: bool, copy_part_size: int, file_fast_path: bool, list_blob_include: null|list, list_blob_max_results: null|int, list_blob_show_only: null|string, tmp_dir: PathData} * @import-type PathData from Path * @import-type PermissionsShape from Permissions */ @@ -36,6 +36,8 @@ final class Options /** @var int<1, max> */ private int $blockSize = 1024 * 1024 * 4; + private bool $bulkDelete = true; + /** @var int<1, 268435456> */ private int $copyPartSize = 256 * 1024 * 1024; @@ -71,6 +73,11 @@ public function blockSize(): int return $this->blockSize; } + public function bulkDelete(): bool + { + return $this->bulkDelete; + } + /** * @return int<1, 268435456> */ @@ -115,6 +122,7 @@ public static function fromArray(array $data): self || !array_key_exists('block_permissions', $data) || $data['block_permissions'] !== null && !is_array($data['block_permissions']) || !is_int($data['block_size'] ?? null) + || !is_bool($data['bulk_delete'] ?? null) || !is_int($data['copy_part_size'] ?? null) || !is_bool($data['file_fast_path'] ?? null) || !is_array($data['tmp_dir'] ?? null) @@ -123,7 +131,7 @@ public static function fromArray(array $data): self || !array_key_exists('list_blob_show_only', $data) ) { throw new InvalidArgumentException( - 'Azure options must hold block_location, block_permissions, block_size, copy_part_size, file_fast_path, list_blob_include, list_blob_max_results, list_blob_show_only and tmp_dir', + 'Azure options must hold block_location, block_permissions, block_size, bulk_delete, copy_part_size, file_fast_path, list_blob_include, list_blob_max_results, list_blob_show_only and tmp_dir', ); } @@ -135,6 +143,7 @@ public static function fromArray(array $data): self ), ) ->withBlockSize($data['block_size']) + ->withBulkDelete($data['bulk_delete']) ->withCopyPartSize($data['copy_part_size']) ->withFileFastPath($data['file_fast_path']) ->withTmpDir(Path::fromArray($data['tmp_dir'])); @@ -184,6 +193,7 @@ public function normalize(): ?array 'block_location' => $this->blockFactory->blockLocation(), 'block_permissions' => $this->blockFactory->permissions()?->normalize(), 'block_size' => $this->blockSize, + 'bulk_delete' => $this->bulkDelete, 'copy_part_size' => $this->copyPartSize, 'file_fast_path' => $this->fileFastPath, 'list_blob_include' => $this->listBlobInclude === null @@ -221,6 +231,13 @@ public function withBlockSize(int $blockSize): self return $this; } + public function withBulkDelete(bool $enabled = true): self + { + $this->bulkDelete = $enabled; + + return $this; + } + public function withCopyPartSize(int $bytes): self { if ($bytes < 1 || $bytes > (256 * 1024 * 1024)) { diff --git a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/InMemoryBlobService.php b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/InMemoryBlobService.php index ed7da5a055..ece9917b32 100644 --- a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/InMemoryBlobService.php +++ b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/InMemoryBlobService.php @@ -8,6 +8,7 @@ use Flow\Azure\SDK\BlobService\CopyBlob\CopyBlobOptions; use Flow\Azure\SDK\BlobService\CreateContainer\CreateContainerOptions; use Flow\Azure\SDK\BlobService\DeleteBlob\DeleteBlobOptions; +use Flow\Azure\SDK\BlobService\DeleteBlobs\DeleteBlobsOptions; use Flow\Azure\SDK\BlobService\DeleteContainer\DeleteContainerOptions; use Flow\Azure\SDK\BlobService\GetBlob\BlobContent; use Flow\Azure\SDK\BlobService\GetBlob\GetBlobOptions; @@ -52,6 +53,8 @@ public function copyBlob( public function deleteBlob(string $blob, DeleteBlobOptions $options = new DeleteBlobOptions()): void {} + public function deleteBlobs(array $blobs, DeleteBlobsOptions $options = new DeleteBlobsOptions()): void {} + public function deleteContainer(DeleteContainerOptions $options = new DeleteContainerOptions()): void {} public function getBlob(string $blob, GetBlobOptions $options = new GetBlobOptions()): BlobContent diff --git a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/RecordingBlobService.php b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/RecordingBlobService.php index 768a58d643..9159fab976 100644 --- a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/RecordingBlobService.php +++ b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Double/RecordingBlobService.php @@ -8,6 +8,7 @@ use Flow\Azure\SDK\BlobService\CopyBlob\CopyBlobOptions; use Flow\Azure\SDK\BlobService\CreateContainer\CreateContainerOptions; use Flow\Azure\SDK\BlobService\DeleteBlob\DeleteBlobOptions; +use Flow\Azure\SDK\BlobService\DeleteBlobs\DeleteBlobsOptions; use Flow\Azure\SDK\BlobService\DeleteContainer\DeleteContainerOptions; use Flow\Azure\SDK\BlobService\GetBlob\BlobContent; use Flow\Azure\SDK\BlobService\GetBlob\GetBlobOptions; @@ -31,6 +32,8 @@ final class RecordingBlobService implements BlobServiceInterface public int $deleteBlobCount = 0; + public int $deleteBlobsCount = 0; + public int $getBlobPropertiesCount = 0; public int $listBlobsCount = 0; @@ -51,6 +54,12 @@ public function deleteBlob(string $blob, DeleteBlobOptions $options = new Delete $this->delegate->deleteBlob($blob, $options); } + public function deleteBlobs(array $blobs, DeleteBlobsOptions $options = new DeleteBlobsOptions()): void + { + $this->deleteBlobsCount++; + $this->delegate->deleteBlobs($blobs, $options); + } + public function deleteContainer(DeleteContainerOptions $options = new DeleteContainerOptions()): void { $this->delegate->deleteContainer($options); diff --git a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Mother/BlobServiceMother.php b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Mother/BlobServiceMother.php index ac77ef8952..af1a5a109b 100644 --- a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Mother/BlobServiceMother.php +++ b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Mother/BlobServiceMother.php @@ -17,18 +17,21 @@ use function Flow\Azure\SDK\DSL\azure_http_factory; use function Flow\Azure\SDK\DSL\azure_shared_key_authorization_factory; use function Flow\Azure\SDK\DSL\azure_url_factory; +use function htmlspecialchars; +use function implode; use function parse_str; use function parse_url; use function strlen; use function substr; use function trim; +use const ENT_XML1; use const PHP_URL_QUERY; final class BlobServiceMother { /** - * @param array}> $answers "Operation" answers every such request, "Operation#n" its n-th request only + * @param array, 2?: string}> $answers "Operation" answers every such request, "Operation#n" its n-th request only * @param list $calls receives "Operation" per request, "PutBlockFromUrl bytes=-" for a ranged block * @param list> $putBlockListHeaders receives the lowercased headers of every PutBlockList request */ @@ -64,6 +67,8 @@ static function (string $method, string $url, array $options) use ( $name = match (true) { $method === 'HEAD' => 'GetBlobProperties', $method === 'DELETE' => 'DeleteBlob', + $method === 'GET' && ($query['comp'] ?? null) === 'list' => 'ListBlobs', + $method === 'POST' && ($query['comp'] ?? null) === 'batch' => 'BlobBatch', $method === 'PUT' && ($query['comp'] ?? null) === 'blocklist' => 'PutBlockList', $method === 'PUT' && ($query['comp'] ?? null) === 'block' && $copySource => 'PutBlockFromUrl', $method === 'PUT' && $copySource && ($headers['x-ms-requires-sync'] ?? null) === 'true' @@ -77,9 +82,12 @@ static function (string $method, string $url, array $options) use ( $putBlockListHeaders[] = $headers; } - [$status, $responseHeaders] = $answers[$name . '#' . $counts[$name]] ?? $answers[$name] ?? [500, []]; + $answer = $answers[$name . '#' . $counts[$name]] ?? $answers[$name] ?? [500, [], '']; - return new MockResponse('', ['http_code' => $status, 'response_headers' => $responseHeaders]); + return new MockResponse($answer[2] ?? '', [ + 'http_code' => $answer[0], + 'response_headers' => $answer[1], + ]); }, )); @@ -92,4 +100,43 @@ static function (string $method, string $url, array $options) use ( new NullLogger(), ); } + + public static function batchAnswer(int ...$statuses): string + { + $parts = []; + + foreach ($statuses as $contentId => $status) { + $errorCode = match ($status) { + 202 => '', + 403 => "x-ms-error-code: AuthorizationFailure\r\n", + 404 => "x-ms-error-code: BlobNotFound\r\n", + default => "x-ms-error-code: InternalError\r\n", + }; + $parts[] = + "--batchresponse_test\r\nContent-Type: application/http\r\nContent-ID: {$contentId}\r\n\r\n" + . "HTTP/1.1 {$status} Status\r\n{$errorCode}x-ms-version: 2024-08-04\r\n\r\n"; + } + + return implode('', $parts) . "--batchresponse_test--\r\n"; + } + + public static function listing(string ...$blobs): string + { + $entries = []; + + foreach ($blobs as $blob) { + $entries[] = + '' + . htmlspecialchars($blob, ENT_XML1) + . '' + . 'Wed, 18 Nov 2026 12:00:00 GMT1' + . ''; + } + + return ( + '' + . implode('', $entries) + . '' + ); + } } diff --git a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/AzureBlobFilesystemTest.php b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/AzureBlobFilesystemTest.php index c5a4db6b5d..e6dde8ebbd 100644 --- a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/AzureBlobFilesystemTest.php +++ b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/AzureBlobFilesystemTest.php @@ -13,11 +13,14 @@ use Flow\Types\Exception\InvalidArgumentException; use PHPUnit\Framework\TestCase; +use function array_fill; +use function array_map; use function Flow\Filesystem\Bridge\Azure\DSL\azure_filesystem; use function Flow\Filesystem\Bridge\Azure\DSL\azure_filesystem_options; use function Flow\Filesystem\DSL\path; use function in_array; use function iterator_to_array; +use function range; final class AzureBlobFilesystemTest extends TestCase { @@ -269,4 +272,192 @@ public function test_mv_of_a_missing_source_copies_nothing(): void static::assertSame(['GetBlobProperties'], $calls); } + + public function test_rm_of_a_file_rethrows_a_refused_delete(): void + { + $calls = []; + + try { + azure_filesystem(BlobServiceMother::answering([ + 'DeleteBlob' => [403, ['x-ms-error-code' => 'AuthorizationFailure']], + 'ListBlobs' => [200, [], BlobServiceMother::listing()], + ], $calls))->rm(path('azure-blob://a.txt')); + + static::fail('rm() of a refused delete must throw'); + } catch (AzureException) { + } + + static::assertSame(['DeleteBlob'], $calls); + } + + public function test_rm_of_a_directory_sends_one_batch(): void + { + $calls = []; + + static::assertTrue(azure_filesystem(BlobServiceMother::answering([ + 'DeleteBlob#1' => [404, ['x-ms-error-code' => 'BlobNotFound']], + 'DeleteBlob' => [202, []], + 'ListBlobs' => [200, [], BlobServiceMother::listing('dir/a.txt', 'dir/b.txt', 'dir/c.txt')], + 'BlobBatch' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(202, 202, 202), + ], + ], $calls))->rm(path('azure-blob://dir'))); + + static::assertSame(['DeleteBlob', 'ListBlobs', 'BlobBatch'], $calls); + } + + public function test_rm_of_a_pattern_sends_one_batch_per_256_blobs(): void + { + $calls = []; + + static::assertTrue(azure_filesystem(BlobServiceMother::answering([ + 'DeleteBlob' => [202, []], + 'ListBlobs' => [ + 200, + [], + BlobServiceMother::listing(...array_map( + static fn(int $index): string => "dir/{$index}.csv", + range(0, 256), + )), + ], + 'BlobBatch#1' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(...array_fill(0, 256, 202)), + ], + 'BlobBatch#2' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(202), + ], + ], $calls))->rm(path('azure-blob://dir/*.csv'))); + + static::assertSame(['ListBlobs', 'BlobBatch', 'BlobBatch'], $calls); + } + + public function test_rm_without_bulk_delete_sends_one_delete_blob_per_blob(): void + { + $calls = []; + + static::assertTrue(azure_filesystem(BlobServiceMother::answering([ + 'DeleteBlob#1' => [404, ['x-ms-error-code' => 'BlobNotFound']], + 'DeleteBlob' => [202, []], + 'ListBlobs' => [200, [], BlobServiceMother::listing('dir/a.txt', 'dir/b.txt', 'dir/c.txt')], + 'BlobBatch' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(202, 202, 202), + ], + ], $calls), azure_filesystem_options()->withBulkDelete(false))->rm(path('azure-blob://dir'))); + + static::assertSame(['DeleteBlob', 'ListBlobs', 'DeleteBlob', 'DeleteBlob', 'DeleteBlob'], $calls); + } + + public function test_rm_counts_a_missing_blob_of_a_batch_as_deleted(): void + { + $calls = []; + + static::assertTrue(azure_filesystem(BlobServiceMother::answering([ + 'ListBlobs' => [200, [], BlobServiceMother::listing('dir/a.csv', 'dir/b.csv')], + 'BlobBatch' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(202, 404), + ], + ], $calls))->rm(path('azure-blob://dir/*.csv'))); + } + + public function test_rm_of_a_non_empty_directory_without_recursion_sends_no_batch(): void + { + $calls = []; + + try { + azure_filesystem(BlobServiceMother::answering([ + 'DeleteBlob' => [404, ['x-ms-error-code' => 'BlobNotFound']], + 'ListBlobs' => [200, [], BlobServiceMother::listing('dir/a.txt')], + ], $calls))->rm(path('azure-blob://dir'), recursive: false); + + static::fail('rm() of a non-empty directory without recursion must throw'); + } catch (RuntimeException $exception) { + static::assertSame('Directory azure-blob://dir was not removed: it is not empty', $exception->getMessage()); + } + + static::assertSame(['DeleteBlob', 'ListBlobs'], $calls); + } + + public function test_rm_of_refused_blobs_throws_before_the_next_batch(): void + { + $calls = []; + + try { + azure_filesystem(BlobServiceMother::answering([ + 'ListBlobs' => [ + 200, + [], + BlobServiceMother::listing(...array_map( + static fn(int $index): string => "dir/{$index}.csv", + range(0, 256), + )), + ], + 'BlobBatch' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(202, 403, 403, ...array_fill(0, 253, 202)), + ], + ], $calls))->rm(path('azure-blob://dir/*.csv')); + + static::fail('rm() of refused blobs must throw'); + } catch (RuntimeException $exception) { + static::assertSame( + '2 of 256 paths were not removed, the first is azure-blob://dir/1.csv: AuthorizationFailure', + $exception->getMessage(), + ); + static::assertInstanceOf(AzureException::class, $exception->getPrevious()); + } + + static::assertSame(['ListBlobs', 'BlobBatch'], $calls); + } + + public function test_rm_rethrows_a_refused_batch_request(): void + { + $calls = []; + + try { + azure_filesystem(BlobServiceMother::answering([ + 'DeleteBlob' => [404, ['x-ms-error-code' => 'BlobNotFound']], + 'ListBlobs' => [200, [], BlobServiceMother::listing('dir/a.txt', 'dir/b.txt')], + 'BlobBatch' => [403, ['x-ms-error-code' => 'AuthorizationFailure']], + ], $calls))->rm(path('azure-blob://dir')); + + static::fail('rm() of a refused batch request must throw'); + } catch (AzureException) { + } + + static::assertSame(['DeleteBlob', 'ListBlobs', 'BlobBatch'], $calls); + } + + public function test_rm_names_the_longest_matching_blob_of_a_refused_batch(): void + { + $calls = []; + + try { + azure_filesystem(BlobServiceMother::answering([ + 'ListBlobs' => [200, [], BlobServiceMother::listing('b.csv', 'a/b.csv')], + 'BlobBatch' => [ + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + BlobServiceMother::batchAnswer(202, 403), + ], + ], $calls))->rm(path('azure-blob://**/*.csv')); + + static::fail('rm() of a refused blob must throw'); + } catch (RuntimeException $exception) { + static::assertSame( + '1 of 2 paths were not removed, the first is azure-blob://a/b.csv: AuthorizationFailure', + $exception->getMessage(), + ); + } + } } diff --git a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/OptionsTest.php b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/OptionsTest.php index bde4503c05..b95c3d9707 100644 --- a/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/OptionsTest.php +++ b/src/bridge/filesystem/azure/tests/Flow/Filesystem/Bridge/Azure/Tests/Unit/OptionsTest.php @@ -24,6 +24,7 @@ public function test_normalize_round_trips_every_option(): void { $options = (new Options()) ->withBlockSize(1024) + ->withBulkDelete(false) ->withFileFastPath(false) ->withListBlobInclude(OptionInclude::METADATA, OptionInclude::SNAPSHOTS) ->withListBlobMaxResults(50) @@ -32,6 +33,7 @@ public function test_normalize_round_trips_every_option(): void $normalized = $options->normalize(); static::assertNotNull($normalized); + static::assertFalse($normalized['bulk_delete']); static::assertSame(['metadata', 'snapshots'], $normalized['list_blob_include']); static::assertSame('files', $normalized['list_blob_show_only']); static::assertEquals($options, Options::fromArray($normalized)); @@ -111,7 +113,7 @@ public function test_from_array_refuses_a_configuration_without_copy_part_size() $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( - 'Azure options must hold block_location, block_permissions, block_size, copy_part_size, file_fast_path, list_blob_include, list_blob_max_results, list_blob_show_only and tmp_dir', + 'Azure options must hold block_location, block_permissions, block_size, bulk_delete, copy_part_size, file_fast_path, list_blob_include, list_blob_max_results, list_blob_show_only and tmp_dir', ); Options::fromArray($normalized); diff --git a/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AsyncAwsS3FilesystemFactory.php b/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AsyncAwsS3FilesystemFactory.php index 0f530680f4..37002cd1b6 100644 --- a/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AsyncAwsS3FilesystemFactory.php +++ b/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AsyncAwsS3FilesystemFactory.php @@ -21,6 +21,7 @@ use function get_debug_type; use function implode; use function is_array; +use function is_bool; use function is_int; use function is_scalar; use function is_string; @@ -196,7 +197,7 @@ private function buildOptions(mixed $optionsConfig): Options throw new InvalidArgumentException('Filesystem factory for backend "aws_s3" `options` must be an array.'); } - $allowed = ['block_size', 'copy_part_size']; + $allowed = ['block_size', 'bulk_delete', 'copy_part_size']; $unknown = array_diff(array_keys($optionsConfig), $allowed); if ($unknown !== []) { @@ -214,6 +215,13 @@ private function buildOptions(mixed $optionsConfig): Options $options = $options->withBlockSize($optionsConfig['block_size']); } + if (array_key_exists('bulk_delete', $optionsConfig) && $optionsConfig['bulk_delete'] !== null) { + if (!is_bool($optionsConfig['bulk_delete'])) { + throw new InvalidArgumentException('`options.bulk_delete` must be a boolean.'); + } + $options = $options->withBulkDelete($optionsConfig['bulk_delete']); + } + if (array_key_exists('copy_part_size', $optionsConfig) && $optionsConfig['copy_part_size'] !== null) { if (!is_int($optionsConfig['copy_part_size'])) { throw new InvalidArgumentException('`options.copy_part_size` must be an integer.'); diff --git a/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AzureBlobFilesystemFactory.php b/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AzureBlobFilesystemFactory.php index d8b4a2bc2f..c650ce2d9b 100644 --- a/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AzureBlobFilesystemFactory.php +++ b/src/bridge/symfony/filesystem-bundle/src/Flow/Bridge/Symfony/FilesystemBundle/Filesystem/Factory/AzureBlobFilesystemFactory.php @@ -29,6 +29,7 @@ use function get_debug_type; use function implode; use function is_array; +use function is_bool; use function is_int; use function is_string; use function sprintf; @@ -238,7 +239,7 @@ private function buildOptions(mixed $optionsConfig): Options ); } - $allowed = ['block_size', 'copy_part_size', 'list_blob_max_results']; + $allowed = ['block_size', 'bulk_delete', 'copy_part_size', 'list_blob_max_results']; $unknown = array_diff(array_keys($optionsConfig), $allowed); if ($unknown !== []) { @@ -256,6 +257,13 @@ private function buildOptions(mixed $optionsConfig): Options $options = $options->withBlockSize($optionsConfig['block_size']); } + if (array_key_exists('bulk_delete', $optionsConfig) && $optionsConfig['bulk_delete'] !== null) { + if (!is_bool($optionsConfig['bulk_delete'])) { + throw new InvalidArgumentException('`options.bulk_delete` must be a boolean.'); + } + $options = $options->withBulkDelete($optionsConfig['bulk_delete']); + } + if (array_key_exists('copy_part_size', $optionsConfig) && $optionsConfig['copy_part_size'] !== null) { if (!is_int($optionsConfig['copy_part_size'])) { throw new InvalidArgumentException('`options.copy_part_size` must be an integer.'); diff --git a/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Double/StubBlobService.php b/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Double/StubBlobService.php index e61435b988..19d262f44a 100644 --- a/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Double/StubBlobService.php +++ b/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Double/StubBlobService.php @@ -8,6 +8,7 @@ use Flow\Azure\SDK\BlobService\CopyBlob\CopyBlobOptions; use Flow\Azure\SDK\BlobService\CreateContainer\CreateContainerOptions; use Flow\Azure\SDK\BlobService\DeleteBlob\DeleteBlobOptions; +use Flow\Azure\SDK\BlobService\DeleteBlobs\DeleteBlobsOptions; use Flow\Azure\SDK\BlobService\DeleteContainer\DeleteContainerOptions; use Flow\Azure\SDK\BlobService\GetBlob\BlobContent; use Flow\Azure\SDK\BlobService\GetBlob\GetBlobOptions; @@ -36,6 +37,8 @@ public function copyBlob( public function deleteBlob(string $blob, DeleteBlobOptions $options = new DeleteBlobOptions()): void {} + public function deleteBlobs(array $blobs, DeleteBlobsOptions $options = new DeleteBlobsOptions()): void {} + public function deleteContainer(DeleteContainerOptions $options = new DeleteContainerOptions()): void {} public function getBlob(string $blob, GetBlobOptions $options = new GetBlobOptions()): BlobContent diff --git a/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AsyncAwsS3FilesystemFactoryTest.php b/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AsyncAwsS3FilesystemFactoryTest.php index 656022e433..2db9093707 100644 --- a/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AsyncAwsS3FilesystemFactoryTest.php +++ b/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AsyncAwsS3FilesystemFactoryTest.php @@ -298,6 +298,32 @@ public function test_client_http_must_be_an_array(): void ]); } + public function test_options_bulk_delete(): void + { + $configuration = (new AsyncAwsS3FilesystemFactory()) + ->create('aws-s3', [ + 'bucket' => 'b', + 'client' => ['region' => 'us-east-1'], + 'options' => ['bulk_delete' => false], + ]) + ->normalize(); + + static::assertNotNull($configuration); + static::assertFalse($configuration['options']['bulk_delete'] ?? null); + } + + public function test_options_bulk_delete_must_be_a_boolean(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('`options.bulk_delete` must be a boolean.'); + + (new AsyncAwsS3FilesystemFactory())->create('aws-s3', [ + 'bucket' => 'b', + 'client' => ['region' => 'us-east-1'], + 'options' => ['bulk_delete' => 'false'], + ]); + } + public function test_options_copy_part_size(): void { $configuration = (new AsyncAwsS3FilesystemFactory()) diff --git a/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AzureBlobFilesystemFactoryTest.php b/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AzureBlobFilesystemFactoryTest.php index 2ccb82518a..1ec0c31eb4 100644 --- a/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AzureBlobFilesystemFactoryTest.php +++ b/src/bridge/symfony/filesystem-bundle/tests/Flow/Bridge/Symfony/FilesystemBundle/Tests/Unit/Filesystem/Factory/AzureBlobFilesystemFactoryTest.php @@ -43,6 +43,29 @@ public function test_applies_copy_part_size_option(): void static::assertSame(5 * 1024 * 1024, $filesystem->normalize()['options']['copy_part_size'] ?? null); } + public function test_applies_bulk_delete_option(): void + { + $filesystem = (new AzureBlobFilesystemFactory())->create('azure-blob', [ + 'container' => 'c', + 'client' => ['account_name' => 'a', 'auth' => ['shared_key' => base64_encode('k')]], + 'options' => ['bulk_delete' => false], + ]); + + static::assertFalse($filesystem->normalize()['options']['bulk_delete'] ?? null); + } + + public function test_throws_on_invalid_bulk_delete_type(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('`options.bulk_delete` must be a boolean.'); + + (new AzureBlobFilesystemFactory())->create('azure-blob', [ + 'container' => 'c', + 'client' => ['account_name' => 'a', 'auth' => ['shared_key' => 'k']], + 'options' => ['bulk_delete' => 'false'], + ]); + } + public function test_throws_on_invalid_copy_part_size_type(): void { $this->expectException(InvalidArgumentException::class); diff --git a/src/bridge/symfony/filesystem-cache/src/Flow/Bridge/Symfony/FilesystemCache/FlowFilesystemCacheAdapter.php b/src/bridge/symfony/filesystem-cache/src/Flow/Bridge/Symfony/FilesystemCache/FlowFilesystemCacheAdapter.php index 124e09140c..9a29a07841 100644 --- a/src/bridge/symfony/filesystem-cache/src/Flow/Bridge/Symfony/FilesystemCache/FlowFilesystemCacheAdapter.php +++ b/src/bridge/symfony/filesystem-cache/src/Flow/Bridge/Symfony/FilesystemCache/FlowFilesystemCacheAdapter.php @@ -73,13 +73,13 @@ public function prune(): bool protected function doClear(string $namespace): bool { - foreach ($this->filesystem->list($this->listPattern(), new OnlyFiles()) as $status) { - if ($namespace === '') { - $this->filesystem->rm($status->path); + if ($namespace === '') { + $this->filesystem->rm($this->listPattern()); - continue; - } + return true; + } + foreach ($this->filesystem->list($this->listPattern(), new OnlyFiles()) as $status) { if (str_starts_with($this->readId($status->path), $namespace)) { $this->filesystem->rm($status->path); } diff --git a/src/bridge/symfony/filesystem-cache/tests/Flow/Bridge/Symfony/FilesystemCache/Tests/Unit/FlowFilesystemCacheAdapterTest.php b/src/bridge/symfony/filesystem-cache/tests/Flow/Bridge/Symfony/FilesystemCache/Tests/Unit/FlowFilesystemCacheAdapterTest.php index 13665efef4..b23205a41c 100644 --- a/src/bridge/symfony/filesystem-cache/tests/Flow/Bridge/Symfony/FilesystemCache/Tests/Unit/FlowFilesystemCacheAdapterTest.php +++ b/src/bridge/symfony/filesystem-cache/tests/Flow/Bridge/Symfony/FilesystemCache/Tests/Unit/FlowFilesystemCacheAdapterTest.php @@ -4,17 +4,21 @@ namespace Flow\Bridge\Symfony\FilesystemCache\Tests\Unit; +use ArrayObject; use Flow\Bridge\Symfony\FilesystemCache\Exception\FilesystemCacheException; use Flow\Bridge\Symfony\FilesystemCache\Tests\Context\FilesystemCacheContext; use Flow\Bridge\Symfony\FilesystemCache\Tests\Unit\Double\FailingMvFilesystem; use Flow\Bridge\Symfony\FilesystemCache\Tests\Unit\Double\SpyLogger; use Flow\Bridge\Symfony\FilesystemCache\Tests\Unit\Double\SpyMarshaller; +use Flow\Filesystem\Path; +use Flow\Filesystem\Testing\FilesystemOperation; use PHPUnit\Framework\TestCase; use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Marshaller\DefaultMarshaller; use Symfony\Contracts\Cache\ItemInterface as CacheItemInterface; use function explode; +use function Flow\Filesystem\DSL\intercepted_filesystem; use function iterator_to_array; use function sprintf; use function strlen; @@ -51,6 +55,44 @@ public function test_clear_with_empty_prefix_removes_all_items(): void static::assertFalse($adapter->getItem('b')->isHit()); } + public function test_clear_with_empty_prefix_removes_all_items_with_one_rm_call(): void + { + $removals = new ArrayObject(); + $adapter = $this->context->adapter(filesystem: intercepted_filesystem($this->context->filesystem)->onCall(static function ( + FilesystemOperation $operation, + Path $path, + ) use ($removals): void { + if ($operation === FilesystemOperation::Rm) { + $removals->append($path->uri()); + } + })); + + foreach (['a' => 1, 'b' => 2, 'c' => 3] as $key => $value) { + $adapter->save($adapter->getItem($key)->set($value)); + } + + static::assertCount(3, $this->context->listFiles()); + static::assertTrue($adapter->clear()); + + static::assertCount(1, $removals); + static::assertSame([], $this->context->listFiles()); + } + + public function test_save_and_get_item_work_after_clear_with_empty_prefix(): void + { + $adapter = $this->context->adapter(); + $adapter->save($adapter->getItem('a')->set(1)); + $adapter->save($adapter->getItem('b')->set(2)); + + static::assertTrue($adapter->clear()); + static::assertSame([], $this->context->listFiles()); + + $adapter->save($adapter->getItem('a')->set('again')); + + static::assertFalse($adapter->getItem('b')->isHit()); + static::assertSame('again', $adapter->getItem('a')->get()); + } + public function test_clear_with_prefix_only_removes_items_whose_id_starts_with_prefix(): void { $adapter = $this->context->adapter(); diff --git a/src/lib/azure-sdk/src/Flow/Azure/SDK/AuthorizationFactory/SharedKeyFactory.php b/src/lib/azure-sdk/src/Flow/Azure/SDK/AuthorizationFactory/SharedKeyFactory.php index c9a8d120fa..f769d16fbb 100644 --- a/src/lib/azure-sdk/src/Flow/Azure/SDK/AuthorizationFactory/SharedKeyFactory.php +++ b/src/lib/azure-sdk/src/Flow/Azure/SDK/AuthorizationFactory/SharedKeyFactory.php @@ -179,7 +179,8 @@ private function computeSignature(array $headers, string $url, array $queryParam $lowercaseHeaders = array_change_key_case($headers); foreach ($includedHeaders as $header) { - $stringToSign[] = $lowercaseHeaders[$header] ?? ''; + $value = $lowercaseHeaders[$header] ?? ''; + $stringToSign[] = $header === 'content-length' && $value === '0' ? '' : $value; } if (count($canonicalizedHeaders) > 0) { diff --git a/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService.php b/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService.php index 0371b67705..05175d3bdd 100644 --- a/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService.php +++ b/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService.php @@ -12,6 +12,7 @@ use Flow\Azure\SDK\BlobService\CopyBlob\CopyBlobOptions; use Flow\Azure\SDK\BlobService\CreateContainer\CreateContainerOptions; use Flow\Azure\SDK\BlobService\DeleteBlob\DeleteBlobOptions; +use Flow\Azure\SDK\BlobService\DeleteBlobs\DeleteBlobsOptions; use Flow\Azure\SDK\BlobService\DeleteContainer\DeleteContainerOptions; use Flow\Azure\SDK\BlobService\GetBlob\BlobContent; use Flow\Azure\SDK\BlobService\GetBlob\GetBlobOptions; @@ -32,19 +33,31 @@ use Generator; use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\ResponseInterface; use Psr\Log\LoggerInterface; use function array_key_exists; +use function array_keys; use function array_merge; +use function array_values; +use function bin2hex; +use function count; +use function explode; use function Flow\Types\DSL\type_array; use function Flow\Types\DSL\type_integer; use function Flow\Types\DSL\type_list; use function Flow\Types\DSL\type_string; use function Flow\Types\DSL\type_union; use function gmdate; +use function implode; +use function in_array; use function is_array; use function is_resource; use function is_string; +use function ltrim; +use function preg_match; +use function random_bytes; +use function rtrim; use function strlen; final readonly class BlobService implements BlobServiceInterface @@ -135,6 +148,118 @@ public function deleteBlob(string $blob, DeleteBlobOptions $options = new Delete } } + /** + * @param list $blobs at most 256, all in the configured container + * + * @throws AzureException + * @throws ClientExceptionInterface + * @throws InvalidArgumentException + */ + public function deleteBlobs(array $blobs, DeleteBlobsOptions $options = new DeleteBlobsOptions()): void + { + if ($blobs === []) { + return; + } + + count($blobs) <= 256 + || throw new InvalidArgumentException('Blob Batch accepts at most 256 blobs, got ' . count($blobs)); + + $boundary = 'batch_' . bin2hex(random_bytes(16)); + $date = gmdate('D, d M Y H:i:s T', time()); + $subrequests = []; + $body = ''; + + foreach (array_values($blobs) as $index => $blob) { + $subrequest = $this->httpFactory + ->delete($this->urlFactory->create($this->configuration, $blob)) + ->withHeader('date', $date) + ->withHeader('content-length', '0'); + + foreach ($options->toSubrequestHeaders() as $header => $value) { + $subrequest = $subrequest->withHeader($header, $value); + } + + $subrequests[$index] = $subrequest->withHeader( + 'authorization', + $this->authorizationFactory->for($subrequest), + ); + + $body .= + "--{$boundary}\r\nContent-Type: application/http\r\nContent-Transfer-Encoding: binary\r\n" + . "Content-ID: {$index}\r\n\r\nDELETE {$subrequests[$index]->getUri()->getPath()} HTTP/1.1\r\n"; + + foreach ($subrequests[$index]->getHeaders() as $header => $values) { + $body .= $header . ': ' . implode(', ', $values) . "\r\n"; + } + + $body .= "\r\n"; + } + + $body .= "--{$boundary}--\r\n"; + + $request = $this->httpFactory + ->post($this->urlFactory->create( + $this->configuration, + queryParameters: array_merge($options->toURIParameters(), [ + 'restype' => 'container', + 'comp' => 'batch', + ]), + )) + ->withHeader('date', $date) + ->withHeader('content-type', 'multipart/mixed; boundary=' . $boundary) + ->withHeader('content-length', (string) strlen($body)) + ->withBody($this->httpFactory->stream($body)); + + foreach ($options->toHeaders() as $header => $value) { + $request = $request->withHeader($header, $value); + } + + $this->logger->info('Azure - Blob Service - Blob Batch', ['request' => $request]); + + $request = $request->withHeader('authorization', $this->authorizationFactory->for($request)); + + $response = $this->httpClient->sendRequest($request); + + $this->logger->info('Azure - Blob Service - Blob Batch', ['response' => $response]); + + if ($response->getStatusCode() !== 202) { + $this->logger->critical('Azure - Blob Service - Blob Batch', ['response' => $response]); + + throw new AzureException(__METHOD__, $request, $response); + } + + $results = $this->blobBatchResults($response); + $failures = []; + + foreach (array_keys($subrequests) as $index) { + if (!array_key_exists($index, $results) || !in_array($results[$index][0], [202, 404], true)) { + $failures[] = $index; + } + } + + if ($failures === []) { + return; + } + + $this->logger->critical('Azure - Blob Service - Blob Batch', ['response' => $response]); + + if (!array_key_exists($failures[0], $results)) { + throw new AzureException(__METHOD__, $subrequests[$failures[0]], $response, count($failures)); + } + + [$status, $errorCode, $partBody] = $results[$failures[0]]; + + throw new AzureException( + __METHOD__, + $subrequests[$failures[0]], + $response + ->withStatus($status) + ->withHeader('x-ms-error-code', $errorCode) + ->withBody($this->httpFactory->stream($partBody)), + count($failures), + ); + } + /** * @throws AzureException * @throws ClientExceptionInterface @@ -658,4 +783,39 @@ public function putContainer(CreateContainerOptions $options = new CreateContain throw new AzureException(__METHOD__, $request, $response); } } + + /** + * @return array status, x-ms-error-code and body of each part, by Content-ID + */ + private function blobBatchResults(ResponseInterface $response): array + { + $boundary = []; + + if (preg_match('/boundary="?([^";]+)"?/i', $response->getHeaderLine('content-type'), $boundary) !== 1) { + return []; + } + + $results = []; + + foreach (explode('--' . $boundary[1], $response->getBody()->getContents()) as $part) { + $sections = explode("\r\n\r\n", ltrim($part, "\r\n"), 3); + $contentId = []; + $status = []; + $errorCode = []; + + if ( + count($sections) < 2 + || preg_match('/^Content-ID:\s*(\d+)/mi', $sections[0], $contentId) !== 1 + || preg_match('/^HTTP\/1\.1 (\d{3})/', $sections[1], $status) !== 1 + ) { + continue; + } + + preg_match('/^x-ms-error-code:\s*(\S+)/mi', $sections[1], $errorCode); + + $results[(int) $contentId[1]] = [(int) $status[1], $errorCode[1] ?? '', rtrim($sections[2] ?? '', "\r\n")]; + } + + return $results; + } } diff --git a/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService/DeleteBlobs/DeleteBlobsOptions.php b/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService/DeleteBlobs/DeleteBlobsOptions.php new file mode 100644 index 0000000000..0fcfa83b6d --- /dev/null +++ b/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobService/DeleteBlobs/DeleteBlobsOptions.php @@ -0,0 +1,101 @@ + + */ + public function toHeaders(): array + { + $headers = []; + + $headers['user-agent'] = $this->userAgentHeader(); + $headers['x-ms-version'] = $this->version; + + if ($this->requestId !== null) { + $headers['x-ms-client-request-id'] = $this->requestId; + } + + return $headers; + } + + /** + * @return array + */ + public function toSubrequestHeaders(): array + { + if ($this->deleteSnapshots === null) { + return []; + } + + return ['x-ms-delete-snapshots' => $this->deleteSnapshots->value]; + } + + /** + * @return array + */ + public function toURIParameters(): array + { + if ($this->timeoutSeconds === null) { + return []; + } + + return ['timeout' => $this->timeoutSeconds]; + } + + public function withDeleteSnapshots(DeleteSnapshots $deleteSnapshots): self + { + $this->deleteSnapshots = $deleteSnapshots; + + return $this; + } + + public function withRequestId(string $requestId): self + { + $this->requestId = $requestId; + + return $this; + } + + public function withTimeoutSeconds(int $timeoutSeconds): self + { + $this->timeoutSeconds = $timeoutSeconds; + + return $this; + } + + public function withVersion(string $version): self + { + $this->version = $version; + + return $this; + } + + public function userAgentHeader(): string + { + return $this->userAgentHeader; + } + + public function withUserAgent(string $userAgentHeader): void + { + $this->userAgentHeader = $userAgentHeader; + } +} diff --git a/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobServiceInterface.php b/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobServiceInterface.php index 1f0371c400..68ac33e60a 100644 --- a/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobServiceInterface.php +++ b/src/lib/azure-sdk/src/Flow/Azure/SDK/BlobServiceInterface.php @@ -8,6 +8,7 @@ use Flow\Azure\SDK\BlobService\CopyBlob\CopyBlobOptions; use Flow\Azure\SDK\BlobService\CreateContainer\CreateContainerOptions; use Flow\Azure\SDK\BlobService\DeleteBlob\DeleteBlobOptions; +use Flow\Azure\SDK\BlobService\DeleteBlobs\DeleteBlobsOptions; use Flow\Azure\SDK\BlobService\DeleteContainer\DeleteContainerOptions; use Flow\Azure\SDK\BlobService\GetBlob\BlobContent; use Flow\Azure\SDK\BlobService\GetBlob\GetBlobOptions; @@ -22,7 +23,10 @@ use Flow\Azure\SDK\BlobService\PutBlockBlobBlock\PutBlockBlobBlockOptions; use Flow\Azure\SDK\BlobService\PutBlockBlobBlockList\PutBlockBlobBlockListOptions; use Flow\Azure\SDK\BlobService\PutBlockBlobBlockList\SimpleXMLSerializer; +use Flow\Azure\SDK\Exception\AzureException; +use Flow\Azure\SDK\Exception\InvalidArgumentException; use Generator; +use Psr\Http\Client\ClientExceptionInterface; interface BlobServiceInterface { @@ -30,6 +34,15 @@ public function copyBlob(string $fromBlob, string $toBlob, CopyBlobOptions $opti public function deleteBlob(string $blob, DeleteBlobOptions $options = new DeleteBlobOptions()): void; + /** + * @param list $blobs at most 256, all in the configured container + * + * @throws AzureException + * @throws ClientExceptionInterface + * @throws InvalidArgumentException + */ + public function deleteBlobs(array $blobs, DeleteBlobsOptions $options = new DeleteBlobsOptions()): void; + public function deleteContainer(DeleteContainerOptions $options = new DeleteContainerOptions()): void; public function getBlob(string $blob, GetBlobOptions $options = new GetBlobOptions()): BlobContent; diff --git a/src/lib/azure-sdk/src/Flow/Azure/SDK/Exception/AzureException.php b/src/lib/azure-sdk/src/Flow/Azure/SDK/Exception/AzureException.php index db35576323..6aa5eef737 100644 --- a/src/lib/azure-sdk/src/Flow/Azure/SDK/Exception/AzureException.php +++ b/src/lib/azure-sdk/src/Flow/Azure/SDK/Exception/AzureException.php @@ -15,6 +15,7 @@ public function __construct( string $endpoint, public readonly RequestInterface $request, public readonly ResponseInterface $response, + public readonly int $failedRequests = 1, ) { parent::__construct(sprintf( 'Azure SDK Exception: %s, %d, %s', diff --git a/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Context/BlobServiceContext.php b/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Context/BlobServiceContext.php index 6a83399a26..ce22a7c264 100644 --- a/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Context/BlobServiceContext.php +++ b/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Context/BlobServiceContext.php @@ -33,6 +33,29 @@ public static function serviceWithClient(FixedResponseClient $client): BlobServi ); } + /** + * @param array $statuses status by Content-ID, in the order of the response parts + */ + public static function batchResponse(array $statuses): ResponseInterface + { + $body = ''; + + foreach ($statuses as $contentId => $status) { + $body .= + "--batchresponse_test\r\nContent-Type: application/http\r\nContent-ID: {$contentId}\r\n\r\n" + . "HTTP/1.1 {$status} Status\r\n" + . ($status >= 400 ? "x-ms-error-code: Code{$status}\r\n" : '') + . "\r\n" + . ($status >= 400 ? "Code{$status}\r\n" : ''); + } + + return self::responseWithHeaders( + 202, + ['Content-Type' => 'multipart/mixed; boundary=batchresponse_test'], + $body . "--batchresponse_test--\r\n", + ); + } + public static function response(int $status, string $body): ResponseInterface { return Psr17FactoryDiscovery::findResponseFactory() diff --git a/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/AuthorizationFactory/SharedKeyFactoryTest.php b/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/AuthorizationFactory/SharedKeyFactoryTest.php index 213096639a..db719b1252 100644 --- a/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/AuthorizationFactory/SharedKeyFactoryTest.php +++ b/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/AuthorizationFactory/SharedKeyFactoryTest.php @@ -10,6 +10,8 @@ use Http\Discovery\Psr17FactoryDiscovery; use PHPUnit\Framework\TestCase; +use function Flow\Azure\SDK\DSL\azure_shared_key_authorization_factory; + final class SharedKeyFactoryTest extends TestCase { public function test_for_returns_string_starting_with_shared_key_prefix_and_account(): void @@ -169,4 +171,19 @@ public function test_read_only_source_url_signs_the_expiry_in_utc(): void ), ); } + + public function test_zero_content_length_signs_as_an_empty_string(): void + { + $request = Psr17FactoryDiscovery::findRequestFactory() + ->createRequest('DELETE', 'https://account.blob.core.windows.net/container/a.txt') + ->withHeader('date', 'Wed, 18 Nov 2026 12:00:00 GMT'); + + static::assertSame( + azure_shared_key_authorization_factory('account', base64_encode('key'))->for($request), + azure_shared_key_authorization_factory('account', base64_encode('key'))->for($request->withHeader( + 'content-length', + '0', + )), + ); + } } diff --git a/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/BlobServiceTest.php b/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/BlobServiceTest.php index 4d5f3f45ba..35595da920 100644 --- a/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/BlobServiceTest.php +++ b/src/lib/azure-sdk/tests/Flow/Azure/SDK/Tests/Unit/BlobServiceTest.php @@ -7,12 +7,117 @@ use Flow\Azure\SDK\BlobService\BlockBlob\BlockState; use Flow\Azure\SDK\BlobService\ListBlobs\Blob; use Flow\Azure\SDK\Exception\AzureException; +use Flow\Azure\SDK\Exception\InvalidArgumentException; use Flow\Azure\SDK\Tests\Context\BlobServiceContext; use Flow\Azure\SDK\Tests\Double\FixedResponseClient; use PHPUnit\Framework\TestCase; +use function array_fill; +use function array_map; +use function range; +use function substr_count; + final class BlobServiceTest extends TestCase { + public function test_delete_blobs_counts_a_missing_blob_as_deleted(): void + { + $client = new FixedResponseClient(BlobServiceContext::batchResponse([0 => 202, 1 => 404])); + + BlobServiceContext::serviceWithClient($client)->deleteBlobs(['a.txt', 'b.txt']); + + static::assertCount(1, $client->requests()); + } + + public function test_delete_blobs_reads_parts_out_of_order(): void + { + $client = new FixedResponseClient(BlobServiceContext::batchResponse([2 => 202, 0 => 202, 1 => 202])); + + BlobServiceContext::serviceWithClient($client)->deleteBlobs(['a.txt', 'b.txt', 'c.txt']); + + static::assertCount(1, $client->requests()); + } + + public function test_delete_blobs_refuses_more_than_256_blobs(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Blob Batch accepts at most 256 blobs, got 257'); + + BlobServiceContext::service()->deleteBlobs(array_map( + static fn(int $index): string => "{$index}.txt", + range(0, 256), + )); + } + + public function test_delete_blobs_reports_every_failed_part_with_the_first_failed_subrequest(): void + { + try { + BlobServiceContext::service(BlobServiceContext::batchResponse([ + 0 => 202, + 1 => 403, + 2 => 500, + ]))->deleteBlobs([ + 'a.txt', + 'b.txt', + 'c.txt', + ]); + + static::fail('deleteBlobs() with failed parts must throw'); + } catch (AzureException $exception) { + static::assertSame(2, $exception->failedRequests); + static::assertSame('/container/b.txt', $exception->request->getUri()->getPath()); + static::assertSame(403, $exception->response->getStatusCode()); + static::assertSame('Code403', $exception->response->getHeaderLine('x-ms-error-code')); + static::assertStringContainsString('Code403', $exception->getMessage()); + } + } + + public function test_delete_blobs_reports_a_blob_without_a_part_as_failed(): void + { + try { + BlobServiceContext::service(BlobServiceContext::batchResponse([0 => 202]))->deleteBlobs(['a.txt', 'b.txt']); + + static::fail('deleteBlobs() with a missing part must throw'); + } catch (AzureException $exception) { + static::assertSame(1, $exception->failedRequests); + static::assertSame('/container/b.txt', $exception->request->getUri()->getPath()); + } + } + + public function test_delete_blobs_sends_no_request_for_no_blobs(): void + { + $client = new FixedResponseClient(); + + BlobServiceContext::serviceWithClient($client)->deleteBlobs([]); + + static::assertSame([], $client->requests()); + } + + public function test_delete_blobs_sends_one_batch_with_a_part_per_blob(): void + { + $client = new FixedResponseClient(BlobServiceContext::batchResponse(array_fill(0, 2, 202))); + + BlobServiceContext::serviceWithClient($client)->deleteBlobs(['dir/a.txt', 'dir/b.txt']); + + $request = $client->requests()[0]; + $body = (string) $request->getBody(); + static::assertSame('POST', $request->getMethod()); + static::assertSame('restype=container&comp=batch', $request->getUri()->getQuery()); + static::assertSame('2024-08-04', $request->getHeaderLine('x-ms-version')); + static::assertStringStartsWith('multipart/mixed; boundary=batch_', $request->getHeaderLine('content-type')); + static::assertSame(2, substr_count($body, "Content-Type: application/http\r\n")); + static::assertStringContainsString("Content-ID: 0\r\n\r\nDELETE /container/dir/a.txt HTTP/1.1\r\n", $body); + static::assertStringContainsString("Content-ID: 1\r\n\r\nDELETE /container/dir/b.txt HTTP/1.1\r\n", $body); + static::assertStringNotContainsString('x-ms-version', $body); + static::assertSame(2, substr_count($body, 'authorization: SharedKey account:')); + } + + public function test_delete_blobs_throws_on_a_batch_status_other_than_202(): void + { + $this->expectException(AzureException::class); + + BlobServiceContext::service(BlobServiceContext::response(400, ''))->deleteBlobs(['a.txt']); + } + public function test_delete_container_addresses_the_container(): void { $client = new FixedResponseClient(BlobServiceContext::response(202, ''));