Skip to content
Permalink
Browse files

Code for step 2

  • Loading branch information
akoutmos committed Jan 7, 2020
1 parent 0547334 commit aba2e1b84448dd9d1b06c1827a020fde7b2116eb
Showing with 43 additions and 2 deletions.
  1. +7 −0 config/config.exs
  2. +9 −2 lib/payments_client/application.ex
  3. +27 −0 lib/rate_limiter.ex
@@ -0,0 +1,7 @@
import Config

config :payments_client, RateLimiter,
rate_limiter: PaymentsClient.RateLimiters.LeakyBucket,
timeframe_max_requests: 60,
timeframe_units: :seconds,
timeframe: 60
@@ -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
@@ -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.
You can’t perform that action at this time.