-
Notifications
You must be signed in to change notification settings - Fork 45
feat(nano): implement fields module [part 5] #1280
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
Merged
Merged
Changes from all commits
Commits
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 hidden or 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,124 @@ | ||
| # Copyright 2023 Hathor Labs | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from hathor.nanocontracts.exception import BlueprintSyntaxError | ||
| from hathor.nanocontracts.types import NC_FALLBACK_METHOD, NC_INITIALIZE_METHOD, NC_METHOD_TYPE_ATTR, NCMethodType | ||
|
|
||
| FORBIDDEN_NAMES = { | ||
| 'syscall', | ||
| 'log', | ||
| } | ||
|
|
||
| NC_FIELDS_ATTR: str = '__fields' | ||
|
|
||
|
|
||
| class _BlueprintBase(type): | ||
| """Metaclass for blueprints. | ||
|
|
||
| This metaclass will modify the attributes and set Fields to them according to their types. | ||
| """ | ||
|
|
||
| def __new__(cls, name, bases, attrs, **kwargs): | ||
| from hathor.nanocontracts.fields import make_field_for_type | ||
|
|
||
| # Initialize only subclasses of Blueprint. | ||
| parents = [b for b in bases if isinstance(b, _BlueprintBase)] | ||
| if not parents: | ||
| return super().__new__(cls, name, bases, attrs, **kwargs) | ||
|
|
||
| cls._validate_initialize_method(attrs) | ||
| cls._validate_fallback_method(attrs) | ||
| nc_fields = attrs.get('__annotations__', {}) | ||
|
|
||
| # Check for forbidden names. | ||
| for field_name in nc_fields: | ||
| if field_name in FORBIDDEN_NAMES: | ||
| raise BlueprintSyntaxError(f'field name is forbidden: `{field_name}`') | ||
|
|
||
| if field_name.startswith('_'): | ||
| raise BlueprintSyntaxError(f'field name cannot start with underscore: `{field_name}`') | ||
|
|
||
| # Create the fields attribute with the type for each field. | ||
| attrs[NC_FIELDS_ATTR] = nc_fields | ||
|
|
||
| # Use an empty __slots__ to prevent storing any attributes directly on instances. | ||
| # The declared attributes are stored as fields on the class, so they still work despite the empty slots. | ||
| attrs['__slots__'] = tuple() | ||
|
|
||
| # Finally, create class! | ||
| new_class = super().__new__(cls, name, bases, attrs, **kwargs) | ||
|
|
||
| # Create the Field instance according to each type. | ||
| for field_name, field_type in attrs[NC_FIELDS_ATTR].items(): | ||
| value = getattr(new_class, field_name, None) | ||
| if value is None: | ||
| # This is the case when a type is specified but not a value. | ||
| # Example: | ||
| # name: str | ||
| # age: int | ||
| try: | ||
| field = make_field_for_type(field_name, field_type) | ||
| except TypeError: | ||
| raise BlueprintSyntaxError( | ||
| f'unsupported field type `{field_type.__name__}` on field `{field_name}`' | ||
| ) | ||
| setattr(new_class, field_name, field) | ||
| else: | ||
| # This is the case when a value is specified. | ||
| # Example: | ||
| # name: str = StrField() | ||
| # | ||
| # This was not implemented yet and will be extended later. | ||
| raise BlueprintSyntaxError(f'fields with default values are currently not supported: `{field_name}`') | ||
|
|
||
| return new_class | ||
|
|
||
| @staticmethod | ||
| def _validate_initialize_method(attrs: Any) -> None: | ||
| if NC_INITIALIZE_METHOD not in attrs: | ||
| raise BlueprintSyntaxError(f'blueprints require a method called `{NC_INITIALIZE_METHOD}`') | ||
|
|
||
| method = attrs[NC_INITIALIZE_METHOD] | ||
| method_type = getattr(method, NC_METHOD_TYPE_ATTR, None) | ||
|
|
||
| if method_type is not NCMethodType.PUBLIC: | ||
| raise BlueprintSyntaxError(f'`{NC_INITIALIZE_METHOD}` method must be annotated with @public') | ||
|
|
||
| @staticmethod | ||
| def _validate_fallback_method(attrs: Any) -> None: | ||
| if NC_FALLBACK_METHOD not in attrs: | ||
| return | ||
|
|
||
| method = attrs[NC_FALLBACK_METHOD] | ||
| method_type = getattr(method, NC_METHOD_TYPE_ATTR, None) | ||
|
|
||
| if method_type is not NCMethodType.FALLBACK: | ||
| raise BlueprintSyntaxError(f'`{NC_FALLBACK_METHOD}` method must be annotated with @fallback') | ||
|
|
||
|
|
||
| class Blueprint(metaclass=_BlueprintBase): | ||
| """Base class for all blueprints. | ||
|
|
||
| Example: | ||
|
|
||
| class MyBlueprint(Blueprint): | ||
| name: str | ||
| age: int | ||
| """ | ||
|
|
||
| __slots__ = ('__env',) |
This file contains hidden or 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,61 @@ | ||
| # Copyright 2023 Hathor Labs | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from collections import deque | ||
| from typing import TypeVar | ||
|
|
||
| from hathor.nanocontracts.fields.deque_field import DequeField | ||
| from hathor.nanocontracts.fields.dict_field import DictField | ||
| from hathor.nanocontracts.fields.field import Field | ||
| from hathor.nanocontracts.fields.set_field import SetField | ||
| from hathor.nanocontracts.fields.utils import TypeToFieldMap | ||
| from hathor.nanocontracts.nc_types import DEFAULT_TYPE_ALIAS_MAP, DEFAULT_TYPE_TO_NC_TYPE_MAP | ||
| from hathor.nanocontracts.nc_types.utils import TypeAliasMap, TypeToNCTypeMap | ||
|
|
||
| __all__ = [ | ||
| 'DEFAULT_TYPE_TO_FIELD_MAP', | ||
| 'DequeField', | ||
| 'DictField', | ||
| 'Field', | ||
| 'SetField', | ||
| 'TypeToFieldMap', | ||
| 'make_field_for_type', | ||
| ] | ||
|
|
||
| T = TypeVar('T') | ||
|
|
||
| DEFAULT_TYPE_TO_FIELD_MAP: TypeToFieldMap = { | ||
| dict: DictField, | ||
| list: DequeField, # XXX: we should really make a ListField, a deque is different from a list | ||
| set: SetField, | ||
| deque: DequeField, | ||
| # XXX: other types fallback to DEFAULT_TYPE_TO_NC_TYPE_MAP | ||
| } | ||
|
|
||
|
|
||
| def make_field_for_type( | ||
| name: str, | ||
| type_: type[T], | ||
| /, | ||
| *, | ||
| type_field_map: TypeToFieldMap = DEFAULT_TYPE_TO_FIELD_MAP, | ||
| type_nc_type_map: TypeToNCTypeMap = DEFAULT_TYPE_TO_NC_TYPE_MAP, | ||
| type_alias_map: TypeAliasMap = DEFAULT_TYPE_ALIAS_MAP, | ||
| ) -> Field[T]: | ||
| """ Like Field.from_name_and_type, but with default maps. | ||
|
|
||
| Default arguments can't be easily added to NCType.from_type signature because of recursion. | ||
| """ | ||
| type_map = Field.TypeMap(type_alias_map, type_nc_type_map, type_field_map) | ||
| return Field.from_name_and_type(name, type_, type_map=type_map) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For all container fields, review which methods we want to provide. See #1280 (comment)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Postponed thread. |
This file contains hidden or 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,117 @@ | ||
| # Copyright 2025 Hathor Labs | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from abc import ABC, abstractmethod | ||
| from collections.abc import Container | ||
| from typing import Generic, TypeVar | ||
|
|
||
| from typing_extensions import TYPE_CHECKING, Self, override | ||
|
|
||
| from hathor.nanocontracts.fields.field import Field | ||
| from hathor.nanocontracts.storage import NCContractStorage | ||
| from hathor.util import not_none | ||
| from hathor.utils.typing import InnerTypeMixin, get_origin | ||
|
|
||
| if TYPE_CHECKING: | ||
| from hathor.nanocontracts.blueprint import Blueprint | ||
|
|
||
| C = TypeVar('C', bound=Container) | ||
|
|
||
| KEY_SEPARATOR: str = ':' | ||
|
|
||
|
|
||
| class StorageContainer(Generic[C], ABC): | ||
| """ Abstraction over the class that will be returned when accessing a container field. | ||
|
|
||
| Every method and property in this class should use either `__dunder` or `__special__` naming pattern, because | ||
| otherwise the property/method would be accessible from an OCB. Even if there would be no harm, this is generally | ||
| avoided. | ||
| """ | ||
| __slots__ = () | ||
|
|
||
| @classmethod | ||
| @abstractmethod | ||
| def __check_name_and_type__(cls, name: str, type_: type[C]) -> None: | ||
| """Should raise a TypeError if the given name or type is incompatible for use with container.""" | ||
| raise NotImplementedError | ||
|
|
||
| @classmethod | ||
| @abstractmethod | ||
| def __from_name_and_type__( | ||
| cls, | ||
| storage: NCContractStorage, | ||
| name: str, | ||
| type_: type[C], | ||
| /, | ||
| *, | ||
| type_map: Field.TypeMap, | ||
| ) -> Self: | ||
| """Every StorageContainer should be able to be built with this signature. | ||
|
|
||
| Expect a type that has been previously checked with `cls.__check_name_and_type__`. | ||
| """ | ||
| raise NotImplementedError | ||
glevco marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| T = TypeVar('T', bound=StorageContainer) | ||
|
|
||
|
|
||
| class ContainerField(InnerTypeMixin[T], Field[T]): | ||
| """ This class models a Field with a StorageContainer, it can't be set, only accessed as a container. | ||
|
|
||
| This is modeled after a Python descriptor, similar to the built in `property`, see: | ||
|
|
||
| - https://docs.python.org/3/reference/datamodel.html#implementing-descriptors | ||
|
|
||
| The observed value behaves like a container, the specific behavior depends on the container type. | ||
| """ | ||
|
|
||
| __slots__ = ('__name', '__type', '__type_map') | ||
| __name: str | ||
| __type: type[T] | ||
| __type_map: Field.TypeMap | ||
|
|
||
| # XXX: customize InnerTypeMixin behavior so it stores the origin type, since that's what we want | ||
| @classmethod | ||
| def __extract_inner_type__(cls, args: tuple[type, ...], /) -> type[T]: | ||
| inner_type: type[T] = InnerTypeMixin.__extract_inner_type__(args) | ||
| return not_none(get_origin(inner_type)) | ||
|
|
||
| @override | ||
| @classmethod | ||
| def _from_name_and_type(cls, name: str, type_: type[T], /, *, type_map: Field.TypeMap) -> Self: | ||
| if not issubclass(cls.__inner_type__, StorageContainer): | ||
| raise TypeError(f'{cls.__inner_type__} is not a StorageContainer') | ||
| cls.__inner_type__.__check_name_and_type__(name, type_) | ||
| field = cls() | ||
| field.__name = name | ||
| field.__type = type_ | ||
| field.__type_map = type_map | ||
| return field | ||
|
|
||
| @override | ||
| def __set__(self, instance: Blueprint, value: T) -> None: | ||
| # XXX: alternatively this could mimick a `my_container.clear(); my_container.update(value)` | ||
| raise AttributeError('cannot set a container field') | ||
|
|
||
| @override | ||
| def __get__(self, instance: Blueprint, owner: object | None = None) -> T: | ||
| raise NotImplementedError('temporarily removed during nano merge') | ||
|
|
||
| @override | ||
| def __delete__(self, instance: Blueprint) -> None: | ||
| # XXX: alternatively delete the database | ||
| raise AttributeError('cannot delete a container field') | ||
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.
I think we should do this. At least the "backend" implementation (how it maps the exposed interface to the storage) can be exactly the same, but
Dequeis not just the implementation it is the exposed interface, which IMO should be different when only alist(and not adeque), is requested.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.
Postponed thread.