gluegun/connection

Connection management for Erlang Gun.

Open a Gun process, wait for it to be ready, choose transport and HTTP protocol preferences, then close or shut down the connection. Connections are Erlang process resources and are available on the Erlang target only.

Types

Address family for DNS lookup and socket connection, without fallback.

pub type AddressFamily {
  Ipv4
  Ipv6
}

Constructors

  • Ipv4
  • Ipv6

Pure representation of connection options before FFI conversion.

Build with options() and the with_* builders. Configure retry count, address family, separate setup timeouts, and TLS options as needed, then pass the result to open(host:, port:).

pub opaque type ConnectOptions

Opaque handle for an open Gun connection.

pub type Connection =
  @internal Connection

HTTP protocol preference for a Gun connection.

This type is closed; new variants are a breaking change. Pin to a major version.

Http2 is encoded as Gun’s http2 protocol atom, so it can be placed before Http1 when TLS + ALPN should prefer HTTP/2 and fall back to HTTP/1.1.

pub type Protocol {
  Http1
  Http2
}

Constructors

  • Http1

    HTTP/1.1. Required for WebSocket upgrades.

  • Http2

    HTTP/2. Negotiated via ALPN when paired with TLS.

Number of reconnection attempts after the initial connection attempt.

pub opaque type RetryCount

Timeout in milliseconds, or no limit.

pub opaque type Timeout

Transport selection for a Gun connection.

This type is closed; new variants are a breaking change. Pin to a major version.

pub type Transport {
  Auto
  Tcp
  Tls
}

Constructors

  • Auto

    Use TLS on port 443 and TCP on all other ports. TCP connections do not load TLS trust roots.

    If TLS options are configured with with_tls_options, Auto uses TLS on every port instead: configured TLS options are treated as explicit TLS intent, so they are never silently discarded on non-443 ports.

  • Tcp

    Force plain TCP (no TLS). Use for http:// endpoints.

  • Tls

    Force TLS. Combine with tls.with_* builders for verification settings.

Values

pub fn await_up(
  connection: Connection,
  timeout: Timeout,
) -> Result(Protocol, error.GluegunError)

Wait until a Gun connection is up and return the negotiated protocol.

Call after open and before any request, WebSocket upgrade, or close. Blocks the caller process until Gun reports readiness or timeout elapses. Consumes this connection’s queued gun_up and gun_down lifecycle events. The latest queued event determines readiness: an up followed by a down does not report ready. A latest up can succeed with a zero timeout. Down events during the wait do not restart the timeout budget. The initial queued-mail scan and scheduler delays can add elapsed time.

Readiness reflects received events, not a guarantee that the socket will remain open. Call from the receiving process. Do not combine this blocking helper with an actor receive loop that needs the same lifecycle events.

Call from the process that opened the connection. Gun sends gun_up only to that owner. A different process cannot receive readiness through this function: it can return Timeout while the connection stays alive, or ConnectionDown if the connection process exits during the wait.

Errors:

  • Timeout — Gun did not report ready within timeout.
  • ConnectionDown / ConnectionError — handshake failed.
  • DecodeError — Gun returned an unrecognized protocol atom.
pub fn close(
  connection: Connection,
) -> Result(Nil, error.GluegunError)

Stop a Gun connection through its supervisor.

Gun’s supervisor waits for process exit, with a supervisor shutdown timeout before forced termination. This is not a graceful HTTP drain. It does not flush the caller’s mailbox. Use terminate for a stalled connection or deadline cleanup.

pub fn infinity() -> Timeout

Construct a timeout with no upper bound.

pub fn milliseconds(
  value: Int,
) -> Result(Timeout, error.GluegunError)

Construct a finite timeout.

Accepts 0 through 4_294_967_295 milliseconds, inclusive, as supported by OTP 27. Returns InvalidOptions outside this range; does not clamp. Use infinity() to wait without a limit.

pub fn monitor(connection: Connection) -> process.Monitor

Monitor a Gun process from its receiver.

Compose process.select_specific_monitor with message.select to observe unexpected process exits that emit no gun_down. Only this monitor’s DOWN is selected. Remove it with process.demonitor_process when closing.

pub fn open(
  options: ConnectOptions,
  host host: String,
  port port: Int,
) -> Result(Connection, error.GluegunError)

Open a Gun connection to host:port.

Accepts DNS names, IPv4 text, and IPv6 text with or without brackets. IP literals are passed to Gun as address tuples so IPv6 HTTP authorities have brackets. DNS lookup keeps the supplied name, including a final root dot. Derived TLS SNI omits that dot; explicit SNI settings are unchanged. TLS certificate identity checks remain enabled for DNS names and IPs.

Returns immediately with a Connection handle; the underlying TCP/TLS handshake completes asynchronously. Call await_up before sending any request or WebSocket upgrade.

The calling process is the connection owner. Gun monitors it and stops the connection when it exits, even if another process holds the handle. Passing the handle does not transfer ownership; Gluegun has no owner transfer API. Open long-lived connections in a long-lived process.

Gun sends connection lifecycle messages, including gun_up and gun_down, only to the owner. Stream replies go to the request caller or a configured reply receiver; this does not change the owner.

Errors:

  • InvalidOptions — the protocol list is empty or Gun rejected the options.
  • ErlangError — Gun could not spawn the connection process.
pub fn options() -> ConnectOptions

Construct default connection options.

pub fn retry_count(
  value: Int,
) -> Result(RetryCount, error.GluegunError)

Construct a retry count. Zero disables retries; negative values are invalid.

pub fn shutdown(
  connection: Connection,
) -> Result(Nil, error.GluegunError)

Request graceful shutdown of a Gun connection.

Sends an asynchronous cast. Gun can finish active streams before it exits; this call does not wait for exit and cannot interrupt blocked setup.

pub fn terminate(
  connection: Connection,
) -> Result(Nil, error.GluegunError)

Stop the connection, wait for process exit, then flush its Gun messages.

Use on deadline expiry, including during DNS, connect, or TLS setup. Attempts supervisor shutdown for up to 100 milliseconds, then uses a kill signal if the stop fails or exceeds that allowance. The allowance is separate from the operation’s deadline; waiting for exit and mailbox cleanup can add time. This is not a graceful HTTP drain. Call from the process that receives the connection’s messages. On return, the Gun process cannot send more messages and its queued messages are gone. This does not drain other receiving processes or third-party forwarders. It discards all streams on this connection, not only one stream.

The flush also removes queued Erlang DOWN messages for this connection from the caller’s mailbox, for every monitor reference, including monitors created by application code. Do not wait for those notifications after this call; they are not preserved for separate lifecycle handling.

pub fn with_address_family(
  options: ConnectOptions,
  family family: AddressFamily,
) -> ConnectOptions

Select only IPv4 or only IPv6 for DNS lookup and TCP connection.

TLS uses the same TCP setup. This does not change TLS verification or SNI. With no selection, Gun uses the runtime’s default address family.

pub fn with_connect_timeout(
  options: ConnectOptions,
  timeout timeout: Timeout,
) -> ConnectOptions

Bound socket connection across the resolved addresses in one attempt.

This does not cover DNS lookup or TLS handshake. Use with_domain_lookup_timeout and with_tls_handshake_timeout for those.

pub fn with_domain_lookup_timeout(
  options: ConnectOptions,
  timeout timeout: Timeout,
) -> ConnectOptions

Bound DNS lookup per connection attempt. Gun defaults to no limit.

pub fn with_protocols(
  options: ConnectOptions,
  protocols protocols: List(Protocol),
) -> ConnectOptions

Set HTTP protocol preference ordering for a connection.

TLS advertises the protocols in this order in the ALPN ClientHello. The server selects the protocol and can use its own preference order. With no explicit list, Gun’s default protocols are unchanged.

Plain TCP uses only the first protocol, with no fallback. This also applies when Auto selects TCP. An empty list makes open return InvalidOptions.

pub fn with_retry(
  options: ConnectOptions,
  retry retry: RetryCount,
) -> ConnectOptions

Set Gun’s retry count, including zero to disable retries.

Gun waits five seconds between subsequent retries by default. This count does not set that delay or any setup timeout. Gun resets the count after an established connection disconnects, so a long-lived connection can reconnect for more than this number of cycles. Reconnection does not replay failed HTTP requests or restore WebSockets.

pub fn with_tls_handshake_timeout(
  options: ConnectOptions,
  timeout timeout: Timeout,
) -> ConnectOptions

Bound the TLS handshake per connection attempt. Gun defaults to no limit.

pub fn with_tls_options(
  options: ConnectOptions,
  tls_options tls_options: tls.TlsOptions,
) -> ConnectOptions

Set TLS options for TLS or auto-transport connections.

Configuring TLS options on an Auto-transport connection is treated as explicit TLS intent: the connection uses TLS on every port, not only port 443, so the configured options are never silently dropped in favor of plaintext.

pub fn with_transport(
  options: ConnectOptions,
  transport transport: Transport,
) -> ConnectOptions

Set the transport Gun should use for a connection.

pub fn with_websocket_keepalive(
  options: ConnectOptions,
  interval interval: Timeout,
) -> ConnectOptions

Set the interval between automatic WebSocket pings, in milliseconds.

Gun reads this setting from the original connection options, not the upgrade options. Set it before open, then upgrade with websocket.upgrade_options() without websocket.with_keepalive. Defaults to infinity() (no automatic pings). This does not change connection, upgrade, or frame receive timeouts.

✨ Search Document