Skip to content

hololinked.metadata.td.interaction_affordance.ActionAffordance

Bases: InteractionAffordance, ActionMetadata

creates action affordance schema from actions (or methods).

Schema
UML Diagram

Source code in repo/hololinked/hololinked/metadata/td/interaction_affordance.py
class ActionAffordance(InteractionAffordance, ActionMetadata):
    """
    creates action affordance schema from actions (or methods).

    [Schema](https://www.w3.org/TR/wot-thing-description11/#actionaffordance) <br>
    [UML Diagram](https://docs.hololinked.dev/UML/PDF/InteractionAffordance.pdf) <br>
    """

    # [Supported Fields]() <br>
    input: JSON | None = None
    output: JSON | None = None
    safe: bool | None = None
    idempotent: bool | None = None
    synchronous: bool | None = None

    def __init__(self):
        super().__init__()

    @property
    def what(self):  # noqa: D102
        return ResourceTypes.ACTION

    def build(self) -> None:  # noqa: D102
        action = cast(Action, self.objekt)
        doc = action.doc
        if doc:
            title = get_summary(doc)
            description = self.format_doc(doc)
            if title and not description.startswith(title):
                self.title = title
                self.description = description
            else:
                self.description = description
        if action.argument_schema:
            if isinstance(action.argument_schema, dict):
                self.input = action.argument_schema
            elif issubklass(action.argument_schema, (BaseModel, RootModel)):
                self.input = type_to_dataschema(action.argument_schema)
            else:
                raise ValueError(
                    f"unknown schema definition for action input, given type: {type(action.argument_schema)}"
                )
        if action.return_value_schema:
            if isinstance(action.return_value_schema, dict):
                self.output = action.return_value_schema
            elif issubklass(action.return_value_schema, (BaseModel, RootModel)):
                self.output = type_to_dataschema(action.return_value_schema)
            else:
                raise ValueError(
                    f"unknown schema definition for action output, given type: {type(action.return_value_schema)}"
                )
        if (
            not (
                hasattr(self.owner, "state_machine")
                and self.owner.state_machine is not None
                and self.owner.state_machine.contains_object(action)
            )
            and action.idempotent
        ):
            self.idempotent = action.idempotent
        if action.synchronous:
            self.synchronous = action.synchronous
        if action.safe:
            self.safe = action.safe

    @classmethod
    def from_descriptor(cls, action: Action, owner: Thing | ThingMeta, **kwargs) -> ActionAffordance:  # noqa: D102
        if not isinstance(action, Action):
            raise TypeError(f"action must be instance of Action, given type {type(action)}")
        affordance = ActionAffordance()
        affordance.owner = owner
        affordance.objekt = action
        affordance.build()
        affordance.build_non_compliant_metadata()
        return affordance

    def to_descriptor(self, obj: Callable | ActionDelegate, validator: str = "pydantic") -> Action:
        """
        Create the `Action` this affordance describes, invoking the given handler.

        Parameters
        ----------
        obj: Callable | ActionDelegate
            the handler, a sync or async method, or the delegate to a method of another object
        validator: str
            name the validator of the input is registered under with `SchemaValidators`

        Returns
        -------
        Action
            the descriptor, not yet assigned to a class

        Raises
        ------
        InputSignatureError
            if the parameters of the handler do not match the input, listing every mismatch
        """
        input_schema, _validator = None, None
        if self.input:
            check_input_signature(obj, self.input)
            input_schema, _validator = schema_validator(self.input, f"{self.name}_input", validator)
        output_schema = None
        if self.output:
            output_schema, _ = schema_validator(self.output, f"{self.name}_output", validator)
        # flags absent from the TD keep the defaults of action(), synchronous=True decides the scheduling
        flags = {
            key: getattr(self, key) for key in ("safe", "idempotent", "synchronous") if getattr(self, key) is not None
        }
        _action = action(
            input_schema=input_schema,
            output_schema=output_schema,
            doc="\n\n".join(text for text in (self.title, self.description) if text) or None,
            **flags,
        )(obj)
        _action._schema_validator = _validator
        return _action

Functions

to_descriptor

to_descriptor(obj: Callable | ActionDelegate, validator: str = 'pydantic') -> Action

Create the Action this affordance describes, invoking the given handler.

Parameters:

Name Type Description Default

obj

Callable | ActionDelegate

the handler, a sync or async method, or the delegate to a method of another object

required

validator

str

name the validator of the input is registered under with SchemaValidators

'pydantic'

Returns:

Type Description
Action

the descriptor, not yet assigned to a class

Raises:

Type Description
InputSignatureError

if the parameters of the handler do not match the input, listing every mismatch

Source code in repo/hololinked/hololinked/metadata/td/interaction_affordance.py
def to_descriptor(self, obj: Callable | ActionDelegate, validator: str = "pydantic") -> Action:
    """
    Create the `Action` this affordance describes, invoking the given handler.

    Parameters
    ----------
    obj: Callable | ActionDelegate
        the handler, a sync or async method, or the delegate to a method of another object
    validator: str
        name the validator of the input is registered under with `SchemaValidators`

    Returns
    -------
    Action
        the descriptor, not yet assigned to a class

    Raises
    ------
    InputSignatureError
        if the parameters of the handler do not match the input, listing every mismatch
    """
    input_schema, _validator = None, None
    if self.input:
        check_input_signature(obj, self.input)
        input_schema, _validator = schema_validator(self.input, f"{self.name}_input", validator)
    output_schema = None
    if self.output:
        output_schema, _ = schema_validator(self.output, f"{self.name}_output", validator)
    # flags absent from the TD keep the defaults of action(), synchronous=True decides the scheduling
    flags = {
        key: getattr(self, key) for key in ("safe", "idempotent", "synchronous") if getattr(self, key) is not None
    }
    _action = action(
        input_schema=input_schema,
        output_schema=output_schema,
        doc="\n\n".join(text for text in (self.title, self.description) if text) or None,
        **flags,
    )(obj)
    _action._schema_validator = _validator
    return _action
field supported meaning default usage
input ✔️ schema of the input required to invoke action input_schema value of action decorator
output ✔️ schema of the output returned by the action output_schema value of action decorator
safe ✔️ true if the action is safe safe value of action decorator
idempotent ✔️ true if the action is idempotent idempotent value of action decorator
synchronous ✔️ true if the action is synchronous synchronous value of action decorator, (false for async or threaded functions)