Skip to content
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

feat: allow configuring the runner class [SBK-233] #29

Merged
merged 10 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ repos:
- id: isort

- repo: https://github.com/psf/black
rev: 22.12.0
rev: 23.7.0
hooks:
- id: black
name: black
Expand All @@ -21,7 +21,7 @@ repos:
- id: flake8

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
rev: v1.4.1
hooks:
- id: mypy
additional_dependencies: [types-setuptools, pydantic]
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"hypothesis>=6.2.0,<7.0", # Strategy-based fuzzer
],
"lint": [
"black>=22.12.0", # auto-formatter and linter
"mypy>=0.991", # Static type analyzer
"black>=23.7.0", # auto-formatter and linter
"mypy>=1.4.1,<2", # Static type analyzer
"types-setuptools", # Needed for mypy type shed
"flake8>=5.0.4", # Style linter
"isort>=5.10.1", # Import sorting linter
Expand Down
48 changes: 36 additions & 12 deletions silverback/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,47 @@ def cli():
"""Work with SilverBack applications in local context (using Ape)."""


def _runner_callback(ctx, param, val):
if not val:
return LiveRunner

elif runner := import_from_string(val):
return runner

raise ValueError(f"Failed to import runner '{val}'.")


def _account_callback(ctx, param, val):
if val:
val = val.alias.replace("dev_", "TEST::")
os.environ["SILVERBACK_SIGNER_ALIAS"] = val

return val


def _network_callback(ctx, param, val):
if val:
os.environ["SILVERBACK_NETWORK_CHOICE"] = val
else:
val = os.environ.get("SILVERBACK_NETWORK_CHOICE", "")

return val


@cli.command()
@ape_cli_context()
@verbosity_option()
@network_option(default=None)
@click.option("--account", type=AccountAliasPromptChoice(), default=None)
@network_option(default=None, callback=_network_callback)
@click.option("--account", type=AccountAliasPromptChoice(), callback=_account_callback)
@click.option(
"--runner",
help="An import str in format '<module>:<CustomRunner>'",
callback=_runner_callback,
)
@click.option("-x", "--max-exceptions", type=int, default=3)
@click.argument("path")
def run(cli_ctx, network, account, max_exceptions, path):
if network:
os.environ["SILVERBACK_NETWORK_CHOICE"] = network
else:
network = os.environ.get("SILVERBACK_NETWORK_CHOICE", "")

if account:
os.environ["SILVERBACK_SIGNER_ALIAS"] = account.alias.replace("dev_", "TEST::")

def run(cli_ctx, network, account, runner, max_exceptions, path):
with cli_ctx.network_manager.parse_network_choice(network):
app = import_from_string(path)
runner = LiveRunner(app, max_exceptions=max_exceptions)
runner = runner(app, max_exceptions=max_exceptions)
asyncio.run(runner.run())
1 change: 1 addition & 0 deletions silverback/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def __init__(self, settings: Optional[Settings] = None):
new_bock_timeout_str = (
f"\n NEW_BLOCK_TIMEOUT={self.new_block_timeout}" if self.new_block_timeout else ""
)

logger.info(
f"Loaded Silverback App:{network_str}"
f"{signer_str}{start_block_str}{new_bock_timeout_str}"
Expand Down
13 changes: 6 additions & 7 deletions silverback/runner.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
from abc import ABC, abstractmethod
from typing import Coroutine

from ape import chain
from ape.contracts import ContractEvent, ContractInstance
Expand Down Expand Up @@ -42,7 +43,7 @@ async def _event_task(
handle an event handler task for the given contract event
"""

async def run(self):
async def run(self, *other_tasks: Coroutine):
await self.app.broker.startup()

if block_handler := self.app.get_block_handler():
Expand All @@ -55,16 +56,14 @@ async def run(self):
if event_handler := self.app.get_event_handler(contract_address, event_name):
tasks.append(self._event_task(contract_event, event_handler))

tasks.extend(other_tasks)
antazoey marked this conversation as resolved.
Show resolved Hide resolved

if len(tasks) == 0:
raise SilverBackException("No tasks to execute")

try:
await asyncio.gather(*tasks)
except Exception as e:
logger.error(f"Critical exception, {type(e).__name__}: {e}")
await asyncio.gather(*tasks)

finally:
await self.app.broker.shutdown()
await self.app.broker.shutdown()


class LiveRunner(BaseRunner):
Expand Down