Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add decorators for api handlers #38

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
6f9caf4
feat: add decorators for event handler registration
jfcherng Nov 15, 2020
05489e9
fix: naming + coding style
jfcherng Nov 18, 2020
b9f8122
refactor: factor out register_decorated_handlers() to decorator.py
jfcherng Nov 18, 2020
35e57d5
chore: no need to expose HANDLER_MARKS
jfcherng Nov 18, 2020
a9966e5
chore: cleanup unused import
jfcherng Nov 18, 2020
509cf2a
chore: revise wording
jfcherng Nov 18, 2020
179920b
refactor: early break for register_decorated_handlers()
jfcherng Nov 18, 2020
668833b
refactor: avoid try...except
jfcherng Nov 18, 2020
f90b898
perf: optimize internal working flow for register_decorated_handlers()
jfcherng Nov 18, 2020
b0838e8
chore: revise wording
jfcherng Nov 18, 2020
1bc23d5
refactor: Iterable -> List
jfcherng Nov 18, 2020
96e31b9
chore: revise term namings
jfcherng Nov 18, 2020
226a293
chore: use more LSP spec terms
jfcherng Nov 18, 2020
4d55387
chore: remove unnecessary casting
jfcherng Nov 18, 2020
43c8b44
chore: revise comment wording with LSP spec terms
jfcherng Nov 18, 2020
60465de
refactor: no need for variable "is_registered" in register_decorated_…
jfcherng Nov 18, 2020
c559ef5
style: follow Python's naming convention
jfcherng Nov 18, 2020
f8d656f
style: fixup, real CamelCase
jfcherng Nov 18, 2020
9950965
chore: use more LSP spec terms
jfcherng Nov 18, 2020
e1a2347
Type fixes for request_handler decorator
rchl Nov 18, 2020
295eedd
Add documentation
rchl Nov 18, 2020
ed3064a
More docs
rchl Nov 18, 2020
121517f
Typo
rchl Nov 18, 2020
ca7e9fe
rename decorator => api_decorator
rchl Nov 21, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/source/api_handler.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,26 @@ ApiWrapperInterface
-------------------

.. autoclass:: lsp_utils.ApiWrapperInterface

API Decorators
--------------

Decorators can be used as an alternative to attaching listeners to the :class:`lsp_utils.ApiWrapperInterface` instance obtained through :meth:`lsp_utils.GenericClientHandler.on_ready()`.

To use, attach the decorator to a function and call it with the name of the notification or the request that you want to handle. It can also be called with a list of names, if you want to use the same handler to handle multiple requests.

Example usage:

.. code:: py

@notification_handler('eslint/status')
def handle_status(self, params: Any) -> None:
print(status)

@request_handler('eslint/openDoc')
def handle_open_doc(self, params: Any, respond: Callable[[Any], None]) -> None:
webbrowser.open(params['url'])
respond({})

.. autoclass:: lsp_utils.request_handler
.. autoclass:: lsp_utils.notification_handler
4 changes: 4 additions & 0 deletions st3/lsp_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from ._client_handler import ClientHandler
from ._client_handler import notification_handler
from ._client_handler import request_handler
from .api_wrapper_interface import ApiWrapperInterface
from .generic_client_handler import GenericClientHandler
from .npm_client_handler import NpmClientHandler
Expand All @@ -14,4 +16,6 @@
'ServerResourceInterface',
'ServerStatus'
'ServerNpmResource',
'notification_handler',
'request_handler',
]
4 changes: 4 additions & 0 deletions st3/lsp_utils/_client_handler/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from .api_decorator import notification_handler
from .api_decorator import request_handler
from LSP.plugin import __version__ as lsp_version


Expand All @@ -8,4 +10,6 @@

__all__ = [
'ClientHandler',
'notification_handler',
'request_handler',
]
5 changes: 4 additions & 1 deletion st3/lsp_utils/_client_handler/abstract_plugin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from ..api_wrapper_interface import ApiWrapperInterface
from ..server_resource_interface import ServerStatus
from .api_decorator import register_decorated_handlers
from .interface import ClientHandlerInterface
from LSP.plugin import AbstractPlugin
from LSP.plugin import ClientConfig
Expand Down Expand Up @@ -158,4 +159,6 @@ def _upgrade_languages_list(cls, languages):

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.on_ready(ApiWrapper(self))
api = ApiWrapper(self)
register_decorated_handlers(self, api)
self.on_ready(api)
86 changes: 86 additions & 0 deletions st3/lsp_utils/_client_handler/api_decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
from ..api_wrapper_interface import ApiWrapperInterface
from .interface import ClientHandlerInterface
from LSP.plugin.core.typing import Any, Callable, List, Optional, TypeVar, Union
import inspect

__all__ = [
"notification_handler",
"request_handler",
"register_decorated_handlers",
]

T = TypeVar('T')
# the first argument is always "self"
NotificationHandler = Callable[[Any, Any], None]
RequestHandler = Callable[[Any, Any, Callable[[Any], None]], None]
MessageMethods = Union[str, List[str]]

_HANDLER_MARKS = {
"notification": "__handle_notification_message_methods",
"request": "__handle_request_message_methods",
}


def notification_handler(notification_methods: MessageMethods) -> Callable[[NotificationHandler], NotificationHandler]:
"""
Marks the decorated function as a "notification" message handler.

On server sending the notification, the decorated function will be called with the `params` argument which contains
the payload.
"""

return _create_handler("notification", notification_methods)


def request_handler(request_methods: MessageMethods) -> Callable[[RequestHandler], RequestHandler]:
"""
Marks the decorated function as a "request" message handler.

On server sending the request, the decorated function will be called with two arguments (`params` and `respond`).
The first argument (`params`) is the payload of the request and the second argument (`respond`) is the function that
must be used to respond to the request. The `respond` function takes any data that should be sent back to the
server.
"""

return _create_handler("request", request_methods)


def _create_handler(client_event: str, message_methods: MessageMethods) -> Callable[[T], T]:
""" Marks the decorated function as a message handler. """

message_methods = [message_methods] if isinstance(message_methods, str) else message_methods

def decorator(func: T) -> T:
setattr(func, _HANDLER_MARKS[client_event], message_methods)
return func

return decorator


def register_decorated_handlers(client_handler: ClientHandlerInterface, api: ApiWrapperInterface) -> None:
"""
Register decorator-style custom message handlers.

This method works as following:

1. Scan through all methods of `client_handler`.
2. If a method is decorated, it will have a "handler mark" attribute which is set by the decorator.
3. Register the method with wanted message methods, which are stored in the "handler mark" attribute.

:param client_handler: The instance of the client handler.
:param api: The API instance for interacting with the server.
"""
for _, func in inspect.getmembers(client_handler, predicate=inspect.isroutine):
for client_event, handler_mark in _HANDLER_MARKS.items():
message_methods = getattr(func, handler_mark, None) # type: Optional[List[str]]
if message_methods is None:
continue

event_registrator = getattr(api, "on_" + client_event, None)
if callable(event_registrator):
for message_method in message_methods:
event_registrator(message_method, func)

# it makes no sense that a handler handles both "notification" and "request"
# so we do early break once we've registered a handler
break
5 changes: 4 additions & 1 deletion st3/lsp_utils/_client_handler/language_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from ..api_wrapper_interface import ApiWrapperInterface
from ..helpers import log_and_show_message
from ..server_resource_interface import ServerStatus
from .api_decorator import register_decorated_handlers
from .interface import ClientHandlerInterface
from LSP.plugin import ClientConfig
from LSP.plugin import LanguageHandler
Expand Down Expand Up @@ -82,7 +83,9 @@ def on_start(cls, window: sublime.Window) -> bool:
return True

def on_initialized(self, client) -> None:
self.on_ready(ApiWrapper(client))
api = ApiWrapper(client)
register_decorated_handlers(self, api)
self.on_ready(api)

# --- ClientHandlerInterface --------------------------------------------------------------------------------------

Expand Down
8 changes: 6 additions & 2 deletions st3/lsp_utils/api_wrapper_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,25 @@
__all__ = ['ApiWrapperInterface']


NotificationHandler = Callable[[Any], None]
RequestHandler = Callable[[Any, Callable[[Any], None]], None]


class ApiWrapperInterface(metaclass=ABCMeta):
"""
An interface for sending and receiving requests and notifications from and to the server. An implementation of it
is available through the :func:`GenericClientHandler.on_ready()` override.
"""

@abstractmethod
def on_notification(self, method: str, handler: Callable[[Any], None]) -> None:
def on_notification(self, method: str, handler: NotificationHandler) -> None:
"""
Registers a handler for given notification name. The handler will be called with optional params.
"""
...

@abstractmethod
def on_request(self, method: str, handler: Callable[[Any, Callable[[Any], None]], None]) -> None:
def on_request(self, method: str, handler: RequestHandler) -> None:
"""
Registers a handler for given request name. The handler will be called with two arguments - first the params
sent with the request and second the function that must be used to respond to the request. The response
Expand Down