forked from cowdao-grants/cow-py
-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
#6 breakdown pt2 - add common module #17
Merged
Merged
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does this trailing slash cause issues?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not that we've noticed, but good catch!