1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Migrators.HashtagsTableMigrator do
7 use Pleroma.Migrators.Support.BaseMigratorState
9 @impl Pleroma.Migrators.Support.BaseMigratorState
10 defdelegate data_migration(), to: Pleroma.DataMigration, as: :populate_hashtags_table
13 use Pleroma.Migrators.Support.BaseMigrator
16 alias Pleroma.Migrators.Support.BaseMigrator
20 def feature_config_path, do: [:features, :improved_hashtag_timeline]
23 def fault_rate_allowance, do: Config.get([:populate_hashtags_table, :fault_rate_allowance], 0)
27 data_migration_id = data_migration_id()
28 max_processed_id = get_stat(:max_processed_id, 0)
30 Logger.info("Transferring embedded hashtags to `hashtags` (from oid: #{max_processed_id})...")
33 |> where([object], object.id > ^max_processed_id)
34 |> Repo.chunk_stream(100, :batches, timeout: :infinity)
35 |> Stream.each(fn objects ->
36 object_ids = Enum.map(objects, & &1.id)
38 results = Enum.map(objects, &transfer_object_hashtags(&1))
42 |> Enum.filter(&(elem(&1, 0) == :error))
43 |> Enum.map(&elem(&1, 1))
45 # Count of objects with hashtags: `{:noop, id}` is returned for objects having other AS2 tags
46 chunk_affected_count =
48 |> Enum.filter(&(elem(&1, 0) == :ok))
51 for failed_id <- failed_ids do
54 "INSERT INTO data_migration_failed_ids(data_migration_id, record_id) " <>
55 "VALUES ($1, $2) ON CONFLICT DO NOTHING;",
56 [data_migration_id, failed_id]
62 "DELETE FROM data_migration_failed_ids " <>
63 "WHERE data_migration_id = $1 AND record_id = ANY($2)",
64 [data_migration_id, object_ids -- failed_ids]
67 max_object_id = Enum.at(object_ids, -1)
69 put_stat(:max_processed_id, max_object_id)
70 increment_stat(:iteration_processed_count, length(object_ids))
71 increment_stat(:processed_count, length(object_ids))
72 increment_stat(:failed_count, length(failed_ids))
73 increment_stat(:affected_count, chunk_affected_count)
74 put_stat(:records_per_second, records_per_second())
77 # A quick and dirty approach to controlling the load this background migration imposes
78 sleep_interval = Config.get([:populate_hashtags_table, :sleep_interval_ms], 0)
79 Process.sleep(sleep_interval)
86 # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
87 # Note: not checking activity type, expecting remove_non_create_objects_hashtags/_ to clean up
91 fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
94 tag: fragment("(?)->'tag'", object.data)
97 |> join(:left, [o], hashtags_objects in fragment("SELECT object_id FROM hashtags_objects"),
98 on: hashtags_objects.object_id == o.id
100 |> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
103 @spec transfer_object_hashtags(Map.t()) :: {:noop | :ok | :error, integer()}
104 defp transfer_object_hashtags(object) do
105 embedded_tags = if Map.has_key?(object, :tag), do: object.tag, else: object.data["tag"]
106 hashtags = Object.object_data_hashtags(%{"tag" => embedded_tags})
108 if Enum.any?(hashtags) do
109 transfer_object_hashtags(object, hashtags)
115 defp transfer_object_hashtags(object, hashtags) do
116 Repo.transaction(fn ->
117 with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
118 maps = Enum.map(hashtag_records, &%{hashtag_id: &1.id, object_id: object.id})
119 base_error = "ERROR when inserting hashtags_objects for object with id #{object.id}"
122 with {rows_count, _} when is_integer(rows_count) <-
123 Repo.insert_all("hashtags_objects", maps, on_conflict: :nothing) do
127 Logger.error("#{base_error}: #{inspect(e)}")
128 Repo.rollback(object.id)
132 Logger.error("#{base_error}: #{inspect(e)}")
133 Repo.rollback(object.id)
137 error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
139 Repo.rollback(object.id)
146 data_migration_id = data_migration_id()
148 failed_objects_query()
149 |> Repo.chunk_stream(100, :one)
150 |> Stream.each(fn object ->
151 with {res, _} when res != :error <- transfer_object_hashtags(object) do
154 "DELETE FROM data_migration_failed_ids " <>
155 "WHERE data_migration_id = $1 AND record_id = $2",
156 [data_migration_id, object.id]
162 put_stat(:failed_count, failures_count())
168 defp failed_objects_query do
170 |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
171 on: dmf.record_id == o.id
173 |> where([_o, dmf], dmf.data_migration_id == ^data_migration_id())
174 |> order_by([o], asc: o.id)
178 Service func to delete `hashtags_objects` for legacy objects not associated with Create activity.
179 Also deletes unreferenced `hashtags` records (might occur after deletion of `hashtags_objects`).
181 def delete_non_create_activities_hashtags do
182 hashtags_objects_cleanup_query = """
183 DELETE FROM hashtags_objects WHERE object_id IN
184 (SELECT DISTINCT objects.id FROM objects
185 JOIN hashtags_objects ON hashtags_objects.object_id = objects.id LEFT JOIN activities
186 ON associated_object_id(activities) =
187 (objects.data->>'id')
188 AND activities.data->>'type' = 'Create'
189 WHERE activities.id IS NULL);
192 hashtags_cleanup_query = """
193 DELETE FROM hashtags WHERE id IN
194 (SELECT hashtags.id FROM hashtags
195 LEFT OUTER JOIN hashtags_objects
196 ON hashtags_objects.hashtag_id = hashtags.id
197 WHERE hashtags_objects.hashtag_id IS NULL);
200 {:ok, %{num_rows: hashtags_objects_count}} =
201 Repo.query(hashtags_objects_cleanup_query, [], timeout: :infinity)
203 {:ok, %{num_rows: hashtags_count}} =
204 Repo.query(hashtags_cleanup_query, [], timeout: :infinity)
206 {:ok, hashtags_objects_count, hashtags_count}