Completed
Pull Request — master (#189)
by Björn
03:20
created

neovim.msgpack_rpc.Session._on_notification()   A

Complexity

Conditions 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 9.762
Metric Value
cc 3
dl 0
loc 14
ccs 1
cts 11
cp 0.0909
crap 9.762
rs 9.4285

1 Method

Rating   Name   Duplication   Size   Complexity  
A neovim.msgpack_rpc.Session.handler() 0 9 2
1
"""Synchronous msgpack-rpc session layer."""
2 6
import logging
3 6
from collections import deque
4
5 6
from traceback import format_exc
6
7 6
import greenlet
0 ignored issues
show
Configuration introduced by
The import greenlet could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
8
9 6
logger = logging.getLogger(__name__)
10 6
error, debug, info, warn = (logger.error, logger.debug, logger.info,
11
                            logger.warning,)
12
13
14 6
class Session(object):
15
16
    """Msgpack-rpc session layer that uses coroutines for a synchronous API.
17
18
    This class provides the public msgpack-rpc API required by this library.
19
    It uses the greenlet module to handle requests and notifications coming
20
    from Nvim with a synchronous API.
21
    """
22
23 6
    def __init__(self, async_session):
24
        """Wrap `async_session` on a synchronous msgpack-rpc interface."""
25 6
        self._async_session = async_session
26 6
        self._request_cb = self._notification_cb = None
27 6
        self._pending_messages = deque()
28 6
        self._is_running = False
29 6
        self._setup_exception = None
30
31 6
    def threadsafe_call(self, fn, *args, **kwargs):
32
        """Wrapper around `AsyncSession.threadsafe_call`."""
33 6
        def handler():
34 6
            try:
35 6
                fn(*args, **kwargs)
36
            except Exception:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
37
                warn("error caught while excecuting async callback\n%s\n",
38
                     format_exc())
39
40 6
        def greenlet_wrapper():
41 6
            gr = greenlet.greenlet(handler)
42 6
            gr.switch()
43
44 6
        self._async_session.threadsafe_call(greenlet_wrapper)
45
46 6
    def next_message(self):
47
        """Block until a message(request or notification) is available.
48
49
        If any messages were previously enqueued, return the first in queue.
50
        If not, run the event loop until one is received.
51
        """
52 6
        if self._is_running:
53 6
            raise Exception('Event loop already running')
54 6
        if self._pending_messages:
55 6
            return self._pending_messages.popleft()
56 6
        self._async_session.run(self._enqueue_request_and_stop,
57
                                self._enqueue_notification_and_stop)
58 6
        if self._pending_messages:
59 6
            return self._pending_messages.popleft()
60
61 6
    def request(self, method, *args, **kwargs):
62
        """Send a msgpack-rpc request and block until as response is received.
63
64
        If the event loop is running, this method must have been called by a
65
        request or notification handler running on a greenlet. In that case,
66
        send the quest and yield to the parent greenlet until a response is
67
        available.
68
69
        When the event loop is not running, it will perform a blocking request
70
        like this:
71
        - Send the request
72
        - Run the loop until the response is available
73
        - Put requests/notifications received while waiting into a queue
74
75
        If the `async` flag is present and True, a asynchronous notification is
76
        sent instead. This will never block, and the return value or error is
77
        ignored.
78
        """
79 6
        async = kwargs.pop('async', False)
80 6
        if async:
81 6
            self._async_session.notify(method, args)
82 6
            return
83
84 6
        if kwargs:
85
            warn("request got unsupported keyword argument(s): %s", ', '.join(kwargs.keys()))
86
87 6
        if self._is_running:
88 6
            v = self._yielding_request(method, args)
89
        else:
90 6
            v = self._blocking_request(method, args)
91 6
        if not v:
92
            # EOF
93
            raise IOError('EOF')
94 6
        err, rv = v
0 ignored issues
show
Bug introduced by
The tuple unpacking with sequence defined at line 156 seems to be unbalanced; 2 value(s) for 0 label(s)

This happens when the amount of values does not equal the amount of labels:

a, b = ("a", "b", "c")  # only 2 labels for 3 values
Loading history...
95 6
        if err:
96 6
            info("'Received error: %s", err)
97 6
            raise self.error_wrapper(err)
0 ignored issues
show
Bug introduced by
The Instance of Session does not seem to have a member named error_wrapper.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
98 6
        return rv
99
100 6
    def run(self, request_cb, notification_cb, setup_cb=None):
101
        """Run the event loop to receive requests and notifications from Nvim.
102
103
        Like `AsyncSession.run()`, but `request_cb` and `notification_cb` are
104
        inside greenlets.
105
        """
106 6
        self._request_cb = request_cb
107 6
        self._notification_cb = notification_cb
108 6
        self._is_running = True
109 6
        self._setup_exception = None
110
111 6
        def on_setup():
112 6
            try:
113 6
                setup_cb()
114
            except Exception as e:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
115
                self._setup_exception = e
116
                self.stop()
117
118 6
        if setup_cb:
119
            # Create a new greenlet to handle the setup function
120 6
            gr = greenlet.greenlet(on_setup)
121 6
            gr.switch()
122
123 6
        if self._setup_exception:
124
            error('Setup error: {0}'.format(self._setup_exception))
125
            raise self._setup_exception
0 ignored issues
show
Bug introduced by
Raising NoneType while only classes or instances are allowed
Loading history...
126
127
        # Process all pending requests and notifications
128 6
        while self._pending_messages:
129
            msg = self._pending_messages.popleft()
130
            getattr(self, '_on_{0}'.format(msg[0]))(*msg[1:])
131 6
        self._async_session.run(self._on_request, self._on_notification)
132 6
        self._is_running = False
133 6
        self._request_cb = None
134 6
        self._notification_cb = None
135
136 6
        if self._setup_exception:
137 1
            raise self._setup_exception
0 ignored issues
show
Bug introduced by
Raising NoneType while only classes or instances are allowed
Loading history...
138
139 6
    def stop(self):
140
        """Stop the event loop."""
141 6
        self._async_session.stop()
142
143 6
    def _yielding_request(self, method, args):
144 6
        gr = greenlet.getcurrent()
145 6
        parent = gr.parent
146
147 6
        def response_cb(err, rv):
148 6
            debug('response is available for greenlet %s, switching back', gr)
149 6
            gr.switch(err, rv)
150
151 6
        self._async_session.request(method, args, response_cb)
152 6
        debug('yielding from greenlet %s to wait for response', gr)
153 6
        return parent.switch()
154
155 6
    def _blocking_request(self, method, args):
156 6
        result = []
157
158 6
        def response_cb(err, rv):
159 6
            result.extend([err, rv])
160 6
            self.stop()
161
162 6
        self._async_session.request(method, args, response_cb)
163 6
        self._async_session.run(self._enqueue_request,
164
                                self._enqueue_notification)
165 6
        return result
166
167 6
    def _enqueue_request_and_stop(self, name, args, response):
168
        self._enqueue_request(name, args, response)
169
        self.stop()
170
171 6
    def _enqueue_notification_and_stop(self, name, args):
172 6
        self._enqueue_notification(name, args)
173 6
        self.stop()
174
175 6
    def _enqueue_request(self, name, args, response):
176
        self._pending_messages.append(('request', name, args, response,))
177
178 6
    def _enqueue_notification(self, name, args):
179 6
        self._pending_messages.append(('notification', name, args,))
180
181 6
    def _on_request(self, name, args, response):
182 6
        def handler():
183 6
            try:
184 6
                rv = self._request_cb(name, args)
185 6
                debug('greenlet %s finished executing, ' +
186
                      'sending %s as response', gr, rv)
187 6
                response.send(rv)
188
            except ErrorResponse as err:
189
                warn("error response from request '%s %s': %s", name,
190
                     args, format_exc())
191
                response.send(err.args[0], error=True)
192
            except Exception as err:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
193
                warn("error caught while processing request '%s %s': %s", name,
194
                     args, format_exc())
195
                response.send(repr(err) + "\n" + format_exc(5), error=True)
196 6
            debug('greenlet %s is now dying...', gr)
197
198
        # Create a new greenlet to handle the request
199 6
        gr = greenlet.greenlet(handler)
200 6
        debug('received rpc request, greenlet %s will handle it', gr)
201 6
        gr.switch()
202
203 6
    def _on_notification(self, name, args):
204
        def handler():
205
            try:
206
                self._notification_cb(name, args)
207
                debug('greenlet %s finished executing', gr)
208
            except Exception:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
209
                warn("error caught while processing notification '%s %s': %s",
210
                     name, args, format_exc())
211
212
            debug('greenlet %s is now dying...', gr)
213
214
        gr = greenlet.greenlet(handler)
215
        debug('received rpc notification, greenlet %s will handle it', gr)
216
        gr.switch()
217
218
219 6
class ErrorResponse(BaseException):
220
221
    """Raise this in a request handler to respond with a given error message.
222
223
    Unlike when other exceptions are caught, this gives full control off the
224
    error response sent. When "ErrorResponse(msg)" is caught "msg" will be
225
    sent verbatim as the error response.No traceback will be appended.
226
    """
227
228
    pass
229