70db52a04eb5ecbdfc7d92cab63e9455d23a5348
[cloudant_bigcouch.git] / apps / couch / src / couch_rep_changes_feed.erl
1 % Licensed under the Apache License, Version 2.0 (the "License"); you may not
2 % use this file except in compliance with the License. You may obtain a copy of
3 % the License at
4 %
5 %   http://www.apache.org/licenses/LICENSE-2.0
6 %
7 % Unless required by applicable law or agreed to in writing, software
8 % distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 % WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 % License for the specific language governing permissions and limitations under
11 % the License.
12
13 -module(couch_rep_changes_feed).
14 -behaviour(gen_server).
15 -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
16     code_change/3]).
17
18 -export([start_link/4, next/1, stop/1]).
19
20 -define(BUFFER_SIZE, 1000).
21 -define(DOC_IDS_FILTER_NAME, "_doc_ids").
22
23 -include("couch_db.hrl").
24 -include_lib("ibrowse/include/ibrowse.hrl").
25
26 -record (state, {
27     changes_from = nil,
28     changes_loop = nil,
29     init_args,
30     last_seq,
31     conn = nil,
32     reqid = nil,
33     complete = false,
34     count = 0,
35     partial_chunk = <<>>,
36     reply_to = nil,
37     rows = queue:new(),
38     doc_ids = nil
39 }).
40
41 -import(couch_util, [
42     get_value/2,
43     get_value/3
44 ]).
45
46 start_link(Parent, Source, StartSeq, PostProps) ->
47     gen_server:start_link(?MODULE, [Parent, Source, StartSeq, PostProps], []).
48
49 next(Server) ->
50     gen_server:call(Server, next_changes, infinity).
51
52 stop(Server) ->
53     catch gen_server:call(Server, stop),
54     ok.
55
56 init([Parent, #http_db{headers = Headers0} = Source, Since, PostProps]) ->
57     process_flag(trap_exit, true),
58     Feed = case get_value(<<"continuous">>, PostProps, false) of
59     false ->
60         normal;
61     true ->
62         continuous
63     end,
64     BaseQS = [
65         {"style", all_docs},
66         {"heartbeat", 10000},
67         {"since", iolist_to_binary(?JSON_ENCODE(Since))},
68         {"feed", Feed}
69     ],
70     {QS, Method, Body, Headers} = case get_value(<<"doc_ids">>, PostProps) of
71     undefined ->
72         {maybe_add_filter_qs_params(PostProps, BaseQS), get, nil, Headers0};
73     DocIds when is_list(DocIds) ->
74         Headers1 = [{"Content-Type", "application/json"} | Headers0],
75         QS1 = [{"filter", ?l2b(?DOC_IDS_FILTER_NAME)} | BaseQS],
76         {QS1, post, {[{<<"doc_ids">>, DocIds}]}, Headers1}
77     end,
78     Pid = couch_rep_httpc:spawn_link_worker_process(Source),
79     Req = Source#http_db{
80         method = Method,
81         body = Body,
82         resource = "_changes",
83         qs = QS,
84         conn = Pid,
85         options = [{stream_to, {self(), once}}] ++
86                 lists:keydelete(inactivity_timeout, 1, Source#http_db.options),
87         headers = Headers -- [{"Accept-Encoding", "gzip"}]
88     },
89     {ibrowse_req_id, ReqId} = couch_rep_httpc:request(Req),
90     Args = [Parent, Req, Since, PostProps],
91     State = #state{
92         conn = Pid,
93         last_seq = Since,
94         reqid = ReqId,
95         init_args = Args,
96         doc_ids = get_value(<<"doc_ids">>, PostProps, nil)
97     },
98
99     receive
100     {ibrowse_async_headers, ReqId, "200", _} ->
101         ibrowse:stream_next(ReqId),
102         {ok, State};
103     {ibrowse_async_headers, ReqId, Code, Hdrs}
104             when Code =:= "301"; Code =:= "302"; Code =:= "303" ->
105         {ReqId2, Req2} = redirect_req(Req, Code, Hdrs),
106         receive
107         {ibrowse_async_headers, ReqId2, "200", _} ->
108             {ok, State#state{
109                 conn = Req2#http_db.conn,
110                 reqid = ReqId2,
111                 init_args = [Parent, Req2, Since, PostProps]}};
112         {ibrowse_async_headers, ReqId2, "405", _} when Method =:= post ->
113             {ReqId3, Req3} = req_no_builtin_doc_ids(Req2, ReqId2),
114             receive
115             {ibrowse_async_headers, ReqId3, "200", _} ->
116                 {ok, State#state{
117                     conn = Req3#http_db.conn,
118                     reqid = ReqId3,
119                     init_args = [Parent, Req3, Since, PostProps]}}
120             after 30000 ->
121                 {stop, changes_timeout}
122             end
123         after 30000 ->
124             {stop, changes_timeout}
125         end;
126     {ibrowse_async_headers, ReqId, "404", _} ->
127         stop_link_worker(Pid),
128         ?LOG_INFO("source doesn't have _changes, trying _all_docs_by_seq", []),
129         Self = self(),
130         BySeqPid = spawn_link(fun() -> by_seq_loop(Self, Source, Since) end),
131         {ok, State#state{changes_loop = BySeqPid}};
132     {ibrowse_async_headers, ReqId, "405", _}  when Method =:= post ->
133         {ReqId2, Req2} = req_no_builtin_doc_ids(Req, ReqId),
134         receive
135         {ibrowse_async_headers, ReqId2, "200", _} ->
136             {ok, State#state{
137                 conn = Req2#http_db.conn,
138                 reqid = ReqId2,
139                 init_args = [Parent, Req2, Since, PostProps]}};
140         {ibrowse_async_headers, ReqId, Code, Hdrs}
141             when Code =:= "301"; Code =:= "302"; Code =:= "303" ->
142             {ReqId3, Req3} = redirect_req(Req2, Code, Hdrs),
143             receive
144             {ibrowse_async_headers, ReqId3, "200", _} ->
145                 {ok, State#state{
146                     conn = Req3#http_db.conn,
147                     reqid = ReqId3,
148                     init_args = [Parent, Req3, Since, PostProps]}}
149             after 30000 ->
150                 {stop, changes_timeout}
151             end
152         after 30000 ->
153             {stop, changes_timeout}
154         end;
155     {ibrowse_async_headers, ReqId, Code, _} ->
156         {stop, {changes_error_code, list_to_integer(Code)}}
157     after 30000 ->
158         {stop, changes_timeout}
159     end;
160
161 init([_Parent, Source, Since, PostProps] = InitArgs) ->
162     process_flag(trap_exit, true),
163     Server = self(),
164     Filter = case get_value(<<"doc_ids">>, PostProps) of
165     undefined ->
166         ?b2l(get_value(<<"filter">>, PostProps, <<>>));
167     DocIds when is_list(DocIds) ->
168         ?DOC_IDS_FILTER_NAME
169     end,
170     ChangesArgs = #changes_args{
171         style = all_docs,
172         since = Since,
173         filter = Filter,
174         feed = case get_value(<<"continuous">>, PostProps, false) of
175             true ->
176                 "continuous";
177             false ->
178                 "normal"
179         end,
180         timeout = infinity
181     },
182     ChangesPid = spawn_link(fun() ->
183         ChangesFeedFun = couch_changes:handle_changes(
184             ChangesArgs,
185             {json_req, filter_json_req(Filter, Source, PostProps)},
186             Source
187         ),
188         ChangesFeedFun(fun({change, Change, _}, _) ->
189                 gen_server:call(Server, {add_change, Change}, infinity);
190             (_, _) ->
191                 ok
192         end)
193     end),
194     {ok, #state{changes_loop=ChangesPid, init_args=InitArgs}}.
195
196 maybe_add_filter_qs_params(PostProps, BaseQS) ->
197     case get_value(<<"filter">>, PostProps) of
198     undefined ->
199         BaseQS;
200     FilterName ->
201         {Params} = get_value(<<"query_params">>, PostProps, {[]}),
202         lists:foldr(
203             fun({K, V}, QSAcc) ->
204                 Ks = couch_util:to_list(K),
205                 case proplists:is_defined(Ks, QSAcc) of
206                 true ->
207                     QSAcc;
208                 false ->
209                     [{Ks, V} | QSAcc]
210                 end
211             end,
212             [{"filter", FilterName} | BaseQS],
213             Params
214         )
215     end.
216
217 filter_json_req([], _Db, _PostProps) ->
218     {[]};
219 filter_json_req(?DOC_IDS_FILTER_NAME, _Db, PostProps) ->
220     {[{<<"doc_ids">>, get_value(<<"doc_ids">>, PostProps)}]};
221 filter_json_req(FilterName, Db, PostProps) ->
222     {Query} = get_value(<<"query_params">>, PostProps, {[]}),
223     {ok, Info} = couch_db:get_db_info(Db),
224     % simulate a request to db_name/_changes
225     {[
226         {<<"info">>, {Info}},
227         {<<"id">>, null},
228         {<<"method">>, 'GET'},
229         {<<"path">>, [couch_db:name(Db), <<"_changes">>]},
230         {<<"query">>, {[{<<"filter">>, FilterName} | Query]}},
231         {<<"headers">>, []},
232         {<<"body">>, []},
233         {<<"peer">>, <<"replicator">>},
234         {<<"form">>, []},
235         {<<"cookie">>, []},
236         {<<"userCtx">>, couch_util:json_user_ctx(Db)}
237     ]}.
238
239 handle_call({add_change, Row}, From, State) ->
240     handle_add_change(Row, From, State);
241
242 handle_call(next_changes, From, State) ->
243     handle_next_changes(From, State);
244     
245 handle_call(stop, _From, State) ->
246     {stop, normal, ok, State}.
247
248 handle_cast(_Msg, State) ->
249     {noreply, State}.
250
251 handle_info({ibrowse_async_headers, Id, Code, Hdrs}, #state{reqid=Id}=State) ->
252     handle_headers(list_to_integer(Code), Hdrs, State);
253
254 handle_info({ibrowse_async_response, Id, {error, sel_conn_closed}},
255         #state{reqid=Id}=State) ->
256     handle_retry(State);
257
258 handle_info({ibrowse_async_response, Id, {error, connection_closed}},
259         #state{reqid=Id}=State) ->
260     handle_retry(State);
261
262 handle_info({ibrowse_async_response, Id, {error,E}}, #state{reqid=Id}=State) ->
263     {stop, {error, E}, State};
264
265 handle_info({ibrowse_async_response, Id, Chunk}, #state{reqid=Id}=State) ->
266     Messages = [M || M <- re:split(Chunk, ",?\n", [trim]), M =/= <<>>],
267     handle_messages(Messages, State);
268
269 handle_info({ibrowse_async_response_end, Id}, #state{reqid=Id} = State) ->
270     handle_feed_completion(State);
271
272 handle_info({'EXIT', From, normal}, #state{changes_loop=From} = State) ->
273     handle_feed_completion(State);
274
275 handle_info({'EXIT', From, normal}, #state{conn=From, complete=true} = State) ->
276     {noreply, State};
277
278 handle_info({'EXIT', From, Reason}, #state{changes_loop=From} = State) ->
279     ?LOG_ERROR("changes_loop died with reason ~p", [Reason]),
280     {stop, changes_loop_died, State};
281
282 handle_info({'EXIT', From, Reason}, State) ->
283     ?LOG_ERROR("changes loop, process ~p died with reason ~p", [From, Reason]),
284     {stop, {From, Reason}, State};
285
286 handle_info(Msg, #state{init_args = InitArgs} = State) ->
287     case Msg of
288     changes_timeout ->
289         [_, #http_db{url = Url} | _] = InitArgs,
290         ?LOG_ERROR("changes loop timeout, no data received from ~s",
291             [couch_util:url_strip_password(Url)]);
292     _ ->
293         ?LOG_ERROR("changes loop received unexpected message ~p", [Msg])
294     end,
295     {stop, Msg, State}.
296
297 terminate(_Reason, State) ->
298     #state{
299         changes_loop = ChangesPid,
300         conn = Conn
301     } = State,
302     if is_pid(ChangesPid) -> exit(ChangesPid, stop); true -> ok end,
303     stop_link_worker(Conn).
304
305 code_change(_OldVsn, State, _Extra) ->
306     {ok, State}.
307
308 %internal funs
309
310 handle_add_change(Row, From, #state{reply_to=nil} = State) ->
311     {Rows2, Count2} = queue_changes_row(Row, State),
312     NewState = State#state{count = Count2, rows = Rows2},
313     if Count2 =< ?BUFFER_SIZE ->
314         {reply, ok, NewState};
315     true ->
316         {noreply, NewState#state{changes_from=From}}
317     end;
318 handle_add_change(Row, _From, #state{count=0} = State) ->
319     gen_server:reply(State#state.reply_to, [Row]),
320     {reply, ok, State#state{reply_to=nil}}.
321
322 handle_next_changes(From, #state{count=0}=State) ->
323     if State#state.complete ->
324         {stop, normal, complete, State};
325     true ->
326         {noreply, State#state{reply_to=From}}
327     end;
328 handle_next_changes(_From, State) ->
329     #state{
330         changes_from = ChangesFrom,
331         rows = Rows
332     } = State,
333     NewState = State#state{count=0, changes_from=nil, rows=queue:new()},
334     maybe_stream_next(NewState),
335     if ChangesFrom =/= nil -> gen_server:reply(ChangesFrom, ok); true -> ok end,
336     {reply, queue:to_list(Rows), NewState}.
337
338 handle_headers(200, _, State) ->
339     maybe_stream_next(State),
340     {noreply, State};
341 handle_headers(Code, Hdrs, #state{init_args = InitArgs} = State)
342         when Code =:= 301 ; Code =:= 302 ; Code =:= 303 ->
343     stop_link_worker(State#state.conn),
344     [Parent, Source, Since, PostProps] = InitArgs,
345     Source2 = couch_rep_httpc:redirected_request(Code, Hdrs, Source),
346     Pid2 = couch_rep_httpc:spawn_link_worker_process(Source2),
347     Source3 = Source2#http_db{conn = Pid2},
348     {ibrowse_req_id, ReqId} = couch_rep_httpc:request(Source3),
349     InitArgs2 = [Parent, Source3, Since, PostProps],
350     {noreply, State#state{conn=Pid2, reqid=ReqId, init_args=InitArgs2}};
351 handle_headers(Code, Hdrs, State) ->
352     ?LOG_ERROR("replicator changes feed failed with code ~s and Headers ~n~p",
353         [Code,Hdrs]),
354     {stop, {error, Code}, State}.
355
356 handle_messages([], State) ->
357     maybe_stream_next(State),
358     {noreply, State};
359 handle_messages([<<"{\"results\":[">>|Rest], State) ->
360     handle_messages(Rest, State);
361 handle_messages([<<"]">>, <<"\"last_seq\":", _/binary>>], State) ->
362     handle_feed_completion(State);
363 handle_messages([<<"{\"last_seq\":", _/binary>>], State) ->
364     handle_feed_completion(State);
365 handle_messages([Chunk|Rest], #state{partial_chunk = Partial} = State) ->
366     NewState = try
367         Row = {Props} = decode_row(<<Partial/binary, Chunk/binary>>),
368         case State of
369         #state{reply_to=nil} ->
370             {Rows2, Count2} = queue_changes_row(Row, State),
371             State#state{
372                 last_seq = couch_util:get_value(<<"seq">>, Props),
373                 partial_chunk = <<>>,
374                 rows = Rows2,
375                 count = Count2
376             };
377         #state{count=0, reply_to=From}->
378             gen_server:reply(From, [Row]),
379             State#state{reply_to = nil, partial_chunk = <<>>}
380         end
381     catch
382     throw:{invalid_json, Bad} ->
383         State#state{partial_chunk = Bad}
384     end,
385     handle_messages(Rest, NewState).
386
387 handle_feed_completion(#state{reply_to=nil} = State)->
388     {noreply, State#state{complete=true}};
389 handle_feed_completion(#state{count=0} = State) ->
390     gen_server:reply(State#state.reply_to, complete),
391     {stop, normal, State}.
392
393 handle_retry(State) ->
394     ?LOG_DEBUG("retrying changes feed because our connection closed", []),
395     #state{
396         count = Count,
397         init_args = [_, Source, _, PostProps],
398         last_seq = Since,
399         reply_to = ReplyTo,
400         rows = Rows
401     } = State,
402     case init([nil, Source, Since, PostProps]) of
403     {ok, State1} ->
404         MergedState = State1#state{
405             count = Count,
406             reply_to = ReplyTo,
407             rows = Rows
408         },
409         {noreply, MergedState};
410     _ ->
411         {stop, {error, connection_closed}, State}
412     end.
413
414 by_seq_loop(Server, Source, StartSeq) ->
415     Req = Source#http_db{
416         resource = "_all_docs_by_seq",
417         qs = [{limit, 1000}, {startkey, StartSeq}]
418     },
419     {Results} = couch_rep_httpc:request(Req),
420     Rows = couch_util:get_value(<<"rows">>, Results),
421     if Rows =:= [] -> exit(normal); true -> ok end,
422     EndSeq = lists:foldl(fun({RowInfoList}, _) ->
423         Id = couch_util:get_value(<<"id">>, RowInfoList),
424         Seq = couch_util:get_value(<<"key">>, RowInfoList),
425         {RowProps} = couch_util:get_value(<<"value">>, RowInfoList),
426         RawRevs = [
427             couch_util:get_value(<<"rev">>, RowProps),
428             couch_util:get_value(<<"conflicts">>, RowProps, []),
429             couch_util:get_value(<<"deleted_conflicts">>, RowProps, [])
430         ],
431         ParsedRevs = couch_doc:parse_revs(lists:flatten(RawRevs)),
432         Change = {[
433             {<<"seq">>, Seq},
434             {<<"id">>, Id},
435             {<<"changes">>, [{[{<<"rev">>,R}]} || R <- ParsedRevs]}
436         ]},
437         gen_server:call(Server, {add_change, Change}, infinity),
438         Seq
439     end, 0, Rows),
440     by_seq_loop(Server, Source, EndSeq).
441
442 decode_row(<<",", Rest/binary>>) ->
443     decode_row(Rest);
444 decode_row(Row) ->
445     ?JSON_DECODE(Row).
446
447 maybe_stream_next(#state{reqid=nil}) ->
448     ok;
449 maybe_stream_next(#state{complete=false, count=N} = S) when N < ?BUFFER_SIZE ->
450     timer:cancel(get(timeout)),
451     {ok, Timeout} = timer:send_after(31000, changes_timeout),
452     put(timeout, Timeout),
453     ibrowse:stream_next(S#state.reqid);
454 maybe_stream_next(_) ->
455     timer:cancel(get(timeout)).
456
457 stop_link_worker(Conn) when is_pid(Conn) ->
458     unlink(Conn),
459     receive {'EXIT', Conn, _} -> ok after 0 -> ok end,
460     catch ibrowse:stop_worker_process(Conn);
461 stop_link_worker(_) ->
462     ok.
463
464 redirect_req(#http_db{conn = WorkerPid} = Req, Code, Headers) ->
465     stop_link_worker(WorkerPid),
466     Req2 = couch_rep_httpc:redirected_request(Code, Headers, Req),
467     WorkerPid2 = couch_rep_httpc:spawn_link_worker_process(Req2),
468     Req3 = Req2#http_db{conn = WorkerPid2},
469     {ibrowse_req_id, ReqId} = couch_rep_httpc:request(Req3),
470     {ReqId, Req3}.
471
472 req_no_builtin_doc_ids(#http_db{conn = WorkerPid, qs = QS} = Req, ReqId) ->
473     % CouchDB versions prior to 1.1.0 don't have the builtin filter _doc_ids
474     % and don't allow POSTing to /database/_changes
475     purge_req_messages(ReqId),
476     stop_link_worker(WorkerPid),
477     Req2 = Req#http_db{method = get, qs = lists:keydelete("filter", 1, QS)},
478     WorkerPid2 = couch_rep_httpc:spawn_link_worker_process(Req2),
479     Req3 = Req2#http_db{conn = WorkerPid2},
480     {ibrowse_req_id, ReqId2} = couch_rep_httpc:request(Req3),
481     {ReqId2, Req3}.
482
483 purge_req_messages(ReqId) ->
484     ibrowse:stream_next(ReqId),
485     receive
486     {ibrowse_async_response, ReqId, {error, _}} ->
487         ok;
488     {ibrowse_async_response, ReqId, _Data} ->
489         purge_req_messages(ReqId);
490     {ibrowse_async_response_end, ReqId} ->
491         ok
492     end.
493
494 queue_changes_row(Row, #state{doc_ids = nil} = State) ->
495     maybe_queue_row(Row, State);
496 queue_changes_row({RowProps} = Row,
497     #state{doc_ids = Ids, count = Count, rows = Rows} = State) ->
498     case lists:member(get_value(<<"id">>, RowProps), Ids) of
499     true ->
500         maybe_queue_row(Row, State);
501     false ->
502         {Rows, Count}
503     end.
504
505 maybe_queue_row({Props} = Row, #state{count = Count, rows = Rows} = State) ->
506     case get_value(<<"id">>, Props) of
507     <<>> ->
508         [_, Db | _] = State#state.init_args,
509         ?LOG_ERROR("Replicator: ignoring document with empty ID in source "
510             "database `~s` (_changes sequence ~p)",
511             [dbname(Db), couch_util:get_value(<<"seq">>, Props)]),
512         {Rows, Count};
513     _ ->
514         {queue:in(Row, Rows), Count + 1}
515     end.
516
517 dbname(#http_db{url = Url}) ->
518     couch_util:url_strip_password(Url);
519 dbname(#db{name = Name}) ->
520     Name.