51637f5412d95df5398c7966e9e0070b2a705fb0
[akkoma] / test / pleroma / gun / connection_pool_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Gun.ConnectionPoolTest do
6 use Pleroma.DataCase
7
8 import Mox
9 import ExUnit.CaptureLog
10 alias Pleroma.Gun.ConnectionPool
11
12 defp gun_mock(_) do
13 Pleroma.GunMock
14 |> stub(:open, fn _, _, _ -> Task.start_link(fn -> Process.sleep(100) end) end)
15 |> stub(:await_up, fn _, _ -> {:ok, :http} end)
16 |> stub(:set_owner, fn _, _ -> :ok end)
17
18 :ok
19 end
20
21 setup :gun_mock
22
23 test "gives the same connection to 2 concurrent requests" do
24 Enum.map(
25 [
26 "http://www.korean-books.com.kp/KBMbooks/en/periodic/pictorial/20200530163914.pdf",
27 "http://www.korean-books.com.kp/KBMbooks/en/periodic/pictorial/20200528183427.pdf"
28 ],
29 fn uri ->
30 uri = URI.parse(uri)
31 task_parent = self()
32
33 Task.start_link(fn ->
34 {:ok, conn} = ConnectionPool.get_conn(uri, [])
35 ConnectionPool.release_conn(conn)
36 send(task_parent, conn)
37 end)
38 end
39 )
40
41 [pid, pid] =
42 for _ <- 1..2 do
43 receive do
44 pid -> pid
45 end
46 end
47 end
48
49 @tag :erratic
50 test "connection limit is respected with concurrent requests" do
51 clear_config([:connections_pool, :max_connections]) do
52 clear_config([:connections_pool, :max_connections], 1)
53 # The supervisor needs a reboot to apply the new config setting
54 Process.exit(Process.whereis(Pleroma.Gun.ConnectionPool.WorkerSupervisor), :kill)
55
56 on_exit(fn ->
57 Process.exit(Process.whereis(Pleroma.Gun.ConnectionPool.WorkerSupervisor), :kill)
58 end)
59 end
60
61 capture_log(fn ->
62 Enum.map(
63 [
64 "https://ninenines.eu/",
65 "https://youtu.be/PFGwMiDJKNY"
66 ],
67 fn uri ->
68 uri = URI.parse(uri)
69 task_parent = self()
70
71 Task.start_link(fn ->
72 result = ConnectionPool.get_conn(uri, [])
73 # Sleep so that we don't end up with a situation,
74 # where request from the second process gets processed
75 # only after the first process already released the connection
76 Process.sleep(50)
77
78 case result do
79 {:ok, pid} ->
80 ConnectionPool.release_conn(pid)
81
82 _ ->
83 nil
84 end
85
86 send(task_parent, result)
87 end)
88 end
89 )
90
91 [{:error, :pool_full}, {:ok, _pid}] =
92 for _ <- 1..2 do
93 receive do
94 result -> result
95 end
96 end
97 |> Enum.sort()
98 end)
99 end
100 end