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
44 changes: 41 additions & 3 deletions lib/event_store/subscriptions/subscriber.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ defmodule EventStore.Subscriptions.Subscriber do
:partition_key,
last_sent: 0,
buffer_size: 1,
in_flight: []
in_flight: [],
superseded: []
]

alias EventStore.RecordedEvent
Expand Down Expand Up @@ -41,15 +42,43 @@ defmodule EventStore.Subscriptions.Subscriber do
}
end

# The subscriber still acknowledges what it was sent before the reset, and those events are
# sent again, so its acknowledgements must not be mistaken for ones of the new deliveries.
def reset_in_flight(%Subscriber{} = subscriber) do
%Subscriber{subscriber | in_flight: [], partition_key: nil}
%Subscriber{in_flight: in_flight, superseded: superseded} = subscriber

%Subscriber{
subscriber
| in_flight: [],
superseded: in_flight ++ superseded,
partition_key: nil
}
end

@doc """
Acknowledge the in-flight event by number and all events sent to the
subscriber before the ack'd event.
"""
def acknowledge(%Subscriber{} = subscriber, ack) do
def acknowledge(%Subscriber{superseded: superseded} = subscriber, ack) do
# Earlier deliveries reach the subscriber before the ones sent after a reset, so acknowledging
# one of the later deliveries means none of the earlier ones will be acknowledged anymore.
case oldest_ack_event_index(superseded, ack) do
nil -> acknowledge_in_flight(%Subscriber{subscriber | superseded: []}, ack)
index -> {:ok, %Subscriber{subscriber | superseded: Enum.take(superseded, index)}, []}
end
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
end

@doc """
Discard an acknowledgement of an event sent before the in-flight events were reset.
"""
def discard_superseded(%Subscriber{superseded: superseded} = subscriber, ack) do
case oldest_ack_event_index(superseded, ack) do
nil -> subscriber
index -> %Subscriber{subscriber | superseded: Enum.take(superseded, index)}
end
end

defp acknowledge_in_flight(%Subscriber{} = subscriber, ack) do
%Subscriber{in_flight: in_flight} = subscriber

case ack_event_index(in_flight, ack) do
Expand All @@ -73,6 +102,15 @@ defmodule EventStore.Subscriptions.Subscriber do
end
end

# An event sent again before the subscriber caught up is superseded once per reset, and each
# acknowledgement of it accounts for the oldest delivery still unaccounted for.
defp oldest_ack_event_index(superseded, ack) do
case superseded |> Enum.reverse() |> ack_event_index(ack) do
nil -> nil
index -> length(superseded) - 1 - index
end
end

defp ack_event_index(in_flight, ack) do
Enum.find_index(in_flight, fn
%RecordedEvent{event_number: ^ack} -> true
Expand Down
15 changes: 14 additions & 1 deletion lib/event_store/subscriptions/subscription_fsm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,20 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do
end
end

def ack(%__MODULE__{data: %SubscriptionState{}} = fsm, _ack, _subscriber), do: fsm
def ack(%__MODULE__{data: %SubscriptionState{} = data} = fsm, ack, subscriber_pid) do
%SubscriptionState{subscribers: subscribers} = data

case subscriber_by_pid(subscribers, subscriber_pid) do
{:ok, subscriber} ->
subscriber = Subscriber.discard_superseded(subscriber, ack)
subscribers = Map.put(subscribers, subscriber_pid, subscriber)

%__MODULE__{fsm | data: %SubscriptionState{data | subscribers: subscribers}}

{:error, :unknown_subscriber} ->
fsm
end
end

def checkpoint(%__MODULE__{state: :request_catch_up, data: %SubscriptionState{} = data} = fsm) do
%__MODULE__{fsm | state: :request_catch_up, data: persist_checkpoint(data)}
Expand Down
67 changes: 67 additions & 0 deletions test/subscriptions/subscriber_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
defmodule EventStore.Subscriptions.SubscriberTest do
use ExUnit.Case, async: true

alias EventStore.RecordedEvent
alias EventStore.Subscriptions.Subscriber

describe "acknowledgement sent before more than one reset" do
test "covers only the delivery it was sent for" do
event = %RecordedEvent{event_number: 1}

subscriber =
%Subscriber{}
|> Subscriber.track_in_flight(event, nil)
|> Subscriber.reset_in_flight()
|> Subscriber.track_in_flight(event, nil)
|> Subscriber.reset_in_flight()
|> Subscriber.track_in_flight(event, nil)

assert {:ok, subscriber, []} = Subscriber.acknowledge(subscriber, 1)
assert {:ok, subscriber, []} = Subscriber.acknowledge(subscriber, 1)
assert {:ok, _subscriber, [^event]} = Subscriber.acknowledge(subscriber, 1)
end

test "is discarded for only the delivery it was sent for" do
event = %RecordedEvent{event_number: 1}

subscriber =
%Subscriber{}
|> Subscriber.track_in_flight(event, nil)
|> Subscriber.reset_in_flight()
|> Subscriber.track_in_flight(event, nil)
|> Subscriber.reset_in_flight()
|> Subscriber.discard_superseded(1)
|> Subscriber.track_in_flight(event, nil)

assert {:ok, subscriber, []} = Subscriber.acknowledge(subscriber, 1)
assert {:ok, _subscriber, [^event]} = Subscriber.acknowledge(subscriber, 1)
end
end

describe "acknowledgement of an event sent after a reset" do
test "accounts for every earlier delivery the subscriber went past" do
[event2, event3, event4] = Enum.map(2..4, &%RecordedEvent{event_number: &1})

subscriber =
%Subscriber{}
|> Subscriber.track_in_flight(event2, nil)
|> Subscriber.track_in_flight(event3, nil)
|> Subscriber.reset_in_flight()
|> Subscriber.track_in_flight(event2, nil)
|> Subscriber.track_in_flight(event3, nil)
|> Subscriber.track_in_flight(event4, nil)

assert {:ok, subscriber, [^event4, ^event3, ^event2]} =
Subscriber.acknowledge(subscriber, 4)

# Resuming from a checkpoint that had not caught up sends the acknowledged events again.
subscriber =
subscriber
|> Subscriber.reset_in_flight()
|> Subscriber.track_in_flight(event2, nil)
|> Subscriber.track_in_flight(event3, nil)

assert {:ok, _subscriber, [^event3, ^event2]} = Subscriber.acknowledge(subscriber, 3)
end
end
end
144 changes: 128 additions & 16 deletions test/subscriptions/subscription_locking_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,63 @@ defmodule EventStore.Subscriptions.SubscriptionLockingTest do
end
end

describe "acknowledgement sent before a disconnect" do
@describetag retry_interval: 60_000

setup context do
{:ok, subscription} = start_subscription(context)

[subscription: subscription]
end

test "does not cover events redelivered after the reconnect", %{
event_store: event_store,
subscription: subscription
} do
{departed, survivor} =
connect_departing_and_surviving_subscribers(subscription, event_store)

:ok = disconnect(subscription)

depart(subscription, departed)

:ok = reconnect(subscription)

Wait.until(5_000, fn -> assert in_flight(subscription, survivor) == [2, 1] end)

# The survivor acknowledges the delivery of event 2 it received before the disconnect, which
# says nothing about event 1 it has only just been sent.
:ok = Subscription.ack(subscription, 2, survivor)

assert Subscription.last_seen(subscription) == 0
assert in_flight(subscription, survivor) == [2, 1]

:ok = Subscription.ack(subscription, 2, survivor)

assert Subscription.last_seen(subscription) == 2
end

test "does not cover events redelivered after the reconnect when it arrives while disconnected",
%{event_store: event_store, subscription: subscription} do
{departed, survivor} =
connect_departing_and_surviving_subscribers(subscription, event_store)

:ok = disconnect(subscription)

depart(subscription, departed)

:ok = Subscription.ack(subscription, 2, survivor)

:ok = reconnect(subscription)

Wait.until(5_000, fn -> assert in_flight(subscription, survivor) == [2, 1] end)

:ok = Subscription.ack(subscription, 2, survivor)

assert Subscription.last_seen(subscription) == 2
end
end

describe "subscription stopped after another owner took over" do
test "should leave the progress of the new owner untouched", %{
conn: conn,
Expand Down Expand Up @@ -375,6 +432,14 @@ defmodule EventStore.Subscriptions.SubscriptionLockingTest do
end

defp create_subscription(context) do
{:ok, subscription} = start_subscription(context)

{:ok, ^subscription} = Subscription.connect(subscription, self(), buffer_size: 3)

[subscription: subscription]
end

defp start_subscription(context) do
%{
conn: conn,
schema: schema,
Expand All @@ -385,24 +450,71 @@ defmodule EventStore.Subscriptions.SubscriptionLockingTest do
causation_id_type: causation_id_type
} = context

{:ok, subscription} =
Subscription.start_link(
event_store: event_store,
conn: conn,
schema: schema,
serializer: serializer,
correlation_id_type: correlation_id_type,
causation_id_type: causation_id_type,
retry_interval: Map.get(context, :retry_interval, 1_000),
stream_uuid: "$all",
subscription_name: subscription_name,
buffer_size: 3,
start_from: 0
)
Subscription.start_link(
event_store: event_store,
conn: conn,
schema: schema,
serializer: serializer,
correlation_id_type: correlation_id_type,
causation_id_type: causation_id_type,
retry_interval: Map.get(context, :retry_interval, 1_000),
stream_uuid: "$all",
subscription_name: subscription_name,
buffer_size: 3,
start_from: 0
)
end

{:ok, ^subscription} = Subscription.connect(subscription, self(), buffer_size: 3)
# Leaves the departing subscriber holding event 1 and the surviving one holding event 2, so the
# survivor is handed both once the departed subscriber is gone.
defp connect_departing_and_surviving_subscribers(subscription, event_store) do
departed = idle_subscriber()
survivor = idle_subscriber()

[subscription: subscription]
{:ok, ^subscription} =
Subscription.connect(subscription, departed, buffer_size: 1, concurrency_limit: 2)

Wait.until(5_000, fn -> assert subscription_state(subscription) == :subscribed end)

append_events_to_stream(event_store, 1)

Wait.until(5_000, fn -> assert in_flight(subscription, departed) == [1] end)

{:ok, ^subscription} =
Subscription.connect(subscription, survivor, buffer_size: 2, concurrency_limit: 2)

append_events_to_stream(event_store, 1)

Wait.until(5_000, fn -> assert in_flight(subscription, survivor) == [2] end)

{departed, survivor}
end

defp idle_subscriber do
subscriber = spawn(fn -> Process.sleep(:infinity) end)

on_exit(fn -> Process.exit(subscriber, :kill) end)

subscriber
end

defp depart(subscription, subscriber) do
Process.exit(subscriber, :kill)

Wait.until(5_000, fn -> refute Map.has_key?(subscribers(subscription), subscriber) end)
end

defp in_flight(subscription, subscriber) do
%{^subscriber => %{in_flight: in_flight}} = subscribers(subscription)

pluck(in_flight, :event_number)
end

defp subscribers(subscription) do
%Subscription{subscription: %{data: %{subscribers: subscribers}}} =
:sys.get_state(subscription)

subscribers
end

defp terminate_lock_session(conn) do
Expand Down
Loading