Skip to content

Commit

Permalink
Fix missing try/catch on all get_message()
Browse files Browse the repository at this point in the history
  • Loading branch information
philogicae committed Jan 10, 2025
1 parent 9bf025d commit f411ced
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 68 deletions.
27 changes: 19 additions & 8 deletions src/aleph_client/commands/instance/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,23 +282,31 @@ async def create(

# Validate rootfs message exist
async with AlephHttpClient(api_server=settings.API_HOST) as client:
rootfs_message: StoreMessage = await client.get_message(item_hash=rootfs, message_type=StoreMessage)
if not rootfs_message:
rootfs_message: Optional[StoreMessage] = None
try:
rootfs_message = await client.get_message(item_hash=rootfs, message_type=StoreMessage)
except MessageNotFoundError:

Check warning on line 288 in src/aleph_client/commands/instance/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/__init__.py#L288

Added line #L288 was not covered by tests
echo("Given rootfs volume does not exist on aleph.im")
except ForgottenMessageError:
echo("Given rootfs volume has been deleted on aleph.im")

Check warning on line 291 in src/aleph_client/commands/instance/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/__init__.py#L290-L291

Added lines #L290 - L291 were not covered by tests
if not rootfs_message:
raise typer.Exit(code=1)
if rootfs_size is None and rootfs_message.content.size:
rootfs_size = rootfs_message.content.size
elif rootfs_size is None:
rootfs_size = safe_getattr(rootfs_message, "content.size")

Check warning on line 295 in src/aleph_client/commands/instance/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/__init__.py#L295

Added line #L295 was not covered by tests

# Validate confidential firmware message exist
confidential_firmware_as_hash = None
if confidential:
async with AlephHttpClient(api_server=settings.API_HOST) as client:
confidential_firmware_as_hash = ItemHash(confidential_firmware)
firmware_message: StoreMessage = await client.get_message(
item_hash=confidential_firmware, message_type=StoreMessage
)
if not firmware_message:
firmware_message: Optional[StoreMessage] = None
try:
firmware_message = await client.get_message(item_hash=confidential_firmware, message_type=StoreMessage)
except MessageNotFoundError:

Check warning on line 305 in src/aleph_client/commands/instance/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/__init__.py#L305

Added line #L305 was not covered by tests
echo("Confidential Firmware hash does not exist on aleph.im")
except ForgottenMessageError:
echo("Confidential Firmware hash has been deleted on aleph.im")

Check warning on line 308 in src/aleph_client/commands/instance/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/__init__.py#L307-L308

Added lines #L307 - L308 were not covered by tests
if not firmware_message:
raise typer.Exit(code=1)

name = name or validated_prompt("Instance name", lambda x: len(x) < 65)
Expand Down Expand Up @@ -469,6 +477,9 @@ async def create(
f"{account.get_address()} on {account.CHAIN} has {e.available_funds} ALEPH but needs {e.required_funds} ALEPH."
)
raise typer.Exit(code=1)
except Exception as e:
echo(f"Instance creation failed:\n{e}")
raise typer.Exit(code=1)

Check warning on line 482 in src/aleph_client/commands/instance/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/__init__.py#L480-L482

Added lines #L480 - L482 were not covered by tests
if print_message:
echo(f"{message.json(indent=4)}")

Expand Down
13 changes: 12 additions & 1 deletion src/aleph_client/commands/instance/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@
import aiohttp
from aleph.sdk import AlephHttpClient
from aleph.sdk.conf import settings
from aleph.sdk.exceptions import ForgottenMessageError, MessageNotFoundError
from aleph.sdk.utils import safe_getattr
from aleph_message.models import InstanceMessage
from aleph_message.models.execution.base import PaymentType
from aleph_message.models.item_hash import ItemHash
from click import echo
from pydantic import ValidationError
from typer import Exit

from aleph_client.commands import help_strings
from aleph_client.commands.node import NodeInfo, _fetch_nodes
Expand Down Expand Up @@ -141,7 +144,15 @@ async def fetch_vm_info(message: InstanceMessage, node_list: NodeInfo) -> tuple[

async def find_crn_of_vm(vm_id: str) -> Optional[str]:
async with AlephHttpClient(api_server=settings.API_HOST) as client:
message: InstanceMessage = await client.get_message(item_hash=ItemHash(vm_id), message_type=InstanceMessage)
message: Optional[InstanceMessage] = None
try:
message = await client.get_message(item_hash=ItemHash(vm_id), message_type=InstanceMessage)
except MessageNotFoundError:
echo("Instance does not exist on aleph.im")
except ForgottenMessageError:
echo("Instance has been deleted on aleph.im")

Check warning on line 153 in src/aleph_client/commands/instance/network.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/network.py#L150-L153

Added lines #L150 - L153 were not covered by tests
if not message:
raise Exit(code=1)

Check warning on line 155 in src/aleph_client/commands/instance/network.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/instance/network.py#L155

Added line #L155 was not covered by tests
node_list: NodeInfo = await _fetch_nodes()
_, info = await fetch_vm_info(message, node_list)
is_valid = info["crn_url"] not in [help_strings.CRN_PENDING, help_strings.CRN_UNKNOWN]
Expand Down
115 changes: 68 additions & 47 deletions src/aleph_client/commands/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from aleph.sdk import AlephHttpClient, AuthenticatedAlephHttpClient
from aleph.sdk.account import _load_account
from aleph.sdk.conf import settings
from aleph.sdk.exceptions import ForgottenMessageError, MessageNotFoundError
from aleph.sdk.query.filters import MessageFilter
from aleph.sdk.query.responses import MessagesResponse
from aleph.sdk.types import AccountFromPrivateKey, StorageEnum
Expand Down Expand Up @@ -42,13 +43,20 @@ async def get(
item_hash: str = typer.Argument(..., help="Item hash of the message"),
):
async with AlephHttpClient(api_server=settings.API_HOST) as client:
message, status = await client.get_message(item_hash=ItemHash(item_hash), with_status=True)
typer.echo(f"Message Status: {colorized_status(status)}")
if status == MessageStatus.REJECTED:
reason = await client.get_message_error(item_hash=ItemHash(item_hash))
typer.echo(colorful_json(json.dumps(reason, indent=4)))
else:
typer.echo(colorful_message_json(message))
message: Optional[AlephMessage] = None
try:
message, status = await client.get_message(item_hash=ItemHash(item_hash), with_status=True)
except MessageNotFoundError:
typer.echo("Message does not exist on aleph.im")
except ForgottenMessageError:
typer.echo("Message has been forgotten on aleph.im")

Check warning on line 52 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L49-L52

Added lines #L49 - L52 were not covered by tests
if message:
typer.echo(f"Message Status: {colorized_status(status)}")
if status == MessageStatus.REJECTED:
reason = await client.get_message_error(item_hash=ItemHash(item_hash))
typer.echo(colorful_json(json.dumps(reason, indent=4)))

Check warning on line 57 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L56-L57

Added lines #L56 - L57 were not covered by tests
else:
typer.echo(colorful_message_json(message))


@app.command()
Expand Down Expand Up @@ -173,41 +181,47 @@ async def amend(
account: AccountFromPrivateKey = _load_account(private_key, private_key_file)

async with AlephHttpClient(api_server=settings.API_HOST) as client:
existing_message: AlephMessage = await client.get_message(item_hash=item_hash)

editor: str = os.getenv("EDITOR", default="nano")
with tempfile.NamedTemporaryFile(suffix="json") as fd:
# Fill in message template
fd.write(existing_message.content.json(indent=4).encode())
fd.seek(0)

# Launch editor
subprocess.run([editor, fd.name], check=True)

# Read new message
fd.seek(0)
new_content_json = fd.read()

content_type = type(existing_message).__annotations__["content"]
new_content_dict = json.loads(new_content_json)
new_content = content_type(**new_content_dict)

if isinstance(existing_message, ProgramMessage):
new_content.replaces = existing_message.item_hash
else:
new_content.ref = existing_message.item_hash

new_content.time = time.time()
new_content.type = "amend"

typer.echo(new_content)
async with AuthenticatedAlephHttpClient(account=account, api_server=settings.API_HOST) as client:
message, status, response = await client.submit(
content=new_content.dict(),
message_type=existing_message.type,
channel=existing_message.channel,
)
typer.echo(f"{message.json(indent=4)}")
existing_message: Optional[AlephMessage] = None
try:
existing_message = await client.get_message(item_hash=item_hash)
except MessageNotFoundError:
typer.echo("Message does not exist on aleph.im")
except ForgottenMessageError:
typer.echo("Message has been forgotten on aleph.im")

Check warning on line 190 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L184-L190

Added lines #L184 - L190 were not covered by tests
if existing_message:
editor: str = os.getenv("EDITOR", default="nano")
with tempfile.NamedTemporaryFile(suffix="json") as fd:

Check warning on line 193 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L192-L193

Added lines #L192 - L193 were not covered by tests
# Fill in message template
fd.write(existing_message.content.json(indent=4).encode())
fd.seek(0)

Check warning on line 196 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L195-L196

Added lines #L195 - L196 were not covered by tests

# Launch editor
subprocess.run([editor, fd.name], check=True)

Check warning on line 199 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L199

Added line #L199 was not covered by tests

# Read new message
fd.seek(0)
new_content_json = fd.read()

Check warning on line 203 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L202-L203

Added lines #L202 - L203 were not covered by tests

content_type = type(existing_message).__annotations__["content"]
new_content_dict = json.loads(new_content_json)
new_content = content_type(**new_content_dict)

Check warning on line 207 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L205-L207

Added lines #L205 - L207 were not covered by tests

if isinstance(existing_message, ProgramMessage):
new_content.replaces = existing_message.item_hash

Check warning on line 210 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L210

Added line #L210 was not covered by tests
else:
new_content.ref = existing_message.item_hash

Check warning on line 212 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L212

Added line #L212 was not covered by tests

new_content.time = time.time()
new_content.type = "amend"

Check warning on line 215 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L214-L215

Added lines #L214 - L215 were not covered by tests

typer.echo(new_content)
async with AuthenticatedAlephHttpClient(account=account, api_server=settings.API_HOST) as client:
message, status, response = await client.submit(

Check warning on line 219 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L217-L219

Added lines #L217 - L219 were not covered by tests
content=new_content.dict(),
message_type=existing_message.type,
channel=existing_message.channel,
)
typer.echo(f"{message.json(indent=4)}")

Check warning on line 224 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L224

Added line #L224 was not covered by tests


@app.command()
Expand Down Expand Up @@ -241,11 +255,18 @@ async def watch(
setup_logging(debug)

async with AlephHttpClient(api_server=settings.API_HOST) as client:
original: AlephMessage = await client.get_message(item_hash=ref)
async for message in client.watch_messages(
message_filter=MessageFilter(refs=[ref], addresses=[original.content.address])
):
typer.echo(f"{message.json(indent=indent)}")
original: Optional[AlephMessage] = None
try:
original = await client.get_message(item_hash=ref)
except MessageNotFoundError:
typer.echo("Message does not exist on aleph.im")
except ForgottenMessageError:
typer.echo("Message has been forgotten on aleph.im")

Check warning on line 264 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L258-L264

Added lines #L258 - L264 were not covered by tests
if original:
async for message in client.watch_messages(
message_filter=MessageFilter(refs=[ref], addresses=[original.content.address])
):
typer.echo(f"{message.json(indent=indent)}")

Check warning on line 269 in src/aleph_client/commands/message.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/message.py#L269

Added line #L269 was not covered by tests


@app.command()
Expand Down
30 changes: 18 additions & 12 deletions src/aleph_client/commands/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,18 +248,24 @@ async def update(
try:
program_message: ProgramMessage = await client.get_message(item_hash=item_hash, message_type=ProgramMessage)
except MessageNotFoundError:
typer.echo("Program does not exist")
typer.echo("Program does not exist on aleph.im")
return 1
except ForgottenMessageError:
typer.echo("Program has been forgotten")
typer.echo("Program has been deleted on aleph.im")
return 1

Check warning on line 255 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L250-L255

Added lines #L250 - L255 were not covered by tests
if program_message.sender != account.get_address():
typer.echo("You are not the owner of this program")
return 1

Check warning on line 258 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L257-L258

Added lines #L257 - L258 were not covered by tests

code_ref = program_message.content.code.ref
code_message: StoreMessage = await client.get_message(item_hash=code_ref, message_type=StoreMessage)

try:
code_message: StoreMessage = await client.get_message(item_hash=code_ref, message_type=StoreMessage)
except MessageNotFoundError:
typer.echo("Code volume does not exist on aleph.im")
return 1
except ForgottenMessageError:
typer.echo("Code volume has been deleted on aleph.im")
return 1

Check warning on line 268 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L263-L268

Added lines #L263 - L268 were not covered by tests
if encoding != program_message.content.code.encoding:
logger.error(
f"Code must be encoded with the same encoding as the previous version "
Expand Down Expand Up @@ -341,10 +347,10 @@ async def delete(
item_hash=item_hash, message_type=ProgramMessage
)
except MessageNotFoundError:
typer.echo("Program does not exist")
typer.echo("Program does not exist on aleph.im")
return 1
except ForgottenMessageError:
typer.echo("Program already forgotten")
typer.echo("Program has been already deleted on aleph.im")
return 1

Check warning on line 354 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L349-L354

Added lines #L349 - L354 were not covered by tests
if existing_message.sender != account.get_address():
typer.echo("You are not the owner of this program")
Expand All @@ -360,10 +366,10 @@ async def delete(
typer.echo("Code volume does not exist. Skipping...")
return 1
except ForgottenMessageError:
typer.echo("Code volume already forgotten, Skipping...")
typer.echo("Code volume has been already deleted. Skipping...")
return 1

Check warning on line 370 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L365-L370

Added lines #L365 - L370 were not covered by tests
if existing_message.sender != account.get_address():
typer.echo("You are not the owner of this code volume, Skipping...")
typer.echo("You are not the owner of this code volume. Skipping...")
return 1

Check warning on line 373 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L372-L373

Added lines #L372 - L373 were not covered by tests

code_message, _ = await client.forget(
Expand Down Expand Up @@ -515,10 +521,10 @@ async def persist(
try:
message: ProgramMessage = await client.get_message(item_hash=item_hash, message_type=ProgramMessage)
except MessageNotFoundError:
typer.echo("Program does not exist")
typer.echo("Program does not exist on aleph.im")
return None
except ForgottenMessageError:
typer.echo("Program has been forgotten")
typer.echo("Program has been deleted on aleph.im")
return None

Check warning on line 528 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L523-L528

Added lines #L523 - L528 were not covered by tests
if message.sender != account.get_address():
typer.echo("You are not the owner of this program")
Expand Down Expand Up @@ -607,10 +613,10 @@ async def unpersist(
try:
message: ProgramMessage = await client.get_message(item_hash=item_hash, message_type=ProgramMessage)
except MessageNotFoundError:
typer.echo("Program does not exist")
typer.echo("Program does not exist on aleph.im")
return None
except ForgottenMessageError:
typer.echo("Program has been forgotten")
typer.echo("Program has been deleted on aleph.im")
return None

Check warning on line 620 in src/aleph_client/commands/program.py

View check run for this annotation

Codecov / codecov/patch

src/aleph_client/commands/program.py#L615-L620

Added lines #L615 - L620 were not covered by tests
if message.sender != account.get_address():
typer.echo("You are not the owner of this program")
Expand Down

0 comments on commit f411ced

Please sign in to comment.