Skip to content

Commit

Permalink
HTTP/2: Cache whether the port is default in the conn
Browse files Browse the repository at this point in the history
When constructing the authority pseudo header we check if the conn's
port is the default for the conn's scheme using `URI.default_port/1`.
That corresponds to an ETS lookup into the `:elixir_config` table. It's
relatively fast to read that information but the conn's port and scheme
are static for the life of the conn, so we should determine this
information once while initiating the conn (`Mint.HTTP2.initiate/5`).
This change saves a small amount of time per request and becomes more
valuable as the conn is re-used for more requests.
  • Loading branch information
the-mikedavis committed Feb 3, 2024
1 parent 321c830 commit 53e988e
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions lib/mint/http2.ex
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,9 @@ defmodule Mint.HTTP2 do
:port,
:scheme,

# Whether the port is the default for the scheme
:default_port?,

# Connection state (open, closed, and so on).
:state,

Expand Down Expand Up @@ -974,6 +977,7 @@ defmodule Mint.HTTP2 do
) :: {:ok, t()} | {:error, Types.error()}
def initiate(scheme, socket, hostname, port, opts) do
transport = scheme_to_transport(scheme)
scheme_string = Atom.to_string(scheme)
mode = Keyword.get(opts, :mode, :active)
log? = Keyword.get(opts, :log, false)
client_settings_params = Keyword.get(opts, :client_settings, [])
Expand All @@ -992,10 +996,11 @@ defmodule Mint.HTTP2 do
conn = %__MODULE__{
hostname: hostname,
port: port,
default_port?: URI.default_port(scheme_string) == port,
transport: scheme_to_transport(scheme),
socket: socket,
mode: mode,
scheme: Atom.to_string(scheme),
scheme: scheme_string,
state: :handshaking,
log: log?
}
Expand Down Expand Up @@ -1358,15 +1363,15 @@ defmodule Mint.HTTP2 do
if String.upcase(method) == "CONNECT" do
[
{":method", method},
{":authority", authority_pseudo_header(conn.scheme, conn.port, conn.hostname)}
{":authority", authority_pseudo_header(conn)}
| headers
]
else
[
{":method", method},
{":path", path},
{":scheme", conn.scheme},
{":authority", authority_pseudo_header(conn.scheme, conn.port, conn.hostname)}
{":authority", authority_pseudo_header(conn)}
| headers
]
end
Expand Down Expand Up @@ -1720,12 +1725,12 @@ defmodule Mint.HTTP2 do
end

# If the port is the default for the scheme, don't add it to the :authority pseudo-header
defp authority_pseudo_header(scheme, port, hostname) do
if URI.default_port(scheme) == port do
hostname
else
"#{hostname}:#{port}"
end
defp authority_pseudo_header(%__MODULE__{default_port?: true, hostname: hostname}) do
hostname
end

defp authority_pseudo_header(%__MODULE__{hostname: hostname, port: port}) do
"#{hostname}:#{port}"
end

defp join_cookie_headers(headers) do
Expand Down

0 comments on commit 53e988e

Please sign in to comment.