FFFF fix(huddl): release non-member spots on members-only edits by mwoods79 · Pull Request #771 · 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
14 changes: 13 additions & 1 deletion lib/huddlz/communities/huddl.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule Huddlz.Communities.Huddl do
"""

alias Huddlz.Communities
alias Huddlz.Communities.Group
alias Huddlz.Communities.{Group, ReleaseSpots}

require Ash.Query

Expand Down Expand Up @@ -514,6 +514,18 @@ defmodule Huddlz.Communities.Huddl do

change Huddlz.Communities.Huddl.Changes.ForcePrivateForPrivateGroups
change Huddlz.Communities.Huddl.Changes.ClearUnusedLocationFields

change after_action(fn changeset, huddl, _context ->
ReleaseSpots.release_non_members(
huddl,
Huddlz.Audit.nested_opts(changeset, %{automatic?: true})
)

{:ok, huddl}
end) do
where [changing(:is_private), attribute_equals(:is_private, true)]
end

change Huddlz.Communities.Huddl.Changes.EditRecurringHuddlz
change Huddlz.Communities.Huddl.Changes.DefaultLocationFromGroup
change Huddlz.Communities.Huddl.Changes.EnforceCapacityFloor
Expand Down
61 changes: 50 additions & 11 deletions lib/huddlz/communities/huddl/changes/hold_series_in_order.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ defmodule Huddlz.Communities.Huddl.Changes.HoldSeriesInOrder do
`RequireActiveGroup` first locks that group with `FOR NO KEY UPDATE`.
Under that lock, reread the source's series and collect the source and
every date in the same group with that template, including earlier dates.
When the edit makes the huddlz members only, the memberships of their
current attendees are locked by ID for key share before the huddlz, so no
attendee can leave between the check and the release.
`LockedHuddl.hold_in_order/1` locks the selected huddl rows by ascending
ID with `FOR UPDATE`, the same order used when releasing spots.

Expand All @@ -16,37 +19,73 @@ defmodule Huddlz.Communities.Huddl.Changes.HoldSeriesInOrder do

use Ash.Resource.Change

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

require Ash.Query

@impl true
def change(changeset, _opts, _context) do
Ash.Changeset.before_action(changeset, fn changeset ->
if Ash.Changeset.get_argument(changeset, :edit_type) == "all", do: hold(changeset)
cond do
Ash.Changeset.get_argument(changeset, :edit_type) == "all" ->
hold_series(changeset)

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

true ->
:ok
end

changeset
end)
end

defp hold(%{data: %{id: id, group_id: group_id}}) do
series = current_series(id)
defp hold_series(%{data: %{id: id, group_id: group_id}} = changeset) do
{series, private?} = current_series(id)

Huddl
|> Ash.Query.for_read(:read_for_group_lifecycle)
|> Ash.Query.filter(group_id == ^group_id and (id == ^id or huddl_template_id in ^series))
|> LockedHuddl.hold_in_order()
dates =
Huddl
|> Ash.Query.for_read(:read_for_group_lifecycle)
|> Ash.Query.filter(group_id == ^group_id and (id == ^id or huddl_template_id in ^series))

# Even when the source is already private, a later date may still be public.
# Reserve its attendees' memberships before holding *any* huddl in the series.
if Map.get(changeset.attributes, :is_private, private?) do
public_ids =
dates
|> Ash.Query.filter(not is_private)
|> Ash.Query.select(:id)
|> Ash.read!(authorize?: false)
|> Enum.map(& &1.id)

hold_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)
|> Ash.Query.filter(id == ^id and in_series)
|> Ash.Query.select(:huddl_template_id)
|> Ash.Query.select([:huddl_template_id, :is_private])
|> Ash.read_one!(authorize?: false)
|> case do
nil -> []
huddl -> List.wrap(huddl.huddl_template_id)
nil -> {[], false}
huddl -> {[huddl.huddl_template_id], huddl.is_private}
end
end
end
49 changes: 42 additions & 7 deletions lib/huddlz/communities/release_spots.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +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. 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 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.

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 @@ -20,7 +21,8 @@ defmodule Huddlz.Communities.ReleaseSpots do
| 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 |
| Make a huddl members only | Active group → affected attendee memberships by ID for key share → huddl → cancel non-member spots → 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 |
| 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 |
Expand Down Expand Up @@ -50,11 +52,14 @@ defmodule Huddlz.Communities.ReleaseSpots do
alias Huddlz.Accounts.User
alias Huddlz.Communities
alias Huddlz.Communities.Group
alias Huddlz.Communities.GroupMember
alias Huddlz.Communities.Huddl
alias Huddlz.Communities.Huddl.Changes.LockedHuddl
alias Huddlz.Communities.HuddlAttendee
alias Huddlz.Communities.WaitlistPromotion
alias Huddlz.Repo

import Ecto.Query, only: [from: 2]
require Ash.Query

@doc """
Expand Down Expand Up @@ -114,6 +119,38 @@ defmodule Huddlz.Communities.ReleaseSpots do
end
end

@doc """
Release non-members' spots after a huddl becomes private. The edit holds
the group, attendees' memberships and the huddl. Remove every ineligible
spot before filling seats so only members move up the waitlist.
"""
@spec release_non_members(Huddl.t(), keyword()) :: :ok
def release_non_members(huddl, opts) do
if upcoming?(huddl) do
members = from m in GroupMember, where: m.group_id == ^huddl.group_id, select: m.user_id

spots =
Repo.all(
from a in HuddlAttendee,
where: a.huddl_id == ^huddl.id and a.user_id not in subquery(members)
)

Enum.each(spots, &cancel_spot(&1, opts))

if Enum.any?(spots, &is_nil(&1.waitlisted_at)) do
WaitlistPromotion.fill_open_seats(huddl, opts)
end
end

:ok
end

defp cancel_spot(attendee, opts) do
attendee
|> Ash.Changeset.for_destroy(:cancel_rsvp, %{}, opts)
|> Ash.destroy!(authorize?: false)
end

defp group_visibility(group_id) do
Group
|> Ash.Query.for_read(:read_with_archived, %{}, authorize?: false)
Expand Down Expand Up @@ -163,9 +200,7 @@ defmodule Huddlz.Communities.ReleaseSpots do
end

defp release(attendee, opts) do
attendee
|> Ash.Changeset.for_destroy(:cancel_rsvp, %{}, opts)
|> Ash.destroy!(authorize?: false)
cancel_spot(attendee, opts)

if is_nil(attendee.waitlisted_at), do: fill_seat(attendee.huddl_id, opts)
attendee
Expand Down
36 changes: 36 additions & 0 deletions test/features/members_only_spots.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
@async @database @conn @members_only_spots
Feature: Attendance when a huddl becomes members only
Scenario: A member on the waitlist gets the seat released by a drop-in
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 huddl "Game Night"
And I check "Members only"
And I click the "Save changes" button
Then I should see "Huddl updated successfully"
And "next@example.com" is confirmed 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 members-only series keeps its dates and releases drop-in spots
Given a group has a weekly series that people are going to
When the owner makes the whole series members only through "<api>"
Then the original dates are members only and the drop-in has no spots on them

Examples:
| api |
| JSON:API |
| GraphQL |
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ defmodule NotificationAccessSteps do
user = find_user(email)
huddl = find_huddl(title)

# A spot kept from before memberships released them on leaving.
# Model a spot kept before privacy edits and membership changes released it.
if attendances(huddl, user) == [] do
Ash.Seed.seed!(HuddlAttendee, %{huddl_id: huddl.id, user_id: user.id})
end
Expand Down
30 changes: 30 additions & 0 deletions test/features/step_definitions/series_membership_steps.exs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,41 @@ defmodule SeriesMembershipSteps do

Map.merge(context, %{
series_owner: owner,
series_attendee: attendee,
series_template_id: first.huddl_template_id,
series_before: series_snapshot(first.huddl_template_id)
})
end

step "the owner makes the whole series members only through {string}",
%{args: [api]} = context do
[first | _] = dates = context.series_before.huddlz
repeat_until = dates |> List.last() |> Map.fetch!(:starts_at) |> DateTime.to_date()

context.conn
|> authenticated_conn(context.series_owner)
|> update(api, first.id, %{
"edit_type" => "all",
"frequency" => "weekly",
"repeat_until" => Date.to_iso8601(repeat_until),
"is_private" => true
})
|> json_response(200)

context
end

step "the original dates are members only and the drop-in has no spots on them", context do
for date <- context.series_before.huddlz do
huddl = Ash.get!(Huddl, date.id, actor: context.series_owner)
assert huddl.is_private and is_nil(huddl.cancelled_at)
assert huddl.starts_at == date.starts_at
assert [] == Communities.check_user_rsvp!(huddl.id, actor: context.series_attendee)
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
3 changes: 2 additions & 1 deletion test/features/whos_going.feature
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,9 @@ Feature: Who's going
| JSON:API |
| GraphQL |

Scenario Outline: The API names nobody to someone who can no longer open the huddl
Scenario Outline: A spot kept from before a privacy edit does not grant access to the attendee list
Given "Elixir hack night" becomes members-only
And "maya14@example.com" still holds a spot on "Elixir hack night"
When "owner14@example.com" reads who is going to "Elixir hack night" through "<api>"
Then the API names "Maya Chen" among the people going
When "maya14@example.com" reads who is going to "Elixir hack night" through "<api>"
Expand Down
55 changes: 54 additions & 1 deletion test/huddlz/communities/huddl_rsvp_concurrency_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,58 @@ defmodule Huddlz.Communities.HuddlRsvpConcurrencyTest do
end
end

describe "making a huddl members only" do
for spot <- [:rsvp, :waitlist] do
@spot spot

test "the privacy edit releases a #{@spot} that commits first" do
Sandbox.unboxed_run(Repo, fn ->
ctx = members_only_huddl(@spot, group: [is_public: true])
:ok = end_it(:leaving, ctx)

assert {:ok, %{is_private: true}} =
commit_while_waiting(
fn -> assert {:ok, _} = take_spot(@spot, ctx) end,
fn ->
Communities.update_huddl(ctx.huddl, %{is_private: true}, actor: ctx.owner)
end
)

assert_spot_gone(ctx)
end)
end
end

test "a leave can finish before a private source closes the other dates in place" do
Sandbox.unboxed_run(Repo, fn ->
ctx = series_with_spots(is_public: true)
source = Communities.update_huddl!(ctx.huddl, %{is_private: true}, actor: ctx.owner)

for date <- ctx.dates, do: Communities.rsvp_huddl!(date, actor: ctx.other_member)

assert {:ok, _huddl} =
commit_while_waiting(
fn ->
Ash.get!(Communities.GroupMember, ctx.membership.id,
lock: "FOR UPDATE",
authorize?: false
)
end,
fn -> edit_all(%{ctx | huddl: source}) end,
fn -> assert :ok = end_it(:leaving, ctx) end
)

for date <- ctx.dates do
assert Ash.get!(Communities.Huddl, date.id, actor: ctx.owner).is_private
assert [] = Communities.check_user_rsvp!(date.id, actor: ctx.member)

assert [%{waitlisted_at: nil}] =
Communities.check_user_rsvp!(date.id, actor: ctx.other_member)
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 @@ -985,13 +1037,14 @@ defmodule Huddlz.Communities.HuddlRsvpConcurrencyTest do
defp assert_ended(_ending, ctx), do: assert_membership_and_spot_gone(ctx)

# A weekly series of members-only huddlz, the member going to every date.
defp series_with_spots do
defp series_with_spots(group_opts \\ [is_public: false]) do
first = Date.add(Date.utc_today(), 3)
repeat_until = Date.add(first, 22)

ctx =
Oban.Testing.with_testing_mode(:inline, fn ->
members_only_huddl(:rsvp,
group: group_opts,
huddl: [
date: first,
is_recurring: true,
Expand Down
0