logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

gun.ex (2421B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.HTTP.AdapterHelper.Gun do
  5. @behaviour Pleroma.HTTP.AdapterHelper
  6. alias Pleroma.Config
  7. alias Pleroma.HTTP.AdapterHelper
  8. require Logger
  9. @defaults [
  10. retry: 1,
  11. retry_timeout: 1_000
  12. ]
  13. @type pool() :: :federation | :upload | :media | :rich_media | :default
  14. @spec options(keyword(), URI.t()) :: keyword()
  15. def options(incoming_opts \\ [], %URI{} = uri) do
  16. proxy =
  17. [:http, :proxy_url]
  18. |> Config.get()
  19. |> AdapterHelper.format_proxy()
  20. config_opts = Config.get([:http, :adapter], [])
  21. @defaults
  22. |> Keyword.merge(config_opts)
  23. |> add_scheme_opts(uri)
  24. |> AdapterHelper.maybe_add_proxy(proxy)
  25. |> Keyword.merge(incoming_opts)
  26. |> put_timeout()
  27. |> maybe_stream()
  28. end
  29. defp add_scheme_opts(opts, %{scheme: "http"}), do: opts
  30. defp add_scheme_opts(opts, %{scheme: "https"}) do
  31. Keyword.put(opts, :certificates_verification, true)
  32. end
  33. defp put_timeout(opts) do
  34. {recv_timeout, opts} = Keyword.pop(opts, :recv_timeout, pool_timeout(opts[:pool]))
  35. # this is the timeout to receive a message from Gun
  36. # `:timeout` key is used in Tesla
  37. Keyword.put(opts, :timeout, recv_timeout)
  38. end
  39. # Gun uses [body_as: :stream]
  40. defp maybe_stream(opts) do
  41. case Keyword.pop(opts, :stream, nil) do
  42. {true, opts} -> Keyword.put(opts, :body_as, :stream)
  43. {_, opts} -> opts
  44. end
  45. end
  46. @spec pool_timeout(pool()) :: non_neg_integer()
  47. def pool_timeout(pool) do
  48. default = Config.get([:pools, :default, :recv_timeout], 5_000)
  49. Config.get([:pools, pool, :recv_timeout], default)
  50. end
  51. def limiter_setup do
  52. prefix = Pleroma.Gun.ConnectionPool
  53. wait = Config.get([:connections_pool, :connection_acquisition_wait])
  54. retries = Config.get([:connections_pool, :connection_acquisition_retries])
  55. :pools
  56. |> Config.get([])
  57. |> Enum.each(fn {name, opts} ->
  58. max_running = Keyword.get(opts, :size, 50)
  59. max_waiting = Keyword.get(opts, :max_waiting, 10)
  60. result =
  61. ConcurrentLimiter.new(:"#{prefix}.#{name}", max_running, max_waiting,
  62. wait: wait,
  63. max_retries: retries
  64. )
  65. case result do
  66. :ok -> :ok
  67. {:error, :existing} -> :ok
  68. end
  69. end)
  70. :ok
  71. end
  72. end