Extensions

Route and write extensions

Add middleware to the routes of every resource, refuse a write with a status of your own, and observe the writes and reads of the endpoints.

Four kinds act on routes, writes and reads: AddsRouteMiddleware, GuardsWrites, ObservesWrites and ObservesReads. See Extensions for registering an extension.

Adding route middleware

AddsRouteMiddleware::routeMiddleware(RouteMiddlewareContext $context) returns middleware for the routes of an endpoint:

Vendor/Plans/PlanRoutesExtension.php
use Lomkit\Rest\Extensions\Contexts\RouteMiddlewareContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\AddsRouteMiddleware;
use Lomkit\Rest\Http\Routing\Endpoint;

final class PlanRoutesExtension extends Extension implements AddsRouteMiddleware
{
    #[\Override]
    public static function name(): string
    {
        return 'plans';
    }

    #[\Override]
    public function routeMiddleware(RouteMiddlewareContext $context): array
    {
        return $context->endpoint === Endpoint::Search ? ['throttle:searches'] : [];
    }
}
  • It receives $context->resource, $context->endpoint, $context->controller and $context->routeName, no user, once per endpoint when the routes register.
  • Its middleware comes after the package, resource and endpoint middleware and before the middleware of an action or a metric, in extension name order, each middleware once. The routes of the actions and metrics of an endpoint get it too.
  • An extension can only add. withoutMiddleware(), withoutMiddlewareFor() and the $withoutMiddleware of an action still remove its middleware.
  • An auth middleware that it adds makes the OpenAPI document list the 401, and rest:check counts the route as authenticated.
  • Use a named limiter, such as throttle:searches: two unnamed throttle middleware count each request twice. Route middleware also runs on Precognition requests.
  • A list item that is not a non-empty string throws Lomkit\Rest\Exceptions\InvalidRouteExtensionException, which names the extension, the resource and the endpoint.
The middleware is written into the routes when they register. Run php artisan route:cache again after you add, remove or change an extension. A test suite with WithCachedRoutes keeps the middleware of its first test: a test that configures other extensions extends a base test case without the trait.

When the routes register, the package builds only the enabled extensions whose class implements this kind or is bound in the container, once for all Rest::resource() calls, and skips the classes of disabled_extensions. The name of any other entry is not read there, so an invalid extension of another kind does not stop the routes, migrations or rest:check: the request that needs it refuses it. An invalid AddsRouteMiddleware class, or a name that two of these classes share, stops the registration. Keep the constructors of route extensions light.

Refusing writes

GuardsWrites::guardWrite(WriteGuardContext $context) can refuse a write:

Vendor/Plans/WriteQuotaExtension.php
use Lomkit\Rest\Extensions\Contexts\WriteGuardContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\GuardsWrites;

final class WriteQuotaExtension extends Extension implements GuardsWrites
{
    public function __construct(private readonly WriteQuota $quota) {}

    #[\Override]
    public static function name(): string
    {
        return 'write_quota';
    }

    #[\Override]
    public function guardWrite(WriteGuardContext $context): void
    {
        if ($this->quota->exhausted($context->user)) {
            $context->refuse('The monthly quota is reached.', 429);
        }
    }
}
429 Too Many Requests
{"message": "The monthly quota is reached."}
  • refuse($message, $status = 403, $headers = []) rolls the transaction back and does not run it again: nothing is written and no write event is dispatched. The client gets {"message": "..."} with the status and the headers, such as $context->refuse('The archive is under maintenance.', 503, ['Retry-After' => '600']).
  • The status is 403, another client error status from 400 to 499, such as 423 or 429, or 503. 409, 422 and 428, which the package answers with another body, and any other status throw Lomkit\Rest\Exceptions\InvalidWriteExtensionException.
  • refuse() throws Lomkit\Rest\Exceptions\WriteRefused. $extension holds the extension name and $reason the text of the client. Its exception message is The [write_quota] extension refused the write.
  • Extensions run in name order, and the first refusal answers.
  • A 403 already matches the documented RestForbidden. Document another status with DocumentsExtension.

The context

PropertyValue
$context->resource, $context->endpoint, $context->userThe resource, the Endpoint and the user, null for a guest, the user of the job in a worker
$context->entriesThe MutationNode list of a mutate that write or link rows of the resource
$context->rowsCopies of the stored rows of the transaction: the rows of the chunk for an action
$context->action, $context->fieldsThe action and its ActionFields

When it runs

It runs at the head of each write transaction, after the entry checks, the row checks and the confirmation:

  • mutate: before mutatingAll(), once for each resource that the request reaches, the resource of the endpoint first, with the entries and stored rows of that resource, the rows that a sync detaches included. An extension that applies only to a related resource refuses a nested write too.
  • destroy, restore and forceDestroy: before destroyingAll() and its twins.
  • An action: at the head of each transaction, each chunk, or each row with ActionTransaction::Row, in the request or in the queued worker; before each chunk of a Whole run, inside its transaction; before each handle() with ActionTransaction::None.
  • Never under Precognition.

The link checks of a row that a mutation creates need its key and run later, so a refusal answers before their 403.

Rules

  • No side effects. A deadlock retry runs the guard again with a new context: it reads and decides, and writes nothing.
  • The rows are copies that the package never saves, but save() on a copy writes it. They can hold columns that the response does not render, such as the columns of fields that NarrowsFields hides: keep them out of what the extension sends elsewhere.
  • The chunks or rows of an action committed before a refusal stay written, and so do the handle() calls that ran before it with ActionTransaction::None. With ActionTransaction::Row, beforeRow() runs before the guard, outside the transaction.
  • A queued action is guarded in the request for each chunk, and its jobs are queued only once every chunk passed: a refusal queues nothing. Each job is guarded again in the worker, where a refusal fails the job without a retry, whatever its $tries. See Queued actions.

Observing writes

ObservesWrites::observeWrite(WriteObservationContext $context) is notified once after the commit of each write transaction:

Vendor/History/WriteHistoryExtension.php
use Lomkit\Rest\Extensions\Contexts\WriteObservationContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\ObservesWrites;

final class WriteHistoryExtension extends Extension implements ObservesWrites
{
    public function __construct(private readonly HistoryStore $history) {}

    #[\Override]
    public static function name(): string
    {
        return 'history';
    }

    #[\Override]
    public function observeWrite(WriteObservationContext $context): void
    {
        $this->history->record($context->resource::class, $context->endpoint->value, $context->user?->getAuthIdentifier(), $context->operations ?? []);
    }
}
EndpointContext
mutateoperations, the operations of the response, and written, a list of Lomkit\Rest\Mutations\WrittenRow (resource, entry, model), once for each resource that the request wrote, with the rows that a sync detaches
destroy, restore, forceDestroyrows
An actionaction, fields, impacted and rows for each committed transaction, in the worker for a queued action
  • It is never notified for an attempt that a deadlock rolled back or for a write that rolls back later in the same transaction.
  • It waits for the commit of a transaction of the application on the connection of the resource. A transaction on another connection does not delay it.
  • When the db.transactions of the container differs from the transactions manager of the connection, as in an Octane application whose warm list leaves it out, the notification is deferred through Connection::afterCommit(), which attaches it to the last pending transaction of that manager, on any connection: a transaction on another connection opened after the transaction of the application can then release or keep it.
  • An exception that it throws is reported with report(), the next extension still runs and the response does not change.
  • The models are copies that the package never saves. A write of the extension runs after the commit, outside the transaction of the package.

Observing reads

ObservesReads::observeRead(ReadObservationContext $context) is notified after an HTTP search, a metric and /details:

Vendor/Plans/ReadUsageExtension.php
use Lomkit\Rest\Extensions\Contexts\ReadObservationContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\ObservesReads;

final class ReadUsageExtension extends Extension implements ObservesReads
{
    public function __construct(private readonly UsageMeter $usage) {}

    #[\Override]
    public static function name(): string
    {
        return 'usage';
    }

    #[\Override]
    public function observeRead(ReadObservationContext $context): void
    {
        $this->usage->add($context->user, $context->endpoint->value, count($context->rows ?? []));
    }
}
EndpointContext
Searchrows, copies of the rows of the page with their includes, total, page and perPage, after searched() and the meta
Metric, computed or read from the cachemetric and result
/detailsdetails, after described()
  • The keys that do not apply are null.
  • Only the HTTP endpoints notify. Rest::search() notifies nothing, through page(), render() or lazy(): the code that calls it observes its own calls.
  • appliesTo() is asked with the resource of the endpoint. The included rows come with the rows of the page and do not notify the extensions of their resources.
  • It runs in the request: keep writes and slow calls out of it. Its exceptions reach the caller.
  • On a search engine page, the rows can hold a row that the RestrictsQueries restrictions would exclude while the index still matches it, since the engine is the proof.