# `Alternera.Plugin.Provisional.Source`
[🔗](https://github.com/10e-ab/alternera-sdk/blob/v0.9.0/alternera_plugin_sdk/lib/alternera/plugin/provisional/source.ex#L1)

Provisional: added for consuming queues from a pipeline trigger, and a
change to it needs a changelog line but no new major
(`docs/USER_PLUGINS_DESIGN.md`).

A message source: a queue a plugin can read messages from and settle
them on, for a runner the proxy owns. The proxy opens the source, asks it
for messages when it has room for them, runs a pipeline once per message
and settles each message by how its run ended. The loop, the
concurrency, the backoff and the recording are the proxy's; the broker's
verbs are the plugin's.

A plugin offers one by exporting `source/0`, answering the module that
implements this behaviour (`of/1` finds it). The plugin's step and its
source are separate: a source stands in no pipeline and runs outside any
exchange.

## Settings

A source has settings of its own, described by `source_schema/0` as a
step's are by `settings_schema/0`. `init/2` checks them before the
plugin's `source_init/1` sees them:

  * every key is one the schema names;
  * no text holds a `${…}` reference: there is no exchange to read;
  * a `{{secret.NAME}}` reference stands only in a field declared
    `reveal: true`, as exactly the field's value, for the source to reveal
    with `Alternera.Plugin.Secret.reveal/3`; nothing resolves one
    anywhere else outside an exchange.

`source_init/1` sees the settings twice: as stored, when the proxy checks
a save (tenant variable references `{{NAME}}` still in them, so a check
that needs the value must let a reference through), and with every
`{{NAME}}` outside the `reveal: true` fields replaced, when the proxy
opens the source. It answers the source's opts, plain data.

## The session

`open/2` answers a session, a handle the proxy passes to every later
call. The proxy may receive and settle at the same time from different
processes, so the calls do not hand a new session back: a source whose
state changes as it runs (a broker connection) keeps it in a process of
its own and puts the pid in the session.

## The context

`open/2` gets the context the source makes its calls with: the tenant,
the proxy user the trigger runs as, the keys it may reveal. A source
makes each HTTP call through `Alternera.Plugin.Provisional.Outbound.call/3`
with `call_context/2` of that context and the call's time, as the proxy
user (`as: {:proxy_user, context.proxy_user_id}`), so the forward side's
pipelines, the SSRF guard and the tenant's outbound settings apply to it.

## Recording a source's calls

Whether the proxy records a source's calls is the trigger's
`record_source_calls`, which the context carries; a source passes the
context through and does nothing about it. For the `messages` level the
proxy records a receive only when it brought messages, and only the
source can tell an empty receive from its call: the optional
`empty_receive?/2` does, from the call's request (method, url, headers)
and its answer (status, headers, body). The forward side asks it once
the answer is in, before the call's exchange is written, so it must be
quick and must not call out. A source without it has every receive
recorded at that level.

## Messages and verdicts

A message is `t:message/0`: `handle` is the source's own, opaque to the
proxy but plain data, since it is kept in the runner's state and crosses
processes. A verdict is `:ack` (done with it), `{:retry, delay_ms}`
(deliver it again, not before the delay) or `:reject` (it cannot be
processed). A source whose capabilities say `settles_reject` is asked
`{:reject, delay_ms}` instead: a reject, which waits the delay first
only where the broker would deliver a rejected message again.

## Keeping a hold alive

A source whose broker can lengthen a message's hold after the receive
says so with `extend_hold: true` in its capabilities and implements the
optional `extend/2`, which hides each handle for `hold_ms` more, counted
from the call. The proxy then receives with a short hold and extends it
while the message waits for its run and while the run lasts, so a message
whose consumer died comes back after that short hold, not after the
longest a run may take. A source without it is held, from the receive,
for as long as its run may take.

## Calling a source

The proxy and the test kit call a source through `open/3`, `receive/5`,
`settle/3`, `extend/3`, `close/3`, `capabilities/2` and `init/2` here, never directly:
they rescue a source that raises, check the shape of what it answers and
log what is wrong, so a broken source is a consumer failure and never the
runner's crash.

# `call_request`

```elixir
@type call_request() :: %{
  method: String.t(),
  url: String.t(),
  headers: [{String.t(), String.t()}]
}
```

A call as `empty_receive?/2` sees it.

# `call_response`

```elixir
@type call_response() :: %{
  status: 100..599 | nil,
  headers: [{String.t(), String.t()}],
  body: binary() | nil
}
```

An answer as `empty_receive?/2` sees it: `body` is nil when the answer was
larger than the forward side keeps for the check (it then holds messages).

# `capabilities`

```elixir
@type capabilities() :: %{
  :max_batch =&gt; pos_integer(),
  :max_wait_ms =&gt; pos_integer(),
  :max_hold_ms =&gt; pos_integer(),
  optional(:extend_hold) =&gt; boolean(),
  optional(:settles_reject) =&gt; boolean()
}
```

What a source can do: the most messages one `receive/4` brings
(`max_batch`), the longest it blocks waiting for the first
(`max_wait_ms`) and the longest it can keep a message from other
consumers (`max_hold_ms`). A source must honour `{:retry, delay}`'s delay
at the broker: the proxy's backoff and its floor on a reject rely on it,
and a broker that can only redeliver at once cannot be a source.

`extend_hold` is optional, `false` when absent: `true` says `extend/2`
can lengthen a hold (see "Keeping a hold alive"). `capabilities/2` keeps
it `true` only when the source exports `extend/2`.

`settles_reject` is optional, `false` when absent: `true` says the source
settles a `:reject` at its broker (a RabbitMQ reject to the queue's
dead-letter exchange, a Camel consumer's failed exchange), so the
proxy hands it the reject as `{:reject, delay_ms}`: where a rejected
message would come back (a Camel file consumer reads a failed exchange
again), the source waits the delay before it settles. Without it a
reject is settled as a retry and the queue's own redrive policy moves a
message that keeps coming back.

# `context`

```elixir
@type context() :: %{
  :tenant_id =&gt; String.t() | nil,
  :proxy_user_id =&gt; String.t() | nil,
  :reveal_keys =&gt; [String.t()],
  optional(atom()) =&gt; term()
}
```

What a source makes its calls with: `tenant_id`, `proxy_user_id` (whom
its calls are made as), `reveal_keys` (the `reveal: true` fields of
`source_schema/0`) and, from the host, whatever it needs to make them,
among it `max_messages`, the most messages the trigger's runner holds at
once (its runs in flight and one poll waiting), for a source whose broker
takes a prefetch, and `trigger_id`, the trigger that opens it, for a
source that is one trigger's at a time.

# `failure`

```elixir
@type failure() :: {:error, String.t(), String.t()}
```

Why a call failed: an error type (`connection`, `timeout`, `http_status`…) and a message.

# `message`

```elixir
@type message() :: %{
  id: String.t(),
  handle: term(),
  body: binary(),
  attributes: %{required(String.t()) =&gt; String.t()},
  receive_count: pos_integer() | nil,
  sent_at: DateTime.t() | nil
}
```

A message a source delivered.

# `settle_result`

```elixir
@type settle_result() :: :ok | failure()
```

# `verdict`

```elixir
@type verdict() ::
  :ack | {:retry, non_neg_integer()} | :reject | {:reject, non_neg_integer()}
```

# `capabilities`

```elixir
@callback capabilities(opts :: term()) :: capabilities()
```

What the source opened with `opts` can do.

# `close`

```elixir
@callback close(session :: term(), reason :: term()) :: :ok
```

Closes the source; `reason` is why. Always answers `:ok`.

# `empty_receive?`
*optional* 

```elixir
@callback empty_receive?(call_request(), call_response()) :: boolean()
```

Whether one of the source's calls was a receive that brought no message
(see "Recording a source's calls"). Optional: without it every receive
counts as one that brought messages.

# `extend`
*optional* 

```elixir
@callback extend(session :: term(), [{handle :: term(), hold_ms :: pos_integer()}]) ::
  {:ok, [{handle :: term(), settle_result()}]} | failure()
```

Hides each handle from other consumers for its `hold_ms` more, counted
from the call (see "Keeping a hold alive"). Answers each handle with
`:ok` or why it failed, or one failure for all of them. Optional; called
only when the capabilities say `extend_hold: true`.

# `open`

```elixir
@callback open(opts :: term(), context()) :: {:ok, session :: term()} | failure()
```

Opens the source: anything it must do before the first receive. Answers the session.

# `receive`

```elixir
@callback receive(
  session :: term(),
  max :: pos_integer(),
  wait_ms :: non_neg_integer(),
  hold_ms :: pos_integer()
) :: {:ok, [message()]} | failure()
```

Up to `max` messages, waiting up to `wait_ms` for the first, each kept
from other consumers for `hold_ms`. `{:ok, []}` when none came.

# `settle`

```elixir
@callback settle(session :: term(), [{handle :: term(), verdict()}]) ::
  {:ok, [{handle :: term(), settle_result()}]} | failure()
```

Settles each handle with its verdict. Answers each handle with `:ok` or
why it failed, or one failure for all of them.

# `source_init`

```elixir
@callback source_init(settings :: map()) :: {:ok, opts :: term()} | {:error, [String.t()]}
```

The settings checked into the source's opts (see the moduledoc), or messages.

# `source_schema`

```elixir
@callback source_schema() :: [Alternera.Plugin.schema_field()]
```

The source's settings, as `settings_schema/0` describes a step's.

# `call_context`

```elixir
@spec call_context(context(), pos_integer()) :: map()
```

The context for one of the source's outbound calls: `context` with the
call's time, which `Outbound.call/3` takes as the call's deadline.

# `capabilities`

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

`module.capabilities(opts)`, rescued and checked: `{:ok, capabilities}`
or `{:error, message}`, logged.

# `check_message`

```elixir
@spec check_message(term()) :: {:ok, message()} | {:error, String.t()}
```

`message` as `t:message/0` has it, its optional keys (`attributes`,
`receive_count`, `sent_at`) filled in when absent, or why it is not one.

# `close`

```elixir
@spec close(module(), term(), term()) :: :ok
```

`module.close(session, reason)`, rescued: always `:ok`.

# `empty_receive?`

```elixir
@spec empty_receive?(module(), call_request(), call_response()) :: boolean()
```

`module.empty_receive?(request, response)`, rescued: `false` (the call is
recorded) when the source does not implement it, raises or answers
anything but a boolean, which is logged.

# `extend`

```elixir
@spec extend(module(), term(), [{term(), pos_integer()}]) :: [
  {term(), settle_result()}
]
```

`module.extend(session, holds)`, rescued and checked as `settle/3` is:
one answer per `{handle, hold_ms}` given, in the order given.

# `init`

```elixir
@spec init(module(), term()) :: {:ok, term()} | {:error, [String.t()]}
```

`settings` checked as the moduledoc says, then by `module.source_init/1`:
`{:ok, opts}` or `{:error, messages}`, never a raise.

# `of`

```elixir
@spec of(module()) :: {:ok, module()} | :none
```

The module that implements `plugin`'s source (its `source/0`), or `:none`
when the plugin offers none.

# `open`

```elixir
@spec open(module(), term(), context()) :: {:ok, term()} | failure()
```

`module.open(opts, context)`, rescued and checked.

# `plain_data?`

```elixir
@spec plain_data?(term()) :: boolean()
```

Whether `term` is plain data the compiler can embed as a literal: no pid,
port, reference, function or compiled regex anywhere in it.

# `receive`

```elixir
@spec receive(module(), term(), pos_integer(), non_neg_integer(), pos_integer()) ::
  {:ok, [message()]} | failure()
```

`module.receive(session, max, wait_ms, hold_ms)`, rescued and checked:
every message well-formed (its optional keys filled in), at most `max`.
A message that is not is dropped and logged; it comes back when its hold
lapses.

# `reveal_keys`

```elixir
@spec reveal_keys(module()) :: [String.t()]
```

The `reveal: true` keys of `module`'s `source_schema/0`; none, logged,
when the schema cannot be read (`init/2` then refuses the settings).

# `settle`

```elixir
@spec settle(module(), term(), [{term(), verdict()}]) :: [{term(), settle_result()}]
```

`module.settle(session, verdicts)`, rescued and checked: one answer per
handle given, in the order given. A handle the source did not answer, or
a failure of the whole call, answers that handle with a failure.

# `source?`

```elixir
@spec source?(module()) :: boolean()
```

Whether `module` implements every required callback of a source.

---

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