Skip to content

Commit

Permalink
fix: handle race condition on contact creation (#2289)
Browse files Browse the repository at this point in the history
  • Loading branch information
cquintana92 authored Oct 24, 2024
1 parent d65994c commit 01d5f40
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions app/contact_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
class ContactCreateError(Enum):
InvalidEmail = "Invalid email"
NotAllowed = "Your plan does not allow to create contacts"
Unknown = "Unknown error when trying to create contact"


@dataclass
Expand Down Expand Up @@ -87,6 +88,7 @@ def create_contact(
return __update_contact_if_needed(contact, name, mail_from)
# Create the contact
reply_email = generate_reply_email(email, alias)
alias_id = alias.id
try:
flags = Contact.FLAG_PARTNER_CREATED if from_partner else 0
contact = Contact.create(
Expand Down Expand Up @@ -114,11 +116,21 @@ def create_contact(
LOG.d(
f"Created contact {contact} for alias {alias} with email {email} invalid_email={contact.invalid_email}"
)
return ContactCreateResult(contact, created=True, error=None)
except IntegrityError:
Session.rollback()
LOG.info(
f"Contact with email {email} for alias_id {alias.id} already existed, fetching from DB"
f"Contact with email {email} for alias_id {alias_id} already existed, fetching from DB"
)
contact = Contact.get_by(alias_id=alias.id, website_email=email)
return __update_contact_if_needed(contact, name, mail_from)
return ContactCreateResult(contact, created=True, error=None)
contact: Optional[Contact] = Contact.get_by(
alias_id=alias_id, website_email=email
)
if contact:
return __update_contact_if_needed(contact, name, mail_from)
else:
LOG.warning(
f"Could not find contact with email {email} for alias_id {alias_id} and it should exist"
)
return ContactCreateResult(
None, created=False, error=ContactCreateError.Unknown
)

0 comments on commit 01d5f40

Please sign in to comment.