# Extensions

> Add behavior to every resource from one class, registered by an app or a package, with a name, a list of kinds and checks at registration.

An extension adds behavior to every resource of an application from one class: a tenant restriction, field rules per plan, a quota on writes, a line in the meta of each page. The class extends `Lomkit\Rest\Extensions\Extension` and implements one or more kinds, the interfaces of `Lomkit\Rest\Extensions\Kinds`, each of which extends `ExtensionKind`.

```php [app/Rest/Extensions/ArchiveExtension.php]
use Lomkit\Rest\Extensions\Contexts\RestrictionContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\RestrictsQueries;

final class ArchiveExtension extends Extension implements RestrictsQueries
{
    public function __construct(private readonly ArchivePolicy $policy) {}

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

    #[\Override]
    public function appliesTo(string $resource): bool
    {
        return is_subclass_of($resource, ArchivableResource::class);
    }

    #[\Override]
    public function restrict(RestrictionContext $context): void
    {
        if (! $this->policy->showsArchived($context->user)) {
            $context->query->where($context->query->qualifyColumn('archived'), false);
        }
    }
}
```

The methods of the resources stay the path of the application. Extensions apply after them, and their order never changes the result.

## The name

`name()` is the one abstract method of `Extension`. It returns the name of the extension:

- The name is a public contract. It is the meta key (`meta.archive` of searches and `/details`) and the prefix of the instruction keys, response components, cache keys and SQL aliases that the extension adds. A package picks a name specific to it and keeps it for its whole major version.
- A name has 1 to 32 lowercase letters or digits, starts with a letter and joins words with single underscores, such as `acl` or `row_lock`. Two underscores separate it from the keys it prefixes (`acl__locked`), so `acl__x` and `acl_` are refused.
- Return a constant. A `name()` that returns an invalid name, or that throws, is refused with `Lomkit\Rest\Exceptions\InvalidExtensionException`, which names the class and the value or the error.
- A subclass inherits the name. Override it only to run the subclass beside its parent.

## Registering an extension

An application lists its extension classes in `config/rest.php`:

```php [config/rest.php]
'extensions' => [
    App\Rest\Extensions\ArchiveExtension::class,
],
```

A package registers its classes from the `register()` method of a service provider, so they are active on install:

```php
use Lomkit\Rest\Facades\Rest;

public function register(): void
{
    Rest::registerExtension(AccessControlExtension::class);
}
```

`Rest::registerExtensions([AccessControlExtension::class, TenantExtension::class])` registers several classes.

- Extensions are registered by class name. An instance passed to `registerExtension()` is a PHP `TypeError`. An instance, a value that is not a string, or an array that is not a list in `registerExtensions()` throws `InvalidExtensionException`, which shows the list form `[AccessControlExtension::class]`. In the config, a `rest.extensions` or `rest.disabled_extensions` value that is not a list throws `Lomkit\Rest\Exceptions\InvalidConfigException`, and an instance or a value that is not a string in the list throws `InvalidExtensionException` when a context first reads its extensions. Both name the config key.
- A registration checks the class first: it exists, extends `Extension` and is not abstract. It then reads the name. A package author sees the error on install. The classes of the config get the same checks when a context first reads its extensions.
- From `register()`, a registration works in any provider order. From `boot()`, it works only before every provider that declares `Rest::resource()` routes in its own `boot()`.
- Runtime registrations are fixed once the application has booted, or earlier when the package builds its first context or registers its first `Rest::resource()` route. A later registration throws `InvalidExtensionException`, which names the class: never register from a deferred provider or a `booted()` callback.
- The config is read again for each context: a request, a queued action, `Rest::search()`, the OpenAPI document and `rest:check`. A config cached without the `extensions` key reads as no extension.
- One class counts once, registered twice or both registered by a package and listed in the config. Its origin is `config` when `rest.extensions` lists it, else `runtime`.

<tip>

In the tests of a package, register through a provider, `defineEnvironment()` or `#[DefineEnvironment]`, which run before the boot, or with `#[WithConfig('rest.extensions', [...])]`. A registration from a test body throws.

</tip>

## Disabling or replacing an extension

`disabled_extensions` lists the classes to disable, wherever they come from:

```php [config/rest.php]
'disabled_extensions' => [
    Vendor\Acl\AccessControlExtension::class,
],
```

- A disabled class is never built, and its name never collides with another.
- The exact class is compared: a subclass stays enabled when its parent is disabled. A leading backslash or another letter case still designates the same class.
- To replace a package extension, extend it, list the subclass in `extensions` and the package class in `disabled_extensions`. The subclass inherits the name, so its meta and instruction keys stay the same.
- Two enabled classes with one name are refused when a context builds its extensions, with a message that names both classes: `The extensions App\Rest\Extensions\AclExtension and Vendor\Acl\AccessControlExtension share the name [acl]. Add one of them to the [rest.disabled_extensions] config, or extend one of them and override name() to give it another name.` A subclass listed beside its enabled parent is refused the same way.

## How extensions run

- The container builds each extension once per context, at first use, so its constructor can inject services. With no extension, nothing is built.
- Keep settings in properties. For other settings, register a subclass with its own `name()`, or with the parent in `disabled_extensions`.
- Never bind an extension as a singleton: one instance would serve every context of an Octane or queue worker. Bind it with `bind()`, or not at all.
- Building an extension checks its class again: a class that implements no kind, or a binding that builds another class, throws `InvalidExtensionException`.
- `appliesTo(string $resource)` returns `true` by default. Each context asks it once per resource class and keeps the answer, so it may read the resource class and the config, never the user or the request.
- Each kind method receives one context object of `Lomkit\Rest\Extensions\Contexts`. Each kind calls its extensions in name order, so the order of the config never shows.
- An exception thrown by an extension reaches the caller, except from `ObservesWrites`, whose exceptions are reported, and from `ChecksResources`, whose exceptions are problems of `rest:check`.

### Errors

Every error about an extension extends `Lomkit\Rest\Exceptions\ExtensionException`: catch that class for all of them. Each message names the extension by its name and its class, and `concerns($class)` tells whether an error is about that extension class:

```php
use Lomkit\Rest\Exceptions\ExtensionException;
use Lomkit\Rest\Facades\Rest;

try {
    $page = Rest::search(TicketResource::class)->as($user)->payload($search)->page();
} catch (ExtensionException $e) {
    if (! $e->concerns(AccessControlExtension::class)) {
        throw $e;
    }

    // ...
}
```

<table>
<thead>
  <tr>
    <th>
      Exception
    </th>
    
    <th>
      Thrown by
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        InvalidExtensionException
      </code>
    </td>
    
    <td>
      registration, names and building
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidQueryExtensionException
      </code>
    </td>
    
    <td>
      the query kinds
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidEngineExtensionException
      </code>
    </td>
    
    <td>
      the engine kinds
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidAuthorizationExtensionException
      </code>
    </td>
    
    <td>
      the authorization kinds
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidFieldExtensionException
      </code>
    </td>
    
    <td>
      <code>
        NarrowsFields
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidRouteExtensionException
      </code>
    </td>
    
    <td>
      <code>
        AddsRouteMiddleware
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidWriteExtensionException
      </code>
    </td>
    
    <td>
      <code>
        GuardsWrites
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidMetaExtensionException
      </code>
    </td>
    
    <td>
      <code>
        AddsSearchMeta
      </code>
      
       and <code>
        AddsDetailsMeta
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        InvalidDocumentationExtensionException
      </code>
    </td>
    
    <td>
      <code>
        DocumentsExtension
      </code>
    </td>
  </tr>
</tbody>
</table>

## The kinds

<table>
<thead>
  <tr>
    <th>
      Family
    </th>
    
    <th>
      Kind
    </th>
    
    <th>
      What it does
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <a href="/extensions/queries">
        Queries
      </a>
    </td>
    
    <td>
      <code>
        RestrictsQueries
      </code>
    </td>
    
    <td>
      Adds where clauses to the perimeter of a resource, wherever the perimeter applies
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        ProvidesPerimeter
      </code>
    </td>
    
    <td>
      Marks a restriction that is the perimeter, for <code>
        rest:check
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        AugmentsQueries
      </code>
    </td>
    
    <td>
      Adds columns, subqueries and eager loads to the rendered rows, for the policies
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        NarrowsLimits
      </code>
    </td>
    
    <td>
      Narrows the page sizes, the total cap and the include limit for the user, never upward
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        DeclaresInstructions
      </code>
    </td>
    
    <td>
      Adds search instructions, keyed by the extension name
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="/extensions/engines">
        Search engines
      </a>
    </td>
    
    <td>
      <code>
        RestrictsEngineQueries
      </code>
    </td>
    
    <td>
      Restricts each search engine query, AND-ed with the perimeter and the client filters
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        DeclaresIndexAttributes
      </code>
    </td>
    
    <td>
      Declares server-only index attributes, lists of strings included
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        ProvidesEngineProfiles
      </code>
    </td>
    
    <td>
      Provides the profile of a Scout engine
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="/extensions/authorization">
        Authorization
      </a>
    </td>
    
    <td>
      <code>
        PreparesRowChecks
      </code>
    </td>
    
    <td>
      Prepares the data that the policies read, before a batch of row checks
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        VersionsRowChecks
      </code>
    </td>
    
    <td>
      Adds row versions to the key of a kept decision
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        ContributesCacheContext
      </code>
    </td>
    
    <td>
      Adds items to the cache keys of decisions and metric results, shortens or drops kept decisions
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        DeclaresGates
      </code>
    </td>
    
    <td>
      Adds gates to a resource
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        NarrowsFields
      </code>
    </td>
    
    <td>
      Hides fields, or makes them read-only, unfilterable or unsortable, for the user
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="/extensions/routes-and-writes">
        Routes and writes
      </a>
    </td>
    
    <td>
      <code>
        AddsRouteMiddleware
      </code>
    </td>
    
    <td>
      Adds middleware to the routes of an endpoint
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        GuardsWrites
      </code>
    </td>
    
    <td>
      Refuses a write before it runs
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        ObservesWrites
      </code>
    </td>
    
    <td>
      Is notified after the commit of each write
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        ObservesReads
      </code>
    </td>
    
    <td>
      Is notified after each HTTP search, metric and <code>
        /details
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="/extensions/responses-and-checks">
        Responses and checks
      </a>
    </td>
    
    <td>
      <code>
        AddsSearchMeta
      </code>
    </td>
    
    <td>
      Adds keys under <code>
        meta.{name}
      </code>
      
       of a search page
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        AddsDetailsMeta
      </code>
    </td>
    
    <td>
      Adds keys under <code>
        meta.{name}
      </code>
      
       of <code>
        /details
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        DocumentsExtension
      </code>
    </td>
    
    <td>
      Documents the extension in the OpenAPI document
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      <code>
        ChecksResources
      </code>
    </td>
    
    <td>
      Adds checks to <code>
        rest:check
      </code>
    </td>
  </tr>
</tbody>
</table>

## Checking extensions

`php artisan rest:check` lists each extension with its name, class, origin (`config` or `runtime`) and disabled state, and builds each enabled one:

```text
extensions ... 2 extensions built, 1 disabled
Vendor\Notes\NotingExtension ... runtime, disabled
acl ... Vendor\Acl\AccessControlExtension, runtime
quota ... App\Rest\Extensions\QuotaExtension, config
```

- The name of a disabled class is not read.
- It fails on a `rest.extensions` or `rest.disabled_extensions` value that is not a list, on each refused entry, on each pair of classes with one name and on each class that cannot be built, and still lists the others.
- It notes, without failing, a `disabled_extensions` entry that disables nothing: a class neither registered nor configured.
- `--json` adds the `extensions` key: `registered` (`name`, `class`, `origin`, `disabled`), `problems` and `notes`.

See [Extensions in rest:check](/digging-deeper/artisan#extensions) and [Extension checks](/digging-deeper/artisan#extension-checks).
