diff --git a/README.md b/README.md index e50e2db8e..614233e2b 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ The SDK provides a number of abstract base components and services (collectively 1. Define all requirements of the resource in `{RESOURCE_NAME}.py` 1. Implement the gRPC service for the new resource in `service.py` 1. Create a gRPC client for the new resource in `client.py` - 1. Register the subtype and define package exports in `__init__.py` + 1. Register the API and define package exports in `__init__.py` 1. Write tests for the new resource and add the resource to `tests.mocks.{components|services}` 1. If the resource is a component, add the component to `examples.server.v1.components` and its corresponding concrete type in `examples.server.v1.server` diff --git a/docs/examples/module_step2.py b/docs/examples/module_step2.py index bd13327bd..2e6ed7f35 100644 --- a/docs/examples/module_step2.py +++ b/docs/examples/module_step2.py @@ -35,7 +35,7 @@ async def close(self): async def main(): - Registry.register_resource_creator(Sensor.SUBTYPE, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new)) + Registry.register_resource_creator(Sensor.API, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new)) if __name__ == "__main__": diff --git a/docs/examples/module_step2_optional.py b/docs/examples/module_step2_optional.py index f4a34edcc..ff7175a04 100644 --- a/docs/examples/module_step2_optional.py +++ b/docs/examples/module_step2_optional.py @@ -57,7 +57,7 @@ async def close(self): async def main(): - Registry.register_resource_creator(Sensor.SUBTYPE, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new, MySensor.validate_config)) + Registry.register_resource_creator(Sensor.API, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new, MySensor.validate_config)) if __name__ == "__main__": diff --git a/docs/examples/module_step3.py b/docs/examples/module_step3.py index d648c51f4..75cdff2a2 100644 --- a/docs/examples/module_step3.py +++ b/docs/examples/module_step3.py @@ -40,10 +40,10 @@ async def main(): This function creates and starts a new module, after adding all desired resource model. Resource creators must be registered to the resource registry before the module adds the resource model. """ - Registry.register_resource_creator(Sensor.SUBTYPE, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new)) + Registry.register_resource_creator(Sensor.API, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new)) module = Module.from_args() - module.add_model_from_registry(Sensor.SUBTYPE, MySensor.MODEL) + module.add_model_from_registry(Sensor.API, MySensor.MODEL) await module.start() diff --git a/examples/complex_module/src/arm/my_arm.py b/examples/complex_module/src/arm/my_arm.py index 0b6f1ce87..00b3000df 100644 --- a/examples/complex_module/src/arm/my_arm.py +++ b/examples/complex_module/src/arm/my_arm.py @@ -115,4 +115,4 @@ async def close(self): LOGGER.info(f"{self.name} is closed.") -Registry.register_resource_creator(Arm.SUBTYPE, MyArm.MODEL, ResourceCreatorRegistration(MyArm.new)) +Registry.register_resource_creator(Arm.API, MyArm.MODEL, ResourceCreatorRegistration(MyArm.new)) diff --git a/examples/complex_module/src/base/my_base.py b/examples/complex_module/src/base/my_base.py index 1b7be83f2..92f7508c3 100644 --- a/examples/complex_module/src/base/my_base.py +++ b/examples/complex_module/src/base/my_base.py @@ -147,4 +147,4 @@ async def get_geometries(self) -> List[Geometry]: raise NotImplementedError() -Registry.register_resource_creator(Base.SUBTYPE, MyBase.MODEL, ResourceCreatorRegistration(MyBase.new, MyBase.validate_config)) +Registry.register_resource_creator(Base.API, MyBase.MODEL, ResourceCreatorRegistration(MyBase.new, MyBase.validate_config)) diff --git a/examples/complex_module/src/gizmo/__init__.py b/examples/complex_module/src/gizmo/__init__.py index e5aada91b..d0e81a3c1 100644 --- a/examples/complex_module/src/gizmo/__init__.py +++ b/examples/complex_module/src/gizmo/__init__.py @@ -1,5 +1,5 @@ """ -This file registers the Gizmo subtype with the Viam Registry, as well as the specific MyGizmo model. +This file registers the Gizmo API with the Viam Registry, as well as the specific MyGizmo model. """ from viam.components.motor import * # noqa: F403 Need to import motor so the component registers itself @@ -7,4 +7,4 @@ from .api import Gizmo, GizmoClient, GizmoService -Registry.register_subtype(ResourceRegistration(Gizmo, GizmoService, lambda name, channel: GizmoClient(name, channel))) +Registry.register_api(ResourceRegistration(Gizmo, GizmoService, lambda name, channel: GizmoClient(name, channel))) diff --git a/examples/complex_module/src/gizmo/api.py b/examples/complex_module/src/gizmo/api.py index 0dda33086..2c5bf64f2 100644 --- a/examples/complex_module/src/gizmo/api.py +++ b/examples/complex_module/src/gizmo/api.py @@ -6,7 +6,7 @@ and the gRPC client that will be able to make calls to this component. In this example, the ``Gizmo`` abstract class defines what functionality is required for all Gizmos. It extends ``ComponentBase``, -as all component types must. It also defines its specific ``SUBTYPE``, which is used internally to keep track of supported types. +as all component types must. It also defines its specific ``API``, which is used internally to keep track of supported types. The ``GizmoService`` implements the gRPC service for the Gizmo. This will allow other robots and clients to make requests of the Gizmo. It extends both from ``GizmoServiceBase`` and ``ResourceRPCServiceBase``. The former is the gRPC service as defined by the proto, @@ -28,7 +28,7 @@ from viam.components.component_base import ComponentBase from viam.components.generic.client import do_command from viam.resource.rpc_service_base import ResourceRPCServiceBase -from viam.resource.types import RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import RESOURCE_TYPE_COMPONENT, API from viam.utils import ValueTypes from ..proto.gizmo_grpc import GizmoServiceBase, GizmoServiceStub @@ -49,7 +49,7 @@ class Gizmo(ComponentBase): """Example component to use with the example module.""" - SUBTYPE: Final = Subtype("acme", RESOURCE_TYPE_COMPONENT, "gizmo") + API: Final = API("acme", RESOURCE_TYPE_COMPONENT, "gizmo") @abc.abstractmethod async def do_one(self, arg1: str, **kwargs) -> bool: diff --git a/examples/complex_module/src/gizmo/my_gizmo.py b/examples/complex_module/src/gizmo/my_gizmo.py index e885c82bf..35a19ea32 100644 --- a/examples/complex_module/src/gizmo/my_gizmo.py +++ b/examples/complex_module/src/gizmo/my_gizmo.py @@ -38,7 +38,7 @@ def validate_config(cls, config: ComponentConfig) -> Sequence[str]: # can raise errors that will be returned to the parent through gRPC. Validate functions can # also return a sequence of strings representing the implicit dependencies of the resource. if "invalid" in config.attributes.fields: - raise Exception(f"'invalid' attribute not allowed for model {cls.SUBTYPE}:{cls.MODEL}") + raise Exception(f"'invalid' attribute not allowed for model {cls.API}:{cls.MODEL}") arg1 = config.attributes.fields["arg1"].string_value if arg1 == "": raise Exception("A arg1 attribute is required for Gizmo component.") @@ -79,4 +79,4 @@ async def close(self): LOGGER.info(f"{self.name} is closed.") -Registry.register_resource_creator(Gizmo.SUBTYPE, MyGizmo.MODEL, ResourceCreatorRegistration(MyGizmo.new, MyGizmo.validate_config)) +Registry.register_resource_creator(Gizmo.API, MyGizmo.MODEL, ResourceCreatorRegistration(MyGizmo.new, MyGizmo.validate_config)) diff --git a/examples/complex_module/src/main.py b/examples/complex_module/src/main.py index da67cb7ed..1974bde57 100644 --- a/examples/complex_module/src/main.py +++ b/examples/complex_module/src/main.py @@ -15,10 +15,10 @@ async def main(): Resource models must be pre-registered. For an example, see the `gizmo.__init__.py` file. """ module = Module.from_args() - module.add_model_from_registry(Gizmo.SUBTYPE, MyGizmo.MODEL) - module.add_model_from_registry(SummationService.SUBTYPE, MySummationService.MODEL) - module.add_model_from_registry(Arm.SUBTYPE, MyArm.MODEL) - module.add_model_from_registry(Base.SUBTYPE, MyBase.MODEL) + module.add_model_from_registry(Gizmo.API, MyGizmo.MODEL) + module.add_model_from_registry(SummationService.API, MySummationService.MODEL) + module.add_model_from_registry(Arm.API, MyArm.MODEL) + module.add_model_from_registry(Base.API, MyBase.MODEL) await module.start() diff --git a/examples/complex_module/src/summation/__init__.py b/examples/complex_module/src/summation/__init__.py index e585041f8..90a61268f 100644 --- a/examples/complex_module/src/summation/__init__.py +++ b/examples/complex_module/src/summation/__init__.py @@ -1,9 +1,9 @@ """ -This file registers the Summation subtype with the Viam Registry, as well as the specific MySummation model. +This file registers the Summation API with the Viam Registry, as well as the specific MySummation model. """ from viam.resource.registry import Registry, ResourceRegistration from .api import SummationClient, SummationRPCService, SummationService -Registry.register_subtype(ResourceRegistration(SummationService, SummationRPCService, lambda name, channel: SummationClient(name, channel))) +Registry.register_api(ResourceRegistration(SummationService, SummationRPCService, lambda name, channel: SummationClient(name, channel))) diff --git a/examples/complex_module/src/summation/api.py b/examples/complex_module/src/summation/api.py index 80a70c631..df11c3aef 100644 --- a/examples/complex_module/src/summation/api.py +++ b/examples/complex_module/src/summation/api.py @@ -7,7 +7,7 @@ In this example, the ``Summation`` abstract class defines what functionality is required for all Summation services. It extends ``ServiceBase``, as all service types must. -It also defines its specific ``SUBTYPE``, which is used internally to keep track of supported types. +It also defines its specific ``API``, which is used internally to keep track of supported types. The ``SummationRPCService`` implements the gRPC service for the Summation service. This will allow other robots and clients to make requests of the Summation service. It extends both from ``SummationServiceBase`` and ``RPCServiceBase``. @@ -27,7 +27,7 @@ from grpclib.server import Stream from viam.resource.rpc_service_base import ResourceRPCServiceBase -from viam.resource.types import RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import RESOURCE_TYPE_SERVICE, API from viam.services.service_base import ServiceBase from ..proto.summation_grpc import SummationServiceBase, SummationServiceStub @@ -37,7 +37,7 @@ class SummationService(ServiceBase): """Example service to use with the example module""" - SUBTYPE: Final = Subtype("acme", RESOURCE_TYPE_SERVICE, "summation") + API: Final = API("acme", RESOURCE_TYPE_SERVICE, "summation") @abc.abstractmethod async def sum(self, nums: Sequence[float]) -> float: diff --git a/examples/complex_module/src/summation/my_summation.py b/examples/complex_module/src/summation/my_summation.py index ff718c932..7eca4f29c 100644 --- a/examples/complex_module/src/summation/my_summation.py +++ b/examples/complex_module/src/summation/my_summation.py @@ -45,4 +45,4 @@ def reconfigure(self, config: ComponentConfig, dependencies: Mapping[ResourceNam self.subtract = config.attributes.fields["subtract"].bool_value or False -Registry.register_resource_creator(SummationService.SUBTYPE, MySummationService.MODEL, ResourceCreatorRegistration(MySummationService.new)) +Registry.register_resource_creator(SummationService.API, MySummationService.MODEL, ResourceCreatorRegistration(MySummationService.new)) diff --git a/examples/simple_module/src/main.py b/examples/simple_module/src/main.py index b7b0a2a99..0af1d44c7 100644 --- a/examples/simple_module/src/main.py +++ b/examples/simple_module/src/main.py @@ -63,10 +63,10 @@ async def main(): """This function creates and starts a new module, after adding all desired resource models. Resource creators must be registered to the resource registry before the module adds the resource model. """ - Registry.register_resource_creator(Sensor.SUBTYPE, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new, MySensor.validate_config)) + Registry.register_resource_creator(Sensor.API, MySensor.MODEL, ResourceCreatorRegistration(MySensor.new, MySensor.validate_config)) module = Module.from_args() - module.add_model_from_registry(Sensor.SUBTYPE, MySensor.MODEL) + module.add_model_from_registry(Sensor.API, MySensor.MODEL) await module.start() diff --git a/src/viam/app/data_client.py b/src/viam/app/data_client.py index 723aa39dc..5eb96b6aa 100644 --- a/src/viam/app/data_client.py +++ b/src/viam/app/data_client.py @@ -158,8 +158,8 @@ class TabularDataPoint: resource_name: str """The resource name""" - resource_subtype: str - """The resource subtype. Ex: `rdk:component:sensor`""" + resource_api: str + """The resource API. Ex: `rdk:component:sensor`""" method_name: str """The method used for data capture. Ex: `Readings`""" @@ -196,7 +196,7 @@ def __str__(self) -> str: f"TabularDataPoint(" f"robot='{self.robot_name}' (id={self.robot_id}), " f"part='{self.part_name}' (id={self.part_id}), " - f"resource='{self.resource_name}' ({self.resource_subtype}), " + f"resource='{self.resource_name}' ({self.resource_api}), " f"method='{self.method_name}', " f"org={self.organization_id}, " f"location={self.location_id}, " @@ -211,6 +211,15 @@ def __eq__(self, other: object) -> bool: return str(self) == str(other) return False + @property + def resource_subtype(self) -> str: + warnings.warn( + "`TabularDataPoint.resource_subtype` is deprecated. Use `TabularDataPoint.resource_api` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.resource_api + def __init__(self, channel: Channel, metadata: Mapping[str, str]): """Create a `DataClient` that maintains a connection to app. @@ -367,8 +376,9 @@ async def tabular_data_by_mql( response: TabularDataByMQLResponse = await self._data_client.TabularDataByMQL(request, metadata=self._metadata) return [bson.decode(bson_bytes) for bson_bytes in response.raw_data] + @_alias_param("resource_api", param_alias="resource_subtype") async def get_latest_tabular_data( - self, part_id: str, resource_name: str, resource_subtype: str, method_name: str + self, part_id: str, resource_name: str, resource_api: str, method_name: str ) -> Optional[Tuple[datetime, datetime, Dict[str, ValueTypes]]]: """Gets the most recent tabular data captured from the specified data source, as long as it was synced within the last year. @@ -377,7 +387,7 @@ async def get_latest_tabular_data( tabular_data = await data_client.get_latest_tabular_data( part_id="77ae3145-7b91-123a-a234-e567cdca8910", resource_name="camera-1", - resource_subtype="rdk:component:camera", + resource_api="rdk:component:camera", method_name="GetImage" ) @@ -392,7 +402,7 @@ async def get_latest_tabular_data( Args: part_id (str): The ID of the part that owns the data. resource_name (str): The name of the requested resource that captured the data. Ex: "my-sensor". - resource_subtype (str): The subtype of the requested resource that captured the data. Ex: "rdk:component:sensor". + resource_api (str): The API of the requested resource that captured the data. Ex: "rdk:component:sensor". method_name (str): The data capture method name. Ex: "Readings". Returns: @@ -406,18 +416,19 @@ async def get_latest_tabular_data( """ request = GetLatestTabularDataRequest( - part_id=part_id, resource_name=resource_name, resource_subtype=resource_subtype, method_name=method_name + part_id=part_id, resource_name=resource_name, resource_subtype=resource_api, method_name=method_name ) response: GetLatestTabularDataResponse = await self._data_client.GetLatestTabularData(request, metadata=self._metadata) if not response.payload: return None return response.time_captured.ToDatetime(), response.time_synced.ToDatetime(), struct_to_dict(response.payload) + @_alias_param("resource_api", param_alias="resource_subtype") async def export_tabular_data( self, part_id: str, resource_name: str, - resource_subtype: str, + resource_api: str, method_name: str, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, @@ -429,7 +440,7 @@ async def export_tabular_data( tabular_data = await data_client.export_tabular_data( part_id="", resource_name="", - resource_subtype="", + resource_api="", method_name="", start_time="" end_time="" @@ -440,7 +451,7 @@ async def export_tabular_data( Args: part_id (str): The ID of the part that owns the data. resource_name (str): The name of the requested resource that captured the data. - resource_subtype (str): The subtype of the requested resource that captured the data. + resource_api (str): The API of the requested resource that captured the data. method_name (str): The data capture method name. start_time (datetime): Optional start time for requesting a specific range of data. end_time (datetime): Optional end time for requesting a specific range of data. @@ -453,7 +464,7 @@ async def export_tabular_data( interval = CaptureInterval(start=datetime_to_timestamp(start_time), end=datetime_to_timestamp(end_time)) request = ExportTabularDataRequest( - part_id=part_id, resource_name=resource_name, resource_subtype=resource_subtype, method_name=method_name, interval=interval + part_id=part_id, resource_name=resource_name, resource_subtype=resource_api, method_name=method_name, interval=interval ) response: List[ExportTabularDataResponse] = await self._data_client.ExportTabularData(request, metadata=self._metadata) @@ -461,7 +472,7 @@ async def export_tabular_data( DataClient.TabularDataPoint( part_id=resp.part_id, resource_name=resp.resource_name, - resource_subtype=resp.resource_subtype, + resource_api=resp.resource_subtype, method_name=resp.method_name, time_captured=resp.time_captured.ToDatetime(), organization_id=resp.organization_id, diff --git a/src/viam/components/arm/__init__.py b/src/viam/components/arm/__init__.py index 98c1e3416..60278e410 100644 --- a/src/viam/components/arm/__init__.py +++ b/src/viam/components/arm/__init__.py @@ -13,4 +13,4 @@ "Pose", ] -Registry.register_subtype(ResourceRegistration(Arm, ArmRPCService, lambda name, channel: ArmClient(name, channel))) +Registry.register_api(ResourceRegistration(Arm, ArmRPCService, lambda name, channel: ArmClient(name, channel))) diff --git a/src/viam/components/arm/arm.py b/src/viam/components/arm/arm.py index 7d80cf2ca..a61d52136 100644 --- a/src/viam/components/arm/arm.py +++ b/src/viam/components/arm/arm.py @@ -1,7 +1,7 @@ import abc from typing import Any, Dict, Final, Optional, Tuple -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase from . import JointPositions, KinematicsFileFormat, Pose @@ -26,7 +26,7 @@ class Arm(ComponentBase): For more information, see `Arm component `_. """ - SUBTYPE: Final = Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm") # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm") # pyright: ignore [reportIncompatibleVariableOverride] @abc.abstractmethod async def get_end_position( diff --git a/src/viam/components/audio_input/__init__.py b/src/viam/components/audio_input/__init__.py index 457fa34c9..70bfcfc97 100644 --- a/src/viam/components/audio_input/__init__.py +++ b/src/viam/components/audio_input/__init__.py @@ -9,7 +9,7 @@ ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( AudioInput, AudioInputRPCService, diff --git a/src/viam/components/audio_input/audio_input.py b/src/viam/components/audio_input/audio_input.py index 2c61ade0b..f48d31f46 100644 --- a/src/viam/components/audio_input/audio_input.py +++ b/src/viam/components/audio_input/audio_input.py @@ -8,7 +8,7 @@ from viam.media.audio import Audio, AudioStream from viam.proto.component.audioinput import PropertiesResponse -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from viam.streams import StreamSource from ..component_base import ComponentBase @@ -22,7 +22,7 @@ class AudioInput(ComponentBase, StreamSource[Audio]): overridden, it must call the ``super().__init__()`` function. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "audio_input" ) diff --git a/src/viam/components/base/__init__.py b/src/viam/components/base/__init__.py index 5ab6a3ce0..4641c5bd8 100644 --- a/src/viam/components/base/__init__.py +++ b/src/viam/components/base/__init__.py @@ -10,4 +10,4 @@ "Vector3", ] -Registry.register_subtype(ResourceRegistration(Base, BaseRPCService, lambda name, channel: BaseClient(name, channel))) +Registry.register_api(ResourceRegistration(Base, BaseRPCService, lambda name, channel: BaseClient(name, channel))) diff --git a/src/viam/components/base/base.py b/src/viam/components/base/base.py index a7f56da25..11973405d 100644 --- a/src/viam/components/base/base.py +++ b/src/viam/components/base/base.py @@ -2,7 +2,7 @@ from dataclasses import dataclass from typing import Any, Dict, Final, Optional -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase from . import Vector3 @@ -23,7 +23,7 @@ class Base(ComponentBase): For more information, see `Base component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "base" ) diff --git a/src/viam/components/board/__init__.py b/src/viam/components/board/__init__.py index bd410a555..0ce67448e 100644 --- a/src/viam/components/board/__init__.py +++ b/src/viam/components/board/__init__.py @@ -6,4 +6,4 @@ __all__ = ["Board", "Tick", "TickStream"] -Registry.register_subtype(ResourceRegistration(Board, BoardRPCService, lambda name, channel: BoardClient(name, channel))) +Registry.register_api(ResourceRegistration(Board, BoardRPCService, lambda name, channel: BoardClient(name, channel))) diff --git a/src/viam/components/board/board.py b/src/viam/components/board/board.py index 62b57d707..fa0295e6a 100644 --- a/src/viam/components/board/board.py +++ b/src/viam/components/board/board.py @@ -4,7 +4,7 @@ from typing import Any, Dict, Final, List, Optional from viam.proto.component.board import PowerMode, ReadAnalogReaderResponse, StreamTicksResponse -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from viam.streams import Stream from ..component_base import ComponentBase @@ -34,7 +34,7 @@ class Board(ComponentBase): For more information, see `Board component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "board" ) diff --git a/src/viam/components/camera/__init__.py b/src/viam/components/camera/__init__.py index c4c4ff8e8..578ddf262 100644 --- a/src/viam/components/camera/__init__.py +++ b/src/viam/components/camera/__init__.py @@ -13,7 +13,7 @@ "ViamImage", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( Camera, CameraRPCService, diff --git a/src/viam/components/camera/camera.py b/src/viam/components/camera/camera.py index f9491d5b6..1b530f65f 100644 --- a/src/viam/components/camera/camera.py +++ b/src/viam/components/camera/camera.py @@ -5,7 +5,7 @@ from viam.media.video import NamedImage, ViamImage from viam.proto.common import ResponseMetadata from viam.proto.component.camera import GetPropertiesResponse -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -30,7 +30,7 @@ class Camera(ComponentBase): For more information, see `Camera component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "camera" ) diff --git a/src/viam/components/component_base.py b/src/viam/components/component_base.py index 786bead58..728b80761 100644 --- a/src/viam/components/component_base.py +++ b/src/viam/components/component_base.py @@ -10,7 +10,7 @@ from viam.resource.base import ResourceBase if TYPE_CHECKING: - from viam.resource.types import Subtype + from viam.resource.types import API from viam.robot.client import RobotClient @@ -23,11 +23,11 @@ class ComponentBase(abc.ABC, ResourceBase): All components must inherit from this class. """ - SUBTYPE: ClassVar["Subtype"] + API: ClassVar["API"] def __init__(self, name: str, *, logger: Optional[Logger] = None): self.name = name - self.logger = logger if logger is not None else getLogger(f"{self.SUBTYPE}.{name}") + self.logger = logger if logger is not None else getLogger(f"{self.API}.{name}") @classmethod def from_robot(cls, robot: "RobotClient", name: str) -> Self: diff --git a/src/viam/components/encoder/__init__.py b/src/viam/components/encoder/__init__.py index c885d409b..06173a0ec 100644 --- a/src/viam/components/encoder/__init__.py +++ b/src/viam/components/encoder/__init__.py @@ -9,7 +9,7 @@ ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( Encoder, EncoderRPCService, diff --git a/src/viam/components/encoder/encoder.py b/src/viam/components/encoder/encoder.py index bad6fe17c..aa6ea3403 100644 --- a/src/viam/components/encoder/encoder.py +++ b/src/viam/components/encoder/encoder.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Final, Optional, Tuple from viam.proto.component.encoder import PositionType -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -28,7 +28,7 @@ class Properties: For more information, see `Encoder component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "encoder" ) diff --git a/src/viam/components/gantry/__init__.py b/src/viam/components/gantry/__init__.py index 536b82015..a829e33e6 100644 --- a/src/viam/components/gantry/__init__.py +++ b/src/viam/components/gantry/__init__.py @@ -8,4 +8,4 @@ "Gantry", ] -Registry.register_subtype(ResourceRegistration(Gantry, GantryRPCService, lambda name, channel: GantryClient(name, channel))) +Registry.register_api(ResourceRegistration(Gantry, GantryRPCService, lambda name, channel: GantryClient(name, channel))) diff --git a/src/viam/components/gantry/gantry.py b/src/viam/components/gantry/gantry.py index c8ef7dc56..865b09e91 100644 --- a/src/viam/components/gantry/gantry.py +++ b/src/viam/components/gantry/gantry.py @@ -1,7 +1,7 @@ import abc from typing import Any, Dict, Final, List, Optional -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -21,7 +21,7 @@ class Gantry(ComponentBase): For more information, see `Gantry component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "gantry" ) diff --git a/src/viam/components/generic/__init__.py b/src/viam/components/generic/__init__.py index a199d1af7..c5799942c 100644 --- a/src/viam/components/generic/__init__.py +++ b/src/viam/components/generic/__init__.py @@ -9,7 +9,7 @@ "Generic", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( Generic, GenericRPCService, diff --git a/src/viam/components/generic/generic.py b/src/viam/components/generic/generic.py index bb2fe785d..72de64e96 100644 --- a/src/viam/components/generic/generic.py +++ b/src/viam/components/generic/generic.py @@ -1,6 +1,6 @@ from typing import Final -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -71,6 +71,6 @@ def complex_command(self, arg1, arg2, arg3): For more information, see `Gantry component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "generic" ) diff --git a/src/viam/components/gripper/__init__.py b/src/viam/components/gripper/__init__.py index 22d3869ee..6da00cfcd 100644 --- a/src/viam/components/gripper/__init__.py +++ b/src/viam/components/gripper/__init__.py @@ -8,4 +8,4 @@ "Gripper", ] -Registry.register_subtype(ResourceRegistration(Gripper, GripperRPCService, lambda name, channel: GripperClient(name, channel))) +Registry.register_api(ResourceRegistration(Gripper, GripperRPCService, lambda name, channel: GripperClient(name, channel))) diff --git a/src/viam/components/gripper/gripper.py b/src/viam/components/gripper/gripper.py index f6f97e43d..286c2eeef 100644 --- a/src/viam/components/gripper/gripper.py +++ b/src/viam/components/gripper/gripper.py @@ -2,7 +2,7 @@ from typing import Any, Dict, Final, Optional from viam.components.component_base import ComponentBase -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT class Gripper(ComponentBase): @@ -20,7 +20,7 @@ class Gripper(ComponentBase): For more information, see `Gripper component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "gripper" ) diff --git a/src/viam/components/input/__init__.py b/src/viam/components/input/__init__.py index 6e94ee2dd..7994deb22 100644 --- a/src/viam/components/input/__init__.py +++ b/src/viam/components/input/__init__.py @@ -12,6 +12,4 @@ "EventType", ] -Registry.register_subtype( - ResourceRegistration(Controller, InputControllerRPCService, lambda name, channel: ControllerClient(name, channel)) -) +Registry.register_api(ResourceRegistration(Controller, InputControllerRPCService, lambda name, channel: ControllerClient(name, channel))) diff --git a/src/viam/components/input/input.py b/src/viam/components/input/input.py index 92523b7a4..963a724d5 100644 --- a/src/viam/components/input/input.py +++ b/src/viam/components/input/input.py @@ -10,7 +10,7 @@ from viam.components.component_base import ComponentBase from viam.errors import NotSupportedError from viam.proto.component.inputcontroller import Event as PBEvent -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT class EventType(str, Enum): @@ -143,7 +143,7 @@ class Controller(ComponentBase): For more information, see `Input Controller component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "input_controller" ) diff --git a/src/viam/components/motor/__init__.py b/src/viam/components/motor/__init__.py index 794206adf..7e4885d67 100644 --- a/src/viam/components/motor/__init__.py +++ b/src/viam/components/motor/__init__.py @@ -8,4 +8,4 @@ "Motor", ] -Registry.register_subtype(ResourceRegistration(Motor, MotorRPCService, lambda name, channel: MotorClient(name, channel))) +Registry.register_api(ResourceRegistration(Motor, MotorRPCService, lambda name, channel: MotorClient(name, channel))) diff --git a/src/viam/components/motor/motor.py b/src/viam/components/motor/motor.py index 7c178bd9a..1a350eab1 100644 --- a/src/viam/components/motor/motor.py +++ b/src/viam/components/motor/motor.py @@ -2,7 +2,7 @@ from dataclasses import dataclass from typing import Any, Dict, Final, Optional, Tuple -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -25,7 +25,7 @@ class Motor(ComponentBase): class Properties: position_reporting: bool - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "motor" ) diff --git a/src/viam/components/movement_sensor/__init__.py b/src/viam/components/movement_sensor/__init__.py index e934b5fc0..042c0d3cd 100644 --- a/src/viam/components/movement_sensor/__init__.py +++ b/src/viam/components/movement_sensor/__init__.py @@ -12,7 +12,7 @@ "Vector3", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( MovementSensor, MovementSensorRPCService, diff --git a/src/viam/components/movement_sensor/movement_sensor.py b/src/viam/components/movement_sensor/movement_sensor.py index 1239724d9..214453634 100644 --- a/src/viam/components/movement_sensor/movement_sensor.py +++ b/src/viam/components/movement_sensor/movement_sensor.py @@ -7,7 +7,7 @@ from viam.components.component_base import ComponentBase from viam.proto.component.movementsensor import GetAccuracyResponse, GetPropertiesResponse -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from viam.utils import SensorReading from . import GeoPoint, Orientation, Vector3 @@ -31,7 +31,7 @@ class MovementSensor(ComponentBase): For more information, see `Movement Sensor component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "movement_sensor" ) diff --git a/src/viam/components/pose_tracker/__init__.py b/src/viam/components/pose_tracker/__init__.py index 15c64bf45..90af107b4 100644 --- a/src/viam/components/pose_tracker/__init__.py +++ b/src/viam/components/pose_tracker/__init__.py @@ -8,7 +8,7 @@ "PoseTracker", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( PoseTracker, PoseTrackerRPCService, diff --git a/src/viam/components/pose_tracker/pose_tracker.py b/src/viam/components/pose_tracker/pose_tracker.py index ca0b70843..29329d59a 100644 --- a/src/viam/components/pose_tracker/pose_tracker.py +++ b/src/viam/components/pose_tracker/pose_tracker.py @@ -2,7 +2,7 @@ from typing import Any, Dict, Final, List, Mapping, Optional from viam.proto.common import PoseInFrame -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -16,7 +16,7 @@ class PoseTracker(ComponentBase): overridden, it must call the ``super().__init__()`` function. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "pose_tracker" ) diff --git a/src/viam/components/power_sensor/__init__.py b/src/viam/components/power_sensor/__init__.py index 9df79eedc..e23c782ef 100644 --- a/src/viam/components/power_sensor/__init__.py +++ b/src/viam/components/power_sensor/__init__.py @@ -8,7 +8,7 @@ "PowerSensor", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( PowerSensor, PowerSensorRPCService, diff --git a/src/viam/components/power_sensor/power_sensor.py b/src/viam/components/power_sensor/power_sensor.py index d936bb9f7..2fd47023d 100644 --- a/src/viam/components/power_sensor/power_sensor.py +++ b/src/viam/components/power_sensor/power_sensor.py @@ -2,7 +2,7 @@ from typing import Any, Dict, Final, Mapping, Optional, Tuple from viam.components.component_base import ComponentBase -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from viam.utils import SensorReading @@ -19,7 +19,7 @@ class PowerSensor(ComponentBase): For more information, see `Power Sensor component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "power_sensor" ) diff --git a/src/viam/components/sensor/__init__.py b/src/viam/components/sensor/__init__.py index 716276aa4..264aa1797 100644 --- a/src/viam/components/sensor/__init__.py +++ b/src/viam/components/sensor/__init__.py @@ -9,7 +9,7 @@ "Sensor", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( Sensor, SensorRPCService, diff --git a/src/viam/components/sensor/sensor.py b/src/viam/components/sensor/sensor.py index 08a35e361..674662666 100644 --- a/src/viam/components/sensor/sensor.py +++ b/src/viam/components/sensor/sensor.py @@ -1,7 +1,7 @@ import abc from typing import Any, Final, Mapping, Optional -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from viam.utils import SensorReading from ..component_base import ComponentBase @@ -22,7 +22,7 @@ class Sensor(ComponentBase): For more information, see `Sensor component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "sensor" ) diff --git a/src/viam/components/servo/__init__.py b/src/viam/components/servo/__init__.py index 79db2f1a5..09104152a 100644 --- a/src/viam/components/servo/__init__.py +++ b/src/viam/components/servo/__init__.py @@ -8,4 +8,4 @@ "Servo", ] -Registry.register_subtype(ResourceRegistration(Servo, ServoRPCService, lambda name, channel: ServoClient(name, channel))) +Registry.register_api(ResourceRegistration(Servo, ServoRPCService, lambda name, channel: ServoClient(name, channel))) diff --git a/src/viam/components/servo/servo.py b/src/viam/components/servo/servo.py index 532145de5..c40d4de87 100644 --- a/src/viam/components/servo/servo.py +++ b/src/viam/components/servo/servo.py @@ -1,7 +1,7 @@ import abc from typing import Any, Final, Mapping, Optional -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from ..component_base import ComponentBase @@ -21,7 +21,7 @@ class Servo(ComponentBase): For more information, see `Servo component `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "servo" ) diff --git a/src/viam/logging.py b/src/viam/logging.py index b8ce5c87a..f67cf8bd3 100644 --- a/src/viam/logging.py +++ b/src/viam/logging.py @@ -83,7 +83,7 @@ async def handle_task_result(self, task: asyncio.Task): def emit(self, record: logging.LogRecord): assert isinstance(record, logging.LogRecord) - # Fully qualified name of form "{subtype triplet}/{name}", e.g. "rdk:component:arm/myarm" + # Fully qualified name of form "{API triplet}/{name}", e.g. "rdk:component:arm/myarm" name = record.name.replace(".", "/") message = f"{record.filename}:{record.lineno}\t{record.getMessage()}" stack = f"exc_info: {record.exc_info}, exc_text: {record.exc_text}, stack_info: {record.stack_info}" diff --git a/src/viam/module/module.py b/src/viam/module/module.py index 5748534ae..22401722e 100644 --- a/src/viam/module/module.py +++ b/src/viam/module/module.py @@ -27,7 +27,7 @@ from viam.proto.robot import ResourceRPCSubtype from viam.resource.base import ResourceBase from viam.resource.registry import Registry -from viam.resource.types import RESOURCE_TYPE_COMPONENT, RESOURCE_TYPE_SERVICE, Model, ResourceName, Subtype, resource_name_from_string +from viam.resource.types import API, RESOURCE_TYPE_COMPONENT, RESOURCE_TYPE_SERVICE, Model, ResourceName, resource_name_from_string from viam.robot.client import RobotClient from viam.rpc.dial import DialOptions from viam.rpc.server import Server @@ -83,7 +83,7 @@ async def run_with_models(cls, *models: ResourceBase): for model in models: if not hasattr(model, "MODEL"): raise TypeError(f"missing MODEL field on {model}. Resource implementations must define MODEL") - module.add_model_from_registry(model.SUBTYPE, model.MODEL) # pyright: ignore [reportAttributeAccessIssue] + module.add_model_from_registry(model.API, model.MODEL) # pyright: ignore [reportAttributeAccessIssue] await module.start() @classmethod @@ -180,9 +180,9 @@ def set_ready(self, ready: bool): async def add_resource(self, request: AddResourceRequest): dependencies = await self._get_dependencies(request.dependencies) config: ComponentConfig = request.config - subtype = Subtype.from_string(config.api) + api = API.from_string(config.api) model = Model.from_string(config.model, ignore_errors=True) - creator = Registry.lookup_resource_creator(subtype, model) + creator = Registry.lookup_resource_creator(api, model) resource = creator(config, dependencies) update_log_level(resource.logger, config.log_configuration.level.upper()) self.server.register(resource) @@ -190,9 +190,9 @@ async def add_resource(self, request: AddResourceRequest): async def reconfigure_resource(self, request: ReconfigureResourceRequest): dependencies = await self._get_dependencies(request.dependencies) config: ComponentConfig = request.config - subtype = Subtype.from_string(config.api) + api = API.from_string(config.api) name = config.name - rn = ResourceName(namespace=subtype.namespace, type=subtype.resource_type, subtype=subtype.resource_subtype, name=name) + rn = ResourceName(namespace=api.namespace, type=api.resource_type, subtype=api.resource_subtype, name=name) resource = self.server.get_resource(ResourceBase, rn) if isinstance(resource, Reconfigurable): resource.reconfigure(config, dependencies) @@ -220,28 +220,28 @@ async def ready(self, request: ReadyRequest) -> ReadyResponse: self._parent_address = request.parent_address await self._connect_to_parent() - svcname_to_models: Mapping[Tuple[str, Subtype], List[Model]] = {} - for subtype_model_str in Registry.REGISTERED_RESOURCE_CREATORS().keys(): - subtype_str, model_str = subtype_model_str.split("/") - subtype = Subtype.from_string(subtype_str) + svcname_to_models: Mapping[Tuple[str, API], List[Model]] = {} + for api_model_str in Registry.REGISTERED_RESOURCE_CREATORS().keys(): + api_str, model_str = api_model_str.split("/") + api = API.from_string(api_str) model = Model.from_string(model_str) - registration = Registry.lookup_subtype(subtype) + registration = Registry.lookup_api(api) service = registration.rpc_service(self.server) service_name = _service_name(service) - models = svcname_to_models.get((service_name, subtype), []) + models = svcname_to_models.get((service_name, api), []) models.append(model) - svcname_to_models[(service_name, subtype)] = models + svcname_to_models[(service_name, api)] = models handlers: List[HandlerDefinition] = [] for key, value in svcname_to_models.items(): - svc_name, subtype = key + svc_name, api = key rpc_subtype = ResourceRPCSubtype( subtype=ResourceName( - namespace=subtype.namespace, - type=subtype.resource_type, - subtype=subtype.resource_subtype, + namespace=api.namespace, + type=api.resource_type, + subtype=api.resource_subtype, name="", ), proto_service=svc_name, @@ -251,20 +251,20 @@ async def ready(self, request: ReadyRequest) -> ReadyResponse: return ReadyResponse(ready=self._ready, handlermap=HandlerMap(handlers=handlers)) - def add_model_from_registry(self, subtype: Subtype, model: Model): + def add_model_from_registry(self, api: API, model: Model): """Add a pre-registered model to this Module""" # All we need to do is double check that the model has already been registered try: - Registry.lookup_resource_creator(subtype, model) + Registry.lookup_resource_creator(api, model) except ResourceNotFoundError: - raise ValueError(f"Cannot add model because it has not been registered. Subtype: {subtype}. Model: {model}") + raise ValueError(f"Cannot add model because it has not been registered. API: {api}. Model: {model}") async def validate_config(self, request: ValidateConfigRequest) -> ValidateConfigResponse: config: ComponentConfig = request.config - subtype = Subtype.from_string(config.api) + api = API.from_string(config.api) model = Model.from_string(config.model) - validator = Registry.lookup_validator(subtype, model) + validator = Registry.lookup_validator(api, model) try: dependencies = validator(config) return ValidateConfigResponse(dependencies=dependencies) diff --git a/src/viam/proto/robot/__init__.py b/src/viam/proto/robot/__init__.py index a860e990d..e5a58631a 100644 --- a/src/viam/proto/robot/__init__.py +++ b/src/viam/proto/robot/__init__.py @@ -10,8 +10,8 @@ CancelOperationRequest, CancelOperationResponse, ConfigStatus, - DiscoverComponentsRequest, - DiscoverComponentsResponse, + DiscoverComponentsRequest, # deprecated, remove on march 10th + DiscoverComponentsResponse, # deprecated, remove on march 10th Discovery, DiscoveryQuery, FrameSystemConfig, @@ -73,8 +73,8 @@ "CancelOperationRequest", "CancelOperationResponse", "ConfigStatus", - "DiscoverComponentsRequest", - "DiscoverComponentsResponse", + "DiscoverComponentsRequest", # deprecated, remove on march 10th + "DiscoverComponentsResponse", # deprecated, remove on march 10th "Discovery", "DiscoveryQuery", "FrameSystemConfig", diff --git a/src/viam/resource/base.py b/src/viam/resource/base.py index ee99b2491..57d4cadf7 100644 --- a/src/viam/resource/base.py +++ b/src/viam/resource/base.py @@ -7,7 +7,7 @@ from viam.operations import Operation from viam.proto.common import ResourceName -from .types import Subtype +from .types import API if TYPE_CHECKING: from viam.robot.client import RobotClient @@ -20,8 +20,8 @@ class ResourceBase(Protocol): The base requirements for a Resource. """ - SUBTYPE: ClassVar["Subtype"] - """The Subtype of the Resource""" + API: ClassVar["API"] + """The API of the Resource""" name: str """The name of the Resource""" @@ -46,9 +46,9 @@ def get_resource_name(cls, name: str) -> ResourceName: ResourceName: The ResourceName of this Resource """ return ResourceName( - namespace=cls.SUBTYPE.namespace, - type=cls.SUBTYPE.resource_type, - subtype=cls.SUBTYPE.resource_subtype, + namespace=cls.API.namespace, + type=cls.API.resource_type, + subtype=cls.API.resource_subtype, name=name, ) diff --git a/src/viam/resource/easy_resource.py b/src/viam/resource/easy_resource.py index 9f40de5a1..a3529a7b2 100644 --- a/src/viam/resource/easy_resource.py +++ b/src/viam/resource/easy_resource.py @@ -10,7 +10,7 @@ from ..errors import MethodNotImplementedError from .base import ResourceBase from .registry import Registry, ResourceCreatorRegistration -from .types import Model, ModelFamily, Subtype +from .types import API, Model, ModelFamily modelRegex = re.compile(r"^([^:]+):([^:]+):([^:]+)$") @@ -92,7 +92,7 @@ async def get_readings(self, **kwargs): See examples/easy_resource/main.py for extended usage. """ - SUBTYPE: ClassVar[Subtype] + API: ClassVar[API] MODEL: ClassVar[Model] def __init_subclass__(cls, register=True, **kwargs): @@ -117,7 +117,7 @@ def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, Resour when an instance of your model is instantiated. You can override this in your subclass. """ self = cls(config.name) - logger.debug("created %s %s %s", cls.SUBTYPE, cls.MODEL, config.name) + logger.debug("created %s %s %s", cls.API, cls.MODEL, config.name) self.reconfigure(config, dependencies) return self @@ -140,14 +140,14 @@ def register(cls): This adds the model to the global registry. It is called by __init_subclass__ and you typically won't call it directly. """ - logger.debug("registering %s %s", cls.SUBTYPE, cls.MODEL) + logger.debug("registering %s %s", cls.API, cls.MODEL) # note: We could fix this pyright-ignore if EasyResource inherited ResourceBase, but that crashes in the mro() # walk in ResourceManager.register. Registry.register_resource_creator( - cls.SUBTYPE, + cls.API, cls.MODEL, ResourceCreatorRegistration(cls.new, cls.validate_config), # pyright: ignore [reportArgumentType] ) def reconfigure(self, config: ComponentConfig, dependencies: Mapping[ResourceName, ResourceBase]): - logger.debug("reconfigure %s %s", self.SUBTYPE, self.MODEL) + logger.debug("reconfigure %s %s", self.API, self.MODEL) diff --git a/src/viam/resource/manager.py b/src/viam/resource/manager.py index 1904f559f..2153fc107 100644 --- a/src/viam/resource/manager.py +++ b/src/viam/resource/manager.py @@ -39,12 +39,12 @@ def register(self, resource: ResourceBase): Raises: DuplicateResourceError: Error if attempting to register resource with the name of an existing resource - ResourceNotFoundError: Raised if the subtype of the resource is not registered + ResourceNotFoundError: Raised if the API of the resource is not registered Args: resource (ResourceBase): The resource to register """ - Registry.lookup_subtype(resource.SUBTYPE) # confirm the subtype is registered in Registry + Registry.lookup_api(resource.API) # confirm the API is registered in Registry _BaseClasses = (ResourceBase, ComponentBase, ServiceBase) rnames: Dict[ResourceName, ResourceBase] = {} diff --git a/src/viam/resource/registry.py b/src/viam/resource/registry.py index bdc6cde46..b29516162 100644 --- a/src/viam/resource/registry.py +++ b/src/viam/resource/registry.py @@ -10,7 +10,7 @@ if TYPE_CHECKING: from .rpc_service_base import ResourceRPCServiceBase - from .types import Model, ResourceCreator, Subtype, Validator + from .types import API, Model, ResourceCreator, Validator Resource = TypeVar("Resource", bound=ResourceBase) @@ -70,44 +70,44 @@ class Registry: resource using ``Registry.register(...)``. """ - _SUBTYPES: ClassVar[Dict["Subtype", ResourceRegistration]] = {} + _APIS: ClassVar[Dict["API", ResourceRegistration]] = {} _RESOURCES: ClassVar[Dict[str, ResourceCreatorRegistration]] = {} _lock: ClassVar[Lock] = Lock() @classmethod - def register_subtype(cls, registration: ResourceRegistration[Resource]): - """Register a Subtype with the Registry + def register_api(cls, registration: ResourceRegistration[Resource]): + """Register a API with the Registry Args: - registration (ResourceRegistration): Object containing registration data for the subtype + registration (ResourceRegistration): Object containing registration data for the API Raises: - DuplicateResourceError: Raised if the Subtype to register is already in the registry + DuplicateResourceError: Raised if the API to register is already in the registry ValidationError: Raised if registration is missing any necessary parameters """ with cls._lock: - if registration.resource_type.SUBTYPE in cls._SUBTYPES: - raise DuplicateResourceError(str(registration.resource_type.SUBTYPE)) + if registration.resource_type.API in cls._APIS: + raise DuplicateResourceError(str(registration.resource_type.API)) if registration.resource_type and registration.rpc_service and registration.create_rpc_client: - cls._SUBTYPES[registration.resource_type.SUBTYPE] = registration + cls._APIS[registration.resource_type.API] = registration else: raise ValidationError("Passed resource registration does not have correct parameters") @classmethod - def register_resource_creator(cls, subtype: "Subtype", model: "Model", registration: ResourceCreatorRegistration): - """Register a specific ``Model`` and validator function for the specific resource ``Subtype`` with the Registry + def register_resource_creator(cls, api: "API", model: "Model", registration: ResourceCreatorRegistration): + """Register a specific ``Model`` and validator function for the specific resource ``API`` with the Registry Args: - subtype (Subtype): The Subtype of the resource + api (API): The API of the resource model (Model): The Model of the resource registration (ResourceCreatorRegistration): The registration functions of the model Raises: - DuplicateResourceError: Raised if the Subtype and Model pairing is already registered + DuplicateResourceError: Raised if the API and Model pairing is already registered ValidationError: Raised if registration does not have creator """ - key = f"{subtype}/{model}" + key = f"{api}/{model}" with cls._lock: if key in cls._RESOURCES: raise DuplicateResourceError(key) @@ -118,78 +118,78 @@ def register_resource_creator(cls, subtype: "Subtype", model: "Model", registrat raise ValidationError("A creator function was not provided") @classmethod - def lookup_subtype(cls, subtype: "Subtype") -> ResourceRegistration: - """Lookup and retrieve a registered Subtype by its name + def lookup_api(cls, api: "API") -> ResourceRegistration: + """Lookup and retrieve a registered API by its name Args: - subtype (str): The subtype of the resource + api (str): The API of the resource Raises: - ResourceNotFoundError: Raised if the Subtype is not registered + ResourceNotFoundError: Raised if the API is not registered Returns: ResourceRegistration: The registration object of the resource """ with cls._lock: try: - return cls._SUBTYPES[subtype] + return cls._APIS[api] except KeyError: - raise ResourceNotFoundError(subtype.resource_type, subtype.resource_subtype) + raise ResourceNotFoundError(api.resource_type, api.resource_subtype) @classmethod - def lookup_resource_creator(cls, subtype: "Subtype", model: "Model") -> "ResourceCreator": - """Lookup and retrieve a registered resource creator by its subtype and model + def lookup_resource_creator(cls, api: "API", model: "Model") -> "ResourceCreator": + """Lookup and retrieve a registered resource creator by its API and model Args: - subtype (Subtype): The Subtype of the resource + api (API): The API of the resource model (Model): The Model of the resource Raises: - ResourceNotFoundError: Raised if the Subtype Model pairing is not registered + ResourceNotFoundError: Raised if the API Model pairing is not registered Returns: ResourceCreator: The function to create the resource """ with cls._lock: try: - return cls._RESOURCES[f"{subtype}/{model}"].creator + return cls._RESOURCES[f"{api}/{model}"].creator except KeyError: - raise ResourceNotFoundError(subtype.resource_type, subtype.resource_subtype) + raise ResourceNotFoundError(api.resource_type, api.resource_subtype) @classmethod - def lookup_validator(cls, subtype: "Subtype", model: "Model") -> "Validator": - """Lookup and retrieve a registered validator function by its subtype and model. If there is none, return None + def lookup_validator(cls, api: "API", model: "Model") -> "Validator": + """Lookup and retrieve a registered validator function by its API and model. If there is none, return None Args: - subtype (Subtype): The Subtype of the resource + api (API): The API of the resource model (Model): The Model of the resource Returns: Validator: The function to validate the resource """ try: - return cls._RESOURCES[f"{subtype}/{model}"].validator + return cls._RESOURCES[f"{api}/{model}"].validator except AttributeError: return lambda x: [] except KeyError: - raise ResourceNotFoundError(subtype.resource_type, subtype.resource_subtype) + raise ResourceNotFoundError(api.resource_type, api.resource_subtype) @classmethod - def REGISTERED_SUBTYPES(cls) -> Mapping["Subtype", ResourceRegistration]: + def REGISTERED_APIS(cls) -> Mapping["API", ResourceRegistration]: """The dictionary of all registered resources - - Key: Subtype of the resource + - Key: API of the resource - Value: The registration object for the resource Returns: - Mapping[Subtype, ResourceRegistration]: All registered resources + Mapping[API, ResourceRegistration]: All registered resources """ with cls._lock: - return cls._SUBTYPES.copy() + return cls._APIS.copy() @classmethod def REGISTERED_RESOURCE_CREATORS(cls) -> Mapping[str, "ResourceCreatorRegistration"]: """The dictionary of all registered resources - - Key: subtype/model + - Key: API/model - Value: The ResourceCreatorRegistration for the resource Returns: diff --git a/src/viam/resource/types.py b/src/viam/resource/types.py index c01fd60f7..f98803855 100644 --- a/src/viam/resource/types.py +++ b/src/viam/resource/types.py @@ -20,7 +20,7 @@ RESOURCE_TYPE_SERVICE = "service" -class Subtype: +class API: """Represents a known component/service (resource) API""" namespace: str @@ -41,45 +41,45 @@ def __str__(self) -> str: return f"{self.namespace}:{self.resource_type}:{self.resource_subtype}" def __repr__(self) -> str: - return f"" + return f"" def __hash__(self) -> int: return hash(str(self)) def __eq__(self, other: object) -> bool: - if isinstance(other, Subtype): + if isinstance(other, API): return str(self) == str(other) return False @classmethod def from_resource_name(cls, resource_name: ResourceName) -> Self: - """Convert a ```ResourceName``` into a ```Subtype``` + """Convert a ```ResourceName``` into a ```API``` Args: resource_name (viam.proto.common.ResourceName): The ResourceName to convert Returns: - Self: A new Subtype + Self: A new API """ return cls(resource_name.namespace, resource_name.type, resource_name.subtype) @classmethod def from_string(cls, string: str) -> Self: - """Create a ```Subtype``` from its string representation (namespace:resource_type:resource_subtype) + """Create a ```API``` from its string representation (namespace:resource_type:resource_subtype) Args: - string (str): The Subtype as a string + string (str): The API as a string Raises: - ValueError: Raised if the string does not represent a valid Subtype + ValueError: Raised if the string does not represent a valid API Returns: - Self: A new Subtype + Self: A new API """ regex = re.compile(r"^([\w-]+):([\w-]+):([\w-]+)$") match = regex.match(string) if not match: - raise ValueError(f"{string} is not a valid Subtype") + raise ValueError(f"{string} is not a valid API") return cls(match.group(1), match.group(2), match.group(3)) diff --git a/src/viam/robot/client.py b/src/viam/robot/client.py index 333cbcd17..294c48fb0 100644 --- a/src/viam/robot/client.py +++ b/src/viam/robot/client.py @@ -48,7 +48,7 @@ from viam.resource.manager import ResourceManager from viam.resource.registry import Registry from viam.resource.rpc_client_base import ReconfigurableResourceRPCClientBase, ResourceRPCClientBase -from viam.resource.types import RESOURCE_TYPE_COMPONENT, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_TYPE_COMPONENT, RESOURCE_TYPE_SERVICE from viam.rpc.dial import DialOptions, ViamChannel, dial from viam.services.service_base import ServiceBase from viam.sessions_client import SessionsClient @@ -341,12 +341,12 @@ async def _create_or_reset_client(self, resourceName: ResourceName): else: await self._manager.remove_resource(resourceName) self._manager.register( - Registry.lookup_subtype(Subtype.from_resource_name(resourceName)).create_rpc_client(resourceName.name, self._channel) + Registry.lookup_api(API.from_resource_name(resourceName)).create_rpc_client(resourceName.name, self._channel) ) else: try: self._manager.register( - Registry.lookup_subtype(Subtype.from_resource_name(resourceName)).create_rpc_client(resourceName.name, self._channel) + Registry.lookup_api(API.from_resource_name(resourceName)).create_rpc_client(resourceName.name, self._channel) ) except ResourceNotFoundError: pass diff --git a/src/viam/robot/service.py b/src/viam/robot/service.py index 715cbe11f..151fe7e9f 100644 --- a/src/viam/robot/service.py +++ b/src/viam/robot/service.py @@ -26,7 +26,7 @@ def _generate_metadata(self) -> List[ResourceName]: for resource in self.manager.resources.values(): # If the resource is a MovementSensor, DO NOT include Sensor as well (it will get added via MovementSensor) - if resource.SUBTYPE == Sensor.SUBTYPE and MovementSensor.get_resource_name(resource.name) in self.manager.resources: + if resource.API == Sensor.API and MovementSensor.get_resource_name(resource.name) in self.manager.resources: continue md.update(resource_names_for_resource(resource)) diff --git a/src/viam/rpc/server.py b/src/viam/rpc/server.py index 446b25215..5ea55c73f 100644 --- a/src/viam/rpc/server.py +++ b/src/viam/rpc/server.py @@ -41,7 +41,7 @@ def __init__(self, resources: List[ResourceBase], *, module_service: Optional["M super().__init__(resources) services = [SignalingService(), RobotService(manager=self)] - for registration in Registry.REGISTERED_SUBTYPES().values(): + for registration in Registry.REGISTERED_APIS().values(): if issubclass(registration.rpc_service, ResourceRPCServiceBase): services.append(registration.rpc_service(manager=self)) else: diff --git a/src/viam/services/generic/__init__.py b/src/viam/services/generic/__init__.py index 509803fec..4bf17db42 100644 --- a/src/viam/services/generic/__init__.py +++ b/src/viam/services/generic/__init__.py @@ -9,7 +9,7 @@ "Generic", ] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( Generic, GenericRPCService, diff --git a/src/viam/services/generic/generic.py b/src/viam/services/generic/generic.py index 5343a0826..45a0fe0f3 100644 --- a/src/viam/services/generic/generic.py +++ b/src/viam/services/generic/generic.py @@ -1,6 +1,6 @@ from typing import Final -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE from ..service_base import ServiceBase @@ -53,6 +53,6 @@ def complex_command(self, arg1, arg2, arg3): service.val # 5 """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "generic" ) diff --git a/src/viam/services/mlmodel/__init__.py b/src/viam/services/mlmodel/__init__.py index 77d33e27c..da6ba840e 100644 --- a/src/viam/services/mlmodel/__init__.py +++ b/src/viam/services/mlmodel/__init__.py @@ -21,4 +21,4 @@ __all__ = ["File", "LabelType", "Metadata", "MLModel", "MLModelClient", "TensorInfo"] -Registry.register_subtype(ResourceRegistration(MLModel, MLModelRPCService, lambda name, channel: MLModelClient(name, channel))) +Registry.register_api(ResourceRegistration(MLModel, MLModelRPCService, lambda name, channel: MLModelClient(name, channel))) diff --git a/src/viam/services/mlmodel/mlmodel.py b/src/viam/services/mlmodel/mlmodel.py index e0b08880d..0416eb4a0 100644 --- a/src/viam/services/mlmodel/mlmodel.py +++ b/src/viam/services/mlmodel/mlmodel.py @@ -4,7 +4,7 @@ from numpy.typing import NDArray from viam.proto.service.mlmodel import Metadata -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE from viam.utils import ValueTypes from ..service_base import ServiceBase @@ -21,7 +21,7 @@ class MLModel(ServiceBase): For more information, see `ML model service `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "mlmodel" ) diff --git a/src/viam/services/motion/__init__.py b/src/viam/services/motion/__init__.py index 9e1eee436..38d662fec 100644 --- a/src/viam/services/motion/__init__.py +++ b/src/viam/services/motion/__init__.py @@ -8,7 +8,7 @@ __all__ = ["Motion", "MotionClient", "MotionConfiguration", "Constraints"] -Registry.register_subtype( +Registry.register_api( ResourceRegistration( Motion, MotionRPCService, diff --git a/src/viam/services/motion/motion.py b/src/viam/services/motion/motion.py index 721061462..dc33a2f6c 100644 --- a/src/viam/services/motion/motion.py +++ b/src/viam/services/motion/motion.py @@ -9,7 +9,7 @@ from viam.proto.common import GeoGeometry, Geometry, GeoPoint, Pose, PoseInFrame, ResourceName, Transform, WorldState from viam.proto.service.motion import Constraints, GetPlanResponse, MotionConfiguration, PlanStatusWithID -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE from viam.utils import ValueTypes from ..service_base import ServiceBase @@ -26,7 +26,7 @@ class Motion(ServiceBase): Plan: "TypeAlias" = GetPlanResponse - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "motion" ) diff --git a/src/viam/services/navigation/__init__.py b/src/viam/services/navigation/__init__.py index 5e8a04431..e3587fc61 100644 --- a/src/viam/services/navigation/__init__.py +++ b/src/viam/services/navigation/__init__.py @@ -8,4 +8,4 @@ __all__ = ["GeoPoint", "GeoGeometry", "NavigationClient", "Navigation", "Waypoint", "Mode", "Path", "MapType"] -Registry.register_subtype(ResourceRegistration(Navigation, NavigationRPCService, lambda name, channel: NavigationClient(name, channel))) +Registry.register_api(ResourceRegistration(Navigation, NavigationRPCService, lambda name, channel: NavigationClient(name, channel))) diff --git a/src/viam/services/navigation/navigation.py b/src/viam/services/navigation/navigation.py index 4b142ffa9..a374e62e2 100644 --- a/src/viam/services/navigation/navigation.py +++ b/src/viam/services/navigation/navigation.py @@ -1,7 +1,7 @@ import abc from typing import Final, List, Optional -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE from ..service_base import ServiceBase from . import GeoGeometry, GeoPoint, MapType, Mode, Path, Waypoint @@ -18,7 +18,7 @@ class Navigation(ServiceBase): For more information, see `Navigation service `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "navigation" ) diff --git a/src/viam/services/service_base.py b/src/viam/services/service_base.py index e13fc2f91..87d3455b9 100644 --- a/src/viam/services/service_base.py +++ b/src/viam/services/service_base.py @@ -9,7 +9,7 @@ from viam.utils import ValueTypes if TYPE_CHECKING: - from viam.resource.types import Subtype + from viam.resource.types import API from viam.robot.client import RobotClient @@ -18,11 +18,11 @@ class ServiceBase(abc.ABC, ResourceBase): All services must inherit from this class. """ - SUBTYPE: ClassVar["Subtype"] + API: ClassVar["API"] def __init__(self, name: str, *, logger: Optional[Logger] = None) -> None: self.name = name - self.logger = logger if logger is not None else getLogger(f"{self.SUBTYPE}.{name}") + self.logger = logger if logger is not None else getLogger(f"{self.API}.{name}") @classmethod def from_robot(cls, robot: "RobotClient", name: str) -> Self: diff --git a/src/viam/services/service_client_base.py b/src/viam/services/service_client_base.py index 5c3ad4de8..af95bb142 100644 --- a/src/viam/services/service_client_base.py +++ b/src/viam/services/service_client_base.py @@ -6,7 +6,7 @@ from viam.errors import ResourceNotFoundError from viam.proto.common import ResourceName -from viam.resource.base import ResourceBase, Subtype +from viam.resource.base import API, ResourceBase from viam.utils import ValueTypes if TYPE_CHECKING: @@ -19,7 +19,7 @@ class ServiceClientBase(abc.ABC, ResourceBase): All service clients must inherit from this class. """ - SUBTYPE: ClassVar[Subtype] + API: ClassVar[API] channel: Channel def __init__(self, name: str, channel: Channel): @@ -37,7 +37,7 @@ def from_robot(cls, robot: "RobotClient", name: str = "builtin") -> Self: Returns: Self: The service client, if it exists on the robot """ - resource_name = ResourceName(namespace="rdk", type="service", subtype=cls.SUBTYPE.resource_subtype, name=name) + resource_name = ResourceName(namespace="rdk", type="service", subtype=cls.API.resource_subtype, name=name) if resource_name not in robot.resource_names: raise ResourceNotFoundError(resource_name.subtype, resource_name.name) return cls(name, robot._channel) diff --git a/src/viam/services/slam/__init__.py b/src/viam/services/slam/__init__.py index c32cea77f..11c2e33de 100644 --- a/src/viam/services/slam/__init__.py +++ b/src/viam/services/slam/__init__.py @@ -14,4 +14,4 @@ "SLAM", ] -Registry.register_subtype(ResourceRegistration(SLAM, SLAMRPCService, lambda name, channel: SLAMClient(name, channel))) +Registry.register_api(ResourceRegistration(SLAM, SLAMRPCService, lambda name, channel: SLAMClient(name, channel))) diff --git a/src/viam/services/slam/slam.py b/src/viam/services/slam/slam.py index fb59b18db..759c59f8c 100644 --- a/src/viam/services/slam/slam.py +++ b/src/viam/services/slam/slam.py @@ -3,7 +3,7 @@ from typing import Final, List, Optional from viam.proto.service.slam import GetPropertiesResponse -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE from ..service_base import ServiceBase from . import Pose @@ -25,7 +25,7 @@ class SLAM(ServiceBase): For more information, see `SLAM service `_. """ - SUBTYPE: Final = Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "slam") # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "slam") # pyright: ignore [reportIncompatibleVariableOverride] Properties: "TypeAlias" = GetPropertiesResponse diff --git a/src/viam/services/vision/__init__.py b/src/viam/services/vision/__init__.py index 55b35e8b2..3cf69e34f 100644 --- a/src/viam/services/vision/__init__.py +++ b/src/viam/services/vision/__init__.py @@ -12,4 +12,4 @@ "Vision", ] -Registry.register_subtype(ResourceRegistration(Vision, VisionRPCService, lambda name, channel: VisionClient(name, channel))) +Registry.register_api(ResourceRegistration(Vision, VisionRPCService, lambda name, channel: VisionClient(name, channel))) diff --git a/src/viam/services/vision/vision.py b/src/viam/services/vision/vision.py index f881d338e..6a3c65233 100644 --- a/src/viam/services/vision/vision.py +++ b/src/viam/services/vision/vision.py @@ -5,7 +5,7 @@ from viam.media.video import ViamImage from viam.proto.common import PointCloudObject from viam.proto.service.vision import Classification, Detection, GetPropertiesResponse -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE from viam.utils import ValueTypes from ..service_base import ServiceBase @@ -63,7 +63,7 @@ class Vision(ServiceBase): For more information, see `Computer Vision service `_. """ - SUBTYPE: Final = Subtype( # pyright: ignore [reportIncompatibleVariableOverride] + API: Final = API( # pyright: ignore [reportIncompatibleVariableOverride] RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_SERVICE, "vision" ) diff --git a/src/viam/utils.py b/src/viam/utils.py index 4e86b4c61..e8fa4e1b8 100644 --- a/src/viam/utils.py +++ b/src/viam/utils.py @@ -16,7 +16,7 @@ from viam.resource.base import ResourceBase from viam.resource.registry import Registry from viam.resource.rpc_client_base import ResourceRPCClientBase -from viam.resource.types import Subtype, SupportsGetGeometries +from viam.resource.types import API, SupportsGetGeometries if sys.version_info >= (3, 9): from collections.abc import Callable @@ -104,14 +104,10 @@ def resource_names_for_resource(resource: ResourceBase) -> List[ResourceName]: rns: List[ResourceName] = [] for klass in resource.__class__.mro(): - for registration in Registry.REGISTERED_SUBTYPES().values(): + for registration in Registry.REGISTERED_APIS().values(): if klass is registration.resource_type: - subtype: Subtype = registration.resource_type.SUBTYPE - rns.append( - ResourceName( - namespace=subtype.namespace, type=subtype.resource_type, subtype=subtype.resource_subtype, name=resource.name - ) - ) + api: API = registration.resource_type.API + rns.append(ResourceName(namespace=api.namespace, type=api.resource_type, subtype=api.resource_subtype, name=resource.name)) return rns diff --git a/tests/mocks/module/gizmo/__init__.py b/tests/mocks/module/gizmo/__init__.py index 8d09f9926..369c7e72d 100644 --- a/tests/mocks/module/gizmo/__init__.py +++ b/tests/mocks/module/gizmo/__init__.py @@ -4,6 +4,6 @@ from .api import Gizmo, GizmoClient, GizmoService from .my_gizmo import MyGizmo -Registry.register_subtype(ResourceRegistration(Gizmo, GizmoService, lambda name, channel: GizmoClient(name, channel))) +Registry.register_api(ResourceRegistration(Gizmo, GizmoService, lambda name, channel: GizmoClient(name, channel))) -Registry.register_resource_creator(Gizmo.SUBTYPE, MyGizmo.MODEL, ResourceCreatorRegistration(MyGizmo.new, MyGizmo.validate_config)) +Registry.register_resource_creator(Gizmo.API, MyGizmo.MODEL, ResourceCreatorRegistration(MyGizmo.new, MyGizmo.validate_config)) diff --git a/tests/mocks/module/gizmo/api.py b/tests/mocks/module/gizmo/api.py index cfb56097c..75269a2a8 100644 --- a/tests/mocks/module/gizmo/api.py +++ b/tests/mocks/module/gizmo/api.py @@ -7,7 +7,7 @@ from viam.components.component_base import ComponentBase from viam.components.generic.client import do_command from viam.resource.rpc_service_base import ResourceRPCServiceBase -from viam.resource.types import RESOURCE_TYPE_COMPONENT, Subtype +from viam.resource.types import API, RESOURCE_TYPE_COMPONENT from viam.utils import ValueTypes from ..proto.gizmo_grpc import GizmoServiceBase, GizmoServiceStub @@ -28,7 +28,7 @@ class Gizmo(ComponentBase): """Example component to use with the example module.""" - SUBTYPE: Final = Subtype("acme", RESOURCE_TYPE_COMPONENT, "gizmo") + API: Final = API("acme", RESOURCE_TYPE_COMPONENT, "gizmo") @abc.abstractmethod async def do_one(self, arg1: str, **kwargs) -> bool: ... diff --git a/tests/mocks/module/gizmo/my_gizmo.py b/tests/mocks/module/gizmo/my_gizmo.py index 006ceb8a2..b745cadd1 100644 --- a/tests/mocks/module/gizmo/my_gizmo.py +++ b/tests/mocks/module/gizmo/my_gizmo.py @@ -26,7 +26,7 @@ def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, Resour @classmethod def validate_config(cls, config: ComponentConfig) -> List[str]: if "invalid" in config.attributes.fields: - raise Exception(f"'invalid' attribute not allowed for model {cls.SUBTYPE}:{cls.MODEL}") + raise Exception(f"'invalid' attribute not allowed for model {cls.API}:{cls.MODEL}") arg1 = config.attributes.fields["arg1"].string_value if arg1 == "": raise Exception("A arg1 attribute is required for Gizmo component.") diff --git a/tests/mocks/module/summation/__init__.py b/tests/mocks/module/summation/__init__.py index 9ced0989f..3917d8ab7 100644 --- a/tests/mocks/module/summation/__init__.py +++ b/tests/mocks/module/summation/__init__.py @@ -3,6 +3,6 @@ from .api import SummationClient, SummationRPCService, SummationService from .my_summation import MySummationService -Registry.register_subtype(ResourceRegistration(SummationService, SummationRPCService, lambda name, channel: SummationClient(name, channel))) +Registry.register_api(ResourceRegistration(SummationService, SummationRPCService, lambda name, channel: SummationClient(name, channel))) -Registry.register_resource_creator(SummationService.SUBTYPE, MySummationService.MODEL, ResourceCreatorRegistration(MySummationService.new)) +Registry.register_resource_creator(SummationService.API, MySummationService.MODEL, ResourceCreatorRegistration(MySummationService.new)) diff --git a/tests/mocks/module/summation/api.py b/tests/mocks/module/summation/api.py index ddb8834f0..d7f5acde3 100644 --- a/tests/mocks/module/summation/api.py +++ b/tests/mocks/module/summation/api.py @@ -5,7 +5,7 @@ from grpclib.server import Stream from viam.resource.rpc_service_base import ResourceRPCServiceBase -from viam.resource.types import RESOURCE_TYPE_SERVICE, Subtype +from viam.resource.types import API, RESOURCE_TYPE_SERVICE from viam.services.service_base import ServiceBase from ..proto.summation_grpc import SummationServiceBase, SummationServiceStub @@ -15,7 +15,7 @@ class SummationService(ServiceBase): """Example service to use with the example module""" - SUBTYPE: Final = Subtype("acme", RESOURCE_TYPE_SERVICE, "summation") + API: Final = API("acme", RESOURCE_TYPE_SERVICE, "summation") @abc.abstractmethod async def sum(self, nums: Sequence[float]) -> float: ... diff --git a/tests/test_component_service_base.py b/tests/test_component_service_base.py index e49ec6713..73984f038 100644 --- a/tests/test_component_service_base.py +++ b/tests/test_component_service_base.py @@ -13,12 +13,12 @@ from viam.resource.registry import Registry, ResourceRegistration from viam.resource.rpc_client_base import ReconfigurableResourceRPCClientBase from viam.resource.rpc_service_base import ResourceRPCServiceBase -from viam.resource.types import Subtype +from viam.resource.types import API async def test_cancellation_propagation(): class TestComponent(ComponentBase): - SUBTYPE = Subtype("test", "test", "test") + API = API("test", "test", "test") long_running_task_cancelled = False @@ -52,7 +52,7 @@ def __mapping__(self) -> Mapping[str, const.Handler]: with pytest.raises(ResourceNotFoundError): service = TestService(ResourceManager([component])) - Registry.register_subtype(ResourceRegistration(TestComponent, TestService, lambda name, channel: TestClient(name, channel))) + Registry.register_api(ResourceRegistration(TestComponent, TestService, lambda name, channel: TestClient(name, channel))) service = TestService(ResourceManager([component])) # Test bare functions diff --git a/tests/test_data_client.py b/tests/test_data_client.py index 9ea0ba0ea..1fa928b20 100644 --- a/tests/test_data_client.py +++ b/tests/test_data_client.py @@ -221,7 +221,7 @@ async def test_export_tabular_data(self, service: MockData): assert tabular_datum is not None assert tabular_datum.part_id == TABULAR_METADATA.part_id assert tabular_datum.resource_name == TABULAR_METADATA.component_name - assert tabular_datum.resource_subtype == TABULAR_METADATA.component_type + assert tabular_datum.resource_api == TABULAR_METADATA.component_type assert tabular_datum.time_captured == END_DATETIME assert tabular_datum.organization_id == TABULAR_METADATA.organization_id assert tabular_datum.location_id == TABULAR_METADATA.location_id diff --git a/tests/test_easy_resource.py b/tests/test_easy_resource.py index 00c6f9815..7ff52bd4b 100644 --- a/tests/test_easy_resource.py +++ b/tests/test_easy_resource.py @@ -11,7 +11,7 @@ @pytest.fixture def clear_registry(monkeypatch): "helper to patch registry global state for duration of test" - monkeypatch.setattr(Registry, "_SUBTYPES", {}) + monkeypatch.setattr(Registry, "_APIS", {}) monkeypatch.setattr(Registry, "_RESOURCES", {}) diff --git a/tests/test_module.py b/tests/test_module.py index 7b4e424f6..9f7d48c89 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -18,7 +18,7 @@ ValidateConfigResponse, ) from viam.proto.robot import ResourceRPCSubtype -from viam.resource.types import Model, Subtype +from viam.resource.types import API, Model from viam.robot.client import RobotClient from viam.robot.service import RobotService from viam.utils import dict_to_struct @@ -33,7 +33,7 @@ @pytest.fixture async def module(request): module = Module("some_fake_address") - module.add_model_from_registry(Gizmo.SUBTYPE, MyGizmo.MODEL) + module.add_model_from_registry(Gizmo.API, MyGizmo.MODEL) request.cls.module = module yield module await module.stop() @@ -175,10 +175,10 @@ async def test_ready(self, module: Module): def test_add_model_from_registry(self): mod = Module("fake") - mod.add_model_from_registry(Gizmo.SUBTYPE, MyGizmo.MODEL) + mod.add_model_from_registry(Gizmo.API, MyGizmo.MODEL) with pytest.raises(ValueError): - mod.add_model_from_registry(Subtype.from_string("fake:fake:fake"), Model.from_string("faker:faker:faker")) + mod.add_model_from_registry(API.from_string("fake:fake:fake"), Model.from_string("faker:faker:faker")) async def test_multiple_resources_same_model(self, module: Module): req = AddResourceRequest( diff --git a/tests/test_registry.py b/tests/test_registry.py index a424a9ec7..3b36d8bb8 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -6,11 +6,11 @@ from viam.errors import DuplicateResourceError, ResourceNotFoundError from viam.resource.registry import Registry, ResourceRegistration from viam.resource.rpc_service_base import ResourceRPCServiceBase -from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Model, ModelFamily, Subtype, resource_name_from_string +from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Model, ModelFamily, resource_name_from_string class FakeComponent(ComponentBase): - SUBTYPE = Subtype("fake", "fake", "fake") + API = API("fake", "fake", "fake") class FakeComponentService(ResourceRPCServiceBase): @@ -23,67 +23,67 @@ def __init__(self, name: str, channel: Channel): def test_components_register_themselves_correctly(): - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "audio_input") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "base") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "board") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "camera") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "gantry") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "gripper") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "motor") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "movement_sensor") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "pose_tracker") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "sensor") in Registry.REGISTERED_SUBTYPES() - assert Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "servo") in Registry.REGISTERED_SUBTYPES() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "audio_input") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "base") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "board") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "camera") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "gantry") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "gripper") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "motor") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "movement_sensor") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "pose_tracker") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "sensor") in Registry.REGISTERED_APIS() + assert API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "servo") in Registry.REGISTERED_APIS() def test_lookup(): with pytest.raises(ResourceNotFoundError): - Registry.lookup_subtype(Subtype("fake", "fake", "fake")) + Registry.lookup_api(API("fake", "fake", "fake")) - component = Registry.lookup_subtype(Subtype(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm")) - assert component.resource_type.SUBTYPE == Arm.SUBTYPE + component = Registry.lookup_api(API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm")) + assert component.resource_type.API == Arm.API def test_registration(): - assert FakeComponent.SUBTYPE not in Registry.REGISTERED_SUBTYPES() + assert FakeComponent.API not in Registry.REGISTERED_APIS() - Registry.register_subtype( + Registry.register_api( ResourceRegistration(FakeComponent, FakeComponentService, lambda name, channel: FakeComponentClient(name, channel)) ) - assert FakeComponent.SUBTYPE in Registry.REGISTERED_SUBTYPES() - component = Registry.lookup_subtype(FakeComponent.SUBTYPE) + assert FakeComponent.API in Registry.REGISTERED_APIS() + component = Registry.lookup_api(FakeComponent.API) assert component is not None with pytest.raises(DuplicateResourceError): - Registry.register_subtype( + Registry.register_api( ResourceRegistration(FakeComponent, FakeComponentService, lambda name, channel: FakeComponentClient(name, channel)) ) -def test_subtype(): +def test_api(): # test fields should always be lowercase - subtype = Subtype("test", "TEST", "TeSt") - assert subtype.namespace == "test" - assert subtype.resource_type != "test" - assert subtype.resource_subtype != "test" + api = API("test", "TEST", "TeSt") + assert api.namespace == "test" + assert api.resource_type != "test" + assert api.resource_subtype != "test" # test from resource name rn = Arm.get_resource_name("test_arm") - subtype = Subtype.from_resource_name(rn) - assert subtype == Arm.SUBTYPE + api = API.from_resource_name(rn) + assert api == Arm.API # test from string - subtype = Subtype.from_string("TEST:tester:TESTerson") - assert subtype.namespace != "test" - assert subtype.resource_type == "tester" - assert subtype.resource_subtype != "testerson" + api = API.from_string("TEST:tester:TESTerson") + assert api.namespace != "test" + assert api.resource_type == "tester" + assert api.resource_subtype != "testerson" with pytest.raises(ValueError): - Subtype.from_string("this:should:not:work") + API.from_string("this:should:not:work") # test str - assert str(subtype) != "test:tester:testerson" + assert str(api) != "test:tester:testerson" def test_model_family(): diff --git a/tests/test_robot.py b/tests/test_robot.py index 024a8d8fa..387f172a5 100644 --- a/tests/test_robot.py +++ b/tests/test_robot.py @@ -536,8 +536,8 @@ async def get_geometries( ) -> List[Geometry]: return await self.actual_client.get_geometries(timeout=timeout) - old_create_client = Registry._SUBTYPES[Arm.SUBTYPE].create_rpc_client - Registry._SUBTYPES[Arm.SUBTYPE].create_rpc_client = lambda name, channel: FakeArmClient(name, channel) + old_create_client = Registry._APIS[Arm.API].create_rpc_client + Registry._APIS[Arm.API].create_rpc_client = lambda name, channel: FakeArmClient(name, channel) client = await RobotClient.with_channel(channel, RobotClient.Options()) @@ -548,7 +548,7 @@ async def get_geometries( assert arm_client is not client.get_component(Arm.get_resource_name(arm_client.name)) # Should be a new client now await client.close() - Registry._SUBTYPES[Arm.SUBTYPE].create_rpc_client = old_create_client + Registry._APIS[Arm.API].create_rpc_client = old_create_client async def test_shutdown(self, service: RobotService): async with ChannelFor([service]) as channel: diff --git a/tests/test_rpc.py b/tests/test_rpc.py index 0b98effe7..f7b13b40e 100644 --- a/tests/test_rpc.py +++ b/tests/test_rpc.py @@ -31,8 +31,8 @@ def __init__(self, channel: Channel) -> None: async def test_builtin_clients_are_reconfigurable(): async with ChannelFor([]) as channel: - for subtype, registration in Registry.REGISTERED_SUBTYPES().items(): - if subtype.namespace == RESOURCE_NAMESPACE_RDK: + for api, registration in Registry.REGISTERED_APIS().items(): + if api.namespace == RESOURCE_NAMESPACE_RDK: client = registration.create_rpc_client("client", channel) assert isinstance(client, ReconfigurableResourceRPCClientBase)