Skip to content
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

[WIP] [0.6.x] Concurrent consuming #171

Draft
wants to merge 1 commit into
base: 0.6.x
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ parameters:
-
message: '#^Cannot call method (toArray)\(\) on Bunny\\Protocol\\ContentHeaderFrame\|null\.$#'
path: src/Channel.php
-
identifier: smallerOrEqual.alwaysFalse
path: src/Channel.php
count: 1
-
message: '#^Cannot call method (channelOpen|awaitConnectionTune|connectionTuneOk|connectionOpen|startHeartbeatTimer|connectionStartOk|disconnect)\(\) on Bunny\\Connection\|null\.$#'
path: src/Client.php
Expand Down
74 changes: 64 additions & 10 deletions src/Channel.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
use SplQueue;
use function React\Async\async;
use function React\Async\await;
use function array_key_exists;
use function array_splice;
use function gettype;
use function sprintf;
Expand Down Expand Up @@ -66,12 +67,15 @@ class Channel implements ChannelInterface, EventEmitterInterface
/** @var list<callable(\Bunny\Message, \Bunny\Protocol\MethodBasicReturnFrame): void> */
private array $returnCallbacks = [];

/** @var array<string,int> */
private array $consumeConcurrency = [];

/** @var array<string,int> */
private array $consumeConcurrent = [];

/** @var array<string,callable(\Bunny\Message, \Bunny\Channel, \Bunny\Client): (\React\Promise\PromiseInterface<mixed>|void)> */
private array $deliverCallbacks = [];

/** @var array<string,bool> */
private array $deliveryBusy = [];

/** @var array<string,\SplQueue<\Bunny\Message>> */
private array $deliveryQueue = [];

Expand Down Expand Up @@ -216,19 +220,50 @@ public function close(int $replyCode = 0, string $replyText = ''): void
await($this->closePromise);
}

/**
* Creates new consumer on channel.
*
* @param array<string,mixed> $arguments
* @param positive-int $concurrency
*/
public function consume(callable $callback, string $queue = '', string $consumerTag = '', bool $noLocal = false, bool $noAck = false, bool $exclusive = false, bool $nowait = false, array $arguments = [], int $concurrency = 1): MethodBasicConsumeOkFrame
{
if ($concurrency <= 0) {
throw new ChannelException(
'basic.consume concurrency must be 1 or higher',
);
}

$response = $this->consumeImpl($queue, $consumerTag, $noLocal, $noAck, $exclusive, $nowait, $arguments);

if ($response instanceof MethodBasicConsumeOkFrame) {
$this->consumeConcurrency[$response->consumerTag] = $concurrency;
$this->consumeConcurrent[$response->consumerTag] = 0;
$this->deliverCallbacks[$response->consumerTag] = $callback;
$this->deliveryQueue[$response->consumerTag] = new SplQueue();

return $response;
}

throw new ChannelException(
'basic.consume unexpected response of type ' . gettype($response) . '.',
);
}

/**
* Creates new consumer on channel.
*
* @param array<string,mixed> $arguments
*/
public function consume(callable $callback, string $queue = '', string $consumerTag = '', bool $noLocal = false, bool $noAck = false, bool $exclusive = false, bool $nowait = false, array $arguments = []): MethodBasicConsumeOkFrame
public function stream(int $concurrency, callable $callback, string $queue = '', string $consumerTag = '', bool $noLocal = false, bool $noAck = false, bool $exclusive = false, bool $nowait = false, array $arguments = []): MethodBasicConsumeOkFrame
{
$response = $this->consumeImpl($queue, $consumerTag, $noLocal, $noAck, $exclusive, $nowait, $arguments);

if ($response instanceof MethodBasicConsumeOkFrame) {
$this->consumeConcurrency[$response->consumerTag] = $concurrency;
$this->consumeConcurrent[$response->consumerTag] = 0;
$this->deliverCallbacks[$response->consumerTag] = $callback;
$this->deliveryQueue[$response->consumerTag] = new SplQueue();
$this->deliveryBusy[$response->consumerTag] = false;

return $response;
}
Expand Down Expand Up @@ -337,6 +372,8 @@ public function publish(string $body, array $headers = [], string $exchange = ''
public function cancel(string $consumerTag, bool $nowait = false): bool|MethodBasicCancelOkFrame
{
$response = $this->cancelImpl($consumerTag, $nowait);
unset($this->consumeConcurrency[$consumerTag]);
unset($this->consumeConcurrent[$consumerTag]);
unset($this->deliverCallbacks[$consumerTag]);
unset($this->deliveryQueue[$consumerTag]);

Expand Down Expand Up @@ -453,9 +490,10 @@ public function onFrameReceived(AbstractFrame $frame): void
// // break reference cycle, must be called after resolving promise
// $this->client = null;
// break consumers' reference cycle
$this->consumeConcurrency = [];
$this->consumeConcurrent = [];
$this->deliverCallbacks = [];
$this->deliveryQueue = [];
$this->deliveryBusy = [];
} elseif ($frame instanceof MethodBasicReturnFrame) {
$this->returnFrame = $frame;
$this->state = ChannelState::AwaitingHeader;
Expand Down Expand Up @@ -598,25 +636,41 @@ private function onBodyComplete(): void

private function deliveryTick(string $consumerTag): void
{
if ($this->deliveryBusy[$consumerTag] === true || empty($this->deliveryQueue[$consumerTag]) || $this->deliveryQueue[$consumerTag]->isEmpty()) {
if (
(
!array_key_exists($consumerTag, $this->consumeConcurrent)
) ||
(
array_key_exists($consumerTag, $this->consumeConcurrent) && $this->consumeConcurrent[$consumerTag] >= $this->consumeConcurrency[$consumerTag]
) ||
(
empty($this->deliveryQueue[$consumerTag])
) ||
(
$this->deliveryQueue[$consumerTag]->isEmpty()
)
) {
return;
}

$this->deliveryBusy[$consumerTag] = true;
$this->consumeConcurrent[$consumerTag]++;
$message = $this->deliveryQueue[$consumerTag]->dequeue();
$callback = $this->deliverCallbacks[$consumerTag];

$outcome = $callback($message, $this, $this->client);

if (!($outcome instanceof PromiseInterface)) {
$this->deliveryBusy[$consumerTag] = false;
$this->consumeConcurrent[$consumerTag]--;
$this->deliveryTick($consumerTag);

return;
}

$outcome->finally(function () use ($consumerTag): void {
$this->deliveryBusy[$consumerTag] = false;
if (array_key_exists($consumerTag, $this->consumeConcurrent)) {
$this->consumeConcurrent[$consumerTag]--;
}

$this->deliveryTick($consumerTag);
});
}
Expand Down
3 changes: 2 additions & 1 deletion src/ChannelInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ public function close(int $replyCode = 0, string $replyText = ''): void;
* Creates new consumer on channel.
*
* @param array<string,mixed> $arguments
* @param positive-int $concurrency
*/
public function consume(callable $callback, string $queue = '', string $consumerTag = '', bool $noLocal = false, bool $noAck = false, bool $exclusive = false, bool $nowait = false, array $arguments = []): MethodBasicConsumeOkFrame;
public function consume(callable $callback, string $queue = '', string $consumerTag = '', bool $noLocal = false, bool $noAck = false, bool $exclusive = false, bool $nowait = false, array $arguments = [], int $concurrency = 1): MethodBasicConsumeOkFrame;

/**
* Acks given message.
Expand Down
36 changes: 36 additions & 0 deletions test/ChannelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

use Bunny\Channel;
use Bunny\Client;
use Bunny\Exception\ChannelException;
use Bunny\Message;
use Bunny\Test\Library\ClientHelper;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -108,6 +109,41 @@ public function testConsume(): void
self::assertFalse($c->isConnected());
}

/**
* @return iterable<array<int>>
*/
public static function invalidConsumeConcurrencyProvider(): iterable
{
yield [0];
yield [-1];
}

/**
* @param positive-int $concurrency; This is a ly to stop PHPStan from complaining this is an int
*
* @dataProvider invalidConsumeConcurrencyProvider
*/
public function testConsumeWithInvalidConcurrency(int $concurrency): void
{
self::expectException(ChannelException::class);
self::expectExceptionMessage('basic.consume concurrency must be 1 or higher');

$c = $this->helper->createClient();

$ch = $c->connect()->channel();
self::assertTrue($c->isConnected());
$ch->queueDeclare('test_queue', false, false, false, true);
self::assertTrue($c->isConnected());
$ch->consume(static function (Message $msg, Channel $ch, Client $c): void {
self::assertEquals('hi', $msg->content);
}, concurrency: $concurrency);
self::assertTrue($c->isConnected());
$ch->publish('hi', [], '', 'test_queue');
self::assertTrue($c->isConnected());
$c->disconnect();
self::assertFalse($c->isConnected());
}

public function testHeaders(): void
{
$c = $this->helper->createClient();
Expand Down