Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Concurrency issue when updating projection version #49

Closed
wants to merge 2 commits into from
Closed
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
53 changes: 31 additions & 22 deletions lib/projections/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ defmodule Commanded.Projections.Ecto do
- [Usage](usage.html)

"""

defmacro __using__(opts) do
opts = opts || []

Expand Down Expand Up @@ -67,29 +66,39 @@ defmodule Commanded.Projections.Ecto do

multi =
Ecto.Multi.new()
|> Ecto.Multi.run(:verify_projection_version, fn repo, _changes ->
version =
case repo.get(ProjectionVersion, projection_name, prefix: prefix) do
nil ->
repo.insert!(
%ProjectionVersion{
projection_name: projection_name,
last_seen_event_number: 0
},
prefix: prefix
)

version ->
version
|> Ecto.Multi.insert_all(
:insert_version,
ProjectionVersion,
[
%{
inserted_at: DateTime.to_naive(DateTime.utc_now()),
updated_at: DateTime.to_naive(DateTime.utc_now()),
projection_name: projection_name,
last_seen_event_number: 0
}
],
on_conflict: :nothing,
prefix: prefix
)
|> Ecto.Multi.update_all(
:update_version,
from(version in ProjectionVersion,
select: version,
where: version.projection_name == ^projection_name,
where: version.last_seen_event_number < ^event_number
),
[set: [last_seen_event_number: event_number]],
prefix: prefix
)
Comment on lines +69 to +92
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two separate INSERT and UPDATE statements will need to be combined as a single UPSERT query otherwise there is still the possibilty of a concurrency issue due to executing two queries.

|> Ecto.Multi.run(
:verify_projection_version,
fn _repo, %{update_version: {_, versions}} ->
case versions do
[] -> {:error, :already_seen_event}
[version] -> {:ok, %{version: version}}
end

if version.last_seen_event_number < event_number do
{:ok, %{version: version}}
else
{:error, :already_seen_event}
end
end)
|> Ecto.Multi.update(:projection_version, changeset, prefix: prefix)
)

with %Ecto.Multi{} = multi <- apply(multi_fn, [multi]),
{:ok, changes} <- transaction(multi) do
Expand Down