1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Migrators.HashtagsTableMigrator do
12 alias __MODULE__.State
18 defdelegate data_migration(), to: State
20 defdelegate state(), to: State
21 defdelegate persist_state(), to: State, as: :persist_to_db
22 defdelegate get_stat(key, value \\ nil), to: State, as: :get_data_key
23 defdelegate put_stat(key, value), to: State, as: :put_data_key
24 defdelegate increment_stat(key, increment), to: State, as: :increment_data_key
26 @reg_name {:global, __MODULE__}
28 def whereis, do: GenServer.whereis(@reg_name)
33 GenServer.start_link(__MODULE__, nil, name: @reg_name)
42 {:ok, nil, {:continue, :init_state}}
46 def handle_continue(:init_state, _state) do
47 {:ok, _} = State.start_link(nil)
49 update_status(:pending)
51 data_migration = data_migration()
52 manual_migrations = Config.get([:instance, :manual_data_migrations], [])
55 Config.get(:env) == :test ->
58 is_nil(data_migration) ->
59 update_status(:failed, "Data migration does not exist.")
61 data_migration.state == :manual or data_migration.name in manual_migrations ->
62 update_status(:manual, "Data migration is in manual execution state.")
64 data_migration.state == :complete ->
65 on_complete(data_migration)
68 send(self(), :migrate_hashtags)
75 def handle_info(:migrate_hashtags, state) do
78 update_status(:running)
79 put_stat(:started_at, NaiveDateTime.utc_now())
81 %{id: data_migration_id} = data_migration()
82 max_processed_id = get_stat(:max_processed_id, 0)
84 Logger.info("Transferring embedded hashtags to `hashtags` (from oid: #{max_processed_id})...")
87 |> where([object], object.id > ^max_processed_id)
88 |> Repo.chunk_stream(100, :batches, timeout: :infinity)
89 |> Stream.each(fn objects ->
90 object_ids = Enum.map(objects, & &1.id)
94 |> Enum.map(&transfer_object_hashtags(&1))
95 |> Enum.filter(&(elem(&1, 0) == :error))
96 |> Enum.map(&elem(&1, 1))
98 for failed_id <- failed_ids do
101 "INSERT INTO data_migration_failed_ids(data_migration_id, record_id) " <>
102 "VALUES ($1, $2) ON CONFLICT DO NOTHING;",
103 [data_migration_id, failed_id]
109 "DELETE FROM data_migration_failed_ids " <>
110 "WHERE data_migration_id = $1 AND record_id = ANY($2)",
111 [data_migration_id, object_ids -- failed_ids]
114 max_object_id = Enum.at(object_ids, -1)
116 put_stat(:max_processed_id, max_object_id)
117 increment_stat(:processed_count, length(object_ids))
118 increment_stat(:failed_count, length(failed_ids))
119 put_stat(:records_per_second, records_per_second())
122 # A quick and dirty approach to controlling the load this background migration imposes
123 sleep_interval = Config.get([:populate_hashtags_table, :sleep_interval_ms], 0)
124 Process.sleep(sleep_interval)
128 with 0 <- failures_count(data_migration_id) do
129 _ = delete_non_create_activities_hashtags()
133 update_status(:failed, "Please check data_migration_failed_ids records.")
139 defp records_per_second do
140 get_stat(:processed_count, 0) / Enum.max([running_time(), 1])
144 NaiveDateTime.diff(NaiveDateTime.utc_now(), get_stat(:started_at, NaiveDateTime.utc_now()))
147 @hashtags_objects_cleanup_query """
148 DELETE FROM hashtags_objects WHERE object_id IN
149 (SELECT DISTINCT objects.id FROM objects
150 JOIN hashtags_objects ON hashtags_objects.object_id = objects.id LEFT JOIN activities
151 ON COALESCE(activities.data->'object'->>'id', activities.data->>'object') =
152 (objects.data->>'id')
153 AND activities.data->>'type' = 'Create'
154 WHERE activities.id IS NULL);
157 @hashtags_cleanup_query """
158 DELETE FROM hashtags WHERE id IN
159 (SELECT hashtags.id FROM hashtags
160 LEFT OUTER JOIN hashtags_objects
161 ON hashtags_objects.hashtag_id = hashtags.id
162 WHERE hashtags_objects.hashtag_id IS NULL);
166 Deletes `hashtags_objects` for legacy objects not asoociated with Create activity.
167 Also deletes unreferenced `hashtags` records (might occur after deletion of `hashtags_objects`).
169 def delete_non_create_activities_hashtags do
170 {:ok, %{num_rows: hashtags_objects_count}} =
171 Repo.query(@hashtags_objects_cleanup_query, [], timeout: :infinity)
173 {:ok, %{num_rows: hashtags_count}} =
174 Repo.query(@hashtags_cleanup_query, [], timeout: :infinity)
176 {:ok, hashtags_objects_count, hashtags_count}
180 # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
181 # Note: not checking activity type, expecting remove_non_create_objects_hashtags/_ to clean up
185 fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
188 tag: fragment("(?)->'tag'", object.data)
191 |> join(:left, [o], hashtags_objects in fragment("SELECT object_id FROM hashtags_objects"),
192 on: hashtags_objects.object_id == o.id
194 |> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
197 defp transfer_object_hashtags(object) do
198 embedded_tags = if Map.has_key?(object, :tag), do: object.tag, else: object.data["tag"]
199 hashtags = Object.object_data_hashtags(%{"tag" => embedded_tags})
201 if Enum.any?(hashtags) do
202 transfer_object_hashtags(object, hashtags)
208 defp transfer_object_hashtags(object, hashtags) do
209 Repo.transaction(fn ->
210 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
211 maps = Enum.map(hashtag_records, &%{hashtag_id: &1.id, object_id: object.id})
212 expected_rows = length(hashtag_records)
215 "ERROR when inserting #{expected_rows} hashtags_objects for obj. #{object.id}"
218 with {^expected_rows, _} <- Repo.insert_all("hashtags_objects", maps) do
222 Logger.error("#{base_error}: #{inspect(e)}")
223 Repo.rollback(object.id)
227 Logger.error("#{base_error}: #{inspect(e)}")
228 Repo.rollback(object.id)
232 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
234 Repo.rollback(object.id)
239 @doc "Approximate count for current iteration (including processed records count)"
240 def count(force \\ false, timeout \\ :infinity) do
241 stored_count = get_stat(:count)
243 if stored_count && !force do
246 processed_count = get_stat(:processed_count, 0)
247 max_processed_id = get_stat(:max_processed_id, 0)
248 query = where(query(), [object], object.id > ^max_processed_id)
250 count = Repo.aggregate(query, :count, :id, timeout: timeout) + processed_count
251 put_stat(:count, count)
258 defp on_complete(data_migration) do
260 data_migration.feature_lock ->
263 not is_nil(Config.get([:database, :improved_hashtag_timeline])) ->
267 Config.put([:database, :improved_hashtag_timeline], true)
272 def failed_objects_query do
274 |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
275 on: dmf.record_id == o.id
277 |> where([_o, dmf], dmf.data_migration_id == ^data_migration().id)
278 |> order_by([o], asc: o.id)
281 def failures_count(data_migration_id \\ nil) do
282 data_migration_id = data_migration_id || data_migration().id
284 with {:ok, %{rows: [[count]]}} <-
286 "SELECT COUNT(record_id) FROM data_migration_failed_ids WHERE data_migration_id = $1;",
294 data_migration = data_migration()
296 failed_objects_query()
297 |> Repo.chunk_stream(100, :one)
298 |> Stream.each(fn object ->
299 with {:ok, _} <- transfer_object_hashtags(object) do
302 "DELETE FROM data_migration_failed_ids " <>
303 "WHERE data_migration_id = $1 AND record_id = $2",
304 [data_migration.id, object.id]
311 def force_continue do
312 send(whereis(), :migrate_hashtags)
321 update_status(:complete)
323 on_complete(data_migration())
326 defp update_status(status, message \\ nil) do
327 put_stat(:state, status)
328 put_stat(:message, message)