Skip to content

Commit

Permalink
Ignore open exception on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Dec 8, 2024
1 parent b431ee1 commit 2d4e4a1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,13 @@ public function truncate(int $size): void;
/**
* Makes a non-blocking attempt to lock the file. Returns true if the lock was obtained.
*
* @throws FilesystemException If there is an error when attempting to lock the file.
* @throws ClosedException If the file has been closed.
*/
public function lock(LockMode $mode): bool;

/**
* @throws FilesystemException If there is an error when attempting to unlock the file.
* @throws ClosedException If the file has been closed.
*/
public function unlock(): void;
Expand Down
17 changes: 13 additions & 4 deletions src/FileMutex.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

namespace Amp\File;

use Amp\ByteStream\StreamException;
use Amp\Cancellation;
use Amp\Sync\Lock;
use Amp\Sync\Mutex;
use Amp\Sync\SyncException;
use function Amp\delay;
use const Amp\Process\IS_WINDOWS;

final class FileMutex implements Mutex
{
Expand Down Expand Up @@ -40,12 +42,19 @@ public function acquire(?Cancellation $cancellation = null): Lock
for ($attempt = 0; true; ++$attempt) {
try {
$file = $this->filesystem->openFile($this->fileName, 'a');
if ($file->lock(LockMode::Exclusive)) {
return new Lock(fn () => $this->release($file));

try {
if ($file->lock(LockMode::Exclusive)) {
return new Lock(fn () => $this->release($file));
}
$file->close();
} catch (FilesystemException|StreamException $exception) {
throw new SyncException($exception->getMessage(), previous: $exception);
}
$file->close();
} catch (FilesystemException $exception) {
throw new SyncException($exception->getMessage(), previous: $exception);
if (!IS_WINDOWS) { // Windows fails to open the file if a lock is held.
throw new SyncException($exception->getMessage(), previous: $exception);
}
}

$multiplier = 2 ** \min(31, $attempt);
Expand Down

0 comments on commit 2d4e4a1

Please sign in to comment.