[#3213] `timeout` option for `HashtagsTableMigrator.count/_`.
[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.DataMigration
15 alias Pleroma.Hashtag
16 alias Pleroma.Object
17 alias Pleroma.Repo
18
19 defdelegate state(), to: State, as: :get
20 defdelegate put_stat(key, value), to: State, as: :put
21 defdelegate increment_stat(key, increment), to: State, as: :increment
22
23 defdelegate data_migration(), to: DataMigration, as: :populate_hashtags_table
24
25 @reg_name {:global, __MODULE__}
26
27 def whereis, do: GenServer.whereis(@reg_name)
28
29 def start_link(_) do
30 case whereis() do
31 nil ->
32 GenServer.start_link(__MODULE__, nil, name: @reg_name)
33
34 pid ->
35 {:ok, pid}
36 end
37 end
38
39 @impl true
40 def init(_) do
41 {:ok, nil, {:continue, :init_state}}
42 end
43
44 @impl true
45 def handle_continue(:init_state, _state) do
46 {:ok, _} = State.start_link(nil)
47
48 update_status(:init)
49
50 data_migration = data_migration()
51 manual_migrations = Config.get([:instance, :manual_data_migrations], [])
52
53 cond do
54 Config.get(:env) == :test ->
55 update_status(:noop)
56
57 is_nil(data_migration) ->
58 update_status(:halt, "Data migration does not exist.")
59
60 data_migration.state == :manual or data_migration.name in manual_migrations ->
61 update_status(:noop, "Data migration is in manual execution state.")
62
63 data_migration.state == :complete ->
64 handle_success(data_migration)
65
66 true ->
67 send(self(), :migrate_hashtags)
68 end
69
70 {:noreply, nil}
71 end
72
73 @impl true
74 def handle_info(:migrate_hashtags, state) do
75 data_migration = data_migration()
76
77 persistent_data = Map.take(data_migration.data, ["max_processed_id"])
78
79 {:ok, data_migration} =
80 DataMigration.update(data_migration, %{state: :running, data: persistent_data})
81
82 update_status(:running)
83
84 Logger.info("Starting transferring object embedded hashtags to `hashtags` table...")
85
86 max_processed_id = data_migration.data["max_processed_id"] || 0
87
88 query()
89 |> where([object], object.id > ^max_processed_id)
90 |> Repo.chunk_stream(100, :batches, timeout: :infinity)
91 |> Stream.each(fn objects ->
92 object_ids = Enum.map(objects, & &1.id)
93
94 failed_ids =
95 objects
96 |> Enum.map(&transfer_object_hashtags(&1))
97 |> Enum.filter(&(elem(&1, 0) == :error))
98 |> Enum.map(&elem(&1, 1))
99
100 for failed_id <- failed_ids do
101 _ =
102 Repo.query(
103 "INSERT INTO data_migration_failed_ids(data_migration_id, record_id) " <>
104 "VALUES ($1, $2) ON CONFLICT DO NOTHING;",
105 [data_migration.id, failed_id]
106 )
107 end
108
109 _ =
110 Repo.query(
111 "DELETE FROM data_migration_failed_ids WHERE id = ANY($1)",
112 [object_ids -- failed_ids]
113 )
114
115 max_object_id = Enum.at(object_ids, -1)
116
117 put_stat(:max_processed_id, max_object_id)
118 increment_stat(:processed_count, length(object_ids))
119 increment_stat(:failed_count, length(failed_ids))
120
121 persist_stats(data_migration)
122
123 # A quick and dirty approach to controlling the load this background migration imposes
124 sleep_interval = Config.get([:populate_hashtags_table, :sleep_interval_ms], 0)
125 Process.sleep(sleep_interval)
126 end)
127 |> Stream.run()
128
129 with {:ok, %{rows: [[0]]}} <-
130 Repo.query(
131 "SELECT COUNT(record_id) FROM data_migration_failed_ids WHERE data_migration_id = $1;",
132 [data_migration.id]
133 ) do
134 _ = DataMigration.update_state(data_migration, :complete)
135
136 handle_success(data_migration)
137 else
138 _ ->
139 _ = DataMigration.update_state(data_migration, :failed)
140
141 update_status(:failed, "Please check data_migration_failed_ids records.")
142 end
143
144 {:noreply, state}
145 end
146
147 defp query do
148 # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
149 from(
150 object in Object,
151 left_join: hashtag in assoc(object, :hashtags),
152 where: is_nil(hashtag.id),
153 where:
154 fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
155 select: %{
156 id: object.id,
157 tag: fragment("(?)->'tag'", object.data)
158 }
159 )
160 end
161
162 defp transfer_object_hashtags(object) do
163 hashtags = Object.object_data_hashtags(%{"tag" => object.tag})
164
165 Repo.transaction(fn ->
166 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
167 for hashtag_record <- hashtag_records do
168 with {:ok, _} <-
169 Repo.query(
170 "insert into hashtags_objects(hashtag_id, object_id) values ($1, $2);",
171 [hashtag_record.id, object.id]
172 ) do
173 nil
174 else
175 {:error, e} ->
176 error =
177 "ERROR: could not link object #{object.id} and hashtag " <>
178 "#{hashtag_record.id}: #{inspect(e)}"
179
180 Logger.error(error)
181 Repo.rollback(object.id)
182 end
183 end
184
185 object.id
186 else
187 e ->
188 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
189 Logger.error(error)
190 Repo.rollback(object.id)
191 end
192 end)
193 end
194
195 def count(force \\ false, timeout \\ :infinity) do
196 stored_count = state()[:count]
197
198 if stored_count && !force do
199 stored_count
200 else
201 count = Repo.aggregate(query(), :count, :id, timeout: timeout)
202 put_stat(:count, count)
203 count
204 end
205 end
206
207 defp persist_stats(data_migration) do
208 runner_state = Map.drop(state(), [:status])
209 _ = DataMigration.update(data_migration, %{data: runner_state})
210 end
211
212 defp handle_success(data_migration) do
213 update_status(:complete)
214
215 cond do
216 data_migration.feature_lock ->
217 :noop
218
219 not is_nil(Config.improved_hashtag_timeline()) ->
220 :noop
221
222 true ->
223 Config.put(Config.improved_hashtag_timeline_path(), true)
224 :ok
225 end
226 end
227
228 def failed_objects_query do
229 from(o in Object)
230 |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
231 on: dmf.record_id == o.id
232 )
233 |> where([_o, dmf], dmf.data_migration_id == ^data_migration().id)
234 |> order_by([o], asc: o.id)
235 end
236
237 def force_continue do
238 send(whereis(), :migrate_hashtags)
239 end
240
241 def force_restart do
242 {:ok, _} = DataMigration.update(data_migration(), %{state: :pending, data: %{}})
243 force_continue()
244 end
245
246 defp update_status(status, message \\ nil) do
247 put_stat(:status, status)
248 put_stat(:message, message)
249 end
250 end