Skip to content

Commit

Permalink
refactor(langserver): rename core.concurrent.FutureEx to Task
Browse files Browse the repository at this point in the history
  • Loading branch information
d-biehl committed Jan 5, 2024
1 parent e98a865 commit d75eb9a
Show file tree
Hide file tree
Showing 32 changed files with 141 additions and 155 deletions.
42 changes: 21 additions & 21 deletions packages/core/src/robotcode/core/concurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
__THREADED_MARKER = "__robotcode_threaded"


class FutureEx(Future, Generic[_TResult]): # type: ignore[type-arg]
class Task(Future, Generic[_TResult]): # type: ignore[type-arg]
def __init__(self) -> None:
super().__init__()
self.cancelation_requested_event = Event()
Expand All @@ -38,7 +38,7 @@ def cancel(self) -> bool:
def result(self, timeout: Optional[float] = None) -> _TResult:
return cast(_TResult, super().result(timeout))

def add_done_callback(self, fn: Callable[["FutureEx[Any]"], Any]) -> None:
def add_done_callback(self, fn: Callable[["Task[Any]"], Any]) -> None:
super().add_done_callback(fn) # type: ignore[arg-type]


Expand Down Expand Up @@ -74,14 +74,14 @@ def is_threaded_callable(callable: Callable[..., Any]) -> bool:
class _Local(local):
def __init__(self) -> None:
super().__init__()
self._local_future: Optional[FutureEx[Any]] = None
self._local_future: Optional[Task[Any]] = None


_local_storage = _Local()


def _run_callable_in_thread_handler(
future: FutureEx[_TResult],
def _run_task_in_thread_handler(
future: Task[_TResult],
callable: Callable[..., _TResult],
args: Tuple[Any, ...],
kwargs: Dict[str, Any],
Expand All @@ -102,12 +102,12 @@ def _run_callable_in_thread_handler(
_local_storage._local_future = None


def is_current_thread_cancelled() -> bool:
def is_current_task_cancelled() -> bool:
local_future = _local_storage._local_future
return local_future is not None and local_future.cancelation_requested


def check_current_thread_canceled(at_least_seconds: Optional[float] = None, raise_exception: bool = True) -> bool:
def check_current_task_canceled(at_least_seconds: Optional[float] = None, raise_exception: bool = True) -> bool:
local_future = _local_storage._local_future
if local_future is None:
return False
Expand All @@ -125,39 +125,39 @@ def check_current_thread_canceled(at_least_seconds: Optional[float] = None, rais
return True


_running_callables_lock = RLock()
_running_callables: Dict[FutureEx[Any], Thread] = {}
_running_tasks_lock = RLock()
_running_tasks: Dict[Task[Any], Thread] = {}


def _remove_future_from_running_callables(future: FutureEx[Any]) -> None:
with _running_callables_lock:
_running_callables.pop(future, None)
def _remove_future_from_running_tasks(future: Task[Any]) -> None:
with _running_tasks_lock:
_running_tasks.pop(future, None)


_P = ParamSpec("_P")


def run_in_thread(callable: Callable[_P, _TResult], *args: _P.args, **kwargs: _P.kwargs) -> FutureEx[_TResult]:
future: FutureEx[_TResult] = FutureEx()
with _running_callables_lock:
def run_as_task(callable: Callable[_P, _TResult], *args: _P.args, **kwargs: _P.kwargs) -> Task[_TResult]:
future: Task[_TResult] = Task()
with _running_tasks_lock:
thread = Thread(
target=_run_callable_in_thread_handler,
target=_run_task_in_thread_handler,
args=(future, callable, args, kwargs),
name=str(callable),
)
_running_callables[future] = thread
future.add_done_callback(_remove_future_from_running_callables)
_running_tasks[future] = thread
future.add_done_callback(_remove_future_from_running_tasks)
# TODO: don't set daemon=True because it can be deprecated in future pyhton versions
thread.daemon = True
thread.start()

return future


def cancel_running_callables(timeout: Optional[float] = None) -> None:
def _cancel_all_running_tasks(timeout: Optional[float] = None) -> None:
threads: List[Thread] = []
with _running_callables_lock:
for future, thread in _running_callables.items():
with _running_tasks_lock:
for future, thread in _running_tasks.items():
if not future.cancelation_requested:
future.cancel()
threads.append(thread)
Expand Down
6 changes: 3 additions & 3 deletions packages/debugger/src/robotcode/debugger/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
Union,
)

from robotcode.core.concurrent import FutureEx
from robotcode.core.concurrent import Task
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 @@ -308,8 +308,8 @@ def send_response(
)

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

with self._sended_request_lock:
self._sended_request[request.seq] = SendedRequestEntry(result, return_type)
Expand Down
12 changes: 6 additions & 6 deletions packages/jsonrpc2/src/robotcode/jsonrpc2/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
)

from robotcode.core.async_tools import run_coroutine_in_thread
from robotcode.core.concurrent import FutureEx, run_in_thread
from robotcode.core.concurrent import Task, run_as_task
from robotcode.core.event import event
from robotcode.core.utils.dataclasses import as_json, from_dict
from robotcode.core.utils.inspect import ensure_coroutine, iter_methods
Expand Down Expand Up @@ -352,7 +352,7 @@ def get_param_type(self, name: str) -> Optional[Type[Any]]:


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

Expand Down Expand Up @@ -567,8 +567,8 @@ def send_request(
method: str,
params: Optional[Any] = None,
return_type: Optional[Type[_TResult]] = None,
) -> FutureEx[_TResult]:
result: FutureEx[_TResult] = FutureEx()
) -> Task[_TResult]:
result: Task[_TResult] = Task()

with self._sended_request_lock:
self._sended_request_count += 1
Expand Down Expand Up @@ -753,7 +753,7 @@ async def handle_request(self, message: JsonRPCRequest) -> None:
**params[1],
)
else:
task = asyncio.wrap_future(run_in_thread(e.method, *params[0], **params[1]))
task = asyncio.wrap_future(run_as_task(e.method, *params[0], **params[1]))
else:
task = asyncio.create_task(e.method(*params[0], **params[1]), name=message.method)

Expand Down Expand Up @@ -850,7 +850,7 @@ async def handle_notification(self, message: JsonRPCNotification) -> None:
ensure_coroutine(cast(Callable[..., Any], e.method)), *params[0], **params[1]
)
else:
task = asyncio.wrap_future(run_in_thread(e.method, *params[0], **params[1]))
task = asyncio.wrap_future(run_as_task(e.method, *params[0], **params[1]))
else:
task = asyncio.create_task(e.method(*params[0], **params[1]), name=message.method)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from itertools import chain
from typing import TYPE_CHECKING, Any, Final, List, Optional, Union, cast

from robotcode.core.concurrent import check_current_thread_canceled
from robotcode.core.concurrent import check_current_task_canceled
from robotcode.core.event import event
from robotcode.core.lsp.types import (
CodeAction,
Expand Down Expand Up @@ -94,7 +94,7 @@ def _text_document_code_action(
context,
callback_filter=language_id_filter(document),
):
check_current_thread_canceled()
check_current_task_canceled()

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand All @@ -113,7 +113,7 @@ def _text_document_code_action_resolve(self, params: CodeAction, *args: Any, **k
results: List[CodeAction] = []

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

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from concurrent.futures import CancelledError
from typing import TYPE_CHECKING, Any, Final, List, Optional

from robotcode.core.concurrent import FutureEx, check_current_thread_canceled, run_in_thread
from robotcode.core.concurrent import Task, check_current_task_canceled, run_as_task
from robotcode.core.event import event
from robotcode.core.lsp.types import (
CodeLens,
Expand All @@ -26,7 +26,7 @@ class CodeLensProtocolPart(LanguageServerProtocolPart):

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

@event
Expand All @@ -51,7 +51,7 @@ def _text_document_code_lens(
return None

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

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand All @@ -73,7 +73,7 @@ def _code_lens_resolve(self, params: CodeLens, *args: Any, **kwargs: Any) -> Cod
results: List[CodeLens] = []

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

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand All @@ -92,7 +92,7 @@ def refresh(self, now: bool = True) -> None:
if self.refresh_task is not None and not self.refresh_task.done():
self.refresh_task.cancel()

self.refresh_task = run_in_thread(self._refresh, now)
self.refresh_task = run_as_task(self._refresh, now)

def _refresh(self, now: bool = True) -> None:
if (
Expand All @@ -102,6 +102,6 @@ def _refresh(self, now: bool = True) -> None:
and self.parent.client_capabilities.workspace.code_lens.refresh_support
):
if not now:
check_current_thread_canceled(1)
check_current_task_canceled(1)

self.parent.send_request("workspace/codeLens/refresh").result(self._refresh_timeout)
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from itertools import chain
from typing import TYPE_CHECKING, Any, Final, List, Optional, Union, cast

from robotcode.core.concurrent import check_current_thread_canceled
from robotcode.core.concurrent import check_current_task_canceled
from robotcode.core.event import event
from robotcode.core.lsp.types import (
CompletionContext,
Expand Down Expand Up @@ -96,7 +96,7 @@ def _text_document_completion(
results: List[Union[List[CompletionItem], CompletionList]] = []

if context is not None and context.trigger_kind == CompletionTriggerKind.TRIGGER_CHARACTER:
check_current_thread_canceled(0.25)
check_current_task_canceled(0.25)

document = self.parent.documents.get(text_document.uri)
if document is None:
Expand All @@ -111,7 +111,7 @@ def _text_document_completion(
context,
callback_filter=language_id_filter(document),
):
check_current_thread_canceled()
check_current_task_canceled()

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand All @@ -124,7 +124,7 @@ def _text_document_completion(
return None

for result in results:
check_current_thread_canceled()
check_current_task_canceled()

if isinstance(result, CompletionList):
for item in result.items:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from asyncio import CancelledError
from typing import TYPE_CHECKING, Any, Final, List, Optional, Union

from robotcode.core.concurrent import check_current_thread_canceled
from robotcode.core.concurrent import check_current_task_canceled
from robotcode.core.event import event
from robotcode.core.lsp.types import (
DeclarationParams,
Expand Down Expand Up @@ -70,7 +70,7 @@ def _text_document_declaration(
position,
callback_filter=language_id_filter(document),
):
check_current_thread_canceled()
check_current_task_canceled()

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from concurrent.futures import CancelledError
from typing import TYPE_CHECKING, Any, Final, List, Optional, Union

from robotcode.core.concurrent import check_current_thread_canceled
from robotcode.core.concurrent import check_current_task_canceled
from robotcode.core.event import event
from robotcode.core.lsp.types import (
DefinitionParams,
Expand Down Expand Up @@ -70,7 +70,7 @@ def _text_document_definition(
document.position_from_utf16(position),
callback_filter=language_id_filter(document),
):
check_current_thread_canceled()
check_current_task_canceled()

if isinstance(result, BaseException):
if not isinstance(result, CancelledError):
Expand Down
Loading

0 comments on commit d75eb9a

Please sign in to comment.