From 91505b49e72deba8e4bc0186dd1b5e8aa66dd969 Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Sun, 20 Nov 2022 10:39:47 -0600 Subject: [PATCH] Await pending writes before closing --- src/Internal/QueuedWritesFile.php | 11 ++++++++++- test/FileTest.php | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/Internal/QueuedWritesFile.php b/src/Internal/QueuedWritesFile.php index ad08ebd..9f1ec45 100644 --- a/src/Internal/QueuedWritesFile.php +++ b/src/Internal/QueuedWritesFile.php @@ -70,7 +70,16 @@ abstract class QueuedWritesFile implements File public function end(): void { $this->writable = false; - $this->close(); + + if ($this->queue->isEmpty()) { + $this->close(); + return; + } + + $future = $this->queue->top()->finally($this->close(...)); + $this->queue->push($future); + + $future->await(); } /** diff --git a/test/FileTest.php b/test/FileTest.php index 3efcbe1..9c84ddd 100644 --- a/test/FileTest.php +++ b/test/FileTest.php @@ -4,6 +4,7 @@ namespace Amp\File\Test; use Amp\ByteStream\ClosedException; use Amp\File; +use function Amp\async; abstract class FileTest extends FilesystemTest { @@ -204,6 +205,22 @@ abstract class FileTest extends FilesystemTest $handle->read(); } + public function testCloseWithPendingWrites(): void + { + $path = Fixture::path() . "/write"; + + $handle = $this->driver->openFile($path, "c+"); + + $data = "data"; + $writeFuture = async($handle->write(...), $data); + $closeFuture = async($handle->close(...)); + + $writeFuture->await(); + $closeFuture->await(); + + $this->assertSame($data, $this->driver->read($path)); + } + /** * @depends testWrite */