Skip to content

Commit

Permalink
fix possible thread racing when creating new session clients
Browse files Browse the repository at this point in the history
  • Loading branch information
marrony committed Nov 3, 2016
1 parent 5a6cf05 commit 3d5c403
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions faunadb/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,24 @@
from faunadb._json import parse_json_or_none, to_json

class _Counter(object):
def __init__(self):
def __init__(self, init_value=0):
self.lock = threading.Lock()
self.counter = 0
self.counter = init_value

def __str__(self):
return "Counter(%s)" % self.counter

def increment(self):
def get_and_increment(self):
with self.lock:
counter = self.counter
self.counter += 1
return self.counter
return counter

def decrement(self):
with self.lock:
self.counter -= 1
return self.counter

def get(self):
with self.lock:
return self.counter

class FaunaClient(object):
"""
Directly communicates with FaunaDB via JSON.
Expand Down Expand Up @@ -82,7 +79,7 @@ def __init__(

if ('session' not in kwargs) or ('counter' not in kwargs):
self.session = Session()
self.counter = _Counter()
self.counter = _Counter(1)

self.session.headers.update({
"Accept-Encoding": "gzip",
Expand All @@ -93,8 +90,6 @@ def __init__(
self.session = kwargs['session']
self.counter = kwargs['counter']

self.counter.increment()

def __del__(self):
# pylint: disable=bare-except
if self.counter.decrement() == 0:
Expand Down Expand Up @@ -130,7 +125,7 @@ def new_session_client(self, secret, observer=None):
Callback that will be passed a :any:`RequestResult` after every completed request.
:return:
"""
if self.counter.get() > 0:
if self.counter.get_and_increment() > 0:
return FaunaClient(secret=secret,
domain=self.domain,
scheme=self.scheme,
Expand Down

0 comments on commit 3d5c403

Please sign in to comment.