@@ -8,17 +8,32 @@ defmodule Realtime.UsersCounter do
8
8
Adds a RealtimeChannel pid to the `:users` scope for a tenant so we can keep track of all connected clients for a tenant.
9
9
"""
10
10
@ spec add ( pid ( ) , String . t ( ) ) :: :ok
11
- def add ( pid , tenant ) , do: :syn . join ( :users , tenant , pid )
11
+ def add ( pid , tenant_id ) , do: tenant_id |> scope ( ) |> :syn . join ( tenant_id , pid )
12
12
13
13
@ doc """
14
14
Returns the count of all connected clients for a tenant for the cluster.
15
15
"""
16
16
@ spec tenant_users ( String . t ( ) ) :: non_neg_integer ( )
17
- def tenant_users ( tenant ) , do: :syn . member_count ( :users , tenant )
17
+ def tenant_users ( tenant_id ) , do: tenant_id |> scope ( ) |> :syn . member_count ( tenant_id )
18
18
19
19
@ doc """
20
20
Returns the count of all connected clients for a tenant for a single node.
21
21
"""
22
22
@ spec tenant_users ( atom , String . t ( ) ) :: non_neg_integer ( )
23
- def tenant_users ( node_name , tenant ) , do: :syn . member_count ( :users , tenant , node_name )
23
+ def tenant_users ( node_name , tenant_id ) , do: tenant_id |> scope ( ) |> :syn . member_count ( tenant_id , node_name )
24
+
25
+ @ doc """
26
+ Returns the scope for a given tenant id.
27
+ """
28
+ @ spec scope ( String . t ( ) ) :: atom ( )
29
+ def scope ( tenant_id ) do
30
+ shards = Application . get_env ( :realtime , :users_scope_shards )
31
+ shard = :erlang . phash2 ( tenant_id , shards )
32
+ :"users_#{ shard } "
33
+ end
34
+
35
+ def scopes ( ) do
36
+ shards = Application . get_env ( :realtime , :users_scope_shards )
37
+ Enum . map ( 0 .. ( shards - 1 ) , fn shard -> :"users_#{ shard } " end )
38
+ end
24
39
end
0 commit comments