From ea0a266515f697acb6a0000a53133d12a91f6e0c Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Wed, 11 Nov 2026 03:02:35 -0600 Subject: [PATCH 1/3] feat(view): dashboard sheets by consumer folder, through one shared folder walk (LD-1) Dashboard folders mirror report-spec consumer folders: a root RootCollection::DashboardSheets (PYEGERIA_DASHBOARD_ROOT) holds one DashboardFolder::Consumer:: CollectionFolder per consumer, sub-folders allowed; members are the sheets' Dashboard elements, and a sheet may sit in several consumer folders. - pyegeria/view/egeria_folders.py: the folder walk and the consumer-tree read, lifted out of egeria_spec_cache and parametrised by root QN, consumer prefix and a member predicate. Cycle-safe, depth-capped, never up to the root or across into a sibling consumer; a folder whose read failed says so, never reads as empty. Walk.paths records where each member was found. - egeria_spec_cache uses it with no behaviour change (its private names stay as thin wrappers); its consumer-folder and tier tests are unchanged and pass. - dashboards: list_dashboard_sheets(client, folders=None) and list_dashboard_sheets_for_viewer take configured folders (PYEGERIA_DASHBOARD_FOLDERS, else config.json "Pyegeria Dashboard Folders"): only the sheets in them, recursive inside the consumer folder, each tagged with folders and used_by. With none configured: every Dashboard:: sheet as before, plus the note "no dashboard folders configured: listing every Dashboard:: sheet". The result is a DashboardSheetListing (a list, so callers keep working) carrying notes and per-folder status; a folder not found or unreadable is stated. - build_dashboard_consumer_index / read_dashboard_consumer_index: the report-spec consumer index's shape over the dashboard tree. - Tests: the dashboard fake (shapes checked live 2026-11-09) plus the collection reads; sheets written by the real writer. Recursion and tags, a sheet in two consumers, a sub-folder's consumer, env config, folder not found, unreadable folder and sub-folder, sibling and root never followed, a cycle, the depth cap, the member predicate, the consumer index (read, root missing, partial). Signed-off-by: Dan Wolfson --- pyegeria/core/config.py | 4 + pyegeria/view/dashboard_resolver.py | 11 +- pyegeria/view/dashboards.py | 196 ++++++++++++- pyegeria/view/egeria_folders.py | 288 ++++++++++++++++++++ pyegeria/view/egeria_spec_cache.py | 211 ++------------ tests/micro-tests/test_dashboard_folders.py | 214 +++++++++++++++ 6 files changed, 726 insertions(+), 198 deletions(-) create mode 100644 pyegeria/view/egeria_folders.py create mode 100644 tests/micro-tests/test_dashboard_folders.py diff --git a/pyegeria/core/config.py b/pyegeria/core/config.py index eeae6b04..1995bc12 100644 --- a/pyegeria/core/config.py +++ b/pyegeria/core/config.py @@ -150,6 +150,10 @@ class EnvironmentConfig(BaseModel): # RS-EGERIA-TIER stage 1). PYEGERIA_REPORT_SPEC_FOLDERS (comma-separated) overrides it. # Empty by default: a sync never takes "every ReportSpec visible". pyegeria_report_spec_folders: List[str] = Field(default_factory=list, alias="Pyegeria Report Spec Folders") + # Dashboard folders (LD-1): CollectionFolder qualified names whose Dashboard sheets a listing + # shows, e.g. "DashboardFolder::Consumer::Portal". PYEGERIA_DASHBOARD_FOLDERS (comma-separated) + # overrides it. Empty means every Dashboard:: sheet, and the listing says so. + pyegeria_dashboard_folders: List[str] = Field(default_factory=list, alias="Pyegeria Dashboard Folders") model_config = ConfigDict(populate_by_name=True, extra='allow') diff --git a/pyegeria/view/dashboard_resolver.py b/pyegeria/view/dashboard_resolver.py index 84bd799a..5d3fbbc2 100644 --- a/pyegeria/view/dashboard_resolver.py +++ b/pyegeria/view/dashboard_resolver.py @@ -374,12 +374,13 @@ async def _text(base=base, p=p): return resolved -async def async_list_dashboard_sheets_for_viewer(client: Any) -> List[Any]: +async def async_list_dashboard_sheets_for_viewer(client: Any, folders: Optional[List[str]] = None) -> List[Any]: """The sheets Egeria holds that the viewer `client` is signed in as can see. Listing is per viewer: a sheet in a zone they cannot see is not listed, so an app caching this keys it by the viewer's - credential identity, never a shared key.""" + credential identity, never a shared key. `folders` (else the configured dashboard folders) scopes it + as `async_list_dashboard_sheets` does; the result is its DashboardSheetListing, notes included.""" from pyegeria.view.dashboards import async_list_dashboard_sheets - return await async_list_dashboard_sheets(client) + return await async_list_dashboard_sheets(client, folders) def resolve_dashboard_sheet(client: Any, name: str, *, perspective: Optional[str] = None, run: bool = False, @@ -400,7 +401,7 @@ def resolve_sheet(client: Any, sheet: Any, *, perspective: Optional[str] = None, check_spec_visibility=check_spec_visibility)) -def list_dashboard_sheets_for_viewer(client: Any) -> List[Any]: +def list_dashboard_sheets_for_viewer(client: Any, folders: Optional[List[str]] = None) -> List[Any]: """Sync form of async_list_dashboard_sheets_for_viewer.""" from pyegeria.core.async_runner import run_sync - return run_sync(async_list_dashboard_sheets_for_viewer(client)) + return run_sync(async_list_dashboard_sheets_for_viewer(client, folders)) diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py index 2d8dac69..fe1e0cd6 100644 --- a/pyegeria/view/dashboards.py +++ b/pyegeria/view/dashboards.py @@ -6,7 +6,16 @@ (report-spec pipeline note v5.5 §8d / §10.6(c); BRIEF RS-DASH PR-2). load_dashboard_sheet(name) -> the sheet, read from its Egeria element chain, or None - list_dashboard_sheets() -> every sheet held in Egeria (Dashboard::* elements) + list_dashboard_sheets() -> the sheets in the configured dashboard folders; with none configured, + every sheet held in Egeria (Dashboard::* elements), and it says so + read_dashboard_consumer_index() -> {sheet: [consumer, ...]} over the dashboard folder tree + +Dashboard folders (LD-1) mirror report-spec consumer folders: a root `RootCollection::DashboardSheets` +(PYEGERIA_DASHBOARD_ROOT) holds one `DashboardFolder::Consumer::` CollectionFolder per consumer +(Portal, EgeriaAdvisor, ...), sub-folders allowed; a sheet's `Dashboard` element is the member, and one +sheet may sit in several consumer folders. Which folders a listing takes: PYEGERIA_DASHBOARD_FOLDERS +(comma-separated), else config.json's "Pyegeria Dashboard Folders". The walk is egeria_folders', the +same one the report-spec cache uses. Both return today's `DashboardSheet` / `Placement` model, so a consumer keeps its code. The objects are the subclasses `EgeriaDashboardSheet` / `EgeriaPlacement`, which add only what an Egeria-held sheet must say: @@ -41,6 +50,7 @@ from __future__ import annotations import argparse +import asyncio import os import sys from typing import Any, Dict, List, Literal, Optional @@ -52,12 +62,16 @@ DASHBOARD_QN_PREFIX, DashboardSheetEgeriaWriter, _default_store_path, _load_store, dashboard_qn, perspective_qualified_name, sheet_name_from_dashboard_qn, ) +from pyegeria.view import egeria_folders as _folders from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict, Placement __all__ = [ - "EgeriaDashboardSheet", "EgeriaPlacement", "REPORT_LINK_MISSING", "as_local_model", - "async_list_dashboard_sheets", "async_load_dashboard_sheet", "async_migrate_dashboard_sheets", - "async_resolve_dashboard_sheet", "list_dashboard_sheets", "load_dashboard_sheet", "main", + "DASHBOARD_CONSUMER_PREFIX", "DASHBOARD_CONSUMERS_FORMAT", "DASHBOARD_FOLDERS_ENV", "DASHBOARD_ROOT_ENV", + "DEFAULT_DASHBOARD_ROOT", "DashboardSheetListing", "EgeriaDashboardSheet", "EgeriaPlacement", + "NO_FOLDERS_NOTE", "REPORT_LINK_MISSING", "as_local_model", "async_list_dashboard_sheets", + "async_load_dashboard_sheet", "async_migrate_dashboard_sheets", "async_resolve_dashboard_sheet", + "build_dashboard_consumer_index", "configured_dashboard_folders", "configured_dashboard_root", + "list_dashboard_sheets", "load_dashboard_sheet", "main", "read_dashboard_consumer_index", "read_sheet_from_chain", "resolve_dashboard_sheet", ] @@ -66,6 +80,13 @@ _SPANS = ("1", "2", "full") _STYLES = ("kpi", "panel") +DASHBOARD_ROOT_ENV = "PYEGERIA_DASHBOARD_ROOT" +DEFAULT_DASHBOARD_ROOT = "RootCollection::DashboardSheets" +DASHBOARD_CONSUMER_PREFIX = "DashboardFolder::Consumer::" +DASHBOARD_FOLDERS_ENV = "PYEGERIA_DASHBOARD_FOLDERS" +DASHBOARD_CONSUMERS_FORMAT = "pyegeria-dashboard-consumers/1" +NO_FOLDERS_NOTE = "no dashboard folders configured: listing every Dashboard:: sheet" + class EgeriaPlacement(Placement): """A Placement read from Egeria. `kind`: "report", "text", or "missing" (a report placement whose @@ -85,6 +106,25 @@ class EgeriaDashboardSheet(DashboardSheet): source: str = "egeria" guid: Optional[str] = None breaks: List[str] = Field(default_factory=list) + #: The configured dashboard folders the sheet was found in (empty for an unfiltered listing). + folders: List[str] = Field(default_factory=list) + #: The consumers those folders belong to (`DashboardFolder::Consumer::`). + used_by: List[str] = Field(default_factory=list) + + +class DashboardSheetListing(list): + """The sheets a listing found (a plain list, so existing callers keep working), and how it read them. + + `notes` says what the reader should know: no folders configured, a folder not found or not readable, + a sub-folder the walk could not read. `folders` has one entry per configured folder: its + `qualifiedName`, `status` ("read", "partial", "not found", "not read"), `reason` and `sheets`. A + folder that could not be read is never reported as an empty one.""" + + def __init__(self, sheets: Any = (), *, notes: Optional[List[str]] = None, + folders: Optional[List[Dict[str, Any]]] = None) -> None: + super().__init__(sheets) + self.notes: List[str] = list(notes or []) + self.folders: List[Dict[str, Any]] = list(folders or []) def as_local_model(sheet: DashboardSheet) -> DashboardSheet: @@ -252,9 +292,7 @@ async def _dashboard_elements(client: Any) -> List[Dict[str, Any]]: start += len(items) -async def async_list_dashboard_sheets(client: Any) -> List[EgeriaDashboardSheet]: - """Every sheet held in Egeria, by name. A Dashboard whose chain is broken (for example one made with - plain `Create Dashboard`) is listed with its `breaks`, not dropped.""" +async def _all_sheets(client: Any) -> List[EgeriaDashboardSheet]: sheets: List[EgeriaDashboardSheet] = [] seen = set() for element in await _dashboard_elements(client): @@ -269,6 +307,131 @@ async def async_list_dashboard_sheets(client: Any) -> List[EgeriaDashboardSheet] return sheets +def configured_dashboard_folders() -> List[str]: + """The folders a listing takes: PYEGERIA_DASHBOARD_FOLDERS (comma-separated qualified names), else + config.json's "Pyegeria Dashboard Folders". Empty by default.""" + env_val = os.getenv(DASHBOARD_FOLDERS_ENV) + if env_val is not None: + return [p.strip() for p in env_val.split(",") if p.strip()] + try: + from pyegeria.core.config import settings + return list(getattr(settings.Environment, "pyegeria_dashboard_folders", None) or []) + except Exception: # noqa: BLE001 -- settings may not load in every context; then nothing is configured + return [] + + +def configured_dashboard_root() -> str: + """The root of the dashboard folder tree: PYEGERIA_DASHBOARD_ROOT, else RootCollection::DashboardSheets.""" + return (os.getenv(DASHBOARD_ROOT_ENV) or "").strip() or DEFAULT_DASHBOARD_ROOT + + +def _is_dashboard_member(el: Dict[str, Any]) -> bool: + """A sheet's Dashboard element: type Dashboard, qualifiedName Dashboard::.""" + qn = (el.get("properties") or {}).get("qualifiedName") or "" + return "Dashboard" in _folders._type_names(el) and bool(sheet_name_from_dashboard_qn(qn)) + + +def _used_by(folder: Dict[str, Any]) -> List[str]: + """The consumer a configured folder belongs to: its own name if it is a consumer folder, the consumer + segment of its qualified name if it is a sub-folder of one, else none.""" + qn = (folder.get("properties") or {}).get("qualifiedName") or "" + if _folders.is_top_consumer_qn(qn, DASHBOARD_CONSUMER_PREFIX): + return [_folders.consumer_name(folder, DASHBOARD_CONSUMER_PREFIX)] + if _folders.is_consumer_qn(qn, DASHBOARD_CONSUMER_PREFIX): + return [qn[len(DASHBOARD_CONSUMER_PREFIX):].split("::", 1)[0]] + return [] + + +def _walk_dashboard_folders(client: Any, folder_qns: List[str], depth_cap: int): + """Read each configured folder (recursively, inside its consumer) and gather its Dashboard members. + Synchronous, like the report-spec cache's walk: callers in a loop run it in a worker thread. + + Returns ({sheet name: {"element", "folders", "used_by"}}, notes, per-folder status).""" + found: Dict[str, Dict[str, Any]] = {} + notes: List[str] = [] + status: List[Dict[str, Any]] = [] + identity = _folders.client_identity(client) + stop = [configured_dashboard_root()] + for qn in folder_qns: + entry: Dict[str, Any] = {"qualifiedName": qn, "status": "read", "reason": None, "sheets": 0} + status.append(entry) + try: + folder = _folders.find_folder(client, qn) + except Exception as exc: # noqa: BLE001 -- one folder failing must not hide the others + entry.update(status="not read", reason=f"could not be read: {exc}") + notes.append(f"{qn}: {entry['reason']}") + continue + if folder is None: + entry.update(status="not found", reason=f"not found, or not visible to {identity}") + notes.append(f"{qn}: {entry['reason']}") + continue + try: + walk = _folders.walk_folder(client, folder, recursive=True, consumer_prefix=DASHBOARD_CONSUMER_PREFIX, + depth_cap=depth_cap, stop_qns=stop, member=_is_dashboard_member) + except Exception as exc: # noqa: BLE001 + entry.update(status="not read", reason=f"its members could not be read: {exc}") + notes.append(f"{qn}: {entry['reason']}") + continue + problems = [f"{p}: {e}" for p, e in walk.errors] + if walk.capped: + problems.append(f"depth cap reached ({depth_cap} levels); not read: " + ", ".join(walk.capped)) + if problems: + entry.update(status="partial", reason="; ".join(problems)) + notes.append(f"{qn}: not fully read: {entry['reason']}") + notes.extend(f"{qn}: {p} not visible or not found" for p, _e in walk.gone) + used_by = _used_by(folder) + names = set() + for m in walk.members: + name = sheet_name_from_dashboard_qn((m.get("properties") or {}).get("qualifiedName") or "") + hit = found.setdefault(name, {"element": m, "folders": [], "used_by": []}) + if qn not in hit["folders"]: + hit["folders"].append(qn) + hit["used_by"].extend(u for u in used_by if u not in hit["used_by"]) + names.add(name) + entry["sheets"] = len(names) + return found, notes, status + + +async def async_list_dashboard_sheets(client: Any, folders: Optional[List[str]] = None, *, + depth_cap: int = _folders.DEPTH_CAP) -> DashboardSheetListing: + """The sheets held in Egeria, by name, as a DashboardSheetListing. + + `folders` (else `configured_dashboard_folders()`): only the sheets in those CollectionFolders, followed + recursively inside their consumer folder, each tagged with `folders` and `used_by`; a folder not found + or not readable is named in `notes` and `folders`, never shown as empty. With no folders: every + `Dashboard::` sheet, as before, and `notes` says that is what it is. A Dashboard whose chain is broken + (for example one made with plain `Create Dashboard`) is listed with its `breaks`, not dropped.""" + chosen = configured_dashboard_folders() if folders is None else [f for f in folders if f] + if not chosen: + return DashboardSheetListing(await _all_sheets(client), notes=[NO_FOLDERS_NOTE]) + found, notes, status = await asyncio.to_thread(_walk_dashboard_folders, client, chosen, depth_cap) + sheets: List[EgeriaDashboardSheet] = [] + for name in sorted(found, key=str.lower): + hit = found[name] + sheet = await read_sheet_from_chain(client, name, dashboard=hit["element"]) + if sheet is None: + notes.append(f"{name}: in {', '.join(hit['folders'])}, but its Dashboard could not be read") + continue + sheet.folders, sheet.used_by = list(hit["folders"]), sorted(hit["used_by"]) + sheets.append(sheet) + return DashboardSheetListing(sheets, notes=notes, folders=status) + + +def _sheet_key(m: Dict[str, Any], consumer: str, notes: List[str]) -> Optional[str]: + return sheet_name_from_dashboard_qn((m.get("properties") or {}).get("qualifiedName") or "") + + +def build_dashboard_consumer_index(client: Any, *, root: Optional[str] = None, + depth_cap: int = _folders.DEPTH_CAP) -> Dict[str, Any]: + """Read the dashboard folder tree once: `{sheet: [consumer, ...]}` with how it was read, in the shape of + the report-spec consumer index (`status` read / partial / not read, `consumers`, `notes`; each consumer + entry counts its `sheets`). A tree that could not be read is "not read" with a reason, never empty.""" + return _folders.read_consumer_tree(client, root_qn=root or configured_dashboard_root(), + consumer_prefix=DASHBOARD_CONSUMER_PREFIX, key=_sheet_key, + fmt=DASHBOARD_CONSUMERS_FORMAT, depth_cap=depth_cap, + member=_is_dashboard_member, count_field="sheets") + + def _client_from_env() -> Any: """An EgeriaTech client from the environment (EGERIA_VIEW_SERVER, EGERIA_VIEW_SERVER_URL or EGERIA_PLATFORM_URL, EGERIA_USER / EGERIA_USER_PASSWORD, else pyegeria's settings), not yet signed in.""" @@ -296,15 +459,30 @@ async def _go(): return run_sync(_go()) -def list_dashboard_sheets(client: Any = None) -> List[EgeriaDashboardSheet]: +def list_dashboard_sheets(client: Any = None, folders: Optional[List[str]] = None) -> DashboardSheetListing: """Sync form of async_list_dashboard_sheets. With no client, one is made from the environment.""" from pyegeria.core.async_runner import run_sync async def _go(): - return await async_list_dashboard_sheets(client or await _signed_in_client()) + return await async_list_dashboard_sheets(client or await _signed_in_client(), folders) return run_sync(_go()) +def read_dashboard_consumer_index(client: Any = None, *, root: Optional[str] = None, + depth_cap: int = _folders.DEPTH_CAP) -> Dict[str, Any]: + """The dashboard consumer index, read from Egeria now (sheets have no local cache to read it from). + With no client, one is made from the environment; a failure to sign in is "not read", with its reason.""" + if client is None: + from pyegeria.core.async_runner import run_sync + try: + client = run_sync(_signed_in_client()) + except Exception as exc: # noqa: BLE001 -- said in the result, never an empty index + return {"format": DASHBOARD_CONSUMERS_FORMAT, "root": root or configured_dashboard_root(), + "status": "not read", "reason": f"could not sign in to Egeria: {exc}", "consumers": [], + "index": {}, "notes": []} + return build_dashboard_consumer_index(client, root=root, depth_cap=depth_cap) + + # ---------------------------------------------------------------------------- the data step (B4 / D4) async def async_resolve_dashboard_sheet(client: Any, name: str, **kwargs: Any): diff --git a/pyegeria/view/egeria_folders.py b/pyegeria/view/egeria_folders.py new file mode 100644 index 00000000..5ed28f0a --- /dev/null +++ b/pyegeria/view/egeria_folders.py @@ -0,0 +1,288 @@ +""" +SPDX-License-Identifier: Apache-2.0 +Copyright Contributors to the ODPi Egeria project. + +Consumer-folder trees held in Egeria: one walk, shared by report specs and dashboard sheets. + +The convention (report-spec consumer folders, phases 1-2; dashboard folders, LD-1): + + a RootCollection, e.g. RootCollection::ReportSpecs + one CollectionFolder per consuming tool, e.g. + :: ... ReportSpecFolder::Consumer::Portal; sub-folders allowed + members what the tree publishes (ReportSpec, Dashboard, ...) + +A walk goes DOWN inside one consumer folder: CollectionFolder members are followed (cycle-safe: a GUID +is read once; depth-capped), and it never goes up to a RootCollection or across into a sibling +consumer folder. "Unread is not empty": a folder whose members could not be read is named with its +reason, never treated as a folder with no members. + +Parametrised by the root's qualified name, the consumer prefix, and (optionally) a member predicate +choosing which non-folder members count. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +__all__ = [ + "DEPTH_CAP", + "Walk", + "consumer_name", + "find_folder", + "is_consumer_qn", + "is_folder", + "is_gone_error", + "is_top_consumer_qn", + "read_consumer_tree", + "walk_folder", +] + +DEPTH_CAP = 5 + +MemberPredicate = Callable[[Dict[str, Any]], bool] +#: Given a member, its consumer's name and the notes list: the key it is indexed under, or None to +#: leave it out (append a note to say why, when the reader should know). +MemberKey = Callable[[Dict[str, Any], str, List[str]], Optional[str]] + + +# ── Element shapes ── + +def _now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _header(el: Dict[str, Any]) -> Dict[str, Any]: + return el.get("elementHeader") or {} + + +def _guid(el: Dict[str, Any]) -> str: + return _header(el).get("guid") or "" + + +def _type_names(el: Dict[str, Any]) -> List[str]: + t = _header(el).get("type") or {} + return [t.get("typeName") or ""] + list(t.get("superTypeNames") or []) + + +def _props(el: Dict[str, Any]) -> Dict[str, Any]: + return el.get("properties") or {} + + +def _elements(result: Any) -> List[Dict[str, Any]]: + if isinstance(result, dict): + result = [result] + if not isinstance(result, list): + return [] + return [e for e in result if isinstance(e, dict)] + + +def _call(fn, *args, **kwargs): + """Call a client method; an Egeria 'nothing found' string becomes an empty list.""" + result = fn(*args, **kwargs) + return _elements(result) + + +def client_identity(client) -> str: + return str(getattr(client, "user_id", "") or "?") + + +# ── Names ── + +def is_consumer_qn(qn: str, prefix: str) -> bool: + """A consumer folder or a folder inside one (its qualified name starts with `prefix`).""" + return bool(qn) and qn.startswith(prefix) and len(qn) > len(prefix) + + +def is_top_consumer_qn(qn: str, prefix: str) -> bool: + """A consumer folder itself (``), not a sub-folder.""" + return is_consumer_qn(qn, prefix) and "::" not in qn[len(prefix):] + + +def consumer_name(el: Dict[str, Any], prefix: str) -> str: + """A consumer folder's name: its displayName, else the qualified name after the prefix.""" + props = _props(el) + qn = props.get("qualifiedName") or "" + tail = qn[len(prefix):] if is_consumer_qn(qn, prefix) else qn + return props.get("displayName") or tail or _guid(el) + + +def is_folder(el: Dict[str, Any]) -> bool: + return "CollectionFolder" in _type_names(el) + + +# ── Reads ── + +def find_folder(client, qn: str) -> Optional[Dict[str, Any]]: + """The CollectionFolder whose qualified name is exactly `qn`, or None.""" + found = _call(client.get_collections_by_name, qn, metadata_element_type="CollectionFolder", + output_format="JSON") + exact = [e for e in found if _props(e).get("qualifiedName") == qn] + return exact[0] if exact else None + + +def is_gone_error(exc: BaseException) -> bool: + """A read refused because the element is not visible to the caller, or not found: the folder is + gone for this reader. Anything else (timeout, 5xx, refused connection) is a genuine error.""" + try: + from pyegeria.view.dashboard_resolver import ( + _is_not_found_error, + is_not_visible_error, + ) + return bool(is_not_visible_error(exc) or _is_not_found_error(exc)) + except Exception: # noqa: BLE001 -- if the classifiers cannot load, keep what was read (the safe side) + return False + + +@dataclass +class Walk: + """What a walk of one folder (and, when recursive, the folders inside it) found.""" + members: List[Dict[str, Any]] = field(default_factory=list) # every non-folder member, once per GUID + read: List[str] = field(default_factory=list) # folders read, "Top / Sub" paths + capped: List[str] = field(default_factory=list) # sub-folders the depth cap stopped + not_followed: List[Tuple[str, str]] = field(default_factory=list) + errors: List[Tuple[str, str]] = field(default_factory=list) # sub-folders whose members could not be read + gone: List[Tuple[str, str]] = field(default_factory=list) # sub-folders not visible or not found + #: Every non-folder member's folder paths, by GUID: where in the tree each was found. + paths: Dict[str, List[str]] = field(default_factory=dict) + + +def walk_folder(client, folder: Dict[str, Any], *, recursive: bool, consumer_prefix: str, + depth_cap: int = DEPTH_CAP, stop_qns: Iterable[str] = (), + member: Optional[MemberPredicate] = None) -> Walk: + """Read `folder`'s members; when `recursive`, follow CollectionFolder members downwards. + + Only CollectionFolder members are followed. A GUID is read at most once (the cycle guard); a + folder deeper than `depth_cap` below `folder` is not read and is named in `capped`. A member + that is a RootCollection, a consumer folder (under `consumer_prefix`) other than this one, or a + qualified name in `stop_qns` is never followed: the walk goes down inside one consumer, never up + to the root or across into a sibling. `member`, when given, chooses which non-folder members + count. The top folder's members are read without a guard, so an error there raises to the + caller; an error in a sub-folder is recorded in `errors` (or `gone`, when the folder is not + visible to the reader or no longer exists).""" + top_qn = _props(folder).get("qualifiedName") or _guid(folder) + stops = set(stop_qns) - {top_qn} + w = Walk() + seen = {_guid(folder)} + member_guids: set = set() + queue: List[Tuple[Dict[str, Any], int, str]] = [(folder, 0, top_qn)] + while queue: + current, depth, path = queue.pop(0) + if depth == 0: + listed = _call(client.get_collection_members, collection_guid=_guid(current), output_format="JSON") + else: + try: + listed = _call(client.get_collection_members, collection_guid=_guid(current), + output_format="JSON") + except Exception as exc: # noqa: BLE001 + if is_gone_error(exc): + # Not visible (zoned away from the reader) or deleted: what it held is no longer + # published through this folder, so it is pruned, never kept as "unread". + w.gone.append((path, str(exc))) + else: # a genuine error (timeout, 5xx): an outage must not unpublish the consumer + w.errors.append((path, str(exc))) + continue + w.read.append(path) + for m in listed: + g = _guid(m) + if not g: + continue + is_root = "RootCollection" in _type_names(m) + if not (recursive and (is_folder(m) or is_root)): + if member is not None and not member(m): + continue + w.paths.setdefault(g, []) + if path not in w.paths[g]: + w.paths[g].append(path) + if g not in member_guids: + member_guids.add(g) + w.members.append(m) + continue + qn = _props(m).get("qualifiedName") or g + sub_path = f"{path} / {qn}" + if is_root: + w.not_followed.append((sub_path, "a RootCollection; the walk never goes up to the root")) + elif g in seen: + w.not_followed.append((sub_path, "already read (a cycle, or a second path to the same folder)")) + elif qn in stops or (is_top_consumer_qn(qn, consumer_prefix) and qn != top_qn): + w.not_followed.append((sub_path, "another consumer folder; the walk never goes across")) + elif depth + 1 > depth_cap: + w.capped.append(sub_path) + else: + seen.add(g) + queue.append((m, depth + 1, sub_path)) + return w + + +def _not_read(out: Dict[str, Any], reason: str) -> Dict[str, Any]: + out.update(status="not read", reason=reason, consumers=[], index={}) + return out + + +def read_consumer_tree(client, *, root_qn: str, consumer_prefix: str, key: MemberKey, fmt: str, + depth_cap: int = DEPTH_CAP, member: Optional[MemberPredicate] = None, + count_field: str = "members") -> Dict[str, Any]: + """Read a consumer-folder tree once and return `{key: [consumer, ...]}` with how it was read. + + The root is a RootCollection; each CollectionFolder member is one consumer, named by its + displayName. Each consumer folder is walked recursively (cycle-safe, `depth_cap`, never into a + sibling). `key` turns a member into the key it is indexed under (or None to leave it out). + + `status` is "read"; "partial" (some consumer folders were not fully read: `reason` and each + consumer's own `status` say which); or "not read" (the root itself could not be read: `index` + is empty and must never be shown as "used by none"). `consumers` lists every consumer folder, + read or not, so a reader can claim "used by none" only against a fully read tree. Each consumer + entry carries `count_field`: how many keys it holds.""" + identity = client_identity(client) + out: Dict[str, Any] = {"format": fmt, "root": root_qn, "read_at": _now(), "read_as": identity, + "status": "read", "reason": None, "consumers": [], "index": {}, "notes": []} + try: + found = _call(client.get_collections_by_name, root_qn, metadata_element_type="RootCollection", + output_format="JSON") + except Exception as exc: # noqa: BLE001 + return _not_read(out, f"the root {root_qn} could not be read: {exc}") + roots = [e for e in found if _props(e).get("qualifiedName") == root_qn] + if not roots: + return _not_read(out, f"the root {root_qn} was not found, or is not visible to {identity}") + try: + listed = _call(client.get_collection_members, collection_guid=_guid(roots[0]), output_format="JSON") + except Exception as exc: # noqa: BLE001 + return _not_read(out, f"the members of the root {root_qn} could not be read: {exc}") + folders = [m for m in listed if is_folder(m)] + out["notes"].extend(f"{_props(m).get('qualifiedName') or _guid(m)}: a member of the root that is not a " + f"CollectionFolder, so not a consumer" for m in listed if not is_folder(m)) + stop = [_props(f).get("qualifiedName") or "" for f in folders] + [root_qn] + index: Dict[str, List[str]] = {} + unread: List[str] = [] + for f in sorted(folders, key=lambda el: consumer_name(el, consumer_prefix)): + name = consumer_name(f, consumer_prefix) + entry = {"name": name, "qualifiedName": _props(f).get("qualifiedName"), "guid": _guid(f), + "status": "read", "reason": None, count_field: 0} + out["consumers"].append(entry) + try: + walk = walk_folder(client, f, recursive=True, consumer_prefix=consumer_prefix, depth_cap=depth_cap, + stop_qns=stop, member=member) + except Exception as exc: # noqa: BLE001 + entry.update(status="not read", reason=str(exc)) + unread.append(name) + continue + problems = [f"{p}: {e}" for p, e in walk.errors] + out["notes"].extend(f"{name}: {p} not visible or not found" for p, _e in walk.gone) + if walk.capped: + problems.append(f"depth cap reached ({depth_cap} levels); not read: " + ", ".join(walk.capped)) + if problems: + entry.update(status="partial", reason="; ".join(problems)) + unread.append(name) + keys = set() + for m in walk.members: + k = key(m, name, out["notes"]) + if k: + keys.add(k) + for k in keys: + index.setdefault(k, []).append(name) + entry[count_field] = len(keys) + out["index"] = {k: sorted(v) for k, v in sorted(index.items())} + if unread: + out.update(status="partial", reason="not fully read: " + ", ".join(unread)) + return out diff --git a/pyegeria/view/egeria_spec_cache.py b/pyegeria/view/egeria_spec_cache.py index bc88a2ca..0fe753f0 100644 --- a/pyegeria/view/egeria_spec_cache.py +++ b/pyegeria/view/egeria_spec_cache.py @@ -39,6 +39,9 @@ from loguru import logger +from pyegeria.view import egeria_folders as _folders +from pyegeria.view.egeria_folders import _call, _elements, _guid, _header, _props, _type_names + __all__ = [ "CACHE_DIR_ENV", "FOLDERS_ENV", @@ -195,12 +198,12 @@ def configured_root() -> str: def _is_consumer_qn(qn: str) -> bool: """A consumer folder or a folder inside one (its qualified name starts with the prefix).""" - return bool(qn) and qn.startswith(CONSUMER_PREFIX) and len(qn) > len(CONSUMER_PREFIX) + return _folders.is_consumer_qn(qn, CONSUMER_PREFIX) def _is_top_consumer_qn(qn: str) -> bool: """A consumer folder itself (`ReportSpecFolder::Consumer::`), not a sub-folder.""" - return _is_consumer_qn(qn) and "::" not in qn[len(CONSUMER_PREFIX):] + return _folders.is_top_consumer_qn(qn, CONSUMER_PREFIX) # ── Files ── @@ -301,14 +304,6 @@ def _now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") -def _header(el: Dict[str, Any]) -> Dict[str, Any]: - return el.get("elementHeader") or {} - - -def _guid(el: Dict[str, Any]) -> str: - return _header(el).get("guid") or "" - - def _version(el: Dict[str, Any]) -> int: v = (_header(el).get("versions") or {}).get("version") try: @@ -317,15 +312,6 @@ def _version(el: Dict[str, Any]) -> int: return 0 -def _type_names(el: Dict[str, Any]) -> List[str]: - t = _header(el).get("type") or {} - return [t.get("typeName") or ""] + list(t.get("superTypeNames") or []) - - -def _props(el: Dict[str, Any]) -> Dict[str, Any]: - return el.get("properties") or {} - - def _zones(el: Dict[str, Any]) -> List[str]: """The governance zones on an element. In Egeria 6.2 ZoneMembership is its own header key (`elementHeader.zoneMembership.classificationProperties.zoneMembership`), not an entry of @@ -349,14 +335,6 @@ def _zones(el: Dict[str, Any]) -> List[str]: ZONED_REASON = "zoned: not synced into a shared cache (until B6's public-only read)" -def _elements(result: Any) -> List[Dict[str, Any]]: - if isinstance(result, dict): - result = [result] - if not isinstance(result, list): - return [] - return [e for e in result if isinstance(e, dict)] - - @dataclass class _Built: label: str @@ -567,17 +545,8 @@ def render(self) -> str: return "\n".join(lines) -def _call(fn, *args, **kwargs): - """Call a client method; an Egeria 'nothing found' string becomes an empty list.""" - result = fn(*args, **kwargs) - return _elements(result) - - def _find_folder(client, qn: str) -> Optional[Dict[str, Any]]: - found = _call(client.get_collections_by_name, qn, metadata_element_type="CollectionFolder", - output_format="JSON") - exact = [e for e in found if _props(e).get("qualifiedName") == qn] - return exact[0] if exact else None + return _folders.find_folder(client, qn) def _find_specs_by_label(client, label: str) -> List[Dict[str, Any]]: @@ -602,91 +571,19 @@ def _get_full(client, guid: str) -> Optional[Dict[str, Any]]: def _client_identity(client) -> str: - return str(getattr(client, "user_id", "") or "?") - - -def _is_folder(el: Dict[str, Any]) -> bool: - return "CollectionFolder" in _type_names(el) + return _folders.client_identity(client) -@dataclass -class _Walk: - """What a walk of one folder (and, when recursive, the folders inside it) found.""" - members: List[Dict[str, Any]] = field(default_factory=list) # every non-folder member, once per GUID - read: List[str] = field(default_factory=list) # folders read, "Top / Sub" paths - capped: List[str] = field(default_factory=list) # sub-folders the depth cap stopped - not_followed: List[Tuple[str, str]] = field(default_factory=list) - errors: List[Tuple[str, str]] = field(default_factory=list) # sub-folders whose members could not be read - gone: List[Tuple[str, str]] = field(default_factory=list) # sub-folders not visible or not found - - -def _is_gone_error(exc: BaseException) -> bool: - """A read refused because the element is not visible to the caller, or not found: the folder is - gone for this reader. Anything else (timeout, 5xx, refused connection) is a genuine error.""" - try: - from pyegeria.view.dashboard_resolver import _is_not_found_error, is_not_visible_error - return bool(is_not_visible_error(exc) or _is_not_found_error(exc)) - except Exception: # noqa: BLE001 -- if the classifiers cannot load, keep the cache (the safe side) - return False +_is_folder = _folders.is_folder +_Walk = _folders.Walk +_is_gone_error = _folders.is_gone_error def _walk_folder(client, folder: Dict[str, Any], *, recursive: bool, depth_cap: int = DEPTH_CAP, stop_qns: Iterable[str] = ()) -> _Walk: - """Read `folder`'s members; when `recursive`, follow CollectionFolder members downwards. - - Only CollectionFolder members are followed. A GUID is read at most once (the cycle guard); a - folder deeper than `depth_cap` below `folder` is not read and is named in `capped`. A member - that is a RootCollection, a consumer folder other than this one, or a qualified name in - `stop_qns` is never followed: the walk goes down inside one consumer, never up to the root or - across into a sibling. The top folder's members are read without a guard, so an error there - raises to the caller; an error in a sub-folder is recorded in `errors`.""" - top_qn = _props(folder).get("qualifiedName") or _guid(folder) - stops = set(stop_qns) - {top_qn} - w = _Walk() - seen = {_guid(folder)} - member_guids: set = set() - queue: List[Tuple[Dict[str, Any], int, str]] = [(folder, 0, top_qn)] - while queue: - current, depth, path = queue.pop(0) - if depth == 0: - listed = _call(client.get_collection_members, collection_guid=_guid(current), output_format="JSON") - else: - try: - listed = _call(client.get_collection_members, collection_guid=_guid(current), - output_format="JSON") - except Exception as exc: # noqa: BLE001 - if _is_gone_error(exc): - # Not visible (zoned away from the reader) or deleted: its specs are no longer - # published through this folder, so they are pruned, never kept as "unread". - w.gone.append((path, str(exc))) - else: # a genuine error (timeout, 5xx): an outage must not unpublish the consumer - w.errors.append((path, str(exc))) - continue - w.read.append(path) - for m in listed: - g = _guid(m) - if not g: - continue - is_root = "RootCollection" in _type_names(m) - if not (recursive and (_is_folder(m) or is_root)): - if g not in member_guids: - member_guids.add(g) - w.members.append(m) - continue - qn = _props(m).get("qualifiedName") or g - sub_path = f"{path} / {qn}" - if is_root: - w.not_followed.append((sub_path, "a RootCollection; the walk never goes up to the root")) - elif g in seen: - w.not_followed.append((sub_path, "already read (a cycle, or a second path to the same folder)")) - elif qn in stops or (_is_top_consumer_qn(qn) and qn != top_qn): - w.not_followed.append((sub_path, "another consumer folder; the walk never goes across")) - elif depth + 1 > depth_cap: - w.capped.append(sub_path) - else: - seen.add(g) - queue.append((m, depth + 1, sub_path)) - return w + """The shared walk (`egeria_folders.walk_folder`) over report-spec consumer folders.""" + return _folders.walk_folder(client, folder, recursive=recursive, consumer_prefix=CONSUMER_PREFIX, + depth_cap=depth_cap, stop_qns=stop_qns) def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: Optional[Iterable[str]] = None, @@ -934,16 +831,17 @@ def _resolve_cache_dir(client, override: Optional[str]) -> Path: _CONSUMERS_MEMO: Dict[str, Any] = {} -def _consumer_name(el: Dict[str, Any]) -> str: - props = _props(el) - qn = props.get("qualifiedName") or "" - tail = qn[len(CONSUMER_PREFIX):] if _is_consumer_qn(qn) else qn - return props.get("displayName") or tail or _guid(el) - - -def _not_read(out: Dict[str, Any], reason: str) -> Dict[str, Any]: - out.update(status="not read", reason=reason, consumers=[], index={}) - return out +def _spec_label(m: Dict[str, Any], consumer: str, notes: List[str]) -> Optional[str]: + """A member's spec label for the consumer index; None for what the index leaves out.""" + try: + label, _qn = _identify(m) + except _Skip: + return None # not a well-formed spec: the sync reports those; the facet ignores them + if _zones(m): + # The index is a shared file shown to every viewer: a zoned spec's label stays out (§9). + notes.append(f"{consumer}: {label}: {ZONED_REASON}") + return None + return label def build_consumer_index(client, *, root: Optional[str] = None, depth_cap: int = DEPTH_CAP) -> Dict[str, Any]: @@ -957,64 +855,9 @@ def build_consumer_index(client, *, root: Optional[str] = None, depth_cap: int = consumer's own `status` say which); or "not read" (the root itself could not be read: `index` is empty and must never be shown as "used by none"). `consumers` lists every consumer folder, read or not, so a reader can claim "used by none" only against a fully read tree.""" - root_qn = root or configured_root() - identity = _client_identity(client) - out: Dict[str, Any] = {"format": CONSUMERS_FORMAT, "root": root_qn, "read_at": _now(), "read_as": identity, - "status": "read", "reason": None, "consumers": [], "index": {}, "notes": []} - try: - found = _call(client.get_collections_by_name, root_qn, metadata_element_type="RootCollection", - output_format="JSON") - except Exception as exc: # noqa: BLE001 - return _not_read(out, f"the root {root_qn} could not be read: {exc}") - roots = [e for e in found if _props(e).get("qualifiedName") == root_qn] - if not roots: - return _not_read(out, f"the root {root_qn} was not found, or is not visible to {identity}") - try: - listed = _call(client.get_collection_members, collection_guid=_guid(roots[0]), output_format="JSON") - except Exception as exc: # noqa: BLE001 - return _not_read(out, f"the members of the root {root_qn} could not be read: {exc}") - folders = [m for m in listed if _is_folder(m)] - out["notes"].extend(f"{_props(m).get('qualifiedName') or _guid(m)}: a member of the root that is not a " - f"CollectionFolder, so not a consumer" for m in listed if not _is_folder(m)) - stop = [_props(f).get("qualifiedName") or "" for f in folders] + [root_qn] - index: Dict[str, List[str]] = {} - unread: List[str] = [] - for f in sorted(folders, key=_consumer_name): - name = _consumer_name(f) - entry = {"name": name, "qualifiedName": _props(f).get("qualifiedName"), "guid": _guid(f), - "status": "read", "reason": None, "specs": 0} - out["consumers"].append(entry) - try: - walk = _walk_folder(client, f, recursive=True, depth_cap=depth_cap, stop_qns=stop) - except Exception as exc: # noqa: BLE001 - entry.update(status="not read", reason=str(exc)) - unread.append(name) - continue - problems = [f"{p}: {e}" for p, e in walk.errors] - out["notes"].extend(f"{name}: {p} not visible or not found" for p, _e in walk.gone) - if walk.capped: - problems.append(f"depth cap reached ({depth_cap} levels); not read: " + ", ".join(walk.capped)) - if problems: - entry.update(status="partial", reason="; ".join(problems)) - unread.append(name) - labels = set() - for m in walk.members: - try: - label, _qn = _identify(m) - except _Skip: - continue # not a well-formed spec: the sync reports those; the facet ignores them - if _zones(m): - # The index is a shared file shown to every viewer: a zoned spec's label stays out (§9). - out["notes"].append(f"{name}: {label}: {ZONED_REASON}") - continue - labels.add(label) - for label in labels: - index.setdefault(label, []).append(name) - entry["specs"] = len(labels) - out["index"] = {k: sorted(v) for k, v in sorted(index.items())} - if unread: - out.update(status="partial", reason="not fully read: " + ", ".join(unread)) - return out + return _folders.read_consumer_tree(client, root_qn=root or configured_root(), consumer_prefix=CONSUMER_PREFIX, + key=_spec_label, fmt=CONSUMERS_FORMAT, depth_cap=depth_cap, + count_field="specs") def refresh_consumer_index(client, *, cache_dir: Optional[str] = None, root: Optional[str] = None, diff --git a/tests/micro-tests/test_dashboard_folders.py b/tests/micro-tests/test_dashboard_folders.py new file mode 100644 index 00000000..95361836 --- /dev/null +++ b/tests/micro-tests/test_dashboard_folders.py @@ -0,0 +1,214 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Dashboard folders (LD-1): sheets listed by consumer folder, through the walk report specs use. + + RootCollection::DashboardSheets + DashboardFolder::Consumer::Portal -> Dashboard::Ops, sub-folder Portal::Exec + DashboardFolder::Consumer::Portal::Exec -> Dashboard::Board + DashboardFolder::Consumer::EgeriaAdvisor -> Dashboard::Ops (one sheet, two consumers) + +The Egeria is dashboard_fake_egeria's (element shapes checked live on 2026-11-09; sheets are written +through the real sheet writer), plus the two collection reads the folder walk makes. +""" +import copy + +import pytest + +# micro-tests is on sys.path under pytest; the fake's element shapes were checked live on 2026-11-09. +from dashboard_fake_egeria import FakeEgeria + +from md_processing.v2.dashboard_sheet import DashboardSheetEgeriaWriter +from pyegeria.view import dashboards as dash +from pyegeria.view import egeria_folders as folders +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + +pytestmark = pytest.mark.unit + +ROOT = dash.DEFAULT_DASHBOARD_ROOT +PORTAL = "DashboardFolder::Consumer::Portal" +EXEC = PORTAL + "::Exec" +ADVISOR = "DashboardFolder::Consumer::EgeriaAdvisor" + + +class FolderEgeria(FakeEgeria): + """FakeEgeria plus CollectionFolder / RootCollection membership, read the way the walk reads it.""" + + def __init__(self): + super().__init__() + self.members = {} + self.failing = set() # GUIDs whose members cannot be read (a genuine error: HTTP 500) + self.user_id = "erinoverview" + + def folder(self, qn, display=None, type_name="CollectionFolder"): + guid = self.add_entity(type_name, qn, display or qn.rsplit("::", 1)[-1]) + self.members[guid] = [] + return guid + + def put(self, parent_guid, child_guid): + self.members[parent_guid].append(child_guid) + + def get_collections_by_name(self, name, metadata_element_type=None, output_format="JSON", **_): + hits = [self.element(g) for g, e in self.entities.items() if e["props"].get("qualifiedName") == name + and metadata_element_type in (None, e["type"])] + return copy.deepcopy(hits) or "No elements found" + + def get_collection_members(self, collection_guid=None, output_format="JSON", **_): + if collection_guid in self.failing: + raise RuntimeError("HTTP 500 from the view server") + return [self.element(g) for g in self.members.get(collection_guid, [])] or "No elements found" + + +async def _sheet(fake, name): + await DashboardSheetEgeriaWriter(fake).write_sheet( + DashboardSheet(name=name, heading=name, placements=[Placement(ref="note", content=f"{name} text")])) + return fake.by_qn(f"Dashboard::{name}") + + +@pytest.fixture +async def tree(): + fake = FolderEgeria() + root = fake.folder(ROOT, type_name="RootCollection") + portal, exec_, advisor = fake.folder(PORTAL, "Portal"), fake.folder(EXEC, "Exec"), fake.folder(ADVISOR, "EgeriaAdvisor") + ops, board, loose = await _sheet(fake, "Ops"), await _sheet(fake, "Board"), await _sheet(fake, "Loose") + fake.put(root, portal) + fake.put(root, advisor) + fake.put(portal, ops) + fake.put(portal, exec_) + fake.put(exec_, board) + fake.put(advisor, ops) + return {"fake": fake, "root": root, "portal": portal, "exec": exec_, "advisor": advisor, "loose": loose} + + +@pytest.fixture(autouse=True) +def _no_configured_folders(monkeypatch): + monkeypatch.setenv(dash.DASHBOARD_FOLDERS_ENV, "") + monkeypatch.delenv(dash.DASHBOARD_ROOT_ENV, raising=False) + + +# ── listing ── + +async def test_no_folders_configured_lists_every_sheet_and_says_so(tree): + listing = await dash.async_list_dashboard_sheets(tree["fake"]) + assert [s.name for s in listing] == ["Board", "Loose", "Ops"] + assert listing.notes == [dash.NO_FOLDERS_NOTE] + assert all(s.folders == [] and s.used_by == [] for s in listing) + + +async def test_a_consumer_folder_lists_its_sheets_recursively_and_tags_them(tree): + listing = await dash.async_list_dashboard_sheets(tree["fake"], [PORTAL]) + assert [s.name for s in listing] == ["Board", "Ops"] # Board is in the Exec sub-folder; Loose in none + assert all(s.folders == [PORTAL] and s.used_by == ["Portal"] for s in listing) + assert listing.notes == [] + assert listing.folders == [{"qualifiedName": PORTAL, "status": "read", "reason": None, "sheets": 2}] + + +async def test_a_sheet_in_two_consumer_folders_is_listed_once_with_both(tree): + listing = await dash.async_list_dashboard_sheets(tree["fake"], [PORTAL, ADVISOR]) + ops = next(s for s in listing if s.name == "Ops") + assert [s.name for s in listing].count("Ops") == 1 + assert ops.folders == [PORTAL, ADVISOR] and ops.used_by == ["EgeriaAdvisor", "Portal"] + + +async def test_a_sub_folder_is_used_by_its_consumer(tree): + listing = await dash.async_list_dashboard_sheets(tree["fake"], [EXEC]) + assert [(s.name, s.used_by) for s in listing] == [("Board", ["Portal"])] + + +async def test_the_configured_folders_come_from_the_environment(tree, monkeypatch): + monkeypatch.setenv(dash.DASHBOARD_FOLDERS_ENV, f" {ADVISOR} , ") + assert dash.configured_dashboard_folders() == [ADVISOR] + listing = await dash.async_list_dashboard_sheets(tree["fake"]) + assert [s.name for s in listing] == ["Ops"] + + +async def test_a_folder_not_found_is_stated_never_an_empty_list(tree): + listing = await dash.async_list_dashboard_sheets(tree["fake"], ["DashboardFolder::Consumer::Nope", ADVISOR]) + assert [s.name for s in listing] == ["Ops"] # the other folder is still read + assert listing.folders[0]["status"] == "not found" + assert listing.notes == ["DashboardFolder::Consumer::Nope: not found, or not visible to erinoverview"] + + +async def test_an_unreadable_folder_is_not_read_with_its_reason(tree): + tree["fake"].failing.add(tree["portal"]) + listing = await dash.async_list_dashboard_sheets(tree["fake"], [PORTAL]) + assert list(listing) == [] + assert listing.folders[0]["status"] == "not read" + assert "HTTP 500" in listing.notes[0] and listing.notes[0].startswith(PORTAL) + + +async def test_an_unreadable_sub_folder_makes_the_folder_partial(tree): + tree["fake"].failing.add(tree["exec"]) + listing = await dash.async_list_dashboard_sheets(tree["fake"], [PORTAL]) + assert [s.name for s in listing] == ["Ops"] + assert listing.folders[0]["status"] == "partial" + assert listing.notes == [f"{PORTAL}: not fully read: {PORTAL} / {EXEC}: HTTP 500 from the view server"] + + +async def test_the_walk_never_goes_across_to_a_sibling_consumer_or_up_to_the_root(tree): + fake = tree["fake"] + fake.put(tree["exec"], tree["advisor"]) # a sibling consumer, filed inside Portal by mistake + fake.put(tree["exec"], tree["root"]) # and the root + listing = await dash.async_list_dashboard_sheets(fake, [EXEC]) + assert [s.name for s in listing] == ["Board"] # not Ops, which only Advisor would add here + walk = folders.walk_folder(fake, fake.element(tree["exec"]), recursive=True, + consumer_prefix=dash.DASHBOARD_CONSUMER_PREFIX) + reasons = [why for _p, why in walk.not_followed] + assert "another consumer folder; the walk never goes across" in reasons + assert "a RootCollection; the walk never goes up to the root" in reasons + + +async def test_a_cycle_is_read_once(tree): + fake = tree["fake"] + fake.put(tree["exec"], tree["portal"]) + listing = await dash.async_list_dashboard_sheets(fake, [PORTAL]) + assert [s.name for s in listing] == ["Board", "Ops"] + assert listing.folders[0]["status"] == "read" + + +async def test_the_depth_cap_is_stated(tree): + fake = tree["fake"] + parent = tree["exec"] + for i in range(3): + child = fake.folder(f"{EXEC}::L{i}") + fake.put(parent, child) + parent = child + deep = await _sheet(fake, "Deep") + fake.put(parent, deep) + listing = await dash.async_list_dashboard_sheets(fake, [PORTAL], depth_cap=2) + assert "Deep" not in [s.name for s in listing] + assert listing.folders[0]["status"] == "partial" + assert "depth cap reached (2 levels)" in listing.notes[0] + + +async def test_only_dashboard_members_count(tree): + fake = tree["fake"] + fake.put(tree["portal"], fake.add_entity("Report", "DeployedReport::X", "X")) + walk = folders.walk_folder(fake, fake.element(tree["portal"]), recursive=True, + consumer_prefix=dash.DASHBOARD_CONSUMER_PREFIX, member=dash._is_dashboard_member) + assert sorted(m["properties"]["qualifiedName"] for m in walk.members) == ["Dashboard::Board", "Dashboard::Ops"] + assert walk.paths[tree["fake"].by_qn("Dashboard::Board")] == [f"{PORTAL} / {EXEC}"] + + +# ── the consumer index ── + +async def test_the_consumer_index_has_the_spec_index_shape(tree): + idx = dash.build_dashboard_consumer_index(tree["fake"]) + assert idx["format"] == dash.DASHBOARD_CONSUMERS_FORMAT and idx["root"] == ROOT + assert idx["status"] == "read" and idx["reason"] is None + assert idx["index"] == {"Board": ["Portal"], "Ops": ["EgeriaAdvisor", "Portal"]} + assert [(c["name"], c["status"], c["sheets"]) for c in idx["consumers"]] == [("EgeriaAdvisor", "read", 1), + ("Portal", "read", 2)] + + +async def test_a_missing_root_is_not_read_never_empty(tree, monkeypatch): + monkeypatch.setenv(dash.DASHBOARD_ROOT_ENV, "RootCollection::Elsewhere") + idx = dash.build_dashboard_consumer_index(tree["fake"]) + assert idx["status"] == "not read" and idx["index"] == {} and "RootCollection::Elsewhere" in idx["reason"] + + +async def test_an_unreadable_consumer_makes_the_index_partial(tree): + tree["fake"].failing.add(tree["exec"]) + idx = dash.build_dashboard_consumer_index(tree["fake"]) + assert idx["status"] == "partial" and "Portal" in idx["reason"] + assert idx["index"] == {"Ops": ["EgeriaAdvisor", "Portal"]} From 386698b0fc5858ee340f08e14323273d697f145d Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Wed, 11 Nov 2026 03:02:48 -0600 Subject: [PATCH 2/3] feat(view): a sheet's spec no tier holds is fetched as the viewer, and says so Consumer folders govern what a tool LISTS, not whether a spec a sheet already references can RUN (Architect, B7a read-back). "Analytic - Generic Metric Trend" sits only in ReportSpecFolder::Consumer::Portal while EA syncs only Consumer::EgeriaAdvisor, so a sheet both apps show failed in EA. - dashboard_resolver: when spec_lookup finds no tier holding a placement's spec, it is fetched from Egeria as the viewer (async_fetch_spec_for_call; Egeria's zone check on that read is the authority). The placement's note says SPEC_NOT_IN_FOLDER ("held in Egeria, not in this tool's folder"), fetched_as carries the internal name, and run=True executes under it. - A spec the viewer cannot read stays absent: error keeps "was not found in any tier" and adds the fetch's reason (NOT_VISIBLE when Egeria refuses the read). A client that cannot read collections keeps today's words. - fetch_missing (default on) on every resolve entry point turns it off. - egeria_spec_cache.fetched_spec_source(name): a fetched spec's provenance. - Tests: readable spec runs with the note and under its fetched name; a spec hidden from the viewer stays absent with its reason, both by search and by GUID; fetching can be turned off. Signed-off-by: Dan Wolfson --- pyegeria/view/dashboard_resolver.py | 63 +++++++++-- pyegeria/view/egeria_spec_cache.py | 12 ++ .../micro-tests/test_dashboard_spec_fetch.py | 107 ++++++++++++++++++ 3 files changed, 171 insertions(+), 11 deletions(-) create mode 100644 tests/micro-tests/test_dashboard_spec_fetch.py diff --git a/pyegeria/view/dashboard_resolver.py b/pyegeria/view/dashboard_resolver.py index 5d3fbbc2..e9fe5bec 100644 --- a/pyegeria/view/dashboard_resolver.py +++ b/pyegeria/view/dashboard_resolver.py @@ -50,7 +50,7 @@ __all__ = [ "NOT_VISIBLE", "REPORT_GONE", "ResolvedPlacement", "ResolvedReport", "ResolvedSheet", "async_list_dashboard_sheets_for_viewer", "async_resolve_dashboard_sheet", "async_resolve_sheet", - "is_not_visible_error", "list_dashboard_sheets_for_viewer", "placements_for_perspective", + "is_not_visible_error", "list_dashboard_sheets_for_viewer", "placements_for_perspective", "SPEC_NOT_IN_FOLDER", "report_from_element", "resolve_dashboard_sheet", "resolve_sheet", ] @@ -58,6 +58,9 @@ NOT_VISIBLE = "not visible to you" #: A Report this viewer was linked to but Egeria no longer holds. REPORT_GONE = "the Report this placement shows is no longer in Egeria" +#: A placement whose spec no tier here holds, fetched from Egeria as the viewer: consumer folders govern +#: what a tool LISTS, not whether a spec a sheet already references can RUN (Architect, B7a read-back). +SPEC_NOT_IN_FOLDER = "held in Egeria, not in this tool's folder" #: Egeria's message ids for "this element is in a zone you cannot see": an explicit read (403-020) and a #: filtered one (500-002, normally swallowed by the server, matched in case it surfaces). @@ -106,6 +109,8 @@ class ResolvedPlacement(BaseModel): refusal: Optional[str] = None # the spec resolver's words when not runnable result: Optional[Dict[str, Any]] = None # with run=True: exec_report_spec's result error: Optional[str] = None # what went wrong finding the spec or running it, in words + #: The internal name ("egeria: