8000 fix(groups): release non-member spots when a group becomes private by mwoods79 · Pull Request #775 · 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
10 changes: 10 additions & 0 deletions lib/huddlz/communities/group.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ defmodule Huddlz.Communities.Group do
@slug_max_length 255

require Ash.Query
alias Huddlz.Communities.ReleaseSpots

use Ash.Resource,
otp_app: :huddlz,
Expand Down Expand Up @@ -357,6 +358,15 @@ defmodule Huddlz.Communities.Group do
description "Update group details"
change Huddlz.Communities.Changes.RequireActiveGroup

# Both locks prepend their hooks. Take the actor's lifecycle lock first.
change {Huddlz.Accounts.AccountLifecycleLock, participants: [:actor]} do
where [changing(:is_public), attribute_equals(:is_public, false)]
end

change before_action(&ReleaseSpots.when_group_becomes_private/2) do
where [changing(:is_public), attribute_equals(:is_public, false)]
end

accept [
:name,
:description,
Expand Down
17 changes: 3 additions & 14 deletions lib/huddlz/communities/huddl/changes/hold_series_in_order.ex
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ defmodule Huddlz.Communities.Huddl.Changes.HoldSeriesInOrder do

use Ash.Resource.Change

alias Huddlz.Communities.{GroupMember, Huddl}
alias Huddlz.Communities.{Huddl, ReleaseSpots}
alias Huddlz.Communities.Huddl.Changes.LockedHuddl

require Ash.Query
Expand All @@ -32,7 +32,7 @@ defmodule Huddlz.Communities.Huddl.Changes.HoldSeriesInOrder do
hold_series(changeset)

Ash.Changeset.fetch_change(changeset, :is_private) == {:ok, true} ->
hold_memberships(changeset.data.group_id, [changeset.data.id])
ReleaseSpots.hold_attendee_memberships(changeset.data.group_id, [changeset.data.id])

true ->
:ok
Expand Down Expand Up @@ -60,23 +60,12 @@ defmodule Huddlz.Communities.Huddl.Changes.HoldSeriesInOrder do
|> Ash.read!(authorize?: false)
|> Enum.map(& &1.id)

hold_memberships(group_id, public_ids)
ReleaseSpots.hold_attendee_memberships(group_id, public_ids)
end

LockedHuddl.hold_in_order(dates)
end

defp hold_memberships(_group_id, []), do: :ok

defp hold_memberships(group_id, huddl_ids) do
GroupMember
|> Ash.Query.filter(group_id == ^group_id and exists(user.rsvps, huddl_id in ^huddl_ids))
|> Ash.Query.select(:id)
|> Ash.Query.sort(id: :asc)
|> Ash.Query.lock("FOR KEY SHARE")
|> Ash.read!(authorize?: false)
end

defp current_series(id) do
Huddl
|> Ash.Query.for_read(:read_for_group_lifecycle)
Expand Down
57 changes: 53 additions & 4 deletions lib/huddlz/communities/release_spots.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ defmodule Huddlz.Communities.ReleaseSpots do
@moduledoc """
Releases a person's upcoming RSVP and waitlist spots: all of them on
suspension or account deletion, and the ones on a group's members-only
huddlz when their membership of it ends or when a huddl becomes members
only. The ordinary `:cancel_rsvp` action records who released each spot
and when. When a confirmed seat opens, the next person on the waitlist
gets the seat and a notification.
huddlz when their membership ends or a huddl or its group becomes private.
The ordinary `:cancel_rsvp` action records who released each spot and when.
When a confirmed seat opens, the next person on the waitlist gets the seat
and a notification.

Runs inside the caller's transaction, one huddl at a time under the same
row lock `:rsvp` and `:cancel_rsvp` take, so concurrent RSVP attempts
Expand All @@ -22,6 +22,7 @@ defmodule Huddlz.Communities.ReleaseSpots do
| Cancel RSVP | Group → huddl → departing spot → promotion if a seat opens |
| Promote during release | Already-held huddl → next waitlisted spot → promotion notice |
| Make a huddl members only | Active group → affected attendee memberships by ID for key share → huddl → cancel non-member spots → promote members |
| Make a group private | Actor’s shared lifecycle lock → active group for no key update → verify public visibility and update group → affected attendee memberships by ID for key share → upcoming huddlz by ID for update → cancel non-member spots and promote members |
| 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 → when propagating members-only attendance, lock affected memberships by ID for key share → 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 | 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 |
Expand Down Expand Up @@ -119,6 +120,54 @@ defmodule Huddlz.Communities.ReleaseSpots do
end
end

@doc """
Register the release only for a public-to-private write. RequireActiveGroup
holds the group here, so a stale edit cannot repeat an earlier release.
"""
def when_group_becomes_private(changeset, _context) do
case group_visibility(changeset.data.id) do
%Group{is_public: true} -> Ash.Changeset.after_action(changeset, &release_group_spots/2)
_already_private -> changeset
end
end

defp release_group_spots(changeset, group) do
ids =
Huddl
|> Ash.Query.for_read(:read_for_group_lifecycle)
|> Ash.Query.filter(
group_id == ^group.id and ends_at > now() and not cancelled and exists(attendees, true)
)
|> Ash.Query.select(:id)
|> Ash.read!(authorize?: false)
|> Enum.map(& &1.id)

hold_attendee_memberships(group.id, ids)
opts = Huddlz.Audit.nested_opts(changeset, %{automatic?: true})

Huddl
|> Ash.Query.for_read(:read_for_group_lifecycle)
|> Ash.Query.filter(id in ^ids)
|> Ash.Query.sort(id: :asc)
|> Ash.Query.lock("FOR UPDATE")
|> Ash.read!(authorize?: false)
|> Enum.each(&release_non_members(&1, opts))

{:ok, group}
end

@doc "Reserve attendees' memberships before locking any huddl whose attendance is changing."
def hold_attendee_memberships(_group_id, []), do: :ok

def hold_attendee_memberships(group_id, huddl_ids) do
GroupMember
|> Ash.Query.filter(group_id == ^group_id and exists(user.rsvps, huddl_id in ^huddl_ids))
|> Ash.Query.select(:id)
|> Ash.Query.sort(id: :asc)
|> Ash.Query.lock("FOR KEY SHARE")
|> Ash.read!(authorize?: false)
end

@doc """
Release non-members' spots after a huddl becomes private. The edit holds
the group, attendees' memberships and the huddl. Remove every ineligible
Expand Down
38 changes: 38 additions & 0 deletions test/features/private_group_spots.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
@async @database @conn @private_group_spots
Feature: Attendance when a group becomes private
Scenario: A member gets the seat when their group becomes private
Given the following users exist:
| email | display_name | role |
| host@example.com | Host | user |
| guest@example.com | Guest | user |
| queue@example.com | Queued Guest | user |
| next@example.com | Next Member | user |
And a public group "Board Games" exists with owner "host@example.com"
And "next@example.com" is a member of "Board Games"
And the following capped huddl exists in "Board Games":
| title | description | event_type | starts_at | virtual_link | max_attendees |
| Game Night | Board games | virtual | tomorrow 2pm | https://example.com | 2 |
And "guest@example.com" has RSVPed to "Game Night"
And "queue@example.com" is on the waitlist for "Game Night"
And "next@example.com" is on the waitlist for "Game Night"
And I am signed in as "host@example.com"
When I visit the edit page for "Board Games"
And I uncheck "Public group"
And I click "Save Changes"
Then I should see "Visibility is now private"
And "next@example.com" is confirmed for "Game Night"
And the agent for "next@example.com" shows a confirmed spot for "Game Night"
And "next@example.com" has one notification about getting a spot at "Game Night"
And "guest@example.com" is no longer attending "Game Night"
And "queue@example.com" is no longer attending "Game Night"

Scenario Outline: A drop-in's RSVPs across a series are released together
Given a group has a weekly series that people are going to
When the owner makes the series' group private through "<api>"
Then the drop-in has no spots on any of the original dates
And the drop-in receives no email about the released spots

Examples:
| api |
| JSON:API |
| GraphQL |
59 changes: 59 additions & 0 deletions test/features/step_definitions/series_membership_steps.exs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,65 @@ defmodule SeriesMembershipSteps do
context
end

step "the owner makes the series' group private through {string}", %{args: [api]} = context do
[first | _] = context.series_before.huddlz
id = first.group_id
conn = authenticated_conn(context.conn, context.series_owner)

case api do
"JSON:API" ->
response =
conn
|> json_api_headers()
|> dispatch(HuddlzWeb.Endpoint, :patch, "/api/json/groups/#{id}", %{
"data" => %{"type" => "group", "id" => id, "attributes" => %{"is_public" => false}}
})

assert %{"data" => %{"attributes" => %{"is_public" => false}}} =
json_response(response, 200)

"GraphQL" ->
response =
gql_post(conn, """
mutation {
updateGroup(id: "#{id}", input: {isPublic: false}) {
result { isPublic }
errors { message }
}
}
""")

assert %{
"data" => %{
"updateGroup" => %{"result" => %{"isPublic" => false}, "errors" => []}
}
} =
json_response(response, 200)
end

context
end

step "the drop-in has no spots on any of the original dates", context do
for date <- context.series_before.huddlz do
assert [] == Communities.check_user_rsvp!(date.id, actor: context.series_attendee)
assert Ash.get!(Huddl, date.id, actor: context.series_owner).starts_at == date.starts_at
end

context
end

step "the drop-in receives no email about the released spots", context do
Oban.drain_queue(queue: :notifications)
address = to_string(context.series_attendee.email)

refute Enum.any?(flush_emails(), fn email ->
Enum.any?(email.to, &(elem(&1, 1) == address))
end)

context
end

step "I organize a different group with a huddl of my own", context do
me = generate(user())
my_group = generate(group(actor: me, owner_id: me.id, is_public: true))
Expand Down
12 changes: 12 additions & 0 deletions test/features/step_definitions/waitlist_steps.exs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ defmodule WaitlistSteps do
context
end

step "the agent for {string} shows a confirmed spot for {string}",
%{args: [email, title]} = context do
member = Huddlz.Accounts.get_by_email!(email, authorize?: false)
huddl = Huddl |> Ash.Query.filter(title == ^title) |> Ash.read_one!(actor: member)
agent = HuddlzWeb.McpCase.connect(member)

assert %{"attendance_state" => "confirmed"} =
HuddlzWeb.McpCase.call(agent, "get_huddl", %{huddl_id: huddl.id})

context
end

step "I have joined the waitlist for {string}", %{args: [huddl_title]} = context do
user = context.current_user

Expand Down
54 changes: 54 additions & 0 deletions test/huddlz/communities/huddl_rsvp_concurrency_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,57 @@ defmodule Huddlz.Communities.HuddlRsvpConcurrencyTest do
end
end

describe "making a group private" do
test "a drop-in RSVP that commits first is released" do
Sandbox.unboxed_run(Repo, fn ->
ctx = members_only_huddl(:rsvp, group: [is_public: true])
:ok = end_it(:leaving, ctx)

assert {:ok, %{is_public: false}} =
commit_while_waiting(
fn -> assert {:ok, _} = take_spot(:rsvp, ctx) end,
fn -> make_group_private(ctx) end
)

assert_spot_gone(ctx)
end)
end

test "a drop-in RSVP waiting for the edit is refused" do
Sandbox.unboxed_run(Repo, fn ->
ctx = members_only_huddl(:rsvp, group: [is_public: true])
:ok = end_it(:leaving, ctx)

assert {:error, error} =
commit_while_waiting(
fn -> assert {:ok, %{is_public: false}} = make_group_private(ctx) end,
fn -> take_spot(:rsvp, ctx) end
)

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

test "a member leaving during the edit releases their spot in either commit order" do
Sandbox.unboxed_run(Repo, fn ->
for first <- [:leave, :edit] do
ctx = members_only_huddl(:rsvp, group: [is_public: true])
assert {:ok, _} = take_spot(:rsvp, ctx)
leave = fn -> assert :ok = end_it(:leaving, ctx) end
edit = fn -> assert {:ok, %{is_public: false}} = make_group_private(ctx) end

case first do
:leave -> commit_while_waiting(leave, edit)
:edit -> commit_while_waiting(edit, leave)
end

assert_membership_and_spot_gone(ctx)
end
end)
end
end

describe "several huddlz held at once are taken in one order" do
for ending <- [:leaving, :removal, :suspension, :account_deletion] do
@ending ending
Expand Down Expand Up @@ -1012,6 +1063,9 @@ defmodule Huddlz.Communities.HuddlRsvpConcurrencyTest do
assert [] = Communities.list_group_invitations!(ctx.group.id, actor: ctx.owner)
end

defp make_group_private(ctx),
do: Ash.update(ctx.group, %{is_public: false}, action: :update_details, actor: ctx.owner)

defp take_spot(:rsvp, ctx), do: Communities.rsvp_huddl(ctx.huddl, actor: ctx.member)

defp take_spot(:waitlist, ctx),
Expand Down
46 changes: 46 additions & 0 deletions test/huddlz/communities/release_spots_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,52 @@ defmodule Huddlz.Communities.ReleaseSpotsTest do
end
end

describe "making a group private" do
test "keeps attendance history and other groups' spots", %{owner: owner, member: drop_in} do
group = generate(group(actor: owner, is_public: true))
other_group = generate(group(actor: owner, is_public: true))

[cancelled, finished, upcoming, elsewhere] =
for group_id <- [group.id, group.id, group.id, other_group.id] do
huddl = generate(huddl(group_id: group_id, actor: owner))
rsvp!(huddl, drop_in)
huddl
end

Communities.cancel_huddl!(cancelled, "Venue closed", actor: owner)

Ash.Seed.update!(finished, %{
starts_at: DateTime.add(DateTime.utc_now(), -2, :hour),
ends_at: DateTime.add(DateTime.utc_now(), -1, :hour)
})

Ash.update!(group, %{is_public: false}, action: :update_details, actor: owner)

for huddl <- [cancelled, finished, elsewhere], do: assert([_spot] = spots(huddl, drop_in))
assert [] = spots(upcoming, drop_in)
end

test "an already-private group retains legacy spots until a new public-to-private edit",
%{owner: owner, member: drop_in} do
public = generate(group(actor: owner, is_public: true))
huddl = generate(huddl(group_id: public.id, actor: owner))
rsvp!(huddl, drop_in)

# A group made private before the release rule was introduced.
private = Ash.Seed.update!(public, %{is_public: false})
update = [action: :update_details, actor: owner]
Ash.update!(private, %{description: "New description"}, update)
Ash.update!(public, %{is_public: false}, update)
assert [_spot] = spots(huddl, drop_in)

reopened = Ash.update!(private, %{is_public: true}, update)
assert [_spot] = spots(huddl, drop_in)

Ash.update!(reopened, %{is_public: false}, update)
assert [] = spots(huddl, drop_in)
end
end

describe "deleting the account that owns a private group" do
test "promotes nobody into a huddl the deletion cancels", context do
owner = generate(user(hashed_password: Bcrypt.hash_pwd_salt("Password123!")))
Expand Down
Loading
0