Skip to content
Open
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
5 changes: 5 additions & 0 deletions etc/qa/infection.json5
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@
"ReactParallel\\EventLoop\\EventLoopBridge::handleKillEvent",
"ReactParallel\\EventLoop\\EventLoopBridge::handleErrorEvent"
]
},
"ReturnRemoval": {
"ignore": [
"ReactParallel\\EventLoop\\Stream::done"
]
}
},
"threads": 64
Expand Down
41 changes: 33 additions & 8 deletions src/EventLoopBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<mixed> $channel
* @param StreamInterface<mixed> $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();
}

/**
Expand Down Expand Up @@ -266,16 +294,13 @@ private function handleChannelReadEvent(Event $event): void
/** @param Event<mixed> $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<mixed> $event */
Expand Down
18 changes: 18 additions & 0 deletions src/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ final class Stream implements StreamInterface
/** @var Deferred<Value|Done> */
private Deferred $wait;

private bool $isDone = false;

public function __construct()
{
$this->queue = new SplQueue();
Expand All @@ -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<T> */
Expand Down
54 changes: 53 additions & 1 deletion tests/EventLoopBridgeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand Down Expand Up @@ -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
{
Expand Down
53 changes: 53 additions & 0 deletions tests/StreamTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace ReactParallel\Tests;

use PHPUnit\Framework\Attributes\Test;
use ReactParallel\EventLoop\Stream;
use WyriHaximus\AsyncTestUtilities\AsyncTestCase;

use function React\Async\async;
use function React\Async\await;

final class StreamTest extends AsyncTestCase
{
#[Test]
public function donePreventsSubsequentResolution(): void
{
/** @var Stream<string> $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<string> $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;
})()));
}
}
Loading