def begin(self): """ Begins this transaction. """ if hasattr(self._locals, 'transaction_exists') and self._locals.transaction_exists: raise TransactionError("Nested transactions are not allowed.") if self.state != _STATE_NOT_STARTED: raise TransactionError("Transaction has already been started.") self._locals.transaction_exists = True self.start_time = time.time() self.thread_id = thread_id() try: request = transaction_create_codec.encode_request( timeout=int(self.timeout * 1000), durability=self.durability, transaction_type=self.transaction_type, thread_id=self.thread_id) response = self.client.invoker.invoke_on_connection( request, self.connection).result() self.id = transaction_create_codec.decode_response( response)["response"] self.state = _STATE_ACTIVE except: self._locals.transaction_exists = False raise
def _get_or_create_object(self, name, proxy_type): if self.state != _STATE_ACTIVE: raise TransactionError("Transaction is not in active state.") self._check_thread() key = (proxy_type, name) try: return self._objects[key] except KeyError: proxy = proxy_type(name, self) self._objects[key] = proxy return make_blocking(proxy)
def rollback(self): self._check_thread() if self.state not in (_STATE_ACTIVE, _STATE_PARTIAL_COMMIT): raise TransactionError("Transaction is not active.") try: if self.state != _STATE_PARTIAL_COMMIT: request = transaction_rollback_codec.encode_request( self.id, self.thread_id) self.client.invoker.invoke_on_connection( request, self.connection).result() self.state = _STATE_ROLLED_BACK finally: self._locals.transaction_exists = False
def commit(self): self._check_thread() if self.state != _STATE_ACTIVE: raise TransactionError("Transaction is not active.") try: self._check_timeout() request = transaction_commit_codec.encode_request( self.id, self.thread_id) self.client.invoker.invoke_on_connection(request, self.connection).result() self.state = _STATE_COMMITTED except: self.state = _STATE_PARTIAL_COMMIT raise finally: self._locals.transaction_exists = False
def _check_timeout(self): if time.time() > self.timeout + self.start_time: raise TransactionError("Transaction has timed out.")
def _check_thread(self): if not thread_id() == self.thread_id: raise TransactionError("Transaction cannot span multiple threads.")