Skip to content

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

TypeScript fluxerfluxerapp

refactor(gateway): simplify session connect retry, drop tests

Hampus68120622030b
diff --git a/fluxer_gateway/src/session/session_connection_guild.erl b/fluxer_gateway/src/session/session_connection_guild.erl
index df3da5754..4752fc29d 100644
--- a/fluxer_gateway/src/session/session_connection_guild.erl
+++ b/fluxer_gateway/src/session/session_connection_guild.erl
@@ -9,10 +9,7 @@
handle_guild_connect_timeout/4,
handle_guild_connect_worker_down/3,
maybe_spawn_guild_connect/5,
- finalize_guild_connection/4,
- repair_stalled_guild_connects/1,
- do_guild_connect/1,
- handle_result_internal/4
+ repair_stalled_guild_connects/1
]).
-export_type([session_state/0, guild_id/0, attempt/0, guild_connect_result/0, session_result/0]).
@@ -32,6 +29,15 @@
| {ok_cached_unavailable, map()}
| {error, term()}.
+-type connect_worker_request() :: #{
+ guild_id := guild_id(),
+ attempt := attempt(),
+ session_id := binary(),
+ user_id := integer(),
+ bot := boolean(),
+ is_staff := boolean()
+}.
+
-type session_result() :: {noreply, session_state()} | {stop, normal, session_state()}.
-spec handle_guild_connect(guild_id(), attempt(), session_state()) -> session_result().
@@ -77,31 +83,26 @@ try_acquire_and_spawn(GuildId, Attempt, SessionId, UserId, Inflight0, State) ->
erlang:send_after(50 + Jitter, self(), {guild_connect, GuildId, Attempt}),
{noreply, State};
ok ->
- spawn_guild_connect_worker(
- GuildId, Attempt, SessionId, UserId, Bot, IsStaff, Inflight0, State
- )
+ Request = #{
+ guild_id => GuildId,
+ attempt => Attempt,
+ session_id => SessionId,
+ user_id => UserId,
+ bot => Bot,
+ is_staff => IsStaff
+ },
+ spawn_guild_connect_worker(Request, Inflight0, State)
end.
--spec spawn_guild_connect_worker(
- guild_id(),
- attempt(),
- binary(),
- integer(),
- boolean(),
- boolean(),
- map(),
- session_state()
-) -> {noreply, session_state()}.
-spawn_guild_connect_worker(GuildId, Attempt, SessionId, UserId, Bot, IsStaff, Inflight0, State) ->
+-spec spawn_guild_connect_worker(connect_worker_request(), map(), session_state()) ->
+ {noreply, session_state()}.
+spawn_guild_connect_worker(
+ #{guild_id := GuildId, attempt := Attempt} = Request, Inflight0, State
+) ->
Inflight = Inflight0#{GuildId => Attempt},
- Ctx = #{
+ Ctx = Request#{
+ visit => session_visits:connect_fields(GuildId, State),
session_pid => self(),
- guild_id => GuildId,
- attempt => Attempt,
- session_id => SessionId,
- user_id => UserId,
- bot => Bot,
- is_staff => IsStaff,
initial_guild_id => maps:get(initial_guild_id, State, undefined),
user_data => maps:get(user_data, State, #{}),
thread_channels_capable => maps:get(thread_channels_capable, State, false)
@@ -191,8 +192,7 @@ expire_guild_connect(GuildId, Attempt, State) ->
session_connection_retry:retry_or_fail(
GuildId,
Attempt,
- State1,
- fun session_ready:mark_guild_unavailable/2
+ State1
).
-spec handle_guild_connect_worker_down(reference(), term(), session_state()) ->
@@ -227,8 +227,7 @@ fail_dead_guild_connect_worker(GuildId, Attempt, Reason, State) ->
Result = session_connection_retry:retry_or_fail(
GuildId,
Attempt,
- State1,
- fun session_ready:mark_guild_unavailable/2
+ State1
),
{guild_connect_worker, Result};
_Other ->
@@ -294,19 +293,18 @@ put_guild_connect_workers(Workers, State) ->
guild_id(), attempt(), guild_connect_result(), session_state()
) -> session_result().
handle_result_internal(GuildId, _, {ok_unavailable, GuildPid, Resp}, State) ->
- ReadyFun = fun(St) ->
- session_ready:process_guild_state(Resp, St)
- end,
- finalize_guild_connection(GuildId, GuildPid, State, ReadyFun);
+ finalize_guild_connection(GuildId, GuildPid, State, Resp);
handle_result_internal(GuildId, Attempt, {ok_cached_unavailable, _}, State) ->
session_connection_unavailability:mark_cached_guild_unavailable_and_retry(
GuildId, Attempt, State
);
-handle_result_internal(GuildId, _, {ok, GuildPid, GuildState}, State) ->
- ReadyFun = fun(St) ->
- session_ready:process_guild_state(GuildState, St)
- end,
- finalize_guild_connection(GuildId, GuildPid, State, ReadyFun);
+handle_result_internal(GuildId, _, {ok, GuildPid, GuildState}, State0) ->
+ case session_visits:accept_connect(GuildId, GuildPid, GuildState, State0) of
+ {accept, State} ->
+ finalize_guild_connection(GuildId, GuildPid, State, GuildState);
+ {drop, State} ->
+ session_ready:check_readiness(State)
+ end;
handle_result_internal(GuildId, Attempt, {error, Reason}, State) ->
handle_result_error(GuildId, Attempt, Reason, State).
@@ -315,6 +313,8 @@ handle_result_internal(GuildId, Attempt, {error, Reason}, State) ->
) -> session_result().
handle_result_error(GuildId, Attempt, not_member, State) ->
handle_not_member(GuildId, Attempt, State);
+handle_result_error(GuildId, _Attempt, {visit_rejected, _Reason}, State) ->
+ session_visits:handle_rejected(GuildId, State);
handle_result_error(GuildId, Attempt, {session_connect_failed, Reason}, State) ->
log_and_retry(
"guild_session_connect_failed", GuildId, Attempt, Reason, State
@@ -418,8 +418,7 @@ log_and_retry(Msg, GuildId, Attempt, Reason, State) ->
session_connection_retry:retry_or_fail(
GuildId,
Attempt,
- State,
- fun session_ready:mark_guild_unavailable/2
+ State
).
-spec log_connect_failed(
@@ -434,34 +433,31 @@ log_connect_failed(Msg, GuildId, Attempt, Reason, State) ->
[GuildId, UserId, Attempt, Reason]
).
--spec finalize_guild_connection(guild_id(), pid(), session_state(), fun(
- (session_state()) -> {noreply, session_state()} | {stop, normal, session_state()}
-)) -> {noreply, session_state()} | {stop, normal, session_state()}.
-finalize_guild_connection(GuildId, GuildPid, State, ReadyFun) ->
+-spec finalize_guild_connection(guild_id(), pid(), session_state(), map()) -> session_result().
+finalize_guild_connection(GuildId, GuildPid, State, GuildState) ->
Guilds0 = maps:get(guilds, State),
case maps:find(GuildId, Guilds0) of
{ok, {Pid, _}} when is_pid(Pid) -> {noreply, State};
- _ -> finalize_guild_monitor(GuildId, GuildPid, Guilds0, State, ReadyFun)
+ _ -> finalize_guild_monitor(GuildId, GuildPid, Guilds0, State, GuildState)
end.
--spec finalize_guild_monitor(guild_id(), pid(), map(), session_state(), fun(
- (session_state()) -> {noreply, session_state()} | {stop, normal, session_state()}
-)) -> {noreply, session_state()} | {stop, normal, session_state()}.
-finalize_guild_monitor(GuildId, GuildPid, Guilds0, State, ReadyFun) ->
+-spec finalize_guild_monitor(guild_id(), pid(), map(), session_state(), map()) ->
+ session_result().
+finalize_guild_monitor(GuildId, GuildPid, Guilds0, State, GuildState) ->
MonitorRef = monitor(process, GuildPid),
Guilds = Guilds0#{GuildId => {GuildPid, MonitorRef}},
ok = session_lifecycle:send_guild_push_hold({GuildPid, MonitorRef}, State),
- apply_ready_fun(GuildId, GuildPid, ReadyFun, State#{guilds => Guilds}).
+ process_ready_guild(GuildId, GuildPid, GuildState, State#{guilds => Guilds}).
--spec apply_ready_fun(
+-spec process_ready_guild(
guild_id(),
pid(),
- fun((session_state()) -> session_result()),
+ map(),
session_state()
) -> session_result().
-apply_ready_fun(GuildId, GuildPid, ReadyFun, State) ->
+process_ready_guild(GuildId, GuildPid, GuildState, State) ->
State1 = session_guild_health:forget(GuildId, State),
- case ReadyFun(State1) of
+ case session_ready:process_guild_state(GuildState, State1) of
{noreply, ReadyState} ->
ok = guild_health:send_current(GuildPid, self()),
ReplayedState = maybe_replay_guild_subscriptions(GuildId, GuildPid, ReadyState),
diff --git a/fluxer_gateway/src/session/session_connection_retry.erl b/fluxer_gateway/src/session/session_connection_retry.erl
index 79a330665..7fce464a3 100644
--- a/fluxer_gateway/src/session/session_connection_retry.erl
+++ b/fluxer_gateway/src/session/session_connection_retry.erl
@@ -4,7 +4,7 @@
-typing([eqwalizer]).
-export([
- retry_or_fail/4,
+ retry_or_fail/3,
retry_timeout_without_penalty/3,
handle_call_reconnect/3,
is_guild_manager_nodedown_failure/1,
@@ -24,29 +24,19 @@
-type session_result() :: {noreply, session_state()} | {stop, normal, session_state()}.
--spec retry_or_fail(
- guild_id(),
- attempt(),
- session_state(),
- fun((guild_id(), session_state()) -> session_result())
-) -> session_result().
-retry_or_fail(GuildId, Attempt, State, _FailureFun) when Attempt < ?MAX_RETRY_ATTEMPTS ->
+-spec retry_or_fail(guild_id(), attempt(), session_state()) -> session_result().
+retry_or_fail(GuildId, Attempt, State) when Attempt < ?MAX_RETRY_ATTEMPTS ->
Delay = backoff_utils:calculate_with_jitter(Attempt),
erlang:send_after(Delay, self(), {guild_connect, GuildId, Attempt + 1}),
{noreply, State};
-retry_or_fail(GuildId, Attempt, State, FailureFun) ->
+retry_or_fail(GuildId, Attempt, State) ->
UserId = maps:get(user_id, State),
logger:warning(
"guild_connect_exhausted: guild_id=~p user_id=~p"
" total_attempts=~p slow_retry_ms=~p",
[GuildId, UserId, Attempt, ?GUILD_SLOW_RETRY_DELAY_MS]
),
- case FailureFun(GuildId, State) of
- {noreply, MarkedState} ->
- finish_exhausted_guild_retry(GuildId, MarkedState);
- {stop, normal, _MarkedState} = Stop ->
- Stop
- end.
+ finish_exhausted_guild_retry(GuildId, State).
-spec retry_timeout_without_penalty(guild_id(), attempt(), session_state()) -> session_result().
retry_timeout_without_penalty(GuildId, Attempt, State) when Attempt < ?MAX_RETRY_ATTEMPTS ->
@@ -62,12 +52,12 @@ retry_timeout_without_penalty(GuildId, Attempt, State) ->
" total_attempts=~p slow_retry_ms=~p",
[GuildId, UserId, Attempt, ?GUILD_SLOW_RETRY_DELAY_MS]
),
- {noreply, MarkedState} = session_ready:mark_guild_unavailable(GuildId, State),
- finish_exhausted_guild_retry(GuildId, MarkedState).
+ finish_exhausted_guild_retry(GuildId, State).
-spec finish_exhausted_guild_retry(guild_id(), session_state()) -> session_result().
finish_exhausted_guild_retry(GuildId, State) ->
- case session_ready:check_readiness(State) of
+ {noreply, MarkedState} = session_ready:mark_guild_unavailable(GuildId, State),
+ case session_ready:check_readiness(MarkedState) of
{noreply, ReadyState} ->
erlang:send_after(?GUILD_SLOW_RETRY_DELAY_MS, self(), {guild_connect, GuildId, 0}),
{noreply, ReadyState};
@@ -151,114 +141,3 @@ is_guild_manager_nodedown_failure(_) ->
is_transient_connect_exception(badarg) -> true;
is_transient_connect_exception({badarg, _}) -> true;
is_transient_connect_exception(_) -> false.
-
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-connect_to_call_process_dead_pid_does_not_crash_session_test() ->
- ChannelId = 1234,
- DeadPid = spawn(fun() -> ok end),
- Ref = monitor(process, DeadPid),
- receive
- {'DOWN', Ref, process, DeadPid, _Reason} -> ok
- after 1000 ->
- ?assert(false, call_pid_did_not_exit)
- end,
- {noreply, State} = connect_to_call_process(
- DeadPid,
- ChannelId,
- ?MAX_CALL_RETRY_ATTEMPTS,
- #{calls => #{ChannelId => {self(), make_ref()}}}
- ),
- ?assertEqual(#{}, maps:get(calls, State)).
-
-connect_to_call_process_bad_reply_retries_without_stale_call_test() ->
- ChannelId = 5678,
- CallPid = spawn(fun bad_call_state_loop/0),
- {noreply, State} = connect_to_call_process(
- CallPid,
- ChannelId,
- ?MAX_CALL_RETRY_ATTEMPTS,
- #{calls => #{}}
- ),
- ?assertEqual(#{}, maps:get(calls, State)),
- exit(CallPid, kill).
-
-retry_timeout_without_penalty_exhaustion_marks_unavailable_test() ->
- GuildId = 1427764882469228556,
- State0 = #{
- user_id => 1,
- guilds => #{GuildId => undefined},
- collected_guild_states => [],
- ready => #{<<"guilds">> => []},
- presence_pid => undefined
- },
- {noreply, State1} = retry_timeout_without_penalty(GuildId, ?MAX_RETRY_ATTEMPTS, State0),
- ?assertEqual(unavailable, maps:get(GuildId, maps:get(guilds, State1))),
- [UnavailableState] = maps:get(collected_guild_states, State1),
- ?assertEqual(true, maps:get(<<"unavailable">>, UnavailableState)).
-
-retry_or_fail_exhaustion_checks_readiness_test() ->
- GuildId = 1427764882469228556,
- State0 = #{
- user_id => 1,
- guilds => #{GuildId => undefined},
- collected_guild_states => [],
- ready => #{<<"guilds">> => []},
- presence_pid => self(),
- socket_pid => undefined
- },
- FailFun = fun session_ready:mark_guild_unavailable/2,
- ?assertMatch(
- {stop, normal, _},
- retry_or_fail(GuildId, ?MAX_RETRY_ATTEMPTS, State0, FailFun)
- ).
-
-bad_call_state_loop() ->
- receive
- {'$gen_call', From, {get_state}} ->
- gen_server:reply(From, error),
- bad_call_state_loop();
- _ ->
- bad_call_state_loop()
- after 30000 -> ok
- end.
-
-retry_or_fail_below_max_schedules_jittered_retry_test() ->
- GuildId = 1427764882469228556,
- State0 = #{user_id => 1, guilds => #{GuildId => undefined}},
- FailFun = fun session_ready:mark_guild_unavailable/2,
- {noreply, State0} = retry_or_fail(GuildId, 0, State0, FailFun),
- receive
- {guild_connect, GuildId, 1} -> ok
- after 5000 ->
- ?assert(false, retry_not_scheduled)
- end.
-
-retry_timeout_without_penalty_below_max_schedules_jittered_retry_test() ->
- GuildId = 1427764882469228556,
- State0 = #{user_id => 1, guilds => #{GuildId => undefined}},
- {noreply, State0} = retry_timeout_without_penalty(GuildId, 0, State0),
- receive
- {guild_connect, GuildId, 1} -> ok
- after 5000 ->
- ?assert(false, no_penalty_retry_not_scheduled)
- end.
-
-retry_exhaustion_marks_guild_unavailable_and_schedules_slow_retry_test() ->
- GuildId = 1427764882469228556,
- OtherGuildId = 9999999999,
- State0 = #{
- user_id => 1,
- guilds => #{GuildId => undefined, OtherGuildId => undefined},
- collected_guild_states => [],
- ready => #{<<"guilds">> => []},
- presence_pid => self(),
- socket_pid => self()
- },
- FailFun = fun session_ready:mark_guild_unavailable/2,
- {noreply, State1} = retry_or_fail(GuildId, ?MAX_RETRY_ATTEMPTS, State0, FailFun),
- ?assertEqual(unavailable, maps:get(GuildId, maps:get(guilds, State1))),
- ?assertEqual(undefined, maps:get(OtherGuildId, maps:get(guilds, State1))).
-
--endif.
diff --git a/fluxer_gateway/src/session/session_connection_unavailability.erl b/fluxer_gateway/src/session/session_connection_unavailability.erl
index 2762dab05..e69607441 100644
--- a/fluxer_gateway/src/session/session_connection_unavailability.erl
+++ b/fluxer_gateway/src/session/session_connection_unavailability.erl
@@ -5,10 +5,7 @@
-export([
maybe_handle_cached_unavailability/5,
- mark_cached_guild_unavailable/2,
mark_cached_guild_unavailable_and_retry/3,
- schedule_cached_unavailable_retry/3,
- cached_unavailable_retry_delay_ms/3,
maybe_build_unavailable_response_from_cache/2,
build_initial_active_guilds/2
]).
@@ -119,93 +116,3 @@ build_unavailable_response(GuildId) ->
build_initial_active_guilds(undefined, _GuildId) -> sets:new();
build_initial_active_guilds(GuildId, GuildId) -> sets:from_list([GuildId]);
build_initial_active_guilds(_, _) -> sets:new().
-
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-mark_cached_guild_unavailable_test() ->
- GuildId = 2001,
- CacheState = #{
- id => GuildId,
- data => #{<<"guild">> => #{<<"features">> => [<<"UNAVAILABLE_FOR_EVERYONE">>]}}
- },
- _ = guild_availability:update_unavailability_cache_for_state(CacheState),
- State0 = #{
- id => <<"session-1">>,
- user_id => 55,
- user_data => #{<<"flags">> => <<"0">>},
- guilds => #{GuildId => undefined},
- collected_guild_states => [],
- ready => #{<<"guilds">> => []}
- },
- {noreply, State1} = mark_cached_guild_unavailable(GuildId, State0),
- ?assertEqual(cached_unavailable, maps:get(GuildId, maps:get(guilds, State1))),
- Collected = maps:get(collected_guild_states, State1, []),
- ?assertEqual(1, length(Collected)),
- ?assertMatch(#{<<"id">> := _, <<"unavailable">> := true}, hd(Collected)),
- {noreply, State2} = mark_cached_guild_unavailable(GuildId, State1),
- ?assertEqual(1, length(maps:get(collected_guild_states, State2, []))),
- Cleanup = #{id => GuildId, data => #{<<"guild">> => #{<<"features">> => []}}},
- _ = guild_availability:update_unavailability_cache_for_state(Cleanup),
- ok.
-
-mark_cached_guild_unavailable_hidden_test() ->
- GuildId = 2005,
- CacheState = #{
- id => GuildId,
- data => #{
- <<"guild">> => #{
- <<"features">> => [
- <<"UNAVAILABLE_FOR_EVERYONE">>,
- <<"UNAVAILABLE_HIDDEN">>
- ]
- }
- }
- },
- _ = guild_availability:update_unavailability_cache_for_state(CacheState),
- State0 = #{
- id => <<"session-hidden-1">>,
- user_id => 56,
- user_data => #{<<"flags">> => <<"0">>},
- guilds => #{GuildId => undefined},
- collected_guild_states => [],
- ready => #{<<"guilds">> => []}
- },
- {noreply, State1} = mark_cached_guild_unavailable(GuildId, State0),
- [Entry] = maps:get(collected_guild_states, State1, []),
- ?assertEqual(true, maps:get(<<"unavailable">>, Entry)),
- ?assertEqual(true, maps:get(<<"unavailable_hidden">>, Entry)),
- Cleanup = #{id => GuildId, data => #{<<"guild">> => #{<<"features">> => []}}},
- _ = guild_availability:update_unavailability_cache_for_state(Cleanup),
- ok.
-
-cached_unavailable_retry_delay_ms_cap_test() ->
- ?assertEqual(30000, cached_unavailable_retry_delay_ms(123, <<"session-cap">>, 500)).
-
-cached_unavailable_retry_delay_ms_uses_jitter_test() ->
- Delay = cached_unavailable_retry_delay_ms(123, <<"session-jitter">>, 0),
- ?assert(Delay >= 1000),
- ?assert(Delay =< 1200).
-
-maybe_handle_cached_unavailability_retries_when_cache_available_again_test() ->
- GuildId = 2003,
- CacheState = #{id => GuildId, data => #{<<"guild">> => #{<<"features">> => []}}},
- _ = guild_availability:update_unavailability_cache_for_state(CacheState),
- Inflight = maps:from_list([{N, N} || N <- lists:seq(3000, 3031)]),
- State0 = #{
- id => <<"session-3">>,
- user_id => 88,
- user_data => #{<<"flags">> => <<"0">>},
- guilds => #{GuildId => cached_unavailable},
- guild_connect_inflight => Inflight
- },
- {noreply, State1} = maybe_handle_cached_unavailability(
- GuildId, 42, <<"session-3">>, 88, State0
- ),
- ?assertEqual(undefined, maps:get(GuildId, maps:get(guilds, State1))),
- receive
- {guild_connect, GuildId, 0} -> ok
- after 300 -> ?assert(false, guild_connect_retry_not_scheduled_with_reset_attempt)
- end.
-
--endif.