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

177 upgrade pydantic version #179

Open
wants to merge 43 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
a409433
Migrate to Pydantic v2, update model validation and fix async issues
Antonyjin Oct 4, 2024
660762f
fix: lint tests were failing
Antonyjin Oct 4, 2024
4908fbe
feat: add pyproject-fmt
Psycojoker Sep 25, 2024
e50fabb
fix: run pyproject-fmt
Psycojoker Sep 25, 2024
29b3a1b
Post-SOL fixes (#178)
philogicae Oct 11, 2024
cd2f8e4
Migrate to Pydantic v2, update model validation and fix async issues
Antonyjin Oct 4, 2024
a86da5f
fix: add explicit float type for HTTP_REQUEST_TIMEOUT to comply with …
Antonyjin Oct 15, 2024
fa8e7c8
Fix: Linting tests did not pass:
Antonyjin Oct 15, 2024
706f63a
Merge branch 'main' into 177-upgrade-pydantic-version
Antonyjin Oct 15, 2024
213982b
Fix: Project don't use the good version of aleph-message
Antonyjin Oct 21, 2024
8894347
fix: Wrong aleph-message version
Antonyjin Nov 5, 2024
5674356
Fix: list[str] rise an error in ubuntu 20.04
Antonyjin Nov 5, 2024
00177ae
style: isort
Antonyjin Nov 5, 2024
5028e86
Merge branch 'main' into 177-upgrade-pydantic-version
Antonyjin Nov 26, 2024
afe055d
fix: Hugo comments
Antonyjin Nov 29, 2024
4132ea0
Merge branch 'main' into 177-upgrade-pydantic-version
philogicae Dec 4, 2024
3e88f28
Add pydantic for better mypy tests + Fixes
philogicae Dec 4, 2024
2d0c486
Merge branch 'main' into 177-upgrade-pydantic-version
Antonyjin Jan 15, 2025
c7d3a88
fix: Changing version of aleph-message
Antonyjin Jan 15, 2025
f9bdd3c
style: Missing type for URL
Antonyjin Jan 15, 2025
d1e4e51
style: Missing type for URL
Antonyjin Jan 15, 2025
2c68cd3
fix: Changing version of aleph-message and fix mypy
Antonyjin Jan 21, 2025
ac1b48f
fix: Changing version of aleph-message
Antonyjin Jan 21, 2025
5ce940e
fix: Changing version of pytezos
Antonyjin Jan 21, 2025
7c942c7
Changes for new pricing system (#199)
philogicae Feb 18, 2025
5fdc4a8
Migrate to Pydantic v2, update model validation and fix async issues
Antonyjin Oct 4, 2024
696cf90
fix: lint tests were failing
Antonyjin Oct 4, 2024
5b9148a
Migrate to Pydantic v2, update model validation and fix async issues
Antonyjin Oct 4, 2024
be79a36
Fix: Linting tests did not pass:
Antonyjin Oct 15, 2024
322de8a
fix: Wrong aleph-message version
Antonyjin Nov 5, 2024
bbbdb3f
fix: Hugo comments
Antonyjin Nov 29, 2024
f09f346
Add pydantic for better mypy tests + Fixes
philogicae Dec 4, 2024
cf20656
fix: Changing version of aleph-message
Antonyjin Jan 15, 2025
10f01cd
style: Missing type for URL
Antonyjin Jan 15, 2025
1db00a8
fix: Changing version of aleph-message and fix mypy
Antonyjin Jan 21, 2025
3a18227
fix: Changing version of aleph-message
Antonyjin Jan 21, 2025
dd80a66
Fix: Missing pydantic_core and wrong version of tezos
Antonyjin Feb 25, 2025
1524a3e
Fix: Access to PersistentVolumeSizeMib is incompatible after migratin…
Antonyjin Feb 25, 2025
0a2cff2
Fix: Wrong name given to the variable
Antonyjin Feb 25, 2025
8a23e42
Merge branch 'main' into 177-upgrade-pydantic-version
Antonyjin Feb 25, 2025
2af612f
Style: isort
Antonyjin Feb 25, 2025
bff304f
Merge branch 'main' into 177-upgrade-pydantic-version
Antonyjin Mar 12, 2025
6ded657
Fix: PersistentVolumeSizeMib no longer exist
Antonyjin Mar 14, 2025
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
12 changes: 8 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@ dynamic = [ "version" ]
dependencies = [
"aiohttp>=3.8.3",
"aioresponses>=0.7.6",
"aleph-message>=0.6",
"aleph-message @ git+https://github.com/aleph-im/aleph-message@108-upgrade-pydantic-version#egg=aleph-message",
"aleph-superfluid>=0.2.1",
"base58==2.1.1", # Needed now as default with _load_account changement
"base58==2.1.1", # Needed now as default with _load_account changement
"coincurve; python_version<'3.11'",
"coincurve>=19; python_version>='3.11'",
"eth-abi>=4; python_version>='3.11'",
"eth-typing==4.3.1",
"jwcrypto==1.5.6",
"pynacl==1.5", # Needed now as default with _load_account changement
"pydantic-core>=2",
"pydantic-settings>=2",
"pynacl==1.5", # Needed now as default with _load_account changement
"python-magic",
"typing-extensions",
"web3==6.3",
Expand All @@ -61,7 +63,7 @@ optional-dependencies.encryption = [
"eciespy>=0.3.13; python_version>='3.11'",
]
optional-dependencies.ledger = [
"ledgereth==0.10",
"ledgereth==0.9.1",
]
optional-dependencies.mqtt = [
"aiomqtt<=0.1.3",
Expand Down Expand Up @@ -153,6 +155,8 @@ dependencies = [
"ruff==0.4.8",
"isort==5.13.2",
"pyproject-fmt==2.2.1",
"pydantic-core>=2",
"pydantic-settings>=2",
]
[tool.hatch.envs.linting.scripts]
typing = "mypy --config-file=pyproject.toml {args:} ./src/ ./tests/ ./examples/"
Expand Down
2 changes: 1 addition & 1 deletion src/aleph/sdk/chains/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ async def sign_message(self, message: Dict) -> Dict:
"""
message = self._setup_sender(message)
signature = await self.sign_raw(get_verification_buffer(message))
message["signature"] = signature.hex()
message["signature"] = "0x" + signature.hex()
return message

@abstractmethod
Expand Down
4 changes: 2 additions & 2 deletions src/aleph/sdk/chains/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ async def from_crypto_host(
session = aiohttp.ClientSession(connector=connector)

async with session.get(f"{host}/properties") as response:
response.raise_for_status()
await response.raise_for_status()
data = await response.json()
properties = AccountProperties(**data)

Expand All @@ -75,7 +75,7 @@ def private_key(self):
async def sign_message(self, message: Dict) -> Dict:
"""Sign a message inplace."""
async with self._session.post(f"{self._host}/sign", json=message) as response:
response.raise_for_status()
await response.raise_for_status()
return await response.json()

async def sign_raw(self, buffer: bytes) -> bytes:
Expand Down
18 changes: 9 additions & 9 deletions src/aleph/sdk/client/authenticated_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ async def _broadcast(
url = "/api/v0/messages"
logger.debug(f"Posting message on {url}")

message_dict = message.dict(include=self.BROADCAST_MESSAGE_FIELDS)
message_dict = message.model_dump(include=self.BROADCAST_MESSAGE_FIELDS)
async with self.http_session.post(
url,
json={
Expand Down Expand Up @@ -293,7 +293,7 @@ async def create_post(
)

message, status, _ = await self.submit(
content=content.dict(exclude_none=True),
content=content.model_dump(exclude_none=True),
message_type=MessageType.post,
channel=channel,
allow_inlining=inline,
Expand Down Expand Up @@ -321,7 +321,7 @@ async def create_aggregate(
)

message, status, _ = await self.submit(
content=content_.dict(exclude_none=True),
content=content_.model_dump(exclude_none=True),
message_type=MessageType.aggregate,
channel=channel,
allow_inlining=inline,
Expand Down Expand Up @@ -395,7 +395,7 @@ async def create_store(
content = StoreContent.parse_obj(values)

message, status, _ = await self.submit(
content=content.dict(exclude_none=True),
content=content.model_dump(exclude_none=True),
message_type=MessageType.store,
channel=channel,
allow_inlining=True,
Expand Down Expand Up @@ -449,7 +449,7 @@ async def create_program(
)

message, status, _ = await self.submit(
content=content.dict(exclude_none=True),
content=content.model_dump(exclude_none=True),
message_type=MessageType.program,
channel=channel,
storage_engine=storage_engine,
Expand Down Expand Up @@ -573,7 +573,7 @@ async def forget(
)

message, status, _ = await self.submit(
content=content.dict(exclude_none=True),
content=content.model_dump(exclude_none=True),
message_type=MessageType.forget,
channel=channel,
storage_engine=storage_engine,
Expand Down Expand Up @@ -617,11 +617,11 @@ async def _storage_push_file_with_message(
# Prepare the STORE message
message = await self.generate_signed_message(
message_type=MessageType.store,
content=store_content.dict(exclude_none=True),
content=store_content.model_dump(exclude_none=True),
channel=channel,
)
metadata = {
"message": message.dict(exclude_none=True),
"message": message.model_dump(exclude_none=True),
"sync": sync,
}
data.add_field(
Expand Down Expand Up @@ -665,7 +665,7 @@ async def _upload_file_native(
item_hash=ItemHash(file_hash),
mime_type=mime_type, # type: ignore
time=time.time(),
**extra_fields,
**(extra_fields or {}),
)
message, _ = await self._storage_push_file_with_message(
file_content=file_content,
Expand Down
2 changes: 1 addition & 1 deletion src/aleph/sdk/client/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ async def get_posts(
posts: List[Post] = []
for post_raw in posts_raw:
try:
posts.append(Post.parse_obj(post_raw))
posts.append(Post.model_validate(post_raw))
except ValidationError as e:
if not ignore_invalid_messages:
raise e
Expand Down
2 changes: 1 addition & 1 deletion src/aleph/sdk/client/vm_confidential_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ async def measurement(self, vm_id: ItemHash) -> SEVMeasurement:
status, text = await self.perform_operation(
vm_id, "confidential/measurement", method="GET"
)
sev_measurement = SEVMeasurement.parse_raw(text)
sev_measurement = SEVMeasurement.model_validate_json(text)
return sev_measurement

async def validate_measure(
Expand Down
43 changes: 21 additions & 22 deletions src/aleph/sdk/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import os
from pathlib import Path
from shutil import which
from typing import Dict, Optional, Union
from typing import ClassVar, Dict, List, Optional, Union

from aleph_message.models import Chain
from aleph_message.models.execution.environment import HypervisorType
from pydantic import BaseModel, BaseSettings, Field
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings, SettingsConfigDict

from aleph.sdk.types import ChainInfo

Expand Down Expand Up @@ -41,7 +42,7 @@ class Settings(BaseSettings):
REMOTE_CRYPTO_HOST: Optional[str] = None
REMOTE_CRYPTO_UNIX_SOCKET: Optional[str] = None
ADDRESS_TO_USE: Optional[str] = None
HTTP_REQUEST_TIMEOUT = 15.0
HTTP_REQUEST_TIMEOUT: ClassVar[float] = 15.0

DEFAULT_CHANNEL: str = "ALEPH-CLOUDSOLUTIONS"

Expand Down Expand Up @@ -78,14 +79,14 @@ class Settings(BaseSettings):

CODE_USES_SQUASHFS: bool = which("mksquashfs") is not None # True if command exists

VM_URL_PATH = "https://aleph.sh/vm/{hash}"
VM_URL_HOST = "https://{hash_base32}.aleph.sh"
IPFS_GATEWAY = "https://ipfs.aleph.cloud/ipfs/"
CRN_URL_FOR_PROGRAMS = "https://dchq.staging.aleph.sh/"
VM_URL_PATH: ClassVar[str] = "https://aleph.sh/vm/{hash}"
VM_URL_HOST: ClassVar[str] = "https://{hash_base32}.aleph.sh"
IPFS_GATEWAY: ClassVar[str] = "https://ipfs.aleph.cloud/ipfs/"
CRN_URL_FOR_PROGRAMS: ClassVar[str] = "https://dchq.staging.aleph.sh/"

# Web3Provider settings
TOKEN_DECIMALS = 18
TX_TIMEOUT = 60 * 3
TOKEN_DECIMALS: ClassVar[int] = 18
TX_TIMEOUT: ClassVar[int] = 60 * 3
CHAINS: Dict[Union[Chain, str], ChainInfo] = {
# TESTNETS
"SEPOLIA": ChainInfo(
Expand Down Expand Up @@ -214,16 +215,15 @@ class Settings(BaseSettings):
DEFAULT_CHAIN: Chain = Chain.ETH

# Dns resolver
DNS_IPFS_DOMAIN = "ipfs.public.aleph.sh"
DNS_PROGRAM_DOMAIN = "program.public.aleph.sh"
DNS_INSTANCE_DOMAIN = "instance.public.aleph.sh"
DNS_STATIC_DOMAIN = "static.public.aleph.sh"
DNS_RESOLVERS = ["9.9.9.9", "1.1.1.1"]

class Config:
env_prefix = "ALEPH_"
case_sensitive = False
env_file = ".env"
DNS_IPFS_DOMAIN: ClassVar[str] = "ipfs.public.aleph.sh"
DNS_PROGRAM_DOMAIN: ClassVar[str] = "program.public.aleph.sh"
DNS_INSTANCE_DOMAIN: ClassVar[str] = "instance.public.aleph.sh"
DNS_STATIC_DOMAIN: ClassVar[str] = "static.public.aleph.sh"
DNS_RESOLVERS: ClassVar[List[str]] = ["9.9.9.9", "1.1.1.1"]

model_config = SettingsConfigDict(
env_prefix="ALEPH_", case_sensitive=False, env_file=".env"
)


class MainConfiguration(BaseModel):
Expand All @@ -234,8 +234,7 @@ class MainConfiguration(BaseModel):
path: Path
chain: Chain

class Config:
use_enum_values = True
model_config = SettingsConfigDict(use_enum_values=True)


# Settings singleton
Expand Down Expand Up @@ -291,7 +290,7 @@ def save_main_configuration(file_path: Path, data: MainConfiguration):
Synchronously save a single ChainAccount object as JSON to a file.
"""
with file_path.open("w") as file:
data_serializable = data.dict()
data_serializable = data.model_dump()
data_serializable["path"] = str(data_serializable["path"])
json.dump(data_serializable, file, indent=4)

Expand Down
4 changes: 2 additions & 2 deletions src/aleph/sdk/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ def raise_error(self, status: Dict[str, bool]):
def hostname_from_url(url: Union[HttpUrl, str]) -> Hostname:
"""Extract FQDN from url"""

parsed = urlparse(url)
parsed = urlparse(str(url))
if all([parsed.scheme, parsed.netloc]) is True:
url = parsed.netloc

return Hostname(url)
return Hostname(str(url))


async def get_target_type(fqdn: Hostname) -> Optional[TargetType]:
Expand Down
10 changes: 5 additions & 5 deletions src/aleph/sdk/query/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
ItemType,
MessageConfirmation,
)
from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field


class Post(BaseModel):
Expand Down Expand Up @@ -48,9 +48,9 @@ class Post(BaseModel):
ref: Optional[Union[str, Any]] = Field(
description="Other message referenced by this one"
)
address: Optional[str] = Field(description="Address of the sender")

class Config:
allow_extra = False
model_config = ConfigDict(extra="forbid")


class PaginationResponse(BaseModel):
Expand All @@ -64,14 +64,14 @@ class PostsResponse(PaginationResponse):
"""Response from an aleph.im node API on the path /api/v0/posts.json"""

posts: List[Post]
pagination_item = "posts"
pagination_item: str = "posts"


class MessagesResponse(PaginationResponse):
"""Response from an aleph.im node API on the path /api/v0/messages.json"""

messages: List[AlephMessage]
pagination_item = "messages"
pagination_item: str = "messages"


class PriceResponse(BaseModel):
Expand Down
10 changes: 5 additions & 5 deletions src/aleph/sdk/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from enum import Enum
from typing import Dict, Optional, Protocol, TypeVar

from pydantic import BaseModel
from pydantic import BaseModel, Field

__all__ = ("StorageEnum", "Account", "AccountFromPrivateKey", "GenericMessage")

Expand Down Expand Up @@ -87,10 +87,10 @@ class StoredContent(BaseModel):
A stored content.
"""

filename: Optional[str]
hash: Optional[str]
url: Optional[str]
error: Optional[str]
filename: Optional[str] = Field(default=None)
hash: Optional[str] = Field(default=None)
url: Optional[str] = Field(default=None)
error: Optional[str] = Field(default=None)


class TokenType(str, Enum):
Expand Down
12 changes: 7 additions & 5 deletions src/aleph/sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from uuid import UUID
from zipfile import BadZipFile, ZipFile

import pydantic_core
from aleph_message.models import (
Chain,
InstanceContent,
Expand Down Expand Up @@ -56,14 +57,13 @@
from aleph_message.models.execution.volume import (
MachineVolume,
ParentVolume,
PersistentVolumeSizeMib,
PersistentVolume,
VolumePersistence,
)
from aleph_message.utils import Mebibytes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from jwcrypto.jwa import JWA
from pydantic.json import pydantic_encoder

from aleph.sdk.conf import settings
from aleph.sdk.types import GenericMessage, SEVInfo, SEVMeasurement
Expand Down Expand Up @@ -202,7 +202,7 @@ def extended_json_encoder(obj: Any) -> Any:
elif isinstance(obj, time):
return obj.hour * 3600 + obj.minute * 60 + obj.second + obj.microsecond / 1e6
else:
return pydantic_encoder(obj)
return pydantic_core.to_jsonable_python(obj)


def parse_volume(volume_dict: Union[Mapping, MachineVolume]) -> MachineVolume:
Expand All @@ -213,7 +213,7 @@ def parse_volume(volume_dict: Union[Mapping, MachineVolume]) -> MachineVolume:

for volume_type in get_args(MachineVolume):
try:
return volume_type.parse_obj(volume_dict)
return volume_type.model_validate(volume_dict)
except ValueError:
pass
raise ValueError(f"Could not parse volume: {volume_dict}")
Expand Down Expand Up @@ -503,7 +503,9 @@ def make_instance_content(
ref=ItemHash(rootfs),
use_latest=True,
),
size_mib=PersistentVolumeSizeMib(rootfs_size),
size_mib=PersistentVolume.model_validate(
{"size_mib": rootfs_size}
).size_mib,
persistence=VolumePersistence.host,
),
volumes=[parse_volume(volume) for volume in volumes],
Expand Down
2 changes: 1 addition & 1 deletion src/aleph/sdk/vm/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(
)

self.cache = {}
self.api_host = connector_url if connector_url else settings.API_HOST
self.api_host = str(connector_url) if connector_url else settings.API_HOST

async def get(self, key: str) -> Optional[bytes]:
sanitized_key = sanitize_cache_key(key)
Expand Down
Loading
Loading