8000 fix(groups): coordinate departures with group and account closure by mwoods79 · Pull Request #772 · huddlz-hq/huddlz · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/huddlz/communities/group.ex 8000
Original file line number Diff line number Diff line change
Expand Up @@ -182,12 +182,14 @@ defmodule Huddlz.Communities.Group do
primary? true
require_atomic? false
change Huddlz.Communities.Group.Changes.HoldInOrder
change {Huddlz.Accounts.AccountLifecycleLock, participants: [:actor]}
change Huddlz.Communities.Group.Changes.NotifyArchived
end

destroy :archive do
require_atomic? false
change Huddlz.Communities.Group.Changes.LockLifecycle
change {Huddlz.Accounts.AccountLifecycleLock, participants: [:actor]}
change Huddlz.Communities.Group.Changes.NotifyArchived
end

Expand Down
8 changes: 8 additions & 0 deletions lib/huddlz/communities/group_lock.ex
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ defmodule Huddlz.Communities.GroupLock do
@doc "Reserve the group reference needed when an account leaves a joined group."
def for_departure(group_id), do: take(group_id, "FOR NO KEY UPDATE")

@doc "Hold the group for a membership's reminder, including when the group is archived."
def reserve_for_leave(changeset, _context) do
case take(changeset.data.group_id, "FOR KEY SHARE") do
nil -> Ash.Changeset.add_error(changeset, "This group is no longer available.")
%Group{} -> changeset
end
end

defp take(group_id, strength) do
Group
|> Ash.Query.for_read(:read_with_archived, %{}, authorize?: false)
Expand Down
17 changes: 13 additions & 4 deletions lib/huddlz/communities/group_member.ex
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,13 @@ defmodule Huddlz.Communities.GroupMember do
mixin {Huddlz.Audit.Version, :mixin, []}
end

alias Huddlz.Communities.GroupLock
alias Huddlz.Communities.GroupMember.Checks.GroupOrganizer
alias Huddlz.Communities.GroupMember.Checks.GroupOwner
alias Huddlz.Communities.GroupMember.Checks.PublicGroup

@owner_leave_message "owners cannot leave their own group; transfer ownership first"

postgres do
table "group_members"
repo Huddlz.Repo
Expand Down Expand Up @@ -259,10 +262,16 @@ defmodule Huddlz.Communities.GroupMember do
description "Leave a group (member removes themselves; owners must transfer ownership first)"
require_atomic? false

# Keep this invariant even for trusted internal calls that bypass authorization.
validate attribute_does_not_equal(:role, :owner) do
message "owners cannot leave their own group; transfer ownership first"
end
validate attribute_does_not_equal(:role, :owner), message: @owner_leave_message

change {Huddlz.Accounts.AccountLifecycleLock, participants: [:user_id]}
change before_action(&GroupLock.reserve_for_leave/2)
change get_and_lock("FOR UPDATE")

# A transfer can commit after the initial validation and authorization.
validate attribute_does_not_equal(:role, :owner),
before_action?: true,
message: @owner_leave_message

change Huddlz.Communities.GroupMember.Changes.CloseDropInReminder
change Huddlz.Communities.GroupMember.Changes.ReleaseMembersOnlySpots
Expand Down
18 changes: 8 additions & 10 deletions lib/huddlz/communities/release_spots.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ defmodule Huddlz.Communities.ReleaseSpots do

| Action | Locks and writes in acquisition order |
| --- | --- |
| Leave | Delete own membership → close reminder (first insert references group) → affected huddlz by ID → released and promoted spots |
| Leave | Shared account lifecycle lock → group key share → lock own membership, check its current role and delete it → close reminder → affected huddlz by ID → released and promoted spots |
| Remove member | Group → membership → removal notice → close reminder → affected huddlz by ID → released and promoted spots |
| Change role | Group → membership → role change and notice |
| RSVP or join waitlist | Shared account lifecycle lock → group → membership key share if members-only → huddl → spot |
| Cancel RSVP | Group → huddl → departing spot → promotion if a seat opens |
| Promote during release | Already-held huddl → next waitlisted spot → promotion notice |
| Edit all dates | Check series membership → active group `FOR NO KEY UPDATE` → reread source series and select source and all same-group series date IDs → those huddlz `FOR UPDATE` by ID → update source → load and update its group’s template → reconcile later dates in that group → record source and scheduled starts |
| Archive group | Group for update → archive and notify members |
| Delete group permanently | Group for update → memberships by ID → huddlz by ID → cascade and notify members |
| Archive group | Actor’s shared lifecycle lock → group for update → archive and notify members |
| Delete group permanently | Actor’s shared lifecycle lock → group for update → memberships by ID → huddlz by ID → cascade and notify members |
| Invite by account or email | Look up the addressed account ID → inviter and candidate account rows `FOR SHARE` by ID → active group → resolve the confirmed recipient → expire matching expired pending invitations → insert invitation |
| Claim invitation | Actor’s shared lifecycle lock → actor and original inviter `FOR SHARE` by ID → active group → pending invitation `FOR UPDATE` → record link opening and, if confirmed, lock any pending invitation already bound to the account and reconcile the offers |
| Accept invitation | Shared participant lifecycle locks → actor account `FOR SHARE` → active group → pending invitation `FOR UPDATE` → accept and grant membership if needed |
Expand All @@ -42,9 +42,9 @@ defmodule Huddlz.Communities.ReleaseSpots do
at `FOR NO KEY UPDATE` through anonymization. The partial unique index on
the required email keeps references to the account ID compatible with that write.

An ordinary first-time leave still writes its reminder after deleting the
membership. The group reference can contend with a concurrent permanent
deletion. Account deletion reserves its joined groups before this step.
Leaving takes a key-share lock on the group before removing the membership.
This reserves the group reference for the reminder while allowing unrelated
members to leave or change roles.
"""

alias Huddlz.Accounts.User
Expand Down Expand Up @@ -92,10 +92,8 @@ defmodule Huddlz.Communities.ReleaseSpots do
def release_members_only_in_group(%User{id: user_id} = user, group_id, opts) do
# The group's own visibility is read once, so every spot is judged by the
# same answer even if the group is being opened or closed at the same
# moment. The group's row is not locked: a leave takes no lock on its
# group. What settles this against the person's own RSVP is the
# membership row (`SpotLocks`): an RSVP in flight held it, so this ran
# only after that RSVP committed, and one that comes now finds it gone.
# moment. The membership row orders the departure against the person's
# own RSVP: an earlier RSVP is released, and a later one finds it gone.
case group_visibility(group_id) do
nil ->
[]
Expand Down
130 changes: 126 additions & 4 deletions test/huddlz/communities/huddl_rsvp_concurrency_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -386,10 +386,6 @@ defmodule Huddlz.Communities.HuddlRsvpConcurrencyTest do
end)
end

# A returning member: leaving for the first time writes the person's
# reminder for the group after the membership is deleted, and that write
# waits for the group's row while the deletion waits for the membership.
# That order is the leave's own and is the same on main.
for ending <- [:leaving, :account_deletion] do
@ending ending

Expand All @@ -412,6 +408,132 @@ defmodule Huddlz.Communities.HuddlRsvpConcurrencyTest do
end
end

describe "group closure, departures and ownership" do
for action <- [:archive_group, :destroy_group] do
@group_action action

test "#{action} honors the owner's account closure" do
Sandbox.unboxed_run(Repo, fn ->
owner = generate(user(hashed_password: Bcrypt.hash_pwd_salt(@password)))
cleanup_on_exit([owner])
group = generate(group(actor: owner))

assert {:error, error} =
commit_while_waiting(
fn -> Accounts.AccountLifecycleLock.take(owner.id, :exclusive) end,
fn -> apply(Communities, @group_action, [group, [actor: owner]]) end,
fn -> Accounts.delete_account!(owner, @password, actor: owner) end
)

assert Exception.message(error) =~ "Account unavailable"

assert %{archived_at: %DateTime{}} =
Ash.get!(Communities.Group, group.id,
action: :read_with_archived,
authorize?: false
)
end)
end
end

test "leaving honors the departing member's account closure" do
Sandbox.unboxed_run(Repo, fn ->
ctx = members_only_huddl(:rsvp)
Communities.rsvp_huddl!(ctx.huddl, actor: ctx.member)

assert {:error, error} =
commit_while_waiting(
fn -> Accounts.AccountLifecycleLock.take(ctx.member.id, :exclusive) end,
fn -> end_it(:leaving, ctx) end,
fn -> assert :ok = end_it(:account_deletion, ctx) end
)

assert Exception.message(error) =~ "Account unavailable"
assert_membership_and_spot_gone(ctx)
end)
end

test "a departure uses the roster role committed by the ownership transfer" do
Sandbox.unboxed_run(Repo, fn ->
ctx = members_only_huddl(:rsvp)

# Observe the decision without allowing the probe to modify the roster.
departure =
ctx.membership
|> Ash.Changeset.for_destroy(:leave_group, %{}, actor: ctx.member)
|> Ash.Changeset.before_action(&Ash.Changeset.add_error(&1, "departure probe"))

assert {:error, error} =
commit_while_waiting(
fn ->
Communities.transfer_group_ownership!(ctx.group, ctx.member.id,
actor: ctx.owner
)
end,
fn -> Ash.destroy(departure, authorize?: false) end
)

assert Exception.message(error) =~ "owners cannot leave their own group"
current = Communities.get_group_member!(ctx.group.id, ctx.member.id, authorize?: false)
assert current.role == :owner
assert {:error, _} = Communities.leave_group(current, actor: ctx.member)
assert {:error, _} = Communities.leave_group(current, authorize?: false)
end)
end

test "a replacement invitation waits for a closing group before expiring the old offer" do
Sandbox.unboxed_run(Repo, fn ->
ctx = account_and_group()

offer =
Communities.invite_to_group!(ctx.group.id, ctx.person.id, :member, actor: ctx.owner)
|> Ash.Seed.update!(%{expires_at: DateTime.add(DateTime.utc_now(), -1, :day)})

assert {:error, error} =
commit_while_waiting(
fn -> Communities.GroupLock.take(ctx.group.id) end,
fn -> add_to_group(:invitation_by_account, ctx) end,
fn ->
assert %{num_rows: 1} =
Repo.query!(
"SELECT id FROM group_invitations WHERE id = $1 FOR UPDATE NOWAIT",
[Ecto.UUID.dump!(offer.id)]
)

:ok = Communities.destroy_group(ctx.group, actor: ctx.owner)
end
)

assert Exception.message(error) =~ "archived or unavailable"
assert [] = Communities.list_group_invitations!(ctx.group.id, authorize?: false)
end)
end

test "a first departure waits for permanent group deletion" do
Sandbox.unboxed_run(Repo, fn ->
ctx = members_only_huddl(:rsvp)

assert {:error, error} =
commit_while_waiting(
fn -> Communities.GroupLock.take(ctx.group.id) end,
fn -> end_it(:leaving, ctx) end,
fn ->
assert %{num_rows: 1} =
Repo.query!(
"SELECT id FROM group_members WHERE id = $1 FOR UPDATE NOWAIT",
[Ecto.UUID.dump!(ctx.membership.id)]
)

:ok = Communities.destroy_group(ctx.group, actor: ctx.owner)
end
)

assert Exception.message(error) =~ "no longer available"
assert_membership_gone(ctx)
end)
end
end

describe "membership changes sent together finish without a deadlock" do
test "two members leaving" do
Sandbox.unboxed_run(Repo, fn ->
Expand Down
0