platybus-dashboards 0.1.0__tar.gz
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.
- platybus_dashboards-0.1.0/.gitignore +46 -0
- platybus_dashboards-0.1.0/LICENSE +21 -0
- platybus_dashboards-0.1.0/PKG-INFO +41 -0
- platybus_dashboards-0.1.0/README.md +16 -0
- platybus_dashboards-0.1.0/pyproject.toml +43 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/__init__.py +85 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/cache.py +47 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/params.py +194 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/py.typed +0 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/router.py +114 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/schemas.py +69 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/service.py +266 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/shaping.py +109 -0
- platybus_dashboards-0.1.0/src/platybus_dashboards/spec.py +370 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
.venv/
|
|
5
|
+
dist/
|
|
6
|
+
build/
|
|
7
|
+
*.egg-info/
|
|
8
|
+
.pytest_cache/
|
|
9
|
+
.mypy_cache/
|
|
10
|
+
.ruff_cache/
|
|
11
|
+
.coverage
|
|
12
|
+
htmlcov/
|
|
13
|
+
|
|
14
|
+
# Node
|
|
15
|
+
web/node_modules/
|
|
16
|
+
web/dist/
|
|
17
|
+
src/platybus/server/static/
|
|
18
|
+
web/*.tsbuildinfo
|
|
19
|
+
# Playwright artifacts
|
|
20
|
+
web/playwright-report/
|
|
21
|
+
web/test-results/
|
|
22
|
+
web/blob-report/
|
|
23
|
+
web/playwright/.cache/
|
|
24
|
+
|
|
25
|
+
# Platybus local state and demos
|
|
26
|
+
.platybus/
|
|
27
|
+
.tmp/
|
|
28
|
+
*.duckdb
|
|
29
|
+
*.duckdb.wal
|
|
30
|
+
|
|
31
|
+
# Secrets
|
|
32
|
+
.env
|
|
33
|
+
.env.*
|
|
34
|
+
!.env.example
|
|
35
|
+
|
|
36
|
+
# Editors / OS
|
|
37
|
+
.idea/
|
|
38
|
+
.vscode/
|
|
39
|
+
.DS_Store
|
|
40
|
+
Thumbs.db
|
|
41
|
+
|
|
42
|
+
# Claude Code local settings
|
|
43
|
+
.claude/settings.local.json
|
|
44
|
+
.claude
|
|
45
|
+
# MkDocs output
|
|
46
|
+
site/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yaroslav Ozerov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: platybus-dashboards
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Platybus plugin: dashboards as code (YAML + SQL) rendered by the Platybus UI.
|
|
5
|
+
Project-URL: Homepage, https://github.com/RobbyTheFish/platybus
|
|
6
|
+
Project-URL: Documentation, https://robbythefish.github.io/platybus/
|
|
7
|
+
Project-URL: Repository, https://github.com/RobbyTheFish/platybus
|
|
8
|
+
Project-URL: Issues, https://github.com/RobbyTheFish/platybus/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Yaroslav Ozerov
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: dashboards,duckdb,platybus,platybus-plugin
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Database
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: platybus>=0.1.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# platybus-dashboards
|
|
27
|
+
|
|
28
|
+
dashboards as code (YAML + SQL) rendered by the Platybus UI.
|
|
29
|
+
|
|
30
|
+
A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
|
|
31
|
+
a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
|
|
32
|
+
ETL, dbt and dashboards.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install platybus platybus-dashboards
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Platybus discovers the plugin through the `platybus.plugins` entry point; no configuration
|
|
39
|
+
is needed. Documentation: <https://robbythefish.github.io/platybus/> (this plugin: <https://robbythefish.github.io/platybus/dashboards/>).
|
|
40
|
+
|
|
41
|
+
License: MIT.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# platybus-dashboards
|
|
2
|
+
|
|
3
|
+
dashboards as code (YAML + SQL) rendered by the Platybus UI.
|
|
4
|
+
|
|
5
|
+
A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
|
|
6
|
+
a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
|
|
7
|
+
ETL, dbt and dashboards.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install platybus platybus-dashboards
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Platybus discovers the plugin through the `platybus.plugins` entry point; no configuration
|
|
14
|
+
is needed. Documentation: <https://robbythefish.github.io/platybus/> (this plugin: <https://robbythefish.github.io/platybus/dashboards/>).
|
|
15
|
+
|
|
16
|
+
License: MIT.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "platybus-dashboards"
|
|
3
|
+
version = "0.1.0" # x-release-please-version
|
|
4
|
+
description = "Platybus plugin: dashboards as code (YAML + SQL) rendered by the Platybus UI."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Yaroslav Ozerov" }]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
keywords = ["platybus", "platybus-plugin", "duckdb", "dashboards"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Programming Language :: Python :: 3.13",
|
|
18
|
+
"Topic :: Database",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"platybus>=0.1.0", # x-release-please-version
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/RobbyTheFish/platybus"
|
|
27
|
+
Documentation = "https://robbythefish.github.io/platybus/"
|
|
28
|
+
Repository = "https://github.com/RobbyTheFish/platybus"
|
|
29
|
+
Issues = "https://github.com/RobbyTheFish/platybus/issues"
|
|
30
|
+
Changelog = "https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md"
|
|
31
|
+
|
|
32
|
+
[project.entry-points."platybus.plugins"]
|
|
33
|
+
native = "platybus_dashboards:plugin"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["hatchling>=1.26"]
|
|
37
|
+
build-backend = "hatchling.build"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/platybus_dashboards"]
|
|
41
|
+
|
|
42
|
+
[tool.uv.sources]
|
|
43
|
+
platybus = { workspace = true }
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Platybus plugin: dashboards as code (YAML + SQL), rendered by the Platybus UI.
|
|
2
|
+
|
|
3
|
+
Spec loading, parameter binding, query shaping and the result cache live here; the
|
|
4
|
+
plugin also contributes the ``/api/dashboards`` router. See docs/dashboards.md.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from platybus.plugins import DashboardEntry, Plugin, ProviderContext
|
|
11
|
+
from platybus.plugins.dashboards import ProviderMode
|
|
12
|
+
from platybus_dashboards.cache import TTLCache
|
|
13
|
+
from platybus_dashboards.params import bind_params, resolve_daterange, resolve_filters
|
|
14
|
+
from platybus_dashboards.service import (
|
|
15
|
+
Dashboard,
|
|
16
|
+
DashboardService,
|
|
17
|
+
DashboardSummary,
|
|
18
|
+
WidgetResult,
|
|
19
|
+
service_for,
|
|
20
|
+
)
|
|
21
|
+
from platybus_dashboards.spec import DashboardSpec
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from fastapi import APIRouter
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class NativeProvider:
|
|
28
|
+
"""Dashboards from ``dashboards/*.yml`` of the project."""
|
|
29
|
+
|
|
30
|
+
name = "native"
|
|
31
|
+
title = "Platybus"
|
|
32
|
+
mode: ProviderMode = "native"
|
|
33
|
+
|
|
34
|
+
def __init__(self, context: ProviderContext) -> None:
|
|
35
|
+
self.service = service_for(context.project, context.engine)
|
|
36
|
+
|
|
37
|
+
def list_dashboards(self) -> list[DashboardEntry]:
|
|
38
|
+
return [
|
|
39
|
+
DashboardEntry(
|
|
40
|
+
id=s.id,
|
|
41
|
+
title=s.title,
|
|
42
|
+
description=s.description,
|
|
43
|
+
widget_count=s.widget_count,
|
|
44
|
+
error=s.error,
|
|
45
|
+
)
|
|
46
|
+
for s in self.service.summaries()
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
def home_url(self) -> str | None:
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
def stop(self) -> None:
|
|
53
|
+
self.service.stop()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _routers() -> "Sequence[APIRouter]":
|
|
57
|
+
from platybus_dashboards.router import router
|
|
58
|
+
|
|
59
|
+
return [router]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
plugin = Plugin(
|
|
63
|
+
name="native",
|
|
64
|
+
kind="dashboards",
|
|
65
|
+
title="Platybus dashboards",
|
|
66
|
+
description="Dashboards as code: YAML + SQL files in dashboards/, rendered with ECharts.",
|
|
67
|
+
dashboards=NativeProvider,
|
|
68
|
+
routers=_routers,
|
|
69
|
+
schemas={"dashboard": DashboardSpec},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"Dashboard",
|
|
74
|
+
"DashboardService",
|
|
75
|
+
"DashboardSpec",
|
|
76
|
+
"DashboardSummary",
|
|
77
|
+
"NativeProvider",
|
|
78
|
+
"TTLCache",
|
|
79
|
+
"WidgetResult",
|
|
80
|
+
"bind_params",
|
|
81
|
+
"plugin",
|
|
82
|
+
"resolve_daterange",
|
|
83
|
+
"resolve_filters",
|
|
84
|
+
"service_for",
|
|
85
|
+
]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""In-memory TTL cache for widget results (bounded, thread-safe, LRU eviction)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections import OrderedDict
|
|
8
|
+
from collections.abc import Callable, Hashable
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TTLCache[V]:
|
|
12
|
+
"""Maps keys to values that expire ``ttl`` seconds after being stored."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, max_entries: int = 512, clock: Callable[[], float] = time.monotonic) -> None:
|
|
15
|
+
self.max_entries = max_entries
|
|
16
|
+
self._clock = clock
|
|
17
|
+
self._data: OrderedDict[Hashable, tuple[float, V]] = OrderedDict()
|
|
18
|
+
self._lock = threading.Lock()
|
|
19
|
+
|
|
20
|
+
def get(self, key: Hashable) -> V | None:
|
|
21
|
+
with self._lock:
|
|
22
|
+
entry = self._data.get(key)
|
|
23
|
+
if entry is None:
|
|
24
|
+
return None
|
|
25
|
+
expires, value = entry
|
|
26
|
+
if expires <= self._clock():
|
|
27
|
+
del self._data[key]
|
|
28
|
+
return None
|
|
29
|
+
self._data.move_to_end(key)
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
def set(self, key: Hashable, value: V, ttl: float) -> None:
|
|
33
|
+
if ttl <= 0:
|
|
34
|
+
return
|
|
35
|
+
with self._lock:
|
|
36
|
+
self._data[key] = (self._clock() + ttl, value)
|
|
37
|
+
self._data.move_to_end(key)
|
|
38
|
+
while len(self._data) > self.max_entries:
|
|
39
|
+
self._data.popitem(last=False)
|
|
40
|
+
|
|
41
|
+
def clear(self) -> None:
|
|
42
|
+
with self._lock:
|
|
43
|
+
self._data.clear()
|
|
44
|
+
|
|
45
|
+
def __len__(self) -> int:
|
|
46
|
+
with self._lock:
|
|
47
|
+
return len(self._data)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Filter values → SQL parameters.
|
|
2
|
+
|
|
3
|
+
Dashboard SQL uses ``:name`` placeholders. :func:`bind_params` rewrites the known ones into
|
|
4
|
+
DuckDB named parameters (``$name``) with a small tokenizer, so ``::`` casts, string
|
|
5
|
+
literals, quoted identifiers, comments and dollar-quoted strings are left untouched.
|
|
6
|
+
Values are always passed as bound parameters, never interpolated into the SQL text.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from calendar import monthrange
|
|
13
|
+
from collections.abc import Iterable, Mapping
|
|
14
|
+
from datetime import date, timedelta
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from pydantic import ValidationError
|
|
18
|
+
|
|
19
|
+
from platybus.errors import InvalidRequestError
|
|
20
|
+
from platybus_dashboards.spec import DATERANGE_PRESETS, DashboardSpec, DateRange, FilterSpec
|
|
21
|
+
|
|
22
|
+
type ParamValue = str | int | float | bool | date | None
|
|
23
|
+
|
|
24
|
+
_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
25
|
+
_DOLLAR_TAG = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)?\$")
|
|
26
|
+
_IDENT_CHARS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")
|
|
27
|
+
|
|
28
|
+
#: ``all_time`` bounds: wide enough for any real data, still valid DATE values.
|
|
29
|
+
ALL_TIME = (date(1900, 1, 1), date(2999, 12, 31))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _skip_quoted(sql: str, start: int, quote: str, *, backslash: bool = False) -> int:
|
|
33
|
+
"""Index just past the literal/identifier opened at ``start`` (doubled quotes escape)."""
|
|
34
|
+
i = start + 1
|
|
35
|
+
n = len(sql)
|
|
36
|
+
while i < n:
|
|
37
|
+
ch = sql[i]
|
|
38
|
+
if backslash and ch == "\\":
|
|
39
|
+
i += 2
|
|
40
|
+
continue
|
|
41
|
+
if ch == quote:
|
|
42
|
+
if i + 1 < n and sql[i + 1] == quote:
|
|
43
|
+
i += 2
|
|
44
|
+
continue
|
|
45
|
+
return i + 1
|
|
46
|
+
i += 1
|
|
47
|
+
return n
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def bind_params(sql: str, known: Iterable[str]) -> tuple[str, list[str]]:
|
|
51
|
+
"""Rewrite ``:name`` → ``$name`` for names in ``known``.
|
|
52
|
+
|
|
53
|
+
Returns the rewritten SQL and the referenced parameter names (first-use order).
|
|
54
|
+
Unknown ``:x`` tokens are kept as-is (e.g. list slices ``arr[1:n]``).
|
|
55
|
+
"""
|
|
56
|
+
names = set(known)
|
|
57
|
+
out: list[str] = []
|
|
58
|
+
used: list[str] = []
|
|
59
|
+
i = 0
|
|
60
|
+
n = len(sql)
|
|
61
|
+
while i < n:
|
|
62
|
+
ch = sql[i]
|
|
63
|
+
prev = sql[i - 1] if i else ""
|
|
64
|
+
if ch in "eE" and i + 1 < n and sql[i + 1] == "'" and prev not in _IDENT_CHARS:
|
|
65
|
+
end = _skip_quoted(sql, i + 1, "'", backslash=True)
|
|
66
|
+
out.append(sql[i:end])
|
|
67
|
+
i = end
|
|
68
|
+
elif ch in "'\"":
|
|
69
|
+
end = _skip_quoted(sql, i, ch)
|
|
70
|
+
out.append(sql[i:end])
|
|
71
|
+
i = end
|
|
72
|
+
elif sql.startswith("--", i):
|
|
73
|
+
end = sql.find("\n", i)
|
|
74
|
+
end = n if end < 0 else end
|
|
75
|
+
out.append(sql[i:end])
|
|
76
|
+
i = end
|
|
77
|
+
elif sql.startswith("/*", i):
|
|
78
|
+
end = sql.find("*/", i + 2)
|
|
79
|
+
end = n if end < 0 else end + 2
|
|
80
|
+
out.append(sql[i:end])
|
|
81
|
+
i = end
|
|
82
|
+
elif ch == "$" and (tag := _DOLLAR_TAG.match(sql, i)) is not None:
|
|
83
|
+
close = sql.find(tag.group(0), tag.end())
|
|
84
|
+
end = n if close < 0 else close + len(tag.group(0))
|
|
85
|
+
out.append(sql[i:end])
|
|
86
|
+
i = end
|
|
87
|
+
elif ch == ":":
|
|
88
|
+
if i + 1 < n and sql[i + 1] == ":": # ``::type`` cast
|
|
89
|
+
out.append("::")
|
|
90
|
+
i += 2
|
|
91
|
+
continue
|
|
92
|
+
match = _IDENT.match(sql, i + 1)
|
|
93
|
+
if match is not None and match.group(0) in names:
|
|
94
|
+
name = match.group(0)
|
|
95
|
+
out.append("$" + name)
|
|
96
|
+
if name not in used:
|
|
97
|
+
used.append(name)
|
|
98
|
+
i = match.end()
|
|
99
|
+
else:
|
|
100
|
+
out.append(ch)
|
|
101
|
+
i += 1
|
|
102
|
+
else:
|
|
103
|
+
out.append(ch)
|
|
104
|
+
i += 1
|
|
105
|
+
return "".join(out), used
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def resolve_daterange(value: str | DateRange, today: date) -> tuple[date, date]:
|
|
109
|
+
"""A preset name or explicit range → inclusive ``(from, to)`` dates."""
|
|
110
|
+
if isinstance(value, DateRange):
|
|
111
|
+
return value.from_, value.to
|
|
112
|
+
match value:
|
|
113
|
+
case "all_time":
|
|
114
|
+
return ALL_TIME
|
|
115
|
+
case "today":
|
|
116
|
+
return today, today
|
|
117
|
+
case "last_7_days":
|
|
118
|
+
return today - timedelta(days=6), today
|
|
119
|
+
case "last_30_days":
|
|
120
|
+
return today - timedelta(days=29), today
|
|
121
|
+
case "last_90_days":
|
|
122
|
+
return today - timedelta(days=89), today
|
|
123
|
+
case "last_365_days":
|
|
124
|
+
return today - timedelta(days=364), today
|
|
125
|
+
case "this_month":
|
|
126
|
+
return today.replace(day=1), today.replace(day=monthrange(today.year, today.month)[1])
|
|
127
|
+
case "this_year":
|
|
128
|
+
return date(today.year, 1, 1), date(today.year, 12, 31)
|
|
129
|
+
raise InvalidRequestError(
|
|
130
|
+
f"unknown date range {value!r} (expected one of {', '.join(DATERANGE_PRESETS)} "
|
|
131
|
+
"or {from, to})"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _daterange_value(flt: FilterSpec, raw: Any) -> str | DateRange:
|
|
136
|
+
if raw is None:
|
|
137
|
+
return "all_time"
|
|
138
|
+
if isinstance(raw, DateRange):
|
|
139
|
+
return raw
|
|
140
|
+
if isinstance(raw, str):
|
|
141
|
+
return raw
|
|
142
|
+
if isinstance(raw, Mapping):
|
|
143
|
+
try:
|
|
144
|
+
return DateRange.model_validate(dict(raw))
|
|
145
|
+
except ValidationError as exc:
|
|
146
|
+
msg = "; ".join(str(e["msg"]) for e in exc.errors())
|
|
147
|
+
raise InvalidRequestError(f"filter '{flt.name}': invalid date range: {msg}") from None
|
|
148
|
+
raise InvalidRequestError(f"filter '{flt.name}': expected a preset name or {{from, to}}")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _scalar_value(flt: FilterSpec, raw: Any) -> ParamValue:
|
|
152
|
+
if raw is None or raw == "":
|
|
153
|
+
return None
|
|
154
|
+
if isinstance(raw, Mapping | DateRange | list):
|
|
155
|
+
raise InvalidRequestError(f"filter '{flt.name}': expected a single value")
|
|
156
|
+
if flt.type == "number":
|
|
157
|
+
if isinstance(raw, bool):
|
|
158
|
+
raise InvalidRequestError(f"filter '{flt.name}': expected a number")
|
|
159
|
+
if isinstance(raw, int | float):
|
|
160
|
+
return raw
|
|
161
|
+
try:
|
|
162
|
+
number = float(str(raw))
|
|
163
|
+
except ValueError:
|
|
164
|
+
raise InvalidRequestError(f"filter '{flt.name}': expected a number") from None
|
|
165
|
+
return int(number) if number.is_integer() and "." not in str(raw) else number
|
|
166
|
+
if flt.type == "text":
|
|
167
|
+
return str(raw)
|
|
168
|
+
# select
|
|
169
|
+
if flt.options is not None and str(raw) not in {str(o) for o in flt.options}:
|
|
170
|
+
raise InvalidRequestError(
|
|
171
|
+
f"filter '{flt.name}': {raw!r} is not one of the options "
|
|
172
|
+
f"({', '.join(str(o) for o in flt.options)})"
|
|
173
|
+
)
|
|
174
|
+
if isinstance(raw, str | int | float | bool):
|
|
175
|
+
return raw
|
|
176
|
+
raise InvalidRequestError(f"filter '{flt.name}': unsupported value")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def resolve_filters(
|
|
180
|
+
spec: DashboardSpec, supplied: Mapping[str, Any], today: date
|
|
181
|
+
) -> dict[str, ParamValue]:
|
|
182
|
+
"""Supplied filter values (or defaults) → SQL parameter values for every filter."""
|
|
183
|
+
unknown = sorted(set(supplied) - {f.name for f in spec.filters})
|
|
184
|
+
if unknown:
|
|
185
|
+
raise InvalidRequestError(f"unknown filter(s): {', '.join(unknown)}")
|
|
186
|
+
params: dict[str, ParamValue] = {}
|
|
187
|
+
for flt in spec.filters:
|
|
188
|
+
raw = supplied.get(flt.name, flt.default)
|
|
189
|
+
if flt.type == "daterange":
|
|
190
|
+
start, end = resolve_daterange(_daterange_value(flt, raw), today)
|
|
191
|
+
params[f"{flt.name}_from"], params[f"{flt.name}_to"] = start, end
|
|
192
|
+
else:
|
|
193
|
+
params[flt.name] = _scalar_value(flt, raw)
|
|
194
|
+
return params
|
|
File without changes
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""``/api/dashboards`` — dashboards as code: specs, widget queries, filter options."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter, Depends
|
|
8
|
+
|
|
9
|
+
from platybus.server.context import AppContext, get_context
|
|
10
|
+
from platybus.server.schemas.common import ErrorResponse
|
|
11
|
+
from platybus.server.schemas.sql import ColumnModel
|
|
12
|
+
from platybus_dashboards.schemas import (
|
|
13
|
+
DashboardDetail,
|
|
14
|
+
DashboardSummaryModel,
|
|
15
|
+
DashboardWidgetModel,
|
|
16
|
+
FilterOptionsResponse,
|
|
17
|
+
WidgetQueryRequest,
|
|
18
|
+
WidgetQueryResponse,
|
|
19
|
+
)
|
|
20
|
+
from platybus_dashboards.service import DashboardService, service_for
|
|
21
|
+
from platybus_dashboards.spec import DataWidget
|
|
22
|
+
|
|
23
|
+
router = APIRouter(prefix="/dashboards", tags=["dashboards"])
|
|
24
|
+
|
|
25
|
+
_ERRORS: dict[int | str, dict[str, object]] = {
|
|
26
|
+
400: {"model": ErrorResponse},
|
|
27
|
+
404: {"model": ErrorResponse},
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_service(ctx: Annotated[AppContext, Depends(get_context)]) -> DashboardService:
|
|
32
|
+
"""One :class:`DashboardService` (and result cache) per server process."""
|
|
33
|
+
return service_for(ctx.project, ctx.engine)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
Service = Annotated[DashboardService, Depends(get_service)]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@router.get("", response_model=list[DashboardSummaryModel])
|
|
40
|
+
def list_dashboards(service: Service) -> list[DashboardSummaryModel]:
|
|
41
|
+
"""Dashboards in ``dashboards/``; invalid files are listed with an ``error``."""
|
|
42
|
+
return [
|
|
43
|
+
DashboardSummaryModel(
|
|
44
|
+
id=d.id,
|
|
45
|
+
title=d.title,
|
|
46
|
+
description=d.description,
|
|
47
|
+
widget_count=d.widget_count,
|
|
48
|
+
error=d.error,
|
|
49
|
+
)
|
|
50
|
+
for d in service.summaries()
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@router.get("/{dashboard_id}", response_model=DashboardDetail, responses=_ERRORS)
|
|
55
|
+
def get_dashboard(dashboard_id: str, service: Service) -> DashboardDetail:
|
|
56
|
+
"""Full dashboard spec with every widget's SQL."""
|
|
57
|
+
dash = service.get(dashboard_id)
|
|
58
|
+
spec = dash.spec
|
|
59
|
+
return DashboardDetail(
|
|
60
|
+
id=dash.id,
|
|
61
|
+
title=spec.title,
|
|
62
|
+
description=spec.description,
|
|
63
|
+
refresh=spec.refresh,
|
|
64
|
+
refresh_seconds=spec.refresh_seconds,
|
|
65
|
+
filters=list(spec.filters),
|
|
66
|
+
widgets=[
|
|
67
|
+
DashboardWidgetModel(
|
|
68
|
+
id=w.id or "",
|
|
69
|
+
type=w.type,
|
|
70
|
+
title=w.title,
|
|
71
|
+
description=w.description,
|
|
72
|
+
width=w.width,
|
|
73
|
+
height=w.height,
|
|
74
|
+
sql=dash.sql.get(w.id or ""),
|
|
75
|
+
sql_file=w.sql_file if isinstance(w, DataWidget) else None,
|
|
76
|
+
queryable=w.queryable,
|
|
77
|
+
spec=w,
|
|
78
|
+
)
|
|
79
|
+
for w in spec.widgets
|
|
80
|
+
],
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@router.post(
|
|
85
|
+
"/{dashboard_id}/widgets/{widget_id}:query",
|
|
86
|
+
response_model=WidgetQueryResponse,
|
|
87
|
+
responses={**_ERRORS, 408: {"model": ErrorResponse}},
|
|
88
|
+
)
|
|
89
|
+
def query_widget(
|
|
90
|
+
dashboard_id: str, widget_id: str, body: WidgetQueryRequest, service: Service
|
|
91
|
+
) -> WidgetQueryResponse:
|
|
92
|
+
"""Run a widget's query with filter values; results are cached per lake snapshot."""
|
|
93
|
+
result = service.query_widget(dashboard_id, widget_id, body.filters, force=body.force)
|
|
94
|
+
return WidgetQueryResponse(
|
|
95
|
+
widget_id=widget_id,
|
|
96
|
+
columns=[ColumnModel(name=c.name, type=c.type) for c in result.columns],
|
|
97
|
+
rows=result.rows,
|
|
98
|
+
row_count=result.row_count,
|
|
99
|
+
truncated=result.truncated,
|
|
100
|
+
cached=result.cached,
|
|
101
|
+
elapsed_ms=result.elapsed_ms,
|
|
102
|
+
snapshot_id=result.snapshot_id,
|
|
103
|
+
params=result.params,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@router.get(
|
|
108
|
+
"/{dashboard_id}/filters/{name}/options",
|
|
109
|
+
response_model=FilterOptionsResponse,
|
|
110
|
+
responses=_ERRORS,
|
|
111
|
+
)
|
|
112
|
+
def filter_options(dashboard_id: str, name: str, service: Service) -> FilterOptionsResponse:
|
|
113
|
+
"""Choices of a select filter (static options or the ``options_sql`` result)."""
|
|
114
|
+
return FilterOptionsResponse(name=name, options=service.filter_options(dashboard_id, name))
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Models for ``/api/dashboards``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
from platybus.server.schemas.sql import ColumnModel, JsonScalar, JsonValue
|
|
8
|
+
from platybus_dashboards.spec import DateRange, FilterSpec, Widget
|
|
9
|
+
|
|
10
|
+
type FilterInput = DateRange | str | int | float | bool | None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DashboardSummaryModel(BaseModel):
|
|
14
|
+
id: str = Field(..., description="File stem of dashboards/<id>.yml.")
|
|
15
|
+
title: str
|
|
16
|
+
description: str | None
|
|
17
|
+
widget_count: int
|
|
18
|
+
error: str | None = Field(None, description="Validation error if the file is invalid.")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DashboardWidgetModel(BaseModel):
|
|
22
|
+
id: str
|
|
23
|
+
type: str = Field(..., description="kpi | line | bar | area | pie | table | markdown")
|
|
24
|
+
title: str | None
|
|
25
|
+
description: str | None
|
|
26
|
+
width: int = Field(..., description="Grid columns out of 12.")
|
|
27
|
+
height: int | None
|
|
28
|
+
sql: str | None = Field(None, description="Query text (sql_file content resolved).")
|
|
29
|
+
sql_file: str | None = None
|
|
30
|
+
queryable: bool = Field(..., description="False for markdown widgets.")
|
|
31
|
+
spec: Widget = Field(..., description="The widget as written in YAML (ids resolved).")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class DashboardDetail(BaseModel):
|
|
35
|
+
id: str
|
|
36
|
+
title: str
|
|
37
|
+
description: str | None
|
|
38
|
+
refresh: str | None = Field(None, description="Refresh interval as written, e.g. 5m.")
|
|
39
|
+
refresh_seconds: int | None
|
|
40
|
+
filters: list[FilterSpec]
|
|
41
|
+
widgets: list[DashboardWidgetModel]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class WidgetQueryRequest(BaseModel):
|
|
45
|
+
filters: dict[str, FilterInput] = Field(
|
|
46
|
+
default_factory=dict,
|
|
47
|
+
description="Filter values by name: a scalar, a daterange preset or {from, to}. "
|
|
48
|
+
"Missing filters use their default.",
|
|
49
|
+
)
|
|
50
|
+
force: bool = Field(False, description="Bypass the result cache.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class WidgetQueryResponse(BaseModel):
|
|
54
|
+
widget_id: str
|
|
55
|
+
columns: list[ColumnModel]
|
|
56
|
+
rows: list[list[JsonValue]]
|
|
57
|
+
row_count: int
|
|
58
|
+
truncated: bool = Field(..., description="True when the engine row limit cut the result.")
|
|
59
|
+
cached: bool = Field(..., description="Served from the result cache.")
|
|
60
|
+
elapsed_ms: float = Field(..., description="Query time of the (original) execution.")
|
|
61
|
+
snapshot_id: int | None = Field(..., description="Lake snapshot the result was read at.")
|
|
62
|
+
params: dict[str, JsonScalar] = Field(
|
|
63
|
+
..., description="Parameters bound into the query (resolved filter values)."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class FilterOptionsResponse(BaseModel):
|
|
68
|
+
name: str
|
|
69
|
+
options: list[JsonScalar]
|