forked from cowdao-grants/cow-py
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #17 from bleu-fi/cow-2-core-common
#6 breakdown pt2 - add common module
- Loading branch information
Showing
20 changed files
with
356 additions
and
254 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
from abc import ABC | ||
from typing import Any, Optional | ||
|
||
import httpx | ||
|
||
from cow_py.common.api.decorators import rate_limitted, with_backoff | ||
from cow_py.common.config import SupportedChainId | ||
|
||
Context = dict[str, Any] | ||
|
||
|
||
class APIConfig(ABC): | ||
"""Base class for API configuration with common functionality.""" | ||
|
||
config_map = {} | ||
|
||
def __init__( | ||
self, chain_id: SupportedChainId, base_context: Optional[Context] = None | ||
): | ||
self.chain_id = chain_id | ||
self.context = base_context or {} | ||
|
||
def get_base_url(self) -> str: | ||
return self.config_map.get( | ||
self.chain_id, "default URL if chain_id is not found" | ||
) | ||
|
||
def get_context(self) -> Context: | ||
return {"base_url": self.get_base_url(), **self.context} | ||
|
||
|
||
class RequestStrategy: | ||
async def make_request(self, client, url, method, **request_kwargs): | ||
headers = { | ||
"accept": "application/json", | ||
"content-type": "application/json", | ||
} | ||
|
||
return await client.request( | ||
url=url, headers=headers, method=method, **request_kwargs | ||
) | ||
|
||
|
||
class ResponseAdapter: | ||
async def adapt_response(self, _response): | ||
raise NotImplementedError() | ||
|
||
|
||
class RequestBuilder: | ||
def __init__(self, strategy, response_adapter): | ||
self.strategy = strategy | ||
self.response_adapter = response_adapter | ||
|
||
async def execute(self, client, url, method, **kwargs): | ||
response = await self.strategy.make_request(client, url, method, **kwargs) | ||
return self.response_adapter.adapt_response(response) | ||
|
||
|
||
class JsonResponseAdapter(ResponseAdapter): | ||
def adapt_response(self, response): | ||
if response.headers.get("content-type") == "application/json": | ||
return response.json() | ||
else: | ||
return response.text | ||
|
||
|
||
class ApiBase: | ||
"""Base class for APIs utilizing configuration and request execution.""" | ||
|
||
def __init__(self, config: APIConfig): | ||
self.config = config | ||
|
||
@with_backoff() | ||
@rate_limitted() | ||
async def _fetch(self, path, method="GET", **kwargs): | ||
url = self.config.get_base_url() + path | ||
|
||
del kwargs["context_override"] | ||
|
||
async with httpx.AsyncClient() as client: | ||
builder = RequestBuilder( | ||
RequestStrategy(), | ||
JsonResponseAdapter(), | ||
) | ||
return await builder.execute(client, url, method, **kwargs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import backoff | ||
import httpx | ||
from aiolimiter import AsyncLimiter | ||
|
||
DEFAULT_LIMITER_OPTIONS = {"rate": 5, "per": 1.0} | ||
|
||
DEFAULT_BACKOFF_OPTIONS = { | ||
"max_tries": 10, | ||
"max_time": None, | ||
"jitter": None, | ||
} | ||
|
||
|
||
def dig(self, *keys): | ||
try: | ||
for key in keys: | ||
self = self[key] | ||
return self | ||
except KeyError: | ||
return None | ||
|
||
|
||
def with_backoff(): | ||
def decorator(func): | ||
async def wrapper(*args, **kwargs): | ||
backoff_opts = dig(kwargs, "context_override", "backoff_opts") | ||
|
||
if backoff_opts is None: | ||
internal_backoff_opts = DEFAULT_BACKOFF_OPTIONS | ||
else: | ||
internal_backoff_opts = backoff_opts | ||
|
||
@backoff.on_exception( | ||
backoff.expo, httpx.HTTPStatusError, **internal_backoff_opts | ||
) | ||
async def closure(): | ||
return await func(*args, **kwargs) | ||
|
||
return await closure() | ||
|
||
return wrapper | ||
|
||
return decorator | ||
|
||
|
||
def rate_limitted( | ||
rate=DEFAULT_LIMITER_OPTIONS["rate"], per=DEFAULT_LIMITER_OPTIONS["per"] | ||
): | ||
limiter = AsyncLimiter(rate, per) | ||
|
||
def decorator(func): | ||
async def wrapper(*args, **kwargs): | ||
async with limiter: | ||
return await func(*args, **kwargs) | ||
|
||
return wrapper | ||
|
||
return decorator |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
from cow_py.common.chains import CHAIN_SCANNER_MAP, Chain | ||
from cow_py.common.chains import Chain | ||
|
||
|
||
def get_explorer_link(chain: Chain, tx_hash: str) -> str: | ||
"""Return the scan link for the provided transaction hash.""" | ||
return f"{CHAIN_SCANNER_MAP[chain]}/tx/{tx_hash}" | ||
return f"{chain.explorer_url}/tx/{tx_hash}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.