# `AshHooks.Plug`
[🔗](https://github.com/baselabs/ash_hooks/blob/v3.3.0/lib/ash_hooks/plug.ex#L2)

Optional Plug adapter for the synchronous inbound webhook pipeline.

Resolves a source, captures exact raw request bytes, consults the provider's
optional handshake, checks the method, and calls `AshHooks.Ingress.ingest/4`
once. Every answer is sent and the connection halted. Plug must be installed
by the host; this module is absent when Plug is unavailable.

Configure `AshHooks.BodyReader` on the endpoint's `Plug.Parsers`, then
`forward` a webhook route to this plug from the router, outside
browser/session/CSRF pipelines: with `:source` for a fixed source on a
single-tenant ledger, or with `:resolve` for a scoped or multitenant one. The
README's [Mounting the plug](README.md#mounting-the-plug)
section shows both in a Phoenix endpoint and router; the test suite compiles
and runs those examples as written.

`:resolve` is called with the conn followed by its configured arguments.
It must return `{:ok, %{source: atom}}`, optionally including `:tenant`,
`:scope`, `:connection`, and opaque `:host_context` for ingress, and
`:signature_header`, which
overrides the plug option of that name for the resolved source. Look up stored endpoint records;
never trust a path string as a module or tenant. `{:error, :not_found}`
answers 404 and `{:error, :unavailable}` answers 503, with no ledger write.

Options (validated by `init/1` without resource introspection):

  * `:resource`: required ledger module carrying `AshHooks.InboundDelivery`.
  * Exactly one of `:source` (inbound name atom for a fixed single-tenant
    route) or `:resolve` (`{module, function, args}`).
  * `:request_uri`: `nil` (default, no URI in ctx), a public base URL
    string, or an MFA called with the conn to return the full public URI.
    A base has trailing slashes trimmed and the original request path and
    query appended. The conn's host, scheme and port are never used.
  * `:methods`: uppercase HTTP method strings, default `["POST"]`.
    A provider handshake is consulted before a 405 refusal with `allow`.
  * `:length`: positive total body limit, default 8,000,000 bytes;
    `:read_length`: positive socket read size, default 1,000,000 bytes;
    `:read_timeout`: socket read timeout, default 15,000 milliseconds.
    These apply only to reads made by this plug. Configure preceding
    parsers' limits separately.
  * `:respond`: optional MFA called with the exact ingest outcome,
    returning `{status, headers, body}` or `:default`.
  * `:refuse`: optional MFA called with `:not_found`, `:unavailable`,
    `:method_not_allowed`, `:too_large`, or `:body_consumed`, returning
    `{headers, body}` or `:default`. Status stays fixed. Required `allow`
    and `retry-after` headers win over conflicting host headers.
  * `:retry_after`: positive seconds, default 60, for `retry-after` on
    resolver unavailability and every 503 from `default_response/2`.
  * `:signature_header`: lowercase request header name, default `nil`.
    Its value becomes `ctx.signature` for providers whose
    `signature_source/0` is `:header`, the default for a provider written
    directly against `AshHooks.Provider`. A request with no such header,
    or with more than one line of it, carries no signature and is refused
    as unsigned (400). With `ingress_tracking :on`, ingress may store a
    rejection row.

All MFAs receive their configured arguments after the request/outcome/reason.
Response headers use lowercase names, as required by Plug.

Cached bytes from `AshHooks.BodyReader.raw_body/1` take priority. A host's
own endpoint reader can supply the complete exact bytes through
`AshHooks.BodyReader.put_raw_body/2`, without a second read. Otherwise the
plug reads and accumulates chunks up to `:length` (413 on overflow). An
empty read with a positive declared content-length means a parser consumed
the body without `AshHooks.BodyReader`: answer 500, log the configuration
fix once, and write nothing. Parsed params are never re-encoded.

`AshHooks.Provider.handshake/2` dispatches a provider's optional
`handshake/1` before method and signature checks. A handshake response writes
nothing. After ingest, response precedence is provider `response/1`, then
`:respond`, then `default_response/2`; `:default` falls through each policy.
Those policies do not receive refusals. Custom provider or host 503s own
their headers and are not amended with `:retry_after`.

Configured providers (`use AshHooks.Provider, verify: [...]`) extract their
signature from request headers or the body and need no `:signature_header`.
A provider whose signature source is `:header` reads only `ctx.signature`;
name its header with `:signature_header`, here or from the resolver.
`AshHooks.Ingress.ingest/4` remains available for lower-level composition.

# `default_response`

```elixir
@spec default_response(AshHooks.Provider.ingest_outcome(), keyword()) ::
  AshHooks.Provider.http_response()
```

Maps an ingest outcome to `{status, headers, body}` using validated plug
options returned by `init/1`. A host `:respond` policy may call this function
explicitly with the same options.

Terminal rows (`:processed`, `:failed_permanent`, `:superseded`) get 200;
other successful ledger outcomes get 500 to request a sender retry. Typed
invalid-signature, stale-timestamp and malformed-payload errors get 400.
`UnknownSource` gets 404; `KeyKindMismatch` and `UnknownKey` get 500.
`KeyUnavailable` and unrecognized failures get 503 with `retry-after`
from `options[:retry_after]`.
All default bodies are empty. Custom policies' responses are never amended.

---

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