emqx_utils_maps.erl 9.8 KB

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