Queue
RustIn Appwrite#
Appwrite runs the Rust crate: the PHP extension serves the library and none of its PHP is left.
Rust 1,776 lines (1,328 code)· PHP 7,628 lines (4,433 code)split
| Part | Code | Comments | Blank | Total | Files |
|---|---|---|---|---|---|
| Rust source | 1,328 | 292 | 156 | 1,776 | 7 |
| PHP source | 4,433 | 2,242 | 953 | 7,628 | 30 |
Comments include doc comments. Each side counts its src/; the PHP side is what the package still has in PHP.
Still PHP (30)
Utopia\Queue\AdapterUtopia\Queue\Adapter\KubernetesJobUtopia\Queue\Adapter\SwooleUtopia\Queue\Adapter\WorkermanUtopia\Queue\Broker\BackgroundUtopia\Queue\Broker\NatsUtopia\Queue\Broker\PoolUtopia\Queue\Broker\ProvisioningUtopia\Queue\Broker\RedisUtopia\Queue\CodecUtopia\Queue\Codec\CompatUtopia\Queue\Codec\IgbinaryUtopia\Queue\Codec\JsonUtopia\Queue\ConnectionUtopia\Queue\Connection\LockingUtopia\Queue\Connection\RedisUtopia\Queue\Connection\RedisClusterUtopia\Queue\ConsumerUtopia\Queue\Consumer\BoundedUtopia\Queue\Consumer\ExclusiveUtopia\Queue\Consumer\StreamingUtopia\Queue\Internal\BufferUtopia\Queue\JobUtopia\Queue\MessageUtopia\Queue\PermanentFailureUtopia\Queue\Publisher\AsynchronousUtopia\Queue\Publisher\BufferFullExceptionUtopia\Queue\Publisher\SynchronousUtopia\Queue\QueueUtopia\Queue\ServerInstall#
cargo add utopia-queueGetting started#
Common tasks with Queue, each a complete program you can copy and run.
A worker in Rust takes messages from the same NATS JetStream or Redis queue as the utopia-php/queue workers, at the same time, and settles them the way Broker\Nats or Broker\Redis does. A queue can move to Rust one replica at a time. This guide covers the common tasks.
Consume a queue
Connect with the queue's nats:// or redis:// DSN, name the queue, and give consume a handler. Each call gets one message: Ok commits it, and an Err rejects it, to come back on the queue's backoff. Up to concurrency calls run at once, and a message is held from when it arrives until it is settled, so it does not go back to another worker meanwhile. Once stop completes, consume lets the running calls finish, settles their messages and returns.
use utopia_queue::{Consume, Delivery, Worker};
let worker = Worker::connect("nats://user:password@nats:4222", "v1-mails").await?;
let stop = std::future::pending::<()>(); // tokio::signal::ctrl_c(), say
worker
.consume(Consume { concurrency: 6, prefetch: 0 }, stop, async |delivery: &Delivery| {
// Process delivery.envelope.payload.
Ok(())
})
.await?;use Utopia\DSN\DSN;
use Utopia\Queue;
use Utopia\Queue\Broker\Nats;
use Utopia\Queue\Consumer;
use Utopia\Queue\Message;
$consumer = fn (): Consumer => Nats::fromDSN(new DSN('nats://user:password@nats:4222'), 'worker-mails');
$server = new Queue\Server(new Queue\Adapter\Swoole($consumer, workerNum: 1));
$server
->job('v1-mails', 6)
->inject('message')
->action(function (Message $message) {
// Process $message->getPayload(). A throw rejects it.
});
$server->start();Prefetch
prefetch messages wait ahead of the running calls, so a call that ends finds the next one waiting instead of asking the server for it. That saves one round trip per call, and it is held against the queue's maxAckPending, which every worker on the queue shares, and run before a stop returns. Choose it by how long a call takes:
| Handler | Prefetch |
|---|---|
| Slow: builds, deletes, mails, webhooks | 0. A message waiting behind a slow call is one another worker could be running, and one a stop has to wait for. |
| Quick, about a round trip | About concurrency |
Prefetch or not, messages come from a pull request held open on the server and handed over as they arrive, so a quiet queue is not asked once per message. PHP's prefetch defaults to coroutines; there is no default here.
Consume in batches
For work that is cheaper done together, such as one insert for many rows, implement Batch and call consume_batch. add takes each message into the open batch as it arrives, full says when to write before the batch has size messages, and flush writes it. A batch is written at most linger after its first message. Each message is held until its batch is written and gets its own result: an Err from add fails it alone, an Err from flush fails the whole batch, and flush can fail some messages by their position.
use std::time::Duration;
use utopia_queue::{Batch, Batches, Delivery, Failure, Flushed, Worker};
#[derive(Default)]
struct Rows(Vec<serde_json::Value>);
impl Batch for Rows {
fn add(&mut self, delivery: &Delivery) -> Result<(), Failure> {
self.0.push(delivery.envelope.payload.clone());
Ok(())
}
async fn flush(self) -> Flushed {
// Write self.0 in one insert.
Ok(Vec::new())
}
}
let batches = Batches { linger: Duration::from_millis(500), size: 1_000 };
worker.consume_batch(batches, stop, Rows::default).await?;There is no concurrency to set: add does not wait on anything, and one batch is written at a time while the next one fills. A worker holds at most 2 × size messages, so a write slower than the next batch fills stops it taking more until the write ends.
PHP has no batch handler: a job is one message.
Give up on a message
A failure no retry can fix, such as a payload naming something that does not exist, goes straight to the dead stream instead of spending its retries. retry() in PHP requeues it once the fault is fixed.
use utopia_queue::Failure;
// The handler's result for the message, or add's in a batch:
Err(Failure::Permanent)use Utopia\Queue\PermanentFailure;
throw new PermanentFailure('The region is not configured');Provision a queue
connect provisions the queue before it consumes, as Broker\Nats does on a PHP worker's first receive: the Q_<NAME> work stream, the Q_<NAME>_DEAD dead stream and the worker consumer, created or rewritten to what the DSN's query says. The query is read as Broker\Nats::fromDSN() reads it (ackWait, maxDeliver, replicas, backoff, deadMaxAge, duplicateWindow, maxAge, maxMsgSize, maxMsgs, maxBytes, discard, maxAckPending, maxWaiting), and anything else in it is refused. Given the same DSN, a Rust worker and a PHP one write the same configuration, so a DSN change reaches the queue when either restarts.
use std::time::Duration;
use utopia_queue::{Provision, Worker};
let provision = Provision { ack_wait: Duration::from_secs(120), max_deliver: 10, replicas: 3, ..Default::default() };
let worker = Worker::join(js, "v1-mails", &provision).await?;A stream that another queue's name maps to is refused rather than rewritten.
What stays in PHP
Dead letters land on the same subjects with the same headers, so PHP's retry() and failed counts see them. A message that cannot be decoded, or that reaches the spare delivery, is dead-lettered on arrival.
The max-deliveries advisory and reap() stay with the PHP workers.
Reference#
Queue workers that share their queues with utopia-php/queue.
Worker consumes a queue on NATS JetStream the way Utopia\Queue\Broker\Nats does, so a
Rust worker and PHP workers can take messages from the same queue at the same time:
- It joins the
workerdurable consumer on theQ_<NAME>stream thatBroker\Natsprovisions. It provisions nothing itself: publishers create the stream on their first publish, and a worker started before that waits for it. - Messages are the JSON envelope
Broker\Natswrites:pid,queue,timestampandpayload. - The redelivery budget and the backoff are read from the consumer, which carries the values the queue's DSN gave it, so this worker retries exactly as the PHP ones do.
- What
Broker\Natsdead-letters, this dead-letters to the same subjects with the same headers, soretry()in PHP requeues it.
What stays with the PHP workers sharing the queue: provisioning, the max-deliveries advisory
and reap(). Both of the last two only matter for a message whose every delivery died
unacknowledged, which Worker::receive dead-letters itself on its spare delivery.
API#
What utopia_queue exports at its root.