Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(gateway): flatten handlers, drop unused helpers, tests

Hampus03103dfdced8
diff --git a/fluxer_gateway/src/gateway/gateway_handler_dispatch.erl b/fluxer_gateway/src/gateway/gateway_handler_dispatch.erl
index 7b54fb0da..62f932cb7 100644
--- a/fluxer_gateway/src/gateway/gateway_handler_dispatch.erl
+++ b/fluxer_gateway/src/gateway/gateway_handler_dispatch.erl
@@ -10,14 +10,11 @@
handle_session_down/1,
handle_session_reconnect/1,
handle_presence_update/3,
- handle_request_guild_members/3,
handle_request_guild_members_worker_down/1,
handle_request_worker_down/4,
handle_request_worker_timeout/3,
cleanup_request_workers/1,
- handle_request_guild_counts/3,
handle_request_channel_member_counts/3,
- handle_request_forum_unreads/3,
handle_lazy_request/3,
validate_presence_data/1,
adjust_status/1
@@ -470,15 +467,7 @@ do_request_channel_member_counts_inner(Data, SocketPid, SessionPid) ->
handle_request_forum_unreads(Data, Pid, State) when is_map(Data) ->
case channel_threads_config:enabled() orelse not channel_threads_config:loaded() of
true ->
- SocketPid = self(),
- Fun = fun() -> do_request_forum_unreads(Data, SocketPid, Pid) end,
- case start_request_worker(request_forum_unreads, Fun, State) of
- {ok, _WorkerPid, WorkerState} ->
- {ok, WorkerState};
- dropped ->
- _ = spawn(fun() -> do_request_forum_unreads(#{}, SocketPid, Pid) end),
- {ok, State}
- end;
+ start_forum_unreads(Data, Pid, State);
false ->
gateway_handler_encode:close_with_reason(
unknown_opcode, <<"Unknown opcode">>, State
@@ -487,26 +476,43 @@ handle_request_forum_unreads(Data, Pid, State) when is_map(Data) ->
handle_request_forum_unreads(_Data, _Pid, State) ->
gateway_handler_encode:close_with_reason(unknown_opcode, <<"Unknown opcode">>, State).
+-spec start_forum_unreads(map(), pid(), state()) -> ws_result().
+start_forum_unreads(Data, Pid, State) ->
+ SocketPid = self(),
+ Fun = fun() -> do_request_forum_unreads(Data, SocketPid, Pid) end,
+ case start_request_worker(request_forum_unreads, Fun, State) of
+ {ok, _WorkerPid, WorkerState} ->
+ {ok, WorkerState};
+ dropped ->
+ spawn_empty_forum_unreads(SocketPid, Pid),
+ {ok, State}
+ end.
+
+-spec spawn_empty_forum_unreads(pid(), pid()) -> ok.
+spawn_empty_forum_unreads(SocketPid, Pid) ->
+ _ = spawn(fun() -> do_request_forum_unreads(#{}, SocketPid, Pid) end),
+ ok.
+
-spec do_request_forum_unreads(map(), pid(), pid()) -> ok.
do_request_forum_unreads(Data, SocketPid, SessionPid) ->
case forum_unreads_session_state(SessionPid) of
{ok, SessionState} ->
- try
- guild_request_forum_unreads:handle_request(
- Data, SocketPid, SessionState#{session_pid => SessionPid}
- )
- of
- ok -> ok
- catch
- error:_Reason -> ok;
- exit:_Reason -> ok;
- throw:_Reason -> ok
- end;
+ handle_forum_unreads(Data, SocketPid, SessionState#{session_pid => SessionPid});
error ->
SocketPid ! forum_unreads_unknown_opcode,
ok
end.
+-spec handle_forum_unreads(map(), pid(), map()) -> ok.
+handle_forum_unreads(Data, SocketPid, SessionState) ->
+ try guild_request_forum_unreads:handle_request(Data, SocketPid, SessionState) of
+ ok -> ok
+ catch
+ error:_Reason -> ok;
+ exit:_Reason -> ok;
+ throw:_Reason -> ok
+ end.
+
-spec forum_unreads_session_state(pid()) -> {ok, map()} | error.
forum_unreads_session_state(SessionPid) ->
try gen_server:call(SessionPid, {get_state}, 5000) of
diff --git a/fluxer_gateway/src/gateway/gateway_nats_pool.erl b/fluxer_gateway/src/gateway/gateway_nats_pool.erl
index 8aab37cbb..271459878 100644
--- a/fluxer_gateway/src/gateway/gateway_nats_pool.erl
+++ b/fluxer_gateway/src/gateway/gateway_nats_pool.erl
@@ -112,10 +112,6 @@ init([]) ->
max_handlers => gateway_nats_pool_conn:max_handlers()
}}.
--spec nats_rpc_enabled() -> boolean().
-nats_rpc_enabled() ->
- fluxer_gateway_env:get(nats_rpc_enabled) =/= false.
-
-spec handle_call(term(), gen_server:from(), map()) -> {reply, term(), map()}.
handle_call(get_pool_status, _From, State) ->
{reply, build_pool_status(State), State};
@@ -351,12 +347,6 @@ handle_ready_slot(Idx, Conn, Slots, State) ->
_ -> State
end.
--spec decrement_handler_count(map()) -> map().
-decrement_handler_count(#{handler_count := HC} = State) when HC > 0 ->
- State#{handler_count => HC - 1};
-decrement_handler_count(State) ->
- State.
-
-spec handle_rpc_msg(binary(), binary(), map(), map()) -> map().
handle_rpc_msg(
Subject,
@@ -506,91 +496,6 @@ cancel_connect_timer(#{timer := TimerRef}) when is_reference(TimerRef) ->
cancel_connect_timer(_) ->
ok.
--spec maybe_kill_connect_pid(pid() | undefined) -> ok.
-maybe_kill_connect_pid(Pid) when is_pid(Pid) ->
- unlink(Pid),
- exit(Pid, kill),
- ok;
-maybe_kill_connect_pid(undefined) ->
- ok.
-
-spec conn_from_term(term()) -> nats:conn().
conn_from_term(Conn) when is_pid(Conn) ->
Conn.
-
--spec ignore_disconnect(nats:conn()) -> ok.
-ignore_disconnect(Conn) ->
- try nats:disconnect(Conn) of
- _ -> ok
- catch
- throw:_ -> ok;
- error:_ -> ok;
- exit:_ -> ok
- end.
-
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
--define(TEST_WAIT_LOOP_TIMEOUT_MS, 60000).
-
-stale_connect_timeout_does_not_kill_current_slot_worker_test() ->
- Token = make_ref(),
- StaleToken = make_ref(),
- Pid = spawn(fun wait_forever/0),
- State = #{
- connecting => #{0 => #{pid => Pid, token => Token, timer => undefined}},
- slots => #{},
- monitors => #{},
- pool_size => 1,
- subs => #{}
- },
- try
- ?assertEqual(State, handle_connect_timeout(0, StaleToken, State)),
- ?assert(erlang:is_process_alive(Pid))
- after
- exit(Pid, kill)
- end.
-
-legacy_connect_timeout_ignores_tokened_slot_worker_test() ->
- Token = make_ref(),
- Pid = spawn(fun wait_forever/0),
- State = #{
- connecting => #{0 => #{pid => Pid, token => Token, timer => undefined}},
- slots => #{},
- monitors => #{},
- pool_size => 1,
- subs => #{}
- },
- try
- ?assertEqual(State, handle_legacy_connect_timeout(0, State)),
- ?assert(erlang:is_process_alive(Pid))
- after
- exit(Pid, kill)
- end.
-
-pool_keeps_rpc_unsubscribed_when_switched_off_test() ->
- persistent_term:put({fluxer_gateway, runtime_config}, #{nats_rpc_enabled => false}),
- Parent = self(),
- try
- Pid = spawn(fun() -> Parent ! {self(), init([])} end),
- {ok, State} =
- receive
- {Pid, Reply} -> Reply
- after 5000 -> timeout
- end,
- ?assertEqual(false, maps:get(rpc_enabled, State)),
- ?assertEqual(State, handle_ready(self(), false, #{0 => self()}, State))
- after
- persistent_term:erase(?PERSISTENT_TERM_KEY),
- persistent_term:erase(?REPLY_FAILURE_KEY),
- persistent_term:erase({fluxer_gateway, runtime_config})
- end.
-
-wait_forever() ->
- receive
- stop -> ok
- after ?TEST_WAIT_LOOP_TIMEOUT_MS ->
- ok
- end.
-
--endif.
diff --git a/fluxer_gateway/src/gateway/gateway_rpc_guild_infra.erl b/fluxer_gateway/src/gateway/gateway_rpc_guild_infra.erl
index 98bdfb30a..13112bd5a 100644
--- a/fluxer_gateway/src/gateway/gateway_rpc_guild_infra.erl
+++ b/fluxer_gateway/src/gateway/gateway_rpc_guild_infra.erl
@@ -2,10 +2,6 @@
-module(gateway_rpc_guild_infra).
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
--endif.
-
-typing([eqwalizer]).
-export([
@@ -17,7 +13,6 @@
get_or_start_guild_pid/1,
get_guild_pid_with_retry/1,
safe_guild_call/4,
- safe_gen_server_call/3,
resolve_voice_pid/2,
cache_guild_pid/2,
delete_cached_guild_pid/2,
@@ -57,13 +52,15 @@ run_with_guild_pid(GuildId, Pid, Fun, NotFoundError) ->
with_guild_unchecked(GuildId, Fun) ->
case ensure_guild_pid(GuildId) of
{ok, Pid} ->
- run_with_guild_pid_guard(
- GuildId, Pid, fun() -> Fun(Pid) end, Fun, <<"guild_not_found">>
- );
+ run_unchecked(GuildId, Pid, Fun);
error ->
gateway_rpc_error:raise(<<"guild_not_found">>)
end.
+-spec run_unchecked(integer(), pid(), fun((pid()) -> T)) -> T when T :: term().
+run_unchecked(GuildId, Pid, Fun) ->
+ run_with_guild_pid_guard(GuildId, Pid, fun() -> Fun(Pid) end, Fun, <<"guild_not_found">>).
+
-spec ensure_responsive(pid()) -> ok.
ensure_responsive(Pid) ->
case guild_health:is_overloaded(Pid) of
@@ -358,19 +355,6 @@ is_cached_guild_pid_alive(Pid) ->
RemoteNode -> lists:member(RemoteNode, nodes())
end.
--spec safe_gen_server_call(pid(), term(), pos_integer()) -> {ok, term()} | error.
-safe_gen_server_call(Pid, Request, Timeout) ->
- try gen_server:call(Pid, Request, Timeout) of
- Reply -> {ok, Reply}
- catch
- exit:{timeout, _} -> error;
- exit:{nodedown, _} -> error;
- exit:{noproc, _} -> error;
- throw:_Reason -> error;
- error:_Reason -> error;
- exit:_ -> error
- end.
-
-spec safe_guild_call(integer(), pid(), {atom(), map()}, pos_integer()) ->
{ok, term()} | error.
safe_guild_call(GuildId, Pid, Request, Timeout) ->
@@ -422,53 +406,3 @@ retry_guild_call_pid(GuildId, NewPid, Request, Timeout) ->
delete_cached_guild_pid(GuildId, NewPid),
error
end.
-
--ifdef(TEST).
-
-overloaded_guild_is_rejected_before_enqueuing_work_test() ->
- ok = guild_ets_owner:ensure_table(guild_health_status, [named_table, public, set]),
- Pid = spawn(fun() ->
- receive
- stop -> ok
- end
- end),
- Pending = {make_ref(), erlang:monotonic_time(millisecond), 2500},
- true = ets:insert(guild_health_status, {Pid, 42, true, undefined, Pending}),
- try
- ?assertError(
- {gateway_rpc_error, <<"guild_overloaded">>},
- safe_guild_call(42, Pid, {get_viewer_counts, #{user_id => 200}}, 4000)
- ),
- ?assertError(
- {gateway_rpc_error, <<"guild_overloaded">>},
- retry_guild_call_pid(42, Pid, {get_viewer_counts, #{user_id => 200}}, 4000)
- ),
- ?assertEqual({message_queue_len, 0}, process_info(Pid, message_queue_len))
- after
- ets:delete(guild_health_status, Pid),
- Pid ! stop
- end.
-
-run_with_guild_pid_guard_generic_exit_returns_domain_error_test() ->
- ?assertError(
- {gateway_rpc_error, <<"guild_not_found">>},
- run_with_guild_pid_guard(
- 123,
- self(),
- fun() -> exit(kaboom) end,
- fun(_Pid) -> ok end,
- <<"guild_not_found">>
- )
- ).
-
-safe_gen_server_call_dead_pid_returns_error_test() ->
- DeadPid = spawn(fun() -> ok end),
- Ref = monitor(process, DeadPid),
- receive
- {'DOWN', Ref, process, DeadPid, _Reason} -> ok
- after 1000 ->
- ?assert(false, guild_rpc_pid_did_not_exit)
- end,
- ?assertEqual(error, safe_gen_server_call(DeadPid, ping, 250)).
-
--endif.
diff --git a/fluxer_gateway/src/gateway/gateway_rpc_guild_lifecycle.erl b/fluxer_gateway/src/gateway/gateway_rpc_guild_lifecycle.erl
index 0426db820..a5640d3be 100644
--- a/fluxer_gateway/src/gateway/gateway_rpc_guild_lifecycle.erl
+++ b/fluxer_gateway/src/gateway/gateway_rpc_guild_lifecycle.erl
@@ -113,11 +113,15 @@ read_guild(GuildId, Request) ->
{ok, Reply} ->
Reply;
miss ->
- gateway_rpc_guild_infra:with_guild(GuildId, fun(Pid) ->
- guild_query_handler:call(Pid, Request, ?GUILD_CALL_TIMEOUT)
- end)
+ call_guild(GuildId, Request)
end.
+-spec call_guild(integer(), {atom(), map()}) -> term().
+call_guild(GuildId, Request) ->
+ gateway_rpc_guild_infra:with_guild(GuildId, fun(Pid) ->
+ guild_query_handler:call(Pid, Request, ?GUILD_CALL_TIMEOUT)
+ end).
+
-spec handle_start(map()) -> true.
handle_start(#{<<"guild_id">> := GuildIdBin}) ->
GuildId = validation:snowflake_or_throw(<<"guild_id">>, GuildIdBin),
diff --git a/fluxer_gateway/src/gateway/gateway_rpc_guild_mentions.erl b/fluxer_gateway/src/gateway/gateway_rpc_guild_mentions.erl
index 67ac6125c..90ec6f759 100644
--- a/fluxer_gateway/src/gateway/gateway_rpc_guild_mentions.erl
+++ b/fluxer_gateway/src/gateway/gateway_rpc_guild_mentions.erl
@@ -2,10 +2,6 @@
-module(gateway_rpc_guild_mentions).
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
--endif.
-
-typing([eqwalizer]).
-export([handle/2]).
@@ -36,7 +32,7 @@ do_resolve_sources_page(GuildId, Request) ->
-spec guild_call_sources_page(pid(), map()) -> map().
guild_call_sources_page(Pid, Request) ->
Msg = {resolve_mention_sources_page, Request},
- case guild_query_handler:call(Pid, Msg, ?GUILD_CALL_TIMEOUT) of
+ case eqwalizer:dynamic_cast(guild_query_handler:call(Pid, Msg, ?GUILD_CALL_TIMEOUT)) of
#{mentions := Mentions, next_cursor := NextCursor} ->
#{
<<"mentions">> => fmt_mention_entries(Mentions),
@@ -156,76 +152,3 @@ clamp_page_limit(V) ->
N ->
N
end.
-
--ifdef(TEST).
-
-clamp_page_limit_test() ->
- ?assertEqual(?MENTION_SOURCE_PAGE_DEFAULT_LIMIT, clamp_page_limit(undefined)),
- ?assertEqual(1, clamp_page_limit(0)),
- ?assertEqual(50, clamp_page_limit(50)),
- ?assertEqual(?MENTION_SOURCE_PAGE_MAX_LIMIT, clamp_page_limit(100000)).
-
-resolve_mention_sources_page_malformed_payload_rejected_test() ->
- ?assertError(
- {gateway_rpc_error, <<"resolve_mention_sources_page_validation_error">>},
- handle(<<"guild.resolve_mention_sources_page">>, #{})
- ),
- ?assertError(
- {gateway_rpc_error, <<"resolve_mention_sources_page_validation_error">>},
- handle_resolve_sources_page(null)
- ).
-
-parse_page_params_defaults_optional_fields_test() ->
- Params = #{
- <<"guild_id">> => <<"1">>,
- <<"channel_id">> => <<"2">>,
- <<"author_id">> => <<"3">>
- },
- {ok, 1, Req} = parse_page_params(Params),
- ?assertEqual(2, maps:get(channel_id, Req)),
- ?assertEqual(false, maps:get(mention_everyone, Req)),
- ?assertEqual([], maps:get(role_ids, Req)),
- ?assertEqual(
- ?MENTION_SOURCE_PAGE_DEFAULT_LIMIT,
- maps:get(limit, Req)
- ).
-
-mention_guild_calls_pass_the_caller_deadline_test() ->
- assert_call_passes_deadline(
- {
- fun(Pid) -> guild_call_sources_page(Pid, #{limit => 5}) end,
- #{mentions => [], next_cursor => undefined},
- #{<<"mentions">> => [], <<"next_cursor">> => null}
- }
- ).
-
-assert_call_passes_deadline({Call, GuildReply, Expected}) ->
- Self = self(),
- Guild = spawn(fun() ->
- receive
- {'$gen_call', From, Msg} ->
- Self ! {guild_request, Msg},
- gen_server:reply(From, GuildReply)
- end
- end),
- Before = os:system_time(millisecond),
- ?assertEqual(Expected, Call(Guild)),
- receive
- {guild_request, {_Tag, #{deadline := Deadline}}} ->
- ?assert(Deadline >= Before + ?GUILD_CALL_TIMEOUT)
- after 1000 ->
- ?assert(false, guild_request_not_received)
- end.
-
-parse_page_params_rejects_malformed_optional_ids_test() ->
- Base = #{
- <<"guild_id">> => <<"1">>,
- <<"channel_id">> => <<"2">>,
- <<"author_id">> => <<"3">>
- },
- ?assertEqual(error, parse_page_params(Base#{<<"role_ids">> => [<<"4">>, <<"0">>]})),
- ?assertEqual(error, parse_page_params(Base#{<<"user_ids">> => [<<"5">>, <<"bad">>]})),
- ?assertEqual(error, parse_page_params(Base#{<<"cursor">> => <<"001">>})),
- ?assertEqual(error, parse_page_params(Base#{<<"role_ids">> => not_a_list})).
-
--endif.
diff --git a/fluxer_gateway/src/gateway/session_abuse_protection.erl b/fluxer_gateway/src/gateway/session_abuse_protection.erl
index c94da1246..4b71d54d6 100644
--- a/fluxer_gateway/src/gateway/session_abuse_protection.erl
+++ b/fluxer_gateway/src/gateway/session_abuse_protection.erl
@@ -4,7 +4,6 @@
-typing([eqwalizer]).
-export([
- ensure_tables/0,
check_user_session_limit/1,
increment_user_sessions/1,
decrement_user_sessions/1,
@@ -18,12 +17,6 @@
-define(IDENTIFY_CLEANUP_INTERVAL_MS, ?IDENTIFY_WINDOW_SECS * 2 * 1000).
-define(MAX_SESSIONS_PER_USER, 100).
--spec ensure_tables() -> ok.
-ensure_tables() ->
- ensure_identify_table(),
- ensure_session_user_counts_table(),
- ok.
-
-spec check_user_session_limit(term()) -> ok | {error, too_many_sessions}.
check_user_session_limit(UserId) when is_integer(UserId), UserId > 0 ->
case gateway_handler_rate_limit:rate_limits_disabled() of
@@ -175,262 +168,3 @@ prune_old_identify_entries(Table) ->
catch
error:badarg -> gone
end.
-
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-check_identify_rate_allows_under_limit_test() ->
- ensure_tables(),
- IP = <<"192.0.2.100">>,
- ?assertEqual(ok, check_identify_rate(IP)).
-
-check_identify_rate_blocks_over_limit_test() ->
- with_rate_limits_enabled(fun() ->
- ensure_tables(),
- IP = <<"192.0.2.200">>,
- lists:foreach(
- fun(_) -> check_identify_rate(IP) end,
- lists:seq(1, ?IDENTIFY_MAX_PER_IP)
- ),
- ?assertEqual({error, identify_rate_limited}, check_identify_rate(IP))
- end).
-
-check_identify_rate_disabled_by_env_test() ->
- OldValue = os:getenv("FLUXER_DISABLE_RATE_LIMITS"),
- os:putenv("FLUXER_DISABLE_RATE_LIMITS", "true"),
- try
- ensure_tables(),
- IP = <<"192.0.2.201">>,
- lists:foreach(
- fun(_) -> ?assertEqual(ok, check_identify_rate(IP)) end,
- lists:seq(1, ?IDENTIFY_MAX_PER_IP + 1)
- ),
- ?assertEqual(ok, check_identify_rate(IP))
- after
- restore_env("FLUXER_DISABLE_RATE_LIMITS", OldValue)
- end.
-
-user_session_limit_allows_under_limit_test() ->
- ensure_tables(),
- UserId = 900001,
- delete_user_session_count(UserId),
- ?assertEqual(ok, check_user_session_limit(UserId)),
- lists:foreach(fun(_) -> increment_user_sessions(UserId) end, lists:seq(1, 5)),
- ?assertEqual(ok, check_user_session_limit(UserId)),
- delete_user_session_count(UserId).
-
-user_session_limit_blocks_over_limit_test() ->
- with_rate_limits_enabled(fun() ->
- ensure_tables(),
- UserId = 900002,
- delete_user_session_count(UserId),
- lists:foreach(
- fun(_) -> increment_user_sessions(UserId) end,
- lists:seq(1, ?MAX_SESSIONS_PER_USER)
- ),
- ?assertEqual({error, too_many_sessions}, check_user_session_limit(UserId)),
- delete_user_session_count(UserId)
- end).
-
-check_user_session_limit_disabled_by_env_test() ->
- OldValue = os:getenv("FLUXER_DISABLE_RATE_LIMITS"),
- os:putenv("FLUXER_DISABLE_RATE_LIMITS", "true"),
- try
- ensure_tables(),
- UserId = 900005,
- delete_user_session_count(UserId),
- lists:foreach(
- fun(_) -> increment_user_sessions(UserId) end,
- lists:seq(1, ?MAX_SESSIONS_PER_USER + 1)
- ),
- ?assertEqual(ok, check_user_session_limit(UserId)),
- delete_user_session_count(UserId)
- after
- restore_env("FLUXER_DISABLE_RATE_LIMITS", OldValue)
- end.
-
-user_session_decrement_works_test() ->
- with_rate_limits_enabled(fun() ->
- ensure_tables(),
- UserId = 900003,
- delete_user_session_count(UserId),
- lists:foreach(
- fun(_) -> increment_user_sessions(UserId) end,
- lists:seq(1, ?MAX_SESSIONS_PER_USER)
- ),
- ?assertEqual({error, too_many_sessions}, check_user_session_limit(UserId)),
- decrement_user_sessions(UserId),
- ?assertEqual(ok, check_user_session_limit(UserId)),
- delete_user_session_count(UserId)
- end).
-
-user_session_decrement_does_not_go_negative_test() ->
- ensure_tables(),
- UserId = 900004,
- delete_user_session_count(UserId),
- increment_user_sessions(UserId),
- decrement_user_sessions(UserId),
- decrement_user_sessions(UserId),
- ?assertEqual(ok, check_user_session_limit(UserId)).
-
-prune_old_identify_entries_removes_old_buckets_test() ->
- ensure_tables(),
- Now = erlang:system_time(second),
- CurrentBucket = Now div ?IDENTIFY_WINDOW_SECS,
- OldBucket = CurrentBucket - 5,
- OldKey = {<<"10.0.0.1">>, OldBucket},
- CurrentKey = {<<"10.0.0.2">>, CurrentBucket},
- ets:insert(?IDENTIFY_TABLE, {OldKey, 3}),
- ets:insert(?IDENTIFY_TABLE, {CurrentKey, 7}),
- prune_old_identify_entries(?IDENTIFY_TABLE),
- ?assertEqual([], ets:lookup(?IDENTIFY_TABLE, OldKey)),
- ?assertEqual([{CurrentKey, 7}], ets:lookup(?IDENTIFY_TABLE, CurrentKey)),
- ets:delete(?IDENTIFY_TABLE, CurrentKey).
-
-prune_old_identify_entries_keeps_recent_buckets_test() ->
- ensure_tables(),
- Now = erlang:system_time(second),
- CurrentBucket = Now div ?IDENTIFY_WINDOW_SECS,
- RecentKey = {<<"10.0.0.3">>, CurrentBucket - 1},
- ets:insert(?IDENTIFY_TABLE, {RecentKey, 5}),
- prune_old_identify_entries(?IDENTIFY_TABLE),
- ?assertNotEqual([], ets:lookup(?IDENTIFY_TABLE, RecentKey)),
- ets:delete(?IDENTIFY_TABLE, RecentKey).
-
-identify_bucket_survives_creating_process_death_test() ->
- drop_identify_table(),
- {ok, _} = guild_ets_owner:start_link(),
- try
- assert_identify_bucket_outlives_creator()
- after
- gen_server:stop(guild_ets_owner)
- end.
-
-assert_identify_bucket_outlives_creator() ->
- IP = <<"192.0.2.220">>,
- stop_table_owner(start_identify_bucket_creator(IP)),
- ?assertNotEqual(undefined, ets:whereis(?IDENTIFY_TABLE)),
- Key = {IP, erlang:system_time(second) div ?IDENTIFY_WINDOW_SECS},
- ?assertEqual([{Key, 1}], ets:lookup(?IDENTIFY_TABLE, Key)).
-
-start_identify_bucket_creator(IP) ->
- Parent = self(),
- Pid = spawn(fun() -> create_identify_bucket(Parent, IP) end),
- receive
- {owner_ready, Pid} -> Pid
- after 1000 -> error(owner_start_timeout)
- end.
-
-create_identify_bucket(Parent, IP) ->
- ok = check_identify_rate(IP),
- Parent ! {owner_ready, self()},
- receive
- stop -> ok
- after 30000 -> ok
- end.
-
-identify_cleanup_loops_do_not_outlive_their_table_test() ->
- meck:new(gateway_retry_timer, [passthrough]),
- meck:expect(gateway_retry_timer, wait, fun(_) -> timer:sleep(5) end),
- try
- assert_identify_cleanup_loops_do_not_leak()
- after
- meck:unload(gateway_retry_timer)
- end.
-
-assert_identify_cleanup_loops_do_not_leak() ->
- drop_identify_table(),
- Before = count_identify_cleanup_loops(),
- lists:foreach(fun(_) -> churn_identify_table_owner() end, lists:seq(1, 5)),
- Owner = start_identify_table_owner(),
- try
- ?assert(await_identify_cleanup_loops(Before + 1, 200))
- after
- stop_table_owner(Owner)
- end.
-
-drop_identify_table() ->
- case ets:whereis(?IDENTIFY_TABLE) of
- undefined ->
- ok;
- _ ->
- ets:delete(?IDENTIFY_TABLE),
- ok
- end.
-
-churn_identify_table_owner() ->
- stop_table_owner(start_identify_table_owner()).
-
-start_identify_table_owner() ->
- Parent = self(),
- Pid = spawn(fun() -> own_identify_table(Parent) end),
- receive
- {owner_ready, Pid} -> Pid
- after 1000 -> error(owner_start_timeout)
- end.
-
-own_identify_table(Parent) ->
- ok = check_identify_rate(<<"192.0.2.210">>),
- Parent ! {owner_ready, self()},
- receive
- stop -> ok
- after 30000 -> ok
- end.
-
-stop_table_owner(Pid) ->
- Ref = erlang:monitor(process, Pid),
- Pid ! stop,
- receive
- {'DOWN', Ref, process, Pid, _Reason} -> ok
- after 1000 -> error(owner_stop_timeout)
- end.
-
-count_identify_cleanup_loops() ->
- length([Pid || Pid <- erlang:processes(), is_identify_cleanup_loop(Pid)]).
-
-is_identify_cleanup_loop(Pid) ->
- case erlang:process_info(Pid, current_stacktrace) of
- {current_stacktrace, Stack} ->
- lists:any(fun is_identify_cleanup_frame/1, Stack);
- _ ->
- false
- end.
-
-is_identify_cleanup_frame({?MODULE, identify_cleanup_loop, _Arity, _Location}) ->
- true;
-is_identify_cleanup_frame(_Frame) ->
- false.
-
-await_identify_cleanup_loops(Max, 0) ->
- count_identify_cleanup_loops() =< Max;
-await_identify_cleanup_loops(Max, Attempts) ->
- case count_identify_cleanup_loops() =< Max of
- true ->
- true;
- false ->
- timer:sleep(10),
- await_identify_cleanup_loops(Max, Attempts - 1)
- end.
-
-delete_user_session_count(UserId) ->
- try ets:delete(?SESSION_USER_COUNTS, UserId) of
- _ -> ok
- catch
- error:badarg -> ok
- end.
-
-restore_env(Key, false) ->
- os:unsetenv(Key);
-restore_env(Key, Value) ->
- os:putenv(Key, Value).
-
-with_rate_limits_enabled(Fun) ->
- OldValue = os:getenv("FLUXER_DISABLE_RATE_LIMITS"),
- os:unsetenv("FLUXER_DISABLE_RATE_LIMITS"),
- try
- Fun()
- after
- restore_env("FLUXER_DISABLE_RATE_LIMITS", OldValue)
- end.
-
--endif.