Skip to content

Commit

Permalink
Merge pull request #501 from Kraigie/ratelimiter-2.0
Browse files Browse the repository at this point in the history
Convert ratelimiter into an async state machine
  • Loading branch information
jchristgit authored Jun 1, 2023
2 parents 2435a6a + ae659c4 commit f3ceb26
Show file tree
Hide file tree
Showing 10 changed files with 543 additions and 645 deletions.
2 changes: 1 addition & 1 deletion guides/intro/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ they're given or using `Nostrum.Api.request/4` to call an endpoint.

To ensure that every request is handled properly, no matter if they're called
asynchronously or not, nostrum funnels all requests through the
`Nostrum.Api.Ratelimiter` GenServer.
`Nostrum.Api.Ratelimiter` state machine.


## REST-only
Expand Down
4 changes: 2 additions & 2 deletions guides/intro/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ The following options are only used for testing nostrum itself.
## Logging

nostrum uses Elixir's standard logger to inform you about regular and irregular
events. Normal messages include Discord-requested shard reconnections,
ratelimiter waits, and the `IDENTIFY` and `READY` events.
events. Normal messages include Discord-requested shard reconnections and the
`IDENTIFY` and `READY` events.

The following metadata fields through logger:

Expand Down
21 changes: 2 additions & 19 deletions lib/nostrum/api/base.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ defmodule Nostrum.Api.Base do
@type methods :: :get | :post | :put | :delete

@spec request(pid, methods(), String.t(), iodata(), [{String.t(), String.t()}], Enum.t()) ::
{:error, :timeout | {:connection_error, any} | {:down, any} | {:stream_error, any}}
| {:ok, {non_neg_integer, [{String.t(), String.t()}], binary}}
:gun.stream_ref()
def request(conn, method, route, body, raw_headers, params) do
headers = process_request_headers(raw_headers)
# Convert method from atom to string for `:gun`
Expand All @@ -23,23 +22,7 @@ defmodule Nostrum.Api.Base do

full_route = "#{base_route()}#{route}?#{query_string}"
headers = process_request_headers(headers, body)
stream = :gun.request(conn, method, full_route, headers, process_request_body(body))

case :gun.await(conn, stream) do
{:response, :fin, status, headers} ->
{:ok, {status, headers, ""}}

{:response, :nofin, status, headers} ->
{:ok, body} = :gun.await_body(conn, stream)
{:ok, {status, headers, body}}

{:error, :timeout} = result ->
Logger.debug("Request for #{inspect(full_route)} timed out")
result

{:error, _reason} = result ->
result
end
:gun.request(conn, method, full_route, headers, process_request_body(body))
end

def process_request_headers(headers, ""), do: :proplists.delete("content-type", headers)
Expand Down
Loading

0 comments on commit f3ceb26

Please # to comment.