@@ -4,6 +4,7 @@ defmodule PostHog.Sender do
4
4
5
5
defstruct [
6
6
:registry ,
7
+ :index ,
7
8
:api_client ,
8
9
:max_batch_time_ms ,
9
10
:max_batch_events ,
@@ -15,7 +16,7 @@ defmodule PostHog.Sender do
15
16
name =
16
17
opts
17
18
|> Keyword . fetch! ( :supervisor_name )
18
- |> PostHog.Registry . via ( __MODULE__ )
19
+ |> PostHog.Registry . via ( __MODULE__ , opts [ :index ] )
19
20
20
21
callers = Process . get ( :"$callers" , [ ] )
21
22
Process . flag ( :trap_exit , true )
@@ -33,8 +34,16 @@ defmodule PostHog.Sender do
33
34
PostHog.Test . remember_event ( supervisor_name , event )
34
35
35
36
_ ->
36
- supervisor_name
37
- |> PostHog.Registry . via ( __MODULE__ )
37
+ senders =
38
+ supervisor_name
39
+ |> PostHog.Registry . registry_name ( )
40
+ |> Registry . select ( [ { { { __MODULE__ , :_ } , :"$1" , :"$2" } , [ ] , [ { { :"$2" , :"$1" } } ] } ] )
41
+
42
+ # Pick the first available sender, otherwise random busy one.
43
+ senders
44
+ |> Keyword . get_lazy ( :available , fn ->
45
+ senders |> Keyword . values ( ) |> Enum . random ( )
46
+ end )
38
47
|> GenServer . cast ( { :event , event } )
39
48
end
40
49
end
@@ -45,6 +54,7 @@ defmodule PostHog.Sender do
45
54
def init ( { opts , callers } ) do
46
55
state = % __MODULE__ {
47
56
registry: PostHog.Registry . registry_name ( opts [ :supervisor_name ] ) ,
57
+ index: Keyword . fetch! ( opts , :index ) ,
48
58
api_client: Keyword . fetch! ( opts , :api_client ) ,
49
59
max_batch_time_ms: Keyword . fetch! ( opts , :max_batch_time_ms ) ,
50
60
max_batch_events: Keyword . fetch! ( opts , :max_batch_events ) ,
@@ -54,6 +64,9 @@ defmodule PostHog.Sender do
54
64
55
65
Process . put ( :"$callers" , callers )
56
66
67
+ { :available , nil } =
68
+ Registry . update_value ( state . registry , registry_key ( state . index ) , fn _ -> :available end )
69
+
57
70
{ :ok , state }
58
71
end
59
72
@@ -81,7 +94,9 @@ defmodule PostHog.Sender do
81
94
82
95
@ impl GenServer
83
96
def handle_continue ( :send_batch , state ) do
97
+ Registry . update_value ( state . registry , registry_key ( state . index ) , fn _ -> :busy end )
84
98
PostHog.API . post_batch ( state . api_client , state . events )
99
+ Registry . update_value ( state . registry , registry_key ( state . index ) , fn _ -> :available end )
85
100
{ :noreply , % { state | events: [ ] , num_events: 0 } }
86
101
end
87
102
@@ -91,4 +106,6 @@ defmodule PostHog.Sender do
91
106
end
92
107
93
108
def terminate ( _reason , _state ) , do: :ok
109
+
110
+ defp registry_key ( index ) , do: { __MODULE__ , index }
94
111
end
0 commit comments