v0.148.0
 1from __future__ import annotations
 2
 3from typing import Any
 4
 5from plain.runtime import settings
 6from plain.toolbar import ToolbarItem, register_toolbar_item
 7
 8from .tracing import current_trace
 9
10
11@register_toolbar_item
12class ConnectToolbarItem(ToolbarItem):
13    """Links the current request to its exported trace in Plain Cloud.
14
15    This module is only imported when plain.toolbar is installed (it is
16    autodiscovered by the toolbar package), so the `plain.toolbar` import
17    above is safe without a guard. The item is a button-only toolbar entry —
18    no panel — that points at the `/t/<trace_id>` short URL on the dashboard,
19    which resolves the trace back to its app and redirects.
20    """
21
22    name = "Connect"
23    button_template_name = "toolbar/connect_button.html"
24
25    def is_enabled(self) -> bool:
26        """Only show the item when connect is actively exporting."""
27        return bool(settings.CONNECT_EXPORT_ENABLED and settings.CONNECT_EXPORT_TOKEN)
28
29    def get_template_context(self) -> dict[str, Any]:
30        context = super().get_template_context()
31
32        trace = current_trace()
33        context["sampled"] = trace.sampled
34        if trace.sampled:
35            cloud_url = str(settings.CONNECT_CLOUD_URL).rstrip("/")
36            context["trace_url"] = f"{cloud_url}/t/{trace.trace_id}"
37        else:
38            context["trace_url"] = ""
39
40        return context