Skip to content

Commit

Permalink
Resolve race condition for deployment
Browse files Browse the repository at this point in the history
Signed-off-by: Zack Siri <[email protected]>
  • Loading branch information
zacksiri committed Nov 11, 2023
1 parent 0e4353c commit 84e954a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
3 changes: 3 additions & 0 deletions lib/uplink/packages/deployment.ex
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ defmodule Uplink.Packages.Deployment do
deployment
|> cast(params, @valid_attrs)
|> validate_required(@required_attrs)
|> unique_constraint(:hash,
name: :deployments_app_id_hash_index
)
end

def update_changeset(deployment, params) do
Expand Down
33 changes: 29 additions & 4 deletions lib/uplink/packages/deployment/manager.ex
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,47 @@ defmodule Uplink.Packages.Deployment.Manager do
end

@spec get_or_create(%App{}, map) :: {:ok, %Deployment{}}
def get_or_create(%App{id: app_id}, params) do
def get_or_create(%App{id: app_id} = app, params) do
hash = Map.get(params, :hash) || Map.get(params, "hash")

Deployment
|> Repo.get_by(app_id: app_id, hash: hash)
|> case do
nil ->
%Deployment{app_id: app_id}
|> Deployment.changeset(params)
|> Repo.insert()
create(app, params)

%Deployment{} = deployment ->
{:ok, deployment}
end
end

def create(%App{id: app_id}, params) do
%Deployment{app_id: app_id}
|> Deployment.changeset(params)
|> Repo.insert()
|> case do
{:ok, deployment} ->
{:ok, deployment}

{:error,
%Ecto.Changeset{
changes: %{hash: hash},
errors: [
hash:
{_,
[
constraint: :unique,
constraint_name: "deployments_app_id_hash_index"
]}
]
}} ->
{:ok, Repo.get_by!(Deployment, app_id: app_id, hash: hash)}

error ->
error
end
end

def update(%Deployment{} = deployment, params) do
deployment
|> Deployment.update_changeset(params)
Expand Down

0 comments on commit 84e954a

Please sign in to comment.