Skip to content

Commit f3ae182

Browse files
authored
feat: --days on stats commands, --zone filter for nxdomains, column docs (v1.0.7) (#6)
User feedback from a 26-zone production deployment: the stats/report commands' biggest weakness was observability depth — unlabeled columns when piped and no time-window flags. - Added --days N (1-180) to `rc0 stats queries`, `rc0 stats topzones`, and `rc0 stats zone queries`. The first two forward `days` as a query parameter; the zone-scoped endpoint has no server-side filter so --days slices the last N days client-side after fetching the full 180-day history. - Added --zone <apex> to `rc0 report nxdomains`. The upstream endpoint cannot filter by zone, so the CLI applies it client-side after fetching the account-wide response. Trailing dots are normalised. - Help text for `zone list`, `stats queries`, `stats zone queries`, `stats topzones`, and `report nxdomains` now documents the column names and their meaning, so users piping to plain output (no headers by design, mission plan §9) can still interpret the fields. Users wanting headers in redirected output can use -o tsv / -o csv.
1 parent e7cdc17 commit f3ae182

10 files changed

Lines changed: 271 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [1.0.7] — 2026-04-23
11+
12+
### Added
13+
- `rc0 stats queries` and `rc0 stats topzones` now accept `--days N` (1-180),
14+
forwarded to the API's `days` query parameter. Without the flag the API
15+
default of 30 days still applies.
16+
- `rc0 stats zone queries` accepts `--days N` as a client-side slice of the
17+
most recent N days, since the upstream endpoint has no `days` parameter and
18+
always returns the full 180-day history.
19+
- `rc0 report nxdomains --zone <apex>` filters the report to a single zone
20+
client-side (trailing dots are ignored). The underlying API has no zone
21+
parameter for this endpoint, so the filter runs after fetching the full
22+
account-wide response.
23+
24+
### Changed
25+
- Help text for `rc0 zone list`, `rc0 stats queries`, `rc0 stats zone queries`,
26+
`rc0 stats topzones`, and `rc0 report nxdomains` now names the output
27+
columns and their meaning. Previously only the table output carried
28+
headers; when piped (plain/TSV fallback) users had to guess which column
29+
was which. Use `-o tsv` or `-o csv` to get headers in redirected output.
30+
1031
## [1.0.6] — 2026-04-23
1132

1233
### Fixed

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "rc0-cli"
3-
version = "1.0.6"
3+
version = "1.0.7"
44
description = "Command line for RcodeZero DNS."
55
readme = "README.md"
66
requires-python = ">=3.14"

‎src/rc0/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
from __future__ import annotations
44

5-
__version__ = "1.0.6"
5+
__version__ = "1.0.7"
66

77
__all__ = ["__version__"]

‎src/rc0/api/stats.py‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from __future__ import annotations
99

10-
from typing import TYPE_CHECKING
10+
from typing import TYPE_CHECKING, Any
1111

1212
from rc0.models.stats import (
1313
CountryRow,
@@ -26,14 +26,34 @@
2626
from rc0.client.http import Client
2727

2828

29-
def list_querycounts(client: Client) -> list[QueryCountRow]:
30-
"""GET /api/v2/stats/querycounts — bare array."""
31-
return [QueryCountRow.model_validate(r) for r in client.get("/api/v2/stats/querycounts").json()]
29+
def list_querycounts(client: Client, *, days: int | None = None) -> list[QueryCountRow]:
30+
"""GET /api/v2/stats/querycounts — bare array.
31+
32+
``days`` (1-180) selects the size of the lookback window. The API
33+
defaults to 30 when the parameter is omitted.
34+
"""
35+
params: dict[str, Any] = {}
36+
if days is not None:
37+
params["days"] = days
38+
return [
39+
QueryCountRow.model_validate(r)
40+
for r in client.get("/api/v2/stats/querycounts", params=params).json()
41+
]
3242

3343

34-
def list_topzones(client: Client) -> list[TopzoneRow]:
35-
"""GET /api/v2/stats/topzones — bare array."""
36-
return [TopzoneRow.model_validate(r) for r in client.get("/api/v2/stats/topzones").json()]
44+
def list_topzones(client: Client, *, days: int | None = None) -> list[TopzoneRow]:
45+
"""GET /api/v2/stats/topzones — bare array.
46+
47+
``days`` (1-180) selects the size of the lookback window. The API
48+
defaults to 30 when the parameter is omitted.
49+
"""
50+
params: dict[str, Any] = {}
51+
if days is not None:
52+
params["days"] = days
53+
return [
54+
TopzoneRow.model_validate(r)
55+
for r in client.get("/api/v2/stats/topzones", params=params).json()
56+
]
3757

3858

3959
def list_countries(client: Client) -> list[CountryRow]:

‎src/rc0/commands/report.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,34 @@ def nxdomains_cmd(
8989
str | None,
9090
typer.Option("--day", help=_NXDOMAIN_DAY_HELP),
9191
] = None,
92+
zone: Annotated[
93+
str | None,
94+
typer.Option(
95+
"--zone",
96+
help="Filter results to a single zone apex (client-side; trailing dot ignored).",
97+
),
98+
] = None,
9299
) -> None:
93-
"""NXDOMAIN report. API: GET /api/v2/reports/nxdomains"""
100+
"""NXDOMAIN report. API: GET /api/v2/reports/nxdomains
101+
102+
Columns: date, domain, qname, qtype, querycount.
103+
104+
The API itself has no zone parameter for this endpoint, so --zone
105+
is applied client-side after fetching the full account-wide report.
106+
107+
Examples:
108+
109+
rc0 report nxdomains
110+
rc0 report nxdomains --day yesterday
111+
rc0 report nxdomains --zone example.com
112+
"""
94113
_validate_nxdomain_day(day)
95114
state: AppState = ctx.obj
96115
with _client(state) as client:
97116
rows = reports_api.list_nxdomains(client, day=day)
117+
if zone is not None:
118+
target = zone.rstrip(".")
119+
rows = [r for r in rows if (r.domain or "").rstrip(".") == target]
98120
typer.echo(
99121
render(
100122
[r.model_dump(exclude_none=True) for r in rows],

‎src/rc0/commands/stats.py‎

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,35 @@
2424

2525
ZoneArg = Annotated[str, typer.Argument(help="Fully-qualified zone apex, e.g. example.com.")]
2626

27+
DaysOpt = Annotated[
28+
int | None,
29+
typer.Option(
30+
"--days",
31+
min=1,
32+
max=180,
33+
help="Lookback window in days (1-180). API default is 30.",
34+
),
35+
]
36+
2737

2838
# ----------------------------------------------------------- top-level (live)
2939

3040

3141
@app.command("queries")
32-
def queries_cmd(ctx: typer.Context) -> None:
33-
"""Query counts per day. API: GET /api/v2/stats/querycounts"""
42+
def queries_cmd(ctx: typer.Context, days: DaysOpt = None) -> None:
43+
"""Query counts per day. API: GET /api/v2/stats/querycounts
44+
45+
Columns: date, count (total queries), nxcount (NXDOMAIN responses).
46+
47+
Examples:
48+
49+
rc0 stats queries
50+
rc0 stats queries --days 7
51+
rc0 -o tsv stats queries --days 30
52+
"""
3453
state: AppState = ctx.obj
3554
with _client(state) as client:
36-
rows = stats_api.list_querycounts(client)
55+
rows = stats_api.list_querycounts(client, days=days)
3756
typer.echo(
3857
render(
3958
[r.model_dump(exclude_none=True) for r in rows],
@@ -44,11 +63,20 @@ def queries_cmd(ctx: typer.Context) -> None:
4463

4564

4665
@app.command("topzones")
47-
def topzones_cmd(ctx: typer.Context) -> None:
48-
"""Top zones by traffic. API: GET /api/v2/stats/topzones"""
66+
def topzones_cmd(ctx: typer.Context, days: DaysOpt = None) -> None:
67+
"""Top zones by traffic. API: GET /api/v2/stats/topzones
68+
69+
Returns up to 1000 zones ranked by query count over the lookback
70+
window. Columns: domain, qc (query count).
71+
72+
Examples:
73+
74+
rc0 stats topzones
75+
rc0 stats topzones --days 7
76+
"""
4977
state: AppState = ctx.obj
5078
with _client(state) as client:
51-
rows = stats_api.list_topzones(client)
79+
rows = stats_api.list_topzones(client, days=days)
5280
typer.echo(
5381
render(
5482
[r.model_dump(exclude_none=True) for r in rows],
@@ -124,11 +152,24 @@ def topqnames_cmd(ctx: typer.Context) -> None:
124152

125153

126154
@zone_app.command("queries")
127-
def zone_queries_cmd(ctx: typer.Context, zone: ZoneArg) -> None:
128-
"""Query counts for one zone. API: GET /api/v2/zones/{zone}/stats/queries"""
155+
def zone_queries_cmd(ctx: typer.Context, zone: ZoneArg, days: DaysOpt = None) -> None:
156+
"""Query counts for one zone. API: GET /api/v2/zones/{zone}/stats/queries
157+
158+
Columns: date, qcount (total queries), nxcount (NXDOMAIN responses).
159+
160+
The API always returns the full 180-day history; --days N keeps
161+
only the most recent N days client-side.
162+
163+
Examples:
164+
165+
rc0 stats zone queries example.com
166+
rc0 stats zone queries example.com --days 7
167+
"""
129168
state: AppState = ctx.obj
130169
with _client(state) as client:
131170
rows = stats_api.list_zone_queries(client, zone)
171+
if days is not None:
172+
rows = sorted(rows, key=lambda r: r.date or "")[-days:]
132173
typer.echo(
133174
render(
134175
[r.model_dump(exclude_none=True) for r in rows],

‎src/rc0/commands/zone.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ def list_cmd(
4141
) -> None:
4242
"""List zones on the account. API: GET /api/v2/zones
4343
44+
Columns: domain, type (MASTER/SLAVE), serial, dnssec (yes/no),
45+
last_check (timestamp of last zone check; '-' when the zone has
46+
never been checked).
47+
4448
Examples:
4549
4650
rc0 zone list

‎tests/integration/test_report_commands.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,77 @@ def test_nxdomains_rejects_explicit_iso_date(cli: CliRunner, isolated_config: Pa
112112
assert "today" in out and "yesterday" in out
113113

114114

115+
@respx.mock
116+
def test_nxdomains_zone_filter_keeps_matching_rows(
117+
cli: CliRunner,
118+
isolated_config: Path,
119+
) -> None:
120+
"""``--zone`` must drop rows whose domain does not match (client-side filter)."""
121+
respx.get("https://my.rcodezero.at/api/v2/reports/nxdomains").mock(
122+
return_value=httpx.Response(
123+
200,
124+
json=[
125+
{
126+
"date": "2026-04-23",
127+
"domain": "a.example.",
128+
"qname": "x",
129+
"qtype": "A",
130+
"querycount": 1,
131+
},
132+
{
133+
"date": "2026-04-23",
134+
"domain": "b.example.",
135+
"qname": "y",
136+
"qtype": "A",
137+
"querycount": 2,
138+
},
139+
{
140+
"date": "2026-04-23",
141+
"domain": "a.example.",
142+
"qname": "z",
143+
"qtype": "A",
144+
"querycount": 3,
145+
},
146+
],
147+
),
148+
)
149+
r = cli.invoke(
150+
app,
151+
["--token", "tk", "-o", "json", "report", "nxdomains", "--zone", "a.example"],
152+
)
153+
assert r.exit_code == 0, r.stdout
154+
rows = json.loads(r.stdout)
155+
assert [row["domain"] for row in rows] == ["a.example.", "a.example."]
156+
157+
158+
@respx.mock
159+
def test_nxdomains_zone_filter_ignores_trailing_dot(
160+
cli: CliRunner,
161+
isolated_config: Path,
162+
) -> None:
163+
"""Both ``example.com`` and ``example.com.`` must match the same API rows."""
164+
respx.get("https://my.rcodezero.at/api/v2/reports/nxdomains").mock(
165+
return_value=httpx.Response(
166+
200,
167+
json=[
168+
{
169+
"date": "2026-04-23",
170+
"domain": "example.com.",
171+
"qname": "x",
172+
"qtype": "A",
173+
"querycount": 1,
174+
},
175+
],
176+
),
177+
)
178+
r = cli.invoke(
179+
app,
180+
["--token", "tk", "-o", "json", "report", "nxdomains", "--zone", "example.com."],
181+
)
182+
assert r.exit_code == 0, r.stdout
183+
assert len(json.loads(r.stdout)) == 1
184+
185+
115186
@respx.mock
116187
def test_nxdomains_empty_body_returns_empty_list(cli: CliRunner, isolated_config: Path) -> None:
117188
"""Empty API body must not crash — returns [] gracefully."""

‎tests/integration/test_stats_commands.py‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,79 @@ def test_stats_non_deprecated(
7070
assert json.loads(r.stdout) == body
7171

7272

73+
@respx.mock
74+
def test_stats_queries_sends_days_param(cli: CliRunner, isolated_config: Path) -> None:
75+
"""``--days N`` must be forwarded to /stats/querycounts as a query parameter."""
76+
route = respx.get("https://my.rcodezero.at/api/v2/stats/querycounts").mock(
77+
return_value=httpx.Response(200, json=[]),
78+
)
79+
r = cli.invoke(app, ["--token", "tk", "-o", "json", "stats", "queries", "--days", "7"])
80+
assert r.exit_code == 0, r.stdout
81+
assert route.called
82+
assert dict(route.calls[0].request.url.params)["days"] == "7"
83+
84+
85+
@respx.mock
86+
def test_stats_topzones_sends_days_param(cli: CliRunner, isolated_config: Path) -> None:
87+
"""``--days N`` must be forwarded to /stats/topzones as a query parameter."""
88+
route = respx.get("https://my.rcodezero.at/api/v2/stats/topzones").mock(
89+
return_value=httpx.Response(200, json=[]),
90+
)
91+
r = cli.invoke(app, ["--token", "tk", "-o", "json", "stats", "topzones", "--days", "14"])
92+
assert r.exit_code == 0, r.stdout
93+
assert route.called
94+
assert dict(route.calls[0].request.url.params)["days"] == "14"
95+
96+
97+
@respx.mock
98+
def test_stats_queries_omits_days_when_not_provided(
99+
cli: CliRunner,
100+
isolated_config: Path,
101+
) -> None:
102+
"""Without ``--days`` the request must not send a ``days`` param (API default)."""
103+
route = respx.get("https://my.rcodezero.at/api/v2/stats/querycounts").mock(
104+
return_value=httpx.Response(200, json=[]),
105+
)
106+
r = cli.invoke(app, ["--token", "tk", "-o", "json", "stats", "queries"])
107+
assert r.exit_code == 0, r.stdout
108+
assert "days" not in dict(route.calls[0].request.url.params)
109+
110+
111+
def test_stats_queries_rejects_days_out_of_range(cli: CliRunner, isolated_config: Path) -> None:
112+
"""``--days`` must be clamped to [1, 180] by Typer validation."""
113+
r = cli.invoke(app, ["--token", "tk", "stats", "queries", "--days", "200"])
114+
assert r.exit_code == 2
115+
116+
117+
@respx.mock
118+
def test_stats_zone_queries_slices_days_client_side(
119+
cli: CliRunner,
120+
isolated_config: Path,
121+
) -> None:
122+
"""The zone-queries endpoint has no ``days`` param; ``--days`` must slice client-side."""
123+
full_history = [
124+
{"date": f"2026-04-{d:02d}", "qcount": d * 10, "nxcount": d} for d in range(1, 21)
125+
]
126+
route = respx.get("https://my.rcodezero.at/api/v2/zones/example.com/stats/queries").mock(
127+
return_value=httpx.Response(200, json=full_history),
128+
)
129+
r = cli.invoke(
130+
app,
131+
["--token", "tk", "-o", "json", "stats", "zone", "queries", "example.com", "--days", "5"],
132+
)
133+
assert r.exit_code == 0, r.stdout
134+
assert "days" not in dict(route.calls[0].request.url.params)
135+
rows = json.loads(r.stdout)
136+
assert len(rows) == 5
137+
assert [row["date"] for row in rows] == [
138+
"2026-04-16",
139+
"2026-04-17",
140+
"2026-04-18",
141+
"2026-04-19",
142+
"2026-04-20",
143+
]
144+
145+
73146
@respx.mock
74147
def test_stats_topmagnitude_emits_deprecation_warning(
75148
cli: CliRunner,

‎uv.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)