Better error handling for OstatusController.
[akkoma] / lib / pleroma / web / federator / federator.ex
1 defmodule Pleroma.Web.Federator do
2 use GenServer
3 alias Pleroma.User
4 alias Pleroma.Activity
5 alias Pleroma.Web.{WebFinger, Websub}
6 alias Pleroma.Web.ActivityPub.ActivityPub
7 alias Pleroma.Web.ActivityPub.Transmogrifier
8 alias Pleroma.Web.ActivityPub.Utils
9 require Logger
10
11 @websub Application.get_env(:pleroma, :websub)
12 @ostatus Application.get_env(:pleroma, :ostatus)
13 @httpoison Application.get_env(:pleroma, :httpoison)
14 @instance Application.get_env(:pleroma, :instance)
15 @federating Keyword.get(@instance, :federating)
16 @max_jobs 20
17
18 def init(args) do
19 {:ok, args}
20 end
21
22 def start_link do
23 spawn(fn ->
24 # 1 minute
25 Process.sleep(1000 * 60 * 1)
26 enqueue(:refresh_subscriptions, nil)
27 end)
28
29 GenServer.start_link(
30 __MODULE__,
31 %{
32 in: {:sets.new(), []},
33 out: {:sets.new(), []}
34 },
35 name: __MODULE__
36 )
37 end
38
39 def handle(:refresh_subscriptions, _) do
40 Logger.debug("Federator running refresh subscriptions")
41 Websub.refresh_subscriptions()
42
43 spawn(fn ->
44 # 6 hours
45 Process.sleep(1000 * 60 * 60 * 6)
46 enqueue(:refresh_subscriptions, nil)
47 end)
48 end
49
50 def handle(:request_subscription, websub) do
51 Logger.debug("Refreshing #{websub.topic}")
52
53 with {:ok, websub} <- Websub.request_subscription(websub) do
54 Logger.debug("Successfully refreshed #{websub.topic}")
55 else
56 _e -> Logger.debug("Couldn't refresh #{websub.topic}")
57 end
58 end
59
60 def handle(:publish, activity) do
61 Logger.debug(fn -> "Running publish for #{activity.data["id"]}" end)
62
63 with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
64 {:ok, actor} = WebFinger.ensure_keys_present(actor)
65
66 if ActivityPub.is_public?(activity) do
67 Logger.info(fn -> "Sending #{activity.data["id"]} out via WebSub" end)
68 Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
69
70 Logger.info(fn -> "Sending #{activity.data["id"]} out via Salmon" end)
71 Pleroma.Web.Salmon.publish(actor, activity)
72 end
73
74 Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
75 Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
76 end
77 end
78
79 def handle(:verify_websub, websub) do
80 Logger.debug(fn ->
81 "Running WebSub verification for #{websub.id} (#{websub.topic}, #{websub.callback})"
82 end)
83
84 @websub.verify(websub)
85 end
86
87 def handle(:incoming_doc, doc) do
88 Logger.info("Got document, trying to parse")
89 @ostatus.handle_incoming(doc)
90 end
91
92 def handle(:incoming_ap_doc, params) do
93 Logger.info("Handling incoming AP activity")
94
95 params = Utils.normalize_params(params)
96
97 with {:ok, _user} <- ap_enabled_actor(params["actor"]),
98 nil <- Activity.get_by_ap_id(params["id"]),
99 {:ok, _activity} <- Transmogrifier.handle_incoming(params) do
100 else
101 %Activity{} ->
102 Logger.info("Already had #{params["id"]}")
103
104 _e ->
105 # Just drop those for now
106 Logger.info("Unhandled activity")
107 Logger.info(Poison.encode!(params, pretty: 2))
108 end
109 end
110
111 def handle(:publish_single_ap, params) do
112 ActivityPub.publish_one(params)
113 end
114
115 def handle(:publish_single_websub, %{xml: xml, topic: topic, callback: callback, secret: secret}) do
116 signature = @websub.sign(secret || "", xml)
117 Logger.debug(fn -> "Pushing #{topic} to #{callback}" end)
118
119 with {:ok, %{status_code: code}} <-
120 @httpoison.post(
121 callback,
122 xml,
123 [
124 {"Content-Type", "application/atom+xml"},
125 {"X-Hub-Signature", "sha1=#{signature}"}
126 ],
127 timeout: 10000,
128 recv_timeout: 20000,
129 hackney: [pool: :default]
130 ) do
131 Logger.debug(fn -> "Pushed to #{callback}, code #{code}" end)
132 else
133 e ->
134 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(e)}" end)
135 end
136 end
137
138 def handle(type, _) do
139 Logger.debug(fn -> "Unknown task: #{type}" end)
140 {:error, "Don't know what to do with this"}
141 end
142
143 def enqueue(type, payload, priority \\ 1) do
144 if @federating do
145 if Mix.env() == :test do
146 handle(type, payload)
147 else
148 GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
149 end
150 end
151 end
152
153 def maybe_start_job(running_jobs, queue) do
154 if :sets.size(running_jobs) < @max_jobs && queue != [] do
155 {{type, payload}, queue} = queue_pop(queue)
156 {:ok, pid} = Task.start(fn -> handle(type, payload) end)
157 mref = Process.monitor(pid)
158 {:sets.add_element(mref, running_jobs), queue}
159 else
160 {running_jobs, queue}
161 end
162 end
163
164 def handle_cast({:enqueue, type, payload, _priority}, state)
165 when type in [:incoming_doc, :incoming_ap_doc] do
166 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
167 i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
168 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
169 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
170 end
171
172 def handle_cast({:enqueue, type, payload, _priority}, state) do
173 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
174 o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
175 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
176 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
177 end
178
179 def handle_cast(m, state) do
180 IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
181 {:noreply, state}
182 end
183
184 def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
185 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
186 i_running_jobs = :sets.del_element(ref, i_running_jobs)
187 o_running_jobs = :sets.del_element(ref, o_running_jobs)
188 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
189 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
190
191 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
192 end
193
194 def enqueue_sorted(queue, element, priority) do
195 [%{item: element, priority: priority} | queue]
196 |> Enum.sort_by(fn %{priority: priority} -> priority end)
197 end
198
199 def queue_pop([%{item: element} | queue]) do
200 {element, queue}
201 end
202
203 def ap_enabled_actor(id) do
204 user = User.get_by_ap_id(id)
205
206 if User.ap_enabled?(user) do
207 {:ok, user}
208 else
209 ActivityPub.make_user_from_ap_id(id)
210 end
211 end
212 end