# `HL7v2.MLLP.Connection`
[🔗](https://github.com/Balneario-de-Cofrentes/hl7v2/blob/v3.10.1/lib/hl7v2/mllp/connection.ex#L1)

Ranch protocol handler for MLLP connections.

Manages the lifecycle of a single MLLP connection:

1. Accept the TCP connection via Ranch handshake
2. Read data, buffering until a complete MLLP frame arrives
3. Extract the message, invoke the configured handler
4. Frame the response and send it back
5. Continue reading (MLLP connections are persistent)
6. Handle timeouts and disconnects gracefully

## Options (passed through from `HL7v2.MLLP.Listener`)

- `:handler` (required) — module implementing `HL7v2.MLLP.Handler`.
- `:handler_state` — arbitrary term passed to the handler in metadata.
- `:timeout` — idle connection timeout in milliseconds (default: `60_000`).
- `:max_message_size` — maximum allowed buffer size in bytes before the
  connection is closed (default: `10_485_760` — 10 MB). Protects against
  memory exhaustion from misbehaving or malicious senders.
- `:handler_timeout` — maximum time in milliseconds to wait for the handler
  to return (default: `60_000`). If the handler does not respond within this
  window, the handler process is killed and the connection continues accepting
  new messages.

## Telemetry events

- `[:hl7v2, :mllp, :connection, :start]` — emitted when a connection is accepted
  - Measurements: `%{system_time: integer()}`
  - Metadata: `%{ref: term(), peer: {address, port}}`

- `[:hl7v2, :mllp, :connection, :stop]` — emitted when a connection closes
  - Measurements: `%{duration: integer()}`
  - Metadata: `%{ref: term(), peer: {address, port}, reason: term()}`

- `[:hl7v2, :mllp, :message, :start]` — emitted before handler invocation
  - Measurements: `%{system_time: integer()}`
  - Metadata: `%{ref: term(), peer: {address, port}, message_size: integer()}`

- `[:hl7v2, :mllp, :message, :stop]` — emitted after handler returns
  - Measurements: `%{duration: integer()}`
  - Metadata: `%{ref: term(), peer: {address, port}, response_size: integer()}`

- `[:hl7v2, :mllp, :message, :exception]` — emitted when handler raises, errors, or times out
  - Measurements: `%{duration: integer()}`
  - Metadata: `%{ref: term(), peer: {address, port}, kind: term(), reason: term(), stacktrace: list()}`

---

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