Skip to content

Commit

Permalink
Fix race condition in version slug generation (#133)
Browse files Browse the repository at this point in the history
The previous use of `select_for_update` fell out of scope too quickly and caused the lock on the database to be removed too quickly. This potentially allowed a race condition if, for example, a user hit the "Create new version" button too many times and the queries were evaluated at the same time. It is possible that this caused the duplicate slug issue that we've observed before, in some cases.
  • Loading branch information
super-cooper authored Aug 2, 2023
1 parent 6fecb08 commit 7ab2554
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions trovi/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,14 +299,12 @@ def generate_slug(instance: "ArtifactVersion", created: bool = False, **_):
time_stamp = instance.created_at.strftime("%Y-%m-%d")
with transaction.atomic():
if instance.artifact:
versions_today = (
instance.artifact.versions.filter(
artifact__created_at__date=instance.created_at.date(),
)
.exclude(slug__exact="")
.select_for_update()
.count()
)
versions_today_query = instance.artifact.versions.filter(
artifact__created_at__date=instance.created_at.date(),
).select_for_update()
versions_today = versions_today_query.exclude(
slug__exact=""
).count()
else:
versions_today = 0
if versions_today:
Expand Down

0 comments on commit 7ab2554

Please sign in to comment.