Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 75 additions & 5 deletions google/cloud/managed_spark_connect/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,73 @@ def _status_line_html(
return f"<div>{_LINK_SEPARATOR.join(parts)}</div>"


def _colab_enterprise_button_html(
label: str, url: str, icon: str = "open_in_new"
) -> str:
"""Colab Enterprise resource button HTML (matching Vertex AI's display_link).

Rendered inline rather than via google.cloud.aiplatform.utils._ipython_utils
because importing google.cloud.aiplatform initializes the full Vertex AI SDK
(~3s on session connect).
"""
button_id = f"view-vertex-resource-{uuid.uuid4()}"
safe_label = html_lib.escape(label)
safe_icon = html_lib.escape(icon)
safe_url_js = json.dumps(url).replace("</", r"<\/")
return f"""
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
.view-vertex-resource,
.view-vertex-resource:hover,
.view-vertex-resource:visited {{
position: relative;
display: inline-flex;
flex-direction: row;
height: 32px;
padding: 0 12px;
margin: 4px 18px;
gap: 4px;
border-radius: 4px;
align-items: center;
justify-content: center;
background-color: rgb(255, 255, 255);
color: rgb(51, 103, 214);
font-family: Roboto,"Helvetica Neue",sans-serif;
font-size: 13px;
font-weight: 500;
text-transform: uppercase;
text-decoration: none !important;
transition: box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1) 0s;
box-shadow: 0px 3px 1px -2px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 1px 5px 0px rgba(0,0,0,0.12);
}}
.view-vertex-resource:active {{
box-shadow: 0px 5px 5px -3px rgba(0,0,0,0.2),0px 8px 10px 1px rgba(0,0,0,0.14),0px 3px 14px 2px rgba(0,0,0,0.12);
}}
.view-vertex-icon {{
font-size: 18px;
}}
</style>
<a class="view-vertex-resource" id="{button_id}" href="#view-{button_id}">
<span class="material-icons view-vertex-icon">{safe_icon}</span>
<span>{safe_label}</span>
</a>
<script>
(function () {{
const link = document.getElementById('{button_id}');
link.addEventListener('click', (e) => {{
if (window.google?.colab?.openUrl) {{
window.google.colab.openUrl({safe_url_js});
}} else {{
window.open({safe_url_js}, '_blank');
}}
e.stopPropagation();
e.preventDefault();
}});
}})();
</script>
"""


def _versions_text(spark_version: Optional[str]) -> str:
"""E.g. "(Spark 4.0.2)", or empty when unknown."""
return f"(Spark {spark_version})" if spark_version else ""
Expand Down Expand Up @@ -1870,16 +1937,19 @@ def _display_view_session_details_button(self, session_id):
return

try:
session_url = f"{_MANAGED_SPARK_SESSIONS_BASE_URL}/{self._region}/{session_id}?project={self._project_id}"
from IPython.core.interactiveshell import InteractiveShell
from IPython.display import HTML, display

if not InteractiveShell.initialized():
return

from google.cloud.aiplatform.utils import _ipython_utils

_ipython_utils.display_link(
"View Session Details", f"{session_url}", "dashboard"
session_url = f"{_MANAGED_SPARK_SESSIONS_BASE_URL}/{self._region}/{session_id}?project={self._project_id}"
display(
HTML(
_colab_enterprise_button_html(
_SESSION_LINK_LABEL, session_url, "dashboard"
)
)
)
except ImportError as e:
logger.debug(f"Import error: {e}")
Expand Down
93 changes: 37 additions & 56 deletions tests/unit/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,16 +153,10 @@ def _setup_session_creation_mocks(
"IPython.core.interactiveshell.InteractiveShell.initialized",
return_value=True,
)
@mock.patch.dict(
"sys.modules",
{
"google.cloud.aiplatform.utils": mock.MagicMock(
_ipython_utils=mock.MagicMock()
),
},
)
@mock.patch("IPython.display.display")
def test_create_spark_session_with_default_notebook_behavior(
self,
mock_display,
mock_interactive_shell,
mock_get_client_environment_label,
mock_is_s8s_session_active,
Expand Down Expand Up @@ -196,11 +190,7 @@ def test_create_spark_session_with_default_notebook_behavior(
mock_operation
)
mock_get_client_environment_label.return_value = "unknown"
mock_ipython_utils = mock.sys.modules[
"google.cloud.aiplatform.utils"
]._ipython_utils
test_session_url = f"{_MANAGED_SPARK_SESSIONS_BASE_URL}/test-region/{session_id}?project=test-project"
mock_display_link = mock_ipython_utils.display_link
mock.patch.dict(
os.environ,
{
Expand Down Expand Up @@ -247,8 +237,14 @@ def test_create_spark_session_with_default_notebook_behavior(
mock_session_controller_client_instance.get_session.assert_called_once_with(
get_session_request
)
mock_display_link.assert_called_once_with(
"View Session Details", test_session_url, "dashboard"
displayed_html = "\n".join(
call.args[0].data for call in mock_display.call_args_list
)
self.assertIn("View Session Details", displayed_html)
self.assertIn("dashboard", displayed_html)
self.assertIn(
f'window.google.colab.openUrl("{test_session_url}")',
displayed_html,
)

@mock.patch("google.cloud.dataproc_v1.SessionControllerClient")
Expand Down Expand Up @@ -1677,15 +1673,16 @@ def test_create_session_with_default_datasource_env_var(
mock_session_controller_client_instance.create_session.reset_mock()
mock_logger.warning.reset_mock()

@mock.patch.dict("sys.modules", {"google.cloud.aiplatform": None})
@mock.patch(
"IPython.core.interactiveshell.InteractiveShell.initialized",
return_value=True,
@mock.patch.dict(
"sys.modules",
{
"IPython": None,
"IPython.core": None,
"IPython.core.interactiveshell": None,
},
)
@mock.patch("google.cloud.managed_spark_connect.session.logger")
def test_display_button_with_aiplatform_not_installed(
self, mock_logger, _mock_ipy
):
def test_display_button_with_ipython_not_installed(self, mock_logger):
mock.patch.dict(
os.environ,
{
Expand All @@ -1695,74 +1692,58 @@ def test_display_button_with_aiplatform_not_installed(
ManagedSparkSession.builder._display_view_session_details_button(
"test_session"
)
mock_logger.debug.assert_called_once_with(
"Import error: No module named 'google.cloud.aiplatform.utils'; 'google.cloud.aiplatform' is not a package"
)
mock_logger.debug.assert_called_once()
self.assertIn("Import error:", mock_logger.debug.call_args[0][0])

@mock.patch.dict(
"sys.modules",
{
"google.cloud.aiplatform.utils": mock.MagicMock(
_ipython_utils=mock.MagicMock()
),
},
)
@mock.patch.dict("sys.modules", {"google.cloud.aiplatform": None})
@mock.patch(
"IPython.core.interactiveshell.InteractiveShell.initialized",
return_value=True,
)
def test_display_button_with_aiplatform_installed_ipython_interactive(
self, _mock_ipy
@mock.patch("IPython.display.display")
def test_display_button_without_aiplatform_ipython_interactive(
self, mock_display, _mock_ipy
):
mock.patch.dict(
os.environ,
{
"VERTEX_PRODUCT": "COLAB_ENTERPRISE",
},
).start()
mock_ipython_utils = mock.sys.modules[
"google.cloud.aiplatform.utils"
]._ipython_utils
test_session_url = f"{_MANAGED_SPARK_SESSIONS_BASE_URL}/test-region/test_session?project=test-project"

mock_display_link = mock_ipython_utils.display_link
ManagedSparkSession.builder._display_view_session_details_button(
"test_session"
)
mock_display_link.assert_called_once_with(
"View Session Details", test_session_url, "dashboard"
mock_display.assert_called_once()
html_output = mock_display.call_args[0][0].data
self.assertIn(
'<span class="material-icons view-vertex-icon">dashboard</span>',
html_output,
)
self.assertIn("<span>View Session Details</span>", html_output)
self.assertIn(
f'window.google.colab.openUrl("{test_session_url}")', html_output
)

@mock.patch.dict(
"sys.modules",
{
"google.cloud.aiplatform.utils": mock.MagicMock(
_ipython_utils=mock.MagicMock()
),
},
)
@mock.patch(
"IPython.core.interactiveshell.InteractiveShell.initialized",
return_value=False,
)
def test_display_button_with_aiplatform_installed_ipython_non_interactive(
self, _mock_ipy
@mock.patch("IPython.display.display")
def test_display_button_ipython_non_interactive(
self, mock_display, _mock_ipy
):
mock.patch.dict(
os.environ,
{
"VERTEX_PRODUCT": "COLAB_ENTERPRISE",
},
).start()
mock_ipython_utils = mock.sys.modules[
"google.cloud.aiplatform.utils"
]._ipython_utils

mock_display_link = mock_ipython_utils.display_link
ManagedSparkSession.builder._display_view_session_details_button(
"test_session"
)
mock_display_link.assert_not_called()
mock_display.assert_not_called()

@mock.patch(
"IPython.core.interactiveshell.InteractiveShell.initialized",
Expand Down
Loading