[#582] Optimized federation retirement by reducing the number of SQL calls
[akkoma] / lib / pleroma / web / federator / federator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Federator do
6 use GenServer
7 alias Pleroma.User
8 alias Pleroma.Activity
9 alias Pleroma.Web.{WebFinger, Websub, Salmon}
10 alias Pleroma.Web.Federator.RetryQueue
11 alias Pleroma.Web.ActivityPub.ActivityPub
12 alias Pleroma.Web.ActivityPub.Relay
13 alias Pleroma.Web.ActivityPub.Transmogrifier
14 alias Pleroma.Web.ActivityPub.Utils
15 alias Pleroma.Web.OStatus
16 require Logger
17
18 @websub Application.get_env(:pleroma, :websub)
19 @ostatus Application.get_env(:pleroma, :ostatus)
20
21 def init(args) do
22 {:ok, args}
23 end
24
25 def start_link do
26 spawn(fn ->
27 # 1 minute
28 Process.sleep(1000 * 60 * 1)
29 enqueue(:refresh_subscriptions, nil)
30 end)
31
32 GenServer.start_link(
33 __MODULE__,
34 %{
35 in: {:sets.new(), []},
36 out: {:sets.new(), []}
37 },
38 name: __MODULE__
39 )
40 end
41
42 def handle(:refresh_subscriptions, _) do
43 Logger.debug("Federator running refresh subscriptions")
44 Websub.refresh_subscriptions()
45
46 spawn(fn ->
47 # 6 hours
48 Process.sleep(1000 * 60 * 60 * 6)
49 enqueue(:refresh_subscriptions, nil)
50 end)
51 end
52
53 def handle(:request_subscription, websub) do
54 Logger.debug("Refreshing #{websub.topic}")
55
56 with {:ok, websub} <- Websub.request_subscription(websub) do
57 Logger.debug("Successfully refreshed #{websub.topic}")
58 else
59 _e -> Logger.debug("Couldn't refresh #{websub.topic}")
60 end
61 end
62
63 def handle(:publish, activity) do
64 Logger.debug(fn -> "Running publish for #{activity.data["id"]}" end)
65
66 with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
67 {:ok, actor} = WebFinger.ensure_keys_present(actor)
68
69 if ActivityPub.is_public?(activity) do
70 if OStatus.is_representable?(activity) do
71 Logger.info(fn -> "Sending #{activity.data["id"]} out via WebSub" end)
72 Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
73
74 Logger.info(fn -> "Sending #{activity.data["id"]} out via Salmon" end)
75 Pleroma.Web.Salmon.publish(actor, activity)
76 end
77
78 if Keyword.get(Application.get_env(:pleroma, :instance), :allow_relay) do
79 Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
80 Relay.publish(activity)
81 end
82 end
83
84 Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
85 Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
86 end
87 end
88
89 def handle(:verify_websub, websub) do
90 Logger.debug(fn ->
91 "Running WebSub verification for #{websub.id} (#{websub.topic}, #{websub.callback})"
92 end)
93
94 @websub.verify(websub)
95 end
96
97 def handle(:incoming_doc, doc) do
98 Logger.info("Got document, trying to parse")
99 @ostatus.handle_incoming(doc)
100 end
101
102 def handle(:incoming_ap_doc, params) do
103 Logger.info("Handling incoming AP activity")
104
105 params = Utils.normalize_params(params)
106
107 # NOTE: we use the actor ID to do the containment, this is fine because an
108 # actor shouldn't be acting on objects outside their own AP server.
109 with {:ok, _user} <- ap_enabled_actor(params["actor"]),
110 nil <- Activity.normalize(params["id"]),
111 :ok <- Transmogrifier.contain_origin_from_id(params["actor"], params),
112 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
113 {:ok, activity}
114 else
115 %Activity{} ->
116 Logger.info("Already had #{params["id"]}")
117 :error
118
119 _e ->
120 # Just drop those for now
121 Logger.info("Unhandled activity")
122 Logger.info(Poison.encode!(params, pretty: 2))
123 :error
124 end
125 end
126
127 def handle(:publish_single_salmon, params) do
128 Salmon.send_to_user(params)
129 end
130
131 def handle(:publish_single_ap, params) do
132 case ActivityPub.publish_one(params) do
133 {:ok, _} ->
134 :ok
135
136 {:error, _} ->
137 RetryQueue.enqueue(params, ActivityPub)
138 end
139 end
140
141 def handle(
142 :publish_single_websub,
143 %{xml: _xml, topic: _topic, callback: _callback, secret: _secret} = params
144 ) do
145 case Websub.publish_one(params) do
146 {:ok, _} ->
147 :ok
148
149 {:error, _} ->
150 RetryQueue.enqueue(params, Websub)
151 end
152 end
153
154 def handle(type, _) do
155 Logger.debug(fn -> "Unknown task: #{type}" end)
156 {:error, "Don't know what to do with this"}
157 end
158
159 if Mix.env() == :test do
160 def enqueue(type, payload, _priority \\ 1) do
161 if Pleroma.Config.get([:instance, :federating]) do
162 handle(type, payload)
163 end
164 end
165 else
166 def enqueue(type, payload, priority \\ 1) do
167 if Pleroma.Config.get([:instance, :federating]) do
168 GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
169 end
170 end
171 end
172
173 def maybe_start_job(running_jobs, queue) do
174 if :sets.size(running_jobs) < Pleroma.Config.get([__MODULE__, :max_jobs]) && queue != [] do
175 {{type, payload}, queue} = queue_pop(queue)
176 {:ok, pid} = Task.start(fn -> handle(type, payload) end)
177 mref = Process.monitor(pid)
178 {:sets.add_element(mref, running_jobs), queue}
179 else
180 {running_jobs, queue}
181 end
182 end
183
184 def handle_cast({:enqueue, type, payload, _priority}, state)
185 when type in [:incoming_doc, :incoming_ap_doc] do
186 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
187 i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
188 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
189 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
190 end
191
192 def handle_cast({:enqueue, type, payload, _priority}, state) do
193 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
194 o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
195 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
196 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
197 end
198
199 def handle_cast(m, state) do
200 IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
201 {:noreply, state}
202 end
203
204 def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
205 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
206 i_running_jobs = :sets.del_element(ref, i_running_jobs)
207 o_running_jobs = :sets.del_element(ref, o_running_jobs)
208 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
209 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
210
211 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
212 end
213
214 def enqueue_sorted(queue, element, priority) do
215 [%{item: element, priority: priority} | queue]
216 |> Enum.sort_by(fn %{priority: priority} -> priority end)
217 end
218
219 def queue_pop([%{item: element} | queue]) do
220 {element, queue}
221 end
222
223 def ap_enabled_actor(id) do
224 user = User.get_by_ap_id(id)
225
226 if User.ap_enabled?(user) do
227 {:ok, user}
228 else
229 ActivityPub.make_user_from_ap_id(id)
230 end
231 end
232 end