From 8c08056e912f08f6a642e8a4b2cc3115791f78f5 Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 20 Nov 2026 00:16:17 +0100 Subject: [PATCH 1/3] Bump quic to 3.2.0, h2 to 0.18.3 and webtransport to 0.5.12 Also moves the cowboy test dependency to 2.21.0. --- rebar.config | 8 ++++---- rebar.lock | 18 +++++++++--------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/rebar.config b/rebar.config index a6531d1a..108c8ea6 100644 --- a/rebar.config +++ b/rebar.config @@ -53,11 +53,11 @@ {deps, [ %% Pure Erlang QUIC + HTTP/3 stack - {quic, "~>3.1.0"}, + {quic, "~>3.2.0"}, %% Pure Erlang HTTP/2 stack - {h2, "~>0.18.0"}, + {h2, "~>0.18.3"}, %% WebTransport client (HTTP/3 and HTTP/2) - powers the wt_* API - {webtransport, "~>0.5.11"}, + {webtransport, "~>0.5.12"}, {idna, "~>8.0.0"}, {mimerl, "~>1.5"}, {certifi, "~>2.19.0"}, @@ -66,7 +66,7 @@ ]}. {profiles, [{test, [ - {deps, [{cowboy, "2.20.0"}, {jsx, "3.1.0"}]}, + {deps, [{cowboy, "2.21.0"}, {jsx, "3.1.0"}]}, %% rebar3 can't parse cowboy 2.13+ Elixir-style ">= X and < Y" %% reqs for cowlib/ranch; override with bare names so rebar3 %% resolves them itself (rebar3#2364). diff --git a/rebar.lock b/rebar.lock index 73991732..d96579f6 100644 --- a/rebar.lock +++ b/rebar.lock @@ -1,29 +1,29 @@ {"1.2.0", [{<<"certifi">>,{pkg,<<"certifi">>,<<"2.19.0">>},0}, - {<<"h2">>,{pkg,<<"h2">>,<<"0.18.0">>},0}, + {<<"h2">>,{pkg,<<"h2">>,<<"0.18.3">>},0}, {<<"idna">>,{pkg,<<"idna">>,<<"8.0.0">>},0}, {<<"mimerl">>,{pkg,<<"mimerl">>,<<"1.5.0">>},0}, {<<"parse_trans">>,{pkg,<<"parse_trans">>,<<"3.4.2">>},0}, - {<<"quic">>,{pkg,<<"quic">>,<<"3.1.0">>},0}, + {<<"quic">>,{pkg,<<"quic">>,<<"3.2.0">>},0}, {<<"ssl_verify_fun">>,{pkg,<<"ssl_verify_fun">>,<<"1.1.9">>},0}, - {<<"webtransport">>,{pkg,<<"webtransport">>,<<"0.5.11">>},0}]}. + {<<"webtransport">>,{pkg,<<"webtransport">>,<<"0.5.12">>},0}]}. [ {pkg_hash,[ {<<"certifi">>, <<"B3965751ECB7D7BF1D6E86AC26236FA338A606CB8E441CA8C77CD839296E0883">>}, - {<<"h2">>, <<"1F6B488556E7410B1B341517B720B67E39D0279D73FDCA71EFC8D4B6C9CD20FA">>}, + {<<"h2">>, <<"0F91CE547CA1CF38486E344F8D7B7195231A7A8D997A8C939427DDF520987524">>}, {<<"idna">>, <<"BB8795A18AADCE07DCE6A3928C4FCAE74AC66EAF95186B46EA11598BCCC719F9">>}, {<<"mimerl">>, <<"F35ACA6F23242339B3666E0AC0702379E362B469D0AEA167F6CC713547E777ED">>}, {<<"parse_trans">>, <<"C352DDC1A0D5E54F9B1654D45F9C432EEF76F9CEA371C55DDFF769EF688FDB74">>}, - {<<"quic">>, <<"BE5811BD1199906EA4C6D54DC8C115A5EC97DF9D469085F179B2F299E734529C">>}, + {<<"quic">>, <<"B3F66B10B6E946F8AA4F0BCBB812A195BBFA02394D57D81418C9261FE4A9B844">>}, {<<"ssl_verify_fun">>, <<"4FF292DC16E728FDE1235CF5FA6BCD3CA01864004526F71A4A70935509D1A7F1">>}, - {<<"webtransport">>, <<"8B9D05C44805E66DFF23F19056F7AF70700A664F1872AA098E0DCEC634CADBE3">>}]}, + {<<"webtransport">>, <<"3BE744C549A7C2E60ECC6B1E3631C11CF4FF2869E7B01BCE9DABE9DB7B160C6F">>}]}, {pkg_hash_ext,[ {<<"certifi">>, <<"7BAC57B76EAE5C4B576D4A61A4FD083D186BA7F7918EE2C2B42CB02095E366A8">>}, - {<<"h2">>, <<"11824E2963716B1DF80A1F2C6C1EB31E67BF2176931E6FBC74C362E0F872539A">>}, + {<<"h2">>, <<"CC53D7A6CB67DCCA975DBAAA0B41C190677E77808A6748D11810CC1D76320E0F">>}, {<<"idna">>, <<"E0C5CE7846F14515AF66142A55B8097D5F46D10DF9235E781F168BEF5622BCF9">>}, {<<"mimerl">>, <<"DB648CE065BAE14EA84CA8B5DD123F42F49417CEF693541110BF6F9E9BE9ECC4">>}, {<<"parse_trans">>, <<"4C25347DE3B7C35732D32E69AB43D1CEEE0BEAE3F3B3ADE1B59CBD3DD224D9CA">>}, - {<<"quic">>, <<"3F70147CDC6C5BB3DF2C08D4C04C7263620D59069FA5A38FF7D946451F13B265">>}, + {<<"quic">>, <<"A82C28AFEFAAEDAEEC1F59ED400CEF0746F94C11A91F3A8DFC7F4EC260B43481">>}, {<<"ssl_verify_fun">>, <<"19F24AD715EF6255D530B2F0DB8B2D2191AE435B6527234E943F523E84ED0895">>}, - {<<"webtransport">>, <<"B4C4A9C3CA0B8EB77F7D86BFE1B89FD0619C7F6B07F9533FDA85E019C04DAB19">>}]} + {<<"webtransport">>, <<"0791420E8F80E8E0112BCC2FCDDD91B121796DDFD031FFB59A42F812382A24AD">>}]} ]. From c01b1320b7d41562634adf847dfc7a451c428c5d Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 20 Nov 2026 00:28:04 +0100 Subject: [PATCH 2/3] Fix the design guide and add a code map The design guide described hackney 3.x: it said TLS connections are never pooled, showed HTTP/2 code from modules that no longer exist and drew a state machine that hackney_conn does not have. It now matches the code. A new Where Things Live page maps each concept to its modules and tests, CONTRIBUTING says where to start for common changes, and the stale TODO is gone. --- CONTRIBUTING.md | 17 +++ DEVELOPMENT.md | 2 +- README.md | 20 ++-- TODO.md | 4 - guides/code_map.md | 66 ++++++++++++ guides/design.md | 236 +++++++++++++++++------------------------- guides/http3_guide.md | 8 +- rebar.config | 1 + src/hackney_conn.erl | 5 +- 9 files changed, 202 insertions(+), 157 deletions(-) delete mode 100644 TODO.md create mode 100644 guides/code_map.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d5100b85..99d1a596 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,6 +87,23 @@ rebar3 eunit --verbose rebar3 dialyzer ``` +## Finding Your Way + +[Where Things Live](guides/code_map.md) maps each concept to its modules and +tests. The table below tells you where to start for common changes. + +| If you want to | Start in | Check with | +|----------------|----------|------------| +| Add a request option | `src/hackney.erl`, then `src/hackney_conn.erl` | `hackney_integration_tests`, plus the HTTP/2 and HTTP/3 tests if the option applies there | +| Change pool or checkout behaviour | `src/hackney_pool.erl`, `src/hackney_load_regulation.erl` | `hackney_pool_tests` and the fault and chaos suites in [DEVELOPMENT.md](DEVELOPMENT.md) | +| Change HTTP/2 or HTTP/3 behaviour | `src/hackney_conn.erl`, `src/hackney_h3.erl`. Check first whether the fix belongs in the `h2` or `quic` dependency | `hackney_http2_*_tests`, `hackney_http3_*_tests`, `hackney_h3_*_tests` | +| Change the HTTP/1.1 parser | `src/hackney_http.erl` | `hackney_http_tests`, `hackney_header_limits_tests`, `hackney_chunk_limit_tests` | +| Add a proxy type or transport | `src/hackney_http_connect.erl`, `src/hackney_socks5.erl`, `src/hackney_tcp.erl` | `hackney_proxy_tests`, `hackney_socks5_tests` | +| Add a function to the public API | `src/hackney.erl` | A test in `test/`, and the matching guide in `guides/` | +| Bump a dependency | `rebar.config`, then `rebar3 upgrade --all` | `rebar3 eunit`, `rebar3 xref`, `rebar3 dialyzer` | + +Put tests in `test/`. Do not export functions from `src/` only for tests. + ## Code Style - Follow existing code conventions diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 7359020a..0eac05aa 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -204,7 +204,7 @@ Types: `fix`, `feat`, `docs`, `test`, `refactor`, `ci`, `chore` ## Continuous Integration CI runs on: -- Linux x86_64 (OTP 27.2, 28.0) +- Linux x86_64 (OTP 27.2, 28.0, 29.0) - Linux ARM64 (OTP 27.2) - macOS ARM64 (OTP 27) - FreeBSD 14.2 (OTP 28) diff --git a/README.md b/README.md index 65d55e1b..e77c231f 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,8 @@ Payload = <<"{\"key\": \"value\"}">>, | [WebSocket Guide](guides/websocket_guide.md) | Connect, send, receive, active mode | | [WebTransport Guide](guides/webtransport_guide.md) | Streams, datagrams, multiplexing, server handlers | | [Design Guide](guides/design.md) | Architecture, pooling, load regulation internals | -| [Migration Guide](guides/MIGRATION.md) | Upgrading from hackney 1.x | +| [Where Things Live](guides/code_map.md) | Which modules and tests implement each concept | +| [Migration Guide](guides/MIGRATION.md) | Upgrading from hackney 1.x and 2.x | | [API Reference](https://hexdocs.pm/hackney) | Full module documentation | | [Changelog](NEWS.md) | Version history | @@ -307,15 +308,14 @@ This applies to HTTP/1.1, HTTP/2 and HTTP/3. ## Modules -| Module | Purpose | -|--------|---------| -| `hackney` | Main API - requests, connections, WebSocket | -| `hackney_pool` | Connection pool management | -| `hackney_url` | URL parsing and encoding | -| `hackney_headers` | Header manipulation | -| `hackney_multipart` | Multipart encoding | -| `hackney_cookie` | Cookie parsing | -| `hackney_http` | HTTP protocol parser | +You call `hackney` for requests, WebSocket (`ws_*`), WebTransport (`wt_*`) and +HTTP/2 streams (`h2_*`), and `hackney_pool` to configure pools. `hackney_url`, +`hackney_headers`, `hackney_multipart` and `hackney_cookie` are helpers you can +use on their own. + +If you want to change hackney itself, start with +[Where Things Live](guides/code_map.md): it maps each concept to its modules +and tests. ## Requirements diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 0e68c3b1..00000000 --- a/TODO.md +++ /dev/null @@ -1,4 +0,0 @@ -# TODO - -Future: -- SOCKS5 and HTTP CONNECT proxy support diff --git a/guides/code_map.md b/guides/code_map.md new file mode 100644 index 00000000..35b83cc8 --- /dev/null +++ b/guides/code_map.md @@ -0,0 +1,66 @@ +# Where Things Live + +This page maps each part of hackney to the modules that implement it and the +tests that cover it. Use it when you want to change hackney or follow a bug +into the source: find the concept, open the module, run the tests listed next +to it. For how the parts work together, read the [Design Guide](design.md) +first. + +## How a request travels + +1. `hackney:request/5` (`src/hackney.erl`) parses the URL and options, runs + the middleware chain, and asks for a connection. +2. `hackney_load_regulation` takes a per-host slot, then `hackney_pool` hands + out a connection process. +3. `hackney_conn` owns the socket. It sends the request and reads the response + for HTTP/1.1 itself, through the `h2` dependency for HTTP/2, and through + `hackney_h3` and the `quic` dependency for HTTP/3. +4. When the response is read, an HTTP/1.1 connection goes back to the pool or + closes. HTTP/2 and HTTP/3 connections stay registered in the pool and are + shared by every caller for that host. + +## Map + +Source modules are in `src/`. Test modules are in `test/` and end in `_tests`, +so `hackney_pool` below means `test/hackney_pool_tests.erl`. + +| Concept | Modules | Tests | +|---------|---------|-------| +| Public API | `hackney` | `hackney_integration`, `hackney_query`, `hackney_redirect`, `hackney_send_request` | +| Connection process | `hackney_conn`, `hackney_conn_sup` | `hackney_conn`, `hackney_direct_owner`, `hackney_close_hang`, `hackney_recv_timeout` | +| Pool and concurrency | `hackney_pool`, `hackney_load_regulation`, `hackney_keepalive` | `hackney_pool`, `hackney_pool_fault`, `hackney_pool_h2h3_fault`, `hackney_pool_chaos`, `hackney_pool_safety`, `hackney_load_regulation` | +| HTTP/1.1 wire format | `hackney_http`, `hackney_headers`, `hackney_multipart`, `hackney_cookie`, `hackney_deflate` | `hackney_http`, `hackney_header_limits`, `hackney_chunk_limit`, `hackney_max_body_size`, `hackney_multipart` | +| HTTP/2 | `hackney_conn` (functions prefixed `h2_`), `hackney_h2_stream` | `hackney_http2_*`, `hackney_h2_bidi` | +| HTTP/3 | `hackney_h3`, `hackney_altsvc`, `hackney_conn` (functions prefixed `h3_`) | `hackney_http3_*`, `hackney_h3_*`, `hackney_altsvc`, `hackney_pool_h3` | +| TLS | `hackney_ssl`, `hackney_ssl_certificate` | `hackney_ssl`, `hackney_ssl_alpn`, `hackney_insecure`, `hackney_tls_resumption_race` | +| Connecting | `hackney_happy`, `hackney_tcp`, `hackney_local_tcp`, `hackney_cidr` | `hackney_happy`, `hackney_connect_race`, `hackney_pool_unix_socket` | +| Proxies | `hackney_http_connect`, `hackney_socks5` | `hackney_proxy`, `hackney_https_proxy`, `hackney_http_connect`, `hackney_socks5` | +| WebSocket | `hackney_ws`, `hackney_ws_proto` | `hackney_ws`, `hackney_ws_proto` | +| WebTransport | `hackney_wt` | `hackney_wt` | +| Middleware | `hackney_middleware` | `hackney_middleware`, `hackney_middleware_integration` | +| URLs and helpers | `hackney_url`, `hackney_bstr`, `hackney_date`, `hackney_util`, `hackney_trace` | `hackney_url`, `hackney_bstr`, `hackney_date`, `hackney_util`, `hackney_trace` | + +Run one test module with: + +```sh +rebar3 eunit --module=hackney_pool_tests +``` + +## What is public and what is internal + +You can rely on `hackney`, `hackney_pool`, `hackney_url`, `hackney_headers`, +`hackney_multipart`, `hackney_cookie` and the `hackney_middleware` behaviour. +The other modules are internal and can change between releases. + +## Notes + +- `hackney_conn` is the largest module. Its states are separated by `State:` + banner comments; the HTTP/2 and HTTP/3 code is in functions prefixed `h2_` + and `h3_`. Read the state machine section of the Design Guide before + changing it. +- HTTP/2 framing, QUIC and WebTransport are not implemented here. They come + from the `h2`, `quic` and `webtransport` dependencies. If a bug is in + framing or flow control, it probably belongs there. +- `test/` also holds test servers (`hackney_h3_test_server`, + `mock_proxy_server`), the fault harness described in the Development guide, + and reproduction harnesses (`repro_h1_hang`, `repro_h2_hang`). diff --git a/guides/design.md b/guides/design.md index 82e315d1..204d77b6 100644 --- a/guides/design.md +++ b/guides/design.md @@ -1,6 +1,6 @@ # Hackney Architecture -This document describes the internal architecture of hackney 3.x, including the process-per-connection model, connection pooling, load regulation, and SSL handling. +This document describes the internal architecture of hackney: the process-per-connection model, connection pooling, load regulation, and TLS handling. Read it when you need to understand why a request behaves as it does, or before you change the connection or the pool. To find the module and the tests behind a concept, see [Where Things Live](code_map.md). ## Overview @@ -13,17 +13,20 @@ Hackney uses a **process-per-connection** architecture where each HTTP connectio ``` hackney_sup -├── hackney_manager (connection registry) +├── hackney_manager (kept for the get_state/1 and +│ async_response_pid/1 accessors) ├── hackney_conn_sup (connection supervisor) -│ └── hackney_conn [1..N] (connection processes for HTTP/1.1, HTTP/2) -├── hackney_pools_sup (pool supervisor) -│ └── hackney_pool [1..N] (pool processes) -└── hackney_altsvc (Alt-Svc cache for HTTP/3 discovery) - -QUIC connections (HTTP/3): -└── hackney_h3.erl (HTTP/3 high-level + adapter over quic_h3) +│ └── hackney_conn [1..N] (one process per connection, any protocol) +└── hackney_pool [1..N] (one process per pool, started on demand) ``` +Three things are not processes of their own. The Alt-Svc cache +(`hackney_altsvc`) and the per-host counters (`hackney_load_regulation`) are +ETS tables. HTTP/2 and HTTP/3 are provided by the `h2` and `quic` +dependencies: a `hackney_conn` process owns an `h2_connection` process, or a +QUIC connection reached through `hackney_h3`, and translates their events for +the caller. + ## Connection Process (hackney_conn) Each connection is a `gen_statem` process that manages: @@ -35,59 +38,33 @@ Each connection is a `gen_statem` process that manages: ### State Machine +`hackney_conn` has nine states. Each is a function of the same name in +`src/hackney_conn.erl`, under a `State:` banner comment. + +| State | Meaning | Leaves to | +|-------|---------|-----------| +| `idle` | Process started, not connected. `connect` dials from here and moves straight to `connected` | `connected`, `closed` | +| `connecting` | Reserved for a handshake in progress. Nothing enters it today | | +| `connected` | Ready for a request | `sending`, `streaming_body`, `closed` | +| `sending` | Writing a request that has its whole body | `receiving`, `closed` | +| `streaming_body` | The caller sends the request body in chunks | `receiving`, `connected`, `closed` | +| `receiving` | Waiting for, or reading, the response | `connected`, `streaming`, `streaming_once`, `closed` | +| `streaming` | Async response, chunks pushed to the caller (`async = true`) | `streaming_once`, `receiving`, `connected`, `closed` | +| `streaming_once` | Async response, one chunk per `stream_next/1` (`async = once`) | `streaming`, `receiving`, `connected`, `closed` | +| `closed` | Connection terminated | `connected` (reconnect), exit | + +An HTTP/1.1 request walks through these states one at a time: + ``` - ┌─────────────┐ - │ created │ - └──────┬──────┘ - │ connect - ▼ - ┌─────────────┐ - ┌─────│ connected │─────┐ - │ └─────────────┘ │ - │ │ │ - send_request │ upgrade_to_ssl - │ │ │ - ▼ │ ▼ - ┌────────────┐ │ ┌────────────┐ - │ on_body │ │ │ connected │ (SSL) - └─────┬──────┘ │ └────────────┘ - │ │ - finish_send_body │ - │ │ - ▼ │ - ┌─────────────────┐ │ - │ waiting_response│ │ - └────────┬────────┘ │ - │ │ - start_response │ - │ │ - ▼ │ - ┌────────────┐ │ - │ on_status │ │ - └─────┬──────┘ │ - │ │ - ▼ │ - ┌────────────┐ │ - │ on_headers │───────┤ - └─────┬──────┘ │ - │ │ - ▼ │ - ┌──────────────┐ │ - │ on_resp_body │ │ - └───────┬──────┘ │ - │ │ - │ body done │ - └──────────────┘ - │ - ▼ - ┌────────────┐ - │ closing │ - └─────┬──────┘ - │ - ▼ - [exit] +idle -> connected -> sending -> receiving -> connected + \-> streaming_body -/ \-> streaming | streaming_once ``` +An HTTP/2 or HTTP/3 connection stays in `connected` while it serves requests. +Each request is a stream, tracked in the `h2_streams` or `h3_streams` map, so +several callers use the connection at the same time. This is why `connected` +is by far the largest state in the module. + ### Owner Monitoring The connection process monitors its owner: the process that checked out the connection, or for a connection opened without a pool, the process that opened it (with `stream_to`, the `stream_to` process once the async request starts). If the owner crashes, the connection terminates automatically, preventing socket leaks. An HTTP/1.1 read waiting on the server checks for this every second. `hackney_conn:set_owner/2` moves ownership to another process. @@ -101,29 +78,49 @@ MonitorRef = monitor(process, Owner), ## Connection Pool (hackney_pool) -The pool stores **TCP connections only** for reuse. SSL connections are never pooled for security reasons (they close after use). +The pool keeps three kinds of connection, and treats them differently: + +| Kind | How it is used | Kept after a request | +|------|----------------|----------------------| +| HTTP/1.1 over TCP | Checked out by one caller at a time | Yes, as an idle connection | +| HTTP/1.1 over TLS | Checked out by one caller at a time | Only with `ssl_pooling`, otherwise closed | +| HTTP/2 and HTTP/3 | Shared: every caller for the host uses the same connection | Yes, until idle or closed by the server | + +### TLS Connections -### Why TCP-Only Pooling? +By default the pool stores TCP connections only. An HTTPS request takes a TCP +connection, upgrades it to TLS, and closes it when the request is done, so +every HTTPS/1.1 request does a fresh handshake. -1. **Security** - SSL session state should not be shared across requests -2. **Simplicity** - No need to validate SSL session freshness -3. **Flexibility** - TCP connections can be upgraded to SSL when needed +With `{ssl_pooling, true}` (request option or application env), an upgraded +HTTPS/1.1 connection goes back to the pool. It is only handed to a later +request whose effective TLS options hash to the same key, so a connection +verified against one CA or SNI is never reused for another. ### Pool State ```erlang -record(state, { name, %% Pool name - max_connections, %% Global max (legacy, per-host preferred) + max_connections, %% Warm (idle) connections kept for reuse keepalive_timeout, %% Max idle time (default 2000ms, max 2000ms) prewarm_count, %% Connections to maintain per host (default 4) - available = #{}, %% #{Key => [Pid]} - idle TCP connections + available = #{}, %% #{Key => [Pid]} - idle connections in_use = #{}, %% #{Pid => Key} - checked out connections + dialing = #{}, %% Handed out undialed, the requester is dialing pid_monitors = #{}, %% #{Pid => MonitorRef} - activated_hosts %% Hosts with prewarm enabled + activated_hosts, %% Hosts with prewarm enabled + sock_opts = #{}, %% connect_options per socket options bucket + h2_connections = #{}, %% #{Key => Pid} - one shared connection per host + h3_connections = #{}, %% #{Key => Pid} - one shared connection per host + h3_sessions = #{} %% HTTP/3 session tickets for resumption }). ``` +The pool process never dials. It starts the connection process and hands it +out; the requester dials it and reports the result. A slow or failing connect +therefore blocks one caller, not the pool. + ### Pool Operations **Checkout**: Get an available TCP connection or `none` @@ -135,7 +132,7 @@ hackney_pool:checkout(Host, Port, Transport, Opts) **Checkin**: Return a connection to the pool ```erlang hackney_pool:checkin(PoolInfo, Pid) -%% TCP connections are stored, SSL connections are closed +%% TCP connections are stored; TLS connections only with ssl_pooling ``` ### Keepalive Timeout @@ -195,36 +192,28 @@ HTTPS requests use **TCP connection upgrade** rather than direct SSL connections ``` 1. Get TCP connection (from pool or new) 2. Upgrade to SSL in-place: ssl:connect(Socket, SslOpts) -3. Use SSL connection for request -4. Close connection (SSL connections not pooled) -5. Trigger TCP prewarm for next HTTPS request +3. If ALPN negotiated HTTP/2, register the connection as shared +4. Use the connection for the request +5. HTTP/1.1: close it at checkin, or return it to the pool with ssl_pooling +6. Trigger TCP prewarm for the next HTTPS request ``` ### Benefits - **Connection reuse** - Pooled TCP connections can serve HTTP or HTTPS - **Prewarm works for HTTPS** - TCP connections ready to upgrade -- **Security** - SSL state never shared between requests +- **One connect path** - Proxies, happy eyeballs and socket options apply the same way to HTTP and HTTPS ### Code Flow -```erlang -%% In hackney.erl -connect_pool(Host, Port, Transport, Opts) -> - %% Always checkout as TCP - case hackney_pool:checkout(Host, Port, hackney_tcp, Opts) of - {ok, PoolInfo, Pid} -> - %% Upgrade if HTTPS - case Transport of - hackney_ssl -> - ok = hackney_conn:upgrade_to_ssl(Pid, SslOpts), - {ok, PoolInfo, Pid}; - _ -> - {ok, PoolInfo, Pid} - end; - ... - end. -``` +The flow lives in `connect_pool_new/6` in `src/hackney.erl`: + +1. `hackney_load_regulation:acquire/4` takes a per-host slot. +2. `hackney_pool:checkout/4` returns a TCP connection (`checkout_ssl/4` with + `ssl_pooling`, which may return an already upgraded one). +3. `hackney_conn:upgrade_to_ssl/2,3` upgrades it for an HTTPS request. +4. `hackney_conn:get_protocol/1` tells whether HTTP/2 was negotiated. If so, + the connection is shared and registered with `hackney_pool:register_h2/5`. ## Protocol Selection @@ -459,54 +448,23 @@ hackney:get("https://api.example.com/data") ### Stream Multiplexing in hackney_conn -Each `hackney_conn` process maintains a map of active HTTP/2 streams: - -```erlang --record(conn_data, { - %% HTTP/2 state machine (from cowlib) - h2_machine :: tuple(), - - %% Active streams: #{StreamId => {Caller, State}} - h2_streams = #{} :: #{ - pos_integer() => {gen_statem:from(), atom()} - } -}). -``` - -When a request arrives: - -```erlang -%% In hackney_conn.erl -do_h2_request(From, Method, Path, Headers, Body, Data) -> - %% 1. Get next stream ID from h2_machine - {ok, StreamId, H2Machine1} = hackney_cow_http2_machine:init_stream(...), +HTTP/2 framing, HPACK and flow control come from the `h2` dependency. When +ALPN selects HTTP/2, `hackney_conn` starts an `h2_connection` process on the +socket and keeps its pid in `h2_conn`. From then on: - %% 2. Track caller for this stream - Streams = maps:put(StreamId, {From, waiting_response}, Data#conn_data.h2_streams), +1. A request calls `h2_connection:send_request_headers`, which returns a + stream id. +2. `hackney_conn` records the caller and the stream's progress in the + `h2_streams` map, keyed by stream id. +3. The `h2` library sends its events as `{h2, H2Conn, Event}` messages. + `hackney_conn` looks up the stream id and replies to the right caller. +4. When the stream ends, its entry is removed. - %% 3. Send HEADERS frame (and DATA if body present) - HeadersFrame = hackney_cow_http2:headers(StreamId, ...), - Transport:send(Socket, HeadersFrame), +A connection shared through the pool has no single owner. Each stream +monitors its own caller, and the connection closes itself once it is idle. - %% 4. Return updated state (caller will receive reply when response arrives) - {keep_state, Data#conn_data{h2_streams = Streams}}. -``` - -When a response arrives: - -```erlang -%% Response for StreamId received -handle_h2_frame({headers, StreamId, ...}, Data) -> - %% Lookup caller from h2_streams - {From, _State} = maps:get(StreamId, Data#conn_data.h2_streams), - - %% Reply to the correct caller - gen_statem:reply(From, {ok, Status, Headers, Body}), - - %% Remove completed stream - Streams = maps:remove(StreamId, Data#conn_data.h2_streams), - {ok, Data#conn_data{h2_streams = Streams}}. -``` +The `h2_*` bidirectional API (`hackney_h2_stream`) is separate: it opens a +dedicated connection and receives its stream's events directly from `h2`. ### Benefits of HTTP/2 Multiplexing @@ -563,7 +521,7 @@ hackney_pool:prewarm(default, "api.example.com", 443, 10). ### Prewarm for HTTPS -When an SSL connection is checked in (and closed), the pool still triggers TCP prewarm. This ensures TCP connections are ready for the next HTTPS request to upgrade. +When an SSL connection is checked in and closed (the default, without `ssl_pooling`), the pool still triggers TCP prewarm. This ensures TCP connections are ready for the next HTTPS request to upgrade. ## Request Flow @@ -616,7 +574,7 @@ hackney:get("https://api.example.com/data") ▼ ┌─────────────────────────────────────┐ │ 5. Checkin (async) │ -│ Connection closed (SSL) │ +│ Closed (or pooled: ssl_pooling) │ │ TCP prewarm triggered │ └─────────────────┬───────────────────┘ │ @@ -663,12 +621,12 @@ hackney_load_regulation:current(Host, Port). ### vs. hackney 1.x -| Aspect | 1.x | 2.x | +| Aspect | 1.x | 2.x and later | |--------|-----|-----| | State storage | ETS tables | Process state | | Socket ownership | Transferred between processes | Always connection process | | Error cleanup | Manual via manager | Automatic via process exit | -| SSL pooling | Yes (security risk) | No (TCP only) | +| SSL pooling | Yes, keyed by host and port only | Off by default; opt-in, keyed by TLS options | | Connection limits | Global pool size | Per-host limits | | Prewarm | No | Yes | @@ -680,7 +638,7 @@ hackney_load_regulation:current(Host, Port). **Resource control**: Per-host limits prevent a single slow host from consuming all connections. Different hosts are isolated. -**SSL security**: SSL connections are never reused, preventing session confusion attacks and ensuring fresh handshakes. +**SSL security**: By default an HTTPS/1.1 connection is not reused, so each request does a fresh handshake. With `ssl_pooling`, a connection is only reused for requests with the same TLS options. **Prewarm efficiency**: Frequently-used hosts have warm connections ready, eliminating connection latency for subsequent requests. diff --git a/guides/http3_guide.md b/guides/http3_guide.md index 15b8dad8..5334c3ab 100644 --- a/guides/http3_guide.md +++ b/guides/http3_guide.md @@ -213,8 +213,9 @@ hackney:get(<<"https://example.com/">>, [], <<>>, After the first HTTP/3 connection to a host, hackney caches the server's TLS session ticket in the pool, keyed by `{host, port, transport}`, and replays it on -the next connection to resume the handshake. For a **bodyless** request this can -also send the request as QUIC 0-RTT (in the first flight), saving a round trip. +the next connection to resume the handshake. For a **bodyless** GET, HEAD, +OPTIONS or TRACE request this can also send the request as QUIC 0-RTT (in the +first flight), saving a round trip. This is enabled by default and controlled by the `zero_rtt` request option: @@ -235,6 +236,9 @@ Scope: - **Request-in-0-RTT** (request bytes in the first flight) applies only to **bodyless** requests via the one-shot `hackney_h3` API. quic carries only the HEADERS as early data, so a request with a body resumes at 1-RTT. + - Only **GET, HEAD, OPTIONS and TRACE** are sent as 0-RTT. Early data can be + replayed by an attacker, so a request with any other method waits for the + handshake and is sent at 1-RTT (RFC 8470). - The **pooled/multiplexed path** uses the ticket for a resumed (abbreviated) handshake; requests are sent at 1-RTT since they arrive after connect. - On 0-RTT rejection, the one-shot path retries once at 1-RTT and the cached diff --git a/rebar.config b/rebar.config index 108c8ea6..eb28bccd 100644 --- a/rebar.config +++ b/rebar.config @@ -93,6 +93,7 @@ {"guides/webtransport_guide.md", #{title => "WebTransport Guide"}}, {"guides/middleware.md", #{title => "Middleware Guide"}}, {"guides/design.md", #{title => "Design Guide"}}, + {"guides/code_map.md", #{title => "Where Things Live"}}, {"guides/MIGRATION.md", #{title => "Migration Guide"}}, {"NEWS.md", #{title => "Changelog"}}, {"CONTRIBUTING.md", #{title => "Contributing"}}, diff --git a/src/hackney_conn.erl b/src/hackney_conn.erl index 46f679be..6f0dc760 100644 --- a/src/hackney_conn.erl +++ b/src/hackney_conn.erl @@ -13,10 +13,13 @@ %%% %%% States: %%% - idle: Process started, not connected -%%% - connecting: TCP/SSL handshake in progress +%%% - connecting: TCP/SSL handshake in progress (not entered today) %%% - connected: Ready for requests %%% - sending: Sending request data +%%% - streaming_body: Streaming request body %%% - receiving: Awaiting/streaming response +%%% - streaming: Continuous async body streaming (async=true) +%%% - streaming_once: On-demand async streaming (async=once) %%% - closed: Connection terminated -module(hackney_conn). From 381c3732a9a65ed6000b16fa18a4715571fe4bda Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 20 Nov 2026 00:28:04 +0100 Subject: [PATCH 3/3] Release 4.12.2 --- NEWS.md | 24 ++++++++++++++++++++++++ src/hackney.app.src | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 9096623b..3f3e0bfd 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,29 @@ # NEWS +4.12.2 - 2026-11-20 +------------------- + +### Changed + +- quic 3.2.0, h2 0.18.3 and webtransport 0.5.12. +- HTTP/3: on a resumed connection, only GET, HEAD, OPTIONS and TRACE + requests are sent as 0-RTT. A request with another method now waits + for the handshake, because 0-RTT data can be replayed. It still + succeeds, one round trip later. +- Documentation: the Design Guide now describes the current connection + states, TLS pooling and HTTP/2 handling, and a new "Where Things Live" + page maps each part of hackney to its modules and tests. + +### Fixed + +- HTTP/3 and WebTransport: a small write or the end of a stream could + reach the server ahead of data still waiting to be sent on the same + stream. Writes now leave in the order they were made. +- HTTP/3: sending on many streams of one connection no longer slows + down as the amount of queued data grows. +- HTTP/2: a request answered with a malformed response now fails at + once instead of waiting for the timeout. + 4.12.1 - 2026-11-15 ------------------- diff --git a/src/hackney.app.src b/src/hackney.app.src index 82697ddc..254b5e86 100644 --- a/src/hackney.app.src +++ b/src/hackney.app.src @@ -4,7 +4,7 @@ {application, hackney, [ {description, "Simple HTTP client with HTTP/1.1, HTTP/2, and HTTP/3 support"}, - {vsn, "4.12.1"}, + {vsn, "4.12.2"}, {registered, [hackney_pool]}, {applications, [kernel, stdlib,