Exemple #1
0
 def notify(self, method, params=None):
     """ Send a notification to the client, expects no response. """
     request = JSONRPC20Request(method=method,
                                params=params,
                                is_notification=True)
     logger.debug(f"Sending notification {method} {request.data}")
     self.__write_message(data=request.data)
Exemple #2
0
 def write_file(self, filename: Union[str, Path], file_content: str) -> None:
     _LOGGER.debug("Writing a file: %s", filename)
     filename = os.fspath(filename)
     request = JSONRPC20Request(
         method="WriteFile",
         params=[self.session_id, filename, file_content, None],  # sourceMap ?
         is_notification=True,
     )
     write_message(request.json)
Exemple #3
0
 def message(self, channel: Channel, text: str) -> None:
     # https://github.com/Azure/autorest/blob/ad7f01ffe17aa74ad0075d6b1562a3fa78fd2e96/src/autorest-core/lib/message.ts#L53
     # Don't log anything here, or you will create a cycle with the autorest handler
     message = {
         "Channel": channel.value,
         "Text": text,
     }
     request = JSONRPC20Request(method="Message", params=[self.session_id, message], is_notification=True)
     write_message(request.json)
Exemple #4
0
 def create_request_from_json(body):
     json_request = JSONRPC20Request.from_json(body)
     request_mgr = DriverManager(namespace=DOR_REQUEST_NAMESPACE,
                                 name=json_request.method,
                                 invoke_kwds=json_request.params,
                                 invoke_on_load=True)
     driver = request_mgr.driver
     driver._id = json.loads(body)['id']  # preserve original id
     return driver
Exemple #5
0
def notify20(websocket, method, params=None):
    # Sending notifications to the clients helper function
    try:
        notification = unicode(
            JSONRPC20Request(method, params, is_notification=True).json,
            'utf-8')
        logger.info("Sending notification: %r", notification)
        websocket.sendMessage(notification)
    except Exception as e:
        logger.exception(e)
def message(session_id, message):
    _LOGGER.info(f"Sending a message to Autorest: {message}")
    request = JSONRPC20Request(
        method="Message",
        params=[
            session_id,
            message
        ],
        is_notification=True
    )
    write_message(request.json)
Exemple #7
0
 def __call__(self, *args, **kwargs) -> int:
     assert len(args) == 0 or len(kwargs) == 0, \
         "You can use positional or named args, not both"
     if len(args) == 0:
         params = kwargs
     else:
         params = list(args)
     _id = self.batch._client.id()
     req = JSONRPC20Request(_id=_id, method=self.method, params=params)
     self.batch._batch.append(req)
     return _id
def list_inputs(session_id):
    _LOGGER.info("Calling list inputs to Autorest")
    request = JSONRPC20Request(
        method="ListInputs",
        params=[
            session_id,
            None
        ],
        _id=42
    )
    write_message(request.json)
    return json.loads(read_message())["result"]
def read_file(session_id, filename):
    _LOGGER.info(f"Asking content for file {filename}")
    request = JSONRPC20Request(
        method="ReadFile",
        params=[
            session_id,
            filename
        ],
        _id=42
    )
    write_message(request.json)
    return json.loads(read_message())["result"]
Exemple #10
0
    def notify(self, method, params=None):
        """Send a JSONRPC notification.

         Args:
             method (str): The method name of the notification to send
             params (dict): The payload of the notification
         """
        log.debug('Notify %s %s', method, params)
        notification = JSONRPC20Request(method=method,
                                        params=params,
                                        is_notification=True)
        self._message_manager.write_message(notification)
def get_value(session_id, key):
    _LOGGER.info(f"Calling get value to Autorest: {key}")
    request = JSONRPC20Request(
        method="GetValue",
        params=[
            session_id,
            key
        ],
        _id=42
    )
    write_message(request.json)
    return json.loads(read_message())["result"]
Exemple #12
0
    def __call__(self, *args, **kwargs):
        assert len(args) == 0 or len(kwargs) == 0, \
            "You can use positional or named args, not both"
        if len(args) == 0:
            params = kwargs
        else:
            params = list(args)

        _id = self.client.id()
        req = JSONRPC20Request(_id=_id, method=self.method, params=params)
        self.client.responses[_id] = None
        self.client.tr.send_raw(req.json)
        return _response(self.client.tr.receive_json())
def write_file(session_id, filename, file_content):
    _LOGGER.info(f"Writing a file: {filename}")
    request = JSONRPC20Request(
        method="WriteFile",
        params=[
            session_id,
            filename,
            file_content,
            None  # sourceMap ?
        ],
        is_notification=True
    )
    write_message(request.json)
Exemple #14
0
def create_json_rpc_request(method: str,
                            args: List[Any],
                            encode: bool = True) -> JSONRPC20Request:
    """Creates a JSONRPC20Request object.

    Args:
        method (str): Method to call
        args (List[Any]): Arguments for the method.

    Returns:
        JSONRPC20Request: Request object.
    """

    req = JSONRPC20Request(method=method, params=args)
    return req.json.encode("utf-8") if encode else req
def server(loop, path):
    if os.path.exists(path):
        os.remove(path)
    print("Listening %s" % path)
    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server.bind(path)
    dispatcher["hello"] = lambda hello: "Hello %s" % hello
    server.listen(1)
    while True:
        connection, client_address = server.accept()
        tr = SyncPascalStringTransport(connection)
        command = JSONRPC20Request.from_data(tr.receive_json())
        print("command", command)
        response = JSONRPCResponseManager.handle_request(command, dispatcher)
        print('server response', response.data)
        tr.send_raw(response.json)
        connection.close()
Exemple #16
0
    def call(self, method, params=None):
        """Send a JSONRPC request.

        Args:
            method (str): The method name of the message to send
            params (dict): The payload of the message

        Returns:
            Future that will resolve once a response has been received
        """
        log.debug('Calling %s %s', method, params)
        request = JSONRPC20Request(_id=str(uuid4()),
                                   method=method,
                                   params=params)
        request_future = Future()
        self._sent_requests[request._id] = request_future
        self._message_manager.write_message(request)
        return request_future
Exemple #17
0
def extract_rpc_request(request: ByteString) -> Optional[JSONRPC20Request]:
    """Extracts a JSON RPC 2.0 request from an incoming bytestring

    Args:
        request (ByteString): Incoming request from a client

    Returns:
        Optional[JSONRPC20Request]: JSONRPCRequest if successful, otherwise None
    """

    try:
        # Decode from bytes to string
        rpc_string = request.decode("utf-8")

        # Return request
        return JSONRPC20Request.from_json(rpc_string)

    # Unable to convert to JSONRPC20Request
    except (json.JSONDecodeError, JSONRPCInvalidRequestException):
        return None
Exemple #18
0
    async def run(self):
        async for req in self.requests:
            req = JSONRPC20Request.from_data(req)
            if req._id != None:
                assert req._id not in self.ids, "Replayed id: %s" % req._id
                self.ids.add(req._id)
            if req.method not in self.methods:
                logging.error("Unknown method: %s" % req.method)
                await write_error(self.transport, req._id,
                                    JSONRPCMethodNotFound())
                return
            f = self.methods[req.method]
            try:
                if isinstance(req.params, list):
                    t = asyncio.ensure_future(f(*req.params,
                                                __context=self.context))
                else: # It's a dict
                    req.params['__context'] = self.context
                    t = asyncio.ensure_future(f(**req.params))

                asyncio.ensure_future(self._response(req._id,
                                                     time(REQ_TIME, future=t)))
                self.tasks[req._id] = t
                #def clean_task(f):
                    #del self.tasks[req._id]
                #t.add_done_callback(clean_task)
                for cb in self.callbacks:
                    t.add_done_callback(cb)
            except Exception as e:
                if self.raven_client is None:
                    raven_id = None
                else:
                    raven_id = self.raven_client.captureException()
                await write_error(self.transport, req._id, JSONRPCServerError(
                    message=str(e),
                    data=dict(raven_id=raven_id)))
                return
Exemple #19
0
 def get_value(self, key: str) -> Any:
     _LOGGER.debug("Calling get value to Autorest: %s", key)
     request = JSONRPC20Request(method="GetValue", params=[self.session_id, key], _id=42)
     write_message(request.json)
     return json.loads(read_message())["result"]
Exemple #20
0
 def read_file(self, filename: Union[str, Path]) -> str:
     _LOGGER.debug("Asking content for file %s", filename)
     filename = os.fspath(filename)
     request = JSONRPC20Request(method="ReadFile", params=[self.session_id, filename], _id=42)
     write_message(request.json)
     return json.loads(read_message())["result"]