./ct_report/coverage/mod_mam_elasticsearch_arch.COVER.html

1 %%------------------------------------------------------------------
2 %% Copyright 2018 Erlang Solutions Ltd.
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 %% @doc ElasticSearch backend for Message Archive Management for
17 %% one-to-one messages.
18 %%%------------------------------------------------------------------
19 -module(mod_mam_elasticsearch_arch).
20
21 -behaviour(gen_mod).
22 -behaviour(ejabberd_gen_mam_archive).
23 -behaviour(mongoose_module_metrics).
24
25 %% gen_mod callbacks
26 -export([start/2]).
27 -export([stop/1]).
28 -export([hooks/1]).
29
30 %% ejabberd_gen_mam_archive callbacks
31 -export([archive_message/3]).
32 -export([lookup_messages/3]).
33 -export([remove_archive/3]).
34 -export([archive_size/3]).
35 -export([get_mam_pm_gdpr_data/3]).
36
37 -include("mongoose.hrl").
38 -include("mongoose_rsm.hrl").
39 -include("mod_mam.hrl").
40 -include("jlib.hrl").
41
42 -define(INDEX_NAME, <<"messages">>).
43 -define(TYPE_NAME, <<"pm">>).
44
45 %%-------------------------------------------------------------------
46 %% gen_mod callbacks
47 %%-------------------------------------------------------------------
48
49 -spec start(mongooseim:host_type(), gen_mod:module_opts()) -> ok.
50 start(_HostType, _Opts) ->
51
:-(
ok.
52
53 -spec stop(mongooseim:host_type()) -> ok.
54 stop(_HostType) ->
55
:-(
ok.
56
57 -spec get_mam_pm_gdpr_data(Acc, Params, Extra) -> {ok, Acc} when
58 Acc :: ejabberd_gen_mam_archive:mam_pm_gdpr_data(),
59 Params :: #{jid := jid:jid()},
60 Extra :: gen_hook:extra().
61 get_mam_pm_gdpr_data(Acc, #{jid := Owner}, _Extra) ->
62
:-(
BinOwner = mod_mam_utils:bare_jid(Owner),
63
:-(
Filter = #{term => #{owner => BinOwner}},
64
:-(
Sorting = #{mam_id => #{order => asc}},
65
:-(
SearchQuery = #{query => #{bool => #{filter => Filter}}, sort => Sorting},
66
:-(
{ok, #{<<"hits">> := #{<<"hits">> := Hits}}}
67 = mongoose_elasticsearch:search(?INDEX_NAME, ?TYPE_NAME, SearchQuery),
68
:-(
Messages = lists:map(fun hit_to_gdpr_mam_message/1, Hits),
69
:-(
{ok, Messages ++ Acc}.
70
71 %%-------------------------------------------------------------------
72 %% ejabberd_gen_mam_archive callbacks
73 %%-------------------------------------------------------------------
74
75 -spec archive_message(Acc, Params, Extra) -> {ok, Acc} when
76 Acc :: ok | {error, term()},
77 Params :: mod_mam:archive_message_params(),
78 Extra :: gen_hook:extra().
79 archive_message(_Result,
80 #{message_id := MessageId,
81 local_jid := LocalJid,
82 remote_jid := RemoteJid,
83 source_jid := SourceJid,
84 packet := Packet,
85 is_groupchat := IsGroupChat},
86 #{host_type := Host}) ->
87
:-(
Owner = mod_mam_utils:bare_jid(LocalJid),
88
:-(
Remote = mod_mam_utils:bare_jid(RemoteJid),
89
:-(
SourceBinJid = mod_mam_utils:full_jid(SourceJid),
90
:-(
DocId = make_document_id(Owner, MessageId),
91
:-(
IsGroupChatBin = atom_to_binary(IsGroupChat),
92
:-(
Doc = make_document(MessageId, Owner, Remote, SourceBinJid, Packet, IsGroupChatBin),
93
:-(
case mongoose_elasticsearch:insert_document(?INDEX_NAME, ?TYPE_NAME, DocId, Doc) of
94 {ok, _} ->
95
:-(
{ok, ok};
96 {error, Reason} = Err ->
97
:-(
?LOG_ERROR(#{what => archive_message_failed,
98 user => Owner, server => Host, remote => Remote,
99
:-(
message_id => MessageId, reason => Reason}),
100
:-(
mongoose_metrics:update(Host, modMamDropped, 1),
101
:-(
{ok, Err}
102 end.
103
104 -spec lookup_messages(Acc, Params, Extra) -> {ok, Acc} when
105 Acc :: {ok, mod_mam:lookup_result()} | {error, term()},
106 Params :: mam_iq:lookup_params(),
107 Extra :: gen_hook:extra().
108 lookup_messages(Result,
109 #{rsm := #rsm_in{direction = before, id = ID} = RSM} = Params,
110 #{host_type := HostType})
111 when ID =/= undefined ->
112
:-(
{ok, lookup_message_page(Result, HostType, RSM, Params)};
113 lookup_messages(Result,
114 #{rsm := #rsm_in{direction = aft, id = ID} = RSM} = Params,
115 #{host_type := HostType})
116 when ID =/= undefined ->
117
:-(
{ok, lookup_message_page(Result, HostType, RSM, Params)};
118 lookup_messages(Result, Params, #{host_type := HostType}) ->
119
:-(
{ok, do_lookup_messages(Result, HostType, Params)}.
120
121 lookup_message_page(AccResult, Host, #rsm_in{id = _ID} = RSM, Params) ->
122
:-(
PageSize = maps:get(page_size, Params),
123
:-(
case do_lookup_messages(AccResult, Host, Params#{page_size := 1 + PageSize}) of
124
:-(
{error, _} = Err -> Err;
125 {ok, LookupResult} ->
126
:-(
mod_mam_utils:check_for_item_not_found(RSM, PageSize, LookupResult)
127 end.
128
129 do_lookup_messages(_Result, Host, Params) ->
130
:-(
SearchQuery0 = build_search_query(Params),
131
:-(
Sorting = [#{mam_id => #{order => determine_sorting(Params)}}],
132
:-(
ResultLimit = maps:get(page_size, Params),
133
:-(
SearchQuery1 = SearchQuery0#{sort => Sorting,
134 size => ResultLimit},
135
:-(
SearchQuery2 = maybe_add_from_constraint(SearchQuery1, Params),
136
:-(
case mongoose_elasticsearch:search(?INDEX_NAME, ?TYPE_NAME, SearchQuery2) of
137 {ok, Result} ->
138
:-(
{ok, search_result_to_mam_lookup_result(Result, Params)};
139 {error, Reason} = Err ->
140
:-(
?LOG_ERROR(maps:merge(Params,
141 #{what => lookup_messages_failed,
142
:-(
server => Host, reason => Reason})),
143
:-(
Err
144 end.
145
146 -spec archive_size(Acc, Params, Extra) -> {ok, Acc} when
147 Acc :: integer(),
148 Params :: #{archive_id := mod_mam:archive_id() | undefined, owner := jid:jid()},
149 Extra :: gen_hook:extra().
150 archive_size(_Size, #{owner := OwnerJid}, _Extra)->
151
:-(
SearchQuery = build_search_query(#{owner_jid => OwnerJid}),
152
:-(
{ok, archive_size(SearchQuery)}.
153
154 -spec remove_archive(Acc, Params, Extra) -> {ok, Acc} when
155 Acc :: term(),
156 Params :: #{archive_id := mod_mam:archive_id() | undefined, owner := jid:jid()},
157 Extra :: gen_hook:extra().
158 remove_archive(Acc, #{owner := OwnerJid}, #{host_type := HostType}) ->
159
:-(
remove_archive(HostType, OwnerJid),
160
:-(
{ok, Acc}.
161
162 remove_archive(Host, OwnerJid) ->
163
:-(
SearchQuery = build_search_query(#{owner_jid => OwnerJid}),
164
:-(
case mongoose_elasticsearch:delete_by_query(?INDEX_NAME, ?TYPE_NAME, SearchQuery) of
165 ok ->
166
:-(
ok;
167 {error, Reason} ->
168
:-(
?LOG_ERROR(#{what => remove_archive_failed,
169
:-(
server => Host, user_jid => OwnerJid, reason => Reason}),
170
:-(
ok
171 end.
172
173 %%-------------------------------------------------------------------
174 %% Helpers
175 %%-------------------------------------------------------------------
176
177 -spec hooks(mongooseim:host_type()) -> gen_hook:hook_list().
178 hooks(Host) ->
179
:-(
[{mam_archive_message, Host, fun ?MODULE:archive_message/3, #{}, 50},
180 {mam_lookup_messages, Host, fun ?MODULE:lookup_messages/3, #{}, 50},
181 {mam_archive_size, Host, fun ?MODULE:archive_size/3, #{}, 50},
182 {mam_remove_archive, Host, fun ?MODULE:remove_archive/3, #{}, 50},
183 {get_mam_pm_gdpr_data, Host, fun ?MODULE:get_mam_pm_gdpr_data/3, #{}, 50}].
184
185 -spec make_document_id(binary(), mod_mam:message_id()) -> binary().
186 make_document_id(Owner, MessageId) ->
187
:-(
<<Owner/binary, $$, (integer_to_binary(MessageId))/binary>>.
188
189 -spec make_document(mod_mam:message_id(), binary(), binary(),
190 binary(), exml:element(), binary()) ->
191 map().
192 make_document(MessageId, Owner, Remote, SourceBinJid, Packet, IsGroupChat) ->
193
:-(
#{mam_id => MessageId,
194 owner => Owner,
195 remote => Remote,
196 source_jid => SourceBinJid,
197 message => exml:to_binary(Packet),
198 body => exml_query:path(Packet, [{element, <<"body">>}, cdata]),
199 is_groupchat => IsGroupChat
200 }.
201
202 -spec build_search_query(map()) -> mongoose_elasticsearch:query().
203 build_search_query(Params) ->
204
:-(
Filters = build_filters(Params),
205
:-(
TextSearchQuery = build_text_search_query(Params),
206
:-(
#{query =>
207 #{bool =>
208 #{must => TextSearchQuery,
209 filter => Filters}}}.
210
211 -spec build_filters(map()) -> [map()].
212 build_filters(Params) ->
213
:-(
Builders = [fun owner_filter/1,
214 fun with_jid_filter/1,
215 fun is_groupchat_filter/1,
216 fun range_filter/1],
217
:-(
lists:flatmap(fun(F) -> F(Params) end, Builders).
218
219 -spec owner_filter(map()) -> [map()].
220 owner_filter(#{owner_jid := Owner}) ->
221
:-(
BinOwner = mod_mam_utils:bare_jid(Owner),
222
:-(
[#{term => #{owner => BinOwner}}].
223
224 -spec with_jid_filter(map()) -> [map()].
225 with_jid_filter(#{with_jid := #jid{} = WithJid}) ->
226
:-(
[#{term => #{remote => mod_mam_utils:bare_jid(WithJid)}}];
227 with_jid_filter(_) ->
228
:-(
[].
229
230 -spec is_groupchat_filter(map()) -> [map()].
231 is_groupchat_filter(#{include_groupchat := false}) ->
232
:-(
[#{term => #{is_groupchat => <<"false">>}}];
233 is_groupchat_filter(_) ->
234
:-(
[].
235
236 -spec range_filter(map()) -> [map()].
237 range_filter(#{end_ts := End, start_ts := Start, borders := Borders, rsm := RSM}) ->
238
:-(
{StartId, EndId} = mod_mam_utils:calculate_msg_id_borders(RSM, Borders, Start, End),
239
:-(
Range1 = maybe_add_end_filter(EndId, #{}),
240
:-(
Range2 = maybe_add_start_filter(StartId, Range1),
241
:-(
case maps:size(Range2) of
242 0 ->
243
:-(
[];
244 _ ->
245
:-(
[#{range => #{mam_id => Range2}}]
246 end;
247 range_filter(_) ->
248
:-(
[].
249
250 -spec maybe_add_end_filter(undefined | mod_mam:message_id(), map()) -> map().
251 maybe_add_end_filter(undefined, RangeMap) ->
252
:-(
RangeMap;
253 maybe_add_end_filter(Value, RangeMap) ->
254
:-(
RangeMap#{le => Value}.
255
256 -spec maybe_add_start_filter(undefined | mod_mam:message_id(), map()) -> map().
257 maybe_add_start_filter(undefined, RangeMap) ->
258
:-(
RangeMap;
259 maybe_add_start_filter(Value, RangeMap) ->
260
:-(
RangeMap#{ge => Value}.
261
262 -spec build_text_search_query(map()) -> map().
263 build_text_search_query(#{search_text := SearchText}) when is_binary(SearchText) ->
264
:-(
#{simple_query_string => #{query => SearchText,
265 fields => [<<"body">>],
266 default_operator => <<"and">>}};
267 build_text_search_query(_) ->
268
:-(
#{match_all => #{}}.
269
270 -spec determine_sorting(map()) -> asc | desc.
271 determine_sorting(#{rsm := #rsm_in{direction = before}}) ->
272
:-(
desc;
273 determine_sorting(_) ->
274
:-(
asc.
275
276 -spec maybe_add_from_constraint(mongoose_elasticsearch:query(), map()) ->
277 mongoose_elasticsearch:query().
278 maybe_add_from_constraint(Query, #{rsm := #rsm_in{index = Offset}}) when is_integer(Offset) ->
279
:-(
Query#{from => Offset};
280 maybe_add_from_constraint(Query, _) ->
281
:-(
Query.
282
283 -spec search_result_to_mam_lookup_result(map(), map()) -> mod_mam:lookup_result().
284 search_result_to_mam_lookup_result(Result, Params) ->
285
:-(
#{<<"hits">> :=
286 #{<<"hits">> := Hits,
287 <<"total">> := TotalCount}} = Result,
288
289
:-(
Messages = lists:sort(
290 lists:map(fun hit_to_mam_message/1, Hits)),
291
292
:-(
case maps:get(is_simple, Params) of
293 true ->
294
:-(
{undefined, undefined, Messages};
295 _ ->
296
:-(
CorrectedTotalCount = corrected_total_count(TotalCount, Params),
297
:-(
Count = length(Messages),
298
:-(
Offset = calculate_offset(TotalCount, Count, Params),
299
:-(
{CorrectedTotalCount, Offset, Messages}
300 end.
301
302 -spec hit_to_mam_message(map()) -> mod_mam:message_row().
303 hit_to_mam_message(#{<<"_source">> := JSON}) ->
304
:-(
MessageId = maps:get(<<"mam_id">>, JSON),
305
:-(
Packet = maps:get(<<"message">>, JSON),
306
:-(
SourceBinJid = maps:get(<<"source_jid">>, JSON),
307
:-(
{ok, Stanza} = exml:parse(Packet),
308
:-(
#{id => MessageId, jid => jid:from_binary(SourceBinJid), packet => Stanza}.
309
310 hit_to_gdpr_mam_message(#{<<"_source">> := JSON}) ->
311
:-(
MessageId = maps:get(<<"mam_id">>, JSON),
312
:-(
Packet = maps:get(<<"message">>, JSON),
313
:-(
SourceBinJid = maps:get(<<"source_jid">>, JSON),
314
:-(
{integer_to_binary(MessageId), SourceBinJid, Packet}.
315
316 %% Usage of RSM affects the `"total"' value returned by ElasticSearch. Per RSM spec, the count
317 %% returned by the query should represent the size of the whole result set, which in case of MAM
318 %% is bound only by the MAM filters.
319 %% The solution is to compute the archive size as if the RSM wasn't used. There is an obvious race
320 %% condition here, because a user may send a message between initial request to ElasticSearch and
321 %% the count request issued here.
322 -spec corrected_total_count(non_neg_integer(), mongoose_elasticsearch:query()) ->
323 non_neg_integer().
324 corrected_total_count(_, #{rsm := #rsm_in{id = Id}} = Params) when is_integer(Id) ->
325
:-(
Query = build_search_query(Params#{rsm := undefined}),
326
:-(
archive_size(Query);
327 corrected_total_count(Count, _) ->
328
:-(
Count.
329
330 -spec calculate_offset(non_neg_integer(), non_neg_integer(), map()) -> non_neg_integer().
331 calculate_offset(_, _, #{rsm := #rsm_in{direction = undefined, index = Index}}) when is_integer(Index) ->
332
:-(
Index;
333 calculate_offset(TotalCount, Count, #{rsm := #rsm_in{direction = before}}) ->
334
:-(
TotalCount - Count;
335 calculate_offset(_, _, #{rsm := #rsm_in{direction = aft, id = Id}} = Params0) when is_integer(Id) ->
336 %% Not sure how this works..
337
:-(
Params1 = update_borders(Params0#{rsm := undefined}, Id + 1),
338
:-(
Query = build_search_query(Params1),
339
:-(
archive_size(Query);
340 calculate_offset(_, _, _) ->
341
:-(
0.
342
343 -spec update_borders(map(), non_neg_integer()) -> map().
344 update_borders(#{borders := Borders} = Params, EndId) ->
345
:-(
Params#{borders := update_borders_to_id(Borders, EndId)}.
346
347 -spec update_borders_to_id(#mam_borders{} | undefined, non_neg_integer()) -> #mam_borders{}.
348 update_borders_to_id(undefined, EndId) ->
349
:-(
#mam_borders{to_id = EndId};
350 update_borders_to_id(Borders, EndId) ->
351
:-(
Borders#mam_borders{to_id = EndId}.
352
353 -spec archive_size(mongoose_elasticsearch:query()) -> non_neg_integer().
354 archive_size(Query) ->
355
:-(
case mongoose_elasticsearch:count(?INDEX_NAME, ?TYPE_NAME, Query) of
356 {ok, Count} ->
357
:-(
Count;
358 {error, Reason} ->
359
:-(
?LOG_ERROR(#{what => archive_size_failed, reason => Reason, es_query => Query,
360
:-(
text => <<"Failed to retrieve count of messages from ElasticSearch">>}),
361
:-(
0
362 end.
Line Hits Source