Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Configuration for correlation plugin #245

Merged
merged 3 commits into from Dec 27, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 29 additions & 4 deletions src/plugins/nova_correlation_plugin.erl
Expand Up @@ -7,11 +7,13 @@

-include_lib("kernel/include/logger.hrl").

pre_request(Req, _) ->
UUID = uuid:uuid_to_string(uuid:get_v4()),
pre_request(Req, Opts) ->
CorrId = get_correlation_id(Req, Opts),
%% Update the loggers metadata with correlation-id
logger:update_process_metadata(#{<<"correlation-id">> => UUID}),
Req1 = cowboy_req:set_resp_header(<<"X-Correlation-ID">>, UUID, Req),
ok = update_logger_metadata(CorrId, Opts),
%% Redundant entry, allow controllers to erlang:get(correlation_id)
ok = put_process_dictionary(CorrId, Opts),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably a better idea to set a key in the Req object instead for keeping this in the process-dictionary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed so that it is set as the correlation_id field in the request object.

Req1 = cowboy_req:set_resp_header(<<"X-Correlation-ID">>, CorrId, Req),
{ok, Req1}.

post_request(Req, _) ->
Expand All @@ -25,3 +27,26 @@ plugin_info() ->
<<"Add X-Correlation-ID headers to response">>,
[]
}.

get_correlation_id(Req, #{ request_correlation_header := CorrelationHeader }) ->
case cowboy_req:header(CorrelationHeader, Req) of
undefined ->
uuid();
CorrId ->
CorrId
end;
get_correlation_id(_Req, _Opts) ->
uuid().

uuid() ->
uuid:uuid_to_string(uuid:get_v4()).

update_logger_metadata(CorrId, Opts) ->
LoggerKey = maps:get(logger_metadata_key, Opts, <<"correlation-id">>),
logger:update_process_metadata(#{LoggerKey => CorrId}).

put_process_dictionary(CorrId, Opts) ->
DictionaryKey = maps:get(dictionary_key, Opts, correlation_id),
erlang:put(DictionaryKey, CorrId),
ok.