# Exceptions and dates

> Write a rule with exceptions as positive search keys, and a right that holds during a period with the clock read on the reader side, never on the row side.

## Keys only add rows

A document is found when it shares a key with the reader, and nothing in the filter removes a document that a key found. There is **no negative key**: a rule with an exception, such as a stand-in who sees the posts of the author they stand in for except some sectors or some posts, becomes a positive key.

A `whereNotIn` would not do: a reader sees the union of what each of their perimeters grants, and a global `whereNotIn` would also remove the rows that another perimeter grants. A negation also fails open: a document indexed before its exclusion, or whose exclusion is not reindexed yet, does not carry the excluded value and passes a `NOT IN`. A missing positive key hides the row instead.

### An exception on a dimension of the row

When the exception is on a finite dimension of the row, such as a sector, a category or a status, the reader gets the complement of their exclusions: one key per sector they may see.

```php
StandInPerimeter::new()
    // allowed() and query() with the exclusions, as in SQL
    ->searchKeys(
        name: 'stand_in',
        row: fn (Post $post) => [[$post->author_id, $post->sector_id]],
        reader: fn (User $user) => $user->standingInFor->flatMap(
            fn (StandIn $standIn) => array_map(fn (int $sector): array => [$standIn->principal_id, $sector], $standIn->allowedSectorIds()),
        )->all(),
    ),
```

`standingInFor` stands for the stand-ins the reader holds, and `allowedSectorIds()` for every sector of your application minus the ones the stand-in excludes. Nothing is reindexed when an exclusion changes, since the keys of a reader are computed at each search.

### An exception on specific rows

When the exception is on specific rows, such as a table of excluded posts, each row lists the readers who see it through the perimeter, and the reader has one key, their own id:

```php
StandInPerimeter::new()
    // allowed() and query() with the exclusions, as in SQL
    ->searchKeys(
        name: 'stand_in',
        row: fn (Post $post) => $post->author->standIns
            ->reject(fn (StandIn $standIn) => $standIn->excludes($post))
            ->pluck('stand_in_id')
            ->all(),
        reader: fn (User $user) => $user->id,
        load: ['author.standIns.exclusions'],
    )
    ->reindexWhen(StandIn::class, changed: ['principal_id', 'stand_in_id'], rows: fn (StandIn $standIn) => Post::where('author_id', $standIn->principal_id))
    ->reindexWhen(StandInExclusion::class, changed: ['post_id'], rows: fn (StandInExclusion $exclusion) => Post::whereKey($exclusion->post_id)),
```

A new stand-in reindexes the posts of the author, an exclusion reindexes one post. Until its job has run, the stand-in who excludes the post still finds it: see [the window](/search/keeping-the-keys-fresh#the-window).

When neither form fits, such as an exclusion that depends on the time, keep the model in SQL: search it with the `database` engine or with a controlled query.

### Testing the exceptions

Check the recipe with [`assertSearchAgrees()`](/testing-and-tooling/testing#the-search) on a stand-in and rows that cover each case: rows of an excluded sector, an excluded row, and an excluded row that another perimeter grants, such as a post of a sector that the stand-in also manages. That last row must be found: it proves that the search keeps the union of the perimeters.

## Rights that depend on the date

The keys of a row are computed when it is indexed, the keys of a reader at each search. **Read the clock in reader, never in row.** A row key computed from `now()`, such as the users whose loan of a vehicle is active, stays in the index after the loan ends, and is missing before it starts, until the row is indexed again.

When the period ties the reader to something the row names without a date, such as a loan, an assignment to a site or a delegation from an author, key the row by that thing, and give the reader the ones whose period is active now:

```php
LoanPerimeter::new()
    ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} borrowed vehicles"))
    ->query(fn (Builder $query, User $user) => $query->whereHas('loans', fn (Builder $loans) => $loans
        ->whereBelongsTo($user)
        ->where('starts_at', '<=', now())
        ->where(fn (Builder $end) => $end->whereNull('ends_at')->orWhere('ends_at', '>=', now()))))
    ->searchKeys(
        name: 'loan',
        row: fn (Vehicle $vehicle) => $vehicle->getKey(),
        reader: fn (User $user) => Loan::query()
            ->whereBelongsTo($user)
            ->where('starts_at', '<=', now())
            ->where(fn (Builder $end) => $end->whereNull('ends_at')->orWhere('ends_at', '>=', now()))
            ->pluck('vehicle_id')
            ->all(),
    ),
```

The document carries only the key of the vehicle, neither the user nor the dates, and nothing is reindexed when a period starts or ends. Write the same condition in `query()` and in `reader`, and compare with `now()` from PHP rather than the database's `NOW()`: a database clock in another time zone, or on another server, makes the SQL and the keys disagree.

### What keeps an answer longer

The keys of a reader follow the clock wherever they are computed at each search: `controlled()`, `controlledFor()`, a [guarded search](/search/from-the-browser#through-a-route-of-the-application), laravel-rest-api and `Access::indexReaderKeys()`. Three things keep an answer longer:

- A [browser search token](/search/from-the-browser) keeps the keys of the instant it was issued until it expires. Keep its expiry short.
- laravel-rest-api files a kept decision under the `updated_at` of the row, which the end of a period does not touch: leave the abilities that a period decides out of `authorizationCache()`, or shorten their duration.
- A long-running console command keeps its [decisions](/digging-deeper/decisions) for its whole run. Call `Access::forgetDecisions()` at the start of each unit of work.

### When the period belongs to the row

When the period belongs to the row and many readers share it, such as the publication window of each post, the reader cannot list the rows: keep the model in SQL, with the `database` engine or a controlled query.

A window that only opens, such as an embargo lifted at a date, has a recipe of its own: a scheduled job writes the state into a column when the date passes, `row` and `query()` read that column, and the job reindexes the rows, through the save of the model or a `reindexWhen()` on the model it writes. A job that runs late keeps the rows closed a little longer, never open.

### Testing the periods

Test with [`assertSearchAgrees()`](/testing-and-tooling/testing#the-search) before, during and after each period, and one second on each side of its bounds, with `$this->travelTo()`. The documents do not depend on the clock, so the rows of the test are indexed once. `assertSearchAgrees()` and `assertIndexKeysAgree()` fail when the keys of a row read the clock.
