summaryrefslogtreecommitdiff
path: root/test/elixir/test/changes_async_test.exs
blob: 26a0c5037050d8e8c1fb5aaebf14f174cccc4867 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
defmodule ChangesAsyncTest do
  use CouchTestCase

  @moduletag :changes
  @moduletag kind: :single_node

  @moduledoc """
  Test CouchDB /{db}/_changes
  """

  @tag :with_db
  test "live changes", context do
    db_name = context[:db_name]
    test_changes(db_name, "live")
  end

  @tag :with_db
  test "continuous changes", context do
    db_name = context[:db_name]
    test_changes(db_name, "continuous")
  end

  @tag :with_db
  test "longpoll changes", context do
    db_name = context[:db_name]

    check_empty_db(db_name)

    create_doc(db_name, sample_doc_foo())

    req_id =
      Couch.get("/#{db_name}/_changes?feed=longpoll",
        stream_to: self()
      )

    changes = process_response(req_id.id, &parse_chunk/1)
    assert length(changes["results"]) == 1, "db should not be empty"
    last_seq = changes["last_seq"]
    assert last_seq != 0

    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    req_id =
      Couch.get("/#{db_name}/_changes?feed=longpoll&since=#{last_seq}",
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)

    create_doc_bar(db_name, "bar")

    changes =
      req_id.id
      |> process_response(&parse_chunk/1)

    assert length(changes["results"]) == 1, "should return one change"
    next_last_seq = changes["last_seq"]
    assert next_last_seq > last_seq

    req_id =
      Couch.get("/#{db_name}/_changes?feed=longpoll&since=now",
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)

    create_doc_bar(db_name, "barzzzz")

    changes = process_response(req_id.id, &parse_chunk/1)
    assert length(changes["results"]) == 1, "should return one change"
    assert Enum.at(changes["results"], 0)["id"] == "barzzzz"
    assert changes["last_seq"] > next_last_seq
  end

  @tag :with_db
  test "eventsource changes", context do
    db_name = context[:db_name]

    check_empty_db(db_name)

    create_doc(db_name, sample_doc_foo())
    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    req_id =
      Rawresp.get("/#{db_name}/_changes?feed=eventsource&timeout=2000",
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)

    create_doc_bar(db_name, "bar")

    changes = process_response(req_id.id, &parse_event/1, 5000)

    assert length(changes) == 2
    assert Enum.at(changes, 0)["id"] == "foo"
    assert Enum.at(changes, 1)["id"] == "bar"

    HTTPotion.stop_worker_process(worker_pid)
  end

  @tag :with_db
  test "eventsource heartbeat", context do
    db_name = context[:db_name]

    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    req_id =
      Rawresp.get("/#{db_name}/_changes?feed=eventsource&heartbeat=10",
        stream_to: {self(), :once},
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)
    beats = wait_for_heartbeats(req_id.id, 0, 3)
    assert beats == 3
    HTTPotion.stop_worker_process(worker_pid)
  end

  @tag :with_db
  test "longpoll filtered changes", context do
    db_name = context[:db_name]
    create_filters_view(db_name)

    create_doc(db_name, %{bop: "foom"})
    create_doc(db_name, %{bop: false})

    req_id =
      Couch.get("/#{db_name}/_changes?feed=longpoll&filter=changes_filter/bop",
        stream_to: self()
      )

    changes = process_response(req_id.id, &parse_chunk/1)
    assert length(changes["results"]) == 1, "db should not be empty"
    assert changes["last_seq"] != 0

    last_seq = changes["last_seq"]
    # longpoll waits until a matching change before returning
    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    req_id =
      Couch.get(
        "/#{db_name}/_changes?feed=longpoll&filter=changes_filter/bop&since=#{last_seq}",
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)
    create_doc(db_name, %{_id: "falsy", bop: ""})
    # Doc doesn't match the filter
    changes = process_response(req_id.id, &parse_chunk/1)
    assert changes == :timeout

    # Doc matches the filter
    create_doc(db_name, %{_id: "bingo", bop: "bingo"})
    changes = process_response(req_id.id, &parse_chunk/1)
    assert length(changes["results"]) == 1, "db should not be empty"
    assert changes["last_seq"] > last_seq
    assert Enum.at(changes["results"], 0)["id"] == "bingo"
  end

  @tag :with_db
  test "continuous filtered changes", context do
    db_name = context[:db_name]
    create_filters_view(db_name)

    create_doc(db_name, %{bop: false})
    create_doc(db_name, %{_id: "bingo", bop: "bingo"})

    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    req_id =
      Rawresp.get(
        "/#{db_name}/_changes?feed=continuous&filter=changes_filter/bop&timeout=2000",
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)
    create_doc(db_name, %{_id: "rusty", bop: "plankton"})

    changes = process_response(req_id.id, &parse_changes_line_chunk/1, 5000)

    changes_ids =
      changes
      |> Enum.filter(fn p -> Map.has_key?(p, "id") end)
      |> Enum.map(fn p -> p["id"] end)

    assert Enum.member?(changes_ids, "bingo")
    assert Enum.member?(changes_ids, "rusty")
    assert length(changes_ids) == 2
  end

  @tag :with_db
  test "continuous filtered changes with doc ids", context do
    db_name = context[:db_name]
    doc_ids = %{doc_ids: ["doc1", "doc3", "doc4"]}

    create_doc(db_name, %{_id: "doc1", value: 1})
    create_doc(db_name, %{_id: "doc2", value: 2})

    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    req_id =
      Rawresp.post(
        "/#{db_name}/_changes?feed=continuous&timeout=2000&filter=_doc_ids",
        body: doc_ids,
        headers: ["Content-Type": "application/json"],
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id.id, 200)
    create_doc(db_name, %{_id: "doc3", value: 3})

    changes = process_response(req_id.id, &parse_changes_line_chunk/1, 5000)

    changes_ids =
      changes
      |> Enum.filter(fn p -> Map.has_key?(p, "id") end)
      |> Enum.map(fn p -> p["id"] end)

    assert Enum.member?(changes_ids, "doc1")
    assert Enum.member?(changes_ids, "doc3")
    assert length(changes_ids) == 2
  end

  @tag :with_db
  test "COUCHDB-1852", context do
    db_name = context[:db_name]

    create_doc(db_name, %{bop: "foom"})
    create_doc(db_name, %{bop: "foom"})
    create_doc(db_name, %{bop: "foom"})
    create_doc(db_name, %{bop: "foom"})

    resp = Couch.get("/#{db_name}/_changes")
    assert length(resp.body["results"]) == 4
    seq = Enum.at(resp.body["results"], 1)["seq"]

    {:ok, worker_pid} = HTTPotion.spawn_link_worker_process(Couch.base_url())

    # simulate an EventSource request with a Last-Event-ID header
    req_id =
      Rawresp.get(
        "/#{db_name}/_changes?feed=eventsource&timeout=100&since=0",
        headers: [Accept: "text/event-stream", "Last-Event-ID": seq],
        stream_to: self(),
        direct: worker_pid
      )

    changes = process_response(req_id.id, &parse_event/1)
    assert length(changes) == 2
  end

  defp wait_for_heartbeats(id, beats, expexted_beats) do
    if beats < expexted_beats do
      :ibrowse.stream_next(id)
      is_heartbeat = process_response(id, &parse_heartbeat/1)

      case is_heartbeat do
        :heartbeat -> wait_for_heartbeats(id, beats + 1, expexted_beats)
        :timeout -> beats
        _ -> wait_for_heartbeats(id, beats, expexted_beats)
      end
    else
      beats
    end
  end

  defp wait_for_headers(id, status, timeout \\ 1000) do
    receive do
      %HTTPotion.AsyncHeaders{id: ^id, status_code: ^status} ->
        :ok

      _ ->
        wait_for_headers(id, status, timeout)
    after
      timeout -> :timeout
    end
  end

  defp process_response(id, chunk_parser, timeout \\ 2000) do
    receive do
      %HTTPotion.AsyncChunk{id: ^id} = msg ->
        chunk_parser.(msg)

      _ ->
        process_response(id, chunk_parser, timeout)
    after
      timeout -> :timeout
    end
  end

  defp parse_chunk(msg) do
    msg.chunk |> IO.iodata_to_binary() |> :jiffy.decode([:return_maps])
  end

  defp parse_event(msg) do
    captures = Regex.scan(~r/data: (.*)/, msg.chunk)

    captures
    |> Enum.map(fn p -> Enum.at(p, 1) end)
    |> Enum.filter(fn p -> String.trim(p) != "" end)
    |> Enum.map(fn p ->
      p
      |> IO.iodata_to_binary()
      |> :jiffy.decode([:return_maps])
    end)
  end

  defp parse_heartbeat(msg) do
    is_heartbeat = Regex.match?(~r/event: heartbeat/, msg.chunk)

    if is_heartbeat do
      :heartbeat
    else
      :other
    end
  end

  defp check_empty_db(db_name) do
    resp = Couch.get("/#{db_name}/_changes")
    assert resp.body["results"] == [], "db must be empty"
    assert resp.body["last_seq"] == 0
  end

  defp test_changes(db_name, feed) do
    check_empty_db(db_name)
    {_, resp} = create_doc(db_name, sample_doc_foo())
    rev = resp.body["rev"]

    # TODO: retry_part
    resp = Couch.get("/#{db_name}/_changes")
    assert length(resp.body["results"]) == 1, "db must not be empty"
    assert resp.body["last_seq"] != 0

    # increase timeout to 100 to have enough time 2 assemble
    # (seems like too little timeouts kill
    resp = Rawresp.get("/#{db_name}/_changes?feed=#{feed}&timeout=100")
    changes = parse_changes_line(resp.body)

    change = Enum.at(changes, 0)
    assert Enum.at(change["changes"], 0)["rev"] == rev

    # the sequence is not fully ordered and a complex structure now
    change = Enum.at(changes, 1)
    assert change["last_seq"] != 0

     create_doc_bar(db_name, "bar1")
    {:ok, worker_pid} = HTTPotion.spawn_worker_process(Couch.base_url())

    %HTTPotion.AsyncResponse{id: req_id} =
      Rawresp.get("/#{db_name}/_changes?feed=#{feed}&timeout=500",
        stream_to: self(),
        direct: worker_pid
      )

    :ok = wait_for_headers(req_id, 200)
    create_doc_bar(db_name, "bar2")

    changes = process_response(req_id, &parse_changes_line_chunk/1)
    assert length(changes) == 3

    HTTPotion.stop_worker_process(worker_pid)
  end

  def create_doc_bar(db_name, id) do
    create_doc(db_name, %{:_id => id, :bar => 1})
  end

  defp parse_changes_line_chunk(msg) do
    parse_changes_line(msg.chunk)
  end

  defp parse_changes_line(body) do
    body_lines = String.split(body, "\n")

    body_lines
    |> Enum.filter(fn line -> line != "" end)
    |> Enum.map(fn line ->
      line |> IO.iodata_to_binary() |> :jiffy.decode([:return_maps])
    end)
  end

  defp create_filters_view(db_name) do
    dynamic_fun = """
    function(doc, req) {
      var field = req.query.field;
      return doc[field];
    }
    """

    userctx_fun = """
    function(doc, req) {
      var field = req.query.field;
      return doc[field];
    }
    """

    blah_fun = """
    function(doc) {
              if (doc._id == "blah") {
              emit(null, null);
            }
          }
    """

    ddoc = %{
      _id: "_design/changes_filter",
      filters: %{
        bop: "function(doc, req) { return (doc.bop);}",
        dynamic: dynamic_fun,
        userCtx: userctx_fun,
        conflicted: "function(doc, req) { return (doc._conflicts);}"
      },
      options: %{
        local_seq: true
      },
      views: %{
        local_seq: %{
          map: "function(doc) {emit(doc._local_seq, null)}"
        },
        blah: %{
          map: blah_fun
        }
      }
    }

    create_doc(db_name, ddoc)
  end
end