-
Notifications
You must be signed in to change notification settings - Fork 49
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
Query crawler #686
Draft
kompotkot
wants to merge
3
commits into
main
Choose a base branch
from
crawler-queries-cu
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Query crawler #686
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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,22 @@ | ||
import logging | ||
from typing import Any, Dict | ||
|
||
import boto3 # type: ignore | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def push_data_to_bucket( | ||
data: Any, key: str, bucket: str, metadata: Dict[str, Any] = {} | ||
) -> None: | ||
s3 = boto3.client("s3") | ||
s3.put_object( | ||
Body=data, | ||
Bucket=bucket, | ||
Key=key, | ||
ContentType="application/json", | ||
Metadata=metadata, | ||
) | ||
|
||
logger.info(f"Data pushed to bucket: s3://{bucket}/{key}") |
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.
165 changes: 165 additions & 0 deletions
165
crawlers/mooncrawl/mooncrawl/queries_crawler/actions.py
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,165 @@ | ||
import csv | ||
import json | ||
import logging | ||
import re | ||
import uuid | ||
from datetime import datetime, timezone | ||
from enum import Enum | ||
from io import StringIO | ||
from typing import Any, Dict, List, Optional, Tuple | ||
|
||
from moonstreamdb.db import ( | ||
MOONSTREAM_DB_URI_READ_ONLY, | ||
MOONSTREAM_POOL_SIZE, | ||
create_moonstream_engine, | ||
) | ||
from sqlalchemy.orm import sessionmaker | ||
from sqlalchemy.sql import text | ||
|
||
from ..reporter import reporter | ||
from ..settings import ( | ||
BUGOUT_REQUEST_TIMEOUT_SECONDS, | ||
MOONSTREAM_ADMIN_ACCESS_TOKEN, | ||
MOONSTREAM_QUERIES_JOURNAL_ID, | ||
MOONSTREAM_QUERY_API_DB_STATEMENT_TIMEOUT_MILLIS, | ||
bugout_client, | ||
) | ||
from ..stats_worker.queries import to_json_types | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger(__name__) | ||
|
||
QUERY_REGEX = re.compile("[\[\]@#$%^&?;`/]") | ||
|
||
|
||
class OutputType(Enum): | ||
NONE = None | ||
CSV = "csv" | ||
JSON = "json" | ||
|
||
|
||
class QueryNotValid(Exception): | ||
""" | ||
Raised when query validation not passed. | ||
""" | ||
|
||
|
||
class QueryNotApproved(Exception): | ||
""" | ||
Raised when query not approved | ||
""" | ||
|
||
|
||
def query_validation(query: str) -> str: | ||
""" | ||
Sanitize provided query. | ||
""" | ||
if QUERY_REGEX.search(query) != None: | ||
raise QueryNotValid("Query contains restricted symbols") | ||
|
||
return query | ||
|
||
|
||
def fetch_query_from_journal(query_id: uuid.UUID, allow_not_approved: bool = False): | ||
""" | ||
Fetch query from moonstream-queries journal. | ||
""" | ||
query = bugout_client.get_entry( | ||
token=MOONSTREAM_ADMIN_ACCESS_TOKEN, | ||
journal_id=MOONSTREAM_QUERIES_JOURNAL_ID, | ||
entry_id=query_id, | ||
timeout=BUGOUT_REQUEST_TIMEOUT_SECONDS, | ||
) | ||
|
||
approved = False | ||
for tag in query.tags: | ||
if tag == "approved": | ||
approved = True | ||
if not approved and not allow_not_approved: | ||
raise QueryNotApproved("Query not approved") | ||
|
||
return query | ||
|
||
|
||
def fetch_data_from_db( | ||
query_id: str, | ||
query: str, | ||
params: Optional[Dict[str, Any]] = None, | ||
) -> Tuple[Any, Any]: | ||
""" | ||
Fetch data from moonstream database. | ||
""" | ||
engine = create_moonstream_engine( | ||
MOONSTREAM_DB_URI_READ_ONLY, | ||
pool_pre_ping=True, | ||
pool_size=MOONSTREAM_POOL_SIZE, | ||
statement_timeout=MOONSTREAM_QUERY_API_DB_STATEMENT_TIMEOUT_MILLIS, | ||
) | ||
process_session = sessionmaker(bind=engine) | ||
db_session = process_session() | ||
|
||
time_now = datetime.now(timezone.utc) | ||
|
||
try: | ||
result = db_session.execute(text(query), params) | ||
data_keys = result.keys() | ||
data_rows = result.fetchall() | ||
except Exception as err: | ||
db_session.rollback() | ||
reporter.error_report( | ||
err, | ||
[ | ||
"queries", | ||
"execution", | ||
"db", | ||
f"query_id:{query_id}", | ||
], | ||
) | ||
finally: | ||
db_session.close() | ||
|
||
exec_timedelta = datetime.now(timezone.utc) - time_now | ||
logger.info( | ||
f"Database query finished in {int(exec_timedelta.total_seconds())} seconds" | ||
) | ||
|
||
return data_keys, data_rows | ||
|
||
|
||
def prepare_output( | ||
output_type: OutputType, data_keys: Tuple[Any], data_rows: Tuple[List[Any]] | ||
) -> str: | ||
""" | ||
Parse incoming data from database to proper format OutputType. | ||
""" | ||
|
||
def prepare_dict( | ||
data_temp_keys: Tuple[Any], data_temp_rows: Tuple[List[Any]] | ||
) -> List[Dict[str, Any]]: | ||
output_raw = [] | ||
for row in data_temp_rows: | ||
data_r = {} | ||
for i, k in enumerate(data_temp_keys): | ||
data_r[k] = to_json_types(row[i]) | ||
output_raw.append(data_r) | ||
|
||
return output_raw | ||
|
||
output: Any = None | ||
if output_type.value == "csv": | ||
csv_buffer = StringIO() | ||
csv_writer = csv.writer(csv_buffer, delimiter=";") | ||
|
||
csv_writer.writerow(data_keys) | ||
csv_writer.writerows(data_rows) | ||
|
||
output = csv_buffer.getvalue().encode("utf-8") | ||
elif output_type.value == "json": | ||
output_raw = prepare_dict(data_keys, data_rows) | ||
output = json.dumps(output_raw).encode("utf-8") | ||
elif output_type.value is None: | ||
output = prepare_dict(data_keys, data_rows) | ||
else: | ||
raise Exception("Unsupported output type") | ||
|
||
return output |
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,91 @@ | ||
import argparse | ||
import logging | ||
|
||
from moonstreamdb.blockchain import AvailableBlockchainType | ||
|
||
from ..actions import push_data_to_bucket | ||
from ..settings import MOONSTREAM_S3_DATA_BUCKET, MOONSTREAM_S3_DATA_BUCKET_PREFIX | ||
from .actions import ( | ||
OutputType, | ||
fetch_data_from_db, | ||
fetch_query_from_journal, | ||
prepare_output, | ||
query_validation, | ||
) | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def parser_queries_execute_handler(args: argparse.Namespace) -> None: | ||
""" | ||
Execute query from moonstream-queries journal and push to bucket. | ||
""" | ||
try: | ||
query = fetch_query_from_journal(query_id=args.id, allow_not_approved=False) | ||
if args.id != str(query.id): | ||
raise Exception("Proposed query id is not equal to fetch query (entry id)") | ||
|
||
query_content = query_validation(query.content) | ||
data_keys, data_rows = fetch_data_from_db(query_id=args.id, query=query_content) | ||
|
||
output = prepare_output( | ||
output_type=OutputType(args.output), | ||
data_keys=data_keys, | ||
data_rows=data_rows, | ||
) | ||
|
||
if args.output is not None: | ||
if args.upload: | ||
bucket_metadata = {"source": "queries-crawler"} | ||
push_data_to_bucket( | ||
data=output, | ||
key=f"{MOONSTREAM_S3_DATA_BUCKET_PREFIX}/queries/{str(args.id)}/data.{args.output}", | ||
bucket=MOONSTREAM_S3_DATA_BUCKET, | ||
metadata=bucket_metadata, | ||
) | ||
else: | ||
print(output) | ||
except Exception as e: | ||
logger.error(e) | ||
|
||
|
||
def main() -> None: | ||
parser = argparse.ArgumentParser(description="Moonstream query crawlers CLI") | ||
parser.set_defaults(func=lambda _: parser.print_help()) | ||
subcommands = parser.add_subparsers(description="Query crawlers commands") | ||
|
||
parser_queries_execute = subcommands.add_parser( | ||
"execute", description="Execute query" | ||
) | ||
parser_queries_execute.add_argument( | ||
"-i", | ||
"--id", | ||
required=True, | ||
help="Query id (entry id in moonstream-queries journal)", | ||
) | ||
parser_queries_execute.add_argument( | ||
"-o", | ||
"--output", | ||
default=OutputType.NONE.value, | ||
help=f"Available output types: {[member.value for member in OutputType]}", | ||
) | ||
parser_queries_execute.add_argument( | ||
"-u", | ||
"--upload", | ||
action="store_true", | ||
help="Set this flag to push output into AWS S3 bucket", | ||
) | ||
parser_queries_execute.add_argument( | ||
"--blockchain", | ||
required=True, | ||
help=f"Available blockchain types: {[member.value for member in AvailableBlockchainType]}", | ||
) | ||
parser_queries_execute.set_defaults(func=parser_queries_execute_handler) | ||
|
||
args = parser.parse_args() | ||
args.func(args) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
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
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.
After discussing with @kompotkot and @Andrei-Dolgolev:
We realized that we want this crawler to go through the Query API like any other user would.
The plan is to remove this
mooncrawl/queries_crawler
code and update the Moonstream Python client to provide this functionality similarly to how we used it inautocorns biologist
:https://github.com/bugout-dev/autocorns/blob/cf00fb492de254821730a256d238d5a332810db6/autocorns/biologist.py#L371
We can remove the existing Moonstream Python client, bump the client version, and publish the new client.