deephaven-plugin-alerts 0.1.0__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.
@@ -0,0 +1,129 @@
1
+ """Alerts and watch rules for ticking Deephaven tables.
2
+
3
+ Define conditions on live tables and get notified when rows start matching them:
4
+ toasts in the UI, webhooks (Slack, Teams), logs or Python callbacks. Every alert is
5
+ also recorded in a ticking history table.
6
+
7
+ Example:
8
+
9
+ .. code-block:: python
10
+
11
+ from deephaven import alerts
12
+
13
+ alerts.rule(
14
+ positions, "abs(PnL) > 1e6", by="Account", cooldown="5m", severity="critical"
15
+ )
16
+ alerts_panel = alerts.panel()
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from datetime import timedelta
22
+ from typing import Any, Callable, Sequence
23
+
24
+ from deephaven.table import Table
25
+
26
+ from ._engine import (
27
+ AlertManager,
28
+ AlertRule,
29
+ default_manager,
30
+ parse_duration,
31
+ )
32
+ from ._notifiers import Alert, Callback, Log, Notifier, NotifyTarget, Webhook
33
+ from ._components import literal, panel, toaster, watch
34
+
35
+
36
+ def rule(
37
+ table: Table,
38
+ condition: str,
39
+ name: str | None = None,
40
+ by: str | Sequence[str] | None = None,
41
+ cooldown: float | int | timedelta | str | None = "1m",
42
+ hold: float | int | timedelta | str | None = None,
43
+ reset: str | None = None,
44
+ severity: str = "warning",
45
+ message: str | Callable[[dict[str, Any]], str] | None = None,
46
+ notify: NotifyTarget | Sequence[NotifyTarget] | None = ("toast",),
47
+ fire_on_start: bool = False,
48
+ ) -> AlertRule:
49
+ """Alert when rows of a table start matching a condition.
50
+
51
+ Rules are edge-triggered: a row (or ``by`` key) fires when it enters the condition,
52
+ not on every tick while the condition keeps holding.
53
+
54
+ Args:
55
+ table: The table to watch. Usually ticking.
56
+ condition: A Deephaven filter expression, for example ``"abs(PnL) > 1e6"``.
57
+ name: The rule name. Defaults to the condition. Adding a rule with an existing
58
+ name replaces it.
59
+ by: Key column(s). Cooldown, hold and reset are tracked per key.
60
+ cooldown: Minimum time between alerts for the same key. Accepts seconds,
61
+ ``timedelta``, ``"30s"``/``"5m"``/``"1h"`` or ISO-8601 (``"PT5M"``).
62
+ hold: Only fire if the key still matches after this long (debounce).
63
+ reset: Hysteresis. After firing, a key only re-arms once a row matching this
64
+ filter is seen, for example ``"abs(PnL) < 5e5"``.
65
+ severity: ``"info"``, ``"warning"`` or ``"critical"``.
66
+ message: A template such as ``"{Sym} at {Price}"`` (any column, plus ``{rule}``,
67
+ ``{key}`` and ``{condition}``), or a function of the row values.
68
+ notify: ``"toast"``, ``"log"``, a :class:`Webhook`, a :class:`Notifier`, a
69
+ function taking an :class:`Alert`, or a list of these.
70
+ fire_on_start: Whether rows that already match when the rule is created fire.
71
+
72
+ Returns:
73
+ The rule.
74
+ """
75
+ return default_manager().add_rule(
76
+ table,
77
+ condition,
78
+ name=name,
79
+ by=by,
80
+ cooldown=cooldown,
81
+ hold=hold,
82
+ reset=reset,
83
+ severity=severity,
84
+ message=message,
85
+ notify=notify,
86
+ fire_on_start=fire_on_start,
87
+ )
88
+
89
+
90
+ def remove(name: str) -> bool:
91
+ """Remove a rule from the shared manager."""
92
+ return default_manager().remove(name)
93
+
94
+
95
+ def rules() -> Table:
96
+ """The shared manager's rules, with fired counts."""
97
+ return default_manager().rules_table
98
+
99
+
100
+ def history() -> Table:
101
+ """The shared manager's recent alerts."""
102
+ return default_manager().history
103
+
104
+
105
+ def events() -> Table:
106
+ """A blink table of alerts from the shared manager, as they fire."""
107
+ return default_manager().events
108
+
109
+
110
+ __all__ = [
111
+ "Alert",
112
+ "AlertManager",
113
+ "AlertRule",
114
+ "Callback",
115
+ "Log",
116
+ "Notifier",
117
+ "Webhook",
118
+ "default_manager",
119
+ "events",
120
+ "history",
121
+ "literal",
122
+ "panel",
123
+ "parse_duration",
124
+ "remove",
125
+ "rule",
126
+ "rules",
127
+ "toaster",
128
+ "watch",
129
+ ]
@@ -0,0 +1,265 @@
1
+ """deephaven.ui components for alerts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Sequence
6
+
7
+ from deephaven import ui
8
+ from deephaven.ui.types import ToastVariant
9
+ from deephaven.table import Table
10
+
11
+ from ._engine import AlertManager, default_manager
12
+ from ._notifiers import NotifyTarget
13
+
14
+ TOAST_VARIANTS: Dict[str, ToastVariant] = {
15
+ "info": "info",
16
+ "warning": "neutral",
17
+ "critical": "negative",
18
+ }
19
+ TOAST_TIMEOUT_MS = 8000
20
+ MAX_TOASTS_PER_UPDATE = 3
21
+
22
+
23
+ def _cell_value(data: dict[str, Any], column: str) -> Any:
24
+ # always_fetch_columns maps column name -> cell info ({"value", "text", ...}).
25
+ cell = (data.get("always_fetch_columns") or {}).get(column)
26
+ return cell.get("value") if isinstance(cell, dict) else cell
27
+
28
+
29
+ def literal(value: Any) -> str | None:
30
+ """Return a Deephaven query-language literal for a value, or None if unsupported."""
31
+ if isinstance(value, bool):
32
+ return "true" if value else "false"
33
+ if isinstance(value, int):
34
+ return str(value)
35
+ if isinstance(value, float):
36
+ return repr(value) if value == value and abs(value) != float("inf") else None
37
+ if isinstance(value, str) and "`" not in value:
38
+ return f"`{value}`"
39
+ return None
40
+
41
+
42
+ @ui.component
43
+ def toaster(manager: AlertManager | None = None) -> None:
44
+ """Show a toast for each alert sent to the ``"toast"`` channel.
45
+
46
+ Renders nothing. Include it in any component or dashboard to get alert toasts there.
47
+
48
+ Args:
49
+ manager: The alert manager to listen to. Defaults to the shared manager.
50
+ """
51
+ mgr = manager if manager is not None else default_manager()
52
+ render_queue = ui.use_render_queue()
53
+
54
+ def on_update(update: Any, is_replay: bool) -> None:
55
+ if is_replay:
56
+ return
57
+ added = update.added(["Severity", "Message", "Notify"])
58
+ toasts = [
59
+ (str(message), str(severity))
60
+ for message, severity, notify in zip(
61
+ added["Message"], added["Severity"], added["Notify"]
62
+ )
63
+ if "toast" in str(notify or "").split(",")
64
+ ]
65
+ if not toasts:
66
+ return
67
+ shown, extra = (
68
+ toasts[:MAX_TOASTS_PER_UPDATE],
69
+ len(toasts) - MAX_TOASTS_PER_UPDATE,
70
+ )
71
+
72
+ def show() -> None:
73
+ for message, severity in shown:
74
+ ui.toast(
75
+ message,
76
+ variant=TOAST_VARIANTS.get(severity, "neutral"),
77
+ timeout=TOAST_TIMEOUT_MS,
78
+ )
79
+ if extra > 0:
80
+ ui.toast(
81
+ f"+{extra} more alerts", variant="info", timeout=TOAST_TIMEOUT_MS
82
+ )
83
+
84
+ render_queue(show)
85
+
86
+ ui.use_table_listener(mgr.events, on_update, [mgr])
87
+ return None
88
+
89
+
90
+ SEVERITY_FORMATS = [
91
+ ui.TableFormat(
92
+ cols="Severity", if_="Severity == `critical`", background_color="red-600"
93
+ ),
94
+ ui.TableFormat(
95
+ cols="Severity", if_="Severity == `warning`", background_color="orange-600"
96
+ ),
97
+ ui.TableFormat(
98
+ cols="Severity", if_="Severity == `info`", background_color="blue-600"
99
+ ),
100
+ ]
101
+
102
+
103
+ @ui.component
104
+ def panel(manager: AlertManager | None = None, toasts: bool = True) -> ui.Element:
105
+ """A live view of alert rules and fired alerts.
106
+
107
+ Right-click a rule to enable, disable or remove it, or to send a test alert.
108
+
109
+ Args:
110
+ manager: The alert manager to show. Defaults to the shared manager.
111
+ toasts: Whether to show toasts for new alerts.
112
+
113
+ Returns:
114
+ The panel element.
115
+ """
116
+ mgr = manager if manager is not None else default_manager()
117
+ history = ui.use_memo(lambda: mgr.history.reverse(), [mgr])
118
+
119
+ def rules_menu(data: Any) -> Any:
120
+ if data.get("is_column_header"):
121
+ return None
122
+ name = _cell_value(data, "Rule")
123
+ rule = mgr.rules.get(name) if name else None
124
+ if rule is None:
125
+ return None
126
+
127
+ def send_test(_: Any) -> None:
128
+ mgr.test(name)
129
+
130
+ return [
131
+ {
132
+ "title": "Disable rule" if rule.enabled else "Enable rule",
133
+ "icon": "vsBellSlash" if rule.enabled else "vsBell",
134
+ "action": lambda _: mgr.set_enabled(name, not rule.enabled),
135
+ },
136
+ {"title": "Send test alert", "icon": "vsBellDot", "action": send_test},
137
+ {
138
+ "title": "Remove rule",
139
+ "icon": "vsTrash",
140
+ "action": lambda _: mgr.remove(name) and None,
141
+ },
142
+ ]
143
+
144
+ return ui.flex(
145
+ toaster(mgr) if toasts else None,
146
+ ui.heading("Rules", level=4, margin=0, flex="none"),
147
+ ui.view(
148
+ ui.table(
149
+ mgr.rules_table,
150
+ context_menu=rules_menu,
151
+ always_fetch_columns=["Rule"],
152
+ format_=[
153
+ *SEVERITY_FORMATS,
154
+ ui.TableFormat(if_="!Enabled", color="gray-500"),
155
+ ],
156
+ ),
157
+ flex=1,
158
+ min_height=0,
159
+ ),
160
+ ui.heading("Alerts", level=4, margin=0, flex="none"),
161
+ ui.view(
162
+ ui.table(history, format_=SEVERITY_FORMATS, hidden_columns=["Notify"]),
163
+ flex=2,
164
+ min_height=0,
165
+ ),
166
+ direction="column",
167
+ gap="size-100",
168
+ height="100%",
169
+ )
170
+
171
+
172
+ @ui.component
173
+ def watch(
174
+ table: Table,
175
+ by: str | Sequence[str] | None = None,
176
+ manager: AlertManager | None = None,
177
+ cooldown: float | str | None = "1m",
178
+ severity: str = "warning",
179
+ notify: NotifyTarget | Sequence[NotifyTarget] | None = ("toast",),
180
+ toasts: bool = True,
181
+ ) -> ui.Element:
182
+ """Display a table whose context menu creates alert rules from a cell.
183
+
184
+ Right-click a cell and choose *Create alert* to alert when the column crosses the
185
+ clicked value, for every row or (with ``by``) for the clicked row only.
186
+
187
+ Args:
188
+ table: The table to watch.
189
+ by: Key column(s). Alerts fire per key, and *this row only* rules are offered.
190
+ manager: The alert manager to add rules to. Defaults to the shared manager.
191
+ cooldown: Cooldown for created rules.
192
+ severity: Severity for created rules.
193
+ notify: Channels for created rules.
194
+ toasts: Whether to show toasts for new alerts.
195
+
196
+ Returns:
197
+ The table element.
198
+ """
199
+ mgr = manager if manager is not None else default_manager()
200
+ by_cols = [by] if isinstance(by, str) else list(by or [])
201
+
202
+ def create(condition: str, name: str | None = None) -> None:
203
+ try:
204
+ rule = mgr.add_rule(
205
+ table,
206
+ condition,
207
+ name=name,
208
+ by=by_cols or None,
209
+ cooldown=cooldown,
210
+ severity=severity,
211
+ notify=notify,
212
+ )
213
+ except Exception as e: # noqa: BLE001 - surface failures to the user
214
+ ui.toast(f"Could not create alert: {e}", variant="negative", timeout=5000)
215
+ return
216
+ ui.toast(f"Alert created: {rule.name}", variant="positive", timeout=5000)
217
+
218
+ def menu(data: Any) -> Any:
219
+ if data.get("is_column_header") or data.get("is_row_header"):
220
+ return None
221
+ column = data.get("column_name")
222
+ value = data.get("value")
223
+ value_literal = literal(value)
224
+ if not column or value_literal is None:
225
+ return None
226
+ numeric = isinstance(value, (int, float)) and not isinstance(value, bool)
227
+ ops = [">", "<", ">=", "<="] if numeric else ["==", "!="]
228
+ text = data.get("text") or str(value)
229
+
230
+ row_parts = []
231
+ for col in by_cols:
232
+ key_literal = literal(_cell_value(data, col))
233
+ if key_literal is None:
234
+ row_parts = []
235
+ break
236
+ row_parts.append(f"{col} == {key_literal}")
237
+ row_condition = " && ".join(row_parts)
238
+ row_label = ", ".join(str(_cell_value(data, c)) for c in by_cols)
239
+
240
+ actions = []
241
+ for op in ops:
242
+ condition = f"{column} {op} {value_literal}"
243
+ actions.append(
244
+ {
245
+ "title": f"When {column} {op} {text}",
246
+ "action": lambda _d, c=condition: create(c),
247
+ }
248
+ )
249
+ if row_condition:
250
+ actions.append(
251
+ {
252
+ "title": f"When {column} {op} {text} ({row_label} only)",
253
+ "action": lambda _d, c=condition: create(
254
+ f"{row_condition} && {c}", f"{row_label}: {c}"
255
+ ),
256
+ }
257
+ )
258
+ return {"title": "Create alert", "icon": "vsBell", "actions": actions}
259
+
260
+ return ui.flex(
261
+ toaster(mgr) if toasts else None,
262
+ ui.table(table, context_menu=menu, always_fetch_columns=by_cols or None),
263
+ direction="column",
264
+ height="100%",
265
+ )