# `MDL`
[🔗](https://github.com/zthacker/mdl/blob/v0.2.0/bindings/elixir/lib/mdl.ex#L1)

MDL's runtime for Elixir: open an artifact store `morphc` built, decode
telemetry, encode commands, describe the build, and look up which asset
a native id is. It calls the runtime every binding calls (spec/api.md),
through a native library, and holds no MDL semantics of its own.

    {:ok, mdl} = MDL.open("store", bindings: File.read!("bindings.toml"))

    {:ok, decoded} =
      MDL.decode(mdl, "sat", %{
        payload: payload,
        metadata: %{"apid" => 100},
        ground_time: System.os_time(:nanosecond)
      })

    for %MDL.Sample{param: param, value: value, quality: :good} <- decoded.samples do
      {param, value}
    end

    {:ok, command} =
      MDL.encode(mdl, "sat", %{
        set: "sat_v1",
        command: "eps.set_mode",
        arguments: %{"mode" => "SAFE"}
      })

## Values

Results use Elixir's own values:

* The results' fixed shapes are structs (`MDL.Decoded`, `MDL.Sample`,
  `MDL.Encoded`, `MDL.Route`, `MDL.Error`, `MDL.Problem`, `MDL.Vec3`,
  `MDL.Quat`), and MDL's own names in them are atoms: a quality, a frame,
  an error's code, an event time's kind, a time unit.
* Everything that comes from definitions or messages is a string: param
  and entry names, paths, units, state names, metadata keys, the
  record's keys. A node that keeps reloading stores never grows its atom
  table.
* Integers are of any size. NaN and the infinities, which the BEAM's
  floats can't hold, are `:nan`, `:infinity` and `:neg_infinity`.
* Text and bytes are both binaries; a param's or field's type, which
  `describe/1` gives, says which. A bytes argument to `encode/3` is
  `{:bytes, binary}`.
* An instant is an integer: nanoseconds since 1970-01-01T00:00:00Z,
  every day 86,400 seconds. `DateTime` holds microseconds.

## Errors

Every operation returns `{:ok, result}` or `{:error, %MDL.Error{}}`,
whose `:code` names the problem and is stable across releases. An
argument of the wrong shape (a payload that isn't a binary, a metadata
key that isn't a string) raises `ArgumentError`.

## Handles and scheduling

A handle is immutable and may be used by any number of processes at
once: store it where every process can reach it (`:persistent_term`, an
ETS table, a process's state). Opening the store again gives a new
handle; an older one keeps working, on the build it opened, until it's
garbage collected.

Every function that does MDL's work runs on a dirty CPU scheduler, so no
definition or payload, however large, holds up the BEAM's normal
schedulers. The switch costs a few microseconds a call; `decode_many/3`
pays it once for a batch.

# `argument`

```elixir
@type argument() ::
  integer()
  | float()
  | :nan
  | :infinity
  | :neg_infinity
  | boolean()
  | String.t()
  | {:bytes, binary()}
  | [argument()]
```

An argument's value: bytes are `{:bytes, binary}`, text a string.

# `event_time`

```elixir
@type event_time() ::
  {:ground, instant()}
  | {:at, instant()}
  | {:since_boot, non_neg_integer(), :s | :ms | :us | :ns}
```

When a message's values were taken: its ground time, when the packet
gives none; an instant the packet gives; or a count since the asset
booted, which isn't an instant until correlated.

# `family`

```elixir
@type family() :: String.t()
```

A family's name.

# `float_value`

```elixir
@type float_value() :: float() | :nan | :infinity | :neg_infinity
```

A float, or NaN or an infinity.

# `frame`

```elixir
@type frame() :: :ecef | :eci_j2000 | :body | :ned | :enu | :geodetic
```

A composite's frame: its IR name, `ECI_J2000`, in lower case.

# `handle`

```elixir
@opaque handle()
```

An opened store.

# `instant`

```elixir
@type instant() :: integer()
```

Nanoseconds since 1970-01-01T00:00:00Z, every day 86,400 seconds.

# `message`

```elixir
@type message() :: %{
  :payload =&gt; binary(),
  :ground_time =&gt; instant(),
  optional(:metadata) =&gt; metadata()
}
```

A message: its payload (a JSON family's is the document's UTF-8 text),
the metadata the link delivers with it, and when the ground received it.

# `metadata`

```elixir
@type metadata() :: %{optional(String.t()) =&gt; integer() | String.t()}
```

Metadata a link delivers with a payload, by name.

# `native_id`

```elixir
@type native_id() :: integer() | String.t()
```

What a family's alias locator reads: an integer or a string.

# `quality`

```elixir
@type quality() ::
  :good
  | :invalid
  | :unknown_state
  | :out_of_calibration
  | :out_of_range
  | :non_finite
```

Whether a value can be trusted; any but `:good` is the raw value.

# `request`

```elixir
@type request() :: %{
  :set =&gt; String.t(),
  :command =&gt; String.t(),
  optional(:arguments) =&gt; %{optional(String.t()) =&gt; argument()},
  optional(:native_id) =&gt; native_id() | nil
}
```

A command to encode: the set that encodes it, the catalog command, its
arguments by name, and the native id of the asset it's sent to, for a
packet that writes it.

# `result`

```elixir
@type result(ok) :: {:ok, ok} | {:error, MDL.Error.t()}
```

An operation's result.

# `value`

```elixir
@type value() ::
  integer()
  | float_value()
  | boolean()
  | binary()
  | MDL.Vec3.t()
  | MDL.Quat.t()
  | nil
  | [value()]
  | %{optional(String.t()) =&gt; value()}
```

A decoded value: a record's, a sample's or an engineering value's.

# `asset`

```elixir
@spec asset(handle(), family(), String.t(), instant()) :: result(MDL.Route.t() | nil)
```

The native id that is `asset` in `family` at `at`, with its binding
(spec/api.md section 2.6): where a command to the asset goes. `nil` when
no native id is the asset then; `:ambiguous_asset` when several are.

# `binding`

```elixir
@spec binding(handle(), family(), native_id(), instant()) ::
  result(MDL.Route.t() | nil)
```

What `native_id` of `family` is at `at` (spec/api.md section 2.6), as a
message received then would resolve it: its binding, or without bindings
the asset it stands for; `nil` when it's no asset then.

# `decode`

```elixir
@spec decode(handle(), family(), message()) :: result(MDL.Decoded.t())
```

Decodes a message `family` sent (spec/api.md section 2.2): routes it to
an asset and a set, identifies its packet, and gives its samples.

# `decode_many`

```elixir
@spec decode_many(handle(), family(), [message()]) :: [result(MDL.Decoded.t())]
```

Decodes each message, in order (spec/api.md section 2.3): one result per
message, one message's error not stopping the others. One call for the
batch, so the switch to a dirty scheduler is paid once.

# `describe`

```elixir
@spec describe(handle()) :: result(map())
```

Describes the build (spec/api.md section 3.3): the catalog, each family
and each set as the IR has them, with their digests, and where each
entry of a binary set can be. The description is maps with string keys,
as the IR's JSON is: `"format"`, `"catalog"`, `"families"` and `"sets"`.

# `encode`

```elixir
@spec encode(handle(), family(), request()) :: result(MDL.Encoded.t())
```

Encodes a catalog command as one of `family`'s sets' command packets
(spec/api.md section 2.4), its arguments checked against their types,
states, ranges and lists.

# `open`

```elixir
@spec open(Path.t(), keyword()) :: result(handle())
```

Opens the store in `dir` (spec/api.md section 2.1).

Options:

* `:bindings`: the text of a bindings file, which names the asset each
  native id is and the set that decodes it. Without it, each native id
  stands for an asset of its own.

Bindings that can't be read refuse the open. Anything else they say that
the build doesn't have is a warning (`warnings/1`), and the messages it
affects are refused when decoded.

# `open_bytes`

```elixir
@spec open_bytes(binary(), [binary()], keyword()) :: result(handle())
```

Opens a store given as its files' bytes: the manifest's, and each
artifact's, which are found by their own identity and need no names.
Takes the options `open/2` takes.

# `warnings`

```elixir
@spec warnings(handle()) :: [MDL.Problem.t()]
```

What the handle's bindings say that its build doesn't have: a set it
lacks, a set named for a family whose version locator chooses. The
messages these affect are refused when decoded, with their own codes.

# `with_bindings`

```elixir
@spec with_bindings(handle(), String.t() | nil) :: result(handle())
```

The handle's build with other bindings (their text), or none (`nil`),
without reading or assembling the build again.

---

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