From 6455b967ec6cf2006e02486251f65e32137b54d4 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier" <contact@hacktivis.me>
Date: Thu, 12 Aug 2021 10:29:53 +0200
Subject: [PATCH] Activity.Search: fallback on status resolution on DB Timeout

---
 CHANGELOG.md                   |  3 +++
 lib/pleroma/activity/search.ex | 30 +++++++++++++++++-------------
 2 files changed, 20 insertions(+), 13 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 45a365505..421b6e043 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
 
 ### Removed
 
+## Unreleased-patch
+- Mastodon API: Activity Search fallbacks on status fetching after a DB Timeout/Error
+
 ## 2.4.0 - 2021-08-xx
 
 ### Changed
diff --git a/lib/pleroma/activity/search.ex b/lib/pleroma/activity/search.ex
index ed898ba4f..a5923519c 100644
--- a/lib/pleroma/activity/search.ex
+++ b/lib/pleroma/activity/search.ex
@@ -26,19 +26,23 @@ def search(user, search_query, options \\ []) do
         :plain
       end
 
-    Activity
-    |> Activity.with_preloaded_object()
-    |> Activity.restrict_deactivated_users()
-    |> restrict_public()
-    |> query_with(index_type, search_query, search_function)
-    |> maybe_restrict_local(user)
-    |> maybe_restrict_author(author)
-    |> maybe_restrict_blocked(user)
-    |> Pagination.fetch_paginated(
-      %{"offset" => offset, "limit" => limit, "skip_order" => index_type == :rum},
-      :offset
-    )
-    |> maybe_fetch(user, search_query)
+    try do
+      Activity
+      |> Activity.with_preloaded_object()
+      |> Activity.restrict_deactivated_users()
+      |> restrict_public()
+      |> query_with(index_type, search_query, search_function)
+      |> maybe_restrict_local(user)
+      |> maybe_restrict_author(author)
+      |> maybe_restrict_blocked(user)
+      |> Pagination.fetch_paginated(
+        %{"offset" => offset, "limit" => limit, "skip_order" => index_type == :rum},
+        :offset
+      )
+      |> maybe_fetch(user, search_query)
+    rescue
+      _ -> maybe_fetch([], user, search_query)
+    end
   end
 
   def maybe_restrict_author(query, %User{} = author) do