Use race-condition free mass follow.

This commit is contained in:
lain 2019-01-30 19:33:25 +01:00
parent 935e65e261
commit 47ec690c54
2 changed files with 15 additions and 8 deletions

View file

@ -309,20 +309,21 @@ def maybe_follow(%User{} = follower, %User{info: _info} = followed) do
@doc "A mass follow for local users. Ignores blocks and has no side effects" @doc "A mass follow for local users. Ignores blocks and has no side effects"
@spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()} @spec follow_all(User.t(), list(User.t())) :: {atom(), User.t()}
def follow_all(follower, followeds) do def follow_all(follower, followeds) do
following = followed_addresses = Enum.map(followeds, fn %{follower_address: fa} -> fa end)
(follower.following ++ Enum.map(followeds, fn %{follower_address: fa} -> fa end))
|> Enum.uniq()
{:ok, follower} = q =
follower from(u in User,
|> follow_changeset(%{following: following}) where: u.id == ^follower.id,
|> update_and_set_cache update: [set: [following: fragment("array_cat(?, ?)", u.following, ^followed_addresses)]]
)
{1, [follower]} = Repo.update_all(q, [], returning: true)
Enum.each(followeds, fn followed -> Enum.each(followeds, fn followed ->
update_follower_count(followed) update_follower_count(followed)
end) end)
{:ok, follower} set_cache(follower)
end end
def follow(%User{} = follower, %User{info: info} = followed) do def follow(%User{} = follower, %User{info: info} = followed) do

View file

@ -50,13 +50,19 @@ test "ap_followers returns the followers collection for the user" do
test "follow_all follows mutliple users" do test "follow_all follows mutliple users" do
user = insert(:user) user = insert(:user)
followed_zero = insert(:user)
followed_one = insert(:user) followed_one = insert(:user)
followed_two = insert(:user) followed_two = insert(:user)
not_followed = insert(:user)
{:ok, user} = User.follow(user, followed_zero)
{:ok, user} = User.follow_all(user, [followed_one, followed_two]) {:ok, user} = User.follow_all(user, [followed_one, followed_two])
assert User.following?(user, followed_one) assert User.following?(user, followed_one)
assert User.following?(user, followed_two) assert User.following?(user, followed_two)
assert User.following?(user, followed_zero)
refute User.following?(user, not_followed)
end end
test "follow takes a user and another user" do test "follow takes a user and another user" do