logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

hashtags_table_migrator.ex (7059B)


  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. defmodule Pleroma.Migrators.HashtagsTableMigrator do
  5. defmodule State do
  6. use Pleroma.Migrators.Support.BaseMigratorState
  7. @impl Pleroma.Migrators.Support.BaseMigratorState
  8. defdelegate data_migration(), to: Pleroma.DataMigration, as: :populate_hashtags_table
  9. end
  10. use Pleroma.Migrators.Support.BaseMigrator
  11. alias Pleroma.Hashtag
  12. alias Pleroma.Migrators.Support.BaseMigrator
  13. alias Pleroma.Object
  14. @impl BaseMigrator
  15. def feature_config_path, do: [:features, :improved_hashtag_timeline]
  16. @impl BaseMigrator
  17. def fault_rate_allowance, do: Config.get([:populate_hashtags_table, :fault_rate_allowance], 0)
  18. @impl BaseMigrator
  19. def perform do
  20. data_migration_id = data_migration_id()
  21. max_processed_id = get_stat(:max_processed_id, 0)
  22. Logger.info("Transferring embedded hashtags to `hashtags` (from oid: #{max_processed_id})...")
  23. query()
  24. |> where([object], object.id > ^max_processed_id)
  25. |> Repo.chunk_stream(100, :batches, timeout: :infinity)
  26. |> Stream.each(fn objects ->
  27. object_ids = Enum.map(objects, & &1.id)
  28. results = Enum.map(objects, &transfer_object_hashtags(&1))
  29. failed_ids =
  30. results
  31. |> Enum.filter(&(elem(&1, 0) == :error))
  32. |> Enum.map(&elem(&1, 1))
  33. # Count of objects with hashtags: `{:noop, id}` is returned for objects having other AS2 tags
  34. chunk_affected_count =
  35. results
  36. |> Enum.filter(&(elem(&1, 0) == :ok))
  37. |> length()
  38. for failed_id <- failed_ids do
  39. _ =
  40. Repo.query(
  41. "INSERT INTO data_migration_failed_ids(data_migration_id, record_id) " <>
  42. "VALUES ($1, $2) ON CONFLICT DO NOTHING;",
  43. [data_migration_id, failed_id]
  44. )
  45. end
  46. _ =
  47. Repo.query(
  48. "DELETE FROM data_migration_failed_ids " <>
  49. "WHERE data_migration_id = $1 AND record_id = ANY($2)",
  50. [data_migration_id, object_ids -- failed_ids]
  51. )
  52. max_object_id = Enum.at(object_ids, -1)
  53. put_stat(:max_processed_id, max_object_id)
  54. increment_stat(:iteration_processed_count, length(object_ids))
  55. increment_stat(:processed_count, length(object_ids))
  56. increment_stat(:failed_count, length(failed_ids))
  57. increment_stat(:affected_count, chunk_affected_count)
  58. put_stat(:records_per_second, records_per_second())
  59. persist_state()
  60. # A quick and dirty approach to controlling the load this background migration imposes
  61. sleep_interval = Config.get([:populate_hashtags_table, :sleep_interval_ms], 0)
  62. Process.sleep(sleep_interval)
  63. end)
  64. |> Stream.run()
  65. end
  66. @impl BaseMigrator
  67. def query do
  68. # Note: most objects have Mention-type AS2 tags and no hashtags (but we can't filter them out)
  69. # Note: not checking activity type, expecting remove_non_create_objects_hashtags/_ to clean up
  70. from(
  71. object in Object,
  72. where:
  73. fragment("(?)->'tag' IS NOT NULL AND (?)->'tag' != '[]'::jsonb", object.data, object.data),
  74. select: %{
  75. id: object.id,
  76. tag: fragment("(?)->'tag'", object.data)
  77. }
  78. )
  79. |> join(:left, [o], hashtags_objects in fragment("SELECT object_id FROM hashtags_objects"),
  80. on: hashtags_objects.object_id == o.id
  81. )
  82. |> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
  83. end
  84. @spec transfer_object_hashtags(map()) :: {:noop | :ok | :error, integer()}
  85. defp transfer_object_hashtags(object) do
  86. embedded_tags = if Map.has_key?(object, :tag), do: object.tag, else: object.data["tag"]
  87. hashtags = Object.object_data_hashtags(%{"tag" => embedded_tags})
  88. if Enum.any?(hashtags) do
  89. transfer_object_hashtags(object, hashtags)
  90. else
  91. {:noop, object.id}
  92. end
  93. end
  94. defp transfer_object_hashtags(object, hashtags) do
  95. Repo.transaction(fn ->
  96. with {:ok, hashtag_records} <- Hashtag.get_or_create_by_names(hashtags) do
  97. maps = Enum.map(hashtag_records, &%{hashtag_id: &1.id, object_id: object.id})
  98. base_error = "ERROR when inserting hashtags_objects for object with id #{object.id}"
  99. try do
  100. with {rows_count, _} when is_integer(rows_count) <-
  101. Repo.insert_all("hashtags_objects", maps, on_conflict: :nothing) do
  102. object.id
  103. else
  104. e ->
  105. Logger.error("#{base_error}: #{inspect(e)}")
  106. Repo.rollback(object.id)
  107. end
  108. rescue
  109. e ->
  110. Logger.error("#{base_error}: #{inspect(e)}")
  111. Repo.rollback(object.id)
  112. end
  113. else
  114. e ->
  115. error = "ERROR: could not create hashtags for object #{object.id}: #{inspect(e)}"
  116. Logger.error(error)
  117. Repo.rollback(object.id)
  118. end
  119. end)
  120. end
  121. @impl BaseMigrator
  122. def retry_failed do
  123. data_migration_id = data_migration_id()
  124. failed_objects_query()
  125. |> Repo.chunk_stream(100, :one)
  126. |> Stream.each(fn object ->
  127. with {res, _} when res != :error <- transfer_object_hashtags(object) do
  128. _ =
  129. Repo.query(
  130. "DELETE FROM data_migration_failed_ids " <>
  131. "WHERE data_migration_id = $1 AND record_id = $2",
  132. [data_migration_id, object.id]
  133. )
  134. end
  135. end)
  136. |> Stream.run()
  137. put_stat(:failed_count, failures_count())
  138. persist_state()
  139. force_continue()
  140. end
  141. defp failed_objects_query do
  142. from(o in Object)
  143. |> join(:inner, [o], dmf in fragment("SELECT * FROM data_migration_failed_ids"),
  144. on: dmf.record_id == o.id
  145. )
  146. |> where([_o, dmf], dmf.data_migration_id == ^data_migration_id())
  147. |> order_by([o], asc: o.id)
  148. end
  149. @doc """
  150. Service func to delete `hashtags_objects` for legacy objects not associated with Create activity.
  151. Also deletes unreferenced `hashtags` records (might occur after deletion of `hashtags_objects`).
  152. """
  153. def delete_non_create_activities_hashtags do
  154. hashtags_objects_cleanup_query = """
  155. DELETE FROM hashtags_objects WHERE object_id IN
  156. (SELECT DISTINCT objects.id FROM objects
  157. JOIN hashtags_objects ON hashtags_objects.object_id = objects.id LEFT JOIN activities
  158. ON associated_object_id(activities) =
  159. (objects.data->>'id')
  160. AND activities.data->>'type' = 'Create'
  161. WHERE activities.id IS NULL);
  162. """
  163. hashtags_cleanup_query = """
  164. DELETE FROM hashtags WHERE id IN
  165. (SELECT hashtags.id FROM hashtags
  166. LEFT OUTER JOIN hashtags_objects
  167. ON hashtags_objects.hashtag_id = hashtags.id
  168. WHERE hashtags_objects.hashtag_id IS NULL);
  169. """
  170. {:ok, %{num_rows: hashtags_objects_count}} =
  171. Repo.query(hashtags_objects_cleanup_query, [], timeout: :infinity)
  172. {:ok, %{num_rows: hashtags_count}} =
  173. Repo.query(hashtags_cleanup_query, [], timeout: :infinity)
  174. {:ok, hashtags_objects_count, hashtags_count}
  175. end
  176. end