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