Coverage for app / util / knowledge_config.py: 93%
74 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""What of a knowledge source's config a reader may see.
3A source's ``source_config`` holds whatever its type needs, and for a
4database or an API that includes a credential: a connection string with its
5password, an auth header's value. Only someone who may change the source
6needs those (its edit form), so everyone else — every listing, a reader of
7the source's page, a repository's member list, a generation proposal — reads
8:func:`reader_config`: per type, the keys a reader may see, with addresses
9served without their userinfo, query or fragment. Listings used to send the
10whole config to anyone who could read the workspace, and the Sources page
11printed a database's connection string on its card.
13Pure, with no app imports: the response schemas apply it.
14"""
16from __future__ import annotations
18from collections.abc import Callable
19from typing import Any
20from urllib.parse import urlsplit
22#: Per source type, the config keys a reader is served. ``None`` is all of
23#: them: a website's config holds no secrets (it is in the edit history, for
24#: the same reason). A type not listed is served nothing.
25READABLE: dict[str, frozenset[str] | None] = {
26 "web": None,
27 "file": frozenset({"paths", "extensions"}),
28 "graph": frozenset({"node_count", "edge_count"}),
29 "db": frozenset(),
30 "api": frozenset({"auth_header"}),
31}
33#: Keys holding an address, served to a reader as :func:`safe_address` reads
34#: it — where the source points, never how it signs in.
35ADDRESSES: dict[str, tuple[str, ...]] = {
36 "db": ("connection_string",),
37 "api": ("endpoint",),
38}
40#: Keys an edit form never shows back (it cannot: they are secrets), so an
41#: edit that leaves them blank keeps what is stored (:func:`kept_secrets`) —
42#: as long as the key each one belongs to is still set: an API with its auth
43#: header removed has no use for the header's value.
44SECRETS: dict[str, dict[str, str]] = {
45 "api": {"auth_value": "auth_header"},
46}
49def safe_address(value: Any) -> str | None:
50 """``value`` as ``scheme://host[:port]/path``, or None when it is not a
51 URL with a host — a connection string in another form says nothing a
52 reader can be shown safely, so it is withheld whole."""
53 if not isinstance(value, str) or not value.strip():
54 return None
55 try:
56 parts = urlsplit(value.strip())
57 host = parts.hostname
58 port = parts.port
59 except ValueError:
60 return None
61 if not parts.scheme or not host:
62 return None
63 netloc = f"[{host}]" if ":" in host else host
64 if port is not None:
65 netloc = f"{netloc}:{port}"
66 return f"{parts.scheme}://{netloc}{parts.path}"
69def reader_config(source_type: Any, config: Any) -> dict:
70 """What a reader is served of ``config`` for a source of ``source_type``."""
71 if not isinstance(config, dict):
72 return {}
73 allowed = READABLE.get(
74 source_type if isinstance(source_type, str) else "", frozenset()
75 )
76 if allowed is None:
77 return dict(config)
78 shown = {key: value for key, value in config.items() if key in allowed}
79 for key in ADDRESSES.get(source_type, ()):
80 address = safe_address(config.get(key))
81 if address is not None:
82 shown[key] = address
83 return shown
86def kept_secrets(source_type: Any, config: Any, previous: Any) -> dict:
87 """``config`` with each secret the edit left blank taken from
88 ``previous`` — the edit form cannot show a stored secret, so a blank
89 one means "unchanged", never "remove it"."""
90 if not isinstance(config, dict):
91 return config
92 secrets = SECRETS.get(source_type if isinstance(source_type, str) else "", {})
93 if not secrets or not isinstance(previous, dict):
94 return config
95 kept = dict(config)
96 for key, belongs_to in secrets.items():
97 if not kept.get(key) and kept.get(belongs_to) and previous.get(key):
98 kept[key] = previous[key]
99 return kept
102# ── One line on where a source points ────────────────────────────────────────
104#: Hosts a website's summary names before "+N more".
105SUMMARY_HOSTS = 3
108def _hosts(urls: Any) -> list[str]:
109 hosts: dict[str, None] = {}
110 for url in urls if isinstance(urls, list) else []:
111 try:
112 host = urlsplit(str(url)).hostname
113 except ValueError:
114 continue
115 if host:
116 hosts.setdefault(host.removeprefix("www."), None)
117 return list(hosts)
120def _web_summary(config: dict) -> str | None:
121 hosts = _hosts(config.get("urls"))
122 if not hosts:
123 return None
124 shown = ", ".join(hosts[:SUMMARY_HOSTS])
125 more = len(hosts) - SUMMARY_HOSTS
126 return f"{shown} +{more} more" if more > 0 else shown
129def _graph_summary(config: dict) -> str | None:
130 nodes, edges = config.get("node_count"), config.get("edge_count")
131 if not isinstance(nodes, int) or not isinstance(edges, int):
132 return None
133 return (
134 f"{nodes} {'entity' if nodes == 1 else 'entities'} · "
135 f"{edges} {'relationship' if edges == 1 else 'relationships'}"
136 )
139#: Per source type, one line on where it points — never how it signs in.
140#: A type not listed (a file source, whose documents say what it holds) has
141#: none.
142SUMMARIES: dict[str, Callable[[dict], str | None]] = {
143 "web": _web_summary,
144 "db": lambda config: safe_address(config.get("connection_string")),
145 "api": lambda config: safe_address(config.get("endpoint")),
146 "graph": _graph_summary,
147}
150def summary(source_type: Any, config: Any) -> str | None:
151 """One line on where a source of ``source_type`` points, for its card."""
152 describe = SUMMARIES.get(source_type if isinstance(source_type, str) else "")
153 if describe is None or not isinstance(config, dict):
154 return None
155 return describe(config)