fastpluggy-debug-tools 0.0.14__py3-none-any.whl

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-debug-tools might be problematic. Click here for more details.

Files changed (33) hide show
  1. fastpluggy_debug_tools-0.0.14.dist-info/METADATA +12 -0
  2. fastpluggy_debug_tools-0.0.14.dist-info/RECORD +33 -0
  3. fastpluggy_debug_tools-0.0.14.dist-info/WHEEL +5 -0
  4. fastpluggy_debug_tools-0.0.14.dist-info/entry_points.txt +2 -0
  5. fastpluggy_debug_tools-0.0.14.dist-info/top_level.txt +1 -0
  6. fastpluggy_plugin/debug_tools/__init__.py +1 -0
  7. fastpluggy_plugin/debug_tools/config.py +14 -0
  8. fastpluggy_plugin/debug_tools/plugin.py +43 -0
  9. fastpluggy_plugin/debug_tools/requirements_tools.py +89 -0
  10. fastpluggy_plugin/debug_tools/router/__init__.py +274 -0
  11. fastpluggy_plugin/debug_tools/router/debug.py +94 -0
  12. fastpluggy_plugin/debug_tools/router/memory_tools.py +77 -0
  13. fastpluggy_plugin/debug_tools/router/menu_tools.py +48 -0
  14. fastpluggy_plugin/debug_tools/router/module_tools.py +70 -0
  15. fastpluggy_plugin/debug_tools/router/pool_info.py +59 -0
  16. fastpluggy_plugin/debug_tools/router/psutil_analyzer.py +43 -0
  17. fastpluggy_plugin/debug_tools/router/requirements.py +42 -0
  18. fastpluggy_plugin/debug_tools/router/task_thread_tools.py +94 -0
  19. fastpluggy_plugin/debug_tools/router/websocket_tool.py +46 -0
  20. fastpluggy_plugin/debug_tools/static/debug.css +0 -0
  21. fastpluggy_plugin/debug_tools/tasks/__init__.py +0 -0
  22. fastpluggy_plugin/debug_tools/tasks/locked_tasks.py +26 -0
  23. fastpluggy_plugin/debug_tools/tasks/progress.py +27 -0
  24. fastpluggy_plugin/debug_tools/tasks/sample_tasks.py +67 -0
  25. fastpluggy_plugin/debug_tools/tasks/task_sample.py +53 -0
  26. fastpluggy_plugin/debug_tools/templates/psutil_analyzer.html.j2 +243 -0
  27. fastpluggy_plugin/debug_tools/templates/widgets/debug/debug_panel.html.j2 +325 -0
  28. fastpluggy_plugin/debug_tools/templates/widgets/packages_view.html.j2 +207 -0
  29. fastpluggy_plugin/debug_tools/widgets/__init__.py +3 -0
  30. fastpluggy_plugin/debug_tools/widgets/debug/__init__.py +0 -0
  31. fastpluggy_plugin/debug_tools/widgets/debug/debug_panel.py +308 -0
  32. fastpluggy_plugin/debug_tools/widgets/packages_view.py +44 -0
  33. fastpluggy_plugin/debug_tools/widgets/psutil_analyzer.py +33 -0
@@ -0,0 +1,48 @@
1
+ from fastapi import Depends, APIRouter
2
+ from fastapi.routing import APIRoute
3
+ from starlette.requests import Request
4
+
5
+ from fastpluggy.core.dependency import get_view_builder, get_fastpluggy
6
+ from fastpluggy.core.widgets.categories.data.debug import DebugView
7
+
8
+ menu_debug_router = APIRouter()
9
+
10
+ @menu_debug_router.get("/list_menu")
11
+ async def list_menu(
12
+ request: Request,
13
+ view_builder=Depends(get_view_builder),
14
+ fast_pluggy=Depends(get_fastpluggy)):
15
+
16
+ return view_builder.generate(
17
+ request,
18
+ title="List menu",
19
+ widgets=[
20
+ DebugView(
21
+ data=fast_pluggy.menu_manager.menus,
22
+ )
23
+ ]
24
+ )
25
+
26
+
27
+ @menu_debug_router.get("/list_menu_entry")
28
+ async def list_menu_entry(
29
+ request: Request,
30
+ view_builder=Depends(get_view_builder),
31
+ fast_pluggy=Depends(get_fastpluggy)):
32
+ app_routes = fast_pluggy.app.router.routes
33
+ list_entry = []
34
+ for route in app_routes:
35
+ if isinstance(route, APIRoute) and hasattr(route.endpoint, "_menu_entry"):
36
+ menu_entry = route.endpoint._menu_entry
37
+ list_entry.append(menu_entry)
38
+
39
+ return view_builder.generate(
40
+ request,
41
+ title="List _menu_entry",
42
+ widgets=[
43
+ DebugView(
44
+ data=list_entry,
45
+ )
46
+ ]
47
+ )
48
+
@@ -0,0 +1,70 @@
1
+ from importlib.metadata import entry_points
2
+
3
+ from fastapi import APIRouter, Request, Depends
4
+ from fastapi.responses import HTMLResponse
5
+ from fastpluggy.core.dependency import get_view_builder, get_fastpluggy
6
+ from fastpluggy.core.plugin.dependency_resolver import PluginDependencyResolver
7
+ from fastpluggy.core.widgets.categories.data.debug import DebugView
8
+ from fastpluggy.core.view_builer.components.model import ModelView
9
+ from fastpluggy.core.view_builer.components.table import TableView
10
+
11
+ debug_module_router = APIRouter()
12
+
13
+
14
+ @debug_module_router.get("/list_modules_dependencies", response_class=HTMLResponse, name="list_modules_dependencies")
15
+ def list_modules_dependencies(
16
+ request: Request,
17
+ view_builder=Depends(get_view_builder),
18
+ fast_pluggy=Depends(get_fastpluggy)
19
+ ):
20
+ """
21
+ """
22
+
23
+ modules_info = fast_pluggy.module_manager.modules
24
+ dependency = PluginDependencyResolver.get_sorted_modules_by_dependency(modules_info)
25
+
26
+ return view_builder.generate(
27
+ request,
28
+ widgets=[
29
+ ModelView(
30
+ model=dependency['modules'],
31
+ title="Modules Dependencies"
32
+ ),
33
+ DebugView(data=dependency)
34
+ ]
35
+ )
36
+
37
+
38
+ @debug_module_router.get("/list_modules_package", response_class=HTMLResponse, name="list_modules_package")
39
+ def list_modules_package(
40
+ request: Request,
41
+ view_builder=Depends(get_view_builder),
42
+ ):
43
+ """
44
+ Endpoint to list all plugins declared via entry point group 'fastpluggy.plugins'.
45
+ """
46
+ try:
47
+ eps = entry_points(group="fastpluggy.plugins")
48
+ except TypeError:
49
+ # For Python <3.10 compat (not strictly needed here since you're on 3.10+)
50
+ eps = entry_points().get("fastpluggy.plugins", [])
51
+
52
+ data = [{
53
+ "name": ep.name,
54
+ "module": ep.module,
55
+ "attr": ep.attr,
56
+ "value": ep.value,
57
+ "dist": getattr(ep, "dist", None).name if hasattr(ep, "dist") else None,
58
+ "version": getattr(ep, "dist", None).version if hasattr(ep, "dist") else None,
59
+ } for ep in eps]
60
+
61
+ return view_builder.generate(
62
+ request,
63
+ widgets=[
64
+ TableView(
65
+ data=data,
66
+ title="Discovered FastPluggy Plugins",
67
+ fields=["name", "module", "attr", "value", "dist", "version"]
68
+ )
69
+ ]
70
+ )
@@ -0,0 +1,59 @@
1
+ from fastapi import Depends, APIRouter
2
+ from starlette.requests import Request
3
+ from starlette.responses import HTMLResponse
4
+
5
+ from fastpluggy.core.database import get_engine
6
+ from fastpluggy.core.dependency import get_view_builder
7
+ from fastpluggy.core.view_builer.components.model import ModelView
8
+ from fastpluggy.core.widgets.categories.data.debug import DebugView
9
+
10
+
11
+ # Create a FastAPI router for pool inspection
12
+ pool_router = APIRouter(prefix="/pool", tags=["pool"])
13
+
14
+
15
+ @pool_router.get(
16
+ "/info",
17
+ response_class=HTMLResponse,
18
+ name="pool_info"
19
+ )
20
+ def pool_info_html(
21
+ request: Request,
22
+ view_builder=Depends(get_view_builder),
23
+ engine=Depends(get_engine)
24
+ ):
25
+ """
26
+ Renders detailed SQLAlchemy connection pool information as an HTML page.
27
+ """
28
+ pool = engine.pool
29
+
30
+ # Gather key metrics
31
+ metrics = {
32
+ "checked_out": pool.checkedout(), # connections currently in use
33
+ "pool_size": pool.size(), # configured max size
34
+ "overflow": pool.overflow(), # connections opened beyond pool_size
35
+ "status": pool.status(), # human-readable status
36
+ }
37
+
38
+ # Access internal connections for deep debugging (use with caution)
39
+ raw_pool = []
40
+ if hasattr(pool, "_pool"):
41
+ try:
42
+ inner_queue = pool._pool
43
+ # queue.Queue uses .queue attr to store widgets
44
+ if hasattr(inner_queue, "queue"):
45
+ raw_pool = list(inner_queue.queue)
46
+ except Exception:
47
+ raw_pool = []
48
+
49
+ # Render via fastpluggy's view builder
50
+ return view_builder.generate(
51
+ request,
52
+ widgets=[
53
+ ModelView(model=metrics, title="Connection Pool Metrics"),
54
+ DebugView(data={
55
+ "raw_pool_connections": len(raw_pool),
56
+ "raw_pool": raw_pool
57
+ })
58
+ ]
59
+ )
@@ -0,0 +1,43 @@
1
+ from fastapi import APIRouter, Request, Depends
2
+ from fastpluggy.core.auth import require_authentication
3
+ from fastpluggy.core.dependency import get_view_builder, get_fastpluggy
4
+ from fastpluggy.core.widgets import ButtonListWidget, AutoLinkWidget
5
+
6
+ from ..widgets.psutil_analyzer import PsutilAnalyzerWidget
7
+
8
+ # Create router with authentication
9
+ psutil_analyzer_router = APIRouter(
10
+ prefix="/psutil-analyzer",
11
+ tags=["debug", "psutil"],
12
+ dependencies=[Depends(require_authentication)],
13
+ )
14
+
15
+ @psutil_analyzer_router.get("/", name="psutil_analyzer_dashboard")
16
+ async def psutil_analyzer_dashboard(
17
+ request: Request,
18
+ view_builder=Depends(get_view_builder),
19
+ fast_pluggy=Depends(get_fastpluggy)
20
+ ):
21
+ """
22
+ Render the PSUtil Analyzer dashboard using the custom widget.
23
+ """
24
+ # Register the widget if not already registered
25
+ #available_widgets = fast_pluggy.get_global('available_widget', {})
26
+ #if PsutilAnalyzerWidget.widget_type not in available_widgets:
27
+ # from fastpluggy_plugin.website_builder.src.widgets import get_class_path
28
+ # available_widgets[PsutilAnalyzerWidget.widget_type] = get_class_path(PsutilAnalyzerWidget)
29
+ # fast_pluggy.set_global('available_widget', available_widgets)
30
+
31
+ # Generate the view with the PSUtil Analyzer widget
32
+ return view_builder.generate(
33
+ request,
34
+ title="PSUtil Memory Analysis Dashboard",
35
+ widgets=[
36
+ PsutilAnalyzerWidget(
37
+ title="PSUtil Memory Analysis Dashboard"
38
+ ),
39
+ ButtonListWidget(buttons=[
40
+ AutoLinkWidget(label="Back to Debug Tools", route_name="list_tools"),
41
+ ]),
42
+ ]
43
+ )
@@ -0,0 +1,42 @@
1
+ from fastapi import Depends, APIRouter
2
+ from starlette.requests import Request
3
+ from starlette.responses import HTMLResponse
4
+
5
+ from ..requirements_tools import get_requirements_files, get_installed_packages, \
6
+ check_multiple_requirements_files
7
+ from fastpluggy.core.dependency import get_view_builder, get_fastpluggy
8
+ from fastpluggy.core.widgets.categories.data.debug import DebugView
9
+ from ..widgets.packages_view import PackagesView
10
+
11
+ requirements_router = APIRouter()
12
+
13
+
14
+ @requirements_router.get("/list_requirements", response_class=HTMLResponse, name="list_requirements")
15
+ def list_requirements(
16
+ request: Request,
17
+ view_builder=Depends(get_view_builder),
18
+ fast_pluggy=Depends(get_fastpluggy)
19
+ ):
20
+ list_requirements = get_requirements_files(fast_pluggy.module_manager.modules)
21
+ installed_packages = get_installed_packages()
22
+ missing_packages = check_multiple_requirements_files(list_requirements)
23
+ widgets = [
24
+ DebugView(
25
+ title="Missing Requirements",
26
+ data=missing_packages,
27
+ ),
28
+ DebugView(
29
+ title="Requirements Files",
30
+ data=list_requirements, collapsed=True
31
+ ),
32
+ PackagesView(
33
+ packages=installed_packages,
34
+ title="Installed Packages",
35
+ collapsed=False
36
+ )
37
+ ]
38
+ return view_builder.generate(
39
+ request,
40
+ title="List menu",
41
+ widgets=widgets
42
+ )
@@ -0,0 +1,94 @@
1
+ import asyncio
2
+ import pkgutil
3
+
4
+ from fastapi import APIRouter, Request, Depends
5
+ from fastapi.responses import HTMLResponse
6
+
7
+ from fastpluggy.core.dependency import get_view_builder, get_module_manager
8
+ from fastpluggy.core.widgets import TableWidget
9
+
10
+ task_thread_tools_router = APIRouter()
11
+
12
+ # ── your application’s own prefixes ──────────────────────────────────────────
13
+ # Adjust these two to match your real code’s top‐level package names.
14
+ USER_PREFIXES = ["fastpluggy", "fastpluggy_plugin"]
15
+
16
+ def gather_top_level_packages() -> set[str]:
17
+ """
18
+ Scan sys.path once and return all importable top-level module/package names.
19
+ """
20
+ return {info.name for info in pkgutil.iter_modules()}
21
+
22
+
23
+ ALL_PACKAGES = gather_top_level_packages()
24
+
25
+ @task_thread_tools_router.get(
26
+ "/list_tasks",
27
+ response_class=HTMLResponse,
28
+ name="list_all_tasks"
29
+ )
30
+ async def list_all_tasks(
31
+ request: Request,
32
+ view_builder=Depends(get_view_builder),
33
+ module_manager = Depends(get_module_manager)
34
+ ):
35
+ """
36
+ Endpoint to list all running asyncio.Tasks in the current event loop.
37
+ """
38
+
39
+ for item in module_manager.modules.values():
40
+ if item.package_name:
41
+ USER_PREFIXES.append(item.package_name)
42
+
43
+ clean_user_prefixes = list(set(USER_PREFIXES))
44
+
45
+ # 1. Grab every Task in the loop
46
+ all_tasks = asyncio.all_tasks()
47
+ user_rows = []
48
+ system_rows = []
49
+
50
+ for t in all_tasks:
51
+ coro = t.get_coro()
52
+
53
+ # 1) Try to grab the module from the live frame, if still running:
54
+ module_name = ""
55
+ if hasattr(coro, "cr_frame") and coro.cr_frame is not None:
56
+ module_name = coro.cr_frame.f_globals.get("__name__", "")
57
+ else:
58
+ # 2) If the coroutine is already finished, fallback to __module__ or empty
59
+ module_name = getattr(coro, "__module__", "") or ""
60
+
61
+ # Extract just the top‐level prefix (e.g. "uvicorn", "starlette", "myapp"):
62
+ top_level = module_name.split(".", 1)[0] if module_name else ""
63
+
64
+ # Prepare a common row format
65
+ entry = {
66
+ "coro_name": coro.__qualname__,
67
+ "module": module_name,
68
+ "top_level": top_level,
69
+ "done": t.done(),
70
+ "cancelled": t.cancelled(),
71
+ "repr": repr(coro),
72
+ }
73
+
74
+ if top_level in clean_user_prefixes:
75
+ user_rows.append(entry)
76
+ else:
77
+ system_rows.append(entry)
78
+
79
+ return view_builder.generate(
80
+ request,
81
+ widgets=[
82
+ TableWidget(
83
+ data=user_rows,
84
+ title=(
85
+ "User‐Defined Asyncio Tasks "
86
+ f"(top_level ∈ {sorted(clean_user_prefixes)})"
87
+ )
88
+ ),
89
+ TableWidget(
90
+ data=system_rows,
91
+ title="System/Library Asyncio Tasks"
92
+ )
93
+ ]
94
+ )
@@ -0,0 +1,46 @@
1
+ from fastpluggy.core.widgets import ButtonWidget
2
+ from fastapi import Request
3
+
4
+
5
+ def websocket_notification_button(request: Request):
6
+ """
7
+ Create a button to send a WebSocket notification.
8
+ """
9
+
10
+ try:
11
+ url_ws_send_message = request.url_for('send_message', method='json')
12
+
13
+ content = """
14
+ fetch('__url_ws_send_message__', {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': 'application/json'
18
+ },
19
+ body: JSON.stringify({type: 'message', content: 'test notification'})
20
+ })
21
+ .then(response => {
22
+ if (!response.ok) {
23
+ throw new Error(`HTTP error! Status: ${response.status}`);
24
+ }
25
+ return response.json();
26
+ })
27
+ .then(data => console.log(data))
28
+ .catch(error => console.error('Error sending message:', error));
29
+ """.replace('__url_ws_send_message__', url_ws_send_message)
30
+
31
+ return ButtonWidget(
32
+ url= "#", # No direct URL needed since we use JavaScript
33
+ label= "Send WebSocket Notification",
34
+ css_class= "btn btn-primary",
35
+ onclick=content ,
36
+ )
37
+ except Exception as e:
38
+ error_message = f"Error creating WebSocket notification button: {e}"
39
+ print(error_message)
40
+ return ButtonWidget(
41
+ url="#", # Dummy URL since the button is disabled
42
+ label="Send WebSocket Notification (Error)",
43
+ css_class="btn btn-danger",
44
+ disabled=True,
45
+ onclick=f"console.error('{error_message}')",
46
+ )
File without changes
File without changes
@@ -0,0 +1,26 @@
1
+ import time
2
+ from typing import Annotated
3
+
4
+ from loguru import logger
5
+ from fastpluggy_plugin.tasks_worker.task_registry import task_registry
6
+ from fastpluggy_plugin.tasks_worker.schema.context import TaskContext
7
+
8
+ from fastpluggy.core.tools.inspect_tools import InjectDependency
9
+
10
+
11
+ @task_registry.register(
12
+ description="Sample task with locking logic",
13
+ allow_concurrent=False, # This flag is used by TaskLockManager
14
+ )
15
+ def locked_sample_task(context: Annotated[TaskContext, InjectDependency] ):
16
+ task_name = context.task_name
17
+
18
+ logger.info(f"Task {task_name} is locked")
19
+
20
+ try:
21
+ for i in range(15):
22
+ logger.info(f"[{task_name}] Running... {i+1}/15")
23
+ time.sleep(1)
24
+ return f"{task_name} finished work!"
25
+ finally:
26
+ logger.info(f"Releasing lock for {task_name}")
@@ -0,0 +1,27 @@
1
+ import asyncio
2
+ from typing import Annotated
3
+
4
+ from fastpluggy.core.tools.inspect_tools import InjectDependency
5
+
6
+ from fastpluggy_plugin.tasks_worker.task_registry import task_registry
7
+ from fastpluggy_plugin.tasks_worker.schema.context import TaskContext
8
+ from fastpluggy_plugin.tasks_worker.services.notification_service import TaskNotificationService
9
+
10
+
11
+ @task_registry.register()
12
+ async def sample_progress_task(context: Annotated[TaskContext, InjectDependency], i: int, delay: float = 1.0, ):
13
+ from loguru import logger
14
+ logger.info("Starting sample task...")
15
+ for step in range(5):
16
+ logger.info(f"[Task {i}] Step {step + 1}")
17
+ await asyncio.sleep(delay)
18
+
19
+ if context:
20
+ TaskNotificationService.notify_progress(
21
+ context,
22
+ message=f"Completed step {step + 1}/5",
23
+ percent=(step + 1) * 20,
24
+ step=f"Step-{step + 1}"
25
+ )
26
+
27
+ return f"Task {i} complete"
@@ -0,0 +1,67 @@
1
+ import logging
2
+ import time
3
+
4
+ from loguru import logger
5
+
6
+ from fastpluggy_plugin.tasks_worker.task_registry import task_registry
7
+
8
+
9
+ @task_registry.register()
10
+ def sync_job(x, name=None):
11
+ logging.info("Running sync job...")
12
+ logger.info(f"Hello from loguru - {name}")
13
+ return f"Sync result: {x} by {name}"
14
+
15
+
16
+ @task_registry.register()
17
+ async def async_job(x):
18
+ import asyncio
19
+ logger.info("Running async job...")
20
+ await asyncio.sleep(1)
21
+ return f"Async result: {x}"
22
+
23
+
24
+ @task_registry.register()
25
+ def failing_sync(x):
26
+ logging.info("About to fail...")
27
+ raise ValueError(f"Bad value: {x}")
28
+
29
+
30
+ @task_registry.register()
31
+ async def failing_async():
32
+ logger.info("This will always fail")
33
+ raise ValueError("Nope, still broken")
34
+
35
+
36
+ @task_registry.register(description='Flaky task')
37
+ def flaky_task(attempts_left=[2]):
38
+ logging.info("Trying...")
39
+ if attempts_left[0] > 0:
40
+ attempts_left[0] -= 1
41
+ raise RuntimeError("Temporary failure.")
42
+ return "Succeeded!"
43
+
44
+
45
+ @task_registry.register()
46
+ async def sample_task(i: int, delay: float = 1.0):
47
+ """
48
+ Sample of task
49
+ """
50
+ logger.info("Starting sample task...")
51
+ logger.info(f"Task {i}")
52
+ logger.info(f"Delay {delay}")
53
+ for x in range(5):
54
+ logging.info(f"[Task {i}] Step {x + 1}")
55
+ time.sleep(delay)
56
+ return f"Task {i} complete"
57
+
58
+ @task_registry.register(
59
+ description="Syncs data to remote",
60
+ tags=["sync", "data"],
61
+ schedule="*/5 * * * *",
62
+ max_retries=3
63
+ )
64
+ def sync_data_task():
65
+ """This task syncs data to the remote server."""
66
+ ...
67
+ print("Task sync_data_task running ...")
@@ -0,0 +1,53 @@
1
+ import time
2
+ from typing import Annotated
3
+
4
+ from loguru import logger
5
+
6
+ from fastpluggy.core.tools.inspect_tools import InjectDependency
7
+
8
+ from fastpluggy_plugin.tasks_worker.schema.context import TaskContext
9
+
10
+
11
+ def some_task_function(context: Annotated[TaskContext, InjectDependency], task_input: dict = None):
12
+ logger.info("Starting some_task_function execution.")
13
+ context.log_context({"input": task_input})
14
+
15
+ # Simulate task steps
16
+ for i in range(1, 6):
17
+ time.sleep(1) # Simulate work
18
+ logger.info(f"Processing step {i}")
19
+ context.log_context({"step": i, "progress": f"{i * 20}%"})
20
+
21
+ logger.info("Task execution completed.")
22
+ context.log_context({"result": "success"})
23
+ return "Task completed!"
24
+
25
+
26
+ def some_task_exception():
27
+ logger.info("Starting some_task_exception execution.")
28
+
29
+ raise Exception("Some Exception")
30
+
31
+
32
+ def some_task_function_loguru(task_input: dict = None):
33
+ """
34
+ Execute a task and log progress using loguru.
35
+
36
+ Args:
37
+ task_input (dict): Input data for the task.
38
+
39
+ Returns:
40
+ str: Task result message.
41
+ """
42
+ logger.info("Starting some_task_function_loguru execution.")
43
+ logger.debug(f"Task input: {task_input}")
44
+
45
+ # Simulate task steps
46
+ for i in range(1, 6):
47
+ time.sleep(1) # Simulate work
48
+ logger.info(f"Processing step {i}")
49
+ logger.debug(f"Step {i}: Progress: {i * 20}%")
50
+
51
+ logger.info("Task execution completed.")
52
+ logger.debug("Result: success")
53
+ return "Task completed!"