move to 2.5.5
[anni] / lib / pleroma / migrators / hashtags_table_migrator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Migrators.HashtagsTableMigrator do
6   defmodule State do
7     use Pleroma.Migrators.Support.BaseMigratorState
8
9     @impl Pleroma.Migrators.Support.BaseMigratorState
10     defdelegate data_migration(), to: Pleroma.DataMigration, as: :populate_hashtags_table
11   end
12
13   use Pleroma.Migrators.Support.BaseMigrator
14
15   alias Pleroma.Hashtag
16   alias Pleroma.Migrators.Support.BaseMigrator
17   alias Pleroma.Object
18
19   @impl BaseMigrator
20   def feature_config_path, do: [:features, :improved_hashtag_timeline]
21
22   @impl BaseMigrator
23   def fault_rate_allowance, do: Config.get([:populate_hashtags_table, :fault_rate_allowance], 0)
24
25   @impl BaseMigrator
26   def perform do
27     data_migration_id = data_migration_id()
28     max_processed_id = get_stat(:max_processed_id, 0)
29
30     Logger.info("Transferring embedded hashtags to `hashtags` (from oid: #{max_processed_id})...")
31
32     query()
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)
37
38       results = Enum.map(objects, &transfer_object_hashtags(&1))
39
40       failed_ids =
41         results
42         |> Enum.filter(&(elem(&1, 0) == :error))
43         |> Enum.map(&elem(&1, 1))
44
45       # Count of objects with hashtags: `{:noop, id}` is returned for objects having other AS2 tags
46       chunk_affected_count =
47         results
48         |> Enum.filter(&(elem(&1, 0) == :ok))
49         |> length()
50
51       for failed_id <- failed_ids do
52         _ =
53           Repo.query(
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]
57           )
58       end
59
60       _ =
61         Repo.query(
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]
65         )
66
67       max_object_id = Enum.at(object_ids, -1)
68
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())
75       persist_state()
76
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)
80     end)
81     |> Stream.run()
82   end
83
84   @impl BaseMigrator
85   def query do
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
88     from(
89       object in Object,
90       where:
91         fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
92       select: %{
93         id: object.id,
94         tag: fragment("(?)->'tag'", object.data)
95       }
96     )
97     |> join(:left, [o], hashtags_objects in fragment("SELECT object_id FROM hashtags_objects"),
98       on: hashtags_objects.object_id == o.id
99     )
100     |> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
101   end
102
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})
107
108     if Enum.any?(hashtags) do
109       transfer_object_hashtags(object, hashtags)
110     else
111       {:noop, object.id}
112     end
113   end
114
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}"
120
121         try do
122           with {rows_count, _} when is_integer(rows_count) <-
123                  Repo.insert_all("hashtags_objects", maps, on_conflict: :nothing) do
124             object.id
125           else
126             e ->
127               Logger.error("#{base_error}: #{inspect(e)}")
128               Repo.rollback(object.id)
129           end
130         rescue
131           e ->
132             Logger.error("#{base_error}: #{inspect(e)}")
133             Repo.rollback(object.id)
134         end
135       else
136         e ->
137           error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
138           Logger.error(error)
139           Repo.rollback(object.id)
140       end
141     end)
142   end
143
144   @impl BaseMigrator
145   def retry_failed do
146     data_migration_id = data_migration_id()
147
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
152         _ =
153           Repo.query(
154             "DELETE FROM data_migration_failed_ids " <>
155               "WHERE data_migration_id = $1 AND record_id = $2",
156             [data_migration_id, object.id]
157           )
158       end
159     end)
160     |> Stream.run()
161
162     put_stat(:failed_count, failures_count())
163     persist_state()
164
165     force_continue()
166   end
167
168   defp failed_objects_query do
169     from(o in Object)
170     |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
171       on: dmf.record_id == o.id
172     )
173     |> where([_o, dmf], dmf.data_migration_id == ^data_migration_id())
174     |> order_by([o], asc: o.id)
175   end
176
177   @doc """
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`).
180   """
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);
190     """
191
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);
198     """
199
200     {:ok, %{num_rows: hashtags_objects_count}} =
201       Repo.query(hashtags_objects_cleanup_query, [], timeout: :infinity)
202
203     {:ok, %{num_rows: hashtags_count}} =
204       Repo.query(hashtags_cleanup_query, [], timeout: :infinity)
205
206     {:ok, hashtags_objects_count, hashtags_count}
207   end
208 end