Repository navigation
Lightrail
Lightrail is blink's event bus. Emit something that happened, and whoever is watching reacts, each on its own terms: right away, after the response has gone out, on a Ticker runner, or collected into a batch and handled once.
Every emission leaves a trail: one dispatch row and one handler row per eligible handler, with status, duration and, on failure, the id of an error report. The trail is what lightrail:dispatch and lightrail:retry work from.
namespace App\Event;
use Blink\Lightrail\Event\BaseEvent;
class InvoicePaid extends BaseEvent {
public function invoiceID(): int {
return (int) ($this -> context["invoice"] ?? 0);
}
}BaseEvent gives you context, the payload, and created. The payload is stored with the dispatch and read back on a runner, so keep it to ids and scalars: a background handler runs in another process, against whatever the row says by then.
For a one-off signal that is not worth a class, Lightrail::emitGeneric(array( ... )) emits a GenericEvent.
use Blink\Lightrail;
Lightrail::emitEvent(new InvoicePaid(array( "invoice" => $invoice -> id )));
Lightrail::emit(InvoicePaid::class, array( "invoice" => $invoice -> id ));emit() returns the results of the handlers that ran immediately, one array per handler.
An observer is a class whose static methods carry #[Observe]. A module lists its observers in observers():
namespace App\Observer;
use App\Event\InvoicePaid;
use Blink\Lightrail\Attribute\Batch;
use Blink\Lightrail\Attribute\Context;
use Blink\Lightrail\Attribute\ExecuteIn;
use Blink\Lightrail\Attribute\Observe;
use Blink\Lightrail\Attribute\Priority;
use Blink\Lightrail\Event\EventBatch;
use Blink\Lightrail\ExecutionMode;
class InvoiceObserver {
#[Observe(InvoicePaid::class)]
#[Priority(100)]
public static function markPaid(InvoicePaid $event): void { ... }
#[Observe(InvoicePaid::class)]
#[ExecuteIn(ExecutionMode::SHUTDOWN)]
public static function notifySales(InvoicePaid $event, Mailer $mailer): void { ... }
#[Observe(InvoicePaid::class)]
#[ExecuteIn(ExecutionMode::BACKGROUND)]
public static function sendReceipt(InvoicePaid $event): void { ... }
#[Observe(InvoicePaid::class)]
#[Context([ "currency" => "EUR" ])]
public static function reportVat(InvoicePaid $event): void { ... }
#[Observe(InvoicePaid::class)]
#[Batch(window: 60, maxSize: 500, dedupe: "context.invoice")]
public static function rebuildLedger(EventBatch $batch): void {
foreach ($batch -> pluck("context.invoice") as $id) { ... }
}
}// AppModule
public function observers(): array {
return array( InvoiceObserver::class );
}Handlers are called through Essence, so they can type-hint services after the event. A method may carry several #[Observe] attributes.
| Attribute | Effect |
|---|---|
#[Observe(Event::class)] |
Marks the method as a handler for that event |
#[Priority(int)] |
Higher runs earlier. Default 0; ties keep declaration order. |
#[Context([ ... ])] |
Runs only when every key matches event -> context, nested arrays included |
#[ExecuteIn(mode)] |
When the handler runs; see below |
#[Batch(...)] |
Buffers events and calls the handler once with the batch |
#[Middleware(...)], #[WithoutMiddleware(...)]
|
Ether handler middleware for this handler only |
| Mode | Runs |
|---|---|
IMMEDIATE |
During emit(), in the emitting process. The default. |
SHUTDOWN |
From the shutdown handler, after the response has gone to the client |
BACKGROUND |
On a Ticker runner, as a DispatchTask queued to CONFIG::$LIGHTRAIL_QUEUE
|
BATCHED |
Implied by #[Batch]; the handler runs once per flush |
A deployment that uses background or batched handlers needs a runner on the Lightrail queue alongside the default one: php core/blink ticker:run lightrail. Both modes resume from the stored dispatch row, so they need CONFIG::$LIGHTRAIL_TRAIL left on.
A high-frequency event can fire hundreds of times in a burst. #[Batch] buffers matching events in lightrail_batched_events and calls the handler once with all of them after a debounce window, so the burst collapses into one call.
| Option | Default | Meaning |
|---|---|---|
window |
60 | Seconds after the first event before the flush. Later events join it. |
maxSize |
500 | Flush early once this many are buffered. 0 disables. |
key |
null | A dot path; events with different values flush separately |
dedupe |
null | A dot path; only the latest event per value is kept |
The handler receives an EventBatch: events(), count(), pluck($path). A failed handler releases its claim and the flush is retried, so batched handlers should be safe to run twice. Order within a batch is not guaranteed. An hourly lightrail:flush --stale sweeps buffers whose flush never came.
For a handler that is not an observer method:
Lightrail::registerListener(InvoicePaid::class, [ Ledger::class, "record" ], priority: 50, executionMode: ExecutionMode::BACKGROUND);The callable must be static, since a background handler is resolved in another process. Listeners registered this way survive a registry rebuild.
Two Ether stages wrap Lightrail. EventMiddleware runs once per emission and can short-circuit the whole event; HandlerMiddleware runs around each handler call, wherever that handler runs. See Ether.
lightrail_dispatch_logs holds one row per emission: event class, payload, mode, counts of pending, completed, succeeded and failed handlers, and a status of pending, running, success, partial or failed. lightrail_handler_logs holds one row per handler attempt: handler, module, execution mode, status (pending, success, failed, skipped), attempt number, duration, error message and the id of the error report filed for a failure.
php core/blink lightrail:listeners # every handler, by event
php core/blink lightrail:dispatch --status=failed
php core/blink lightrail:dispatch 1234 # one dispatch and its handlers
php core/blink lightrail:dispatch 1234 --run # run its pending handlers now
php core/blink lightrail:retry 5678 # retry one failed handler
php core/blink lightrail:retry --all
php core/blink lightrail:flush --list
php core/blink lightrail:purge --days=30 --keep-failed
A retry appends a new handler row pointing at the original through retry_of; the failure stays on record.
Handler discovery reads attributes off every observer class, so the result is cached under DATA_ROOT/caches. The cache version includes the blink and application versions, the module list, and the names and modification times of every observer file, so adding or editing an observer takes effect on the next request without a cache:clear. lightrail:listeners --rebuild forces discovery.