forked from goodboy/tractor
1
0
Fork 0
tractor/tractor/_state.py

69 lines
1.6 KiB
Python
Raw Normal View History

2018-07-14 20:09:05 +00:00
"""
Per process state
"""
2020-10-13 15:03:55 +00:00
from typing import Optional, Dict, Any
2020-12-18 22:58:07 +00:00
from collections.abc import Mapping
2020-07-23 17:14:15 +00:00
import multiprocessing as mp
2018-07-14 20:09:05 +00:00
import trio
2018-07-14 20:09:05 +00:00
2021-04-27 15:07:53 +00:00
from ._exceptions import NoRuntime
2021-01-03 16:18:31 +00:00
_current_actor: Optional['Actor'] = None # type: ignore # noqa
2020-10-13 15:03:55 +00:00
_runtime_vars: Dict[str, Any] = {
2020-07-23 17:14:15 +00:00
'_debug_mode': False,
'_is_root': False,
'_root_mailbox': (None, None)
2020-07-23 17:14:15 +00:00
}
2018-08-31 21:16:24 +00:00
2021-01-03 16:18:31 +00:00
def current_actor(err_on_no_runtime: bool = True) -> 'Actor': # type: ignore # noqa
2018-07-14 20:09:05 +00:00
"""Get the process-local actor instance.
"""
2021-01-03 02:35:13 +00:00
if _current_actor is None and err_on_no_runtime:
2021-04-27 15:07:53 +00:00
raise NoRuntime("No local actor has been initialized yet")
2021-01-03 02:35:13 +00:00
2018-07-14 20:09:05 +00:00
return _current_actor
2021-01-03 16:18:31 +00:00
_conc_name_getters = {
'task': trio.lowlevel.current_task,
'actor': current_actor
}
class ActorContextInfo(Mapping):
"Dyanmic lookup for local actor and task names"
_context_keys = ('task', 'actor')
def __len__(self):
return len(self._context_keys)
def __iter__(self):
return iter(self._context_keys)
2021-01-03 16:18:31 +00:00
def __getitem__(self, key: str) -> str:
try:
2021-01-03 16:18:31 +00:00
return _conc_name_getters[key]().name # type: ignore
except RuntimeError:
# no local actor/task context initialized yet
return f'no {key} context'
2020-07-23 17:14:15 +00:00
def is_main_process() -> bool:
"""Bool determining if this actor is running in the top-most process.
"""
return mp.current_process().name == 'MainProcess'
def debug_mode() -> bool:
"""Bool determining if "debug mode" is on which enables
remote subactor pdb entry on crashes.
"""
2020-10-13 15:03:55 +00:00
return bool(_runtime_vars['_debug_mode'])
2020-07-23 17:14:15 +00:00
def is_root_process() -> bool:
return _runtime_vars['_is_root']