Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions api/configs/sample.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export BUGOUT_SPIRE_URL="https://spire.bugout.dev"
export ENTITY_CORS_ALLOWED_ORIGINS="http://localhost:3000,https://moonstream.to,https://www.moonstream.to"
export ENTITY_HUMBUG_REPORTS_BUGOUT_TOKEN="<bugout_access_token_for_humbug_reports>"

# Web3 signature variables
export BUGOUT_APPLICATION_ID_HEADER="x-bugout-application-id"
Expand Down
22 changes: 17 additions & 5 deletions api/entityapi/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,17 @@
from web3 import Web3

from . import data
from .reporter import ExceptionWithReporting

logger = logging.getLogger(__name__)


class UnparsableJournalEntry(ExceptionWithReporting):
"""
Unable to parse journals entry.
"""


def to_json_types(value):
"""
Validate types from source to json types.
Expand All @@ -30,20 +37,23 @@ def to_json_types(value):

def parse_entity_to_entry(
create_entity: data.Entity,
) -> Tuple[str, List[str], Dict[str, Any]]:
) -> Tuple[str, List[str], Dict[str, Any], str]:
"""
Parse Entity create request structure to Bugout journal scheme.
"""
title = f"{create_entity.name}"
tags: List[str] = []
content: Dict[str, Any] = {}

unknown_blockchain_address = ""

for field, vals in create_entity._iter():
if field == "address":
try:
address = Web3.toChecksumAddress(cast(str, vals))
except Exception:
logger.info(f"Unknown type of web3 address {vals}")
logger.info(f"Unknown type of blockchain address {vals}")
unknown_blockchain_address = vals
address = vals
title = f"{address} - {title}"
tags.append(f"{field}:{address}")
Expand Down Expand Up @@ -73,7 +83,7 @@ def parse_entity_to_entry(
for k, v in vals.items():
content[k] = v

return title, tags, content
return title, tags, content, unknown_blockchain_address


def parse_entry_to_entity(
Expand All @@ -88,9 +98,11 @@ def parse_entry_to_entity(
if type(entry) == BugoutJournalEntry:
entity_id = entry.id
else:
raise Exception("Unable to parse entity_id")
raise UnparsableJournalEntry("Unable to parse entry id")
if entry.title is None:
raise Exception(f"Unable to parse entry title")
raise UnparsableJournalEntry(
f"Unable to parse entry title at entry: {str(entry.id)}"
)
name = " - ".join(entry.title.split(" - ")[1:])

address: Optional[str] = None
Expand Down
54 changes: 49 additions & 5 deletions api/entityapi/apps/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from web3login.middlewares.fastapi import AuthorizationCheckMiddleware

from .. import actions, data
from ..reporter import humbug_reporter
from ..settings import (
BUGOUT_APPLICATION_ID_HEADER,
DOCS_TARGET_PATH,
Expand Down Expand Up @@ -151,10 +152,14 @@ async def add_entity_handler(
token = request.state.token
auth_type = request.state.auth_type

unknown_blockchain_address = ""
try:
title, tags, content = actions.parse_entity_to_entry(
create_entity=create_request
)
(
title,
tags,
content,
unknown_blockchain_address,
) = actions.parse_entity_to_entry(create_entity=create_request)

response: BugoutJournalEntry = bc.create_entry(
token=token,
Expand All @@ -173,10 +178,23 @@ async def add_entity_handler(

except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)

if unknown_blockchain_address != "":
humbug_reporter.custom_report(
title="Unknown type of blockchain address",
content=f"Added entity with unknown blockchain addresses "
f"`{unknown_blockchain_address}` to collection `{collection_id}` entity `{response.id}`",
tags=[
f"collection_id:{collection_id}",
f"unknown_blockchain_address:{unknown_blockchain_address}",
],
)

return entity_response


Expand All @@ -193,10 +211,16 @@ async def add_entity_bulk_handler(
token = request.state.token
auth_type = request.state.auth_type

unknown_blockchain_address = ""
try:
create_entries = []
for entity in create_request:
title, tags, content = actions.parse_entity_to_entry(create_entity=entity)
(
title,
tags,
content,
unknown_blockchain_address,
) = actions.parse_entity_to_entry(create_entity=entity)
create_entries.append(
{
"title": title,
Expand All @@ -223,10 +247,22 @@ async def add_entity_bulk_handler(

except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)

if unknown_blockchain_address != "":
humbug_reporter.custom_report(
title="Unknown type of blockchain address - pack",
content=f"Added pack of entities with unknown blockchain addresses to collection `{collection_id}`",
tags=[
f"collection_id:{collection_id}",
f"unknown_blockchain_address:pack",
],
)

return entities_response


Expand Down Expand Up @@ -261,6 +297,8 @@ async def get_entity_handler(

except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)
Expand All @@ -283,7 +321,7 @@ async def update_entity_handler(
auth_type = request.state.auth_type

try:
title, tags, content = actions.parse_entity_to_entry(
title, tags, content, _ = actions.parse_entity_to_entry(
create_entity=update_request
)
response: BugoutJournalEntryContent = bc.update_entry_content(
Expand All @@ -304,6 +342,8 @@ async def update_entity_handler(

except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)
Expand Down Expand Up @@ -340,6 +380,8 @@ async def get_entities_handler(

except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)
Expand Down Expand Up @@ -563,6 +605,8 @@ async def search_entity_handler(

except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)
Expand Down
25 changes: 22 additions & 3 deletions api/entityapi/apps/public.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from fastapi import Body, FastAPI, HTTPException, Path, Query

from .. import actions, data
from ..reporter import humbug_reporter
from ..settings import DOCS_TARGET_PATH
from ..settings import bugout_client as bc
from ..version import VERSION
Expand Down Expand Up @@ -176,10 +177,15 @@ async def add_public_entity_handler(
"""
Create public entity.
"""
unknown_blockchain_address = ""

try:
title, tags, content = actions.parse_entity_to_entry(
create_entity=create_request
)
(
title,
tags,
content,
unknown_blockchain_address,
) = actions.parse_entity_to_entry(create_entity=create_request)

response = bc.create_public_journal_entry(
journal_id=collection_id,
Expand All @@ -194,10 +200,23 @@ async def add_public_entity_handler(
)
except BugoutResponseException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail)
except actions.UnparsableJournalEntry:
raise HTTPException(status_code=500, detail="Unable to form entity")
except Exception as e:
logger.error(e)
raise HTTPException(status_code=500)

if unknown_blockchain_address != "":
humbug_reporter.custom_report(
title="Unknown type of blockchain address",
content=f"Added public entity with unknown blockchain addresses "
f"`{unknown_blockchain_address}` to collection `{collection_id}` entity `{response.id}`",
tags=[
f"collection_id:{collection_id}",
f"unknown_blockchain_address:{unknown_blockchain_address}",
],
)

return entity_response


Expand Down
29 changes: 29 additions & 0 deletions api/entityapi/reporter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import uuid

from humbug.consent import HumbugConsent
from humbug.report import HumbugReporter

from .settings import ENTITY_HUMBUG_REPORTS_BUGOUT_TOKEN
from .version import VERSION

session_id = str(uuid.uuid4())
client_id = "entity-backend"

humbug_consent = HumbugConsent(True)
humbug_reporter = HumbugReporter(
name="entity",
consent=HumbugConsent(True),
client_id=client_id,
session_id=session_id,
bugout_token=ENTITY_HUMBUG_REPORTS_BUGOUT_TOKEN,
tags=[],
)

humbug_version_tag = f"version:{VERSION}"
humbug_tags = [humbug_version_tag]


class ExceptionWithReporting(Exception):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
humbug_reporter.error_report(self, tags=humbug_tags, publish=True)
5 changes: 5 additions & 0 deletions api/entityapi/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,8 @@
MOONSTREAM_APPLICATION_ID = os.environ.get("MOONSTREAM_APPLICATION_ID", "")
if MOONSTREAM_APPLICATION_ID == "":
raise ValueError("MOONSTREAM_APPLICATION_ID environment variable must be set")

# Humbug reporting
ENTITY_HUMBUG_REPORTS_BUGOUT_TOKEN = os.environ.get(
"ENTITY_HUMBUG_REPORTS_BUGOUT_TOKEN"
)
2 changes: 1 addition & 1 deletion api/entityapi/version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.0.5
0.0.6
1 change: 1 addition & 0 deletions api/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
install_requires=[
"bugout>=0.2.5",
"fastapi",
"humbug>=0.2.7",
"psycopg2-binary",
"pydantic",
"sqlalchemy",
Expand Down