Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Task: The Valkey dashboard panel reads the flat INFO mapping and the keyring password (#1113)

**Issue**: [#1113](https://github.com/dan-petty/devops-cli/issues/1113)
**Scope**: scope/cli, scope/security
**Feasibility**: This check used valkey-py 6.2.0 and fakeredis 2.40.0 in the project environment. It also used the code of the release tip. `ValkeyClient.info()` returns the mapping that valkey-py parses from the INFO text. The parser drops the `# Server` and `# Memory` headings. The mapping is therefore flat.

A loopback listener answered INFO with a Valkey 8 text. The mapping then held `valkey_version` and `uptime_in_seconds` at the top level. `FakeValkey().info()` raises `unknown command 'info'`. The in-memory server cannot supply this shape. The tests therefore use a loopback listener.

`build_default_resolver` reads the keyring first and the plaintext `valkey.password` setting last. `get_valkey_password` therefore returns the keyring value when both exist. The new tests ran on the tree before the fix. The panel showed the version `unknown` and an uptime of 0. It sent no `AUTH` for a keyring-only password. It sent the plaintext password when both passwords existed.

## Description

Step E of #1113. The Valkey panel of the dashboard had two defects.

- `fetch_valkey_status` read `info["server"]`, `info["clients"]`, `info["memory"]` and `info["stats"]`. `ValkeyClient.info()` returns one flat mapping, as `devops valkey stats` and `tests/test_valkey.py` already read it. The panel therefore always showed the version `unknown` and an uptime of 0. It also showed the default values for memory, clients, commands and hit ratio.
- The panel passed the plaintext setting `valkey.password` to the client. It did not call `get_valkey_password`. A password in the keyring never reached the server.

The panel now reads each field from the flat mapping. It passes the password that `get_valkey_password` resolves.

The tests change with the code:

- `tests/test_ui_dashboard.py` no longer builds a nested INFO dictionary on a `MagicMock`. The new tests call `fetch_valkey_status` through a real `ValkeyClient`. The client talks to a loopback listener that answers INFO with a Valkey 8 text. The parser of valkey-py makes the mapping, so its shape cannot drift from the real client.
- The loopback listener moves from `tests/test_valkey.py` to `tests/support/fakes/valkey.py`, as `serving_valkey` with `bulk_reply`. Both test modules use it. The module docstring names it as the way to test INFO, because the in-memory server answers no INFO.
- `tests/test_ui_dashboard.py` uses the `mock_keyring` fixture for the whole module. The panel now reads the keyring. The test floor refuses a keyring that no test fakes.
- The offline test `test_fetch_valkey_status_failure` stays as it was.

The change builds no new code. It deletes the nested reads and calls the existing `get_valkey_password`.

## Acceptance Criteria

- [x] `fetch_valkey_status` reads a flat INFO reply (`test_fetch_valkey_status_reads_the_flat_info_the_client_returns`). The panel returns `version == "8.0.0"`, `uptime_seconds == 3600`, `used_memory == "2.40M"`, `connected_clients == 4`, `total_commands == 5000`, `hit_ratio == 80.0` and `key_count == 150`.
- [x] The first command that the panel sends is `AUTH` with the keyring password (`test_fetch_valkey_status_authenticates_with_the_keyring_password`). This holds when the keyring is the only source. It also holds when the plaintext `valkey.password` setting holds another value.
- [x] Each of the seven INFO fields and the password source has a mutation proof. A change to the key of one field fails a test of the panel. A return to `cfg.password` also fails a test of the panel.
- [x] `tests/test_ui_dashboard.py` builds no nested INFO dictionary.
- [x] `serving_valkey` and `bulk_reply` live in `tests/support/fakes/valkey.py`. `tests/test_valkey.py` and `tests/test_ui_dashboard.py` import them from there.
- [x] These commands pass: `uv run ruff check src tests`, `uv run ruff format --check src tests`, `uv run mypy src` and `uv run devops docs check`. The targeted tests of the changed modules pass.
- Pending a person: against a real Valkey 8, run `uv run devops dashboard --summary`. The Valkey Caching panel shows the version of the server, not `unknown`.
- Pending a person: set `requirepass` on that server and keep the password in the keyring. The same command then shows `Connected`. With a wrong keyring password, it shows `Offline`.

## Deliverables

- [x] Change `fetch_valkey_status` in `src/devops_cli/ui/data_providers.py`. It reads the flat INFO mapping and calls `get_valkey_password`.
- [x] Replace the nested-INFO test in `tests/test_ui_dashboard.py` with two tests over a real `ValkeyClient` and a loopback listener. Fake the keyring for the module.
- [x] Move the loopback listener to `tests/support/fakes/valkey.py`. Update `tests/test_valkey.py` and the module docstring.
- [x] Tick the dashboard step in `docs/agent/tasks/task-1113-valkey-py-replaces-the-hand-written-client.md`.
- Not done: the validated `valkey.url`, the vetted dial and the k8s URL writers (Steps B to D, later Parts of #1113).
- Not done: the shared fail-soft client (Step F, a later Part of #1113).
- Not done: the closing changelog (Step G, the last Part of #1113).
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Behaviour that changes with the library:
- Not done: one validated `valkey.url` with `--url` on the `devops valkey` commands, in place of `valkey.host`, `valkey.port` and `valkey.db` (a later Part of #1113).
- Not done: resolve a name once, check every answer and dial the checked address, under #898's resolve-and-check function (a later Part of #1113).
- Not done: build the k8s URLs with `httpx2.URL` (a later Part of #1113).
- Not done: fix the dashboard INFO reading and its plaintext password (a later Part of #1113).
- [x] Fix the dashboard INFO reading and its plaintext password. `docs/agent/tasks/task-1113-the-valkey-dashboard-panel-reads-the-real-client.md` describes this step.
- Not done: share one fail-soft client between the embeddings, library-symbol and threat-intel caches (a later Part of #1113).
- Not done: add a contract suite for the in-memory Valkey server. A recorded exchange or a local Valkey must become available first (a later Part of #1113).
- Not done: add the changelog fragment `changelog.d/1113.md`. The Part that closes #1113 adds it.
27 changes: 9 additions & 18 deletions src/devops_cli/ui/data_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
DEFAULT_VALKEY_PANEL_TIMEOUT_SECONDS,
DEFAULT_VALKEY_PORT,
)
from devops_cli.config.settings import load_settings
from devops_cli.config.settings import get_valkey_password, load_settings
from devops_cli.exceptions import DevOpsCLIError
from devops_cli.k8s.service_http import describe_endpoint
from devops_cli.models.k8s import PodEventInfo, PodInfo, node_is_ready
Expand Down Expand Up @@ -575,23 +575,14 @@ def fetch_valkey_status() -> ValkeySummary:
client = ValkeyClient(
host=endpoint,
port=int(getattr(cfg, "port", DEFAULT_VALKEY_PORT)),
password=getattr(cfg, "password", None),
password=get_valkey_password(settings),
db=int(getattr(cfg, "db", 0)),
timeout=DEFAULT_VALKEY_PANEL_TIMEOUT_SECONDS,
)
endpoint = f"{client.host}:{client.port}"
info = client.info()
server_raw = info.get("server")
server_dict: dict[str, Any] = server_raw if isinstance(server_raw, dict) else {}
clients_raw = info.get("clients")
clients_dict: dict[str, Any] = clients_raw if isinstance(clients_raw, dict) else {}
memory_raw = info.get("memory")
memory_dict: dict[str, Any] = memory_raw if isinstance(memory_raw, dict) else {}
stats_raw = info.get("stats")
stats_dict: dict[str, Any] = stats_raw if isinstance(stats_raw, dict) else {}

hits = float(stats_dict.get("keyspace_hits", 0))
misses = float(stats_dict.get("keyspace_misses", 0))
hits = float(info.get("keyspace_hits", 0))
misses = float(info.get("keyspace_misses", 0))
total_queries = hits + misses
hit_ratio = round((hits / total_queries) * 100.0, 1) if total_queries > 0 else 0.0

Expand All @@ -604,12 +595,12 @@ def fetch_valkey_status() -> ValkeySummary:
return ValkeySummary(
connected=True,
endpoint=endpoint,
version=str(server_dict.get("valkey_version", "unknown")),
uptime_seconds=int(server_dict.get("uptime_in_seconds", 0)),
used_memory=str(memory_dict.get("used_memory_human", "0M")),
version=str(info.get("valkey_version", "unknown")),
uptime_seconds=int(info.get("uptime_in_seconds", 0)),
used_memory=str(info.get("used_memory_human", "0M")),
hit_ratio=hit_ratio,
connected_clients=int(clients_dict.get("connected_clients", 0)),
total_commands=int(stats_dict.get("total_commands_processed", 0)),
connected_clients=int(info.get("connected_clients", 0)),
total_commands=int(info.get("total_commands_processed", 0)),
key_count=key_count,
)
except Exception as exc:
Expand Down
62 changes: 60 additions & 2 deletions tests/support/fakes/valkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,23 @@
holds a silent or slow server only as a connection that fails; a test of a timeout binds a
loopback listener that never answers, as the floor's `refusing_port` does for a refused port.
The pool is the fake's own, so a test of what the client's own `password`, `db` and decoding
arguments send and read binds a loopback listener that records the commands it receives.
arguments send and read binds a loopback listener that records the commands it receives. That
listener is `serving_valkey`. A test of INFO uses it too. It replies with the text of a server,
and the client's own parser turns that text into the mapping the test reads.
"""

from __future__ import annotations

from collections.abc import Iterator
import socket
import threading
from collections.abc import Iterator, Mapping
from contextlib import contextmanager

import pytest
from fakeredis import FakeServer, FakeValkey

from devops_cli.valkey.client import ValkeyClient
from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS


def valkey_client_on(server: FakeServer, *, password: str | None = None) -> ValkeyClient:
Expand All @@ -48,3 +54,55 @@ def valkey_client(valkey_server: FakeServer) -> Iterator[ValkeyClient]:
client = valkey_client_on(valkey_server)
yield client
client.close()


def bulk_reply(payload: bytes) -> bytes:
"""A RESP bulk string reply."""
return b"$%d\r\n%s\r\n" % (len(payload), payload)


def _commands_in(request: bytes) -> list[list[str]]:
"""The commands in the bytes a client sent: an array header, then a bulk string per word."""
lines = request.decode().split("\r\n")
commands: list[list[str]] = []
position = 0
while position < len(lines) and lines[position].startswith("*"):
words = int(lines[position][1:])
commands.append(lines[position + 2 : position + 1 + 2 * words : 2])
position += 1 + 2 * words
return commands


@contextmanager
def serving_valkey(
replies: Mapping[str, bytes] | None = None,
) -> Iterator[tuple[int, list[list[str]]]]:
"""A loopback server that records the commands it receives and answers each from `replies`.

`replies` maps an upper-case command name to its RESP reply; any other command is answered
+OK. The yielded record is complete once the block exits, which waits for the client to close
its connection. valkey-py announces its name and version with `CLIENT SETINFO` after it
connects; the record leaves those out.
"""
answers = replies or {}
received: list[list[str]] = []
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
listener.listen(1)

def serve() -> None:
connection, _ = listener.accept()
with connection:
while request := connection.recv(4096):
commands = _commands_in(request)
received.extend(c for c in commands if c[:2] != ["CLIENT", "SETINFO"])
connection.sendall(
b"".join(
answers.get(command[0].upper(), b"+OK\r\n") for command in commands
)
)

server = threading.Thread(target=serve, daemon=True)
server.start()
yield listener.getsockname()[1], received
server.join(timeout=THREAD_HANDOFF_BOUND_SECONDS)
73 changes: 52 additions & 21 deletions tests/test_ui_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
)
from devops_cli.ui.projections import k8s_banner
from tests.k8s_fakes import FakeCoreV1, crashlooping_pod, healthy_pod, node
from tests.support.fakes.valkey import bulk_reply, serving_valkey

pytestmark = pytest.mark.usefixtures("mock_keyring")

runner = CliRunner()

Expand Down Expand Up @@ -414,29 +417,57 @@ def test_the_review_summary_has_no_session_for_a_reviews_directory_setting_that_
assert fetch_review_status() == ReviewSummary(has_session=False)


def test_fetch_valkey_status_success() -> None:
"""fetch_valkey_status returns parsed info and hit ratios."""
mock_client = MagicMock()
mock_client.info.return_value = {
"server": {"valkey_version": "8.0.1", "uptime_in_seconds": "3600"},
"clients": {"connected_clients": "4"},
"memory": {"used_memory_human": "2.4M", "used_memory_peak_human": "4.1M"},
"stats": {
"keyspace_hits": "800",
"keyspace_misses": "200",
"total_commands_processed": "5000",
},
}
mock_client.dbsize.return_value = 150
# The text a Valkey 8 server answers to INFO: one flat list of `field:value` lines under section
# headings. valkey-py drops the headings, so the client returns one flat mapping.
_VALKEY_INFO_TEXT = (
"# Server\r\nredis_version:7.2.4\r\nserver_name:valkey\r\nvalkey_version:8.0.0\r\n"
"uptime_in_seconds:3600\r\n\r\n"
"# Clients\r\nconnected_clients:4\r\n\r\n"
"# Memory\r\nused_memory:2516582\r\nused_memory_human:2.40M\r\n\r\n"
"# Stats\r\ntotal_commands_processed:5000\r\nkeyspace_hits:800\r\nkeyspace_misses:200\r\n"
)

with patch("devops_cli.ui.data_providers.ValkeyClient", return_value=mock_client):

def test_fetch_valkey_status_reads_the_flat_info_the_client_returns(
config: Callable[..., Path],
) -> None:
"""The panel shows what a server reports: version, uptime, memory, clients, commands, hits."""
replies = {"INFO": bulk_reply(_VALKEY_INFO_TEXT.encode()), "DBSIZE": b":150\r\n"}
with serving_valkey(replies) as (port, _received):
config(valkey={"host": "127.0.0.1", "port": port})
summary = fetch_valkey_status()
assert isinstance(summary, ValkeySummary)
assert summary.connected is True
assert summary.version == "8.0.1"
assert summary.used_memory == "2.4M"
assert summary.hit_ratio == 80.0
assert summary.key_count == 150

assert summary == ValkeySummary(
connected=True,
endpoint=f"127.0.0.1:{port}",
version="8.0.0",
uptime_seconds=3600,
used_memory="2.40M",
hit_ratio=80.0,
connected_clients=4,
total_commands=5000,
key_count=150,
)


@pytest.mark.parametrize(
"plaintext_password",
[
pytest.param(None, id="keyring-only"),
pytest.param("plaintext-password", id="keyring-over-plaintext-setting"),
],
)
def test_fetch_valkey_status_authenticates_with_the_keyring_password(
config: Callable[..., Path], mock_keyring: Any, plaintext_password: str | None
) -> None:
"""The panel sends the password `get_valkey_password` resolves, never the plaintext setting."""
mock_keyring.values["valkey_password"] = "keyring-password"
valkey_settings = {"host": "127.0.0.1", "password": plaintext_password}
with serving_valkey({"INFO": bulk_reply(_VALKEY_INFO_TEXT.encode())}) as (port, received):
config(valkey={**valkey_settings, "port": port})
fetch_valkey_status()

assert received[0] == ["AUTH", "keyring-password"]


def test_fetch_valkey_status_failure() -> None:
Expand Down
Loading
Loading