Skip to content

Commit

Permalink
Merge pull request #978 from ImageMarkup/fix-publishing
Browse files Browse the repository at this point in the history
Fix exception handling in publishing transaction
  • Loading branch information
danlamanna authored Oct 4, 2024
2 parents 8b1f22e + ff818f3 commit 8bc527f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
24 changes: 17 additions & 7 deletions isic/core/models/isic_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,29 @@

from django.core.validators import RegexValidator
from django.db import IntegrityError, models
from tenacity import retry, retry_if_exception_type, stop_after_attempt

from isic.core.constants import ISIC_ID_REGEX


class IsicIdManager(models.Manager):
@retry(
reraise=True,
retry=retry_if_exception_type(IntegrityError),
stop=stop_after_attempt(10),
)
def create_random(self):
return self.create(id=f"ISIC_{secrets.randbelow(9999999):07}")
"""
Create a random unused ISIC ID.
Note that this is prone to race conditions. The actual creation should be wrapped
in a call to lock_table_for_writes(IsicId).
"""
obj = None
for _ in range(10):
isic_id = f"ISIC_{secrets.randbelow(9999999):07}"
if not self.filter(pk=isic_id).exists():
obj = self.create(pk=isic_id)
break

if obj is None:
raise IntegrityError("Failed to create a unique ISIC ID")

return obj


class IsicId(models.Model):
Expand Down
2 changes: 1 addition & 1 deletion isic/ingest/services/cohort/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def cohort_publish(
)

# this creates a transaction
with lock_table_for_writes(IsicId), cachalot_disabled():
with lock_table_for_writes(IsicId), cachalot_disabled(), transaction.atomic():
for accession in cohort.accessions.publishable().iterator():
image = image_create(creator=publisher, accession=accession, public=public)
collection_add_images(collection=cohort.collection, image=image, ignore_lock=True)
Expand Down

0 comments on commit 8bc527f

Please sign in to comment.