Add swaggerUI options (#66)
[akkoma] / lib / pleroma / application.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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 @mix_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.Endpoint.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 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 setup_instrumenters()
57 load_custom_modules()
58 Pleroma.Docs.JSON.compile()
59 limiters_setup()
60
61 # Define workers and child supervisors to be supervised
62 children =
63 [
64 Pleroma.Repo,
65 Config.TransferTask,
66 Pleroma.Emoji,
67 Pleroma.Web.Plugs.RateLimiter.Supervisor
68 ] ++
69 cachex_children() ++
70 http_children() ++
71 [
72 Pleroma.Stats,
73 Pleroma.JobQueueMonitor,
74 {Majic.Pool, [name: Pleroma.MajicPool, pool_size: Config.get([:majic_pool, :size], 2)]},
75 {Oban, Config.get(Oban)},
76 Pleroma.Web.Endpoint
77 ] ++
78 elasticsearch_children() ++
79 task_children(@mix_env) ++
80 dont_run_in_test(@mix_env) ++
81 shout_child(shout_enabled?())
82
83 # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
84 # for other strategies and supported options
85 # If we have a lot of caches, default max_restarts can cause test
86 # resets to fail.
87 # Go for the default 3 unless we're in test
88 max_restarts =
89 if @mix_env == :test do
90 100
91 else
92 3
93 end
94
95 opts = [strategy: :one_for_one, name: Pleroma.Supervisor, max_restarts: max_restarts]
96 result = Supervisor.start_link(children, opts)
97
98 set_postgres_server_version()
99
100 result
101 end
102
103 defp set_postgres_server_version do
104 version =
105 with %{rows: [[version]]} <- Ecto.Adapters.SQL.query!(Pleroma.Repo, "show server_version"),
106 {num, _} <- Float.parse(version) do
107 num
108 else
109 e ->
110 Logger.warn(
111 "Could not get the postgres version: #{inspect(e)}.\nSetting the default value of 9.6"
112 )
113
114 9.6
115 end
116
117 :persistent_term.put({Pleroma.Repo, :postgres_version}, version)
118 end
119
120 def load_custom_modules do
121 dir = Config.get([:modules, :runtime_dir])
122
123 if dir && File.exists?(dir) do
124 dir
125 |> Pleroma.Utils.compile_dir()
126 |> case do
127 {:error, _errors, _warnings} ->
128 raise "Invalid custom modules"
129
130 {:ok, modules, _warnings} ->
131 if @mix_env != :test do
132 Enum.each(modules, fn mod ->
133 Logger.info("Custom module loaded: #{inspect(mod)}")
134 end)
135 end
136
137 :ok
138 end
139 end
140 end
141
142 defp setup_instrumenters do
143 require Prometheus.Registry
144
145 if Application.get_env(:prometheus, Pleroma.Repo.Instrumenter) do
146 :ok =
147 :telemetry.attach(
148 "prometheus-ecto",
149 [:pleroma, :repo, :query],
150 &Pleroma.Repo.Instrumenter.handle_event/4,
151 %{}
152 )
153
154 Pleroma.Repo.Instrumenter.setup()
155 end
156
157 Pleroma.Web.Endpoint.MetricsExporter.setup()
158 Pleroma.Web.Endpoint.PipelineInstrumenter.setup()
159
160 # Note: disabled until prometheus-phx is integrated into prometheus-phoenix:
161 # Pleroma.Web.Endpoint.Instrumenter.setup()
162 PrometheusPhx.setup()
163 end
164
165 defp cachex_children do
166 [
167 build_cachex("used_captcha", ttl_interval: seconds_valid_interval()),
168 build_cachex("user", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
169 build_cachex("object", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
170 build_cachex("rich_media", default_ttl: :timer.minutes(120), limit: 5000),
171 build_cachex("scrubber", limit: 2500),
172 build_cachex("idempotency", expiration: idempotency_expiration(), limit: 2500),
173 build_cachex("web_resp", limit: 2500),
174 build_cachex("emoji_packs", expiration: emoji_packs_expiration(), limit: 10),
175 build_cachex("failed_proxy_url", limit: 2500),
176 build_cachex("banned_urls", default_ttl: :timer.hours(24 * 30), limit: 5_000),
177 build_cachex("chat_message_id_idempotency_key",
178 expiration: chat_message_id_idempotency_key_expiration(),
179 limit: 500_000
180 )
181 ]
182 end
183
184 defp emoji_packs_expiration,
185 do: expiration(default: :timer.seconds(5 * 60), interval: :timer.seconds(60))
186
187 defp idempotency_expiration,
188 do: expiration(default: :timer.seconds(6 * 60 * 60), interval: :timer.seconds(60))
189
190 defp chat_message_id_idempotency_key_expiration,
191 do: expiration(default: :timer.minutes(2), interval: :timer.seconds(60))
192
193 defp seconds_valid_interval,
194 do: :timer.seconds(Config.get!([Pleroma.Captcha, :seconds_valid]))
195
196 @spec build_cachex(String.t(), keyword()) :: map()
197 def build_cachex(type, opts),
198 do: %{
199 id: String.to_atom("cachex_" <> type),
200 start: {Cachex, :start_link, [String.to_atom(type <> "_cache"), opts]},
201 type: :worker
202 }
203
204 defp shout_enabled?, do: Config.get([:shout, :enabled])
205
206 defp dont_run_in_test(env) when env in [:test, :benchmark], do: []
207
208 defp dont_run_in_test(_) do
209 [
210 {Registry,
211 [
212 name: Pleroma.Web.Streamer.registry(),
213 keys: :duplicate,
214 partitions: System.schedulers_online()
215 ]}
216 ] ++ background_migrators()
217 end
218
219 defp background_migrators do
220 [
221 Pleroma.Migrators.HashtagsTableMigrator
222 ]
223 end
224
225 defp shout_child(true) do
226 [
227 Pleroma.Web.ShoutChannel.ShoutChannelState,
228 {Phoenix.PubSub, [name: Pleroma.PubSub, adapter: Phoenix.PubSub.PG2]}
229 ]
230 end
231
232 defp shout_child(_), do: []
233
234 defp task_children(:test) do
235 [
236 %{
237 id: :web_push_init,
238 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
239 restart: :temporary
240 }
241 ]
242 end
243
244 defp task_children(_) do
245 [
246 %{
247 id: :web_push_init,
248 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
249 restart: :temporary
250 },
251 %{
252 id: :internal_fetch_init,
253 start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
254 restart: :temporary
255 }
256 ]
257 end
258
259 def elasticsearch_children do
260 config = Config.get([Pleroma.Search, :module])
261
262 if config == Pleroma.Search.Elasticsearch do
263 [Pleroma.Search.Elasticsearch.Cluster]
264 else
265 []
266 end
267 end
268
269 @spec limiters_setup() :: :ok
270 def limiters_setup do
271 config = Config.get(ConcurrentLimiter, [])
272
273 [
274 Pleroma.Web.RichMedia.Helpers,
275 Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy,
276 Pleroma.Search
277 ]
278 |> Enum.each(fn module ->
279 mod_config = Keyword.get(config, module, [])
280
281 max_running = Keyword.get(mod_config, :max_running, 5)
282 max_waiting = Keyword.get(mod_config, :max_waiting, 5)
283
284 ConcurrentLimiter.new(module, max_running, max_waiting)
285 end)
286 end
287
288 defp http_children do
289 config =
290 [:http, :adapter]
291 |> Config.get([])
292 |> Keyword.put(:name, MyFinch)
293
294 [{Finch, config}]
295 end
296 end