Skip to content

Commit

Permalink
refactor(langserver): remove async code from code lens
Browse files Browse the repository at this point in the history
  • Loading branch information
d-biehl committed Jan 2, 2024
1 parent faee359 commit 204624c
Show file tree
Hide file tree
Showing 8 changed files with 105 additions and 123 deletions.
14 changes: 4 additions & 10 deletions packages/debugger/src/robotcode/debugger/protocol.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import asyncio
import concurrent.futures
import inspect
import json
import threading
Expand All @@ -21,6 +20,7 @@
Union,
)

from robotcode.core.concurrent import FutureEx
from robotcode.core.utils.dataclasses import as_dict, as_json, from_dict
from robotcode.core.utils.inspect import ensure_coroutine
from robotcode.core.utils.logging import LoggingDescriptor
Expand Down Expand Up @@ -293,12 +293,8 @@ def send_response(
)

@_logger.call
def send_request(
self,
request: Request,
return_type: Optional[Type[TResult]] = None,
) -> concurrent.futures.Future[TResult]:
result: concurrent.futures.Future[TResult] = concurrent.futures.Future()
def send_request(self, request: Request, return_type: Optional[Type[TResult]] = None) -> FutureEx[TResult]:
result: FutureEx[TResult] = FutureEx()

with self._sended_request_lock:
self._sended_request[request.seq] = SendedRequestEntry(result, return_type)
Expand All @@ -309,9 +305,7 @@ def send_request(

@_logger.call
def send_request_async(
self,
request: Request,
return_type: Optional[Type[TResult]] = None,
self, request: Request, return_type: Optional[Type[TResult]] = None
) -> asyncio.Future[TResult]:
return asyncio.wrap_future(self.send_request(request, return_type))

Expand Down
9 changes: 4 additions & 5 deletions packages/jsonrpc2/src/robotcode/jsonrpc2/protocol.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import asyncio
import concurrent.futures
import functools
import inspect
import json
Expand Down Expand Up @@ -38,7 +37,7 @@
create_sub_task,
run_coroutine_in_thread,
)
from robotcode.core.concurrent import is_threaded_callable, run_in_thread
from robotcode.core.concurrent import FutureEx, is_threaded_callable, run_in_thread
from robotcode.core.utils.dataclasses import as_json, from_dict
from robotcode.core.utils.inspect import ensure_coroutine, iter_methods
from robotcode.core.utils.logging import LoggingDescriptor
Expand Down Expand Up @@ -344,7 +343,7 @@ def get_param_type(self, name: str) -> Optional[Type[Any]]:


class SendedRequestEntry:
def __init__(self, future: concurrent.futures.Future[Any], result_type: Optional[Type[Any]]) -> None:
def __init__(self, future: FutureEx[Any], result_type: Optional[Type[Any]]) -> None:
self.future = future
self.result_type = result_type

Expand Down Expand Up @@ -563,8 +562,8 @@ def send_request(
method: str,
params: Optional[Any] = None,
return_type_or_converter: Optional[Type[_TResult]] = None,
) -> concurrent.futures.Future[_TResult]:
result: concurrent.futures.Future[_TResult] = concurrent.futures.Future()
) -> FutureEx[_TResult]:
result: FutureEx[_TResult] = FutureEx()

with self._sended_request_lock:
self._sended_request_count += 1
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from __future__ import annotations

import asyncio
from asyncio import CancelledError
from concurrent.futures import CancelledError
from typing import TYPE_CHECKING, Any, Final, List, Optional

from robotcode.core.async_tools import async_tasking_event, create_sub_task
from robotcode.core.concurrent import threaded
from robotcode.core.concurrent import FutureEx, check_current_thread_canceled, threaded
from robotcode.core.event import event
from robotcode.core.lsp.types import (
CodeLens,
CodeLensOptions,
Expand All @@ -27,16 +24,17 @@
class CodeLensProtocolPart(LanguageServerProtocolPart):
_logger: Final = LoggingDescriptor()

def __init__(self, parent: LanguageServerProtocol) -> None:
def __init__(self, parent: "LanguageServerProtocol") -> None:
super().__init__(parent)
self.refresh_task: Optional[asyncio.Task[Any]] = None
self.refresh_task: Optional[FutureEx[Any]] = None
self._refresh_timeout = 5

@async_tasking_event
async def collect(sender, document: TextDocument) -> Optional[List[CodeLens]]: # NOSONAR
@event
def collect(sender, document: TextDocument) -> Optional[List[CodeLens]]: # NOSONAR
...

@async_tasking_event
async def resolve(sender, code_lens: CodeLens) -> Optional[CodeLens]: # NOSONAR
@event
def resolve(sender, code_lens: CodeLens) -> Optional[CodeLens]: # NOSONAR
...

def extend_capabilities(self, capabilities: ServerCapabilities) -> None:
Expand All @@ -45,15 +43,17 @@ def extend_capabilities(self, capabilities: ServerCapabilities) -> None:

@rpc_method(name="textDocument/codeLens", param_type=CodeLensParams)
@threaded
async def _text_document_code_lens(
def _text_document_code_lens(
self, text_document: TextDocumentIdentifier, *args: Any, **kwargs: Any
) -> Optional[List[CodeLens]]:
results: List[CodeLens] = []
document = self.parent.documents.get(text_document.uri)
if document is None:
return None

for result in await self.collect(self, document, callback_filter=language_id_filter(document)):
for result in self.collect(self, document, callback_filter=language_id_filter(document)):
check_current_thread_canceled()

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
self._logger.exception(result, exc_info=result)
Expand All @@ -64,17 +64,19 @@ async def _text_document_code_lens(
if not results:
return None

for result in results:
result.range = document.range_to_utf16(result.range)
for r in results:
r.range = document.range_to_utf16(r.range)

return results

@rpc_method(name="codeLens/resolve", param_type=CodeLens)
@threaded
async def _code_lens_resolve(self, params: CodeLens, *args: Any, **kwargs: Any) -> CodeLens:
def _code_lens_resolve(self, params: CodeLens, *args: Any, **kwargs: Any) -> CodeLens:
results: List[CodeLens] = []

for result in await self.resolve(self, params):
for result in self.resolve(self, params):
check_current_thread_canceled()

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
self._logger.exception(result, exc_info=result)
Expand All @@ -88,19 +90,7 @@ async def _code_lens_resolve(self, params: CodeLens, *args: Any, **kwargs: Any)

return params

async def __do_refresh(self, now: bool = False) -> None:
if not now:
await asyncio.sleep(1)

await self.__refresh()

async def refresh(self, now: bool = False) -> None:
if self.refresh_task is not None and not self.refresh_task.done():
self.refresh_task.get_loop().call_soon_threadsafe(self.refresh_task.cancel)

self.refresh_task = create_sub_task(self.__do_refresh(now), loop=self.parent.diagnostics.diagnostics_loop)

async def __refresh(self) -> None:
def refresh(self) -> None:
if not (
self.parent.client_capabilities is not None
and self.parent.client_capabilities.workspace is not None
Expand All @@ -109,4 +99,4 @@ async def __refresh(self) -> None:
):
return

await self.parent.send_request_async("workspace/codeLens/refresh")
self.parent.send_request("workspace/codeLens/refresh").result(self._refresh_timeout)
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
create_sub_task,
)
from robotcode.core.concurrent import threaded
from robotcode.core.event import event
from robotcode.core.lsp.types import (
Diagnostic,
DiagnosticOptions,
Expand Down Expand Up @@ -241,8 +242,8 @@ async def collect(sender, document: TextDocument) -> Optional[DiagnosticsResult]
async def load_workspace_documents(sender) -> Optional[List[WorkspaceDocumentsResult]]: # NOSONAR
...

@async_tasking_event
async def on_workspace_loaded(sender) -> None: # NOSONAR
@event
def on_workspace_loaded(sender) -> None: # NOSONAR
...

@async_event
Expand All @@ -262,7 +263,7 @@ async def ensure_workspace_loaded(self) -> None:
finally:
self._workspace_loaded = True
self.workspace_loaded_event.set()
await self.on_workspace_loaded(self)
self.on_workspace_loaded(self)
await self.force_refresh_all()

async def force_refresh_all(self, refresh: bool = True) -> None:
Expand Down
Loading

0 comments on commit 204624c

Please sign in to comment.