Skip to content

PHPLIB-1324 Implement rename for GridFS stream wrapper #1207

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ Supported stream functions:
- :php:`filemtime() <filemtime>`
- :php:`filesize() <filesize>`
- :php:`file() <file>`
- :php:`fopen() <fopen>` (with "r", "rb", "w", and "wb" modes)
- :php:`fopen() <fopen>` with "r", "rb", "w", and "wb" modes
- :php:`rename() <rename>` rename all revisions of a file in the same bucket

In read mode, the stream context can contain the option ``gridfs['revision']``
to specify the revision number of the file to read. If omitted, the most recent
Expand Down
11 changes: 11 additions & 0 deletions src/GridFS/CollectionWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,17 @@ public function insertFile($file): void
$this->filesCollection->insertOne($file);
}

/**
* Updates the filename field in the file document for all the files with a given filename.
*/
public function updateFilenameForFilename(string $filename, string $newFilename): UpdateResult
{
return $this->filesCollection->updateMany(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this warrants a spec change to Renaming Stored Files before doing something wildly different in PHPLIB. I don't recall why filename matching was not advised in the original spec, but selecting IDs in advance allows for error checking (see below).

As I suggested in a previous comment, I think the least controversial spec change would be to use updateMany on the list of collected IDs. If we can't wait for that, though, sticking with the spec's existing, inefficient approach would seem the right course of action.

With regard to the discussion of successful return values in #1207 (comment), you could assert that updateMany modifies exactly as many documents as the size of the ID list being updated and raise an exception if the write result reports an unexpected modified count. Users can decide for themselves if that's an error, but I reckon it'd only come up if a revision was deleted in another process while the rename was executing (between ID collection and issuing the updateMany).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sincerely, I don't see the difference between collecting IDs first then modifying filenames, vs making 1 single request that finds and modifies filenames.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ack - I think since renaming files by filename is not part of the spec and the spec only contains a suggested implementation for users, we should be fine adding this implementation. I'd suggest we amend the spec to add APIs to work on all revisions of a file (i.e. remove and rename by filename instead of by ID).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

renaming files by filename is not part of the spec and the spec only contains a suggested implementation for users

@alcaeus: Good point. I overlooked that the instructions were telling users to run the rename() operation for each ID, instead of discussing how a driver should implement filename-based renames.

['filename' => $filename],
['$set' => ['filename' => $newFilename]],
);
}

/**
* Updates the filename field in the file document for a given ID.
*
Expand Down
10 changes: 10 additions & 0 deletions src/GridFS/Exception/LogicException.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,14 @@ public static function openModeNotSupported(string $mode): self
{
return new self(sprintf('Mode "%s" is not supported by "gridfs://" files. Use one of "r", "rb", "w", or "wb".', $mode));
}

/**
* Thrown when the origin and destination paths are not in the same bucket.
*
* @internal
*/
public static function renamePathMismatch(string $from, string $to): self
{
return new self(sprintf('Cannot rename "%s" to "%s" because they are not in the same GridFS bucket.', $from, $to));
}
}
16 changes: 16 additions & 0 deletions src/GridFS/ReadableStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@
use MongoDB\Driver\CursorInterface;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\GridFS\Exception\CorruptFileException;
use MongoDB\GridFS\Exception\LogicException;

use function assert;
use function ceil;
use function floor;
use function is_integer;
use function is_object;
use function is_string;
use function property_exists;
use function sprintf;
use function strlen;
Expand Down Expand Up @@ -176,6 +178,20 @@ public function readBytes(int $length): string
return $data;
}

/**
* Rename all revisions of the file.
*/
public function rename(string $newFilename): bool
{
if (! isset($this->file->filename) || ! is_string($this->file->filename)) {
throw new LogicException('Cannot rename file without a filename');
}

$this->collectionWrapper->updateFilenameForFilename($this->file->filename, $newFilename);

return true;
}

/**
* Seeks the chunk and buffer offsets for the next read operation.
*
Expand Down
27 changes: 27 additions & 0 deletions src/GridFS/StreamWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@
use MongoDB\GridFS\Exception\FileNotFoundException;
use MongoDB\GridFS\Exception\LogicException;

use function array_slice;
use function assert;
use function explode;
use function implode;
use function in_array;
use function is_array;
use function is_integer;
use function is_resource;
use function str_starts_with;
use function stream_context_get_options;
use function stream_get_wrappers;
use function stream_wrapper_register;
Expand Down Expand Up @@ -90,6 +93,30 @@ public static function register(string $protocol = 'gridfs'): void
stream_wrapper_register($protocol, static::class, STREAM_IS_URL);
}

/**
* Rename all revisions of a filename.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this only supports the bucket alias API, since we still only have a single Bucket::rename() method. Is this something that Drupal requires?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if Drupal needs rename.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a rename from stream wrapper only. If you do rename('original.txt', 'renamed.txt), you expect original.txt to no longer exist.

*
* @return bool True on success or false on failure.
*/
public function rename(string $fromPath, string $toPath): bool
{
$prefix = implode('/', array_slice(explode('/', $fromPath, 4), 0, 3)) . '/';
if (! str_starts_with($toPath, $prefix)) {
throw LogicException::renamePathMismatch($fromPath, $toPath);
}

try {
$this->stream_open($fromPath, 'r', 0, $openedPath);
} catch (FileNotFoundException $e) {
return false;
}

$newName = explode('/', $toPath, 4)[3] ?? '';
assert($this->stream instanceof ReadableStream);

return $this->stream->rename($newName);
}

/**
* @see Bucket::resolveStreamContext()
*
Expand Down
24 changes: 24 additions & 0 deletions tests/GridFS/StreamWrapperFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use function is_dir;
use function is_file;
use function is_link;
use function rename;
use function stream_context_create;
use function stream_get_contents;
use function time;
Expand Down Expand Up @@ -363,4 +364,27 @@ public function testCopy(): void
$this->assertSame('foobar', file_get_contents($path . '.copy'));
$this->assertSame('foobar', file_get_contents($path));
}

public function testRenameAllRevisions(): void
{
$this->bucket->registerGlobalStreamWrapperAlias('bucket');
$path = 'gridfs://bucket/filename';

$this->assertSame(6, file_put_contents($path, 'foobar'));
$this->assertSame(6, file_put_contents($path, 'foobar'));
$this->assertSame(6, file_put_contents($path, 'foobar'));

$this->assertTrue(rename($path, $path . '.renamed'));
$this->assertTrue(file_exists($path . '.renamed'));
$this->assertFalse(file_exists($path));
$this->assertSame('foobar', file_get_contents($path . '.renamed'));
}

public function testRenamePathMismatch(): void
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot rename "gridfs://bucket/filename" to "gridfs://other/newname" because they are not in the same GridFS bucket.');

rename('gridfs://bucket/filename', 'gridfs://other/newname');
}
}