emqx_utils_maps.erl 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. deep_get/2,
  19. deep_get/3,
  20. deep_find/2,
  21. deep_put/3,
  22. deep_force_put/3,
  23. deep_remove/2,
  24. deep_merge/2,
  25. binary_key_map/1,
  26. safe_atom_key_map/1,
  27. unsafe_atom_key_map/1,
  28. jsonable_map/1,
  29. jsonable_map/2,
  30. binary_string/1,
  31. deep_convert/3,
  32. diff_maps/2,
  33. best_effort_recursive_sum/3,
  34. if_only_to_toggle_enable/2,
  35. update_if_present/3,
  36. put_if/4
  37. ]).
  38. -export_type([config_key/0, config_key_path/0]).
  39. -type config_key() :: atom() | binary() | [byte()].
  40. -type config_key_path() :: [config_key()].
  41. -type convert_fun() :: fun((...) -> {K1 :: any(), V1 :: any()} | drop).
  42. -define(CONFIG_NOT_FOUND_MAGIC, '$0tFound').
  43. %%-----------------------------------------------------------------
  44. -spec deep_get(config_key_path(), map()) -> term().
  45. deep_get(ConfKeyPath, Map) ->
  46. case deep_get(ConfKeyPath, Map, ?CONFIG_NOT_FOUND_MAGIC) of
  47. ?CONFIG_NOT_FOUND_MAGIC -> error({config_not_found, ConfKeyPath});
  48. Res -> Res
  49. end.
  50. -spec deep_get(config_key_path(), map(), term()) -> term().
  51. deep_get(ConfKeyPath, Map, Default) ->
  52. case deep_find(ConfKeyPath, Map) of
  53. {not_found, _KeyPath, _Data} -> Default;
  54. {ok, Data} -> Data
  55. end.
  56. -spec deep_find(config_key_path(), map()) ->
  57. {ok, term()} | {not_found, config_key_path(), term()}.
  58. deep_find([], Map) ->
  59. {ok, Map};
  60. deep_find([Key | KeyPath] = Path, Map) when is_map(Map) ->
  61. case maps:find(Key, Map) of
  62. {ok, SubMap} -> deep_find(KeyPath, SubMap);
  63. error -> {not_found, Path, Map}
  64. end;
  65. deep_find(KeyPath, Data) ->
  66. {not_found, KeyPath, Data}.
  67. -spec deep_put(config_key_path(), map(), term()) -> map().
  68. deep_put([], _Map, Data) ->
  69. Data;
  70. deep_put([Key | KeyPath], Map, Data) ->
  71. SubMap = maps:get(Key, Map, #{}),
  72. Map#{Key => deep_put(KeyPath, SubMap, Data)}.
  73. %% Like deep_put, but ensures that the key path is present.
  74. %% If key path is not present in map, creates the keys, until it's present
  75. %% deep_force_put([x, y, z], #{a => 1}, 0) -> #{a => 1, x => #{y => #{z => 0}}}
  76. -spec deep_force_put(config_key_path(), map(), term()) -> map().
  77. deep_force_put([], _Map, Data) ->
  78. Data;
  79. deep_force_put([Key | KeyPath] = FullPath, Map, Data) ->
  80. case Map of
  81. #{Key := InnerValue} ->
  82. Map#{Key => deep_force_put(KeyPath, InnerValue, Data)};
  83. #{} ->
  84. maps:put(Key, path_to_map(KeyPath, Data), Map);
  85. _ ->
  86. path_to_map(FullPath, Data)
  87. end.
  88. -spec path_to_map(config_key_path(), term()) -> map().
  89. path_to_map([], Data) -> Data;
  90. path_to_map([Key | Tail], Data) -> #{Key => path_to_map(Tail, Data)}.
  91. -spec deep_remove(config_key_path(), map()) -> map().
  92. deep_remove([], Map) ->
  93. Map;
  94. deep_remove([Key], Map) ->
  95. maps:remove(Key, Map);
  96. deep_remove([Key | KeyPath], Map) ->
  97. case maps:find(Key, Map) of
  98. {ok, SubMap} when is_map(SubMap) ->
  99. Map#{Key => deep_remove(KeyPath, SubMap)};
  100. {ok, _Val} ->
  101. Map;
  102. error ->
  103. Map
  104. end.
  105. %% #{a => #{b => 3, c => 2}, d => 4}
  106. %% = deep_merge(#{a => #{b => 1, c => 2}, d => 4}, #{a => #{b => 3}}).
  107. -spec deep_merge(map(), map()) -> map().
  108. deep_merge(BaseMap, NewMap) ->
  109. NewKeys = maps:keys(NewMap) -- maps:keys(BaseMap),
  110. MergedBase = maps:fold(
  111. fun(K, V, Acc) ->
  112. case maps:find(K, NewMap) of
  113. error ->
  114. Acc#{K => V};
  115. {ok, NewV} when is_map(V), is_map(NewV) ->
  116. Acc#{K => deep_merge(V, NewV)};
  117. {ok, NewV} ->
  118. Acc#{K => NewV}
  119. end
  120. end,
  121. #{},
  122. BaseMap
  123. ),
  124. maps:merge(MergedBase, maps:with(NewKeys, NewMap)).
  125. -spec deep_convert(any(), convert_fun(), Args :: list()) -> any().
  126. deep_convert(Map, ConvFun, Args) when is_map(Map) ->
  127. maps:fold(
  128. fun(K, V, Acc) ->
  129. case apply(ConvFun, [K, deep_convert(V, ConvFun, Args) | Args]) of
  130. drop -> Acc;
  131. {K1, V1} -> Acc#{K1 => V1}
  132. end
  133. end,
  134. #{},
  135. Map
  136. );
  137. deep_convert(ListV, ConvFun, Args) when is_list(ListV) ->
  138. [deep_convert(V, ConvFun, Args) || V <- ListV];
  139. deep_convert(Val, _, _Args) ->
  140. Val.
  141. -spec unsafe_atom_key_map(#{binary() | atom() => any()}) -> #{atom() => any()}.
  142. unsafe_atom_key_map(Map) ->
  143. convert_keys_to_atom(Map, fun(K) -> binary_to_atom(K, utf8) end).
  144. -spec binary_key_map(map()) -> map().
  145. binary_key_map(Map) ->
  146. deep_convert(
  147. Map,
  148. fun
  149. (K, V) when is_atom(K) -> {atom_to_binary(K, utf8), V};
  150. (K, V) when is_binary(K) -> {K, V}
  151. end,
  152. []
  153. ).
  154. -spec safe_atom_key_map(#{binary() | atom() => any()}) -> #{atom() => any()}.
  155. safe_atom_key_map(Map) ->
  156. convert_keys_to_atom(Map, fun(K) -> binary_to_existing_atom(K, utf8) end).
  157. -spec jsonable_map(map() | list()) -> map() | list().
  158. jsonable_map(Map) ->
  159. jsonable_map(Map, fun(K, V) -> {K, V} end).
  160. jsonable_map(Map, JsonableFun) ->
  161. deep_convert(Map, fun binary_string_kv/3, [JsonableFun]).
  162. -spec diff_maps(map(), map()) ->
  163. #{
  164. added := map(),
  165. identical := map(),
  166. removed := map(),
  167. changed := #{any() => {OldValue :: any(), NewValue :: any()}}
  168. }.
  169. diff_maps(NewMap, OldMap) ->
  170. InitR = #{identical => #{}, changed => #{}, removed => #{}},
  171. {Result, RemInNew} =
  172. lists:foldl(
  173. fun({OldK, OldV}, {Result0 = #{identical := I, changed := U, removed := D}, RemNewMap}) ->
  174. Result1 =
  175. case maps:find(OldK, NewMap) of
  176. error ->
  177. Result0#{removed => D#{OldK => OldV}};
  178. {ok, NewV} when NewV == OldV ->
  179. Result0#{identical => I#{OldK => OldV}};
  180. {ok, NewV} ->
  181. Result0#{changed => U#{OldK => {OldV, NewV}}}
  182. end,
  183. {Result1, maps:remove(OldK, RemNewMap)}
  184. end,
  185. {InitR, NewMap},
  186. maps:to_list(OldMap)
  187. ),
  188. Result#{added => RemInNew}.
  189. binary_string_kv(K, V, JsonableFun) ->
  190. case JsonableFun(K, V) of
  191. drop -> drop;
  192. {K1, V1} -> {binary_string(K1), V1}
  193. end.
  194. %% [FIXME] this doesn't belong here
  195. binary_string([]) ->
  196. [];
  197. binary_string(Val) when is_list(Val) ->
  198. case io_lib:printable_unicode_list(Val) of
  199. true -> unicode:characters_to_binary(Val);
  200. false -> [binary_string(V) || V <- Val]
  201. end;
  202. binary_string(Val) ->
  203. Val.
  204. %%---------------------------------------------------------------------------
  205. convert_keys_to_atom(BinKeyMap, Conv) ->
  206. deep_convert(
  207. BinKeyMap,
  208. fun
  209. (K, V) when is_atom(K) -> {K, V};
  210. (K, V) when is_binary(K) -> {Conv(K), V}
  211. end,
  212. []
  213. ).
  214. %% @doc Sum-merge map values.
  215. %% For bad merges, ErrorLogger is called to log the key, and value in M2 is ignored.
  216. best_effort_recursive_sum(M10, M20, ErrorLogger) ->
  217. FilterF = fun(K, V) ->
  218. case erlang:is_number(V) of
  219. true ->
  220. true;
  221. false ->
  222. ErrorLogger(#{failed_to_merge => K, bad_value => V}),
  223. false
  224. end
  225. end,
  226. M1 = deep_filter(M10, FilterF),
  227. M2 = deep_filter(M20, FilterF),
  228. do_best_effort_recursive_sum(M1, M2, ErrorLogger).
  229. do_best_effort_recursive_sum(M1, M2, ErrorLogger) ->
  230. F =
  231. fun(Key, V1, V2) ->
  232. case {erlang:is_map(V1), erlang:is_map(V2)} of
  233. {true, true} ->
  234. do_best_effort_recursive_sum(V1, V2, ErrorLogger);
  235. {true, false} ->
  236. ErrorLogger(#{failed_to_merge => Key, bad_value => V2}),
  237. do_best_effort_recursive_sum(V1, #{}, ErrorLogger);
  238. {false, true} ->
  239. ErrorLogger(#{failed_to_merge => Key, bad_value => V1}),
  240. do_best_effort_recursive_sum(V2, #{}, ErrorLogger);
  241. {false, false} ->
  242. true = is_number(V1),
  243. true = is_number(V2),
  244. V1 + V2
  245. end
  246. end,
  247. maps:merge_with(F, M1, M2).
  248. deep_filter(M, F) when is_map(M) ->
  249. %% maps:filtermap is not available before OTP 24
  250. maps:from_list(
  251. lists:filtermap(
  252. fun
  253. ({K, V}) when is_map(V) ->
  254. {true, {K, deep_filter(V, F)}};
  255. ({K, V}) ->
  256. F(K, V) andalso {true, {K, V}}
  257. end,
  258. maps:to_list(M)
  259. )
  260. ).
  261. if_only_to_toggle_enable(OldConf, Conf) ->
  262. #{added := Added, removed := Removed, changed := Updated} =
  263. emqx_utils_maps:diff_maps(OldConf, Conf),
  264. case {Added, Removed, Updated} of
  265. {Added, Removed, #{enable := _} = Updated} when
  266. map_size(Added) =:= 0,
  267. map_size(Removed) =:= 0,
  268. map_size(Updated) =:= 1
  269. ->
  270. true;
  271. {_, _, _} ->
  272. false
  273. end.
  274. %% Like `maps:update_with', but does nothing if key does not exist.
  275. update_if_present(Key, Fun, Map) ->
  276. case Map of
  277. #{Key := Val} ->
  278. Map#{Key := Fun(Val)};
  279. _ ->
  280. Map
  281. end.
  282. put_if(Acc, K, V, true) ->
  283. Acc#{K => V};
  284. put_if(Acc, _K, _V, false) ->
  285. Acc.