fastpluggy-websocket-tool 0.1.21__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fastpluggy-websocket-tool might be problematic. Click here for more details.

Files changed (34) hide show
  1. fastpluggy_websocket_tool-0.1.21/MANIFEST.in +12 -0
  2. fastpluggy_websocket_tool-0.1.21/PKG-INFO +11 -0
  3. fastpluggy_websocket_tool-0.1.21/README.md +202 -0
  4. fastpluggy_websocket_tool-0.1.21/fastpluggy_websocket_tool.egg-info/PKG-INFO +11 -0
  5. fastpluggy_websocket_tool-0.1.21/fastpluggy_websocket_tool.egg-info/SOURCES.txt +32 -0
  6. fastpluggy_websocket_tool-0.1.21/fastpluggy_websocket_tool.egg-info/dependency_links.txt +1 -0
  7. fastpluggy_websocket_tool-0.1.21/fastpluggy_websocket_tool.egg-info/entry_points.txt +2 -0
  8. fastpluggy_websocket_tool-0.1.21/fastpluggy_websocket_tool.egg-info/requires.txt +6 -0
  9. fastpluggy_websocket_tool-0.1.21/fastpluggy_websocket_tool.egg-info/top_level.txt +1 -0
  10. fastpluggy_websocket_tool-0.1.21/pyproject.toml +37 -0
  11. fastpluggy_websocket_tool-0.1.21/setup.cfg +4 -0
  12. fastpluggy_websocket_tool-0.1.21/src/__init__.py +1 -0
  13. fastpluggy_websocket_tool-0.1.21/src/config.py +13 -0
  14. fastpluggy_websocket_tool-0.1.21/src/extra_widget/__init__.py +6 -0
  15. fastpluggy_websocket_tool-0.1.21/src/extra_widget/async_registry.py +86 -0
  16. fastpluggy_websocket_tool-0.1.21/src/extra_widget/async_widget.py +78 -0
  17. fastpluggy_websocket_tool-0.1.21/src/extra_widget/async_worker.py +76 -0
  18. fastpluggy_websocket_tool-0.1.21/src/extra_widget/websocket_details_widget.py +34 -0
  19. fastpluggy_websocket_tool-0.1.21/src/notifiers/__init__.py +0 -0
  20. fastpluggy_websocket_tool-0.1.21/src/notifiers/websocket.py +103 -0
  21. fastpluggy_websocket_tool-0.1.21/src/plugin.py +65 -0
  22. fastpluggy_websocket_tool-0.1.21/src/register_handlers.py +67 -0
  23. fastpluggy_websocket_tool-0.1.21/src/routers/__init__.py +43 -0
  24. fastpluggy_websocket_tool-0.1.21/src/routers/admin.py +410 -0
  25. fastpluggy_websocket_tool-0.1.21/src/routers/info.py +131 -0
  26. fastpluggy_websocket_tool-0.1.21/src/routers/ws.py +214 -0
  27. fastpluggy_websocket_tool-0.1.21/src/schema/__init__.py +55 -0
  28. fastpluggy_websocket_tool-0.1.21/src/schema/ws_message.py +24 -0
  29. fastpluggy_websocket_tool-0.1.21/src/static/scripts.js +312 -0
  30. fastpluggy_websocket_tool-0.1.21/src/static/service-worker.js +290 -0
  31. fastpluggy_websocket_tool-0.1.21/src/static/websocket-client.js +240 -0
  32. fastpluggy_websocket_tool-0.1.21/src/templates/async_ws_wrapper.html.j2 +30 -0
  33. fastpluggy_websocket_tool-0.1.21/src/templates/websocket_details.html.j2 +190 -0
  34. fastpluggy_websocket_tool-0.1.21/src/ws_manager.py +461 -0
@@ -0,0 +1,12 @@
1
+ # Include all Python files
2
+ recursive-include src *.py
3
+
4
+ # Include all template files
5
+ recursive-include src/templates *.html *.j2
6
+
7
+ # Include all static files (CSS, JS, etc.)
8
+ recursive-include src/static *
9
+
10
+ # Include README and license files
11
+ include README.md
12
+ include LICENSE
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastpluggy-websocket-tool
3
+ Version: 0.1.21
4
+ Summary: FastPluggy plugin for real-time WebSocket communication
5
+ Author: FastPluggy Team
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: pydantic>=2.0.0
8
+ Requires-Dist: websockets>=11.0.3
9
+ Requires-Dist: fastpluggy-ui-tools>=0.0.5
10
+ Provides-Extra: client
11
+ Requires-Dist: websockets>=11.0.3; extra == "client"
@@ -0,0 +1,202 @@
1
+ # WebSocketTool Plugin for FastPluggy
2
+
3
+ The WebSocketTool plugin provides real-time WebSocket communication capabilities for FastPluggy applications. It enables bidirectional communication between the server and clients, supports message broadcasting, targeted messaging, and integrates with the task worker system for real-time task monitoring.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Installation](#installation)
8
+ - [Configuration](#configuration)
9
+ - [Core Components](#core-components)
10
+ - [API Reference](#api-reference)
11
+ - [Integration with Other Modules](#integration-with-other-modules)
12
+ - [Tasks Worker Integration](#tasks-worker-integration)
13
+ - [WebSocket Integration](#websocket-integration)
14
+ - [Connecting to WebSocket](#connecting-to-websocket)
15
+ - [Registering Backend Message Handlers](#registering-backend-message-handlers)
16
+ - [Registering Event Hooks](#registering-event-hooks)
17
+ - [Frontend Integration](#frontend-integration)
18
+ - [Naming Convention for Message Types](#naming-convention-for-message-types)
19
+ - [Using AsyncWidget [WIP]](#using-asyncwidget-wip)
20
+ - [Advanced Usage and Troubleshooting](#advanced-usage-and-troubleshooting)
21
+ - [License](#license)
22
+
23
+ ## Installation
24
+
25
+ ### Requirements
26
+
27
+ - FastPluggy framework >=0.0.3
28
+ - UI Tools plugin >=0.0.3
29
+
30
+ ### Quick Start & Installation
31
+
32
+ ```bash
33
+ pip install fastpluggy-websocket-tool
34
+ ```
35
+
36
+ ## Configuration
37
+
38
+ The WebSocketTool plugin can be configured through the `WebSocketSettings` class:
39
+
40
+ | Setting | Type | Default | Description |
41
+ |---------|------|---------|-------------|
42
+ | `max_queue_size` | int | 10000 | Maximum size of the message queue |
43
+ | `enable_heartbeat` | bool | True | Enable heartbeat mechanism to monitor connection health |
44
+ | `heartbeat_interval` | int | 30 | Seconds between heartbeat pings |
45
+ | `heartbeat_timeout` | int | 60 | Seconds before a connection is considered timed out |
46
+
47
+
48
+ ## Core Components
49
+
50
+ For detailed information about the core components of the WebSocketTool plugin, including the ConnectionManager, WebSocketMessage, and AsyncWidget classes, see the [Core Components Documentation](docs/core_components.md).
51
+
52
+ ## API Reference
53
+
54
+ For detailed information about the WebSocket API endpoints and interfaces, see the [API Reference Documentation](docs/api_reference.md).
55
+
56
+ ## Integration with Other Modules
57
+
58
+ ### Tasks Worker Integration
59
+
60
+ The WebSocketTool plugin integrates with the Tasks Worker module to provide real-time monitoring of task execution, streaming of task logs, and task completion notifications.
61
+
62
+ For detailed information about the Tasks Worker integration, see the [Tasks Worker Integration Documentation](docs/tasks_worker_integration.md).
63
+
64
+ ## WebSocket Integration
65
+
66
+ The WebSocketTool plugin provides a powerful handler registry system that allows you to easily register handlers for both frontend and backend WebSocket messages. This simplifies the integration of WebSocket functionality into your application.
67
+
68
+ For detailed information about the handler registry system, see the [Handler Registry Documentation](docs/websocket_handlers.md).
69
+
70
+
71
+ ### Registering Backend Message Handlers
72
+
73
+ Backend message handlers process messages received from clients. Here's how to register them:
74
+
75
+ ```python
76
+ from fastpluggy.fastpluggy import FastPluggy
77
+ from typing import Dict, Any
78
+
79
+ # Define a handler function for a specific message type
80
+ async def handle_chat_message(client_id: str, data: Dict[str, Any]):
81
+ """Handler for chat messages from clients"""
82
+ print(f"Received chat from {client_id}: {data.get('content')}")
83
+
84
+ # You can access the WebSocket manager to send responses
85
+ manager = FastPluggy.get_global("ws_manager")
86
+
87
+ # Process the message and potentially send a response
88
+ # ...
89
+
90
+ # Get the WebSocket manager
91
+ ws_manager = FastPluggy.get_global("ws_manager")
92
+
93
+ # Register the handler for the "chat.message" message type
94
+ ws_manager.register_handler("chat.message", handle_chat_message)
95
+ ```
96
+
97
+ ### Registering Event Hooks
98
+
99
+ You can register hooks for WebSocket events:
100
+
101
+ ```python
102
+ from fastpluggy.fastpluggy import FastPluggy
103
+ from fastpluggy_plugin.websocket_tool.schema.ws_message import WebSocketMessage
104
+
105
+ # Define hook functions
106
+ async def on_client_connected(client_id: str):
107
+ """Called when a client connects"""
108
+ print(f"Client connected: {client_id}")
109
+
110
+ # Send a welcome message
111
+ manager = FastPluggy.get_global("ws_manager")
112
+ welcome_msg = WebSocketMessage(
113
+ type="system.welcome",
114
+ content=f"Welcome {client_id}!",
115
+ meta={"event": "connected"}
116
+ )
117
+ await manager.send_to_client(welcome_msg, client_id)
118
+
119
+ # Get the WebSocket manager
120
+ ws_manager = FastPluggy.get_global("ws_manager")
121
+
122
+ # Register the hook
123
+ ws_manager.add_hook("client_connected", on_client_connected)
124
+ ```
125
+
126
+
127
+ ### Frontend Integration
128
+
129
+ To handle WebSocket messages in the frontend, include the websocket-client.js file in your HTML:
130
+
131
+ ```html
132
+ <script src="/static/websocket-client.js"></script>
133
+ ```
134
+
135
+ This file provides:
136
+ - `WebSocketRegistry`: A registry for WebSocket message handlers
137
+ - `safeRegisterHandler`: A function to safely register handlers even if the registry isn't loaded yet
138
+
139
+ Here's how to use these features:
140
+
141
+ ```javascript
142
+
143
+ // Register handlers for specific message types using safeRegisterHandler
144
+ // This works even if WebSocketRegistry isn't loaded yet
145
+ safeRegisterHandler("chat.message", (data) => {
146
+ displayChatMessage(data.content, data.meta);
147
+ });
148
+
149
+ // Send a message to the backend
150
+ function sendChatMessage(message) {
151
+ socket.send(JSON.stringify({
152
+ type: "chat.message", // This will be handled by the registered "chat.message" handler
153
+ content: message,
154
+ meta: {
155
+ timestamp: Date.now(),
156
+ user: "current_user"
157
+ }
158
+ }));
159
+ }
160
+
161
+ // Example usage
162
+ document.getElementById('send-button').addEventListener('click', () => {
163
+ const messageInput = document.getElementById('message-input');
164
+ sendChatMessage(messageInput.value);
165
+ messageInput.value = '';
166
+ });
167
+ ```
168
+
169
+ The `safeRegisterHandler` function ensures that your handlers are registered even if the WebSocketRegistry is loaded after your code runs. It's the recommended way to register handlers in the frontend.
170
+
171
+ ### Naming Convention for Message Types
172
+
173
+ To avoid conflicts between different plugins, it's recommended to use a namespaced approach for message types:
174
+
175
+ ```
176
+ <plugin_name>.<action_or_event>
177
+ ```
178
+
179
+ For example:
180
+ - `chat.message` - For chat messages
181
+ - `user.login` - For user login events
182
+ - `data.request` - For data requests
183
+
184
+ This ensures that handlers from different plugins don't accidentally override each other.
185
+
186
+ For more detailed information about message types and naming conventions, see the [WebSocket Message Types Documentation](docs/ws.md).
187
+
188
+ ### Using AsyncWidget [WIP]
189
+
190
+ The AsyncWidget feature allows for asynchronous loading of UI components, improving the responsiveness of your application by rendering complex components in the background.
191
+
192
+ **Note:** This feature is currently a Work In Progress (WIP) and not fully implemented yet.
193
+
194
+ For detailed information about the AsyncWidget feature, including usage examples, current status, and planned improvements, see the [AsyncWidget Documentation](docs/async_widget.md).
195
+
196
+ ## Advanced Usage and Troubleshooting
197
+
198
+ For detailed information about advanced usage, health monitoring, and troubleshooting, see the [Advanced Usage Documentation](docs/advanced_usage.md).
199
+
200
+ ## License
201
+
202
+ This plugin is licensed under the same license as the FastPluggy framework.
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastpluggy-websocket-tool
3
+ Version: 0.1.21
4
+ Summary: FastPluggy plugin for real-time WebSocket communication
5
+ Author: FastPluggy Team
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: pydantic>=2.0.0
8
+ Requires-Dist: websockets>=11.0.3
9
+ Requires-Dist: fastpluggy-ui-tools>=0.0.5
10
+ Provides-Extra: client
11
+ Requires-Dist: websockets>=11.0.3; extra == "client"
@@ -0,0 +1,32 @@
1
+ MANIFEST.in
2
+ README.md
3
+ pyproject.toml
4
+ fastpluggy_websocket_tool.egg-info/PKG-INFO
5
+ fastpluggy_websocket_tool.egg-info/SOURCES.txt
6
+ fastpluggy_websocket_tool.egg-info/dependency_links.txt
7
+ fastpluggy_websocket_tool.egg-info/entry_points.txt
8
+ fastpluggy_websocket_tool.egg-info/requires.txt
9
+ fastpluggy_websocket_tool.egg-info/top_level.txt
10
+ src/__init__.py
11
+ src/config.py
12
+ src/plugin.py
13
+ src/register_handlers.py
14
+ src/ws_manager.py
15
+ src/extra_widget/__init__.py
16
+ src/extra_widget/async_registry.py
17
+ src/extra_widget/async_widget.py
18
+ src/extra_widget/async_worker.py
19
+ src/extra_widget/websocket_details_widget.py
20
+ src/notifiers/__init__.py
21
+ src/notifiers/websocket.py
22
+ src/routers/__init__.py
23
+ src/routers/admin.py
24
+ src/routers/info.py
25
+ src/routers/ws.py
26
+ src/schema/__init__.py
27
+ src/schema/ws_message.py
28
+ src/static/scripts.js
29
+ src/static/service-worker.js
30
+ src/static/websocket-client.js
31
+ src/templates/async_ws_wrapper.html.j2
32
+ src/templates/websocket_details.html.j2
@@ -0,0 +1,2 @@
1
+ [fastpluggy.plugins]
2
+ websocket_tool = fastpluggy_plugin.websocket_tool.plugin:WebSocketToolPlugin
@@ -0,0 +1,6 @@
1
+ pydantic>=2.0.0
2
+ websockets>=11.0.3
3
+ fastpluggy-ui-tools>=0.0.5
4
+
5
+ [client]
6
+ websockets>=11.0.3
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fastpluggy-websocket-tool"
7
+ version = "0.1.21"
8
+ description = "FastPluggy plugin for real-time WebSocket communication"
9
+ requires-python = ">=3.10"
10
+ authors = [
11
+ {name = "FastPluggy Team"}
12
+ ]
13
+
14
+
15
+ # Server requirements
16
+ dependencies = [
17
+ "pydantic>=2.0.0",
18
+ "websockets>=11.0.3",
19
+ "fastpluggy-ui-tools>=0.0.5"
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ # Client-only requirements
24
+ client = [
25
+ "websockets>=11.0.3"
26
+ ]
27
+
28
+ [tool.setuptools]
29
+ packages = ["fastpluggy_plugin.websocket_tool"]
30
+ package-dir = { "fastpluggy_plugin.websocket_tool" = "src" }
31
+ include-package-data = true
32
+
33
+ [tool.setuptools.package-data]
34
+ "fastpluggy_plugin.websocket_tool" = ["**/*","templates/**/*.html", "templates/**/*.j2", "static/**/*"]
35
+
36
+ [project.entry-points."fastpluggy.plugins"]
37
+ websocket_tool = "fastpluggy_plugin.websocket_tool.plugin:WebSocketToolPlugin"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ from .plugin import WebSocketToolPlugin
@@ -0,0 +1,13 @@
1
+
2
+ from fastpluggy.core.config import BaseDatabaseSettings
3
+
4
+
5
+ class WebSocketSettings(BaseDatabaseSettings):
6
+ max_queue_size: int = 10000
7
+
8
+ enable_heartbeat: bool = True
9
+ heartbeat_interval: int = 30
10
+ heartbeat_timeout: int = 60
11
+
12
+
13
+ # todo add prefix for var like FP_WST_
@@ -0,0 +1,6 @@
1
+ # __init__.py for extra_widget package
2
+
3
+ from .async_widget import AsyncWidget
4
+ from .websocket_details_widget import WebSocketDetailsWidget
5
+
6
+ __all__ = ['AsyncWidget', 'WebSocketDetailsWidget']
@@ -0,0 +1,86 @@
1
+ # async_registry.py
2
+
3
+ import asyncio
4
+ from typing import Dict, Any, Set
5
+
6
+ # -----------------------------------------------------------------------------
7
+ # 1) Registry mapping widget_id → configuration dict.
8
+ # Each config dict should include at least:
9
+ # - "instance": the AsyncWidget instance
10
+ # - "subwidgets": list of its child widgets (if needed)
11
+ # -----------------------------------------------------------------------------
12
+ _WIDGET_REGISTRY: Dict[str, Dict[str, Any]] = {}
13
+
14
+ # -----------------------------------------------------------------------------
15
+ # 2) Global asyncio.Queue holding pending widget_ids for background processing.
16
+ # -----------------------------------------------------------------------------
17
+ widget_queue: asyncio.Queue[str] = asyncio.Queue()
18
+
19
+ # -----------------------------------------------------------------------------
20
+ # 3) Mapping of widget_id → set of connection_keys that have subscribed.
21
+ # -----------------------------------------------------------------------------
22
+ uuid_to_clients: Dict[str, Set[str]] = {}
23
+
24
+ # -----------------------------------------------------------------------------
25
+ # 4) Public API to register a widget’s configuration.
26
+ # -----------------------------------------------------------------------------
27
+ def register_widget(widget_id: str, config: Dict[str, Any]) -> None:
28
+ """
29
+ Store the given config under widget_id in the global registry.
30
+ Call this when an AsyncWidget is instantiated (or first rendered).
31
+ """
32
+ _WIDGET_REGISTRY[widget_id] = config
33
+
34
+ return True
35
+
36
+ # -----------------------------------------------------------------------------
37
+ # 5) Public API to retrieve a widget’s configuration by widget_id.
38
+ # -----------------------------------------------------------------------------
39
+ def get_widget_config(widget_id: str) -> Dict[str, Any]:
40
+ """
41
+ Fetch the configuration dict for the given widget_id.
42
+ Returns None if no such entry exists.
43
+ """
44
+ return _WIDGET_REGISTRY.get(widget_id)
45
+
46
+ # -----------------------------------------------------------------------------
47
+ # 6) Public API to enqueue a widget_id for background processing.
48
+ # -----------------------------------------------------------------------------
49
+ def enqueue_widget(widget_id: str) -> None:
50
+ """
51
+ Put the widget_id onto the global widget_queue for the worker to pick up.
52
+ """
53
+ try:
54
+ widget_queue.put_nowait(widget_id)
55
+ except asyncio.QueueFull:
56
+ # The queue is full; you may choose to log or handle overflow here.
57
+ pass
58
+
59
+ # -----------------------------------------------------------------------------
60
+ # 7) Public API to add a subscriber (connection_key) for a given widget_id.
61
+ # -----------------------------------------------------------------------------
62
+ def subscribe_client(widget_id: str, connection_key: str) -> None:
63
+ """
64
+ Record that connection_key wants updates for widget_id.
65
+ """
66
+ subscribers = uuid_to_clients.setdefault(widget_id, set())
67
+ subscribers.add(connection_key)
68
+
69
+ # -----------------------------------------------------------------------------
70
+ # 8) Public API to get all subscribers for a given widget_id.
71
+ # -----------------------------------------------------------------------------
72
+ def get_subscribers(widget_id: str) -> Set[str]:
73
+ """
74
+ Return the set of connection_keys subscribed to widget_id.
75
+ If no one has subscribed yet, returns an empty set.
76
+ """
77
+ return uuid_to_clients.get(widget_id, set())
78
+
79
+ # -----------------------------------------------------------------------------
80
+ # 9) Public API to clear all subscribers after pushing an update.
81
+ # -----------------------------------------------------------------------------
82
+ def clear_subscribers(widget_id: str) -> None:
83
+ """
84
+ Remove the widget_id entry from uuid_to_clients, so we don’t resend.
85
+ """
86
+ uuid_to_clients.pop(widget_id, None)
@@ -0,0 +1,78 @@
1
+ # async_widget.py
2
+
3
+ import asyncio
4
+ from typing import Any, Dict, List, Union, Optional
5
+ from fastpluggy.core.widgets.base import AbstractWidget
6
+
7
+ from .async_registry import register_widget, widget_queue
8
+
9
+ class AsyncWidget(AbstractWidget):
10
+ """
11
+ Wraps subwidgets so that:
12
+ - On first render, we show a spinner + JS that calls safeRegisterHandler("async_widget", …).
13
+ - We save (widget_id → config) in a registry & enqueue widget_id on widget_queue.
14
+ - A background worker will call render_inner() and push HTML via WebSocket using msg.type="async_widget".
15
+ """
16
+
17
+ widget_type :str = "async"
18
+ template_name :str = "ui_tools/extra_widget/async_ws_wrapper.html.j2"
19
+ category :str = "async"
20
+ description :str = "Asynchronously loads subwidgets (via safeRegisterHandler)."
21
+ icon:str = "sync-alt"
22
+
23
+ def __init__(
24
+ self,
25
+ subwidgets: Optional[List[Union[AbstractWidget, Dict[str, Any]]]] = None,
26
+ **kwargs
27
+ ):
28
+ super().__init__(**kwargs)
29
+ self.subwidgets = subwidgets or []
30
+
31
+ # 1) Instead of generating a new UUID, use the inherited self.widget_id
32
+ wid = self.widget_id
33
+
34
+ # 2) Register this instance in the global registry under widget_id
35
+ register_widget(wid, {
36
+ "instance": self,
37
+ "subwidgets": self.subwidgets,
38
+ })
39
+
40
+ # 3) Enqueue for background processing using widget_id
41
+ try:
42
+ widget_queue.put_nowait(wid)
43
+ except asyncio.QueueFull:
44
+ # Queue overflow; you can log or handle as needed
45
+ pass
46
+
47
+ def process(self, **kwargs) -> None:
48
+ """
49
+ On initial render, we do NOT process subwidgets. We only need self.widget_id
50
+ so that the template can emit the spinner + safeRegisterHandler JS.
51
+ """
52
+ return
53
+
54
+ def render_inner(self, **kwargs) -> str:
55
+ """
56
+ Called by the background worker to produce the final HTML:
57
+ - Look up subwidgets from the registry under self.widget_id
58
+ - Call .process() + .render() on each
59
+ - Return the combined HTML string
60
+ """
61
+ config = register_widget(self.widget_id) # or use a getter
62
+ if not config:
63
+ raise RuntimeError(f"No registry entry for AsyncWidget {self.widget_id}")
64
+
65
+ html_parts: List[str] = []
66
+ for item in config["subwidgets"]:
67
+ if isinstance(item, AbstractWidget):
68
+ w = item
69
+ w.process(**kwargs)
70
+ html_parts.append(w.render(**kwargs))
71
+ elif isinstance(item, dict):
72
+ w = item.pop("widget")
73
+ w.process(**kwargs)
74
+ html_parts.append(w.render(**kwargs))
75
+ else:
76
+ raise ValueError("Invalid subwidget type inside AsyncWidget")
77
+
78
+ return "\n".join(html_parts)
@@ -0,0 +1,76 @@
1
+ # async_worker.py
2
+
3
+ import asyncio
4
+ from typing import Any, Dict, Set
5
+
6
+ from fastpluggy.fastpluggy import FastPluggy
7
+ from .async_registry import widget_queue, get_widget_config
8
+ from .async_widget import AsyncWidget
9
+ from ..schema.ws_message import WebSocketMessage
10
+ from ..ws_manager import ConnectionManager
11
+
12
+
13
+ async def widget_worker():
14
+ """
15
+ Continuously pull widget_id strings from widget_queue, render each AsyncWidget’s subwidgets,
16
+ and then push the resulting HTML over WebSocket to any clients that subscribed for this widget_id.
17
+ """
18
+ while True:
19
+ try:
20
+ widget_id: str = await widget_queue.get()
21
+ except asyncio.CancelledError:
22
+ break
23
+
24
+ config: Dict[str, Any] = get_widget_config(widget_id)
25
+ if not config:
26
+ # No registry entry—nothing to do
27
+ widget_queue.task_done()
28
+ continue
29
+
30
+ async_widget: AsyncWidget = config.get("instance")
31
+ if not async_widget:
32
+ widget_queue.task_done()
33
+ continue
34
+
35
+ # 1) Render the inner HTML for this widget
36
+ try:
37
+ html: str = async_widget.render_inner()
38
+ except Exception as exc:
39
+ html = f"<div class='text-danger'>Error rendering widget: {exc}</div>"
40
+
41
+ manager: ConnectionManager = FastPluggy.get_global("ws_manager")
42
+ # 2) Look up all WebSocket clients that subscribed to this widget_id
43
+ #subscribers: Set[str] = manager.uuid_to_clients.get(widget_id, set())
44
+ ll = manager.list_clients()
45
+ subscribers: Set[str] = [item['client_id'] for item in ll if item['client_id'] in manager.uuid_to_clients]
46
+
47
+ # 3) For each subscriber, send a WebSocketMessage of type "async_widget"
48
+ for conn_key in subscribers:
49
+ payload = WebSocketMessage(
50
+ type="async_widget",
51
+ content=None,
52
+ meta={
53
+ "widget_id": widget_id,
54
+ "html": html
55
+ }
56
+ )
57
+ await manager.send_to_client(payload, conn_key)
58
+
59
+ # 4) Once pushed, remove those subscribers so we don’t resend
60
+ #uuid_to_clients.pop(widget_id, None)
61
+
62
+ widget_queue.task_done()
63
+
64
+ # async_worker_starter.py
65
+
66
+
67
+ def start_async_widget_worker():
68
+ """
69
+ Schedule widget_worker() on the same loop that ConnectionManager uses.
70
+ Call this once at application startup, after initializing manager.loop.
71
+ """
72
+ # Ensure ConnectionManager has its loop set
73
+ loop = asyncio.get_event_loop()
74
+
75
+ # Schedule widget_worker() as a background task on manager.loop
76
+ loop.create_task(widget_worker())
@@ -0,0 +1,34 @@
1
+ # websocket_details_widget.py
2
+
3
+ from fastpluggy.core.widgets.base import AbstractWidget
4
+
5
+
6
+ class WebSocketDetailsWidget(AbstractWidget):
7
+ """
8
+ Widget that displays WebSocket connection details including:
9
+ - Connection status
10
+ - Health score
11
+ - Messages sent
12
+ - Connection duration
13
+
14
+ This widget fetches data from the WebSocket stats and clients endpoints
15
+ and updates the UI every 5 seconds.
16
+ """
17
+
18
+ widget_type = "websocket_details"
19
+ template_name = "websocket_tool/websocket_details.html.j2"
20
+ category = "websocket"
21
+ description = "Displays WebSocket connection details"
22
+ icon = "rss"
23
+
24
+ def __init__(self, **kwargs):
25
+ """Initialize the WebSocket details widget."""
26
+ super().__init__(**kwargs)
27
+ self.title = kwargs.get('title', 'WebSocket Details')
28
+
29
+ def process(self, **kwargs) -> None:
30
+ """
31
+ Process the widget data and prepare for rendering.
32
+ This widget doesn't require any processing as it fetches data client-side.
33
+ """
34
+ pass