diff --git a/src/nipanel/_streamlit_constants.py b/src/nipanel/_streamlit_constants.py index f1350c11..2cd9601e 100644 --- a/src/nipanel/_streamlit_constants.py +++ b/src/nipanel/_streamlit_constants.py @@ -1,2 +1 @@ STREAMLIT_PYTHON_PANEL_SERVICE = "ni.pythonpanel.v1.PythonPanelService" -STREAMLIT_REFRESH_COMPONENT_URL = "http://localhost:42001/panel-service/refresh" diff --git a/src/nipanel/streamlit_refresh/__init__.py b/src/nipanel/streamlit_refresh/__init__.py index ec9f1c5a..72c35ac0 100644 --- a/src/nipanel/streamlit_refresh/__init__.py +++ b/src/nipanel/streamlit_refresh/__init__.py @@ -1,17 +1,41 @@ """Initializes a refresh component for Streamlit.""" -from typing import Any +from __future__ import annotations -import streamlit.components.v1 as components +import threading -from nipanel._streamlit_constants import STREAMLIT_REFRESH_COMPONENT_URL +from ni_measurement_plugin_sdk_service.discovery import DiscoveryClient +from ni_measurement_plugin_sdk_service.grpc.channelpool import GrpcChannelPool +from streamlit.components.v1 import declare_component +from streamlit.components.v1.custom_component import CustomComponent -def initialize_refresh_component(panel_id: str) -> Any: +_grpc_client_lock = threading.RLock() +_panel_service_proxy_location: str | None = None + + +def initialize_refresh_component(panel_id: str) -> CustomComponent: """Initialize a refresh component to the Streamlit app.""" - _refresh_component_func = components.declare_component( + proxy_base_address = _get_or_resolve_proxy() + component_url = f"http://{proxy_base_address}/panel-service/refresh/{panel_id}" + _refresh_component_func = declare_component( "panelRefreshComponent", - url=f"{STREAMLIT_REFRESH_COMPONENT_URL}/{panel_id}", + url=component_url, ) return _refresh_component_func + + +def _get_or_resolve_proxy() -> str: + with _grpc_client_lock: + global _panel_service_proxy_location + if _panel_service_proxy_location is None: + with GrpcChannelPool() as grpc_channel_pool: + discovery_client = DiscoveryClient(grpc_channel_pool=grpc_channel_pool) + service_location = discovery_client.resolve_service( + provided_interface="ni.http1.proxy", + service_class="", + ) + _panel_service_proxy_location = service_location.insecure_address + + return _panel_service_proxy_location