from storm.tracer import install_tracer, remove_tracer_type, get_tracers
from storm.zope.zstorm import ZStorm

from backends.db.errors import (
    IntegrityError,
    NoTimeoutTracer,
    RetryLimitReached,
)

#
# Since some of the account data is maintained by django, the basic
# transaction manager is used as this is what storm.django uses
#
account_tm = transaction
account_zstorm = ZStorm()
account_zstorm.transaction_manager = account_tm

storage_tm = transaction.ThreadTransactionManager()
storage_zstorm = ZStorm()
storage_zstorm.transaction_manager = storage_tm

# these are the default retryable exceptions
RETRYABLE_EXCEPTIONS = (
    DisconnectionError,
    TransactionRollbackError,
    psycopg2.InternalError,
    psycopg2.OperationalError,
)

# This is the maximum time a transaction can take before pgkillactive kills it.
TRANSACTION_MAX_TIME = 600
from psycopg2.extensions import TransactionRollbackError
from storm.databases.postgres import PostgresTimeoutTracer
from storm.exceptions import DisconnectionError, TimeoutError, ProgrammingError
from storm.tracer import install_tracer, remove_tracer_type, get_tracers
from storm.zope.zstorm import ZStorm

from backends.db.errors import (
    IntegrityError,
    NoTimeoutTracer,
    RetryLimitReached,
)

filesync_tm = transaction
filesync_zstorm = ZStorm()
filesync_zstorm.transaction_manager = filesync_tm

# these are the default retryable exceptions
RETRYABLE_EXCEPTIONS = (
    DisconnectionError,
    TransactionRollbackError,
    psycopg2.InternalError,
    psycopg2.OperationalError,
)

# This is the maximum time a transaction can take before pgkillactive kills it.
TRANSACTION_MAX_TIME = 600


def retryable_transaction(max_time=4.0, max_retries=3, variance=0.5,
                          exceptions=RETRYABLE_EXCEPTIONS):