mirror of
https://github.com/tiqi-group/pydase.git
synced 2025-12-18 12:11:20 +01:00
Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
197268255b | ||
|
|
3698cb7f92 | ||
|
|
0625832457 | ||
|
|
f35bcf3be6 | ||
|
|
3fe77bb4e5 | ||
|
|
9b2d181f4a | ||
|
|
045334e51e | ||
|
|
1d8d17d715 | ||
|
|
4d84c9778f | ||
|
|
e3c144fa6e | ||
|
|
192075057f | ||
|
|
053050a62c | ||
|
|
aacc69ae94 | ||
|
|
de1483bdc5 | ||
|
|
b24db00eda | ||
|
|
36ee760610 | ||
|
|
3a67c07bad | ||
|
|
b9a91e5ee2 | ||
|
|
f83bc0073b | ||
|
|
c66b90c4e5 | ||
|
|
d0b0803407 | ||
|
|
e25511768d | ||
|
|
303de82318 | ||
|
|
db559e8ada | ||
|
|
1b35dba64f | ||
|
|
8a8ac9d297 | ||
|
|
40a8863ecd | ||
|
|
1dca04f693 | ||
|
|
2b520834dc | ||
|
|
d6bad37233 | ||
|
|
53a2a3303f | ||
|
|
4f206bbae9 | ||
|
|
090b8acd44 | ||
|
|
17b2ad32e5 | ||
|
|
3c99f3fe04 | ||
|
|
2bcc6b9660 | ||
|
|
c1ace54c78 | ||
|
|
56af2a423b | ||
|
|
eba0eb83e6 | ||
|
|
b7818c0d8a | ||
|
|
a0c3882f35 | ||
|
|
1d773ba09b | ||
|
|
10f1b8691c | ||
|
|
a99db6f053 |
5
.github/ISSUE_TEMPLATE/bug_report.md
vendored
5
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -18,7 +18,10 @@ Provide steps to reproduce the behaviour, including a minimal code snippet (if a
|
||||
## Expected behaviour
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
## Screenshot/Video
|
||||
## Actual behaviour
|
||||
Describe what you see instead of the expected behaviour.
|
||||
|
||||
### Screenshot/Video
|
||||
If applicable, add visual content that helps explain your problem.
|
||||
|
||||
## Additional context
|
||||
|
||||
6
.github/workflows/publish-to-pypi.yaml
vendored
6
.github/workflows/publish-to-pypi.yaml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
- name: Build a binary wheel and a source tarball
|
||||
run: python3 -m build
|
||||
- name: Store the distribution packages
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: python-package-distributions
|
||||
path: dist/
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Download all the dists
|
||||
uses: actions/download-artifact@v3
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: python-package-distributions
|
||||
path: dist/
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Download all the dists
|
||||
uses: actions/download-artifact@v3
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: python-package-distributions
|
||||
path: dist/
|
||||
|
||||
@@ -247,6 +247,7 @@ You have two primary ways to adjust the log levels in `pydase`:
|
||||
# logging.getLogger("pydase.data_service").setLevel(logging.DEBUG)
|
||||
|
||||
# Your logger for the current script
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.info("My info message.")
|
||||
```
|
||||
|
||||
55
docs/user-guide/Logging.md
Normal file
55
docs/user-guide/Logging.md
Normal file
@@ -0,0 +1,55 @@
|
||||
## Logging in pydase
|
||||
|
||||
The `pydase` library organizes its loggers per module, mirroring the Python package hierarchy. This structured approach allows for granular control over logging levels and behaviour across different parts of the library. Logs can also include details about client identification based on headers sent by the client or proxy, providing additional context for debugging or auditing.
|
||||
|
||||
### Changing the Log Level
|
||||
|
||||
You have two primary ways to adjust the log levels in `pydase`:
|
||||
|
||||
1. **Directly targeting `pydase` loggers**
|
||||
|
||||
You can set the log level for any `pydase` logger directly in your code. This method is useful for fine-tuning logging levels for specific modules within `pydase`. For instance, if you want to change the log level of the main `pydase` logger or target a submodule like `pydase.data_service`, you can do so as follows:
|
||||
|
||||
```python
|
||||
# <your_script.py>
|
||||
import logging
|
||||
|
||||
# Set the log level for the main pydase logger
|
||||
logging.getLogger("pydase").setLevel(logging.INFO)
|
||||
|
||||
# Optionally, target a specific submodule logger
|
||||
# logging.getLogger("pydase.data_service").setLevel(logging.DEBUG)
|
||||
|
||||
# Your logger for the current script
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.info("My info message.")
|
||||
```
|
||||
|
||||
This approach allows for specific control over different parts of the `pydase` library, depending on your logging needs.
|
||||
|
||||
2. **Using the `ENVIRONMENT` environment variable**
|
||||
|
||||
For a more global setting that affects the entire `pydase` library, you can utilize the `ENVIRONMENT` environment variable. Setting this variable to `"production"` will configure all `pydase` loggers to only log messages of level `"INFO"` and above, filtering out more verbose logging. This is particularly useful for production environments where excessive logging can be overwhelming or unnecessary.
|
||||
|
||||
```bash
|
||||
ENVIRONMENT="production" python -m <module_using_pydase>
|
||||
```
|
||||
|
||||
In the absence of this setting, the default behavior is to log everything of level `"DEBUG"` and above, suitable for development environments where more detailed logs are beneficial.
|
||||
|
||||
### Client Identification in Logs
|
||||
|
||||
The logging system in `pydase` includes information about clients based on headers sent by the client or a proxy. The priority for identifying the client is fixed and as follows:
|
||||
|
||||
1. **`Remote-User` Header**: This header is typically set by authentication servers like [Authelia](https://www.authelia.com/). While it can be set manually by users, its primary purpose is to provide client information authenticated through such servers.
|
||||
2. **`X-Client-ID` Header**: This header is intended for use by Python clients to pass custom client identification information. It acts as a fallback when the `Remote-User` header is not available.
|
||||
3. **Default Socket.IO Session ID**: If neither of the above headers is present, the system falls back to the default Socket.IO session ID to identify the client.
|
||||
|
||||
For example, a log entries might include the following details based on the available headers:
|
||||
|
||||
```plaintext
|
||||
2025-01-20 06:47:50.940 | INFO | pydase.server.web_server.api.v1.application:_get_value:36 - Client [id=This is me!] is getting the value of 'property_attr'
|
||||
|
||||
2025-01-20 06:48:13.710 | INFO | pydase.server.web_server.api.v1.application:_get_value:36 - Client [user=Max Muster] is getting the value of 'property_attr'
|
||||
```
|
||||
@@ -1,8 +1,8 @@
|
||||
# Understanding Tasks
|
||||
|
||||
In `pydase`, a task is defined as an asynchronous function without arguments that is decorated with the `@task` decorator and contained in a class that inherits from `pydase.DataService`. These tasks usually contain a while loop and are designed to carry out periodic functions. For example, a task might be used to periodically read sensor data, update a database, or perform any other recurring job.
|
||||
In `pydase`, a task is defined as an asynchronous function without arguments that is decorated with the [`@task`][pydase.task.decorator.task] decorator and contained in a class that inherits from [`pydase.DataService`][pydase.DataService]. These tasks usually contain a while loop and are designed to carry out periodic functions. For example, a task might be used to periodically read sensor data, update a database, or perform any other recurring job.
|
||||
|
||||
`pydase` allows you to control task execution via both the frontend and Python clients and can automatically start tasks upon initialization of the service. By using the `@task` decorator with the `autostart=True` argument in your service class, `pydase` will automatically start these tasks when the server is started. Here's an example:
|
||||
`pydase` allows you to control task execution via both the frontend and Python clients and can automatically start tasks upon initialization of the service. By using the [`@task`][pydase.task.decorator.task] decorator with the `autostart=True` argument in your service class, `pydase` will automatically start these tasks when the server is started. Here's an example:
|
||||
|
||||
```python
|
||||
import pydase
|
||||
@@ -35,4 +35,48 @@ if __name__ == "__main__":
|
||||
|
||||
In this example, `read_sensor_data` is a task that continuously reads data from a sensor. By decorating it with `@task(autostart=True)`, it will automatically start running when `pydase.Server(service).run()` is executed.
|
||||
|
||||
The `@task` decorator replaces the function with a task object that has `start()` and `stop()` methods. This means you can control the task execution directly using these methods. For instance, you can manually start or stop the task by calling `service.read_sensor_data.start()` and `service.read_sensor_data.stop()`, respectively.
|
||||
## Task Lifecycle Control
|
||||
|
||||
The [`@task`][pydase.task.decorator.task] decorator replaces the function with a task object that has `start()` and `stop()` methods. This means you can control the task execution directly using these methods. For instance, you can manually start or stop the task by calling `service.read_sensor_data.start()` and `service.read_sensor_data.stop()`, respectively.
|
||||
|
||||
## Advanced Task Options
|
||||
|
||||
The [`@task`][pydase.task.decorator.task] decorator supports several options inspired by systemd unit services, allowing fine-grained control over task behavior:
|
||||
|
||||
- **`autostart`**: Automatically starts the task when the service initializes. Defaults to `False`.
|
||||
- **`restart_on_exception`**: Configures whether the task should restart if it exits due to an exception (other than `asyncio.CancelledError`). Defaults to `True`.
|
||||
- **`restart_sec`**: Specifies the delay (in seconds) before restarting a failed task. Defaults to `1.0`.
|
||||
- **`start_limit_interval_sec`**: Configures a time window (in seconds) for rate limiting task restarts. If the task restarts more than `start_limit_burst` times within this interval, it will no longer restart. Defaults to `None` (disabled).
|
||||
- **`start_limit_burst`**: Defines the maximum number of restarts allowed within the interval specified by `start_limit_interval_sec`. Defaults to `3`.
|
||||
- **`exit_on_failure`**: If set to `True`, the service will exit if the task fails and either `restart_on_exception` is `False` or the start rate limiting is exceeded. Defaults to `False`.
|
||||
|
||||
### Example with Advanced Options
|
||||
|
||||
Here is an example showcasing advanced task options:
|
||||
|
||||
```python
|
||||
import pydase
|
||||
from pydase.task.decorator import task
|
||||
|
||||
|
||||
class AdvancedTaskService(pydase.DataService):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
@task(
|
||||
autostart=True,
|
||||
restart_on_exception=True,
|
||||
restart_sec=2.0,
|
||||
start_limit_interval_sec=10.0,
|
||||
start_limit_burst=5,
|
||||
exit_on_failure=True,
|
||||
)
|
||||
async def critical_task(self):
|
||||
while True:
|
||||
raise Exception("Critical failure")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
service = AdvancedTaskService()
|
||||
pydase.Server(service=service).run()
|
||||
```
|
||||
|
||||
@@ -199,16 +199,8 @@ export const NumberComponent = React.memo((props: NumberComponentProps) => {
|
||||
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
const { key, target } = event;
|
||||
|
||||
// Typecast
|
||||
const inputTarget = target as HTMLInputElement;
|
||||
if (
|
||||
key === "F1" ||
|
||||
key === "F5" ||
|
||||
key === "F12" ||
|
||||
key === "Tab" ||
|
||||
key === "ArrowRight" ||
|
||||
key === "ArrowLeft"
|
||||
) {
|
||||
if (key === "F1" || key === "F5" || key === "F12" || key === "Tab") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
@@ -223,6 +215,11 @@ export const NumberComponent = React.memo((props: NumberComponentProps) => {
|
||||
// Select everything when pressing Ctrl + a
|
||||
inputTarget.setSelectionRange(0, value.length);
|
||||
return;
|
||||
} else if (key === "ArrowRight" || key === "ArrowLeft") {
|
||||
// Move the cursor with the arrow keys and store its position
|
||||
selectionStart = key === "ArrowRight" ? selectionStart + 1 : selectionStart - 1;
|
||||
setCursorPosition(selectionStart);
|
||||
return;
|
||||
} else if ((key >= "0" && key <= "9") || key === "-") {
|
||||
// Check if a number key or a decimal point key is pressed
|
||||
({ value: newValue, selectionStart } = handleNumericKey(
|
||||
|
||||
@@ -12,6 +12,7 @@ nav:
|
||||
- Understanding Units: user-guide/Understanding-Units.md
|
||||
- Validating Property Setters: user-guide/Validating-Property-Setters.md
|
||||
- Configuring pydase: user-guide/Configuration.md
|
||||
- Logging in pydase: user-guide/Logging.md
|
||||
- Advanced:
|
||||
- Deploying behind a Reverse Proxy: user-guide/advanced/Reverse-Proxy.md
|
||||
- Developer Guide:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "pydase"
|
||||
version = "0.10.7"
|
||||
version = "0.10.8"
|
||||
description = "A flexible and robust Python library for creating, managing, and interacting with data services, with built-in support for web and RPC servers, and customizable features for diverse use cases."
|
||||
authors = ["Mose Mueller <mosmuell@ethz.ch>"]
|
||||
readme = "README.md"
|
||||
|
||||
@@ -13,11 +13,11 @@ class NumberSlider(DataService):
|
||||
|
||||
Args:
|
||||
value:
|
||||
The initial value of the slider. Defaults to 0.
|
||||
The initial value of the slider. Defaults to 0.0.
|
||||
min_:
|
||||
The minimum value of the slider. Defaults to 0.
|
||||
The minimum value of the slider. Defaults to 0.0.
|
||||
max_:
|
||||
The maximum value of the slider. Defaults to 100.
|
||||
The maximum value of the slider. Defaults to 100.0.
|
||||
step_size:
|
||||
The increment/decrement step size of the slider. Defaults to 1.0.
|
||||
|
||||
@@ -84,9 +84,9 @@ class NumberSlider(DataService):
|
||||
def __init__(
|
||||
self,
|
||||
value: Any = 0.0,
|
||||
min_: float = 0.0,
|
||||
max_: float = 100.0,
|
||||
step_size: float = 1.0,
|
||||
min_: Any = 0.0,
|
||||
max_: Any = 100.0,
|
||||
step_size: Any = 1.0,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._step_size = step_size
|
||||
@@ -95,17 +95,17 @@ class NumberSlider(DataService):
|
||||
self._max = max_
|
||||
|
||||
@property
|
||||
def min(self) -> float:
|
||||
def min(self) -> Any:
|
||||
"""The min property."""
|
||||
return self._min
|
||||
|
||||
@property
|
||||
def max(self) -> float:
|
||||
def max(self) -> Any:
|
||||
"""The min property."""
|
||||
return self._max
|
||||
|
||||
@property
|
||||
def step_size(self) -> float:
|
||||
def step_size(self) -> Any:
|
||||
"""The min property."""
|
||||
return self._step_size
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ from pydase.observer_pattern.observer.property_observer import (
|
||||
)
|
||||
from pydase.utils.helpers import (
|
||||
get_object_attr_from_path,
|
||||
normalize_full_access_path_string,
|
||||
)
|
||||
from pydase.utils.serialization.serializer import (
|
||||
SerializationPathError,
|
||||
@@ -102,8 +101,7 @@ class DataServiceObserver(PropertyObserver):
|
||||
)
|
||||
|
||||
def _notify_dependent_property_changes(self, changed_attr_path: str) -> None:
|
||||
normalized_attr_path = normalize_full_access_path_string(changed_attr_path)
|
||||
changed_props = self.property_deps_dict.get(normalized_attr_path, [])
|
||||
changed_props = self.property_deps_dict.get(changed_attr_path, [])
|
||||
for prop in changed_props:
|
||||
# only notify about changing attribute if it is not currently being
|
||||
# "changed" e.g. when calling the getter of a property within another
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,7 +7,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta name="description" content="Web site displaying a pydase UI." />
|
||||
<script type="module" crossorigin src="/assets/index-BqF7l_R8.js"></script>
|
||||
<script type="module" crossorigin src="/assets/index-B4RiTBEo.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-D2aktF3W.css">
|
||||
</head>
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ class PropertyObserver(Observer):
|
||||
elif isinstance(collection, dict):
|
||||
for key, val in collection.items():
|
||||
if isinstance(val, Observable):
|
||||
new_prefix = f"{parent_path}['{key}']"
|
||||
new_prefix = f'{parent_path}["{key}"]'
|
||||
deps.update(
|
||||
self._get_properties_and_their_dependencies(val, new_prefix)
|
||||
)
|
||||
|
||||
@@ -258,7 +258,7 @@ class Server:
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("Cancelled '%s' server.", server_name)
|
||||
except Exception as e:
|
||||
logger.error("Unexpected exception: %s", e)
|
||||
logger.exception("Unexpected exception: %s", e)
|
||||
|
||||
async def __cancel_tasks(self) -> None:
|
||||
for task in asyncio.all_tasks(self._loop):
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import inspect
|
||||
import logging
|
||||
from functools import partial
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import aiohttp.web
|
||||
import aiohttp_middlewares.error
|
||||
import click
|
||||
|
||||
from pydase.data_service.state_manager import StateManager
|
||||
from pydase.server.web_server.api.v1.endpoints import (
|
||||
@@ -25,12 +27,14 @@ STATUS_FAILED = 400
|
||||
|
||||
|
||||
async def _get_value(
|
||||
state_manager: StateManager, request: aiohttp.web.Request
|
||||
request: aiohttp.web.Request, state_manager: StateManager
|
||||
) -> aiohttp.web.Response:
|
||||
logger.info("Handle api request: %s", request)
|
||||
log_id = get_log_id(request)
|
||||
|
||||
access_path = request.rel_url.query["access_path"]
|
||||
|
||||
logger.info("Client [%s] is getting the value of '%s'", log_id, access_path)
|
||||
|
||||
status = STATUS_OK
|
||||
try:
|
||||
result = get_value(state_manager, access_path)
|
||||
@@ -42,10 +46,16 @@ async def _get_value(
|
||||
|
||||
|
||||
async def _update_value(
|
||||
state_manager: StateManager, request: aiohttp.web.Request
|
||||
request: aiohttp.web.Request, state_manager: StateManager
|
||||
) -> aiohttp.web.Response:
|
||||
log_id = get_log_id(request)
|
||||
|
||||
data: UpdateDict = await request.json()
|
||||
|
||||
logger.info(
|
||||
"Client [%s] is updating the value of '%s'", log_id, data["access_path"]
|
||||
)
|
||||
|
||||
try:
|
||||
update_value(state_manager, data)
|
||||
|
||||
@@ -56,11 +66,17 @@ async def _update_value(
|
||||
|
||||
|
||||
async def _trigger_method(
|
||||
state_manager: StateManager, request: aiohttp.web.Request
|
||||
request: aiohttp.web.Request, state_manager: StateManager
|
||||
) -> aiohttp.web.Response:
|
||||
log_id = get_log_id(request)
|
||||
|
||||
data: TriggerMethodDict = await request.json()
|
||||
|
||||
method = get_object_attr_from_path(state_manager.service, data["access_path"])
|
||||
access_path = data["access_path"]
|
||||
|
||||
logger.info("Client [%s] is triggering the method '%s'", log_id, access_path)
|
||||
|
||||
method = get_object_attr_from_path(state_manager.service, access_path)
|
||||
|
||||
try:
|
||||
if inspect.iscoroutinefunction(method):
|
||||
@@ -77,22 +93,33 @@ async def _trigger_method(
|
||||
return aiohttp.web.json_response(dump(e), status=STATUS_FAILED)
|
||||
|
||||
|
||||
def get_log_id(request: aiohttp.web.Request) -> str:
|
||||
client_id_header = request.headers.get("x-client-id", None)
|
||||
remote_username_header = request.headers.get("remote-user", None)
|
||||
|
||||
if remote_username_header is not None:
|
||||
log_id = f"user={click.style(remote_username_header, fg='cyan')}"
|
||||
elif client_id_header is not None:
|
||||
log_id = f"id={click.style(client_id_header, fg='cyan')}"
|
||||
else:
|
||||
log_id = f"id={click.style(None, fg='cyan')}"
|
||||
|
||||
return log_id
|
||||
|
||||
|
||||
def create_api_application(state_manager: StateManager) -> aiohttp.web.Application:
|
||||
api_application = aiohttp.web.Application(
|
||||
middlewares=(aiohttp_middlewares.error.error_middleware(),)
|
||||
)
|
||||
|
||||
api_application.router.add_get(
|
||||
"/get_value",
|
||||
lambda request: _get_value(state_manager=state_manager, request=request),
|
||||
"/get_value", partial(_get_value, state_manager=state_manager)
|
||||
)
|
||||
api_application.router.add_put(
|
||||
"/update_value",
|
||||
lambda request: _update_value(state_manager=state_manager, request=request),
|
||||
"/update_value", partial(_update_value, state_manager=state_manager)
|
||||
)
|
||||
api_application.router.add_put(
|
||||
"/trigger_method",
|
||||
lambda request: _trigger_method(state_manager=state_manager, request=request),
|
||||
"/trigger_method", partial(_trigger_method, state_manager=state_manager)
|
||||
)
|
||||
|
||||
return api_application
|
||||
|
||||
@@ -141,22 +141,41 @@ def setup_sio_server(
|
||||
def setup_sio_events(sio: socketio.AsyncServer, state_manager: StateManager) -> None: # noqa: C901
|
||||
@sio.event # type: ignore
|
||||
async def connect(sid: str, environ: Any) -> None:
|
||||
logger.debug("Client [%s] connected", click.style(str(sid), fg="cyan"))
|
||||
client_id_header = environ.get("HTTP_X_CLIENT_ID", None)
|
||||
remote_username_header = environ.get("HTTP_REMOTE_USER", None)
|
||||
|
||||
if remote_username_header is not None:
|
||||
log_id = f"user={click.style(remote_username_header, fg='cyan')}"
|
||||
elif client_id_header is not None:
|
||||
log_id = f"id={click.style(client_id_header, fg='cyan')}"
|
||||
else:
|
||||
log_id = f"sid={click.style(sid, fg='cyan')}"
|
||||
|
||||
async with sio.session(sid) as session:
|
||||
session["client_id"] = log_id
|
||||
logger.info("Client [%s] connected", session["client_id"])
|
||||
|
||||
@sio.event # type: ignore
|
||||
async def disconnect(sid: str) -> None:
|
||||
logger.debug("Client [%s] disconnected", click.style(str(sid), fg="cyan"))
|
||||
async with sio.session(sid) as session:
|
||||
logger.info("Client [%s] disconnected", session["client_id"])
|
||||
|
||||
@sio.event # type: ignore
|
||||
async def service_serialization(sid: str) -> SerializedObject:
|
||||
logger.debug(
|
||||
"Client [%s] requested service serialization",
|
||||
click.style(str(sid), fg="cyan"),
|
||||
)
|
||||
async with sio.session(sid) as session:
|
||||
logger.info(
|
||||
"Client [%s] requested service serialization", session["client_id"]
|
||||
)
|
||||
return state_manager.cache_manager.cache
|
||||
|
||||
@sio.event
|
||||
async def update_value(sid: str, data: UpdateDict) -> SerializedObject | None:
|
||||
async with sio.session(sid) as session:
|
||||
logger.info(
|
||||
"Client [%s] is updating the value of '%s'",
|
||||
session["client_id"],
|
||||
data["access_path"],
|
||||
)
|
||||
try:
|
||||
endpoints.update_value(state_manager=state_manager, data=data)
|
||||
except Exception as e:
|
||||
@@ -166,6 +185,12 @@ def setup_sio_events(sio: socketio.AsyncServer, state_manager: StateManager) ->
|
||||
|
||||
@sio.event
|
||||
async def get_value(sid: str, access_path: str) -> SerializedObject:
|
||||
async with sio.session(sid) as session:
|
||||
logger.info(
|
||||
"Client [%s] is getting the value of '%s'",
|
||||
session["client_id"],
|
||||
access_path,
|
||||
)
|
||||
try:
|
||||
return endpoints.get_value(
|
||||
state_manager=state_manager, access_path=access_path
|
||||
@@ -176,16 +201,23 @@ def setup_sio_events(sio: socketio.AsyncServer, state_manager: StateManager) ->
|
||||
|
||||
@sio.event
|
||||
async def trigger_method(sid: str, data: TriggerMethodDict) -> Any:
|
||||
method = get_object_attr_from_path(state_manager.service, data["access_path"])
|
||||
|
||||
async with sio.session(sid) as session:
|
||||
logger.debug(
|
||||
"Client [%s] is triggering the method '%s'",
|
||||
session["client_id"],
|
||||
data["access_path"],
|
||||
)
|
||||
try:
|
||||
method = get_object_attr_from_path(
|
||||
state_manager.service, data["access_path"]
|
||||
)
|
||||
if inspect.iscoroutinefunction(method):
|
||||
return await endpoints.trigger_async_method(
|
||||
state_manager=state_manager, data=data
|
||||
)
|
||||
return endpoints.trigger_method(state_manager=state_manager, data=data)
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
logger.exception(e)
|
||||
return dump(e)
|
||||
|
||||
|
||||
|
||||
@@ -26,15 +26,25 @@ class PerInstanceTaskDescriptor(Generic[R]):
|
||||
the service class.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
def __init__( # noqa: PLR0913
|
||||
self,
|
||||
func: Callable[[Any], Coroutine[None, None, R]]
|
||||
| Callable[[], Coroutine[None, None, R]],
|
||||
autostart: bool = False,
|
||||
autostart: bool,
|
||||
restart_on_exception: bool,
|
||||
restart_sec: float,
|
||||
start_limit_interval_sec: float | None,
|
||||
start_limit_burst: int,
|
||||
exit_on_failure: bool,
|
||||
) -> None:
|
||||
self.__func = func
|
||||
self.__autostart = autostart
|
||||
self.__task_instances: dict[object, Task[R]] = {}
|
||||
self.__restart_on_exception = restart_on_exception
|
||||
self.__restart_sec = restart_sec
|
||||
self.__start_limit_interval_sec = start_limit_interval_sec
|
||||
self.__start_limit_burst = start_limit_burst
|
||||
self.__exit_on_failure = exit_on_failure
|
||||
|
||||
def __set_name__(self, owner: type[DataService], name: str) -> None:
|
||||
"""Stores the name of the task within the owning class. This method is called
|
||||
@@ -67,14 +77,28 @@ class PerInstanceTaskDescriptor(Generic[R]):
|
||||
if instance not in self.__task_instances:
|
||||
self.__task_instances[instance] = instance._initialise_new_objects(
|
||||
self.__task_name,
|
||||
Task(self.__func.__get__(instance, owner), autostart=self.__autostart),
|
||||
Task(
|
||||
self.__func.__get__(instance, owner),
|
||||
autostart=self.__autostart,
|
||||
restart_on_exception=self.__restart_on_exception,
|
||||
restart_sec=self.__restart_sec,
|
||||
start_limit_interval_sec=self.__start_limit_interval_sec,
|
||||
start_limit_burst=self.__start_limit_burst,
|
||||
exit_on_failure=self.__exit_on_failure,
|
||||
),
|
||||
)
|
||||
|
||||
return self.__task_instances[instance]
|
||||
|
||||
|
||||
def task(
|
||||
*, autostart: bool = False
|
||||
def task( # noqa: PLR0913
|
||||
*,
|
||||
autostart: bool = False,
|
||||
restart_on_exception: bool = True,
|
||||
restart_sec: float = 1.0,
|
||||
start_limit_interval_sec: float | None = None,
|
||||
start_limit_burst: int = 3,
|
||||
exit_on_failure: bool = False,
|
||||
) -> Callable[
|
||||
[
|
||||
Callable[[Any], Coroutine[None, None, R]]
|
||||
@@ -96,13 +120,30 @@ def task(
|
||||
periodically or perform asynchronous operations, such as polling data sources,
|
||||
updating databases, or any recurring job that should be managed within the context
|
||||
of a `DataService`.
|
||||
time.
|
||||
|
||||
The keyword arguments that can be passed to this decorator are inspired by systemd
|
||||
unit services.
|
||||
|
||||
Args:
|
||||
autostart:
|
||||
If set to True, the task will automatically start when the service is
|
||||
initialized. Defaults to False.
|
||||
|
||||
restart_on_exception:
|
||||
Configures whether the task shall be restarted when it exits with an
|
||||
exception other than [`asyncio.CancelledError`][asyncio.CancelledError].
|
||||
restart_sec:
|
||||
Configures the time to sleep before restarting a task. Defaults to 1.0.
|
||||
start_limit_interval_sec:
|
||||
Configures start rate limiting. Tasks which are started more than
|
||||
`start_limit_burst` times within an `start_limit_interval_sec` time span are
|
||||
not permitted to start any more. Defaults to None (disabled rate limiting).
|
||||
start_limit_burst:
|
||||
Configures unit start rate limiting. Tasks which are started more than
|
||||
`start_limit_burst` times within an `start_limit_interval_sec` time span are
|
||||
not permitted to start any more. Defaults to 3.
|
||||
exit_on_failure:
|
||||
If True, exit the service if the task fails and restart_on_exception is
|
||||
False or burst limits are exceeded.
|
||||
Returns:
|
||||
A decorator that wraps an asynchronous function in a
|
||||
[`PerInstanceTaskDescriptor`][pydase.task.decorator.PerInstanceTaskDescriptor]
|
||||
@@ -140,6 +181,14 @@ def task(
|
||||
func: Callable[[Any], Coroutine[None, None, R]]
|
||||
| Callable[[], Coroutine[None, None, R]],
|
||||
) -> PerInstanceTaskDescriptor[R]:
|
||||
return PerInstanceTaskDescriptor(func, autostart=autostart)
|
||||
return PerInstanceTaskDescriptor(
|
||||
func,
|
||||
autostart=autostart,
|
||||
restart_on_exception=restart_on_exception,
|
||||
restart_sec=restart_sec,
|
||||
start_limit_interval_sec=start_limit_interval_sec,
|
||||
start_limit_burst=start_limit_burst,
|
||||
exit_on_failure=exit_on_failure,
|
||||
)
|
||||
|
||||
return decorator
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import asyncio
|
||||
import inspect
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
from collections.abc import Callable, Coroutine
|
||||
from datetime import datetime
|
||||
from time import time
|
||||
from typing import (
|
||||
Generic,
|
||||
TypeVar,
|
||||
@@ -28,6 +31,9 @@ class Task(pydase.data_service.data_service.DataService, Generic[R]):
|
||||
decorator, it is replaced by a `Task` instance that controls the execution of the
|
||||
original function.
|
||||
|
||||
The keyword arguments that can be passed to this class are inspired by systemd unit
|
||||
services.
|
||||
|
||||
Args:
|
||||
func:
|
||||
The asynchronous function that this task wraps. It must be a coroutine
|
||||
@@ -35,6 +41,22 @@ class Task(pydase.data_service.data_service.DataService, Generic[R]):
|
||||
autostart:
|
||||
If set to True, the task will automatically start when the service is
|
||||
initialized. Defaults to False.
|
||||
restart_on_exception:
|
||||
Configures whether the task shall be restarted when it exits with an
|
||||
exception other than [`asyncio.CancelledError`][asyncio.CancelledError].
|
||||
restart_sec:
|
||||
Configures the time to sleep before restarting a task. Defaults to 1.0.
|
||||
start_limit_interval_sec:
|
||||
Configures start rate limiting. Tasks which are started more than
|
||||
`start_limit_burst` times within an `start_limit_interval_sec` time span are
|
||||
not permitted to start any more. Defaults to None (disabled rate limiting).
|
||||
start_limit_burst:
|
||||
Configures unit start rate limiting. Tasks which are started more than
|
||||
`start_limit_burst` times within an `start_limit_interval_sec` time span are
|
||||
not permitted to start any more. Defaults to 3.
|
||||
exit_on_failure:
|
||||
If True, exit the service if the task fails and restart_on_exception is
|
||||
False or burst limits are exceeded.
|
||||
|
||||
Example:
|
||||
```python
|
||||
@@ -63,14 +85,24 @@ class Task(pydase.data_service.data_service.DataService, Generic[R]):
|
||||
`service.my_task.start()` and `service.my_task.stop()`, respectively.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
def __init__( # noqa: PLR0913
|
||||
self,
|
||||
func: Callable[[], Coroutine[None, None, R | None]],
|
||||
*,
|
||||
autostart: bool = False,
|
||||
autostart: bool,
|
||||
restart_on_exception: bool,
|
||||
restart_sec: float,
|
||||
start_limit_interval_sec: float | None,
|
||||
start_limit_burst: int,
|
||||
exit_on_failure: bool,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._autostart = autostart
|
||||
self._restart_on_exception = restart_on_exception
|
||||
self._restart_sec = restart_sec
|
||||
self._start_limit_interval_sec = start_limit_interval_sec
|
||||
self._start_limit_burst = start_limit_burst
|
||||
self._exit_on_failure = exit_on_failure
|
||||
self._func_name = func.__name__
|
||||
self._func = func
|
||||
self._task: asyncio.Task[R | None] | None = None
|
||||
@@ -109,38 +141,95 @@ class Task(pydase.data_service.data_service.DataService, Generic[R]):
|
||||
self._task = None
|
||||
self._status = TaskStatus.NOT_RUNNING
|
||||
|
||||
exception = task.exception()
|
||||
exception = None
|
||||
try:
|
||||
exception = task.exception()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
|
||||
if exception is not None:
|
||||
# Handle the exception, or you can re-raise it.
|
||||
logger.error(
|
||||
"Task '%s' encountered an exception: %s: %s",
|
||||
"Task '%s' encountered an exception: %r",
|
||||
self._func_name,
|
||||
type(exception).__name__,
|
||||
exception,
|
||||
)
|
||||
raise exception
|
||||
|
||||
self._result = task.result()
|
||||
|
||||
async def run_task() -> R | None:
|
||||
if inspect.iscoroutinefunction(self._func):
|
||||
logger.info("Starting task %r", self._func_name)
|
||||
self._status = TaskStatus.RUNNING
|
||||
res: Coroutine[None, None, R | None] = self._func()
|
||||
try:
|
||||
return await res
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Task '%s' was cancelled", self._func_name)
|
||||
return None
|
||||
logger.warning(
|
||||
"Cannot start task %r. Function has not been bound yet", self._func_name
|
||||
)
|
||||
return None
|
||||
os.kill(os.getpid(), signal.SIGTERM)
|
||||
else:
|
||||
self._result = task.result()
|
||||
|
||||
logger.info("Creating task %r", self._func_name)
|
||||
self._task = self._loop.create_task(run_task())
|
||||
self._task = self._loop.create_task(self.__running_task_loop())
|
||||
self._task.add_done_callback(task_done_callback)
|
||||
|
||||
async def __running_task_loop(self) -> R | None:
|
||||
logger.info("Starting task %r", self._func_name)
|
||||
self._status = TaskStatus.RUNNING
|
||||
attempts = 0
|
||||
start_time_of_start_limit_interval = None
|
||||
|
||||
while True:
|
||||
try:
|
||||
return await self._func()
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Task '%s' was cancelled", self._func_name)
|
||||
raise
|
||||
except Exception as e:
|
||||
attempts, start_time_of_start_limit_interval = (
|
||||
self._handle_task_exception(
|
||||
e, attempts, start_time_of_start_limit_interval
|
||||
)
|
||||
)
|
||||
if not self._should_restart_task(
|
||||
attempts, start_time_of_start_limit_interval
|
||||
):
|
||||
if self._exit_on_failure:
|
||||
raise e
|
||||
break
|
||||
await asyncio.sleep(self._restart_sec)
|
||||
return None
|
||||
|
||||
def _handle_task_exception(
|
||||
self,
|
||||
exception: Exception,
|
||||
attempts: int,
|
||||
start_time_of_start_limit_interval: float | None,
|
||||
) -> tuple[int, float]:
|
||||
"""Handle an exception raised during task execution."""
|
||||
if start_time_of_start_limit_interval is None:
|
||||
start_time_of_start_limit_interval = time()
|
||||
|
||||
attempts += 1
|
||||
logger.exception(
|
||||
"Task %r encountered an exception: %r [attempt %s since %s].",
|
||||
self._func.__name__,
|
||||
exception,
|
||||
attempts,
|
||||
datetime.fromtimestamp(start_time_of_start_limit_interval),
|
||||
)
|
||||
return attempts, start_time_of_start_limit_interval
|
||||
|
||||
def _should_restart_task(
|
||||
self, attempts: int, start_time_of_start_limit_interval: float
|
||||
) -> bool:
|
||||
"""Determine if the task should be restarted."""
|
||||
if not self._restart_on_exception:
|
||||
return False
|
||||
|
||||
if self._start_limit_interval_sec is not None:
|
||||
if (
|
||||
time() - start_time_of_start_limit_interval
|
||||
) > self._start_limit_interval_sec:
|
||||
# Reset attempts if interval is exceeded
|
||||
start_time_of_start_limit_interval = time()
|
||||
attempts = 1
|
||||
elif attempts > self._start_limit_burst:
|
||||
logger.error(
|
||||
"Task %r exceeded restart burst limit. Stopping.",
|
||||
self._func.__name__,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stops the running asynchronous task by cancelling it."""
|
||||
|
||||
|
||||
@@ -223,25 +223,3 @@ def current_event_loop_exists() -> bool:
|
||||
import asyncio
|
||||
|
||||
return asyncio.get_event_loop_policy()._local._loop is not None # type: ignore
|
||||
|
||||
|
||||
def normalize_full_access_path_string(s: str) -> str:
|
||||
"""Normalizes a string representing a full access path by converting double quotes
|
||||
to single quotes.
|
||||
|
||||
This function is useful for ensuring consistency in strings that represent access
|
||||
paths containing dictionary keys, by replacing all double quotes (`"`) with single
|
||||
quotes (`'`).
|
||||
|
||||
Args:
|
||||
s (str): The input string to be normalized.
|
||||
|
||||
Returns:
|
||||
A new string with all double quotes replaced by single quotes.
|
||||
|
||||
Example:
|
||||
>>> normalize_full_access_path_string('dictionary["first"].my_task')
|
||||
"dictionary['first'].my_task"
|
||||
"""
|
||||
|
||||
return s.replace('"', "'")
|
||||
|
||||
@@ -393,7 +393,7 @@ def set_nested_value_by_path(
|
||||
current_dict, path_parts[-1], allow_append=True
|
||||
)
|
||||
except (SerializationPathError, KeyError) as e:
|
||||
logger.error("Error occured trying to change %a: %s", path, e)
|
||||
logger.exception("Error occured trying to change %a: %s", path, e)
|
||||
return
|
||||
|
||||
if next_level_serialized_object["type"] == "method": # state change of task
|
||||
|
||||
@@ -167,8 +167,8 @@ def test_normalized_attr_path_in_dependent_property_changes(
|
||||
state_manager = StateManager(service=service_instance)
|
||||
observer = DataServiceObserver(state_manager=state_manager)
|
||||
|
||||
assert observer.property_deps_dict["service_dict['one']._prop"] == [
|
||||
"service_dict['one'].prop"
|
||||
assert observer.property_deps_dict['service_dict["one"]._prop'] == [
|
||||
'service_dict["one"].prop'
|
||||
]
|
||||
|
||||
# We can use dict key path encoded with double quotes
|
||||
@@ -184,3 +184,41 @@ def test_normalized_attr_path_in_dependent_property_changes(
|
||||
)
|
||||
assert service_instance.service_dict["one"].prop == 12.0
|
||||
assert "'service_dict[\"one\"].prop' changed to '12.0'" in caplog.text
|
||||
|
||||
|
||||
def test_nested_dict_property_changes(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
def get_voltage() -> float:
|
||||
"""Mocking a remote device."""
|
||||
return 2.0
|
||||
|
||||
def set_voltage(value: float) -> None:
|
||||
"""Mocking a remote device."""
|
||||
|
||||
class OtherService(pydase.DataService):
|
||||
_voltage = 1.0
|
||||
|
||||
@property
|
||||
def voltage(self) -> float:
|
||||
# Property dependency _voltage changes within the property itself.
|
||||
# This should be handled gracefully, i.e. not introduce recursion
|
||||
self._voltage = get_voltage()
|
||||
return self._voltage
|
||||
|
||||
@voltage.setter
|
||||
def voltage(self, value: float) -> None:
|
||||
self._voltage = value
|
||||
set_voltage(self._voltage)
|
||||
|
||||
class MyService(pydase.DataService):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.my_dict = {"key": OtherService()}
|
||||
|
||||
service = MyService()
|
||||
pydase.Server(service)
|
||||
|
||||
# Changing the _voltage attribute should re-evaluate the voltage property, but avoid
|
||||
# recursion
|
||||
service.my_dict["key"].voltage = 1.2
|
||||
|
||||
@@ -185,6 +185,7 @@ async def test_update_value(
|
||||
new_value: dict[str, Any],
|
||||
ok: bool,
|
||||
pydase_server: pydase.DataService,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
async with aiohttp.ClientSession("http://localhost:9998") as session:
|
||||
resp = await session.put(
|
||||
@@ -250,3 +251,43 @@ async def test_trigger_method(
|
||||
if resp.ok:
|
||||
content = Deserializer.deserialize(json.loads(await resp.text()))
|
||||
assert content == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers, log_id",
|
||||
[
|
||||
({}, "id=None"),
|
||||
(
|
||||
{
|
||||
"X-Client-Id": "client-header",
|
||||
},
|
||||
"id=client-header",
|
||||
),
|
||||
(
|
||||
{
|
||||
"Remote-User": "Remote User",
|
||||
},
|
||||
"user=Remote User",
|
||||
),
|
||||
(
|
||||
{
|
||||
"X-Client-Id": "client-header",
|
||||
"Remote-User": "Remote User",
|
||||
},
|
||||
"user=Remote User",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio()
|
||||
async def test_client_information_logging(
|
||||
headers: dict[str, str],
|
||||
log_id: str,
|
||||
pydase_server: pydase.DataService,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
async with aiohttp.ClientSession("http://localhost:9998") as session:
|
||||
await session.get(
|
||||
"/api/v1/get_value?access_path=readonly_attr", headers=headers
|
||||
)
|
||||
|
||||
assert log_id in caplog.text
|
||||
|
||||
312
tests/server/web_server/test_sio_setup.py
Normal file
312
tests/server/web_server/test_sio_setup.py
Normal file
@@ -0,0 +1,312 @@
|
||||
import threading
|
||||
from collections.abc import Generator
|
||||
from typing import Any
|
||||
|
||||
import pydase
|
||||
import pytest
|
||||
import socketio
|
||||
from pydase.utils.serialization.deserializer import Deserializer
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def pydase_server() -> Generator[None, None, None]:
|
||||
class SubService(pydase.DataService):
|
||||
name = "SubService"
|
||||
|
||||
subservice_instance = SubService()
|
||||
|
||||
class MyService(pydase.DataService):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self._readonly_attr = "MyService"
|
||||
self._my_property = 12.1
|
||||
self.sub_service = SubService()
|
||||
self.list_attr = [1, 2]
|
||||
self.dict_attr = {
|
||||
"foo": subservice_instance,
|
||||
"dotted.key": subservice_instance,
|
||||
}
|
||||
|
||||
@property
|
||||
def my_property(self) -> float:
|
||||
return self._my_property
|
||||
|
||||
@my_property.setter
|
||||
def my_property(self, value: float) -> None:
|
||||
self._my_property = value
|
||||
|
||||
@property
|
||||
def readonly_attr(self) -> str:
|
||||
return self._readonly_attr
|
||||
|
||||
def my_method(self, input_str: str) -> str:
|
||||
return f"{input_str}: my_method"
|
||||
|
||||
async def my_async_method(self, input_str: str) -> str:
|
||||
return f"{input_str}: my_async_method"
|
||||
|
||||
server = pydase.Server(MyService(), web_port=9997)
|
||||
thread = threading.Thread(target=server.run, daemon=True)
|
||||
thread.start()
|
||||
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"access_path, expected",
|
||||
[
|
||||
(
|
||||
"readonly_attr",
|
||||
{
|
||||
"full_access_path": "readonly_attr",
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "str",
|
||||
"value": "MyService",
|
||||
},
|
||||
),
|
||||
(
|
||||
"sub_service.name",
|
||||
{
|
||||
"full_access_path": "sub_service.name",
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "str",
|
||||
"value": "SubService",
|
||||
},
|
||||
),
|
||||
(
|
||||
"list_attr[0]",
|
||||
{
|
||||
"full_access_path": "list_attr[0]",
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "int",
|
||||
"value": 1,
|
||||
},
|
||||
),
|
||||
(
|
||||
'dict_attr["foo"]',
|
||||
{
|
||||
"full_access_path": 'dict_attr["foo"]',
|
||||
"doc": None,
|
||||
"name": "SubService",
|
||||
"readonly": False,
|
||||
"type": "DataService",
|
||||
"value": {
|
||||
"name": {
|
||||
"doc": None,
|
||||
"full_access_path": 'dict_attr["foo"].name',
|
||||
"readonly": False,
|
||||
"type": "str",
|
||||
"value": "SubService",
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio()
|
||||
async def test_get_value(
|
||||
access_path: str,
|
||||
expected: dict[str, Any],
|
||||
pydase_server: None,
|
||||
) -> None:
|
||||
client = socketio.AsyncClient()
|
||||
await client.connect(
|
||||
"http://localhost:9997", socketio_path="/ws/socket.io", transports=["websocket"]
|
||||
)
|
||||
response = await client.call("get_value", access_path)
|
||||
assert response == expected
|
||||
await client.disconnect()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"access_path, new_value, ok",
|
||||
[
|
||||
(
|
||||
"sub_service.name",
|
||||
{
|
||||
"full_access_path": "sub_service.name",
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "str",
|
||||
"value": "New Name",
|
||||
},
|
||||
True,
|
||||
),
|
||||
(
|
||||
"list_attr[0]",
|
||||
{
|
||||
"full_access_path": "list_attr[0]",
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "int",
|
||||
"value": 11,
|
||||
},
|
||||
True,
|
||||
),
|
||||
(
|
||||
'dict_attr["foo"].name',
|
||||
{
|
||||
"full_access_path": 'dict_attr["foo"].name',
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "str",
|
||||
"value": "foo name",
|
||||
},
|
||||
True,
|
||||
),
|
||||
(
|
||||
"readonly_attr",
|
||||
{
|
||||
"full_access_path": "readonly_attr",
|
||||
"doc": None,
|
||||
"readonly": True,
|
||||
"type": "str",
|
||||
"value": "Other Name",
|
||||
},
|
||||
False,
|
||||
),
|
||||
(
|
||||
"invalid_attribute",
|
||||
{
|
||||
"full_access_path": "invalid_attribute",
|
||||
"doc": None,
|
||||
"readonly": False,
|
||||
"type": "float",
|
||||
"value": 12.0,
|
||||
},
|
||||
False,
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio()
|
||||
async def test_update_value(
|
||||
access_path: str,
|
||||
new_value: dict[str, Any],
|
||||
ok: bool,
|
||||
pydase_server: None,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
client = socketio.AsyncClient()
|
||||
await client.connect(
|
||||
"http://localhost:9997", socketio_path="/ws/socket.io", transports=["websocket"]
|
||||
)
|
||||
response = await client.call(
|
||||
"update_value",
|
||||
{"access_path": access_path, "value": new_value},
|
||||
)
|
||||
|
||||
if ok:
|
||||
assert response is None
|
||||
else:
|
||||
assert response["type"] == "Exception"
|
||||
|
||||
await client.disconnect()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"access_path, expected, ok",
|
||||
[
|
||||
(
|
||||
"my_method",
|
||||
"Hello from function: my_method",
|
||||
True,
|
||||
),
|
||||
(
|
||||
"my_async_method",
|
||||
"Hello from function: my_async_method",
|
||||
True,
|
||||
),
|
||||
(
|
||||
"invalid_method",
|
||||
None,
|
||||
False,
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio()
|
||||
async def test_trigger_method(
|
||||
access_path: str,
|
||||
expected: Any,
|
||||
ok: bool,
|
||||
pydase_server: pydase.DataService,
|
||||
) -> None:
|
||||
client = socketio.AsyncClient()
|
||||
await client.connect(
|
||||
"http://localhost:9997", socketio_path="/ws/socket.io", transports=["websocket"]
|
||||
)
|
||||
response = await client.call(
|
||||
"trigger_method",
|
||||
{
|
||||
"access_path": access_path,
|
||||
"kwargs": {
|
||||
"full_access_path": "",
|
||||
"type": "dict",
|
||||
"value": {
|
||||
"input_str": {
|
||||
"docs": None,
|
||||
"full_access_path": "",
|
||||
"readonly": False,
|
||||
"type": "str",
|
||||
"value": "Hello from function",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if ok:
|
||||
content = Deserializer.deserialize(response)
|
||||
assert content == expected
|
||||
else:
|
||||
assert response["type"] == "Exception"
|
||||
|
||||
await client.disconnect()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers, log_id",
|
||||
[
|
||||
({}, "sid="),
|
||||
(
|
||||
{
|
||||
"X-Client-Id": "client-header",
|
||||
},
|
||||
"id=client-header",
|
||||
),
|
||||
(
|
||||
{
|
||||
"Remote-User": "Remote User",
|
||||
},
|
||||
"user=Remote User",
|
||||
),
|
||||
(
|
||||
{
|
||||
"X-Client-Id": "client-header",
|
||||
"Remote-User": "Remote User",
|
||||
},
|
||||
"user=Remote User",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio()
|
||||
async def test_client_information_logging(
|
||||
headers: dict[str, str],
|
||||
log_id: str,
|
||||
pydase_server: pydase.DataService,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
client = socketio.AsyncClient()
|
||||
await client.connect(
|
||||
"http://localhost:9997",
|
||||
socketio_path="/ws/socket.io",
|
||||
transports=["websocket"],
|
||||
headers=headers,
|
||||
)
|
||||
await client.call("get_value", "readonly_attr")
|
||||
|
||||
assert log_id in caplog.text
|
||||
|
||||
await client.disconnect()
|
||||
@@ -289,3 +289,171 @@ async def test_manual_start_with_multiple_service_instances(
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
assert "Task 'my_task' was cancelled" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_restart_on_exception(caplog: LogCaptureFixture) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task(restart_on_exception=True, restart_sec=0.1)
|
||||
async def my_task(self) -> None:
|
||||
logger.info("Triggered task.")
|
||||
raise Exception("Task failure")
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.01)
|
||||
assert "Task 'my_task' encountered an exception" in caplog.text
|
||||
caplog.clear()
|
||||
await asyncio.sleep(0.1)
|
||||
assert service_instance.my_task.status == TaskStatus.RUNNING
|
||||
assert "Task 'my_task' encountered an exception" in caplog.text
|
||||
assert "Triggered task." in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_restart_sec(caplog: LogCaptureFixture) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task(restart_on_exception=True, restart_sec=0.1)
|
||||
async def my_task(self) -> None:
|
||||
logger.info("Triggered task.")
|
||||
raise Exception("Task failure")
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.001)
|
||||
assert "Triggered task." in caplog.text
|
||||
caplog.clear()
|
||||
await asyncio.sleep(0.05)
|
||||
assert "Triggered task." not in caplog.text
|
||||
await asyncio.sleep(0.05)
|
||||
assert "Triggered task." in caplog.text # Ensures the task restarted after 0.2s
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_exceeding_start_limit_interval_sec_and_burst(
|
||||
caplog: LogCaptureFixture,
|
||||
) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task(
|
||||
restart_on_exception=True,
|
||||
restart_sec=0.0,
|
||||
start_limit_interval_sec=1.0,
|
||||
start_limit_burst=2,
|
||||
)
|
||||
async def my_task(self) -> None:
|
||||
raise Exception("Task failure")
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
assert "Task 'my_task' exceeded restart burst limit" in caplog.text
|
||||
assert service_instance.my_task.status == TaskStatus.NOT_RUNNING
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_non_exceeding_start_limit_interval_sec_and_burst(
|
||||
caplog: LogCaptureFixture,
|
||||
) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task(
|
||||
restart_on_exception=True,
|
||||
restart_sec=0.1,
|
||||
start_limit_interval_sec=0.1,
|
||||
start_limit_burst=2,
|
||||
)
|
||||
async def my_task(self) -> None:
|
||||
raise Exception("Task failure")
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
assert "Task 'my_task' exceeded restart burst limit" not in caplog.text
|
||||
assert service_instance.my_task.status == TaskStatus.RUNNING
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_exit_on_failure(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: LogCaptureFixture
|
||||
) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task(restart_on_exception=False, exit_on_failure=True)
|
||||
async def my_task(self) -> None:
|
||||
logger.info("Triggered task.")
|
||||
raise Exception("Critical failure")
|
||||
|
||||
def mock_os_kill(pid: int, signal: int) -> None:
|
||||
logger.critical("os.kill called with signal=%s and pid=%s", signal, pid)
|
||||
|
||||
monkeypatch.setattr("os.kill", mock_os_kill)
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
assert "os.kill called with signal=" in caplog.text
|
||||
assert "Task 'my_task' encountered an exception" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_exit_on_failure_exceeding_rate_limit(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: LogCaptureFixture
|
||||
) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task(
|
||||
restart_on_exception=True,
|
||||
restart_sec=0.0,
|
||||
start_limit_interval_sec=0.1,
|
||||
start_limit_burst=2,
|
||||
exit_on_failure=True,
|
||||
)
|
||||
async def my_task(self) -> None:
|
||||
raise Exception("Critical failure")
|
||||
|
||||
def mock_os_kill(pid: int, signal: int) -> None:
|
||||
logger.critical("os.kill called with signal=%s and pid=%s", signal, pid)
|
||||
|
||||
monkeypatch.setattr("os.kill", mock_os_kill)
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
assert "os.kill called with signal=" in caplog.text
|
||||
assert "Task 'my_task' encountered an exception" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio(scope="function")
|
||||
async def test_gracefully_finishing_task(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: LogCaptureFixture
|
||||
) -> None:
|
||||
class MyService(pydase.DataService):
|
||||
@task()
|
||||
async def my_task(self) -> None:
|
||||
print("Hello")
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
service_instance = MyService()
|
||||
state_manager = StateManager(service_instance)
|
||||
DataServiceObserver(state_manager)
|
||||
service_instance.my_task.start()
|
||||
|
||||
await asyncio.sleep(0.05)
|
||||
assert service_instance.my_task.status == TaskStatus.RUNNING
|
||||
await asyncio.sleep(0.1)
|
||||
assert service_instance.my_task.status == TaskStatus.NOT_RUNNING
|
||||
|
||||
Reference in New Issue
Block a user