diff --git a/commands/tech/report_specs.py b/commands/tech/report_specs.py index 2f0fc84d..5c1fd9a9 100644 --- a/commands/tech/report_specs.py +++ b/commands/tech/report_specs.py @@ -7,10 +7,13 @@ registry's EGERIA tier reads (report-spec pipeline model §7a "Sync"; RS-EGERIA-TIER stage 1). pyegeria report-specs sync [--folder QN]... [--spec LABEL]... [--include-drafts] - [--cache-dir D] [--shared] + [--cache-dir D] [--shared] [--recursive | --no-recursive] With no --folder and no --spec it takes the folders configured in "Pyegeria Report Spec Folders" (config.json) or PYEGERIA_REPORT_SPEC_FOLDERS; with none configured it says so and syncs nothing. +Sub-folders of a consumer folder (`ReportSpecFolder::Consumer::...`) are followed by default +(cycle-safe, depth-capped, never into a sibling consumer); --recursive/--no-recursive overrides that +for every folder. A folder sync also refreshes the consumer index ("Used by"). It prints the sync report as it is. Credentials come from the usual pyegeria settings (EGERIA_VIEW_SERVER, EGERIA_VIEW_SERVER_URL, EGERIA_USER, EGERIA_USER_PASSWORD) or the options. """ @@ -34,7 +37,7 @@ def _sync(args) -> int: client.create_egeria_bearer_token() report = sync_report_specs(client, folders=args.folder or None, specs=args.spec or None, include_drafts=args.include_drafts, cache_dir=args.cache_dir, - shared=True if args.shared else None) + shared=True if args.shared else None, recursive=args.recursive) except SyncAlreadyRunning as exc: print(str(exc), file=sys.stderr) return 2 @@ -63,6 +66,11 @@ def main(argv=None) -> int: "else ~/.pyegeria/cache/report_specs//).") sync.add_argument("--shared", action="store_true", help="Mark the cache shared: a fetch-on-call never writes into it.") + rec = sync.add_mutually_exclusive_group() + rec.add_argument("--recursive", dest="recursive", action="store_true", default=None, + help="Follow sub-folders of every folder (default: only of consumer folders).") + rec.add_argument("--no-recursive", dest="recursive", action="store_false", + help="Read each folder's direct members only.") sync.add_argument("--json", action="store_true", help="Print the report as JSON.") sync.add_argument("--server", help="View server name.") sync.add_argument("--url", help="View server platform URL.") diff --git a/pyegeria/view/egeria_spec_cache.py b/pyegeria/view/egeria_spec_cache.py index 16eaa41b..bc88a2ca 100644 --- a/pyegeria/view/egeria_spec_cache.py +++ b/pyegeria/view/egeria_spec_cache.py @@ -48,7 +48,15 @@ "SpecFetchError", "cache_dir", "configured_folders", + "configured_root", "sync_report_specs", + "refresh_consumer_index", + "read_consumer_index", + "build_consumer_index", + "CONSUMER_PREFIX", + "DEFAULT_ROOT", + "DEPTH_CAP", + "ROOT_ENV", "fetch_spec_for_call", "async_fetch_spec_for_call", "egeria_tier", @@ -70,6 +78,15 @@ _ACTIVE = "ACTIVE" _DRAFT_STATUSES = ("DRAFT", "PROPOSED") _RELOAD_INTERVAL_S = 1.0 +# Consumer folders (report-spec consumer folders, phases 1-2): a RootCollection whose members are +# one CollectionFolder per consuming tool. A tool syncs its own consumer folder; sub-folders inside +# it are followed (cycle-safe, depth-capped); the root and sibling consumers are never walked into. +ROOT_ENV = "PYEGERIA_REPORT_SPEC_ROOT" +DEFAULT_ROOT = "RootCollection::ReportSpecs" +CONSUMER_PREFIX = "ReportSpecFolder::Consumer::" +DEPTH_CAP = 5 +CONSUMERS = "consumers.json" +CONSUMERS_FORMAT = "pyegeria-report-spec-consumers/1" #: Tier prefixes accepted wherever a spec name is (§7a "Resolution order"). `seed:` is stage 2's #: name for `builtin:`; both are accepted now. @@ -170,6 +187,22 @@ def configured_folders() -> List[str]: return list(getattr(env, "pyegeria_report_spec_folders", None) or []) if env else [] +def configured_root() -> str: + """The root of the consumer-folder tree: `PYEGERIA_REPORT_SPEC_ROOT`, else + `RootCollection::ReportSpecs`.""" + return (os.getenv(ROOT_ENV) or "").strip() or DEFAULT_ROOT + + +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) + + +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):] + + # ── Files ── def _atomic_write_json(path: Path, obj: Any) -> None: @@ -211,7 +244,7 @@ def _read_manifest(directory: Path) -> Dict[str, Any]: def _prune_unnamed(directory: Path, manifest: Dict[str, Any]) -> None: - keep = {MANIFEST} + keep = {MANIFEST, CONSUMERS} for entry in manifest.get("entries", {}).values(): keep.add(entry.get("file", "")) keep.add(entry.get("provenance", "")) @@ -293,6 +326,29 @@ 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 + `elementHeader.classifications`; both places are read, so a list-only check never reports + "no zones" for a zoned element.""" + header = _header(el) + found: List[str] = [] + candidates = [header.get("zoneMembership")] + [c for c in (header.get("classifications") or []) + if isinstance(c, dict) + and c.get("classificationName") == "ZoneMembership"] + for c in candidates: + if not isinstance(c, dict): + continue + z = (c.get("classificationProperties") or {}).get("zoneMembership") + if isinstance(z, str): + z = [z] + found.extend(str(v) for v in (z or []) if v) + return sorted(set(found)) + + +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] @@ -468,10 +524,17 @@ class SyncReport: skipped: List[Tuple[str, str]] = field(default_factory=list) notes: List[str] = field(default_factory=list) drafts: Optional["SyncReport"] = None + # Every folder whose members were read, sub-folders as "Top / Sub" paths (recursive sync). + folders_read: List[str] = field(default_factory=list) + # Sub-folders not read because the depth cap stopped the walk ("depth cap reached"). + depth_cap_reached: List[str] = field(default_factory=list) + # The consumer index refreshed by this sync: {"status", "reason", "consumers", "labels"}, or + # None when this sync did not refresh it (a --spec sync, or index_consumers=False). + consumers: Optional[Dict[str, Any]] = None def to_dict(self) -> Dict[str, Any]: out = {k: getattr(self, k) for k in ("cache_dir", "folders", "added", "updated", "unchanged", "pruned", - "notes")} + "notes", "folders_read", "depth_cap_reached", "consumers")} out["skipped"] = [list(s) for s in self.skipped] if self.drafts is not None: out["drafts"] = self.drafts.to_dict() @@ -480,12 +543,24 @@ def to_dict(self) -> Dict[str, Any]: def render(self) -> str: lines = [f"Report spec cache: {self.cache_dir}"] lines.append(f"Folders: {', '.join(self.folders) if self.folders else '(none)'}") + if self.folders_read and self.folders_read != self.folders: + lines.append(f"Folders read ({len(self.folders_read)}): {', '.join(self.folders_read)}") + if self.depth_cap_reached: + lines.append(f"Depth cap reached, not read: {', '.join(self.depth_cap_reached)}") for name in ("added", "updated", "unchanged", "pruned"): vals = getattr(self, name) lines.append(f"{name.capitalize()} ({len(vals)}): {', '.join(vals) if vals else '-'}") lines.append(f"Skipped ({len(self.skipped)}):" + ("" if self.skipped else " -")) lines.extend(f" - {who}: {why}" for who, why in self.skipped) lines.extend(f"Note: {n}" for n in self.notes) + if self.consumers is not None: + c = self.consumers + if c.get("status") == "not read": + lines.append(f"Consumers: not read ({c.get('reason')})") + else: + extra = f"; {c.get('reason')}" if c.get("reason") else "" + lines.append(f"Consumers: {c.get('status')} ({c.get('consumers')} consumer folders, " + f"{c.get('labels')} specs{extra})") if self.drafts is not None: lines.append("Drafts cache:") lines.extend(" " + ln for ln in self.drafts.render().splitlines()) @@ -530,9 +605,94 @@ 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) + + +@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 + + +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 + + def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: Optional[Iterable[str]] = None, include_drafts: bool = False, cache_dir: Optional[str] = None, - shared: Optional[bool] = None) -> SyncReport: + shared: Optional[bool] = None, recursive: Optional[bool] = None, + depth_cap: int = DEPTH_CAP, index_consumers: bool = True) -> SyncReport: """Sync report specs held in Egeria into the local cache (§7a "Sync"). - `folders`: CollectionFolder qualified names. Default: `configured_folders()` (O-H5); never @@ -543,7 +703,17 @@ def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: synced folder, or gone from Egeria, are pruned and named. - `include_drafts`: DRAFT and PROPOSED specs go to the separate `drafts/` cache. - `shared`: mark the cache shared (a fetch-on-call never writes a shared cache). Default: - keep what the manifest says (False for a new cache). + keep what the manifest says (False for a new cache). A shared cache never takes a spec that + carries a governance zone (report-spec consumer folders §9, until B6's public-only read): it + is skipped as "zoned: not synced into a shared cache", and a cached copy is pruned. + - `recursive`: follow CollectionFolder members of each folder (cycle-safe, at most `depth_cap` + levels below it; never up to the root nor across into a sibling consumer folder). Default + (None): on for consumer folders (`ReportSpecFolder::Consumer::...`), off for any other folder. + A spec found in a sub-folder is recorded against the folder that was named. The report lists + `folders_read`, and `depth_cap_reached` names any sub-folder the cap stopped. + - `index_consumers`: after a folder sync, refresh the consumer index (`refresh_consumer_index`) + in the same cache directory; `report.consumers` says whether the root was read. Its failure + never fails the sync. - One bad spec never fails the sync; it is skipped with its reason. A second sync of the same cache while one runs raises `SyncAlreadyRunning` at once. """ @@ -571,19 +741,34 @@ def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: if folder is None: report.skipped.append((qn, f"folder not found, or not visible to {identity}")) continue + walk_recursive = _is_consumer_qn(qn) if recursive is None else bool(recursive) try: - listed = _call(client.get_collection_members, collection_guid=_guid(folder), output_format="JSON") + walk = _walk_folder(client, folder, recursive=walk_recursive, depth_cap=depth_cap, + stop_qns=folder_qns) except Exception as exc: # noqa: BLE001 report.skipped.append((qn, f"the folder's members could not be read, so its specs are kept as " f"cached: {exc}")) unread_folders.add(qn) continue - for m in listed: + report.folders_read.extend(walk.read) + report.depth_cap_reached.extend(walk.capped) + if walk.capped: + # Not read is not "no longer a member": keep what the folder held, prune nothing. + unread_folders.add(qn) + report.notes.append(f"{qn}: depth cap reached ({depth_cap} levels below it); not read, so its " + f"cached specs are kept: " + ", ".join(walk.capped)) + report.notes.extend(f"{path}: not followed, {why}" for path, why in walk.not_followed) + report.notes.extend(f"{path}: not visible or not found, so its specs are no longer published through " + f"{qn}: {why}" for path, why in walk.gone) + if walk.errors: + unread_folders.add(qn) + report.skipped.extend((path, f"the sub-folder's members could not be read, so {qn}'s specs are " + f"kept as cached: {why}") for path, why in walk.errors) + for m in walk.members: g = _guid(m) - if not g: - continue if g in members: - members[g][1].append(qn) + if qn not in members[g][1]: + members[g][1].append(qn) else: members[g] = (m, [qn]) pinned_lookups: Dict[str, List[Dict[str, Any]]] = {} @@ -600,6 +785,7 @@ def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: main_dir, drafts_dir = directory, directory / DRAFTS_DIR main_old, drafts_old = _read_manifest(main_dir), _read_manifest(drafts_dir) main_new = _new_manifest(main_old, identity, shared) + shared_cache = bool(main_new.get("shared")) # §9: a shared cache never holds a zoned spec drafts_new = _new_manifest(drafts_old, identity, shared) drafts_report = SyncReport(cache_dir=str(drafts_dir), folders=folder_qns) if include_drafts else None @@ -635,6 +821,9 @@ def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: registry_names = _known_names() | set(candidates) for label, [(g, m, fl, pinned)] in candidates.items(): + if shared_cache and _zones(m): + report.skipped.append((label, f"{ZONED_REASON}; zones {', '.join(_zones(m))}")) + continue status_notes: List[str] = [] status = _status(m, status_notes) if status == _ACTIVE: @@ -659,6 +848,9 @@ def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: continue try: full = _get_full(client, g) or m + if shared_cache and _zones(full): # the member listing may not carry the header's zones + rep.skipped.append((label, f"{ZONED_REASON}; zones {', '.join(_zones(full))}")) + continue built = _build(full, folders=folders_now, identity=identity, registry_names=registry_names) except _Skip as s: rep.skipped.append((s.who, s.reason)) @@ -712,6 +904,13 @@ def sync_report_specs(client, *, folders: Optional[Iterable[str]] = None, specs: main_dir.mkdir(parents=True, exist_ok=True) _write_manifest(main_dir, main_new) _prune_unnamed(main_dir, main_new) + if index_consumers and folder_qns: + try: + idx = refresh_consumer_index(client, cache_dir=str(main_dir), depth_cap=depth_cap) + except Exception as exc: # noqa: BLE001 -- the index never fails the sync + idx = {"status": "not read", "reason": f"{type(exc).__name__}: {exc}", "consumers": [], "index": {}} + report.consumers = {"status": idx.get("status"), "reason": idx.get("reason"), + "consumers": len(idx.get("consumers") or []), "labels": len(idx.get("index") or {})} _invalidate_tier() logger.info(f"Report spec sync into {directory}: {len(report.added)} added, {len(report.updated)} updated, " f"{len(report.unchanged)} unchanged, {len(report.pruned)} pruned, {len(report.skipped)} skipped") @@ -730,6 +929,132 @@ def _resolve_cache_dir(client, override: Optional[str]) -> Path: return cache_dir(url, server, override) +# ── The consumer index: which tools each Egeria-held spec is published to ── + +_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 build_consumer_index(client, *, root: Optional[str] = None, depth_cap: int = DEPTH_CAP) -> Dict[str, Any]: + """Read the consumer-folder tree once and return `{label: [consumer, ...]}` with how it was read. + + Names and labels only: no spec is fetched in full. The root (`configured_root()`) is a + RootCollection; each CollectionFolder member is one consumer, named by its displayName. Each + consumer folder is walked like a recursive sync (cycle-safe, `depth_cap`, never into a sibling). + + `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.""" + 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 + + +def refresh_consumer_index(client, *, cache_dir: Optional[str] = None, root: Optional[str] = None, + depth_cap: int = DEPTH_CAP) -> Dict[str, Any]: + """Build the consumer index and write it to `consumers.json` in the spec cache directory. + A "not read" result is written too, with its reason, so a reader never mistakes a failed read + for an empty tree. Returns what was written.""" + directory = _resolve_cache_dir(client, cache_dir) + idx = build_consumer_index(client, root=root, depth_cap=depth_cap) + directory.mkdir(parents=True, exist_ok=True) + _atomic_write_json(directory / CONSUMERS, idx) + _CONSUMERS_MEMO.pop(str(directory), None) + return idx + + +def read_consumer_index(*, cache_dir: Optional[str] = None, client=None) -> Dict[str, Any]: + """The consumer index the last sync wrote (`consumers.json`), read offline and memoised on the + file's mtime. With no index yet, or an unreadable file, the result has `status` "not read" and a + reason: absence is never returned as an empty index.""" + try: + directory = _resolve_cache_dir(client, cache_dir) + except ValueError as exc: + return {"format": CONSUMERS_FORMAT, "status": "not read", "reason": str(exc), "consumers": [], "index": {}} + path = directory / CONSUMERS + try: + mtime = path.stat().st_mtime + except OSError: + return {"format": CONSUMERS_FORMAT, "status": "not read", "consumers": [], "index": {}, + "reason": f"no consumer index in {directory} yet; a report-spec sync writes it"} + memo = _CONSUMERS_MEMO.get(str(directory)) + if memo and memo[0] == mtime: + return memo[1] + data = _read_json(path) + if not isinstance(data, dict) or data.get("format") != CONSUMERS_FORMAT: + return {"format": CONSUMERS_FORMAT, "status": "not read", "consumers": [], "index": {}, + "reason": f"{path} is not a consumer index this pyegeria can read"} + _CONSUMERS_MEMO[str(directory)] = (mtime, data) + return data + + # ── The EGERIA tier: what the registry reads ── _TIER: Dict[str, Any] = {"key": None, "checked": 0.0, "stamp": None, "specs": {}, "meta": {}, "aliases_dropped": {}} diff --git a/tests/micro-tests/test_rs_consumer_folders.py b/tests/micro-tests/test_rs_consumer_folders.py new file mode 100644 index 00000000..9da67505 --- /dev/null +++ b/tests/micro-tests/test_rs_consumer_folders.py @@ -0,0 +1,409 @@ +"""Report-spec consumer folders, phase 2: recursive consumer-folder sync and the consumer index. + +Covers: sub-folders followed inside a consumer folder (and not, by default, inside any other +folder); the cycle guard; the depth cap ("depth cap reached", nothing pruned on a capped walk); +never walking up to the root or across into a sibling consumer; a sub-folder read error keeping +the cached specs; and the consumer index ({label: [consumers]}), including "not read" and +"partial" so that absence is never shown as "used by none"; §9 enforced in code (a shared cache +never takes a zoned spec); and a sub-folder that is not visible or not found counts as gone (its +specs are pruned), unlike a genuine read error. No live Egeria: an in-memory fake. +""" +from __future__ import annotations + +import copy +import json + +import pytest + +import pyegeria.view.egeria_spec_cache as esc +from test_rs_egeria_tier import spec_element, tier # noqa: F401 -- `tier` is a fixture + +pytestmark = pytest.mark.unit + +ROOT_QN = esc.DEFAULT_ROOT +PORTAL = "ReportSpecFolder::Consumer::Portal" +ADVISOR = "ReportSpecFolder::Consumer::EgeriaAdvisor" +JUPYTER = "ReportSpecFolder::Consumer::Jupyter" +SCRATCH = "ReportSpecFolder::scratch::Nested" + + +def _guid(n: int) -> str: + return f"00000000-0000-0000-0000-{n:012d}" + + +def folder(qn, guid, display=None, type_name="CollectionFolder"): + supers = ["Collection", "Referenceable"] + return {"elementHeader": {"guid": guid, "type": {"typeName": type_name, "superTypeNames": supers}, + "versions": {"version": 1}}, + "properties": {"qualifiedName": qn, "displayName": display or qn.rsplit("::", 1)[-1]}} + + +class Tree: + """An in-memory Egeria holding folders, a root and specs; members are by GUID.""" + + def __init__(self): + self.user_id = "erinoverview" + self.platform_url = "https://localhost:9443" + self.view_server = "qs-view-server" + self.by_guid = {} + self.members = {} + self.failing = set() # GUIDs whose members cannot be read (a genuine error) + self.refusals = {} # GUID -> exception raised when its members are read + self.root_error = None + self.member_reads = [] + self._n = 100 + + def add(self, el): + self.by_guid[el["elementHeader"]["guid"]] = el + self.members.setdefault(el["elementHeader"]["guid"], []) + return el + + def new_folder(self, qn, display=None, type_name="CollectionFolder"): + self._n += 1 + return self.add(folder(qn, _guid(self._n), display, type_name)) + + def new_spec(self, label): + self._n += 1 + return self.add(spec_element(label=label, guid=_guid(self._n), aliases=[])) + + def link(self, parent, child): + self.members[parent["elementHeader"]["guid"]].append(child) + + def get_collections_by_name(self, name, metadata_element_type=None, output_format="JSON", **_): + if metadata_element_type == "RootCollection" and self.root_error: + raise RuntimeError(self.root_error) + hits = [e for e in self.by_guid.values() if e["properties"]["qualifiedName"] == name + and (metadata_element_type in (None, e["elementHeader"]["type"]["typeName"]))] + return copy.deepcopy(hits) or "No elements found" + + def get_collection_members(self, collection_guid=None, output_format="JSON", **_): + self.member_reads.append(collection_guid) + if collection_guid in self.failing: + raise RuntimeError("HTTP 500 from the view server") + if collection_guid in self.refusals: + raise self.refusals[collection_guid] + return copy.deepcopy(self.members.get(collection_guid)) or "No elements found" + + def get_collection_by_guid(self, guid, output_format="JSON", **_): + e = self.by_guid.get(guid) + return copy.deepcopy(e) if e else "No elements found" + + +def manifest(tier): + return json.loads((tier["cache"] / esc.MANIFEST).read_text()) + + +@pytest.fixture +def portal_tree(): + """Portal holds A and the sub-folder Overview; Overview holds B and Overview/Tiles; Tiles holds C.""" + t = Tree() + portal = t.new_folder(PORTAL, "Portal") + overview = t.new_folder(PORTAL + "::Overview", "Overview") + tiles = t.new_folder(PORTAL + "::Overview::Tiles", "Tiles") + a, b, c = t.new_spec("Spec-A"), t.new_spec("Spec-B"), t.new_spec("Spec-C") + t.link(portal, a) + t.link(portal, overview) + t.link(overview, b) + t.link(overview, tiles) + t.link(tiles, c) + return t, portal, overview, tiles + + +# ── Recursive sync ── + +def test_consumer_folder_sync_follows_sub_folders(tier, portal_tree): + t, *_ = portal_tree + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert sorted(report.added) == ["Spec-A", "Spec-B", "Spec-C"] + assert report.folders_read == [PORTAL, f"{PORTAL} / {PORTAL}::Overview", + f"{PORTAL} / {PORTAL}::Overview / {PORTAL}::Overview::Tiles"] + assert not report.depth_cap_reached and not report.skipped + # A spec in a sub-folder is recorded against the folder that was named (what a tool configures). + assert manifest(tier)["entries"]["Spec-C"]["folders"] == [PORTAL] + assert "Folders read (3)" in report.render() + + +def test_any_other_folder_reads_direct_members_unless_asked(tier): + t = Tree() + top, sub = t.new_folder(SCRATCH), t.new_folder(SCRATCH + "::Sub") + a, b = t.new_spec("Spec-A"), t.new_spec("Spec-B") + t.link(top, a) + t.link(top, sub) + t.link(sub, b) + flat = esc.sync_report_specs(t, folders=[SCRATCH], index_consumers=False) + assert flat.added == ["Spec-A"] and flat.folders_read == [SCRATCH] + assert any("not a ReportSpec (it is a CollectionFolder)" in why for _, why in flat.skipped) + deep = esc.sync_report_specs(t, folders=[SCRATCH], recursive=True, index_consumers=False) + assert deep.added == ["Spec-B"] and deep.unchanged == ["Spec-A"] + off = esc.sync_report_specs(t, folders=[SCRATCH], recursive=False, index_consumers=False) + assert off.pruned == ["Spec-B"] + + +def test_cycle_guard_reads_each_folder_once(tier, portal_tree): + t, portal, overview, tiles = portal_tree + t.link(tiles, portal) # Tiles -> Portal: a cycle back to the top + t.link(overview, overview) # a folder that is its own member + t.link(portal, tiles) # a second path to Tiles + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert sorted(report.added) == ["Spec-A", "Spec-B", "Spec-C"] + for g in (portal, overview, tiles): + assert t.member_reads.count(g["elementHeader"]["guid"]) == 1 + assert len(report.folders_read) == 3 + assert sum("already read" in n for n in report.notes) == 3 + + +def test_depth_cap_stops_and_says_so_and_prunes_nothing(tier): + t = Tree() + chain = [t.new_folder(PORTAL, "Portal")] + for i in range(1, 8): # Portal / L1 / ... / L7 + chain.append(t.new_folder(f"{PORTAL}::L{i}")) + t.link(chain[i - 1], chain[i]) + for i, f in enumerate(chain): + t.link(f, t.new_spec(f"Spec-L{i}")) + full = esc.sync_report_specs(t, folders=[PORTAL], depth_cap=10, index_consumers=False) + assert len(full.added) == 8 and not full.depth_cap_reached + capped = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) # the default cap, 5 + assert esc.DEPTH_CAP == 5 + assert len(capped.folders_read) == 6 # the top and five levels below it + assert capped.depth_cap_reached == [" / ".join([PORTAL] + [f"{PORTAL}::L{i}" for i in range(1, 7)])] + assert "Depth cap reached" in capped.render() + assert any("depth cap reached" in n for n in capped.notes) + # L6 and L7 were not read, which is not "no longer a member": they stay cached. + assert not capped.pruned + assert {"Spec-L6", "Spec-L7"} <= set(manifest(tier)["entries"]) + + +def test_never_up_to_the_root_nor_across_to_a_sibling_consumer(tier): + t = Tree() + root = t.new_folder(ROOT_QN, "Report Specs", type_name="RootCollection") + portal, advisor = t.new_folder(PORTAL, "Portal"), t.new_folder(ADVISOR, "Egeria Advisor") + t.link(root, portal) + t.link(root, advisor) + t.link(portal, t.new_spec("Spec-P")) + t.link(advisor, t.new_spec("Spec-EA")) + t.link(portal, advisor) # misfiled: a sibling consumer inside Portal + t.link(portal, root) # misfiled: the root inside Portal + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert report.added == ["Spec-P"] + assert report.folders_read == [PORTAL] + notes = " ".join(report.notes) + assert "another consumer folder" in notes and "never goes up to the root" in notes + assert advisor["elementHeader"]["guid"] not in t.member_reads + assert root["elementHeader"]["guid"] not in t.member_reads + + +def test_a_sub_folder_read_error_keeps_the_cached_specs(tier, portal_tree): + t, _portal, overview, _tiles = portal_tree + esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + t.failing.add(overview["elementHeader"]["guid"]) + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert not report.pruned + assert any(who.endswith("::Overview") and "could not be read" in why for who, why in report.skipped) + assert {"Spec-A", "Spec-B", "Spec-C"} <= set(manifest(tier)["entries"]) + + +# ── The consumer index ── + +@pytest.fixture +def rooted(portal_tree): + """The root holds Portal (A; Overview: B; Tiles: C), Egeria Advisor (A) and Jupyter (empty).""" + t, portal, *_ = portal_tree + root = t.new_folder(ROOT_QN, "Report Specs", type_name="RootCollection") + advisor, jupyter = t.new_folder(ADVISOR, "Egeria Advisor"), t.new_folder(JUPYTER, "Jupyter") + for f in (portal, advisor, jupyter): + t.link(root, f) + t.link(advisor, next(m for m in t.members[portal["elementHeader"]["guid"]] + if m["properties"]["qualifiedName"] == "ReportSpec::Spec-A")) + return t, root + + +def test_the_index_maps_each_label_to_every_consumer(tier, rooted): + t, _root = rooted + idx = esc.build_consumer_index(t) + assert idx["status"] == "read" and idx["reason"] is None + assert idx["index"] == {"Spec-A": ["Egeria Advisor", "Portal"], "Spec-B": ["Portal"], "Spec-C": ["Portal"]} + assert [(c["name"], c["status"], c["specs"]) for c in idx["consumers"]] == [ + ("Egeria Advisor", "read", 1), ("Jupyter", "read", 0), ("Portal", "read", 3)] + # Names and labels only: no spec is fetched in full. + assert all(g not in t.member_reads or t.by_guid[g]["elementHeader"]["type"]["typeName"] != "ReportSpec" + for g in t.member_reads) + + +def test_a_folder_sync_refreshes_the_cached_index(tier, rooted): + t, _root = rooted + before = esc.read_consumer_index() + assert before["status"] == "not read" and "a report-spec sync writes it" in before["reason"] + report = esc.sync_report_specs(t, folders=[PORTAL]) + assert report.consumers == {"status": "read", "reason": None, "consumers": 3, "labels": 3} + assert "Consumers: read (3 consumer folders, 3 specs)" in report.render() + cached = esc.read_consumer_index() + assert cached["index"]["Spec-A"] == ["Egeria Advisor", "Portal"] + assert esc.read_consumer_index() is cached # memoised until the file changes + # A --spec sync leaves the index alone, and does not delete it. + assert esc.sync_report_specs(t, specs=["Spec-A"]).consumers is None + assert (tier["cache"] / esc.CONSUMERS).is_file() + + +def test_no_root_is_not_read_never_used_by_none(tier, portal_tree): + t, *_ = portal_tree + report = esc.sync_report_specs(t, folders=[PORTAL]) + assert report.consumers["status"] == "not read" + assert "not found, or is not visible to erinoverview" in report.consumers["reason"] + assert "Consumers: not read (" in report.render() + cached = esc.read_consumer_index() + assert cached["status"] == "not read" and cached["index"] == {} and cached["consumers"] == [] + + +def test_a_root_read_error_is_not_read_with_the_reason(tier, rooted): + t, _root = rooted + t.root_error = "HTTP 503 from the view server" + idx = esc.build_consumer_index(t) + assert idx["status"] == "not read" and "HTTP 503" in idx["reason"] + t.root_error = None + t.failing.add(_root["elementHeader"]["guid"]) + idx = esc.build_consumer_index(t) + assert idx["status"] == "not read" and "members of the root" in idx["reason"] + + +def test_one_unreadable_consumer_makes_the_index_partial(tier, rooted): + t, _root = rooted + advisor = t.get_collections_by_name(ADVISOR, metadata_element_type="CollectionFolder")[0] + t.failing.add(advisor["elementHeader"]["guid"]) + idx = esc.build_consumer_index(t) + assert idx["status"] == "partial" and idx["reason"] == "not fully read: Egeria Advisor" + by_name = {c["name"]: c for c in idx["consumers"]} + assert by_name["Egeria Advisor"]["status"] == "not read" + assert idx["index"]["Spec-A"] == ["Portal"] # what was read; the status says it is incomplete + + +def test_the_index_is_cycle_safe_and_depth_capped(tier, rooted): + t, root = rooted + portal = t.get_collections_by_name(PORTAL, metadata_element_type="CollectionFolder")[0] + tiles = t.get_collections_by_name(PORTAL + "::Overview::Tiles", metadata_element_type="CollectionFolder")[0] + t.link(tiles, portal) + t.link(tiles, root) + idx = esc.build_consumer_index(t) + assert idx["status"] == "read" and idx["index"]["Spec-C"] == ["Portal"] + capped = esc.build_consumer_index(t, depth_cap=1) + assert capped["status"] == "partial" + portal_entry = next(c for c in capped["consumers"] if c["name"] == "Portal") + assert portal_entry["status"] == "partial" and "depth cap reached" in portal_entry["reason"] + assert "Spec-C" not in capped["index"] + + +def test_root_is_configurable(tier, monkeypatch): + assert esc.configured_root() == "RootCollection::ReportSpecs" + monkeypatch.setenv(esc.ROOT_ENV, "RootCollection::Other") + assert esc.configured_root() == "RootCollection::Other" + + +def test_cli_recursive_flags(): + import argparse + from commands.tech import report_specs as cli + seen = {} + real = argparse.ArgumentParser.parse_args + + def capture(self, *a, **k): + ns = real(self, *a, **k) + seen["ns"] = ns + raise SystemExit(0) + with pytest.MonkeyPatch.context() as mp: + mp.setattr(argparse.ArgumentParser, "parse_args", capture) + for argv, want in ((["report-specs", "sync"], None), (["report-specs", "sync", "--recursive"], True), + (["report-specs", "sync", "--no-recursive"], False)): + with pytest.raises(SystemExit): + cli.main(argv) + assert seen["ns"].recursive is want + + +# ── §9: a shared cache never takes a zoned spec ── + +def zone(el, *zones, where="header"): + """Put governance zones on an element the way Egeria 6.2 returns them (own header key), or in + the legacy classifications list.""" + cls = {"class": "ElementClassification", "classificationName": "ZoneMembership", + "classificationProperties": {"zoneMembership": list(zones)}} + if where == "header": + el["elementHeader"]["zoneMembership"] = cls + else: + el["elementHeader"]["classifications"] = [cls] + return el + + +@pytest.fixture +def zoned_tree(portal_tree): + """Portal holds A, and Z1 (zoned) directly; Overview holds B, and Z2 (zoned, legacy list) in the sub-folder.""" + t, portal, overview, tiles = portal_tree + z1, z2 = zone(t.new_spec("Spec-Z1"), "finance"), zone(t.new_spec("Spec-Z2"), "hr", where="classifications") + t.link(portal, z1) + t.link(overview, z2) + return t, portal, overview, z1, z2 + + +def test_a_shared_sync_skips_zoned_specs_in_the_folder_and_its_sub_folders(tier, zoned_tree): + t, *_ = zoned_tree + report = esc.sync_report_specs(t, folders=[PORTAL], shared=True, index_consumers=False) + assert sorted(report.added) == ["Spec-A", "Spec-B", "Spec-C"] + skipped = dict(report.skipped) + assert skipped["Spec-Z1"].startswith("zoned: not synced into a shared cache") and "finance" in skipped["Spec-Z1"] + assert skipped["Spec-Z2"].startswith("zoned: not synced into a shared cache") and "hr" in skipped["Spec-Z2"] + assert not {"Spec-Z1", "Spec-Z2"} & set(manifest(tier)["entries"]) + + +def test_a_private_sync_still_takes_zoned_specs(tier, zoned_tree): + t, *_ = zoned_tree + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert {"Spec-Z1", "Spec-Z2"} <= set(report.added) + + +def test_a_spec_zoned_after_it_was_cached_is_pruned_from_a_shared_cache(tier, portal_tree): + t, portal, *_ = portal_tree + esc.sync_report_specs(t, folders=[PORTAL], shared=True, index_consumers=False) + a = next(m for m in t.members[portal["elementHeader"]["guid"]] + if m["properties"]["qualifiedName"] == "ReportSpec::Spec-A") + zone(a, "finance") + zone(t.by_guid[a["elementHeader"]["guid"]], "finance") + # The manifest stays shared without passing shared= again. + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert report.pruned == ["Spec-A"] and "Spec-A" not in manifest(tier)["entries"] + + +def test_zones_only_on_the_full_element_are_still_caught(tier, portal_tree): + t, portal, *_ = portal_tree + z = t.new_spec("Spec-Z3") + t.link(portal, copy.deepcopy(z)) # the member listing carries no zones + zone(t.by_guid[z["elementHeader"]["guid"]], "finance") # the full element does + report = esc.sync_report_specs(t, folders=[PORTAL], shared=True, index_consumers=False) + assert "Spec-Z3" in dict(report.skipped) and "Spec-Z3" not in manifest(tier)["entries"] + + +def test_the_index_leaves_zoned_labels_out(tier, rooted): + t, _root = rooted + advisor = t.get_collections_by_name(ADVISOR, metadata_element_type="CollectionFolder")[0] + t.link(advisor, zone(t.new_spec("Spec-Z"), "finance")) + idx = esc.build_consumer_index(t) + assert "Spec-Z" not in idx["index"] and any("Spec-Z: zoned" in n for n in idx["notes"]) + + +# ── A sub-folder that is not visible or not found is gone, not unread ── + +@pytest.mark.parametrize("exc", [ + RuntimeError("OPEN-METADATA-SECURITY-403-020 The element abc is not visible to user erinoverview"), + RuntimeError("OMAG-REPOSITORY-HANDLER-404-001 Unknown guid"), +], ids=["not-visible", "not-found"]) +def test_a_hidden_or_deleted_sub_folder_prunes_its_specs(tier, portal_tree, exc): + t, _portal, overview, _tiles = portal_tree + esc.sync_report_specs(t, folders=[PORTAL], shared=True, index_consumers=False) + t.refusals[overview["elementHeader"]["guid"]] = exc + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert sorted(report.pruned) == ["Spec-B", "Spec-C"] + assert any("not visible or not found" in n for n in report.notes) + assert not any("could not be read" in why for _, why in report.skipped) + + +def test_a_genuine_sub_folder_error_still_keeps_the_cache(tier, portal_tree): + t, _portal, overview, _tiles = portal_tree + esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + t.refusals[overview["elementHeader"]["guid"]] = TimeoutError("read timed out") + report = esc.sync_report_specs(t, folders=[PORTAL], index_consumers=False) + assert not report.pruned and {"Spec-B", "Spec-C"} <= set(manifest(tier)["entries"]) diff --git a/tests/micro-tests/test_rs_egeria_tier.py b/tests/micro-tests/test_rs_egeria_tier.py index 566cb085..bf77a3f5 100644 --- a/tests/micro-tests/test_rs_egeria_tier.py +++ b/tests/micro-tests/test_rs_egeria_tier.py @@ -528,7 +528,8 @@ def test_incremental_sync_fetches_only_new_or_higher_versions_and_prunes_by_memb assert pruned.pruned == ["E-Collections"] assert any("no longer a member" in n for n in pruned.notes) assert json.loads((tier["cache"] / esc.MANIFEST).read_text())["entries"] == {} - assert sorted(p.name for p in tier["cache"].glob("*.json")) == [esc.MANIFEST] + # No spec file is left behind; the consumer index (written by every folder sync) stays. + assert sorted(p.name for p in tier["cache"].glob("*.json")) == [esc.CONSUMERS, esc.MANIFEST] def test_spec_in_two_folders_is_cached_once_listing_both(tier):