lightfall 0.1.1__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.
- lightfall/__init__.py +8 -0
- lightfall/__main__.py +10 -0
- lightfall/_version.py +24 -0
- lightfall/acquire/__init__.py +74 -0
- lightfall/acquire/buffer.py +363 -0
- lightfall/acquire/device_wrapper.py +416 -0
- lightfall/acquire/engine/__init__.py +155 -0
- lightfall/acquire/engine/base.py +587 -0
- lightfall/acquire/engine/bluesky.py +358 -0
- lightfall/acquire/engine/mock.py +165 -0
- lightfall/acquire/engine/plugins/__init__.py +9 -0
- lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
- lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
- lightfall/acquire/engine/protocol.py +145 -0
- lightfall/acquire/engine/registry.py +152 -0
- lightfall/acquire/engine/state.py +32 -0
- lightfall/acquire/engine/waiting_hook.py +225 -0
- lightfall/acquire/nats_bridge.py +62 -0
- lightfall/acquire/plan_ui.py +78 -0
- lightfall/acquire/plans/__init__.py +38 -0
- lightfall/acquire/plans/adaptive.py +288 -0
- lightfall/acquire/plans/example_plans.py +995 -0
- lightfall/acquire/plans/lightfall_plans.py +587 -0
- lightfall/acquire/plans/registry.py +543 -0
- lightfall/acquire/plans/standard_plans.py +186 -0
- lightfall/acquire/plans/user_plans.py +470 -0
- lightfall/acquire/runengine.py +36 -0
- lightfall/acquire/signals.py +452 -0
- lightfall/acquire/triggers/__init__.py +16 -0
- lightfall/acquire/triggers/base.py +25 -0
- lightfall/acquire/triggers/filter.py +37 -0
- lightfall/acquire/triggers/manager.py +73 -0
- lightfall/acquire/triggers/manual.py +36 -0
- lightfall/acquire/triggers/run_end.py +74 -0
- lightfall/acquire/triggers/run_start.py +52 -0
- lightfall/auth/__init__.py +38 -0
- lightfall/auth/policy.py +518 -0
- lightfall/auth/providers/__init__.py +30 -0
- lightfall/auth/providers/base.py +124 -0
- lightfall/auth/providers/keycloak.py +1017 -0
- lightfall/auth/providers/local.py +319 -0
- lightfall/auth/providers/pam.py +250 -0
- lightfall/auth/service_key.py +173 -0
- lightfall/auth/service_key_auth.py +79 -0
- lightfall/auth/session.py +656 -0
- lightfall/claude/__init__.py +52 -0
- lightfall/claude/_internal/__init__.py +1 -0
- lightfall/claude/_internal/serialization.py +195 -0
- lightfall/claude/_internal/threading.py +61 -0
- lightfall/claude/_internal/worker.py +757 -0
- lightfall/claude/_session_assembly.py +124 -0
- lightfall/claude/agent.py +596 -0
- lightfall/claude/lightfall_core_tools.py +410 -0
- lightfall/claude/markdown.py +103 -0
- lightfall/claude/permission_manager.py +588 -0
- lightfall/claude/tools/__init__.py +45 -0
- lightfall/claude/tools/controller.py +143 -0
- lightfall/claude/tools/interaction.py +177 -0
- lightfall/claude/tools/introspection.py +127 -0
- lightfall/claude/tools/logs.py +155 -0
- lightfall/claude/tools/screenshot.py +87 -0
- lightfall/claude/widget.py +851 -0
- lightfall/claude/widgets/__init__.py +5 -0
- lightfall/claude/widgets/permission_request.py +282 -0
- lightfall/claude/widgets/question_request.py +227 -0
- lightfall/claude/widgets/task_card.py +223 -0
- lightfall/config/__init__.py +23 -0
- lightfall/config/layers.py +317 -0
- lightfall/config/manager.py +244 -0
- lightfall/config/schema.py +154 -0
- lightfall/core/__init__.py +23 -0
- lightfall/core/application.py +727 -0
- lightfall/core/services.py +235 -0
- lightfall/devices/__init__.py +53 -0
- lightfall/devices/backends/__init__.py +17 -0
- lightfall/devices/backends/bcs.py +448 -0
- lightfall/devices/backends/happi.py +986 -0
- lightfall/devices/backends/mock.py +646 -0
- lightfall/devices/base.py +338 -0
- lightfall/devices/catalog.py +1039 -0
- lightfall/devices/connection_manager.py +676 -0
- lightfall/devices/model.py +290 -0
- lightfall/devices/monitoring.py +442 -0
- lightfall/devices/sim/__init__.py +26 -0
- lightfall/devices/sim/areadetector.py +436 -0
- lightfall/devices/sim/generators.py +223 -0
- lightfall/devices/sim/plugins.py +116 -0
- lightfall/epics/__init__.py +28 -0
- lightfall/epics/ca/__init__.py +10 -0
- lightfall/epics/ca/context.py +100 -0
- lightfall/epics/ca/pv.py +303 -0
- lightfall/epics/widgets/__init__.py +49 -0
- lightfall/epics/widgets/areadetector/__init__.py +16 -0
- lightfall/epics/widgets/areadetector/areadetector.py +281 -0
- lightfall/epics/widgets/areadetector/controls.py +478 -0
- lightfall/epics/widgets/areadetector/image_view.py +447 -0
- lightfall/epics/widgets/auto.py +319 -0
- lightfall/epics/widgets/base.py +404 -0
- lightfall/epics/widgets/checkbox.py +239 -0
- lightfall/epics/widgets/combobox.py +202 -0
- lightfall/epics/widgets/label.py +176 -0
- lightfall/epics/widgets/lineedit.py +253 -0
- lightfall/epics/widgets/motor.py +694 -0
- lightfall/epics/widgets/ophyd_base.py +469 -0
- lightfall/epics/widgets/ophyd_combobox.py +86 -0
- lightfall/epics/widgets/ophyd_label.py +54 -0
- lightfall/epics/widgets/ophyd_lineedit.py +170 -0
- lightfall/epics/widgets/ophyd_spinbox.py +79 -0
- lightfall/epics/widgets/slider.py +272 -0
- lightfall/epics/widgets/status_indicator.py +98 -0
- lightfall/epics/widgets/style.py +188 -0
- lightfall/exporter/__init__.py +1 -0
- lightfall/exporter/cli.py +67 -0
- lightfall/exporter/converters/__init__.py +26 -0
- lightfall/exporter/converters/base.py +39 -0
- lightfall/exporter/converters/noop.py +39 -0
- lightfall/exporter/converters/nxsas.py +73 -0
- lightfall/exporter/service.py +200 -0
- lightfall/exporter/tiled_utils.py +92 -0
- lightfall/ipc/__init__.py +6 -0
- lightfall/ipc/service.py +701 -0
- lightfall/ipc/trust.py +144 -0
- lightfall/logbook/__init__.py +46 -0
- lightfall/logbook/action_dialog.py +207 -0
- lightfall/logbook/action_logger.py +432 -0
- lightfall/logbook/block_mapper.py +562 -0
- lightfall/logbook/client.py +799 -0
- lightfall/logbook/converter.py +273 -0
- lightfall/logbook/editors/__init__.py +19 -0
- lightfall/logbook/editors/highlighter.py +305 -0
- lightfall/logbook/editors/markdown_editor.py +319 -0
- lightfall/logbook/editors/richtext_editor.py +1397 -0
- lightfall/logbook/entry_widget.py +1065 -0
- lightfall/logbook/event_listener.py +221 -0
- lightfall/logbook/fragment_widgets.py +925 -0
- lightfall/logbook/position_mapper.py +320 -0
- lightfall/logbook/protection.py +402 -0
- lightfall/logbook/style.py +394 -0
- lightfall/logbook/url.py +29 -0
- lightfall/logbook/visual_protection.py +330 -0
- lightfall/logbook/widget.py +680 -0
- lightfall/main.py +1091 -0
- lightfall/pipelines/__init__.py +4 -0
- lightfall/pipelines/client.py +148 -0
- lightfall/plugins/__init__.py +119 -0
- lightfall/plugins/agent_plugin.py +106 -0
- lightfall/plugins/agents/__init__.py +10 -0
- lightfall/plugins/agents/_mcp_helpers.py +52 -0
- lightfall/plugins/agents/alignment.py +94 -0
- lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
- lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
- lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
- lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
- lightfall/plugins/agents/current_esaf.py +435 -0
- lightfall/plugins/agents/device_tools.py +1043 -0
- lightfall/plugins/agents/engine_tools.py +720 -0
- lightfall/plugins/agents/ipython_tools.py +444 -0
- lightfall/plugins/agents/panel_builder.py +637 -0
- lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
- lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
- lightfall/plugins/agents/panel_design.py +94 -0
- lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
- lightfall/plugins/agents/plan_design.py +90 -0
- lightfall/plugins/agents/plan_tools.py +878 -0
- lightfall/plugins/agents/scan_planning.py +101 -0
- lightfall/plugins/builtin_manifest.py +348 -0
- lightfall/plugins/controller_plugin.py +162 -0
- lightfall/plugins/engine_plugin.py +124 -0
- lightfall/plugins/errors.py +104 -0
- lightfall/plugins/info.py +112 -0
- lightfall/plugins/loader.py +878 -0
- lightfall/plugins/manifest.py +150 -0
- lightfall/plugins/panel_plugin.py +119 -0
- lightfall/plugins/plan_plugin.py +163 -0
- lightfall/plugins/registry.py +309 -0
- lightfall/plugins/settings_plugin.py +226 -0
- lightfall/plugins/statusbar_plugin.py +289 -0
- lightfall/plugins/theme_plugin.py +165 -0
- lightfall/plugins/types.py +136 -0
- lightfall/plugins/user_plugins.py +764 -0
- lightfall/project/__init__.py +37 -0
- lightfall/project/model.py +375 -0
- lightfall/project/service.py +427 -0
- lightfall/project/welcome.py +106 -0
- lightfall/resources/__init__.py +126 -0
- lightfall/resources/images/__init__.py +1 -0
- lightfall/resources/images/icon.ico +0 -0
- lightfall/resources/images/icon.png +0 -0
- lightfall/resources/images/logo.png +0 -0
- lightfall/services/__init__.py +33 -0
- lightfall/services/_alshub_client.py +73 -0
- lightfall/services/access_stamper.py +240 -0
- lightfall/services/als_beam_status.py +347 -0
- lightfall/services/ca_tunnel.py +325 -0
- lightfall/services/threaded_tiled_writer.py +174 -0
- lightfall/services/tiled_auth.py +21 -0
- lightfall/services/tiled_service.py +971 -0
- lightfall/services/tiled_writer_patch.py +301 -0
- lightfall/settings/__init__.py +1 -0
- lightfall/settings/image_helpers.py +30 -0
- lightfall/settings/user_settings_client.py +232 -0
- lightfall/ui/__init__.py +28 -0
- lightfall/ui/annotations.py +208 -0
- lightfall/ui/common/__init__.py +7 -0
- lightfall/ui/dialogs/__init__.py +26 -0
- lightfall/ui/dialogs/about_dialog.py +131 -0
- lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
- lightfall/ui/dialogs/base.py +44 -0
- lightfall/ui/dialogs/bug_report_dialog.py +353 -0
- lightfall/ui/dialogs/create_plan_dialog.py +189 -0
- lightfall/ui/dialogs/device_edit_dialog.py +183 -0
- lightfall/ui/dialogs/export_dialog.py +565 -0
- lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
- lightfall/ui/dialogs/login_dialog.py +756 -0
- lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
- lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
- lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
- lightfall/ui/docking/__init__.py +22 -0
- lightfall/ui/docking/icon_sidebar.py +806 -0
- lightfall/ui/docking/manager.py +682 -0
- lightfall/ui/docking/state.py +113 -0
- lightfall/ui/docking/theme.py +399 -0
- lightfall/ui/docking/widget.py +214 -0
- lightfall/ui/events.py +75 -0
- lightfall/ui/mainwindow.py +1006 -0
- lightfall/ui/models/__init__.py +49 -0
- lightfall/ui/models/device_selection.py +389 -0
- lightfall/ui/models/device_tree.py +1095 -0
- lightfall/ui/models/thread_model.py +667 -0
- lightfall/ui/models/tiled_model.py +384 -0
- lightfall/ui/panels/__init__.py +28 -0
- lightfall/ui/panels/base.py +525 -0
- lightfall/ui/panels/bluesky_panel.py +619 -0
- lightfall/ui/panels/claude/__init__.py +9 -0
- lightfall/ui/panels/claude/agent_registry.py +168 -0
- lightfall/ui/panels/claude_panel.py +887 -0
- lightfall/ui/panels/device_panel.py +370 -0
- lightfall/ui/panels/documents_panel.py +166 -0
- lightfall/ui/panels/ipython_panel.py +580 -0
- lightfall/ui/panels/logbook_entries_panel.py +84 -0
- lightfall/ui/panels/logbook_panel.py +627 -0
- lightfall/ui/panels/logging_panel.py +587 -0
- lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
- lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
- lightfall/ui/panels/plugins/__init__.py +34 -0
- lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
- lightfall/ui/panels/plugins/claude_plugin.py +29 -0
- lightfall/ui/panels/plugins/device_plugin.py +27 -0
- lightfall/ui/panels/plugins/documents_plugin.py +26 -0
- lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
- lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
- lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
- lightfall/ui/panels/plugins/logging_plugin.py +27 -0
- lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
- lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
- lightfall/ui/panels/plugins/queue_plugin.py +29 -0
- lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
- lightfall/ui/panels/plugins/threads_plugin.py +27 -0
- lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
- lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
- lightfall/ui/panels/queue.py +754 -0
- lightfall/ui/panels/registry.py +483 -0
- lightfall/ui/panels/synoptic/__init__.py +27 -0
- lightfall/ui/panels/synoptic/editors.py +481 -0
- lightfall/ui/panels/synoptic/items.py +556 -0
- lightfall/ui/panels/synoptic/models.py +336 -0
- lightfall/ui/panels/synoptic/panel.py +889 -0
- lightfall/ui/panels/synoptic/serialization.py +300 -0
- lightfall/ui/panels/synoptic/view.py +504 -0
- lightfall/ui/panels/threads_panel.py +621 -0
- lightfall/ui/panels/tiled_browser_panel.py +854 -0
- lightfall/ui/panels/visualization_panel.py +508 -0
- lightfall/ui/preferences/__init__.py +24 -0
- lightfall/ui/preferences/backend.py +148 -0
- lightfall/ui/preferences/builtin.py +220 -0
- lightfall/ui/preferences/claude_settings.py +762 -0
- lightfall/ui/preferences/device_settings.py +461 -0
- lightfall/ui/preferences/dialog.py +234 -0
- lightfall/ui/preferences/editor_settings.py +227 -0
- lightfall/ui/preferences/ipc_settings.py +226 -0
- lightfall/ui/preferences/logbook_settings.py +232 -0
- lightfall/ui/preferences/login_settings.py +183 -0
- lightfall/ui/preferences/manager.py +562 -0
- lightfall/ui/preferences/plugin_settings.py +392 -0
- lightfall/ui/preferences/proxy_settings.py +561 -0
- lightfall/ui/preferences/skill_settings.py +28 -0
- lightfall/ui/preferences/tiled_settings.py +469 -0
- lightfall/ui/preferences/tool_settings.py +393 -0
- lightfall/ui/preferences/user_portable_backend.py +131 -0
- lightfall/ui/preferences/user_profile_settings.py +316 -0
- lightfall/ui/preferences/visualization_settings.py +159 -0
- lightfall/ui/resources/__init__.py +1 -0
- lightfall/ui/resources/logo.png +0 -0
- lightfall/ui/statusbar/__init__.py +11 -0
- lightfall/ui/statusbar/manager.py +379 -0
- lightfall/ui/statusbar/plugins/__init__.py +28 -0
- lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
- lightfall/ui/statusbar/plugins/auth_status.py +116 -0
- lightfall/ui/statusbar/plugins/connection_status.py +100 -0
- lightfall/ui/statusbar/plugins/thread_status.py +556 -0
- lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
- lightfall/ui/statusbar/plugins/user_status.py +84 -0
- lightfall/ui/theater/__init__.py +28 -0
- lightfall/ui/theater/manager.py +124 -0
- lightfall/ui/theater/overlay.py +279 -0
- lightfall/ui/theater/proxy.py +111 -0
- lightfall/ui/theme/__init__.py +18 -0
- lightfall/ui/theme/builtin.py +1015 -0
- lightfall/ui/theme/manager.py +875 -0
- lightfall/ui/theme/registry.py +195 -0
- lightfall/ui/toast.py +221 -0
- lightfall/ui/tutorial.py +1100 -0
- lightfall/ui/widgets/__init__.py +110 -0
- lightfall/ui/widgets/base_control.py +259 -0
- lightfall/ui/widgets/camera/__init__.py +36 -0
- lightfall/ui/widgets/camera/base.py +815 -0
- lightfall/ui/widgets/camera/dark_frames.py +213 -0
- lightfall/ui/widgets/camera/image_view.py +649 -0
- lightfall/ui/widgets/camera/panels/__init__.py +14 -0
- lightfall/ui/widgets/camera/panels/cooler.py +320 -0
- lightfall/ui/widgets/camera/panels/temperature.py +192 -0
- lightfall/ui/widgets/camera/plan_based.py +202 -0
- lightfall/ui/widgets/compact_motor.py +522 -0
- lightfall/ui/widgets/controller_matcher.py +278 -0
- lightfall/ui/widgets/controller_registry.py +144 -0
- lightfall/ui/widgets/device_control.py +411 -0
- lightfall/ui/widgets/device_selector.py +438 -0
- lightfall/ui/widgets/device_tree_tab.py +461 -0
- lightfall/ui/widgets/document_stream.py +1028 -0
- lightfall/ui/widgets/favorites_tab.py +191 -0
- lightfall/ui/widgets/motor_control.py +1120 -0
- lightfall/ui/widgets/observers/__init__.py +8 -0
- lightfall/ui/widgets/observers/camera.py +48 -0
- lightfall/ui/widgets/observers/image_view.py +130 -0
- lightfall/ui/widgets/plan_config.py +954 -0
- lightfall/ui/widgets/plan_edit_dialog.py +294 -0
- lightfall/ui/widgets/plan_selector.py +452 -0
- lightfall/ui/widgets/profile_avatar.py +128 -0
- lightfall/ui/widgets/queue_view.py +647 -0
- lightfall/ui/widgets/runengine_control.py +549 -0
- lightfall/ui/widgets/signal_control.py +793 -0
- lightfall/ui/widgets/skill_trigger_button.py +183 -0
- lightfall/ui/widgets/tiled_filter_widget.py +314 -0
- lightfall/ui/widgets/tiled_status.py +149 -0
- lightfall/ui/widgets/warning_banner.py +185 -0
- lightfall/utils/__init__.py +53 -0
- lightfall/utils/crash_diagnostics.py +454 -0
- lightfall/utils/data_migration.py +22 -0
- lightfall/utils/editor_launcher.py +594 -0
- lightfall/utils/error_collector.py +245 -0
- lightfall/utils/git_tracker.py +197 -0
- lightfall/utils/log_buffer.py +233 -0
- lightfall/utils/logging.py +229 -0
- lightfall/utils/module_resolver.py +70 -0
- lightfall/utils/sentry.py +722 -0
- lightfall/utils/threads.py +991 -0
- lightfall/utils/tiled_helpers.py +96 -0
- lightfall/visualization/__init__.py +50 -0
- lightfall/visualization/base.py +5 -0
- lightfall/visualization/base_visualization.py +74 -0
- lightfall/visualization/fitting/__init__.py +24 -0
- lightfall/visualization/fitting/base.py +267 -0
- lightfall/visualization/fitting/fitters.py +325 -0
- lightfall/visualization/fitting/panel.py +265 -0
- lightfall/visualization/memory.py +392 -0
- lightfall/visualization/motor_mixin.py +524 -0
- lightfall/visualization/pg.py +156 -0
- lightfall/visualization/registry.py +144 -0
- lightfall/visualization/spec.py +79 -0
- lightfall/visualization/theme.py +266 -0
- lightfall/visualization/widgets/__init__.py +28 -0
- lightfall/visualization/widgets/adaptive/__init__.py +1 -0
- lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
- lightfall/visualization/widgets/adaptive/plot.py +233 -0
- lightfall/visualization/widgets/heatmap.py +264 -0
- lightfall/visualization/widgets/image_stack.py +316 -0
- lightfall/visualization/widgets/image_view_toolbar.py +227 -0
- lightfall/visualization/widgets/lazy_image_view.py +590 -0
- lightfall/visualization/widgets/plot_1d.py +262 -0
- lightfall/visualization/widgets/scatter.py +247 -0
- lightfall/visualization/widgets/table.py +221 -0
- lightfall/visualization/widgets/time_axis.py +93 -0
- lightfall-0.1.1.dist-info/METADATA +223 -0
- lightfall-0.1.1.dist-info/RECORD +388 -0
- lightfall-0.1.1.dist-info/WHEEL +4 -0
- lightfall-0.1.1.dist-info/entry_points.txt +6 -0
- lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
- lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
lightfall/ipc/service.py
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
"""NATS-based IPC service for Lightfall.
|
|
2
|
+
|
|
3
|
+
Provides a Qt-integrated wrapper around nats-py that handles connection
|
|
4
|
+
lifecycle, topic routing, pub/sub, and request/reply patterns.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import ssl
|
|
14
|
+
import threading
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import nats
|
|
20
|
+
from loguru import logger
|
|
21
|
+
from PySide6.QtCore import QObject, Signal
|
|
22
|
+
|
|
23
|
+
from lightfall.ipc.trust import TrustManager, TrustState
|
|
24
|
+
from lightfall.utils.threads import invoke_in_main_thread
|
|
25
|
+
|
|
26
|
+
__all__ = ["IPCService", "ActionInfo", "EventInfo", "_ActionHandle", "get_ipc_service"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
# Data classes
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class ActionInfo:
|
|
36
|
+
"""Metadata for an IPC action (request/reply subject)."""
|
|
37
|
+
|
|
38
|
+
subject: str
|
|
39
|
+
description: str = ""
|
|
40
|
+
schema: dict[str, Any] | None = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class EventInfo:
|
|
45
|
+
"""Metadata for an IPC event (publish/subscribe subject)."""
|
|
46
|
+
|
|
47
|
+
subject: str
|
|
48
|
+
description: str = ""
|
|
49
|
+
schema: dict[str, Any] | None = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class _Subscription:
|
|
54
|
+
"""Internal subscription record."""
|
|
55
|
+
|
|
56
|
+
subject: str
|
|
57
|
+
callback: Callable[[str, dict, str | None], Any]
|
|
58
|
+
main_thread: bool
|
|
59
|
+
nats_sub: Any # nats.aio.subscription.Subscription | None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ---------------------------------------------------------------------------
|
|
63
|
+
# _ActionHandle
|
|
64
|
+
# ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _ActionHandle:
|
|
68
|
+
"""Handle returned by :meth:`IPCService.register_action`.
|
|
69
|
+
|
|
70
|
+
Calling :meth:`unregister` removes the action from the catalog and
|
|
71
|
+
cancels its NATS subscription.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(self, service: IPCService, suffix: str, subject: str) -> None:
|
|
75
|
+
self._service = service
|
|
76
|
+
self._suffix = suffix
|
|
77
|
+
self._subject = subject
|
|
78
|
+
|
|
79
|
+
def unregister(self) -> None:
|
|
80
|
+
"""Remove this action from the catalog and unsubscribe."""
|
|
81
|
+
self._service._action_catalog.pop(self._suffix, None)
|
|
82
|
+
self._service.unsubscribe(self._subject)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ---------------------------------------------------------------------------
|
|
86
|
+
# IPCService
|
|
87
|
+
# ---------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class IPCService(QObject):
|
|
91
|
+
"""NATS-backed IPC service with Qt integration.
|
|
92
|
+
|
|
93
|
+
Runs a dedicated asyncio event loop on a background daemon thread so that
|
|
94
|
+
NATS async I/O does not block the Qt main thread.
|
|
95
|
+
|
|
96
|
+
Signals:
|
|
97
|
+
sigConnectionChanged(bool): Emitted whenever the NATS connection state
|
|
98
|
+
changes. True = connected, False = disconnected.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
sigConnectionChanged = Signal(bool)
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
nats_url: str,
|
|
106
|
+
topic_prefix: str = "",
|
|
107
|
+
parent: QObject | None = None,
|
|
108
|
+
) -> None:
|
|
109
|
+
super().__init__(parent)
|
|
110
|
+
self._nats_url = nats_url
|
|
111
|
+
self._topic_prefix = topic_prefix
|
|
112
|
+
|
|
113
|
+
self._connected_lock = threading.Lock()
|
|
114
|
+
self._connected: bool = False
|
|
115
|
+
self._connectivity_error_logged: bool = False
|
|
116
|
+
self._nc: nats.NATS | None = None
|
|
117
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
118
|
+
self._thread: threading.Thread | None = None
|
|
119
|
+
self._shutdown_event = threading.Event()
|
|
120
|
+
self._subscriptions: dict[str, _Subscription] = {}
|
|
121
|
+
self._action_catalog: dict[str, ActionInfo] = {}
|
|
122
|
+
self._event_catalog: dict[str, EventInfo] = {}
|
|
123
|
+
self._trust: TrustManager | None = None
|
|
124
|
+
self._instance_id = f"{platform.node()}-{os.getpid()}"
|
|
125
|
+
self._display_name: str | None = None
|
|
126
|
+
|
|
127
|
+
# ------------------------------------------------------------------
|
|
128
|
+
# Properties
|
|
129
|
+
# ------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def instance_id(self) -> str:
|
|
133
|
+
"""Unique identity for this IPCService instance (``{hostname}-{pid}``)."""
|
|
134
|
+
return self._instance_id
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def display_name(self) -> str | None:
|
|
138
|
+
"""Optional human-readable name for this instance."""
|
|
139
|
+
return self._display_name
|
|
140
|
+
|
|
141
|
+
@display_name.setter
|
|
142
|
+
def display_name(self, value: str | None) -> None:
|
|
143
|
+
self._display_name = value
|
|
144
|
+
|
|
145
|
+
# ------------------------------------------------------------------
|
|
146
|
+
# Topic builder
|
|
147
|
+
# ------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
def topic(self, suffix: str) -> str:
|
|
150
|
+
"""Build a full subject by joining the configured prefix and *suffix*.
|
|
151
|
+
|
|
152
|
+
If the prefix is empty the suffix is returned unchanged (no leading dot).
|
|
153
|
+
"""
|
|
154
|
+
if self._topic_prefix:
|
|
155
|
+
return f"{self._topic_prefix}.{suffix}"
|
|
156
|
+
return suffix
|
|
157
|
+
|
|
158
|
+
# ------------------------------------------------------------------
|
|
159
|
+
# Action & event catalog
|
|
160
|
+
# ------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
def register_action(
|
|
163
|
+
self,
|
|
164
|
+
suffix: str,
|
|
165
|
+
callback: Callable[[str, dict, str | None], Any],
|
|
166
|
+
*,
|
|
167
|
+
description: str = "",
|
|
168
|
+
schema: dict[str, Any] | None = None,
|
|
169
|
+
main_thread: bool = True,
|
|
170
|
+
) -> _ActionHandle:
|
|
171
|
+
"""Register a request/reply action handler.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
suffix: Subject suffix (appended to the topic prefix).
|
|
175
|
+
callback: Called as ``callback(subject, data, reply)`` for each
|
|
176
|
+
incoming request.
|
|
177
|
+
description: Human-readable description for meta-discovery.
|
|
178
|
+
schema: Optional JSON Schema describing the request payload.
|
|
179
|
+
main_thread: If True (default) the callback runs on the Qt main
|
|
180
|
+
thread.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
An :class:`_ActionHandle` whose :meth:`~_ActionHandle.unregister`
|
|
184
|
+
method removes both the catalog entry and the subscription.
|
|
185
|
+
"""
|
|
186
|
+
full_subject = self.topic(suffix)
|
|
187
|
+
self._action_catalog[suffix] = ActionInfo(
|
|
188
|
+
subject=suffix, description=description, schema=schema
|
|
189
|
+
)
|
|
190
|
+
self.subscribe(full_subject, callback, main_thread=main_thread)
|
|
191
|
+
return _ActionHandle(self, suffix, full_subject)
|
|
192
|
+
|
|
193
|
+
def register_event(
|
|
194
|
+
self,
|
|
195
|
+
suffix: str,
|
|
196
|
+
*,
|
|
197
|
+
description: str = "",
|
|
198
|
+
schema: dict[str, Any] | None = None,
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Register an event in the event catalog (no subscription created).
|
|
201
|
+
|
|
202
|
+
This is catalog-only — it exists so that remote clients can discover
|
|
203
|
+
which events this service may publish via ``list_events()`` / the
|
|
204
|
+
``meta.events`` endpoint.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
suffix: Subject suffix used when publishing the event.
|
|
208
|
+
description: Human-readable description for meta-discovery.
|
|
209
|
+
schema: Optional JSON Schema describing the event payload.
|
|
210
|
+
"""
|
|
211
|
+
self._event_catalog[suffix] = EventInfo(
|
|
212
|
+
subject=suffix, description=description, schema=schema
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
def list_actions(self) -> list[dict[str, Any]]:
|
|
216
|
+
"""Return catalog metadata for all registered actions."""
|
|
217
|
+
return [
|
|
218
|
+
{"subject": info.subject, "description": info.description, "schema": info.schema}
|
|
219
|
+
for info in self._action_catalog.values()
|
|
220
|
+
]
|
|
221
|
+
|
|
222
|
+
def list_events(self) -> list[dict[str, Any]]:
|
|
223
|
+
"""Return catalog metadata for all registered events."""
|
|
224
|
+
return [
|
|
225
|
+
{"subject": info.subject, "description": info.description, "schema": info.schema}
|
|
226
|
+
for info in self._event_catalog.values()
|
|
227
|
+
]
|
|
228
|
+
|
|
229
|
+
# ------------------------------------------------------------------
|
|
230
|
+
# Meta-discovery endpoints
|
|
231
|
+
# ------------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
def _handle_meta_actions(
|
|
234
|
+
self, subject: str, data: dict, reply: str | None
|
|
235
|
+
) -> None:
|
|
236
|
+
"""Respond to a ``meta.actions`` request with the action catalog."""
|
|
237
|
+
if reply:
|
|
238
|
+
self.reply(reply, {
|
|
239
|
+
"instance_id": self._instance_id,
|
|
240
|
+
"display_name": self._display_name,
|
|
241
|
+
"prefix": self._topic_prefix,
|
|
242
|
+
"actions": self.list_actions(),
|
|
243
|
+
})
|
|
244
|
+
|
|
245
|
+
def _handle_meta_events(
|
|
246
|
+
self, subject: str, data: dict, reply: str | None
|
|
247
|
+
) -> None:
|
|
248
|
+
"""Respond to a ``meta.events`` request with the event catalog."""
|
|
249
|
+
if reply:
|
|
250
|
+
self.reply(reply, {
|
|
251
|
+
"instance_id": self._instance_id,
|
|
252
|
+
"display_name": self._display_name,
|
|
253
|
+
"prefix": self._topic_prefix,
|
|
254
|
+
"events": self.list_events(),
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
def _handle_discover(self, subject: str, data: dict, reply: str | None) -> None:
|
|
258
|
+
"""Respond to ``_lightfall.discover`` with instance identity and actions."""
|
|
259
|
+
if reply:
|
|
260
|
+
self.reply(reply, {
|
|
261
|
+
"instance_id": self._instance_id,
|
|
262
|
+
"display_name": self._display_name,
|
|
263
|
+
"prefix": self._topic_prefix,
|
|
264
|
+
"actions": self.list_actions(),
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
def register_meta_endpoints(self) -> None:
|
|
268
|
+
"""Register ``meta.actions`` and ``meta.events`` discovery endpoints."""
|
|
269
|
+
self.register_action(
|
|
270
|
+
"meta.actions",
|
|
271
|
+
self._handle_meta_actions,
|
|
272
|
+
description="List all registered actions",
|
|
273
|
+
)
|
|
274
|
+
self.register_action(
|
|
275
|
+
"meta.events",
|
|
276
|
+
self._handle_meta_events,
|
|
277
|
+
description="List all registered events",
|
|
278
|
+
)
|
|
279
|
+
# Well-known discovery subject (not prefixed)
|
|
280
|
+
self.subscribe("_lightfall.discover", self._handle_discover, main_thread=False)
|
|
281
|
+
|
|
282
|
+
# -- Trust & auth --
|
|
283
|
+
|
|
284
|
+
def set_trust_manager(self, trust: TrustManager) -> None:
|
|
285
|
+
"""Store the trust manager to use for application trust evaluation."""
|
|
286
|
+
self._trust = trust
|
|
287
|
+
|
|
288
|
+
def evaluate_trust(self, app_name: str) -> TrustState:
|
|
289
|
+
"""Evaluate the trust state for *app_name*.
|
|
290
|
+
|
|
291
|
+
Delegates to the configured :class:`TrustManager`. Returns
|
|
292
|
+
:attr:`TrustState.DENIED` when no trust manager has been set.
|
|
293
|
+
"""
|
|
294
|
+
if self._trust is None:
|
|
295
|
+
return TrustState.DENIED
|
|
296
|
+
return self._trust.check(app_name)
|
|
297
|
+
|
|
298
|
+
def build_auth_response(
|
|
299
|
+
self,
|
|
300
|
+
*,
|
|
301
|
+
approved: bool,
|
|
302
|
+
session=None,
|
|
303
|
+
tiled_url: str = "",
|
|
304
|
+
reason: str = "",
|
|
305
|
+
) -> dict:
|
|
306
|
+
"""Build a response dict for an auth handshake.
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
approved: Whether the connection was approved. When True, the
|
|
310
|
+
cached Tiled API key is read from :class:`SessionManager`
|
|
311
|
+
(auth-v2); ``session`` is still required to gate the
|
|
312
|
+
approved/denied branch.
|
|
313
|
+
session: Session object; used as a presence flag for the
|
|
314
|
+
approved branch. Its ``.token`` attribute is no longer
|
|
315
|
+
read — the credential comes from the API-key cache.
|
|
316
|
+
tiled_url: Tiled server URL to include in an approved response.
|
|
317
|
+
reason: Optional denial reason; only included when non-empty.
|
|
318
|
+
|
|
319
|
+
Returns:
|
|
320
|
+
A plain dict ready to be JSON-serialised and sent over IPC.
|
|
321
|
+
|
|
322
|
+
Note:
|
|
323
|
+
The field name ``"tiled_token"`` is preserved as a public IPC
|
|
324
|
+
contract (see ``docs/ipc-architecture.md`` /
|
|
325
|
+
``docs/ipc-client-guide.md``). Its *value* is now a Tiled API
|
|
326
|
+
key, not a Keycloak bearer token — external clients consume it
|
|
327
|
+
as ``api_key=tiled_token`` when building their Tiled client,
|
|
328
|
+
which is the intended usage. The field rename is deferred to
|
|
329
|
+
the auth cleanup plan, coordinated with IPC client updates.
|
|
330
|
+
"""
|
|
331
|
+
if approved and session is not None:
|
|
332
|
+
from lightfall.auth.session import SessionManager
|
|
333
|
+
|
|
334
|
+
return {
|
|
335
|
+
"status": "approved",
|
|
336
|
+
# Historical name; actually carries an API key under auth-v2.
|
|
337
|
+
"tiled_token": SessionManager.get_instance().get_api_key("tiled"),
|
|
338
|
+
"tiled_url": tiled_url,
|
|
339
|
+
}
|
|
340
|
+
response: dict = {"status": "denied"}
|
|
341
|
+
if reason:
|
|
342
|
+
response["reason"] = reason
|
|
343
|
+
return response
|
|
344
|
+
|
|
345
|
+
# ------------------------------------------------------------------
|
|
346
|
+
# Connection lifecycle
|
|
347
|
+
# ------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
@property
|
|
350
|
+
def is_connected(self) -> bool:
|
|
351
|
+
"""True when the NATS client is connected."""
|
|
352
|
+
with self._connected_lock:
|
|
353
|
+
return self._connected
|
|
354
|
+
|
|
355
|
+
def start(self) -> None:
|
|
356
|
+
"""Connect to NATS on a background thread.
|
|
357
|
+
|
|
358
|
+
Does nothing when ``nats_url`` is empty or already running.
|
|
359
|
+
"""
|
|
360
|
+
if not self._nats_url:
|
|
361
|
+
return
|
|
362
|
+
if self._thread is not None:
|
|
363
|
+
return
|
|
364
|
+
|
|
365
|
+
self._shutdown_event.clear()
|
|
366
|
+
self._loop = asyncio.new_event_loop()
|
|
367
|
+
self._thread = threading.Thread(
|
|
368
|
+
target=self._run_loop,
|
|
369
|
+
daemon=True,
|
|
370
|
+
name="ipc-nats",
|
|
371
|
+
)
|
|
372
|
+
self._thread.start()
|
|
373
|
+
|
|
374
|
+
def stop(self) -> None:
|
|
375
|
+
"""Disconnect from NATS and join the background thread."""
|
|
376
|
+
if self._thread is None:
|
|
377
|
+
return
|
|
378
|
+
|
|
379
|
+
self._shutdown_event.set()
|
|
380
|
+
|
|
381
|
+
if self._loop is not None and self._nc is not None:
|
|
382
|
+
future = asyncio.run_coroutine_threadsafe(
|
|
383
|
+
self._drain_and_close(), self._loop
|
|
384
|
+
)
|
|
385
|
+
try:
|
|
386
|
+
future.result(timeout=5)
|
|
387
|
+
except Exception as exc:
|
|
388
|
+
logger.warning("IPCService: error during drain/close: {}", exc)
|
|
389
|
+
|
|
390
|
+
if self._loop is not None:
|
|
391
|
+
self._loop.call_soon_threadsafe(self._loop.stop)
|
|
392
|
+
|
|
393
|
+
self._thread.join(timeout=5)
|
|
394
|
+
self._thread = None
|
|
395
|
+
self._loop = None
|
|
396
|
+
|
|
397
|
+
# ------------------------------------------------------------------
|
|
398
|
+
# Subscribe / publish / request
|
|
399
|
+
# ------------------------------------------------------------------
|
|
400
|
+
|
|
401
|
+
def subscribe(
|
|
402
|
+
self,
|
|
403
|
+
subject: str,
|
|
404
|
+
callback: Callable[[str, dict, str | None], Any],
|
|
405
|
+
*,
|
|
406
|
+
main_thread: bool = True,
|
|
407
|
+
) -> None:
|
|
408
|
+
"""Register *callback* for messages on *subject*.
|
|
409
|
+
|
|
410
|
+
If the service is already connected the NATS subscription is created
|
|
411
|
+
immediately; otherwise it is deferred until the connection is established.
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
subject: NATS subject to subscribe to.
|
|
415
|
+
callback: Called as ``callback(subject, data, reply)`` where *data*
|
|
416
|
+
is the decoded JSON payload and *reply* is the reply-to subject
|
|
417
|
+
(or ``None``).
|
|
418
|
+
main_thread: If True (default) the callback is dispatched to the Qt
|
|
419
|
+
main thread via ``invoke_in_main_thread``.
|
|
420
|
+
"""
|
|
421
|
+
sub = _Subscription(subject=subject, callback=callback, main_thread=main_thread, nats_sub=None)
|
|
422
|
+
self._subscriptions[subject] = sub
|
|
423
|
+
|
|
424
|
+
if self.is_connected and self._loop is not None and self._nc is not None:
|
|
425
|
+
asyncio.run_coroutine_threadsafe(
|
|
426
|
+
self._create_nats_sub(subject, sub), self._loop
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
def unsubscribe(self, subject: str) -> None:
|
|
430
|
+
"""Remove the subscription for *subject*.
|
|
431
|
+
|
|
432
|
+
Safe to call even when *subject* was never subscribed.
|
|
433
|
+
"""
|
|
434
|
+
sub = self._subscriptions.pop(subject, None)
|
|
435
|
+
if sub is None:
|
|
436
|
+
return
|
|
437
|
+
|
|
438
|
+
if sub.nats_sub is not None and self._loop is not None:
|
|
439
|
+
asyncio.run_coroutine_threadsafe(
|
|
440
|
+
self._drain_sub(sub.nats_sub), self._loop
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
def publish(self, subject: str, data: dict) -> None:
|
|
444
|
+
"""JSON-encode *data* and publish to *subject*.
|
|
445
|
+
|
|
446
|
+
Dropped silently when not connected.
|
|
447
|
+
"""
|
|
448
|
+
if not self.is_connected or self._loop is None or self._nc is None:
|
|
449
|
+
return
|
|
450
|
+
|
|
451
|
+
payload = json.dumps(data).encode()
|
|
452
|
+
asyncio.run_coroutine_threadsafe(
|
|
453
|
+
self._nc.publish(subject, payload), self._loop
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
def request(
|
|
457
|
+
self, subject: str, data: dict, timeout_ms: int = 1000
|
|
458
|
+
) -> dict | None:
|
|
459
|
+
"""Send a request and wait for a reply.
|
|
460
|
+
|
|
461
|
+
Thread-safe — can be called from any thread including the Qt main
|
|
462
|
+
thread. Blocks the *calling* thread for up to *timeout_ms*.
|
|
463
|
+
|
|
464
|
+
Args:
|
|
465
|
+
subject: NATS subject to send the request to.
|
|
466
|
+
data: JSON-serialisable request payload.
|
|
467
|
+
timeout_ms: Maximum time to wait for a reply in milliseconds.
|
|
468
|
+
|
|
469
|
+
Returns:
|
|
470
|
+
Decoded JSON reply dict, or ``None`` on timeout / error /
|
|
471
|
+
not connected.
|
|
472
|
+
"""
|
|
473
|
+
if not self.is_connected or self._loop is None or self._nc is None:
|
|
474
|
+
return None
|
|
475
|
+
|
|
476
|
+
payload = json.dumps(data).encode()
|
|
477
|
+
timeout = timeout_ms / 1000.0
|
|
478
|
+
|
|
479
|
+
future = asyncio.run_coroutine_threadsafe(
|
|
480
|
+
self._do_request(payload, subject, timeout), self._loop
|
|
481
|
+
)
|
|
482
|
+
try:
|
|
483
|
+
result = future.result(timeout=timeout + 1.0)
|
|
484
|
+
return result
|
|
485
|
+
except Exception as exc:
|
|
486
|
+
logger.warning("IPCService: request to '{}' failed: {}", subject, exc)
|
|
487
|
+
return None
|
|
488
|
+
|
|
489
|
+
async def _do_request(
|
|
490
|
+
self, payload: bytes, subject: str, timeout: float
|
|
491
|
+
) -> dict | None:
|
|
492
|
+
"""Async helper — execute NATS request/reply."""
|
|
493
|
+
if self._nc is None:
|
|
494
|
+
return None
|
|
495
|
+
try:
|
|
496
|
+
msg = await self._nc.request(subject, payload, timeout=timeout)
|
|
497
|
+
return json.loads(msg.data.decode())
|
|
498
|
+
except TimeoutError:
|
|
499
|
+
logger.debug("IPCService: request to '{}' timed out", subject)
|
|
500
|
+
return None
|
|
501
|
+
except Exception as exc:
|
|
502
|
+
logger.warning("IPCService: request error on '{}': {}", subject, exc)
|
|
503
|
+
return None
|
|
504
|
+
|
|
505
|
+
def reply(self, reply_subject: str | None, data: dict) -> None:
|
|
506
|
+
"""Send a reply to *reply_subject*.
|
|
507
|
+
|
|
508
|
+
No-op when *reply_subject* is falsy (``None`` or empty string).
|
|
509
|
+
"""
|
|
510
|
+
if not reply_subject:
|
|
511
|
+
return
|
|
512
|
+
self.publish(reply_subject, data)
|
|
513
|
+
|
|
514
|
+
# ------------------------------------------------------------------
|
|
515
|
+
# Internal: event loop runner
|
|
516
|
+
# ------------------------------------------------------------------
|
|
517
|
+
|
|
518
|
+
def _run_loop(self) -> None:
|
|
519
|
+
"""Entry point for the background daemon thread."""
|
|
520
|
+
asyncio.set_event_loop(self._loop)
|
|
521
|
+
try:
|
|
522
|
+
self._loop.run_until_complete(self._connect_and_serve())
|
|
523
|
+
except Exception as exc:
|
|
524
|
+
logger.error("IPCService: event loop exited with error: {}", exc)
|
|
525
|
+
finally:
|
|
526
|
+
try:
|
|
527
|
+
self._loop.close()
|
|
528
|
+
except Exception:
|
|
529
|
+
pass
|
|
530
|
+
|
|
531
|
+
async def _connect_and_serve(self) -> None:
|
|
532
|
+
"""Open NATS connection, re-subscribe, then wait for shutdown."""
|
|
533
|
+
try:
|
|
534
|
+
tls_ctx = ssl.create_default_context()
|
|
535
|
+
self._nc = await nats.connect(
|
|
536
|
+
self._nats_url,
|
|
537
|
+
tls=tls_ctx,
|
|
538
|
+
error_cb=self._error_cb,
|
|
539
|
+
disconnected_cb=self._disconnected_cb,
|
|
540
|
+
reconnected_cb=self._reconnected_cb,
|
|
541
|
+
)
|
|
542
|
+
except Exception as exc:
|
|
543
|
+
logger.error("IPCService: failed to connect to NATS at {}: {}", self._nats_url, exc)
|
|
544
|
+
return
|
|
545
|
+
|
|
546
|
+
with self._connected_lock:
|
|
547
|
+
self._connected = True
|
|
548
|
+
invoke_in_main_thread(self.sigConnectionChanged.emit, True)
|
|
549
|
+
logger.info("IPCService: connected to NATS at {}", self._nats_url)
|
|
550
|
+
|
|
551
|
+
# Re-create any subscriptions that were registered before connect
|
|
552
|
+
for subject, sub in list(self._subscriptions.items()):
|
|
553
|
+
await self._create_nats_sub(subject, sub)
|
|
554
|
+
|
|
555
|
+
# Wait until stop() signals shutdown
|
|
556
|
+
while not self._shutdown_event.is_set():
|
|
557
|
+
await asyncio.sleep(0.1)
|
|
558
|
+
|
|
559
|
+
async def _drain_and_close(self) -> None:
|
|
560
|
+
"""Drain pending messages and close the NATS connection."""
|
|
561
|
+
if self._nc is None:
|
|
562
|
+
return
|
|
563
|
+
try:
|
|
564
|
+
await self._nc.drain()
|
|
565
|
+
except Exception as exc:
|
|
566
|
+
logger.debug("IPCService: drain error (may be normal during shutdown): {}", exc)
|
|
567
|
+
with self._connected_lock:
|
|
568
|
+
was_connected = self._connected
|
|
569
|
+
self._connected = False
|
|
570
|
+
if was_connected:
|
|
571
|
+
invoke_in_main_thread(self.sigConnectionChanged.emit, False)
|
|
572
|
+
|
|
573
|
+
async def _create_nats_sub(self, subject: str, sub: _Subscription) -> None:
|
|
574
|
+
"""Create a NATS subscription and store the handle in *sub*."""
|
|
575
|
+
if self._nc is None:
|
|
576
|
+
return
|
|
577
|
+
handler = self._make_handler(sub)
|
|
578
|
+
try:
|
|
579
|
+
nats_sub = await self._nc.subscribe(subject, cb=handler)
|
|
580
|
+
sub.nats_sub = nats_sub
|
|
581
|
+
except Exception as exc:
|
|
582
|
+
logger.error("IPCService: failed to subscribe to {}: {}", subject, exc)
|
|
583
|
+
|
|
584
|
+
@staticmethod
|
|
585
|
+
async def _drain_sub(nats_sub: Any) -> None:
|
|
586
|
+
"""Drain a single NATS subscription."""
|
|
587
|
+
try:
|
|
588
|
+
await nats_sub.drain()
|
|
589
|
+
except Exception as exc:
|
|
590
|
+
logger.debug("IPCService: error draining sub: {}", exc)
|
|
591
|
+
|
|
592
|
+
# ------------------------------------------------------------------
|
|
593
|
+
# Internal: message handler factory
|
|
594
|
+
# ------------------------------------------------------------------
|
|
595
|
+
|
|
596
|
+
def _make_handler(self, sub: _Subscription) -> Callable:
|
|
597
|
+
"""Return an async NATS message handler for *sub*."""
|
|
598
|
+
subject = sub.subject
|
|
599
|
+
|
|
600
|
+
async def handler(msg: Any) -> None:
|
|
601
|
+
reply: str = msg.reply if msg.reply else ""
|
|
602
|
+
|
|
603
|
+
# Decode JSON payload
|
|
604
|
+
try:
|
|
605
|
+
data = json.loads(msg.data.decode())
|
|
606
|
+
except Exception as exc:
|
|
607
|
+
logger.warning(
|
|
608
|
+
"IPCService: malformed JSON on subject '{}': {}", subject, exc
|
|
609
|
+
)
|
|
610
|
+
if reply:
|
|
611
|
+
error_payload = json.dumps({"error": "malformed JSON"}).encode()
|
|
612
|
+
try:
|
|
613
|
+
await self._nc.publish(reply, error_payload)
|
|
614
|
+
except Exception:
|
|
615
|
+
pass
|
|
616
|
+
return
|
|
617
|
+
|
|
618
|
+
try:
|
|
619
|
+
if sub.main_thread:
|
|
620
|
+
invoke_in_main_thread(sub.callback, subject, data, reply)
|
|
621
|
+
else:
|
|
622
|
+
sub.callback(subject, data, reply)
|
|
623
|
+
except Exception as exc:
|
|
624
|
+
logger.error(
|
|
625
|
+
"IPCService: unhandled exception in callback for '{}': {}",
|
|
626
|
+
subject,
|
|
627
|
+
exc,
|
|
628
|
+
)
|
|
629
|
+
logger.exception(exc)
|
|
630
|
+
if reply:
|
|
631
|
+
error_payload = json.dumps({"error": str(exc)}).encode()
|
|
632
|
+
if self._loop is not None and self._nc is not None:
|
|
633
|
+
asyncio.run_coroutine_threadsafe(
|
|
634
|
+
self._nc.publish(reply, error_payload),
|
|
635
|
+
self._loop,
|
|
636
|
+
)
|
|
637
|
+
|
|
638
|
+
return handler
|
|
639
|
+
|
|
640
|
+
# ------------------------------------------------------------------
|
|
641
|
+
# Internal: NATS callbacks
|
|
642
|
+
# ------------------------------------------------------------------
|
|
643
|
+
|
|
644
|
+
async def _error_cb(self, exc: Exception) -> None:
|
|
645
|
+
# str(exc) is often empty for nats errors (StaleConnection, SlowConsumer, ...)
|
|
646
|
+
msg = str(exc) or type(exc).__name__
|
|
647
|
+
# Connectivity errors fire on every reconnect attempt while the broker
|
|
648
|
+
# is unreachable. Log the first one, then stay silent until we
|
|
649
|
+
# reconnect (cleared in _reconnected_cb).
|
|
650
|
+
if isinstance(
|
|
651
|
+
exc,
|
|
652
|
+
(
|
|
653
|
+
nats.errors.NoServersError,
|
|
654
|
+
nats.errors.ConnectionClosedError,
|
|
655
|
+
nats.errors.StaleConnectionError,
|
|
656
|
+
TimeoutError,
|
|
657
|
+
),
|
|
658
|
+
):
|
|
659
|
+
if self._connectivity_error_logged:
|
|
660
|
+
return
|
|
661
|
+
self._connectivity_error_logged = True
|
|
662
|
+
logger.warning(
|
|
663
|
+
"IPCService: NATS {} (further reconnect errors suppressed until reconnect)",
|
|
664
|
+
msg,
|
|
665
|
+
)
|
|
666
|
+
elif isinstance(exc, nats.errors.SlowConsumerError):
|
|
667
|
+
logger.warning("IPCService: NATS {}", msg)
|
|
668
|
+
else:
|
|
669
|
+
logger.error(
|
|
670
|
+
"IPCService: NATS error: {} ({})", msg, type(exc).__name__
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
async def _disconnected_cb(self) -> None:
|
|
674
|
+
logger.warning("IPCService: disconnected from NATS")
|
|
675
|
+
with self._connected_lock:
|
|
676
|
+
self._connected = False
|
|
677
|
+
invoke_in_main_thread(self.sigConnectionChanged.emit, False)
|
|
678
|
+
|
|
679
|
+
async def _reconnected_cb(self) -> None:
|
|
680
|
+
logger.info("IPCService: reconnected to NATS")
|
|
681
|
+
with self._connected_lock:
|
|
682
|
+
self._connected = True
|
|
683
|
+
self._connectivity_error_logged = False
|
|
684
|
+
invoke_in_main_thread(self.sigConnectionChanged.emit, True)
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
# ---------------------------------------------------------------------------
|
|
688
|
+
# Module-level convenience accessor
|
|
689
|
+
# ---------------------------------------------------------------------------
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def get_ipc_service() -> IPCService | None:
|
|
693
|
+
"""Return the application's IPCService instance, or None if unavailable.
|
|
694
|
+
|
|
695
|
+
Uses the :class:`~lightfall.core.services.ServiceRegistry` singleton to look
|
|
696
|
+
up the registered :class:`IPCService`.
|
|
697
|
+
"""
|
|
698
|
+
from lightfall.core.services import ServiceRegistry
|
|
699
|
+
|
|
700
|
+
registry = ServiceRegistry.get_instance()
|
|
701
|
+
return registry.get(IPCService, None)
|