# `AshHooks.KeyRegistry`
[🔗](https://github.com/baselabs/ash_hooks/blob/v3.3.0/lib/ash_hooks/key_registry.ex#L1)

Tracks opaque webhook keys that must be destroyed, using a host Ash resource.

Use this extension on a resource backed by AshPostgres or AshSqlite, with
the same repository for writes and attribute tenancy as its custody owners.
The host owns migrations, policies and scheduling. References are globally unique
`ahk_` UUIDv7 values, and each occupies one owner slot only.

Schedule `sweep/2` beside the endpoint lifecycle sweep for every tenant.
Issued references time out after `issue_timeout` seconds (900 by default);
configure this longer than the custodian's store timeout. Committed retired
references are destroyed outside transactions using their stored canonical
`custody_tenant`, even when the owner has been deleted.

Owner existence uses the injected `read_custody_owner` action, without the
host primary read's filters, preparations or pagination. The resource's
`base_filter` still applies; a row it hides counts as gone.

Only `:ok` marks a reference destroyed. An unavailable custodian is retried
with exponential backoff capped at one hour. Other answers park the obligation
in `:destroy_failed` with a fixed classification and emit
`[:ash_hooks, :key_registry, :destroy_failed]`, with `count: 1` and metadata
`registry`, `ref`, and `reason`. Backend answers are never stored or emitted.
Raised exceptions, exits and missing custodians park only that reference as
`unclassified`; subsequent references are still swept. Unavailable results
also match the attempt count they read, preserving newer retry state.
Operators inspect `pending/2`, repair the cause, then call `rearm/3`.
`destroy_generation` fences results that were in flight before rearming.
`prune/2` removes destroyed audit rows only; custody tombstones remain in
the custodian for the life of its store.

The extension injects these actions when the host has not supplied them:

* `:read`: primary read with optional keyset pagination.
* `:issue_key`: create accepting `:ref`, `:kind`, `:owner_resource`,
  `:owner_key`, `:state`, `:custody_tenant`, `:issued_at`, `:destroy_after`,
  `:attempts`, `:next_attempt_at`, `:destroy_generation`, `:last_error`,
  `:inserted_at`, and `:updated_at`.
* `:transition_key`: update accepting `:state`, `:owner_resource`,
  `:owner_key`, `:destroy_after`, `:attempts`, `:next_attempt_at`,
  `:destroy_generation`, `:last_error`, and `:updated_at`.
* `:prune_keys`: destroy a registry row.

Host-supplied actions must preserve these contracts. Restrict direct
application access to the machine write actions. Retirement returns
`{:error, :key_not_attached}` if the registry reference is not attached;
the owner write rolls back. Repair the owner/registry inconsistency before
retrying retirement; do not bypass the registry transition.

These functions perform system operations with `authorize?: false`.
Authorize application callers before exposing them.

# `key_registry`
*macro* 

# `pending`

```elixir
@spec pending(module(), keyword()) :: {:ok, [struct()]} | {:error, term()}
```

Lists final destruction failures for the supplied `:tenant`.

# `prune`

```elixir
@spec prune(module(), keyword()) :: {:ok, non_neg_integer()} | {:error, term()}
```

Removes destroyed audit rows older than the required `:before` UTC timestamp.

Accepts `:tenant`. Active, retired and failed obligations are never pruned.
Returns `{:ok, count}`. This does not prune the custodian's tombstones.

# `rearm`

```elixir
@spec rearm(module(), String.t(), keyword()) :: {:ok, struct()} | {:error, term()}
```

Re-arms a failed reference after its cause has been repaired.

Accepts `:tenant`. Increments `destroy_generation`, clears the failure and
retry timing, and resets attempts. Returns `{:error, :not_destroy_failed}`
if another writer already moved the row.

# `sweep`

```elixir
@spec sweep(module(), keyword()) ::
  {:ok,
   %{
     destroyed: non_neg_integer(),
     retired: non_neg_integer(),
     destroy_failed: non_neg_integer()
   }}
  | {:error, term()}
```

Reconciles owners, retires expired issues and destroys eligible references.

Options: `:tenant` and `:now` (UTC clock). Reads use batches of 100 rows.
Each transition commits in its own bounded transaction. Custody destruction
runs outside transactions. Refuses an enclosing transaction with
`{:error, :inside_transaction}`. Returns `{:ok, counts}` including the
current number of `:destroy_failed` rows.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
