diff --git a/commands/tech/report_specs.py b/commands/tech/report_specs.py new file mode 100644 index 00000000..2f0fc84d --- /dev/null +++ b/commands/tech/report_specs.py @@ -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//).") + 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()) diff --git a/md_processing/data/compact_commands/commands_report_compact.json b/md_processing/data/compact_commands/commands_report_compact.json index efa10547..b4d65d91 100644 --- a/md_processing/data/compact_commands/commands_report_compact.json +++ b/md_processing/data/compact_commands/commands_report_compact.json @@ -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, @@ -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", diff --git a/md_processing/md_processing_utils/common_md_utils.py b/md_processing/md_processing_utils/common_md_utils.py index 34768948..66b15a6c 100644 --- a/md_processing/md_processing_utils/common_md_utils.py +++ b/md_processing/md_processing_utils/common_md_utils.py @@ -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. @@ -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), diff --git a/md_processing/v2/collection_manager_processor.py b/md_processing/v2/collection_manager_processor.py index b51f660c..9dee76e0 100644 --- a/md_processing/v2/collection_manager_processor.py +++ b/md_processing/v2/collection_manager_processor.py @@ -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 @@ -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. diff --git a/md_processing/v2/processors.py b/md_processing/v2/processors.py index 786123a3..551d33a5 100644 --- a/md_processing/v2/processors.py +++ b/md_processing/v2/processors.py @@ -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" @@ -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") diff --git a/pyegeria/core/_server_client.py b/pyegeria/core/_server_client.py index 199c86e4..1f36ef33 100644 --- a/pyegeria/core/_server_client.py +++ b/pyegeria/core/_server_client.py @@ -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: