Skip to content

Commit

Permalink
Use json module when Erlang/OTP 27, jiffy with older ones
Browse files Browse the repository at this point in the history
  • Loading branch information
badlop committed May 2, 2024
1 parent 87f4828 commit 40d6724
Show file tree
Hide file tree
Showing 15 changed files with 100 additions and 66 deletions.
6 changes: 4 additions & 2 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ defmodule Ejabberd.MixProject do
def application do
[mod: {:ejabberd_app, []},
applications: [:idna, :inets, :kernel, :sasl, :ssl, :stdlib, :mix,
:fast_tls, :fast_xml, :fast_yaml, :jiffy, :jose,
:fast_tls, :fast_xml, :fast_yaml, :jose,
:p1_utils, :stringprep, :syntax_tools, :yconf]
++ cond_apps(),
included_applications: [:mnesia, :os_mon,
Expand Down Expand Up @@ -114,6 +114,7 @@ defmodule Ejabberd.MixProject do
if_version_below(~c"24", [{:d, :SYSTOOLS_APP_DEF_WITHOUT_OPTIONAL}]) ++
if_version_below(~c"24", [{:d, :OTP_BELOW_24}]) ++
if_version_below(~c"25", [{:d, :OTP_BELOW_25}]) ++
if_version_below(~c"27", [{:d, :OTP_BELOW_27}]) ++
if_type_exported(:odbc, {:opaque, :connection_reference, 0}, [{:d, :ODBC_HAS_TYPES}])
defines = for {:d, value} <- result, do: {:d, value}
result ++ [{:d, :ALL_DEFS, defines}]
Expand All @@ -139,7 +140,6 @@ defmodule Ejabberd.MixProject do
{:fast_xml, ">= 1.1.51"},
{:fast_yaml, "~> 1.0"},
{:idna, "~> 6.0"},
{:jiffy, "~> 1.1.1"},
{:mqtree, "~> 1.0"},
{:p1_acme, git: "https://github.com/processone/p1_acme", branch: "master"},
{:p1_oauth2, "~> 0.6"},
Expand Down Expand Up @@ -173,6 +173,7 @@ defmodule Ejabberd.MixProject do
{config(:zlib), {:ezlib, "~> 1.0"}},
{if_version_above(~c"23", true), {:jose, "~> 1.11.10"}},
{if_version_below(~c"24", true), {:jose, "1.11.1"}},
{if_version_below(~c"27", true), {:jiffy, "~> 1.1.1"}},
{if_version_below(~c"22", true), {:lager, "~> 3.9.1"}},
{config(:lua), {:luerl, "~> 1.2.0"}},
{config(:mysql), {:p1_mysql, ">= 1.0.23" }},
Expand All @@ -185,6 +186,7 @@ defmodule Ejabberd.MixProject do
defp cond_apps do
for {:true, app} <- [{config(:stun), :stun},
{Map.has_key?(System.get_env(), "RELIVE"), :exsync},
{if_version_below(~c"27", true), :jiffy},
{config(:tools), :observer}], do:
app
end
Expand Down
9 changes: 5 additions & 4 deletions rebar.config
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@
{fast_xml, "~> 1.1.51", {git, "https://github.com/processone/fast_xml", {tag, "1.1.51"}}},
{fast_yaml, "~> 1.0.36", {git, "https://github.com/processone/fast_yaml", {tag, "1.0.36"}}},
{idna, "~> 6.0", {git, "https://github.com/benoitc/erlang-idna", {tag, "6.0.0"}}},
{if_version_above, "19",
{jiffy, "~> 1.1.1", {git, "https://github.com/davisp/jiffy", {tag, "1.1.1"}}},
{jiffy, "1.1.0", {git, "https://github.com/davisp/jiffy", {tag, "1.1.0"}}} % for R19 and below
{if_version_below, "27",
{jiffy, "~> 1.1.1", {git, "https://github.com/davisp/jiffy", {tag, "1.1.1"}}}
},
{if_version_above, "23",
{jose, "~> 1.11.10", {git, "https://github.com/potatosalad/erlang-jose", {tag, "1.11.10"}}},
Expand Down Expand Up @@ -131,6 +130,7 @@
{if_version_below, "24", {d, 'SYSTOOLS_APP_DEF_WITHOUT_OPTIONAL'}},
{if_version_below, "24", {d, 'OTP_BELOW_24'}},
{if_version_below, "25", {d, 'OTP_BELOW_25'}},
{if_version_below, "27", {d, 'OTP_BELOW_27'}},
{if_var_false, debug, no_debug_info},
{if_var_true, debug, debug_info},
{if_var_true, elixir, {d, 'ELIXIR_ENABLED'}},
Expand Down Expand Up @@ -206,10 +206,11 @@
{if_version_above, "25",
{plt_extra_apps,
[asn1, odbc, public_key, stdlib, syntax_tools,
idna, jiffy, jose,
idna, jose,
cache_tab, eimp, fast_tls, fast_xml, fast_yaml,
mqtree, p1_acme, p1_oauth2, p1_utils, pkix,
stringprep, xmpp, yconf,
{if_version_below, "27", jiffy},
{if_var_true, pam, epam},
{if_var_true, redis, eredis},
{if_var_true, sip, esip},
Expand Down
2 changes: 1 addition & 1 deletion src/ejabberd_ctl.erl
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ format_arg(Arg, {tuple, Elements}) ->
list_to_tuple(format_args(Args, Elements));
format_arg(Arg, Format) ->
S = unicode:characters_to_binary(Arg, utf8),
JSON = jiffy:decode(S),
JSON = misc:json_decode_list(S),
mod_http_api:format_arg(JSON, Format).
format_arg2(Arg, Parse)->
Expand Down
15 changes: 7 additions & 8 deletions src/ejabberd_oauth.erl
Original file line number Diff line number Diff line change
Expand Up @@ -721,11 +721,10 @@ process(_Handlers,
ExpiresIn
end,
{ok, VerifiedScope} = oauth2_response:scope(Response),
json_response(200, {[
{<<"access_token">>, AccessToken},
{<<"token_type">>, Type},
{<<"scope">>, str:join(VerifiedScope, <<" ">>)},
{<<"expires_in">>, Expires}]});
json_response(200, #{<<"access_token">> => AccessToken,
<<"token_type">> => Type,
<<"scope">> => str:join(VerifiedScope, <<" ">>),
<<"expires_in">> => Expires});
{error, Error} when is_atom(Error) ->
json_error(400, <<"invalid_grant">>, Error)
end;
Expand Down Expand Up @@ -756,14 +755,14 @@ json_response(Code, Body) ->
{Code, [{<<"Content-Type">>, <<"application/json;charset=UTF-8">>},
{<<"Cache-Control">>, <<"no-store">>},
{<<"Pragma">>, <<"no-cache">>}],
jiffy:encode(Body)}.
misc:json_encode(Body)}.

%% OAauth error are defined in:
%% https://tools.ietf.org/html/draft-ietf-oauth-v2-25#section-5.2
json_error(Code, Error, Reason) ->
Desc = json_error_desc(Reason),
Body = {[{<<"error">>, Error},
{<<"error_description">>, Desc}]},
Body = #{<<"error">> => Error,
<<"error_description">> => Desc},
json_response(Code, Body).

json_error_desc(access_denied) -> <<"Access denied">>;
Expand Down
2 changes: 1 addition & 1 deletion src/ext_mod.erl
Original file line number Diff line number Diff line change
Expand Up @@ -884,7 +884,7 @@ get_commit_details2(Path) ->
end.

parse_details(Body) ->
{Contents} = jiffy:decode(Body),
Contents = misc:json_decode_list(Body),

{_, {Commit}} = lists:keyfind(<<"commit">>, 1, Contents),
{_, Sha} = lists:keyfind(<<"sha">>, 1, Commit),
Expand Down
28 changes: 28 additions & 0 deletions src/misc.erl
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
is_mucsub_message/1, best_match/2, pmap/2, peach/2, format_exception/4,
get_my_ipv4_address/0, get_my_ipv6_address/0, parse_ip_mask/1,
crypto_hmac/3, crypto_hmac/4, uri_parse/1, uri_parse/2, uri_quote/1,
json_encode/1, json_decode_maps/1, json_decode_list/1,
match_ip_mask/3, format_hosts_list/1, format_cycle/1, delete_dir/1,
semver_to_xxyy/1, logical_processors/0, get_mucsub_event_type/1]).

Expand All @@ -58,6 +59,13 @@
-type re_mp() :: {re_pattern, _, _, _, _}.
-export_type([re_mp/0]).

-ifdef(OTP_BELOW_27).
-type json_value() :: jiffy:json_value().
-else.
-type json_value() :: json:encode_value().
-endif.
-export_type([json_value/0]).

-type distance_cache() :: #{{string(), string()} => non_neg_integer()}.

-spec uri_parse(binary()|string()) -> {ok, string(), string(), string(), number(), string(), string()} | {error, term()}.
Expand Down Expand Up @@ -122,6 +130,26 @@ crypto_hmac(Type, Key, Data) -> crypto:mac(hmac, Type, Key, Data).
crypto_hmac(Type, Key, Data, MacL) -> crypto:macN(hmac, Type, Key, Data, MacL).
-endif.

-ifdef(OTP_BELOW_27).
json_encode(Term) ->
jiffy:encode(Term).
json_decode_maps(Bin) ->
jiffy:decode(Bin, [return_maps]).
json_decode_list(Bin) ->
case jiffy:decode(Bin) of
List when is_list(List) -> List;
{List} when is_list(List) -> List;
Other -> [Other]
end.
-else.
json_encode(Term) ->
iolist_to_binary(json:encode(Term)).
json_decode_maps(Bin) ->
json:decode(Bin).
json_decode_list(Bin) ->
maps:to_list(json:decode(Bin)).
-endif.

%%%===================================================================
%%% API
%%%===================================================================
Expand Down
12 changes: 10 additions & 2 deletions src/mod_bosh.erl
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,22 @@ get_type(Hdrs) ->
depends(_Host, _Opts) ->
[].

mod_opt_type(json) ->
-ifdef(OTP_BELOW_27).
mod_opt_type_json() ->
econf:and_then(
econf:bool(),
fun(false) -> false;
(true) ->
ejabberd:start_app(jiffy),
true
end);
end).
-else.
mod_opt_type_json() ->
econf:bool().
-endif.

mod_opt_type(json) ->
mod_opt_type_json();
mod_opt_type(max_concat) ->
econf:pos_int(unlimited);
mod_opt_type(max_inactivity) ->
Expand Down
3 changes: 2 additions & 1 deletion src/mod_conversejs.erl
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ process([], #request{method = 'GET', host = Host, raw_path = RawPath}) ->
undefined -> Init2;
BoshURL -> [{<<"bosh_service_url">>, BoshURL} | Init2]
end,
InitMap = maps:from_list(Init3),
{200, [html],
[<<"<!DOCTYPE html>">>,
<<"<html>">>,
Expand All @@ -89,7 +90,7 @@ process([], #request{method = 'GET', host = Host, raw_path = RawPath}) ->
<<"</head>">>,
<<"<body>">>,
<<"<script>">>,
<<"converse.initialize(">>, jiffy:encode({Init3}), <<");">>,
<<"converse.initialize(">>, misc:json_encode(InitMap), <<");">>,
<<"</script>">>,
<<"</body>">>,
<<"</html>">>]};
Expand Down
2 changes: 1 addition & 1 deletion src/mod_host_meta.erl
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ file_json(Host) ->
{200, [html,
{<<"Content-Type">>, <<"application/json">>},
{<<"Access-Control-Allow-Origin">>, <<"*">>}],
[jiffy:encode(#{links => BoshList ++ WsList})]}.
[misc:json_encode(#{links => BoshList ++ WsList})]}.

get_url(M, bosh, Tls, Host) ->
get_url(M, Tls, Host, bosh_service_url, mod_bosh);
Expand Down
16 changes: 6 additions & 10 deletions src/mod_http_api.erl
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,7 @@ perform_call(Command, Args, Req, Version) ->
%% Be tolerant to make API more easily usable from command-line pipe.
extract_args(<<"\n">>) -> [];
extract_args(Data) ->
case jiffy:decode(Data) of
List when is_list(List) -> List;
{List} when is_list(List) -> List;
Other -> [Other]
end.
misc:json_decode_list(Data).

% get API version N from last "vN" element in URL path
get_api_version(#request{path = Path}) ->
Expand Down Expand Up @@ -495,10 +491,10 @@ invalid_token_response() ->
badrequest_response() ->
badrequest_response(<<"400 Bad Request">>).
badrequest_response(Body) ->
json_response(400, jiffy:encode(Body)).
json_response(400, misc:json_encode(Body)).

json_format({Code, Result}) ->
json_response(Code, jiffy:encode(Result));
json_response(Code, misc:json_encode(Result));
json_format({HTMLCode, JSONErrorCode, Message}) ->
json_error(HTMLCode, JSONErrorCode, Message).

Expand All @@ -509,9 +505,9 @@ json_response(Code, Body) when is_integer(Code) ->
%% message is binary
json_error(HTTPCode, JSONCode, Message) ->
{HTTPCode, ?HEADER(?CT_JSON),
jiffy:encode({[{<<"status">>, <<"error">>},
{<<"code">>, JSONCode},
{<<"message">>, Message}]})
misc:json_encode(#{<<"status">> => <<"error">>,
<<"code">> => JSONCode,
<<"message">> => Message})
}.

log(Call, Args, {Addr, Port}) ->
Expand Down
Loading

0 comments on commit 40d6724

Please sign in to comment.