Use same context for quote posts as the post that's being quoted (#379)
[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 load_custom_modules()
57 Pleroma.Docs.JSON.compile()
58 limiters_setup()
59
60 # Define workers and child supervisors to be supervised
61 children =
62 [
63 Pleroma.Repo,
64 Config.TransferTask,
65 Pleroma.Emoji,
66 Pleroma.Web.Plugs.RateLimiter.Supervisor,
67 {Task.Supervisor, name: Pleroma.TaskSupervisor}
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 Pleroma.Web.Telemetry
78 ] ++
79 elasticsearch_children() ++
80 task_children(@mix_env) ++
81 dont_run_in_test(@mix_env)
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
97 with {:ok, data} <- Supervisor.start_link(children, opts) do
98 set_postgres_server_version()
99 {:ok, data}
100 else
101 e ->
102 Logger.error("Failed to start!")
103 Logger.error("#{inspect(e)}")
104 e
105 end
106 end
107
108 defp set_postgres_server_version do
109 version =
110 with %{rows: [[version]]} <- Ecto.Adapters.SQL.query!(Pleroma.Repo, "show server_version"),
111 {num, _} <- Float.parse(version) do
112 num
113 else
114 e ->
115 Logger.warn(
116 "Could not get the postgres version: #{inspect(e)}.\nSetting the default value of 9.6"
117 )
118
119 9.6
120 end
121
122 :persistent_term.put({Pleroma.Repo, :postgres_version}, version)
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 @mix_env != :test 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("banned_urls", default_ttl: :timer.hours(24 * 30), limit: 5_000),
160 build_cachex("translations", default_ttl: :timer.hours(24 * 30), limit: 2500),
161 build_cachex("instances", default_ttl: :timer.hours(24), ttl_interval: 1000, limit: 2500),
162 build_cachex("request_signatures", default_ttl: :timer.hours(24 * 30), limit: 3000),
163 build_cachex("rel_me", default_ttl: :timer.hours(24 * 30), limit: 300)
164 ]
165 end
166
167 defp emoji_packs_expiration,
168 do: expiration(default: :timer.seconds(5 * 60), interval: :timer.seconds(60))
169
170 defp idempotency_expiration,
171 do: expiration(default: :timer.seconds(6 * 60 * 60), interval: :timer.seconds(60))
172
173 defp seconds_valid_interval,
174 do: :timer.seconds(Config.get!([Pleroma.Captcha, :seconds_valid]))
175
176 @spec build_cachex(String.t(), keyword()) :: map()
177 def build_cachex(type, opts),
178 do: %{
179 id: String.to_atom("cachex_" <> type),
180 start: {Cachex, :start_link, [String.to_atom(type <> "_cache"), opts]},
181 type: :worker
182 }
183
184 defp dont_run_in_test(env) when env in [:test, :benchmark], do: []
185
186 defp dont_run_in_test(_) do
187 [
188 {Registry,
189 [
190 name: Pleroma.Web.Streamer.registry(),
191 keys: :duplicate,
192 partitions: System.schedulers_online()
193 ]}
194 ] ++ background_migrators()
195 end
196
197 defp background_migrators do
198 [
199 Pleroma.Migrators.HashtagsTableMigrator
200 ]
201 end
202
203 @spec task_children(atom()) :: [map()]
204
205 defp task_children(:test) do
206 [
207 %{
208 id: :web_push_init,
209 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
210 restart: :temporary
211 }
212 ]
213 end
214
215 defp task_children(_) do
216 [
217 %{
218 id: :web_push_init,
219 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
220 restart: :temporary
221 },
222 %{
223 id: :internal_fetch_init,
224 start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
225 restart: :temporary
226 }
227 ]
228 end
229
230 @spec elasticsearch_children :: [Pleroma.Search.Elasticsearch.Cluster]
231 def elasticsearch_children do
232 config = Config.get([Pleroma.Search, :module])
233
234 if config == Pleroma.Search.Elasticsearch do
235 [Pleroma.Search.Elasticsearch.Cluster]
236 else
237 []
238 end
239 end
240
241 @spec limiters_setup() :: :ok
242 def limiters_setup do
243 config = Config.get(ConcurrentLimiter, [])
244
245 [
246 Pleroma.Web.RichMedia.Helpers,
247 Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy,
248 Pleroma.Search
249 ]
250 |> Enum.each(fn module ->
251 mod_config = Keyword.get(config, module, [])
252
253 max_running = Keyword.get(mod_config, :max_running, 5)
254 max_waiting = Keyword.get(mod_config, :max_waiting, 5)
255
256 ConcurrentLimiter.new(module, max_running, max_waiting)
257 end)
258 end
259
260 defp http_children do
261 proxy_url = Config.get([:http, :proxy_url])
262 proxy = Pleroma.HTTP.AdapterHelper.format_proxy(proxy_url)
263 pool_size = Config.get([:http, :pool_size])
264
265 config =
266 [:http, :adapter]
267 |> Config.get([])
268 |> Pleroma.HTTP.AdapterHelper.add_pool_size(pool_size)
269 |> Pleroma.HTTP.AdapterHelper.maybe_add_proxy_pool(proxy)
270 |> Keyword.put(:name, MyFinch)
271
272 [{Finch, config}]
273 end
274 end