diff --git a/etc/qa/infection.json5 b/etc/qa/infection.json5 index eac1360..93eea6c 100644 --- a/etc/qa/infection.json5 +++ b/etc/qa/infection.json5 @@ -77,6 +77,11 @@ "ReactParallel\\EventLoop\\EventLoopBridge::handleKillEvent", "ReactParallel\\EventLoop\\EventLoopBridge::handleErrorEvent" ] + }, + "ReturnRemoval": { + "ignore": [ + "ReactParallel\\EventLoop\\Stream::done" + ] } }, "threads": 64 diff --git a/src/EventLoopBridge.php b/src/EventLoopBridge.php index f2be788..3cc84d3 100644 --- a/src/EventLoopBridge.php +++ b/src/EventLoopBridge.php @@ -88,7 +88,35 @@ public function observe(Channel $channel): iterable $this->startTimer(); - yield from $stream->iterable(); + try { + yield from $stream->iterable(); + } finally { + $this->unobserve($channel, $stream); + } + } + + /** + * @param Channel $channel + * @param StreamInterface $stream + */ + private function unobserve(Channel $channel, StreamInterface $stream): void + { + $id = spl_object_id($channel); + + if (! isset($this->channels[$id])) { + return; + } + + unset($this->channels[$id]); + $stream->done(); + + if ($this->metrics instanceof Metrics) { + $channels = $this->metrics->channels(); + $channels->gauge(new Label('state', 'active'))->dcr(); + $channels->gauge(new Label('state', 'close'))->incr(); + } + + $this->stopTimer(); } /** @@ -266,16 +294,13 @@ private function handleChannelReadEvent(Event $event): void /** @param Event $event */ private function handleCloseEvent(Event $event): void { - $this->channels[spl_object_id($event->object)]->done(); - unset($this->channels[spl_object_id($event->object)]); - - if (! ($this->metrics instanceof Metrics)) { + $id = spl_object_id($event->object); + if (! isset($this->channels[$id])) { return; } - $channels = $this->metrics->channels(); - $channels->gauge(new Label('state', 'active'))->dcr(); - $channels->gauge(new Label('state', 'close'))->incr(); + $this->channels[$id]->done(); + unset($this->channels[$id]); } /** @param Event $event */ diff --git a/src/Stream.php b/src/Stream.php index e1a4c20..cf87c3d 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -21,6 +21,8 @@ final class Stream implements StreamInterface /** @var Deferred */ private Deferred $wait; + private bool $isDone = false; + public function __construct() { $this->queue = new SplQueue(); @@ -37,7 +39,23 @@ public function value(mixed $value): void public function done(): void { + if ($this->isDone) { + return; + } + + $this->isDone = true; + $this->resolveDone(); + } + + private function resolveDone(): void + { + // Suppress FiberError: the Fiber may already be in the finally block + // when done() is called, making resume() fail. + $promise = $this->wait->promise(); $this->wait->resolve(new Done()); + $promise->catch(static function (): void { + // Ignore FiberError and any other rejection + }); } /** @return iterable */ diff --git a/tests/EventLoopBridgeTest.php b/tests/EventLoopBridgeTest.php index cc8624e..4bd53a0 100644 --- a/tests/EventLoopBridgeTest.php +++ b/tests/EventLoopBridgeTest.php @@ -109,7 +109,7 @@ public function close(): void } self::assertFalse($onNext, 'onNext should never be called'); - $this->assertPrint($metricsRegistry, 'react_parallel_event_loop_timer_total{event="start"} 1', 'react_parallel_event_loop_channels{state="active"} 1'); + $this->assertPrint($metricsRegistry, 'react_parallel_event_loop_timer_total{event="start"} 1', 'react_parallel_event_loop_channels{state="active"} 0', 'react_parallel_event_loop_channels{state="close"} 1'); $this->assertPrintMatchesRegularExpression($metricsRegistry, '/react_parallel_event_loop_timer_total\{event\="tick"\} [0-9]/m', '/react_parallel_event_loop_timer_items_total\{count\="0"\} [0-9]/m'); } @@ -338,6 +338,58 @@ public function timerScaling(): void $this->assertPrint($metricsRegistry, 'react_parallel_event_loop_timer_total{event="start"} 1'); } + #[Test] + public function observeCleansUpWhenChannelIsClosed(): void + { + $d = bin2hex(random_bytes(13)); + + $channel = Channel::make($d . '_cleanup', Channel::Infinite); + + [$eventLoopBridge, $metricsRegistry] = $this->createBridge(); + + // Send a value, then close the channel — observe should clean up properly + $channel->send('hello'); + Loop::addTimer(0.1, static function () use ($channel): void { + $channel->close(); + }); + + $items = []; + foreach ($eventLoopBridge->observe($channel) as $item) { + $items[] = $item; + } + + self::assertSame(['hello'], $items); + + // After observe completes, the channel should be fully cleaned up + $this->assertPrint($metricsRegistry, 'react_parallel_event_loop_channels{state="active"} 0', 'react_parallel_event_loop_channels{state="close"} 1'); + } + + #[Test] + public function handleCloseEventIsIdempotent(): void + { + $d = bin2hex(random_bytes(13)); + + $channel = Channel::make($d . '_close_idempotent', Channel::Infinite); + + [$eventLoopBridge, $metricsRegistry] = $this->createBridge(); + + // Send a value, then close the channel — observe should clean up without FiberError + $channel->send('test'); + Loop::addTimer(0.1, static function () use ($channel): void { + $channel->close(); + }); + + $items = []; + foreach ($eventLoopBridge->observe($channel) as $item) { + $items[] = $item; + } + + self::assertSame(['test'], $items); + + // Verify cleanup happened without FiberError + $this->assertPrint($metricsRegistry, 'react_parallel_event_loop_channels{state="active"} 0', 'react_parallel_event_loop_channels{state="close"} 1'); + } + /** @return array{EventLoopBridge, RegistryContract} */ private function createBridge(): array { diff --git a/tests/StreamTest.php b/tests/StreamTest.php new file mode 100644 index 0000000..e4c27ee --- /dev/null +++ b/tests/StreamTest.php @@ -0,0 +1,53 @@ + $stream */ + $stream = new Stream(); + + self::assertSame([], await(async(static function () use ($stream): array { + $stream->done(); + // If done() is not idempotent, the second resolve would cause issues + $stream->done(); + + $items = []; + foreach ($stream->iterable() as $item) { + $items[] = $item; + } + + return $items; + })())); + } + + #[Test] + public function iterableStopsWithoutYieldingWhenDoneBeforeValues(): void + { + /** @var Stream $stream */ + $stream = new Stream(); + + self::assertSame([], await(async(static function () use ($stream): array { + $stream->done(); + + $items = []; + foreach ($stream->iterable() as $item) { + $items[] = $item; + } + + return $items; + })())); + } +}