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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions commands/tech/report_specs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""
SPDX-License-Identifier: Apache-2.0
Copyright Contributors to the ODPi Egeria project.

`pyegeria report-specs sync`: sync report specs held in Egeria into the local cache that the
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]

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.
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.
"""
from __future__ import annotations

import argparse
import json
import sys


def _sync(args) -> int:
from pyegeria.core.config import settings
from pyegeria.omvs.collection_manager import CollectionManager
from pyegeria.view.egeria_spec_cache import SyncAlreadyRunning, sync_report_specs

client = CollectionManager(args.server or settings.Environment.egeria_view_server,
args.url or settings.Environment.egeria_view_server_url,
user_id=args.userid or settings.User_Profile.user_name,
user_pwd=args.password or settings.User_Profile.user_pwd)
try:
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)
except SyncAlreadyRunning as exc:
print(str(exc), file=sys.stderr)
return 2
finally:
try:
client.close_session()
except Exception: # noqa: BLE001
pass
print(json.dumps(report.to_dict(), indent=2) if args.json else report.render())
return 1 if report.skipped and not (report.added or report.updated or report.unchanged) else 0


def main(argv=None) -> int:
parser = argparse.ArgumentParser(prog="pyegeria", description="pyegeria command line tools.")
groups = parser.add_subparsers(dest="group", required=True)
rs = groups.add_parser("report-specs", help="Report specs held in Egeria.")
cmds = rs.add_subparsers(dest="command", required=True)
sync = cmds.add_parser("sync", help="Sync report specs held in Egeria into the local cache.")
sync.add_argument("--folder", action="append", metavar="QN",
help="CollectionFolder qualified name (repeatable). Default: the configured folders.")
sync.add_argument("--spec", action="append", metavar="LABEL",
help="Sync only this spec label (repeatable); prunes nothing else.")
sync.add_argument("--include-drafts", action="store_true",
help="Also take DRAFT and PROPOSED specs, into the separate drafts/ cache.")
sync.add_argument("--cache-dir", metavar="D", help="Cache directory (default: PYEGERIA_REPORT_SPEC_CACHE_DIR, "
"else ~/.pyegeria/cache/report_specs/<platform>/<server>).")
sync.add_argument("--shared", action="store_true",
help="Mark the cache shared: a fetch-on-call never writes into it.")
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.")
sync.add_argument("--userid", help="User id.")
sync.add_argument("--password", help="Password (prefer the environment).")
args = parser.parse_args(argv)
if args.group == "report-specs" and args.command == "sync":
return _sync(args)
parser.error("unknown command")
return 2


if __name__ == "__main__":
sys.exit(main())
Original file line number Diff line number Diff line change
Expand Up @@ -818,11 +818,11 @@
"variable_name": "microflow",
"inUpdate": true,
"attr_labels": "",
"examples": "[{\"function\": \"find_glossaries\", \"params\": {\"search_string\": \"*\"}}]",
"examples": "{\"format\": \"microflow/1\", \"params\": {\"search_string\": {\"type\": \"string\", \"required\": true}}, \"stages\": [{\"stage\": \"producer/find\", \"type\": \"Glossary\", \"function\": \"GlossaryManager.find_glossaries\", \"params\": {\"search_string\": \"$search_string\"}}], \"formatters\": {\"TABLE\": {\"columns\": [\"display_name\", \"qualified_name\", \"description\"]}}}",
"default_value": "",
"valid_values": [],
"existing_element": "",
"description": "The ordered list of stages to run, with their parameters, as a JSON string.",
"description": "The report spec's micro-flow, parameters and formatters, as microflow/1 JSON: {\"format\": \"microflow/1\", \"params\": {name: {type, default, required}}, \"stages\": [...], \"formatters\": {OUTPUT_TYPE: {\"columns\": [...]}}}. A find stage names its method as Class.method (read-only: find_, get_ or list_); an analytic stage names a registered analytic. A bare JSON list of stages (the older format 0) is accepted and converted to microflow/1 when written. Invalid JSON is an error.",
"generated": false,
"style": "Simple",
"user_specified": true,
Expand All @@ -831,7 +831,7 @@
"min_cardinality": 0,
"max_cardinality": 1,
"level": "Basic",
"Journal Entry": "2026-11-07 -- Egeria 6.3 report specs / measurements / dashboards (odpi/egeria#9432)."
"Journal Entry": "2026-11-07 -- Egeria 6.3 report specs / measurements / dashboards (odpi/egeria#9432). 2026-11-08 -- RS-EGERIA-TIER stage 1: stored as microflow/1; a bare list (format 0) is converted."
},
"Target Type Name": {
"variable_name": "target_type_name",
Expand Down
20 changes: 19 additions & 1 deletion md_processing/md_processing_utils/common_md_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,22 @@ def set_element_prop_body(object_type: str, qualified_name: str, attributes: dic
body.update(element_status_properties(body["class"], attributes))
return body

def report_spec_microflow(attributes: dict) -> str | None:
"""The Report Spec's `Microflow` attribute as canonical microflow/1 text, or None if not given.

A bare JSON list (legacy format 0) is converted with `microflow_from_legacy`, the same function
the report-spec sync uses; a microflow/1 object is validated. Raises ValueError with words for
invalid JSON or an invalid micro-flow (RS-EGERIA-TIER, report-spec pipeline model §7a)."""
from pyegeria.view.microflow import MicroflowError, normalize_microflow_text
value = attributes.get('Microflow', {}).get('value', None)
if value is None or (isinstance(value, str) and not value.strip()):
return None
try:
return normalize_microflow_text(value)
except MicroflowError as exc:
raise ValueError(f"Microflow: {exc}") from exc


def set_collection_manager_body(object_type: str, qualified_name: str, attributes: dict) -> dict:
"""
Build the INNER element-specific Properties body for Collection Manager elements.
Expand Down Expand Up @@ -460,7 +476,9 @@ def set_collection_manager_body(object_type: str, qualified_name: str, attribute
# Handle Report Spec (a ReportType subtype, Egeria 6.3 / odpi/egeria#9432)
if object_type in ["Report Spec", "ReportSpec"]:
prop_bod.update({
"microflow": attributes.get('Microflow', {}).get('value', None),
# RS-EGERIA-TIER: always stored as microflow/1 (a bare list is converted, an object
# validated); invalid JSON raises with words instead of passing through verbatim.
"microflow": report_spec_microflow(attributes),
"targetTypeName": attributes.get('Target Type Name', {}).get('value', None),
"aliases": attributes.get('Aliases', {}).get('value', None),
"outputTypes": attributes.get('Output Types', {}).get('value', None),
Expand Down
14 changes: 13 additions & 1 deletion md_processing/v2/collection_manager_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
update_element_dictionary,
set_collection_manager_body, set_rel_request_body, set_delete_request_body,
set_delete_rel_request_body,
async_add_note_in_dr_e, set_object_classifications
async_add_note_in_dr_e, set_object_classifications, report_spec_microflow
)
from pyegeria.core.utils import body_slimmer
from md_processing.v2.multilink import async_link_or_update, update_body
Expand All @@ -22,6 +22,18 @@ class CollectionManagerProcessor(AsyncBaseCommandProcessor):
Supports subtypes like Folders, Root Collections, Digital Products, and Agreements.
"""

def check_parsed_attributes(self, attributes: Dict[str, Any]) -> list:
"""A Report Spec's Microflow must be valid JSON: a microflow/1 object, or a bare list
(format 0), which is converted to microflow/1 when written (RS-EGERIA-TIER)."""
object_type = getattr(self, 'canonical_object_type', self.command.object_type)
if object_type not in ("Report Spec", "ReportSpec"):
return []
try:
report_spec_microflow(attributes)
except ValueError as exc:
return [f"Report Spec '{attributes.get('Display Name', {}).get('value')}': {exc}"]
return []

async def _async_resolve_agreement_actor_relationship_guid(
self, agreement_guid: str, actor_guid: str) -> Optional[str]:
"""Look up the AgreementActor relationship guid linking a given agreement and actor.
Expand Down
11 changes: 11 additions & 0 deletions md_processing/v2/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,11 @@ def _derive_egeria_type_name(self) -> str:
return "".join(w[0].upper() + w[1:] for w in words)
return self.canonical_object_type or None

def check_parsed_attributes(self, attributes: Dict[str, Any]) -> List[str]:
"""Command-specific value checks run right after parsing; returns error sentences. None by
default; a processor overrides it for attributes whose value has its own syntax."""
return []

def is_report_view_command(self) -> bool:
"""True when this command is a report runner, not an element-targeting command."""
return self.command.verb.lower() == "view" and self.command.object_type.strip().lower() == "report"
Expand Down Expand Up @@ -617,6 +622,12 @@ async def _execute(self) -> Dict[str, Any]:
if explicit_request_id:
self.context["request_id"] = explicit_request_id

# Command-specific checks of attribute values (e.g. a Report Spec's Microflow JSON); an
# error here fails pre-flight validation (step 2) with its words.
for msg in self.check_parsed_attributes(attributes) or []:
self.parsed_output["valid"] = False
self.parsed_output.setdefault("errors", []).append(msg)

# Extract Display Name if present
if self.is_report_view_command():
display_name = attributes.get("Report Spec", {}).get("value")
Expand Down
24 changes: 23 additions & 1 deletion pyegeria/core/_server_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1843,6 +1843,18 @@ def find_comments(

return resp

async def _async_refresh_report_spec(self, report_spec: Any, kwargs: dict) -> Any:
"""Fetch-on-call (RS-EGERIA-TIER, §7a): pop `refresh_spec` from a request's kwargs and, when it
is true, fetch the named report spec from Egeria for this call. Returns the name the call should
use (an in-process "egeria:<label>@v<N>" for a fetched spec). A failed fetch raises with words;
it never falls back to the cached copy."""
if not kwargs.pop("refresh_spec", False):
return report_spec
if not isinstance(report_spec, str) or not report_spec:
raise ValueError("refresh_spec=True needs report_spec to name a report spec")
from pyegeria.view.egeria_spec_cache import async_fetch_spec_for_call
return await async_fetch_spec_for_call(self, report_spec)

def _generate_formatted_output(
self,
elements: dict | list[dict],
Expand Down Expand Up @@ -1896,7 +1908,7 @@ def _generate_formatted_output(
'get_additional_props_func', 'columns_struct']:
kwargs.pop(key, None)

return generate_output(
result = generate_output(
elements=elements,
search_string=query_string,
entity_type=entity_type,
Expand All @@ -1906,6 +1918,11 @@ def _generate_formatted_output(
columns_struct=output_formats,
**kwargs
)
if isinstance(report_spec, str) and isinstance(result, str):
# Provenance footer for an Egeria-held spec on REPORT/MD/HTML (RS-EGERIA-TIER §7a).
from pyegeria.view.base_report_formats import add_spec_footer
result = add_spec_footer(result, report_spec, output_format)
return result

def _generate_comment_output(self, elements: dict | list[dict], search_string: Optional[str] = None,
element_type_name: Optional[str] = None,
Expand Down Expand Up @@ -6462,6 +6479,7 @@ async def _async_find_request(self, url: str, _type: str, _gen_output: Callable[
property_names: Optional[list[str]] = None,
body: dict | SearchStringRequestBody | FindPropertyNamesRequestBody = None,
**kwargs) -> Any:
report_spec = await self._async_refresh_report_spec(report_spec, kwargs) # refresh_spec=True (RS-EGERIA-TIER)

effective_search_string = None if search_string == '*' else search_string

Expand Down Expand Up @@ -6568,6 +6586,7 @@ async def _async_get_name_request(self, url: str, _type: str, _gen_output: Calla
report_spec: Optional[str | dict] = None,
body: Optional[dict | FilterRequestBody] = None,
max_mermaid_node_count=10, **kwargs) -> Any:
report_spec = await self._async_refresh_report_spec(report_spec, kwargs) # refresh_spec=True (RS-EGERIA-TIER)

# _async_find_request spells this argument `metadata_element_type`; a wrapper copied from a find_*
# sibling passed that spelling here, where it fell into **kwargs and FilterRequestBody silently
Expand Down Expand Up @@ -6640,6 +6659,7 @@ async def _async_get_guid_request(self, url: str, _type: str, _gen_output: Calla
rather than switching to _async_get_results_body_request, because only
this helper understands the singular "elementGraph" response key.
"""
report_spec = await self._async_refresh_report_spec(report_spec, kwargs) # refresh_spec=True (RS-EGERIA-TIER)
if isinstance(body, (GetRequestBody, ResultsRequestBody)):
validated_body = body
elif isinstance(body, dict):
Expand Down Expand Up @@ -6702,6 +6722,7 @@ async def _async_get_request_body_request(self, url: str, _type: str, _gen_outpu
max_mermaid_node_count ():
graph_query_depth ():
"""
report_spec = await self._async_refresh_report_spec(report_spec, kwargs) # refresh_spec=True (RS-EGERIA-TIER)
if isinstance(body, GetRequestBody):
validated_body = body
elif isinstance(body, dict):
Expand Down Expand Up @@ -7175,6 +7196,7 @@ async def _async_get_results_body_request(self, url: str, _type: str, _gen_outpu
`filter_results_by_type=False` when `_type` is only a rendering hint, so the
default request body doesn't wrongly filter results by it.
"""
report_spec = await self._async_refresh_report_spec(report_spec, kwargs) # refresh_spec=True (RS-EGERIA-TIER)
if isinstance(body, ResultsRequestBody):
validated_body = body
elif isinstance(body, dict):
Expand Down
6 changes: 5 additions & 1 deletion pyegeria/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,11 @@ class EnvironmentConfig(BaseModel):
# that the setting is ignored. Use the `pyegeria.report_specs` entry-point
# group or register_report_specs() instead.
pyegeria_report_spec_modules: List[str] = Field(default_factory=list, alias="Pyegeria Report Spec Modules")

# CollectionFolder qualified names a plain `pyegeria report-specs sync` takes (O-H5;
# 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")

model_config = ConfigDict(populate_by_name=True, extra='allow')


Expand Down
6 changes: 6 additions & 0 deletions pyegeria/core/mcp_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ def run_report(
user: Optional[str] = None,
user_pass: Optional[str] = None,
token: Optional[str] = None,
refresh_spec: bool = False,
) -> Dict[str, Any]:
"""
Execute a format set action as an MCP-style tool. Enforces DICT/ALL by default.
Expand All @@ -183,6 +184,10 @@ def run_report(
as that user instead of falling back to the `user`/`user_pass` service
account. `user`/`user_pass` remain fully backward compatible when
`token` is not given.

RS-EGERIA-TIER: `report` may be tier-addressed (`egeria:<label>`, `builtin:<label>`); pass
`refresh_spec=True` to fetch the spec from Egeria for this call. The result carries
`spec_source` beside `kind`.
"""
description = _describe_call(report, params, view_server, view_url, user, user_pass, token)
print(description, file=sys.stderr)
Expand All @@ -198,6 +203,7 @@ def run_report(
user=user if user is not None else _settings.User_Profile.user_name,
user_pass=user_pass if user_pass is not None else _settings.User_Profile.user_pwd,
token=token,
refresh_spec=refresh_spec,
)

async def _async_run_report_tool(
Expand Down
Loading
Loading