|
| 1 | +"""" |
| 2 | +Async Dune Client Class responsible for refreshing Dune Queries |
| 3 | +Framework built on Dune's API Documentation |
| 4 | +https://duneanalytics.notion.site/API-Documentation-1b93d16e0fa941398e15047f643e003a |
| 5 | +""" |
| 6 | +import asyncio |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from aiohttp import ( |
| 10 | + ClientSession, |
| 11 | + ClientResponse, |
| 12 | + ContentTypeError, |
| 13 | + TCPConnector, |
| 14 | + ClientTimeout, |
| 15 | +) |
| 16 | + |
| 17 | +from dune_client.base_client import BaseDuneClient |
| 18 | +from dune_client.models import ( |
| 19 | + ExecutionResponse, |
| 20 | + DuneError, |
| 21 | + ExecutionStatusResponse, |
| 22 | + ResultsResponse, |
| 23 | + ExecutionState, |
| 24 | +) |
| 25 | + |
| 26 | +from dune_client.query import Query |
| 27 | + |
| 28 | + |
| 29 | +# pylint: disable=duplicate-code |
| 30 | +class AsyncDuneClient(BaseDuneClient): |
| 31 | + """ |
| 32 | + An asynchronous interface for Dune API with a few convenience methods |
| 33 | + combining the use of endpoints (e.g. refresh) |
| 34 | + """ |
| 35 | + |
| 36 | + _connection_limit = 3 |
| 37 | + |
| 38 | + def __init__(self, api_key: str, connection_limit: int = 3): |
| 39 | + """ |
| 40 | + api_key - Dune API key |
| 41 | + connection_limit - number of parallel requests to execute. |
| 42 | + For non-pro accounts Dune allows only up to 3 requests but that number can be increased. |
| 43 | + """ |
| 44 | + super().__init__(api_key=api_key) |
| 45 | + self._connection_limit = connection_limit |
| 46 | + self._session = self._create_session() |
| 47 | + |
| 48 | + def _create_session(self) -> ClientSession: |
| 49 | + conn = TCPConnector(limit=self._connection_limit) |
| 50 | + return ClientSession( |
| 51 | + connector=conn, |
| 52 | + base_url=self.BASE_URL, |
| 53 | + timeout=ClientTimeout(total=self.DEFAULT_TIMEOUT), |
| 54 | + ) |
| 55 | + |
| 56 | + async def close_session(self) -> None: |
| 57 | + """Closes client session""" |
| 58 | + await self._session.close() |
| 59 | + |
| 60 | + async def __aenter__(self) -> None: |
| 61 | + self._session = self._create_session() |
| 62 | + |
| 63 | + async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: |
| 64 | + await self.close_session() |
| 65 | + |
| 66 | + async def _handle_response( |
| 67 | + self, |
| 68 | + response: ClientResponse, |
| 69 | + ) -> Any: |
| 70 | + try: |
| 71 | + # Some responses can be decoded and converted to DuneErrors |
| 72 | + response_json = await response.json() |
| 73 | + self.logger.debug(f"received response {response_json}") |
| 74 | + return response_json |
| 75 | + except ContentTypeError as err: |
| 76 | + # Others can't. Only raise HTTP error for not decodable errors |
| 77 | + response.raise_for_status() |
| 78 | + raise ValueError("Unreachable since previous line raises") from err |
| 79 | + |
| 80 | + async def _get(self, url: str) -> Any: |
| 81 | + self.logger.debug(f"GET received input url={url}") |
| 82 | + response = await self._session.get( |
| 83 | + url=f"{self.API_PATH}{url}", |
| 84 | + headers=self.default_headers(), |
| 85 | + ) |
| 86 | + return await self._handle_response(response) |
| 87 | + |
| 88 | + async def _post(self, url: str, params: Any) -> Any: |
| 89 | + self.logger.debug(f"POST received input url={url}, params={params}") |
| 90 | + response = await self._session.post( |
| 91 | + url=f"{self.API_PATH}{url}", |
| 92 | + json=params, |
| 93 | + headers=self.default_headers(), |
| 94 | + ) |
| 95 | + return await self._handle_response(response) |
| 96 | + |
| 97 | + async def execute(self, query: Query) -> ExecutionResponse: |
| 98 | + """Post's to Dune API for execute `query`""" |
| 99 | + response_json = await self._post( |
| 100 | + url=f"/query/{query.query_id}/execute", |
| 101 | + params=query.request_format(), |
| 102 | + ) |
| 103 | + try: |
| 104 | + return ExecutionResponse.from_dict(response_json) |
| 105 | + except KeyError as err: |
| 106 | + raise DuneError(response_json, "ExecutionResponse", err) from err |
| 107 | + |
| 108 | + async def get_status(self, job_id: str) -> ExecutionStatusResponse: |
| 109 | + """GET status from Dune API for `job_id` (aka `execution_id`)""" |
| 110 | + response_json = await self._get( |
| 111 | + url=f"/execution/{job_id}/status", |
| 112 | + ) |
| 113 | + try: |
| 114 | + return ExecutionStatusResponse.from_dict(response_json) |
| 115 | + except KeyError as err: |
| 116 | + raise DuneError(response_json, "ExecutionStatusResponse", err) from err |
| 117 | + |
| 118 | + async def get_result(self, job_id: str) -> ResultsResponse: |
| 119 | + """GET results from Dune API for `job_id` (aka `execution_id`)""" |
| 120 | + response_json = await self._get(url=f"/execution/{job_id}/results") |
| 121 | + try: |
| 122 | + return ResultsResponse.from_dict(response_json) |
| 123 | + except KeyError as err: |
| 124 | + raise DuneError(response_json, "ResultsResponse", err) from err |
| 125 | + |
| 126 | + async def cancel_execution(self, job_id: str) -> bool: |
| 127 | + """POST Execution Cancellation to Dune API for `job_id` (aka `execution_id`)""" |
| 128 | + response_json = await self._post(url=f"/execution/{job_id}/cancel", params=None) |
| 129 | + try: |
| 130 | + # No need to make a dataclass for this since it's just a boolean. |
| 131 | + success: bool = response_json["success"] |
| 132 | + return success |
| 133 | + except KeyError as err: |
| 134 | + raise DuneError(response_json, "CancellationResponse", err) from err |
| 135 | + |
| 136 | + async def refresh(self, query: Query, ping_frequency: int = 5) -> ResultsResponse: |
| 137 | + """ |
| 138 | + Executes a Dune `query`, waits until execution completes, |
| 139 | + fetches and returns the results. |
| 140 | + Sleeps `ping_frequency` seconds between each status request. |
| 141 | + """ |
| 142 | + job_id = (await self.execute(query)).execution_id |
| 143 | + status = await self.get_status(job_id) |
| 144 | + while status.state not in ExecutionState.terminal_states(): |
| 145 | + self.logger.info( |
| 146 | + f"waiting for query execution {job_id} to complete: {status}" |
| 147 | + ) |
| 148 | + await asyncio.sleep(ping_frequency) |
| 149 | + status = await self.get_status(job_id) |
| 150 | + |
| 151 | + full_response = await self.get_result(job_id) |
| 152 | + if status.state == ExecutionState.FAILED: |
| 153 | + self.logger.error(status) |
| 154 | + raise Exception(f"{status}. Perhaps your query took too long to run!") |
| 155 | + return full_response |
0 commit comments