Skip to content

Commit 221c633

Browse files
connection_timeout option (#127)
* `connection_timeout` tunable * Fix timeout
1 parent 937e932 commit 221c633

File tree

5 files changed

+17
-15
lines changed

5 files changed

+17
-15
lines changed

src/dipdup/config.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ class PostgresDatabaseConfig:
7979
schema_name: str = 'public'
8080
password: str = ''
8181
immune_tables: List[str] = Field(default_factory=list)
82+
connection_timeout: int = 60
8283

8384
@property
8485
def connection_string(self) -> str:
@@ -102,7 +103,8 @@ class HTTPConfig:
102103
retry_multiplier: Optional[float] = None
103104
ratelimit_rate: Optional[int] = None
104105
ratelimit_period: Optional[int] = None
105-
connection_limit: Optional[int] = None
106+
connection_limit: Optional[int] = None # default 100
107+
connection_timeout: Optional[int] = None # default 60
106108
batch_size: Optional[int] = None
107109

108110
def merge(self, other: Optional['HTTPConfig']) -> 'HTTPConfig':
@@ -151,7 +153,7 @@ def module_name(self) -> str:
151153
@validator('address', allow_reuse=True)
152154
def valid_address(cls, v):
153155
# NOTE: Wallet addresses are allowed for debugging purposes (source field). Do we need a separate section?
154-
if not (v.startswith('KT1') or v.startswith('tz1')) or len(v) != 36:
156+
if not (v.startswith('KT') or v.startswith('tz')) or len(v) != 36:
155157
raise ConfigurationError(f'`{v}` is not a valid contract address')
156158
return v
157159

@@ -755,7 +757,6 @@ class HasuraConfig:
755757
select_limit: int = 100
756758
allow_aggregations: bool = True
757759
camel_case: bool = False
758-
connection_timeout: int = 5
759760
rest: bool = True
760761
http: Optional[HTTPConfig] = None
761762

src/dipdup/dipdup.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,8 +290,9 @@ async def _set_up_database(self, stack: AsyncExitStack, reindex: bool) -> None:
290290
validate_models(self._config.package)
291291

292292
url = self._config.database.connection_string
293+
timeout = self._config.database.connection_timeout if isinstance(self._config.database, PostgresDatabaseConfig) else None
293294
models = f'{self._config.package}.models'
294-
await stack.enter_async_context(tortoise_wrapper(url, models))
295+
await stack.enter_async_context(tortoise_wrapper(url, models, timeout or 60))
295296

296297
if reindex:
297298
await self._ctx.reindex(reason='run with `--reindex` option')

src/dipdup/hasura.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,14 +143,15 @@ async def _hasura_request(self, endpoint: str, json: Dict[str, Any]) -> Dict[str
143143

144144
async def _healthcheck(self) -> None:
145145
self._logger.info('Waiting for Hasura instance to be ready')
146-
for _ in range(self._hasura_config.connection_timeout):
146+
timeout = self._http_config.connection_timeout or 60
147+
for _ in range(timeout):
147148
with suppress(ClientConnectorError, ClientOSError):
148149
response = await self._http._session.get(f'{self._hasura_config.url}/healthz')
149150
if response.status == 200:
150151
break
151152
await asyncio.sleep(1)
152153
else:
153-
raise HasuraError(f'Hasura instance not responding for {self._hasura_config.connection_timeout} seconds')
154+
raise HasuraError(f'Hasura instance not responding for {timeout} seconds')
154155

155156
version_json = await (
156157
await self._http._session.get(

src/dipdup/http.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ async def __aenter__(self) -> None:
6565
"""Create underlying aiohttp session"""
6666
self.__session = aiohttp.ClientSession(
6767
connector=aiohttp.TCPConnector(limit=self._config.connection_limit or 100),
68+
timeout=aiohttp.ClientTimeout(self._config.connection_timeout or 60),
6869
)
6970

7071
async def __aexit__(self, exc_type, exc, tb):

src/dipdup/utils/database.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,21 @@
2222

2323

2424
@asynccontextmanager
25-
async def tortoise_wrapper(url: str, models: Optional[str] = None) -> AsyncIterator:
25+
async def tortoise_wrapper(url: str, models: Optional[str] = None, timeout: int = 60) -> AsyncIterator:
2626
"""Initialize Tortoise with internal and project models, close connections when done"""
27-
# TODO: Fail fast
28-
attempts = 60
27+
modules = {'int_models': ['dipdup.models']}
28+
if models:
29+
modules['models'] = [models]
2930
try:
30-
modules = {'int_models': ['dipdup.models']}
31-
if models:
32-
modules['models'] = [models]
33-
for attempt in range(attempts):
31+
for attempt in range(timeout):
3432
try:
3533
await Tortoise.init(
3634
db_url=url,
3735
modules=modules, # type: ignore
3836
)
3937
except (OSError, ConnectionRefusedError):
40-
_logger.warning('Can\'t establish database connection, attempt %s/%s', attempt, attempts)
41-
if attempt == attempts - 1:
38+
_logger.warning('Can\'t establish database connection, attempt %s/%s', attempt, timeout)
39+
if attempt == timeout - 1:
4240
raise
4341
await asyncio.sleep(1)
4442
else:

0 commit comments

Comments
 (0)