Skip to content

feat(publisher): add ping method to publisher #38

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
13 changes: 9 additions & 4 deletions src/Queue/Broker/AMQP.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ public function close(): void
}
}

public function ping(): bool
{
return $this->withChannel(fn (AMQPChannel $channel) => $channel->is_open());
}

public function enqueue(Queue $queue, array $payload): bool
{
$payload = [
Expand Down Expand Up @@ -172,10 +177,10 @@ public function getQueueSize(Queue $queue, bool $failedJobs = false): int
}

/**
* @param callable(AMQPChannel $channel): void $callback
* @param callable(AMQPChannel $channel): mixed $callback
* @throws \Exception
*/
private function withChannel(callable $callback): void
private function withChannel(callable $callback): mixed
{
$createChannel = function (): AMQPChannel {
$connection = new AMQPStreamConnection($this->host, $this->port, $this->user, $this->password, $this->vhost, heartbeat: $this->heartbeat);
Expand All @@ -194,13 +199,13 @@ private function withChannel(callable $callback): void
}

try {
$callback($this->channel);
return $callback($this->channel);
} catch (\Throwable $th) {
// createChannel() might throw, in that case set the channel to `null` first.
$this->channel = null;
// try creating a new connection once, if this still fails, throw the error
$this->channel = $createChannel();
$callback($this->channel);
return $callback($this->channel);
}
}
}
5 changes: 5 additions & 0 deletions src/Queue/Broker/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ public function close(): void
$this->closed = true;
}

public function ping(): bool
{
return $this->connection->ping();
}

public function enqueue(Queue $queue, array $payload): bool
{
$payload = [
Expand Down
7 changes: 7 additions & 0 deletions src/Queue/Publisher.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@

interface Publisher
{
/**
* Checks if the publisher can reach the queue.
*
* @return bool
*/
public function ping(): bool;

/**
* Publishes a new message onto the queue.
*
Expand Down