emqx_utils_maps.erl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2023 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_utils_maps).
  17. -export([
  18. best_effort_recursive_sum/3,
  19. binary_key_map/1,
  20. binary_string/1,
  21. deep_convert/3,
  22. deep_find/2,
  23. deep_force_put/3,
  24. deep_get/2,
  25. deep_get/3,
  26. deep_merge/2,
  27. deep_put/3,
  28. deep_remove/2,
  29. diff_maps/2,
  30. if_only_to_toggle_enable/2,
  31. indent/3,
  32. jsonable_map/1,
  33. jsonable_map/2,
  34. key_comparer/1,
  35. put_if/4,
  36. rename/3,
  37. safe_atom_key_map/1,
  38. unindent/2,
  39. unsafe_atom_key_map/1,
  40. update_if_present/3
  41. ]).
  42. -export_type([config_key/0, config_key_path/0]).
  43. -type config_key() :: atom() | binary() | [byte()].
  44. -type config_key_path() :: [config_key()].
  45. -type convert_fun() :: fun((...) -> {K1 :: any(), V1 :: any()} | drop).
  46. -define(CONFIG_NOT_FOUND_MAGIC, '$0tFound').
  47. %%-----------------------------------------------------------------
  48. -spec deep_get(config_key_path(), map()) -> term().
  49. deep_get(ConfKeyPath, Map) ->
  50. case deep_get(ConfKeyPath, Map, ?CONFIG_NOT_FOUND_MAGIC) of
  51. ?CONFIG_NOT_FOUND_MAGIC -> error({config_not_found, ConfKeyPath});
  52. Res -> Res
  53. end.
  54. -spec deep_get(config_key_path(), map(), term()) -> term().
  55. deep_get(ConfKeyPath, Map, Default) ->
  56. case deep_find(ConfKeyPath, Map) of
  57. {not_found, _KeyPath, _Data} -> Default;
  58. {ok, Data} -> Data
  59. end.
  60. -spec deep_find(config_key_path(), map()) ->
  61. {ok, term()} | {not_found, config_key_path(), term()}.
  62. deep_find([], Map) ->
  63. {ok, Map};
  64. deep_find([Key | KeyPath] = Path, Map) when is_map(Map) ->
  65. case maps:find(Key, Map) of
  66. {ok, SubMap} -> deep_find(KeyPath, SubMap);
  67. error -> {not_found, Path, Map}
  68. end;
  69. deep_find(KeyPath, Data) ->
  70. {not_found, KeyPath, Data}.
  71. -spec deep_put(config_key_path(), map(), term()) -> map().
  72. deep_put([], _Map, Data) ->
  73. Data;
  74. deep_put([Key | KeyPath], Map, Data) ->
  75. SubMap = maps:get(Key, Map, #{}),
  76. Map#{Key => deep_put(KeyPath, SubMap, Data)}.
  77. %% Like deep_put, but ensures that the key path is present.
  78. %% If key path is not present in map, creates the keys, until it's present
  79. %% deep_force_put([x, y, z], #{a => 1}, 0) -> #{a => 1, x => #{y => #{z => 0}}}
  80. -spec deep_force_put(config_key_path(), map(), term()) -> map().
  81. deep_force_put([], _Map, Data) ->
  82. Data;
  83. deep_force_put([Key | KeyPath] = FullPath, Map, Data) ->
  84. case Map of
  85. #{Key := InnerValue} ->
  86. Map#{Key => deep_force_put(KeyPath, InnerValue, Data)};
  87. #{} ->
  88. maps:put(Key, path_to_map(KeyPath, Data), Map);
  89. _ ->
  90. path_to_map(FullPath, Data)
  91. end.
  92. -spec path_to_map(config_key_path(), term()) -> map().
  93. path_to_map([], Data) -> Data;
  94. path_to_map([Key | Tail], Data) -> #{Key => path_to_map(Tail, Data)}.
  95. -spec deep_remove(config_key_path(), map()) -> map().
  96. deep_remove([], Map) ->
  97. Map;
  98. deep_remove([Key], Map) ->
  99. maps:remove(Key, Map);
  100. deep_remove([Key | KeyPath], Map) ->
  101. case maps:find(Key, Map) of
  102. {ok, SubMap} when is_map(SubMap) ->
  103. Map#{Key => deep_remove(KeyPath, SubMap)};
  104. {ok, _Val} ->
  105. Map;
  106. error ->
  107. Map
  108. end.
  109. %% #{a => #{b => 3, c => 2}, d => 4}
  110. %% = deep_merge(#{a => #{b => 1, c => 2}, d => 4}, #{a => #{b => 3}}).
  111. -spec deep_merge(map(), map()) -> map().
  112. deep_merge(BaseMap, NewMap) ->
  113. NewKeys = maps:keys(NewMap) -- maps:keys(BaseMap),
  114. MergedBase = maps:fold(
  115. fun(K, V, Acc) ->
  116. case maps:find(K, NewMap) of
  117. error ->
  118. Acc#{K => V};
  119. {ok, NewV} when is_map(V), is_map(NewV) ->
  120. Acc#{K => deep_merge(V, NewV)};
  121. {ok, NewV} ->
  122. Acc#{K => NewV}
  123. end
  124. end,
  125. #{},
  126. BaseMap
  127. ),
  128. maps:merge(MergedBase, maps:with(NewKeys, NewMap)).
  129. -spec deep_convert(any(), convert_fun(), Args :: list()) -> any().
  130. deep_convert(Map, ConvFun, Args) when is_map(Map) ->
  131. maps:fold(
  132. fun(K, V, Acc) ->
  133. case apply(ConvFun, [K, deep_convert(V, ConvFun, Args) | Args]) of
  134. drop -> Acc;
  135. {K1, V1} -> Acc#{K1 => V1}
  136. end
  137. end,
  138. #{},
  139. Map
  140. );
  141. deep_convert(ListV, ConvFun, Args) when is_list(ListV) ->
  142. [deep_convert(V, ConvFun, Args) || V <- ListV];
  143. deep_convert(Val, _, _Args) ->
  144. Val.
  145. -spec unsafe_atom_key_map(#{binary() | atom() => any()}) -> #{atom() => any()}.
  146. unsafe_atom_key_map(Map) ->
  147. convert_keys_to_atom(Map, fun(K) -> binary_to_atom(K, utf8) end).
  148. -spec binary_key_map(map()) -> map().
  149. binary_key_map(Map) ->
  150. deep_convert(
  151. Map,
  152. fun
  153. (K, V) when is_atom(K) -> {atom_to_binary(K, utf8), V};
  154. (K, V) when is_binary(K) -> {K, V}
  155. end,
  156. []
  157. ).
  158. -spec safe_atom_key_map(#{binary() | atom() => any()}) -> #{atom() => any()}.
  159. safe_atom_key_map(Map) ->
  160. convert_keys_to_atom(Map, fun(K) -> binary_to_existing_atom(K, utf8) end).
  161. -spec jsonable_map(map() | list()) -> map() | list().
  162. jsonable_map(Map) ->
  163. jsonable_map(Map, fun(K, V) -> {K, V} end).
  164. jsonable_map(Map, JsonableFun) ->
  165. deep_convert(Map, fun binary_string_kv/3, [JsonableFun]).
  166. -spec diff_maps(map(), map()) ->
  167. #{
  168. added := map(),
  169. identical := map(),
  170. removed := map(),
  171. changed := #{any() => {OldValue :: any(), NewValue :: any()}}
  172. }.
  173. diff_maps(NewMap, OldMap) ->
  174. InitR = #{identical => #{}, changed => #{}, removed => #{}},
  175. {Result, RemInNew} =
  176. lists:foldl(
  177. fun({OldK, OldV}, {Result0 = #{identical := I, changed := U, removed := D}, RemNewMap}) ->
  178. Result1 =
  179. case maps:find(OldK, NewMap) of
  180. error ->
  181. Result0#{removed => D#{OldK => OldV}};
  182. {ok, NewV} when NewV == OldV ->
  183. Result0#{identical => I#{OldK => OldV}};
  184. {ok, NewV} ->
  185. Result0#{changed => U#{OldK => {OldV, NewV}}}
  186. end,
  187. {Result1, maps:remove(OldK, RemNewMap)}
  188. end,
  189. {InitR, NewMap},
  190. maps:to_list(OldMap)
  191. ),
  192. Result#{added => RemInNew}.
  193. binary_string_kv(K, V, JsonableFun) ->
  194. case JsonableFun(K, V) of
  195. drop -> drop;
  196. {K1, V1} -> {binary_string(K1), V1}
  197. end.
  198. %% [FIXME] this doesn't belong here
  199. binary_string([]) ->
  200. [];
  201. binary_string(Val) when is_list(Val) ->
  202. case io_lib:printable_unicode_list(Val) of
  203. true -> unicode:characters_to_binary(Val);
  204. false -> [binary_string(V) || V <- Val]
  205. end;
  206. binary_string(Val) ->
  207. Val.
  208. %%---------------------------------------------------------------------------
  209. convert_keys_to_atom(BinKeyMap, Conv) ->
  210. deep_convert(
  211. BinKeyMap,
  212. fun
  213. (K, V) when is_atom(K) -> {K, V};
  214. (K, V) when is_binary(K) -> {Conv(K), V}
  215. end,
  216. []
  217. ).
  218. %% @doc Sum-merge map values.
  219. %% For bad merges, ErrorLogger is called to log the key, and value in M2 is ignored.
  220. best_effort_recursive_sum(M10, M20, ErrorLogger) ->
  221. FilterF = fun(K, V) ->
  222. case erlang:is_number(V) of
  223. true ->
  224. true;
  225. false ->
  226. ErrorLogger(#{failed_to_merge => K, bad_value => V}),
  227. false
  228. end
  229. end,
  230. M1 = deep_filter(M10, FilterF),
  231. M2 = deep_filter(M20, FilterF),
  232. do_best_effort_recursive_sum(M1, M2, ErrorLogger).
  233. do_best_effort_recursive_sum(M1, M2, ErrorLogger) ->
  234. F =
  235. fun(Key, V1, V2) ->
  236. case {erlang:is_map(V1), erlang:is_map(V2)} of
  237. {true, true} ->
  238. do_best_effort_recursive_sum(V1, V2, ErrorLogger);
  239. {true, false} ->
  240. ErrorLogger(#{failed_to_merge => Key, bad_value => V2}),
  241. do_best_effort_recursive_sum(V1, #{}, ErrorLogger);
  242. {false, true} ->
  243. ErrorLogger(#{failed_to_merge => Key, bad_value => V1}),
  244. do_best_effort_recursive_sum(V2, #{}, ErrorLogger);
  245. {false, false} ->
  246. true = is_number(V1),
  247. true = is_number(V2),
  248. V1 + V2
  249. end
  250. end,
  251. maps:merge_with(F, M1, M2).
  252. deep_filter(M, F) when is_map(M) ->
  253. %% maps:filtermap is not available before OTP 24
  254. maps:from_list(
  255. lists:filtermap(
  256. fun
  257. ({K, V}) when is_map(V) ->
  258. {true, {K, deep_filter(V, F)}};
  259. ({K, V}) ->
  260. F(K, V) andalso {true, {K, V}}
  261. end,
  262. maps:to_list(M)
  263. )
  264. ).
  265. if_only_to_toggle_enable(OldConf, Conf) ->
  266. #{added := Added, removed := Removed, changed := Updated} =
  267. emqx_utils_maps:diff_maps(OldConf, Conf),
  268. case {Added, Removed, Updated} of
  269. {Added, Removed, #{enable := _} = Updated} when
  270. map_size(Added) =:= 0,
  271. map_size(Removed) =:= 0,
  272. map_size(Updated) =:= 1
  273. ->
  274. true;
  275. {_, _, _} ->
  276. false
  277. end.
  278. %% Like `maps:update_with', but does nothing if key does not exist.
  279. update_if_present(Key, Fun, Map) ->
  280. case Map of
  281. #{Key := Val} ->
  282. Map#{Key := Fun(Val)};
  283. _ ->
  284. Map
  285. end.
  286. put_if(Acc, K, V, true) ->
  287. Acc#{K => V};
  288. put_if(Acc, _K, _V, false) ->
  289. Acc.
  290. rename(OldKey, NewKey, Map) ->
  291. case maps:find(OldKey, Map) of
  292. {ok, Value} ->
  293. maps:put(NewKey, Value, maps:remove(OldKey, Map));
  294. error ->
  295. Map
  296. end.
  297. -spec key_comparer(K) -> fun((M, M) -> boolean()) when M :: #{K => _V}.
  298. key_comparer(K) ->
  299. fun
  300. (#{K := V1}, #{K := V2}) ->
  301. V1 < V2;
  302. (#{K := _}, _) ->
  303. false;
  304. (_, #{K := _}) ->
  305. true;
  306. (M1, M2) ->
  307. M1 < M2
  308. end.
  309. -spec indent(term(), [term()], map()) -> map().
  310. indent(IndentKey, PickKeys, Map) ->
  311. maps:put(
  312. IndentKey,
  313. maps:with(PickKeys, Map),
  314. maps:without(PickKeys, Map)
  315. ).
  316. -spec unindent(term(), map()) -> map().
  317. unindent(Key, Map) ->
  318. deep_merge(
  319. maps:remove(Key, Map),
  320. maps:get(Key, Map, #{})
  321. ).