diff --git a/README.md b/README.md index 976cea0..66b79d3 100644 --- a/README.md +++ b/README.md @@ -275,25 +275,25 @@ A malformed or unsupported-`schema_version` envelope is always **quarantined** ## Documentation -Full guides live in [`docs/`](docs/): +Full guides live in [`docs/`](docs/Home.md): | Guide | What it covers | | ----- | -------------- | -| [Getting started](docs/getting-started.md) | Install, the three moving parts, your first producer + worker. | -| [Envelope & URNs](docs/envelope-and-urns.md) | The wire format and how to name message URNs. | -| [Handlers & routing](docs/handlers-and-routing.md) | Writing handlers, the `HandlerMap`, unknown-URN strategies. | -| [The worker & retries](docs/worker-and-retries.md) | The loop, `WorkerOptions`, back-off, limits, graceful shutdown, the CLI. | -| [Dead-letter handling](docs/dead-letter.md) | When messages are quarantined and how to inspect/replay them. | -| [PDO transport](docs/transports/pdo.md) | Schema, production DDL, reservation semantics. | -| [Redis transport](docs/transports/redis.md) | Keys, the reliable-queue pattern, delayed retries. | -| [RabbitMQ transport](docs/transports/amqp.md) | Properties, headers, retry/delay caveats. | -| [Interoperability](docs/interoperability.md) | Consuming a Go/Python-produced message end to end. | -| [Migrating from 1.x](docs/migrating-from-v1.md) | What changed and how to port `1.x` jobs. | +| [Getting started](docs/Quick-Start.md) | Install, the three moving parts, your first producer + worker. | +| [Envelope & URNs](docs/The-Message-Envelope.md) | The wire format and how to name message URNs. | +| [Handlers & routing](docs/Handlers-and-Routing.md) | Writing handlers, the `HandlerMap`, unknown-URN strategies. | +| [The worker & retries](docs/The-Worker.md) | The loop, `WorkerOptions`, back-off, limits, graceful shutdown, the CLI. | +| [Dead-letter handling](docs/Retries-and-Dead-Letters.md) | When messages are quarantined and how to inspect/replay them. | +| [PDO transport](docs/Transport-PDO.md) | Schema, production DDL, reservation semantics. | +| [Redis transport](docs/Transport-Redis.md) | Keys, the reliable-queue pattern, delayed retries. | +| [RabbitMQ transport](docs/Transport-RabbitMQ.md) | Properties, headers, retry/delay caveats. | +| [Interoperability](docs/Interoperability.md) | Consuming a Go/Python-produced message end to end. | +| [Migrating from 1.x](docs/Migration-from-1.x.md) | What changed and how to port `1.x` jobs. | ## Migrating from 1.x `2.0` is a breaking rewrite. See [UPGRADE-2.0.md](UPGRADE-2.0.md) and -[docs/migrating-from-v1.md](docs/migrating-from-v1.md). +[docs/Migration-from-1.x.md](docs/Migration-from-1.x.md). ## Testing diff --git a/UPGRADE-2.0.md b/UPGRADE-2.0.md index 5368ef3..177b733 100644 --- a/UPGRADE-2.0.md +++ b/UPGRADE-2.0.md @@ -39,4 +39,4 @@ orphaned any failed job already on the queue. `2.0` serialises the The `2.0` PDO transport stores the full canonical envelope as JSON rather than a column per field, so it no longer depends on column order. The new schema and a -migration note ship in [`docs/transports/pdo.md`](docs/transports/pdo.md). +migration note ship in [`docs/Transport-PDO.md`](docs/Transport-PDO.md). diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..b35af93 --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,309 @@ +# API Reference + +The complete public surface of `initphp/queue`. Types from the underlying +`babelqueue/php-sdk` are referenced where they appear in signatures. + +> Namespaces: everything here is under `InitPHP\Queue\`. SDK types are under +> `BabelQueue\`. + +--- + +## Producer + +`InitPHP\Queue\Producer\Producer` — publishes canonical envelopes through a +`BabelQueue\Contracts\Transport`. + +```php +public function __construct( + BabelQueue\Contracts\Transport $transport, + string $defaultQueue = 'default', +) + +public function dispatch(BabelQueue\Contracts\PolyglotJob $job, ?string $queue = null): ?string +public function send(string $urn, array $data = [], ?string $queue = null, ?string $traceId = null): ?string +``` + +- `dispatch()` reads the URN and payload from the job; honours `HasTraceId`. +- `send()` builds the envelope from a URN + array. +- Both return the transport's message id, or `null`. +- Throws `BabelQueue\Exceptions\BabelQueueException` on an empty URN and + `\JsonException` on an unencodable payload. + +See [Producing Messages](Producing-Messages.md). + +--- + +## Consumer + +### Worker + +`InitPHP\Queue\Consumer\Worker` — the consume loop. + +```php +public function __construct( + InitPHP\Queue\Contracts\ConsumerTransport $transport, + InitPHP\Queue\Consumer\Dispatcher $dispatcher, + InitPHP\Queue\Consumer\WorkerOptions $options = new WorkerOptions(), + ?callable $logger = null, // ($level, $event, $context) +) + +public function run(string $queue): void // loop until stop/limit (resilient) +public function runOnce(string $queue): bool // process one; true if a message was handled +public function stop(): void // request graceful stop +public function processedCount(): int +``` + +See [The Worker](The-Worker.md). + +### WorkerOptions + +`InitPHP\Queue\Consumer\WorkerOptions` — immutable worker tuning. + +```php +public function __construct( + int $maxAttempts = 3, + array $backoff = [0], // list seconds + float $reserveTimeout = 5.0, + float $sleepWhenEmpty = 0.5, + int $maxJobs = 0, + float $maxRuntime = 0.0, + int $memoryLimitMb = 0, + bool $stopWhenEmpty = false, +) + +public function delayForAttempt(int $attempt): int +``` + +Public readonly properties match the constructor parameters. Out-of-range values +throw `ConfigurationException`. + +### Dispatcher + +`InitPHP\Queue\Consumer\Dispatcher` — validates and routes a message. + +```php +public function __construct( + InitPHP\Queue\Contracts\HandlerResolver $resolver, + string $unknownUrnStrategy = BabelQueue\Routing\UnknownUrnStrategy::FAIL, +) + +public function dispatch(InitPHP\Queue\Message\ReceivedMessage $message): InitPHP\Queue\Consumer\Outcome +``` + +An unknown strategy string throws `ConfigurationException`. + +### Outcome / OutcomeKind + +`InitPHP\Queue\Consumer\Outcome` — the dispatcher's decision (immutable). + +```php +public readonly OutcomeKind $kind; +public readonly string $reason; // '' | 'failed' | 'unknown_urn' | a validator reason +public readonly ?\Throwable $exception; + +public static function ack(): self +public static function retry(?\Throwable $exception = null, string $reason = 'failed'): self +public static function deadLetter(string $reason, ?\Throwable $exception = null): self +public static function drop(string $reason): self +public static function release(string $reason): self +``` + +`InitPHP\Queue\Consumer\OutcomeKind` is an enum: `Ack`, `Retry`, `DeadLetter`, +`Drop`, `Release`. + +--- + +## Routing + +### HandlerMap + +`InitPHP\Queue\Routing\HandlerMap implements HandlerResolver`. + +```php +public function register(string $urn, InitPHP\Queue\Contracts\Handler|\Closure|string $handler): self +public function has(string $urn): bool +public function resolve(string $urn): ?InitPHP\Queue\Contracts\Handler +``` + +A `string` handler is a no-arg `Handler` class name; a `Closure` is wrapped in a +`CallableHandler`. Invalid registrations throw `ConfigurationException` on resolve; +an empty URN throws on `register()`. + +### CallableHandler + +`InitPHP\Queue\Routing\CallableHandler implements Handler` — adapts a closure into +a handler. + +```php +public function __construct(callable $callback) // callable(InboundMessage): void +public function handle(BabelQueue\Contracts\InboundMessage $message): void +``` + +See [Handlers & Routing](Handlers-and-Routing.md). + +--- + +## Contracts + +### Handler + +```php +namespace InitPHP\Queue\Contracts; + +interface Handler +{ + public function handle(BabelQueue\Contracts\InboundMessage $message): void; +} +``` + +### HandlerResolver + +```php +interface HandlerResolver +{ + public function resolve(string $urn): ?Handler; +} +``` + +### ConsumerTransport + +```php +interface ConsumerTransport +{ + public function reserve(string $queue, float $timeout = 5.0): ?InitPHP\Queue\Message\ReceivedMessage; + public function ack(InitPHP\Queue\Message\ReceivedMessage $message): void; + public function release(InitPHP\Queue\Message\ReceivedMessage $message, string $payload, int $delaySeconds = 0): void; + public function deadLetter(InitPHP\Queue\Message\ReceivedMessage $message, string $payload): void; +} +``` + +--- + +## Message + +### ReceivedMessage + +`InitPHP\Queue\Message\ReceivedMessage implements BabelQueue\Contracts\InboundMessage`. + +```php +public function __construct(string $queue, string $rawBody, array $envelope, mixed $receipt) + +// InboundMessage: +public function getUrn(): string +public function getTraceId(): string +public function getData(): array +public function getMeta(): array + +// Plus worker-facing accessors: +public function queue(): string +public function rawBody(): string +public function envelope(): array +public function attempts(): int +public function receipt(): mixed +``` + +--- + +## Transports + +All implement `BabelQueue\Contracts\Transport` (publish) **and** +`InitPHP\Queue\Contracts\ConsumerTransport` (consume). + +### PdoTransport + +```php +namespace InitPHP\Queue\Transport\Pdo; + +public function __construct( + PDO $pdo, + string $table = 'jobs', + ?string $failedTable = null, // defaults to "_failed" + string $defaultQueue = 'default', + int $retryAfter = 90, // visibility timeout, seconds +) + +public function createSchema(): void +``` + +See [Transport: PDO](Transport-PDO.md). + +### RedisTransport + +```php +namespace InitPHP\Queue\Transport\Redis; + +public function __construct( + Predis\ClientInterface $client, + string $defaultQueue = 'default', + string $processingSuffix = ':processing', + string $failedSuffix = ':failed', + string $delayedSuffix = ':delayed', +) +``` + +See [Transport: Redis](Transport-Redis.md). + +### AmqpTransport + +```php +namespace InitPHP\Queue\Transport\Amqp; + +public function __construct( + PhpAmqpLib\Channel\AMQPChannel $channel, + string $defaultQueue = 'default', + string $failedSuffix = '.failed', +) +``` + +See [Transport: RabbitMQ](Transport-RabbitMQ.md). + +--- + +## Console + +`InitPHP\Queue\Console\WorkerCommand` — backs `bin/queue`. + +```php +public function __construct(?callable $writer = null) // output sink; defaults to STDERR +public function run(array $argv): int // exit code (0 ok, 1 usage/error) +``` + +CLI: `php vendor/bin/queue work --bootstrap= [--queue=] [--once]`. + +--- + +## Exceptions + +```php +InitPHP\Queue\Exceptions\QueueException + extends BabelQueue\Exceptions\BabelQueueException // extends \RuntimeException + +InitPHP\Queue\Exceptions\ConfigurationException + extends InitPHP\Queue\Exceptions\QueueException +``` + +- `QueueException` — base for runtime errors raised by this package. +- `ConfigurationException` — programmer/config mistakes detectable before any + message flows (empty URN, unknown strategy, bad handler class, out-of-range + options, invalid table name). Never retried. + +Catching `BabelQueue\Exceptions\BabelQueueException` captures both these and the +SDK's own envelope/codec errors. + +--- + +## SDK types you will touch + +From `babelqueue/php-sdk` (installed automatically): + +| Type | Use | +| ---- | --- | +| `BabelQueue\Codec\EnvelopeCodec` | `make` / `fromJob` / `encode` / `decode` / `urn` / `accepts`. | +| `BabelQueue\Contracts\InboundMessage` | The read-only message a handler receives. | +| `BabelQueue\Contracts\PolyglotJob` | `getBabelUrn()` + `toPayload()` — a producible job. | +| `BabelQueue\Contracts\HasTraceId` | `getBabelTraceId()` — opt-in trace propagation. | +| `BabelQueue\Contracts\Transport` | The publish seam a `Producer` needs. | +| `BabelQueue\Routing\UnknownUrnStrategy` | `FAIL` / `DELETE` / `RELEASE` / `DEAD_LETTER`. | +| `BabelQueue\Validation\EnvelopeValidator` | `check()` + `REASON_*` constants. | +| `BabelQueue\DeadLetter\DeadLetter` | `annotate()` — the dead-letter block. | +| `BabelQueue\Exceptions\BabelQueueException` | Base of the exception hierarchy. | diff --git a/docs/Core-Concepts.md b/docs/Core-Concepts.md new file mode 100644 index 0000000..7c18500 --- /dev/null +++ b/docs/Core-Concepts.md @@ -0,0 +1,104 @@ +# Core Concepts + +InitPHP Queue is a small set of parts that snap together. Understanding the three +of them — and the one dependency they sit on — is enough to use the whole package. + +## The dependency: BabelQueue + +[`babelqueue/php-sdk`](https://github.com/BabelQueue/php-sdk) defines the **wire +format**: a canonical JSON envelope (`{ job, trace_id, data, meta, attempts }`) +and the rules for routing on a **URN**, validating an envelope, and annotating a +dead-letter. It is a *contract runtime, not a worker* — it publishes, but it +deliberately does not own a consume loop or retry policy. + +InitPHP Queue is exactly that missing consume side, for plain PHP. See +[The Message Envelope](The-Message-Envelope.md) for the format itself. + +## The three moving parts + +``` + ┌────────────┐ publish ┌─────────┐ + Producer ────►│ Transport │ ───────────► │ Broker │ + └────────────┘ │ (Redis, │ + ┌────────────┐ reserve │ Rabbit, │ + Worker ──────►│ Transport │ ◄─────────── │ DB) │ + │ └────────────┘ └─────────┘ + │ dispatch + ▼ + ┌────────────┐ resolve(urn) ┌─────────────┐ + │ Dispatcher │ ───────────────► │ HandlerMap │ ──► your Handler + └────────────┘ └─────────────┘ +``` + +### 1. Transport + +A transport talks to one broker. It implements **both** sides: + +- **Publish** (the SDK's `BabelQueue\Contracts\Transport`): `publish(string $payload, ?string $queue)`. +- **Consume** (`InitPHP\Queue\Contracts\ConsumerTransport`): `reserve()`, `ack()`, + `release()`, `deadLetter()`. + +Three are bundled — [PDO](Transport-PDO.md), [Redis](Transport-Redis.md), +[RabbitMQ](Transport-RabbitMQ.md) — and a single transport object both produces and +consumes. + +### 2. Dispatcher + HandlerMap (routing) + +The **`Dispatcher`** decodes and validates each reserved message, resolves its +handler by URN via a **`HandlerResolver`** (the bundled one is `HandlerMap`), runs +it, and returns an **`Outcome`** describing what should happen (ack / retry / +dead-letter / drop / release). It contains no broker code. See +[Handlers & Routing](Handlers-and-Routing.md). + +### 3. Worker + +The **`Worker`** is the loop. It reserves a message from the transport, asks the +dispatcher for an outcome, and performs the matching broker action — applying the +retry / back-off / dead-letter policy from **`WorkerOptions`**. It also handles +limits and graceful shutdown. See [The Worker](The-Worker.md). + +## A message's journey + +**Producing:** + +1. `Producer::send($urn, $data)` calls `EnvelopeCodec::make()` + `encode()`. +2. The JSON envelope is handed to `Transport::publish()`. +3. The broker stores it on the queue. + +**Consuming:** + +1. `Worker` calls `Transport::reserve()` → a `ReceivedMessage` (or `null`). +2. `Dispatcher::dispatch()` validates the envelope, resolves the handler by URN, + and runs it. +3. The handler returning → **ack**; throwing → **retry** (re-queue with an + incremented `attempts` and a back-off delay), until `maxAttempts` → + **dead-letter**. +4. The `Worker` performs that action through the transport. + +## Why route on a URN? + +In `1.x` the producing PHP **class name** was serialised into the message and the +consumer did `new $class(...)`. That made every message PHP-only and brittle: a +Go service couldn't consume it, and renaming the class orphaned messages already +queued. + +A **URN** (`urn:babel:orders:created`) is a plain, stable string under your +control. The producing class can be renamed or moved freely, and a consumer in any +language routes on the same string without sharing a type. This is what makes the +queue **polyglot** — see [Interoperability](Interoperability.md). + +## Delivery guarantee + +Delivery is **at-least-once**. A message reserved by a worker that then crashes +becomes reservable again (the PDO visibility timeout; the Redis processing list). +A handler may therefore run more than once for the same message, so **handlers +must be idempotent**. + +## Error handling + +All runtime errors extend `InitPHP\Queue\Exceptions\QueueException`, which extends +the SDK's `BabelQueue\Exceptions\BabelQueueException` — so a single +`catch (BabelQueueException)` captures both envelope/codec errors and runtime +errors. Configuration mistakes (an empty URN, an unknown strategy, a handler class +that does not implement `Handler`) raise `ConfigurationException` immediately and +are never retried. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..392a9e8 --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,82 @@ +# FAQ + +### Is this a replacement for Laravel Queue or Symfony Messenger? + +No — it is for apps that **don't** have one. Laravel and Symfony already own a +worker loop and retry machinery; the BabelQueue adapters plug into those. InitPHP +Queue is the equivalent runtime for a plain PHP / Slim / Mezzio app that has no +such loop of its own. + +### What is the relationship to `babelqueue/php-sdk`? + +The SDK defines the **wire format** (the canonical envelope, URN routing, +validation, dead-letter annotation) and a publish-only `Transport`. It deliberately +does not own a consumer loop. InitPHP Queue **is** that consumer loop for +framework-less PHP, plus a database transport the SDK does not ship. It depends on +the SDK and reuses its codec, so the two never drift. See [Core Concepts](Core-Concepts.md). + +### Why route on a URN instead of a class name? + +So the queue is **polyglot** and **refactor-safe**. A URN is a stable string any +language can match on; a PHP class name is neither. See +[The Message Envelope](The-Message-Envelope.md#urns-naming-your-messages). + +### Do I have to use the `Producer` / `HandlerMap`? + +No. The `Producer` is a one-line convenience over `EnvelopeCodec` + a transport; +`HandlerMap` is one implementation of `HandlerResolver`. You can publish raw +envelopes yourself and back routing with your own container — see +[Producing Messages](Producing-Messages.md#producing-without-this-package) and +[Handlers & Routing](Handlers-and-Routing.md#container-based-resolution). + +### Which transport should I pick? + +If you already have a database and want zero new infrastructure, use +[PDO](Transport-PDO.md). For throughput, use [Redis](Transport-Redis.md). For a real +broker with routing, use [RabbitMQ](Transport-RabbitMQ.md). The +[overview](Transports.md#choosing-one) has a comparison table. + +### How are retries delayed? + +The worker re-queues a failed message with a back-off delay from +`WorkerOptions::$backoff`. PDO and Redis honour the delay natively; RabbitMQ +applies retries immediately unless the delayed-message-exchange plugin is +installed. See [Retries & Dead-Letters](Retries-and-Dead-Letters.md). + +### Is delivery exactly-once? + +No — it is **at-least-once**. A message can be delivered more than once (e.g. a +worker crashes after handling but before acking). Make handlers **idempotent**. + +### Can a Go / Python / Node service consume what PHP produces (and vice-versa)? + +Yes — that is the whole point. They share the canonical envelope and route on the +same URN. See [Interoperability](Interoperability.md). + +### How do I run a worker in production? + +Run `vendor/bin/queue work --bootstrap=worker.php --queue=...` under a process +supervisor (systemd, supervisord, a container restart policy), and set a +`maxJobs`/`memoryLimitMb` limit so each worker exits and restarts with clean +memory. See [The Worker](The-Worker.md#the-cli). + +### How do I stop a worker cleanly during a deploy? + +Send `SIGTERM` (or `SIGINT`). With `ext-pcntl` installed, the worker finishes the +in-flight message and then exits. + +### Does it need an extension for Redis? + +No — `predis/predis` is a pure-PHP client. `ext-redis` (phpredis) is optional; see +[Transport: Redis](Transport-Redis.md#using-phpredis-instead). + +### Where do failed messages go, and can I replay them? + +To a per-transport dead-letter destination (a `*_failed` table, a `:failed` list, +or a `.failed` queue). Decode the stored envelope, drop the `dead_letter` block, +reset `attempts`, and re-publish. See +[Retries & Dead-Letters](Retries-and-Dead-Letters.md#replaying-a-dead-lettered-message). + +### What PHP versions are supported? + +PHP **8.2, 8.3, 8.4 and 8.5** are tested in CI. diff --git a/docs/Handlers-and-Routing.md b/docs/Handlers-and-Routing.md new file mode 100644 index 0000000..b99995e --- /dev/null +++ b/docs/Handlers-and-Routing.md @@ -0,0 +1,151 @@ +# Handlers & Routing + +A consumed message is routed to a **handler** by its **URN**. This page covers +writing handlers, registering them, container integration, and what happens when a +URN has no handler. + +## The `Handler` contract + +```php +namespace InitPHP\Queue\Contracts; + +use BabelQueue\Contracts\InboundMessage; + +interface Handler +{ + public function handle(InboundMessage $message): void; +} +``` + +- **Return** to acknowledge — the worker removes the message. +- **Throw** to fail — the worker retries with back-off, then dead-letters. + +```php +use BabelQueue\Contracts\InboundMessage; +use InitPHP\Queue\Contracts\Handler; + +final class RecordOrder implements Handler +{ + public function __construct(private readonly PDO $db) {} + + public function handle(InboundMessage $message): void + { + $data = $message->getData(); + + $stmt = $this->db->prepare('INSERT INTO orders (id, amount) VALUES (?, ?)'); + $stmt->execute([$data['order_id'], $data['amount']]); + // Return = success. An exception here = failure (retry, then dead-letter). + } +} +``` + +## Registering handlers with `HandlerMap` + +`HandlerMap` is the bundled URN → handler registry. A handler may be registered +three ways: + +```php +use InitPHP\Queue\Routing\HandlerMap; + +$handlers = new HandlerMap(); + +// 1. A class name — lazily instantiated, must have a no-arg constructor: +$handlers->register('urn:babel:users:registered', SendWelcomeEmail::class); + +// 2. A ready-built instance — use this to inject dependencies yourself: +$handlers->register('urn:babel:orders:created', new RecordOrder($pdo)); + +// 3. A closure — for small inline handlers: +$handlers->register('urn:babel:audit:logged', function (InboundMessage $m): void { + error_log('audit: ' . $m->getUrn()); +}); +``` + +API: + +| Method | Returns | Notes | +| ------ | ------- | ----- | +| `register(string $urn, Handler\|Closure\|string $handler)` | `self` | Chainable. Re-registering a URN replaces the previous entry. | +| `has(string $urn)` | `bool` | Whether a URN is mapped. | +| `resolve(string $urn)` | `?Handler` | The handler, or `null` if unmapped. Caches instances. | + +`register()` returns `$this`, so calls chain: + +```php +$handlers = (new HandlerMap()) + ->register('urn:babel:users:registered', SendWelcomeEmail::class) + ->register('urn:babel:orders:created', new RecordOrder($pdo)) + ->register('urn:babel:orders:shipped', OnOrderShipped::class); +``` + +A class name that does not exist, or does not implement `Handler`, raises a +`ConfigurationException` the first time it is resolved — a bug you fix in code, +never a runtime failure that gets retried. Registering an **empty URN** throws +immediately. + +## Container-based resolution + +If your handlers need constructor injection, back the routing with your own +PSR-11 container by implementing `HandlerResolver` instead of using `HandlerMap`: + +```php +use InitPHP\Queue\Contracts\Handler; +use InitPHP\Queue\Contracts\HandlerResolver; +use Psr\Container\ContainerInterface; + +final class ContainerHandlerResolver implements HandlerResolver +{ + /** @param array> $map URN => handler class */ + public function __construct( + private readonly ContainerInterface $container, + private readonly array $map, + ) {} + + public function resolve(string $urn): ?Handler + { + $class = $this->map[$urn] ?? null; + + return $class !== null ? $this->container->get($class) : null; + } +} +``` + +Any `HandlerResolver` can be passed to the `Dispatcher`. + +## The `Dispatcher` + +The dispatcher ties routing together. You build it with a resolver and an +unknown-URN strategy, then hand it to a `Worker` — you rarely call it yourself. + +```php +use BabelQueue\Routing\UnknownUrnStrategy; +use InitPHP\Queue\Consumer\Dispatcher; + +$dispatcher = new Dispatcher($handlers, UnknownUrnStrategy::FAIL); +``` + +For each message it: validates the envelope, resolves the handler by URN, runs it, +and returns an `Outcome` (ack / retry / dead-letter / drop / release) the worker +acts on. + +## Unknown-URN strategies + +When a message's URN has no mapped handler, the dispatcher applies the strategy +passed to its constructor — the four canonical BabelQueue options from +`BabelQueue\Routing\UnknownUrnStrategy`: + +| Strategy | Constant | Behaviour | +| -------- | -------- | --------- | +| Fail *(default)* | `UnknownUrnStrategy::FAIL` | Treat as a failure: retry, then dead-letter. Safest while a fleet is mid-deploy and a consumer hasn't learned a new URN yet. | +| Delete | `UnknownUrnStrategy::DELETE` | Acknowledge and silently discard. | +| Release | `UnknownUrnStrategy::RELEASE` | Put it back on the queue verbatim for another worker/version. | +| Dead-letter | `UnknownUrnStrategy::DEAD_LETTER` | Quarantine immediately, then acknowledge. | + +```php +new Dispatcher($handlers, UnknownUrnStrategy::DEAD_LETTER); +``` + +Passing an unrecognised strategy string throws `ConfigurationException`. + +Whatever the strategy for *unknown* URNs, a **malformed or unsupported-schema** +envelope is always dead-lettered — see [Retries & Dead-Letters](Retries-and-Dead-Letters.md). diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..bc56115 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,73 @@ +# InitPHP Queue — Wiki + +Welcome to the official documentation for **`initphp/queue`** — the +**framework-less [BabelQueue](https://babelqueue.com) runtime for plain PHP**. + +It gives an application that has no Laravel queue or Symfony Messenger of its own +the piece [`babelqueue/php-sdk`](https://github.com/BabelQueue/php-sdk) +deliberately leaves to the framework: the **consumer loop, retries with back-off +and dead-letter routing** — plus a **database (PDO) transport** the core SDK does +not ship. + +Because it reuses the SDK's canonical `{ job, trace_id, data, meta, attempts }` +envelope, the queue you produce and consume here is the **same** queue a Go, +Python, Node or .NET service reads. Messages are routed by a stable **URN** +(`urn:babel:orders:created`), never a PHP class name. + +```bash +composer require initphp/queue predis/predis +``` + +```php +use BabelQueue\Contracts\InboundMessage; +use InitPHP\Queue\Consumer\{Dispatcher, Worker, WorkerOptions}; +use InitPHP\Queue\Contracts\Handler; +use InitPHP\Queue\Producer\Producer; +use InitPHP\Queue\Routing\HandlerMap; +use InitPHP\Queue\Transport\Redis\RedisTransport; + +// A handler is mapped to a URN, not a class name. +final class SendWelcomeEmail implements Handler +{ + public function handle(InboundMessage $message): void + { + $email = $message->getData()['email']; + // ... send it. Throwing marks the message as failed (retry, then dead-letter). + } +} + +$transport = new RedisTransport(new Predis\Client('tcp://127.0.0.1:6379')); + +// Produce +(new Producer($transport, 'emails')) + ->send('urn:babel:users:registered', ['user_id' => 42, 'email' => 'jane@example.com']); + +// Consume +$handlers = (new HandlerMap())->register('urn:babel:users:registered', SendWelcomeEmail::class); +$worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(maxAttempts: 3)); +$worker->run('emails'); +``` + +## Where this package sits + +| Layer | `babelqueue/php-sdk` | **InitPHP Queue** | +| ----- | -------------------- | ----------------- | +| Wire format / contract | Canonical envelope, URN scheme, validation, dead-letter annotation | *reuses it* | +| Producer | `EnvelopeCodec` + a publish `Transport` | `Producer` facade | +| **Consumer loop** | **— (left to the framework)** | **`Worker`: reserve → route → ack / retry / dead-letter** | +| Transports | Redis & AMQP (publish only) | Redis, AMQP **and PDO** (publish **+** consume) | + +## Start here + +- **New to the package?** Read [Installation](Installation.md) then [Quick Start](Quick-Start.md). +- **Want the big picture?** Read [Core Concepts](Core-Concepts.md). +- **Coming from `1.x`?** Read [Migration from 1.x](Migration-from-1.x.md). + +Use the sidebar to navigate. Every code example on this wiki reflects the real +public API of the current release. + +## Requirements + +- PHP **8.2+** +- `babelqueue/php-sdk ^1.0` (installed automatically) +- A client for your broker: `ext-pdo`, `predis/predis` (Redis 6.2+), or `php-amqplib/php-amqplib` diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..7d7b9e4 --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,64 @@ +# Installation + +## Requirements + +| | | +| --- | --- | +| PHP | **8.2** or newer | +| Core dependency | [`babelqueue/php-sdk`](https://packagist.org/packages/babelqueue/php-sdk) `^1.0` (installed automatically) | +| `ext-json` | required (bundled with PHP) | +| `ext-pcntl` | optional — enables graceful `SIGINT`/`SIGTERM` shutdown | + +Plus the client for the broker you choose (see below). + +## Install + +```bash +composer require initphp/queue +``` + +Then add the client for your transport: + +```bash +# Database (PDO) — nothing extra beyond ext-pdo +# Redis 6.2+ +composer require predis/predis +# RabbitMQ +composer require php-amqplib/php-amqplib +``` + +| Transport | Needs | Notes | +| --------- | ----- | ----- | +| [PDO (Database)](Transport-PDO.md) | `ext-pdo` | Works on MySQL and SQLite. No broker process to run. | +| [Redis](Transport-Redis.md) | `predis/predis` | Redis **6.2+** (uses `BLMOVE`). Pure-PHP client, no extension needed. | +| [RabbitMQ](Transport-RabbitMQ.md) | `php-amqplib/php-amqplib` | Also needs `ext-sockets` (a dependency of php-amqplib). | + +## Verify the install + +```php +require 'vendor/autoload.php'; + +$transport = new InitPHP\Queue\Transport\Pdo\PdoTransport(new PDO('sqlite::memory:')); +$transport->createSchema(); + +(new InitPHP\Queue\Producer\Producer($transport, 'demo')) + ->send('urn:demo:hello', ['who' => 'world']); + +echo "ok\n"; +``` + +## The worker CLI + +The package ships an executable at `vendor/bin/queue`. Confirm it is available: + +```bash +php vendor/bin/queue work +# prints the usage banner +``` + +See [The Worker](The-Worker.md#the-cli) for how to drive it with a bootstrap file. + +## Next + +- [Quick Start](Quick-Start.md) — produce and consume your first message. +- [Core Concepts](Core-Concepts.md) — how the pieces fit together. diff --git a/docs/interoperability.md b/docs/Interoperability.md similarity index 56% rename from docs/interoperability.md rename to docs/Interoperability.md index ffecc76..26d7b46 100644 --- a/docs/interoperability.md +++ b/docs/Interoperability.md @@ -1,13 +1,13 @@ # Interoperability -The whole point of building on BabelQueue is that the queue you produce and -consume in PHP is the *same* queue other languages use. The wire format is the -canonical envelope; routing is by URN, never a PHP class name. This guide shows a -message crossing a language boundary in each direction. +The point of building on BabelQueue is that the queue you produce and consume in +PHP is the **same** queue other languages use. The wire format is the canonical +envelope; routing is by URN, never a PHP class name. This page shows a message +crossing a language boundary in each direction. -## A PHP producer, a Go/Python consumer +## PHP produces, another language consumes -Publish from PHP exactly as usual: +Publish from PHP as usual: ```php use InitPHP\Queue\Producer\Producer; @@ -33,37 +33,34 @@ A consumer in any BabelQueue SDK reserves from the same `orders` queue, matches `job == "urn:babel:orders:created"`, and reads `data.order_id`. No shared PHP type, no `serialize()`, no translation layer. -## A non-PHP producer, a PHP consumer +## Another language produces, PHP consumes -When another service produces onto a queue your PHP worker consumes, nothing -changes on your side — the worker decodes and routes by URN: +Nothing changes on the PHP side — the worker decodes and routes by URN: ```php -$handlers = (new HandlerMap()) - ->register('urn:babel:orders:created', RecordOrder::class); - -$worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions()); +$handlers = (new HandlerMap())->register('urn:babel:orders:created', RecordOrder::class); +$worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions()); $worker->run('orders'); ``` Two cross-language details the runtime handles for you: - **The `urn` alias.** Some SDKs emit the field as `urn` instead of `job`; the - worker accepts both (`EnvelopeCodec::urn()` reads either). A Go-produced message - using `urn` routes to your handler identically. -- **Producer language.** `meta.lang` tells you where a message came from - (`go`, `python`, …) via `$message->getMeta()['lang']`, which is handy for - logging but never affects routing. + worker accepts both. A message produced with `urn` routes to your handler + identically. +- **Producer language.** `meta.lang` (`go`, `python`, …) is available via + `$message->getMeta()['lang']` for logging, but never affects routing. ## Trace propagation across services `trace_id` is preserved unchanged across every hop and language. When a handler -dispatches a *downstream* job as a result of the one it is processing, carry the -incoming trace id forward so the whole chain shares one trace: +dispatches a *downstream* job, carry the incoming trace id forward so the whole +chain shares one trace: ```php use BabelQueue\Contracts\InboundMessage; use InitPHP\Queue\Contracts\Handler; +use InitPHP\Queue\Producer\Producer; final class RecordOrder implements Handler { @@ -73,12 +70,11 @@ final class RecordOrder implements Handler { // ... record the order ... - // Continue the same trace into the next message: $this->producer->send( 'urn:babel:billing:invoice.requested', ['order_id' => $message->getData()['order_id']], 'billing', - $message->getTraceId(), // inherited trace id + $message->getTraceId(), // continue the same trace ); } } @@ -90,9 +86,9 @@ single distributed trace spans all of them. ## Conformance The runtime is tested against the SDK's cross-SDK **conformance fixtures** — the -same golden files every BabelQueue SDK must satisfy (`order-created`, the Go +golden files every BabelQueue SDK must satisfy (`order-created`, the Go `urn-alias`, `dead-lettered`, a `unicode-and-numbers` round-trip, and the invalid -cases). See `tests/Conformance/EnvelopeConformanceTest.php`. If those pass, a -message produced by any conforming SDK is consumable here. +cases). If those pass, a message produced by any conforming SDK is consumable +here. For the full cross-language standard, see [babelqueue.com](https://babelqueue.com). diff --git a/docs/Migration-from-1.x.md b/docs/Migration-from-1.x.md new file mode 100644 index 0000000..3786d3f --- /dev/null +++ b/docs/Migration-from-1.x.md @@ -0,0 +1,116 @@ +# Migration from 1.x + +`2.0` is a breaking rewrite. `1.x` was a self-contained, **PHP-only** queue that +serialised the producing class name into the message +(`{"jobClass": "App\\Jobs\\MailJob", …}`) and did `new $jobClass(...)` on the other +end. `2.0` is the framework-less runtime for the **polyglot BabelQueue envelope**, +routing on a stable URN instead — so the same queue is readable by Go, Python, +Node and any other BabelQueue SDK, and renaming a class no longer orphans messages +already queued. + +## Requirements + +| | 1.x | 2.0 | +| --- | --- | --- | +| PHP | `>= 7.4` | `^8.2` | +| Core dependency | none | `babelqueue/php-sdk ^1.0` | + +## What was removed + +| 1.x symbol | Replacement | +| ---------- | ----------- | +| `InitPHP\Queue\Job` (abstract base) | A class implementing `InitPHP\Queue\Contracts\Handler` | +| `InitPHP\Queue\Interfaces\JobInterface` | `InitPHP\Queue\Contracts\Handler` | +| `InitPHP\Queue\Interfaces\AdapterInterface` | `InitPHP\Queue\Contracts\ConsumerTransport` (+ the SDK's `Transport`) | +| `InitPHP\Queue\Adapters\PDOAdapter` | `InitPHP\Queue\Transport\Pdo\PdoTransport` | +| `InitPHP\Queue\Adapters\RabbitMQAdapter` | `InitPHP\Queue\Transport\Amqp\AmqpTransport` | +| `InitPHP\Queue\Exceptions\JobException`, `JobInvalidArgumentException` | `InitPHP\Queue\Exceptions\QueueException` / `ConfigurationException` | + +## Concept mapping + +| 1.x | 2.0 | +| --- | --- | +| `class MailJob extends Job { handle(): bool }` | `final class SendMail implements Handler { handle(InboundMessage $m): void }` | +| The job class **is** the routing identity | A stable **URN** is the identity; the class is free to change | +| `$job->push(['to' => ...])` | `$producer->send('urn:babel:mail:requested', ['to' => ...])` | +| `$adapter->handle($channel, $queue)` | `$worker->run($queue)` | +| `protected string $channel` / `$queue` | The queue name passed to the producer/worker | +| `ack()` / `nack()` inside the job | The worker acks on success and applies the retry/dead-letter policy on failure | +| Return `true`/`false` from `handle()` | **Return** to ack; **throw** to fail | + +## Porting a job + +**1.x:** + +```php +use InitPHP\Queue\Job; + +class MailJob extends Job +{ + protected string $channel = 'mailChannel'; + protected string $queue = 'mailQueue'; + + public function handle(): bool + { + $p = $this->getPayload(); + return mail($p['to'], $p['subject']); + } +} + +$job = new MailJob($adapter); +$job->push(['to' => 'a@b.c', 'subject' => 'Hi']); // produce +$adapter->handle('mailChannel', 'mailQueue'); // consume +``` + +**2.0:** + +```php +use BabelQueue\Contracts\InboundMessage; +use InitPHP\Queue\Contracts\Handler; + +final class SendMail implements Handler +{ + public function handle(InboundMessage $message): void + { + $p = $message->getData(); + if (! mail($p['to'], $p['subject'])) { + throw new \RuntimeException('mail() failed'); // -> retried, then dead-lettered + } + } +} + +// produce +$producer->send('urn:babel:mail:requested', ['to' => 'a@b.c', 'subject' => 'Hi'], 'mail'); + +// consume +$handlers = (new HandlerMap())->register('urn:babel:mail:requested', SendMail::class); +(new Worker($transport, new Dispatcher($handlers), new WorkerOptions()))->run('mail'); +``` + +## Database schema changed + +`1.x` stored a column per field and moved failed rows with a column-position +`INSERT … SELECT *`. `2.0` stores the full envelope as JSON and uses a portable, +abandonment-safe reservation. The old `queue` / `queue_failed` tables are **not** +compatible — create the new `jobs` / `jobs_failed` tables (see +[Transport: PDO](Transport-PDO.md)). + +## In-flight messages + +Because the wire format changed (class name → URN envelope), `1.x` and `2.0` +messages are not interchangeable on the same queue. Either: + +- **Drain** `1.x` queues with the old code before deploying `2.0`, or +- **Migrate** with a short script that maps the old `jobClass` + `payload` to a URN + + `data` and re-publishes via the new `Producer`. + +```php +// one-off migration sketch +foreach ($oldRows as $row) { + $old = json_decode($row->payload, true); // {'jobClass': ..., 'payload': ...} + $urn = $classToUrn[$old['jobClass']]; // your mapping + $producer->send($urn, $old['payload'], $row->queue); +} +``` + +See also the repository's `UPGRADE-2.0.md`. diff --git a/docs/Producing-Messages.md b/docs/Producing-Messages.md new file mode 100644 index 0000000..23a8627 --- /dev/null +++ b/docs/Producing-Messages.md @@ -0,0 +1,131 @@ +# Producing Messages + +The `InitPHP\Queue\Producer\Producer` is a thin facade over the SDK's +`EnvelopeCodec` and a publish `Transport`. It encodes a canonical envelope and +hands the JSON to the transport, so producing a polyglot message is one line. + +## Constructing a producer + +```php +use InitPHP\Queue\Producer\Producer; + +$producer = new Producer($transport, defaultQueue: 'emails'); +``` + +`$transport` is any `BabelQueue\Contracts\Transport` — the bundled +[PDO](Transport-PDO.md), [Redis](Transport-Redis.md) or [RabbitMQ](Transport-RabbitMQ.md) +transports, or the SDK's own reference transports. The default queue is used +whenever you do not pass one explicitly. + +## `send()` — from a URN and data + +```php +$producer->send( + 'urn:babel:users:registered', // the message URN + ['user_id' => 42, 'email' => 'a@b.c'], // pure-JSON payload + 'emails', // optional: queue (defaults to the producer's) + null, // optional: trace id to continue (else a new one) +); +``` + +Signature: + +```php +public function send( + string $urn, + array $data = [], + ?string $queue = null, + ?string $traceId = null, +): ?string +``` + +The return value is the transport's message id when it exposes one (the database +row id for PDO; `null` for Redis, where the envelope's own `meta.id` is the +identity). + +## `dispatch()` — from a job object + +Instead of a raw URN + array, implement `BabelQueue\Contracts\PolyglotJob` and let +the producer read the URN and payload from the object: + +```php +use BabelQueue\Contracts\PolyglotJob; + +final class UserRegistered implements PolyglotJob +{ + public function __construct(private readonly int $userId) {} + + public function getBabelUrn(): string + { + return 'urn:babel:users:registered'; + } + + public function toPayload(): array + { + return ['user_id' => $this->userId]; + } +} + +$producer->dispatch(new UserRegistered(42), 'emails'); +``` + +`toPayload()` must return **pure, JSON-encodable** data — no objects, closures or +resources. + +## Trace propagation + +Every envelope carries a `trace_id`. Normally the producer mints a fresh one. When +you dispatch a *downstream* message while handling another, carry the incoming +trace id forward so the whole chain shares one trace: + +```php +$producer->send( + 'urn:babel:billing:invoice.requested', + ['order_id' => $message->getData()['order_id']], + 'billing', + $message->getTraceId(), // inherited trace id +); +``` + +For job objects, additionally implement `BabelQueue\Contracts\HasTraceId` and +return the inherited id from `getBabelTraceId()` (return `null` to mint a new one); +`EnvelopeCodec::fromJob()` reuses it automatically. + +```php +use BabelQueue\Contracts\HasTraceId; +use BabelQueue\Contracts\PolyglotJob; + +final class InvoiceRequested implements PolyglotJob, HasTraceId +{ + public function __construct( + private readonly int $orderId, + private readonly ?string $traceId, + ) {} + + public function getBabelUrn(): string { return 'urn:babel:billing:invoice.requested'; } + public function toPayload(): array { return ['order_id' => $this->orderId]; } + public function getBabelTraceId(): ?string { return $this->traceId; } +} +``` + +## Producing without this package + +A `Producer` is convenience, not a requirement. Any code that can `publish()` a +JSON envelope can produce — even another BabelQueue SDK in another language. The +PHP one-liner under the hood is just: + +```php +use BabelQueue\Codec\EnvelopeCodec; + +$transport->publish( + EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:users:registered', ['user_id' => 42], 'emails')), + 'emails', +); +``` + +## Errors + +- An **empty URN** throws `BabelQueue\Exceptions\BabelQueueException`. +- A payload that cannot be JSON-encoded throws `\JsonException`. + +Both surface immediately — producing never silently swallows an error. diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..bb34023 --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,122 @@ +# Quick Start + +This walkthrough takes you from nothing to a producer pushing messages and a +worker consuming them. It uses the [PDO transport](Transport-PDO.md) so you need no +broker — just a database (SQLite here). + +## 1. Write a handler + +A handler implements `InitPHP\Queue\Contracts\Handler` and is mapped to a message +**URN**. It receives a read-only `BabelQueue\Contracts\InboundMessage`. **Return** +to acknowledge; **throw** to fail (the worker retries, then dead-letters). + +```php +use BabelQueue\Contracts\InboundMessage; +use InitPHP\Queue\Contracts\Handler; + +final class SendWelcomeEmail implements Handler +{ + public function handle(InboundMessage $message): void + { + $data = $message->getData(); // ['user_id' => 42, 'email' => '...'] + $traceId = $message->getTraceId(); // correlate with the producer + $meta = $message->getMeta(); // ['id' => ..., 'queue' => ..., 'lang' => ...] + + // Do the work. An exception here marks the message as failed. + // mailer()->sendWelcome($data['email']); + } +} +``` + +> **Idempotency.** Delivery is at-least-once: a handler may run more than once for +> the same message (after a crash, for example). Make it safe to repeat. + +## 2. Build a transport + +```php +use InitPHP\Queue\Transport\Pdo\PdoTransport; + +$pdo = new PDO('sqlite:' . __DIR__ . '/queue.sqlite'); +$transport = new PdoTransport($pdo, table: 'jobs'); +$transport->createSchema(); // creates the jobs / jobs_failed tables (dev convenience) +``` + +## 3. Produce a message + +```php +use InitPHP\Queue\Producer\Producer; + +$producer = new Producer($transport, defaultQueue: 'emails'); + +$producer->send('urn:babel:users:registered', [ + 'user_id' => 42, + 'email' => 'jane@example.com', +]); +``` + +`send()` encodes the canonical envelope and publishes it. A consumer in **any** +language subscribed to the `emails` queue can read it. + +## 4. Consume messages + +Map URNs to handlers, wrap them in a `Dispatcher`, and run a `Worker`. + +```php +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\Worker; +use InitPHP\Queue\Consumer\WorkerOptions; +use InitPHP\Queue\Routing\HandlerMap; + +$handlers = (new HandlerMap()) + ->register('urn:babel:users:registered', SendWelcomeEmail::class); + +$worker = new Worker( + $transport, + new Dispatcher($handlers), + new WorkerOptions(maxAttempts: 3, backoff: [1, 5, 15]), +); + +$worker->run('emails'); // loops, processing messages until stopped +``` + +To process the queue once and exit (handy in tests or cron): + +```php +$worker->runOnce('emails'); // returns bool: was a message processed? +``` + +## 5. Run it as a process + +Put the wiring in a **bootstrap file** that returns a configured `Worker`, and run +it with the CLI: + +```php +// worker.php +require __DIR__ . '/vendor/autoload.php'; + +use InitPHP\Queue\Consumer\{Dispatcher, Worker, WorkerOptions}; +use InitPHP\Queue\Routing\HandlerMap; +use InitPHP\Queue\Transport\Pdo\PdoTransport; + +$transport = new PdoTransport(new PDO('sqlite:' . __DIR__ . '/queue.sqlite'), 'jobs'); +$handlers = (new HandlerMap())->register('urn:babel:users:registered', SendWelcomeEmail::class); + +return new Worker($transport, new Dispatcher($handlers), new WorkerOptions(maxAttempts: 3)); +``` + +```bash +php vendor/bin/queue work --bootstrap=worker.php --queue=emails +# or process exactly one message and exit: +php vendor/bin/queue work --bootstrap=worker.php --queue=emails --once +``` + +Run the worker under a process supervisor (systemd, supervisord, a container +restart policy) and set a `maxJobs`/`memoryLimitMb` limit so each worker exits and +is restarted periodically. + +## What next? + +- [Core Concepts](Core-Concepts.md) — the three moving parts and how they interact. +- [Handlers & Routing](Handlers-and-Routing.md) — closures, container resolution, unknown URNs. +- [The Worker](The-Worker.md) — every tuning knob. +- [Transports](Transports.md) — switch from PDO to Redis or RabbitMQ. diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 927a27a..0000000 --- a/docs/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# InitPHP Queue — Documentation - -InitPHP Queue is the **framework-less [BabelQueue](https://babelqueue.com) runtime -for plain PHP**: it owns the consumer loop, retries and dead-letter routing that -[`babelqueue/php-sdk`](https://github.com/BabelQueue/php-sdk) leaves to the -framework, and reuses the SDK's canonical envelope so your queue interoperates -with Go, Python, Node and any other BabelQueue SDK. - -## Contents - -| Guide | What it covers | -| ----- | -------------- | -| [Getting started](getting-started.md) | Install, the three moving parts, your first producer and worker. | -| [Envelope & URNs](envelope-and-urns.md) | The wire format you produce/consume and how to name message URNs. | -| [Handlers & routing](handlers-and-routing.md) | Writing handlers, registering them, and unknown-URN strategies. | -| [The worker & retries](worker-and-retries.md) | The loop, `WorkerOptions`, back-off, limits, graceful shutdown, and the CLI. | -| [Dead-letter handling](dead-letter.md) | When and why messages are quarantined, and how to inspect or replay them. | -| [PDO transport](transports/pdo.md) | Tables, production DDL, the optimistic reservation, and visibility timeout. | -| [Redis transport](transports/redis.md) | Keys, the reliable-queue pattern, and delayed retries. | -| [RabbitMQ transport](transports/amqp.md) | AMQP properties/headers and the retry/delay caveat. | -| [Interoperability](interoperability.md) | Consuming a message produced by another language, end to end. | -| [Migrating from 1.x](migrating-from-v1.md) | What changed in 2.0 and how to port your jobs. | - -## At a glance - -```php -use BabelQueue\Routing\UnknownUrnStrategy; -use InitPHP\Queue\Consumer\{Dispatcher, Worker, WorkerOptions}; -use InitPHP\Queue\Producer\Producer; -use InitPHP\Queue\Routing\HandlerMap; -use InitPHP\Queue\Transport\Redis\RedisTransport; - -$transport = new RedisTransport(new Predis\Client('tcp://127.0.0.1:6379')); - -// Produce -(new Producer($transport, 'emails'))->send('urn:babel:users:registered', ['user_id' => 42]); - -// Consume -$handlers = (new HandlerMap())->register('urn:babel:users:registered', SendWelcomeEmail::class); -$worker = new Worker($transport, new Dispatcher($handlers, UnknownUrnStrategy::FAIL), new WorkerOptions(maxAttempts: 3)); -$worker->run('emails'); -``` - -## The three moving parts - -1. **Transport** — talks to a broker (PDO / Redis / RabbitMQ). It both publishes - (`Transport::publish`) and consumes (`ConsumerTransport::reserve/ack/release/deadLetter`). -2. **Dispatcher + HandlerMap** — decode and validate each message, then route it - by URN to a `Handler`. -3. **Worker** — the loop that ties them together and applies the retry / back-off - / dead-letter policy from `WorkerOptions`. - -## Requirements - -- PHP 8.2 or newer -- `babelqueue/php-sdk ^1.0` -- The client for your broker: `ext-pdo`, `predis/predis`, or `php-amqplib/php-amqplib` diff --git a/docs/Retries-and-Dead-Letters.md b/docs/Retries-and-Dead-Letters.md new file mode 100644 index 0000000..c7a3720 --- /dev/null +++ b/docs/Retries-and-Dead-Letters.md @@ -0,0 +1,118 @@ +# Retries & Dead-Letters + +This page explains exactly when a message is retried, when it is dead-lettered, +and how to inspect or replay the failures. + +## The retry policy + +When a handler throws, the worker treats the message as failed: + +1. It increments the envelope's `attempts`. +2. If `attempts` is still **below** `WorkerOptions::$maxAttempts`, it **re-queues** + the message with the new `attempts` and a back-off delay. +3. Once `attempts` **reaches** `maxAttempts`, it **dead-letters** the message. + +The delay between attempts comes from `WorkerOptions::$backoff` +(`delayForAttempt(n)` uses `backoff[min(n - 1, last index)]`): + +| `backoff` | Delay after attempt 1 / 2 / 3 / 4 … | +| --------- | ----------------------------------- | +| `[0]` *(default)* | 0 / 0 / 0 / 0 — immediate retries | +| `[1, 5, 15]` | 1s / 5s / 15s / 15s — last value repeats | +| `[2]` | 2s / 2s / 2s — fixed delay | + +> Delays are honoured by the PDO transport (`available_at`) and the Redis transport +> (a delayed sorted set). RabbitMQ retries immediately unless you install the +> delayed-message-exchange plugin — see [Transport: RabbitMQ](Transport-RabbitMQ.md). + +## When a message is dead-lettered + +| Cause | Reason in the `dead_letter` block | +| ----- | --------------------------------- | +| Exhausted retries — a handler kept throwing until `attempts` reached `maxAttempts` | `failed` | +| Malformed / poison envelope (missing URN, non-object `data`, bad `attempts`) | an `EnvelopeValidator::REASON_*` value | +| Unsupported `meta.schema_version` (a newer producer) — **quarantined, never dropped** | `unsupported_schema_version` | +| Unknown URN with the `DEAD_LETTER` strategy (or `FAIL` after retries) | `unknown_urn` | + +## The `dead_letter` annotation + +Before moving the message, the worker annotates the original envelope (via the +SDK's `BabelQueue\DeadLetter\DeadLetter`). The original `trace_id`, `meta.id` and +`data` are preserved verbatim: + +```json +{ + "job": "urn:babel:orders:created", + "trace_id": "7b3f9c2a-...", + "data": { "order_id": 1042 }, + "meta": { "id": "f1e2...", "queue": "orders", "lang": "php", "schema_version": 1, "created_at": 1749132727000 }, + "attempts": 3, + "dead_letter": { + "reason": "failed", + "error": "Payment gateway timeout", + "exception": "App\\Exceptions\\GatewayTimeout", + "failed_at": 1749132730000, + "original_queue": "orders", + "attempts": 3, + "lang": "php" + } +} +``` + +## Where dead-lettered messages go + +Each transport has its own destination, derived from the queue name: + +| Transport | Destination | +| --------- | ----------- | +| PDO | The `*_failed` table (e.g. `jobs_failed`) — one row per message with `reason`, `urn`, `attempts` and the full annotated `payload`. | +| Redis | A `:failed` list (e.g. `orders:failed`). | +| RabbitMQ | A durable `.failed` queue (e.g. `orders.failed`). | + +## Inspecting failures + +**PDO** — query the failed table: + +```sql +SELECT id, urn, attempts, reason, failed_at, payload +FROM jobs_failed +ORDER BY id DESC; +``` + +**Redis** — read the list: + +```bash +LRANGE orders:failed 0 -1 +``` + +**RabbitMQ** — consume `orders.failed` with the same `AmqpTransport` pointed at +that queue name. + +## Replaying a dead-lettered message + +Decode the stored envelope, strip the `dead_letter` block, reset `attempts`, and +publish it again: + +```php +use BabelQueue\Codec\EnvelopeCodec; + +$envelope = EnvelopeCodec::decode($storedPayload); +unset($envelope['dead_letter']); +$envelope['attempts'] = 0; + +$transport->publish(EnvelopeCodec::encode($envelope), $envelope['meta']['queue']); +``` + +For PDO you would read `payload` from a `jobs_failed` row; for Redis, `LPOP`/`LRANGE` +from `orders:failed`; for RabbitMQ, consume `orders.failed`. + +## Tuning + +- Raise `maxAttempts` (and lengthen `backoff`) for **transient** failures like a + flaky downstream service. +- Keep `maxAttempts` low for failures that will **never** succeed on retry (bad + input), so they reach the dead-letter queue quickly instead of looping. +- Use `UnknownUrnStrategy::DEAD_LETTER` to quarantine unmapped messages for review + rather than retrying them. See [Handlers & Routing](Handlers-and-Routing.md#unknown-urn-strategies). +- Make handlers **idempotent** — at-least-once delivery means a handler can run + again for a message that actually succeeded but whose ack was lost. diff --git a/docs/Testing.md b/docs/Testing.md new file mode 100644 index 0000000..18ea0f5 --- /dev/null +++ b/docs/Testing.md @@ -0,0 +1,95 @@ +# Testing + +Because the runtime is built from small, injected parts, you can test handlers and +workers without standing up a real broker. + +## Test a handler directly + +A handler is a plain object — call `handle()` with a `ReceivedMessage` you build +from an envelope: + +```php +use BabelQueue\Codec\EnvelopeCodec; +use InitPHP\Queue\Message\ReceivedMessage; + +$envelope = EnvelopeCodec::make('urn:babel:users:registered', ['user_id' => 42], 'emails'); +$message = new ReceivedMessage('emails', EnvelopeCodec::encode($envelope), $envelope, receipt: 1); + +$handler = new SendWelcomeEmail(); +$handler->handle($message); // assert the side effects +``` + +`ReceivedMessage` implements `BabelQueue\Contracts\InboundMessage`, so it is +exactly what the handler sees in production. + +## Test routing and outcomes with the `Dispatcher` + +The dispatcher returns an `Outcome` you can assert on, with no broker involved: + +```php +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\OutcomeKind; +use InitPHP\Queue\Routing\HandlerMap; + +$handlers = (new HandlerMap())->register('urn:babel:users:registered', new SendWelcomeEmail()); +$outcome = (new Dispatcher($handlers))->dispatch($message); + +self::assertSame(OutcomeKind::Ack, $outcome->kind); +``` + +`OutcomeKind` is `Ack`, `Retry`, `DeadLetter`, `Drop` or `Release`; the `Outcome` +also exposes `->reason` and `->exception`. + +## Test the worker with an in-memory transport + +Drive a real `Worker` against a fake `ConsumerTransport`. A minimal in-memory +implementation is enough — it queues payloads, hands them out on `reserve()`, and +records `deadLetter()`/`release()` for assertions: + +```php +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\Worker; +use InitPHP\Queue\Consumer\WorkerOptions; + +$worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(stopWhenEmpty: true)); + +$transport->publish(EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:users:registered', [], 'emails')), 'emails'); + +$worker->run('emails'); // drains and returns (stopWhenEmpty) +self::assertSame(1, $worker->processedCount()); +``` + +Two options make worker tests deterministic: + +- **`stopWhenEmpty: true`** — `run()` returns the moment the queue is empty, so a + test never blocks. +- **`runOnce($queue)`** — process exactly one message and return; ideal for + step-by-step assertions of the retry → dead-letter progression. + +```php +// maxAttempts: 2 — fail twice, then dead-letter: +$worker->runOnce('orders'); // attempt 1 -> re-queued +$worker->runOnce('orders'); // attempt 2 -> dead-lettered +``` + +## Asserting retries and dead-letters + +Because the worker re-queues a failed message with an incremented `attempts`, a +fake transport that records `release()`/`deadLetter()` payloads lets you assert the +whole policy: the delays passed to `release()`, the final `attempts`, and the +`dead_letter.reason` in the annotated envelope. + +## Integration tests against a real broker + +The package's own integration tests connect to real Redis, RabbitMQ and MySQL and +are **skipped unless** the matching environment variables are set, so they are a +no-op locally and run in CI with service containers: + +| Variable | Example | +| -------- | ------- | +| `QUEUE_TEST_REDIS_DSN` | `tcp://127.0.0.1:6379` | +| `QUEUE_TEST_AMQP_HOST` (+ `_PORT`/`_USER`/`_PASS`) | `127.0.0.1` | +| `QUEUE_TEST_MYSQL_DSN` (+ `_USER`/`_PASS`) | `mysql:host=127.0.0.1;port=3306;dbname=queue_test` | + +Adopt the same pattern in your own suite when you want to exercise a real broker: +gate the test on an env var and skip otherwise. diff --git a/docs/The-Message-Envelope.md b/docs/The-Message-Envelope.md new file mode 100644 index 0000000..47534de --- /dev/null +++ b/docs/The-Message-Envelope.md @@ -0,0 +1,132 @@ +# The Message Envelope + +InitPHP Queue does not invent its own message format — it produces and consumes +the **canonical BabelQueue envelope** defined by `babelqueue/php-sdk`. That shared +format is what lets a message be read by a consumer in any language. + +## The shape + +Every message on the wire is this JSON (`schema_version` 1): + +```json +{ + "job": "urn:babel:users:registered", + "trace_id": "7b3f9c2a-e41d-4f88-9b2a-1c0d5e6f7a8b", + "data": { "user_id": 42 }, + "meta": { + "id": "f1e2d3c4-b5a6-4789-90ab-cdef01234567", + "queue": "emails", + "lang": "php", + "schema_version": 1, + "created_at": 1749132727000 + }, + "attempts": 0 +} +``` + +| Field | Meaning | +| ----- | ------- | +| `job` | The message **URN** — its language-independent identity. Consumers also accept the inbound alias `urn`. | +| `trace_id` | A cross-service correlation id, preserved unchanged across every hop and language. | +| `data` | The business payload. Pure JSON only — no PHP objects, closures or resources. | +| `meta.id` | A unique message id (UUID v4). | +| `meta.queue` | The logical queue name. | +| `meta.lang` | The producing language (`php` here; `go`, `python`, … from other SDKs). | +| `meta.schema_version` | Frozen at 1; a consumer refuses versions it does not understand. | +| `attempts` | A transport-level retry counter, incremented by the worker on each failure. | + +You rarely build this by hand — `Producer` and `EnvelopeCodec` do it. The codec is +the SDK's `BabelQueue\Codec\EnvelopeCodec`: + +```php +use BabelQueue\Codec\EnvelopeCodec; + +$envelope = EnvelopeCodec::make('urn:babel:users:registered', ['user_id' => 42], 'emails'); +$json = EnvelopeCodec::encode($envelope); // UTF-8 JSON string +$back = EnvelopeCodec::decode($json); // array, or [] if malformed +$urn = EnvelopeCodec::urn($back); // 'urn:babel:users:registered' +$ok = EnvelopeCodec::accepts($back); // bool: passes consumer validation? +``` + +## Reading a consumed message + +Inside a handler you receive a read-only `BabelQueue\Contracts\InboundMessage`: + +```php +$message->getUrn(); // 'urn:babel:users:registered' +$message->getTraceId(); // correlation id, or '' if absent +$message->getData(); // the 'data' block as an array +$message->getMeta(); // the 'meta' block as an array +``` + +The worker's own `ReceivedMessage` (which implements `InboundMessage`) adds +`queue()`, `rawBody()`, `envelope()`, `attempts()` and `receipt()` — but a handler +only ever sees the read-only view above. + +## URNs: naming your messages + +A URN is a stable, application-controlled string identifying *what a message is*. +Because it is never a PHP class name, the producing class can be renamed, moved or +refactored without breaking any consumer, and a consumer in another language can +route on it without sharing a type. + +Recommended (not enforced) convention: + +``` +urn:babel:: +``` + +Examples: + +``` +urn:babel:orders:created +urn:babel:orders:invoice.requested +urn:babel:users:registered +urn:babel:catalog:item.indexed +``` + +Guidelines: + +- **Keep it stable.** A URN is a contract; treat a change like an API break. +- **One URN per message type.** Routing maps a URN to exactly one handler. +- **Lowercase, dot-separated** for the event part; descriptive over short. + +## Validation (consume side) + +Before dispatching, the worker validates every envelope through +`BabelQueue\Validation\EnvelopeValidator`. `check()` returns `null` when the +envelope is acceptable, or a machine-readable reason otherwise: + +| Reason constant | Meaning | +| --------------- | ------- | +| `REASON_MISSING_URN` | No `job`/`urn` — the message has no identity. | +| `REASON_MISSING_META` | No `meta` block. | +| `REASON_UNSUPPORTED_SCHEMA_VERSION` | `meta.schema_version` is not understood. | +| `REASON_INVALID_DATA` | `data` is not an object. | +| `REASON_MISSING_TRACE_ID` | No `trace_id`. | +| `REASON_INVALID_ATTEMPTS` | `attempts` is not an integer. | + +A message that fails validation is **quarantined** (dead-lettered), never silently +dropped — so a newer producer's messages are never lost. See +[Retries & Dead-Letters](Retries-and-Dead-Letters.md). + +## The `dead_letter` block + +When a message is dead-lettered, the worker adds an **additive** `dead_letter` +block via `BabelQueue\DeadLetter\DeadLetter::annotate()`, preserving the original +`trace_id`, `meta.id` and `data`: + +```json +"dead_letter": { + "reason": "failed", + "error": "Payment gateway timeout", + "exception": "App\\Exceptions\\GatewayTimeout", + "failed_at": 1749132730000, + "original_queue": "orders", + "attempts": 3, + "lang": "php" +} +``` + +Because it is additive, the envelope stays at `schema_version` 1 and consumers of +normal queues ignore it. diff --git a/docs/The-Worker.md b/docs/The-Worker.md new file mode 100644 index 0000000..f178dea --- /dev/null +++ b/docs/The-Worker.md @@ -0,0 +1,173 @@ +# The Worker + +The `InitPHP\Queue\Consumer\Worker` is the consume loop. It reserves a message +from a transport, asks the `Dispatcher` what to do with it, and performs the +resulting broker action — acknowledge, retry with back-off, or dead-letter. + +## Constructing a worker + +```php +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\Worker; +use InitPHP\Queue\Consumer\WorkerOptions; + +$worker = new Worker( + $transport, // a ConsumerTransport (PDO / Redis / AMQP) + new Dispatcher($handlers), // routing + new WorkerOptions(maxAttempts: 3), // tuning (optional; defaults shown below) + $logger, // optional callable for observability +); +``` + +## Running it + +```php +$worker->run('emails'); // loop until a stop signal or a configured limit +$worker->runOnce('emails'); // process at most one message; returns bool +$worker->stop(); // request a graceful stop (e.g. from a handler) +$worker->processedCount(); // messages processed so far (int) +``` + +- **`run()`** is resilient: a transport error on a single iteration is logged and + the loop continues after a short sleep, rather than crashing the worker. +- **`runOnce()`** does **not** swallow errors — it is the strict entry point for + tests and one-shot draining. It returns `true` if a message was processed, + `false` if the queue was empty. + +## `WorkerOptions` + +Every knob, with its default: + +```php +new WorkerOptions( + maxAttempts: 3, // total delivery attempts before dead-lettering (>= 1) + backoff: [0], // per-attempt delay in seconds; the last value repeats + reserveTimeout: 5.0, // seconds a blocking transport waits for a message + sleepWhenEmpty: 0.5, // seconds to sleep when the queue is empty + maxJobs: 0, // stop after N messages (0 = unlimited) + maxRuntime: 0.0, // stop after N seconds (0 = unlimited) + memoryLimitMb: 0, // stop once memory reaches N MB (0 = unlimited) + stopWhenEmpty: false, // stop as soon as the queue drains (drain/batch mode) +); +``` + +`WorkerOptions` is immutable and validates its input: `maxAttempts < 1`, a +negative back-off, or a negative limit throws `ConfigurationException`. + +### Reservation and idling + +- **Blocking transports** (Redis `BLMOVE`) wait up to `reserveTimeout` for a + message before returning. +- **Polling transports** (PDO, RabbitMQ `basic_get`) return immediately when the + queue is empty; the worker then sleeps for `sleepWhenEmpty`. Tune that for your + latency/load trade-off. + +### Stopping cleanly + +Set one or more limits and run each worker under a supervisor that restarts it: + +```php +new WorkerOptions(maxJobs: 1000, memoryLimitMb: 128); +``` + +This is the standard pattern for long-running PHP — the process exits on its own +terms and a fresh one starts with clean memory. `stopWhenEmpty: true` instead +drains the queue and returns (useful for batch jobs and tests). + +### Graceful shutdown + +On platforms with `ext-pcntl` the worker installs `SIGINT`/`SIGTERM` handlers and +stops **after finishing the in-flight message**, so a deploy or `Ctrl-C` never +tears a job in half. Without `ext-pcntl` the loop still stops on a limit or +`stop()`, just not on a signal. + +## Retries and back-off + +When a handler throws, the worker increments the envelope's `attempts` and +re-queues it with a delay from `backoff`: + +- `delayForAttempt(n)` uses `backoff[min(n - 1, last index)]`. +- `[0]` retries immediately; `[1, 5, 15]` waits 1s, then 5s, then 15s, then 15s for + every further attempt. + +Once `attempts` reaches `maxAttempts`, the message is annotated and dead-lettered. +With `maxAttempts: 3, backoff: [1, 5, 15]`: + +| Delivery | `attempts` seen | On failure | +| -------- | --------------- | ---------- | +| 1st | 0 | re-queued with `attempts` 1, after 1s | +| 2nd | 1 | re-queued with `attempts` 2, after 5s | +| 3rd | 2 | dead-lettered with `attempts` 3 | + +> Back-off delays are honoured natively by the PDO and Redis transports. RabbitMQ +> applies retries immediately unless the delayed-message-exchange plugin is +> configured — see [Transport: RabbitMQ](Transport-RabbitMQ.md). + +Full details on [Retries & Dead-Letters](Retries-and-Dead-Letters.md). + +## Observability + +Pass a callable as the fourth constructor argument to receive lifecycle events, +invoked as `($level, $event, $context)`: + +```php +$worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(), function ( + string $level, // 'info' | 'notice' | 'warning' | 'error' + string $event, // see below + array $context, // ['queue' => ..., 'urn' => ..., 'trace_id' => ..., ...] +): void { + $myPsrLogger->log($level, $event, $context); +}); +``` + +| Event | When | +| ----- | ---- | +| `job.ack` | A handler succeeded. | +| `job.retry` | A failure was re-queued (context has `attempt`, `delay`). | +| `job.dead_letter` | A message was quarantined (context has `reason`, `attempts`, `error`). | +| `job.dropped` | An unknown URN was acked-and-discarded (`DELETE` strategy). | +| `job.released` | An unknown URN was put back (`RELEASE` strategy). | +| `reserve.failed` | The transport threw while reserving (loop continues). | +| `process.failed` | The transport threw while acting on a message (loop continues). | + +## The CLI + +`vendor/bin/queue work` loads a **bootstrap file** that returns a configured +`Worker`: + +```bash +php vendor/bin/queue work --bootstrap=worker.php --queue=emails # loop +php vendor/bin/queue work --bootstrap=worker.php --queue=emails --once # one message +``` + +| Option | Meaning | +| ------ | ------- | +| `--bootstrap` | A PHP file that wires and `return`s a `Worker`. Required. | +| `--queue` | The queue to consume (default: `default`). | +| `--once` | Process at most one message, then exit. | + +The bootstrap keeps credentials and the handler map in your application code, not +on the command line: + +```php +// worker.php +require __DIR__ . '/vendor/autoload.php'; + +use InitPHP\Queue\Consumer\{Dispatcher, Worker, WorkerOptions}; +use InitPHP\Queue\Routing\HandlerMap; +use InitPHP\Queue\Transport\Redis\RedisTransport; + +$transport = new RedisTransport(new Predis\Client('tcp://127.0.0.1:6379')); +$handlers = (new HandlerMap())->register('urn:babel:users:registered', SendWelcomeEmail::class); + +return new Worker($transport, new Dispatcher($handlers), new WorkerOptions(maxAttempts: 3, maxJobs: 1000)); +``` + +### Running under systemd (example) + +```ini +[Service] +ExecStart=/usr/bin/php /srv/app/vendor/bin/queue work --bootstrap=/srv/app/worker.php --queue=emails +Restart=always +# The worker exits after maxJobs; systemd restarts it with clean memory. +``` diff --git a/docs/transports/pdo.md b/docs/Transport-PDO.md similarity index 70% rename from docs/transports/pdo.md rename to docs/Transport-PDO.md index b3307c3..2fa0c56 100644 --- a/docs/transports/pdo.md +++ b/docs/Transport-PDO.md @@ -1,10 +1,12 @@ -# PDO (database) transport +# Transport: PDO (Database) `InitPHP\Queue\Transport\Pdo\PdoTransport` is a database-backed transport — the one the core SDK does not ship. It needs no broker process: jobs live in two tables. It is the simplest way to add a durable queue to an app that already has a database, and it works on **MySQL** and **SQLite**. +## Construction + ```php use InitPHP\Queue\Transport\Pdo\PdoTransport; @@ -19,19 +21,19 @@ $transport = new PdoTransport( ); ``` -PHP 8 puts PDO in exception error mode by default; keep it that way so failures +PHP 8 puts PDO in exception error mode by default — keep it that way so failures surface instead of being swallowed. ## Tables -For development and tests, let the transport create the tables: +For development and tests, let the transport create the tables (idempotent): ```php -$transport->createSchema(); // CREATE TABLE IF NOT EXISTS … (idempotent) +$transport->createSchema(); ``` In production you usually own your migrations. The DDL below is what -`createSchema()` produces on MySQL — create it through your migration tool: +`createSchema()` produces on MySQL: ```sql CREATE TABLE IF NOT EXISTS jobs ( @@ -60,10 +62,13 @@ CREATE TABLE IF NOT EXISTS jobs_failed ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ``` +> On SQLite the reservation index is created as a separate `CREATE INDEX` +> statement; the column types are otherwise the same. + ### Columns -The full envelope is stored as JSON in `payload`; `queue`, `urn`, `trace_id` and -`attempts` are denormalised into columns only for indexing and inspection. +The full envelope is stored as JSON in `payload`; the other columns are +denormalised from it for indexing and inspection. | Column | Purpose | | ------ | ------- | @@ -77,16 +82,16 @@ The full envelope is stored as JSON in `payload`; `queue`, `urn`, `trace_id` and | `created_at` | Insert time. | > The table name is validated as a bare SQL identifier (letters, digits, -> underscores) to keep it safe to interpolate; anything else raises a -> `ConfigurationException`. +> underscores); anything else raises `ConfigurationException`. This keeps it safe +> to interpolate into the queries. ## How reservation works -`reserve()` uses a **portable optimistic claim** that is correct on MySQL and -SQLite alike, without `SELECT … FOR UPDATE SKIP LOCKED`: +`reserve()` uses a **portable optimistic claim**, correct on MySQL and SQLite +alike, without `SELECT … FOR UPDATE SKIP LOCKED`: -1. `SELECT` the oldest row for the queue that is ready - (`available_at <= now` and not currently reserved). +1. `SELECT` the oldest ready row for the queue (`available_at <= now`, not + currently reserved). 2. `UPDATE … SET reserved_at = now WHERE id = ? AND (reserved_at IS NULL OR reserved_at <= :stale)`. 3. If exactly one row was affected, the claim succeeded; otherwise another worker won it, so try the next row. @@ -97,28 +102,27 @@ This guarantees two workers never run the same job. A row reserved by a worker that then crashes would otherwise be stuck forever. Any reservation older than `retryAfter` seconds (default 90) is treated as abandoned -and becomes reservable again — so no message is lost. Set it comfortably above -your slowest handler's runtime. +and becomes reservable again, so no message is lost. Set it comfortably above your +slowest handler's runtime. -## Lifecycle, in SQL terms +## Lifecycle in SQL terms | Operation | Effect | | --------- | ------ | -| `publish()` | `INSERT` a ready row; returns the new row id. | -| `reserve()` | The optimistic claim above. | +| `publish()` | `INSERT` a ready row; returns the new row id as a string. | +| `reserve()` | The optimistic claim above; returns a `ReceivedMessage` or `null`. | | `ack()` | `DELETE` the row. | | `release()` | `UPDATE` the row with the new payload/attempts and `available_at = now + delay`, clearing `reserved_at`. | | `deadLetter()` | In one transaction: `INSERT` into the failed table, then `DELETE` the row. | ## Operational notes -- **Polling.** PDO reservation is a poll: when the queue is empty, `reserve()` - returns immediately and the worker sleeps for `WorkerOptions::$sleepWhenEmpty`. - Tune that for your latency/load trade-off. +- **Polling.** Reservation is a poll: on an empty queue `reserve()` returns + immediately and the worker sleeps for `WorkerOptions::$sleepWhenEmpty`. - **Indexing.** The `(queue, available_at, reserved_at)` index keeps reservation - fast as the table grows; keep it. + fast as the table grows — keep it. - **Housekeeping.** `ack()` deletes rows, so the main table stays small. Prune the `*_failed` table on your own schedule once messages are reviewed or replayed. -See [Dead-letter handling](../dead-letter.md) for inspecting and replaying failed -rows. +See [Retries & Dead-Letters](Retries-and-Dead-Letters.md) for inspecting and +replaying failed rows. diff --git a/docs/transports/amqp.md b/docs/Transport-RabbitMQ.md similarity index 84% rename from docs/transports/amqp.md rename to docs/Transport-RabbitMQ.md index 9b1ba35..4b13d10 100644 --- a/docs/transports/amqp.md +++ b/docs/Transport-RabbitMQ.md @@ -1,12 +1,14 @@ -# RabbitMQ (AMQP) transport +# Transport: RabbitMQ (AMQP) `InitPHP\Queue\Transport\Amqp\AmqpTransport` runs the queue on RabbitMQ. Publishing reuses the SDK's `BabelQueue\Transport\AmqpTransport` (durable queue, persistent message, the contract AMQP properties and headers); consuming adds a pull-based loop. -Requires [`php-amqplib/php-amqplib`](https://packagist.org/packages/php-amqplib/php-amqplib) -(and `ext-sockets`). +**Requires** [`php-amqplib/php-amqplib`](https://packagist.org/packages/php-amqplib/php-amqplib) +and `ext-sockets`. + +## Construction ```php use InitPHP\Queue\Transport\Amqp\AmqpTransport; @@ -22,7 +24,7 @@ $transport = new AmqpTransport( ); ``` -Close the connection and channel when your producer or worker shuts down. +Close the channel and connection when your producer or worker shuts down. ## Wire mapping @@ -48,7 +50,7 @@ auto_delete=false`); the body is the canonical envelope JSON. | Operation | AMQP action | | --------- | ----------- | | `publish()` | Declare the queue, `basic_publish` the persistent envelope. | -| `reserve()` | Declare the queue, then `basic_get` one message (pull). Returns `null` when the queue is empty. | +| `reserve()` | Declare the queue, then `basic_get` one message (pull). Returns `null` when empty. | | `ack()` | `basic_ack` on the delivery tag. | | `release()` | `basic_ack` the original, then **republish** the updated envelope. | | `deadLetter()` | `basic_ack` the original, then publish the annotated envelope to `.failed`. | @@ -68,8 +70,8 @@ and dead-letter annotations accurate across redeliveries. delay is not applied on RabbitMQ** — retries are republished immediately — because native delayed delivery requires the [delayed-message-exchange plugin](https://github.com/rabbitmq/rabbitmq-delayed-message-exchange). -If you need back-off windows on RabbitMQ, install that plugin and route the failed -exchange accordingly, or use the PDO/Redis transport where delays are honoured +If you need back-off windows, install that plugin, or use the +[PDO](Transport-PDO.md)/[Redis](Transport-Redis.md) transport where delays are honoured natively. ## Operational notes @@ -81,5 +83,5 @@ natively. - **Connections are not thread-safe.** Use one connection/channel per worker process. -See [The worker & retries](../worker-and-retries.md) and -[Dead-letter handling](../dead-letter.md) for the policy that drives these calls. +See [The Worker](The-Worker.md) and [Retries & Dead-Letters](Retries-and-Dead-Letters.md) +for the policy that drives these calls. diff --git a/docs/transports/redis.md b/docs/Transport-Redis.md similarity index 61% rename from docs/transports/redis.md rename to docs/Transport-Redis.md index fbd1b77..6b273ca 100644 --- a/docs/transports/redis.md +++ b/docs/Transport-Redis.md @@ -1,22 +1,24 @@ -# Redis transport +# Transport: Redis `InitPHP\Queue\Transport\Redis\RedisTransport` runs a durable, reliable queue on Redis. Publishing reuses the SDK's `BabelQueue\Transport\RedisTransport` (`RPUSH`), so the wire convention every BabelQueue SDK shares is never duplicated; consuming adds the reliable-queue mechanics. -Requires **Redis 6.2+** (for `BLMOVE`) and the pure-PHP +**Requires Redis 6.2+** (for `BLMOVE`) and the pure-PHP [`predis/predis`](https://packagist.org/packages/predis/predis) client. +## Construction + ```php use InitPHP\Queue\Transport\Redis\RedisTransport; $transport = new RedisTransport( - client: new Predis\Client('tcp://127.0.0.1:6379'), - defaultQueue: 'default', - processingSuffix:':processing', - failedSuffix: ':failed', - delayedSuffix: ':delayed', + client: new Predis\Client('tcp://127.0.0.1:6379'), + defaultQueue: 'default', + processingSuffix: ':processing', + failedSuffix: ':failed', + delayedSuffix: ':delayed', ); ``` @@ -40,7 +42,7 @@ atomically pops the head of the ready list and pushes it onto the processing lis blocking up to `timeout` seconds. Because the message sits on `orders:processing` until acknowledged, a worker crash leaves it recoverable rather than lost. -The blocking timeout has a 1-second floor so the loop returns periodically to +The blocking timeout has a 1-second floor, so the loop returns periodically to observe a stop signal instead of blocking forever on an empty queue. ### Ack @@ -55,7 +57,7 @@ observe a stop signal instead of blocking forever on an empty queue. - delay `> 0` → `ZADD orders:delayed `. On every `reserve()`, due members of `orders:delayed` (score `<= now`) are migrated -back onto the ready list — each one re-enqueued only by the worker that wins its +back onto the ready list — each re-enqueued only by the worker that wins its `ZREM`, so a delayed retry is never duplicated across workers. ### Dead-letter @@ -66,20 +68,22 @@ onto `orders:failed`. ## Delivery semantics At-least-once. A crashed worker leaves its in-flight message on -`orders:processing`; the [visibility/reclaim] story here is simpler than PDO's — -recover such messages with a small reaper that moves long-idle -`orders:processing` entries back to `orders` if you run workers that can die -mid-job. For most deployments the graceful `SIGTERM` shutdown (finish the in-flight -message, then exit) avoids stranding messages. +`orders:processing`. The graceful `SIGTERM` shutdown (finish the in-flight message, +then exit) avoids stranding messages in normal operation; if you run workers that +can be killed mid-job, add a small reaper that moves long-idle +`orders:processing` entries back onto `orders`. ## Using phpredis instead The consume side is written against `Predis\ClientInterface`. If you use the -`ext-redis` (phpredis) extension, wrap it in a thin adapter exposing the same -`blmove` / `rpush` / `lrem` / `zadd` / `zrangebyscore` / `zrem` methods, or use -`predis/predis` (pure PHP, no extension needed). For **publish-only** producers, -the one-method SDK `Transport` is just an `RPUSH` and is trivial to implement over -phpredis directly. - -See [The worker & retries](../worker-and-retries.md) for back-off configuration -and [Dead-letter handling](../dead-letter.md) for the failed list. +`ext-redis` (phpredis) extension, either: + +- install `predis/predis` (pure PHP, no extension needed — the supported path), or +- wrap phpredis in a thin adapter exposing the same `blmove` / `rpush` / `lrem` / + `zadd` / `zrangebyscore` / `zrem` methods. + +For **publish-only** producers, the SDK's one-method `Transport` is just an +`RPUSH` and is trivial to implement over phpredis directly. + +See [The Worker](The-Worker.md) for back-off configuration and +[Retries & Dead-Letters](Retries-and-Dead-Letters.md) for the failed list. diff --git a/docs/Transports.md b/docs/Transports.md new file mode 100644 index 0000000..fd50a9b --- /dev/null +++ b/docs/Transports.md @@ -0,0 +1,60 @@ +# Transports — Overview + +A **transport** is a binding to one broker. Every bundled transport implements +**both** sides of the contract, so a single object both produces and consumes: + +- **Publish** — `BabelQueue\Contracts\Transport::publish(string $payload, ?string $queue)` +- **Consume** — `InitPHP\Queue\Contracts\ConsumerTransport`: + - `reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage` + - `ack(ReceivedMessage $message): void` + - `release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void` + - `deadLetter(ReceivedMessage $message, string $payload): void` + +## Choosing one + +| | [PDO (Database)](Transport-PDO.md) | [Redis](Transport-Redis.md) | [RabbitMQ](Transport-RabbitMQ.md) | +| --- | --- | --- | --- | +| Extra infrastructure | none (reuse your DB) | a Redis server | a RabbitMQ broker | +| Client | `ext-pdo` | `predis/predis` | `php-amqplib/php-amqplib` | +| Throughput | modest | high | high | +| Native delayed retries | ✅ | ✅ | ⚠️ needs a plugin | +| Inspect/replay failures | SQL on `*_failed` table | `LRANGE :failed` | consume `.failed` | +| Best when | you already have a database and want zero new infra | you want speed and already run Redis | you want a real message broker / routing | + +All three are wire-compatible with every BabelQueue SDK, so the choice is +operational — a Go service can produce to RabbitMQ while your PHP worker consumes, +and so on. + +## Swapping transports + +Only the construction changes; producer, dispatcher, worker and handlers are +identical: + +```php +use InitPHP\Queue\Transport\Pdo\PdoTransport; +use InitPHP\Queue\Transport\Redis\RedisTransport; +use InitPHP\Queue\Transport\Amqp\AmqpTransport; + +$transport = new PdoTransport(new PDO('mysql:host=127.0.0.1;dbname=app', 'u', 'p')); +// or +$transport = new RedisTransport(new Predis\Client('tcp://127.0.0.1:6379')); +// or +$transport = new AmqpTransport((new PhpAmqpLib\Connection\AMQPStreamConnection('127.0.0.1', 5672, 'guest', 'guest'))->channel()); + +$producer = new InitPHP\Queue\Producer\Producer($transport, 'emails'); +$worker = new InitPHP\Queue\Consumer\Worker($transport, $dispatcher, $options); +``` + +## Writing your own transport + +To support another broker, implement the SDK `Transport` (publish) and this +package's `ConsumerTransport` (consume). The contract is small — reserve a message +exclusively, ack it, release it for retry (with an optional delay), and move it to +a dead-letter destination. Use the bundled transports as a reference; the [Redis +one](Transport-Redis.md) is the most compact. + +## Reference + +- [PDO (Database) transport](Transport-PDO.md) +- [Redis transport](Transport-Redis.md) +- [RabbitMQ (AMQP) transport](Transport-RabbitMQ.md) diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md new file mode 100644 index 0000000..32ffc3a --- /dev/null +++ b/docs/Troubleshooting.md @@ -0,0 +1,91 @@ +# Troubleshooting + +Common problems and how to resolve them. + +## Messages are published but the worker never processes them + +- **Wrong queue name.** The worker consumes the queue you pass to `run($queue)`; + the producer publishes to its `defaultQueue` (or the `$queue` argument). They + must match. +- **No handler mapped.** With the default `UnknownUrnStrategy::FAIL`, an unmapped + URN is retried and eventually dead-lettered — check the dead-letter destination + and confirm the URN you registered matches the URN you produced exactly. +- **A blocking reserve.** On Redis the worker blocks up to `reserveTimeout`; that + is normal. Confirm the message is actually on the list (`LLEN `). + +## A message keeps getting retried / lands in the dead-letter queue + +- The handler is **throwing**. Inspect the `dead_letter.error` and + `dead_letter.exception` in the annotated envelope. +- Lower `maxAttempts` for non-transient failures so they stop looping; raise it + (with a longer `backoff`) for transient ones. See + [Retries & Dead-Letters](Retries-and-Dead-Letters.md). + +## `ConfigurationException` on startup + +Raised for mistakes detectable before any message flows: + +| Message contains | Cause | +| ---------------- | ----- | +| "empty URN" | `HandlerMap::register('')` or an empty-URN job. | +| "Unknown unknown-URN strategy" | A bad string passed to `Dispatcher`. Use a `UnknownUrnStrategy::*` constant. | +| "is not a class that exists" / "must implement" | A handler class name that is missing or not a `Handler`. | +| "not a valid SQL identifier" | A `PdoTransport` table name with illegal characters. | +| "maxAttempts must be at least 1" / "must be zero or positive" | An out-of-range `WorkerOptions` value. | + +## The worker exits immediately + +You probably set `stopWhenEmpty: true` (it returns as soon as the queue drains) or +a `maxJobs`/`maxRuntime`/`memoryLimitMb` limit that was already reached. For a +long-running worker, leave `stopWhenEmpty` false and set limits sized for a +supervised restart. + +## `SIGINT`/`SIGTERM` does not stop the worker gracefully + +Graceful shutdown needs **`ext-pcntl`**. Without it the worker still stops on a +limit or a programmatic `stop()`, but not on a signal. Install/enable `ext-pcntl`, +or rely on a `maxJobs` limit plus supervisor restart. + +## Redis: `BLMOVE` errors or "unknown command" + +`RedisTransport` requires **Redis 6.2+** (when `BLMOVE` was added). Upgrade the +server, or use the [PDO](Transport-PDO.md) transport. + +## RabbitMQ: `composer install` fails on platform requirements + +`php-amqplib/php-amqplib` requires **`ext-sockets`** and **`ext-mbstring`**. Enable +them in the PHP that runs Composer and the worker. + +## RabbitMQ: retries fire immediately, ignoring `backoff` + +This is expected — native delayed delivery needs the +[delayed-message-exchange plugin](https://github.com/rabbitmq/rabbitmq-delayed-message-exchange). +Install it, or use the [PDO](Transport-PDO.md)/[Redis](Transport-Redis.md) transport for +native delays. See [Transport: RabbitMQ](Transport-RabbitMQ.md#delay-caveat). + +## RabbitMQ: `guest` user is refused + +By default RabbitMQ's `guest` account can only connect from `localhost`. From a +container or remote host, create a dedicated user (e.g. via `RABBITMQ_DEFAULT_USER` +/ `RABBITMQ_DEFAULT_PASS`) and connect with that instead. + +## PDO: two workers seem to grab the same job + +They cannot — reservation is an atomic optimistic claim (a conditional `UPDATE` +whose affected-row count confirms the claim). If you see duplicate **processing**, +the cause is at-least-once redelivery (a reservation that lapsed after +`retryAfter`), which is expected — make handlers idempotent. Raise `retryAfter` +above your slowest handler's runtime if jobs are being reclaimed mid-flight. + +## A message produced by another language is rejected + +- Check `meta.schema_version` — a version newer than this SDK understands is + quarantined (`unsupported_schema_version`), by design. +- The runtime accepts both `job` and the `urn` alias; other fields must still form + a valid envelope (`data` an object, an integer `attempts`, a non-empty + `trace_id`). See [The Message Envelope](The-Message-Envelope.md#validation-consume-side). + +## Still stuck? + +Open an issue at with the failing +envelope (redact secrets), the transport, and the worker options you used. diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..f2ef625 --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,2 @@ +--- +**InitPHP Queue** · [GitHub](https://github.com/InitPHP/Queue) · [Packagist](https://packagist.org/packages/initphp/queue) · [BabelQueue standard](https://babelqueue.com) · MIT License diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..5f1642b --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,31 @@ +### [Home](Home.md) + +**Getting Started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) +- [Core Concepts](Core-Concepts.md) + +**Messages** +- [The Message Envelope](The-Message-Envelope.md) +- [Producing Messages](Producing-Messages.md) + +**Consuming** +- [Handlers & Routing](Handlers-and-Routing.md) +- [The Worker](The-Worker.md) +- [Retries & Dead-Letters](Retries-and-Dead-Letters.md) + +**Transports** +- [Overview](Transports.md) +- [PDO (Database)](Transport-PDO.md) +- [Redis](Transport-Redis.md) +- [RabbitMQ (AMQP)](Transport-RabbitMQ.md) + +**Guides** +- [Interoperability](Interoperability.md) +- [Testing](Testing.md) +- [API Reference](API-Reference.md) + +**Other** +- [Migration from 1.x](Migration-from-1.x.md) +- [FAQ](FAQ.md) +- [Troubleshooting](Troubleshooting.md) diff --git a/docs/dead-letter.md b/docs/dead-letter.md deleted file mode 100644 index 781c570..0000000 --- a/docs/dead-letter.md +++ /dev/null @@ -1,91 +0,0 @@ -# Dead-letter handling - -A message is **dead-lettered** when it cannot be processed and should be set aside -for inspection rather than retried forever or silently lost. - -## When it happens - -| Cause | Trigger | -| ----- | ------- | -| Exhausted retries | A handler kept throwing until `attempts` reached `WorkerOptions::$maxAttempts`. Reason: `failed`. | -| Poison / malformed | The envelope failed consumer-side validation (missing URN, non-object `data`, bad `attempts`). Reason: one of the `EnvelopeValidator::REASON_*` values. | -| Unsupported schema | `meta.schema_version` is newer than this SDK understands — quarantined, **never dropped**, so a newer producer's messages are not lost. Reason: `unsupported_schema_version`. | -| Unknown URN | No handler is mapped and the strategy is `DEAD_LETTER` (or `FAIL` after retries). Reason: `unknown_urn`. | - -## The `dead_letter` block - -Before moving the message, the worker annotates the original envelope with an -additive `dead_letter` block (via the SDK's `BabelQueue\DeadLetter\DeadLetter`). -The original `trace_id`, `meta.id` and `data` are preserved verbatim: - -```json -{ - "job": "urn:babel:orders:created", - "trace_id": "7b3f9c2a-...", - "data": { "order_id": 1042 }, - "meta": { "id": "f1e2...", "queue": "orders", "lang": "php", "schema_version": 1, "created_at": 1749132727000 }, - "attempts": 3, - "dead_letter": { - "reason": "failed", - "error": "Payment gateway timeout", - "exception": "App\\Exceptions\\GatewayTimeout", - "failed_at": 1749132730000, - "original_queue": "orders", - "attempts": 3, - "lang": "php" - } -} -``` - -Because the block is additive, the envelope stays at `schema_version` 1 and any -consumer that does not care about it simply ignores it. - -## Where it goes - -Each transport has its own dead-letter destination, derived from the queue name: - -| Transport | Dead-letter destination | -| --------- | ----------------------- | -| PDO | The `*_failed` table (e.g. `jobs_failed`), one row per dead-lettered message with `reason`, `urn`, `attempts` and the full annotated `payload`. | -| Redis | A `:failed` list (e.g. `orders:failed`). | -| RabbitMQ | A durable `.failed` queue (e.g. `orders.failed`). | - -## Inspecting and replaying - -**PDO** — query the failed table directly: - -```sql -SELECT id, urn, attempts, reason, failed_at, payload -FROM jobs_failed -ORDER BY id DESC; -``` - -To replay, decode the stored `payload`, strip the `dead_letter` block and reset -`attempts` to 0, then publish it again: - -```php -use BabelQueue\Codec\EnvelopeCodec; - -$envelope = EnvelopeCodec::decode($payloadFromFailedRow); -unset($envelope['dead_letter']); -$envelope['attempts'] = 0; - -$transport->publish(EnvelopeCodec::encode($envelope), $envelope['meta']['queue']); -``` - -**Redis** — read with `LRANGE orders:failed 0 -1`; replay by `RPUSH`-ing a cleaned -envelope back onto the main list. - -**RabbitMQ** — consume the `orders.failed` queue (the same `AmqpTransport`, -pointed at the failed queue name) and republish. - -## Tuning what gets dead-lettered - -- Raise `maxAttempts` (and lengthen `backoff`) for transient failures like a flaky - downstream service. -- Keep `maxAttempts` low for failures that will never succeed on retry (bad input), - so they reach the dead-letter queue quickly. -- Use `UnknownUrnStrategy::DEAD_LETTER` if you want unmapped messages quarantined - for review rather than retried. - -See [The worker & retries](worker-and-retries.md) for the retry policy itself. diff --git a/docs/envelope-and-urns.md b/docs/envelope-and-urns.md deleted file mode 100644 index 794b78f..0000000 --- a/docs/envelope-and-urns.md +++ /dev/null @@ -1,116 +0,0 @@ -# Envelope & URNs - -InitPHP Queue does not invent its own message format — it produces and consumes -the **canonical BabelQueue envelope** defined by `babelqueue/php-sdk`. That is -what makes a message readable by a consumer written in any language. - -## The envelope - -Every message on the wire is this JSON shape (`schema_version` 1): - -```json -{ - "job": "urn:babel:users:registered", - "trace_id": "7b3f9c2a-e41d-4f88-9b2a-1c0d5e6f7a8b", - "data": { "user_id": 42 }, - "meta": { - "id": "f1e2d3c4-b5a6-4789-90ab-cdef01234567", - "queue": "emails", - "lang": "php", - "schema_version": 1, - "created_at": 1749132727000 - }, - "attempts": 0 -} -``` - -| Field | Meaning | -| ----- | ------- | -| `job` | The message **URN** — its language-independent identity. Consumers also accept the inbound alias `urn`. | -| `trace_id` | A cross-service correlation id, preserved unchanged across every hop and language. | -| `data` | The business payload. Pure JSON only — no PHP objects, closures or resources. | -| `meta.id` | A unique message id. | -| `meta.queue` | The logical queue name. | -| `meta.lang` | The producer's language (`php` here). | -| `meta.schema_version` | Frozen at 1; a consumer refuses versions it does not understand. | -| `attempts` | A transport-level retry counter, incremented by the worker on each failure. | - -You rarely build this by hand — the `Producer` and `EnvelopeCodec` do it for you. -The codec is the SDK's `BabelQueue\Codec\EnvelopeCodec`: - -```php -use BabelQueue\Codec\EnvelopeCodec; - -$envelope = EnvelopeCodec::make('urn:babel:users:registered', ['user_id' => 42], 'emails'); -$json = EnvelopeCodec::encode($envelope); // UTF-8 JSON string -$back = EnvelopeCodec::decode($json); // array, or [] if malformed -$urn = EnvelopeCodec::urn($back); // 'urn:babel:users:registered' -``` - -## URNs: how to name messages - -A URN is a stable, application-controlled string that identifies *what a message -is*. Because it is never a PHP class name, the producing class can be renamed, -moved or refactored without breaking any consumer, and a consumer in another -language can route on it without sharing any type. - -The recommended (not enforced) convention is: - -``` -urn:babel:: -``` - -Examples: - -``` -urn:babel:orders:created -urn:babel:orders:invoice.requested -urn:babel:users:registered -urn:babel:catalog:item.indexed -``` - -Rules of thumb: - -- **Keep it stable.** A URN is a contract. Once consumers depend on it, treat a - change like an API break. -- **One URN per message type.** Routing maps a URN to exactly one handler. -- **Make it descriptive, lowercase, dot-separated** for the event part. - -## Producing from a job object - -Instead of a raw URN + array, you can implement `BabelQueue\Contracts\PolyglotJob` -and let the producer read the URN and payload from it: - -```php -use BabelQueue\Contracts\PolyglotJob; - -final class UserRegistered implements PolyglotJob -{ - public function __construct(private readonly int $userId) {} - - public function getBabelUrn(): string - { - return 'urn:babel:users:registered'; - } - - public function toPayload(): array - { - return ['user_id' => $this->userId]; - } -} - -$producer->dispatch(new UserRegistered(42), 'emails'); -``` - -To continue an existing distributed trace (e.g. a downstream job dispatched while -handling another message), additionally implement `BabelQueue\Contracts\HasTraceId` -and return the inherited `trace_id` from `getBabelTraceId()`; the codec reuses it -instead of minting a new one. - -## Validation - -On the consume side, the worker validates every envelope through -`BabelQueue\Validation\EnvelopeValidator` before dispatching. A message that is -malformed, missing its URN, or carries an unsupported `schema_version` is -**quarantined** (dead-lettered), never silently dropped. See -[Dead-letter handling](dead-letter.md). diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index 8b91e89..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,136 +0,0 @@ -# Getting started - -This guide takes you from an empty project to a producer pushing messages and a -worker consuming them. - -## Install - -```bash -composer require initphp/queue -``` - -Then add the client for the broker you want to use: - -```bash -composer require predis/predis # Redis 6.2+ -# or -composer require php-amqplib/php-amqplib # RabbitMQ -# or nothing extra — the PDO transport only needs ext-pdo -``` - -## The three moving parts - -| Part | Class | Role | -| ---- | ----- | ---- | -| Transport | `InitPHP\Queue\Transport\*` | Publishes and consumes against a broker. | -| Routing | `InitPHP\Queue\Routing\HandlerMap` + `InitPHP\Queue\Consumer\Dispatcher` | Maps a message URN to a handler. | -| Worker | `InitPHP\Queue\Consumer\Worker` | The consume loop with retry/dead-letter policy. | - -## 1. Write a handler - -A handler implements `InitPHP\Queue\Contracts\Handler`. It receives a read-only -`BabelQueue\Contracts\InboundMessage`. **Return** to acknowledge the message; -**throw** to fail it (the worker will retry, then dead-letter). - -```php -use BabelQueue\Contracts\InboundMessage; -use InitPHP\Queue\Contracts\Handler; - -final class SendWelcomeEmail implements Handler -{ - public function handle(InboundMessage $message): void - { - $data = $message->getData(); // ['user_id' => 42, 'email' => '...'] - $traceId = $message->getTraceId(); // correlate with the producer's trace - $meta = $message->getMeta(); // ['id' => ..., 'queue' => ..., 'lang' => ...] - - // Do the work. An exception here marks the message as failed. - mailer()->sendWelcome($data['email']); - } -} -``` - -> Delivery is **at-least-once**: a handler may run more than once for the same -> message (after a worker crash, for example), so make it idempotent. - -## 2. Choose a transport - -```php -use InitPHP\Queue\Transport\Redis\RedisTransport; - -$transport = new RedisTransport(new Predis\Client('tcp://127.0.0.1:6379')); -``` - -See [PDO](transports/pdo.md), [Redis](transports/redis.md) and -[RabbitMQ](transports/amqp.md) for the other options. The PDO transport also needs -its tables — call `$transport->createSchema()` once (or run the DDL yourself). - -## 3. Produce messages - -```php -use InitPHP\Queue\Producer\Producer; - -$producer = new Producer($transport, defaultQueue: 'emails'); - -$producer->send('urn:babel:users:registered', [ - 'user_id' => 42, - 'email' => 'jane@example.com', -]); -``` - -`send()` encodes the canonical envelope and publishes it. The return value is the -transport's message id when it exposes one (the DB row id for PDO), or `null`. - -## 4. Consume messages - -Map URNs to handlers, wrap them in a `Dispatcher`, and run a `Worker`. - -```php -use InitPHP\Queue\Consumer\Dispatcher; -use InitPHP\Queue\Consumer\Worker; -use InitPHP\Queue\Consumer\WorkerOptions; -use InitPHP\Queue\Routing\HandlerMap; - -$handlers = (new HandlerMap()) - ->register('urn:babel:users:registered', SendWelcomeEmail::class); - -$worker = new Worker( - $transport, - new Dispatcher($handlers), - new WorkerOptions(maxAttempts: 3, backoff: [1, 5, 15]), -); - -$worker->run('emails'); // blocks, processing messages until stopped -``` - -## 5. Run it as a process - -The bundled CLI loads a **bootstrap file** that returns a configured `Worker`: - -```php -// worker.php -require __DIR__ . '/vendor/autoload.php'; - -use InitPHP\Queue\Consumer\{Dispatcher, Worker, WorkerOptions}; -use InitPHP\Queue\Routing\HandlerMap; -use InitPHP\Queue\Transport\Redis\RedisTransport; - -$transport = new RedisTransport(new Predis\Client('tcp://127.0.0.1:6379')); -$handlers = (new HandlerMap())->register('urn:babel:users:registered', SendWelcomeEmail::class); - -return new Worker($transport, new Dispatcher($handlers), new WorkerOptions(maxAttempts: 3)); -``` - -```bash -php bin/queue work --bootstrap=worker.php --queue=emails -``` - -Run it under a process supervisor (systemd, supervisord, a container restart -policy) and set a `maxJobs`/`memoryLimitMb` limit so each worker exits and is -restarted periodically — the standard way to bound memory in long-running PHP. - -## Next steps - -- [Handlers & routing](handlers-and-routing.md) — closures, container resolution, unknown URNs. -- [The worker & retries](worker-and-retries.md) — every `WorkerOptions` knob. -- [Interoperability](interoperability.md) — consume a message produced by Go/Python. diff --git a/docs/handlers-and-routing.md b/docs/handlers-and-routing.md deleted file mode 100644 index f9edd95..0000000 --- a/docs/handlers-and-routing.md +++ /dev/null @@ -1,120 +0,0 @@ -# Handlers & routing - -A consumed message is routed to a **handler** by its **URN**. This guide covers -writing handlers, registering them, and what happens when a URN has no handler. - -## The `Handler` contract - -```php -namespace InitPHP\Queue\Contracts; - -use BabelQueue\Contracts\InboundMessage; - -interface Handler -{ - public function handle(InboundMessage $message): void; -} -``` - -- **Return** to acknowledge — the worker removes the message. -- **Throw** to fail — the worker retries with back-off, then dead-letters. - -The `InboundMessage` is a read-only view of the envelope: - -```php -$message->getUrn(); // 'urn:babel:users:registered' -$message->getTraceId(); // correlation id, or '' if absent -$message->getData(); // the 'data' block as an array -$message->getMeta(); // the 'meta' block as an array -``` - -## Registering handlers with `HandlerMap` - -`HandlerMap` is the bundled URN → handler registry. A handler may be registered -three ways: - -```php -use InitPHP\Queue\Routing\HandlerMap; - -$handlers = new HandlerMap(); - -// 1. A class name (lazily instantiated, must have a no-arg constructor): -$handlers->register('urn:babel:users:registered', SendWelcomeEmail::class); - -// 2. A ready-built instance (use this to inject dependencies yourself): -$handlers->register('urn:babel:orders:created', new RecordOrder($database)); - -// 3. A closure, for small inline handlers: -$handlers->register('urn:babel:audit:logged', function (InboundMessage $m): void { - error_log('audit: ' . $m->getUrn()); -}); -``` - -`register()` returns `$this`, so calls chain. Re-registering a URN replaces the -previous entry. `has(string $urn): bool` reports whether a URN is mapped. - -A class name that does not exist, or that does not implement `Handler`, raises an -`InitPHP\Queue\Exceptions\ConfigurationException` the first time it is resolved — -a configuration bug you fix in code, never a runtime failure that gets retried. - -## Resolving handlers from a container - -If your handlers need constructor injection, back the routing with your own -PSR-11 container by implementing `HandlerResolver` instead of using `HandlerMap`: - -```php -use InitPHP\Queue\Contracts\Handler; -use InitPHP\Queue\Contracts\HandlerResolver; -use Psr\Container\ContainerInterface; - -final class ContainerHandlerResolver implements HandlerResolver -{ - /** @param array> $map URN => handler class */ - public function __construct( - private readonly ContainerInterface $container, - private readonly array $map, - ) {} - - public function resolve(string $urn): ?Handler - { - $class = $this->map[$urn] ?? null; - - return $class !== null ? $this->container->get($class) : null; - } -} -``` - -Pass any `HandlerResolver` to the `Dispatcher`. - -## The `Dispatcher` - -The dispatcher decodes/validates a message, resolves its handler, runs it, and -returns an `Outcome` the worker acts on: - -```php -use BabelQueue\Routing\UnknownUrnStrategy; -use InitPHP\Queue\Consumer\Dispatcher; - -$dispatcher = new Dispatcher($handlers, UnknownUrnStrategy::FAIL); -``` - -You normally never call the dispatcher yourself — you hand it to a `Worker`. - -## Unknown-URN strategies - -When a message's URN has no mapped handler, the dispatcher applies the strategy -passed to its constructor — the four canonical BabelQueue options: - -| Strategy | Constant | Behaviour | -| -------- | -------- | --------- | -| Fail | `UnknownUrnStrategy::FAIL` *(default)* | Treat as a failure: retry, then dead-letter. Safest while a fleet is mid-deploy and a consumer hasn't learned the URN yet. | -| Delete | `UnknownUrnStrategy::DELETE` | Acknowledge and silently discard. | -| Release | `UnknownUrnStrategy::RELEASE` | Put it back on the queue verbatim for another worker/version. | -| Dead-letter | `UnknownUrnStrategy::DEAD_LETTER` | Quarantine immediately, then acknowledge. | - -```php -new Dispatcher($handlers, UnknownUrnStrategy::DEAD_LETTER); -``` - -Whatever the strategy for *unknown* URNs, a **malformed or unsupported-schema** -envelope is always dead-lettered — see [Dead-letter handling](dead-letter.md). diff --git a/docs/migrating-from-v1.md b/docs/migrating-from-v1.md deleted file mode 100644 index fe99967..0000000 --- a/docs/migrating-from-v1.md +++ /dev/null @@ -1,107 +0,0 @@ -# Migrating from 1.x - -`2.0` is a breaking rewrite. `1.x` was a self-contained, **PHP-only** queue that -serialised the producing class name into the message (`{"jobClass": "App\\Jobs\\MailJob", …}`) -and did `new $jobClass(...)` on the other end. `2.0` is the framework-less runtime -for the **polyglot BabelQueue envelope**, routing on a stable URN instead — so the -same queue is readable by Go, Python, Node and any other BabelQueue SDK, and -renaming a class no longer orphans messages already on the queue. - -## Requirements - -| | 1.x | 2.0 | -| --- | --- | --- | -| PHP | `>= 7.4` | `^8.2` | -| Core dependency | none | `babelqueue/php-sdk ^1.0` | - -## What was removed - -The entire `1.x` surface is gone: - -- `InitPHP\Queue\Job` (abstract base) and `InitPHP\Queue\Interfaces\JobInterface` -- `InitPHP\Queue\Interfaces\AdapterInterface` -- `InitPHP\Queue\Adapters\PDOAdapter` and `RabbitMQAdapter` -- `InitPHP\Queue\Exceptions\JobException`, `JobInvalidArgumentException` - -## Concept mapping - -| 1.x | 2.0 | -| --- | --- | -| `class MailJob extends Job { handle(): bool }` | A class implementing `InitPHP\Queue\Contracts\Handler` — `handle(InboundMessage $message): void` | -| The job class **is** the routing identity | A stable **URN** (`urn:babel:mail:requested`) is the identity; the handler class is free to change | -| `$job->push(['to' => ...])` | `$producer->send('urn:babel:mail:requested', ['to' => ...])` | -| `$adapter->handle($channel, $queue)` | `$worker->run($queue)` | -| `protected string $channel` / `$queue` | The queue name passed to the producer/worker | -| `new PDOAdapter($pdo, 'queue')` | `new PdoTransport($pdo, 'jobs')` | -| `new RabbitMQAdapter($host, $port, $user, $pass)` | `new AmqpTransport((new AMQPStreamConnection(...))->channel())` | -| `ack()` / `nack()` called inside the job | The worker acks on success and applies the retry/dead-letter policy on failure | -| Return `true`/`false` from `handle()` | **Return** to ack; **throw** to fail | - -## Porting a job - -**1.x:** - -```php -use InitPHP\Queue\Job; - -class MailJob extends Job -{ - protected string $channel = 'mailChannel'; - protected string $queue = 'mailQueue'; - - public function handle(): bool - { - $p = $this->getPayload(); - return mail($p['to'], $p['subject']); - } -} - -// produce -$job = new MailJob($adapter); -$job->push(['to' => 'a@b.c', 'subject' => 'Hi']); - -// consume -$adapter->handle('mailChannel', 'mailQueue'); -``` - -**2.0:** - -```php -use BabelQueue\Contracts\InboundMessage; -use InitPHP\Queue\Contracts\Handler; - -final class SendMail implements Handler -{ - public function handle(InboundMessage $message): void - { - $p = $message->getData(); - if (! mail($p['to'], $p['subject'])) { - throw new \RuntimeException('mail() failed'); // -> retried, then dead-lettered - } - } -} - -// produce -$producer->send('urn:babel:mail:requested', ['to' => 'a@b.c', 'subject' => 'Hi'], 'mail'); - -// consume -$handlers = (new HandlerMap())->register('urn:babel:mail:requested', SendMail::class); -(new Worker($transport, new Dispatcher($handlers), new WorkerOptions()))->run('mail'); -``` - -## Database (PDO) schema changed - -`1.x` stored a column per field and moved failed rows with a column-position -`INSERT … SELECT *`. `2.0` stores the full envelope as JSON and uses a portable, -abandonment-safe reservation. The old `queue` / `queue_failed` tables are not -compatible — create the new `jobs` / `jobs_failed` tables (see -[the PDO transport guide](transports/pdo.md)). Drain the old queue with a `1.x` -worker before switching, or write a one-off script that reads old rows and -re-publishes them through a `2.0` `Producer`. - -## In-flight messages - -Because the wire format changed (class name → URN envelope), `1.x` and `2.0` -messages are not interchangeable on the same queue. Drain `1.x` queues with the -old code before deploying `2.0`, or migrate them with a short script that maps the -old `jobClass`/`payload` to a URN + `data` and re-publishes via the new `Producer`. diff --git a/docs/worker-and-retries.md b/docs/worker-and-retries.md deleted file mode 100644 index b4ae566..0000000 --- a/docs/worker-and-retries.md +++ /dev/null @@ -1,126 +0,0 @@ -# The worker & retries - -The `Worker` is the consume loop. It reserves a message from a transport, asks the -`Dispatcher` what to do with it, and performs the resulting broker action — -acknowledge, retry with back-off, or dead-letter. - -## Constructing a worker - -```php -use InitPHP\Queue\Consumer\Dispatcher; -use InitPHP\Queue\Consumer\Worker; -use InitPHP\Queue\Consumer\WorkerOptions; - -$worker = new Worker( - $transport, // a ConsumerTransport (PDO / Redis / AMQP) - new Dispatcher($handlers), // routing - new WorkerOptions(maxAttempts: 3),// tuning (optional) - $logger, // optional callable (see below) -); -``` - -## Running it - -```php -$worker->run('emails'); // loop until a stop signal or a configured limit -$worker->runOnce('emails'); // process at most one message; returns bool -$worker->stop(); // request a graceful stop (e.g. from a handler) -$worker->processedCount(); // messages processed so far -``` - -`run()` is resilient: a transport error on a single iteration is logged and the -loop continues after a short sleep, instead of crashing the worker. `runOnce()` -does **not** swallow errors — it is the strict entry point for tests and one-shot -draining. - -## `WorkerOptions` - -Every knob, with its default: - -```php -new WorkerOptions( - maxAttempts: 3, // total delivery attempts before dead-lettering (>= 1) - backoff: [0], // per-attempt delay in seconds; last value repeats - reserveTimeout: 5.0, // seconds a blocking transport waits for a message - sleepWhenEmpty: 0.5, // seconds to sleep when the queue is empty - maxJobs: 0, // stop after N messages (0 = unlimited) - maxRuntime: 0.0, // stop after N seconds (0 = unlimited) - memoryLimitMb: 0, // stop once memory reaches N MB (0 = unlimited) - stopWhenEmpty: false, // stop as soon as the queue drains (drain/batch mode) -); -``` - -### Retries and back-off - -When a handler throws, the worker increments the envelope's `attempts` and -re-queues it with a delay from `backoff`: - -- `delayForAttempt(n)` uses `backoff[min(n - 1, last index)]`. -- `[0]` retries immediately; `[1, 5, 15]` waits 1s, then 5s, then 15s, then 15s for - every further attempt. - -Once `attempts` reaches `maxAttempts`, the message is annotated with a -`dead_letter` block and moved to the dead-letter destination. With -`maxAttempts: 3` and `backoff: [1, 5, 15]`: - -| Delivery | On failure | -| -------- | ---------- | -| 1st (`attempts` 0) | re-queued with `attempts` 1, after 1s | -| 2nd (`attempts` 1) | re-queued with `attempts` 2, after 5s | -| 3rd (`attempts` 2) | dead-lettered with `attempts` 3 | - -> Back-off delays are honoured by the PDO and Redis transports. RabbitMQ applies -> retries immediately unless you configure the delayed-message exchange plugin — -> see [the AMQP transport guide](transports/amqp.md). - -### Stopping cleanly - -Set one or more limits and run each worker under a supervisor that restarts it: - -```php -new WorkerOptions(maxJobs: 1000, memoryLimitMb: 128); -``` - -This is the standard pattern for long-running PHP — the process exits on its own -terms and a fresh one starts with clean memory. - -On platforms with `ext-pcntl` the worker installs `SIGINT`/`SIGTERM` handlers and -stops **after finishing the in-flight message**, so a deploy or `Ctrl-C` never -tears a job in half. - -## Observability - -Pass a callable as the fourth constructor argument to receive lifecycle events. -It is invoked as `($level, $event, $context)`: - -```php -$worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(), function ( - string $level, // 'info' | 'notice' | 'warning' | 'error' - string $event, // 'job.ack' | 'job.retry' | 'job.dead_letter' | ... - array $context, // ['queue' => ..., 'urn' => ..., 'trace_id' => ..., ...] -): void { - $myPsrLogger->log($level, $event, $context); -}); -``` - -Events: `job.ack`, `job.retry`, `job.dead_letter`, `job.dropped`, `job.released`, -`reserve.failed`, `process.failed`. - -## The CLI - -`bin/queue work` loads a bootstrap file that returns a configured `Worker`: - -```bash -php bin/queue work --bootstrap=worker.php --queue=emails # loop -php bin/queue work --bootstrap=worker.php --queue=emails --once # one message -``` - -| Option | Meaning | -| ------ | ------- | -| `--bootstrap` | A PHP file that wires and `return`s a `Worker`. Required. | -| `--queue` | The queue to consume (default: `default`). | -| `--once` | Process at most one message, then exit. | - -The bootstrap pattern keeps credentials and the handler map in your application -code, not on the command line. See [Getting started](getting-started.md#5-run-it-as-a-process) -for a complete `worker.php`.