1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTTP do
7 Wrapper for `Tesla.request/2`.
10 alias Pleroma.HTTP.AdapterHelper
11 alias Pleroma.HTTP.Request
12 alias Pleroma.HTTP.RequestBuilder, as: Builder
19 @type method() :: :get | :post | :put | :delete | :head
24 See `Pleroma.HTTP.request/5`
26 @spec get(Request.url() | nil, Request.headers(), keyword()) ::
27 nil | {:ok, Env.t()} | {:error, any()}
28 def get(url, headers \\ [], options \\ [])
29 def get(nil, _, _), do: nil
30 def get(url, headers, options), do: request(:get, url, "", headers, options)
32 @spec head(Request.url(), Request.headers(), keyword()) :: {:ok, Env.t()} | {:error, any()}
33 def head(url, headers \\ [], options \\ []), do: request(:head, url, "", headers, options)
36 Performs POST request.
38 See `Pleroma.HTTP.request/5`
40 @spec post(Request.url(), String.t(), Request.headers(), keyword()) ::
41 {:ok, Env.t()} | {:error, any()}
42 def post(url, body, headers \\ [], options \\ []),
43 do: request(:post, url, body, headers, options)
46 Builds and performs http request.
49 `method` - :get, :post, :put, :delete, :head
52 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
53 `options` - custom, per-request middleware or adapter options
56 `{:ok, %Tesla.Env{}}` or `{:error, error}`
59 @spec request(method(), Request.url(), String.t(), Request.headers(), keyword()) ::
60 {:ok, Env.t()} | {:error, any()}
61 def request(method, url, body, headers, options) when is_binary(url) do
63 adapter_opts = AdapterHelper.options(uri, options[:adapter] || [])
65 case AdapterHelper.get_conn(uri, adapter_opts) do
66 {:ok, adapter_opts} ->
67 options = put_in(options[:adapter], adapter_opts)
68 params = options[:params] || []
69 request = build_request(method, headers, options, url, body, params)
71 adapter = Application.get_env(:tesla, :adapter)
73 client = Tesla.client(adapter_middlewares(adapter), adapter)
77 request(client, request)
83 # Connection release is handled in a custom FollowRedirects middleware
89 @spec request(Client.t(), keyword()) :: {:ok, Env.t()} | {:error, any()}
90 def request(client, request), do: Tesla.request(client, request)
92 defp build_request(method, headers, options, url, body, params) do
94 |> Builder.method(method)
95 |> Builder.headers(headers)
96 |> Builder.opts(options)
98 |> Builder.add_param(:body, :body, body)
99 |> Builder.add_param(:query, :query, params)
100 |> Builder.convert_to_keyword()
103 @prefix Pleroma.Gun.ConnectionPool
104 defp maybe_limit(fun, Tesla.Adapter.Gun, opts) do
105 ConcurrentLimiter.limit(:"#{@prefix}.#{opts[:pool] || :default}", fun)
108 defp maybe_limit(fun, _, _) do
112 defp adapter_middlewares(Tesla.Adapter.Gun) do
113 [Pleroma.HTTP.Middleware.FollowRedirects]
116 defp adapter_middlewares(_), do: []