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

Two fixes with DBMutexTimeoutError #32

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
23 changes: 17 additions & 6 deletions db_mutex/db_mutex.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from django.conf import settings
from django.db import transaction, IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone

from .exceptions import DBMutexError, DBMutexTimeoutError
from .models import DBMutex
Expand Down Expand Up @@ -91,8 +93,8 @@ def __call__(self, func):
def __enter__(self):
self.start()

def __exit__(self, *args):
self.stop()
def __exit__(self, type, value, traceback):
return self.stop(type, value, traceback)

def start(self):
"""
Expand All @@ -107,14 +109,23 @@ def start(self):
except IntegrityError:
raise DBMutexError('Could not acquire lock: {0}'.format(self.lock_id))

def stop(self):
def stop(self, type, value, traceback):
"""
Releases the db mutex lock. Throws an error if the lock was released before the function finished.
"""
if not DBMutex.objects.filter(id=self.lock.id).exists():
raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id))
else:
ttl_seconds = self.get_mutex_ttl_seconds()

try:
dbmutex = DBMutex.objects.get(id=self.lock.id)
self.lock.delete()
except ObjectDoesNotExist:
dbmutex = None

if value:
return # Any exception takes precedence over DBMutexTimeoutError

if not dbmutex or (ttl_seconds and dbmutex.creation_time <= timezone.now() - timedelta(seconds=ttl_seconds)):
raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id))

def decorate_callable(self, func):
"""
Expand Down