# `NodeWire`
[🔗](https://github.com/c2bw/nodewire/blob/v0.1.0/lib/node_wire.ex#L1)

Authenticated TLS connections between Elixir agents and servers.

Define messages with `NodeWire.Protocol`, implement `NodeWire.Handler`, and
supervise a `NodeWire.Server` or `NodeWire.Client`. See the README for a
complete TLS echo example. Public sends use identity routing through the
server or the persistent client; asynchronous work uses
`NodeWire.Connection.notify/3` with a `NodeWire.Conn` snapshot.

## Endpoint options

Both endpoints require:

  * `:protocols` — one to eight compiled protocol modules, with unique versions
    in one family. The highest compatible version and codec are negotiated.
  * `:handler` — a compiled handler module. Servers require `authenticate/3`;
    clients require `handshake_data/2` in addition to the shared callbacks.
  * `:phases` — `initial: atom, ready: atom, states: map`. Each state maps to
    `%{incoming: [message_name], outgoing: [message_name], next: [phase]}`.
    Names must exist in every configured protocol; ready must be reachable.
  * `:transport` — `{:tls, options}` with `:port`, client `:host` (string or
    charlist), and `:options` containing SSL options. Servers may use port 0.
    Supply server `:certfile`/`:keyfile` and client trust roots such as
    `:cacertfile`. Client verification defaults to `:verify_peer` with hostname
    matching and SNI. Explicit `:verify_none` disables server authentication.

Optional settings:

  * `:name` — an OTP registered name; also the default supervisor child ID.
    Wrap the child spec with a distinct ID when supervising multiple unnamed
    endpoints of the same kind.
  * `:handler_args` — argument to handler `init/1`, default `nil`. State is
    recreated for each connection, including reconnects.
  * `:handshake` — `timeout_ms: 10_000, required_capabilities: []`.
  * `:tls_handshake_timeout_ms` — 5,000; a positive integer.
  * `:readiness_timeout_ms` — 35,000 after negotiation; reaching the ready
    phase cancels it. Heartbeats do not extend this deadline.
  * `:heartbeat` — `send_interval_ms` and `receive_timeout_ms`. Client defaults
    are 10,000 and `nil`; server defaults are `nil` and 30,000. `nil` disables
    the corresponding timer; other values must be positive integers.
  * `:limits` — positive integer overrides listed below.
  * `:reconnect` — client `enabled: true, interval_ms: 20_000`. No application
    messages are replayed. Authentication, trust and incompatibility failures
    stop automatic retry; transport and readiness/heartbeat failures retry.
    Duplicate identities, missing capabilities and invalid handshakes also
    stop automatic retry and cannot be overridden by `:reconnect_policy`.
  * `:reconnect_policy` — client map of at most 32 reason atoms to `:transient`
    or `:permanent`. It cannot override authentication or trust failures.
  * `:lifecycle_observer` — server PID or registered name receiving
    `{:nodewire, :connected | :ready | :disconnected, conn, reason}`. Delivery
    is best effort; reconcile with `NodeWire.Server.connections/1`.

SSL framing, active mode, packet limits and send timeouts are managed by
NodeWire. Supplied `:active`, `:packet`, `:mode`, `:packet_size`, `:send_timeout`
and `:send_timeout_close` values are overridden.

## Limits

| Option | Default |
| --- | --- |
| `:max_packet_bytes` | 16,777,216 |
| `:max_handshake_packet_bytes` | 16,384 |
| `:max_control_packet_bytes` | 16,384 |
| `:max_connections` (server) | 1,024 |
| `:max_handshakes` (server) | 128 |
| `:max_pending_messages` (per connection) | 256 |
| `:max_pending_bytes` (per connection) | 16,777,216 |

Admission counts the external Erlang representation of requests, options and
tracking tags. Encoded packet limits apply separately. JSON decoding also
bounds depth to eight and collections to 1,024 entries; increasing packet
limits does not remove these parser bounds.

## Delivery and timeouts

Send `:ok` means a local SSL write and any post-send tracking have completed.
It does not acknowledge remote receipt or execution. `{:error, :busy}` means
admission refused the request before dispatch and is safe to retry.
`{:error, {:outcome_unknown, reason}}` means the operation may have executed;
do not automatically replay it. `:timeout_ms` defaults to 5,000 for dispatched
sends and notifications; admission and endpoint lookup have separate waits,
so this is not an end-to-end deadline.

Telemetry events use `[:node_wire, event]`. See the README's telemetry table
for measurements and metadata. Durations are native monotonic units. Handlers
run synchronously in the emitting process and must remain fast.

# `call_options`

```elixir
@type call_options() :: [{:timeout_ms, timeout()}]
```

Local dispatch wait in milliseconds, or `:infinity`.

# `limits`

```elixir
@type limits() :: [
  {:max_packet_bytes
   | :max_handshake_packet_bytes
   | :max_control_packet_bytes
   | :max_connections
   | :max_handshakes
   | :max_pending_messages
   | :max_pending_bytes, pos_integer()}
]
```

Positive integer overrides for packet, concurrency and admission limits.

# `message`

```elixir
@type message() :: {atom(), term()}
```

A declared message name and its application payload.

# `options`

```elixir
@type options() :: [
  protocols: [module()],
  handler: module(),
  handler_args: term(),
  name: GenServer.name(),
  phases: phases(),
  transport: transport(),
  handshake: [timeout_ms: pos_integer(), required_capabilities: [String.t()]],
  tls_handshake_timeout_ms: pos_integer(),
  readiness_timeout_ms: pos_integer(),
  heartbeat: [{:send_interval_ms | :receive_timeout_ms, pos_integer() | nil}],
  limits: limits(),
  reconnect: [enabled: boolean(), interval_ms: pos_integer()],
  reconnect_policy: %{optional(atom()) =&gt; :transient | :permanent},
  lifecycle_observer: pid() | atom()
]
```

Shared endpoint configuration; role-specific requirements are described above.

# `phase`

```elixir
@type phase() :: atom()
```

Application phase name.

# `phase_policy`

```elixir
@type phase_policy() :: %{incoming: [atom()], outgoing: [atom()], next: [phase()]}
```

Allowed incoming messages, outgoing messages and next phases.

# `phases`

```elixir
@type phases() :: [
  initial: phase(),
  ready: phase(),
  states: %{required(phase()) =&gt; phase_policy()}
]
```

Initial and ready phases plus the transition graph.

# `send_error`

```elixir
@type send_error() ::
  :not_connected
  | :not_ready
  | :busy
  | :stale_connection
  | {:message_not_allowed, phase()}
  | {:invalid_outbound, atom() | NodeWire.Error.t()}
  | {:outcome_unknown, term()}
```

Pre-write rejection or an explicitly unknown delivery outcome.

# `send_options`

```elixir
@type send_options() :: [timeout_ms: timeout(), on_sent: term()]
```

Dispatch timeout and optional tag passed to `c:NodeWire.Handler.handle_sent/3`.

# `send_result`

```elixir
@type send_result() :: :ok | {:error, send_error()}
```

Local write/tracking result; never a remote execution acknowledgment.

# `transport`

```elixir
@type transport() ::
  {:tls,
   host: String.t() | charlist(), port: :inet.port_number(), options: keyword()}
```

TLS endpoint address and SSL options.

---

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