Options processing for HTTP.fetch/2 requests.
HTTP.fetch/2 accepts a flat init keyword list or map, mirroring the browser
fetch(input, init) shape. Supported fetch-style options are:
method- nonempty ASCII HTTP method token, defaulting toGET. Common methods normalize to their conventional atoms; other binary methods retain their case, and atom methods are uppercased on the wire. DAV methods such as:propfindand:reportcarry bodies normally. Invalid token bytes reject before network I/O; extension strings are never converted into new atoms.headers- request headers as a list, map, orHTTP.Headersbody- request bodyduplex- request streaming mode;:halfor"half"for streaming bodiessignal-HTTP.AbortControllerPID (nilfor none); any other value raisesArgumentErrorredirect-:follow,:manual, or:error; defaults to:follow
Unknown option keys raise ArgumentError.
The socket transport also accepts Elixir-specific extensions:
telemetry- emit request and stream telemetry; defaults totrue. Shared pool/connection counters require the global opt-out inHTTP.Telemetry.decode_body- decode response Content-Encoding; defaults totrue. Setfalseto preserve stored entity bytes for buffered and streamed HTTP/1, HTTP/2, and HTTP/3 responses without changing headers.max_decoded_body_size- maximum decoded size in bytes of a response body whose Content-Encoding is decoded, as a positive integer or:infinity. Defaults toHTTP.Config.max_decoded_body_size/0(50,000,000 bytes). Inflation is incremental, so a compression bomb fails with{:error, :decoded_body_too_large}(buffered) or a stream error with that reason (streamed) before the expansion is held in memory. Bodies that are not decoded (decode_body: false, identity or unknown encodings) are not limited.stream_response- settrueto resolve at final response headers and expose an acknowledged body stream, even for small Content-Length bodies. Defaults tofalse(automatic size/framing policy). HEAD and bodyless statuses remain buffered empty responses. The request timeout still bounds the entire response; callers can observe headers before applying a body deadline.request_mode-:fetch(default) or:proxy; proxy mode retains request entities for all admitted methods, including GET, DELETE, and HEAD, and adds no defaultUser-Agent(a caller-supplied one is sent unchanged)content_type- convenience Content-Type value for request bodiestimeout- request timeout in non-negative milliseconds or:infinity(HTTP/1, HTTP/2 and HTTP/3); other values raiseArgumentErrorerror_mode-:raw(default) or:structured; structured failures returnHTTP.RequestErrorwith conservative pre-send evidence. Retry classification uses the raw reason; only the final failure is wrapped.retry-false(default, one attempt),:transient,:safe_transientor a 2-arity function(request, response_or_error) -> boolean; string values"transient"and"safe_transient"are also accepted. See "Retries" inHTTP.fetch/2. Rejected withtransport_scope.max_retries- additional attempts as a non-negative integer; defaults to 3retry_delay- non-negative milliseconds, or a 1-arity function of the 1-based number of the attempt being retried; defaults to exponential 500 ms doubling up to 10,000 ms.Retry-Afteron 429/503 takes precedence.read_idle_timeout- positive milliseconds (1..4,294,967,295), ornilto disable (default). Bounds each pending HTTP/1 transport read, including headers; nonempty transport data resets the clock. Consumer acknowledgement backpressure pauses reads and this clock. Writes do not reset it.write_idle_timeout- positive milliseconds (same range), ornilto disable (default). Bounds each at-most-16KiB HTTP/1 transport write; each successful nonempty send starts a fresh write budget. This is transport acceptance, not peer acknowledgement or a partial-syscall progress guarantee. Waiting for an upload source does not consume a write budget. Shorter existingsocket_opts[:send_timeout]and overall request limits still apply. Both idle options support ordinary HTTP/1 TCP and ExSSL TLS, including HTTP/1 reuse. They requirehttp_version: :http1(the default); automatic/H2/H3 protocols and managedtransport_scopeare rejected. Timeouts report:read_idle_timeout/:write_idle_timeout(orHTTP.RequestErrorin structured mode before response headers). Neither changes connection or overall request deadlines or the cleanup completion contract.connect_timeout- connection timeout in non-negative milliseconds or:infinity; other values raiseArgumentErrorresponse_stream_idle_timeout- ordinary HTTP/1 response-stream inactivity in positive milliseconds (1..4,294,967,295), or:infinityto disable the network-wait clock.nil(default) retains the global streaming timeout. Consumer acknowledgement waits use the separate ACK policy below. Convenience body readers use the same stream policy. Other protocols and managedtransport_scopereject explicit policies.response_stream_ack_timeout- ordinary HTTP/1 response chunk delivery and consumer acknowledgement budget in positive milliseconds (1..4,294,967,295), or:infinity.nil(default) retains the global streaming timeout. This covers a buffered chunk awaiting a reader and a delivered chunk awaiting acknowledgement. It does not change network idle, overall request deadlines, cancellation or reader-death cleanup. Other protocols and managedtransport_scopereject explicit policies.adapter- a module or{module, config}implementingHTTP.Adapter. Context is prepared in the caller and executed in the Promise worker.pool- a namedHTTP.Runtime.Poolfamily or opaqueHTTP.Poolreference. Explicit selection binds one generation and rejects incompatible reuse/protocol options.transport_scope- opaqueHTTP.ManagedTransportgeneration selecting private reusable HTTP/1 or HTTP/2 transports. Requires raw streamed responses, manual/error redirects, and the origin/policy frozen byopen/1.connect_address- caller-validated literal IPv4/IPv6 tuple to dial instead of resolving the URL hostname. Keeps original HTTP authority, TLS SNI and certificate hostname verification. No DNS/address fallback or request replay. Requiresredirect: :manualor:error; validate every permitted redirect hop independently and provide that hop's pin. HTTP/3, Unix sockets and proxies are unsupported. Pools isolate each pin from DNS and other targets. Cancellation and request/connect deadlines cover establishment. Conflicting TLS SNI rejects before I/O; native verification and trust defaults remain. With:ex_ssl, a literal-IP HTTPS URL must match the pin, since a distinct original IP verification identity is currently unsupported.http_version- protocol selection, one of:http1,:http2,:http3,:h2c, or:auto; defaults to:http1alt_svc- opt in to RFC 7838 Alt-Svc HTTP/3 discovery; defaults tofalseand requireshttp_version: :auto(other versions raiseArgumentError). Finalhttpsresponses carryingAlt-Svcupdate a bounded per-origin cache of same-hosth3alternatives (madefaults to 86,400 s;clearremoves the origin). A later eligiblehttpsrequest with a fresh entry uses HTTP/3 on the alternative UDP port, keeping the origin authority, SNI and certificate identity. Requests with a proxy, Unix socket,connect_address,socket_opts,http2_profile,transport_scopeor explicitpoolnever use the alternative. If the QUIC connection is never established ({:http3_not_established, _}or:opening_timeout), the request runs on the normal:autoH2/HTTP/1.1 path within the original deadline and the origin is marked broken for five minutes. Failures after the connection is established are returned without replay. Redirect hops re-select per origin;response.http_versionreports the actual protocol.prefer_ipv6- Prefer IPv6 with IPv4 fallback only during TCP establishment. Explicitconnect_addresspins and:inet/:inet6socket options remain strict. For a proxy route this policy selects the proxy endpoint address family.response_header_limits- Request-local HTTP/1 and CONNECT budgets; seeHTTP.ResponseHeaderLimits. Also applies to informational and redirect heads.ssl- TLS options passed to theex_sslTLS enginesocket_opts- socket options passed to the underlying transportunix_socket- Unix Domain Socket pathhttp1_reuse- opt in to HTTP/1 keep-alive; requireshttp_version: :http1. Only fully consumed, self-delimited responses are reusable. Failed or cancelled requests are closed, and requests are never retried on stale peers unless theretrypolicy classifies the failure as retryable.http1_scope- optional atom or string separating caller routes sharing an origin.http1_pool_size- retained idle sockets per route/policy, 1..16 (default 2).http1_idle_timeout- idle retention in milliseconds, 1..60,000 (default 30,000). All callers share a maximum of 256 idle sockets. TLS identities, socket options, isolation scope and route policies are part of the reuse key; opaque callbacks disable reuse. HTTP/1 reuse defaults tofalse.proxy- explicit proxy{:http, host, port, opts}or{:https, host, port, opts}. Options areheaders: [{"Proxy-Authorization", value}]and a finite positivetimeout. HTTP/1 cleartext uses absolute-form forwarding; HTTPS uses CONNECT and then origin TLS/ALPN. H2 over HTTPS and ExSSL IP-origin tunnels are supported; H2c, HTTP/3 and Unix socket proxy routes are rejected explicitly. Environment/NO_PROXY selection belongs to the caller. HTTPS proxies support HTTP/1 forwarding to HTTP origins and CONNECT tunnels to HTTPS origins. Proxysslsettings verify the proxy independently from originsslsettings. Proxy scheme, endpoint, credentials and both TLS policies isolate pools.http2_profile- versioned HTTP/2 wire profile (only used by HTTP/2)http2_reuse- whether an HTTP/2 connection may be reused; defaults totruehttp2_unprocessed_retry- whether a non-streamed HTTP/2 request the server provably did not process is replayed; defaults totrue. RFC 9113 §8.7 treats a stream above a GOAWAY last-stream-id, a stream reset withREFUSED_STREAM, and an open refused by a draining pooled connection as unprocessed. By default such a request moves to another connection under the same deadline, at most three connections per redirect hop, and each move emits[:http_fetch, :request, :retry]withsource: :http2_unprocessed(seeHTTP.Telemetry). Withfalsethe first such failure is returned exactly as when those attempts are exhausted:{:goaway, last_stream_id, error_code, :unprocessed},{:stream_reset, :refused_stream}or:draining(wrapped byerror_mode: :structured). Applies to pooled and exclusive (http2_reuse: false) HTTP/2 connections,:auto-negotiated h2, explicitpool:andtransport_scoperequests. Streamed (duplex: "half") bodies are never replayed either way. It has no effect on HTTP/1.1, on HTTP/3 (whose transfer rule is separate), or with anadapter:. It is independent ofretry:, which may still retry the returned failure under its own policy.http3_profile- QUIC wire profile; defaults to:orderedhttp3_reuse- whether an HTTP/3 connection may be reused; defaults totruehttp3_resumption- beta opt-in QUIC session resumption for HTTP/3; defaults tofalse. New connections dial through a runtime-owned endpoint whose bounded ticket store is partitioned by origin, dialed port, TLS trust and reference identity, QUIC profile and 0-RTT policy. HTTP/3 responses then carryresponse.http3 == %{resumed: boolean, early_data: boolean}.early_data- beta per-request QUIC 0-RTT; defaults tofalse. Only GET, HEAD and OPTIONS without a body may set it (others raiseArgumentError). It takes effect only withhttp3_resumption: true, a ticket that allows 0-RTT and remembered peer HTTP/3 SETTINGS; otherwise the request is sent after the handshake. A request whose 0-RTT is rejected is re-sent once after the handshake, and a425 Too Earlyresponse to a request carried in 0-RTT is retried once after the handshake (RFC 8470). Seedocs/http3-fetch-contract.md.http2_scope- non-sensitive caller isolation scopehttp2_priority- per-request HTTP/2 priority metadata
Summary
Functions
Extracts body from options.
Extracts content type from options.
Extracts the request body streaming mode from options.
Extracts headers from options.
Extracts the HTTP method from options.
Creates a new FetchOptions struct from a flat map, keyword list, or existing FetchOptions struct.
Converts fetch init options to the internal socket transport option list.
Types
@type http_version() :: :http1 | :http2 | :http3 | :h2c | :auto
@type redirect() :: :follow | :manual | :error
@type t() :: %HTTP.FetchOptions{ adapter: module() | {module(), term()} | nil, alt_svc: boolean(), body: any(), connect_address: :inet.ip_address() | nil, connect_timeout: timeout() | nil, content_type: String.t() | nil, decode_body: boolean(), duplex: :half | nil, early_data: boolean(), error_mode: :raw | :structured, headers: HTTP.Headers.t(), http1_idle_timeout: pos_integer(), http1_pool_size: pos_integer(), http1_reuse: boolean(), http1_scope: atom() | String.t() | nil, http2_priority: map() | keyword() | nil, http2_profile: atom() | String.t() | map() | nil, http2_reuse: boolean(), http2_scope: atom() | String.t() | nil, http2_unprocessed_retry: boolean(), http3_profile: atom() | map() | nil, http3_resumption: boolean(), http3_reuse: boolean(), http_version: http_version(), max_decoded_body_size: pos_integer() | :infinity | nil, max_retries: non_neg_integer(), method: HTTP.Request.method(), pool: term(), prefer_ipv6: boolean(), proxy: {:http | :https, String.t(), :inet.port_number(), keyword()} | nil, read_idle_timeout: pos_integer() | nil, redirect: redirect(), request_mode: HTTP.Request.request_mode(), response_header_limits: map() | nil, response_stream_ack_timeout: pos_integer() | :infinity | nil, response_stream_idle_timeout: pos_integer() | :infinity | nil, retry: false | HTTP.Retry.mode(), retry_delay: non_neg_integer() | (pos_integer() -> non_neg_integer()) | nil, signal: any() | nil, socket_opts: list() | nil, ssl: list() | nil, stream_response: boolean(), telemetry: boolean(), timeout: timeout() | nil, transport_scope: term(), unix_socket: String.t() | nil, write_idle_timeout: pos_integer() | nil }
Functions
Extracts body from options.
Extracts content type from options.
@spec get_duplex(t()) :: :half | nil
Extracts the request body streaming mode from options.
@spec get_headers(t()) :: HTTP.Headers.t()
Extracts headers from options.
@spec get_method(t()) :: HTTP.Request.method()
Extracts the HTTP method from options.
Creates a new FetchOptions struct from a flat map, keyword list, or existing FetchOptions struct.
Converts fetch init options to the internal socket transport option list.