Skip to content

Commit

Permalink
Code for step 2
Browse files Browse the repository at this point in the history
  • Loading branch information
akoutmos committed Jan 7, 2020
1 parent 0547334 commit aba2e1b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
7 changes: 7 additions & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Config

config :payments_client, RateLimiter,
rate_limiter: PaymentsClient.RateLimiters.LeakyBucket,
timeframe_max_requests: 60,
timeframe_units: :seconds,
timeframe: 60
11 changes: 9 additions & 2 deletions lib/payments_client/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,17 @@ defmodule PaymentsClient.Application do

use Application

alias PaymentsClient.RateLimiter

def start(_type, _args) do
children = [
# Starts a worker by calling: PaymentsClient.Worker.start_link(arg)
# {PaymentsClient.Worker, arg}
{Task.Supervisor, name: RateLimiter.TaskSupervisor},
{RateLimiter.get_rate_limiter(),
%{
timeframe_max_requests: RateLimiter.get_requests_per_timeframe(),
timeframe_units: RateLimiter.get_timeframe_unit(),
timeframe: RateLimiter.get_timeframe()
}}
]

# See https://hexdocs.pm/elixir/Supervisor.html
Expand Down
27 changes: 27 additions & 0 deletions lib/rate_limiter.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
defmodule PaymentsClient.RateLimiter do
@callback make_request(request_handler :: tuple(), response_handler :: tuple()) :: :ok

def make_request(request_handler, response_handler) do
get_rate_limiter().make_request(request_handler, response_handler)
end

def get_rate_limiter, do: get_rate_limiter_config(:rate_limiter)
def get_requests_per_timeframe, do: get_rate_limiter_config(:timeframe_max_requests)
def get_timeframe_unit, do: get_rate_limiter_config(:timeframe_units)
def get_timeframe, do: get_rate_limiter_config(:timeframe)

def calculate_refresh_rate(num_requests, time, timeframe_units) do
floor(convert_time_to_milliseconds(timeframe_units, time) / num_requests)
end

def convert_time_to_milliseconds(:hours, time), do: :timer.hours(time)
def convert_time_to_milliseconds(:minutes, time), do: :timer.minutes(time)
def convert_time_to_milliseconds(:seconds, time), do: :timer.seconds(time)
def convert_time_to_milliseconds(:milliseconds, milliseconds), do: milliseconds

defp get_rate_limiter_config(config) do
:payments_client
|> Application.get_env(RateLimiter)
|> Keyword.get(config)
end
end

0 comments on commit aba2e1b

Please sign in to comment.