Пример #1
0
def create_web_socket_configuration(parsed_args):
    # type: (argparse.Namespace) -> WebSocketConfiguration
    """Create websocket configuration instance with parsed debug config
    parameters.

    WebSocket configures the server URI used to connect for local debug session
    and sets the headers information for initial handshake of sockets and
    authorization of clients.

    :param parsed_args: Parsed parameter object returned from
        parser.argument_parser function.
    :type parsed_args: object
    :return: WebSocketConfiguration instance.
    :rtype: :py:class:`ask_sdk_local_debug.config.WebSocketConfiguration`
    """
    client_config = create_client_configuration(parsed_args)
    access_token = parsed_args.access_token
    if parsed_args.region not in list(Region.__members__):
        error_message = "Invalid region - {}. Please ensure that the region value is one of " \
                        "{}".format(parsed_args.region, list(Region.__members__))
        logger.error(error_message)
        raise LocalDebugSdkException(error_message)
    logger.info("Region chosen: " + parsed_args.region)
    debug_endpoint_uri = DEBUG_ENDPOINT_URI.format(
        Region[parsed_args.region].value, client_config.skill_id)

    headers = {
        AUTHORIZATION_HEADER_NAME: access_token,
        UPGRADE_HEADER_NAME: UPGRADE_HEADER_VALUE,
        CONNECTION_HEADER_NAME: CONNECTION_HEADER_VALUE
    }
    return WebSocketConfiguration(web_socket_server_uri=debug_endpoint_uri,
                                  headers=headers)
 def __get_skill_builder_func(self):
     try:
         return getattr(self.__initialize_skill_invoker(), self.skill_handler)
     except Exception as e:
         raise LocalDebugSdkException(
             "Handler function does not exist. Make sure that the skill file path:{} and "
             "the handler name:{} are correct. Exception:{}".format(
                 self.skill_file_path, self.skill_handler, str(e)))
    def error(self, message):
        # type: (str) -> None
        """Raise Local Debug Sdk Exception when invalid arguments are passed.

        :param message: Exception message raised.
        :type message: str
        :raises: :py:class:`ask_sdk_local_debug.exception.LocalDebugSdkException`
        """
        raise LocalDebugSdkException(message)
Пример #4
0
    def __initialize_skill_invoker(self):
        # type: () -> Any
        """Returns a skill invoker module based on spec loaded from skill
        file path and skill handler.

        :return: Module used to invoke the skill handler.
        :rtype: object
        """
        try:
            skill_invoker = importlib.util.module_from_spec(self.spec)
            self.spec.loader.exec_module(skill_invoker)
        except Exception as e:
            raise LocalDebugSdkException(
                "Failed to load the module from {} : {}".format(
                    self.skill_file_path, str(e)))
        return skill_invoker
Пример #5
0
    def spec(self):
        # type: () -> Any
        """Returns the spec module loaded from the skill file path and skill
        handler.

        :return: Spec module from skill file path
        :rtype: object
        """
        try:
            self._spec = importlib.util.spec_from_file_location(
                self.skill_handler, self.skill_file_path)
        except Exception as e:
            raise LocalDebugSdkException(
                "Failed to import spec from the file location {} : {}".format(
                    self.skill_file_path, str(e)))
        return self._spec
Пример #6
0
 def invoke(self):
     # type: () -> None
     """Triggers the web socket client to make a connection attempt
     on the provided websocket uri.
     """
     try:
         connectWS(self.factory,
                   contextFactory=None,
                   timeout=CONNECTION_TIMEOUT_SECONDS)
         reactor.run()
     except Exception as e:
         logger.error(
             'Unable to initiate a socket client connection : {}'.format(
                 str(e)))
         raise LocalDebugSdkException(
             "Unable to initiate a socket client connection : {}".format(
                 str(e)))
Пример #7
0
def get_deserialized_request(skill_request_payload):
    # type:(str) -> Request
    """Deserialize the incoming request payload into
    :py:class:`ask_sdk_model.dynamic_endpoints.Request` class.

    :param skill_request_payload: Incoming skill request payload.
    :type skill_request_payload: str
    :return: Serialized skill request.
    :rtype: :py:class:`ask_sdk_model.dynamic_endpoints.Request
    """
    try:
        default_serializer = Serializer.get_instance()  # type: ignore
        return default_serializer.deserialize(payload=skill_request_payload,
                                              obj_type=Request)
    except Exception as ex:
        logger.error("Failed to deserialize request : {}".format(str(ex)))
        raise LocalDebugSdkException(
            "Failed to deserialize skill_request : {}".format(str(ex)))
Пример #8
0
def get_skill_response(local_debug_request, skill_invoker_config):
    # type: (Request, SkillInvokerConfiguration) -> str
    """Invokes skill code with skill request payload.

    :param local_debug_request: Skill request payload.
    :type local_debug_request: :py:class:`ask_sdk_model.dynamic_endpoints.Request`
    :param skill_invoker_config: Skill Invoker instance to invoke skill code
    :type skill_invoker_config: :py:class:`ask_sdk_local_debug.skill_invoker_config.SkillInvokerConfiguration`
    :return: Response payload.
    :rtype: str
    """
    try:
        request_envelope = json.loads(local_debug_request.request_payload)
        skill_builder_func = getattr(skill_invoker_config.skill_invoker,
                                     skill_invoker_config.skill_handler)
        default_serializer = Serializer.get_instance()  # type: ignore
        response_payload = None  # type: BaseResponse

        try:
            skill_response = skill_builder_func(request_envelope, None)
        except Exception as ex:
            logger.error("Failed to retrieve skill response : {}".format(
                str(ex)))
            response_payload = get_local_debug_failure_response(
                local_debug_request=local_debug_request, exception=ex)

        if response_payload is None:
            skill_response = json.dumps(skill_response)
            response_payload = get_local_debug_success_response(
                local_debug_request=local_debug_request,
                skill_success_response=skill_response)
        serialized_response = default_serializer.serialize(response_payload)

        return json.dumps(serialized_response)
    except Exception as ex:
        logger.error("Error in get_skill_response : {}".format(str(ex)))
        raise LocalDebugSdkException("Error in get_skill_response : {}".format(
            str(ex)))
Пример #9
0
def get_local_debug_success_response(local_debug_request,
                                     skill_success_response):
    # type: (Request, str) -> SuccessResponse
    """Builds a success response for response payload obtained when
    invoking skill code.

    :param local_debug_request: Skill request parameter.
    :type local_debug_request: :py:class:`ask_sdk_model.dynamic_endpoints.Request`
    :param skill_success_response: Skill Response.
    :type skill_success_response: str
    :return: Skill success response.
    :rtype: :py:class:`ask_sdk_model.dynamic_endpoints.SuccessResponse`
    """
    try:
        return SuccessResponse(
            original_request_id=local_debug_request.request_id,
            response_payload=skill_success_response,
            version=local_debug_request.version)
    except Exception as ex:
        logger.error(
            "Failed to create SuccessResponse instance : {}".format(str(ex)))
        raise LocalDebugSdkException("Failed to create SuccessResponse "
                                     "instance : {}".format(str(ex)))
Пример #10
0
def get_local_debug_failure_response(local_debug_request, exception):
    # type: (Request, Exception) -> FailureResponse
    """Builds a failure response for runtime exception encountered when
    invoking skill code.

    :param local_debug_request: Skill request parameter.
    :type local_debug_request: :py:class:`ask_sdk_model.dynamic_endpoints.Request`
    :param exception: Exception object available when skill invocation results
        in an error.
    :type exception: Exception class object.
    :return: Skill failure response.
    :rtype: :py:class:`ask_sdk_model.dynamic_endpoints.FailureResponse`
    """
    try:
        return FailureResponse(version=local_debug_request.version,
                               original_request_id=local_debug_request.request_id,
                               error_code=str(
                                   HTTPStatus.INTERNAL_SERVER_ERROR.value),
                               error_message=str(exception))
    except Exception as ex:
        logger.error(
            "Failed to create FailureResponse instance : {}".format(str(ex)))
        raise LocalDebugSdkException("Failed to create FailureResponse "
                                     "instance : {}".format(str(ex)))