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