fix(metrics): add default value for the rates

This commit is contained in:
Shawn 2022-03-11 11:08:01 +08:00
parent 09404c555f
commit 2a17798320
1 changed files with 14 additions and 8 deletions

View File

@ -58,13 +58,13 @@
-export_type([metrics/0, handler_name/0, metric_id/0]). -export_type([metrics/0, handler_name/0, metric_id/0]).
-type rate() :: #{ -type rate() :: #{
current => float(), current := float(),
max => float(), max := float(),
last5m => float() last5m := float()
}. }.
-type metrics() :: #{ -type metrics() :: #{
counters => #{atom() => integer()}, counters := #{atom() => integer()},
rate => #{atom() => rate()} rate := #{atom() => rate()}
}. }.
-type handler_name() :: atom(). -type handler_name() :: atom().
-type metric_id() :: binary(). -type metric_id() :: binary().
@ -158,10 +158,10 @@ init(Name) ->
{ok, #state{}}. {ok, #state{}}.
handle_call({get_rate, _Id}, _From, State = #state{rates = undefined}) -> handle_call({get_rate, _Id}, _From, State = #state{rates = undefined}) ->
{reply, #{}, State}; {reply, make_rate(0, 0, 0), State};
handle_call({get_rate, Id}, _From, State = #state{rates = Rates}) -> handle_call({get_rate, Id}, _From, State = #state{rates = Rates}) ->
{reply, case maps:get(Id, Rates, undefined) of {reply, case maps:get(Id, Rates, undefined) of
undefined -> #{}; undefined -> make_rate(0, 0, 0);
RatesPerId -> format_rates_of_id(RatesPerId) RatesPerId -> format_rates_of_id(RatesPerId)
end, State}; end, State};
@ -303,7 +303,13 @@ format_rates_of_id(RatesPerId) ->
end, RatesPerId). end, RatesPerId).
format_rate(#rate{max = Max, current = Current, last5m = Last5Min}) -> format_rate(#rate{max = Max, current = Current, last5m = Last5Min}) ->
#{max => precision(Max, 2), current => precision(Current, 2), last5m => precision(Last5Min, 2)}. make_rate(Current, Max, Last5Min).
make_rate(Current, Max, Last5Min) ->
#{ current => precision(Current, 2)
, max => precision(Max, 2)
, last5m => precision(Last5Min, 2)
}.
precision(Float, N) -> precision(Float, N) ->
Base = math:pow(10, N), Base = math:pow(10, N),