total rebase
[anni] / lib / pleroma / application.ex
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
5 defmodule Pleroma.Application do
6   use Application
7
8   import Cachex.Spec
9
10   alias Pleroma.Config
11
12   require Logger
13
14   @name Mix.Project.config()[:name]
15   @version Mix.Project.config()[:version]
16   @repository Mix.Project.config()[:source_url]
17
18   def name, do: @name
19   def version, do: @version
20   def named_version, do: @name <> " " <> @version
21   def repository, do: @repository
22
23   def user_agent do
24     if Process.whereis(Pleroma.Web.Endpoint) do
25       case Config.get([:http, :user_agent], :default) do
26         :default ->
27           info = "#{Pleroma.Web.Endpoint.url()} <#{Config.get([:instance, :email], "")}>"
28           named_version() <> "; " <> info
29
30         custom ->
31           custom
32       end
33     else
34       # fallback, if endpoint is not started yet
35       "Pleroma Data Loader"
36     end
37   end
38
39   # See http://elixir-lang.org/docs/stable/elixir/Application.html
40   # for more information on OTP Applications
41   def start(_type, _args) do
42     # Scrubbers are compiled at runtime and therefore will cause a conflict
43     # every time the application is restarted, so we disable module
44     # conflicts at runtime
45     Code.compiler_options(ignore_module_conflict: true)
46     # Disable warnings_as_errors at runtime, it breaks Phoenix live reload
47     # due to protocol consolidation warnings
48     Code.compiler_options(warnings_as_errors: false)
49     Pleroma.Telemetry.Logger.attach()
50     Config.Holder.save_default()
51     Pleroma.HTML.compile_scrubbers()
52     Pleroma.Config.Oban.warn()
53     Config.DeprecationWarnings.warn()
54     Pleroma.Web.Plugs.HTTPSecurityPlug.warn_if_disabled()
55     Pleroma.ApplicationRequirements.verify!()
56     load_custom_modules()
57     Pleroma.Docs.JSON.compile()
58     limiters_setup()
59
60     adapter = Application.get_env(:tesla, :adapter)
61
62     if match?({Tesla.Adapter.Finch, _}, adapter) do
63       Logger.info("Starting Finch")
64       Finch.start_link(name: MyFinch)
65     end
66
67     if adapter == Tesla.Adapter.Gun do
68       if version = Pleroma.OTPVersion.version() do
69         [major, minor] =
70           version
71           |> String.split(".")
72           |> Enum.map(&String.to_integer/1)
73           |> Enum.take(2)
74
75         if (major == 22 and minor < 2) or major < 22 do
76           raise "
77             !!!OTP VERSION WARNING!!!
78             You are using gun adapter with OTP version #{version}, which doesn't support correct handling of unordered certificates chains. Please update your Erlang/OTP to at least 22.2.
79             "
80         end
81       else
82         raise "
83           !!!OTP VERSION WARNING!!!
84           To support correct handling of unordered certificates chains - OTP version must be > 22.2.
85           "
86       end
87     end
88
89     # Define workers and child supervisors to be supervised
90     children =
91       [
92         Pleroma.PromEx,
93         Pleroma.Repo,
94         Config.TransferTask,
95         Pleroma.Emoji,
96         Pleroma.Web.Plugs.RateLimiter.Supervisor,
97         {Task.Supervisor, name: Pleroma.TaskSupervisor}
98       ] ++
99         cachex_children() ++
100         http_children(adapter) ++
101         [
102           Pleroma.Stats,
103           Pleroma.JobQueueMonitor,
104           {Majic.Pool, [name: Pleroma.MajicPool, pool_size: Config.get([:majic_pool, :size], 2)]},
105           {Oban, Config.get(Oban)},
106           Pleroma.Web.Endpoint
107         ] ++
108         task_children() ++
109         streamer_registry() ++
110         background_migrators() ++
111         shout_child(shout_enabled?()) ++
112         [Pleroma.Gopher.Server]
113
114     # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
115     # for other strategies and supported options
116     # If we have a lot of caches, default max_restarts can cause test
117     # resets to fail.
118     # Go for the default 3 unless we're in test
119     max_restarts = Application.get_env(:pleroma, __MODULE__)[:max_restarts]
120
121     opts = [strategy: :one_for_one, name: Pleroma.Supervisor, max_restarts: max_restarts]
122     Supervisor.start_link(children, opts)
123   end
124
125   def load_custom_modules do
126     dir = Config.get([:modules, :runtime_dir])
127
128     if dir && File.exists?(dir) do
129       dir
130       |> Pleroma.Utils.compile_dir()
131       |> case do
132         {:error, _errors, _warnings} ->
133           raise "Invalid custom modules"
134
135         {:ok, modules, _warnings} ->
136           if Application.get_env(:pleroma, __MODULE__)[:load_custom_modules] do
137             Enum.each(modules, fn mod ->
138               Logger.info("Custom module loaded: #{inspect(mod)}")
139             end)
140           end
141
142           :ok
143       end
144     end
145   end
146
147   defp cachex_children do
148     [
149       build_cachex("used_captcha", ttl_interval: seconds_valid_interval()),
150       build_cachex("user", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
151       build_cachex("object", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
152       build_cachex("rich_media", default_ttl: :timer.minutes(120), limit: 5000),
153       build_cachex("scrubber", limit: 2500),
154       build_cachex("scrubber_management", limit: 2500),
155       build_cachex("idempotency", expiration: idempotency_expiration(), limit: 2500),
156       build_cachex("web_resp", limit: 2500),
157       build_cachex("emoji_packs", expiration: emoji_packs_expiration(), limit: 10),
158       build_cachex("failed_proxy_url", limit: 2500),
159       build_cachex("failed_media_helper_url", default_ttl: :timer.minutes(15), limit: 2_500),
160       build_cachex("banned_urls", default_ttl: :timer.hours(24 * 30), limit: 5_000),
161       build_cachex("chat_message_id_idempotency_key",
162         expiration: chat_message_id_idempotency_key_expiration(),
163         limit: 500_000
164       ),
165       build_cachex("rel_me", limit: 2500)
166     ]
167   end
168
169   defp emoji_packs_expiration,
170     do: expiration(default: :timer.seconds(5 * 60), interval: :timer.seconds(60))
171
172   defp idempotency_expiration,
173     do: expiration(default: :timer.seconds(6 * 60 * 60), interval: :timer.seconds(60))
174
175   defp chat_message_id_idempotency_key_expiration,
176     do: expiration(default: :timer.minutes(2), interval: :timer.seconds(60))
177
178   defp seconds_valid_interval,
179     do: :timer.seconds(Config.get!([Pleroma.Captcha, :seconds_valid]))
180
181   @spec build_cachex(String.t(), keyword()) :: map()
182   def build_cachex(type, opts),
183     do: %{
184       id: String.to_atom("cachex_" <> type),
185       start: {Cachex, :start_link, [String.to_atom(type <> "_cache"), opts]},
186       type: :worker
187     }
188
189   defp shout_enabled?, do: Config.get([:shout, :enabled])
190
191   defp streamer_registry do
192     if Application.get_env(:pleroma, __MODULE__)[:streamer_registry] do
193       [
194         {Registry,
195          [
196            name: Pleroma.Web.Streamer.registry(),
197            keys: :duplicate,
198            partitions: System.schedulers_online()
199          ]}
200       ]
201     else
202       []
203     end
204   end
205
206   defp background_migrators do
207     if Application.get_env(:pleroma, __MODULE__)[:background_migrators] do
208       [
209         Pleroma.Migrators.HashtagsTableMigrator,
210         Pleroma.Migrators.ContextObjectsDeletionMigrator
211       ]
212     else
213       []
214     end
215   end
216
217   defp shout_child(true) do
218     [
219       Pleroma.Web.ShoutChannel.ShoutChannelState,
220       {Phoenix.PubSub, [name: Pleroma.PubSub, adapter: Phoenix.PubSub.PG2]}
221     ]
222   end
223
224   defp shout_child(_), do: []
225
226   defp task_children do
227     children = [
228       %{
229         id: :web_push_init,
230         start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
231         restart: :temporary
232       }
233     ]
234
235     if Application.get_env(:pleroma, __MODULE__)[:internal_fetch] do
236       children ++
237         [
238           %{
239             id: :internal_fetch_init,
240             start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
241             restart: :temporary
242           }
243         ]
244     else
245       children
246     end
247   end
248
249   # start hackney and gun pools in tests
250   defp http_children(adapter) do
251     if Application.get_env(:pleroma, __MODULE__)[:test_http_pools] do
252       http_children_hackney() ++ http_children_gun()
253     else
254       cond do
255         match?(Tesla.Adapter.Hackney, adapter) -> http_children_hackney()
256         match?(Tesla.Adapter.Gun, adapter) -> http_children_gun()
257         true -> []
258       end
259     end
260   end
261
262   defp http_children_hackney do
263     pools = [:federation, :media]
264
265     pools =
266       if Config.get([Pleroma.Upload, :proxy_remote]) do
267         [:upload | pools]
268       else
269         pools
270       end
271
272     for pool <- pools do
273       options = Config.get([:hackney_pools, pool])
274       :hackney_pool.child_spec(pool, options)
275     end
276   end
277
278   defp http_children_gun do
279     Pleroma.Gun.ConnectionPool.children() ++
280       [{Task, &Pleroma.HTTP.AdapterHelper.Gun.limiter_setup/0}]
281   end
282
283   @spec limiters_setup() :: :ok
284   def limiters_setup do
285     config = Config.get(ConcurrentLimiter, [])
286
287     [
288       Pleroma.Web.RichMedia.Helpers,
289       Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy,
290       Pleroma.Search
291     ]
292     |> Enum.each(fn module ->
293       mod_config = Keyword.get(config, module, [])
294
295       max_running = Keyword.get(mod_config, :max_running, 5)
296       max_waiting = Keyword.get(mod_config, :max_waiting, 5)
297
298       ConcurrentLimiter.new(module, max_running, max_waiting)
299     end)
300   end
301 end