SideEffects: Run in transaction.
authorlain <lain@soykaf.club>
Wed, 22 Apr 2020 16:40:53 +0000 (18:40 +0200)
committerlain <lain@soykaf.club>
Wed, 22 Apr 2020 16:40:53 +0000 (18:40 +0200)
This fixes race conditions.

lib/pleroma/web/activity_pub/side_effects.ex
test/web/common_api/common_api_test.exs

index 6a8f1af960ffe34aadb35b287d2c0e6d38c9365e..a0f71fd889cace170e6fa109ddfb821f0e6b7ee7 100644 (file)
@@ -15,12 +15,15 @@ defmodule Pleroma.Web.ActivityPub.SideEffects do
   # - Add like to object
   # - Set up notification
   def handle(%{data: %{"type" => "Like"}} = object, meta) do
-    liked_object = Object.get_by_ap_id(object.data["object"])
-    Utils.add_like_to_object(object, liked_object)
+    Pleroma.Repo.transaction(fn ->
+      liked_object = Object.get_by_ap_id(object.data["object"])
+      Utils.add_like_to_object(object, liked_object)
 
-    Notification.create_notifications(object)
+      Notification.create_notifications(object)
 
-    {:ok, object, meta}
+      {:ok, object, meta}
+    end)
+    |> (fn {:ok, res} -> res end).()
   end
 
   # Nothing to do
index e130736ecec21cfe1f475892077bb2d4fabad547..68a29108a68457d61180f5ac925a4d117b59b545 100644 (file)
@@ -21,6 +21,33 @@ defmodule Pleroma.Web.CommonAPITest do
   setup do: clear_config([:instance, :limit])
   setup do: clear_config([:instance, :max_pinned_statuses])
 
+  test "favoriting race condition" do
+    user = insert(:user)
+    users_serial = insert_list(10, :user)
+    users = insert_list(10, :user)
+
+    {:ok, activity} = CommonAPI.post(user, %{"status" => "."})
+
+    users_serial
+    |> Enum.map(fn user ->
+      CommonAPI.favorite(user, activity.id)
+    end)
+
+    object = Object.get_by_ap_id(activity.data["object"])
+    assert object.data["like_count"] == 10
+
+    users
+    |> Enum.map(fn user ->
+      Task.async(fn ->
+        CommonAPI.favorite(user, activity.id)
+      end)
+    end)
+    |> Enum.map(&Task.await/1)
+
+    object = Object.get_by_ap_id(activity.data["object"])
+    assert object.data["like_count"] == 20
+  end
+
   test "when replying to a conversation / participation, it will set the correct context id even if no explicit reply_to is given" do
     user = insert(:user)
     {:ok, activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})