# `Juggernaut.Server.Protocol`
[🔗](https://github.com/holsee/juggernaut/blob/v0.4.0/lib/juggernaut/server/protocol.ex#L1)

The frames between `mix juggernaut.server` and its clients (design notes §12): JSON
documents in `{:packet, 4}` frames over a TCP socket on `127.0.0.1`. A frame is only
ever decoded as JSON (never `:erlang.binary_to_term/1`), and every request carries the
server's token, compared in constant time.

Requests (client to server), `{"v": 1, "token", "request", ...}`:

  * `run` and `check` - `argv` (the task's arguments) and `env` (the client's
    `JUGGERNAUT_*` variables, values) and `env_names` (the names of the client's other
    non-empty variables, for the `refuse_env` check; their values never leave the client);
  * `status` and `stop`.

Replies (server to client), one or more frames:

  * `{"queued": n}` - the request waits, `n` jobs ahead of it, sent again as the queue
    moves; `{"queued": 0}` comes once, when the job starts;
  * `{"out": "stdout" | "stderr", "data": text}` - output of the job, in order;
  * `{"exit": code}` - the job's exit code, the last frame;
  * `{"status": {...}}` - the answer to `status`;
  * `{"error": message, "exit": code}` - a refused request (bad token, bad frame).

# `request`

```elixir
@type request() :: %{
  request: String.t(),
  argv: [String.t()],
  env: %{required(String.t()) =&gt; String.t()},
  env_names: [String.t()]
}
```

A decoded request.

# `client_env`

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

The environment a client sends: the values of its `JUGGERNAUT_*` variables and the names
of its other non-empty variables (never their values).

# `decode`

```elixir
@spec decode(binary()) :: {:ok, map()} | {:error, String.t()}
```

Decodes a reply frame (`{:error, message}` for one that is not a JSON object).

# `decode_request`

```elixir
@spec decode_request(binary(), String.t()) :: {:ok, request()} | {:error, String.t()}
```

Decodes a request frame and checks its token against `token`. Returns the request, or
`{:error, message}` for a frame that is not JSON, has another version, a wrong token or
an unknown request.

# `encode`

```elixir
@spec encode(map()) :: iodata()
```

Encodes a frame (a map) as JSON.

# `request`

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

A request frame: `request` with its fields and the token.

# `socket_opts`

```elixir
@spec socket_opts() :: [:gen_tcp.option()]
```

The socket options of both ends.

---

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