4646 password := binary (),
4747 virtual_host := binary (),
4848 confirms_enabled := boolean (),
49- max_worker_queue_len := non_neg_integer () | infinity }.
49+ max_worker_queue_len := non_neg_integer () | infinity ,
50+ reconnect => reconnect ()}.
51+
52+ -type reconnect () :: #{attempts := pos_integer (),
53+ delay := non_neg_integer () % milliseconds
54+ }.
5055
5156-type publish_result () :: boolean () | timeout | {channel_exception , any (), any ()}.
5257
@@ -197,7 +202,30 @@ maybe_restart_rabbit_connection(#{connection := Conn} = State) ->
197202 end .
198203
199204-spec establish_rabbit_connection (state ()) -> state ().
205+ establish_rabbit_connection (State = #{opts := #{reconnect := #{attempts := Attempts }}}) ->
206+ establish_rabbit_connection (State , Attempts );
200207establish_rabbit_connection (State ) ->
208+ establish_rabbit_connection (State , 0 ).
209+
210+ -spec establish_rabbit_connection (state (), non_neg_integer ()) -> state ().
211+ establish_rabbit_connection (State , RemainingAttempts ) ->
212+ case start_amqp_connection (State ) of
213+ {ok , NewState } ->
214+ NewState ;
215+ {error , Error } when RemainingAttempts > 0 ->
216+ ? LOG_WARNING (#{what => rabbit_connection_failed , reason => Error , worker_state => State ,
217+ remaining_attempts => RemainingAttempts }),
218+ #{opts := #{reconnect := #{delay := Delay }}} = State ,
219+ timer :sleep (Delay ),
220+ establish_rabbit_connection (State , RemainingAttempts - 1 );
221+ {error , Error } when RemainingAttempts =:= 0 ->
222+ ErrorInfo = #{what => rabbit_connection_failed , reason => Error , worker_state => State },
223+ ? LOG_ERROR (ErrorInfo ),
224+ exit (ErrorInfo )
225+ end .
226+
227+ -spec start_amqp_connection (state ()) -> {ok , state ()} | {error , term ()}.
228+ start_amqp_connection (State ) ->
201229 #{opts := Opts , host_type := HostType , pool_tag := PoolTag } = State ,
202230 case amqp_connection :start (mongoose_amqp :network_params (Opts )) of
203231 {ok , Connection } ->
@@ -208,14 +236,12 @@ establish_rabbit_connection(State) ->
208236 maybe_enable_confirms (Channel , Opts ),
209237 ? LOG_DEBUG (#{what => rabbit_connection_established ,
210238 host_type => HostType , pool_tag => PoolTag , opts => Opts }),
211- State #{connection => Connection , channel => Channel };
239+ { ok , State #{connection => Connection , channel => Channel } };
212240 {error , Error } ->
213241 mongoose_instrument :execute (wpool_rabbit_connections ,
214242 #{host_type => HostType , pool_tag => PoolTag },
215243 #{failed => 1 }),
216- ? LOG_ERROR (#{what => rabbit_connection_failed , reason => Error ,
217- host_type => HostType , pool_tag => PoolTag , opts => Opts }),
218- exit (" connection to a Rabbit server failed" )
244+ {error , Error }
219245 end .
220246
221247-spec close_rabbit_connection (Connection :: pid (), Channel :: pid (),
0 commit comments