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

The places of an exchange a pipeline step reads from (its source) and
writes to (its target), shared by every plugin that has one, so each
addresses, validates, describes, reads and writes them the same way.

A location is stored as an object with an `in` key and, where the kind
needs one, a `name` or a `path`:

    {"in": "request_headers", "name": "X-User-Id"}
    {"in": "query", "name": "page"}
    {"in": "request_body"}                      (the whole body)
    {"in": "response_body", "path": "$.user.id"}
    {"in": "vars", "name": "order_id"}
    {"in": "vars", "name": "order", "path": "items.0.sku"}
    {"in": "path", "name": "id"}

`parse/1` turns that into a `t:t/0`, plain data the compiler can embed.

## Kinds

  * `query` — a query parameter of the request, by name, or, without a
    name, all of them;
  * `request_headers` / `response_headers` — a header, by name, matched
    without regard to case, or, without a name, all of them. A header
    that is there keeps its spelling, a new one the spelling it was
    written in; the runner indexes each head by lower-case name
    (`with_header_names/1`), so a header is found without a downcase of
    any key, and keeps that index up to date itself;
  * `request_body` / `response_body` — the whole body, or the value at a
    JSON path in it (`Plugin.JsonPath`);
  * `vars` — a variable of the exchange, by name, with an optional
    `path`, the value at that JSON path inside it: read with
    `JsonPath.dig/2` (a plain map is walked by key, text is read as JSON
    first), written with `JsonPath.put/3` into the variable, which an
    unset variable starts as an empty object and JSON text is decoded
    for, and stored back whole (`write/3`);
  * `response_status` — the response's status, an integer: read in the
    response phases, written by a head step in After or among the Implementation's own steps
    (100..599);
  * `error` — the error a catch or On error handles, read only, by
    `name`: `type`, `message`, `step_id`, `status` or `attempt`.
    Outside a catch or On error there is none: it reads as missing;
  * `steps` — an earlier step's output (`Plugin.StepOutputs`), read
    only: the step's `id`, its `output` (`body`, `status`, `headers`,
    `outputs`, …), and an optional `key` (a header, matched in any case,
    or a named output) or `path` (a JSON path inside the value). A step
    that did not run, or did not keep the output, reads as missing.

        {"in": "steps", "id": "master-part", "output": "body", "path": "PartNo"}
        {"in": "steps", "id": "langs", "output": "headers", "key": "etag"}
  * `path` — a parameter of the pipeline's path template, read only, by
    `name`: the segment it matched, percent-decoded
    (`Pipelines.PathParams`, the request's `:path_params`). A name the
    template does not declare is refused at save; a pipeline without a
    template has none, and reads it as missing.

  * `input` — an input the Call step that runs this pipeline passed
    (`Pipelines.CallInputs`), read only, by `name`, with an optional
    `path` inside it, read as a variable is. An input not passed, and
    every input outside a call, reads as missing. In a wrapper, an
    inner parameter (spec 059 Q10) reads what the pipelines inside it
    wrote, or its default (`Pipelines.Declarations.inner_input/2`).

        {"in": "input", "name": "item_number"}

  * `url` — the request's URL as it stands at the step, an earlier
    rewrite included: without a `name` the whole URL, with
    one a part of it, `scheme`, `host` (the name alone, never with a
    port), `port` (an integer), `path` or
    `query` (the query string, without its `?`; missing when empty).
    Written only by a request step whose plugin declares
    `writes_url: true` (`write/3` says what each part takes);

        {"in": "url", "name": "host"}

  * `method` — the request's method, read only;
  * `upstream` — where the request will be sent, read only, by `name`
    `url`: on a reverse site its upstream (scheme, host and port), on the
    forward door the same as `url`. It is never missing while there is a
    request.

        {"in": "upstream", "name": "url"}

  * `outer` — an inner parameter of the pipelines around this one (an
    Outer pipeline parameter, spec 063 D6), write only, by `name`: held
    in the variables under `outer_key/0`, all of them together counted
    as one variable. `wrapper`, its name in spec 059, is refused.

        {"in": "outer", "name": "health"}

## Directions

A request step reads and writes the request's locations and the
variables. A response step reads every location (the request as it was
forwarded) and writes the response's locations and the variables: the
request has already gone upstream (`allowed/3`). An `answer` step, one on
an Implementation of own steps (`Pipelines.Flow`), reads and
writes everything: the request, and the response its flow is making
(`Pipelines.Runner`'s `building`), which is the answer.

`direction/1` parses the direction a plugin is prepared with; `phase_side/1`
says which side's phases it runs in, and `own_body/1` the body that is
its own (an `answer` step's own body is the response it makes).

## Values

A header, a query parameter and a whole body read as a string. A body
path reads the JSON value there, and a variable whatever was stored in
it, or with a path the value there. A header or query parameter sent more than once reads as its values
joined with `", "`. All the query parameters, or all of a head's
headers, read as one JSON object of name to value (header names in
lower case), keys sorted; they are read only, never written at once. Written where a string is needed (a header, a query
parameter, a whole body), a value that is not a string is written as JSON
text; a body path or a variable takes the value as it is. Header names
keep their case: a header that is there keeps its spelling, a new one
gets the one typed. `Content-Length` and `Transfer-Encoding` are not
written: the forwarder frames the body it sends.

## The exchange view

`read/2` and `write/3` work on a `t:view/0`: the request head, the
response head (nil in the request phase), the bodies the forwarder holds
(nil for one it does not), and the variables. A request head carries
`:headers` (a map of names to a string or a list of strings),
`:query_string` and `:url`; a response head is a
`Alternera.Proxy.Response` (header values are lists) or a map. A
write keeps the shape it finds.

# `held_error`

```elixir
@type held_error() ::
  String.t()
  | {:claim_refused, :busy | :size, String.t()}
  | {:memory_limit, String.t()}
```

Why `held/4` did not run its function to the end: the body limit (a
message), a refused claim, the heap limit, or a crash (a message).

# `kind`

```elixir
@type kind() ::
  :query
  | :request_headers
  | :request_body
  | :response_headers
  | :response_body
  | :vars
  | :response_status
  | :error
  | :steps
  | :path
  | :input
  | :outer
  | :context
  | :url
  | :method
  | :upstream
```

A kind of location.

# `op`

```elixir
@type op() :: :remove | {:put_if_present, term()} | {:append, term()}
```

What a write carries besides a value (`write/3`): `:remove`,
`{:put_if_present, value}` or `{:append, value}`.

# `t`

```elixir
@type t() ::
  %{in: :query, name: String.t() | nil}
  | %{
      :in =&gt; :request_headers | :response_headers,
      :name =&gt; String.t() | nil,
      optional(:lower) =&gt; String.t()
    }
  | %{
      :in =&gt; :vars,
      :name =&gt; String.t(),
      optional(:path) =&gt; Alternera.Plugin.JsonPath.segments()
    }
  | %{
      in: :request_body | :response_body,
      path: Alternera.Plugin.JsonPath.segments() | nil
    }
  | %{in: :response_status}
  | %{in: :error, name: String.t()}
  | %{
      in: :steps,
      id: String.t(),
      output: String.t(),
      key: String.t() | nil,
      path: Alternera.Plugin.JsonPath.segments() | nil
    }
  | %{in: :path, name: String.t()}
  | %{in: :url, name: String.t() | nil}
  | %{in: :method}
  | %{in: :upstream, name: String.t()}
  | %{
      :in =&gt; :input | :outer | :context,
      :name =&gt; String.t(),
      optional(:path) =&gt; Alternera.Plugin.JsonPath.segments()
    }
```

A parsed location: `name` for a query parameter, a header or a variable,
`path` (JSON path segments, or nil for the whole body) for a body.

# `view`

```elixir
@type view() :: %{
  :request =&gt; map() | nil,
  :response =&gt; map() | nil,
  :request_body =&gt; binary() | Alternera.Plugin.Body.t() | nil,
  :response_body =&gt; binary() | Alternera.Plugin.Body.t() | nil,
  :vars =&gt; map(),
  optional(:error) =&gt; map() | nil,
  optional(:steps) =&gt; Alternera.Plugin.StepOutputs.scope(),
  optional(:input) =&gt; map() | nil,
  optional(:limits) =&gt; %{var_bytes: pos_integer()}
}
```

What a step sees of its exchange; see the module doc.

# `allowed`

```elixir
@spec allowed(t(), :request | :response | :answer, :read | :write) ::
  :ok | {:error, String.t()}
```

Whether a step of `direction` may read (`:read`) or write (`:write`) the
location; see "Directions" in the module doc.

# `answer_write?`

```elixir
@spec answer_write?(t() | nil) :: boolean()
```

Whether a step of an Implementation of own steps may write `location`
in either phase of its side: a variable, or the response it makes,
which is sent only when the request side ends (`Plugin.Signature.follows?/1`).
Nil, nothing written, counts.

# `body`

```elixir
@spec body(t()) :: :request_body | :response_body | nil
```

The body a location names, or nil.

# `describe`

```elixir
@spec describe(t()) :: String.t()
```

A location in words, for summaries and messages.

# `direction`

```elixir
@spec direction(term()) ::
  {:ok, :request | :response | :answer} | {:error, String.t()}
```

The direction a plugin is prepared with, from its settings'
`"direction"`: `:request`, `:response`, or `:answer` (the request side
of an Implementation of own steps); `{:error, message}` for anything else, nil
included (the runner always injects one).

# `doc_to_edit`

```elixir
@spec doc_to_edit(view(), :request_body | :response_body, term()) ::
  {:ok, Alternera.Plugin.JsonDoc.t()} | {:error, String.t()}
```

The document of the body `kind` to edit: the one the view carries for
this very body, or one built here (noted as `read/2` notes it, a body
that is not JSON as such). An empty body is an empty object, so a field
written to it is the first key of a new one. A body in memory is edited
there; a body held in a file is edited over it and never read whole
(`JsonDoc`'s pieces), its document built, when the view carries none,
in a process of its own under the heap limit for the file's size, as a
path read builds it; a document a step already edited (the view's body,
`JsonDoc.body/1`) is edited on. A plugin that edits a body through
`JsonDoc` itself starts here, and hands the result to `edited/3`.

# `docs`

```elixir
@spec docs(map()) :: %{optional(atom()) =&gt; Alternera.Plugin.JsonDoc.verdict()}
```

The `JsonDoc`s a view carries for its bodies, by body (`:request_body`,
`:response_body`): the host puts in the view (`:json_docs`) those it
kept from earlier steps, and how the pipeline wants each body indexed
(`:json_index`, `:auto` unless it says `:off` or `:always`). A body path
read uses a document only for the body it was built over
(`JsonDoc.reads?/2`).

# `edited`

```elixir
@spec edited(view(), :request_body | :response_body, Alternera.Plugin.JsonDoc.t()) ::
  view()
```

The view with the body `kind` set to an edited document's body
(`JsonDoc.body/1`: its text, or for a body edited over its file the
document itself, which the host writes out after the step), the
document beside it for the step's next read and noted for the host to
keep with the new body; where the pipeline turned the body's index off,
no document is kept for it at all.

# `empty_view`

```elixir
@spec empty_view() :: view()
```

An empty view, for a phase that has nothing yet.

# `header`

```elixir
@spec header(:request_headers | :response_headers, String.t()) :: t()
```

The location of the header `name` on `kind`'s side, with its lower-case
form (`:lower`) worked out here, once: a step builds its header
locations when it is prepared (`parse/1` does this for a stored one),
and every read and write of the location then finds the header by
`:lower` without lower-casing `name` again. `name` keeps the step's
spelling, which a new header is sent with.

A header location built without `:lower` still works: its name is
lower-cased at each use.

# `header_key`

```elixir
@spec header_key(map(), String.t()) :: String.t()
```

The key `head` keeps the header `name` under, in any spelling: its own
when there is one, else `name` itself.

# `header_name?`

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

Whether `name` is a header field name as it stands: a non-empty RFC 9110
`token`, untrimmed. It is the rule `Proxy.Streaming.H1Grammar.token?/1`
holds for the proxy, which a plugin cannot call; a test keeps the two
equal. `parse/1` applies it to a header location's trimmed name.

# `header_names`

```elixir
@spec header_names(map() | nil) :: %{optional(String.t()) =&gt; String.t()} | nil
```

The index `with_header_names/1` gave `head`, as the steps left it:
lower-case name to the key as spelled, for the keys not in lower case
(`%{}` when none is, nil for a head nobody indexed). The runner hands it
to the doors with the message (`Pipelines.Runner.Result`'s
`header_names`), so the name a step wrote is sent as the step spelled it
and found by its lower-case form without lower-casing it again.

# `headers`

```elixir
@spec headers(map() | nil) :: %{required(String.t()) =&gt; String.t()}
```

A head's headers as one map: names in lower case, a header sent more
than once (or under several spellings) as its values joined with `", "`,
or `"; "` for `Cookie` (RFC 9113 8.2.3: a comma may sit inside a cookie
value), as `read/2` reads one.

# `held`

```elixir
@spec held(non_neg_integer(), atom(), map(), (-&gt; result)) ::
  {:ok, result} | {:error, held_error()}
when result: term()
```

`fun` (no arguments) run as work on `bytes` of the body `kind` that the
runner does not account for (a body it handed the step unread): within
the exchange's body limit the view carries, `bytes` claimed through
`Host.claim_held_bytes/1` while it runs, in a process of its own under
the step heap limit for `bytes` (`Provisional.StepHeap.max_words/1`).
`{:ok, result}`; `{:error, {:claim_refused, kind, message}}`, which the
step answers as the application answers its own
(`Host.claim_refusal/2`); `{:error, {:memory_limit, message}}` when the
process was stopped at its limit (logged); `{:error, message}` past the
body limit or when `fun` crashed (logged). What `fun` returns is copied
back to the caller, apart from large binaries.

# `kept_doc`

```elixir
@spec kept_doc(view(), :request_body | :response_body, term()) ::
  Alternera.Plugin.JsonDoc.verdict() | nil
```

The document the view carries for this very `body` of `kind`, its text
in memory, or the verdict that the body is not JSON; nil when it
carries neither. Builds nothing: a plugin that edits a body through
`JsonDoc` in a way of its own starts from this, opening the body
itself when it is nil, and notes what it made (`note_doc/3`).

# `kinds`

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

The kinds, as stored.

# `mark_key`

```elixir
@spec mark_key(t()) :: String.t()
```

The key a step's summary marks a value written to `location` under
(`header_vars`, a variable to the header it came from): a variable's own
name, `context.<name>` for a context name and `outer.<name>` for an
outer pipeline parameter, which no variable name can be (a variable's
name holds only letters, digits and `_`, `parse/1`). Only these three
hold a value a mark follows; any other location raises.

# `max_var_bytes`

```elixir
@spec max_var_bytes() :: pos_integer()
```

The floor of a variable's size, as JSON: the most a variable holds
without a tenant, and for a tenant whose `body_inspect_max_bytes` is
lower. A tenant's variables may be as large as its
`body_inspect_max_bytes` (the view's `limits.var_bytes`).

# `max_vars`

```elixir
@spec max_vars() :: pos_integer()
```

The most variables a pipeline holds on one exchange (each pipeline has its own).

# `note_doc`

```elixir
@spec note_doc(
  view(),
  :request_body | :response_body,
  Alternera.Plugin.JsonDoc.verdict()
) :: :ok
```

Notes a document (or a not-JSON verdict) for the body `kind`, for the
host to keep with the body the step leaves (`JsonDoc.note_built/2`):
only in a view the host built, and not where the pipeline turned the
body's index off. The host keeps it only if it reads that body.

# `only_bodies`

```elixir
@spec only_bodies(map(), [:request_body | :response_body]) :: map()
```

`view` with every body not in `keep` set to nil: what a host hands a step
whose signature reads or writes those bodies (`Signature.bodies/1`,
plus its phase's own), so it reads, holds and counts no other.

# `outer_key`

```elixir
@spec outer_key() :: String.t()
```

The variables' key the values written to Outer pipeline parameters are
held under (`:outer`): not a variable name, so no variable read or write
reaches it.

# `outer_values`

```elixir
@spec outer_values(view()) :: map() | nil
```

The values the pipelines inside a wrapper wrote to its inner parameters
that a view holds (name => value), or nil.

# `own_body`

```elixir
@spec own_body(:request | :response | :answer) :: :request_body | :response_body
```

The body that is a step's own (its default source and target): the
request body for a request step, the response body for a response step
and for an `answer` step, whose own output is the response it makes.

# `parse`

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

Parses a stored location. Strict: an unknown kind, a missing or invalid
name, a path on a kind that takes none, or any other key is refused.

# `phase_side`

```elixir
@spec phase_side(:request | :response | :answer) :: :request | :response
```

The side whose phases a step of `direction` runs in: an `answer` step
runs on the request (its flow makes the response before any upstream).

# `query`

```elixir
@spec query(map() | nil) :: %{required(String.t()) =&gt; String.t()}
```

A request's query parameters as one map, decoded, a parameter sent more
than once as its values joined with `", "`, as `read/2` reads one.

# `read`

```elixir
@spec read(t(), view()) ::
  {:ok, term()}
  | :missing
  | {:error, String.t() | {:claim_refused, :busy | :size, String.t()}}
```

Reads a location: `{:ok, value}`, `:missing` when there is nothing there
(no such header, parameter, field or variable), or `{:error, reason}`
when it cannot be read (a body the forwarder does not hold, a body path
into a body that is not JSON). A JSON path into a spooled body, which
only a step that takes handles sees, is `{:error, {:claim_refused, kind,
message}}` when the application has no room to read it
(`Host.claim_held_bytes/2`; `Host.claim_refusal/2` is the step error it
makes).

# `same?`

```elixir
@spec same?(t(), t()) :: boolean()
```

Whether two locations name the same place: `:lower`, worked out from the
name, is left out of the comparison, so a header location built with it
and one built without are the same.

# `schema_field`

```elixir
@spec schema_field(String.t(), String.t(), boolean()) ::
  Alternera.Plugin.schema_field()
```

The settings field a plugin's `settings_schema/0` lists for a location,
under `key` (`"source"`, `"target"`).

# `schema_note`

```elixir
@spec schema_note() :: String.t()
```

What every location field of a `settings_schema/0` says after its own
description: the shape of the object. The guide's plugin reference prints
it once rather than in every field.

# `side`

```elixir
@spec side(t()) :: :request | :response | :exchange
```

The side of the exchange a location belongs to: `:request`, `:response`,
or `:exchange` for a variable, the error, a step output and an input.

# `to_settings`

```elixir
@spec to_settings(t()) :: map()
```

A parsed location back in its stored form.

# `with_header_names`

```elixir
@spec with_header_names(map()) :: map()
```

`head` with the lower-case index of its header names: lowered name to
the key as spelled, for each key that is not already lower case (empty
for a head whose keys all are, as both doors parse them). The runner
indexes every head it hands a plugin and removes the index from what it
hands back; `read/2` and `write/3` keep it, so a plugin never sees it. A
head without one (a plugin's own test) has its keys searched in any
case instead.

# `with_header_names`

```elixir
@spec with_header_names(map(), %{optional(String.t()) =&gt; String.t()} | nil) :: map()
```

`with_header_names/1`, taking each name's lower-case form from `names`
(an index an earlier run of the head kept, `header_names/1`) where it
holds one: a head handed from one pipeline to the next is indexed
without lower-casing a name the one before already did.

# `with_text`

```elixir
@spec with_text(t(), map(), (binary() -&gt; result)) ::
  {:ok, result} | :missing | {:error, held_error()}
when result: term()
```

`fun` on the whole body of `kind` as text, for a step the runner hands
its body unread (`json_doc:`), which neither claims that body nor bounds
the step's heap for it: a body held in a file, or a document a step
edited over one, is read and given to `fun` in a process of its own
(`held/4`), its size claimed and that process under the heap limit for
it, so what `fun` makes of the text (a decode) is bounded with it. A
body in memory, which the runner accounted for, is read as `read/2`
reads it and `fun` runs in the caller. `{:ok, result}`, `:missing`, or
`held/4`'s errors and `read/2`'s.

# `write`

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

Writes `value` to a location: `{:ok, view}` with the view changed, or
`{:error, reason}` (a body that is not held or not JSON, a header value
with a line break, a variable over its limits). `nil` is not a value:
the caller leaves the location as it is.

Besides a value, a write may carry an operation (`t:op/0`):

  * `:remove` drops a named header (every spelling of it), a named query
    parameter (every occurrence), the query (`url.query`) or the port
    (`url.port`, the scheme's default then); a header or parameter that
    is not there is not an error;
  * `{:put_if_present, value}` writes `value` to a named header or query
    parameter only when the message carries it, and leaves the view as
    it is otherwise;
  * `{:append, value}` adds `value` to a named header or query parameter
    beside what is there: one more value of a header (one more line of a
    header the head keeps as a list, `Set-Cookie` among them, else
    joined with `", "`, RFC 9110 §5.3, or `"; "` for `Cookie`, RFC 9113
    §8.2.3), one more `name=value` at the end of the query.

An operation anywhere else is refused.

The URL (`url`, and its parts `scheme`, `host`, `port`, `path`, `query`)
is written into the request's own fields, the ones the forwarder dials
from, and its `:url` rebuilt from them. `host` takes `name` or
`name:port` (an IPv6 address in brackets), `port` an integer, `scheme`
`http` or `https`, `path` an origin-form path, `query` the query string
without its `?`, and the whole URL an absolute `http` or `https` URL with
a host. None may carry a space or a control character. The `Host` header
is not written here: the runner makes it follow a step's host write.

---

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