-
Notifications
You must be signed in to change notification settings - Fork 0
feat(queue): Synchronous/Asynchronous publishers + Swoole Background decorator #44
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
loks0n
wants to merge
12
commits into
main
Choose a base branch
from
feat/queue-async-publisher
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2a11afe
feat(queue): add Async publisher decorator for background publishing
loks0n 942196b
refactor(queue): drive Async publisher with a bounded channel
loks0n 07da1c7
refactor(queue): split Publisher into Synchronous and Asynchronous
loks0n a9c22e2
refactor(queue): rename Async broker to Background
loks0n 84664ce
feat(queue): let Background dispatch with N reader coroutines
loks0n 00a5956
refactor(queue): rename Background $workers to $coroutines
loks0n 4368fab
feat(queue): add telemetry to the Background publisher
loks0n 3663a71
docs(queue): add interface-level docblocks to Synchronous/Asynchronous
loks0n f1ff889
refactor(queue): drop Background dispatch/error counters
loks0n 4ed6a5c
feat(queue): give Background enqueue a configurable timeout
loks0n b36e2f0
feat(queue)!: make async enqueue void, throw on back pressure
loks0n 67dde51
refactor(queue): rename BackpressureException to BufferFullException
loks0n File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Utopia\Queue\Broker; | ||
|
|
||
| use Swoole\Coroutine; | ||
| use Swoole\Coroutine\Channel; | ||
| use Swoole\Coroutine\WaitGroup; | ||
| use Utopia\Queue\Publisher\Asynchronous; | ||
| use Utopia\Queue\Publisher\BufferFullException; | ||
| use Utopia\Queue\Publisher\Synchronous; | ||
| use Utopia\Queue\Queue; | ||
| use Utopia\Telemetry\Adapter as Telemetry; | ||
| use Utopia\Telemetry\Adapter\None as NoTelemetry; | ||
|
|
||
| /** | ||
| * Wraps a synchronous publisher and adds asynchronous, background dispatch on | ||
| * top of a Swoole coroutine — so it satisfies both the Synchronous and | ||
| * Asynchronous contracts. | ||
| * | ||
| * enqueue() pushes the publish onto a bounded channel and returns; one or more | ||
| * reader coroutines loop over the channel and delegate each dispatch to the | ||
| * wrapped synchronous publisher. The channel capacity is the back-pressure | ||
| * bound — once it fills, enqueue() blocks the producing coroutine until a reader | ||
| * drains a slot, so a slow broker throttles producers instead of piling up | ||
| * unbounded work. $timeout caps that wait: enqueue() throws BufferFullException | ||
| * if no slot frees within it; -1 (the default) waits indefinitely. | ||
| * | ||
| * $coroutines sets how many reader coroutines dispatch concurrently. Values above | ||
| * 1 only make sense when the wrapped publisher tolerates concurrent use across | ||
| * coroutines: a single-connection broker (e.g. a bare Redis) must not be shared | ||
| * — wrap a connection Pool instead, so each dispatch leases its own connection. | ||
| * More than one coroutine also gives up FIFO dispatch order. | ||
| * | ||
| * Telemetry (no-op by default) reports the buffer depth as an observable gauge. | ||
| * Dispatch counts and failures aren't metered here — the wrapped synchronous | ||
| * publisher already sees every publish and can report those itself. | ||
| * | ||
| * publish() bypasses the channel and delegates synchronously. | ||
| */ | ||
| class Background implements Synchronous, Asynchronous | ||
| { | ||
| private readonly Channel $channel; | ||
|
|
||
| private readonly WaitGroup $waitGroup; | ||
|
|
||
| private readonly int $coroutines; | ||
|
|
||
| private bool $started = false; | ||
|
|
||
| public function __construct( | ||
| private readonly Synchronous $publisher, | ||
| int $capacity = 512, | ||
| int $coroutines = 1, | ||
| private readonly float $timeout = -1, | ||
| Telemetry $telemetry = new NoTelemetry(), | ||
| ) { | ||
| $this->channel = new Channel(max(1, $capacity)); | ||
| $this->waitGroup = new WaitGroup(); | ||
| $this->coroutines = max(1, $coroutines); | ||
|
|
||
| $telemetry->createObservableGauge( | ||
| 'messaging.publisher.buffer.depth', | ||
| '{message}', | ||
| 'Publishes buffered awaiting background dispatch.', | ||
| )->observe(function (callable $observe): void { | ||
| $observe($this->channel->length(), []); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Spawn the reader coroutines that drain the channel into the wrapped | ||
| * publisher. Call once from within a coroutine runtime; until then | ||
| * enqueue() publishes synchronously. | ||
| */ | ||
| public function start(): void | ||
| { | ||
| if ($this->started) { | ||
| return; | ||
| } | ||
|
|
||
| $this->started = true; | ||
|
|
||
| for ($i = 0; $i < $this->coroutines; $i++) { | ||
| $this->waitGroup->add(); | ||
|
|
||
| Coroutine::create(function (): void { | ||
| try { | ||
| while (($task = $this->channel->pop()) instanceof \Closure) { | ||
| $task(); | ||
| } | ||
| } finally { | ||
| $this->waitGroup->done(); | ||
| } | ||
| }); | ||
| } | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /** | ||
| * Drain the channel and stop the readers, blocking until they have finished. | ||
| * Messages already enqueued are published before the readers exit. | ||
| */ | ||
| public function shutdown(): void | ||
| { | ||
| if (!$this->started) { | ||
| return; | ||
| } | ||
|
|
||
| for ($i = 0; $i < $this->coroutines; $i++) { | ||
| $this->channel->push(null); // one sentinel per reader; pop() returns non-Closure → loop ends | ||
| } | ||
|
|
||
| $this->waitGroup->wait(); | ||
| $this->started = false; | ||
| } | ||
|
|
||
| /** | ||
| * Publish synchronously, blocking until the broker accepts the message. | ||
| */ | ||
| public function publish(Queue $queue, array $payload, bool $priority = false): bool | ||
| { | ||
| return $this->publisher->publish($queue, $payload, $priority); | ||
| } | ||
|
|
||
| /** | ||
| * Hand the publish to the background reader via the channel. Blocks when the | ||
| * channel is full (back pressure), up to the configured timeout, then throws | ||
| * BufferFullException if no slot frees in time. Falls back to a synchronous | ||
| * publish when no reader loop is running. | ||
| * | ||
| * @throws BufferFullException when the buffer stays full past the timeout. | ||
| */ | ||
| public function enqueue(Queue $queue, array $payload, bool $priority = false): void | ||
| { | ||
| if (!$this->started || Coroutine::getCid() === -1) { | ||
| $this->publish($queue, $payload, $priority); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| $accepted = $this->channel->push(function () use ($queue, $payload, $priority): void { | ||
| try { | ||
| $this->publisher->publish($queue, $payload, $priority); | ||
| } catch (\Throwable $error) { | ||
| // Fire-and-forget: no producer to surface to, so log and move on. | ||
| error_log('Uncaught error while publishing queue message: ' . $error->getMessage()); | ||
| } | ||
| }, $this->timeout); | ||
|
|
||
| if ($accepted === false) { | ||
| throw new BufferFullException('Publisher buffer full; enqueue timed out.'); | ||
| } | ||
| } | ||
|
|
||
| public function retry(Queue $queue, ?int $limit = null): void | ||
| { | ||
| $this->publisher->retry($queue, $limit); | ||
| } | ||
|
|
||
| public function getQueueSize(Queue $queue, bool $failedJobs = false): int | ||
| { | ||
| return $this->publisher->getQueueSize($queue, $failedJobs); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Utopia\Queue\Publisher; | ||
|
|
||
| use Utopia\Queue\Queue; | ||
|
|
||
| /** | ||
| * A publisher that accepts messages without waiting for the broker: enqueue() | ||
| * hands the message off for background delivery and returns immediately. It does | ||
| * not report delivery — only that the message was accepted. When the buffer is | ||
| * full and can't accept more, it throws BufferFullException so the caller can | ||
| * shed or slow down. Implementations decide how the deferred work runs — | ||
| * Broker\Background drains a Swoole channel on reader coroutines. | ||
| */ | ||
| interface Asynchronous | ||
| { | ||
| /** | ||
| * Hands a message off to be published in the background, returning without | ||
| * waiting for the broker to accept it. | ||
| * | ||
| * @throws BufferFullException when the buffer is full and the message | ||
| * cannot be accepted. | ||
| */ | ||
| public function enqueue(Queue $queue, array $payload, bool $priority = false): void; | ||
| } |
11 changes: 11 additions & 0 deletions
11
packages/queue/src/Queue/Publisher/BufferFullException.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Utopia\Queue\Publisher; | ||
|
|
||
| /** | ||
| * Thrown by Asynchronous::enqueue() when the message can't be accepted because | ||
| * the buffer is full and back pressure timed out. The message was not enqueued. | ||
| */ | ||
| class BufferFullException extends \RuntimeException {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Utopia\Queue\Publisher; | ||
|
|
||
| use Utopia\Queue\Queue; | ||
|
|
||
| /** | ||
| * A publisher that hands messages to the broker synchronously: publish() blocks | ||
| * until the broker accepts the message and returns whether it did. Brokers such | ||
| * as Redis and Pool implement this directly; Broker\Background wraps one to add | ||
| * background dispatch. | ||
| */ | ||
| interface Synchronous | ||
| { | ||
| /** | ||
| * Publishes a message onto the queue, blocking until the broker accepts it. | ||
| */ | ||
| public function publish(Queue $queue, array $payload, bool $priority = false): bool; | ||
|
|
||
| /** | ||
| * Retries failed jobs. | ||
| */ | ||
| public function retry(Queue $queue, ?int $limit = null): void; | ||
|
|
||
| /** | ||
| * Returns the amount of pending messages in the queue. | ||
| */ | ||
| public function getQueueSize(Queue $queue, bool $failedJobs = false): int; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.