Merge remote-tracking branch 'remotes/origin/develop' into feature/object-hashtags...
[akkoma] / lib / pleroma / migrators / hashtags_table_migrator.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.Migrators.HashtagsTableMigrator do
6 use GenServer
7
8 require Logger
9
10 import Ecto.Query
11
12 alias __MODULE__.State
13 alias Pleroma.Config
14 alias Pleroma.Hashtag
15 alias Pleroma.Object
16 alias Pleroma.Repo
17
18 defdelegate data_migration(), to: Pleroma.DataMigration, as: :populate_hashtags_table
19 defdelegate data_migration_id(), to: State
20
21 defdelegate state(), to: State
22 defdelegate persist_state(), to: State, as: :persist_to_db
23 defdelegate get_stat(key, value \\ nil), to: State, as: :get_data_key
24 defdelegate put_stat(key, value), to: State, as: :put_data_key
25 defdelegate increment_stat(key, increment), to: State, as: :increment_data_key
26
27 @feature_config_path [:features, :improved_hashtag_timeline]
28 @reg_name {:global, __MODULE__}
29
30 def whereis, do: GenServer.whereis(@reg_name)
31
32 def feature_state, do: Config.get(@feature_config_path)
33
34 def start_link(_) do
35 case whereis() do
36 nil ->
37 GenServer.start_link(__MODULE__, nil, name: @reg_name)
38
39 pid ->
40 {:ok, pid}
41 end
42 end
43
44 @impl true
45 def init(_) do
46 {:ok, nil, {:continue, :init_state}}
47 end
48
49 @impl true
50 def handle_continue(:init_state, _state) do
51 {:ok, _} = State.start_link(nil)
52
53 data_migration = data_migration()
54 manual_migrations = Config.get([:instance, :manual_data_migrations], [])
55
56 cond do
57 Config.get(:env) == :test ->
58 update_status(:noop)
59
60 is_nil(data_migration) ->
61 message = "Data migration does not exist."
62 update_status(:failed, message)
63 Logger.error("#{__MODULE__}: #{message}")
64
65 data_migration.state == :manual or data_migration.name in manual_migrations ->
66 message = "Data migration is in manual execution or manual fix mode."
67 update_status(:manual, message)
68 Logger.warn("#{__MODULE__}: #{message}")
69
70 data_migration.state == :complete ->
71 on_complete(data_migration)
72
73 true ->
74 send(self(), :migrate_hashtags)
75 end
76
77 {:noreply, nil}
78 end
79
80 @impl true
81 def handle_info(:migrate_hashtags, state) do
82 State.reinit()
83
84 update_status(:running)
85 put_stat(:iteration_processed_count, 0)
86 put_stat(:started_at, NaiveDateTime.utc_now())
87
88 data_migration_id = data_migration_id()
89 max_processed_id = get_stat(:max_processed_id, 0)
90
91 Logger.info("Transferring embedded hashtags to `hashtags` (from oid: #{max_processed_id})...")
92
93 query()
94 |> where([object], object.id > ^max_processed_id)
95 |> Repo.chunk_stream(100, :batches, timeout: :infinity)
96 |> Stream.each(fn objects ->
97 object_ids = Enum.map(objects, & &1.id)
98
99 results = Enum.map(objects, &transfer_object_hashtags(&1))
100
101 failed_ids =
102 results
103 |> Enum.filter(&(elem(&1, 0) == :error))
104 |> Enum.map(&elem(&1, 1))
105
106 # Count of objects with hashtags (`{:noop, id}` is returned for objects having other AS2 tags)
107 chunk_affected_count =
108 results
109 |> Enum.filter(&(elem(&1, 0) == :ok))
110 |> length()
111
112 for failed_id <- failed_ids do
113 _ =
114 Repo.query(
115 "INSERT INTO data_migration_failed_ids(data_migration_id, record_id) " <>
116 "VALUES ($1, $2) ON CONFLICT DO NOTHING;",
117 [data_migration_id, failed_id]
118 )
119 end
120
121 _ =
122 Repo.query(
123 "DELETE FROM data_migration_failed_ids " <>
124 "WHERE data_migration_id = $1 AND record_id = ANY($2)",
125 [data_migration_id, object_ids -- failed_ids]
126 )
127
128 max_object_id = Enum.at(object_ids, -1)
129
130 put_stat(:max_processed_id, max_object_id)
131 increment_stat(:iteration_processed_count, length(object_ids))
132 increment_stat(:processed_count, length(object_ids))
133 increment_stat(:failed_count, length(failed_ids))
134 increment_stat(:affected_count, chunk_affected_count)
135 put_stat(:records_per_second, records_per_second())
136 persist_state()
137
138 # A quick and dirty approach to controlling the load this background migration imposes
139 sleep_interval = Config.get([:populate_hashtags_table, :sleep_interval_ms], 0)
140 Process.sleep(sleep_interval)
141 end)
142 |> Stream.run()
143
144 fault_rate = fault_rate()
145 put_stat(:fault_rate, fault_rate)
146 fault_rate_allowance = Config.get([:populate_hashtags_table, :fault_rate_allowance], 0)
147
148 cond do
149 fault_rate == 0 ->
150 set_complete()
151
152 is_float(fault_rate) and fault_rate <= fault_rate_allowance ->
153 message = """
154 Done with fault rate of #{fault_rate} which doesn't exceed #{fault_rate_allowance}.
155 Putting data migration to manual fix mode. Check `retry_failed/0`.
156 """
157
158 Logger.warn("#{__MODULE__}: #{message}")
159 update_status(:manual, message)
160 on_complete(data_migration())
161
162 true ->
163 message = "Too many failures. Check data_migration_failed_ids records / `retry_failed/0`."
164 Logger.error("#{__MODULE__}: #{message}")
165 update_status(:failed, message)
166 end
167
168 persist_state()
169 {:noreply, state}
170 end
171
172 def fault_rate do
173 with failures_count when is_integer(failures_count) <- failures_count() do
174 failures_count / Enum.max([get_stat(:affected_count, 0), 1])
175 else
176 _ -> :error
177 end
178 end
179
180 defp records_per_second do
181 get_stat(:iteration_processed_count, 0) / Enum.max([running_time(), 1])
182 end
183
184 defp running_time do
185 NaiveDateTime.diff(NaiveDateTime.utc_now(), get_stat(:started_at, NaiveDateTime.utc_now()))
186 end
187
188 @hashtags_objects_cleanup_query """
189 DELETE FROM hashtags_objects WHERE object_id IN
190 (SELECT DISTINCT objects.id FROM objects
191 JOIN hashtags_objects ON hashtags_objects.object_id = objects.id LEFT JOIN activities
192 ON COALESCE(activities.data->'object'->>'id', activities.data->>'object') =
193 (objects.data->>'id')
194 AND activities.data->>'type' = 'Create'
195 WHERE activities.id IS NULL);
196 """
197
198 @hashtags_cleanup_query """
199 DELETE FROM hashtags WHERE id IN
200 (SELECT hashtags.id FROM hashtags
201 LEFT OUTER JOIN hashtags_objects
202 ON hashtags_objects.hashtag_id = hashtags.id
203 WHERE hashtags_objects.hashtag_id IS NULL);
204 """
205
206 @doc """
207 Deletes `hashtags_objects` for legacy objects not asoociated with Create activity.
208 Also deletes unreferenced `hashtags` records (might occur after deletion of `hashtags_objects`).
209 """
210 def delete_non_create_activities_hashtags do
211 {:ok, %{num_rows: hashtags_objects_count}} =
212 Repo.query(@hashtags_objects_cleanup_query, [], timeout: :infinity)
213
214 {:ok, %{num_rows: hashtags_count}} =
215 Repo.query(@hashtags_cleanup_query, [], timeout: :infinity)
216
217 {:ok, hashtags_objects_count, hashtags_count}
218 end
219
220 defp query do
221 # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
222 # Note: not checking activity type, expecting remove_non_create_objects_hashtags/_ to clean up
223 from(
224 object in Object,
225 where:
226 fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
227 select: %{
228 id: object.id,
229 tag: fragment("(?)->'tag'", object.data)
230 }
231 )
232 |> join(:left, [o], hashtags_objects in fragment("SELECT object_id FROM hashtags_objects"),
233 on: hashtags_objects.object_id == o.id
234 )
235 |> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
236 end
237
238 @spec transfer_object_hashtags(Map.t()) :: {:noop | :ok | :error, integer()}
239 defp transfer_object_hashtags(object) do
240 embedded_tags = if Map.has_key?(object, :tag), do: object.tag, else: object.data["tag"]
241 hashtags = Object.object_data_hashtags(%{"tag" => embedded_tags})
242
243 if Enum.any?(hashtags) do
244 transfer_object_hashtags(object, hashtags)
245 else
246 {:noop, object.id}
247 end
248 end
249
250 defp transfer_object_hashtags(object, hashtags) do
251 Repo.transaction(fn ->
252 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
253 maps = Enum.map(hashtag_records, &%{hashtag_id: &1.id, object_id: object.id})
254 base_error = "ERROR when inserting hashtags_objects for object with id #{object.id}"
255
256 try do
257 with {rows_count, _} when is_integer(rows_count) <-
258 Repo.insert_all("hashtags_objects", maps, on_conflict: :nothing) do
259 object.id
260 else
261 e ->
262 Logger.error("#{base_error}: #{inspect(e)}")
263 Repo.rollback(object.id)
264 end
265 rescue
266 e ->
267 Logger.error("#{base_error}: #{inspect(e)}")
268 Repo.rollback(object.id)
269 end
270 else
271 e ->
272 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
273 Logger.error(error)
274 Repo.rollback(object.id)
275 end
276 end)
277 end
278
279 @doc "Approximate count for current iteration (including processed records count)"
280 def count(force \\ false, timeout \\ :infinity) do
281 stored_count = get_stat(:count)
282
283 if stored_count && !force do
284 stored_count
285 else
286 processed_count = get_stat(:processed_count, 0)
287 max_processed_id = get_stat(:max_processed_id, 0)
288 query = where(query(), [object], object.id > ^max_processed_id)
289
290 count = Repo.aggregate(query, :count, :id, timeout: timeout) + processed_count
291 put_stat(:count, count)
292 persist_state()
293
294 count
295 end
296 end
297
298 defp on_complete(data_migration) do
299 if data_migration.feature_lock || feature_state() == :disabled do
300 Logger.warn("#{__MODULE__}: migration complete but feature is locked; consider enabling.")
301 :noop
302 else
303 Config.put(@feature_config_path, :enabled)
304 :ok
305 end
306 end
307
308 def failed_objects_query do
309 from(o in Object)
310 |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
311 on: dmf.record_id == o.id
312 )
313 |> where([_o, dmf], dmf.data_migration_id == ^data_migration_id())
314 |> order_by([o], asc: o.id)
315 end
316
317 def failures_count do
318 with {:ok, %{rows: [[count]]}} <-
319 Repo.query(
320 "SELECT COUNT(record_id) FROM data_migration_failed_ids WHERE data_migration_id = $1;",
321 [data_migration_id()]
322 ) do
323 count
324 end
325 end
326
327 def retry_failed do
328 data_migration_id = data_migration_id()
329
330 failed_objects_query()
331 |> Repo.chunk_stream(100, :one)
332 |> Stream.each(fn object ->
333 with {res, _} when res != :error <- transfer_object_hashtags(object) do
334 _ =
335 Repo.query(
336 "DELETE FROM data_migration_failed_ids " <>
337 "WHERE data_migration_id = $1 AND record_id = $2",
338 [data_migration_id, object.id]
339 )
340 end
341 end)
342 |> Stream.run()
343
344 put_stat(:failed_count, failures_count())
345 persist_state()
346
347 force_continue()
348 end
349
350 def force_continue do
351 send(whereis(), :migrate_hashtags)
352 end
353
354 def force_restart do
355 :ok = State.reset()
356 force_continue()
357 end
358
359 def set_complete do
360 update_status(:complete)
361 persist_state()
362 on_complete(data_migration())
363 end
364
365 defp update_status(status, message \\ nil) do
366 put_stat(:state, status)
367 put_stat(:message, message)
368 end
369 end