Repository navigation
Allow setting a maximum heap size during request parsing #1342
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SteffenDE
wants to merge
2
commits into
elixir-plug:main
Choose a base branch
from
SteffenDE:sd-parse-heap-size
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -98,6 +98,15 @@ defmodule Plug.Parsers do | |
| * `:validate_utf8` - boolean that tells whether or not we want to | ||
| validate that parsed binaries are utf8 strings. | ||
|
|
||
| * `:max_heap_size` - limits the memory the process may use while it reads | ||
| and parses the request. The value is the number of extra heap words | ||
| allowed on top of what the process already holds when parsing starts | ||
| (8 bytes per word on 64-bit systems). It also accepts a map in the shape | ||
| of `Process.flag(:max_heap_size, map)`, in which case `:size` is that | ||
| headroom. The previous flag value is restored after parsing. Defaults to | ||
| `4_000_000` (roughly 32MB of headroom); set it to `:infinity` to disable. | ||
| See the "Limiting memory usage" section below. | ||
|
|
||
| * `:body_reader` - an optional replacement (or wrapper) for | ||
| `Plug.Conn.read_body/2` to provide a function that gives access to the | ||
| raw body before it is parsed and discarded. It is in the standard format | ||
|
|
@@ -153,6 +162,50 @@ defmodule Plug.Parsers do | |
| {:multipart, length: 20_000_000} # Increase to 20MB max upload | ||
| ] | ||
|
|
||
| ## Limiting memory usage | ||
|
|
||
| The `:length` option limits the size of the request body, but the parsed | ||
| params may need much more memory than the body itself. For example, each | ||
| element of a JSON list of small integers, such as `1,`, takes 2 bytes in | ||
| the body and 16 bytes once decoded on 64-bit systems. A decoder may also | ||
| need several times the size of the decoded data while it runs. | ||
|
|
||
| `Plug.Parsers` sets a `:max_heap_size` while it parses a request, defaulting | ||
| to `4_000_000` words (roughly 32MB). You can raise it, lower it, or disable | ||
| it: | ||
|
|
||
| plug Plug.Parsers, | ||
| parsers: [:urlencoded, :multipart, :json], | ||
| json_decoder: Jason, | ||
| max_heap_size: 8_000_000 | ||
|
|
||
| # or, to turn the limit off entirely | ||
| plug Plug.Parsers, parsers: [...], max_heap_size: :infinity | ||
|
|
||
| The size is in words (8 bytes on 64-bit systems). It is headroom on top of the | ||
| heap the process already holds when parsing starts, not an absolute ceiling: | ||
| the current heap size is read and the configured size is added to it. This way | ||
| a process that already holds memory, such as garbage left over from an earlier | ||
| request on the same keep-alive connection, is not killed while parsing a small | ||
| body. | ||
|
|
||
| If the limit is exceeded, the process is killed, so no error is raised and no | ||
| response is sent by `Plug.Parsers`. The web server decides how the connection | ||
| ends, and a warning is logged. Large binaries, such as the raw request body | ||
| and large string values, are stored outside of the process heap and, by | ||
| default, do not count towards the limit. | ||
|
|
||
| Pick the limit against the memory a single request legitimately needs to | ||
| parse, not the raw body size. A body made mostly of one large value (an | ||
| upload, a base64 field) costs almost no heap, because that value stays off the | ||
| heap. A body made of many small elements costs much more: decoding is a few | ||
| times the decoded size, and structured data expands further, so tens of | ||
| thousands of small fields or list elements are needed before the default | ||
| limit is reached. To keep a limit from killing legitimate large requests, | ||
| size it above the heap those requests need (or set `:infinity`), and pass a | ||
| map such as `%{size: 4_000_000, kill: true, error_logger: false}` if you want | ||
| to tune the kill or silence the log. | ||
|
|
||
| ## Built-in parsers | ||
|
|
||
| Plug ships with the following parsers: | ||
|
|
@@ -255,13 +308,14 @@ defmodule Plug.Parsers do | |
| {parsers, opts} = Keyword.pop(opts, :parsers) | ||
| {pass, opts} = Keyword.pop(opts, :pass, []) | ||
| {query_string_length, opts} = Keyword.pop(opts, :query_string_length, 1_000_000) | ||
| {max_heap_size, opts} = Keyword.pop(opts, :max_heap_size, 4_000_000) | ||
| validate_utf8 = Keyword.get(opts, :validate_utf8, true) | ||
|
|
||
| unless parsers do | ||
| raise ArgumentError, "Plug.Parsers expects a set of parsers to be given in :parsers" | ||
| end | ||
|
|
||
| {convert_parsers(parsers, opts), pass, query_string_length, validate_utf8} | ||
| {convert_parsers(parsers, opts), pass, query_string_length, validate_utf8, max_heap_size} | ||
| end | ||
|
|
||
| defp convert_parsers(parsers, root_opts) do | ||
|
|
@@ -288,7 +342,52 @@ defmodule Plug.Parsers do | |
| @impl true | ||
| def call(%{method: method, body_params: %Plug.Conn.Unfetched{}} = conn, options) | ||
| when method in @methods do | ||
| {parsers, pass, query_string_length, validate_utf8} = options | ||
| {parsers, pass, query_string_length, validate_utf8, max_heap_size} = options | ||
|
|
||
| with_max_heap_size(max_heap_size, fn -> | ||
| parse_body(conn, parsers, pass, query_string_length, validate_utf8) | ||
| end) | ||
| end | ||
|
|
||
| def call(%{body_params: body_params} = conn, {_, _, query_string_length, validate_utf8, _}) do | ||
| body_params = make_empty_if_unfetched(body_params) | ||
| {conn, params} = merge_params(conn, body_params, query_string_length, validate_utf8) | ||
| %{conn | params: params, body_params: body_params} | ||
| end | ||
|
|
||
| defp with_max_heap_size(limit, fun) when limit in [nil, :infinity], do: fun.() | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We don't seem to document nil is supported anywhere, so I'd pattern match on infinity directly. |
||
|
|
||
| defp with_max_heap_size(max_heap_size, fun) do | ||
| previous = Process.flag(:max_heap_size, add_current_heap_size(max_heap_size)) | ||
|
|
||
| try do | ||
| fun.() | ||
| after | ||
| Process.flag(:max_heap_size, previous) | ||
| end | ||
| end | ||
|
|
||
| # The configured size is extra headroom on top of what the process already | ||
| # holds, not an absolute ceiling. Adding the current heap size means a | ||
| # process that already holds memory (for example, garbage left over from an | ||
| # earlier request on the same keep-alive connection) is not killed while | ||
| # parsing a small body. | ||
| # | ||
| # A bare word count also enables the kill and a logged warning. A map is | ||
| # honored as given (so `:kill` and `:error_logger` can be set), except that | ||
| # its `:size` is likewise treated as headroom over the current heap. | ||
| defp add_current_heap_size(size) when is_integer(size), | ||
| do: %{size: size + current_heap_size(), kill: true, error_logger: true} | ||
|
|
||
| defp add_current_heap_size(%{size: size} = max_heap_size), | ||
| do: %{max_heap_size | size: size + current_heap_size()} | ||
|
|
||
| defp current_heap_size do | ||
| {:total_heap_size, size} = Process.info(self(), :total_heap_size) | ||
| size | ||
| end | ||
|
|
||
| defp parse_body(conn, parsers, pass, query_string_length, validate_utf8) do | ||
| %{req_headers: req_headers} = conn | ||
|
|
||
| conn = | ||
|
|
@@ -323,12 +422,6 @@ defmodule Plug.Parsers do | |
| end | ||
| end | ||
|
|
||
| def call(%{body_params: body_params} = conn, {_, _, query_string_length, validate_utf8}) do | ||
| body_params = make_empty_if_unfetched(body_params) | ||
| {conn, params} = merge_params(conn, body_params, query_string_length, validate_utf8) | ||
| %{conn | params: params, body_params: body_params} | ||
| end | ||
|
|
||
| defp reduce( | ||
| conn, | ||
| [{parser, options} | rest], | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.