Merge branch 'develop' into 'fix/2412-filters'
[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 test "connection limit is respected with concurrent requests" do
50 clear_config([:connections_pool, :max_connections]) do
51 clear_config([:connections_pool, :max_connections], 1)
52 # The supervisor needs a reboot to apply the new config setting
53 Process.exit(Process.whereis(Pleroma.Gun.ConnectionPool.WorkerSupervisor), :kill)
54
55 on_exit(fn ->
56 Process.exit(Process.whereis(Pleroma.Gun.ConnectionPool.WorkerSupervisor), :kill)
57 end)
58 end
59
60 capture_log(fn ->
61 Enum.map(
62 [
63 "https://ninenines.eu/",
64 "https://youtu.be/PFGwMiDJKNY"
65 ],
66 fn uri ->
67 uri = URI.parse(uri)
68 task_parent = self()
69
70 Task.start_link(fn ->
71 result = ConnectionPool.get_conn(uri, [])
72 # Sleep so that we don't end up with a situation,
73 # where request from the second process gets processed
74 # only after the first process already released the connection
75 Process.sleep(50)
76
77 case result do
78 {:ok, pid} ->
79 ConnectionPool.release_conn(pid)
80
81 _ ->
82 nil
83 end
84
85 send(task_parent, result)
86 end)
87 end
88 )
89
90 [{:error, :pool_full}, {:ok, _pid}] =
91 for _ <- 1..2 do
92 receive do
93 result -> result
94 end
95 end
96 |> Enum.sort()
97 end)
98 end
99 end