Current section
Files
Jump to
Current section
Files
usage-rules.md
<!--
SPDX-FileCopyrightText: © 2026 BaseLabs Holdings LLC
SPDX-License-Identifier: MIT
-->
# AshHooks usage rules
Apply these rules when writing or reviewing an AshHooks integration. Use the
[working tutorial](documentation/tutorials/get-started.md) for setup, the
[DSL reference](documentation/dsls/DSL-AshHooks.md) for options and defaults,
and [Compatibility](documentation/topics/support/compatibility.md) for
dependency requirements. Follow [Upgrading](documentation/topics/support/upgrading.md) when migrating.
## Receive the exact bytes
- Configure Ash's `default_string_length_count` before compiling resources.
Use `:codepoints` for new applications.
- Put `AshHooks` and `AshHooks.InboundDelivery` on the ledger. Declare an
explicit `provider` for declaration-based keys. Use `source_record` when an
enrolled source resource selects the provider from its allowlist.
- Configure `AshHooks.BodyReader` on any preceding `Plug.Parsers` or hand the
complete bytes to `AshHooks.BodyReader.put_raw_body/2` from your own reader.
Configure parser size limits separately from the Plug's direct-read limits.
- Mount `AshHooks.Plug` with `resource:` and a non-nil `source:` or an MFA
`resolve:`. Resolve a stored route for scoped or tenanted ledgers and return
`{:ok, %{source: source, tenant: tenant, scope: scope, connection: connection}}`.
Treat path data as a lookup key. Use the stored route's tenant.
- For direct receipt, call `AshHooks.Ingress.ingest/4` before business effects.
Pass ordered headers for configured schemes. Supply the actual method and
configured public URI when the sender signs them. For a provider using
`ctx.signature`, set `signature_header:` on the Plug or its resolver.
- Build provider options from the sender's signing specification. Keep
algorithms, encodings, key sources, and remote authority settings in trusted
configuration. Use a resolver or custodian for key material.
**Correct** Pass the captured body and original header lines.
<!-- not-run: The call needs the host ledger and its original signed request. -->
```elixir
AshHooks.Ingress.ingest(MyApp.WebhookLedger, :orders, raw_body, %{
headers: conn.req_headers,
method: conn.method,
request_uri: public_uri,
tenant: tenant,
scope: %{account_id: account_id}
})
```
**Incorrect** Re-encoding params changes the bytes under verification.
<!-- not-run: This intentionally passes reconstructed bytes in place of the signed body. -->
```elixir
AshHooks.Ingress.ingest(MyApp.WebhookLedger, :orders, Jason.encode!(conn.body_params), %{})
```
## Keep receipt identity and effects stable
- Include every sender scope in `scope_identity` and the database unique index.
Keep the declaration name stable. An explicit `event_id` extractor takes
precedence, with digest fallback for invalid results. A provider identity
callback that returns an invalid ID fails ingestion.
- Map known sender event names to a fixed set of atoms. Return `{:ok, value}`,
`{:error, :retry, reason}`, or `{:error, :permanent, reason}` from the handler.
Make effects idempotent by logical event ID. For ledger retention, schedule
`AshHooks.Ingress.reap/2` for every tenant to recover retryable receipts and
expired claims. Configure sender redelivery for
[receipt-only routes](documentation/how-to/handle-inbound-events.md#keep-only-a-receipt).
- Record `:inserted_at` on ledger-backed routes so the reaper can recover single receipts
stranded before claim. It picks them up after one interval set by
`lease_seconds` in `inbound_delivery`. Without an insertion timestamp,
recovery of those receipts relies on a sender retry.
- Use a signed timestamp or the
[durable replay mode](documentation/how-to/protect-against-replay.md) as the
sender's protocol permits. Ordinary pruning releases a receipt's identity.
- For historical digest identities, review
`AshHooks.Ingress.plan_legacy_identity_adoption/3` before calling
`AshHooks.Ingress.adopt_legacy_identity/3`. Drain ingress and reapers first.
Keep the reviewed scope, tenant, and overrides.
- Use the [HTTP guide](documentation/how-to/receive-http.md) for response
mapping. The Plug calls `handshake/1` only on legacy delivery routes. If
your sender requires a handshake, configure a separate legacy route and
authenticate the handshake under the sender's protocol before answering.
## Persist outbound work before sending
- Declare payload versions as bounded `Ash.TypedStruct` types with exact
examples. Set each `transform` callback with `via: {Module, :function}`.
Construct events with `AshHooks.Event.new/1`, typed `data`, and the
durable fact's UTC `occurred_at`. Keep the type in snake_case segments.
Use `AshHooks.Type.EventType` for host-owned outbound ledger attributes.
- Derive the event ID from the logical event and its revision where needed.
Reuse it on retry. Avoid dots, whitespace, and control characters in IDs.
- Add `AshHooks` to the emitting resource and declare `outbound` with its
subscription and delivery resources. Use `AshHooks.dispatch/4` for immediate
fanout. Supply the generated worker's `enqueue/2` callback when using Oban.
- To publish inside a producer action, use `AshHooks.Changes.Publish` with
`:outbox`, `:declaration`, `:build`, and optional `:route`. Match a known
refusal as `AshHooks.Errors.Invalid.Publication` inside the Ash invalid
error. For explicit publishes use `AshHooks.publish/4` and handle its
`{:ok, :accepted | :duplicate}` or `{:error, reason}` result.
- Drive existing rows with `AshHooks.Delivery.run/2` for queue-free delivery.
Supply the encoded full delivery key and configured resource modules.
Honor `{:snooze, seconds}`. The delivery row owns retry timing and limits.
- Keep stored owner tokens, route names, and endpoint snapshots intact.
Schedule `AshHooks.reconcile_pending/3` per declaration and tenant.
Reuse the enqueue callback and supply a stable `:enqueue_key` for anonymous
callbacks. Make custom enqueue callbacks idempotent.
- Schedule `AshHooks.fanout_pending/3` per tenant for outbox recovery, even
with a trigger. Keep event-log replay separate. Inspect `:created`,
`:re_sent`, `:skipped`, and `:errors` in the replay summary.
## Version outbound declarations and publish their contracts
- Supply the same fact ID in each event when publishing a batch of declaration
and event pairs. Keep the existing declaration on `wire_id :fact`. Choose an
explicit wildcard policy for every derived declaration.
- Enable subscription `version_pinning :on` to store per-type and default pins.
Enqueue from the durable delivery row's bytes and version. Outbox replays of
already admitted rows use the stored message.
- Use `AshHooks.Delivery.enqueue_test/3` for a catalog example or typed
data override in an action transaction. Give it a recoverable enqueue route and
schedule declaration and tenant reconciliation.
- Add the outbound catalog to the host's generated OpenAPI document with
`AshHooks.OpenApi.merge!/2` from its
[`modify_spec/1` callback](documentation/how-to/outbound-contracts.md#export-the-contract).
Pass the OTP app or its domains. Use `AshHooks.OpenApi.json_schema/3` for one
payload version's canonical JSON Schema. Never hand-write webhook schemas.
## Write literal filters and use Ash read policies
- Write literal subscription filter maps and event types. Compute values in
a non-atomic action when they depend on the current row. Avoid the
`{:atomic, value}` form of a bulk query update, which bypasses Ash type checks.
- Use the history list functions, `AshHooks.EndpointHealth.stats/2`,
`AshHooks.Ingress.counts/2`, `AshHooks.OutboundOutbox.list/2`, and
`AshHooks.KeyRegistry.pending/2` through the caller's Ash policy. Pass
`:scope` or explicit `:actor`, `:tenant`, `:context`, and `:tracer` as needed.
Use `authorize?: false` for trusted system reads only when the domain permits it.
- Pass `:action` to select a custom Ash read. Enable keyset pagination on
history actions. Choose an unpaginated action for health statistics.
- Pass a positive `:limit` for history pages. Ash caps it at the action's
`max_page_size`. Pass the opaque `:next_cursor` as `:after` with the same
query.
- Handle `{:error, %Spark.Options.ValidationError{}}` for invalid read
option types. Handle `{:error, :invalid_cursor}` for an undecodable binary
and Ash errors for action resolution or authorization.
**Correct** Keep the reader scope and filters when fetching the next page.
<!-- not-run: This fragment needs a configured delivery resource and an authorized reader scope. -->
```elixir
options = [scope: reader_scope, endpoint_id: endpoint.id, limit: 20]
{:ok, first} = AshHooks.Delivery.list(MyApp.OutboundDelivery, options)
if first.next_cursor do
AshHooks.Delivery.list(
MyApp.OutboundDelivery,
Keyword.put(options, :after, first.next_cursor)
)
end
```
**Incorrect** A cursor is an opaque Ash keyset, with a binary type.
<!-- not-run: This intentionally supplies an invalid cursor type. -->
```elixir
AshHooks.Delivery.list(MyApp.OutboundDelivery, after: 20)
```
## Run key lifecycle writes under Ash policy
- Pass the caller's Ash actor or scope to endpoint and inbound source key
lifecycle calls. Protect the injected owner actions with resource policies.
- Set `before_key_attach` and `after_key_attach` in the owner section.
Use the attachment transaction's repository and tenant for every host
write. Leave external effects until the transaction outcome is known.
- Use the current key reference as the generation fence. Pass `:expected_ref`
when the caller holds a specific reference. Reconcile `CommitUnknown` by
reading owner state before retrying. Follow the
[key custody guide](documentation/how-to/key-custody.md).
## Keep resource and network boundaries explicit
- Use compatible attribute tenancy on every resource touched, including
outboxes, history, inbound sources, and key registries. Use the full primary
key for ledgers. Endpoint and subscription references need one
UUID-compatible key.
- Set the same [payload custody](documentation/how-to/payload-custody.md)
configuration on every ledger used by an outbound declaration. Supply
the configured scope in event metadata and use the ledger retention
helpers to delete references with their rows.
- Define narrow host actions and read policies for payload-bearing resources.
The extension adds machine actions. Reserve them for trusted code.
- Preserve DNS and address checks, TLS identity, body limits, and finite
deadlines in custom transports. Use `AshHooks.Http.Bounded` for HTTPS
certificate pinning. Keep destination validation enabled in production.
- Keep response bodies out of logs. Use bounded, redacted history capture
only when needed. Attach exact event names from `AshHooks.Telemetry`.
- Pass a `DateTime` cutoff as `:older_than` for receipt and delivery pruning
or compaction, and `:before` for key registry pruning. Keep verification
rejection rows under a separate retention policy.
- Use unique names within each declaration kind. Read inbound and outbound
declarations with `AshHooks.Info.webhooks/1`; look up a confirmation policy
through `AshHooks.Info.confirmation_policy/2`.