fix: don't router request until dispatch is ready

This commit is contained in:
Zhongwen Deng 2022-05-09 11:30:48 +08:00
parent 068421d0e1
commit 34ad395abe
2 changed files with 18 additions and 24 deletions

View File

@ -25,7 +25,7 @@
-behaviour(gen_server).
-export([start_link/0, is_ready/0]).
-export([start_link/0, is_ready/1]).
-export([
init/1,
@ -37,8 +37,8 @@
code_change/3
]).
is_ready() ->
ready =:= gen_server:call(?MODULE, get_state, 10000).
is_ready(Timeout) ->
ready =:= gen_server:call(?MODULE, get_state, Timeout).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

View File

@ -21,33 +21,27 @@
-export([execute/2]).
execute(Req, Env) ->
waiting_dispatch_ready(),
case check_dispatch_ready(Env) of
true -> add_cors_flag(Req, Env);
false -> {stop, cowboy_req:reply(503, Req)}
end.
add_cors_flag(Req, Env) ->
CORS = emqx_conf:get([dashboard, cors], false),
case CORS andalso cowboy_req:header(<<"origin">>, Req, undefined) of
Origin = cowboy_req:header(<<"origin">>, Req, undefined),
case CORS andalso Origin =/= undefined of
false ->
{ok, Req, Env};
undefined ->
{ok, Req, Env};
_ ->
true ->
Req2 = cowboy_req:set_resp_header(<<"Access-Control-Allow-Origin">>, <<"*">>, Req),
{ok, Req2, Env}
end.
waiting_dispatch_ready() ->
waiting_dispatch_ready(5).
waiting_dispatch_ready(0) ->
ok;
waiting_dispatch_ready(Count) ->
case emqx_sys:uptime() < timer:minutes(1) of
true ->
case emqx_dashboard_listener:is_ready() of
true ->
ok;
false ->
timer:sleep(100),
waiting_dispatch_ready(Count - 1)
end;
check_dispatch_ready(Env) ->
case maps:is_key(options, Env) of
false ->
ok
true;
true ->
%% dashboard should always ready, if not, is_ready/1 will block until ready.
emqx_dashboard_listener:is_ready(timer:seconds(15))
end.