A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(gateway): remove voice, call, cluster and core eunit tests
Hampusd4be170e9851
diff --git a/fluxer_gateway/src/cache/clustered_ets_cache.erl b/fluxer_gateway/src/cache/clustered_ets_cache.erlindex 876370927..757892a0b 100644--- a/fluxer_gateway/src/cache/clustered_ets_cache.erl+++ b/fluxer_gateway/src/cache/clustered_ets_cache.erl@@ -215,110 +215,3 @@ validate_shard_count(Value) when is_integer(Value), Value > 0 ->{ok, Value};validate_shard_count(_) ->error.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--resolve_owner_node_rejects_invalid_role_owner_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{gateway_role => websocket}- ),- persistent_term:put({gateway_cluster_membership, members_by_role}, #{- websocket => [node()]- }),- ?assertEqual(- unavailable,- resolve_owner_node(42, presence)- ),- persistent_term:erase({gateway_cluster_membership, members_by_role}),- persistent_term:erase({fluxer_gateway, runtime_config}).--group_keys_by_owner_skips_unavailable_role_owner_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{gateway_role => websocket}- ),- persistent_term:put({gateway_cluster_membership, members_by_role}, #{- websocket => [node()]- }),- ?assertEqual([], group_keys_by_owner([1, 2], presence)),- persistent_term:erase({gateway_cluster_membership, members_by_role}),- persistent_term:erase({fluxer_gateway, runtime_config}).--group_keys_by_owner_deduplicates_and_sorts_test() ->- NodeA = '[email protected]',- NodeB = '[email protected]',- Groups = group_keys_by_owner(- [2, 1, 2, 4, 3],- fun- (Key) when Key rem 2 =:= 0 -> NodeB;- (_Key) -> NodeA- end- ),- ?assertEqual([{NodeA, [1, 3]}, {NodeB, [2, 4]}], Groups).--group_keys_by_owner_accepts_role_test() ->- persistent_term:put({gateway_cluster_membership, members_by_role}, #{- presence => ['[email protected]'],- all => ['[email protected]']- }),- Groups = group_keys_by_owner([1, 2], presence),- Owners = [Owner || {Owner, _Keys} <- Groups],- ?assert(- lists:all(- fun(Owner) ->- lists:member(Owner, ['[email protected]', '[email protected]'])- end,- Owners- )- ),- persistent_term:erase({gateway_cluster_membership, members_by_role}).--resolve_owner_nodes_accepts_role_test() ->- persistent_term:put({gateway_cluster_membership, members_by_role}, #{- presence => ['[email protected]', '[email protected]']- }),- Nodes = resolve_owner_nodes(123, 2, presence),- ?assertEqual(2, length(Nodes)),- ?assert(- lists:all(- fun(Node) ->- lists:member(Node, ['[email protected]', '[email protected]'])- end,- Nodes- )- ),- persistent_term:erase({gateway_cluster_membership, members_by_role}).--select_owner_nodes_respects_replica_count_test() ->- SelectedNodes = select_owner_nodes(<<"guild-123">>, Nodes, 2),- ?assertEqual(2, length(SelectedNodes)),- ?assertEqual(length(SelectedNodes), length(lists:usort(SelectedNodes))).--resolve_owner_nodes_includes_primary_owner_test() ->- Key = <<"presence-owner-set">>,- PrimaryNode = '[email protected]',- CandidateNodes = [PrimaryNode, '[email protected]'],- SelectedNodes = select_owner_nodes(Key, CandidateNodes, 2),- ?assert(lists:member(PrimaryNode, SelectedNodes)).--determine_shard_count_uses_first_valid_key_test() ->- {Count, Source} = determine_shard_count(- [guild_counts_cache_shards, guild_shards],- fun- (guild_counts_cache_shards) -> undefined;- (guild_shards) -> 5;- (_) -> undefined- end- ),- ?assertEqual(5, Count),- ?assertEqual(guild_shards, Source).--determine_shard_count_defaults_when_no_keys_set_test() ->- {Count, Source} = determine_shard_count([presence_cache_shards], fun(_) -> undefined end),- ?assert(Count >= 1),- ?assertEqual(auto, Source).---endif.diff --git a/fluxer_gateway/src/call/call_handoff.erl b/fluxer_gateway/src/call/call_handoff.erlindex cbe4328d7..fe0a8629a 100644--- a/fluxer_gateway/src/call/call_handoff.erl+++ b/fluxer_gateway/src/call/call_handoff.erl@@ -166,36 +166,3 @@ normalize_joined_at(Value) when is_integer(Value) ->Value;normalize_joined_at(_Value) ->erlang:system_time(millisecond).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--restore_state_remonitors_live_sessions_test() ->- SessionPid = spawn(fun() ->- receive- stop -> ok- end- end),- SessionId = <<"session-a">>,- VoiceState = #{<<"connection_id">> => <<"conn-a">>},- TransferState = #{- channel_id => 123,- message_id => 456,- region => null,- ringing => [1],- pending_ringing => [],- recipients => [1],- voice_states => #{1 => VoiceState},- sessions => #{SessionId => #{user_id => 1, session_pid => SessionPid}},- pending_connections => #{},- participants_history => [1]- },- Restored = restore_state(TransferState),- ?assertMatch(- {1, SessionPid, Ref} when is_reference(Ref),- maps:get(SessionId, maps:get(sessions, Restored))- ),- ?assertEqual(#{1 => VoiceState}, maps:get(voice_states, Restored)),- SessionPid ! stop.---endif.diff --git a/fluxer_gateway/src/call/call_ringing.erl b/fluxer_gateway/src/call/call_ringing.erlindex 9979d2d59..5683faa48 100644--- a/fluxer_gateway/src/call/call_ringing.erl+++ b/fluxer_gateway/src/call/call_ringing.erl@@ -378,128 +378,3 @@ maybe_stop_if_empty(State) ->-spec call_has_activity(map()) -> boolean().call_has_activity(State) ->maps:size(maps:get(voice_states, State)) > 0 orelse maps:get(ringing, State) =/= [].---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--ring_state(Recipients, Ringing, Pending, VoiceStates) ->- #{- channel_id => 100,- message_id => 200,- region => undefined,- ringing => Ringing,- pending_ringing => Pending,- recipients => Recipients,- voice_states => VoiceStates,- ringing_timers => #{},- initiator_ready => true,- last_call_event => undefined- }.--published_ring_args() ->- History = meck:history(push_job_publisher),- [Args || {_Pid, {push_job_publisher, publish_ring, Args}, _Result} <- History].--published_ring_users() ->- lists:usort([UserId || [UserId, _C, _M, _S, _E, _Caller] <- published_ring_args()]).--mock_ring_publisher() ->- ok = meck:new(push_job_publisher, [passthrough, no_link]),- meck:expect(push_job_publisher, publish_ring, fun(_U, _C, _M, _S, _E, _Caller) -> ok end).--apply_pending_ringing_publishes_one_ring_per_new_user_test() ->- ok = mock_ring_publisher(),- try- State = ring_state([1, 2, 3], [], [2, 3], #{}),- _ = maybe_dispatch_pending_ringing(State, false),- ok = meck:wait(2, push_job_publisher, publish_ring, '_', 2000),- ?assertEqual([2, 3], published_ring_users())- after- meck:unload(push_job_publisher)- end.--apply_pending_ringing_publishes_the_frozen_ring_fields_test() ->- ok = mock_ring_publisher(),- try- State = ring_state([1, 2], [], [2], #{}),- _ = maybe_dispatch_pending_ringing(State, false),- ok = meck:wait(1, push_job_publisher, publish_ring, '_', 2000),- [[UserId, ChannelId, MessageId, StartedAt, ExpiresAt, _Caller]] = published_ring_args(),- ?assertEqual({2, 100, 200}, {UserId, ChannelId, MessageId}),- ?assertEqual(?RING_TIMEOUT_MS, ExpiresAt - StartedAt)- after- meck:unload(push_job_publisher)- end.--apply_pending_ringing_does_not_publish_for_a_user_already_ringing_test() ->- ok = mock_ring_publisher(),- try- State = ring_state([1, 2], [2], [2], #{}),- _ = maybe_dispatch_pending_ringing(State, false),- ?assertEqual([], published_ring_args())- after- meck:unload(push_job_publisher)- end.--apply_pending_ringing_does_not_publish_for_a_connected_user_test() ->- ok = mock_ring_publisher(),- try- State = ring_state([1, 2], [], [2], #{2 => #{}}),- _ = maybe_dispatch_pending_ringing(State, false),- ?assertEqual([], published_ring_args())- after- meck:unload(push_job_publisher)- end.--start_ringing_timers_does_not_publish_test() ->- ok = mock_ring_publisher(),- try- State = ring_state([1, 2], [2], [], #{}),- _ = start_ringing_timers([2], State),- ?assertEqual([], published_ring_args())- after- meck:unload(push_job_publisher)- end.--publish_ring_jobs_suppresses_a_fully_blocked_ring_test() ->- ok = mock_ring_publisher(),- ok = meck:new(push_eligibility, [passthrough, no_link]),- try- ok = meck:expect(push_eligibility, is_user_blocked, fun(_U, _O) -> true end),- ok = publish_ring_jobs(- [2], [1, 2], build_ring_context(ring_state([1, 2], [], [], #{}))- ),- ?assertEqual([], published_ring_args())- after- meck:unload(push_eligibility),- meck:unload(push_job_publisher)- end.--ring_is_suppressed_when_every_other_recipient_is_blocked_test() ->- ok = meck:new(push_eligibility, [passthrough, no_link]),- try- ok = meck:expect(push_eligibility, is_user_blocked, fun(_U, _O) -> true end),- ?assertEqual(true, ring_suppressed(2, [1, 2, 3]))- after- meck:unload(push_eligibility)- end.--ring_is_not_suppressed_when_one_other_recipient_is_unblocked_test() ->- ok = meck:new(push_eligibility, [passthrough, no_link]),- try- ok = meck:expect(push_eligibility, is_user_blocked, fun(_U, Other) -> Other =:= 1 end),- ?assertEqual(false, ring_suppressed(2, [1, 2, 3]))- after- meck:unload(push_eligibility)- end.--ring_is_not_suppressed_for_a_lone_recipient_test() ->- ok = meck:new(push_eligibility, [passthrough, no_link]),- try- ok = meck:expect(push_eligibility, is_user_blocked, fun(_U, _O) -> true end),- ?assertEqual(false, ring_suppressed(2, [2]))- after- meck:unload(push_eligibility)- end.---endif.diff --git a/fluxer_gateway/src/gateway/fluxer_gateway_sup.erl b/fluxer_gateway/src/gateway/fluxer_gateway_sup.erlindex 8ebaa6f17..69c3fe779 100644--- a/fluxer_gateway/src/gateway/fluxer_gateway_sup.erl+++ b/fluxer_gateway/src/gateway/fluxer_gateway_sup.erl@@ -1,9 +1,6 @@%% SPDX-License-Identifier: AGPL-3.0-or-later-module(fluxer_gateway_sup).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.-typing([eqwalizer]).-behaviour(supervisor).@@ -219,85 +216,3 @@ child_spec(Id, Module) ->shutdown => 5000,type => worker}.---ifdef(TEST).--guild_role_starts_ets_owner_before_guild_workers_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => guilds}),- ?assert(lists:member(guild_ets_owner, Ids)),- ?assert(owner_precedes(guild_ets_owner, gateway_nats_rpc, Ids)),- ?assert(owner_precedes(guild_ets_owner, guild_manager, Ids)),- ?assert(owner_precedes(guild_ets_owner, voice_state_counts_sync, Ids)).--calls_role_starts_ets_owner_before_call_workers_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => calls}),- ?assert(lists:member(guild_ets_owner, Ids)),- ?assert(owner_precedes(guild_ets_owner, call_manager, Ids)),- ?assert(owner_precedes(guild_ets_owner, voice_state_counts_sync, Ids)).--calls_role_starts_the_push_outbox_for_rings_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => calls}),- ?assertEqual(1, count_id(push_outbox, Ids)),- ?assert(owner_precedes(push_outbox, call_manager, Ids)).--push_role_starts_the_push_outbox_before_push_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => push}),- ?assertEqual(1, count_id(push_outbox, Ids)),- ?assert(owner_precedes(push_outbox, push, Ids)).--all_role_starts_a_single_push_outbox_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => all}),- ?assertEqual(1, count_id(push_outbox, Ids)).--all_role_starts_single_ets_owner_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => all}),- ?assertEqual(1, count_id(guild_ets_owner, Ids)).--sessions_role_starts_ets_owner_before_session_workers_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => sessions}),- ?assert(lists:member(guild_ets_owner, Ids)),- ?assert(owner_precedes(guild_ets_owner, session_manager, Ids)).--websocket_role_starts_ets_owner_before_rpc_workers_test() ->- Ids = init_child_ids(#{cluster_enabled => true, gateway_role => websocket}),- ?assert(lists:member(guild_ets_owner, Ids)),- ?assert(owner_precedes(guild_ets_owner, gateway_nats_rpc, Ids)).--init_child_ids(Config) ->- persistent_term:put({fluxer_gateway, runtime_config}, Config),- try- {ok, {_SupFlags, Children}} = init([]),- [maps:get(id, Child) || Child <- Children, is_map(Child)]- after- persistent_term:erase({fluxer_gateway, runtime_config})- end.--owner_precedes(Owner, Worker, Ids) ->- index_of(Owner, Ids) < index_of(Worker, Ids).--index_of(Id, Ids) ->- index_of(Id, Ids, 1).--index_of(Id, [Id | _Rest], Index) ->- Index;-index_of(Id, [_Other | Rest], Index) ->- index_of(Id, Rest, Index + 1);-index_of(_Id, [], _Index) ->- 1000000.--channel_threads_config_runs_on_every_role_after_the_flip_scheduler_test() ->- lists:foreach(- fun(Role) ->- Ids = init_child_ids(#{cluster_enabled => false, gateway_role => Role}),- ?assertEqual(1, count_id(channel_threads_config, Ids)),- ?assertEqual(1, count_id(channel_threads_flip, Ids)),- ?assert(owner_precedes(gateway_nats_rpc, channel_threads_config, Ids)),- ?assert(owner_precedes(channel_threads_flip, channel_threads_config, Ids))- end,- [all, websocket, sessions, presence, guilds, calls, push]- ).--count_id(Id, Ids) ->- length([Item || Item <- Ids, Item =:= Id]).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_clock_offset.erl b/fluxer_gateway/src/gateway/gateway_clock_offset.erlindex e1386622b..04bf8ad26 100644--- a/fluxer_gateway/src/gateway/gateway_clock_offset.erl+++ b/fluxer_gateway/src/gateway/gateway_clock_offset.erl@@ -126,17 +126,3 @@ report(_Server, _Node, _Ref, discard) ->-spec read_remote_clock(node()) -> integer().read_remote_clock(Node) ->erpc:call(Node, erlang, monotonic_time, [millisecond], ?PROBE_TIMEOUT_MS).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--sample_retains_the_full_return_trip_uncertainty_test() ->- ?assertEqual({ok, 4990}, sample(15000, 10010, 20)),- ?assertEqual({ok, -5000}, sample(5000, 10000, 0)),- ?assertEqual(discard, sample(15000, 10000, 101)),- ?assertEqual(discard, sample(15000, 10000, -1)).--local_clock_does_not_need_a_probe_test() ->- ?assertEqual(0, offset(node())).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_cluster_handoff_transfer.erl b/fluxer_gateway/src/gateway/gateway_cluster_handoff_transfer.erlindex 5763b0550..00a257ec7 100644--- a/fluxer_gateway/src/gateway/gateway_cluster_handoff_transfer.erl+++ b/fluxer_gateway/src/gateway/gateway_cluster_handoff_transfer.erl@@ -125,112 +125,3 @@ normalize_pids(Pids) when is_list(Pids) ->[Pid || Pid <- Pids, is_pid(Pid)];normalize_pids(_Pids) ->[].---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--run_handoff_handles_missing_managers_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{gateway_role => websocket}- ),- Result = run_handoff([node()]),- ?assertMatch(- #{status := ok, members := [Node]} when- Node =:= node(),- Result- ),- ?assertEqual(skipped, maps:get(guilds, Result)),- ?assertEqual(skipped, maps:get(sessions, Result)),- ?assertEqual(skipped, maps:get(calls, Result)),- ?assert(maps:is_key(caches, Result)),- persistent_term:erase({fluxer_gateway, runtime_config}).--handoff_status_marks_partial_handoff_as_error_test() ->- Result = #{- guilds => #{attempted => 2, handed_off => 1},- sessions => {ok, #{attempted => 0, handed_off => 0}},- caches => #{presence => ok}- },- ?assertEqual(error, handoff_status(Result)).--handoff_status_marks_failed_session_handoff_as_error_test() ->- Result = #{- guilds => #{attempted => 0, handed_off => 0},- sessions => {ok, #{attempted => 2, handed_off => 1}},- caches => #{presence => ok}- },- ?assertEqual(error, handoff_status(Result)).--handoff_status_accepts_complete_handoff_test() ->- Result = #{- guilds => #{attempted => 2, handed_off => 2},- sessions => {ok, #{attempted => 3, handed_off => 3}},- caches => #{presence => ok, push => skipped}- },- ?assertEqual(ok, handoff_status(Result)).--drain_targets_prefers_survivors_test() ->- ?assertEqual(- ['peer@host'],- drain_targets([node(), 'peer@host'])- ),- ?assertEqual([node()], drain_targets([node()])).--role_aware_targets_uses_role_nodes_test() ->- persistent_term:put(- {gateway_cluster_membership, members_by_role},- #{- guilds => ['guilds@a', 'guilds@b'],- sessions => ['sessions@a'],- all => ['all@a']- }- ),- GuildTargets = role_aware_targets(guilds, [node(), 'fallback@a']),- ?assert(lists:member('guilds@a', GuildTargets)),- ?assert(lists:member('all@a', GuildTargets)),- ?assertNot(lists:member('fallback@a', GuildTargets)),- SessionTargets = role_aware_targets(- sessions,- [node(), 'fallback@a']- ),- ?assert(lists:member('sessions@a', SessionTargets)),- ?assert(lists:member('all@a', SessionTargets)),- persistent_term:erase(- {gateway_cluster_membership, members_by_role}- ).--role_aware_targets_does_not_fall_back_to_wrong_role_test() ->- persistent_term:put(- {gateway_cluster_membership, members_by_role},- #{sessions => ['sessions@a']}- ),- Fallback = ['peer@a', 'peer@b'],- ?assertEqual([], role_aware_targets(guilds, Fallback)),- persistent_term:erase(- {gateway_cluster_membership, members_by_role}- ).--role_aware_targets_keeps_self_for_normal_topology_test() ->- persistent_term:put(- {gateway_cluster_membership, members_by_role},- #{guilds => [node(), 'guilds@a']}- ),- Targets = role_aware_targets(guilds, [node()]),- ?assertEqual([node()], Targets),- persistent_term:erase(- {gateway_cluster_membership, members_by_role}- ).--role_aware_targets_keeps_self_when_only_node_test() ->- persistent_term:put(- {gateway_cluster_membership, members_by_role},- #{guilds => [node()]}- ),- Targets = role_aware_targets(guilds, [node()]),- ?assertEqual([node()], Targets),- persistent_term:erase(- {gateway_cluster_membership, members_by_role}- ).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_concurrency.erl b/fluxer_gateway/src/gateway/gateway_concurrency.erlindex a92916b56..fa1a9a194 100644--- a/fluxer_gateway/src/gateway/gateway_concurrency.erl+++ b/fluxer_gateway/src/gateway/gateway_concurrency.erl@@ -122,34 +122,3 @@ terminate(_Reason, _State) ->code_change(_OldVsn, State, _Extra) ->erlang:garbage_collect(),{ok, State}.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--concurrency_acquire_release_test() ->- {ok, _Pid} = start_link(),- ?assertEqual(0, session_start_count()),- ?assertEqual(ok, try_acquire_session_start()),- ?assertEqual(1, session_start_count()),- ?assertEqual(ok, release_session_start()),- ?assertEqual(0, session_start_count()),- gen_server:stop(?MODULE).--release_without_acquire_does_not_underflow_test() ->- {ok, _Pid} = start_link(),- ?assertEqual(ok, release_session_start()),- ?assertEqual(ok, release_guild_start()),- ?assertEqual(0, session_start_count()),- ?assertEqual(0, guild_start_count()),- gen_server:stop(?MODULE).--acquire_is_bounded_at_limit_test() ->- {ok, _Pid} = start_link(),- Ref = persistent_term:get(gateway_concurrency_counters),- ?assertEqual(ok, do_acquire(?SESSION_START_IDX, 1, Ref)),- ?assertEqual(1, session_start_count()),- ?assertEqual({error, at_capacity}, do_acquire(?SESSION_START_IDX, 1, Ref)),- ?assertEqual(1, session_start_count()),- gen_server:stop(?MODULE).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_handler_rate_limit.erl b/fluxer_gateway/src/gateway/gateway_handler_rate_limit.erlindex 121785ae8..d585a5688 100644--- a/fluxer_gateway/src/gateway/gateway_handler_rate_limit.erl+++ b/fluxer_gateway/src/gateway/gateway_handler_rate_limit.erl@@ -29,11 +29,6 @@-type state() :: gateway_handler:state().--ifdef(TEST).---include_lib("eunit/include/eunit.hrl").--endif.--spec check_rate_limit(state(), atom()) ->{ok, state()} | {rate_limited, state()} | {opcode_rate_limited, state()}.check_rate_limit(State, Op) ->@@ -283,268 +278,3 @@ rate_limits_disabled() ->"TRUE" -> true;_ -> falseend.---ifdef(TEST).--check_rate_limit_disabled_by_env_test() ->- Now = erlang:system_time(millisecond),- State = #{- rate_limit_state => #{- events => lists:duplicate(130, Now),- op_events => #{presence_update => lists:duplicate(10, Now)}- }- },- OldValue = os:getenv("FLUXER_DISABLE_RATE_LIMITS"),- os:putenv("FLUXER_DISABLE_RATE_LIMITS", "true"),- try- CastState = eqwalizer:dynamic_cast(State),- ?assertEqual({ok, CastState}, check_rate_limit(CastState, presence_update))- after- restore_env("FLUXER_DISABLE_RATE_LIMITS", OldValue)- 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.--forum_unreads_allows_five_requests_per_five_seconds_test() ->- with_rate_limits_enabled(fun() ->- Now = erlang:system_time(millisecond),- Recent = #{request_forum_unreads => lists:duplicate(4, Now)},- State = eqwalizer:dynamic_cast(#{- rate_limit_state => #{events => [], op_events => Recent}- }),- {ok, Next} = check_rate_limit_limited(State, request_forum_unreads),- ?assertMatch(- {opcode_rate_limited, _}, check_rate_limit_limited(Next, request_forum_unreads)- ),- Old = #{request_forum_unreads => lists:duplicate(5, Now - 5000)},- Expired = eqwalizer:dynamic_cast(#{- rate_limit_state => #{events => [], op_events => Old}- }),- ?assertMatch({ok, _}, check_rate_limit_limited(Expired, request_forum_unreads)),- Full = #{request_guild_counts => lists:duplicate(5, Now)},- Other = eqwalizer:dynamic_cast(#{- rate_limit_state => #{events => [], op_events => Full}- }),- ?assertMatch({ok, _}, check_rate_limit_limited(Other, request_guild_counts))- end).--shared_ip_rate_blocks_over_limit_test() ->- with_rate_limits_enabled(fun() ->- IP = <<"198.51.100.10">>,- reset_shared_ip(IP),- assert_shared_ip_rate_allows_limit(IP),- ?assertEqual({error, ip_rate_limited}, check_shared_ip_rate(IP)),- reset_shared_ip(IP)- end).--shared_ip_rate_ignores_unknown_ip_test() ->- with_rate_limits_enabled(fun() ->- ?assertEqual(ok, check_shared_ip_rate(<<"unknown">>)),- ?assertEqual(ok, check_shared_ip_rate(undefined))- end).--assert_shared_ip_rate_allows_limit(IP) ->- lists:foreach(- fun(_) -> ?assertEqual(ok, check_shared_ip_rate(IP)) end,- lists:seq(1, ?SHARED_IP_RATE_MAX_EVENTS)- ).--reset_shared_ip(IP) ->- case ets:whereis(?SHARED_IP_RATE_TABLE) of- undefined ->- ok;- _ ->- Now = erlang:system_time(millisecond),- Bucket = Now div ?SHARED_IP_RATE_WINDOW_MS,- ets:delete(?SHARED_IP_RATE_TABLE, {IP, Bucket}),- ok- end.--prune_old_window_entries_removes_old_buckets_test() ->- with_rate_limits_enabled(fun() ->- ok = check_shared_ip_rate(<<"198.51.100.50">>),- CurrentBucket = erlang:system_time(millisecond) div ?SHARED_IP_RATE_WINDOW_MS,- OldKey = {<<"198.51.100.51">>, CurrentBucket - 5},- CurrentKey = {<<"198.51.100.52">>, CurrentBucket},- ets:insert(?SHARED_IP_RATE_TABLE, [{OldKey, 3}, {CurrentKey, 7}]),- prune_old_window_entries(?SHARED_IP_RATE_TABLE, ?SHARED_IP_RATE_WINDOW_MS),- ?assertEqual([], ets:lookup(?SHARED_IP_RATE_TABLE, OldKey)),- ?assertEqual([{CurrentKey, 7}], ets:lookup(?SHARED_IP_RATE_TABLE, CurrentKey)),- ets:delete(?SHARED_IP_RATE_TABLE, CurrentKey)- end).--prune_old_window_entries_keeps_recent_buckets_test() ->- with_rate_limits_enabled(fun() ->- ok = check_shared_user_rate(<<"user-900100">>),- CurrentBucket = erlang:system_time(millisecond) div ?SHARED_USER_RATE_WINDOW_MS,- RecentKey = {<<"user-900101">>, CurrentBucket - 1},- ets:insert(?SHARED_USER_RATE_TABLE, {RecentKey, 5}),- prune_old_window_entries(?SHARED_USER_RATE_TABLE, ?SHARED_USER_RATE_WINDOW_MS),- ?assertNotEqual([], ets:lookup(?SHARED_USER_RATE_TABLE, RecentKey)),- ets:delete(?SHARED_USER_RATE_TABLE, RecentKey)- end).--shared_ip_rate_table_sweeps_stale_buckets_test() ->- with_rate_limits_enabled(fun() -> with_fast_cleanup_timer(fun sweep_stale_ip_buckets/0) end).--with_fast_cleanup_timer(Fun) ->- meck:new(gateway_retry_timer, [passthrough]),- meck:expect(gateway_retry_timer, wait, fun(_) -> timer:sleep(5) end),- try- Fun()- after- meck:unload(gateway_retry_timer)- end.--sweep_stale_ip_buckets() ->- drop_table(?SHARED_IP_RATE_TABLE),- IP = <<"198.51.100.40">>,- ?assertEqual(ok, check_shared_ip_rate(IP)),- Bucket = erlang:system_time(millisecond) div ?SHARED_IP_RATE_WINDOW_MS,- fill_stale_buckets(?SHARED_IP_RATE_TABLE, IP, Bucket, 200),- ?assert(await_table_size(?SHARED_IP_RATE_TABLE, 2, 150)).--drop_table(Table) ->- case ets:whereis(Table) of- undefined ->- ok;- _ ->- ets:delete(Table),- ok- end.--fill_stale_buckets(Table, Key, Bucket, Count) ->- lists:foreach(- fun(N) -> ets:insert(Table, {{Key, Bucket - N - 1}, 1}) end,- lists:seq(1, Count)- ).--await_table_size(Table, Max, 0) ->- ets:info(Table, size) =< Max;-await_table_size(Table, Max, Attempts) ->- case ets:info(Table, size) =< Max of- true ->- true;- false ->- timer:sleep(10),- await_table_size(Table, Max, Attempts - 1)- end.--shared_ip_bucket_survives_creating_process_death_test() ->- with_rate_limits_enabled(fun assert_shared_ip_bucket_survives_creator/0).--assert_shared_ip_bucket_survives_creator() ->- drop_table(?SHARED_IP_RATE_TABLE),- {ok, _} = guild_ets_owner:start_link(),- try- assert_shared_ip_bucket_outlives_creator()- after- gen_server:stop(guild_ets_owner)- end.--assert_shared_ip_bucket_outlives_creator() ->- IP = <<"198.51.100.70">>,- stop_table_owner(start_shared_ip_bucket_creator(IP)),- ?assertNotEqual(undefined, ets:whereis(?SHARED_IP_RATE_TABLE)),- Key = {IP, erlang:system_time(millisecond) div ?SHARED_IP_RATE_WINDOW_MS},- ?assertEqual([{Key, 1}], ets:lookup(?SHARED_IP_RATE_TABLE, Key)).--start_shared_ip_bucket_creator(IP) ->- Parent = self(),- Pid = spawn(fun() -> create_shared_ip_bucket(Parent, IP) end),- receive- {owner_ready, Pid} -> Pid- after 1000 -> error(owner_start_timeout)- end.--create_shared_ip_bucket(Parent, IP) ->- ok = check_shared_ip_rate(IP),- Parent ! {owner_ready, self()},- receive- stop -> ok- after 30000 -> ok- end.--window_cleanup_loops_do_not_outlive_their_table_test() ->- with_rate_limits_enabled(fun() ->- with_fast_cleanup_timer(fun assert_window_cleanup_loops_do_not_leak/0)- end).--assert_window_cleanup_loops_do_not_leak() ->- drop_table(?SHARED_IP_RATE_TABLE),- Before = count_window_cleanup_loops(),- lists:foreach(fun(_) -> churn_shared_ip_table_owner() end, lists:seq(1, 5)),- Owner = start_shared_ip_table_owner(),- try- ?assert(await_window_cleanup_loops(Before + 1, 200))- after- stop_table_owner(Owner)- end.--churn_shared_ip_table_owner() ->- stop_table_owner(start_shared_ip_table_owner()).--start_shared_ip_table_owner() ->- Parent = self(),- Pid = spawn(fun() -> own_shared_ip_table(Parent) end),- receive- {owner_ready, Pid} -> Pid- after 1000 -> error(owner_start_timeout)- end.--own_shared_ip_table(Parent) ->- ok = check_shared_ip_rate(<<"198.51.100.60">>),- 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_window_cleanup_loops() ->- length([Pid || Pid <- erlang:processes(), is_window_cleanup_loop(Pid)]).--is_window_cleanup_loop(Pid) ->- case erlang:process_info(Pid, current_stacktrace) of- {current_stacktrace, Stack} ->- lists:any(fun is_window_cleanup_frame/1, Stack);- _ ->- false- end.--is_window_cleanup_frame({?MODULE, window_cleanup_loop, _Arity, _Location}) ->- true;-is_window_cleanup_frame(_Frame) ->- false.--await_window_cleanup_loops(Max, 0) ->- count_window_cleanup_loops() =< Max;-await_window_cleanup_loops(Max, Attempts) ->- case count_window_cleanup_loops() =< Max of- true ->- true;- false ->- timer:sleep(10),- await_window_cleanup_loops(Max, Attempts - 1)- end.---endif.diff --git a/fluxer_gateway/src/gateway/gateway_http_client_request.erl b/fluxer_gateway/src/gateway/gateway_http_client_request.erlindex ad9c0c45e..27638171f 100644--- a/fluxer_gateway/src/gateway/gateway_http_client_request.erl+++ b/fluxer_gateway/src/gateway/gateway_http_client_request.erl@@ -280,94 +280,3 @@ is_char_element(_) -> false.coerce_char_element(V) when is_integer(V) -> V;coerce_char_element(V) when is_binary(V) -> V;coerce_char_element(_) -> $?.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--is_https_url_true_for_https_test() ->- ?assertEqual(true, is_https_url("https://fcm.googleapis.com/v1")),- ?assertEqual(true, is_https_url("HTTPS://oauth2.googleapis.com/token")).--is_https_url_false_for_http_test() ->- ?assertEqual(false, is_https_url("http://127.0.0.1:8088/rpc")),- ?assertEqual(false, is_https_url("not-a-url")).--build_http_options_adds_ssl_for_https_test() ->- case has_ca_store() of- true ->- Opts = #{connect_timeout => 3000, recv_timeout => 5000},- Options = build_http_options("https://fcm.googleapis.com/v1", Opts),- ?assertMatch([{ssl, _} | _], Options),- {ssl, SslOpts} = lists:keyfind(ssl, 1, Options),- ?assertEqual({verify, verify_peer}, lists:keyfind(verify, 1, SslOpts)),- ?assertMatch({cacerts, [_ | _]}, lists:keyfind(cacerts, 1, SslOpts)),- ?assertEqual({depth, 9}, lists:keyfind(depth, 1, SslOpts)),- ?assertMatch(- {customize_hostname_check, _},- lists:keyfind(customize_hostname_check, 1, SslOpts)- );- false ->- ok- end.--has_ca_store() ->- try public_key:cacerts_get() of- Certs when is_list(Certs), Certs =/= [] -> true;- _ -> false- catch- _:_ -> false- end.--build_http_options_omits_ssl_for_http_test() ->- Opts = #{connect_timeout => 5000, recv_timeout => 30000},- Options = build_http_options("http://127.0.0.1:8088/rpc", Opts),- ?assertEqual(false, lists:keyfind(ssl, 1, Options)),- ?assertEqual({connect_timeout, 5000}, lists:keyfind(connect_timeout, 1, Options)),- ?assertEqual({autoredirect, false}, lists:keyfind(autoredirect, 1, Options)).--memoisable_urls() ->- [- <<"http://fluxer-api.fluxer.svc.cluster.local/internal/rpc">>,- <<"https://fcm.googleapis.com/v1/projects/fluxer/messages:send">>,- <<"http://fluxer-api.fluxer.svc.cluster.local:8080/internal/rpc">>,- <<"HTTPS://Fluxer-API.Fluxer.SVC.Cluster.Local:8443/internal/rpc">>- ].--url_metadata_matches_derive_path_test_() ->- [- {binary_to_list(Url), fun() ->- Derived = {extract_host_key(Url), is_https_url(ensure_list(Url))},- ?assertEqual(Derived, url_metadata(Url))- end}- || Url <- memoisable_urls()- ].--url_metadata_values_test() ->- ?assertEqual(- [- {<<"fluxer-api.fluxer.svc.cluster.local">>, false},- {<<"fcm.googleapis.com">>, true},- {<<"fluxer-api.fluxer.svc.cluster.local">>, false},- {<<"fluxer-api.fluxer.svc.cluster.local">>, true}- ],- [url_metadata(Url) || Url <- memoisable_urls()]- ).--url_metadata_handles_unparsable_url_test() ->- ?assertEqual({<<"unknown">>, false}, url_metadata(<<"not-a-url">>)).--build_http_options_uses_memoised_scheme_test() ->- case has_ca_store() of- true ->- Opts = #{connect_timeout => 3000, recv_timeout => 5000, is_https => true},- ?assertMatch([{ssl, _} | _], build_http_options("http://127.0.0.1:8088/rpc", Opts));- false ->- ok- end.--build_http_options_memoised_http_skips_ssl_test() ->- Opts = #{connect_timeout => 3000, recv_timeout => 5000, is_https => false},- Options = build_http_options("https://fcm.googleapis.com/v1", Opts),- ?assertEqual(false, lists:keyfind(ssl, 1, Options)).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_ip_connections.erl b/fluxer_gateway/src/gateway/gateway_ip_connections.erlindex 67abbced8..33a82eeea 100644--- a/fluxer_gateway/src/gateway/gateway_ip_connections.erl+++ b/fluxer_gateway/src/gateway/gateway_ip_connections.erl@@ -1,9 +1,6 @@%% SPDX-License-Identifier: AGPL-3.0-or-later-module(gateway_ip_connections).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.-typing([eqwalizer]).@@ -171,177 +168,3 @@ reclaim_dead_owner(Owner, PeerIP) ->true -> decrement(PeerIP);false -> okend.---ifdef(TEST).--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.--restore_env(Key, false) ->- os:unsetenv(Key);-restore_env(Key, Value) ->- os:putenv(Key, Value).--connection_cap_blocks_over_limit_test() ->- with_rate_limits_enabled(fun() ->- IP = <<"198.51.100.20">>,- reset_connections(IP),- assert_connection_cap_allows_limit(IP),- ?assertEqual({error, too_many_connections}, acquire(IP)),- ok = release(IP),- ?assertEqual(ok, acquire(IP)),- reset_connections(IP)- end).--assert_connection_cap_allows_limit(IP) ->- lists:foreach(- fun(_) -> ?assertEqual(ok, acquire(IP)) end,- lists:seq(1, ?MAX_CONNECTIONS_PER_IP)- ).--connection_release_decrements_test() ->- with_rate_limits_enabled(fun() ->- IP = <<"198.51.100.30">>,- reset_connections(IP),- ok = acquire(IP),- ok = release(IP),- ?assertEqual([], ets:lookup(?CONNECTION_TABLE, IP))- end).--killed_connection_owner_releases_ip_count_test() ->- with_rate_limits_enabled(fun() ->- with_fast_owner_sweep(fun assert_killed_connection_count_is_released/0)- end).--assert_killed_connection_count_is_released() ->- with_heir_owner(fun assert_killed_connection_count_drops/0).--assert_killed_connection_count_drops() ->- IP = <<"198.51.100.80">>,- Holder = start_connection_holder(IP),- ?assertEqual(1, connection_count(IP)),- kill_connection_holder(Holder),- ?assert(await_connection_count(IP, 0, 300)).--released_connection_is_not_released_twice_test() ->- with_rate_limits_enabled(fun() ->- with_fast_owner_sweep(fun assert_released_connection_is_not_double_released/0)- end).--assert_released_connection_is_not_double_released() ->- with_heir_owner(fun assert_released_connection_keeps_peer_count/0).--assert_released_connection_keeps_peer_count() ->- IP = <<"198.51.100.90">>,- Holder = start_connection_holder(IP),- Releaser = start_connection_holder(IP),- ?assertEqual(2, connection_count(IP)),- release_connection_holder(Releaser),- ?assert(await_connection_count(IP, 1, 300)),- timer:sleep(100),- ?assertEqual(1, connection_count(IP)),- stop_connection_holder(Holder).--with_fast_owner_sweep(Fun) ->- meck:new(gateway_retry_timer, [passthrough]),- meck:expect(gateway_retry_timer, wait, fun(_) -> timer:sleep(5) end),- try- Fun()- after- meck:unload(gateway_retry_timer)- end.--with_heir_owner(Fun) ->- drop_table(?CONNECTION_TABLE),- drop_table(?OWNER_TABLE),- {ok, _} = guild_ets_owner:start_link(),- try- Fun()- after- gen_server:stop(guild_ets_owner)- end.--drop_table(Table) ->- case ets:whereis(Table) of- undefined ->- ok;- _ ->- ets:delete(Table),- ok- end.--start_connection_holder(IP) ->- Parent = self(),- Pid = spawn(fun() -> hold_connection(Parent, IP) end),- receive- {connection_acquired, Pid} -> Pid- after 1000 -> error(connection_holder_timeout)- end.--hold_connection(Parent, IP) ->- ok = acquire(IP),- Parent ! {connection_acquired, self()},- receive- release -> release(IP);- stop -> ok- after 30000 -> ok- end.--kill_connection_holder(Pid) ->- exit(Pid, kill),- await_connection_holder_down(Pid).--release_connection_holder(Pid) ->- Pid ! release,- await_connection_holder_down(Pid).--stop_connection_holder(Pid) ->- Pid ! stop,- await_connection_holder_down(Pid).--await_connection_holder_down(Pid) ->- Ref = erlang:monitor(process, Pid),- receive- {'DOWN', Ref, process, Pid, _Reason} -> ok- after 1000 -> error(connection_holder_down_timeout)- end.--connection_count(IP) ->- try ets:lookup(?CONNECTION_TABLE, IP) of- [{_, Count}] -> Count;- [] -> 0- catch- error:badarg -> 0- end.--await_connection_count(IP, Expected, 0) ->- connection_count(IP) =:= Expected;-await_connection_count(IP, Expected, Attempts) ->- case connection_count(IP) =:= Expected of- true ->- true;- false ->- timer:sleep(10),- await_connection_count(IP, Expected, Attempts - 1)- end.--reset_connections(IP) ->- _ = take_owner({self(), IP}),- drop_connection_row(IP).--drop_connection_row(IP) ->- case ets:whereis(?CONNECTION_TABLE) of- undefined ->- ok;- _ ->- ets:delete(?CONNECTION_TABLE, IP),- ok- end.---endif.diff --git a/fluxer_gateway/src/gateway/gateway_nats_rpc_handler.erl b/fluxer_gateway/src/gateway/gateway_nats_rpc_handler.erlindex dda49b861..f5340606a 100644--- a/fluxer_gateway/src/gateway/gateway_nats_rpc_handler.erl+++ b/fluxer_gateway/src/gateway/gateway_nats_rpc_handler.erl@@ -13,7 +13,6 @@max_handlers/0]).--define(DEFAULT_MAX_HANDLERS, 512).-define(RECONNECT_DELAY_MS, 2000).-define(CONNECT_TIMEOUT_MS, 10000).-define(RPC_SUBJECT_WILDCARD, <<"rpc.gateway.>">>).@@ -215,71 +214,3 @@ subscribe_subject(Conn, Role, Subject) ->schedule_reconnect(State) ->erlang:send_after(?RECONNECT_DELAY_MS, self(), connect),State.---spec max_handlers() -> pos_integer().-max_handlers() ->- case fluxer_gateway_env:get(gateway_nats_rpc_max_handlers) of- Value when is_integer(Value), Value > 0 -> Value;- _ -> ?DEFAULT_MAX_HANDLERS- end.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--execute_rpc_method_maps_validation_failure_to_invalid_params_test() ->- Payload = iolist_to_binary(- json:encode(#{- <<"guild_id">> => <<"nope">>,- <<"user_id">> => <<"2">>,- <<"channel_id">> => <<"0">>- })- ),- ?assertEqual(- #{<<"ok">> => false, <<"error">> => <<"invalid_params">>},- execute_rpc_method(<<"guild.get_user_permissions">>, Payload)- ).--execute_rpc_method_maps_oversized_batch_to_batch_too_large_test() ->- GuildIds = [integer_to_binary(N) || N <- lists:seq(1, 101)],- Payload = iolist_to_binary(- json:encode(#{- <<"guild_ids">> => GuildIds,- <<"user_id">> => <<"1">>,- <<"channel_id">> => <<"0">>- })- ),- ?assertEqual(- #{<<"ok">> => false, <<"error">> => <<"batch_too_large">>},- execute_rpc_method(<<"guild.get_user_permissions_batch">>, Payload)- ).--rpc_subjects_for_role_does_not_route_rpc_to_websocket_test() ->- ?assertEqual([], rpc_subjects_for_role(websocket)).--rpc_subjects_for_role_routes_namespaces_to_state_roles_test() ->- ?assertEqual([?RPC_SUBJECT_WILDCARD], rpc_subjects_for_role(all)),- ?assert(lists:member(<<"rpc.gateway.guild.>">>, rpc_subjects_for_role(guilds))),- ?assertEqual([], rpc_subjects_for_role(sessions)),- ?assert(lists:member(<<"rpc.gateway.presence.>">>, rpc_subjects_for_role(presence))),- ?assert(lists:member(<<"rpc.gateway.call.>">>, rpc_subjects_for_role(calls))),- ?assert(lists:member(<<"rpc.gateway.push.>">>, rpc_subjects_for_role(push))).--rpc_subjects_for_role_covers_all_router_prefixes_test() ->- Subjects = lists:append([- rpc_subjects_for_role(guilds),- rpc_subjects_for_role(presence),- rpc_subjects_for_role(calls),- rpc_subjects_for_role(push)- ]),- Prefixes = [- <<"guild">>, <<"presence">>, <<"push">>, <<"call">>, <<"voice">>, <<"process">>- ],- lists:foreach(- fun(Prefix) ->- ExpectedSubject = <<"rpc.gateway.", Prefix/binary, ".>">>,- ?assert(lists:member(ExpectedSubject, Subjects))- end,- Prefixes- ).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_rpc_guild_routing.erl b/fluxer_gateway/src/gateway/gateway_rpc_guild_routing.erlindex 1724051f7..2a3109797 100644--- a/fluxer_gateway/src/gateway/gateway_rpc_guild_routing.erl+++ b/fluxer_gateway/src/gateway/gateway_rpc_guild_routing.erl@@ -2,10 +2,6 @@-module(gateway_rpc_guild_routing).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.--typing([eqwalizer]).-export([@@ -208,41 +204,3 @@ collect_results(Ref, Remaining, Deadline, Acc) ->collect_results(Ref, Remaining, Deadline, Acc)after TimeoutMs -> lists:reverse(Acc)end.---ifdef(TEST).--owner_groups_for_reload_all_empty_ids_uses_active_nodes_test() ->- NodeA = '[email protected]',- NodeB = '[email protected]',- ?assertEqual(- [{NodeA, []}, {NodeB, []}],- owner_groups_for_reload_all([], fun() -> [NodeB, NodeA, NodeB] end)- ).--process_batch_collects_successful_results_test() ->- Results = process_batch([1, 2, 3], fun(N) -> eqwalizer:dynamic_cast(N) * 2 end, 1000),- ?assertEqual([2, 4, 6], lists:sort(Results)).--process_batch_drops_failed_workers_test() ->- Results = process_batch(- [1, 2, 3],- fun- (2) -> erlang:error(boom);- (N) -> N- end,- 1000- ),- ?assertEqual([1, 3], lists:sort(Results)).--process_batch_bounded_by_deadline_under_crashes_test() ->- Timeout = 200,- Start = erlang:monotonic_time(millisecond),- _ = process_batch(- lists:seq(1, 5),- fun(_) -> erlang:error(boom) end,- Timeout- ),- Elapsed = erlang:monotonic_time(millisecond) - Start,- ?assert(Elapsed < Timeout * 3).---endif.diff --git a/fluxer_gateway/src/gateway/gateway_rpc_push.erl b/fluxer_gateway/src/gateway/gateway_rpc_push.erlindex cc3bc4efe..e63071988 100644--- a/fluxer_gateway/src/gateway/gateway_rpc_push.erl+++ b/fluxer_gateway/src/gateway/gateway_rpc_push.erl@@ -62,49 +62,3 @@ fanout_local_cache_mutation(Module, Function, Args) ->),okend.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--sync_user_guild_settings_caches_the_private_scope_test() ->- push_ets_cache:init(),- Settings = #{<<"channel_overrides">> => #{<<"5">> => #{<<"muted">> => true}}},- try- with_registered_push(fun() ->- ?assert(- execute_method(<<"push.sync_user_guild_settings">>, #{- <<"user_id">> => <<"1001">>,- <<"guild_id">> => <<"0">>,- <<"user_guild_settings">> => Settings- })- )- end),- ?assertEqual(Settings, push_ets_cache:get_user_guild_settings(1001, 0))- after- push_ets_cache:delete_user_guild_settings(1001, 0)- end.--sync_user_guild_settings_rejects_an_invalid_guild_id_test() ->- ?assertError(- {validation, _},- execute_method(<<"push.sync_user_guild_settings">>, #{- <<"user_id">> => <<"1001">>,- <<"guild_id">> => <<"nope">>,- <<"user_guild_settings">> => #{}- })- ).--with_registered_push(Fun) ->- case whereis(push) of- undefined ->- register(push, self()),- try- Fun()- after- unregister(push)- end;- _Pid ->- Fun()- end.---endif.diff --git a/fluxer_gateway/src/gateway/rendezvous_router.erl b/fluxer_gateway/src/gateway/rendezvous_router.erlindex b05c09576..692242e92 100644--- a/fluxer_gateway/src/gateway/rendezvous_router.erl+++ b/fluxer_gateway/src/gateway/rendezvous_router.erl@@ -93,78 +93,3 @@ pick_better(Key, CurrentIndex, {BestIndex, BestWeight}) ->-spec weight(term(), non_neg_integer()) -> non_neg_integer().weight(Key, Index) ->erlang:phash2({Key, Index}, ?HASH_LIMIT).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--select_distribution_test() ->- Keys = lists:seq(1, 1000),- ShardCount = 10,- Distribution = count_distribution(Keys, ShardCount),- Counts = maps:values(Distribution),- ?assertEqual(ShardCount, maps:size(Distribution)),- lists:foreach(fun(Count) -> ?assert(Count > 0) end, Counts).--count_distribution(Keys, ShardCount) ->- lists:foldl(- fun(Key, Acc) ->- count_distribution_fold(Key, ShardCount, Acc)- end,- #{},- Keys- ).--count_distribution_fold(Key, ShardCount, Acc) ->- Index = select(Key, ShardCount),- maps:update_with(Index, fun(V) -> V + 1 end, 1, Acc).--group_keys_deduplicates_test() ->- Keys = [1, 2, 3, 1, 2],- Groups = group_keys(Keys, 2),- lists:foreach(- fun({_Index, GroupKeys}) ->- ?assertEqual(GroupKeys, lists:usort(GroupKeys))- end,- Groups- ).--group_keys_sorted_indices_test() ->- Keys = lists:seq(1, 100),- Groups = group_keys(Keys, 5),- Indices = [I || {I, _} <- Groups],- ?assertEqual(Indices, lists:sort(Indices)).--group_keys_all_keys_present_test() ->- Keys = [a, b, c, d, e],- Groups = group_keys(Keys, 3),- AllGroupedKeys = lists:flatten([K || {_, K} <- Groups]),- ?assertEqual(lists:sort(Keys), lists:sort(AllGroupedKeys)).--select_node_independent_of_order_test() ->- Nodes1 = ['n@a', 'n@b', 'n@c'],- Nodes2 = ['n@c', 'n@a', 'n@b'],- ?assertEqual(select_node(<<"k">>, Nodes1), select_node(<<"k">>, Nodes2)).--select_node_member_of_candidates_test() ->- Nodes = ['n@a', 'n@b', 'n@c'],- lists:foreach(- fun(I) ->- Owner = select_node(<<"key-", (integer_to_binary(I))/binary>>, Nodes),- ?assert(lists:member(Owner, Nodes))- end,- lists:seq(1, 100)- ).--select_node_minimal_disruption_on_leave_test() ->- Nodes = ['n@a', 'n@b', 'n@c', 'n@d'],- Remaining = ['n@a', 'n@b', 'n@c'],- Keys = [<<"key-", (integer_to_binary(I))/binary>> || I <- lists:seq(1, 400)],- Moved = length([- K- || K <- Keys,- select_node(K, Nodes) =/= select_node(K, Remaining),- lists:member(select_node(K, Nodes), Remaining)- ]),- ?assertEqual(0, Moved).---endif.diff --git a/fluxer_gateway/src/guild/voice/dm_voice_ring.erl b/fluxer_gateway/src/guild/voice/dm_voice_ring.erlindex a79a1e9e6..82862c560 100644--- a/fluxer_gateway/src/guild/voice/dm_voice_ring.erl+++ b/fluxer_gateway/src/guild/voice/dm_voice_ring.erl@@ -1,9 +1,6 @@%% SPDX-License-Identifier: AGPL-3.0-or-later-module(dm_voice_ring).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.-typing([eqwalizer]).@@ -162,22 +159,3 @@ is_dm_channel_type(_) -> false.-spec is_channel_recipient(integer(), dm_state()) -> boolean().is_channel_recipient(UserId, State) ->UserId =:= maps:get(user_id, State).---ifdef(TEST).--check_recipient_accepts_session_owner_for_dm_types_test() ->- State = #{- user_id => 1,- channels => #{- 100 => #{<<"id">> => <<"100">>, <<"type">> => 1},- 200 => #{<<"id">> => <<"200">>, <<"type">> => 3},- 300 => #{<<"id">> => <<"300">>, <<"type">> => 0}- }- },- ?assert(check_recipient(1, 100, State)),- ?assert(check_recipient(1, 200, State)),- ?assertNot(check_recipient(2, 100, State)),- ?assertNot(check_recipient(1, 300, State)),- ?assertNot(check_recipient(1, 999, State)).---endif.diff --git a/fluxer_gateway/src/guild/voice/guild_voice_disconnect_user.erl b/fluxer_gateway/src/guild/voice/guild_voice_disconnect_user.erlindex b77558496..32ff7112d 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_disconnect_user.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_disconnect_user.erl@@ -367,153 +367,3 @@ resolve_guild_id(VoiceState, State) ->GuildId ->GuildIdend.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--voice_state_fixture(UserId, GuildId, ChannelId) ->- #{- <<"user_id">> => integer_to_binary(UserId),- <<"guild_id">> => integer_to_binary(GuildId),- <<"channel_id">> => integer_to_binary(ChannelId)- }.--collect_force_disconnect_messages(0, Acc) ->- lists:reverse(Acc);-collect_force_disconnect_messages(Count, Acc) when Count > 0 ->- receive- {force_disconnect, _, _, _, _} = Msg ->- collect_force_disconnect_messages(Count - 1, [Msg | Acc])- after 200 -> lists:reverse(Acc)- end.-collect_force_disconnect_messages(Count) -> collect_force_disconnect_messages(Count, []).--test_force_disconnect_fun() ->- Self = self(),- fun(GId, CId, UId, ConnId) ->- Self ! {force_disconnect, GId, CId, UId, ConnId},- {ok, #{success => true}}- end.--assert_disconnect_clears_voice_states(UserId, State) ->- {reply, #{success := true}, #{voice_states := #{}}} =- disconnect_voice_user(#{user_id => UserId, connection_id => null}, State).--disconnect_voice_user_removes_all_connections_test() ->- VoiceStates = #{- <<"a">> => voice_state_fixture(5, 10, 20),- <<"b">> => voice_state_fixture(5, 10, 21)- },- State = #{- voice_states => VoiceStates,- test_force_disconnect_fun => fun(_, _, _, _) -> {ok, #{success => true}} end- },- assert_disconnect_clears_voice_states(5, State).--disconnect_voice_user_with_session_id_test() ->- TestFun = test_force_disconnect_fun(),- VoiceStates = #{- <<"a">> => (voice_state_fixture(5, 10, 20))#{<<"session_id">> => <<"sess-a">>},- <<"b">> => (voice_state_fixture(5, 10, 21))#{<<"session_id">> => <<"sess-b">>},- <<"c">> => (voice_state_fixture(6, 10, 22))#{<<"session_id">> => <<"sess-a">>}- },- State = #{id => 10, voice_states => VoiceStates, test_force_disconnect_fun => TestFun},- {reply, #{success := true}, NewState} =- disconnect_voice_user(- #{user_id => 5, connection_id => null, session_id => <<"sess-a">>}, State- ),- ?assertEqual(- [{force_disconnect, 10, 20, 5, <<"a">>}], collect_force_disconnect_messages(1)- ),- Remaining = maps:get(voice_states, NewState),- ?assertNot(maps:is_key(<<"a">>, Remaining)),- ?assert(maps:is_key(<<"b">>, Remaining)),- ?assert(maps:is_key(<<"c">>, Remaining)).--handle_voice_disconnect_invalid_state_test() ->- VoiceState = #{<<"user_id">> => <<"5">>},- State = #{voice_states => #{<<"conn">> => VoiceState}},- {reply, {error, validation_error, _}, _} =- handle_voice_disconnect(<<"conn">>, undefined, 5, #{<<"conn">> => VoiceState}, State).--disconnect_voice_user_if_in_channel_ignored_test() ->- State = #{voice_states => #{}},- {reply, #{ignored := true}, _} =- disconnect_voice_user_if_in_channel(#{user_id => 5, expected_channel_id => 99}, State).--cache_and_clear_recently_disconnected_test() ->- VS = voice_state_fixture(5, 10, 20),- S1 = guild_voice_disconnect_broadcast:cache_recently_disconnected(#{<<"conn">> => VS}, #{}),- ?assert(- maps:is_key(- <<"conn">>, guild_voice_disconnect_broadcast:recently_disconnected_voice_states(S1)- )- ),- S2 = guild_voice_disconnect_broadcast:clear_recently_disconnected(<<"conn">>, S1),- ?assertEqual(#{}, guild_voice_disconnect_broadcast:recently_disconnected_voice_states(S2)).--clear_recently_disconnected_for_channel_test() ->- VS1 = voice_state_fixture(5, 10, 20),- VS2 = voice_state_fixture(6, 10, 30),- S0 = guild_voice_disconnect_broadcast:cache_recently_disconnected(- #{<<"a">> => VS1, <<"b">> => VS2}, #{}- ),- S1 = guild_voice_disconnect_broadcast:clear_recently_disconnected_for_channel(20, S0),- Cache = guild_voice_disconnect_broadcast:recently_disconnected_voice_states(S1),- ?assertNot(maps:is_key(<<"a">>, Cache)),- ?assert(maps:is_key(<<"b">>, Cache)).--disconnect_voice_user_if_in_channel_caches_test() ->- VS = voice_state_fixture(5, 10, 20),- State = #{voice_states => #{<<"conn">> => VS}},- {reply, #{success := true}, NewState} =- disconnect_voice_user_if_in_channel(- #{user_id => 5, expected_channel_id => 20, connection_id => <<"conn">>}, State- ),- ?assert(- maps:is_key(- <<"conn">>,- guild_voice_disconnect_broadcast:recently_disconnected_voice_states(NewState)- )- ).--disconnect_voice_user_force_disconnect_all_test() ->- TestFun = test_force_disconnect_fun(),- VoiceStates = #{- <<"a">> => voice_state_fixture(5, 10, 20),- <<"b">> => voice_state_fixture(5, 10, 21)- },- State = #{id => 10, voice_states => VoiceStates, test_force_disconnect_fun => TestFun},- assert_disconnect_clears_voice_states(5, State),- Msgs = collect_force_disconnect_messages(2),- ?assertEqual(2, length(Msgs)).--disconnect_all_voice_users_in_channel_test() ->- TestFun = test_force_disconnect_fun(),- VoiceStates = #{- <<"a">> => voice_state_fixture(5, 10, 20),- <<"b">> => voice_state_fixture(6, 10, 20),- <<"c">> => voice_state_fixture(7, 10, 30)- },- State = #{id => 10, voice_states => VoiceStates, test_force_disconnect_fun => TestFun},- {reply, #{success := true, disconnected_count := 2}, NewState} =- guild_voice_disconnect_channel:disconnect_all_voice_users_in_channel(- #{channel_id => 20}, State- ),- _ = collect_force_disconnect_messages(2),- Remaining = maps:get(voice_states, NewState),- ?assert(maps:is_key(<<"c">>, Remaining)),- ?assertNot(maps:is_key(<<"a">>, Remaining)).--disconnect_voice_user_cleans_pending_test() ->- Pending = #{- <<"conn1">> => #{user_id => 5, channel_id => 100},- <<"conn2">> => #{user_id => 6, channel_id => 100}- },- State = #{id => 10, voice_states => #{}, pending_voice_connections => Pending},- {reply, #{success := true}, NewState} = disconnect_voice_user(#{user_id => 5}, State),- NewPending = maps:get(pending_voice_connections, NewState),- ?assertNot(maps:is_key(<<"conn1">>, NewPending)),- ?assert(maps:is_key(<<"conn2">>, NewPending)).---endif.diff --git a/fluxer_gateway/src/guild/voice/guild_voice_e2ee.erl b/fluxer_gateway/src/guild/voice/guild_voice_e2ee.erlindex bab23aa3d..c9c7b8062 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_e2ee.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_e2ee.erl@@ -202,119 +202,3 @@ forget_room_key_if_channel_empty_dm(ChannelId, VoiceStates, DmState) ->generate_key() ->Bytes = crypto:strong_rand_bytes(32),base64:encode(Bytes, #{mode => urlsafe, padding => false}).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--voice_state_e2ee_capable_test() ->- ?assert(voice_state_e2ee_capable(#{<<"e2ee_capable">> => true})),- ?assertNot(voice_state_e2ee_capable(#{<<"e2ee_capable">> => false})),- ?assertNot(voice_state_e2ee_capable(#{})),- ?assertNot(voice_state_e2ee_capable(not_a_map)).--channel_is_e2ee_active_empty_test() ->- ?assertNot(channel_is_e2ee_active(100, #{})).--channel_is_e2ee_active_all_capable_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true},- <<"c2">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assert(channel_is_e2ee_active(100, VoiceStates)).--channel_is_e2ee_active_mixed_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true},- <<"c2">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => false}- },- ?assertNot(channel_is_e2ee_active(100, VoiceStates)).--channel_is_e2ee_active_ignores_other_channels_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true},- <<"c2">> => #{<<"channel_id">> => <<"200">>, <<"e2ee_capable">> => false}- },- ?assert(channel_is_e2ee_active(100, VoiceStates)).--check_join_allowed_guild_empty_test() ->- ?assertEqual(ok, check_join_allowed_guild(100, false, false, #{})).--check_join_allowed_guild_blocked_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assertEqual(- {error, voice_e2ee_required},- check_join_allowed_guild(100, false, false, VoiceStates)- ).--check_join_allowed_guild_bot_breaks_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assertEqual(ok, check_join_allowed_guild(100, false, true, VoiceStates)).--check_join_allowed_guild_e2ee_join_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assertEqual(ok, check_join_allowed_guild(100, true, false, VoiceStates)).--join_downgrades_e2ee_bot_breaks_active_channel_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assert(join_downgrades_e2ee(100, true, true, VoiceStates)).--join_downgrades_e2ee_non_capable_breaks_active_channel_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assert(join_downgrades_e2ee(100, false, false, VoiceStates)).--join_downgrades_e2ee_capable_join_does_not_downgrade_test() ->- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- ?assertNot(join_downgrades_e2ee(100, true, false, VoiceStates)).--join_downgrades_e2ee_inactive_channel_does_not_downgrade_test() ->- ?assertNot(join_downgrades_e2ee(100, false, true, #{})).--get_or_create_room_key_returns_same_key_test() ->- {Key1, State1} = get_or_create_room_key_guild(100, #{}),- {Key2, _State2} = get_or_create_room_key_guild(100, State1),- ?assertEqual(Key1, Key2),- ?assert(is_binary(Key1)),- ?assert(byte_size(Key1) > 0).--forget_room_key_clears_key_test() ->- {_Key, State1} = get_or_create_room_key_guild(100, #{}),- State2 = forget_room_key_guild(100, State1),- {NewKey, _State3} = get_or_create_room_key_guild(100, State2),- {OldKey, _} = get_or_create_room_key_guild(100, State1),- ?assertNotEqual(NewKey, OldKey).--forget_room_key_if_channel_idle_keeps_key_for_active_voice_state_test() ->- {Key, State1} = get_or_create_room_key_guild(100, #{}),- VoiceStates = #{- <<"c1">> => #{<<"channel_id">> => <<"100">>, <<"e2ee_capable">> => true}- },- State2 = forget_room_key_if_channel_idle_guild(100, VoiceStates, #{}, State1),- {Key2, _} = get_or_create_room_key_guild(100, State2),- ?assertEqual(Key, Key2).--forget_room_key_if_channel_idle_keeps_key_for_pending_join_test() ->- {Key, State1} = get_or_create_room_key_guild(100, #{}),- Pending = #{<<"c1">> => #{channel_id => 100, e2ee_capable => true}},- State2 = forget_room_key_if_channel_idle_guild(100, #{}, Pending, State1),- {Key2, _} = get_or_create_room_key_guild(100, State2),- ?assertEqual(Key, Key2).--forget_room_key_if_channel_idle_clears_key_test() ->- {Key, State1} = get_or_create_room_key_guild(100, #{}),- State2 = forget_room_key_if_channel_idle_guild(100, #{}, #{}, State1),- {Key2, _} = get_or_create_room_key_guild(100, State2),- ?assertNotEqual(Key, Key2).---endif.diff --git a/fluxer_gateway/src/guild/voice/guild_voice_move.erl b/fluxer_gateway/src/guild/voice/guild_voice_move.erlindex 6edd1ff27..73e385104 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_move.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_move.erl@@ -1,9 +1,6 @@%% SPDX-License-Identifier: AGPL-3.0-or-later-module(guild_voice_move).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.-typing([eqwalizer]).@@ -159,47 +156,3 @@ send_captured_voice_server_updates(GuildId, ChannelId, SessionDataList, GuildPidend,SessionDataList).---ifdef(TEST).--move_member_user_not_in_voice_test() ->- Request = #{- user_id => 10,- moderator_id => 20,- channel_id => null,- mute => false,- deaf => false- },- State = test_state(#{}),- {reply, {error, not_found, voice_user_not_in_voice}, _} = move_member(Request, State).--select_connections_to_move_specific_connection_test() ->- VoiceStates = #{- <<"conn-a">> => voice_state_fixture(10, 100, <<"conn-a">>),- <<"conn-b">> => voice_state_fixture(11, 101, <<"conn-b">>)- },- Selected = select_connections_to_move(<<"conn-b">>, 11, VoiceStates, #{}),- ?assertEqual(#{<<"conn-b">> => maps:get(<<"conn-b">>, VoiceStates)}, Selected),- ?assertEqual(#{}, select_connections_to_move(<<"conn-b">>, 10, VoiceStates, #{})).--test_state(VoiceStates) ->- #{- id => 1,- data => #{- <<"members">> => [],- <<"channels">> => []- },- voice_states => VoiceStates- }.--voice_state_fixture(UserId, ChannelId, ConnId) ->- #{- <<"user_id">> => integer_to_binary(UserId),- <<"channel_id">> => integer_to_binary(ChannelId),- <<"connection_id">> => ConnId,- <<"member">> => #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)}- }- }.---endif.diff --git a/fluxer_gateway/src/guild/voice/guild_voice_region.erl b/fluxer_gateway/src/guild/voice/guild_voice_region.erlindex cb6f02712..f7875858c 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_region.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_region.erl@@ -1,9 +1,6 @@%% SPDX-License-Identifier: AGPL-3.0-or-later-module(guild_voice_region).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.-typing([eqwalizer]).@@ -283,173 +280,3 @@ store_pending_connection(GuildId, GuildPid, ConnectionId, Metadata) ->{store_pending_connection, ConnectionId, Metadata},10000).---ifdef(TEST).--switch_voice_region_reads_guild_state_once_test() ->- with_region_stubs(fun() ->- {Calls, _Dispatches, _Pending} = run_region_switch(fun switch_voice_region/3),- ?assertEqual(1, Calls)- end).--switch_voice_region_skips_users_without_a_session_id_test() ->- with_region_stubs(fun region_missing_session_id_scenario/0).--region_missing_session_id_scenario() ->- Anonymous = maps:remove(- <<"session_id">>, region_voice_state(<<"conn-c">>, 10, <<"sess1">>)- ),- State = region_state(),- Stateless = State#{voice_states => #{<<"conn-c">> => Anonymous}},- {Calls, Dispatches, Pending} = run_region_switch_with(- fun switch_voice_region/3, Stateless- ),- ?assertEqual(1, Calls),- ?assertEqual([], Dispatches),- ?assertEqual([], Pending).--%% The pre-change implementation, kept as a live oracle: it refetched the guild state once per-%% user in the channel instead of reusing the one the enumeration already fetched.-run_region_switch(Fun) ->- run_region_switch_with(Fun, region_state()).--run_region_switch_with(Fun, State) ->- drain_region_dispatches(),- drain_region_pending(),- erlang:put(region_token_index, 0),- GuildPid = spawn_region_guild(State),- try- Fun(999, 200, GuildPid),- {region_guild_calls(GuildPid), drain_region_dispatches(), drain_region_pending()}- after- GuildPid ! stop- end.--with_region_stubs(Fun) ->- meck:new(rpc_client, [passthrough, no_link, non_strict]),- meck:expect(rpc_client, call, fun(_Request) -> {ok, next_region_token()} end),- meck:new(guild_voice_server, [passthrough, no_link]),- meck:expect(guild_voice_server, resolve, fun(_GuildId, GuildPid) -> GuildPid end),- try- Fun()- after- meck:unload(guild_voice_server),- meck:unload(rpc_client)- end.--next_region_token() ->- Index = erlang:get(region_token_index) + 1,- erlang:put(region_token_index, Index),- #{- <<"token">> => <<"tok-", (integer_to_binary(Index))/binary>>,- <<"endpoint">> => <<"wss://voice.example">>,- <<"connectionId">> => <<"new-conn-", (integer_to_binary(Index))/binary>>,- <<"regionId">> => <<"us-east">>,- <<"serverId">> => <<"voice-1">>- }.--spawn_region_guild(State) ->- Owner = self(),- spawn(fun() -> region_guild_loop(State, Owner, 0) end).--region_guild_loop(State, Owner, Calls) ->- receive- {'$gen_call', From, {get_voice_guild_state}} ->- gen_server:reply(From, State),- region_guild_loop(State, Owner, Calls + 1);- {'$gen_call', From, {store_pending_connection, ConnId, Meta}} ->- Owner ! {region_pending, ConnId, Meta},- gen_server:reply(From, ok),- region_guild_loop(State, Owner, Calls);- {'$gen_call', From, _Other} ->- gen_server:reply(From, ok),- region_guild_loop(State, Owner, Calls);- {region_calls, Caller} ->- Caller ! {region_calls, Calls},- region_guild_loop(State, Owner, Calls);- stop ->- ok- after 30000 ->- ok- end.--region_guild_calls(GuildPid) ->- GuildPid ! {region_calls, self()},- receive- {region_calls, Calls} -> Calls- after 1000 ->- error(region_guild_unresponsive)- end.--drain_region_dispatches() ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} ->- [Payload | drain_region_dispatches()]- after 100 ->- []- end.--%% token_nonce and the timestamps are freshly generated per call by design, so they are-%% excluded before the reference and the threaded run are compared.-drain_region_pending() ->- receive- {region_pending, ConnId, Meta} ->- Stable = maps:without([token_nonce, created_at, expires_at], Meta),- [{ConnId, Stable} | drain_region_pending()]- after 100 ->- []- end.--region_state() ->- #{- id => 999,- data => #{- <<"id">> => <<"999">>,- <<"guild">> => #{<<"owner_id">> => <<"10">>},- <<"channels">> => [#{<<"id">> => <<"200">>, <<"type">> => 2}],- <<"members">> => [region_member(10), region_member(11)]- },- sessions => #{- <<"sess1">> => #{user_id => 10, pid => self(), pending_connect => false},- <<"sess2">> => #{user_id => 11, pid => self(), pending_connect => false}- },- voice_states => #{- <<"conn-a">> => region_voice_state(<<"conn-a">>, 10, <<"sess1">>),- <<"conn-b">> => region_voice_state(<<"conn-b">>, 11, <<"sess2">>)- },- pending_voice_connections => #{}- }.--region_member(UserId) ->- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"mute">> => false,- <<"deaf">> => false- }.--region_voice_state(ConnId, UserId, SessionId) ->- #{- <<"user_id">> => integer_to_binary(UserId),- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"200">>,- <<"connection_id">> => ConnId,- <<"session_id">> => SessionId,- <<"self_mute">> => false,- <<"self_deaf">> => true,- <<"member">> => region_member(UserId)- }.--build_pending_metadata_preserves_voice_routing_test() ->- Metadata = build_pending_metadata(- 10,- 20,- 30,- <<"sess1">>,- #{},- <<"nonce">>,- #{region_id => <<"us-east">>, server_id => <<"voice-ewr-1">>}- ),- ?assertEqual(<<"us-east">>, maps:get(region_id, Metadata)),- ?assertEqual(<<"voice-ewr-1">>, maps:get(server_id, Metadata)).---endif.diff --git a/fluxer_gateway/src/guild/voice/guild_voice_server_state.erl b/fluxer_gateway/src/guild/voice/guild_voice_server_state.erlindex 276ddcd23..f4d5260d2 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_server_state.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_server_state.erl@@ -218,89 +218,3 @@ normalize_rpc_binary(Value) when is_list(Value), Value =/= [] ->end;normalize_rpc_binary(_) ->null.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--guild_state_call_uses_projection_test() ->- with_fake_guild(fun new_guild_handler/1, fun(Pid) ->- ?assertEqual(projected_guild_state(), guild_state_call(Pid, 1000)),- ?assertEqual([{get_voice_guild_state}], drain_requests())- end).--guild_state_call_retries_get_sessions_against_old_peer_test() ->- with_fake_guild(fun old_guild_handler/1, fun(Pid) ->- ?assertEqual(full_guild_state(), guild_state_call(Pid, 1000)),- ?assertEqual([{get_voice_guild_state}, {get_sessions}], drain_requests())- end).--fetch_guild_data_retries_get_sessions_against_old_peer_test() ->- with_fake_guild(fun old_guild_handler/1, fun(Pid) ->- ?assertEqual(full_guild_state(), fetch_guild_data(Pid)),- ?assertEqual([{get_voice_guild_state}, {get_sessions}], drain_requests())- end).--guild_id_call_uses_get_guild_id_test() ->- with_fake_guild(fun new_guild_handler/1, fun(Pid) ->- ?assertEqual(42, guild_id_call(Pid, 1000)),- ?assertEqual([{get_guild_id}], drain_requests())- end).--guild_id_call_returns_real_id_against_old_peer_test() ->- with_fake_guild(fun old_guild_handler/1, fun(Pid) ->- ?assertEqual(42, guild_id_call(Pid, 1000)),- ?assertEqual([{get_guild_id}, {get_sessions}], drain_requests())- end).--guild_id_call_returns_undefined_when_peer_has_no_id_test() ->- with_fake_guild(fun(_) -> ok end, fun(Pid) ->- ?assertEqual(undefined, guild_id_call(Pid, 1000)),- ?assertEqual([{get_guild_id}, {get_sessions}], drain_requests())- end).--new_guild_handler({get_voice_guild_state}) -> projected_guild_state();-new_guild_handler({get_guild_id}) -> 42;-new_guild_handler({get_sessions}) -> full_guild_state();-new_guild_handler(_) -> ok.--old_guild_handler({get_sessions}) -> full_guild_state();-old_guild_handler(_) -> ok.--full_guild_state() ->- #{- id => 42,- sessions => #{},- voice_states => #{},- data => #{<<"id">> => <<"42">>, <<"members">> => #{}}- }.--projected_guild_state() ->- #{id => 42, sessions => #{}, voice_states => #{}, data => #{<<"id">> => <<"42">>}}.--with_fake_guild(Handler, Fun) ->- _ = drain_requests(),- Owner = self(),- Pid = spawn(fun() -> fake_guild_loop(Owner, Handler) end),- try- Fun(Pid)- after- Pid ! stop- end.--fake_guild_loop(Owner, Handler) ->- receive- {'$gen_call', From, Request} ->- Owner ! {fake_guild_request, Request},- gen_server:reply(From, Handler(Request)),- fake_guild_loop(Owner, Handler);- stop ->- ok- end.--drain_requests() ->- receive- {fake_guild_request, Request} -> [Request | drain_requests()]- after 0 -> []- end.---endif.diff --git a/fluxer_gateway/src/guild/voice/voice_state_counts_cache.erl b/fluxer_gateway/src/guild/voice/voice_state_counts_cache.erlindex 013224d3c..a5d5450e8 100644--- a/fluxer_gateway/src/guild/voice/voice_state_counts_cache.erl+++ b/fluxer_gateway/src/guild/voice/voice_state_counts_cache.erl@@ -221,122 +221,3 @@ get_optional_field(Map, PrimaryKey, FallbackKey) ->-spec get_optional_field(map(), term(), term(), term()) -> term().get_optional_field(Map, PrimaryKey, FallbackKey, Default) ->maps:get(PrimaryKey, Map, maps:get(FallbackKey, Map, Default)).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").---spec reset_tables() -> ok.-reset_tables() ->- try- ets:delete(?CONNECTION_TABLE)- catch- error:badarg -> ok- end,- try- ets:delete(?REGION_TABLE)- catch- error:badarg -> ok- end,- try- ets:delete(?SERVER_TABLE)- catch- error:badarg -> ok- end,- ok.--upsert_voice_state_tracks_region_and_server_counts_test() ->- ok = reset_tables(),- VoiceState = #{- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => <<"123">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"us-east-1">>- },- ok = upsert_voice_state(VoiceState),- Counts = get_local_counts(),- ?assertEqual(1, maps:get(<<"total_voice_states">>, Counts)),- ?assertEqual(- [#{<<"region_id">> => <<"us-east">>, <<"voice_state_count">> => 1}],- maps:get(<<"regions">>, Counts)- ),- ?assertEqual(- [#{<<"server_id">> => <<"us-east-1">>, <<"voice_state_count">> => 1}],- maps:get(<<"servers">>, Counts)- ).--upsert_voice_state_replaces_existing_metadata_test() ->- ok = reset_tables(),- ok = upsert_voice_state(#{- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => <<"123">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"us-east-1">>- }),- ok = upsert_voice_state(#{- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => <<"456">>,- <<"region_id">> => <<"eu-west">>,- <<"server_id">> => <<"eu-west-2">>- }),- Counts = get_local_counts(),- ?assertEqual(1, maps:get(<<"total_voice_states">>, Counts)),- ?assertEqual(- [#{<<"region_id">> => <<"eu-west">>, <<"voice_state_count">> => 1}],- maps:get(<<"regions">>, Counts)- ),- ?assertEqual(- [#{<<"server_id">> => <<"eu-west-2">>, <<"voice_state_count">> => 1}],- maps:get(<<"servers">>, Counts)- ).--remove_connection_decrements_counters_test() ->- ok = reset_tables(),- ok = upsert_voice_state(#{- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => <<"123">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"us-east-1">>- }),- ok = remove_connection(<<"conn-1">>),- Counts = get_local_counts(),- ?assertEqual(0, maps:get(<<"total_voice_states">>, Counts)),- ?assertEqual([], maps:get(<<"regions">>, Counts)),- ?assertEqual([], maps:get(<<"servers">>, Counts)).--upsert_voice_state_disconnect_removes_connection_test() ->- ok = reset_tables(),- ok = upsert_voice_state(#{- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => <<"123">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"us-east-1">>- }),- ok = upsert_voice_state(#{- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => null- }),- Counts = get_local_counts(),- ?assertEqual(0, maps:get(<<"total_voice_states">>, Counts)),- ?assertEqual([], maps:get(<<"regions">>, Counts)),- ?assertEqual([], maps:get(<<"servers">>, Counts)).--upsert_voice_state_accepts_atom_keys_test() ->- ok = reset_tables(),- ok = upsert_voice_state(#{- connection_id => <<"conn-atom">>,- channel_id => 123,- region_id => <<"atom-region">>,- server_id => <<"atom-server">>- }),- Counts = get_local_counts(),- ?assertEqual(1, maps:get(<<"total_voice_states">>, Counts)),- ?assertEqual(- [#{<<"region_id">> => <<"atom-region">>, <<"voice_state_count">> => 1}],- maps:get(<<"regions">>, Counts)- ),- ?assertEqual(- [#{<<"server_id">> => <<"atom-server">>, <<"voice_state_count">> => 1}],- maps:get(<<"servers">>, Counts)- ).---endif.diff --git a/fluxer_gateway/src/guild/voice/voice_state_counts_cache_sync.erl b/fluxer_gateway/src/guild/voice/voice_state_counts_cache_sync.erlindex ab5bcfc28..a9c55eed9 100644--- a/fluxer_gateway/src/guild/voice/voice_state_counts_cache_sync.erl+++ b/fluxer_gateway/src/guild/voice/voice_state_counts_cache_sync.erl@@ -188,69 +188,3 @@ apply_default_channel_id(VoiceState, DefaultChannelId) ->undefined -> VoiceState;ChannelId -> VoiceState#{<<"channel_id">> => ChannelId}end.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--reset_count_tables() ->- try- ets:delete(voice_state_count_connections)- catch- error:badarg -> ok- end,- try- ets:delete(voice_state_count_regions)- catch- error:badarg -> ok- end,- try- ets:delete(voice_state_count_servers)- catch- error:badarg -> ok- end,- ok.--merge_live_voice_state_entries_counts_dm_call_voice_states_test() ->- ok = reset_count_tables(),- LiveStates = merge_live_voice_state_entries(- [- #{- <<"connection_id">> => <<"dm-conn-1">>,- <<"user_id">> => <<"100">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"6f47e7f-ewr">>- }- ],- 123,- #{}- ),- VoiceState = maps:get(<<"dm-conn-1">>, LiveStates),- ?assertEqual(<<"123">>, maps:get(<<"channel_id">>, VoiceState)),- ok = voice_state_counts_cache:upsert_voice_state(VoiceState),- Counts = voice_state_counts_cache:get_local_counts(),- ?assertEqual(1, maps:get(<<"total_voice_states">>, Counts)),- ?assertEqual(- [#{<<"region_id">> => <<"us-east">>, <<"voice_state_count">> => 1}],- maps:get(<<"regions">>, Counts)- ),- ?assertEqual(- [#{<<"server_id">> => <<"6f47e7f-ewr">>, <<"voice_state_count">> => 1}],- maps:get(<<"servers">>, Counts)- ).--merge_live_voice_state_entries_uses_map_key_connection_id_test() ->- LiveStates = merge_live_voice_state_entries(- #{- <<"dm-conn-2">> => #{- <<"user_id">> => <<"200">>,- <<"channel_id">> => 456- }- },- undefined,- #{}- ),- VoiceState = maps:get(<<"dm-conn-2">>, LiveStates),- ?assertEqual(<<"dm-conn-2">>, maps:get(<<"connection_id">>, VoiceState)),- ?assertEqual(<<"456">>, maps:get(<<"channel_id">>, VoiceState)).---endif.diff --git a/fluxer_gateway/src/guild/voice/voice_state_utils.erl b/fluxer_gateway/src/guild/voice/voice_state_utils.erlindex 9c1cccde2..df0208654 100644--- a/fluxer_gateway/src/guild/voice/voice_state_utils.erl+++ b/fluxer_gateway/src/guild/voice/voice_state_utils.erl@@ -1,9 +1,6 @@%% SPDX-License-Identifier: AGPL-3.0-or-later-module(voice_state_utils).--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--endif.-typing([eqwalizer]).@@ -251,47 +248,3 @@ require_positive_snowflake(Value) ->Id = snowflake_id:parse_maybe(Value),true = is_integer(Id),Id.---ifdef(TEST).--parse_stream_key_dm_test() ->- Result = parse_stream_key(<<"dm:123:conn-id">>),- ?assertMatch(- {ok, #{scope := dm, channel_id := 123, connection_id := <<"conn-id">>}}, Result- ).--parse_stream_key_guild_test() ->- Result = parse_stream_key(<<"999:123:conn-id">>),- ?assertMatch(- {ok, #{- scope := guild, guild_id := 999, channel_id := 123, connection_id := <<"conn-id">>- }},- Result- ).--parse_stream_key_invalid_test() ->- ?assertEqual({error, invalid_stream_key}, parse_stream_key(<<"invalid">>)),- ?assertEqual({error, invalid_stream_key}, parse_stream_key(<<"a:b">>)),- ?assertEqual({error, invalid_stream_key}, parse_stream_key(<<"dm:001:conn">>)),- ?assertEqual({error, invalid_stream_key}, parse_stream_key(<<"001:123:conn">>)),- ?assertEqual({error, invalid_stream_key}, parse_stream_key(123)).--sanitize_voice_state_for_broadcast_test() ->- VoiceState = #{- <<"user_id">> => <<"1">>,- <<"latitude">> => <<"1.0">>,- <<"longitude">> => <<"2.0">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"voice-1">>- },- Sanitized = sanitize_voice_state_for_broadcast(VoiceState),- ?assertNot(maps:is_key(<<"latitude">>, Sanitized)),- ?assertNot(maps:is_key(<<"longitude">>, Sanitized)),- ?assertNot(maps:is_key(<<"region_id">>, Sanitized)),- ?assertNot(maps:is_key(<<"server_id">>, Sanitized)),- ?assertEqual(<<"1">>, maps:get(<<"user_id">>, Sanitized)),- ?assertEqual(null, maps:get(<<"channel_id">>, Sanitized)),- ?assertEqual(false, maps:get(<<"suppress">>, Sanitized)),- ?assertEqual(0, maps:get(<<"version">>, Sanitized)).---endif.diff --git a/fluxer_gateway/src/telemetry/process_health_watchdog.erl b/fluxer_gateway/src/telemetry/process_health_watchdog.erlindex 96851d0ee..8a5880674 100644--- a/fluxer_gateway/src/telemetry/process_health_watchdog.erl+++ b/fluxer_gateway/src/telemetry/process_health_watchdog.erl@@ -247,78 +247,3 @@ prune_dead(History, LivePids) ->-spec schedule_check() -> reference().schedule_check() ->erlang:send_after(?CHECK_INTERVAL_MS, self(), run_check).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--is_monotonically_growing_true_test() ->- ?assert(is_monotonically_growing([3000, 2000, 1500])).--is_monotonically_growing_false_when_decreasing_test() ->- ?assertNot(is_monotonically_growing([500, 2000, 1500])).--is_monotonically_growing_false_when_flat_test() ->- ?assertNot(is_monotonically_growing([2000, 2000, 2000])).--is_monotonically_growing_false_below_threshold_test() ->- ?assertNot(is_monotonically_growing([500, 400, 300])).--is_monotonically_growing_false_insufficient_samples_test() ->- ?assertNot(is_monotonically_growing([5000, 4000])),- ?assertNot(is_monotonically_growing([5000])),- ?assertNot(is_monotonically_growing([])).--prune_dead_removes_absent_pids_test() ->- Pid1 = self(),- Pid2 = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- History = #{Pid1 => [100], Pid2 => [200]},- LivePids = [{Pid1, <<"test">>}],- Pruned = prune_dead(History, LivePids),- ?assertEqual(#{Pid1 => [100]}, Pruned).--dispatch_relay_workers_are_monitored_test() ->- Key = {gateway_dispatch_relay, state},- Previous = persistent_term:get(Key, undefined),- Worker = self(),- persistent_term:put(Key, #{workers => {Worker}, shard_count => 1}),- try- Expected = {Worker, <<"dispatch_relay_worker:0">>},- ?assertEqual([Expected], dispatch_relay_worker_pids()),- ?assert(lists:member(Expected, collect_monitored_pids()))- after- restore_relay_state_test_term(Key, Previous)- end.--check_pid_dead_process_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- History = #{Pid => [100, 50]},- Result = check_pid(Pid, <<"dead">>, History),- ?assertNot(maps:is_key(Pid, Result)).--is_sustained_over_kill_threshold_true_test() ->- ?assert(is_sustained_over_kill_threshold([70000, 60000, 55000])).--is_sustained_over_kill_threshold_false_single_spike_test() ->- ?assertNot(is_sustained_over_kill_threshold([70000, 100, 100])).--is_sustained_over_kill_threshold_false_not_growing_test() ->- ?assertNot(is_sustained_over_kill_threshold([55000, 60000, 70000])).--is_sustained_over_kill_threshold_false_insufficient_samples_test() ->- ?assertNot(is_sustained_over_kill_threshold([70000, 60000])),- ?assertNot(is_sustained_over_kill_threshold([70000])),- ?assertNot(is_sustained_over_kill_threshold([])).--safe_run_watchdog_check_survives_bad_state_test() ->- BadState = maps:remove(history, #{history => #{}}),- ?assertEqual(BadState, safe_run_watchdog_check(eqwalizer:dynamic_cast(BadState))).--restore_relay_state_test_term(Key, undefined) ->- _ = persistent_term:erase(Key),- ok;-restore_relay_state_test_term(Key, Previous) ->- persistent_term:put(Key, Previous).---endif.diff --git a/fluxer_gateway/src/utils/backoff_utils.erl b/fluxer_gateway/src/utils/backoff_utils.erlindex 0884bb31b..e5fe8599b 100644--- a/fluxer_gateway/src/utils/backoff_utils.erl+++ b/fluxer_gateway/src/utils/backoff_utils.erl@@ -41,28 +41,3 @@ calculate_with_jitter(Attempt, MaxMs) ->Jitter = rand:uniform(JitterRange + 1) - 1,Offset = JitterRange div 2,max(1, min(MaxMs, Base - Offset + Jitter)).---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--calculate_huge_attempt_does_not_overflow_test() ->- ?assertEqual(30000, calculate(1000000000)),- ?assertEqual(5000, calculate(1000000000, 5000)).--calculate_with_jitter_stays_in_range_test() ->- lists:foreach(- fun(_) ->- V0 = calculate_with_jitter(0),- ?assert(V0 >= 750),- ?assert(V0 =< 1250),- V2 = calculate_with_jitter(2),- ?assert(V2 >= 3000),- ?assert(V2 =< 5000),- V10 = calculate_with_jitter(10),- ?assert(V10 >= 22500),- ?assert(V10 =< 30000)- end,- lists:seq(1, 20)- ).---endif.diff --git a/fluxer_gateway/src/utils/shard_utils.erl b/fluxer_gateway/src/utils/shard_utils.erlindex f797eded3..969ca2c2e 100644--- a/fluxer_gateway/src/utils/shard_utils.erl+++ b/fluxer_gateway/src/utils/shard_utils.erl@@ -4,7 +4,6 @@-typing([eqwalizer]).-export([- max_positive/1,find_shard_by_ref/2,find_shard_by_pid/2,safe_gen_call/3,@@ -20,10 +19,6 @@-type shard() :: #{pid := pid(), ref := reference()}.--spec max_positive(list()) -> pos_integer().-max_positive(Candidates) ->- lists:max([C || C <- Candidates, is_integer(C), C > 0] ++ [1]).--spec find_shard_by_ref(reference(), #{non_neg_integer() => shard()}) ->{ok, non_neg_integer()} | not_found.find_shard_by_ref(Ref, Shards) ->@@ -132,64 +127,3 @@ check_pid_mailbox_pressure(Pid) ->{message_queue_len, Len} when Len > ?MAILBOX_PRESSURE_THRESHOLD -> overloaded;_ -> okend.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--safe_gen_call_noproc_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- ?assertEqual({error, unavailable}, safe_gen_call(Pid, ping, 100)).--safe_apply_error_test() ->- ?assertEqual(fallback, safe_apply(fun() -> error(boom) end, fallback)).--safe_apply_exit_test() ->- ?assertEqual(fallback, safe_apply(fun() -> exit(boom) end, fallback)).--safe_gen_call_detailed_noproc_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- ?assertEqual({error, unavailable}, safe_gen_call_detailed(Pid, ping, 100)).--safe_gen_call_remote_noproc_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- ?assertEqual({error, unavailable}, safe_gen_call_remote(Pid, ping, 100)).--safe_gen_call_wrapped_noproc_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- ?assertMatch({exit, _}, safe_gen_call_wrapped(Pid, ping, 100)).--check_mailbox_pressure_ok_test() ->- ?assertEqual(ok, check_mailbox_pressure(self())).--check_mailbox_pressure_dead_pid_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- ?assertEqual(ok, check_mailbox_pressure(Pid)).--check_mailbox_pressure_unregistered_name_test() ->- ?assertEqual(ok, check_mailbox_pressure(nonexistent_name_xyz_test)).--check_mailbox_pressure_remote_tuple_test() ->- ?assertEqual(ok, check_mailbox_pressure({some_name, 'nonode@nohost'})).--safe_cast_ok_test() ->- Pid = spawn(fun safe_cast_test_loop/0),- ?assertEqual(ok, safe_cast(Pid, hello)),- Pid ! stop.--safe_cast_test_loop() ->- receive- stop -> ok- after 5000 -> ok- end.--safe_cast_dead_pid_test() ->- Pid = spawn(fun() -> ok end),- ok = gateway_retry_timer:wait(50),- ?assertEqual(ok, safe_cast(Pid, hello)).---endif.diff --git a/fluxer_gateway/src/utils/snowflake_id.erl b/fluxer_gateway/src/utils/snowflake_id.erlindex 337e4785f..094b0ed65 100644--- a/fluxer_gateway/src/utils/snowflake_id.erl+++ b/fluxer_gateway/src/utils/snowflake_id.erl@@ -165,50 +165,6 @@ all_digits(<<Digit, Rest/binary>>) when Digit >= $0, Digit =< $9 ->all_digits(_) ->false.--ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--parse_accepts_integer_binary_and_list_test() ->- ?assertEqual(123, parse(123)),- ?assertEqual(456, parse(<<"456">>)),- ?assertEqual(789, parse("789")).--parse_rejects_non_canonical_values_test() ->- ?assertError({invalid_snowflake, 0}, parse(0)),- ?assertError({invalid_snowflake, <<"0">>}, parse(<<"0">>)),- ?assertError({invalid_snowflake, -1}, parse(-1)),- ?assertError({invalid_snowflake, <<"001">>}, parse(<<"001">>)),- ?assertError({invalid_snowflake, <<"+1">>}, parse(<<"+1">>)),- ?assertError({invalid_snowflake, <<"abc">>}, parse(<<"abc">>)).--parse_rejects_values_above_int64_test() ->- ?assertEqual(9223372036854775807, parse(9223372036854775807)),- ?assertEqual(9223372036854775807, parse(<<"9223372036854775807">>)),- ?assertEqual(9223372036854775807, parse("9223372036854775807")),- ?assertError({invalid_snowflake, 9223372036854775808}, parse(9223372036854775808)),- ?assertError(- {invalid_snowflake, <<"9223372036854775808">>}, parse(<<"9223372036854775808">>)- ),- ?assertError({invalid_snowflake, "9223372036854775808"}, parse("9223372036854775808")).--member_handles_mixed_edge_values_test() ->- ?assertEqual(true, member(123, [<<"123">>, 456])),- ?assertError({invalid_snowflake, <<"00123">>}, member(123, [<<"00123">>, 456])).--first_returns_first_valid_snowflake_test() ->- ?assertEqual(123, first([undefined, <<"123">>, 456])),- ?assertError({invalid_snowflake, <<"001">>}, first([undefined, <<"001">>, <<"123">>])),- ?assertError({invalid_snowflake, <<"0">>}, first([undefined, <<"0">>])).--get_prefers_integer_key_test() ->- Map = #{123 => int, <<"123">> => bin},- ?assertEqual(int, get(123, Map, missing)).--get_falls_back_to_binary_key_test() ->- ?assertEqual(bin, get(123, #{<<"123">> => bin}, missing)).---endif.--define(FLUXER_EPOCH, 1420070400000).-define(TIMESTAMP_SHIFT, 22).diff --git a/fluxer_gateway/src/utils/utils.erl b/fluxer_gateway/src/utils/utils.erlindex a0ec45aa3..22f23714f 100644--- a/fluxer_gateway/src/utils/utils.erl+++ b/fluxer_gateway/src/utils/utils.erl@@ -128,18 +128,3 @@ user_field_differs(Field, CurrentUserData, NewUserData) ->NewValue = maps:get(Field, NewUserData, undefined),CurrentValue =/= NewValueend.---ifdef(TEST).--include_lib("eunit/include/eunit.hrl").--check_user_data_differs_missing_field_test() ->- Current = #{<<"id">> => <<"123">>, <<"username">> => <<"test">>},- New = #{<<"id">> => <<"123">>},- ?assertEqual(false, check_user_data_differs(Current, New)).--check_user_data_differs_normalizes_equivalent_user_ids_test() ->- Current = #{<<"id">> => 123, <<"username">> => <<"test">>},- New = #{<<"id">> => <<"123">>, <<"username">> => <<"test">>},- ?assertEqual(false, check_user_data_differs(Current, New)).---endif.diff --git a/fluxer_gateway/test/call_p2p_tests.erl b/fluxer_gateway/test/call_p2p_tests.erldeleted file mode 100644index a4041adc8..000000000--- a/fluxer_gateway/test/call_p2p_tests.erl+++ /dev/null@@ -1,679 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(call_p2p_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--agreed_joiners_form_a_mesh_without_pending_connections_test() ->- with_stubs(fun() ->- State = join_all([{1, true}, {2, true}], call_state()),- ?assertEqual([true, true], p2p_flags(State)),- ?assertEqual(#{}, maps:get(pending_connections, State)),- ?assertEqual([], drain_voice_server_updates())- end).--sfu_join_keeps_its_pending_connection_test() ->- with_stubs(fun() ->- State = join_all([{1, false}], call_state()),- ?assert(maps:is_key(connection_id(1), maps:get(pending_connections, State)))- end).--race_sfu_join_after_p2p_start_is_rejected_test() ->- with_stubs(fun() ->- State = join_all([{1, true}], call_state()),- ?assertEqual(- {reply, {error, voice_p2p_consent_required}, State}, join(2, false, State)- ),- ?assertEqual([], drain_voice_server_updates())- end).--race_p2p_join_after_sfu_start_is_rejected_test() ->- with_stubs(fun() ->- State = join_all([{2, false}], call_state()),- ?assertEqual(- {reply, {error, voice_p2p_consent_required}, State}, join(1, true, State)- ),- ?assertEqual([], drain_voice_server_updates())- end).--fifth_joiner_over_the_cap_is_rejected_test() ->- with_stubs(fun() ->- Mesh = join_all([{UserId, true} || UserId <- [1, 2, 3, 4]], call_state()),- ?assertEqual([true, true, true, true], p2p_flags(Mesh)),- ?assertEqual({reply, {error, voice_channel_full}, Mesh}, join(5, true, Mesh)),- ?assertEqual([], drain_voice_server_updates())- end).--race_join_past_the_configured_cap_is_rejected_test() ->- with_stubs(fun() ->- Mesh = join_all([{1, true}, {2, true}], call_state()),- {reply, ok, Full} = call:handle_call(capped_join(3, 3), from(), Mesh),- ?assertEqual([true, true, true], p2p_flags(Full)),- ?assertEqual(- {reply, {error, voice_channel_full}, Full},- call:handle_call(capped_join(4, 3), from(), Full)- ),- ?assertNot(maps:is_key(4, maps:get(voice_states, Full))),- ?assertEqual(#{}, maps:get(pending_connections, Full)),- ?assertEqual([], drain_voice_server_updates())- end).--join_without_a_cap_falls_back_to_the_hard_ceiling_test() ->- with_stubs(fun() ->- Mesh = join_all([{UserId, true} || UserId <- [1, 2, 3]], call_state()),- {reply, ok, Full} = call:handle_call(- {join, 4, voice_state(4, true), session_id(4), erlang:get(call_p2p_sink),- connection_id(4)},- from(),- Mesh- ),- ?assertEqual([true, true, true, true], p2p_flags(Full))- end).--session_p2p_grant_passes_the_cap_to_the_call_join_test() ->- with_stubs(fun() ->- meck:new(gateway_rpc_call_lookup, [passthrough, no_link]),- try- {reply, #{success := true}, _State} = dm_join(true, [voice_state(20, true)]),- ?assertMatch(- [{join, 10, #{<<"p2p">> := true}, <<"sess">>, _Pid, _ConnectionId, 3}],- [- Request- || {_Caller, {gateway_rpc_call_lookup, safe_gen_server_call, [_, Request, _]},- _Result} <- meck:history(gateway_rpc_call_lookup),- element(1, Request) =:= join- ]- )- after- meck:unload(gateway_rpc_call_lookup)- end- end).--rejected_join_rolls_back_without_retrying_test() ->- with_stubs(fun() ->- erlang:put(call_p2p_join_reply, {error, voice_p2p_consent_required}),- ok = dm_voice_token:join_or_create_call(- 100, 10, voice_state(10, false), <<"sess">>, self(), undefined- ),- ?assertEqual(- [- {voice_rejected, voice_p2p_consent_required},- {call_force_disconnect, 100, connection_id(10)}- ],- drain_session_casts()- ),- ?assertEqual(1, meck:num_calls(call_manager, lookup, '_'))- end).--explicit_p2p_false_update_converts_test() ->- with_stubs(fun() ->- State0 = join_all([{1, true}, {2, true}], call_state()),- {reply, ok, State1} = call:handle_call(- {update_voice_state, 1, voice_state(1, false)}, from(), State0- ),- ?assertEqual([false, false], p2p_flags(State1)),- ?assertMatch(#{<<"p2p">> := false}, receive_voice_state_update(connection_id(2))),- ?assertEqual(- [connection_id(1), connection_id(2)], lists:sort(drain_voice_server_updates())- )- end).--update_keeping_p2p_keeps_the_mesh_test() ->- with_stubs(fun() ->- State0 = join_all([{1, true}, {2, true}], call_state()),- {reply, ok, State1} = call:handle_call(- {update_voice_state, 1, (voice_state(1, true))#{<<"self_mute">> => true}},- from(),- State0- ),- ?assertEqual([true, true], p2p_flags(State1)),- ?assertEqual([], drain_voice_server_updates())- end).--stale_p2p_update_after_conversion_stays_sfu_test() ->- with_stubs(fun() ->- Mesh = join_all([{1, true}, {2, true}], call_state()),- {reply, ok, State0} = call:handle_call(- {update_voice_state, 2, voice_state(2, false)}, from(), Mesh- ),- ?assertEqual(2, length(drain_voice_server_updates())),- ok = flush_user_dispatches(),- {reply, ok, State1} = call:handle_call(- {update_voice_state, 1, voice_state(1, true)}, from(), State0- ),- ?assertEqual([false, false], p2p_flags(State1)),- ?assertMatch(#{<<"p2p">> := false}, receive_voice_state_update(connection_id(1))),- ?assertEqual([], drain_voice_server_updates())- end).--same_region_update_converts_a_mesh_test() ->- with_stubs(fun() ->- State0 = join_all([{1, true}, {2, true}], (call_state())#{region => <<"us-east">>}),- ok = flush_user_dispatches(),- {reply, ok, State1} = call:handle_call({update_region, <<"us-east">>}, from(), State0),- ?assertEqual([false, false], p2p_flags(State1)),- ?assertEqual(- [connection_id(1), connection_id(2)], lists:sort(drain_voice_server_updates())- ),- ?assertEqual(- [<<"us-east">>, <<"us-east">>],- [maps:get(<<"rtc_region">>, Request) || Request <- token_requests()]- ),- ?assertMatch(- #{voice_states := [#{<<"p2p">> := false}, #{<<"p2p">> := false}]},- receive_user_dispatch(call_update)- )- end).--same_region_update_leaves_an_sfu_call_alone_test() ->- with_stubs(fun() ->- State0 = join_all([{1, false}, {2, false}], (call_state())#{region => <<"us-east">>}),- {reply, ok, _State1} = call:handle_call({update_region, <<"us-east">>}, from(), State0),- ?assertEqual([], drain_voice_server_updates())- end).--call_event_and_handoff_keep_the_p2p_flag_test() ->- with_stubs(fun() ->- State = join_all([{1, true}], call_state()),- ?assertMatch(- #{voice_states := [#{<<"p2p">> := true}]}, call_state:build_call_event(State)- ),- Restored = call_handoff:restore_state(call_handoff:export_state(State)),- ?assertEqual([true], p2p_flags(Restored))- end).--signal_relay_allowed_test() ->- with_stubs(fun() ->- State = join_all([{1, true}, {2, true}], call_state()),- Data = #{<<"type">> => <<"answer">>, <<"sdp">> => <<"v=0">>},- {noreply, State} = call:handle_cast(- {voice_signal, session_id(1), connection_id(2), Data}, State- ),- ?assertEqual(- #{- <<"channel_id">> => <<"1">>,- <<"from">> => connection_id(1),- <<"user_id">> => <<"1">>,- <<"data">> => Data- },- receive_voice_signal()- )- end).--signal_relay_denied_test() ->- with_stubs(fun() ->- Mesh = join_all([{1, true}, {2, true}], call_state()),- Data = #{<<"type">> => <<"candidate">>},- Denied = [- {voice_signal, session_id(9), connection_id(2), Data},- {voice_signal, session_id(1), connection_id(1), Data},- {voice_signal, session_id(1), <<"unknown">>, Data}- ],- [{noreply, Mesh} = call:handle_cast(Signal, Mesh) || Signal <- Denied],- {reply, ok, Sfu} = call:handle_call({update_region, <<"us-east">>}, from(), Mesh),- {noreply, Sfu} = call:handle_cast(- {voice_signal, session_id(1), connection_id(2), Data}, Sfu- ),- assert_no_voice_signal()- end).--session_p2p_start_without_a_call_test() ->- with_stubs(fun() ->- {reply, #{success := true, connection_id := ConnectionId}, State} = dm_join(- true, not_found- ),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := true,- <<"p2p_participant_count">> := 1,- <<"country_code">> := <<"SE">>- },- lists:last(token_requests())- ),- ?assertEqual(- true, maps:get(<<"p2p">>, maps:get(ConnectionId, maps:get(dm_voice_states, State)))- ),- Update = receive_session_voice_server_update(),- ?assertEqual(- #{- <<"p2p">> => true,- <<"ice_servers">> => [#{<<"urls">> => [<<"stun:stun.example:3478">>]}],- <<"connection_id">> => ConnectionId,- <<"channel_id">> => <<"100">>- },- Update- )- end).--session_p2p_join_of_an_existing_mesh_test() ->- with_stubs(fun() ->- {reply, #{success := true}, _State} = dm_join(true, [voice_state(20, true)]),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := false,- <<"p2p_participant_count">> := 2- },- lists:last(token_requests())- ),- ?assertMatch(#{<<"p2p">> := true}, receive_session_voice_server_update())- end).--session_join_from_a_second_device_counts_the_user_once_test() ->- with_stubs(fun() ->- {reply, #{success := true}, _State} = dm_join(- true, [voice_state(20, true), voice_state(10, true)]- ),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := false,- <<"p2p_participant_count">> := 2- },- lists:last(token_requests())- )- end).--session_join_of_an_sfu_call_does_not_ask_for_p2p_test() ->- with_stubs(fun() ->- {reply, #{success := true, connection_id := ConnectionId}, State} = dm_join(- true, [voice_state(20, false)]- ),- ?assertNot(maps:is_key(<<"p2p">>, lists:last(token_requests()))),- ?assertEqual(- false, maps:get(<<"p2p">>, maps:get(ConnectionId, maps:get(dm_voice_states, State)))- ),- Update = receive_session_voice_server_update(),- ?assertEqual(<<"tok">>, maps:get(<<"token">>, Update)),- ?assertNot(maps:is_key(<<"p2p">>, Update))- end).--session_join_of_a_mesh_without_agreement_is_rejected_test() ->- with_stubs(fun() ->- ?assertMatch(- {reply, {error, permission_denied, voice_p2p_consent_required}, #{- dm_voice_states := #{}- }},- dm_join_reply(undefined, [voice_state(20, true)])- ),- ?assertEqual([], token_requests()),- assert_no_session_voice_server_update()- end).--session_bot_join_of_a_mesh_is_rejected_test() ->- with_stubs(fun() ->- erlang:put(call_p2p_call_voice_states, [voice_state(20, true)]),- State = dm_session_state(#{}),- ?assertMatch(- {reply, {error, permission_denied, voice_p2p_consent_required}, _State},- dm_voice_token:get_dm_voice_token_and_create_state(- (dm_request(true, State))#{bot => true}- )- )- end).--session_join_of_a_full_mesh_is_rejected_test() ->- with_stubs(fun() ->- Mesh = [voice_state(UserId, true) || UserId <- [20, 21, 22, 23]],- ?assertMatch(- {reply, {error, permission_denied, voice_channel_full}, _State},- dm_join_reply(true, Mesh)- ),- ?assertEqual([], token_requests())- end).--session_join_past_the_configured_cap_is_rejected_as_full_test() ->- with_stubs(fun() ->- erlang:put(call_p2p_stub_mode, channel_full),- ?assertMatch(- {reply, {error, permission_denied, voice_channel_full}, #{dm_voice_states := #{}}},- dm_join_reply(true, [voice_state(20, true), voice_state(21, true)])- ),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := false,- <<"p2p_participant_count">> := 3- },- lists:last(token_requests())- ),- assert_no_session_voice_server_update()- end).--session_declined_grant_into_a_mesh_is_rejected_test() ->- with_stubs(fun() ->- erlang:put(call_p2p_stub_mode, decline),- ?assertMatch(- {reply, {error, voice_error, voice_p2p_unavailable}, #{dm_voice_states := #{}}},- dm_join_reply(true, [voice_state(20, true)])- ),- ?assertMatch(- #{<<"p2p">> := true, <<"p2p_initiator">> := false}, lists:last(token_requests())- ),- assert_no_session_voice_server_update()- end).--session_declined_grant_without_a_call_joins_sfu_test() ->- with_stubs(fun() ->- erlang:put(call_p2p_stub_mode, decline),- {reply, #{success := true, connection_id := ConnectionId}, State} = dm_join(- true, not_found- ),- ?assertEqual(- false, maps:get(<<"p2p">>, maps:get(ConnectionId, maps:get(dm_voice_states, State)))- ),- ?assertEqual(<<"tok">>, maps:get(<<"token">>, receive_session_voice_server_update()))- end).--session_update_with_explicit_p2p_false_clears_the_flag_test() ->- with_stubs(fun() ->- ?assertEqual(false, dm_updated_p2p(false)),- ?assertEqual(true, dm_updated_p2p(undefined)),- ?assertEqual(true, dm_updated_p2p(true))- end).--dm_updated_p2p(P2p) ->- Existing = (voice_state(10, true))#{- <<"channel_id">> => <<"100">>, <<"session_id">> => <<"sess">>- },- ConnectionId = connection_id(10),- State = dm_session_state(#{ConnectionId => Existing}),- {reply, #{success := true}, NewState} = dm_voice_connect:handle_dm_connect_or_update(- (dm_request(P2p, State))#{- connection_id => ConnectionId, viewer_stream_keys => undefined- }- ),- maps:get(<<"p2p">>, maps:get(ConnectionId, maps:get(dm_voice_states, NewState))).--dm_join_reply(P2p, CallVoiceStates) ->- erlang:put(call_p2p_call_voice_states, CallVoiceStates),- State = dm_session_state(#{}),- dm_voice_token:get_dm_voice_token_and_create_state(dm_request(P2p, State)).--dm_join(P2p, CallVoiceStates) ->- Reply = dm_join_reply(P2p, CallVoiceStates),- receive- {'$gen_cast', {call_monitor, 100, _CallPid}} -> Reply- after 1000 ->- error(call_not_joined)- end.--dm_session_state(VoiceStates) ->- #{- dm_voice_states => VoiceStates,- channels => #{100 => #{<<"type">> => 1, <<"recipient_ids">> => [20]}},- user_id => 10,- id => <<"sess">>,- session_pid => erlang:get(call_p2p_sink)- }.--dm_request(P2p, State) ->- #{- user_id => 10,- channel_id => 100,- session_id => <<"sess">>,- connection_id => null,- self_mute => false,- self_deaf => false,- self_video => false,- self_stream => false,- viewer_stream_keys => [],- is_mobile => false,- latitude => null,- longitude => null,- e2ee_capable => false,- bot => false,- p2p => P2p,- country_code => <<"SE">>,- voice_states => maps:get(dm_voice_states, State),- state => State- }.--join_all(Joins, State0) ->- lists:foldl(- fun({UserId, P2p}, State) ->- {reply, ok, NewState} = join(UserId, P2p, State),- NewState- end,- State0,- Joins- ).--join(UserId, P2p, State) ->- call_voice:handle_join_internal(- UserId,- voice_state(UserId, P2p),- session_id(UserId),- erlang:get(call_p2p_sink),- connection_id(UserId),- undefined,- State- ).--capped_join(UserId, MaxParticipants) ->- {join, UserId, voice_state(UserId, true), session_id(UserId), erlang:get(call_p2p_sink),- connection_id(UserId), MaxParticipants}.--p2p_flags(State) ->- [- maps:get(<<"p2p">>, VoiceState)- || {_UserId, VoiceState} <- lists:keysort(1, maps:to_list(maps:get(voice_states, State)))- ].--voice_state(UserId, P2p) ->- #{- <<"user_id">> => integer_to_binary(UserId),- <<"channel_id">> => <<"1">>,- <<"connection_id">> => connection_id(UserId),- <<"session_id">> => session_id(UserId),- <<"p2p">> => P2p- }.--connection_id(UserId) ->- <<"conn-", (integer_to_binary(UserId))/binary>>.--session_id(UserId) ->- <<"sess-", (integer_to_binary(UserId))/binary>>.--from() ->- {self(), make_ref()}.--call_state() ->- #{- channel_id => 1,- message_id => 1,- region => undefined,- ringing => [],- pending_ringing => [],- recipients => [1],- voice_states => #{},- sessions => #{},- pending_connections => #{},- initiator_ready => true,- ringing_timers => #{},- idle_timer => undefined,- created_at => 0,- participants_history => sets:new(),- last_call_event => undefined- }.--token_requests() ->- [- Request- || {_Pid, {rpc_client, call, [#{<<"type">> := <<"voice_get_token">>} = Request]}, _Result} <-- meck:history(rpc_client)- ].--drain_voice_server_updates() ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} ->- ?assertEqual(<<"tok">>, maps:get(<<"token">>, Payload)),- ?assertNot(maps:is_key(<<"p2p">>, Payload)),- [maps:get(<<"connection_id">>, Payload) | drain_voice_server_updates()]- after 200 ->- []- end.--receive_session_voice_server_update() ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} -> Payload- after 1000 ->- error(voice_server_update_not_dispatched)- end.--assert_no_session_voice_server_update() ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} ->- error({unexpected_voice_server_update, Payload})- after 100 ->- ok- end.--drain_session_casts() ->- receive- {'$gen_cast', Cast} -> [Cast | drain_session_casts()]- after 100 ->- []- end.--receive_voice_state_update(ConnectionId) ->- case receive_user_dispatch(voice_state_update) of- #{<<"connection_id">> := ConnectionId} = VoiceState -> VoiceState;- _Other -> receive_voice_state_update(ConnectionId)- end.--receive_user_dispatch(Event) ->- receive- {user_dispatch, Event, Data} -> Data- after 1000 ->- error({user_dispatch_not_received, Event})- end.--flush_user_dispatches() ->- receive- {user_dispatch, _Event, _Data} -> flush_user_dispatches()- after 100 ->- ok- end.--receive_voice_signal() ->- receive- {'$gen_cast', {dispatch, voice_signal, Payload}} -> Payload- after 1000 ->- error(voice_signal_not_dispatched)- end.--assert_no_voice_signal() ->- receive- {'$gen_cast', {dispatch, voice_signal, Payload}} ->- error({unexpected_voice_signal, Payload})- after 100 ->- ok- end.--with_stubs(Fun) ->- Test = self(),- Sink = spawn(fun() -> sink(Test) end),- erlang:put(call_p2p_sink, Sink),- erlang:erase(call_p2p_call_voice_states),- erlang:erase(call_p2p_stub_mode),- erlang:erase(call_p2p_join_reply),- meck:new(rpc_client, [passthrough, no_link, non_strict]),- meck:expect(rpc_client, call, fun rpc_reply/1),- meck:new(presence_manager, [passthrough, no_link]),- meck:expect(presence_manager, dispatch_to_user, fun(_UserId, Event, Data) ->- Sink ! {user_dispatch, Event, Data},- ok- end),- CallPid = spawn(fun call_stub/0),- meck:new(call_manager, [passthrough, no_link]),- meck:expect(call_manager, lookup, fun(_ChannelId) ->- case erlang:get(call_p2p_call_voice_states) of- not_found ->- {error, not_found};- VoiceStates when is_list(VoiceStates) ->- CallPid ! {voice_states, VoiceStates},- {ok, CallPid};- undefined ->- CallPid ! {join_reply, erlang:get(call_p2p_join_reply)},- {ok, CallPid}- end- end),- try- Fun()- after- CallPid ! stop,- meck:unload(call_manager),- meck:unload(presence_manager),- meck:unload(rpc_client),- stop_sink(Sink)- end.--sink(Test) ->- receive- Message ->- Test ! Message,- sink(Test)- after 30000 ->- ok- end.--stop_sink(Sink) ->- exit(Sink, kill),- flush_mailbox().--flush_mailbox() ->- receive- _Message -> flush_mailbox()- after 0 ->- ok- end.--call_stub() ->- call_stub([], ok).--call_stub(VoiceStates, JoinReply) ->- receive- {voice_states, NewVoiceStates} ->- call_stub(NewVoiceStates, JoinReply);- {join_reply, undefined} ->- call_stub(VoiceStates, JoinReply);- {join_reply, NewJoinReply} ->- call_stub(VoiceStates, NewJoinReply);- {'$gen_call', From, {get_state}} ->- gen_server:reply(From, {ok, #{voice_states => VoiceStates, region => undefined}}),- call_stub(VoiceStates, JoinReply);- {'$gen_call', From, _Request} ->- gen_server:reply(From, JoinReply),- call_stub(VoiceStates, JoinReply);- stop ->- ok;- _Other ->- call_stub(VoiceStates, JoinReply)- after 30000 ->- ok- end.--rpc_reply(#{<<"type">> := <<"voice_get_token">>} = Request) ->- ConnectionId = maps:get(<<"connection_id">>, Request, <<"conn-new">>),- case {maps:get(<<"p2p">>, Request, false), erlang:get(call_p2p_stub_mode)} of- {true, channel_full} ->- {ok, #{<<"p2p">> => false, <<"declineReason">> => <<"channel_full">>}};- {true, Mode} when Mode =/= decline ->- {ok, #{- <<"p2p">> => true,- <<"connectionId">> => ConnectionId,- <<"iceServers">> => [#{<<"urls">> => [<<"stun:stun.example:3478">>]}],- <<"maxParticipants">> => 3- }};- _ ->- {ok, #{- <<"token">> => <<"tok">>,- <<"endpoint">> => <<"wss://voice.example">>,- <<"connectionId">> => ConnectionId- }}- end;-rpc_reply(_Request) ->- {ok, #{}}.diff --git a/fluxer_gateway/test/call_tests.erl b/fluxer_gateway/test/call_tests.erldeleted file mode 100644index 57f39134c..000000000--- a/fluxer_gateway/test/call_tests.erl+++ /dev/null@@ -1,376 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(call_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--remove_users_from_ringing_test() ->- State = new_call_test_state(#{- ringing => [1, 2, 3],- pending_ringing => [4, 5]- }),- Result = call_ringing:remove_users_from_ringing([2, 4], State),- ?assertEqual([1, 3], maps:get(ringing, Result)),- ?assertEqual([5], maps:get(pending_ringing, Result)).--join_from_ringing_adds_voice_state_test() ->- UserId = 42,- SessionId = <<"session-42">>,- ConnectionId = <<"conn-42">>,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => ConnectionId- },- State = new_call_test_state(#{- ringing => [UserId],- initiator_ready => true- }),- {reply, ok, NewState} = call_voice:handle_join_internal(- UserId, VoiceState, SessionId, self(), ConnectionId, undefined, State- ),- ?assert(maps:is_key(UserId, maps:get(voice_states, NewState))),- ?assertNot(lists:member(UserId, maps:get(ringing, NewState))).--pending_connection_timeout_preserves_active_voice_state_test() ->- UserId = 42,- SessionId = <<"session-42">>,- ConnectionId = <<"conn-42">>,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => ConnectionId- },- State = new_call_test_state(#{- voice_states => #{UserId => VoiceState},- pending_connections => #{- ConnectionId => #{- user_id => UserId,- session_id => SessionId,- connection_id => ConnectionId,- channel_id => 1- }- },- initiator_ready => true- }),- {noreply, NewState} = call_voice:disconnect_user_after_pending_timeout(- ConnectionId, UserId, SessionId, State- ),- ?assert(maps:is_key(UserId, maps:get(voice_states, NewState))),- ?assertEqual(- undefined,- maps:get(- ConnectionId, maps:get(pending_connections, NewState), undefined- )- ).--leave_then_rejoin_keeps_voice_state_test() ->- UserId = 42,- OtherUserId = 84,- SessionId = <<"session-42">>,- OtherSessionId = <<"session-84">>,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => <<"conn-42">>- },- OtherVoiceState = #{- <<"user_id">> => <<"84">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => <<"conn-84">>- },- State = new_call_test_state(#{- voice_states => #{- UserId => VoiceState,- OtherUserId => OtherVoiceState- },- sessions => #{- SessionId => {UserId, self(), make_ref()},- OtherSessionId => {OtherUserId, self(), make_ref()}- },- initiator_ready => true- }),- {reply, ok, PostLeave} = call:handle_call(- {leave, SessionId}, {self(), make_ref()}, State- ),- ?assertEqual(- undefined,- maps:get(- UserId, maps:get(voice_states, PostLeave), undefined- )- ),- ?assertEqual(- undefined,- maps:get(- SessionId, maps:get(sessions, PostLeave), undefined- )- ),- {reply, ok, Rejoined} = call_voice:handle_join_internal(- UserId, VoiceState, SessionId, self(), <<"conn-42">>, undefined, PostLeave- ),- ?assert(maps:is_key(UserId, maps:get(voice_states, Rejoined))).--disconnect_user_if_in_channel_notifies_session_cleanup_test() ->- UserId = 42,- OtherUserId = 84,- SessionId = <<"session-42">>,- OtherSessionId = <<"session-84">>,- ConnectionId = <<"conn-42">>,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => ConnectionId- },- OtherVoiceState = #{- <<"user_id">> => <<"84">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => <<"conn-84">>- },- State = new_call_test_state(#{- voice_states => #{- UserId => VoiceState,- OtherUserId => OtherVoiceState- },- sessions => #{- SessionId => {UserId, self(), make_ref()},- OtherSessionId => {OtherUserId, self(), make_ref()}- },- initiator_ready => true- }),- {reply, #{success := true}, NewState} = call:handle_call(- {disconnect_user_if_in_channel, UserId, 1, ConnectionId},- {self(), make_ref()},- State- ),- ?assertEqual(- undefined,- maps:get(- UserId, maps:get(voice_states, NewState), undefined- )- ),- receive- {'$gen_cast', {call_force_disconnect, 1, ConnectionId}} ->- ok- after 1000 ->- ?assert(false)- end.--disconnect_user_if_in_channel_ignores_a_stale_connection_id_test() ->- UserId = 42,- SessionId = <<"session-42">>,- LiveConnectionId = <<"conn-live">>,- StaleConnectionId = <<"conn-stale">>,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => LiveConnectionId- },- State = new_call_test_state(#{- voice_states => #{UserId => VoiceState},- sessions => #{SessionId => {UserId, self(), make_ref()}},- initiator_ready => true- }),- {reply, Reply, NewState} = call:handle_call(- {disconnect_user_if_in_channel, UserId, 1, StaleConnectionId},- {self(), make_ref()},- State- ),- ?assertMatch(#{ignored := true, reason := <<"not_in_call">>}, Reply),- ?assertEqual(- VoiceState,- maps:get(UserId, maps:get(voice_states, NewState), undefined)- ),- receive- {'$gen_cast', {call_force_disconnect, _, _}} ->- ?assert(false, force_disconnected_a_live_connection)- after 200 ->- ok- end.--leave_removes_voice_state_count_without_full_rebuild_test() ->- UserId = 42,- SessionId = <<"session-count-leave">>,- ConnectionId = <<"conn-count-leave">>,- RegionId = <<"count-test-region">>,- ServerId = <<"count-test-server">>,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => ConnectionId,- <<"region_id">> => RegionId,- <<"server_id">> => ServerId- },- ok = voice_state_counts_cache:remove_connection(ConnectionId),- ok = voice_state_counts_cache:upsert_voice_state(VoiceState),- ?assertEqual(1, voice_count(<<"servers">>, <<"server_id">>, ServerId)),- State = new_call_test_state(#{- voice_states => #{UserId => VoiceState},- sessions => #{SessionId => {UserId, self(), make_ref()}},- initiator_ready => true- }),- {stop, normal, ok, _PostLeave} = call:handle_call(- {leave, SessionId}, {self(), make_ref()}, State- ),- ?assertEqual(0, voice_count(<<"regions">>, <<"region_id">>, RegionId)),- ?assertEqual(0, voice_count(<<"servers">>, <<"server_id">>, ServerId)),- ok = voice_state_counts_cache:remove_connection(ConnectionId).--call_manager_cleanup_call_pid_cache_on_down_test() ->- case ets:info(call_pid_cache) of- undefined ->- ets:new(call_pid_cache, [- named_table,- public,- set,- {read_concurrency, true},- {write_concurrency, true}- ]);- _ ->- ok- end,- FakePid = spawn(fun() ->- receive- stop -> ok- after 30000 ->- ok- end- end),- ChannelId = 999888,- ets:insert(call_pid_cache, {ChannelId, FakePid}),- Ref = make_ref(),- Calls = #{ChannelId => {FakePid, Ref}},- State = #{calls => Calls},- {noreply, NewState} = call_manager:handle_info(- {'DOWN', Ref, process, FakePid, normal}, State- ),- ?assertEqual([], ets:lookup(call_pid_cache, ChannelId)),- ?assertNot(maps:is_key(ChannelId, maps:get(calls, NewState))),- FakePid ! stop.--voice_count(CollectionKey, IdKey, Id) ->- Counts = voice_state_counts_cache:get_local_counts(),- Entries = maps:get(CollectionKey, Counts, []),- lists:foldl(- fun(Entry, Acc) ->- case- {maps:get(IdKey, Entry, undefined), maps:get(<<"voice_state_count">>, Entry, 0)}- of- {Id, Count} when is_integer(Count) -> Count;- _ -> Acc- end- end,- 0,- Entries- ).--leave_with_second_session_keeps_voice_state_test() ->- UserId = 42,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => <<"conn-42">>- },- State = new_call_test_state(#{- voice_states => #{UserId => VoiceState},- sessions => #{- <<"session-a">> => {UserId, self(), make_ref()},- <<"session-b">> => {UserId, self(), make_ref()}- },- initiator_ready => true- }),- {reply, ok, AfterFirstLeave} = call:handle_call(- {leave, <<"session-a">>}, {self(), make_ref()}, State- ),- ?assertEqual(VoiceState, maps:get(UserId, maps:get(voice_states, AfterFirstLeave))),- ?assertNot(maps:is_key(<<"session-a">>, maps:get(sessions, AfterFirstLeave))),- ?assert(maps:is_key(<<"session-b">>, maps:get(sessions, AfterFirstLeave))),- {stop, normal, ok, AfterSecondLeave} = call:handle_call(- {leave, <<"session-b">>}, {self(), make_ref()}, AfterFirstLeave- ),- ?assertNot(maps:is_key(UserId, maps:get(voice_states, AfterSecondLeave))),- ?assertEqual(#{}, maps:get(sessions, AfterSecondLeave)).--session_down_with_second_session_keeps_voice_state_test() ->- UserId = 42,- VoiceState = #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => <<"conn-42">>- },- DownPid = spawn(fun() ->- receive- stop -> ok- after 30000 ->- ok- end- end),- State = new_call_test_state(#{- voice_states => #{UserId => VoiceState},- sessions => #{- <<"session-a">> => {UserId, DownPid, make_ref()},- <<"session-b">> => {UserId, self(), make_ref()}- },- initiator_ready => true- }),- {noreply, NewState} = call_voice:handle_session_down(DownPid, State),- ?assertEqual(VoiceState, maps:get(UserId, maps:get(voice_states, NewState))),- ?assertNot(maps:is_key(<<"session-a">>, maps:get(sessions, NewState))),- ?assert(maps:is_key(<<"session-b">>, maps:get(sessions, NewState))),- DownPid ! stop.--disconnect_user_removes_all_user_sessions_test() ->- UserId = 42,- VoiceStates = #{- UserId => #{- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"1">>,- <<"connection_id">> => <<"conn-42">>- }- },- Sessions = #{- <<"session-a">> => {UserId, self(), make_ref()},- <<"session-b">> => {UserId, self(), make_ref()},- <<"session-other">> => {84, self(), make_ref()}- },- TestPid = self(),- CleanupFun = fun(CleanupUserId, SessionId) ->- TestPid ! {cleanup, CleanupUserId, SessionId},- ok- end,- {ok, NewVoiceStates, NewSessions} = voice_disconnect_common:disconnect_user_if_in_channel(- UserId, 1, undefined, VoiceStates, Sessions, CleanupFun- ),- ?assertEqual(#{}, NewVoiceStates),- ?assertEqual([<<"session-other">>], maps:keys(NewSessions)),- CleanedSessions = lists:sort([- receive- {cleanup, UserId, SId} -> SId- after 1000 ->- error(cleanup_not_called)- end- || _ <- [1, 2]- ]),- ?assertEqual([<<"session-a">>, <<"session-b">>], CleanedSessions).--new_call_test_state(Overrides) ->- maps:merge(- #{- channel_id => 1,- message_id => 1,- region => undefined,- ringing => [],- pending_ringing => [],- recipients => [],- voice_states => #{},- sessions => #{},- pending_connections => #{},- initiator_ready => false,- ringing_timers => #{},- idle_timer => undefined,- created_at => 0,- participants_history => sets:new(),- last_call_event => undefined- },- Overrides- ).diff --git a/fluxer_gateway/test/dm_voice_connect_tests.erl b/fluxer_gateway/test/dm_voice_connect_tests.erldeleted file mode 100644index afafa8cb8..000000000--- a/fluxer_gateway/test/dm_voice_connect_tests.erl+++ /dev/null@@ -1,207 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(dm_voice_connect_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--handle_dm_connect_or_update_user_mismatch_test() ->- State = base_state(existing_voice_states(20)),- {reply, {error, validation_error, voice_user_mismatch}, _} = call_update(State, #{}).--handle_dm_connect_or_update_owner_match_proceeds_test() ->- State = base_state(existing_voice_states(10)),- case call_update(State, #{}) of- {reply, {error, validation_error, voice_user_mismatch}, _} ->- error(should_not_get_user_mismatch);- {reply, _, _} ->- ok- end.--handle_dm_connect_or_update_accepts_dm_viewer_stream_key_test() ->- StreamKey = <<"dm:100:conn-stream">>,- State = base_state(stream_voice_states([])),- {reply, #{success := true}, NewState} = call_update(State, #{- viewer_stream_keys => [StreamKey]- }),- Updated = updated_voice_state(NewState),- ?assertEqual([StreamKey], maps:get(<<"viewer_stream_keys">>, Updated)).--handle_dm_connect_or_update_preserves_viewer_keys_when_omitted_test() ->- StreamKey = <<"dm:100:conn-stream">>,- State = base_state(stream_voice_states([StreamKey])),- {reply, #{success := true}, NewState} = call_update(State, #{- self_mute => true,- viewer_stream_keys => undefined- }),- Updated = updated_voice_state(NewState),- ?assertEqual(true, maps:get(<<"self_mute">>, Updated)),- ?assertEqual([StreamKey], maps:get(<<"viewer_stream_keys">>, Updated)).--handle_dm_connect_or_update_clears_viewer_keys_when_null_test() ->- StreamKey = <<"dm:100:conn-stream">>,- State = base_state(stream_voice_states([StreamKey])),- {reply, #{success := true}, NewState} = call_update(State, #{- viewer_stream_keys => null- }),- Updated = updated_voice_state(NewState),- ?assertEqual([], maps:get(<<"viewer_stream_keys">>, Updated)).--handle_dm_connect_or_update_rejects_guild_scope_viewer_stream_key_test() ->- State = base_state(stream_voice_states([])),- {reply, {error, validation_error, voice_invalid_state}, _} = call_update(State, #{- viewer_stream_keys => [<<"999:100:conn-stream">>]- }).--handle_dm_connect_or_update_rejects_wrong_channel_viewer_stream_key_test() ->- State = base_state(stream_voice_states([])),- {reply, {error, validation_error, voice_invalid_state}, _} = call_update(State, #{- viewer_stream_keys => [<<"dm:101:conn-stream">>]- }).--handle_dm_connect_or_update_rejects_missing_watched_connection_test() ->- State = base_state(stream_voice_states([])),- {reply, {error, not_found, voice_connection_not_found}, _} = call_update(State, #{- viewer_stream_keys => [<<"dm:100:missing-conn">>]- }).--handle_dm_connect_or_update_rejects_non_list_viewer_stream_keys_test() ->- State = base_state(stream_voice_states([])),- {reply, {error, validation_error, voice_invalid_state}, _} = call_update(State, #{- viewer_stream_keys => 123- }).--handle_dm_connect_or_update_enforces_per_user_channel_connection_limit_test() ->- State = base_state(limit_voice_states()),- {reply, {error, permission_denied, voice_connection_limit_reached}, _} =- call_update(State, #{connection_id => null}).--handle_dm_voice_with_channel_accepts_group_dm_existing_update_test() ->- State = base_state(existing_voice_states(10)),- Channel = #{<<"type">> => 3, <<"recipient_ids">> => [20, 30]},- {reply, #{success := true}, _} = dm_voice_connect:handle_dm_voice_with_channel(- Channel, 100, 10, gateway_request(#{connection_id => <<"conn-1">>}), State- ).--handle_dm_voice_with_channel_rejects_non_dm_channel_type_test() ->- State = base_state(existing_voice_states(10)),- Channel = #{<<"type">> => 2, <<"recipient_ids">> => [20]},- {reply, {error, validation_error, dm_invalid_channel_type}, _} =- dm_voice_connect:handle_dm_voice_with_channel(- Channel, 100, 10, gateway_request(#{connection_id => <<"conn-1">>}), State- ).--handle_dm_voice_with_channel_rejects_non_recipient_test() ->- State = base_state(existing_voice_states(20)),- Channel = #{<<"type">> => 1, <<"recipient_ids">> => [10]},- {reply, {error, permission_denied, dm_not_recipient}, _} =- dm_voice_connect:handle_dm_voice_with_channel(- Channel, 100, 20, gateway_request(#{connection_id => <<"conn-1">>}), State- ).--handle_dm_connect_or_update_stress_many_watch_unwatch_updates_test() ->- StreamKey = <<"dm:100:conn-stream">>,- InitialState = base_state(stream_voice_states([])),- FinalState = lists:foldl(- fun(Index, State) ->- Keys =- case Index rem 3 of- 0 -> [];- _ -> [StreamKey]- end,- SelfMute = Index rem 2 =:= 0,- {reply, #{success := true}, NewState} = call_update(State, #{- self_mute => SelfMute,- viewer_stream_keys => Keys- }),- Updated = updated_voice_state(NewState),- ?assertEqual(SelfMute, maps:get(<<"self_mute">>, Updated)),- ?assertEqual(Keys, maps:get(<<"viewer_stream_keys">>, Updated)),- NewState- end,- InitialState,- lists:seq(1, 60)- ),- ?assertMatch(#{dm_voice_states := #{}}, FinalState).--existing_voice_states(UserId) ->- #{<<"conn-1">> => voice_state(<<"conn-1">>, UserId, 100, [])}.--stream_voice_states(InitialViewerKeys) ->- #{- <<"conn-1">> => voice_state(<<"conn-1">>, 10, 100, InitialViewerKeys),- <<"conn-stream">> => voice_state(<<"conn-stream">>, 20, 100, [])- }.--limit_voice_states() ->- maps:from_list([- {- <<"conn-", (integer_to_binary(Index))/binary>>,- voice_state(conn_id(Index), 10, 100, [])- }- || Index <- lists:seq(1, 5)- ]).--conn_id(Index) ->- <<"conn-", (integer_to_binary(Index))/binary>>.--voice_state(ConnectionId, UserId, ChannelId, ViewerKeys) ->- #{- <<"connection_id">> => ConnectionId,- <<"channel_id">> => integer_to_binary(ChannelId),- <<"user_id">> => integer_to_binary(UserId),- <<"session_id">> => <<"sess">>,- <<"self_mute">> => false,- <<"self_deaf">> => false,- <<"self_video">> => false,- <<"self_stream">> => false,- <<"is_mobile">> => false,- <<"viewer_stream_keys">> => ViewerKeys- }.--base_state(VoiceStates) ->- #{- dm_voice_states => VoiceStates,- channels => #{100 => #{<<"type">> => 1, <<"recipient_ids">> => [20, 30]}},- user_id => 10,- id => <<"sess">>,- session_pid => self()- }.--gateway_request(Overrides) ->- maps:merge(- #{- session_id => <<"sess">>,- connection_id => null,- self_mute => false,- self_deaf => false,- self_video => false,- self_stream => false,- viewer_stream_keys => undefined,- is_mobile => false,- latitude => null,- longitude => null,- e2ee_capable => false,- bot => false- },- Overrides- ).--connect_request(State, Overrides) ->- VoiceStates = maps:get(dm_voice_states, State, #{}),- maps:merge(- gateway_request(#{- user_id => 10,- channel_id => 100,- connection_id => <<"conn-1">>,- voice_states => VoiceStates,- state => State- }),- Overrides- ).--call_update(State, Overrides) ->- dm_voice_connect:handle_dm_connect_or_update(connect_request(State, Overrides)).--updated_voice_state(State) ->- maps:get(<<"conn-1">>, maps:get(dm_voice_states, State)).diff --git a/fluxer_gateway/test/dm_voice_state_tests.erl b/fluxer_gateway/test/dm_voice_state_tests.erldeleted file mode 100644index 159ef9ae2..000000000--- a/fluxer_gateway/test/dm_voice_state_tests.erl+++ /dev/null@@ -1,122 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(dm_voice_state_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--handle_dm_disconnect_clears_e2ee_key_when_channel_empty_test() ->- VoiceState = #{- <<"channel_id">> => <<"100">>,- <<"user_id">> => <<"10">>,- <<"session_id">> => <<"sess">>,- <<"e2ee_capable">> => true- },- VoiceStates = #{<<"conn-1">> => VoiceState},- {Key, StateWithKey} = guild_voice_e2ee:get_or_create_room_key_dm(100, #{- id => <<"sess">>,- session_pid => self(),- channels => #{},- dm_voice_states => VoiceStates- }),- {reply, #{success := true}, NewState} =- dm_voice_state:handle_dm_disconnect(<<"conn-1">>, 10, VoiceStates, StateWithKey),- {NextKey, _} = guild_voice_e2ee:get_or_create_room_key_dm(100, NewState),- ?assertNotEqual(Key, NextKey).--disconnect_voice_user_keeps_dm_e2ee_key_until_channel_empty_test() ->- VS1 = #{- <<"channel_id">> => <<"100">>,- <<"user_id">> => <<"10">>,- <<"session_id">> => <<"sess-a">>,- <<"e2ee_capable">> => true- },- VS2 = #{- <<"channel_id">> => <<"100">>,- <<"user_id">> => <<"20">>,- <<"session_id">> => <<"sess-b">>,- <<"e2ee_capable">> => true- },- VoiceStates = #{<<"conn-1">> => VS1, <<"conn-2">> => VS2},- {Key, StateWithKey} = guild_voice_e2ee:get_or_create_room_key_dm(100, #{- dm_voice_states => VoiceStates- }),- {reply, #{success := true}, NewState} =- dm_voice_state:disconnect_voice_user(10, StateWithKey),- {NextKey, _} = guild_voice_e2ee:get_or_create_room_key_dm(100, NewState),- ?assertEqual(Key, NextKey).--disconnect_removes_voice_state_count_for_null_channel_test() ->- Before = maps:get(- <<"total_voice_states">>, voice_state_counts_cache:get_local_counts(), 0- ),- ok = voice_state_counts_cache:upsert_voice_state(#{- <<"connection_id">> => <<"conn-null">>,- <<"channel_id">> => <<"100">>,- <<"region_id">> => <<"us-east">>- }),- VoiceState = #{- <<"channel_id">> => null,- <<"connection_id">> => <<"conn-null">>,- <<"user_id">> => <<"10">>,- <<"session_id">> => <<"sess">>- },- VoiceStates = #{<<"conn-null">> => VoiceState},- State = #{- id => <<"sess">>,- session_pid => self(),- channels => #{},- dm_voice_states => VoiceStates- },- {reply, #{success := true}, _NewState} =- dm_voice_state:handle_dm_disconnect(<<"conn-null">>, 10, VoiceStates, State),- Counts = voice_state_counts_cache:get_local_counts(),- ?assertEqual(Before, maps:get(<<"total_voice_states">>, Counts)).--validate_dm_viewer_stream_keys_accepts_many_same_channel_connections_test() ->- VoiceStates = validation_voice_states(100, 48),- Keys = [<<"dm:100:", (conn_id(Index))/binary>> || Index <- lists:seq(1, 48)],- ?assertEqual(- {ok, Keys}, dm_voice_state:validate_dm_viewer_stream_keys(Keys, 100, VoiceStates)- ).--validate_dm_viewer_stream_keys_rejects_guild_scope_test() ->- VoiceStates = validation_voice_states(100, 1),- ?assertEqual(- {error, voice_invalid_state},- dm_voice_state:validate_dm_viewer_stream_keys([<<"999:100:conn-1">>], 100, VoiceStates)- ).--validate_dm_viewer_stream_keys_rejects_cross_channel_connection_test() ->- VoiceStates = validation_voice_states(101, 1),- ?assertEqual(- {error, voice_invalid_state},- dm_voice_state:validate_dm_viewer_stream_keys([<<"dm:100:conn-1">>], 100, VoiceStates)- ).--validate_dm_viewer_stream_keys_rejects_missing_connection_test() ->- VoiceStates = validation_voice_states(100, 1),- ?assertEqual(- {error, voice_connection_not_found},- dm_voice_state:validate_dm_viewer_stream_keys([<<"dm:100:missing">>], 100, VoiceStates)- ).--validate_dm_viewer_stream_keys_rejects_non_binary_member_test() ->- VoiceStates = validation_voice_states(100, 1),- ?assertEqual(- {error, voice_invalid_state},- dm_voice_state:validate_dm_viewer_stream_keys([123], 100, VoiceStates)- ).--validation_voice_states(ChannelId, Count) ->- maps:from_list([- {conn_id(Index), #{- <<"connection_id">> => conn_id(Index),- <<"channel_id">> => integer_to_binary(ChannelId),- <<"user_id">> => integer_to_binary(1000 + Index)- }}- || Index <- lists:seq(1, Count)- ]).--conn_id(Index) ->- <<"conn-", (integer_to_binary(Index))/binary>>.diff --git a/fluxer_gateway/test/experiment_bucket_tests.erl b/fluxer_gateway/test/experiment_bucket_tests.erldeleted file mode 100644index 570dc36f8..000000000--- a/fluxer_gateway/test/experiment_bucket_tests.erl+++ /dev/null@@ -1,41 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(experiment_bucket_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(VECTORS_PATH, "../packages/schema/src/domains/experiment/ExperimentBucketVectors.json").--bucket_matches_shared_vectors_test() ->- Vectors = read_vectors(),- ?assertMatch([_ | _], Vectors),- lists:foreach(fun run_vector/1, Vectors).--bucket_stays_below_resolution_test() ->- Resolution = experiment_bucket:resolution(),- lists:foreach(- fun(N) ->- Bucket = experiment_bucket:bucket(integer_to_binary(N), <<"range-check">>),- ?assert(Bucket >= 0 andalso Bucket < Resolution)- end,- lists:seq(0, 500)- ).--read_vectors() ->- case file:read_file(?VECTORS_PATH) of- {ok, Contents} -> decode_vectors(Contents);- {error, Reason} -> erlang:error({bucket_vectors_unreadable, ?VECTORS_PATH, Reason})- end.--decode_vectors(Contents) ->- case json:decode(Contents) of- [_ | _] = Vectors -> Vectors;- _ -> erlang:error({bucket_vectors_empty, ?VECTORS_PATH})- end.--run_vector([Salt, Id, Expected] = Vector) when- is_binary(Salt), is_binary(Id), is_integer(Expected)-->- ?assertEqual({Vector, Expected}, {Vector, experiment_bucket:bucket(Id, Salt)});-run_vector(Vector) ->- erlang:error({bucket_vector_malformed, Vector}).diff --git a/fluxer_gateway/test/fluxer_gateway_config_tests.erl b/fluxer_gateway/test/fluxer_gateway_config_tests.erldeleted file mode 100644index 3079c3ba2..000000000--- a/fluxer_gateway/test/fluxer_gateway_config_tests.erl+++ /dev/null@@ -1,165 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(fluxer_gateway_config_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--cluster_static_peers_rejects_invalid_node_names_test() ->- LongPeer = list_to_binary(lists:duplicate(260, $a)),- RawConfig = #{- <<"services">> => #{- <<"gateway">> => #{- <<"cluster_static_peers">> => <<- "[email protected],",- "invalid [email protected],",- "missing-host@,",- LongPeer/binary,- ",[email protected]"- >>- }- }- },- ?assertError(- {invalid_cluster_static_peer, "invalid [email protected]"},- fluxer_gateway_config:build_config(RawConfig)- ).--cluster_static_peers_accepts_valid_node_names_test() ->- RawConfig = #{- <<"services">> => #{- <<"gateway">> => #{- <<"cluster_static_peers">> =>- <<"[email protected],[email protected]">>- }- }- },- Config = fluxer_gateway_config:build_config(RawConfig),- ?assertEqual(- [list_to_atom("[email protected]"), list_to_atom("[email protected]")],- maps:get(cluster_static_peers, Config)- ).--env_int_rejects_a_non_integer_value_test() ->- with_env("FLUXER_GATEWAY_HTTP_RPC_MAX_CONCURRENCY", "abc", fun() ->- ?assertError(- {invalid_integer_env, "FLUXER_GATEWAY_HTTP_RPC_MAX_CONCURRENCY", "abc"},- fluxer_gateway_config:load()- )- end).--env_int_falls_back_to_the_default_for_an_empty_value_test() ->- with_env("FLUXER_GATEWAY_HTTP_RPC_MAX_CONCURRENCY", "", fun() ->- Config = fluxer_gateway_config:load(),- ?assertEqual(512, maps:get(gateway_http_rpc_max_concurrency, Config))- end).--blank_env_values_fall_back_to_the_defaults_test() ->- with_envs(- [- {"FLUXER_GATEWAY_HTTP_RPC_MAX_CONCURRENCY", " "},- {"FLUXER_CLIENT_IP_HEADER_NAME", " "},- {"FLUXER_NATS_URL", "\t"},- {"FLUXER_GATEWAY_API_RPC_ENDPOINT", " "},- {"FLUXER_GATEWAY_LOGGER_LEVEL", " "},- {"FLUXER_GATEWAY_PUSH_ENABLED", " "}- ],- fun() ->- Config = fluxer_gateway_config:load(),- ?assertEqual(512, maps:get(gateway_http_rpc_max_concurrency, Config)),- ?assertEqual(<<"x-forwarded-for">>, maps:get(client_ip_header, Config)),- ?assertEqual("nats://nats:4222", maps:get(nats_core_url, Config)),- ?assertEqual(undefined, maps:get(api_rpc_endpoint, Config)),- ?assertEqual(info, maps:get(logger_level, Config)),- ?assertEqual(true, maps:get(push_enabled, Config))- end- ).--self_hosted_follows_the_fluxer_self_hosted_env_test() ->- with_env("FLUXER_SELF_HOSTED", "", fun() ->- ?assertEqual(false, maps:get(self_hosted, fluxer_gateway_config:load()))- end),- with_env("FLUXER_SELF_HOSTED", "true", fun() ->- ?assertEqual(true, maps:get(self_hosted, fluxer_gateway_config:load()))- end).--pinned_guild_ids_reject_non_snowflakes_test() ->- with_env("FLUXER_GATEWAY_PINNED_GUILD_IDS", "1100000000000000001,ab", fun() ->- ?assertError({invalid_pinned_guild_id, "ab"}, fluxer_gateway_config:load())- end).--env_value_reads_name_file_test() ->- with_env_file(<<"from-file\r\n">>, fun(Path) ->- with_envs(- [{"FLUXER_GATEWAY_TEST_SECRET", ""}, {"FLUXER_GATEWAY_TEST_SECRET_FILE", Path}],- fun() ->- ?assertEqual(- "from-file", fluxer_gateway_config:env_value("FLUXER_GATEWAY_TEST_SECRET")- )- end- )- end).--env_value_trims_only_one_newline_test() ->- with_env_file(<<"line1\nline2\n\n">>, fun(Path) ->- with_env("FLUXER_GATEWAY_TEST_SECRET_FILE", Path, fun() ->- ?assertEqual(- "line1\nline2\n", fluxer_gateway_config:env_value("FLUXER_GATEWAY_TEST_SECRET")- )- end)- end).--env_value_rejects_name_and_name_file_test() ->- with_envs(- [- {"FLUXER_GATEWAY_TEST_SECRET", "direct"},- {"FLUXER_GATEWAY_TEST_SECRET_FILE", "/run/secrets/x"}- ],- fun() ->- ?assertError(- {ambiguous_env, "FLUXER_GATEWAY_TEST_SECRET",- "FLUXER_GATEWAY_TEST_SECRET_FILE"},- fluxer_gateway_config:env_value("FLUXER_GATEWAY_TEST_SECRET")- )- end- ).--env_value_rejects_missing_name_file_test() ->- Path = "/nonexistent/fluxer-gateway-test-secret",- with_env("FLUXER_GATEWAY_TEST_SECRET_FILE", Path, fun() ->- ?assertError(- {unreadable_env_file, "FLUXER_GATEWAY_TEST_SECRET_FILE", Path, enoent},- fluxer_gateway_config:env_value("FLUXER_GATEWAY_TEST_SECRET")- )- end).--with_env_file(Contents, Fun) ->- Path = filename:join(- filename:basedir(user_cache, "fluxer_gateway_tests"),- integer_to_list(erlang:unique_integer([positive]))- ),- ok = filelib:ensure_dir(Path),- ok = file:write_file(Path, Contents),- try- Fun(Path)- after- file:delete(Path)- end.--with_envs([], Fun) ->- Fun();-with_envs([{Name, Value} | Rest], Fun) ->- with_env(Name, Value, fun() -> with_envs(Rest, Fun) end).--with_env(Name, Value, Fun) ->- Previous = os:getenv(Name),- os:putenv(Name, Value),- try- Fun()- after- restore_env(Name, Previous)- end.--restore_env(Name, false) ->- os:unsetenv(Name);-restore_env(Name, Previous) ->- os:putenv(Name, Previous).diff --git a/fluxer_gateway/test/fluxer_gateway_sup_tests.erl b/fluxer_gateway/test/fluxer_gateway_sup_tests.erldeleted file mode 100644index c8dbf9bf7..000000000--- a/fluxer_gateway/test/fluxer_gateway_sup_tests.erl+++ /dev/null@@ -1,175 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(fluxer_gateway_sup_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--role_enabled_allows_monolith_and_exact_role_only_test() ->- ?assert(fluxer_gateway_sup:role_enabled(sessions, all)),- ?assert(fluxer_gateway_sup:role_enabled(guilds, guilds)),- ?assertNot(fluxer_gateway_sup:role_enabled(sessions, websocket)),- ?assertNot(fluxer_gateway_sup:role_enabled(push, guilds)).--invalid_gateway_role_falls_back_to_stateless_websocket_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{gateway_role => <<"guild_session_typo">>}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(gateway_rollout_config, Ids)),- ?assert(lists:member(gateway_dispatch_relay, Ids)),- ?assertNot(lists:member(session_manager, Ids)),- ?assertNot(lists:member(guild_manager, Ids)),- ?assertNot(lists:member(presence_manager, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_returns_baseline_children_without_cluster_flag_test() ->- persistent_term:put({fluxer_gateway, runtime_config}, #{}),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assertNot(lists:member(gateway_cluster_discovery, Ids)),- ?assertNot(lists:member(gateway_cluster_membership, Ids)),- ?assertNot(lists:member(gateway_pg_scope, Ids)),- ?assertNot(lists:member(gateway_cluster_handoff, Ids)),- ?assert(lists:member(gateway_rollout_config, Ids)),- ?assert(lists:member(session_manager, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_websocket_role_excludes_stateful_children_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{gateway_role => websocket}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(gateway_rollout_config, Ids)),- ?assert(lists:member(gateway_dispatch_relay, Ids)),- ?assertNot(lists:member(presence_bus, Ids)),- ?assertNot(lists:member(session_manager, Ids)),- ?assertNot(lists:member(presence_manager, Ids)),- ?assertNot(lists:member(guild_manager, Ids)),- ?assertNot(lists:member(call_manager, Ids)),- ?assertNot(lists:member(push, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_guilds_role_includes_only_guild_state_children_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{cluster_enabled => true, gateway_role => guilds}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(presence_bus, Ids)),- ?assert(lists:member(guild_manager, Ids)),- ?assert(lists:member(guild_counts_cache, Ids)),- ?assert(lists:member(gateway_clock_offset, Ids)),- ?assert(lists:member(voice_state_counts_sync, Ids)),- ?assert(lists:member(gateway_cluster_handoff, Ids)),- ?assertNot(lists:member(session_manager, Ids)),- ?assertNot(lists:member(presence_manager, Ids)),- ?assertNot(lists:member(call_manager, Ids)),- ?assertNot(lists:member(push, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_sessions_role_includes_cluster_handoff_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{cluster_enabled => true, gateway_role => sessions}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(session_manager, Ids)),- ?assert(lists:member(session_state_transfer, Ids)),- ?assert(lists:member(gateway_cluster_handoff, Ids)),- ?assertNot(lists:member(guild_manager, Ids)),- ?assertNot(lists:member(gateway_clock_offset, Ids)),- ?assertNot(lists:member(presence_manager, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_presence_role_includes_cluster_handoff_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{cluster_enabled => true, gateway_role => presence}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(presence_manager, Ids)),- ?assert(lists:member(presence_cache, Ids)),- ?assert(lists:member(gateway_cluster_handoff, Ids)),- ?assertNot(lists:member(voice_state_counts_sync, Ids)),- ?assertNot(lists:member(session_manager, Ids)),- ?assertNot(lists:member(guild_manager, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_calls_role_includes_voice_state_counts_sync_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{cluster_enabled => true, gateway_role => calls}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(call_manager, Ids)),- ?assert(lists:member(voice_state_counts_sync, Ids)),- ?assert(lists:member(gateway_cluster_handoff, Ids)),- ?assertNot(lists:member(guild_manager, Ids)),- ?assertNot(lists:member(presence_manager, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_push_role_includes_cluster_handoff_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{cluster_enabled => true, gateway_role => push}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(push_outbox, Ids)),- ?assert(lists:member(push, Ids)),- ?assert(lists:member(gateway_cluster_handoff, Ids)),- ?assertNot(lists:member(session_manager, Ids)),- ?assertNot(lists:member(guild_manager, Ids)),- persistent_term:erase({fluxer_gateway, runtime_config}).--init_includes_cluster_children_when_flag_set_test() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{cluster_enabled => true}- ),- {ok, {_SupFlags, Children}} = fluxer_gateway_sup:init([]),- Ids = child_ids(Children),- ?assert(lists:member(gateway_cluster_discovery, Ids)),- ?assert(lists:member(gateway_cluster_membership, Ids)),- ?assert(lists:member(gateway_pg_scope, Ids)),- ?assert(lists:member(gateway_cluster_handoff, Ids)),- DiscoveryIdx = index_of(gateway_cluster_discovery, Ids),- MembershipIdx = index_of(gateway_cluster_membership, Ids),- PgScopeIdx = index_of(gateway_pg_scope, Ids),- PresenceBusIdx = index_of(presence_bus, Ids),- GuildManagerIdx = index_of(guild_manager, Ids),- HandoffAfterGuild = index_of_after(gateway_cluster_handoff, Ids, GuildManagerIdx),- ?assert(DiscoveryIdx < MembershipIdx),- ?assert(MembershipIdx < PgScopeIdx),- ?assert(PgScopeIdx < PresenceBusIdx),- ?assert(GuildManagerIdx < HandoffAfterGuild),- ?assertEqual(length(Ids), length(lists:usort(Ids))),- persistent_term:erase({fluxer_gateway, runtime_config}).--index_of(Item, List) ->- index_of(Item, List, 1).-index_of(_Item, [], _Idx) -> not_found;-index_of(Item, [Item | _], Idx) -> Idx;-index_of(Item, [_ | Rest], Idx) -> index_of(Item, Rest, Idx + 1).--index_of_after(Item, List, AfterIdx) ->- index_of_after(Item, List, AfterIdx, 1).-index_of_after(_Item, [], _AfterIdx, _Idx) ->- not_found;-index_of_after(Item, [Item | _], AfterIdx, Idx) when Idx > AfterIdx -> Idx;-index_of_after(Item, [_ | Rest], AfterIdx, Idx) ->- index_of_after(Item, Rest, AfterIdx, Idx + 1).--child_ids(Children) ->- [child_id(Child) || Child <- Children].--child_id(#{id := Id}) -> Id;-child_id({Id, _Start, _Restart, _Shutdown, _Type, _Modules}) -> Id.diff --git a/fluxer_gateway/test/gateway_cluster_discovery_tests.erl b/fluxer_gateway/test/gateway_cluster_discovery_tests.erldeleted file mode 100644index 78de2d0d9..000000000--- a/fluxer_gateway/test/gateway_cluster_discovery_tests.erl+++ /dev/null@@ -1,134 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_cluster_discovery_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(PEERS_KEY, {gateway_cluster_discovery, peers}).--ip_addrs_to_peers_filters_self_test() ->- Self = node(),- SelfStr = atom_to_list(Self),- case string:split(SelfStr, "@") of- [Base, HostStr] ->- case inet:parse_address(HostStr) of- {ok, SelfAddr} ->- Others = other_ip_addrs(),- Peers = gateway_cluster_discovery:ip_addrs_to_peers(- [SelfAddr | Others], Base- ),- ?assertNot(lists:member(Self, Peers)),- ?assertEqual(2, length(Peers));- _ ->- Peers = gateway_cluster_discovery:ip_addrs_to_peers(- other_ip_addrs(), Base- ),- ?assertEqual(2, length(Peers))- end;- _ ->- ok- end.--ip_addrs_to_peers_rejects_invalid_node_basename_test() ->- ?assertEqual(- [],- gateway_cluster_discovery:ip_addrs_to_peers([{10, 0, 0, 1}], "bad node")- ).--poll_with_undefined_dns_returns_empty_test() ->- persistent_term:erase(?PEERS_KEY),- State = base_state(#{dns_name => undefined}),- {Result, _} = gateway_cluster_discovery:poll(State),- ?assertEqual([], Result).--poll_with_static_peers_uses_static_peers_test() ->- persistent_term:erase(?PEERS_KEY),- StaticPeers = [list_to_atom("[email protected]"), node(), list_to_atom("[email protected]")],- Resolver = fun(_Name) -> error(static_peer_resolver_called) end,- State = base_state(#{- static_peers => StaticPeers,- resolver => Resolver,- subscribers => []- }),- {Result, _} = gateway_cluster_discovery:poll(State),- ?assertEqual(- [list_to_atom("[email protected]"), list_to_atom("[email protected]")],- Result- ),- ?assertEqual(Result, persistent_term:get(?PEERS_KEY)),- persistent_term:erase(?PEERS_KEY).--other_ip_addrs() ->- [{10, 0, 0, 2}, {10, 0, 0, 3}].--poll_publishes_peers_and_notifies_subscribers_test() ->- persistent_term:erase(?PEERS_KEY),- Self = self(),- Resolver = fun("svc.test") -> {ok, [{10, 0, 0, 1}, {10, 0, 0, 2}]} end,- State0 = base_state(#{- dns_name => "svc.test",- resolver => Resolver,- subscribers => [{Self, erlang:monitor(process, Self)}]- }),- {Peers, State1} = gateway_cluster_discovery:poll(State0),- ?assertEqual(- [- list_to_atom("[email protected]"),- list_to_atom("[email protected]")- ],- Peers- ),- ?assertEqual(Peers, persistent_term:get(?PEERS_KEY)),- receive- {cluster_peers_changed, P} -> ?assertEqual(Peers, P)- after 100 -> ?assert(false)- end,- {Peers2, _State2} = gateway_cluster_discovery:poll(State1),- ?assertEqual(Peers, Peers2),- receive- {cluster_peers_changed, _} -> ?assert(false)- after 50 -> ok- end,- persistent_term:erase(?PEERS_KEY).--poll_with_resolver_error_keeps_old_peers_test() ->- persistent_term:erase(?PEERS_KEY),- gateway_cluster_metrics:reset_for_tests(),- OldPeers = [list_to_atom("[email protected]")],- Resolver = fun("svc.test") -> {error, nxdomain} end,- State = base_state(#{- dns_name => "svc.test",- resolver => Resolver,- peers => OldPeers- }),- {Result, _} = gateway_cluster_discovery:poll(State),- ?assertEqual(OldPeers, Result),- Snapshot = gateway_cluster_metrics:snapshot(),- ?assertEqual(1, maps:get(<<"gateway_cluster_discovery_resolve_failures_total">>, Snapshot)),- persistent_term:erase(?PEERS_KEY).--subscriber_messages_include_initial_state_test() ->- persistent_term:erase(?PEERS_KEY),- Self = self(),- InitialPeers = [list_to_atom("[email protected]")],- State = base_state(#{peers => InitialPeers}),- NewState = gateway_cluster_discovery:add_subscriber(Self, State),- receive- {cluster_peers_changed, P} -> ?assertEqual(InitialPeers, P)- after 100 -> ?assert(false)- end,- ?assertMatch(#{subscribers := [{Self, _}]}, NewState),- persistent_term:erase(?PEERS_KEY).--base_state(Overrides) ->- Defaults = #{- dns_name => "svc.test",- node_basename => "n",- poll_interval_ms => 5000,- resolver => fun(_) -> {ok, []} end,- static_peers => [],- peers => [],- subscribers => [],- timer => undefined- },- maps:merge(Defaults, Overrides).diff --git a/fluxer_gateway/test/gateway_cluster_membership_tests.erl b/fluxer_gateway/test/gateway_cluster_membership_tests.erldeleted file mode 100644index d118301c8..000000000--- a/fluxer_gateway/test/gateway_cluster_membership_tests.erl+++ /dev/null@@ -1,390 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_cluster_membership_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(MEMBERS_KEY, {gateway_cluster_membership, members}).---define(ROLE_MEMBERS_KEY, {gateway_cluster_membership, members_by_role}).--define(NODE_POD_NAMES_KEY, {gateway_cluster_membership, node_pod_names}).--init_records_self_under_current_role_test() ->- with_clean_cluster_terms(fun() ->- persistent_term:put(- {fluxer_gateway, runtime_config},- #{gateway_role => guilds}- ),- {ok, State} = gateway_cluster_membership:init(#{auto_subscribe => false}),- RoleMembers = maps:get(members_by_role, State),- ?assertEqual([node()], maps:get(guilds, RoleMembers)),- ?assertEqual(RoleMembers, persistent_term:get(?ROLE_MEMBERS_KEY)),- gateway_cluster_membership:terminate(normal, State)- end).--apply_discovered_adds_only_connectable_peers_test() ->- with_clean_cluster_terms(fun() ->- Connect = fun connect_good_host/1,- State0 = base_state(#{connect_fun => Connect}),- State1 = gateway_cluster_membership:apply_discovered(['good@host', 'bad@host'], State0),- ?assertEqual(- lists:usort([node(), 'good@host']),- maps:get(members, State1)- )- end).--connect_good_host('good@host') ->- true;-connect_good_host(_) ->- false.--apply_discovered_strips_self_test() ->- with_clean_cluster_terms(fun() ->- State0 = base_state(#{connect_fun => fun(_) -> true end}),- State1 = gateway_cluster_membership:apply_discovered([node()], State0),- ?assertEqual([node()], maps:get(members, State1))- end).--nodedown_removes_member_but_keeps_self_test() ->- with_clean_cluster_terms(fun() ->- State0 = base_state(#{- connect_fun => fun(_) -> true end- }),- State1 = gateway_cluster_membership:apply_discovered(['peer@a', 'peer@b'], State0),- ?assert(lists:member('peer@a', maps:get(members, State1))),- State2 = gateway_cluster_membership:maybe_remove_member('peer@a', State1),- ?assertNot(lists:member('peer@a', maps:get(members, State2))),- ?assert(lists:member(node(), maps:get(members, State2))),- State3 = gateway_cluster_membership:maybe_remove_member(node(), State2),- ?assert(lists:member(node(), maps:get(members, State3)))- end).--nodeup_for_undiscovered_peer_is_ignored_test() ->- with_clean_cluster_terms(fun() ->- State0 = base_state(#{- role_fun => fun(_) -> unknown end- }),- State1 = gateway_cluster_membership:maybe_add_member('stranger@host', State0),- ?assertNot(lists:member('stranger@host', maps:get(members, State1)))- end).--nodeup_for_discovered_peer_adds_it_test() ->- with_clean_cluster_terms(fun() ->- State0 = (base_state(#{}))#{discovered := ['peer@a']},- State1 = gateway_cluster_membership:maybe_add_member('peer@a', State0),- ?assert(lists:member('peer@a', maps:get(members, State1)))- end).--subscriber_receives_initial_state_then_transitions_test() ->- with_clean_cluster_terms(fun() ->- Self = self(),- State0 = base_state(#{- connect_fun => fun(_) -> true end,- members => [node()]- }),- State1 = gateway_cluster_membership:add_subscriber(Self, State0),- receive- {cluster_membership_changed, M} -> ?assertEqual([node()], M)- after 100 -> ?assert(false)- end,- State2 = gateway_cluster_membership:apply_discovered(['peer@x'], State1),- receive- {cluster_membership_changed, M2} ->- ?assert(lists:member('peer@x', M2)),- ?assert(lists:member(node(), M2))- after 100 -> ?assert(false)- end,- _State3 = gateway_cluster_membership:apply_discovered(['peer@x'], State2),- receive- {cluster_membership_changed, _} -> ?assert(false)- after 50 -> ok- end- end).--reconcile_removes_stale_members_test() ->- with_clean_cluster_terms(fun() ->- StaleNode = 'stale@host',- LiveNode = 'live@host',- State0 = base_state(#{- members => [node(), StaleNode, LiveNode],- connected_nodes_fun => fun() -> [LiveNode] end- }),- State1 = gateway_cluster_membership:reconcile_against_connected_nodes(State0),- ?assertNot(lists:member(StaleNode, maps:get(members, State1))),- ?assert(lists:member(LiveNode, maps:get(members, State1))),- ?assert(lists:member(node(), maps:get(members, State1)))- end).--reconcile_ignores_connected_non_members_missing_from_discovery_test() ->- with_clean_cluster_terms(fun() ->- LiveNode = 'live@host',- State0 = base_state(#{- members => [node()],- connected_nodes_fun => fun() -> [LiveNode] end,- role_fun => fun- (Node) when Node =:= LiveNode -> guilds;- (_) -> websocket- end- }),- State1 = gateway_cluster_membership:reconcile_against_connected_nodes(State0),- ?assertNot(lists:member(LiveNode, maps:get(members, State1))),- ?assertEqual(undefined, maps:get(guilds, maps:get(members_by_role, State1), undefined))- end).--reconcile_noop_when_all_connected_test() ->- with_clean_cluster_terms(fun() ->- LiveNode = 'live@host',- State0 = base_state(#{- members => [node(), LiveNode],- connected_nodes_fun => fun() -> [LiveNode] end- }),- State1 = gateway_cluster_membership:reconcile_against_connected_nodes(State0),- ?assertEqual(lists:usort(maps:get(members, State0)), maps:get(members, State1))- end).--reconcile_keeps_previous_role_when_lookup_temporarily_unknown_test() ->- with_clean_cluster_terms(fun() ->- LiveNode = 'live@host',- State0 = base_state(#{- members => [node(), LiveNode],- members_by_role => #{sessions => [LiveNode], websocket => [node()]},- connected_nodes_fun => fun() -> [LiveNode] end,- role_fun => fun- (Node) when Node =:= LiveNode -> unknown;- (_) -> websocket- end- }),- State1 = gateway_cluster_membership:reconcile_against_connected_nodes(State0),- ?assertEqual([LiveNode], maps:get(sessions, maps:get(members_by_role, State1)))- end).--apply_discovered_retains_connected_existing_member_missing_from_dns_test() ->- with_clean_cluster_terms(fun() ->- ExistingNode = '[email protected]',- NewNode = '[email protected]',- State0 = membership_state(#{- members => [node(), ExistingNode],- discovered => [ExistingNode],- connected_nodes => [ExistingNode],- roles => #{node() => websocket, ExistingNode => sessions, NewNode => guilds}- }),- State1 = gateway_cluster_membership:apply_discovered([NewNode], State0),- ?assertEqual(lists:usort([node(), ExistingNode, NewNode]), maps:get(members, State1)),- RoleMembers = maps:get(members_by_role, State1),- ?assertEqual([ExistingNode], maps:get(sessions, RoleMembers)),- ?assertEqual([NewNode], maps:get(guilds, RoleMembers))- end).--apply_discovered_ignores_unrelated_connected_controller_test() ->- with_clean_cluster_terms(fun() ->- ControllerNode = '[email protected]',- DiscoveredNode = '[email protected]',- State0 = membership_state(#{- members => [node()],- discovered => [],- connected_nodes => [ControllerNode],- roles => #{- node() => websocket,- ControllerNode => all,- DiscoveredNode => sessions- }- }),- State1 = gateway_cluster_membership:apply_discovered([DiscoveredNode], State0),- ?assertEqual(lists:usort([node(), DiscoveredNode]), maps:get(members, State1)),- ?assertNot(lists:member(ControllerNode, maps:get(members, State1))),- RoleMembers = maps:get(members_by_role, State1),- ?assertEqual([DiscoveredNode], maps:get(sessions, RoleMembers)),- ?assertEqual(undefined, maps:get(all, RoleMembers, undefined))- end).--maybe_add_member_rejects_valid_role_node_not_seen_in_discovery_test() ->- with_clean_cluster_terms(fun() ->- RemoteNode = '[email protected]',- State0 = membership_state(#{- members => [node()],- discovered => [],- connected_nodes => [RemoteNode],- roles => #{node() => websocket, RemoteNode => presence}- }),- State1 = gateway_cluster_membership:maybe_add_member(RemoteNode, State0),- ?assertEqual([node()], maps:get(members, State1)),- ?assertEqual(- undefined,- maps:get(presence, maps:get(members_by_role, State1), undefined)- )- end).--maybe_add_member_rejects_unknown_role_node_not_seen_in_dns_test() ->- with_clean_cluster_terms(fun() ->- RemoteNode = '[email protected]',- State0 = membership_state(#{- members => [node()],- discovered => [],- connected_nodes => [RemoteNode],- roles => #{node() => websocket, RemoteNode => unknown}- }),- State1 = gateway_cluster_membership:maybe_add_member(RemoteNode, State0),- ?assertEqual([node()], maps:get(members, State1))- end).--update_members_refreshes_role_for_existing_member_test() ->- with_clean_cluster_terms(fun() ->- RemoteNode = '[email protected]',- RoleKey = {gateway_cluster_membership_test_role, RemoteNode},- persistent_term:put(RoleKey, unknown),- RoleFun = fun- (Node) when Node =:= node() -> websocket;- (Node) -> persistent_term:get({gateway_cluster_membership_test_role, Node}, unknown)- end,- State0 = base_state(#{- members => [node(), RemoteNode],- members_by_role => #{websocket => [node()]},- discovered => [RemoteNode],- connect_fun => fun(_Node) -> true end,- connected_nodes_fun => fun() -> [RemoteNode] end,- role_fun => RoleFun- }),- ?assertEqual(- undefined, maps:get(sessions, maps:get(members_by_role, State0), undefined)- ),- persistent_term:put(RoleKey, sessions),- State1 = gateway_cluster_membership:update_members([node(), RemoteNode], State0),- ?assertEqual([RemoteNode], maps:get(sessions, maps:get(members_by_role, State1))),- persistent_term:erase(RoleKey)- end).--update_members_role_lookups_run_concurrently_test() ->- with_clean_cluster_terms(fun() ->- Nodes = [- '[email protected]',- '[email protected]',- '[email protected]',- '[email protected]',- ],- State0 = base_state(#{- members => [],- role_fun => fun(_Node) ->- timer:sleep(100),- sessions- end- }),- Start = erlang:monotonic_time(millisecond),- State1 = gateway_cluster_membership:update_members(Nodes, State0),- ElapsedMs = erlang:monotonic_time(millisecond) - Start,- ?assert(ElapsedMs < 300),- ?assertEqual(lists:usort(Nodes), maps:get(sessions, maps:get(members_by_role, State1)))- end).--member_nodedown_starts_presence_grace_and_nodeup_cancels_it_test() ->- with_clean_cluster_terms(fun() ->- with_presence_cache(fun(CachePid) ->- Peer = 'peer@a',- State0 = (base_state(#{members => lists:usort([node(), Peer])}))#{- discovered => [Peer]- },- {noreply, State1} = gateway_cluster_membership:handle_info(- {nodedown, Peer}, State0- ),- ?assertNot(lists:member(Peer, maps:get(members, State1))),- ?assert(maps:is_key(Peer, pending_nodedown_cleanups(CachePid))),- {noreply, State2} = gateway_cluster_membership:handle_info({nodeup, Peer}, State1),- ?assert(lists:member(Peer, maps:get(members, State2))),- ?assertEqual(#{}, pending_nodedown_cleanups(CachePid))- end)- end).--non_member_nodedown_does_not_start_presence_grace_test() ->- with_clean_cluster_terms(fun() ->- with_presence_cache(fun(CachePid) ->- State0 = base_state(#{}),- {noreply, _State1} = gateway_cluster_membership:handle_info(- {nodedown, 'remsh@host'}, State0- ),- ?assertEqual(#{}, pending_nodedown_cleanups(CachePid))- end)- end).--with_presence_cache(Fun) ->- {ok, Pid} =- case whereis(presence_cache) of- undefined -> presence_cache:start_link();- Existing -> {ok, Existing}- end,- try- Fun(Pid)- after- unlink(Pid),- gen_server:stop(Pid)- end.--pending_nodedown_cleanups(CachePid) ->- maps:get(pending_nodedown_cleanups, sys:get_state(CachePid)).--base_state(Overrides) ->- Defaults = #{- members => [node()],- members_by_role => #{all => [node()]},- discovered => [],- connect_fun => fun(_) -> false end,- connected_nodes_fun => fun() -> [] end,- role_fun => fun(_) -> all end,- subscribers => [],- node_reconcile_timer => undefined- },- maps:merge(Defaults, Overrides).--membership_state(Options) ->- Members = maps:get(members, Options, [node()]),- ConnectedNodes = maps:get(connected_nodes, Options, []),- Roles = maps:get(roles, Options, #{node() => websocket}),- RoleFun = fun(Node) -> maps:get(Node, Roles, unknown) end,- base_state(#{- members => Members,- members_by_role => test_role_members(Members, RoleFun),- discovered => maps:get(discovered, Options, []),- connect_fun => fun(_Node) -> true end,- connected_nodes_fun => fun() -> ConnectedNodes end,- role_fun => RoleFun- }).--test_role_members(Members, RoleFun) ->- lists:foldl(- fun(Node, Acc) ->- Role = RoleFun(Node),- Nodes = maps:get(Role, Acc, []),- Acc#{Role => lists:usort([Node | Nodes])}- end,- #{},- Members- ).--with_clean_cluster_terms(Fun) ->- with_restored_terms(- [- ?MEMBERS_KEY,- ?ROLE_MEMBERS_KEY,- ?NODE_POD_NAMES_KEY,- {fluxer_gateway, runtime_config}- ],- fun() ->- persistent_term:erase(?MEMBERS_KEY),- persistent_term:erase(?ROLE_MEMBERS_KEY),- persistent_term:erase(?NODE_POD_NAMES_KEY),- persistent_term:erase({fluxer_gateway, runtime_config}),- Fun()- end- ).--with_restored_terms(Keys, Fun) ->- Saved = [{Key, persistent_term:get(Key, undefined)} || Key <- Keys],- try- Fun()- after- lists:foreach(fun restore_persistent_term/1, Saved)- end.--restore_persistent_term({Key, undefined}) ->- persistent_term:erase(Key);-restore_persistent_term({Key, Value}) ->- persistent_term:put(Key, Value).diff --git a/fluxer_gateway/test/gateway_dispatch_relay_bound_tests.erl b/fluxer_gateway/test/gateway_dispatch_relay_bound_tests.erldeleted file mode 100644index cf984ddf9..000000000--- a/fluxer_gateway/test/gateway_dispatch_relay_bound_tests.erl+++ /dev/null@@ -1,375 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_dispatch_relay_bound_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").---define(STATE_KEY, {gateway_dispatch_relay, state}).--define(CONFIG_KEY, gateway_rollout_config).--define(BOUND, 8).--define(FILL, 6).--define(EVENT_COUNT, 6).--define(PROBE_BOUND, 1000).--define(PROBE_EVENT_COUNT, 200).--define(PROBE_BUDGET, 2).--define(SHARD_COUNT, 2).--define(FAST_SHARD_TIMEOUT_MS, 1500).--define(PRODUCER_COUNTS, [1, 10, 64]).--define(PEAK_SAMPLES, 100).--define(PEAK_INTERVAL_MS, 5).--dispatch_is_bounded_and_stays_ordered_test_() ->- {timeout, 30, fun dispatch_is_bounded_and_stays_ordered/0}.--dispatch_many_is_bounded_and_stays_ordered_test_() ->- {timeout, 30, fun dispatch_many_is_bounded_and_stays_ordered/0}.--max_queue_config_governs_the_bound_test_() ->- {timeout, 30, fun max_queue_config_governs_the_bound/0}.--max_queue_zero_keeps_the_bound_test_() ->- {timeout, 60, fun max_queue_zero_keeps_the_bound/0}.--max_queue_is_capped_by_the_watchdog_kill_threshold_test_() ->- {timeout, 30, fun max_queue_is_capped_by_the_watchdog_kill_threshold/0}.--dispatch_does_not_probe_the_worker_per_event_test_() ->- {timeout, 30, fun dispatch_does_not_probe_the_worker_per_event/0}.--saturated_shard_does_not_delay_other_shards_test_() ->- {timeout, 60, fun saturated_shard_does_not_delay_other_shards/0}.--concurrent_producers_share_the_worker_bound_test_() ->- {timeout, 120, fun concurrent_producers_share_the_worker_bound/0}.--restarted_worker_starts_from_an_empty_bound_test_() ->- {timeout, 30, fun restarted_worker_starts_from_an_empty_bound/0}.--dispatch_is_bounded_and_stays_ordered() ->- assert_bounded_and_ordered(fun send_dispatch/2).--dispatch_many_is_bounded_and_stays_ordered() ->- assert_bounded_and_ordered(fun send_dispatch_many/2).--send_dispatch(SessionPid, N) ->- gateway_dispatch_relay:dispatch(SessionPid, relay_bound_event, #{<<"n">> => N}).--send_dispatch_many(SessionPid, N) ->- gateway_dispatch_relay:dispatch_many([SessionPid], relay_bound_event, #{<<"n">> => N}).--max_queue_config_governs_the_bound() ->- ?assertEqual(blocked, producer_status_with_bound(?BOUND, ?BOUND)),- ?assertEqual(finished, producer_status_with_bound(?BOUND * 8, ?BOUND)).--max_queue_zero_keeps_the_bound() ->- Ceiling = process_health_watchdog:kill_threshold(),- with_max_queue(0, fun() ->- ?assertEqual(Ceiling, gateway_dispatch_relay_batch:max_queue())- end),- ?assertEqual(blocked, producer_status_with_bound(0, Ceiling)).--max_queue_is_capped_by_the_watchdog_kill_threshold() ->- Ceiling = process_health_watchdog:kill_threshold(),- with_max_queue(Ceiling * 4, fun() ->- ?assertEqual(Ceiling, gateway_dispatch_relay_batch:max_queue())- end),- with_max_queue(Ceiling - 1, fun() ->- ?assertEqual(Ceiling - 1, gateway_dispatch_relay_batch:max_queue())- end).--dispatch_does_not_probe_the_worker_per_event() ->- with_max_queue(?PROBE_BOUND, fun() ->- with_worker(fun(Worker) ->- Ref = make_ref(),- Session = spawn_session(self(), Ref),- Producer = spawn_gated_producer(Session, ?PROBE_EVENT_COUNT),- Probes = count_probes(Worker, Producer),- ?assertEqual(- lists:seq(1, ?PROBE_EVENT_COUNT),- collect_observed(Ref, ?PROBE_EVENT_COUNT, [])- ),- Session ! stop,- ?assert(Probes =< ?PROBE_BUDGET)- end)- end).--saturated_shard_does_not_delay_other_shards() ->- with_max_queue(?BOUND, fun() ->- with_workers(?SHARD_COUNT, fun([Blocked, _Free]) ->- SlowRef = make_ref(),- FastRef = make_ref(),- Slow = session_for_shard(1, self(), SlowRef),- Fast = session_for_shard(2, self(), FastRef),- ok = sys:suspend(Blocked),- fill_queue(Blocked, ?BOUND),- Producer = spawn_fanout_producer([Slow, Fast]),- ?assertEqual([1], collect_within(FastRef, ?FAST_SHARD_TIMEOUT_MS)),- ?assertEqual(blocked, producer_status(Producer, 100)),- ok = sys:resume(Blocked),- ?assertEqual([1], collect_observed(SlowRef, 1, [])),- ?assertEqual(finished, producer_status(Producer, 20000)),- Slow ! stop,- Fast ! stop- end)- end).--restarted_worker_starts_from_an_empty_bound() ->- with_max_queue(?BOUND, fun() ->- Saturated = saturate_worker(),- Ref = make_ref(),- Session = spawn_session(self(), Ref),- with_worker(fun(_Restarted) ->- Producer = spawn_producer(fun send_dispatch/2, Session),- ?assertEqual(finished, producer_status(Producer, 5000)),- ?assertEqual(lists:seq(1, ?EVENT_COUNT), collect_observed(Ref, ?EVENT_COUNT, []))- end),- Session ! stop,- stop_worker(Saturated)- end).--saturate_worker() ->- Worker = gateway_dispatch_relay_batch:start_worker(0),- Session = spawn_session(self(), make_ref()),- with_relay_workers([Worker], fun() ->- ok = sys:suspend(Worker),- fill_queue(Worker, ?BOUND),- Producer = spawn_producer(fun send_dispatch/2, Session),- ?assertEqual(blocked, producer_status(Producer, 500))- end),- Session ! stop,- Worker.--concurrent_producers_share_the_worker_bound() ->- lists:foreach(fun assert_peak_within_bound/1, ?PRODUCER_COUNTS).--assert_peak_within_bound(Producers) ->- Verdict = bound_verdict(peak_queue_len(Producers)),- ?assertEqual({Producers, within_bound}, {Producers, Verdict}).--bound_verdict(Peak) when Peak =< ?BOUND + 1 -> within_bound;-bound_verdict(Peak) -> {over_bound, Peak}.--peak_queue_len(Producers) ->- with_max_queue(?BOUND, fun() ->- with_worker(fun(Worker) -> concurrent_peak(Worker, Producers) end)- end).--concurrent_peak(Worker, Producers) ->- Ref = make_ref(),- Session = spawn_session(self(), Ref),- ok = sys:suspend(Worker),- Pids = [spawn_producer(fun send_dispatch/2, Session) || _ <- lists:seq(1, Producers)],- Peak = sample_peak(Worker, ?PEAK_SAMPLES, 0),- ok = sys:resume(Worker),- lists:foreach(fun(Pid) -> ok = await_producer(Pid, blocked) end, Pids),- _ = collect_observed(Ref, Producers * ?EVENT_COUNT, []),- Session ! stop,- Peak.--sample_peak(_Worker, 0, Peak) ->- Peak;-sample_peak(Worker, Remaining, Peak) ->- ok = gateway_retry_timer:wait(?PEAK_INTERVAL_MS),- Sampled = gateway_dispatch_relay_batch:message_queue_len(Worker),- sample_peak(Worker, Remaining - 1, max(Peak, Sampled)).--assert_bounded_and_ordered(SendFun) ->- {Status, QueueLen, Observed} = run_over_bound(SendFun),- ?assertEqual(lists:seq(1, ?EVENT_COUNT), Observed),- ?assertEqual(blocked, Status),- ?assert(QueueLen =< ?BOUND + 1).--run_over_bound(SendFun) ->- with_max_queue(?BOUND, fun() ->- with_worker(fun(Worker) ->- Ref = make_ref(),- Session = spawn_session(self(), Ref),- ok = sys:suspend(Worker),- fill_queue(Worker, ?FILL),- Producer = spawn_producer(SendFun, Session),- Status = producer_status(Producer, 500),- QueueLen = gateway_dispatch_relay_batch:message_queue_len(Worker),- ok = sys:resume(Worker),- ok = await_producer(Producer, Status),- Observed = collect_observed(Ref, ?EVENT_COUNT, []),- Session ! stop,- {Status, QueueLen, Observed}- end)- end).--producer_status_with_bound(MaxQueue, Fill) ->- with_max_queue(MaxQueue, fun() ->- with_worker(fun(Worker) ->- Ref = make_ref(),- Session = spawn_session(self(), Ref),- ok = sys:suspend(Worker),- fill_queue(Worker, Fill),- Producer = spawn_producer(fun send_dispatch/2, Session),- Status = producer_status(Producer, 500),- ok = sys:resume(Worker),- ok = await_producer(Producer, Status),- ?assertEqual(lists:seq(1, ?EVENT_COUNT), collect_observed(Ref, ?EVENT_COUNT, [])),- Session ! stop,- Status- end)- end).--spawn_producer(SendFun, Session) ->- Parent = self(),- spawn_link(fun() ->- lists:foreach(fun(N) -> ok = SendFun(Session, N) end, lists:seq(1, ?EVENT_COUNT)),- Parent ! {producer_finished, self()}- end).--spawn_gated_producer(Session, Count) ->- Parent = self(),- spawn_link(fun() ->- receive- start -> ok- end,- lists:foreach(fun(N) -> ok = send_dispatch(Session, N) end, lists:seq(1, Count)),- Parent ! {producer_finished, self()}- end).--spawn_fanout_producer(Sessions) ->- Parent = self(),- spawn_link(fun() ->- ok = gateway_dispatch_relay:dispatch_many(Sessions, relay_bound_event, #{<<"n">> => 1}),- Parent ! {producer_finished, self()}- end).--session_for_shard(Index, Parent, Ref) ->- Session = spawn_session(Parent, Ref),- case erlang:phash2(Session, ?SHARD_COUNT) + 1 of- Index -> Session;- _ -> session_for_shard(Index, Parent, Ref)- end.--count_probes(Worker, Producer) ->- 1 = erlang:trace(Producer, true, [call]),- _ = erlang:trace_pattern({erlang, process_info, 2}, true, [global]),- Producer ! start,- try- drain_probes(Worker, Producer, 0)- after- _ = erlang:trace_pattern({erlang, process_info, 2}, false, [global]),- untrace(Producer)- end.--untrace(Producer) ->- try erlang:trace(Producer, false, [call]) of- _ -> ok- catch- error:badarg -> ok- end.--drain_probes(Worker, Producer, Count) ->- receive- {trace, Producer, call, {erlang, process_info, [Worker, message_queue_len]}} ->- drain_probes(Worker, Producer, Count + 1);- {producer_finished, Producer} ->- Count- after 20000 ->- ?assert(false, {probe_count_timeout, Count})- end.--await_producer(_Producer, finished) ->- ok;-await_producer(Producer, blocked) ->- ?assertEqual(finished, producer_status(Producer, 20000)),- ok.--producer_status(Producer, Timeout) ->- receive- {producer_finished, Producer} -> finished- after Timeout ->- blocked- end.--fill_queue(_Worker, 0) ->- ok;-fill_queue(Worker, Remaining) ->- Worker ! relay_bound_filler,- fill_queue(Worker, Remaining - 1).--spawn_session(Parent, Ref) ->- spawn_link(fun() -> session_loop(Parent, Ref) end).--session_loop(Parent, Ref) ->- receive- {'$gen_cast', {dispatch, relay_bound_event, #{<<"n">> := N}}} ->- Parent ! {relay_bound_received, Ref, N},- session_loop(Parent, Ref);- stop ->- ok- after 30000 ->- ok- end.--collect_within(Ref, Timeout) ->- receive- {relay_bound_received, Ref, N} -> [N]- after Timeout ->- []- end.--collect_observed(_Ref, 0, Acc) ->- lists:reverse(Acc);-collect_observed(Ref, Remaining, Acc) ->- receive- {relay_bound_received, Ref, N} -> collect_observed(Ref, Remaining - 1, [N | Acc])- after 10000 ->- ?assert(false, {relay_bound_timeout, Remaining, lists:reverse(Acc)})- end.--with_worker(Fun) ->- with_workers(1, fun([Worker]) -> Fun(Worker) end).--with_workers(Count, Fun) ->- Workers = [- gateway_dispatch_relay_batch:start_worker(Index)- || Index <- lists:seq(0, Count - 1)- ],- try- with_relay_workers(Workers, fun() -> Fun(Workers) end)- after- lists:foreach(fun stop_worker/1, Workers)- end.--with_relay_workers(Workers, Fun) ->- Previous = persistent_term:get(?STATE_KEY, undefined),- persistent_term:put(?STATE_KEY, #{- workers => list_to_tuple(Workers),- shard_count => length(Workers)- }),- try- Fun()- after- restore_term(?STATE_KEY, Previous)- end.--with_max_queue(MaxQueue, Fun) ->- Previous = persistent_term:get(?CONFIG_KEY, undefined),- Config = gateway_rollout_config:get(),- persistent_term:put(?CONFIG_KEY, Config#{- <<"gateway_dispatch_relay_max_queue">> => MaxQueue- }),- try- Fun()- after- restore_term(?CONFIG_KEY, Previous)- end.--restore_term(Key, undefined) ->- _ = persistent_term:erase(Key),- ok;-restore_term(Key, Previous) ->- persistent_term:put(Key, Previous).--stop_worker(Pid) ->- try gen_server:stop(Pid, normal, 5000) of- _ -> ok- catch- exit:_ -> ok- end.diff --git a/fluxer_gateway/test/gateway_dispatch_relay_stress_tests.erl b/fluxer_gateway/test/gateway_dispatch_relay_stress_tests.erldeleted file mode 100644index dac43cbf6..000000000--- a/fluxer_gateway/test/gateway_dispatch_relay_stress_tests.erl+++ /dev/null@@ -1,184 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_dispatch_relay_stress_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").---define(STATE_KEY, {gateway_dispatch_relay, state}).--define(RELAY_SESSION_COUNT, 2048).--dispatch_many_direct_fallback_delivers_once_to_many_sessions_test_() ->- {timeout, 30, fun dispatch_many_direct_fallback_delivers_once_to_many_sessions/0}.--dispatch_many_worker_shards_deliver_once_to_many_sessions_test_() ->- {timeout, 30, fun dispatch_many_worker_shards_deliver_once_to_many_sessions/0}.--dispatch_many_backpressured_worker_still_relays_delivery_test_() ->- {timeout, 30, fun dispatch_many_backpressured_worker_still_relays_delivery/0}.--dispatch_many_direct_fallback_delivers_once_to_many_sessions() ->- with_relay_state_cleared(fun() ->- {Receivers, Ref} = start_receivers(?RELAY_SESSION_COUNT),- try- Payload = #{<<"stress">> => <<"direct">>},- ok = gateway_dispatch_relay:dispatch_many(Receivers, relay_stress_event, Payload),- assert_received_once(Receivers, Ref, relay_stress_event, Payload)- after- stop_receivers(Receivers)- end- end).--dispatch_many_worker_shards_deliver_once_to_many_sessions() ->- Workers = gateway_dispatch_relay_batch:start_workers(8),- with_relay_workers(Workers, fun() ->- {Receivers, Ref} = start_receivers(?RELAY_SESSION_COUNT),- try- Payload = #{<<"stress">> => <<"workers">>},- ok = gateway_dispatch_relay:dispatch_many(Receivers, relay_stress_event, Payload),- assert_received_once(Receivers, Ref, relay_stress_event, Payload),- assert_worker_queues_drained(Workers)- after- stop_receivers(Receivers)- end- end),- stop_workers(Workers).--dispatch_many_backpressured_worker_still_relays_delivery() ->- Worker = gateway_dispatch_relay_batch:start_worker(0),- with_relay_workers([Worker], fun() ->- ok = sys:suspend(Worker),- backpressure_worker(Worker, 64),- {Receivers, Ref} = start_receivers(512),- try- Payload = #{<<"stress">> => <<"backpressure">>},- ok = gateway_dispatch_relay_batch:relay_or_direct_many(- Receivers, relay_stress_event, Payload- ),- ?assert(gateway_dispatch_relay_batch:message_queue_len(Worker) >= 64),- ok = sys:resume(Worker),- assert_received_once(Receivers, Ref, relay_stress_event, Payload),- assert_worker_queues_drained([Worker])- after- stop_receivers(Receivers)- end- end),- stop_worker(Worker).--with_relay_state_cleared(Fun) ->- Previous = persistent_term:get(?STATE_KEY, undefined),- _ = persistent_term:erase(?STATE_KEY),- try- Fun()- after- restore_relay_state(Previous)- end.--with_relay_workers(Workers, Fun) ->- Previous = persistent_term:get(?STATE_KEY, undefined),- persistent_term:put(?STATE_KEY, #{- workers => list_to_tuple(Workers),- shard_count => length(Workers)- }),- try- Fun()- after- restore_relay_state(Previous)- end.--restore_relay_state(undefined) ->- _ = persistent_term:erase(?STATE_KEY),- ok;-restore_relay_state(Previous) ->- persistent_term:put(?STATE_KEY, Previous),- ok.--start_receivers(Count) ->- Ref = make_ref(),- Parent = self(),- Receivers = [- spawn_link(fun() -> receiver_loop(Parent, Ref) end)- || _ <- lists:seq(1, Count)- ],- {Receivers, Ref}.--receiver_loop(Parent, Ref) ->- receive- {'$gen_cast', {dispatch, Event, Payload}} ->- Parent ! {relay_stress_received, Ref, self(), Event, Payload},- receiver_loop(Parent, Ref);- stop ->- ok- after 30000 ->- ok- end.--stop_receivers(Receivers) ->- lists:foreach(fun(Pid) -> Pid ! stop end, Receivers).--stop_workers(Workers) ->- lists:foreach(fun stop_worker/1, Workers).--stop_worker(Pid) ->- try gen_server:stop(Pid, normal, 5000) of- _ -> ok- catch- exit:_ -> ok- end.--backpressure_worker(Worker, MessageCount) ->- lists:foreach(fun(I) -> Worker ! {queued, I} end, lists:seq(1, MessageCount)).--assert_received_once(Receivers, Ref, Event, Payload) ->- Expected = maps:from_list([{Pid, false} || Pid <- Receivers]),- Seen = collect_received(length(Receivers), Ref, Event, Payload, Expected),- ?assertEqual(maps:from_list([{Pid, true} || Pid <- Receivers]), Seen),- assert_no_extra_received(Ref).--collect_received(0, _Ref, _Event, _Payload, Seen) ->- Seen;-collect_received(Remaining, Ref, Event, Payload, Seen) ->- receive- {relay_stress_received, Ref, Pid, Event, Payload} ->- ?assertEqual(false, maps:get(Pid, Seen, duplicate)),- collect_received(Remaining - 1, Ref, Event, Payload, Seen#{Pid := true});- {relay_stress_received, Ref, Pid, OtherEvent, OtherPayload} ->- ?assert(false, {unexpected_relay_payload, Pid, OtherEvent, OtherPayload})- after 5000 ->- Missing = [Pid || {Pid, false} <- maps:to_list(Seen)],- ?assert(false, {relay_stress_timeout, Remaining, length(Missing)})- end.--assert_no_extra_received(Ref) ->- receive- {relay_stress_received, Ref, Pid, Event, Payload} ->- ?assert(false, {duplicate_relay_delivery, Pid, Event, Payload})- after 100 ->- ok- end.--assert_worker_queues_drained(Workers) ->- ok = wait_until(fun() ->- lists:all(- fun(Pid) -> gateway_dispatch_relay_batch:message_queue_len(Pid) =:= 0 end,- Workers- )- end).--wait_until(Pred) ->- Deadline = erlang:monotonic_time(millisecond) + 5000,- wait_until(Pred, Deadline).--wait_until(Pred, Deadline) ->- case Pred() of- true ->- ok;- false ->- case erlang:monotonic_time(millisecond) >= Deadline of- true ->- ?assert(false, wait_until_timeout);- false ->- timer:sleep(10),- wait_until(Pred, Deadline)- end- end.diff --git a/fluxer_gateway/test/gateway_handler_tests.erl b/fluxer_gateway/test/gateway_handler_tests.erldeleted file mode 100644index 9a6be42b9..000000000--- a/fluxer_gateway/test/gateway_handler_tests.erl+++ /dev/null@@ -1,642 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_handler_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(TEST_GATEWAY_RATE_LIMIT_MAX_EVENTS, 600).--define(TEST_IDENTIFY_MAX_PER_IP, 300).--websocket_info_session_reconnect_sends_reconnect_then_close_test() ->- assert_reconnect_close(- gateway_handler:websocket_info(session_reconnect, new_json_state()),- <<"Session drain requested; reconnect to continue">>- ).--websocket_info_dispatch_list_payload_emits_frame_test() ->- Decoded = decode_dispatch_frame(- gateway_handler:websocket_info(- {dispatch, user_pinned_dms_update, [<<"1">>, <<"2">>], 1}, new_json_state()- )- ),- ?assertEqual(<<"USER_PINNED_DMS_UPDATE">>, maps:get(<<"t">>, Decoded)),- ?assertEqual([<<"1">>, <<"2">>], maps:get(<<"d">>, Decoded)),- ?assertEqual(1, maps:get(<<"s">>, Decoded)).--websocket_info_sessions_replace_list_payload_emits_frame_test() ->- Sessions = [- #{<<"session_id">> => <<"abc">>, <<"status">> => <<"online">>},- #{<<"session_id">> => <<"def">>, <<"status">> => <<"idle">>}- ],- Decoded = decode_dispatch_frame(- gateway_handler:websocket_info(- {dispatch, sessions_replace, Sessions, 7}, new_json_state()- )- ),- ?assertEqual(<<"SESSIONS_REPLACE">>, maps:get(<<"t">>, Decoded)),- ?assertEqual(Sessions, maps:get(<<"d">>, Decoded)),- ?assertEqual(7, maps:get(<<"s">>, Decoded)).--websocket_info_empty_list_payload_emits_json_array_test() ->- Decoded = decode_dispatch_frame(- gateway_handler:websocket_info(- {dispatch, webauthn_credentials_update, [], 3}, new_json_state()- )- ),- ?assertEqual(<<"WEBAUTHN_CREDENTIALS_UPDATE">>, maps:get(<<"t">>, Decoded)),- ?assertEqual([], maps:get(<<"d">>, Decoded)).--start_session_with_drain_guard_holds_during_drain_test() ->- Request = #{},- assert_pending_identify(- gateway_handler_identify:start_session_with_drain_guard(- true, Request, self(), new_json_state()- ),- Request,- self()- ).--handle_session_start_result_holds_draining_without_context_test() ->- assert_held_without_pending(- gateway_handler_identify:handle_session_start_result(- {error, draining}, new_json_state()- )- ).--handle_session_start_result_holds_not_eligible_without_context_test() ->- assert_held_without_pending(- gateway_handler_identify:handle_session_start_result(- {error, not_eligible}, new_json_state()- )- ).--start_session_zero_rollout_holds_socket_test() ->- OldConfig = gateway_rollout_config:get(),- try- persistent_term:put(gateway_rollout_config, OldConfig#{- <<"session_rollout_percentage">> => 0- }),- Request = #{},- assert_pending_identify(- gateway_handler_identify:start_session(Request, self(), new_json_state()),- Request,- self()- )- after- persistent_term:put(gateway_rollout_config, OldConfig)- end.--handle_session_start_result_retries_exhausted_holds_without_context_test() ->- State = (gateway_handler:new_state())#{- version => 1, encoding => json, compress_ctx => gateway_compress:new_context(none)- },- assert_held_without_pending(- gateway_handler_identify:handle_session_start_result(- {error, {retries_exhausted, timeout}}, State- )- ).--handle_session_start_result_retries_exhausted_5xx_holds_without_context_test() ->- State = (gateway_handler:new_state())#{- version => 1, encoding => json, compress_ctx => gateway_compress:new_context(none)- },- assert_held_without_pending(- gateway_handler_identify:handle_session_start_result(- {error, {retries_exhausted, {rpc_error, 503, <<"Service unavailable">>}}}, State- )- ).--handle_session_start_result_server_error_closes_with_unknown_error_test() ->- State = (gateway_handler:new_state())#{- version => 1, encoding => json, compress_ctx => gateway_compress:new_context(none)- },- {[{close, CloseCode, _Reason}], _NewState} =- gateway_handler_identify:handle_session_start_result(- {error, {server_error, 500}}, State- ),- ?assertEqual(constants:close_code_to_num(unknown_error), CloseCode).--handle_session_start_result_unknown_reason_closes_failed_to_start_test() ->- State = (gateway_handler:new_state())#{- version => 1, encoding => json, compress_ctx => gateway_compress:new_context(none)- },- {[{close, CloseCode, Reason}], _NewState} =- gateway_handler_identify:handle_session_start_result(- {error, something_unmapped}, State- ),- ?assertEqual(constants:close_code_to_num(unknown_error), CloseCode),- ?assertEqual(<<"Failed to start session">>, Reason).--websocket_init_schedules_tokened_heartbeat_timer_test() ->- {[{text, _Frame}], State} = gateway_handler:websocket_init(new_json_state()),- ?assertMatch({_TimerRef, _Token}, maps:get(heartbeat_timer, State)),- gateway_handler_heartbeat:cancel_heartbeat_timer(State).--heartbeat_check_ignores_stale_token_test() ->- State0 = heartbeat_test_state(),- State1 = gateway_handler_heartbeat:schedule_heartbeat_check(State0),- {TimerRef, Token} = maps:get(heartbeat_timer, State1),- {ok, State2} = gateway_handler:websocket_info({heartbeat_check, make_ref()}, State1),- ?assertEqual({TimerRef, Token}, maps:get(heartbeat_timer, State2)),- gateway_handler_heartbeat:cancel_heartbeat_timer(State2).--heartbeat_check_replaces_matched_timer_test() ->- State0 = heartbeat_test_state(),- State1 = gateway_handler_heartbeat:schedule_heartbeat_check(State0),- {TimerRef, Token} = maps:get(heartbeat_timer, State1),- {ok, State2} = gateway_handler:websocket_info({heartbeat_check, Token}, State1),- ?assertMatch({_NewTimerRef, _NewToken}, maps:get(heartbeat_timer, State2)),- ?assertNotEqual({TimerRef, Token}, maps:get(heartbeat_timer, State2)),- gateway_handler_heartbeat:cancel_heartbeat_timer(State2).--pending_identify_retry_ignores_stale_token_test() ->- Timer = erlang:send_after(60000, self(), stale_pending_identify_retry),- CurrentToken = make_ref(),- State0 = (new_json_state())#{- pending_identify => {#{token => <<"t">>}, self()},- pending_identify_retry_timer => {Timer, CurrentToken}- },- {ok, State1} = gateway_handler:websocket_info(- {retry_pending_identify, make_ref()}, State0- ),- ?assertEqual(State0, State1),- cancel_pending_identify_timer(State1).--parse_forwarded_for_ipv4_test() ->- ?assertEqual(<<"203.0.113.7">>, gateway_handler:parse_forwarded_for(<<"203.0.113.7">>)).-parse_forwarded_for_ipv4_with_port_test() ->- ?assertEqual(- <<"203.0.113.7">>, gateway_handler:parse_forwarded_for(<<"203.0.113.7:8080">>)- ).-parse_forwarded_for_ipv4_with_port_and_extra_entries_test() ->- ?assertEqual(- <<"203.0.113.7">>,- gateway_handler:parse_forwarded_for(<<" 203.0.113.7:8080 , 10.0.0.1">>)- ).-parse_forwarded_for_ipv6_test() ->- ?assertEqual(<<"2001:db8::1">>, gateway_handler:parse_forwarded_for(<<"2001:db8::1">>)).-parse_forwarded_for_ipv6_with_brackets_test() ->- ?assertEqual(<<"2001:db8::1">>, gateway_handler:parse_forwarded_for(<<"[2001:db8::1]">>)).-parse_forwarded_for_ipv6_with_brackets_and_port_test() ->- ?assertEqual(- <<"2001:db8::1">>, gateway_handler:parse_forwarded_for(<<"[2001:db8::1]:443">>)- ).-parse_forwarded_for_ipv6_with_spaces_test() ->- ?assertEqual(- <<"2001:db8::1">>, gateway_handler:parse_forwarded_for(<<" [2001:db8::1] ">>)- ).-parse_forwarded_for_invalid_ip_test() ->- ?assertEqual(<<>>, gateway_handler:parse_forwarded_for(<<"not_an_ip">>)).-parse_forwarded_for_invalid_ipv4_octet_test() ->- ?assertEqual(<<>>, gateway_handler:parse_forwarded_for(<<"203.0.113.300">>)).-parse_forwarded_for_unterminated_bracket_test() ->- ?assertEqual(<<>>, gateway_handler:parse_forwarded_for(<<"[2001:db8::1">>)).-parse_ignored_events_test() ->- ?assertEqual({ok, []}, gateway_handler_identify:parse_ignored_events(undefined)),- ?assertEqual({ok, []}, gateway_handler_identify:parse_ignored_events(null)),- ?assertEqual(- {ok, [<<"TYPING_START">>]},- gateway_handler_identify:parse_ignored_events([<<"typing_start">>])- ),- ?assertEqual(- {error, invalid_ignored_events}, gateway_handler_identify:parse_ignored_events([123])- ),- ?assertEqual(- {error, invalid_ignored_events},- gateway_handler_identify:parse_ignored_events(<<"not_a_list">>)- ).--check_rate_limit_blocks_general_flood_test() ->- with_rate_limits_enabled(fun() ->- Now = erlang:system_time(millisecond),- Events = lists:duplicate(?TEST_GATEWAY_RATE_LIMIT_MAX_EVENTS, Now - 1000),- State = (gateway_handler:new_state())#{- rate_limit_state => #{events => Events, op_events => #{}}- },- ?assertMatch(- {rate_limited, _}, gateway_handler_rate_limit:check_rate_limit(State, heartbeat)- )- end).--check_presence_rate_limit_soft_drops_only_presence_test() ->- with_rate_limits_enabled(fun() ->- Now = erlang:system_time(millisecond),- Events = lists:duplicate(5, Now - 1000),- State = (gateway_handler:new_state())#{- rate_limit_state => #{- events => [], op_events => #{presence_update => Events}- }- },- {opcode_rate_limited, NewState} = gateway_handler_rate_limit:check_rate_limit(- State, presence_update- ),- RateLimitState = maps:get(rate_limit_state, NewState),- ?assertEqual(1, length(maps:get(events, RateLimitState)))- end).--check_voice_signal_rate_limit_allows_trickle_bursts_test() ->- with_rate_limits_enabled(fun() ->- Now = erlang:system_time(millisecond),- State = fun(Count) ->- (gateway_handler:new_state())#{- rate_limit_state => #{- events => [],- op_events => #{voice_signal => lists:duplicate(Count, Now - 1000)}- }- }- end,- ?assertMatch(- {ok, _}, gateway_handler_rate_limit:check_rate_limit(State(239), voice_signal)- ),- ?assertMatch(- {opcode_rate_limited, _},- gateway_handler_rate_limit:check_rate_limit(State(240), voice_signal)- )- end).--enqueue_voice_update_keeps_latest_update_for_connection_test() ->- Queue0 = queue:new(),- Data1 = #{- <<"guild_id">> => <<"1">>, <<"connection_id">> => <<"conn-1">>, <<"self_mute">> => false- },- Data2 = Data1#{<<"self_mute">> => true},- Queue1 = gateway_handler_voice:enqueue_voice_update(Queue0, Data1),- Queue2 = gateway_handler_voice:enqueue_voice_update(Queue1, Data2),- ?assertEqual([Data2], queue:to_list(Queue2)).--handle_request_guild_members_queues_latest_request_while_worker_active_test() ->- ExistingWorkerPid = self(),- State = (gateway_handler:new_state())#{request_guild_members_pid => ExistingWorkerPid},- Data = #{<<"guild_ids">> => [<<"1">>, <<"2">>]},- ?assertMatch(- {ok, #{request_guild_members_pending := Data}},- gateway_handler_dispatch:handle_request_guild_members(Data, self(), State)- ).--handle_request_guild_counts_drops_when_socket_worker_limit_reached_test() ->- Ref = make_ref(),- WorkerPid = self(),- State = (gateway_handler:new_state())#{- request_worker_max => 1,- request_workers => #{- Ref => #{pid => WorkerPid, type => lazy_request, timer => undefined}- }- },- {ok, NewState} = gateway_handler_dispatch:handle_request_guild_counts(- #{}, self(), eqwalizer:dynamic_cast(State)- ),- ?assertEqual(1, maps:size(maps:get(request_workers, NewState))).--request_worker_timeout_removes_and_kills_worker_test() ->- WorkerPid = spawn(fun request_worker_wait_loop/0),- Ref = make_ref(),- State = (gateway_handler:new_state())#{- request_workers => #{- Ref => #{pid => WorkerPid, type => lazy_request, timer => undefined}- }- },- {ok, NewState} = gateway_handler_dispatch:handle_request_worker_timeout(- Ref, lazy_request, State- ),- ok = gateway_retry_timer:wait(10),- ?assertEqual(#{}, maps:get(request_workers, NewState)),- ?assertNot(erlang:is_process_alive(WorkerPid)).--validate_identify_data_empty_map_test() ->- ?assertEqual(- {error, missing_required_field}, gateway_handler_identify:validate_identify_data(#{})- ).-validate_identify_data_non_map_properties_test() ->- ?assertEqual(- {error, invalid_properties},- gateway_handler_identify:validate_identify_data(#{- <<"token">> => <<"abc">>, <<"properties">> => <<"not_a_map">>- })- ).-validate_identify_data_negative_flags_test() ->- ?assertEqual(- {error, invalid_properties},- gateway_handler_identify:validate_identify_data(#{- <<"token">> => <<"abc">>,- <<"properties">> => #{- <<"os">> => <<"linux">>, <<"browser">> => <<"b">>, <<"device">> => <<"d">>- },- <<"flags">> => -1- })- ).--handle_identify_runs_identify_rate_check_at_zero_rollout_test() ->- with_rate_limits_enabled(fun() ->- session_abuse_protection:ensure_tables(),- OldConfig = gateway_rollout_config:get(),- IP = unique_test_peer_ip(<<"zero-rollout-identify">>),- try- persistent_term:put(gateway_rollout_config, OldConfig#{- <<"session_rollout_percentage">> => 0- }),- lists:foreach(- fun(_) ->- ?assertEqual(ok, session_abuse_protection:check_identify_rate(IP))- end,- lists:seq(1, ?TEST_IDENTIFY_MAX_PER_IP - 1)- ),- {ok, HeldState} = gateway_handler_identify:handle_identify(- valid_identify_data(#{}), IP, new_json_state()- ),- cancel_pending_identify_timer(HeldState),- ?assertEqual(- {error, identify_rate_limited},- session_abuse_protection:check_identify_rate(IP)- )- after- persistent_term:put(gateway_rollout_config, OldConfig)- end- end).--handle_session_start_result_invalid_shard_closes_4010_test() ->- {[{close, CloseCode, _Reason}], _NewState} =- gateway_handler_identify:handle_session_start_result(- {error, invalid_shard}, new_json_state()- ),- ?assertEqual(constants:close_code_to_num(invalid_shard), CloseCode).--handle_session_start_result_sharding_required_closes_4011_test() ->- {[{close, CloseCode, _Reason}], _NewState} =- gateway_handler_identify:handle_session_start_result(- {error, sharding_required}, new_json_state()- ),- ?assertEqual(constants:close_code_to_num(sharding_required), CloseCode).--identify_with_non_map_payload_closes_test() ->- State = (new_json_state())#{peer_ip => unique_test_peer_ip(<<"198.51.100.61">>)},- {[{close, CloseCode, _Reason}], _NewState} = gateway_handler_dispatch:handle_opcode(- identify, #{<<"d">> => null}, State- ),- ?assertEqual(constants:close_code_to_num(decode_error), CloseCode).--voice_state_update_with_non_map_payload_closes_test() ->- State = (new_json_state())#{session_pid => self()},- {[{close, CloseCode, _Reason}], _NewState} = gateway_handler_dispatch:handle_opcode(- voice_state_update, #{<<"d">> => <<"not-a-map">>}, State- ),- ?assertEqual(constants:close_code_to_num(decode_error), CloseCode).--voice_signal_is_cast_to_the_session_test() ->- State = (new_json_state())#{session_pid => self()},- Data = #{<<"channel_id">> => <<"100">>, <<"to">> => <<"conn-b">>, <<"data">> => #{}},- ?assertEqual(- {ok, State},- gateway_handler_dispatch:handle_opcode(voice_signal, #{<<"d">> => Data}, State)- ),- receive- {'$gen_cast', {voice_signal, Data}} -> ok- after 1000 ->- error(voice_signal_not_cast)- end.--voice_signal_with_non_map_payload_is_dropped_test() ->- State = (new_json_state())#{session_pid => self()},- ?assertEqual(- {ok, State},- gateway_handler_dispatch:handle_opcode(- voice_signal, #{<<"d">> => <<"not-a-map">>}, State- )- ).--websocket_info_gateway_error_emits_an_error_frame_test() ->- {[{text, Frame}], _State} = gateway_handler:websocket_info(- {gateway_error, voice_p2p_consent_required}, new_json_state()- ),- ?assertEqual(- #{- <<"op">> => 12,- <<"d">> => #{- <<"code">> => <<"VOICE_P2P_CONSENT_REQUIRED">>,- <<"message">> => <<"This call is peer-to-peer and requires agreement to join">>- }- },- json:decode(Frame)- ).--voice_signal_opcode_is_thirteen_test() ->- ?assertEqual(voice_signal, constants:gateway_opcode(13)),- ?assertEqual(13, constants:opcode_to_num(voice_signal)).--websocket_handle_rejects_compressed_frame_past_max_payload_test() ->- {ok, Compressed, _} = gateway_compress:compress(- binary:copy(<<"a">>, constants:max_payload_size() * 64),- gateway_compress:new_context(zstd_stream)- ),- ?assert(byte_size(Compressed) =< constants:max_payload_size()),- State = (new_json_state())#{compress_ctx => gateway_compress:new_context(zstd_stream)},- {[{close, CloseCode, Reason}], _} =- gateway_handler:websocket_handle({binary, Compressed}, State),- ?assertEqual(constants:close_code_to_num(decode_error), CloseCode),- ?assertEqual(<<"Payload too large">>, Reason).--forum_unreads_gate_off_closes_like_an_unknown_opcode_test() ->- Previous = persistent_term:get(channel_threads_config, undefined),- persistent_term:put(- channel_threads_config, (channel_threads_config:default_config())#{config_version => 1}- ),- try- State = (new_json_state())#{session_pid => self()},- Unknown = gateway_handler_dispatch:handle_opcode(- not_an_opcode, #{<<"d">> => #{}}, State- ),- ?assertEqual({[{close, 4001, <<"Unknown opcode">>}], State}, Unknown),- ?assertEqual(- Unknown,- gateway_handler_dispatch:handle_opcode(- request_forum_unreads,- #{<<"d">> => #{<<"guild_id">> => <<"1">>, <<"channel_id">> => <<"2">>}},- State- )- ),- ?assertEqual(- Unknown, gateway_handler_dispatch:handle_request_forum_unreads(#{}, self(), State)- ),- ?assertEqual(- Unknown, gateway_handler:websocket_info(forum_unreads_unknown_opcode, State)- )- after- case Previous of- undefined -> persistent_term:erase(channel_threads_config);- _ -> persistent_term:put(channel_threads_config, Previous)- end- end.--forum_unreads_closes_like_an_unknown_opcode_once_a_default_config_is_pulled_test() ->- Key = channel_threads_config,- PulledKey = {channel_threads_config, pulled},- Previous = persistent_term:get(Key, undefined),- PreviousPulled = persistent_term:get(PulledKey, undefined),- persistent_term:put(Key, channel_threads_config:default_config()),- persistent_term:put(PulledKey, true),- try- Bot = fake_session(#{user_id => <<"6">>, bot => true, thread_channels_capable => true}),- State = (new_json_state())#{session_pid => Bot},- Unknown = {[{close, 4001, <<"Unknown opcode">>}], State},- ?assertEqual(- Unknown,- gateway_handler_dispatch:handle_opcode(- request_forum_unreads,- #{<<"d">> => #{<<"guild_id">> => <<"1">>, <<"channel_id">> => <<"2">>}},- State- )- ),- ?assertEqual(- Unknown, gateway_handler_dispatch:handle_request_forum_unreads(#{}, Bot, State)- ),- ?assertNot(received_unknown_opcode())- after- case Previous of- undefined -> persistent_term:erase(Key);- _ -> persistent_term:put(Key, Previous)- end,- case PreviousPulled of- undefined -> persistent_term:erase(PulledKey);- _ -> persistent_term:put(PulledKey, PreviousPulled)- end- end.--forum_unreads_gate_on_closes_non_viewers_on_every_path_test() ->- with_threads_enabled(fun() ->- NonViewer = fake_session(#{user_id => <<"5">>, thread_channels_capable => false}),- State = (new_json_state())#{session_pid => NonViewer},- {ok, _} = gateway_handler_dispatch:handle_request_forum_unreads(#{}, NonViewer, State),- ?assert(received_unknown_opcode()),- Full = State#{request_worker_max => 1, request_workers => #{make_ref() => #{}}},- {ok, Full} = gateway_handler_dispatch:handle_request_forum_unreads(- #{}, NonViewer, Full- ),- ?assert(received_unknown_opcode()),- Dead = spawn(fun() -> ok end),- DeadState = State#{session_pid => Dead},- {ok, _} = gateway_handler_dispatch:handle_request_forum_unreads(#{}, Dead, DeadState),- ?assert(received_unknown_opcode()),- Viewer = fake_session(#{user_id => <<"6">>, bot => true}),- ViewerFull = Full#{session_pid => Viewer},- {ok, ViewerFull} = gateway_handler_dispatch:handle_request_forum_unreads(- #{}, Viewer, ViewerFull- ),- ?assertNot(received_unknown_opcode())- end).--with_threads_enabled(Fun) ->- Previous = persistent_term:get(channel_threads_config, undefined),- persistent_term:put(- channel_threads_config, (channel_threads_config:default_config())#{enabled => true}- ),- try- Fun()- after- case Previous of- undefined -> persistent_term:erase(channel_threads_config);- _ -> persistent_term:put(channel_threads_config, Previous)- end- end.--fake_session(SessionState) ->- spawn(fun Loop() ->- receive- {'$gen_call', From, {get_state}} ->- gen_server:reply(From, SessionState),- Loop()- after 2000 -> ok- end- end).--received_unknown_opcode() ->- receive- forum_unreads_unknown_opcode -> true- after 300 -> false- end.--new_json_state() ->- (gateway_handler:new_state())#{- version => 1, encoding => json, compress_ctx => gateway_compress:new_context(none)- }.--heartbeat_test_state() ->- (new_json_state())#{- heartbeat_state => #{- last_ack => erlang:system_time(millisecond),- waiting_for_ack => false- }- }.--valid_identify_data(Extra) ->- maps:merge(- #{- <<"token">> => <<"abc">>,- <<"properties">> => #{- <<"os">> => <<"linux">>,- <<"browser">> => <<"browser">>,- <<"device">> => <<"device">>- }- },- Extra- ).--decode_dispatch_frame(Result) ->- {[Frame], _NewState} = Result,- {_FrameType, EncodedFrame} = Frame,- {ok, DecodedFrame} = gateway_codec:decode(EncodedFrame, json),- ?assertEqual(constants:opcode_to_num(dispatch), maps:get(<<"op">>, DecodedFrame)),- DecodedFrame.--assert_reconnect_close(Result, CloseReason) ->- {[Frame, {close, CloseCode, CloseReason}], _NewState} = Result,- ?assertEqual(constants:close_code_to_num(unknown_error), CloseCode),- {_FrameType, EncodedFrame} = Frame,- {ok, DecodedFrame} = gateway_codec:decode(EncodedFrame, json),- ?assertEqual(constants:opcode_to_num(reconnect), maps:get(<<"op">>, DecodedFrame)).--assert_pending_identify(Result, Request, SocketPid) ->- {ok, State} = Result,- ?assertEqual({Request, SocketPid}, maps:get(pending_identify, State)),- ?assertMatch({_TimerRef, _Token}, maps:get(pending_identify_retry_timer, State)),- cancel_pending_identify_timer(State).--assert_held_without_pending(Result) ->- {ok, State} = Result,- ?assertEqual(undefined, maps:get(pending_identify, State, undefined)),- ?assertEqual(undefined, maps:get(pending_identify_retry_timer, State, undefined)).--request_worker_wait_loop() ->- receive- stop -> ok- after 60000 ->- ok- end.--cancel_pending_identify_timer(State) ->- case maps:get(pending_identify_retry_timer, State, undefined) of- {TimerRef, _Token} when is_reference(TimerRef) ->- _ = erlang:cancel_timer(TimerRef, [{async, true}, {info, false}]),- ok;- TimerRef when is_reference(TimerRef) ->- _ = erlang:cancel_timer(TimerRef, [{async, true}, {info, false}]),- ok;- _ ->- ok- end.--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.--restore_env(Key, false) ->- os:unsetenv(Key);-restore_env(Key, Value) ->- os:putenv(Key, Value).--unique_test_peer_ip(Prefix) ->- Suffix = integer_to_binary(erlang:unique_integer([positive])),- <<Prefix/binary, "-", Suffix/binary>>.diff --git a/fluxer_gateway/test/gateway_http_client_response_tests.erl b/fluxer_gateway/test/gateway_http_client_response_tests.erldeleted file mode 100644index f8dc11ceb..000000000--- a/fluxer_gateway/test/gateway_http_client_response_tests.erl+++ /dev/null@@ -1,127 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_http_client_response_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").---define(CIRCUIT_TABLE, gateway_http_circuit_breaker).--define(CIRCUIT_WINDOW_TABLE, gateway_http_circuit_window).--allow_circuit_request_uses_recovery_timeout_test() ->- cleanup_circuit_tables(),- ensure_circuit_tables(),- Key = {rpc, <<"example.test">>},- Now = erlang:system_time(millisecond),- OpenedAt = Now - 4000,- ets:insert(?CIRCUIT_TABLE, {Key, open, OpenedAt, OpenedAt}),- ?assertEqual(- {error, circuit_open}, gateway_http_client_response:allow_circuit_request(Key, 5000)- ),- ?assertEqual(ok, gateway_http_client_response:allow_circuit_request(Key, 3000)),- ?assertEqual(half_open, circuit_state(Key)),- cleanup_circuit_tables().--update_circuit_state_uses_failure_threshold_test() ->- cleanup_circuit_tables(),- ensure_circuit_tables(),- Key = {rpc, <<"threshold.example.test">>},- record(Key, failure(), 2),- ?assertEqual(closed, circuit_state(Key)),- record(Key, failure(), 1),- ?assertEqual(open, circuit_state(Key)),- ?assertEqual(- {error, circuit_open}, gateway_http_client_response:allow_circuit_request(Key, 60000)- ),- cleanup_circuit_tables().--closed_circuit_stays_closed_under_successes_test() ->- cleanup_circuit_tables(),- ensure_circuit_tables(),- Key = {rpc, <<"healthy.example.test">>},- record(Key, success(), 20),- ?assertEqual(closed, circuit_state(Key)),- ?assertEqual(ok, gateway_http_client_response:allow_circuit_request(Key, 5000)),- cleanup_circuit_tables().--open_circuit_half_opens_then_recloses_on_success_test() ->- cleanup_circuit_tables(),- ensure_circuit_tables(),- Key = {rpc, <<"recovering.example.test">>},- record(Key, failure(), 3),- ?assertEqual(open, circuit_state(Key)),- age_opened_at(Key, 6000),- ?assertEqual(ok, gateway_http_client_response:allow_circuit_request(Key, 5000)),- ?assertEqual(half_open, circuit_state(Key)),- ?assertEqual([], ets:lookup(?CIRCUIT_WINDOW_TABLE, Key)),- record(Key, success(), 1),- ?assertEqual(closed, circuit_state(Key)),- ?assertEqual(ok, gateway_http_client_response:allow_circuit_request(Key, 5000)),- cleanup_circuit_tables().--is_stale_circuit_uses_state_specific_timestamps_test() ->- Now = 10000,- ?assertEqual(- true,- gateway_http_client_response:is_stale_circuit({closed, undefined, 8000}, Now, 1000)- ),- ?assertEqual(- false,- gateway_http_client_response:is_stale_circuit({closed, undefined, 9500}, Now, 1000)- ),- ?assertEqual(- true, gateway_http_client_response:is_stale_circuit({open, 8000, 9500}, Now, 1000)- ),- ?assertEqual(- false, gateway_http_client_response:is_stale_circuit({open, 9500, 8000}, Now, 1000)- ),- ?assertEqual(- false, gateway_http_client_response:is_stale_circuit({half_open, 1, 1}, Now, 1000)- ).--failure() ->- {ok, 503, [], <<>>}.--success() ->- {ok, 200, [], <<>>}.--record(Key, Result, Count) ->- lists:foreach(- fun(_) ->- ok = gateway_http_client_response:update_circuit_state_direct(Key, Result, 3)- end,- lists:seq(1, Count)- ).--circuit_state(Key) ->- [{Key, State, _OpenedAt, _UpdatedAt}] = ets:lookup(?CIRCUIT_TABLE, Key),- State.--age_opened_at(Key, DeltaMs) ->- [{Key, State, OpenedAt, UpdatedAt}] = ets:lookup(?CIRCUIT_TABLE, Key),- ets:insert(?CIRCUIT_TABLE, {Key, State, OpenedAt - DeltaMs, UpdatedAt}),- ok.--ensure_circuit_tables() ->- ensure_table(?CIRCUIT_TABLE),- ensure_table(?CIRCUIT_WINDOW_TABLE).--ensure_table(Name) ->- case ets:whereis(Name) of- undefined ->- ets:new(Name, [named_table, public, set]),- ok;- _ ->- ok- end.--cleanup_circuit_tables() ->- delete_table(?CIRCUIT_TABLE),- delete_table(?CIRCUIT_WINDOW_TABLE).--delete_table(Name) ->- try ets:delete(Name) of- _ -> ok- catch- error:badarg -> ok- end.diff --git a/fluxer_gateway/test/gateway_public_endpoint_tests.erl b/fluxer_gateway/test/gateway_public_endpoint_tests.erldeleted file mode 100644index 9d75d455d..000000000--- a/fluxer_gateway/test/gateway_public_endpoint_tests.erl+++ /dev/null@@ -1,77 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_public_endpoint_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(VECTORS_PATH, "../fluxer_common/src/testdata/public_endpoint_vectors.json").--normalize_missing_inputs_test() ->- ?assertEqual(- <<"https://fluxer.example/media">>,- normalize(- <<"https://fluxer.example/media">>, <<"fluxer.example">>, <<"https">>, undefined- )- ),- ?assertEqual(- <<"https://fluxer.example/media">>,- normalize(<<"https://fluxer.example/media">>, undefined, <<"https">>, 8443)- ),- ?assertEqual(- <<"https://fluxer.example/media">>,- normalize(<<"https://fluxer.example/media">>, <<>>, <<"https">>, 8443)- ).--normalize_single_root_dot_test() ->- ?assertEqual(- <<"http://fluxer.example.:19080/media">>,- normalize(<<"http://fluxer.example./media">>, <<"fluxer.example.">>, <<"http">>, 19080)- ),- ?assertEqual(- <<"http://fluxer.example../media">>,- normalize(<<"http://fluxer.example../media">>, <<"fluxer.example">>, <<"http">>, 19080)- ),- ?assertEqual(- <<"http://fluxer.example/media">>,- normalize(<<"http://fluxer.example/media">>, <<"fluxer.example..">>, <<"http">>, 19080)- ).--normalize_matches_shared_vectors_test() ->- Vectors = read_vectors(),- ?assertMatch([_ | _], Vectors),- lists:foreach(fun run_vector/1, Vectors).--read_vectors() ->- case file:read_file(?VECTORS_PATH) of- {ok, Contents} ->- decode_vectors(Contents);- {error, Reason} ->- erlang:error({public_endpoint_vectors_unreadable, ?VECTORS_PATH, Reason})- end.--decode_vectors(Contents) ->- case json:decode(Contents) of- [_ | _] = Vectors -> Vectors;- _ -> erlang:error({public_endpoint_vectors_empty, ?VECTORS_PATH})- end.--run_vector(- #{<<"url">> := Url, <<"base_domain">> := BaseDomain, <<"normalized">> := Expected} = Vector-) when is_binary(Url), is_binary(BaseDomain), is_binary(Expected) ->- Port = vector_port(Vector),- ?assertEqual(- {Url, BaseDomain, Port, Expected},- {Url, BaseDomain, Port, normalize(Url, BaseDomain, undefined, Port)}- );-run_vector(Vector) ->- erlang:error({public_endpoint_vector_malformed, Vector}).--vector_port(#{<<"public_port">> := null}) ->- undefined;-vector_port(#{<<"public_port">> := Port}) when is_integer(Port) ->- Port;-vector_port(Vector) ->- erlang:error({public_endpoint_vector_malformed, Vector}).--normalize(Url, BaseDomain, Scheme, Port) ->- gateway_public_endpoint:normalize(Url, BaseDomain, Scheme, Port).diff --git a/fluxer_gateway/test/gateway_resume_timings_tests.erl b/fluxer_gateway/test/gateway_resume_timings_tests.erldeleted file mode 100644index ffe8bb004..000000000--- a/fluxer_gateway/test/gateway_resume_timings_tests.erl+++ /dev/null@@ -1,144 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_resume_timings_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--handle_resume_omits_gateway_timings_for_non_staff_test() ->- drain_mailbox(),- SessionPid = spawn(fun() -> fake_resume_session_loop(<<"resume-token">>, 12, false) end),- meck:new(session_manager, [passthrough, no_link]),- meck:new(rpc_client, [passthrough, no_link]),- meck:expect(- session_manager,- lookup_or_rehydrate,- fun(<<"session-non-staff">>, <<"resume-token">>, SocketPid) when is_pid(SocketPid) ->- {ok, SessionPid}- end- ),- meck:expect(rpc_client, call, fun(_Request) -> error(unexpected_resume_api_call) end),- try- State0 = maps:remove(peer_ip, new_json_state()),- {ok, State1} = gateway_handler_identify:handle_resume(- #{- <<"token">> => <<"resume-token">>,- <<"session_id">> => <<"session-non-staff">>,- <<"seq">> => 7- },- State0- ),- ?assertEqual(SessionPid, maps:get(session_pid, State1)),- assert_resumed_dispatch_without_timings(12)- after- SessionPid ! stop,- meck:unload(rpc_client),- meck:unload(session_manager)- end.--handle_resume_missing_session_sends_invalid_session_without_api_test() ->- drain_mailbox(),- meck:new(session_manager, [passthrough, no_link]),- meck:expect(- session_manager,- lookup_or_rehydrate,- fun(<<"missing-session">>, <<"resume-token">>, SocketPid) when is_pid(SocketPid) ->- {error, not_found}- end- ),- try- {Frames, _State1} = gateway_handler_identify:handle_resume(- #{- <<"token">> => <<"resume-token">>,- <<"session_id">> => <<"missing-session">>,- <<"seq">> => 7- },- new_json_state()- ),- ?assertMatch([_Frame], Frames)- after- meck:unload(session_manager)- end.--handle_resume_below_replay_floor_sends_invalid_session_test() ->- drain_mailbox(),- SessionPid = spawn(fun() -> fake_not_resumable_session_loop(<<"resume-token">>) end),- meck:new(session_manager, [passthrough, no_link]),- meck:expect(- session_manager,- lookup_or_rehydrate,- fun(<<"evicted-session">>, <<"resume-token">>, SocketPid) when is_pid(SocketPid) ->- {ok, SessionPid}- end- ),- try- {Frames, _State1} = gateway_handler_identify:handle_resume(- #{- <<"token">> => <<"resume-token">>,- <<"session_id">> => <<"evicted-session">>,- <<"seq">> => 7- },- new_json_state()- ),- [{text, Payload}] = Frames,- Message = json:decode(Payload),- ?assertEqual(constants:opcode_to_num(invalid_session), maps:get(<<"op">>, Message)),- ?assertEqual(false, maps:get(<<"d">>, Message))- after- SessionPid ! stop,- meck:unload(session_manager)- end.--fake_not_resumable_session_loop(Token) ->- receive- {'$gen_call', From, {token_verify, Candidate}} ->- gen_server:reply(From, Candidate =:= Token),- fake_not_resumable_session_loop(Token);- {'$gen_call', From, {resume, _Seq, SocketPid}} when is_pid(SocketPid) ->- gen_server:reply(From, not_resumable),- fake_not_resumable_session_loop(Token);- stop ->- ok- after 30000 ->- ok- end.--assert_resumed_dispatch_without_timings(ExpectedSeq) ->- receive- {dispatch, resumed, ResumedData, ExpectedSeq} ->- ?assertNot(maps:is_key(<<"_timings_gw">>, ResumedData))- after 1000 ->- ?assert(false, resumed_not_dispatched)- end.--fake_resume_session_loop(Token, CurrentSeq, IsStaff) ->- receive- {'$gen_call', From, {token_verify, Candidate}} ->- gen_server:reply(From, Candidate =:= Token),- fake_resume_session_loop(Token, CurrentSeq, IsStaff);- {'$gen_call', From, {resume, _Seq, SocketPid}} when is_pid(SocketPid) ->- gen_server:reply(From, {ok, [], CurrentSeq}),- fake_resume_session_loop(Token, CurrentSeq, IsStaff);- {'$gen_call', From, {is_staff}} ->- gen_server:reply(From, IsStaff),- fake_resume_session_loop(Token, CurrentSeq, IsStaff);- stop ->- ok- after 30000 ->- ok- end.--drain_mailbox() ->- receive- _ -> drain_mailbox()- after 0 ->- ok- end.--new_json_state() ->- (gateway_handler:new_state())#{- version => 1,- encoding => json,- compress_ctx => gateway_compress:new_context(none),- peer_ip => <<"127.0.0.1">>- }.diff --git a/fluxer_gateway/test/gateway_retry_timer_tests.erl b/fluxer_gateway/test/gateway_retry_timer_tests.erldeleted file mode 100644index dd99db2d3..000000000--- a/fluxer_gateway/test/gateway_retry_timer_tests.erl+++ /dev/null@@ -1,15 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_retry_timer_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--wait_keeps_unrelated_mailbox_messages_test() ->- self() ! unrelated_message,- ?assertEqual(ok, gateway_retry_timer:wait(0)),- receive- unrelated_message -> ok- after 0 ->- ?assert(false, unrelated_message_was_consumed)- end.diff --git a/fluxer_gateway/test/gateway_rollout_config_tests.erl b/fluxer_gateway/test/gateway_rollout_config_tests.erldeleted file mode 100644index 91390b536..000000000--- a/fluxer_gateway/test/gateway_rollout_config_tests.erl+++ /dev/null@@ -1,152 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_rollout_config_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(PERSISTENT_TERM_KEY, gateway_rollout_config).--default_config() ->- #{- <<"session_rollout_percentage">> => 100,- <<"session_rollout_mode">> => <<"modulo">>,- <<"guild_rollout_percentage">> => 100,- <<"rpc_request_timeout_ms">> => 10000,- <<"max_concurrent_session_starts">> => 512,- <<"max_concurrent_guild_starts">> => 256,- <<"gateway_dispatch_relay_shards">> => 32,- <<"gateway_dispatch_relay_max_queue">> => 50000,- <<"voice_e2ee_scope">> => <<"guild_feature_only">>- }.--validate_config_rejects_bad_rollout_values_test() ->- ?assertMatch(- {error, {invalid_field, <<"session_rollout_percentage">>, 101}},- gateway_rollout_config_validate:validate(- #{- <<"session_rollout_percentage">> => 101- },- default_config()- )- ),- ?assertMatch(- {error, {invalid_field, <<"session_rollout_mode">>, <<"open">>}},- gateway_rollout_config_validate:validate(- #{- <<"session_rollout_mode">> => <<"open">>- },- default_config()- )- ),- ?assertMatch(- {error, {invalid_field, <<"max_concurrent_session_starts">>, 0}},- gateway_rollout_config_validate:validate(- #{- <<"max_concurrent_session_starts">> => 0- },- default_config()- )- ).--validate_config_ignores_unknown_keys_and_merges_defaults_test() ->- {ok, Config} = gateway_rollout_config_validate:validate(- #{- <<"session_rollout_percentage">> => 25,- <<"unknown">> => unsafe- },- default_config()- ),- ?assertEqual(25, maps:get(<<"session_rollout_percentage">>, Config)),- ?assertEqual(false, maps:is_key(<<"unknown">>, Config)),- ?assertEqual(256, maps:get(<<"max_concurrent_guild_starts">>, Config)).--nats_payload_updates_config_and_notifies_subscribers_test() ->- persistent_term:put(?PERSISTENT_TERM_KEY, default_config()),- Config = (default_config())#{<<"session_rollout_percentage">> => 42},- Payload = iolist_to_binary(- json:encode(#{- <<"type">> => <<"gateway_rollout_config">>,- <<"config">> => Config- })- ),- State = #{- subscribers => [{self(), make_ref()}],- nats_subscription => undefined,- nats_monitor => undefined- },- ?assertMatch(- {noreply, State},- gateway_rollout_config:handle_info(- {nats_msg, <<"config.gateway.rollout">>, Payload, undefined},- State- )- ),- ?assertEqual(42, gateway_rollout_config:session_rollout_percentage()),- receive- rollout_config_changed -> ok- after 100 ->- ?assert(false)- end,- persistent_term:put(?PERSISTENT_TERM_KEY, default_config()).--nats_duplicate_payload_does_not_notify_subscribers_test() ->- persistent_term:put(?PERSISTENT_TERM_KEY, default_config()),- Payload = iolist_to_binary(- json:encode(#{- <<"type">> => <<"gateway_rollout_config">>,- <<"config">> => default_config()- })- ),- State = #{- subscribers => [{self(), make_ref()}],- nats_subscription => undefined,- nats_monitor => undefined- },- ?assertMatch(- {noreply, State},- gateway_rollout_config:handle_info(- {nats_msg, <<"config.gateway.rollout">>, Payload, undefined},- State- )- ),- receive- rollout_config_changed -> ?assert(false)- after 100 ->- ok- end.--validate_config_rejects_relay_max_queue_zero_test() ->- ?assertMatch(- {error, {invalid_field, <<"gateway_dispatch_relay_max_queue">>, 0}},- gateway_rollout_config_validate:validate(- #{<<"gateway_dispatch_relay_max_queue">> => 0},- default_config()- )- ).--validate_config_rejects_relay_max_queue_above_kill_threshold_test() ->- Above = process_health_watchdog:kill_threshold() + 1,- ?assertMatch(- {error, {invalid_field, <<"gateway_dispatch_relay_max_queue">>, Above}},- gateway_rollout_config_validate:validate(- #{<<"gateway_dispatch_relay_max_queue">> => Above},- default_config()- )- ).--validate_config_accepts_relay_max_queue_range_bounds_test() ->- Ceiling = process_health_watchdog:kill_threshold(),- ?assertMatch(- {ok, #{<<"gateway_dispatch_relay_max_queue">> := 1}},- gateway_rollout_config_validate:validate(- #{<<"gateway_dispatch_relay_max_queue">> => 1},- default_config()- )- ),- ?assertMatch(- {ok, #{<<"gateway_dispatch_relay_max_queue">> := Ceiling}},- gateway_rollout_config_validate:validate(- #{<<"gateway_dispatch_relay_max_queue">> => Ceiling},- default_config()- )- ).diff --git a/fluxer_gateway/test/gateway_rpc_guild_channels_tests.erl b/fluxer_gateway/test/gateway_rpc_guild_channels_tests.erldeleted file mode 100644index 61bd7f82c..000000000--- a/fluxer_gateway/test/gateway_rpc_guild_channels_tests.erl+++ /dev/null@@ -1,55 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_rpc_guild_channels_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--get_viewable_channels_rejects_zero_guild_id_test() ->- Params = #{<<"guild_id">> => <<"0">>, <<"user_id">> => <<"1">>},- ?assertError(- {gateway_rpc_error, <<"guild_id_invalid">>},- gateway_rpc_guild_channels:handle(<<"guild.get_viewable_channels">>, Params)- ).--get_viewable_channels_rejects_leading_zero_user_id_test() ->- Params = #{<<"guild_id">> => <<"1">>, <<"user_id">> => <<"001">>},- ?assertError(- {gateway_rpc_error, <<"user_id_invalid">>},- gateway_rpc_guild_channels:handle(<<"guild.get_viewable_channels">>, Params)- ).--resolve_channel_mentions_skips_invalid_channel_ids_test() ->- Params = #{<<"guild_id">> => <<"1">>, <<"channel_ids">> => [<<"0">>, <<"001">>, <<"-1">>]},- ?assertEqual(- #{<<"channels">> => []},- gateway_rpc_guild_channels:handle(<<"guild.resolve_channel_mentions">>, Params)- ).--resolve_channel_mentions_from_snapshot_skips_forum_and_media_test() ->- GuildId = 7301,- ok = guild_permission_cache:put_data(GuildId, #{- <<"guild">> => #{<<"owner_id">> => <<"1">>},- <<"roles">> => [#{<<"id">> => <<"7301">>, <<"permissions">> => <<"1024">>}],- <<"members">> => [],- <<"channels">> => [- #{<<"id">> => <<"10">>, <<"name">> => <<"text">>, <<"type">> => 0},- #{<<"id">> => <<"11">>, <<"name">> => <<"forum">>, <<"type">> => 15},- #{<<"id">> => <<"12">>, <<"name">> => <<"media">>, <<"type">> => 16}- ]- }),- try- Params = #{- <<"guild_id">> => <<"7301">>, <<"channel_ids">> => [<<"10">>, <<"11">>, <<"12">>]- },- ?assertEqual(- #{- <<"channels">> => [- #{<<"id">> => <<"10">>, <<"name">> => <<"text">>, <<"type">> => 0}- ]- },- gateway_rpc_guild_channels:handle(<<"guild.resolve_channel_mentions">>, Params)- )- after- guild_permission_cache:delete(GuildId)- end.diff --git a/fluxer_gateway/test/gateway_rpc_guild_lifecycle_tests.erl b/fluxer_gateway/test/gateway_rpc_guild_lifecycle_tests.erldeleted file mode 100644index 529ba430a..000000000--- a/fluxer_gateway/test/gateway_rpc_guild_lifecycle_tests.erl+++ /dev/null@@ -1,115 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_rpc_guild_lifecycle_tests).---include_lib("eunit/include/eunit.hrl").--with_guild_pid(Fun) ->- meck:new(gateway_rpc_guild_infra, [passthrough, no_link]),- meck:expect(gateway_rpc_guild_infra, with_guild_unchecked, fun(_GuildId, GuildFun) ->- GuildFun(self())- end),- try- Fun()- after- meck:unload(gateway_rpc_guild_infra)- end.--dispatch_many_casts_every_event_in_order_test() ->- with_guild_pid(fun() ->- Params = #{- <<"guild_id">> => <<"1">>,- <<"events">> => [- #{<<"event">> => <<"THREAD_UPDATE">>, <<"data">> => #{<<"id">> => <<"5">>}},- #{- <<"event">> => <<"THREAD_MEMBER_UPDATE">>,- <<"data">> => #{<<"id">> => <<"5">>}- },- #{<<"event">> => <<"MESSAGE_CREATE">>, <<"data">> => #{<<"id">> => <<"6">>}}- ]- },- ?assertEqual(- true, gateway_rpc_guild_lifecycle:handle(<<"guild.dispatch_many">>, Params)- ),- receive- {'$gen_cast', {dispatch_many, Requests}} ->- ?assertEqual(- [- #{event => thread_update, data => #{<<"id">> => <<"5">>}},- #{event => thread_member_update, data => #{<<"id">> => <<"5">>}},- #{event => message_create, data => #{<<"id">> => <<"6">>}}- ],- Requests- )- after 1000 -> ?assert(false)- end- end).--dispatch_many_rejects_malformed_payloads_without_casting_test() ->- with_guild_pid(fun() ->- Malformed = [- #{- <<"guild_id">> => <<"1">>,- <<"events">> => [#{<<"event">> => <<"THREAD_UPDATE">>}]- },- #{- <<"guild_id">> => <<"1">>,- <<"events">> => [- #{<<"event">> => <<"THREAD_UPDATE">>, <<"data">> => #{}},- #{<<"event">> => 7, <<"data">> => #{}}- ]- },- #{<<"guild_id">> => <<"1">>, <<"events">> => #{}},- #{<<"guild_id">> => <<"1">>}- ],- lists:foreach(- fun(Params) ->- ?assertError(- {gateway_rpc_error, validation_invalid_params},- gateway_rpc_guild_lifecycle:handle(<<"guild.dispatch_many">>, Params)- )- end,- Malformed- ),- ?assertError(- {validation, validation_invalid_snowflake},- gateway_rpc_guild_lifecycle:handle(- <<"guild.dispatch_many">>, #{<<"guild_id">> => <<"0">>, <<"events">> => []}- )- ),- receive- {'$gen_cast', {dispatch_many, _}} -> ?assert(false)- after 50 -> ok- end- end).--dispatch_many_reaches_an_overloaded_guild_test() ->- GuildId = 987654321,- guild_manager_cache:ensure_guild_pid_cache(),- ok = guild_ets_owner:ensure_table(guild_health_status, [named_table, public, set]),- Pending = {make_ref(), erlang:monotonic_time(millisecond), 2500},- true = ets:insert(guild_pid_cache, {GuildId, self()}),- true = ets:insert(guild_health_status, {self(), GuildId, true, undefined, Pending}),- try- ?assert(guild_health:is_overloaded(self())),- Params = #{- <<"guild_id">> => integer_to_binary(GuildId),- <<"events">> => [- #{<<"event">> => <<"THREAD_CREATE">>, <<"data">> => #{<<"id">> => <<"5">>}},- #{- <<"event">> => <<"THREAD_MEMBER_UPDATE">>,- <<"data">> => #{<<"id">> => <<"5">>}- }- ]- },- ?assertEqual(- true, gateway_rpc_guild_lifecycle:handle(<<"guild.dispatch_many">>, Params)- ),- receive- {'$gen_cast', {dispatch_many, Requests}} -> ?assertEqual(2, length(Requests))- after 1000 -> ?assert(false)- end- after- ets:delete(guild_health_status, self()),- ets:delete(guild_pid_cache, GuildId)- end.diff --git a/fluxer_gateway/test/gateway_rpc_voice_tests.erl b/fluxer_gateway/test/gateway_rpc_voice_tests.erldeleted file mode 100644index f4a1fc99e..000000000--- a/fluxer_gateway/test/gateway_rpc_voice_tests.erl+++ /dev/null@@ -1,62 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_rpc_voice_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--voice_channel_read_malformed_payloads_return_empty_results_test() ->- ?assertEqual(- #{<<"voice_states">> => []},- gateway_rpc_voice:execute_method(<<"voice.get_voice_states_for_channel">>, #{})- ),- ?assertEqual(- #{<<"voice_states">> => []},- gateway_rpc_voice:execute_method(<<"voice.get_voice_states_for_channel">>, #{- <<"guild_id">> => <<"1">>,- <<"channel_id">> => null- })- ).--validate_voice_channel_read_params_normalizes_ids_test() ->- ?assertEqual(- {ok, <<"2">>, 1},- gateway_rpc_voice:validate_voice_channel_read_params(#{- <<"guild_id">> => <<"1">>, <<"channel_id">> => 2- })- ),- ?assertEqual(- {ok, <<"2">>, undefined},- gateway_rpc_voice:validate_voice_channel_read_params(#{- <<"guild_id">> => null, <<"channel_id">> => <<"2">>- })- ),- ?assertEqual(- {ok, <<"2">>, undefined},- gateway_rpc_voice:validate_voice_channel_read_params(#{- <<"guild_id">> => <<"0">>, <<"channel_id">> => <<"2">>- })- ).--normalize_voice_states_ignores_malformed_entries_test() ->- ?assertEqual(- [- #{- <<"connection_id">> => <<"conn">>,- <<"user_id">> => <<"42">>,- <<"channel_id">> => <<"9">>,- <<"region_id">> => <<"local">>,- <<"server_id">> => <<"dev-1">>- }- ],- gateway_rpc_voice:normalize_voice_states([- not_a_map,- #{- <<"connection_id">> => <<"conn">>,- <<"user_id">> => 42,- <<"channel_id">> => 9,- region_id => <<"local">>,- server_id => <<"dev-1">>- },- #{<<"connection_id">> => undefined, <<"user_id">> => 84, <<"channel_id">> => 9}- ])- ).diff --git a/fluxer_gateway/test/gateway_sharding_tests.erl b/fluxer_gateway/test/gateway_sharding_tests.erldeleted file mode 100644index 199d1698e..000000000--- a/fluxer_gateway/test/gateway_sharding_tests.erl+++ /dev/null@@ -1,43 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_sharding_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--parse_identify_shard_accepts_absent_and_null_test() ->- ?assertEqual({ok, undefined}, gateway_sharding:parse_identify_shard(undefined)),- ?assertEqual({ok, undefined}, gateway_sharding:parse_identify_shard(null)).--parse_identify_shard_accepts_valid_pair_test() ->- ?assertEqual({ok, {3, 8}}, gateway_sharding:parse_identify_shard([3, 8])).--parse_identify_shard_rejects_invalid_shape_and_range_test() ->- ?assertEqual({error, invalid_shard}, gateway_sharding:parse_identify_shard([1])),- ?assertEqual({error, invalid_shard}, gateway_sharding:parse_identify_shard([1, 1])),- ?assertEqual({error, invalid_shard}, gateway_sharding:parse_identify_shard([-1, 2])),- ?assertEqual({error, invalid_shard}, gateway_sharding:parse_identify_shard([0, 0])),- ?assertEqual({error, invalid_shard}, gateway_sharding:parse_identify_shard([0, 16385])).--retain_guild_ids_for_shard_uses_reference_snowflake_formula_test() ->- Guild0 = guild_id_for_shard(0, 4, 0),- Guild1 = guild_id_for_shard(1, 4, 0),- Guild2 = guild_id_for_shard(2, 4, 0),- Guild5 = guild_id_for_shard(1, 4, 1),- ?assertEqual(- [Guild1, Guild5],- gateway_sharding:retain_guild_ids_for_shard(- [Guild0, Guild1, Guild2, Guild5], {1, 4}- )- ).--validate_session_guild_count_uses_filtered_shard_count_test() ->- GuildIds = [guild_id_for_shard(0, 1, I) || I <- lists:seq(0, 2500)],- ?assertEqual(- {error, sharding_required},- gateway_sharding:validate_session_guild_count(GuildIds, undefined)- ),- ?assertEqual(ok, gateway_sharding:validate_session_guild_count(GuildIds, {1, 2})).--guild_id_for_shard(ShardId, NumShards, Offset) ->- ((Offset * NumShards + ShardId) bsl 22) + 1.diff --git a/fluxer_gateway/test/gateway_zstd_stream_stress_tests.erl b/fluxer_gateway/test/gateway_zstd_stream_stress_tests.erldeleted file mode 100644index 288d4a43a..000000000--- a/fluxer_gateway/test/gateway_zstd_stream_stress_tests.erl+++ /dev/null@@ -1,79 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(gateway_zstd_stream_stress_tests).---include_lib("eunit/include/eunit.hrl").---define(STRESS_MESSAGE_COUNT, 10000).--gateway_zstd_stream_roundtrips_10000_json_messages_test_() ->- {timeout, 60, fun gateway_zstd_stream_roundtrips_10000_json_messages/0}.--gateway_zstd_stream_roundtrips_10000_json_messages() ->- ?assertEqual(true, zstd_stream_available()),- run_zstd_stream_stress().--run_zstd_stream_stress() ->- Compression = gateway_compress:parse_compression(<<"zstd-stream">>, <<"1">>),- ?assertEqual(zstd_stream, Compression),- EncodeState = #{- encoding => json,- compress_ctx => gateway_compress:new_context(Compression)- },- DecodeCtx = gateway_compress:new_context(zstd_stream),- {FinalEncodeState, FinalDecodeCtx, TotalCompressedBytes} = lists:foldl(- fun roundtrip_gateway_message/2,- {EncodeState, DecodeCtx, 0},- lists:seq(1, ?STRESS_MESSAGE_COUNT)- ),- ?assert(TotalCompressedBytes > 0),- ok = gateway_compress:close_context(maps:get(compress_ctx, FinalEncodeState)),- ok = gateway_compress:close_context(FinalDecodeCtx).--roundtrip_gateway_message(Seq, {EncodeState, DecodeCtx, TotalCompressedBytes}) ->- Message = gateway_message(Seq),- {ok, {binary, Compressed}, NextEncodeState} =- gateway_handler_encode:encode_and_compress(Message, EncodeState),- ?assert(byte_size(Compressed) > 0),- {ok, Json, NextDecodeCtx} = gateway_compress:decompress(Compressed, DecodeCtx),- {ok, Decoded} = gateway_codec:decode(Json, json),- ?assertEqual(Message, Decoded),- {NextEncodeState, NextDecodeCtx, TotalCompressedBytes + byte_size(Compressed)}.--gateway_message(Seq) ->- SeqBin = integer_to_binary(Seq),- #{- <<"op">> => 0,- <<"t">> => <<"MESSAGE_CREATE">>,- <<"s">> => Seq,- <<"d">> => #{- <<"id">> => SeqBin,- <<"channel_id">> => <<"1497639278555484216">>,- <<"guild_id">> => <<"1427764661718740994">>,- <<"author">> => #{- <<"id">> => <<"1042">>,- <<"username">> => <<"canary">>,- <<"bot">> => false- },- <<"content">> => iolist_to_binary([- <<"gateway zstd stream stress payload ">>,- SeqBin- ]),- <<"mentions">> => [],- <<"attachments">> => [],- <<"embeds">> => [],- <<"flags">> => Seq rem 8- }- }.--zstd_stream_available() ->- case code:ensure_loaded(ezstd) of- {module, ezstd} ->- erlang:function_exported(ezstd, create_compression_context, 1) andalso- erlang:function_exported(ezstd, set_compression_parameter, 3) andalso- erlang:function_exported(ezstd, compress_streaming, 2) andalso- erlang:function_exported(ezstd, create_decompression_context, 1) andalso- erlang:function_exported(ezstd, decompress_streaming, 2);- _ ->- false- end.diff --git a/fluxer_gateway/test/guild_voice_access_revoke_tests.erl b/fluxer_gateway/test/guild_voice_access_revoke_tests.erldeleted file mode 100644index add3c47dc..000000000--- a/fluxer_gateway/test/guild_voice_access_revoke_tests.erl+++ /dev/null@@ -1,268 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_access_revoke_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").---define(GUILD, 42).--define(USER, 10).--define(CHANNEL, 500).--define(ROLE, 999).--overwrite_deny_view_connect_disconnects_connected_user_test() ->- State = guild_state:update_state(channel_update, deny_overwrite_update(), base_state(true)),- Messages = collect_sync_messages(),- ?assert(disconnected(Messages)),- ?assertNot(granted_permissions(Messages)),- ?assert(guild_virtual_channel_access:has_virtual_access(?USER, ?CHANNEL, State)),- ?assertNot(guild_virtual_channel_access:has_voice_access(?USER, ?CHANNEL, State)).--overwrite_deny_connect_only_disconnects_connected_user_test() ->- Update = channel_update_with_user_deny(constants:connect_permission()),- _ = guild_state:update_state(channel_update, Update, base_state(true)),- ?assert(disconnected(collect_sync_messages())).--overwrite_deny_view_connect_disconnects_user_without_session_test() ->- _ = guild_state:update_state(channel_update, deny_overwrite_update(), base_state(false)),- ?assert(disconnected(collect_sync_messages())).--role_removal_disconnects_connected_user_test() ->- Update = #{<<"user">> => #{<<"id">> => integer_to_binary(?USER)}, <<"roles">> => []},- _ = guild_state:update_state(guild_member_update, Update, base_state(true)),- Messages = collect_sync_messages(),- ?assert(disconnected(Messages)),- ?assertNot(granted_permissions(Messages)).--moderator_granted_access_survives_revoke_test() ->- State0 = guild_virtual_channel_access:add_virtual_access(?USER, ?CHANNEL, base_state(true)),- State = guild_state:update_state(channel_update, deny_overwrite_update(), State0),- Messages = collect_sync_messages(),- ?assertNot(disconnected(Messages)),- ?assert(guild_virtual_channel_access:has_voice_access(?USER, ?CHANNEL, State)).--view_only_access_grants_no_publish_rights_test() ->- ViewConnect = constants:view_channel_permission() bor constants:connect_permission(),- State0 = with_role_permissions(ViewConnect, base_state(true)),- State1 = guild_virtual_channel_access:add_view_only_access(?USER, ?CHANNEL, State0),- State = with_overwrites([user_deny(ViewConnect)], State1),- ?assertEqual(- #{can_speak => false, can_stream => false, can_video => false},- voice_utils:compute_voice_permissions(?USER, ?CHANNEL, State)- ).--explicit_access_replaces_view_only_mark_test() ->- State0 = guild_virtual_channel_access:add_view_only_access(?USER, ?CHANNEL, #{}),- ?assert(guild_virtual_channel_access:is_view_only(?USER, ?CHANNEL, State0)),- State1 = guild_virtual_channel_access:add_virtual_access(?USER, ?CHANNEL, State0),- ?assertNot(guild_virtual_channel_access:is_view_only(?USER, ?CHANNEL, State1)),- ?assert(guild_virtual_channel_access:has_voice_access(?USER, ?CHANNEL, State1)).--removing_access_clears_view_only_mark_test() ->- State0 = guild_virtual_channel_access:add_view_only_access(?USER, ?CHANNEL, #{}),- State1 = guild_virtual_channel_access:add_view_only_access(?USER, ?CHANNEL + 1, State0),- State2 = guild_virtual_channel_access:remove_virtual_access(?USER, ?CHANNEL, State1),- ?assertNot(guild_virtual_channel_access:is_view_only(?USER, ?CHANNEL, State2)),- ?assert(guild_virtual_channel_access:is_view_only(?USER, ?CHANNEL + 1, State2)),- State3 = guild_virtual_channel_access:remove_virtual_access(?USER, ?CHANNEL + 1, State2),- ?assertNot(guild_virtual_channel_access:is_view_only(?USER, ?CHANNEL + 1, State3)).--channel_delete_disconnects_everyone_in_channel_test() ->- Self = self(),- VoicePid = spawn(fun() ->- receive- Message -> Self ! {voice_server_got, Message}- end- end),- State0 = (base_state(true))#{voice_server_pid => VoicePid},- _ = guild_state:update_state(- channel_delete,- #{<<"id">> => integer_to_binary(?CHANNEL), <<"type">> => 2},- State0- ),- receive- {voice_server_got, {'$gen_cast', {disconnect_all_voice_users_in_channel, Request}}} ->- ?assertEqual(#{channel_id => ?CHANNEL}, Request)- after 500 ->- exit(VoicePid, kill),- ?assert(false)- end.--voice_server_disconnects_all_users_in_channel_test() ->- Self = self(),- ForceFun = fun(GId, ChId, UId, ConnId) ->- Self ! {force_disconnect, GId, ChId, UId, ConnId},- {ok, #{success => true}}- end,- GuildPid = spawn(fun() -> guild_state_reply_loop(ForceFun) end),- State = #{- guild_id => ?GUILD,- guild_pid => GuildPid,- voice_states => #{- <<"conn-a">> => voice_state(<<"conn-a">>, 5, ?CHANNEL),- <<"conn-b">> => voice_state(<<"conn-b">>, 6, ?CHANNEL),- <<"conn-c">> => voice_state(<<"conn-c">>, 7, ?CHANNEL + 1)- },- pending_voice_connections => #{},- recently_disconnected_voice_states => #{},- e2ee_room_keys => #{}- },- try- {noreply, NewState} = guild_voice_server:handle_cast(- {disconnect_all_voice_users_in_channel, #{channel_id => ?CHANNEL}}, State- ),- ?assertEqual([<<"conn-c">>], maps:keys(maps:get(voice_states, NewState))),- Disconnected = lists:sort([receive_force_disconnect(), receive_force_disconnect()]),- ?assertEqual(- [{?GUILD, ?CHANNEL, 5, <<"conn-a">>}, {?GUILD, ?CHANNEL, 6, <<"conn-b">>}],- Disconnected- )- after- exit(GuildPid, kill)- end.--receive_force_disconnect() ->- receive- {force_disconnect, GId, ChId, UId, ConnId} -> {GId, ChId, UId, ConnId}- after 500 -> erlang:error(missing_force_disconnect)- end.--guild_state_reply_loop(ForceFun) ->- GuildState = #{- id => ?GUILD,- data => #{<<"guild">> => #{<<"owner_id">> => <<"1">>}},- sessions => #{},- test_force_disconnect_fun => ForceFun- },- receive- {'$gen_call', From, {get_voice_guild_state}} ->- gen_server:reply(From, GuildState),- guild_state_reply_loop(ForceFun);- _ ->- guild_state_reply_loop(ForceFun)- end.--voice_state(ConnId, UserId, ChannelId) ->- #{- <<"guild_id">> => integer_to_binary(?GUILD),- <<"user_id">> => integer_to_binary(UserId),- <<"channel_id">> => integer_to_binary(ChannelId),- <<"connection_id">> => ConnId- }.--base_state(WithSession) ->- ok = drain(),- Self = self(),- SyncFun = fun(GId, ChId, UId, ConnId, Perms) ->- Self ! {synced, GId, ChId, UId, ConnId, Perms}- end,- Sessions =- case WithSession of- true ->- #{- <<"sess">> => #{- session_id => <<"sess">>,- user_id => ?USER,- pid => spawn(fun sink/0),- viewable_channels => #{?CHANNEL => true}- }- };- false ->- #{}- end,- RolePerms =- constants:view_channel_permission() bor constants:connect_permission() bor- constants:speak_permission(),- #{- id => ?GUILD,- sessions => Sessions,- voice_states => #{- <<"conn">> => (voice_state(<<"conn">>, ?USER, ?CHANNEL))#{<<"deaf">> => false}- },- member_list_subscriptions => guild_member_list_subs:new(),- test_permission_sync_fun => SyncFun,- data => #{- <<"guild">> => #{<<"owner_id">> => <<"1">>},- <<"roles">> => roles(RolePerms),- <<"members">> => [- #{- <<"user">> => #{<<"id">> => integer_to_binary(?USER)},- <<"roles">> => [integer_to_binary(?ROLE)]- }- ],- <<"channels">> => [voice_channel([])]- }- }.--voice_channel(Overwrites) ->- #{- <<"id">> => integer_to_binary(?CHANNEL),- <<"type">> => 2,- <<"permission_overwrites">> => Overwrites- }.--with_overwrites(Overwrites, State) ->- Data = maps:get(data, State),- State#{data => Data#{<<"channels">> => [voice_channel(Overwrites)]}}.--with_role_permissions(Permissions, State) ->- Data = maps:get(data, State),- State#{data => Data#{<<"roles">> => roles(Permissions)}}.--roles(Permissions) ->- [- #{- <<"id">> => integer_to_binary(?ROLE),- <<"permissions">> => integer_to_binary(Permissions)- },- #{<<"id">> => integer_to_binary(?GUILD), <<"permissions">> => <<"0">>}- ].--user_deny(Deny) ->- #{- <<"id">> => integer_to_binary(?USER),- <<"type">> => 1,- <<"allow">> => <<"0">>,- <<"deny">> => integer_to_binary(Deny)- }.--channel_update_with_user_deny(Deny) ->- voice_channel([user_deny(Deny)]).--deny_overwrite_update() ->- channel_update_with_user_deny(- constants:view_channel_permission() bor constants:connect_permission()- ).--sink() ->- receive- stop -> ok;- _ -> sink()- end.--drain() ->- receive- _ -> drain()- after 0 -> ok- end.--collect_sync_messages() ->- collect_sync_messages([]).--collect_sync_messages(Acc) ->- receive- {synced, _, _, _, _, _} = Message -> collect_sync_messages([Message | Acc])- after 300 -> lists:reverse(Acc)- end.--disconnected(Messages) ->- lists:any(- fun({synced, _, _, _, _, Perms}) -> maps:get(disconnected, Perms, false) =:= true end,- Messages- ).--granted_permissions(Messages) ->- lists:any(- fun({synced, _, _, _, _, Perms}) -> maps:is_key(can_speak, Perms) end,- Messages- ).diff --git a/fluxer_gateway/test/guild_voice_broadcast_tests.erl b/fluxer_gateway/test/guild_voice_broadcast_tests.erldeleted file mode 100644index b1f2b22ac..000000000--- a/fluxer_gateway/test/guild_voice_broadcast_tests.erl+++ /dev/null@@ -1,211 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_broadcast_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--base_guild_state() ->- #{- id => 999,- data => #{<<"channels">> => [#{<<"id">> => <<"100">>, <<"type">> => 2}]},- sessions => #{- <<"s1">> => #{- pid => self(),- user_id => 11,- viewable_channels => #{100 => true}- }- },- voice_states => #{},- pending_voice_connections => #{}- }.--voice_server_state(GuildState) ->- GuildState#{guild_pid => self()}.--join_voice_state(ConnId) ->- #{- <<"user_id">> => <<"10">>,- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"connection_id">> => ConnId,- <<"self_mute">> => false,- <<"self_deaf">> => false- }.--broadcast_payload(VoiceState) ->- maps:merge(- #{- <<"session_id">> => null,- <<"member">> => null,- <<"mute">> => false,- <<"deaf">> => false,- <<"self_video">> => false,- <<"self_stream">> => false,- <<"is_mobile">> => false,- <<"suppress">> => false,- <<"viewer_stream_keys">> => [],- <<"e2ee_capable">> => false,- <<"p2p">> => false,- <<"version">> => 0- },- VoiceState- ).--pending_join(ConnId) ->- #{- user_id => 10,- guild_id => 999,- channel_id => 100,- voice_state => join_voice_state(ConnId)- }.--receive_relay() ->- receive- {'$gen_cast', {relay_voice_state_update, _, _} = RelayMsg} -> RelayMsg- after 1000 ->- error(relay_voice_state_update_not_received)- end.--pump_relay_to_guild(GuildState) ->- RelayMsg = receive_relay(),- {noreply, NewGuildState} = guild_voice_handler:handle_cast(RelayMsg, GuildState),- NewGuildState.--collect_voice_state_dispatches() ->- [decoded_voice_state(Payload) || Payload <- collect_raw_voice_state_dispatches()].--collect_raw_voice_state_dispatches() ->- receive- {'$gen_cast', {dispatch, voice_state_update, Payload}} ->- [Payload | collect_raw_voice_state_dispatches()]- after 0 ->- []- end.--decoded_voice_state({pre_encoded, Bin}) -> json:decode(Bin);-decoded_voice_state(Payload) -> Payload.--map_path_wire_bytes(VoiceState) ->- iolist_to_binary(- json:encode(guild_data_wire:payload(VoiceState), fun json:encode_value/2)- ).--confirm_join(ConnId, GuildState) ->- VoiceServerState = (voice_server_state(GuildState))#{- pending_voice_connections => #{ConnId => pending_join(ConnId)}- },- {reply, #{success := true}, _} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(- #{connection_id => ConnId}, VoiceServerState- ),- pump_relay_to_guild(GuildState).--single_join_dispatches_once_per_recipient_test() ->- GuildState = confirm_join(<<"conn1">>, base_guild_state()),- ?assertEqual(- [broadcast_payload(join_voice_state(<<"conn1">>))], collect_voice_state_dispatches()- ),- ?assertEqual(- join_voice_state(<<"conn1">>),- maps:get(<<"conn1">>, maps:get(voice_states, GuildState))- ).--relay_syncs_guild_cache_without_rebroadcast_test() ->- VS = join_voice_state(<<"conn1">>),- {noreply, NewGuildState} = guild_voice_handler:handle_cast(- {relay_voice_state_update, VS, null}, base_guild_state()- ),- ?assertEqual(VS, maps:get(<<"conn1">>, maps:get(voice_states, NewGuildState))),- ?assertEqual([], collect_voice_state_dispatches()).--mute_change_still_dispatches_test() ->- GuildState0 = confirm_join(<<"conn1">>, base_guild_state()),- ?assertEqual(- [broadcast_payload(join_voice_state(<<"conn1">>))], collect_voice_state_dispatches()- ),- MutedVS = (join_voice_state(<<"conn1">>))#{- <<"self_mute">> => true, <<"self_deaf">> => true- },- ok = guild_voice_broadcast:broadcast_voice_state_update(- MutedVS, voice_server_state(GuildState0), <<"100">>- ),- GuildState1 = pump_relay_to_guild(GuildState0),- ?assertEqual([broadcast_payload(MutedVS)], collect_voice_state_dispatches()),- ?assertEqual(MutedVS, maps:get(<<"conn1">>, maps:get(voice_states, GuildState1))).--rejoin_after_leave_still_dispatches_test() ->- GuildState0 = confirm_join(<<"conn1">>, base_guild_state()),- ?assertEqual(- [broadcast_payload(join_voice_state(<<"conn1">>))], collect_voice_state_dispatches()- ),- LeaveVS = (join_voice_state(<<"conn1">>))#{<<"channel_id">> => null},- ok = guild_voice_broadcast:broadcast_voice_state_update(- LeaveVS, voice_server_state(GuildState0), <<"100">>- ),- GuildState1 = pump_relay_to_guild(GuildState0),- ?assertEqual([broadcast_payload(LeaveVS)], collect_voice_state_dispatches()),- ?assertNot(maps:is_key(<<"conn1">>, maps:get(voice_states, GuildState1))),- GuildState2 = confirm_join(<<"conn2">>, GuildState1),- ?assertEqual(- [broadcast_payload(join_voice_state(<<"conn2">>))], collect_voice_state_dispatches()- ),- ?assertEqual(- join_voice_state(<<"conn2">>),- maps:get(<<"conn2">>, maps:get(voice_states, GuildState2))- ).--broadcast_sanitizes_routing_metadata_test() ->- VS = (join_voice_state(<<"conn1">>))#{- <<"latitude">> => <<"1.0">>,- <<"longitude">> => <<"2.0">>,- <<"region_id">> => <<"us-east">>,- <<"server_id">> => <<"voice-1">>- },- GuildState = base_guild_state(),- ok = guild_voice_broadcast:broadcast_voice_state_update(- VS, voice_server_state(GuildState), null- ),- _ = pump_relay_to_guild(GuildState),- ?assertEqual(- [broadcast_payload(join_voice_state(<<"conn1">>))], collect_voice_state_dispatches()- ).--guild_fanout_pre_encodes_identical_wire_bytes_test() ->- VS = join_voice_state(<<"conn1">>),- ?assertEqual(- {pre_encoded, map_path_wire_bytes(broadcast_payload(VS))}, dispatch_payload_for(VS)- ).--guild_fanout_payload_never_touches_dm_voice_states_test() ->- {pre_encoded, Bin} = dispatch_payload_for(join_voice_state(<<"conn1">>)),- State = #{dm_voice_states => #{}},- EventData = #{} = json:decode(Bin),- ?assertEqual(- State,- session_dispatch_guild:update_dm_voice_states_map(- voice_state_update, EventData, State- )- ).--dm_scoped_voice_state_stays_a_map_and_updates_dm_voice_states_test() ->- DmVS = (join_voice_state(<<"conn1">>))#{<<"guild_id">> => null},- Payload = dispatch_payload_for(DmVS),- ?assertEqual(broadcast_payload(DmVS), Payload),- State = session_dispatch_guild:update_dm_voice_states_map(- voice_state_update, Payload, #{dm_voice_states => #{}}- ),- #{dm_voice_states := #{<<"conn1">> := StoredVoiceState}} = State,- ?assertEqual(- broadcast_payload(DmVS),- StoredVoiceState- ).--dispatch_payload_for(VoiceState) ->- GuildState = base_guild_state(),- ok = guild_voice_broadcast:broadcast_voice_state_update(- VoiceState, voice_server_state(GuildState), null- ),- _ = pump_relay_to_guild(GuildState),- [Payload] = collect_raw_voice_state_dispatches(),- Payload.diff --git a/fluxer_gateway/test/guild_voice_connection_confirm_tests.erl b/fluxer_gateway/test/guild_voice_connection_confirm_tests.erldeleted file mode 100644index 4f4f8ed4f..000000000--- a/fluxer_gateway/test/guild_voice_connection_confirm_tests.erl+++ /dev/null@@ -1,179 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_connection_confirm_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--required_voice_perms() ->- constants:view_channel_permission() bor constants:connect_permission().--base_test_member(UserId) ->- #{<<"user">> => #{<<"id">> => integer_to_binary(UserId)}}.--base_test_channel(ChannelId) ->- #{<<"id">> => integer_to_binary(ChannelId), <<"type">> => 2, <<"user_limit">> => 0}.--base_test_state() ->- #{- id => 999,- data => #{- <<"channels">> => [base_test_channel(100)],- <<"members">> => [base_test_member(10)]- },- voice_states => #{},- test_perm_fun => fun(_) -> required_voice_perms() end- }.--confirm_voice_connection_missing_id_test() ->- State = base_test_state(),- {reply, {error, validation_error, voice_missing_connection_id}, _} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(#{}, State).--confirm_voice_connection_moves_pending_to_voice_states_test() ->- VoiceState = #{- <<"user_id">> => <<"5">>, <<"guild_id">> => <<"999">>, <<"channel_id">> => <<"100">>- },- PendingData = #{- user_id => 5, guild_id => 999, channel_id => 100, voice_state => VoiceState- },- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{<<"conn1">> => PendingData}, voice_states => #{}- }),- NewState = confirm_success(#{connection_id => <<"conn1">>}, State),- NewVoiceStates = maps:get(voice_states, NewState),- NewPending = maps:get(pending_voice_connections, NewState, #{}),- ?assert(maps:is_key(<<"conn1">>, NewVoiceStates)),- ?assertNot(maps:is_key(<<"conn1">>, NewPending)).--confirm_voice_connection_clears_pending_even_without_voice_state_test() ->- PendingData = #{user_id => 5, channel_id => 100},- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{<<"conn1">> => PendingData}, voice_states => #{}- }),- NewState = confirm_success(#{connection_id => <<"conn1">>}, State),- NewPending = maps:get(pending_voice_connections, NewState, #{}),- ?assertNot(maps:is_key(<<"conn1">>, NewPending)).--confirm_voice_connection_not_found_in_pending_test() ->- State = maps:merge(base_test_state(), #{pending_voice_connections => #{}}),- assert_not_found(#{connection_id => <<"missing">>}, State).--confirm_voice_connection_found_in_voice_states_test() ->- VoiceState = #{- <<"user_id">> => <<"5">>, <<"guild_id">> => <<"999">>, <<"channel_id">> => <<"200">>- },- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{}, voice_states => #{<<"conn1">> => VoiceState}- }),- NewState = confirm_success(#{connection_id => <<"conn1">>}, State),- NewVoiceStates = maps:get(voice_states, NewState),- ?assert(maps:is_key(<<"conn1">>, NewVoiceStates)),- ?assertEqual(VoiceState, maps:get(<<"conn1">>, NewVoiceStates)).--try_restore_from_recently_disconnected_restores_test() ->- VS = #{- <<"user_id">> => <<"5">>,- <<"guild_id">> => <<"10">>,- <<"channel_id">> => <<"20">>,- <<"connection_id">> => <<"conn">>- },- Now = erlang:system_time(millisecond),- Cache = #{<<"conn">> => #{voice_state => VS, disconnected_at => Now - 5000}},- State = #{- voice_states => #{},- recently_disconnected_voice_states => Cache,- sessions => #{},- data => #{},- id => 10- },- NewState = confirm_success(#{connection_id => <<"conn">>}, State),- NewVoiceStates = maps:get(voice_states, NewState),- ?assert(maps:is_key(<<"conn">>, NewVoiceStates)),- NewCache = maps:get(recently_disconnected_voice_states, NewState),- ?assertNot(maps:is_key(<<"conn">>, NewCache)).--try_restore_from_recently_disconnected_expired_test() ->- VS = #{- <<"user_id">> => <<"5">>,- <<"guild_id">> => <<"10">>,- <<"channel_id">> => <<"20">>,- <<"connection_id">> => <<"conn">>- },- Now = erlang:system_time(millisecond),- Cache = #{<<"conn">> => #{voice_state => VS, disconnected_at => Now - 70000}},- State = #{voice_states => #{}, recently_disconnected_voice_states => Cache, data => #{}},- assert_not_found(#{connection_id => <<"conn">>}, State).--try_restore_from_recently_disconnected_not_found_test() ->- State = #{voice_states => #{}, data => #{}},- assert_not_found(#{connection_id => <<"conn">>}, State).--confirm_voice_connection_validates_nonce_test() ->- Now = erlang:system_time(millisecond),- PendingData = pending_data_with_nonce(Now),- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{<<"conn1">> => PendingData}, voice_states => #{}- }),- {reply, {error, validation_error, voice_nonce_mismatch}, _} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(- #{connection_id => <<"conn1">>, token_nonce => <<"wrong-nonce">>}, State- ).--confirm_voice_connection_validates_expiry_test() ->- Now = erlang:system_time(millisecond),- PendingData = (pending_data_with_nonce(Now))#{- created_at => Now - 35000, expires_at => Now - 5000- },- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{<<"conn1">> => PendingData}, voice_states => #{}- }),- {reply, {error, validation_error, voice_pending_expired}, _} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(- #{connection_id => <<"conn1">>, token_nonce => <<"valid-nonce">>}, State- ).--confirm_voice_connection_accepts_valid_nonce_test() ->- Now = erlang:system_time(millisecond),- PendingData = pending_data_with_nonce(Now),- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{<<"conn1">> => PendingData}, voice_states => #{}- }),- NewState = confirm_success(- #{connection_id => <<"conn1">>, token_nonce => <<"valid-nonce">>}, State- ),- NewVoiceStates = maps:get(voice_states, NewState),- ?assert(maps:is_key(<<"conn1">>, NewVoiceStates)).--confirm_voice_connection_rejects_missing_nonce_test() ->- Now = erlang:system_time(millisecond),- PendingData = pending_data_with_nonce(Now),- State = maps:merge(base_test_state(), #{- pending_voice_connections => #{<<"conn1">> => PendingData}, voice_states => #{}- }),- {reply, {error, validation_error, voice_nonce_mismatch}, _} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(- #{connection_id => <<"conn1">>}, State- ).--pending_data_with_nonce(Now) ->- #{- user_id => 5,- guild_id => 999,- channel_id => 100,- token_nonce => <<"valid-nonce">>,- created_at => Now - 5000,- expires_at => Now + 25000,- voice_state => #{- <<"user_id">> => <<"5">>, <<"guild_id">> => <<"999">>, <<"channel_id">> => <<"100">>- }- }.--confirm_success(Data, State) ->- {reply, #{success := true}, NewState} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(Data, State),- NewState.--assert_not_found(Data, State) ->- {reply, {error, not_found, voice_connection_not_found}, _} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(Data, State).diff --git a/fluxer_gateway/test/guild_voice_connection_pending_tests.erl b/fluxer_gateway/test/guild_voice_connection_pending_tests.erldeleted file mode 100644index 6ebc9fc0c..000000000--- a/fluxer_gateway/test/guild_voice_connection_pending_tests.erl+++ /dev/null@@ -1,300 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_connection_pending_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--required_voice_perms() ->- constants:view_channel_permission() bor constants:connect_permission().--base_test_member(UserId) ->- #{<<"user">> => #{<<"id">> => integer_to_binary(UserId)}}.--base_test_channel(ChannelId) ->- #{<<"id">> => integer_to_binary(ChannelId), <<"type">> => 2, <<"user_limit">> => 0}.--base_test_state() ->- #{- id => 999,- data => #{- <<"channels">> => [base_test_channel(100)],- <<"members">> => [base_test_member(10)]- },- voice_states => #{},- test_perm_fun => fun(_) -> required_voice_perms() end- }.--sweep_expired_pending_joins_removes_expired_test() ->- Now = erlang:system_time(millisecond),- Expired = #{user_id => 10, guild_id => 999, channel_id => 100, expires_at => Now - 1000},- Valid = #{user_id => 11, guild_id => 999, channel_id => 101, expires_at => Now + 25000},- PendingConnections = #{<<"expired-conn">> => Expired, <<"valid-conn">> => Valid},- State = maps:put(pending_voice_connections, PendingConnections, base_test_state()),- NewState = guild_voice_connection_pending:sweep_expired_pending_joins(State),- NewPending = maps:get(pending_voice_connections, NewState, #{}),- ?assertNot(maps:is_key(<<"expired-conn">>, NewPending)),- ?assert(maps:is_key(<<"valid-conn">>, NewPending)).--sweep_expired_pending_joins_keeps_valid_test() ->- Now = erlang:system_time(millisecond),- V1 = #{user_id => 10, guild_id => 999, channel_id => 100, expires_at => Now + 25000},- V2 = #{user_id => 11, guild_id => 999, channel_id => 101, expires_at => Now + 30000},- PendingConnections = #{<<"conn-1">> => V1, <<"conn-2">> => V2},- State = maps:put(pending_voice_connections, PendingConnections, base_test_state()),- NewState = guild_voice_connection_pending:sweep_expired_pending_joins(State),- NewPending = maps:get(pending_voice_connections, NewState, #{}),- ?assertEqual(2, maps:size(NewPending)),- ?assert(maps:is_key(<<"conn-1">>, NewPending)),- ?assert(maps:is_key(<<"conn-2">>, NewPending)).--sweep_expired_pending_joins_clears_virtual_access_test() ->- Now = erlang:system_time(millisecond),- ExpiredMetadata = #{- user_id => 10, guild_id => 999, channel_id => 100, expires_at => Now - 1000- },- PendingConnections = #{<<"expired-conn">> => ExpiredMetadata},- State = maps:put(pending_voice_connections, PendingConnections, base_test_state()),- State1 = guild_virtual_channel_access:mark_pending_join(10, 100, State),- State2 = guild_virtual_channel_access:mark_preserve(10, 100, State1),- State3 = guild_virtual_channel_access:mark_move_pending(10, 100, State2),- ?assert(guild_virtual_channel_access:is_pending_join(10, 100, State3)),- ?assert(guild_virtual_channel_access:has_preserve(10, 100, State3)),- ?assert(guild_virtual_channel_access:is_move_pending(10, 100, State3)),- NewState = guild_voice_connection_pending:sweep_expired_pending_joins(State3),- ?assertNot(guild_virtual_channel_access:is_pending_join(10, 100, NewState)),- ?assertNot(guild_virtual_channel_access:has_preserve(10, 100, NewState)),- ?assertNot(guild_virtual_channel_access:is_move_pending(10, 100, NewState)).--sweep_expired_pending_joins_empty_map_test() ->- State = maps:put(pending_voice_connections, #{}, base_test_state()),- NewState = guild_voice_connection_pending:sweep_expired_pending_joins(State),- NewPending = maps:get(pending_voice_connections, NewState, #{}),- ?assertEqual(0, maps:size(NewPending)).--sweep_expired_pending_joins_missing_user_id_test() ->- Now = erlang:system_time(millisecond),- InvalidMetadata = #{guild_id => 999, channel_id => 100, expires_at => Now - 1000},- PendingConnections = #{<<"invalid-conn">> => InvalidMetadata},- State = maps:put(pending_voice_connections, PendingConnections, base_test_state()),- NewState = guild_voice_connection_pending:sweep_expired_pending_joins(State),- NewPending = maps:get(pending_voice_connections, NewState, #{}),- ?assertNot(maps:is_key(<<"invalid-conn">>, NewPending)).--build_context_normalizes_fields_test() ->- Request = #{- user_id => <<"42">>,- channel_id => <<"99">>,- connection_id => <<"conn">>,- self_mute => true,- self_deaf => <<"nope">>,- self_video => true,- self_stream => false,- is_mobile => <<"yes">>- },- Context = guild_voice_connection_util:build_context(Request),- ?assertEqual(42, maps:get(user_id, Context)),- ?assertEqual(99, maps:get(channel_id, Context)),- ?assertEqual(<<"conn">>, maps:get(connection_id, Context)),- ?assertEqual(true, maps:get(self_mute, Context)),- ?assertEqual(false, maps:get(self_deaf, Context)),- ?assertEqual(true, maps:get(self_video, Context)),- ?assertEqual(false, maps:get(self_stream, Context)),- ?assertEqual(false, maps:get(is_mobile, Context)).--build_context_normalizes_null_connection_id_test() ->- Context = guild_voice_connection_util:build_context(#{- user_id => 42,- channel_id => null,- connection_id => null- }),- ?assertEqual(undefined, maps:get(connection_id, Context)),- ?assertNot(maps:is_key(raw_connection_id, Context)).--build_context_does_not_accept_zero_ids_test() ->- Context = guild_voice_connection_util:build_context(#{- user_id => 0,- channel_id => <<"0">>- }),- ?assertEqual(undefined, maps:get(user_id, Context)),- ?assertEqual(undefined, maps:get(channel_id, Context)).--build_context_does_not_accept_leading_zero_ids_test() ->- Context = guild_voice_connection_util:build_context(#{- user_id => <<"042">>,- channel_id => <<"099">>- }),- ?assertEqual(undefined, maps:get(user_id, Context)),- ?assertEqual(undefined, maps:get(channel_id, Context)).--resolve_guild_identity_prefers_data_test() ->- State = #{- id => 7, data => #{<<"id">> => <<"555">>, <<"guild">> => #{<<"id">> => <<"111">>}}- },- ?assertMatch(- {ok, 555, <<"555">>}, guild_voice_connection_util:resolve_guild_identity(State)- ).--resolve_guild_identity_does_not_use_zero_state_id_test() ->- ?assertEqual(- {error, voice_guild_id_missing},- guild_voice_connection_util:resolve_guild_identity(#{id => 0, data => #{}})- ),- ?assertEqual(- {error, voice_guild_id_missing},- guild_voice_connection_util:resolve_guild_identity(#{id => <<"007">>, data => #{}})- ).--resolve_voice_state_from_pending_uses_stored_voice_state_test() ->- VoiceState = #{- <<"user_id">> => <<"5">>, <<"guild_id">> => <<"999">>, <<"channel_id">> => <<"100">>- },- PendingData = #{- user_id => 5, guild_id => 999, channel_id => 100, voice_state => VoiceState- },- State = base_test_state(),- Result = guild_voice_connection_pending:resolve_voice_state_from_pending(- <<"conn1">>, PendingData, State, #{}- ),- ?assertEqual(VoiceState, Result).--resolve_voice_state_from_pending_prefers_existing_voice_state_test() ->- ExistingVoiceState = #{- <<"user_id">> => <<"5">>,- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"existing">> => true- },- PendingVoiceState = #{- <<"user_id">> => <<"5">>,- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"existing">> => false- },- PendingData = #{user_id => 5, voice_state => PendingVoiceState},- VoiceStates = #{<<"conn1">> => ExistingVoiceState},- State = base_test_state(),- Result = guild_voice_connection_pending:resolve_voice_state_from_pending(- <<"conn1">>, PendingData, State, VoiceStates- ),- ?assertEqual(ExistingVoiceState, Result).--resolve_voice_state_from_pending_rejects_zero_pending_ids_test() ->- Result = guild_voice_connection_pending:resolve_voice_state_from_pending(- <<"conn1">>, #{user_id => 0, guild_id => 999, channel_id => 100}, base_test_state(), #{}- ),- ?assertEqual(undefined, Result).--resolve_voice_state_from_pending_rejects_leading_zero_pending_ids_test() ->- Result = guild_voice_connection_pending:resolve_voice_state_from_pending(- <<"conn1">>,- #{user_id => <<"05">>, guild_id => 999, channel_id => 100},- base_test_state(),- #{}- ),- ?assertEqual(undefined, Result).--validate_pending_nonce_valid_test() ->- Now = erlang:system_time(millisecond),- PendingData = #{- token_nonce => <<"abc123">>, created_at => Now - 5000, expires_at => Now + 25000- },- ?assertEqual(- ok,- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- <<"abc123">>, PendingData- )- ).--validate_pending_nonce_mismatch_test() ->- Now = erlang:system_time(millisecond),- PendingData = #{- token_nonce => <<"abc123">>, created_at => Now - 5000, expires_at => Now + 25000- },- ?assertEqual(- {error, voice_nonce_mismatch},- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- <<"wrong-nonce">>, PendingData- )- ).--validate_pending_nonce_missing_request_nonce_test() ->- Now = erlang:system_time(millisecond),- PendingData = #{- token_nonce => <<"abc123">>, created_at => Now - 5000, expires_at => Now + 25000- },- ?assertEqual(- {error, voice_nonce_mismatch},- guild_voice_connection_pending:validate_pending_nonce_and_expiry(undefined, PendingData)- ).--validate_pending_nonce_expired_test() ->- Now = erlang:system_time(millisecond),- PendingData = #{- token_nonce => <<"abc123">>, created_at => Now - 35000, expires_at => Now - 5000- },- ?assertEqual(- {error, voice_pending_expired},- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- <<"abc123">>, PendingData- )- ).--validate_pending_nonce_missing_expires_at_test() ->- PendingData = #{token_nonce => <<"abc123">>},- ?assertEqual(- ok,- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- <<"abc123">>, PendingData- )- ).--check_pending_expiry_rejects_entry_without_any_timing_test() ->- PendingData = #{- user_id => 10,- guild_id => 999,- channel_id => 100,- token_nonce => <<"abc123">>- },- PendingConnections = #{<<"conn-no-times">> => PendingData},- State = (base_test_state())#{pending_voice_connections => PendingConnections},- Result = guild_voice_connection_pending:maybe_restore_pending_connection(- <<"conn-no-times">>, 100, 10, #{}, State- ),- ?assertEqual({error, voice_pending_expired}, Result).--check_pending_expiry_accepts_entry_with_recent_joined_at_test() ->- Now = erlang:system_time(millisecond),- PendingData = #{- user_id => 10,- guild_id => 999,- channel_id => 100,- joined_at => Now - 1000- },- PendingConnections = #{<<"conn-joined">> => PendingData},- State = (base_test_state())#{- pending_voice_connections => PendingConnections,- voice_states => #{}- },- Result = guild_voice_connection_pending:maybe_restore_pending_connection(- <<"conn-joined">>, 100, 10, #{}, State- ),- ?assertNotEqual({error, voice_pending_expired}, Result).--check_pending_expiry_rejects_ancient_joined_at_test() ->- Now = erlang:system_time(millisecond),- PendingData = #{- user_id => 10,- guild_id => 999,- channel_id => 100,- joined_at => Now - 400000- },- PendingConnections = #{<<"conn-old">> => PendingData},- State = (base_test_state())#{- pending_voice_connections => PendingConnections,- voice_states => #{}- },- Result = guild_voice_connection_pending:maybe_restore_pending_connection(- <<"conn-old">>, 100, 10, #{}, State- ),- ?assertEqual({error, voice_pending_expired}, Result).diff --git a/fluxer_gateway/test/guild_voice_connection_tests.erl b/fluxer_gateway/test/guild_voice_connection_tests.erldeleted file mode 100644index d649277b1..000000000--- a/fluxer_gateway/test/guild_voice_connection_tests.erl+++ /dev/null@@ -1,458 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_connection_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--required_voice_perms() ->- constants:view_channel_permission() bor constants:connect_permission().--base_test_member(UserId) ->- #{<<"user">> => #{<<"id">> => integer_to_binary(UserId)}}.--base_test_channel(ChannelId) ->- #{<<"id">> => integer_to_binary(ChannelId), <<"type">> => 2, <<"user_limit">> => 0}.--base_test_state() ->- #{- id => 999,- data => #{- <<"channels">> => [base_test_channel(100)],- <<"members">> => [base_test_member(10)]- },- voice_states => #{},- test_perm_fun => fun(_) -> required_voice_perms() end- }.--replace_channels(State, Channels) ->- Data0 = maps:get(data, State, #{}),- maps:put(data, maps:put(<<"channels">>, Channels, Data0), State).--replace_guild_id(State, GuildIdValue) ->- Data0 = maps:get(data, State, #{}),- maps:put(data, maps:put(<<"id">>, GuildIdValue, Data0), State).--replace_guild_meta_id(State, GuildIdValue) ->- Data0 = maps:get(data, State, #{}),- Guild0 = maps:get(<<"guild">>, Data0, #{}),- Guild1 = maps:put(<<"id">>, GuildIdValue, Guild0),- maps:put(data, maps:put(<<"guild">>, Guild1, Data0), State).--voice_state_update_invalid_user_id_test() ->- {reply, {error, validation_error, voice_invalid_user_id}, _} =- guild_voice_connection:voice_state_update(#{channel_id => null}, #{}).--voice_state_update_member_not_found_test() ->- State = base_test_state(),- {reply, {error, not_found, voice_member_not_found}, _} =- guild_voice_connection:voice_state_update(#{user_id => 99, channel_id => null}, State).--voice_state_update_invalid_channel_id_test() ->- State = base_test_state(),- {reply, {error, validation_error, voice_invalid_channel_id}, _} =- guild_voice_connection:voice_state_update(- #{user_id => 10, channel_id => undefined}, State- ).--voice_state_update_guild_leave_null_connection_id_test() ->- State = connected_state(<<"10">>),- {reply, {error, validation_error, voice_missing_connection_id}, NewState} =- guild_voice_connection:voice_state_update(- #{user_id => 10, channel_id => null, connection_id => null}, State- ),- ?assertEqual(connected_voice_states(<<"10">>), maps:get(voice_states, NewState)).--voice_state_update_guild_leave_omitted_connection_id_test() ->- State = connected_state(<<"10">>),- {reply, {error, validation_error, voice_missing_connection_id}, NewState} =- guild_voice_connection:voice_state_update(- #{user_id => 10, channel_id => null}, State- ),- ?assertEqual(connected_voice_states(<<"10">>), maps:get(voice_states, NewState)).--voice_state_update_session_teardown_removes_that_sessions_states_test() ->- State = session_scoped_state(),- {reply, #{success := true}, NewState} =- guild_voice_connection:voice_state_update(- #{- user_id => 10,- channel_id => null,- connection_id => null,- session_id => <<"sess-a">>- },- State- ),- Remaining = maps:get(voice_states, NewState),- ?assertNot(maps:is_key(<<"conn-a">>, Remaining)),- ?assert(maps:is_key(<<"conn-b">>, Remaining)),- ?assert(maps:is_key(<<"conn-c">>, Remaining)).--voice_state_update_session_teardown_works_for_former_members_test() ->- State = maps:put(- data,- #{<<"channels">> => [base_test_channel(100)], <<"members">> => []},- session_scoped_state()- ),- {reply, #{success := true}, NewState} =- guild_voice_connection:voice_state_update(- #{- user_id => 10,- channel_id => null,- connection_id => null,- session_id => <<"sess-a">>- },- State- ),- ?assertNot(maps:is_key(<<"conn-a">>, maps:get(voice_states, NewState))).--voice_state_update_leave_by_connection_works_for_former_members_test() ->- State = maps:put(- data,- #{<<"channels">> => [base_test_channel(100)], <<"members">> => []},- session_scoped_state()- ),- {reply, #{success := true}, NewState} =- guild_voice_connection:voice_state_update(- #{user_id => 10, channel_id => null, connection_id => <<"conn-b">>}, State- ),- ?assertNot(maps:is_key(<<"conn-b">>, maps:get(voice_states, NewState))).--voice_state_update_guild_leave_blank_connection_id_test() ->- State = connected_state(<<"10">>),- assert_voice_state_update_error(- #{user_id => 10, channel_id => null, connection_id => <<>>},- State,- {error, validation_error, voice_missing_connection_id}- ).--voice_state_update_channel_not_found_test() ->- State = replace_channels(base_test_state(), []),- {reply, {error, not_found, voice_channel_not_found}, _} =- guild_voice_connection:voice_state_update(#{user_id => 10, channel_id => 999}, State).--voice_state_update_connection_not_found_test() ->- State = base_test_state(),- Request = #{user_id => 10, channel_id => 100, connection_id => <<"missing-conn">>},- assert_voice_state_update_error(- Request, State, {error, not_found, voice_connection_not_found}- ).--voice_state_update_invalid_viewer_stream_keys_test() ->- State = connected_state(<<"10">>),- Request = #{- user_id => 10,- channel_id => 100,- connection_id => <<"conn-1">>,- viewer_stream_keys => 123- },- assert_voice_state_update_error(- Request, State, {error, validation_error, voice_invalid_state}- ).--voice_state_update_viewer_stream_keys_missing_connection_test() ->- State = connected_state(<<"10">>),- Request = #{- user_id => 10,- channel_id => 100,- connection_id => <<"conn-1">>,- viewer_stream_keys => [<<"999:100:missing-conn">>]- },- assert_voice_state_update_error(- Request, State, {error, not_found, voice_connection_not_found}- ).--voice_state_update_rejects_dm_scope_viewer_stream_key_test() ->- VoiceStates = #{- <<"conn-1">> => connected_voice_state(<<"conn-1">>, <<"10">>, 100, []),- <<"conn-stream">> => connected_voice_state(<<"conn-stream">>, <<"20">>, 100, [])- },- State = maps:put(voice_states, VoiceStates, base_test_state()),- Request = #{- user_id => 10,- channel_id => 100,- connection_id => <<"conn-1">>,- viewer_stream_keys => [<<"dm:100:conn-stream">>]- },- assert_voice_state_update_error(- Request, State, {error, validation_error, voice_invalid_state}- ).--voice_state_update_guild_id_missing_test() ->- State0 = base_test_state(),- State1 = replace_guild_id(State0, undefined),- State2 = replace_guild_meta_id(State1, undefined),- State = maps:remove(id, State2),- Request = #{user_id => 10, channel_id => 100},- {reply, {error, validation_error, voice_guild_id_missing}, _} =- guild_voice_connection:voice_state_update(Request, State).--voice_state_update_invalid_guild_id_test() ->- State0 = base_test_state(),- State1 = replace_guild_id(State0, <<"nope">>),- State2 = replace_guild_meta_id(State1, <<"nope">>),- State = maps:put(id, undefined, State2),- Request = #{user_id => 10, channel_id => 100},- {reply, {error, validation_error, voice_invalid_guild_id}, _} =- guild_voice_connection:voice_state_update(Request, State).--voice_state_update_connection_user_mismatch_test() ->- VoiceStates = connected_voice_states(<<"20">>),- State = maps:put(voice_states, VoiceStates, base_test_state()),- Request = #{user_id => 10, channel_id => 100, connection_id => <<"conn-1">>},- {reply, {error, validation_error, voice_user_mismatch}, _} =- guild_voice_connection:voice_state_update(Request, State).--voice_state_update_connection_owner_match_proceeds_test() ->- VoiceStates = connected_voice_states(<<"10">>),- State = maps:put(voice_states, VoiceStates, base_test_state()),- Request = #{user_id => 10, channel_id => 100, connection_id => <<"conn-1">>},- case guild_voice_connection:voice_state_update(Request, State) of- {reply, {error, validation_error, voice_user_mismatch}, _} ->- error(should_not_get_user_mismatch);- {reply, _, _} ->- ok- end.--voice_state_update_preserves_and_clears_viewer_keys_test() ->- StreamKey = <<"999:100:conn-stream">>,- VoiceStates = #{- <<"conn-1">> => connected_voice_state(<<"conn-1">>, <<"10">>, 100, []),- <<"conn-stream">> => connected_voice_state(<<"conn-stream">>, <<"20">>, 100, [])- },- State0 = maps:put(voice_states, VoiceStates, base_test_state()),- {reply, #{success := true}, State1} = guild_voice_connection:voice_state_update(- update_request(#{viewer_stream_keys => [StreamKey]}), State0- ),- ?assertEqual([StreamKey], viewer_keys(State1)),- {reply, #{success := true}, State2} = guild_voice_connection:voice_state_update(- update_request(#{self_mute => true}), State1- ),- ?assertEqual(true, maps:get(<<"self_mute">>, updated_voice_state(State2))),- ?assertEqual([StreamKey], viewer_keys(State2)),- {reply, #{success := true}, State3} = guild_voice_connection:voice_state_update(- update_request(#{viewer_stream_keys => null}), State2- ),- ?assertEqual([], viewer_keys(State3)).--voice_state_update_stress_many_watch_unwatch_updates_test() ->- StreamKey = <<"999:100:conn-stream">>,- VoiceStates = #{- <<"conn-1">> => connected_voice_state(<<"conn-1">>, <<"10">>, 100, []),- <<"conn-stream">> => connected_voice_state(<<"conn-stream">>, <<"20">>, 100, [])- },- InitialState = maps:put(voice_states, VoiceStates, base_test_state()),- FinalState = lists:foldl(- fun(Index, State) ->- Keys =- case Index rem 4 of- 0 -> [];- _ -> [StreamKey]- end,- SelfDeaf = Index rem 5 =:= 0,- {reply, #{success := true}, NextState} = guild_voice_connection:voice_state_update(- update_request(#{self_deaf => SelfDeaf, viewer_stream_keys => Keys}), State- ),- Updated = updated_voice_state(NextState),- ?assertEqual(SelfDeaf, maps:get(<<"self_deaf">>, Updated)),- ?assertEqual(Keys, maps:get(<<"viewer_stream_keys">>, Updated)),- NextState- end,- InitialState,- lists:seq(1, 80)- ),- ?assertMatch(#{<<"conn-1">> := #{}}, maps:get(voice_states, FinalState)).--voice_state_update_clears_self_stream_without_stream_permission_test() ->- State = connected_state(<<"10">>),- {reply, #{success := true}, NewState} = guild_voice_connection:voice_state_update(- update_request(#{self_stream => true, self_video => true}), State- ),- Updated = updated_voice_state(NewState),- ?assertEqual(false, maps:get(<<"self_stream">>, Updated)),- ?assertEqual(false, maps:get(<<"self_video">>, Updated)).--voice_state_update_keeps_self_stream_with_stream_permission_test() ->- State = maps:put(- voice_states,- connected_voice_states(<<"10">>),- with_stream_permission(base_test_state())- ),- {reply, #{success := true}, NewState} = guild_voice_connection:voice_state_update(- update_request(#{self_stream => true, self_video => true}), State- ),- Updated = updated_voice_state(NewState),- ?assertEqual(true, maps:get(<<"self_stream">>, Updated)),- ?assertEqual(true, maps:get(<<"self_video">>, Updated)).--voice_state_update_allows_twenty_fifth_camera_sharer_test() ->- State = camera_state(24),- {reply, #{success := true}, NewState} = guild_voice_connection:voice_state_update(- update_request(#{self_video => true}), State- ),- ?assertEqual(true, maps:get(<<"self_video">>, updated_voice_state(NewState))).--voice_state_update_blocks_twenty_sixth_camera_sharer_test() ->- State = camera_state(25),- assert_voice_state_update_error(- update_request(#{self_video => true}),- State,- {error, permission_denied, voice_camera_user_limit}- ).--voice_state_update_camera_off_users_do_not_count_toward_camera_limit_test() ->- CameraOff = maps:from_list([- {camera_off_conn_id(N), camera_voice_state(camera_off_conn_id(N), 300 + N, false)}- || N <- lists:seq(1, 25)- ]),- VoiceStates = maps:merge(camera_test_voice_states(24), CameraOff),- State = maps:put(voice_states, VoiceStates, camera_base_state(24)),- {reply, #{success := true}, NewState} = guild_voice_connection:voice_state_update(- update_request(#{self_video => true}), State- ),- ?assertEqual(true, maps:get(<<"self_video">>, updated_voice_state(NewState))).--voice_state_update_same_user_second_connection_does_not_change_camera_count_test() ->- VoiceStates = maps:put(- <<"conn-1b">>,- camera_voice_state(<<"conn-1b">>, 10, true),- camera_test_voice_states(24)- ),- State = maps:put(voice_states, VoiceStates, camera_base_state(24)),- {reply, #{success := true}, NewState} = guild_voice_connection:voice_state_update(- update_request(#{self_video => true}), State- ),- ?assertEqual(true, maps:get(<<"self_video">>, updated_voice_state(NewState))).--voice_state_update_camera_off_frees_slot_for_other_user_test() ->- State0 = camera_state(25),- assert_voice_state_update_error(- update_request(#{self_video => true}),- State0,- {error, permission_denied, voice_camera_user_limit}- ),- {reply, #{success := true}, State1} = guild_voice_connection:voice_state_update(- update_request(#{- user_id => 201, connection_id => camera_conn_id(1), self_video => false- }),- State0- ),- {reply, #{success := true}, State2} = guild_voice_connection:voice_state_update(- update_request(#{self_video => true}), State1- ),- ?assertEqual(true, maps:get(<<"self_video">>, updated_voice_state(State2))).--camera_conn_id(N) ->- <<"camera-conn-", (integer_to_binary(N))/binary>>.--camera_off_conn_id(N) ->- <<"camera-off-conn-", (integer_to_binary(N))/binary>>.--camera_voice_state(ConnId, UserId, SelfVideo) ->- (connected_voice_state(ConnId, integer_to_binary(UserId), 100, []))#{- <<"self_video">> => SelfVideo- }.--camera_test_voice_states(SharerCount) ->- Sharers = maps:from_list([- {camera_conn_id(N), camera_voice_state(camera_conn_id(N), 200 + N, true)}- || N <- lists:seq(1, SharerCount)- ]),- maps:put(<<"conn-1">>, camera_voice_state(<<"conn-1">>, 10, false), Sharers).--camera_base_state(SharerCount) ->- Members = [- base_test_member(10) | [base_test_member(200 + N) || N <- lists:seq(1, SharerCount)]- ],- State = with_stream_permission(base_test_state()),- Data0 = maps:get(data, State, #{}),- maps:put(data, maps:put(<<"members">>, Members, Data0), State).--with_stream_permission(State) ->- Roles = [- #{- <<"id">> => <<"999">>,- <<"permissions">> => integer_to_binary(constants:stream_permission())- }- ],- Data0 = maps:get(data, State, #{}),- maps:put(data, maps:put(<<"roles">>, Roles, Data0), State).--camera_state(SharerCount) ->- maps:put(- voice_states, camera_test_voice_states(SharerCount), camera_base_state(SharerCount)- ).--connected_voice_states(UserId) ->- #{- <<"conn-1">> => #{- <<"guild_id">> => <<"999">>, <<"channel_id">> => <<"100">>, <<"user_id">> => UserId- }- }.--connected_state(UserId) ->- maps:put(voice_states, connected_voice_states(UserId), base_test_state()).--session_scoped_state() ->- VoiceStates = #{- <<"conn-a">> => #{- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"user_id">> => <<"10">>,- <<"session_id">> => <<"sess-a">>- },- <<"conn-b">> => #{- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"user_id">> => <<"10">>,- <<"session_id">> => <<"sess-b">>- },- <<"conn-c">> => #{- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"user_id">> => <<"11">>,- <<"session_id">> => <<"sess-a">>- }- },- (base_test_state())#{- voice_states => VoiceStates,- test_force_disconnect_fun => fun(_, _, _, _) -> {ok, #{success => true}} end- }.--connected_voice_state(ConnectionId, UserId, ChannelId, ViewerKeys) ->- #{- <<"connection_id">> => ConnectionId,- <<"channel_id">> => integer_to_binary(ChannelId),- <<"user_id">> => UserId,- <<"version">> => 0,- <<"self_mute">> => false,- <<"self_deaf">> => false,- <<"self_video">> => false,- <<"self_stream">> => false,- <<"is_mobile">> => false,- <<"viewer_stream_keys">> => ViewerKeys- }.--update_request(Overrides) ->- maps:merge(- #{- user_id => 10,- channel_id => 100,- connection_id => <<"conn-1">>,- self_mute => false,- self_deaf => false,- self_video => false,- self_stream => false,- is_mobile => false- },- Overrides- ).--updated_voice_state(State) ->- maps:get(<<"conn-1">>, maps:get(voice_states, State)).--viewer_keys(State) ->- maps:get(<<"viewer_stream_keys">>, updated_voice_state(State)).--assert_voice_state_update_error(Request, State, Error) ->- {reply, Error, _} = guild_voice_connection:voice_state_update(Request, State).diff --git a/fluxer_gateway/test/guild_voice_move_tests.erl b/fluxer_gateway/test/guild_voice_move_tests.erldeleted file mode 100644index 81629c7f2..000000000--- a/fluxer_gateway/test/guild_voice_move_tests.erl+++ /dev/null@@ -1,491 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_move_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--token_rpc_data() ->- #{- <<"token">> => <<"tok">>,- <<"endpoint">> => <<"wss://voice.example">>,- <<"connectionId">> => <<"new-conn">>,- <<"regionId">> => <<"us-east">>,- <<"serverId">> => <<"voice-1">>- }.--test_member(UserId) ->- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"mute">> => false,- <<"deaf">> => false- }.--existing_voice_state(ConnId, UserId, ChannelIdBin) ->- #{- <<"user_id">> => integer_to_binary(UserId),- <<"guild_id">> => <<"999">>,- <<"channel_id">> => ChannelIdBin,- <<"connection_id">> => ConnId,- <<"session_id">> => <<"sess1">>,- <<"self_mute">> => false,- <<"self_deaf">> => true,- <<"self_video">> => false,- <<"self_stream">> => false,- <<"is_mobile">> => false,- <<"suppress">> => false,- <<"mute">> => false,- <<"deaf">> => false,- <<"viewer_stream_keys">> => [],- <<"e2ee_capable">> => false,- <<"member">> => test_member(UserId),- <<"version">> => 3- }.--base_move_state(VoiceStates) ->- #{- id => 999,- data => #{- <<"id">> => <<"999">>,- <<"guild">> => #{<<"owner_id">> => <<"10">>},- <<"channels">> => [- #{<<"id">> => <<"100">>, <<"type">> => 2},- #{<<"id">> => <<"200">>, <<"type">> => 2}- ],- <<"members">> => [test_member(10)]- },- sessions => #{},- voice_states => VoiceStates,- pending_voice_connections => #{}- }.--move_context() ->- #{- user_id => 10,- session_id => <<"sess1">>,- connection_id => <<"old-conn">>,- self_mute => false,- self_deaf => true,- self_video => false,- self_stream => false,- is_mobile => false,- viewer_stream_keys => undefined,- latitude => <<"1.0">>,- longitude => <<"2.0">>,- e2ee_capable => false,- bot => false- }.--with_token_rpc(Result, Fun) ->- drain_stale_dispatches(),- meck:new(rpc_client, [passthrough, no_link, non_strict]),- meck:expect(rpc_client, call, fun(_Request) -> Result end),- try- Fun()- after- meck:unload(rpc_client)- end.--with_guild_voice_server_stub(Fun) ->- meck:new(guild_voice_server, [passthrough, no_link]),- meck:expect(guild_voice_server, resolve, fun(_GuildId, GuildPid) -> GuildPid end),- try- Fun()- after- meck:unload(guild_voice_server)- end.--drain_stale_dispatches() ->- receive- {'$gen_cast', {dispatch, _Event, _Payload}} ->- drain_stale_dispatches()- after 0 ->- ok- end.--assert_no_dispatch() ->- receive- {'$gen_cast', {dispatch, Event, Payload}} ->- ?assert(false, {unexpected_dispatch, Event, Payload})- after 50 ->- ok- end.--reply_map(Reply) when is_map(Reply) -> Reply.--run_client_move(VoiceStates, State) ->- {reply, Reply, NewState} = guild_voice_connection_move:handle_client_channel_move(- move_context(), 200, test_member(10), <<"old-conn">>, VoiceStates, State- ),- {Reply, NewState}.--client_move_token_failure_preserves_connection_test() ->- with_token_rpc({error, timeout}, fun client_move_token_failure_scenario/0).--client_move_token_failure_scenario() ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = base_move_state(VoiceStates),- {Error, NewState} = run_client_move(VoiceStates, State),- ?assertMatch({error, _, voice_token_failed}, Error),- ?assertEqual(- ExistingVS,- maps:get(<<"old-conn">>, maps:get(voice_states, NewState))- ),- ?assertEqual(#{}, maps:get(pending_voice_connections, NewState)),- assert_no_dispatch().--client_move_success_disconnects_and_stores_pending_test() ->- with_token_rpc({ok, token_rpc_data()}, fun client_move_success_scenario/0).--client_move_success_scenario() ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = base_move_state(VoiceStates),- {Reply0, NewState} = run_client_move(VoiceStates, State),- Reply = reply_map(Reply0),- ?assertEqual(true, maps:get(success, Reply)),- ?assertEqual(true, maps:get(needs_token, Reply)),- ?assertEqual(<<"tok">>, maps:get(token, Reply)),- ?assertEqual(<<"new-conn">>, maps:get(connection_id, Reply)),- ?assertNot(maps:is_key(<<"old-conn">>, maps:get(voice_states, NewState))),- Pending = maps:get(pending_voice_connections, NewState),- ?assert(maps:is_key(<<"new-conn">>, Pending)),- Meta = maps:get(<<"new-conn">>, Pending),- ?assert(is_binary(maps:get(token_nonce, Meta))),- ?assert(maps:get(expires_at, Meta) > maps:get(created_at, Meta)),- ?assertEqual(- ok,- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- maps:get(token_nonce, Meta), Meta- )- ).--client_move_reply_voice_state_is_complete_and_coordinate_free_test() ->- with_token_rpc({ok, token_rpc_data()}, fun client_move_reply_shape_scenario/0).--client_move_reply_shape_scenario() ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = base_move_state(VoiceStates),- {Reply0, NewState} = run_client_move(VoiceStates, State),- Reply = reply_map(Reply0),- ReplyVS = maps:get(voice_state, Reply),- ?assertNot(maps:is_key(<<"latitude">>, ReplyVS)),- ?assertNot(maps:is_key(<<"longitude">>, ReplyVS)),- ?assertEqual(<<"200">>, maps:get(<<"channel_id">>, ReplyVS)),- ?assertEqual(<<"new-conn">>, maps:get(<<"connection_id">>, ReplyVS)),- ?assertEqual(true, maps:get(<<"self_deaf">>, ReplyVS)),- assert_complete_voice_state_fields(ReplyVS),- PendingVS = maps:get(- voice_state, maps:get(<<"new-conn">>, maps:get(pending_voice_connections, NewState))- ),- ?assertEqual(<<"1.0">>, maps:get(<<"latitude">>, PendingVS)).--assert_complete_voice_state_fields(VS) ->- Fields = [- <<"member">>,- <<"mute">>,- <<"deaf">>,- <<"suppress">>,- <<"viewer_stream_keys">>,- <<"e2ee_capable">>,- <<"version">>,- <<"session_id">>- ],- lists:foreach(fun(Field) -> ?assert(maps:is_key(Field, VS), {missing, Field}) end, Fields).--moderator_move_reply_includes_session_data_test() ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = base_move_state(VoiceStates),- {reply, Reply0, NewState} = guild_voice_move_execute:handle_move(- #{<<"old-conn">> => ExistingVS}, 200, 10, 10, <<"old-conn">>, VoiceStates, State- ),- Reply = reply_map(Reply0),- ?assertEqual(true, maps:get(success, Reply)),- ?assertEqual(true, maps:get(needs_token, Reply)),- [SessionInfo] = maps:get(session_data, Reply),- ?assertEqual(<<"old-conn">>, maps:get(connection_id, SessionInfo)),- ?assertEqual(<<"sess1">>, maps:get(session_id, SessionInfo)),- ?assertEqual(true, maps:get(self_deaf, SessionInfo)),- ?assertEqual(false, maps:get(e2ee_capable, SessionInfo)),- ?assertNot(maps:is_key(<<"old-conn">>, maps:get(voice_states, NewState))).--moderator_move_to_unknown_channel_fails_test() ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = base_move_state(VoiceStates),- {reply, Error, _} = guild_voice_move_execute:handle_move(- #{<<"old-conn">> => ExistingVS}, 12345, 10, 10, <<"old-conn">>, VoiceStates, State- ),- ?assertMatch({error, _, voice_channel_not_found}, Error).--moderator_move_without_connections_fails_test() ->- State = base_move_state(#{}),- {reply, ErrorWithConn, _} = guild_voice_move_execute:handle_move(- #{}, 200, 10, 10, <<"old-conn">>, #{}, State- ),- ?assertMatch({error, _, voice_connection_not_found}, ErrorWithConn),- {reply, ErrorNoConn, _} = guild_voice_move_execute:handle_move(- #{}, 200, 10, 10, null, #{}, State- ),- ?assertMatch({error, _, voice_user_not_in_voice}, ErrorNoConn).--moderator_disconnect_move_purges_counts_cache_test() ->- RegionId = <<"region-move-test">>,- VS = (existing_voice_state(<<"move-count-conn">>, 10, <<"100">>))#{- <<"region_id">> => RegionId,- <<"server_id">> => <<"server-move-test">>- },- _ = voice_state_counts_cache:upsert_voice_state(VS),- ?assertEqual(1, region_count(RegionId)),- VoiceStates = #{<<"move-count-conn">> => VS},- State = base_move_state(VoiceStates),- {reply, Reply0, NewState} = guild_voice_move_execute:handle_move(- VoiceStates, null, 10, 20, <<"move-count-conn">>, VoiceStates, State- ),- Reply = reply_map(Reply0),- ?assertEqual(true, maps:get(success, Reply)),- ?assertEqual(10, maps:get(user_id, Reply)),- ?assertEqual(0, region_count(RegionId)),- ?assertNot(maps:is_key(<<"move-count-conn">>, maps:get(voice_states, NewState))).--region_count(RegionId) ->- Counts = voice_state_counts_cache:get_local_counts(),- Regions = maps:get(<<"regions">>, Counts, []),- lists:foldl(- fun(Entry, Acc) -> add_region_entry_count(Entry, RegionId, Acc) end,- 0,- Regions- ).--add_region_entry_count(Entry, RegionId, Acc) ->- case maps:get(<<"region_id">>, Entry, undefined) of- RegionId -> Acc + maps:get(<<"voice_state_count">>, Entry, 0);- _ -> Acc- end.--guild_server_stub(StateData, TestPid) ->- spawn_link(fun() -> guild_server_stub_loop(StateData, TestPid) end).--guild_server_stub_loop(StateData, TestPid) ->- receive- {'$gen_call', From, {get_voice_guild_state}} ->- gen:reply(From, undefined),- guild_server_stub_loop(StateData, TestPid);- {'$gen_call', From, {get_sessions}} ->- gen:reply(From, StateData),- guild_server_stub_loop(StateData, TestPid);- {'$gen_call', From, {store_pending_connection, ConnId, Meta}} ->- TestPid ! {stored_pending, ConnId, Meta},- gen:reply(From, ok),- guild_server_stub_loop(StateData, TestPid)- after 5000 ->- ok- end.--receive_stored_pending() ->- receive- {stored_pending, ConnId, Meta} -> {ConnId, Meta}- after 1000 ->- error(pending_connection_not_stored)- end.--receive_voice_server_update() ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} -> Payload- after 1000 ->- error(voice_server_update_not_dispatched)- end.--send_moderator_move_update(StateData) ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- StubPid = guild_server_stub(StateData, self()),- SessionInfo = guild_voice_state:extract_session_info_from_voice_state(- <<"old-conn">>, ExistingVS- ),- ok = guild_voice_move_execute:send_single_voice_server_update(- 999, 200, SessionInfo, StubPid- ),- receive_stored_pending().--moderator_move_token_delivery_stores_restorable_pending_test() ->- with_token_rpc({ok, token_rpc_data()}, fun() ->- with_guild_voice_server_stub(fun moderator_move_pending_scenario/0)- end).--moderator_move_pending_scenario() ->- StateData = (base_move_state(#{}))#{- sessions => #{<<"sess1">> => #{pid => self(), user_id => 10}}- },- {ConnId, Meta} = send_moderator_move_update(StateData),- ?assertEqual(<<"new-conn">>, ConnId),- ?assert(is_binary(maps:get(token_nonce, Meta))),- ?assert(is_integer(maps:get(created_at, Meta))),- ?assert(maps:get(expires_at, Meta) > maps:get(created_at, Meta)),- ?assertEqual(10, maps:get(user_id, Meta)),- ?assertEqual(200, maps:get(channel_id, Meta)),- ?assertEqual(true, maps:get(self_deaf, Meta)),- ?assertEqual(- ok,- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- maps:get(token_nonce, Meta), Meta- )- ),- ?assertEqual(- {error, voice_nonce_mismatch},- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- <<"wrong-nonce">>, Meta- )- ),- Payload = receive_voice_server_update(),- ?assertEqual(<<"tok">>, maps:get(<<"token">>, Payload)),- ?assertEqual(<<"new-conn">>, maps:get(<<"connection_id">>, Payload)),- assert_pending_restores(ConnId, Meta).--assert_pending_restores(ConnId, Meta) ->- RestoreState = #{- id => 999,- sessions => #{},- voice_states => #{},- pending_voice_connections => #{ConnId => Meta}- },- {ok, RestoredVoiceStates, _RestoredState} =- guild_voice_connection_pending:maybe_restore_pending_connection(- ConnId, 200, 10, #{}, RestoreState- ),- RestoredVS = maps:get(ConnId, RestoredVoiceStates),- ?assertEqual(<<"200">>, maps:get(<<"channel_id">>, RestoredVS)),- ?assertEqual(<<"10">>, maps:get(<<"user_id">>, RestoredVS)),- ?assertEqual(true, maps:get(<<"self_deaf">>, RestoredVS)),- ?assert(maps:is_key(<<"member">>, RestoredVS)),- ?assert(maps:is_key(<<"version">>, RestoredVS)).--moderator_move_pending_sweep_expires_stale_entries_test() ->- with_token_rpc({ok, token_rpc_data()}, fun() ->- with_guild_voice_server_stub(fun moderator_move_sweep_scenario/0)- end).--moderator_move_sweep_scenario() ->- {ConnId, Meta} = send_moderator_move_update(base_move_state(#{})),- ExpiredMeta = Meta#{- created_at => maps:get(created_at, Meta) - 600000,- expires_at => maps:get(expires_at, Meta) - 600000- },- SweepState = #{- id => 999,- sessions => #{},- voice_states => #{},- pending_voice_connections => #{ConnId => ExpiredMeta}- },- SweptState = guild_voice_connection_pending:sweep_expired_pending_joins(SweepState),- ?assertEqual(#{}, maps:get(pending_voice_connections, SweptState)),- ?assertEqual(- {error, voice_pending_expired},- guild_voice_connection_pending:validate_pending_nonce_and_expiry(- maps:get(token_nonce, ExpiredMeta), ExpiredMeta- )- ).--private_member(UserId) ->- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"roles">> => [],- <<"mute">> => false,- <<"deaf">> => false- }.--private_move_state(VoiceStates, VirtualAccess) ->- #{- id => 999,- data => #{- <<"id">> => <<"999">>,- <<"guild">> => #{<<"owner_id">> => <<"20">>},- <<"roles">> => [#{<<"id">> => <<"999">>, <<"permissions">> => <<"0">>}],- <<"members">> => [private_member(10), private_member(20)],- <<"channels">> => [- #{<<"id">> => <<"100">>, <<"type">> => 2, <<"permission_overwrites">> => []},- #{<<"id">> => <<"200">>, <<"type">> => 2, <<"permission_overwrites">> => []}- ]- },- sessions => #{<<"s1">> => #{pid => self(), user_id => 10}},- voice_states => VoiceStates,- pending_voice_connections => #{},- virtual_channel_access => VirtualAccess- }.--receive_channel_dispatch(Event) ->- receive- {'$gen_cast', {dispatch, Event, Payload}} -> Payload- after 1000 ->- error({dispatch_not_received, Event})- end.--moderator_move_into_private_channel_grants_lease_test() ->- drain_stale_dispatches(),- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = private_move_state(VoiceStates, #{}),- {reply, Reply0, NewState} = guild_voice_move_execute:handle_move(- VoiceStates, 200, 10, 20, <<"old-conn">>, VoiceStates, State- ),- Reply = reply_map(Reply0),- ?assertEqual(true, maps:get(success, Reply)),- ?assertEqual(true, maps:get(needs_token, Reply)),- ?assert(guild_virtual_channel_access:has_virtual_access(10, 200, NewState)),- ?assert(guild_virtual_channel_access:is_move_pending(10, 200, NewState)),- Payload = receive_channel_dispatch(channel_create),- ?assertEqual(<<"200">>, maps:get(<<"id">>, Payload)),- ?assertEqual(<<"999">>, maps:get(<<"guild_id">>, Payload)).--moderator_move_out_of_leased_channel_revokes_lease_test() ->- drain_stale_dispatches(),- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = private_move_state(VoiceStates, #{10 => sets:from_list([100])}),- {reply, Reply0, NewState} = guild_voice_move_execute:handle_move(- VoiceStates, 200, 10, 20, <<"old-conn">>, VoiceStates, State- ),- ?assertEqual(true, maps:get(success, reply_map(Reply0))),- ?assertNot(guild_virtual_channel_access:has_virtual_access(10, 100, NewState)),- ?assert(guild_virtual_channel_access:has_virtual_access(10, 200, NewState)),- DeletePayload = receive_channel_dispatch(channel_delete),- ?assertEqual(<<"100">>, maps:get(<<"id">>, DeletePayload)),- ?assertEqual(<<"999">>, maps:get(<<"guild_id">>, DeletePayload)).--moderator_move_without_lease_dispatches_no_channel_delete_test() ->- drain_stale_dispatches(),- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = (base_move_state(VoiceStates))#{- sessions => #{<<"s1">> => #{pid => self(), user_id => 10}}- },- {reply, Reply0, _NewState} = guild_voice_move_execute:handle_move(- VoiceStates, 200, 10, 10, <<"old-conn">>, VoiceStates, State- ),- ?assertEqual(true, maps:get(success, reply_map(Reply0))),- assert_no_channel_delete().--assert_no_channel_delete() ->- receive- {'$gen_cast', {dispatch, channel_delete, Payload}} ->- ?assert(false, {unexpected_channel_delete, Payload})- after 50 ->- ok- end.--self_move_out_of_leased_channel_revokes_lease_test() ->- with_token_rpc({ok, token_rpc_data()}, fun self_move_revokes_lease_scenario/0).--self_move_revokes_lease_scenario() ->- ExistingVS = existing_voice_state(<<"old-conn">>, 10, <<"100">>),- VoiceStates = #{<<"old-conn">> => ExistingVS},- State = (base_move_state(VoiceStates))#{- sessions => #{<<"s1">> => #{pid => self(), user_id => 10}},- virtual_channel_access => #{10 => sets:from_list([100])}- },- {_Reply, NewState} = run_client_move(VoiceStates, State),- ?assertNot(guild_virtual_channel_access:has_virtual_access(10, 100, NewState)),- DeletePayload = receive_channel_dispatch(channel_delete),- ?assertEqual(<<"100">>, maps:get(<<"id">>, DeletePayload)).diff --git a/fluxer_gateway/test/guild_voice_p2p_tests.erl b/fluxer_gateway/test/guild_voice_p2p_tests.erldeleted file mode 100644index 1b507959f..000000000--- a/fluxer_gateway/test/guild_voice_p2p_tests.erl+++ /dev/null@@ -1,681 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_p2p_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").---define(GUILD_ID, 999).--define(CHANNEL_ID, 100).--define(OTHER_CHANNEL_ID, 200).--define(PINNED_CHANNEL_ID, 300).--p2p_start_in_an_empty_channel_test() ->- with_stubs(grant, fun(State0) ->- {Reply, State1} = join(10, true, State0),- ConnectionId = maps:get(connection_id, Reply),- ?assertMatch(#{success := true, p2p := true, ice_servers := [_]}, Reply),- ?assertNot(maps:is_key(token, Reply)),- ?assertNot(maps:is_key(endpoint, Reply)),- ?assertEqual(true, p2p_flag(ConnectionId, State1)),- ?assertEqual(#{}, maps:get(pending_voice_connections, State1)),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := true,- <<"p2p_participant_count">> := 1,- <<"country_code">> := <<"SE">>- },- last_token_request()- ),- ?assertEqual([{ConnectionId, true}], drain_voice_state_updates())- end).--agreed_joiner_joins_the_mesh_test() ->- with_stubs(grant, fun(State0) ->- {ReplyA, State1} = join(10, true, State0),- {ReplyB, State2} = join(11, true, State1),- ?assertMatch(#{p2p := true}, ReplyB),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := false,- <<"p2p_participant_count">> := 2- },- last_token_request()- ),- ?assertEqual(true, p2p_flag(maps:get(connection_id, ReplyA), State2)),- ?assertEqual(true, p2p_flag(maps:get(connection_id, ReplyB), State2)),- ?assertEqual([], served_voice_server_updates(State2))- end).--non_agreeing_joiner_is_rejected_and_nobody_is_converted_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- Requests = token_request_count(),- {Reply, State2} = join(12, undefined, State1),- ?assertEqual({error, permission_denied, voice_p2p_consent_required}, Reply),- ?assertEqual(Requests, token_request_count()),- assert_untouched(Mesh, State1, State2)- end).--bot_is_rejected_like_a_non_agreeing_joiner_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- {reply, Reply, State2} = guild_voice_connection:voice_state_update(- (request(12, true))#{bot => true}, State1- ),- ?assertEqual({error, permission_denied, voice_p2p_consent_required}, Reply),- assert_untouched(Mesh, State1, State2)- end).--fifth_joiner_is_rejected_as_full_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11, 12, 13], State0),- ?assertEqual(4, length(Mesh)),- Requests = token_request_count(),- {Reply, State2} = join(14, true, State1),- ?assertEqual({error, permission_denied, voice_channel_full}, Reply),- ?assertEqual(Requests, token_request_count()),- assert_untouched(Mesh, State1, State2)- end).--joiner_past_the_configured_cap_is_rejected_as_full_test() ->- with_stubs({cap, 2}, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- {Reply, State2} = join(12, true, State1),- ?assertMatch(- #{- <<"p2p">> := true,- <<"p2p_initiator">> := false,- <<"p2p_participant_count">> := 3- },- last_token_request()- ),- ?assertEqual({error, permission_denied, voice_channel_full}, Reply),- assert_untouched(Mesh, State1, State2)- end).--mesh_fills_up_to_the_configured_cap_test() ->- with_stubs({cap, 3}, fun(State0) ->- {[_, _, _] = Mesh, State1} = join_mesh([10, 11, 12], State0),- [?assertEqual(true, p2p_flag(ConnectionId, State1)) || ConnectionId <- Mesh],- {Reply, _State2} = join(13, true, State1),- ?assertEqual({error, permission_denied, voice_channel_full}, Reply)- end).--declined_grant_into_a_live_mesh_is_rejected_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- erlang:put(p2p_stub_mode, decline),- {Reply, State2} = join(12, true, State1),- ?assertMatch(#{<<"p2p">> := true, <<"p2p_initiator">> := false}, last_token_request()),- ?assertEqual({error, voice_error, voice_p2p_unavailable}, Reply),- assert_untouched(Mesh, State1, State2)- end).--declined_grant_on_an_empty_channel_joins_sfu_test() ->- with_stubs(decline, fun(State0) ->- {Reply, State1} = join(10, true, State0),- ?assertMatch(#{<<"p2p">> := true, <<"p2p_initiator">> := true}, last_token_request()),- ?assertMatch(#{success := true, token := _, endpoint := _}, Reply),- ?assertNot(maps:is_key(p2p, Reply)),- ?assertEqual(#{}, maps:get(voice_states, State1)),- ?assertEqual(- [maps:get(connection_id, Reply)],- maps:keys(maps:get(pending_voice_connections, State1))- )- end).--pinned_empty_channel_joins_a_non_agreeing_joiner_on_sfu_test() ->- with_stubs(grant, fun(State0) ->- {reply, Reply, _State1} = guild_voice_connection:voice_state_update(- (request(10, undefined))#{channel_id => ?PINNED_CHANNEL_ID}, State0- ),- ?assertMatch(#{success := true, token := _}, Reply),- ?assertNot(maps:is_key(<<"p2p">>, last_token_request()))- end).--pinned_channel_joins_sfu_when_the_grant_is_declined_test() ->- with_stubs(decline, fun(State0) ->- {reply, Reply, _State1} = guild_voice_connection:voice_state_update(- (request(10, true))#{channel_id => ?PINNED_CHANNEL_ID}, State0- ),- ?assertMatch(#{success := true, token := _}, Reply)- end).--pending_join_blocks_a_p2p_start_test() ->- with_stubs(grant, fun(State0) ->- {_Reply, State1} = join(10, undefined, State0),- ?assertEqual(1, maps:size(maps:get(pending_voice_connections, State1))),- {Reply, _State2} = join(11, true, State1),- ?assertMatch(#{token := _}, Reply),- ?assertNot(maps:is_key(<<"p2p">>, last_token_request()))- end).--explicit_p2p_false_update_converts_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA | _] = Mesh, State1} = join_mesh([10, 11], State0),- {reply, #{success := true}, State2} = guild_voice_connection:voice_state_update(- (request(10, false))#{connection_id => ConnectionA}, State1- ),- assert_converted(Mesh, State2)- end).--explicit_p2p_false_update_is_ignored_in_a_pinned_channel_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA | _] = Mesh, State1} = join_mesh([10, 11], ?PINNED_CHANNEL_ID, State0),- _ = drain_voice_state_updates(),- {reply, #{success := true}, State2} = guild_voice_connection:voice_state_update(- (request(10, false))#{- channel_id => ?PINNED_CHANNEL_ID, connection_id => ConnectionA- },- State1- ),- assert_untouched(Mesh, State1, State2)- end).--update_without_p2p_keeps_the_mesh_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA, ConnectionB], State1} = join_mesh([10, 11], State0),- {reply, #{success := true}, State2} = guild_voice_connection:voice_state_update(- (request(10, undefined))#{connection_id => ConnectionA, self_mute => true},- State1- ),- ?assertEqual(true, p2p_flag(ConnectionA, State2)),- ?assertEqual(true, p2p_flag(ConnectionB, State2)),- ?assertEqual(- true,- maps:get(<<"self_mute">>, maps:get(ConnectionA, maps:get(voice_states, State2)))- )- end).--region_switch_converts_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- {reply, #{success := true}, State2} = guild_voice_region:switch_voice_region_handler(- #{channel_id => ?CHANNEL_ID}, State1- ),- assert_marked_sfu(Mesh, State2),- GuildPid = maps:get(guild_pid, State2),- GuildPid ! {serve, State2},- ok = guild_voice_region:switch_voice_region(?GUILD_ID, ?CHANNEL_ID, GuildPid),- ?assertEqual(lists:sort(Mesh), lists:sort(drain_voice_server_updates(length(Mesh))))- end).--region_switch_keeps_a_pinned_channel_p2p_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], ?PINNED_CHANNEL_ID, State0),- _ = drain_voice_state_updates(),- {reply, #{success := true}, State2} = guild_voice_region:switch_voice_region_handler(- #{channel_id => ?PINNED_CHANNEL_ID}, State1- ),- GuildPid = maps:get(guild_pid, State2),- GuildPid ! {serve, State2},- ok = guild_voice_region:switch_voice_region(?GUILD_ID, ?PINNED_CHANNEL_ID, GuildPid),- assert_untouched(Mesh, State1, State2)- end).--livekit_restore_into_a_mesh_is_refused_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- Stale = (maps:get(hd(Mesh), maps:get(voice_states, State1)))#{- <<"connection_id">> => <<"stale">>, <<"user_id">> => <<"12">>, <<"p2p">> => false- },- State2 = State1#{- recently_disconnected_voice_states => #{- <<"stale">> => #{- voice_state => Stale, disconnected_at => erlang:system_time(millisecond)- }- }- },- {reply, Reply, State3} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(- #{connection_id => <<"stale">>}, State2- ),- ?assertEqual({error, permission_denied, voice_p2p_consent_required}, Reply),- ?assertNot(maps:is_key(<<"stale">>, maps:get(voice_states, State3))),- assert_untouched(Mesh, State2, State3)- end).--livekit_activation_into_a_mesh_is_refused_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- State2 = guild_voice_connection_pending:store_pending(- <<"late">>,- #{- user_id => 12,- guild_id => ?GUILD_ID,- channel_id => ?CHANNEL_ID,- session_id => session_id(12),- token_nonce => <<"nonce">>,- expires_at => erlang:system_time(millisecond) + 30000- },- State1- ),- {reply, Reply, State3} =- guild_voice_connection_confirm:confirm_voice_connection_from_livekit(- #{connection_id => <<"late">>, token_nonce => <<"nonce">>}, State2- ),- ?assertEqual({error, permission_denied, voice_p2p_consent_required}, Reply),- ?assertEqual(lists:sort(Mesh), lists:sort(maps:keys(maps:get(voice_states, State3)))),- ?assertEqual(#{}, maps:get(pending_voice_connections, State3)),- assert_untouched(Mesh, State1, State3)- end).--explicit_switch_converts_without_a_voice_server_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA | _] = Mesh, State1} = join_mesh([10, 11], State0),- Self = self(),- Guild = spawn(fun() ->- {reply, Reply, State2} = guild_voice_connection:voice_state_update(- (request(10, false))#{connection_id => ConnectionA},- maps:remove(guild_pid, State1)- ),- Self ! {converted, Reply, State2},- guild_stub_loop(State2)- end),- receive- {converted, Reply, State2} ->- ?assertMatch(#{success := true}, Reply),- assert_marked_sfu(Mesh, State2),- ?assertEqual(lists:sort(Mesh), lists:sort(drain_voice_server_updates(2)))- after 2000 ->- error(explicit_switch_did_not_convert)- end,- Guild ! stop- end).--moderator_move_into_a_mesh_is_refused_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10, 11], State0),- State2 = with_sfu_voice_state(<<"moved">>, 12, ?OTHER_CHANNEL_ID, State1),- {reply, Reply, State3} = guild_voice_move:move_member(- move_request(12, ?CHANNEL_ID), State2- ),- ?assertEqual({error, permission_denied, voice_p2p_consent_required}, Reply),- ?assert(maps:is_key(<<"moved">>, maps:get(voice_states, State3))),- assert_untouched(Mesh, State2, State3)- end).--moderator_move_into_an_empty_pinned_channel_moves_on_sfu_test() ->- with_stubs(grant, fun(State0) ->- State1 = with_sfu_voice_state(<<"moved">>, 12, ?OTHER_CHANNEL_ID, State0),- {reply, Reply, _State2} = guild_voice_move:move_member(- move_request(12, ?PINNED_CHANNEL_ID), State1- ),- ?assertMatch(#{success := true, needs_token := true}, Reply)- end).--moderator_move_out_of_a_mesh_gets_an_sfu_grant_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA, ConnectionB], State1} = join_mesh([10, 11], State0),- {reply, #{success := true, needs_token := true, session_data := SessionData}, State2} =- guild_voice_move:move_member(move_request(11, ?OTHER_CHANNEL_ID), State1),- ?assertEqual([ConnectionA], maps:keys(maps:get(voice_states, State2))),- ?assertEqual(true, p2p_flag(ConnectionA, State2)),- GuildPid = maps:get(guild_pid, State2),- GuildPid ! {serve, State2},- ok = guild_voice_move_execute:send_single_voice_server_update(- ?GUILD_ID, ?OTHER_CHANNEL_ID, hd(SessionData), GuildPid- ),- ?assertEqual([ConnectionB], drain_voice_server_updates(1)),- ?assertNot(maps:is_key(<<"p2p">>, last_token_request()))- end).--client_move_into_a_mesh_joins_it_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA], State1} = join_mesh([10], State0),- State2 = with_sfu_voice_state(<<"moved">>, 12, ?OTHER_CHANNEL_ID, State1),- {reply, Reply, State3} = guild_voice_connection:voice_state_update(- (request(12, true))#{connection_id => <<"moved">>}, State2- ),- ?assertMatch(#{success := true, p2p := true, connection_id := <<"moved">>}, Reply),- ?assertEqual(true, p2p_flag(<<"moved">>, State3)),- ?assertEqual(true, p2p_flag(ConnectionA, State3)),- ?assertEqual(#{}, maps:get(pending_voice_connections, State3))- end).--client_move_into_a_mesh_without_agreement_is_rejected_test() ->- with_stubs(grant, fun(State0) ->- {Mesh, State1} = join_mesh([10], State0),- State2 = with_sfu_voice_state(<<"moved">>, 12, ?OTHER_CHANNEL_ID, State1),- {reply, Reply, State3} = guild_voice_connection:voice_state_update(- (request(12, undefined))#{connection_id => <<"moved">>}, State2- ),- ?assertEqual({error, permission_denied, voice_p2p_consent_required}, Reply),- ?assertEqual(- <<"200">>,- maps:get(<<"channel_id">>, maps:get(<<"moved">>, maps:get(voice_states, State3)))- ),- assert_untouched(Mesh, State2, State3)- end).--signal_relay_allowed_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA, ConnectionB], State1} = join_mesh([10, 11], State0),- Data = #{<<"type">> => <<"offer">>, <<"sdp">> => <<"v=0">>, <<"id">> => 7},- {noreply, State1} = guild_voice_handler:handle_cast(- {voice_signal, signal(<<"sess-10">>, ConnectionB, Data)}, State1- ),- ?assertEqual(- #{- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"from">> => ConnectionA,- <<"user_id">> => <<"10">>,- <<"data">> => Data- },- receive_voice_signal()- )- end).--signal_relay_denied_test() ->- with_stubs(grant, fun(State0) ->- {[ConnectionA, ConnectionB], State1} = join_mesh([10, 11], State0),- Data = #{<<"type">> => <<"candidate">>},- Denied = [- signal(<<"sess-12">>, ConnectionB, Data),- signal(<<"sess-10">>, ConnectionA, Data),- signal(<<"sess-10">>, <<"unknown">>, Data),- (signal(<<"sess-10">>, ConnectionB, Data))#{channel_id => 200}- ],- [- {noreply, State1} = guild_voice_handler:handle_cast({voice_signal, Request}, State1)- || Request <- Denied- ],- State2 = guild_voice_region:switch_to_sfu(?CHANNEL_ID, State1),- {noreply, State2} = guild_voice_handler:handle_cast(- {voice_signal, signal(<<"sess-10">>, ConnectionB, Data)}, State2- ),- assert_no_voice_signal(),- ?assertEqual(2, length(served_voice_server_updates(State2)))- end).--signal(SessionId, To, Data) ->- #{session_id => SessionId, channel_id => ?CHANNEL_ID, to => To, data => Data}.--with_sfu_voice_state(ConnectionId, UserId, ChannelId, State) ->- VoiceState = voice_state_utils:complete_voice_state(#{- <<"guild_id">> => <<"999">>,- <<"channel_id">> => integer_to_binary(ChannelId),- <<"user_id">> => integer_to_binary(UserId),- <<"connection_id">> => ConnectionId,- <<"session_id">> => session_id(UserId),- <<"member">> => member(UserId)- }),- VoiceStates = maps:get(voice_states, State),- State#{voice_states => VoiceStates#{ConnectionId => VoiceState}}.--move_request(UserId, ChannelId) ->- #{- user_id => UserId,- moderator_id => 10,- channel_id => ChannelId,- mute => false,- deaf => false- }.--assert_converted(Mesh, State) ->- assert_marked_sfu(Mesh, State),- ?assertEqual(lists:sort(Mesh), lists:sort(served_voice_server_updates(State))).--assert_marked_sfu(Mesh, State) ->- [?assertEqual(false, p2p_flag(ConnectionId, State)) || ConnectionId <- Mesh],- Broadcasts = drain_voice_state_updates(),- [?assert(lists:member({ConnectionId, false}, Broadcasts)) || ConnectionId <- Mesh].--assert_untouched(Mesh, Before, After) ->- VoiceStates = maps:get(voice_states, Before),- [- ?assertEqual(- maps:get(ConnectionId, VoiceStates),- maps:get(ConnectionId, maps:get(voice_states, After))- )- || ConnectionId <- Mesh- ],- ?assertEqual(- maps:get(pending_voice_connections, Before), maps:get(pending_voice_connections, After)- ),- Broadcasts = drain_voice_state_updates(),- [?assertNot(lists:member({ConnectionId, false}, Broadcasts)) || ConnectionId <- Mesh],- ?assertEqual([], served_voice_server_updates(After, 0)).--served_voice_server_updates(State) ->- served_voice_server_updates(- State,- maps:size(- voice_state_utils:channel_voice_states(?CHANNEL_ID, maps:get(voice_states, State))- )- ).--served_voice_server_updates(State, Expected) ->- maps:get(guild_pid, State) ! {serve, State},- drain_voice_server_updates(Expected).--drain_voice_server_updates(0) ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} ->- error({unexpected_voice_server_update, Payload})- after 100 ->- []- end;-drain_voice_server_updates(Remaining) ->- receive- {'$gen_cast', {dispatch, voice_server_update, Payload}} ->- ?assertEqual(<<"tok">>, maps:get(<<"token">>, Payload)),- ?assertEqual(<<"wss://voice.example">>, maps:get(<<"endpoint">>, Payload)),- ?assertNot(maps:is_key(<<"p2p">>, Payload)),- [maps:get(<<"connection_id">>, Payload) | drain_voice_server_updates(Remaining - 1)]- after 300 ->- []- end.--drain_voice_state_updates() ->- receive- {'$gen_cast', {dispatch, voice_state_update, {pre_encoded, Encoded}}} ->- #{<<"connection_id">> := ConnectionId, <<"p2p">> := P2p} = json:decode(Encoded),- [{ConnectionId, P2p} | drain_voice_state_updates()]- after 200 ->- []- end.--receive_voice_signal() ->- receive- {'$gen_cast', {dispatch, voice_signal, Payload}} -> Payload- after 1000 ->- error(voice_signal_not_dispatched)- end.--assert_no_voice_signal() ->- receive- {'$gen_cast', {dispatch, voice_signal, Payload}} ->- error({unexpected_voice_signal, Payload})- after 100 ->- ok- end.--p2p_flag(ConnectionId, State) ->- maps:get(<<"p2p">>, maps:get(ConnectionId, maps:get(voice_states, State))).--join_mesh(UserIds, State0) ->- join_mesh(UserIds, ?CHANNEL_ID, State0).--join_mesh(UserIds, ChannelId, State0) ->- lists:foldl(- fun(UserId, {ConnectionIds, State}) ->- {reply, #{p2p := true, connection_id := ConnectionId}, NewState} =- guild_voice_connection:voice_state_update(- (request(UserId, true))#{channel_id => ChannelId}, State- ),- {ConnectionIds ++ [ConnectionId], NewState}- end,- {[], State0},- UserIds- ).--join(UserId, P2p, State) ->- {reply, Reply, NewState} = guild_voice_connection:voice_state_update(- request(UserId, P2p), State- ),- {Reply, NewState}.--request(UserId, P2p) ->- #{- user_id => UserId,- channel_id => ?CHANNEL_ID,- session_id => session_id(UserId),- p2p => P2p,- country_code => <<"SE">>- }.--session_id(UserId) ->- <<"sess-", (integer_to_binary(UserId))/binary>>.--last_token_request() ->- lists:last(token_requests()).--token_request_count() ->- length(token_requests()).--token_requests() ->- [- Request- || {_Pid, {rpc_client, call, [#{<<"type">> := <<"voice_get_token">>} = Request]}, _Result} <-- meck:history(rpc_client)- ].--with_stubs(Mode, Fun) ->- erlang:put(p2p_stub_mode, Mode),- meck:new(rpc_client, [passthrough, no_link, non_strict]),- meck:expect(rpc_client, call, fun rpc_reply/1),- meck:new(guild_voice_server, [passthrough, no_link]),- meck:expect(guild_voice_server, resolve, fun(_GuildId, GuildPid) -> GuildPid end),- GuildPid = spawn(fun guild_stub/0),- Test = self(),- Sink = spawn(fun() -> sink(Test) end),- try- Fun(base_state(GuildPid, Sink))- after- GuildPid ! stop,- meck:unload(guild_voice_server),- meck:unload(rpc_client),- stop_sink(Sink)- end.--sink(Test) ->- receive- Message ->- Test ! Message,- sink(Test)- after 30000 ->- ok- end.--stop_sink(Sink) ->- exit(Sink, kill),- flush_mailbox().--flush_mailbox() ->- receive- _Message -> flush_mailbox()- after 0 ->- ok- end.--rpc_reply(#{<<"type">> := <<"voice_get_token">>} = Request) ->- ConnectionId = maps:get(- <<"connection_id">>,- Request,- <<"conn-", (integer_to_binary(erlang:unique_integer([positive])))/binary>>- ),- case {maps:get(<<"p2p">>, Request, false), erlang:get(p2p_stub_mode)} of- {true, grant} ->- p2p_grant(ConnectionId);- {true, {cap, Max}} ->- case maps:get(<<"p2p_participant_count">>, Request) > Max of- true -> {ok, #{<<"p2p">> => false, <<"declineReason">> => <<"channel_full">>}};- false -> p2p_grant(ConnectionId)- end;- _ ->- {ok, #{- <<"token">> => <<"tok">>,- <<"endpoint">> => <<"wss://voice.example">>,- <<"connectionId">> => ConnectionId,- <<"regionId">> => <<"us-east">>,- <<"serverId">> => <<"voice-1">>- }}- end;-rpc_reply(_Request) ->- {ok, #{}}.--p2p_grant(ConnectionId) ->- {ok, #{- <<"p2p">> => true,- <<"connectionId">> => ConnectionId,- <<"iceServers">> => [#{<<"urls">> => [<<"stun:stun.example:3478">>]}]- }}.--guild_stub() ->- receive- {serve, State} -> guild_stub_loop(State);- stop -> ok- after 30000 ->- ok- end.--guild_stub_loop(State) ->- receive- {serve, NewState} ->- guild_stub_loop(NewState);- {'$gen_call', From, {get_voice_guild_state}} ->- gen_server:reply(From, State),- guild_stub_loop(State);- {'$gen_call', From, _Request} ->- gen_server:reply(From, ok),- guild_stub_loop(State);- stop ->- ok;- _Other ->- guild_stub_loop(State)- after 30000 ->- ok- end.--base_state(GuildPid, Sink) ->- UserIds = [10, 11, 12, 13, 14],- #{- id => ?GUILD_ID,- guild_pid => GuildPid,- data => #{- <<"id">> => <<"999">>,- <<"guild">> => #{<<"owner_id">> => <<"10">>},- <<"channels">> => [- #{<<"id">> => <<"100">>, <<"type">> => 2, <<"user_limit">> => 0},- #{<<"id">> => <<"200">>, <<"type">> => 2, <<"user_limit">> => 0},- #{- <<"id">> => <<"300">>,- <<"type">> => 2,- <<"user_limit">> => 0,- <<"rtc_p2p">> => true- }- ],- <<"members">> => [member(UserId) || UserId <- UserIds]- },- sessions => maps:from_list([- {session_id(UserId), #{user_id => UserId, pid => Sink, pending_connect => false}}- || UserId <- UserIds- ]),- voice_states => #{},- pending_voice_connections => #{},- test_perm_fun => fun(_UserId) ->- constants:view_channel_permission() bor constants:connect_permission()- end- }.--member(UserId) ->- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"mute">> => false,- <<"deaf">> => false- }.diff --git a/fluxer_gateway/test/guild_voice_permissions_tests.erl b/fluxer_gateway/test/guild_voice_permissions_tests.erldeleted file mode 100644index 501fda5a3..000000000--- a/fluxer_gateway/test/guild_voice_permissions_tests.erl+++ /dev/null@@ -1,373 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_permissions_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--voice_permissions_missing_view_test() ->- State = permission_test_state(0, fun(_) -> constants:view_channel_permission() end),- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 0}, #{}, State, false- ),- ?assertMatch({error, permission_denied, voice_permission_denied}, Result).--voice_permissions_full_channel_test() ->- State = permission_test_state(2, fun(_) -> required_voice_perms() end),- VoiceStates = #{- <<"conn1">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>},- <<"conn2">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"2">>}- },- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 3, 10, #{<<"user_limit">> => 2}, VoiceStates, State, false- ),- ?assertMatch({error, permission_denied, voice_channel_full}, Result).--voice_permissions_existing_user_update_test() ->- State = permission_test_state(2, fun(_) -> required_voice_perms() end),- VoiceStates = #{- <<"conn1">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>},- <<"conn2">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"2">>}- },- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 2}, VoiceStates, State, true- ),- ?assertEqual({ok, allowed}, Result).--voice_permissions_unlimited_channel_camera_caps_at_25_test() ->- State = permission_test_state(2, fun(_) -> required_voice_perms() end),- VoiceStates = camera_limited_voice_states(25, 10),- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 26, 10, #{<<"user_limit">> => 0}, VoiceStates, State, false- ),- ?assertMatch({error, permission_denied, voice_channel_full}, Result).--voice_permissions_connection_limit_reached_test() ->- State = permission_test_state(2, fun(_) -> required_voice_perms() end),- VoiceStates = #{- <<"conn1">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>},- <<"conn2">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>}- },- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1,- 10,- #{<<"user_limit">> => 0, <<"voice_connection_limit">> => 2},- VoiceStates,- State,- false- ),- ?assertMatch({error, permission_denied, voice_connection_limit_reached}, Result),- OtherUserResult = guild_voice_permissions:check_voice_permissions_and_limits(- 2,- 10,- #{<<"user_limit">> => 0, <<"voice_connection_limit">> => 2},- VoiceStates,- State,- false- ),- ?assertEqual({ok, allowed}, OtherUserResult).--voice_permissions_connection_limit_counts_pending_test() ->- Future = erlang:system_time(millisecond) + 1000,- State0 = permission_test_state(2, fun(_) -> required_voice_perms() end),- State = maps:put(- pending_voice_connections,- #{- <<"pending">> => #{- user_id => 1,- channel_id => 10,- expires_at => Future- }- },- State0- ),- VoiceStates = #{- <<"conn1">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>},- <<"conn2">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>},- <<"conn3">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>},- <<"conn4">> => #{<<"channel_id">> => <<"10">>, <<"user_id">> => <<"1">>}- },- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 0}, VoiceStates, State, false- ),- ?assertMatch({error, permission_denied, voice_connection_limit_reached}, Result).--voice_permissions_virtual_access_bypass_test() ->- Base = permission_test_state(7, fun(_) -> 0 end),- State = Base#{virtual_channel_access => #{1 => sets:from_list([10])}},- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 0}, #{}, State, false- ),- ?assertEqual({ok, allowed}, Result).--voice_permissions_move_pending_bypass_test() ->- Base = permission_test_state(7, fun(_) -> 0 end),- State = Base#{virtual_channel_access_move_pending => #{1 => sets:from_list([10])}},- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 0}, #{}, State, false- ),- ?assertEqual({ok, allowed}, Result).--voice_permissions_without_lease_denied_test() ->- State = permission_test_state(7, fun(_) -> 0 end),- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 0}, #{}, State, false- ),- ?assertMatch({error, permission_denied, voice_permission_denied}, Result).--voice_permissions_virtual_access_other_channel_denied_test() ->- Base = permission_test_state(7, fun(_) -> 0 end),- State = Base#{virtual_channel_access => #{1 => sets:from_list([99])}},- Result = guild_voice_permissions:check_voice_permissions_and_limits(- 1, 10, #{<<"user_limit">> => 0}, #{}, State, false- ),- ?assertMatch({error, permission_denied, voice_permission_denied}, Result).--permission_sync_disconnects_when_view_channel_lost_test() ->- ok = drain_mailbox(),- ConnectOnly = constants:connect_permission(),- {State, UserId, ChannelId, GuildId} = build_perm_sync_state(ConnectOnly),- ok = guild_voice_permission_sync:sync_user_voice_permissions(UserId, State),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(true, maps:get(disconnected, Perms, false))- after 200 ->- ?assert(false)- end.--permission_sync_does_not_disconnect_with_full_perms_test() ->- ok = drain_mailbox(),- FullPerms =- constants:view_channel_permission() bor- constants:connect_permission() bor- constants:speak_permission(),- {State, UserId, ChannelId, GuildId} = build_perm_sync_state(FullPerms),- ok = guild_voice_permission_sync:sync_user_voice_permissions(UserId, State),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(true, maps:get(can_speak, Perms, false)),- ?assertNot(maps:is_key(disconnected, Perms))- after 200 ->- ?assert(false)- end.--permission_sync_runs_on_role_permission_update_test() ->- ok = drain_mailbox(),- {State, UserId, ChannelId, GuildId, RoleId} = build_sync_wiring_state(),- _ = guild_state:update_state(- guild_role_update,- #{- <<"role">> => #{- <<"id">> => integer_to_binary(RoleId),- <<"permissions">> => <<"0">>- }- },- State- ),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(false, maps:get(can_speak, Perms)),- ?assertEqual(false, maps:get(can_stream, Perms))- after 200 ->- ?assert(false)- end.--permission_sync_runs_on_everyone_role_update_test() ->- ok = drain_mailbox(),- {State, UserId, ChannelId, GuildId, _RoleId} = build_sync_wiring_state(),- _ = guild_state:update_state(- guild_role_update,- #{- <<"role">> => #{- <<"id">> => integer_to_binary(GuildId),- <<"permissions">> => <<"0">>- }- },- State- ),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(true, maps:get(disconnected, Perms, false))- after 200 ->- ?assert(false)- end.--permission_sync_runs_on_role_delete_test() ->- ok = drain_mailbox(),- {State, UserId, ChannelId, GuildId, RoleId} = build_sync_wiring_state(),- _ = guild_state:update_state(- guild_role_delete,- #{<<"role_id">> => integer_to_binary(RoleId)},- State- ),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(false, maps:get(can_speak, Perms)),- ?assertEqual(false, maps:get(can_stream, Perms))- after 200 ->- ?assert(false)- end.--permission_sync_runs_on_channel_overwrite_update_test() ->- ok = drain_mailbox(),- {State, UserId, ChannelId, GuildId, RoleId} = build_sync_wiring_state(),- _ = guild_state:update_state(- channel_update,- #{- <<"id">> => integer_to_binary(ChannelId),- <<"type">> => 2,- <<"permission_overwrites">> => [- #{- <<"id">> => integer_to_binary(RoleId),- <<"type">> => 0,- <<"allow">> => <<"0">>,- <<"deny">> => integer_to_binary(constants:stream_permission())- }- ]- },- State- ),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(true, maps:get(can_speak, Perms)),- ?assertEqual(false, maps:get(can_stream, Perms))- after 200 ->- ?assert(false)- end.--permission_sync_runs_on_member_role_removal_test() ->- ok = drain_mailbox(),- {State, UserId, ChannelId, GuildId, _RoleId} = build_sync_wiring_state(),- _ = guild_state:update_state(- guild_member_update,- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"roles">> => []- },- State- ),- receive- {synced, GuildId, ChannelId, UserId, <<"test-conn">>, Perms} ->- ?assertEqual(false, maps:get(can_speak, Perms)),- ?assertEqual(false, maps:get(can_stream, Perms))- after 200 ->- ?assert(false)- end.--build_sync_wiring_state() ->- Self = self(),- TestFun = fun(GId, ChId, UId, ConnId, Perms) ->- Self ! {synced, GId, ChId, UId, ConnId, Perms}- end,- UserId = 10,- ChannelId = 500,- GuildId = 42,- RoleId = 999,- RoleIdBin = integer_to_binary(RoleId),- EveryonePerms = required_voice_perms(),- RolePerms = constants:speak_permission() bor constants:stream_permission(),- State = #{- id => GuildId,- voice_states => #{- <<"conn">> => #{- <<"user_id">> => integer_to_binary(UserId),- <<"channel_id">> => integer_to_binary(ChannelId),- <<"connection_id">> => <<"test-conn">>,- <<"deaf">> => false- }- },- member_list_subscriptions => guild_member_list_subs:new(),- test_permission_sync_fun => TestFun,- data => #{- <<"guild">> => #{<<"owner_id">> => <<"1">>},- <<"roles">> => [- #{<<"id">> => RoleIdBin, <<"permissions">> => integer_to_binary(RolePerms)},- #{- <<"id">> => integer_to_binary(GuildId),- <<"permissions">> => integer_to_binary(EveryonePerms)- }- ],- <<"members">> => [- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"roles">> => [RoleIdBin]- }- ],- <<"channels">> => [- #{- <<"id">> => integer_to_binary(ChannelId),- <<"type">> => 2,- <<"permission_overwrites">> => []- }- ]- }- },- {State, UserId, ChannelId, GuildId, RoleId}.--build_perm_sync_state(Permissions) ->- Self = self(),- TestFun = fun(GId, ChId, UId, ConnId, Perms) ->- Self ! {synced, GId, ChId, UId, ConnId, Perms}- end,- UserId = 10,- ChannelId = 500,- GuildId = 42,- RoleId = 999,- RoleIdBin = integer_to_binary(RoleId),- GuildIdBin = integer_to_binary(GuildId),- UserIdBin = integer_to_binary(UserId),- ChIdBin = integer_to_binary(ChannelId),- PermsBin = integer_to_binary(Permissions),- VoiceState = #{- <<"user_id">> => UserIdBin,- <<"channel_id">> => ChIdBin,- <<"connection_id">> => <<"test-conn">>,- <<"deaf">> => false- },- State = #{- id => GuildId,- voice_states => #{<<"conn">> => VoiceState},- test_permission_sync_fun => TestFun,- data => #{- <<"guild">> => #{<<"owner_id">> => <<"1">>},- <<"roles">> => [- #{<<"id">> => RoleIdBin, <<"permissions">> => PermsBin},- #{<<"id">> => GuildIdBin, <<"permissions">> => <<"0">>}- ],- <<"members">> => [- #{<<"user">> => #{<<"id">> => UserIdBin}, <<"roles">> => [RoleIdBin]}- ],- <<"channels">> => [- #{<<"id">> => ChIdBin, <<"permission_overwrites">> => []}- ]- }- },- {State, UserId, ChannelId, GuildId}.--required_voice_perms() ->- constants:view_channel_permission() bor constants:connect_permission().--permission_test_state(GuildId, PermFun) ->- #{id => GuildId, test_perm_fun => PermFun}.--camera_limited_voice_states(Count, ChannelId) ->- lists:foldl(- fun(UserId, Acc) ->- ConnId = <<"conn", (integer_to_binary(UserId))/binary>>,- Acc#{- ConnId => #{- <<"channel_id">> => integer_to_binary(ChannelId),- <<"user_id">> => integer_to_binary(UserId),- <<"self_video">> => UserId =:= 1- }- }- end,- #{},- lists:seq(1, Count)- ).--drain_mailbox() ->- receive- _ -> drain_mailbox()- after 0 ->- ok- end.diff --git a/fluxer_gateway/test/guild_voice_state_tests.erl b/fluxer_gateway/test/guild_voice_state_tests.erldeleted file mode 100644index 23bff814b..000000000--- a/fluxer_gateway/test/guild_voice_state_tests.erl+++ /dev/null@@ -1,181 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(guild_voice_state_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--update_voice_state_data_no_change_reply_is_external_test() ->- ExistingVS = #{- <<"guild_id">> => <<"1">>,- <<"channel_id">> => <<"2">>,- <<"user_id">> => <<"3">>,- <<"connection_id">> => <<"conn">>,- <<"latitude">> => <<"1.0">>,- <<"longitude">> => <<"2.0">>,- <<"version">> => 4- },- Flags = #{- self_mute => false,- self_deaf => false,- self_video => false,- self_stream => false,- is_mobile => false,- suppress => false- },- {reply, Reply, _} = guild_voice_state:update_voice_state_data(#{- connection_id => <<"conn">>,- channel_id => <<"2">>,- flags => Flags,- member => #{},- existing_voice_state => ExistingVS,- voice_states => #{<<"conn">> => ExistingVS},- state => #{voice_states => #{<<"conn">> => ExistingVS}},- needs_token => false,- viewer_stream_keys => []- }),- ?assertEqual(true, maps:get(success, Reply)),- ReplyVS = maps:get(voice_state, Reply),- ?assertNot(maps:is_key(<<"latitude">>, ReplyVS)),- ?assertNot(maps:is_key(<<"longitude">>, ReplyVS)),- ?assertEqual(4, maps:get(<<"version">>, ReplyVS)),- ?assertEqual(null, maps:get(<<"member">>, ReplyVS)),- ?assertEqual(false, maps:get(<<"suppress">>, ReplyVS)).--update_voice_state_data_change_bumps_version_and_refreshes_member_test() ->- Member = #{- <<"user">> => #{<<"id">> => <<"3">>},- <<"nick">> => <<"fresh-nick">>,- <<"mute">> => false,- <<"deaf">> => false- },- ExistingVS = #{- <<"guild_id">> => <<"1">>,- <<"channel_id">> => <<"2">>,- <<"user_id">> => <<"3">>,- <<"connection_id">> => <<"conn">>,- <<"self_mute">> => false,- <<"member">> => #{<<"nick">> => <<"stale-nick">>},- <<"latitude">> => <<"1.0">>,- <<"longitude">> => <<"2.0">>,- <<"version">> => 4- },- Flags = #{- self_mute => true,- self_deaf => false,- self_video => false,- self_stream => false,- is_mobile => false,- suppress => false- },- State = #{voice_states => #{<<"conn">> => ExistingVS}, sessions => #{}},- {reply, Reply, NewState} = guild_voice_state:update_voice_state_data(#{- connection_id => <<"conn">>,- channel_id => <<"2">>,- flags => Flags,- member => Member,- existing_voice_state => ExistingVS,- voice_states => #{<<"conn">> => ExistingVS},- state => State,- needs_token => false,- viewer_stream_keys => []- }),- ?assertEqual(true, maps:get(success, Reply)),- StoredVS = maps:get(<<"conn">>, maps:get(voice_states, NewState)),- ?assertEqual(5, maps:get(<<"version">>, StoredVS)),- ?assertEqual(true, maps:get(<<"self_mute">>, StoredVS)),- ?assertEqual(Member, maps:get(<<"member">>, StoredVS)),- ?assertEqual(<<"1.0">>, maps:get(<<"latitude">>, StoredVS)),- ReplyVS = maps:get(voice_state, Reply),- ?assertNot(maps:is_key(<<"latitude">>, ReplyVS)),- ?assertEqual(Member, maps:get(<<"member">>, ReplyVS)),- ?assertEqual(5, maps:get(<<"version">>, ReplyVS)).--has_voice_state_change_no_change_test() ->- ExistingVoiceState = existing_voice_state(#{<<"self_mute">> => true}),- ?assertNot(default_self_mute_change(ExistingVoiceState)).--has_voice_state_change_channel_change_test() ->- ExistingVoiceState = existing_voice_state(#{}),- ?assert(- guild_voice_state:has_voice_state_change(- ExistingVoiceState,- change_fields(#{channel_id => <<"200">>})- )- ).--has_voice_state_change_self_mute_change_test() ->- ExistingVoiceState = existing_voice_state(#{}),- ?assert(default_self_mute_change(ExistingVoiceState)).--has_voice_state_change_server_mute_change_test() ->- ExistingVoiceState = existing_voice_state(#{}),- ?assert(- guild_voice_state:has_voice_state_change(- ExistingVoiceState, change_fields(#{server_mute => true})- )- ).--has_voice_state_change_suppress_change_test() ->- ExistingVoiceState = existing_voice_state(#{}),- ?assert(- guild_voice_state:has_voice_state_change(- ExistingVoiceState, change_fields(#{suppress => true})- )- ).--has_voice_state_change_viewer_stream_keys_change_test() ->- ExistingVoiceState = existing_voice_state(#{}),- ?assert(- guild_voice_state:has_voice_state_change(- ExistingVoiceState,- change_fields(#{viewer_stream_keys => [<<"999:100:conn">>]})- )- ).--has_voice_state_change_defaults_test() ->- ExistingVoiceState = #{},- ?assertNot(- guild_voice_state:has_voice_state_change(- ExistingVoiceState, change_fields(#{channel_id => null})- )- ).--existing_voice_state(Overrides) ->- maps:merge(- #{- <<"channel_id">> => <<"100">>,- <<"mute">> => false,- <<"deaf">> => false,- <<"self_mute">> => false,- <<"self_deaf">> => false,- <<"self_video">> => false,- <<"self_stream">> => false,- <<"is_mobile">> => false,- <<"suppress">> => false,- <<"viewer_stream_keys">> => []- },- Overrides- ).--default_self_mute_change(ExistingVoiceState) ->- guild_voice_state:has_voice_state_change(- ExistingVoiceState, change_fields(#{self_mute => true})- ).--change_fields(Overrides) ->- maps:merge(- #{- channel_id => <<"100">>,- server_mute => false,- server_deaf => false,- self_mute => false,- self_deaf => false,- self_video => false,- self_stream => false,- is_mobile => false,- suppress => false,- viewer_stream_keys => []- },- Overrides- ).diff --git a/fluxer_gateway/test/process_registry_cleanup_tests.erl b/fluxer_gateway/test/process_registry_cleanup_tests.erldeleted file mode 100644index 90f3d0be4..000000000--- a/fluxer_gateway/test/process_registry_cleanup_tests.erl+++ /dev/null@@ -1,98 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(process_registry_cleanup_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--cleanup_on_down_preserves_loading_test() ->- DeadPid = list_to_pid("<0.100.0>"),- AlivePid = list_to_pid("<0.101.0>"),- Ref1 = make_ref(),- Ref2 = make_ref(),-- Map = #{- guild_1 => {DeadPid, Ref1},- guild_2 => loading,- guild_3 => {AlivePid, Ref2}- },-- Result = process_registry:cleanup_on_down(DeadPid, Map),-- ?assertEqual(2, maps:size(Result)),- ?assertEqual(loading, maps:get(guild_2, Result)),- ?assertEqual({AlivePid, Ref2}, maps:get(guild_3, Result)),- ?assertEqual(false, maps:is_key(guild_1, Result)).--cleanup_on_down_duplicate_pids_test() ->- DeadPid = list_to_pid("<0.100.0>"),- Ref1 = make_ref(),- Ref2 = make_ref(),-- Map = #{- guild_1 => {DeadPid, Ref1},- guild_2 => {DeadPid, Ref2}- },-- Result = process_registry:cleanup_on_down(DeadPid, Map),- ?assertEqual(0, maps:size(Result)).--typed_cleanup_on_down_unregisters_runtime_prefixes_test() ->- process_registry:init(),- DeadPid = list_to_pid("<0.100.0>"),- RuntimeEntries = [- {call, 9001},- {guild, 9002},- {presence, 9003},- {session, <<"session-9004">>}- ],- try- lists:foreach(- fun({Prefix, Id}) ->- Key = process_registry:build_process_key(Prefix, Id),- ets:insert(process_registry_table, {Key, DeadPid}),- Result = process_registry:cleanup_on_down(- Prefix, DeadPid, #{Id => {DeadPid, make_ref()}}- ),- ?assertEqual(#{}, Result),- ?assertEqual([], ets:lookup(process_registry_table, Key))- end,- RuntimeEntries- )- after- lists:foreach(- fun({Prefix, Id}) ->- process_registry:safe_unregister(process_registry:build_process_key(Prefix, Id))- end,- RuntimeEntries- )- end.--typed_cleanup_on_down_keeps_replacement_registry_pid_test() ->- process_registry:init(),- Id = 9101,- Key = process_registry:build_process_key(presence, Id),- DeadPid = list_to_pid("<0.100.0>"),- ReplacementPid = list_to_pid("<0.101.0>"),- try- ets:insert(process_registry_table, {Key, ReplacementPid}),- Result = process_registry:cleanup_on_down(- presence, DeadPid, #{Id => {DeadPid, make_ref()}}- ),- ?assertEqual(#{}, Result),- ?assertEqual([{Key, ReplacementPid}], ets:lookup(process_registry_table, Key))- after- process_registry:safe_unregister(Key)- end.--typed_cleanup_on_down_ignores_unkeyable_ids_test() ->- process_registry:init(),- DeadPid = list_to_pid("<0.100.0>"),- Result = process_registry:cleanup_on_down(- guild,- DeadPid,- #{- bad_id => {DeadPid, make_ref()},- 9201 => loading- }- ),- ?assertEqual(#{9201 => loading}, Result).diff --git a/fluxer_gateway/test/process_registry_integration_tests.erl b/fluxer_gateway/test/process_registry_integration_tests.erldeleted file mode 100644index 64992f337..000000000--- a/fluxer_gateway/test/process_registry_integration_tests.erl+++ /dev/null@@ -1,42 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(process_registry_integration_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(REGISTRY_TABLE, process_registry_table).--force_stop_process_kills_unresponsive_test_() ->- {timeout, 15, fun() ->- Pid = spawn(fun trapped_wait_loop/0),- ?assert(process_liveness:is_alive(Pid)),- process_registry:force_stop_process(Pid),- timer:sleep(100),- ?assertEqual(false, process_liveness:is_alive(Pid))- end}.--register_and_monitor_duplicate_stops_loser_test_() ->- {timeout, 15, fun() ->- process_registry:init(),- Key = {test_reg, 1007},- WinnerPid = spawn_sleep(5000),- ets:insert(?REGISTRY_TABLE, {Key, WinnerPid}),- LoserPid = spawn(fun trapped_wait_loop/0),- ?assert(process_liveness:is_alive(LoserPid)),- Result = process_registry:register_and_monitor(Key, LoserPid, #{}),- ?assertMatch({ok, WinnerPid, _, _}, Result),- timer:sleep(100),- ?assertEqual(false, process_liveness:is_alive(LoserPid)),- process_registry:registry_unregister(Key)- end}.--spawn_sleep(Milliseconds) ->- spawn(fun() -> timer:sleep(Milliseconds) end).--trapped_wait_loop() ->- process_flag(trap_exit, true),- receive- never_arrives -> ok- after infinity ->- ok- end.diff --git a/fluxer_gateway/test/process_registry_lookup_tests.erl b/fluxer_gateway/test/process_registry_lookup_tests.erldeleted file mode 100644index 411bfe8b5..000000000--- a/fluxer_gateway/test/process_registry_lookup_tests.erl+++ /dev/null@@ -1,37 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(process_registry_lookup_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(REGISTRY_TABLE, process_registry_table).--lookup_or_monitor_reuses_existing_ref_for_same_pid_test() ->- process_registry:init(),- Key = {test_lookup, 3006},- MapKey = same_pid_key,-- Pid = spawn(fun() -> timer:sleep(300) end),- ets:insert(?REGISTRY_TABLE, {Key, Pid}),-- {ok, Pid, Ref1, Map1} = process_registry:lookup_or_monitor(Key, MapKey, #{}),- {ok, Pid, Ref2, Map2} = process_registry:lookup_or_monitor(Key, MapKey, Map1),-- ?assertEqual(Ref1, Ref2),- ?assertEqual({Pid, Ref1}, maps:get(MapKey, Map2)),-- process_registry:registry_unregister(Key).--safe_unregister_pid_conditional_keeps_other_owner_test() ->- process_registry:init(),- Key = {test_unreg, 4007},- OldPid = list_to_pid("<0.100.0>"),- NewPid = list_to_pid("<0.101.0>"),-- ets:insert(?REGISTRY_TABLE, {Key, NewPid}),-- ?assertEqual(ok, process_registry:safe_unregister(Key, OldPid)),- ?assertEqual([{Key, NewPid}], ets:lookup(?REGISTRY_TABLE, Key)),-- ?assertEqual(ok, process_registry:safe_unregister(Key, NewPid)),- ?assertEqual([], ets:lookup(?REGISTRY_TABLE, Key)).diff --git a/fluxer_gateway/test/process_registry_tests.erl b/fluxer_gateway/test/process_registry_tests.erldeleted file mode 100644index c4de37914..000000000--- a/fluxer_gateway/test/process_registry_tests.erl+++ /dev/null@@ -1,95 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(process_registry_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").---define(REGISTRY_TABLE, process_registry_table).--register_and_monitor_race_condition_test() ->- process_registry:init(),- Key = {test_reg, 1003},- ProcessMap = #{},-- WinnerPid = spawn_sleep(200),- ets:insert(?REGISTRY_TABLE, {Key, WinnerPid}),-- LoserPid = spawn_sleep(100),-- Result = process_registry:register_and_monitor(Key, LoserPid, ProcessMap),-- ?assertMatch({ok, WinnerPid, _Ref, _NewMap}, Result),- {ok, ReturnedPid, Ref, NewMap} = Result,-- ?assertEqual(WinnerPid, ReturnedPid),- ?assertEqual(WinnerPid, process_registry:registry_whereis(Key)),-- timer:sleep(50),- ?assertEqual(false, process_liveness:is_alive(LoserPid)),-- ?assertEqual({WinnerPid, Ref}, maps:get(Key, NewMap)),-- process_registry:registry_unregister(Key).--register_and_monitor_concurrent_test_() ->- {timeout, 10, fun() ->- process_registry:init(),- Key = {test_reg, 1006},-- Parent = self(),- Pids = [spawn_register_worker(Parent, Key) || _ <- lists:seq(1, 5)],-- Results = [- receive- {P, R} -> R- after 2000 -> timeout- end- || P <- Pids- ],-- ?assertEqual(5, length(Results)),-- SuccessResults = [R || R <- Results, is_tuple(R), element(1, R) =:= ok],- RaceErrors = [R || R <- Results, R =:= {error, registration_race_condition}],- Timeouts = [R || R <- Results, R =:= timeout],-- ?assertEqual(0, length(Timeouts)),-- ?assertMatch([_ | _], SuccessResults),-- ?assertEqual(5, length(SuccessResults) + length(RaceErrors)),-- assert_success_results_share_pid(SuccessResults),-- process_registry:registry_unregister(Key)- end}.--registry_whereis_dead_test() ->- process_registry:init(),- Key = {test_whereis, 2002},- Pid = spawn(fun() -> ok end),- timer:sleep(10),- ets:insert(?REGISTRY_TABLE, {Key, Pid}),- ?assertEqual(undefined, process_registry:registry_whereis(Key)).--spawn_sleep(Milliseconds) ->- spawn(fun() -> timer:sleep(Milliseconds) end).--assert_success_results_share_pid([{ok, FirstPid, _, _} | RestResults]) ->- AllSamePid = lists:all(- fun(Result) -> success_pid_matches(FirstPid, Result) end,- RestResults- ),- ?assert(AllSamePid).--success_pid_matches(FirstPid, {ok, Pid, _, _}) ->- Pid =:= FirstPid;-success_pid_matches(_FirstPid, _Result) ->- false.--spawn_register_worker(Parent, Key) ->- spawn(fun() ->- Pid = spawn_sleep(200),- Result = process_registry:register_and_monitor(Key, Pid, #{}),- Parent ! {self(), Result}- end).diff --git a/fluxer_gateway/test/rpc_client_tests.erl b/fluxer_gateway/test/rpc_client_tests.erldeleted file mode 100644index 547e3e4a3..000000000--- a/fluxer_gateway/test/rpc_client_tests.erl+++ /dev/null@@ -1,26 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(rpc_client_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--rpc_headers_uses_request_ip_test() ->- Headers = rpc_client:rpc_headers(#{- <<"type">> => <<"session">>,- <<"ip">> => <<"203.0.113.7">>- }),- ?assertEqual(<<"203.0.113.7">>, proplists:get_value(<<"x-forwarded-for">>, Headers)).--rpc_headers_falls_back_to_loopback_without_request_ip_test() ->- Headers = rpc_client:rpc_headers(#{<<"type">> => <<"guild_collection">>}),- ?assertEqual(<<"127.0.0.1">>, proplists:get_value(<<"x-forwarded-for">>, Headers)).--is_retryable_5xx_test() ->- ?assert(rpc_client:is_retryable({rpc_error, 500, <<"Internal server error">>})),- ?assert(rpc_client:is_retryable({rpc_error, 502, <<"Bad gateway">>})),- ?assert(rpc_client:is_retryable({rpc_error, 503, <<"Service unavailable">>})).--is_retryable_4xx_test() ->- ?assertNot(rpc_client:is_retryable({rpc_error, 401, <<"Unauthorized">>})),- ?assertNot(rpc_client:is_retryable({rpc_error, 404, <<"Not found">>})),- ?assertNot(rpc_client:is_retryable({rpc_error, 429, <<"Rate limited">>})).diff --git a/fluxer_gateway/test/voice_p2p_tests.erl b/fluxer_gateway/test/voice_p2p_tests.erldeleted file mode 100644index af6dca4c9..000000000--- a/fluxer_gateway/test/voice_p2p_tests.erl+++ /dev/null@@ -1,242 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(voice_p2p_tests).--typing([eqwalizer]).---include_lib("eunit/include/eunit.hrl").--peer(ConnectionId, SessionId, P2p) ->- #{- <<"connection_id">> => ConnectionId,- <<"session_id">> => SessionId,- <<"user_id">> => <<"10">>,- <<"p2p">> => P2p- }.--mesh(Count) ->- [- peer(integer_to_binary(Index), <<"sess-", (integer_to_binary(Index))/binary>>, true)- || Index <- lists:seq(1, Count)- ].--agreed_requires_an_explicit_true_from_a_user_test() ->- ?assert(voice_p2p:agreed(true, false)),- ?assertNot(voice_p2p:agreed(true, true)),- ?assertNot(voice_p2p:agreed(false, false)),- ?assertNot(voice_p2p:agreed(undefined, false)),- ?assertNot(voice_p2p:agreed(<<"true">>, false)).--declined_requires_an_explicit_false_test() ->- ?assert(voice_p2p:declined(false)),- ?assertNot(voice_p2p:declined(true)),- ?assertNot(voice_p2p:declined(undefined)),- ?assertNot(voice_p2p:declined(null)).--channel_mode_test() ->- ?assertEqual(empty, voice_p2p:channel_mode([])),- ?assertEqual(p2p, voice_p2p:channel_mode(mesh(2))),- ?assertEqual(sfu, voice_p2p:channel_mode([peer(<<"a">>, <<"s">>, false), #{}])),- ?assertEqual(mixed, voice_p2p:channel_mode([peer(<<"a">>, <<"s">>, false) | mesh(1)])).--pinned_reads_the_channel_flag_test() ->- ?assert(voice_p2p:pinned(#{<<"rtc_p2p">> => true})),- ?assertNot(voice_p2p:pinned(#{<<"rtc_p2p">> => false})),- ?assertNot(voice_p2p:pinned(#{})),- ?assertNot(voice_p2p:pinned(undefined)).--join_decision_for_a_live_mesh_test() ->- ?assertEqual({p2p, joiner, 2}, voice_p2p:join_decision(true, mesh(1), false, false)),- ?assertEqual({p2p, joiner, 4}, voice_p2p:join_decision(true, mesh(3), false, false)),- ?assertEqual(- {reject, voice_p2p_consent_required},- voice_p2p:join_decision(false, mesh(3), false, false)- ),- ?assertEqual(- {reject, voice_p2p_consent_required},- voice_p2p:join_decision(false, mesh(4), false, false)- ),- ?assertEqual(- {reject, voice_channel_full}, voice_p2p:join_decision(true, mesh(4), false, false)- ).--join_decision_for_an_empty_channel_test() ->- ?assertEqual({p2p, initiator, 1}, voice_p2p:join_decision(true, [], false, false)),- ?assertEqual({p2p, initiator, 1}, voice_p2p:join_decision(true, [], false, true)),- ?assertEqual(sfu, voice_p2p:join_decision(false, [], false, false)),- ?assertEqual(sfu, voice_p2p:join_decision(false, [], false, true)),- ?assertEqual(sfu, voice_p2p:join_decision(true, [], true, false)),- ?assertEqual(sfu, voice_p2p:join_decision(false, [], true, true)).--join_decision_for_an_sfu_call_ignores_the_flag_test() ->- Sfu = [peer(<<"a">>, <<"s">>, false)],- ?assertEqual(sfu, voice_p2p:join_decision(true, Sfu, false, false)),- ?assertEqual(sfu, voice_p2p:join_decision(false, Sfu, false, true)).--admit_test() ->- Grant = {p2p, <<"conn">>, [], 2},- Token = #{token => <<"tok">>},- ?assertEqual(Grant, voice_p2p:admit({p2p, initiator, 1}, Grant)),- ?assertEqual(Grant, voice_p2p:admit({p2p, joiner, 3}, Grant)),- ?assertEqual(sfu, voice_p2p:admit({p2p, initiator, 1}, Token)),- ?assertEqual({reject, voice_p2p_unavailable}, voice_p2p:admit({p2p, joiner, 3}, Token)),- ?assertEqual(sfu, voice_p2p:admit(sfu, Token)),- ?assertEqual({reject, voice_token_failed}, voice_p2p:admit(sfu, Grant)).--admit_maps_a_size_decline_to_channel_full_test() ->- Declined = {declined, voice_channel_full},- ?assertEqual({reject, voice_channel_full}, voice_p2p:admit({p2p, joiner, 3}, Declined)),- ?assertEqual({reject, voice_channel_full}, voice_p2p:admit({p2p, initiator, 1}, Declined)),- ?assertEqual({reject, voice_token_failed}, voice_p2p:admit(sfu, Declined)).--invariant_violation_test() ->- ?assertEqual(ok, voice_p2p:invariant_violation([])),- ?assertEqual(ok, voice_p2p:invariant_violation(mesh(4))),- ?assertEqual({error, voice_channel_full}, voice_p2p:invariant_violation(mesh(5))),- ?assertEqual(- {error, voice_p2p_consent_required},- voice_p2p:invariant_violation([peer(<<"a">>, <<"s">>, false) | mesh(1)])- ),- ?assertEqual(ok, voice_p2p:invariant_violation([peer(<<"a">>, <<"s">>, false)])).--invariant_violation_holds_a_mesh_to_the_configured_cap_test() ->- ?assertEqual(ok, voice_p2p:invariant_violation(mesh(2), 2)),- ?assertEqual({error, voice_channel_full}, voice_p2p:invariant_violation(mesh(3), 2)),- ?assertEqual(ok, voice_p2p:invariant_violation(mesh(4), undefined)),- ?assertEqual({error, voice_channel_full}, voice_p2p:invariant_violation(mesh(5), 9)),- ?assertEqual(ok, voice_p2p:invariant_violation([peer(<<"a">>, <<"s">>, false)], 1)).--reports_rejection_test() ->- ?assert(voice_p2p:reports_rejection(voice_p2p_consent_required)),- ?assert(voice_p2p:reports_rejection(voice_p2p_unavailable)),- ?assert(voice_p2p:reports_rejection(voice_channel_full)),- ?assertNot(voice_p2p:reports_rejection(voice_token_failed)).--to_sfu_clears_the_flag_and_bumps_the_version_test() ->- VoiceState = (peer(<<"a">>, <<"s">>, true))#{<<"version">> => 3},- Converted = voice_p2p:to_sfu(VoiceState),- ?assertEqual(false, maps:get(<<"p2p">>, Converted)),- ?assertEqual(4, maps:get(<<"version">>, Converted)).--add_to_token_request_test() ->- Request = #{<<"type">> => <<"voice_get_token">>},- ?assertEqual(Request, voice_p2p:add_to_token_request(Request, sfu, <<"SE">>)),- ?assertEqual(- Request#{- <<"p2p">> => true,- <<"p2p_initiator">> => true,- <<"p2p_participant_count">> => 1,- <<"country_code">> => <<"SE">>- },- voice_p2p:add_to_token_request(Request, {p2p, initiator, 1}, <<"SE">>)- ),- ?assertEqual(- Request#{- <<"p2p">> => true, <<"p2p_initiator">> => false, <<"p2p_participant_count">> => 3- },- voice_p2p:add_to_token_request(Request, {p2p, joiner, 3}, undefined)- ).--grant_reads_a_p2p_grant_test() ->- Stun = #{<<"urls">> => [<<"stun:stun.example:3478">>], <<"ignored">> => true},- Data = #{<<"p2p">> => true, <<"connectionId">> => <<"conn-1">>, <<"iceServers">> => [Stun]},- ?assertEqual(- {p2p, <<"conn-1">>, [#{<<"urls">> => [<<"stun:stun.example:3478">>]}], 4},- voice_p2p:grant(Data)- ).--grant_reads_the_configured_cap_test() ->- Data = #{<<"p2p">> => true, <<"connectionId">> => <<"conn-1">>, <<"iceServers">> => []},- ?assertEqual(- {p2p, <<"conn-1">>, [], 3}, voice_p2p:grant(Data#{<<"maxParticipants">> => 3})- ),- ?assertEqual(- {p2p, <<"conn-1">>, [], 4}, voice_p2p:grant(Data#{<<"maxParticipants">> => 9})- ),- ?assertEqual(- {p2p, <<"conn-1">>, [], 4}, voice_p2p:grant(Data#{<<"maxParticipants">> => 0})- ).--grant_keeps_only_urls_of_each_ice_server_test() ->- Server = #{- <<"urls">> => [<<"stun:stun.example:3478">>],- <<"username">> => <<"user">>,- <<"credential">> => <<"secret">>- },- Data = #{- <<"p2p">> => true, <<"connectionId">> => <<"conn-1">>, <<"iceServers">> => [Server]- },- ?assertEqual(- {p2p, <<"conn-1">>, [#{<<"urls">> => [<<"stun:stun.example:3478">>]}], 4},- voice_p2p:grant(Data)- ).--grant_reads_a_size_decline_test() ->- ?assertEqual(- {declined, voice_channel_full},- voice_p2p:grant(#{<<"p2p">> => false, <<"declineReason">> => <<"channel_full">>})- ),- ?assertEqual(- sfu, voice_p2p:grant(#{<<"p2p">> => false, <<"declineReason">> => <<"unknown">>})- ).--grant_reads_a_token_response_as_sfu_test() ->- ?assertEqual(- sfu,- voice_p2p:grant(#{- <<"token">> => <<"tok">>,- <<"endpoint">> => <<"wss://voice.example">>,- <<"connectionId">> => <<"conn-1">>- })- ).--voice_server_update_shape_test() ->- IceServers = [#{<<"urls">> => [<<"stun:stun.example:3478">>]}],- ?assertEqual(- #{- <<"p2p">> => true,- <<"ice_servers">> => IceServers,- <<"connection_id">> => <<"conn-1">>,- <<"channel_id">> => <<"100">>,- <<"guild_id">> => <<"999">>- },- voice_p2p:voice_server_update(<<"conn-1">>, 100, 999, IceServers)- ),- ?assertNot(- maps:is_key(- <<"guild_id">>, voice_p2p:voice_server_update(<<"conn-1">>, 100, null, IceServers)- )- ).--signal_route_allows_a_mesh_peer_test() ->- [Sender, Target] = mesh(2),- ?assertEqual({ok, Sender, Target}, voice_p2p:signal_route(mesh(2), <<"sess-1">>, <<"2">>)).--signal_route_denies_a_sender_outside_the_mesh_test() ->- ?assertEqual(error, voice_p2p:signal_route(mesh(2), <<"sess-9">>, <<"2">>)).--signal_route_denies_an_unknown_target_test() ->- ?assertEqual(error, voice_p2p:signal_route(mesh(2), <<"sess-1">>, <<"9">>)).--signal_route_denies_the_senders_own_connection_test() ->- ?assertEqual(error, voice_p2p:signal_route(mesh(2), <<"sess-1">>, <<"1">>)).--signal_route_denies_sfu_voice_states_test() ->- Sfu = [peer(<<"1">>, <<"sess-1">>, false), peer(<<"2">>, <<"sess-2">>, false)],- ?assertEqual(error, voice_p2p:signal_route(Sfu, <<"sess-1">>, <<"2">>)),- Mixed = [peer(<<"1">>, <<"sess-1">>, true), peer(<<"2">>, <<"sess-2">>, false)],- ?assertEqual(error, voice_p2p:signal_route(Mixed, <<"sess-1">>, <<"2">>)).--signal_payload_shape_test() ->- [Sender | _] = mesh(1),- Data = #{<<"type">> => <<"offer">>, <<"sdp">> => <<"v=0">>},- ?assertEqual(- #{- <<"guild_id">> => <<"999">>,- <<"channel_id">> => <<"100">>,- <<"from">> => <<"1">>,- <<"user_id">> => <<"10">>,- <<"data">> => Data- },- voice_p2p:signal_payload(999, 100, Sender, Data)- ),- ?assertNot(maps:is_key(<<"guild_id">>, voice_p2p:signal_payload(null, 100, Sender, Data))).diff --git a/fluxer_gateway/test/voice_utils_tests.erl b/fluxer_gateway/test/voice_utils_tests.erldeleted file mode 100644index 52bcea592..000000000--- a/fluxer_gateway/test/voice_utils_tests.erl+++ /dev/null@@ -1,126 +0,0 @@-%% SPDX-License-Identifier: AGPL-3.0-or-later---module(voice_utils_tests).--typing([eqwalizer]).--include_lib("eunit/include/eunit.hrl").--build_force_disconnect_rpc_request_test() ->- Req = voice_utils:build_force_disconnect_rpc_request(123, 456, 789, <<"conn">>),- ?assertEqual(<<"voice_force_disconnect_participant">>, maps:get(<<"type">>, Req)),- ?assertEqual(<<"123">>, maps:get(<<"guild_id">>, Req)),- ?assertEqual(<<"conn">>, maps:get(<<"connection_id">>, Req)).--build_update_participant_rpc_request_with_permissions_test() ->- VoicePerms = #{- can_speak => true,- can_stream => false,- can_video => false- },- Req = voice_utils:build_update_participant_rpc_request(- 123, 456, 789, true, false, VoicePerms- ),- ?assertEqual(true, maps:get(<<"can_speak">>, Req)),- ?assertEqual(false, maps:get(<<"can_stream">>, Req)),- ?assertEqual(false, maps:get(<<"can_video">>, Req)).--apply_voice_permissions_to_flags_suppresses_without_speak_test() ->- Flags = #{self_mute => false, suppress => false},- VoicePerms = #{- can_speak => false,- can_stream => true,- can_video => true- },- Result = voice_utils:apply_voice_permissions_to_flags(Flags, VoicePerms),- ?assertEqual(false, maps:get(self_mute, Result)),- ?assertEqual(true, maps:get(suppress, Result)).--apply_voice_permissions_to_flags_clears_self_stream_without_stream_test() ->- Flags = #{self_stream => true, self_video => true, suppress => false},- VoicePerms = #{- can_speak => true,- can_stream => false,- can_video => false- },- Result = voice_utils:apply_voice_permissions_to_flags(Flags, VoicePerms),- ?assertEqual(false, maps:get(self_stream, Result)),- ?assertEqual(false, maps:get(self_video, Result)),- ?assertEqual(false, maps:get(suppress, Result)).--apply_voice_permissions_to_flags_keeps_self_stream_with_stream_test() ->- Flags = #{self_stream => true, self_video => true, suppress => false},- VoicePerms = #{- can_speak => true,- can_stream => true,- can_video => true- },- Result = voice_utils:apply_voice_permissions_to_flags(Flags, VoicePerms),- ?assertEqual(true, maps:get(self_stream, Result)),- ?assertEqual(true, maps:get(self_video, Result)).--apply_voice_permissions_to_flags_clears_self_stream_denied_by_overwrite_test() ->- UserId = 10,- ChannelId = 500,- State = stream_denied_overwrite_state(UserId, ChannelId),- VoicePerms = voice_utils:compute_voice_permissions(UserId, ChannelId, State),- ?assertEqual(true, maps:get(can_speak, VoicePerms)),- ?assertEqual(false, maps:get(can_stream, VoicePerms)),- Result = voice_utils:apply_voice_permissions_to_flags(- #{self_stream => true, self_video => true, suppress => false}, VoicePerms- ),- ?assertEqual(false, maps:get(self_stream, Result)),- ?assertEqual(false, maps:get(self_video, Result)),- ?assertEqual(false, maps:get(suppress, Result)).--stream_denied_overwrite_state(UserId, ChannelId) ->- GuildId = 90,- RoleId = 300,- RolePerms =- constants:view_channel_permission() bor- constants:connect_permission() bor- constants:speak_permission() bor- constants:stream_permission(),- #{- id => GuildId,- data => #{- <<"guild">> => #{<<"owner_id">> => <<"999">>},- <<"roles">> => [- #{<<"id">> => integer_to_binary(GuildId), <<"permissions">> => <<"0">>},- #{- <<"id">> => integer_to_binary(RoleId),- <<"permissions">> => integer_to_binary(RolePerms)- }- ],- <<"members">> => [- #{- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},- <<"roles">> => [integer_to_binary(RoleId)]- }- ],- <<"channels">> => [- #{- <<"id">> => integer_to_binary(ChannelId),- <<"permission_overwrites">> => [- #{- <<"id">> => integer_to_binary(RoleId),- <<"type">> => 0,- <<"allow">> => <<"0">>,- <<"deny">> => integer_to_binary(constants:stream_permission())- }- ]- }- ]- }- }.--build_voice_token_rpc_request_with_nonce_test() ->- VoicePerms = #{- can_speak => true,- can_stream => false,- can_video => false- },- Req = voice_utils:build_voice_token_rpc_request(- 123, 456, 789, null, null, null, VoicePerms, <<"test-nonce-123">>- ),- ?assertEqual(<<"test-nonce-123">>, maps:get(<<"token_nonce">>, Req)),- ?assertEqual(true, maps:get(<<"can_speak">>, Req)),- ?assertEqual(false, maps:get(<<"can_stream">>, Req)).