agent2dashboard 0.2.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.
- agent2dashboard/__init__.py +593 -0
- agent2dashboard/__main__.py +3 -0
- agent2dashboard/_env.py +79 -0
- agent2dashboard/a2ui/__init__.py +1 -0
- agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
- agent2dashboard/a2ui/checks.py +656 -0
- agent2dashboard/a2ui/express.py +349 -0
- agent2dashboard/a2ui/layout_actions.py +409 -0
- agent2dashboard/a2ui/render.py +252 -0
- agent2dashboard/a2ui/state.py +600 -0
- agent2dashboard/a2ui/surfaces.py +23 -0
- agent2dashboard/agent/__init__.py +83 -0
- agent2dashboard/agent/builtin_tools.py +258 -0
- agent2dashboard/agent/history.py +218 -0
- agent2dashboard/agent/loop.py +341 -0
- agent2dashboard/agent/prompt.py +66 -0
- agent2dashboard/agent/tools.py +162 -0
- agent2dashboard/agent/turn.py +201 -0
- agent2dashboard/auth.py +350 -0
- agent2dashboard/cli/__init__.py +50 -0
- agent2dashboard/errors.py +18 -0
- agent2dashboard/http/__init__.py +40 -0
- agent2dashboard/http/dashboards.py +100 -0
- agent2dashboard/http/functions.py +462 -0
- agent2dashboard/http/queries.py +168 -0
- agent2dashboard/http/revisions.py +126 -0
- agent2dashboard/http/router.py +353 -0
- agent2dashboard/http/schemas.py +102 -0
- agent2dashboard/llm/__init__.py +7 -0
- agent2dashboard/llm/_messages_api.py +123 -0
- agent2dashboard/llm/bedrock.py +96 -0
- agent2dashboard/llm/direct.py +40 -0
- agent2dashboard/llm/messages.py +45 -0
- agent2dashboard/migrations/__init__.py +383 -0
- agent2dashboard/migrations/versions/0001_initial.py +228 -0
- agent2dashboard/ports.py +538 -0
- agent2dashboard/py.typed +0 -0
- agent2dashboard/query/__init__.py +65 -0
- agent2dashboard/query/errors.py +39 -0
- agent2dashboard/query/executor.py +203 -0
- agent2dashboard/query/filters.py +446 -0
- agent2dashboard/query/governed.py +155 -0
- agent2dashboard/query/readonly.py +166 -0
- agent2dashboard/query/registry.py +213 -0
- agent2dashboard/query/row_filter.py +135 -0
- agent2dashboard/query/service.py +93 -0
- agent2dashboard/query/sql_guard.py +219 -0
- agent2dashboard/runs/__init__.py +87 -0
- agent2dashboard/runs/errors.py +65 -0
- agent2dashboard/runs/events.py +147 -0
- agent2dashboard/runs/hooks.py +135 -0
- agent2dashboard/runs/http.py +169 -0
- agent2dashboard/runs/memory.py +148 -0
- agent2dashboard/runs/redis_bus.py +219 -0
- agent2dashboard/runs/service.py +728 -0
- agent2dashboard/runs/writer.py +95 -0
- agent2dashboard/semantic/__init__.py +6 -0
- agent2dashboard/semantic/cube.py +39 -0
- agent2dashboard/semantic/static.py +81 -0
- agent2dashboard/storage/__init__.py +60 -0
- agent2dashboard/storage/lifecycle.py +105 -0
- agent2dashboard/storage/memory.py +488 -0
- agent2dashboard/storage/records.py +219 -0
- agent2dashboard/storage/sql.py +666 -0
- agent2dashboard/storage/tables.py +387 -0
- agent2dashboard/testing/__init__.py +20 -0
- agent2dashboard/testing/event_bus.py +10 -0
- agent2dashboard/testing/fake_llm.py +129 -0
- agent2dashboard/testing/host.py +191 -0
- agent2dashboard/tracing/__init__.py +36 -0
- agent2dashboard/tracing/db.py +143 -0
- agent2dashboard/tracing/fanout.py +153 -0
- agent2dashboard/tracing/langfuse.py +339 -0
- agent2dashboard/tracing/masking.py +26 -0
- agent2dashboard-0.2.0.dist-info/METADATA +81 -0
- agent2dashboard-0.2.0.dist-info/RECORD +79 -0
- agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
- agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
- agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
"""Our check layer over a compiled dashboard surface (design §1.10 decision 4, §7).
|
|
2
|
+
|
|
3
|
+
The A2UI SDK validates the catalog schema, ids, cycles, the root and references. It does not
|
|
4
|
+
know what a `queryId` is or which columns a query returns, so these checks do, modelled on
|
|
5
|
+
XoraOps' `check_spec` (`backend/src/pages/service.py`) and at least as strict:
|
|
6
|
+
|
|
7
|
+
- every data widget's `data` is `runQuery("<queryId>", $/filters)` on a registered query, and
|
|
8
|
+
`runQuery` / `filterOptions` appear nowhere else;
|
|
9
|
+
- every field a component names (`x`, `series[].key`, `value`, `label`, `change`, `status`,
|
|
10
|
+
`trend`, a column `goal`, table `columns[].key`) is a result column of that query, of the
|
|
11
|
+
right kind;
|
|
12
|
+
- no `format` prop: the renderer shows values exactly as the query returns them (§10 #14), so
|
|
13
|
+
the value-changing formats (`percent` multiplied by 100) were removed; display options
|
|
14
|
+
(`decimals`, `prefix`, `suffix`, `currency`, `grouping`) never change a value;
|
|
15
|
+
- layout: at most 4 levels of layout containers, every data widget written in this call
|
|
16
|
+
reachable from `root`, `DashboardGrid` items inside 12 columns without overlapping;
|
|
17
|
+
- filters: pickers bind `$/filters/<key>` for keys the queries declare, every picker is used,
|
|
18
|
+
every dimension a query reads has a picker, and defaults fit;
|
|
19
|
+
- limits: at most 12 data widgets, 4 series per chart and 5 pie slices. The renderer draws a
|
|
20
|
+
pie's rows as returned and never groups them, so the SQL must group the rest into `Other`.
|
|
21
|
+
|
|
22
|
+
Every problem is reported, not only the first, so the model can fix them in one retry. The
|
|
23
|
+
checks are pure functions of the surface document (`{"components": [...], "dataModel": {...}}`)
|
|
24
|
+
and the query registry; the pie slice count is the one fact that needs a query run, and the
|
|
25
|
+
caller passes it in.
|
|
26
|
+
|
|
27
|
+
Writing data outside `/filters` and `/ui`, touching another surface and deleting the surface
|
|
28
|
+
are refused earlier by `express.ExpressProcessor`.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
from collections.abc import Iterable, Iterator, Mapping, Sequence
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from functools import cache
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from agent2dashboard.a2ui.express import load_catalog_json
|
|
39
|
+
from agent2dashboard.query.filters import TIME_FILTER_KEY, TimeRangePreset
|
|
40
|
+
from agent2dashboard.query.registry import QueryRegistry, RegisteredQuery
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"DATA_WIDGETS",
|
|
44
|
+
"GRID_COLUMNS",
|
|
45
|
+
"LAYOUT_CONTAINERS",
|
|
46
|
+
"MAX_LAYOUT_DEPTH",
|
|
47
|
+
"MAX_PIE_SLICES",
|
|
48
|
+
"MAX_SERIES",
|
|
49
|
+
"MAX_WIDGETS",
|
|
50
|
+
"CheckProblem",
|
|
51
|
+
"check_surface",
|
|
52
|
+
"child_ids",
|
|
53
|
+
"compact_components",
|
|
54
|
+
"fill_grid",
|
|
55
|
+
"grid_problems",
|
|
56
|
+
"pie_queries",
|
|
57
|
+
"reachable",
|
|
58
|
+
"walk",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
MAX_WIDGETS = 12
|
|
62
|
+
MAX_SERIES = 4
|
|
63
|
+
MAX_PIE_SLICES = 5
|
|
64
|
+
MAX_LAYOUT_DEPTH = 4
|
|
65
|
+
GRID_COLUMNS = 12
|
|
66
|
+
|
|
67
|
+
DATA_WIDGETS = frozenset({"KpiCard", "BarChart", "LineChart", "AreaChart", "PieChart", "DataTable"})
|
|
68
|
+
LAYOUT_CONTAINERS = frozenset({"Row", "Column", "Card", "Tabs", "DashboardGrid"})
|
|
69
|
+
ROOT_ID = "root"
|
|
70
|
+
ROOT_COMPONENT = "Dashboard"
|
|
71
|
+
FILTERS_PATH = "/filters"
|
|
72
|
+
_CHARTS = frozenset({"BarChart", "LineChart", "AreaChart"})
|
|
73
|
+
_NUMERIC_DISPLAY = ("decimals", "currency")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class CheckProblem:
|
|
78
|
+
"""One reason a surface was refused, worded for the model to fix it."""
|
|
79
|
+
|
|
80
|
+
code: str
|
|
81
|
+
message: str
|
|
82
|
+
component_id: str | None = None
|
|
83
|
+
|
|
84
|
+
def for_model(self) -> str:
|
|
85
|
+
at = f" {self.component_id}:" if self.component_id else ""
|
|
86
|
+
return f"[{self.code}]{at} {self.message}"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --- component tree -------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@cache
|
|
93
|
+
def _child_props() -> dict[str, tuple[tuple[str, str], ...]]:
|
|
94
|
+
"""Per component: the props that hold children, as (prop, shape) where shape is `one`
|
|
95
|
+
(an id), `list` (a ChildList: ids or a template) or `items` (objects with a `child`)."""
|
|
96
|
+
catalog = load_catalog_json()
|
|
97
|
+
shapes: dict[str, tuple[tuple[str, str], ...]] = {}
|
|
98
|
+
for name, schema in catalog["components"].items():
|
|
99
|
+
found: list[tuple[str, str]] = []
|
|
100
|
+
for prop, spec in (schema.get("properties") or {}).items():
|
|
101
|
+
ref = str(spec.get("$ref", ""))
|
|
102
|
+
if ref.endswith("/Child"):
|
|
103
|
+
found.append((prop, "one"))
|
|
104
|
+
elif ref.endswith("/ChildList"):
|
|
105
|
+
found.append((prop, "list"))
|
|
106
|
+
elif spec.get("type") == "array":
|
|
107
|
+
item_props = (spec.get("items") or {}).get("properties") or {}
|
|
108
|
+
if str(item_props.get("child", {}).get("$ref", "")).endswith("/Child"):
|
|
109
|
+
found.append((prop, "items"))
|
|
110
|
+
shapes[name] = tuple(found)
|
|
111
|
+
return shapes
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def child_ids(component: Mapping[str, Any]) -> list[str]:
|
|
115
|
+
"""The ids a component references as children, in order."""
|
|
116
|
+
ids: list[str] = []
|
|
117
|
+
for prop, shape in _child_props().get(str(component.get("component")), ()):
|
|
118
|
+
value = component.get(prop)
|
|
119
|
+
if shape == "one" and isinstance(value, str):
|
|
120
|
+
ids.append(value)
|
|
121
|
+
elif shape == "list":
|
|
122
|
+
if isinstance(value, list):
|
|
123
|
+
ids.extend(v for v in value if isinstance(v, str))
|
|
124
|
+
elif isinstance(value, Mapping) and isinstance(value.get("componentId"), str):
|
|
125
|
+
ids.append(value["componentId"])
|
|
126
|
+
elif shape == "items" and isinstance(value, list):
|
|
127
|
+
ids.extend(
|
|
128
|
+
item["child"]
|
|
129
|
+
for item in value
|
|
130
|
+
if isinstance(item, Mapping) and isinstance(item.get("child"), str)
|
|
131
|
+
)
|
|
132
|
+
return ids
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def walk(
|
|
136
|
+
components: Mapping[str, Mapping[str, Any]], root: str = ROOT_ID
|
|
137
|
+
) -> Iterator[tuple[str, int, int]]:
|
|
138
|
+
"""Depth-first from `root`: (id, depth in the tree, layout containers above it). Each id
|
|
139
|
+
once; missing ids are skipped (the SDK refuses dangling references)."""
|
|
140
|
+
seen: set[str] = set()
|
|
141
|
+
stack: list[tuple[str, int, int]] = [(root, 0, 0)]
|
|
142
|
+
while stack:
|
|
143
|
+
cid, depth, layout = stack.pop()
|
|
144
|
+
component = components.get(cid)
|
|
145
|
+
if cid in seen or component is None:
|
|
146
|
+
continue
|
|
147
|
+
seen.add(cid)
|
|
148
|
+
yield cid, depth, layout
|
|
149
|
+
inner = layout + (1 if component.get("component") in LAYOUT_CONTAINERS else 0)
|
|
150
|
+
stack.extend((c, depth + 1, inner) for c in reversed(child_ids(component)))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def reachable(components: Mapping[str, Mapping[str, Any]], root: str = ROOT_ID) -> list[str]:
|
|
154
|
+
return [cid for cid, _, _ in walk(components, root)]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def compact_components(components: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
|
158
|
+
"""The components reachable from `root`, in tree order: what the stored surface keeps.
|
|
159
|
+
Components an update left without a parent are the ones the model removed."""
|
|
160
|
+
by_id = {str(c["id"]): dict(c) for c in components}
|
|
161
|
+
return [by_id[cid] for cid in reachable(by_id)]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# --- DashboardGrid --------------------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _overlaps(a: Mapping[str, int], b: Mapping[str, int]) -> bool:
|
|
168
|
+
return (
|
|
169
|
+
a["x"] < b["x"] + b["w"]
|
|
170
|
+
and b["x"] < a["x"] + a["w"]
|
|
171
|
+
and a["y"] < b["y"] + b["h"]
|
|
172
|
+
and b["y"] < a["y"] + a["h"]
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _placed(item: Mapping[str, Any]) -> bool:
|
|
177
|
+
return isinstance(item.get("x"), int) and isinstance(item.get("y"), int)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def grid_problems(component_id: str, items: Sequence[Mapping[str, Any]]) -> list[CheckProblem]:
|
|
181
|
+
"""Items must sit inside 12 columns, not overlap, and name each child once."""
|
|
182
|
+
problems: list[CheckProblem] = []
|
|
183
|
+
children = [item.get("child") for item in items]
|
|
184
|
+
for child in sorted({c for c in children if children.count(c) > 1}, key=str):
|
|
185
|
+
problems.append(
|
|
186
|
+
CheckProblem("GRID_DUPLICATE", f"{child} is placed more than once.", component_id)
|
|
187
|
+
)
|
|
188
|
+
boxes = [item for item in items if _placed(item)]
|
|
189
|
+
for item in boxes:
|
|
190
|
+
if item["x"] + int(item.get("w", 1)) > GRID_COLUMNS:
|
|
191
|
+
problems.append(
|
|
192
|
+
CheckProblem(
|
|
193
|
+
"GRID_TOO_WIDE",
|
|
194
|
+
f"{item.get('child')} spans columns {item['x']}..{item['x'] + item['w'] - 1}; "
|
|
195
|
+
f"x + w must be at most {GRID_COLUMNS}.",
|
|
196
|
+
component_id,
|
|
197
|
+
)
|
|
198
|
+
)
|
|
199
|
+
for index, a in enumerate(boxes):
|
|
200
|
+
for b in boxes[index + 1 :]:
|
|
201
|
+
if _overlaps(a, b):
|
|
202
|
+
problems.append(
|
|
203
|
+
CheckProblem(
|
|
204
|
+
"GRID_OVERLAP",
|
|
205
|
+
f"{a.get('child')} and {b.get('child')} overlap; move one with x/y or "
|
|
206
|
+
"leave x and y out to flow it into free space.",
|
|
207
|
+
component_id,
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
return problems
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def fill_grid(items: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
|
214
|
+
"""Items with `x` and `y` filled in: placed items stay; each other item, in order, takes
|
|
215
|
+
the first free spot scanning rows top to bottom and columns left to right (§1.10 *Layout*:
|
|
216
|
+
the server fills the coordinates before storing the surface)."""
|
|
217
|
+
out = [dict(item) for item in items]
|
|
218
|
+
taken = [
|
|
219
|
+
{"x": i["x"], "y": i["y"], "w": int(i["w"]), "h": int(i["h"])} for i in out if _placed(i)
|
|
220
|
+
]
|
|
221
|
+
for item in out:
|
|
222
|
+
if _placed(item):
|
|
223
|
+
continue
|
|
224
|
+
w = min(max(int(item.get("w", GRID_COLUMNS)), 1), GRID_COLUMNS)
|
|
225
|
+
h = max(int(item.get("h", 1)), 1)
|
|
226
|
+
y = 0
|
|
227
|
+
while True:
|
|
228
|
+
spot = next(
|
|
229
|
+
(
|
|
230
|
+
{"x": x, "y": y, "w": w, "h": h}
|
|
231
|
+
for x in range(GRID_COLUMNS - w + 1)
|
|
232
|
+
if not any(_overlaps({"x": x, "y": y, "w": w, "h": h}, t) for t in taken)
|
|
233
|
+
),
|
|
234
|
+
None,
|
|
235
|
+
)
|
|
236
|
+
if spot is not None:
|
|
237
|
+
break
|
|
238
|
+
y += 1
|
|
239
|
+
item["x"], item["y"] = spot["x"], spot["y"]
|
|
240
|
+
taken.append(spot)
|
|
241
|
+
return out
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# --- data bindings --------------------------------------------------------------------------
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _call(value: Any, name: str) -> Mapping[str, Any] | None:
|
|
248
|
+
if isinstance(value, Mapping) and value.get("@call") == name:
|
|
249
|
+
args = value.get("args")
|
|
250
|
+
return args if isinstance(args, Mapping) else {}
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _calls_in(value: Any, path: str = "") -> Iterator[tuple[str, str]]:
|
|
255
|
+
"""Every (function name, prop path) of a function call inside a prop value."""
|
|
256
|
+
if isinstance(value, Mapping):
|
|
257
|
+
if isinstance(value.get("@call"), str):
|
|
258
|
+
yield value["@call"], path
|
|
259
|
+
for key, inner in value.items():
|
|
260
|
+
yield from _calls_in(inner, f"{path}.{key}" if path else str(key))
|
|
261
|
+
elif isinstance(value, list):
|
|
262
|
+
for index, inner in enumerate(value):
|
|
263
|
+
yield from _calls_in(inner, f"{path}[{index}]")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _query_of(component: Mapping[str, Any]) -> str | None:
|
|
267
|
+
args = _call(component.get("data"), "runQuery")
|
|
268
|
+
query_id = args.get("queryId") if args is not None else None
|
|
269
|
+
return query_id if isinstance(query_id, str) else None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def pie_queries(components: Iterable[Mapping[str, Any]]) -> dict[str, str]:
|
|
273
|
+
"""PieChart id -> its queryId, for the caller to count the slices."""
|
|
274
|
+
out: dict[str, str] = {}
|
|
275
|
+
for component in components:
|
|
276
|
+
query_id = _query_of(component)
|
|
277
|
+
if component.get("component") == "PieChart" and query_id:
|
|
278
|
+
out[str(component["id"])] = query_id
|
|
279
|
+
return out
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _filters_arg(args: Mapping[str, Any]) -> tuple[bool, bool]:
|
|
283
|
+
"""(passes the dashboard filters, the filters arg is acceptable)."""
|
|
284
|
+
if "filters" not in args:
|
|
285
|
+
return False, True
|
|
286
|
+
value = args["filters"]
|
|
287
|
+
ok = isinstance(value, Mapping) and value.get("@path") == FILTERS_PATH and len(value) == 1
|
|
288
|
+
return ok, ok
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _columns_text(query: RegisteredQuery) -> str:
|
|
292
|
+
return ", ".join(f"{c.name} ({c.kind})" for c in query.columns) or "no columns"
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _field_problems(cid: str, component: Mapping[str, Any], query: RegisteredQuery) -> list[str]:
|
|
296
|
+
"""Field props against the query's result columns: (name, needed kind or None)."""
|
|
297
|
+
kind = component.get("component")
|
|
298
|
+
fields: list[tuple[str, str, str | None]] = [] # (prop label, column, needed kind)
|
|
299
|
+
|
|
300
|
+
def add(label: str, value: Any, needed: str | None) -> None:
|
|
301
|
+
if isinstance(value, str):
|
|
302
|
+
fields.append((label, value, needed))
|
|
303
|
+
|
|
304
|
+
if kind == "KpiCard":
|
|
305
|
+
add("value", component.get("value"), "number")
|
|
306
|
+
add("change", component.get("change"), "number")
|
|
307
|
+
add("status", component.get("status"), "text")
|
|
308
|
+
add("trend", component.get("trend"), None)
|
|
309
|
+
add("goal", component.get("goal"), "number") # a column; a literal number is fine
|
|
310
|
+
elif kind in _CHARTS:
|
|
311
|
+
add("x", component.get("x"), None)
|
|
312
|
+
for index, series in enumerate(component.get("series") or []):
|
|
313
|
+
if isinstance(series, Mapping):
|
|
314
|
+
add(f"series[{index}].key", series.get("key"), "number")
|
|
315
|
+
elif kind == "PieChart":
|
|
316
|
+
add("label", component.get("label"), None)
|
|
317
|
+
add("value", component.get("value"), "number")
|
|
318
|
+
elif kind == "DataTable":
|
|
319
|
+
for index, column in enumerate(component.get("columns") or []):
|
|
320
|
+
if not isinstance(column, Mapping):
|
|
321
|
+
continue
|
|
322
|
+
numeric = any(column.get(option) is not None for option in _NUMERIC_DISPLAY)
|
|
323
|
+
add(f"columns[{index}].key", column.get("key"), "number" if numeric else None)
|
|
324
|
+
|
|
325
|
+
problems: list[str] = []
|
|
326
|
+
for label, name, needed in fields:
|
|
327
|
+
column = query.column(name)
|
|
328
|
+
if column is None:
|
|
329
|
+
problems.append(
|
|
330
|
+
f"{label} names column `{name}`, which {query.query_id} does not return. "
|
|
331
|
+
f"It returns: {_columns_text(query)}."
|
|
332
|
+
)
|
|
333
|
+
elif needed is not None and column.kind != needed:
|
|
334
|
+
problems.append(
|
|
335
|
+
f"{label} `{name}` is a {column.kind} column; it must be a {needed} column. "
|
|
336
|
+
f"{query.query_id} returns: {_columns_text(query)}."
|
|
337
|
+
)
|
|
338
|
+
return problems
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _removed_formats(component: Mapping[str, Any]) -> list[str]:
|
|
342
|
+
"""Where a widget still uses the removed `format` prop (the SDK refuses it too; this
|
|
343
|
+
keeps the reason readable, e.g. when an older revision is restored)."""
|
|
344
|
+
found = ["the widget's"] if "format" in component else []
|
|
345
|
+
if component.get("component") == "DataTable":
|
|
346
|
+
for index, column in enumerate(component.get("columns") or []):
|
|
347
|
+
if isinstance(column, Mapping) and "format" in column:
|
|
348
|
+
found.append(f"columns[{index}]")
|
|
349
|
+
return found
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
# --- the checks -----------------------------------------------------------------------------
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def check_surface(
|
|
356
|
+
surface: Mapping[str, Any],
|
|
357
|
+
registry: QueryRegistry,
|
|
358
|
+
*,
|
|
359
|
+
changed: Iterable[str] = (),
|
|
360
|
+
pie_slices: Mapping[str, int] | None = None,
|
|
361
|
+
) -> list[CheckProblem]:
|
|
362
|
+
"""Every problem with a candidate surface document.
|
|
363
|
+
|
|
364
|
+
`changed` are the component ids this call wrote: those must be placed in the layout
|
|
365
|
+
(an unplaced data widget is a mistake; an older one left without a parent was removed on
|
|
366
|
+
purpose). `pie_slices` maps a queryId to the rows it returns at the dashboard's default
|
|
367
|
+
filters (more than 5 means too many slices).
|
|
368
|
+
"""
|
|
369
|
+
components: dict[str, dict[str, Any]] = {
|
|
370
|
+
str(c["id"]): dict(c) for c in surface.get("components") or [] if "id" in c
|
|
371
|
+
}
|
|
372
|
+
data_model = surface.get("dataModel") or {}
|
|
373
|
+
problems: list[CheckProblem] = []
|
|
374
|
+
add = problems.append
|
|
375
|
+
|
|
376
|
+
root = components.get(ROOT_ID)
|
|
377
|
+
if root is None or root.get("component") != ROOT_COMPONENT:
|
|
378
|
+
add(CheckProblem("ROOT", f"`root` must be a {ROOT_COMPONENT}.", ROOT_ID))
|
|
379
|
+
|
|
380
|
+
tree = list(walk(components))
|
|
381
|
+
on_screen = {cid for cid, _, _ in tree}
|
|
382
|
+
|
|
383
|
+
# Layout: placement and nesting.
|
|
384
|
+
for cid in changed:
|
|
385
|
+
component = components.get(cid)
|
|
386
|
+
if component is None or cid in on_screen:
|
|
387
|
+
continue
|
|
388
|
+
if component.get("component") in DATA_WIDGETS:
|
|
389
|
+
add(
|
|
390
|
+
CheckProblem(
|
|
391
|
+
"UNPLACED",
|
|
392
|
+
"this widget is not reachable from root; put it in a Row, Column, Card, "
|
|
393
|
+
"Tabs or DashboardGrid under the Dashboard's body.",
|
|
394
|
+
cid,
|
|
395
|
+
)
|
|
396
|
+
)
|
|
397
|
+
for cid, _, layout in tree:
|
|
398
|
+
if layout > MAX_LAYOUT_DEPTH:
|
|
399
|
+
add(
|
|
400
|
+
CheckProblem(
|
|
401
|
+
"TOO_DEEP",
|
|
402
|
+
f"it sits inside {layout} layout containers; at most {MAX_LAYOUT_DEPTH} "
|
|
403
|
+
"levels of Row, Column, Card, Tabs and DashboardGrid are allowed. Flatten "
|
|
404
|
+
"the layout.",
|
|
405
|
+
cid,
|
|
406
|
+
)
|
|
407
|
+
)
|
|
408
|
+
break # one report is enough; the rest are below the same container
|
|
409
|
+
|
|
410
|
+
widgets = [cid for cid in on_screen if components[cid].get("component") in DATA_WIDGETS]
|
|
411
|
+
if len(widgets) > MAX_WIDGETS:
|
|
412
|
+
add(
|
|
413
|
+
CheckProblem(
|
|
414
|
+
"TOO_MANY_WIDGETS",
|
|
415
|
+
f"the dashboard has {len(widgets)} data widgets; at most {MAX_WIDGETS}.",
|
|
416
|
+
)
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
# Data bindings and fields, per component on screen.
|
|
420
|
+
picker_keys: dict[str, str] = {} # filter key -> picker id
|
|
421
|
+
used_keys: set[str] = set() # filter keys read by widgets that pass $/filters
|
|
422
|
+
dimension_keys: dict[str, set[str]] = {} # key -> widgets whose query reads it
|
|
423
|
+
declared_dimensions: set[str] = set()
|
|
424
|
+
for cid, _, _ in tree:
|
|
425
|
+
component = components[cid]
|
|
426
|
+
kind = component.get("component")
|
|
427
|
+
for name, path in _calls_in({k: v for k, v in component.items() if k != "id"}):
|
|
428
|
+
allowed = (name == "runQuery" and kind in DATA_WIDGETS and path == "data") or (
|
|
429
|
+
name == "filterOptions" and kind == "FilterSelect" and path == "options"
|
|
430
|
+
)
|
|
431
|
+
if name in ("runQuery", "filterOptions") and not allowed:
|
|
432
|
+
where = (
|
|
433
|
+
"a data widget's `data`" if name == "runQuery" else "a FilterSelect's `options`"
|
|
434
|
+
)
|
|
435
|
+
add(CheckProblem("MISPLACED_CALL", f"{name} is only allowed as {where}.", cid))
|
|
436
|
+
|
|
437
|
+
if kind in DATA_WIDGETS:
|
|
438
|
+
args = _call(component.get("data"), "runQuery")
|
|
439
|
+
if args is None:
|
|
440
|
+
add(
|
|
441
|
+
CheckProblem(
|
|
442
|
+
"DATA_NOT_QUERY",
|
|
443
|
+
'data must be runQuery("<queryId>", $/filters) on a query registered '
|
|
444
|
+
"with define_query; never write rows or bind another path.",
|
|
445
|
+
cid,
|
|
446
|
+
)
|
|
447
|
+
)
|
|
448
|
+
continue
|
|
449
|
+
query_id = args.get("queryId")
|
|
450
|
+
query = registry.get(query_id) if isinstance(query_id, str) else None
|
|
451
|
+
if query is None:
|
|
452
|
+
known = ", ".join(q.query_id for q in registry) or "none yet"
|
|
453
|
+
add(
|
|
454
|
+
CheckProblem(
|
|
455
|
+
"UNKNOWN_QUERY",
|
|
456
|
+
f"queryId {query_id!r} is not registered. Register it with define_query "
|
|
457
|
+
f"first. Registered: {known}.",
|
|
458
|
+
cid,
|
|
459
|
+
)
|
|
460
|
+
)
|
|
461
|
+
continue
|
|
462
|
+
passes_filters, filters_ok = _filters_arg(args)
|
|
463
|
+
if not filters_ok:
|
|
464
|
+
add(
|
|
465
|
+
CheckProblem(
|
|
466
|
+
"BAD_FILTERS_ARG",
|
|
467
|
+
"runQuery's second argument must be exactly $/filters.",
|
|
468
|
+
cid,
|
|
469
|
+
)
|
|
470
|
+
)
|
|
471
|
+
elif query.filters_used and not passes_filters:
|
|
472
|
+
add(
|
|
473
|
+
CheckProblem(
|
|
474
|
+
"FILTERS_NOT_PASSED",
|
|
475
|
+
f"{query.query_id} reads the filters {', '.join(query.filters_used)}; "
|
|
476
|
+
f'write runQuery("{query.query_id}", $/filters).',
|
|
477
|
+
cid,
|
|
478
|
+
)
|
|
479
|
+
)
|
|
480
|
+
if passes_filters:
|
|
481
|
+
used_keys.update(query.filters_used)
|
|
482
|
+
for key in query.filters_used:
|
|
483
|
+
if key != TIME_FILTER_KEY:
|
|
484
|
+
dimension_keys.setdefault(key, set()).add(cid)
|
|
485
|
+
declared_dimensions.update(d.key for d in query.dimensions)
|
|
486
|
+
for where in _removed_formats(component):
|
|
487
|
+
add(
|
|
488
|
+
CheckProblem(
|
|
489
|
+
"REMOVED_FORMAT",
|
|
490
|
+
f"{where} `format` was removed: the dashboard shows values exactly as "
|
|
491
|
+
"the query returns them. Return the final display value from SQL (a "
|
|
492
|
+
"percentage as ROUND(100.0 * x / NULLIF(y, 0), 1) AS x_pct) and use "
|
|
493
|
+
'decimals, prefix, suffix (e.g. suffix="%"), currency or grouping.',
|
|
494
|
+
cid,
|
|
495
|
+
)
|
|
496
|
+
)
|
|
497
|
+
for message in _field_problems(cid, component, query):
|
|
498
|
+
add(CheckProblem("FIELD", message, cid))
|
|
499
|
+
|
|
500
|
+
series = component.get("series")
|
|
501
|
+
if kind in _CHARTS and isinstance(series, list) and len(series) > MAX_SERIES:
|
|
502
|
+
add(
|
|
503
|
+
CheckProblem(
|
|
504
|
+
"TOO_MANY_SERIES",
|
|
505
|
+
f"{len(series)} series; a chart shows at most {MAX_SERIES}.",
|
|
506
|
+
cid,
|
|
507
|
+
)
|
|
508
|
+
)
|
|
509
|
+
if kind == "PieChart" and pie_slices is not None:
|
|
510
|
+
slices = pie_slices.get(query.query_id)
|
|
511
|
+
if slices is not None and slices > MAX_PIE_SLICES:
|
|
512
|
+
add(
|
|
513
|
+
CheckProblem(
|
|
514
|
+
"TOO_MANY_SLICES",
|
|
515
|
+
f"{query.query_id} returns more than {MAX_PIE_SLICES} rows; a "
|
|
516
|
+
f"pie shows at most {MAX_PIE_SLICES} slices, one per row, and the "
|
|
517
|
+
"dashboard never "
|
|
518
|
+
f"groups rows itself. Return at most {MAX_PIE_SLICES} rows: group "
|
|
519
|
+
"the rest into an 'Other' row in SQL, or use a BarChart.",
|
|
520
|
+
cid,
|
|
521
|
+
)
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
elif kind == "DashboardGrid":
|
|
525
|
+
items = [i for i in component.get("items") or [] if isinstance(i, Mapping)]
|
|
526
|
+
problems.extend(grid_problems(cid, items))
|
|
527
|
+
|
|
528
|
+
elif kind in ("PeriodPicker", "FilterSelect"):
|
|
529
|
+
value = component.get("value")
|
|
530
|
+
path = value.get("@path") if isinstance(value, Mapping) else None
|
|
531
|
+
key = (
|
|
532
|
+
path.removeprefix(FILTERS_PATH + "/")
|
|
533
|
+
if isinstance(path, str) and path.startswith(FILTERS_PATH + "/")
|
|
534
|
+
else None
|
|
535
|
+
)
|
|
536
|
+
if key is None or "/" in key or not key:
|
|
537
|
+
add(
|
|
538
|
+
CheckProblem(
|
|
539
|
+
"PICKER_BINDING",
|
|
540
|
+
"a picker's value must be bound to $/filters/<key>.",
|
|
541
|
+
cid,
|
|
542
|
+
)
|
|
543
|
+
)
|
|
544
|
+
continue
|
|
545
|
+
if kind == "PeriodPicker" and key != TIME_FILTER_KEY:
|
|
546
|
+
add(
|
|
547
|
+
CheckProblem(
|
|
548
|
+
"PICKER_BINDING",
|
|
549
|
+
f"a PeriodPicker binds $/filters/{TIME_FILTER_KEY}, not $/filters/{key}.",
|
|
550
|
+
cid,
|
|
551
|
+
)
|
|
552
|
+
)
|
|
553
|
+
continue
|
|
554
|
+
if kind == "FilterSelect":
|
|
555
|
+
if key == TIME_FILTER_KEY:
|
|
556
|
+
add(
|
|
557
|
+
CheckProblem(
|
|
558
|
+
"PICKER_BINDING",
|
|
559
|
+
f"$/filters/{TIME_FILTER_KEY} is the period; use a PeriodPicker.",
|
|
560
|
+
cid,
|
|
561
|
+
)
|
|
562
|
+
)
|
|
563
|
+
continue
|
|
564
|
+
options = _call(component.get("options"), "filterOptions")
|
|
565
|
+
if options is None or options.get("key") != key:
|
|
566
|
+
add(
|
|
567
|
+
CheckProblem(
|
|
568
|
+
"PICKER_OPTIONS",
|
|
569
|
+
f'options must be filterOptions("{key}"), the key it binds.',
|
|
570
|
+
cid,
|
|
571
|
+
)
|
|
572
|
+
)
|
|
573
|
+
if key in picker_keys:
|
|
574
|
+
add(
|
|
575
|
+
CheckProblem(
|
|
576
|
+
"DUPLICATE_PICKER",
|
|
577
|
+
f"$/filters/{key} already has a picker ({picker_keys[key]}).",
|
|
578
|
+
cid,
|
|
579
|
+
)
|
|
580
|
+
)
|
|
581
|
+
continue
|
|
582
|
+
picker_keys[key] = cid
|
|
583
|
+
|
|
584
|
+
# Filters: every picker is read, every dimension read has a picker, defaults fit.
|
|
585
|
+
for key, cid in picker_keys.items():
|
|
586
|
+
if key != TIME_FILTER_KEY and key not in declared_dimensions:
|
|
587
|
+
add(
|
|
588
|
+
CheckProblem(
|
|
589
|
+
"UNKNOWN_FILTER",
|
|
590
|
+
f"no query on the dashboard declares the filter `{key}`; declare it in "
|
|
591
|
+
"define_query's `filters` and read it as {{filter." + key + "}}.",
|
|
592
|
+
cid,
|
|
593
|
+
)
|
|
594
|
+
)
|
|
595
|
+
elif key not in used_keys:
|
|
596
|
+
what = (
|
|
597
|
+
"{{time_from}} / {{time_to}}"
|
|
598
|
+
if key == TIME_FILTER_KEY
|
|
599
|
+
else "{{filter." + key + "}}"
|
|
600
|
+
)
|
|
601
|
+
add(
|
|
602
|
+
CheckProblem(
|
|
603
|
+
"UNUSED_FILTER",
|
|
604
|
+
f"no widget's query reads $/filters/{key} ({what}) with $/filters passed "
|
|
605
|
+
"to runQuery; drop the picker or use the filter.",
|
|
606
|
+
cid,
|
|
607
|
+
)
|
|
608
|
+
)
|
|
609
|
+
for key, users in sorted(dimension_keys.items()):
|
|
610
|
+
if key not in picker_keys:
|
|
611
|
+
add(
|
|
612
|
+
CheckProblem(
|
|
613
|
+
"MISSING_PICKER",
|
|
614
|
+
f"{', '.join(sorted(users))} read the filter `{key}` but the dashboard has "
|
|
615
|
+
"no picker for it; add FilterSelect(..., "
|
|
616
|
+
f'$/filters/{key}, filterOptions("{key}")) to the FilterBar.',
|
|
617
|
+
)
|
|
618
|
+
)
|
|
619
|
+
defaults = data_model.get("filters") if isinstance(data_model, Mapping) else None
|
|
620
|
+
if isinstance(defaults, Mapping):
|
|
621
|
+
for key, value in defaults.items():
|
|
622
|
+
if key not in picker_keys:
|
|
623
|
+
add(
|
|
624
|
+
CheckProblem(
|
|
625
|
+
"UNKNOWN_FILTER",
|
|
626
|
+
f"$/filters/{key} has a default but no picker binds it.",
|
|
627
|
+
)
|
|
628
|
+
)
|
|
629
|
+
elif key == TIME_FILTER_KEY and not _is_default_period(value):
|
|
630
|
+
presets = ", ".join(p.value for p in TimeRangePreset if p != TimeRangePreset.CUSTOM)
|
|
631
|
+
add(
|
|
632
|
+
CheckProblem(
|
|
633
|
+
"BAD_DEFAULT",
|
|
634
|
+
f"the default period must be one of {presets}.",
|
|
635
|
+
picker_keys[key],
|
|
636
|
+
)
|
|
637
|
+
)
|
|
638
|
+
elif key != TIME_FILTER_KEY and not (
|
|
639
|
+
value is None or isinstance(value, str | int | bool)
|
|
640
|
+
):
|
|
641
|
+
add(
|
|
642
|
+
CheckProblem(
|
|
643
|
+
"BAD_DEFAULT",
|
|
644
|
+
f"the default of $/filters/{key} must be a single value.",
|
|
645
|
+
picker_keys[key],
|
|
646
|
+
)
|
|
647
|
+
)
|
|
648
|
+
return problems
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _is_default_period(value: Any) -> bool:
|
|
652
|
+
return (
|
|
653
|
+
isinstance(value, str)
|
|
654
|
+
and value in {p.value for p in TimeRangePreset}
|
|
655
|
+
and value != TimeRangePreset.CUSTOM
|
|
656
|
+
)
|