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 get_stat(key, value), to: State, as: :get_data_key
22 defdelegate put_stat(key, value), to: State, as: :put_data_key
23 defdelegate increment_stat(key, increment), to: State, as: :increment_data_key
25 @reg_name {:global, __MODULE__}
27 def whereis, do: GenServer.whereis(@reg_name)
32 GenServer.start_link(__MODULE__, nil, name: @reg_name)
41 {:ok, nil, {:continue, :init_state}}
45 def handle_continue(:init_state, _state) do
46 {:ok, _} = State.start_link(nil)
48 update_status(:pending)
50 data_migration = data_migration()
51 manual_migrations = Config.get([:instance, :manual_data_migrations], [])
54 Config.get(:env) == :test ->
57 is_nil(data_migration) ->
58 update_status(:failed, "Data migration does not exist.")
60 data_migration.state == :manual or data_migration.name in manual_migrations ->
61 update_status(:manual, "Data migration is in manual execution state.")
63 data_migration.state == :complete ->
64 on_complete(data_migration)
67 send(self(), :migrate_hashtags)
74 def handle_info(:migrate_hashtags, state) do
77 update_status(:running)
78 put_stat(:started_at, NaiveDateTime.utc_now())
80 %{id: data_migration_id} = data_migration()
81 max_processed_id = get_stat(:max_processed_id, 0)
83 Logger.info("Transferring embedded hashtags to `hashtags` (from oid: #{max_processed_id})...")
86 |> where([object], object.id > ^max_processed_id)
87 |> Repo.chunk_stream(100, :batches, timeout: :infinity)
88 |> Stream.each(fn objects ->
89 object_ids = Enum.map(objects, & &1.id)
93 |> Enum.map(&transfer_object_hashtags(&1))
94 |> Enum.filter(&(elem(&1, 0) == :error))
95 |> Enum.map(&elem(&1, 1))
97 for failed_id <- failed_ids do
100 "INSERT INTO data_migration_failed_ids(data_migration_id, record_id) " <>
101 "VALUES ($1, $2) ON CONFLICT DO NOTHING;",
102 [data_migration_id, failed_id]
108 "DELETE FROM data_migration_failed_ids " <>
109 "WHERE data_migration_id = $1 AND record_id = ANY($2)",
110 [data_migration_id, object_ids -- failed_ids]
113 max_object_id = Enum.at(object_ids, -1)
115 put_stat(:max_processed_id, max_object_id)
116 increment_stat(:processed_count, length(object_ids))
117 increment_stat(:failed_count, length(failed_ids))
118 put_stat(:records_per_second, records_per_second())
119 _ = State.persist_to_db()
121 # A quick and dirty approach to controlling the load this background migration imposes
122 sleep_interval = Config.get([:populate_hashtags_table, :sleep_interval_ms], 0)
123 Process.sleep(sleep_interval)
127 with 0 <- failures_count(data_migration_id) do
128 _ = delete_non_create_activities_hashtags()
132 update_status(:failed, "Please check data_migration_failed_ids records.")
138 defp records_per_second do
139 get_stat(:processed_count, 0) / Enum.max([running_time(), 1])
143 NaiveDateTime.diff(NaiveDateTime.utc_now(), get_stat(:started_at, NaiveDateTime.utc_now()))
146 @hashtags_objects_cleanup_query """
147 DELETE FROM hashtags_objects WHERE object_id IN
148 (SELECT DISTINCT objects.id FROM objects
149 JOIN hashtags_objects ON hashtags_objects.object_id = objects.id LEFT JOIN activities
150 ON COALESCE(activities.data->'object'->>'id', activities.data->>'object') =
151 (objects.data->>'id')
152 AND activities.data->>'type' = 'Create'
153 WHERE activities.id IS NULL);
156 @hashtags_cleanup_query """
157 DELETE FROM hashtags WHERE id IN
158 (SELECT hashtags.id FROM hashtags
159 LEFT OUTER JOIN hashtags_objects
160 ON hashtags_objects.hashtag_id = hashtags.id
161 WHERE hashtags_objects.hashtag_id IS NULL);
165 Deletes `hashtags_objects` for legacy objects not asoociated with Create activity.
166 Also deletes unreferenced `hashtags` records (might occur after deletion of `hashtags_objects`).
168 def delete_non_create_activities_hashtags do
169 {:ok, %{num_rows: hashtags_objects_count}} =
170 Repo.query(@hashtags_objects_cleanup_query, [], timeout: :infinity)
172 {:ok, %{num_rows: hashtags_count}} =
173 Repo.query(@hashtags_cleanup_query, [], timeout: :infinity)
175 {:ok, hashtags_objects_count, hashtags_count}
179 # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
180 # Note: not checking activity type, expecting remove_non_create_objects_hashtags/_ to clean up
184 fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
187 tag: fragment("(?)->'tag'", object.data)
190 |> join(:left, [o], hashtags_objects in fragment("SELECT object_id FROM hashtags_objects"),
191 on: hashtags_objects.object_id == o.id
193 |> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
196 defp transfer_object_hashtags(object) do
197 embedded_tags = if Map.has_key?(object, :tag), do: object.tag, else: object.data["tag"]
198 hashtags = Object.object_data_hashtags(%{"tag" => embedded_tags})
200 if Enum.any?(hashtags) do
201 transfer_object_hashtags(object, hashtags)
207 defp transfer_object_hashtags(object, hashtags) do
208 Repo.transaction(fn ->
209 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
210 maps = Enum.map(hashtag_records, &%{hashtag_id: &1.id, object_id: object.id})
211 expected_rows = length(hashtag_records)
214 "ERROR when inserting #{expected_rows} hashtags_objects for obj. #{object.id}"
217 with {^expected_rows, _} <- Repo.insert_all("hashtags_objects", maps) do
221 Logger.error("#{base_error}: #{inspect(e)}")
222 Repo.rollback(object.id)
226 Logger.error("#{base_error}: #{inspect(e)}")
227 Repo.rollback(object.id)
231 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
233 Repo.rollback(object.id)
238 @doc "Approximate count for current iteration (including processed records count)"
239 def count(force \\ false, timeout \\ :infinity) do
240 stored_count = state()[:count]
242 if stored_count && !force do
245 processed_count = state()[:processed_count] || 0
246 max_processed_id = data_migration().data["max_processed_id"] || 0
247 query = where(query(), [object], object.id > ^max_processed_id)
249 count = Repo.aggregate(query, :count, :id, timeout: timeout) + processed_count
250 put_stat(:count, count)
255 defp on_complete(data_migration) do
257 data_migration.feature_lock ->
260 not is_nil(Config.get([:database, :improved_hashtag_timeline])) ->
264 Config.put([:database, :improved_hashtag_timeline], true)
269 def failed_objects_query do
271 |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
272 on: dmf.record_id == o.id
274 |> where([_o, dmf], dmf.data_migration_id == ^data_migration().id)
275 |> order_by([o], asc: o.id)
278 def failures_count(data_migration_id \\ nil) do
279 data_migration_id = data_migration_id || data_migration().id
281 with {:ok, %{rows: [[count]]}} <-
283 "SELECT COUNT(record_id) FROM data_migration_failed_ids WHERE data_migration_id = $1;",
291 data_migration = data_migration()
293 failed_objects_query()
294 |> Repo.chunk_stream(100, :one)
295 |> Stream.each(fn object ->
296 with {:ok, _} <- transfer_object_hashtags(object) do
299 "DELETE FROM data_migration_failed_ids " <>
300 "WHERE data_migration_id = $1 AND record_id = $2",
301 [data_migration.id, object.id]
308 def force_continue do
309 send(whereis(), :migrate_hashtags)
318 update_status(:complete)
319 _ = State.persist_to_db()
320 on_complete(data_migration())
323 defp update_status(status, message \\ nil) do
324 put_stat(:state, status)
325 put_stat(:message, message)