Merge branch 'develop' into chore/elixir-1.11
[akkoma] / lib / pleroma / application.ex
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.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 @env Mix.env()
18
19 def name, do: @name
20 def version, do: @version
21 def named_version, do: @name <> " " <> @version
22 def repository, do: @repository
23
24 def user_agent do
25 if Process.whereis(Pleroma.Web.Endpoint) do
26 case Config.get([:http, :user_agent], :default) do
27 :default ->
28 info = "#{Pleroma.Web.base_url()} <#{Config.get([:instance, :email], "")}>"
29 named_version() <> "; " <> info
30
31 custom ->
32 custom
33 end
34 else
35 # fallback, if endpoint is not started yet
36 "Pleroma Data Loader"
37 end
38 end
39
40 # See http://elixir-lang.org/docs/stable/elixir/Application.html
41 # for more information on OTP Applications
42 def start(_type, _args) do
43 # Scrubbers are compiled at runtime and therefore will cause a conflict
44 # every time the application is restarted, so we disable module
45 # conflicts at runtime
46 Code.compiler_options(ignore_module_conflict: true)
47 # Disable warnings_as_errors at runtime, it breaks Phoenix live reload
48 # due to protocol consolidation warnings
49 Code.compiler_options(warnings_as_errors: false)
50 Pleroma.Telemetry.Logger.attach()
51 Config.Holder.save_default()
52 Pleroma.HTML.compile_scrubbers()
53 Pleroma.Config.Oban.warn()
54 Config.DeprecationWarnings.warn()
55 Pleroma.Web.Plugs.HTTPSecurityPlug.warn_if_disabled()
56 Pleroma.ApplicationRequirements.verify!()
57 setup_instrumenters()
58 load_custom_modules()
59 Pleroma.Docs.JSON.compile()
60
61 adapter = Application.get_env(:tesla, :adapter)
62
63 if adapter == Tesla.Adapter.Gun do
64 if version = Pleroma.OTPVersion.version() do
65 [major, minor] =
66 version
67 |> String.split(".")
68 |> Enum.map(&String.to_integer/1)
69 |> Enum.take(2)
70
71 if (major == 22 and minor < 2) or major < 22 do
72 raise "
73 !!!OTP VERSION WARNING!!!
74 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.
75 "
76 end
77 else
78 raise "
79 !!!OTP VERSION WARNING!!!
80 To support correct handling of unordered certificates chains - OTP version must be > 22.2.
81 "
82 end
83 end
84
85 # Define workers and child supervisors to be supervised
86 children =
87 [
88 Pleroma.Repo,
89 Config.TransferTask,
90 Pleroma.Emoji,
91 Pleroma.Web.Plugs.RateLimiter.Supervisor
92 ] ++
93 cachex_children() ++
94 http_children(adapter, @env) ++
95 [
96 Pleroma.Stats,
97 Pleroma.JobQueueMonitor,
98 {Oban, Config.get(Oban)}
99 ] ++
100 task_children(@env) ++
101 dont_run_in_test(@env) ++
102 chat_child(chat_enabled?()) ++
103 [
104 Pleroma.Web.Endpoint,
105 Pleroma.Gopher.Server
106 ]
107
108 # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
109 # for other strategies and supported options
110 opts = [strategy: :one_for_one, name: Pleroma.Supervisor]
111 Supervisor.start_link(children, opts)
112 end
113
114 def load_custom_modules do
115 dir = Config.get([:modules, :runtime_dir])
116
117 if dir && File.exists?(dir) do
118 dir
119 |> Pleroma.Utils.compile_dir()
120 |> case do
121 {:error, _errors, _warnings} ->
122 raise "Invalid custom modules"
123
124 {:ok, modules, _warnings} ->
125 if @env != :test do
126 Enum.each(modules, fn mod ->
127 Logger.info("Custom module loaded: #{inspect(mod)}")
128 end)
129 end
130
131 :ok
132 end
133 end
134 end
135
136 defp setup_instrumenters do
137 require Prometheus.Registry
138
139 if Application.get_env(:prometheus, Pleroma.Repo.Instrumenter) do
140 :ok =
141 :telemetry.attach(
142 "prometheus-ecto",
143 [:pleroma, :repo, :query],
144 &Pleroma.Repo.Instrumenter.handle_event/4,
145 %{}
146 )
147
148 Pleroma.Repo.Instrumenter.setup()
149 end
150
151 Pleroma.Web.Endpoint.MetricsExporter.setup()
152 Pleroma.Web.Endpoint.PipelineInstrumenter.setup()
153 Pleroma.Web.Endpoint.Instrumenter.setup()
154 end
155
156 defp cachex_children do
157 [
158 build_cachex("used_captcha", ttl_interval: seconds_valid_interval()),
159 build_cachex("user", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
160 build_cachex("object", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
161 build_cachex("rich_media", default_ttl: :timer.minutes(120), limit: 5000),
162 build_cachex("scrubber", limit: 2500),
163 build_cachex("idempotency", expiration: idempotency_expiration(), limit: 2500),
164 build_cachex("web_resp", limit: 2500),
165 build_cachex("emoji_packs", expiration: emoji_packs_expiration(), limit: 10),
166 build_cachex("failed_proxy_url", limit: 2500),
167 build_cachex("banned_urls", default_ttl: :timer.hours(24 * 30), limit: 5_000)
168 ]
169 end
170
171 defp emoji_packs_expiration,
172 do: expiration(default: :timer.seconds(5 * 60), interval: :timer.seconds(60))
173
174 defp idempotency_expiration,
175 do: expiration(default: :timer.seconds(6 * 60 * 60), interval: :timer.seconds(60))
176
177 defp seconds_valid_interval,
178 do: :timer.seconds(Config.get!([Pleroma.Captcha, :seconds_valid]))
179
180 @spec build_cachex(String.t(), keyword()) :: map()
181 def build_cachex(type, opts),
182 do: %{
183 id: String.to_atom("cachex_" <> type),
184 start: {Cachex, :start_link, [String.to_atom(type <> "_cache"), opts]},
185 type: :worker
186 }
187
188 defp chat_enabled?, do: Config.get([:chat, :enabled])
189
190 defp dont_run_in_test(env) when env in [:test, :benchmark], do: []
191
192 defp dont_run_in_test(_) do
193 [
194 {Registry,
195 [
196 name: Pleroma.Web.Streamer.registry(),
197 keys: :duplicate,
198 partitions: System.schedulers_online()
199 ]},
200 Pleroma.Web.FedSockets.Supervisor
201 ]
202 end
203
204 defp chat_child(true) do
205 [
206 Pleroma.Web.ChatChannel.ChatChannelState,
207 {Phoenix.PubSub, [name: Pleroma.PubSub, adapter: Phoenix.PubSub.PG2]}
208 ]
209 end
210
211 defp chat_child(_), do: []
212
213 defp task_children(:test) do
214 [
215 %{
216 id: :web_push_init,
217 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
218 restart: :temporary
219 }
220 ]
221 end
222
223 defp task_children(_) do
224 [
225 %{
226 id: :web_push_init,
227 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
228 restart: :temporary
229 },
230 %{
231 id: :internal_fetch_init,
232 start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
233 restart: :temporary
234 }
235 ]
236 end
237
238 # start hackney and gun pools in tests
239 defp http_children(_, :test) do
240 http_children(Tesla.Adapter.Hackney, nil) ++ http_children(Tesla.Adapter.Gun, nil)
241 end
242
243 defp http_children(Tesla.Adapter.Hackney, _) do
244 pools = [:federation, :media]
245
246 pools =
247 if Config.get([Pleroma.Upload, :proxy_remote]) do
248 [:upload | pools]
249 else
250 pools
251 end
252
253 for pool <- pools do
254 options = Config.get([:hackney_pools, pool])
255 :hackney_pool.child_spec(pool, options)
256 end
257 end
258
259 defp http_children(Tesla.Adapter.Gun, _) do
260 Pleroma.Gun.ConnectionPool.children() ++
261 [{Task, &Pleroma.HTTP.AdapterHelper.Gun.limiter_setup/0}]
262 end
263
264 defp http_children(_, _), do: []
265 end