Route and write extensions
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:
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->controllerand$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$withoutMiddlewareof an action still remove its middleware. - An
authmiddleware that it adds makes the OpenAPI document list the401, andrest:checkcounts the route as authenticated. - Use a named limiter, such as
throttle:searches: two unnamedthrottlemiddleware 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.
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:
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);
}
}
}
{"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 from400to499, such as423or429, or503.409,422and428, which the package answers with another body, and any other status throwLomkit\Rest\Exceptions\InvalidWriteExtensionException. refuse()throwsLomkit\Rest\Exceptions\WriteRefused.$extensionholds the extension name and$reasonthe text of the client. Its exception message isThe [write_quota] extension refused the write.- Extensions run in name order, and the first refusal answers.
- A
403already matches the documentedRestForbidden. Document another status withDocumentsExtension.
The context
| Property | Value |
|---|---|
$context->resource, $context->endpoint, $context->user | The resource, the Endpoint and the user, null for a guest, the user of the job in a worker |
$context->entries | The MutationNode list of a mutate that write or link rows of the resource |
$context->rows | Copies of the stored rows of the transaction: the rows of the chunk for an action |
$context->action, $context->fields | The 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: beforemutatingAll(), 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 asyncdetaches included. An extension that applies only to a related resource refuses a nested write too.destroy,restoreandforceDestroy: beforedestroyingAll()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 aWholerun, inside its transaction; before eachhandle()withActionTransaction::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 thatNarrowsFieldshides: 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 withActionTransaction::None. WithActionTransaction::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:
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 ?? []);
}
}
| Endpoint | Context |
|---|---|
mutate | operations, 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, forceDestroy | rows |
| An action | action, 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.transactionsof 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 throughConnection::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:
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 ?? []));
}
}
| Endpoint | Context |
|---|---|
| Search | rows, 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 cache | metric and result |
/details | details, after described() |
- The keys that do not apply are
null. - Only the HTTP endpoints notify.
Rest::search()notifies nothing, throughpage(),render()orlazy(): 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
RestrictsQueriesrestrictions would exclude while the index still matches it, since the engine is the proof.
Authorization extensions
Prepare and version row checks, add to the keys of kept decisions, declare gates and narrow the fields of a resource for each user from an extension.
Response and check extensions
Add keys to the meta of search pages and details, document an extension in the OpenAPI document and add checks to rest:check.