From 3ef937a9d8cdcd716536250c93c5771ab0aeb8ac Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 29 Oct 2026 17:46:03 +0100 Subject: [PATCH] feat(web-app-dashboard): move the tile switch to services.dashboard.display The dashboard read `display` from the role's meta/info.yml, which no inventory can override, so a host could not hide a tile. docker_cards now skips a card when `services.dashboard.display` in the merged applications is false, and absent still means shown; a non-bool value fails loudly. roles_with_service drops the same role from the dashboard tile-reachability targets so the Playwright spec does not wait for a hidden tile, and the inventory validator accepts `services.dashboard.display` for every role that declares `services.dashboard`, since no role default carries it. `display` leaves the meta/info.yml allowlist, web-app-jellyfin drops its redundant `display: true`, and base.md and layout.md document the new switch. Real lookups with web-app-gitea set to display false render the Dashboard and Jellyfin cards and only jellyfin as a tile target, and all three without the override; the nine tests for the new behaviour fail against the old code. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../inventory/validate/applications.py | 11 ++- .../contributing/design/role/services/base.md | 19 ++++ .../design/role/services/layout.md | 16 ++-- plugins/lookup/roles_with_service.py | 12 ++- .../lookup_plugins/docker_cards.py | 26 ++--- roles/web-app-jellyfin/meta/info.yml | 1 - tests/lint/ansible/roles/meta/test_info.py | 16 +--- .../inventory/validate/test_applications.py | 27 ++++++ .../plugins/lookup/test_docker_cards.py | 94 +++++++++++++++++++ .../plugins/lookup/test_roles_with_service.py | 31 ++++++ .../roles/applications/test_dashboard.py | 20 +++- utils/roles/applications/dashboard.py | 32 ++++++- 12 files changed, 269 insertions(+), 36 deletions(-) diff --git a/cli/administration/inventory/validate/applications.py b/cli/administration/inventory/validate/applications.py index 8d3a3d1ed6..f3d6672b0a 100644 --- a/cli/administration/inventory/validate/applications.py +++ b/cli/administration/inventory/validate/applications.py @@ -3,10 +3,13 @@ from __future__ import annotations from utils.manager.credential_key import OVERRIDE_SECTION, SECRETS_KEY +from utils.roles.applications.dashboard import DASHBOARD_SERVICE, DISPLAY_PATH from utils.roles.custom import CUSTOM_KEY, SOURCE_KEY, is_custom from .keys import recursive_keys +_DASHBOARD_PATH = f"services.{DASHBOARD_SERVICE}" + def _declares_custom_role(app_id: str, key: str) -> bool: return is_custom(app_id) and key.split(".", 1)[0] in (CUSTOM_KEY, SOURCE_KEY) @@ -22,7 +25,11 @@ def compare_application_keys(applications, application_defaults, source, variant ``custom`` and ``source`` of a custom role are the inventory's declaration of where the role comes from, not role settings, so no - role default carries them.""" + role default carries them. + + ``services.dashboard.display`` is legal wherever the role contract + declares ``services.dashboard``: absent means shown, so no role + default carries it.""" variants = variants or {} errs: list[str] = [] for app_id, conf in applications.items(): @@ -32,6 +39,8 @@ def compare_application_keys(applications, application_defaults, source, variant legal_keys = recursive_keys(application_defaults[app_id]) for variant in variants.get(app_id, []): legal_keys |= recursive_keys(variant) + if _DASHBOARD_PATH in legal_keys: + legal_keys.add(DISPLAY_PATH) for key in recursive_keys(conf): if key == SECRETS_KEY or key.startswith(OVERRIDE_SECTION): continue diff --git a/docs/contributing/design/role/services/base.md b/docs/contributing/design/role/services/base.md index 1a0acaf229..e9f3351c7b 100644 --- a/docs/contributing/design/role/services/base.md +++ b/docs/contributing/design/role/services/base.md @@ -74,6 +74,25 @@ Rules: - `card:` MUST be a key of the role's `canonical` mapping in `meta/domains.yml`; the card URL is `lookup('canonical_url', , )`. - Without `card:` the card targets the primary domain via `lookup('tls', , 'url.base')`. +## Dashboard Card Display 👀 + +`display: false` on a consumer's `dashboard` binding drops its dashboard card, its Apps menu entry and its tile-reachability target. +The switch is read from the merged applications, so an inventory MAY set it per host without touching the role: + +```yaml +applications: + web-app-gitea: + services: + dashboard: + display: false +``` + +Rules: + +- `display:` MUST be a bool; any other value fails the card lookup. +- Without `display:` the card is shown, so a role does not declare `display: true`. +- The inventory validator accepts `services.dashboard.display` for every role whose contract declares `services.dashboard`. + ## Service Discovery 🔍 Service discovery is built from role configs, not from a central registry file. diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index 59df2b1f7b..e24ead744f 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -7,7 +7,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | File | Contents | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| -| `meta/main.yml` | Ansible Galaxy metadata + Ansible `dependencies:`. No project-internal `run_after:` / `lifecycle:` keys, no `logo:` / `homepage:` / `video:` / `display:`. | +| `meta/main.yml` | Ansible Galaxy metadata + Ansible `dependencies:`. No project-internal `run_after:` / `lifecycle:` keys, no `logo:` / `homepage:` / `video:`. | | `meta/services.yml` | Per-entity service config. **File root IS the services map** keyed by ``. No `compose:` and no `services:` wrapper. | | `meta/server.yml` | CSP, `domains`, `status_codes`, plus per-role `networks.local.{subnet,dns_resolver}`. File root IS `applications..server`. | | `meta/rbac.yml` | RBAC declarations. File root IS `applications..rbac`. | @@ -15,7 +15,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | `meta/addons/.yml` | Optional. One file per addon (file root IS the addon spec; filename stem = addon id). See [Unified Addons](#unified-addons-metaaddons-) below. | | `meta/users.yml` | Role-local user definitions. File root IS the users map (no `users:` wrapper). | | `meta/secrets.yml` | Credential schema definitions and runtime credential values. | -| `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`, `display`). File root IS `applications..info` (no `info:` wrapper). | +| `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`). File root IS `applications..info` (no `info:` wrapper). | | `meta/variants.yml` | Optional. Variant overrides deep-merged over the assembled application payload (used by `svc-ai-ollama`, `web-app-phpmyadmin`). | Ansible only auto-loads `meta/main.yml`. @@ -359,7 +359,7 @@ The helper returns `[]` / `None` gracefully when `meta/services.yml` is absent o ## Descriptive Role-Level Metadata: `meta/info.yml` 📝 -Project-internal descriptive metadata (icon, upstream homepage, demo video, dashboard display flag) lives in an OPTIONAL `meta/info.yml`, not nested inside `galaxy_info:`. +Project-internal descriptive metadata (icon, upstream homepage, demo video) lives in an OPTIONAL `meta/info.yml`, not nested inside `galaxy_info:`. The file-root convention applies: there is no wrapping `info:` key, and the file content IS `applications..info`. ```yaml @@ -377,23 +377,23 @@ video: https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC | `logo` | map | UI icon descriptor. Today only `class:` (FontAwesome). Future fields (`source:`, `svg:`) require an explicit allowlist update in the lint. | | `homepage` | string | Upstream project URL: the canonical landing page of the software the role deploys. | | `video` | string | Upstream demo / overview video URL. | -| `display` | bool | Default `true`. `false` opts the role out of dashboards / cards / apps grids. | The lint (`tests/lint/ansible/roles/meta/test_info.py`) rejects any other top-level key so the file does not become a dumping ground. +Whether the dashboard shows the role's card is not set here but in `services.dashboard.display`, see [Dashboard Card Display](base.md#dashboard-card-display-). ### Optionality `meta/info.yml` is OPTIONAL. -A role with none of the four fields does not grow the file. -Consumers MUST treat a missing file or missing field as absent / default, and `display` defaults to `true`. +A role with none of the three fields does not grow the file. +Consumers MUST treat a missing file or missing field as absent / default. ### Materialised Path ``` -applications..info.{logo,homepage,video,display} +applications..info.{logo,homepage,video} ``` -The dashboard's `web-app-dashboard/lookup_plugins/docker_cards.py` reads `logo.class` and `display` from this location, while `description` and `galaxy_tags` continue to come from `galaxy_info` (Galaxy-spec fields). +The dashboard's `web-app-dashboard/lookup_plugins/docker_cards.py` reads `logo.class` from this location, while `description` and `galaxy_tags` continue to come from `galaxy_info` (Galaxy-spec fields). ## Unified Addons: `meta/addons/` 🧩 diff --git a/plugins/lookup/roles_with_service.py b/plugins/lookup/roles_with_service.py index 979c2877f0..980af57963 100644 --- a/plugins/lookup/roles_with_service.py +++ b/plugins/lookup/roles_with_service.py @@ -9,7 +9,9 @@ can tell embeddable cards from those that must open in a new tab. For the ``dashboard`` service a role MAY name ``services.dashboard.card: ``; its entry then carries ``domains.canonical.`` and ``lookup('canonical_url', , )`` instead of the primary domain, so -the tile target matches the card ``docker_cards`` renders. +the tile target matches the card ``docker_cards`` renders. A role whose +``services.dashboard.display`` is false renders no card, so it is no tile +target either. A role keeps declaring the service for inventory completeness but can opt out of this consumer-target list by setting @@ -50,7 +52,11 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.domains.primary_domain import get_primary_domain -from utils.roles.applications.dashboard import DASHBOARD_SERVICE, card_target_key +from utils.roles.applications.dashboard import ( + DASHBOARD_SERVICE, + card_is_displayed, + card_target_key, +) from utils.roles.applications.mcp import ( DEFAULT_MCP_TRANSPORT, derive_allowed_consumers, @@ -202,6 +208,8 @@ class LookupModule(LookupBase): continue if get_entity_name(str(role_id)) == service_name: continue + if lists_dashboard_cards and not card_is_displayed(str(role_id), block): + continue canonical = _resolve_canonical_domain(str(role_id), app_config) if not canonical and direction is None: continue diff --git a/roles/web-app-dashboard/lookup_plugins/docker_cards.py b/roles/web-app-dashboard/lookup_plugins/docker_cards.py index 5d08d82b0c..2620bf3e8e 100644 --- a/roles/web-app-dashboard/lookup_plugins/docker_cards.py +++ b/roles/web-app-dashboard/lookup_plugins/docker_cards.py @@ -9,7 +9,11 @@ from ansible.plugins.lookup import LookupBase from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.roles.applications.config import get -from utils.roles.applications.dashboard import DASHBOARD_SERVICE, card_target_key +from utils.roles.applications.dashboard import ( + DASHBOARD_SERVICE, + card_is_displayed, + card_target_key, +) from utils.roles.mapping import ( ROLE_FILE_META_INFO, ROLE_FILE_META_MAIN, @@ -27,7 +31,8 @@ class LookupModule(LookupBase): - Reads the title from the role's README.md (the first H1 line) - Retrieves the description from galaxy_info.description in meta/main.yml - Retrieves the icon class from meta/info.yml.logo.class - - Retrieves the display flag from meta/info.yml.display + - Skips the role when services.dashboard.display in applications + is false - Retrieves the tags from galaxy_info.galaxy_tags - Builds the URL from the primary domain, or from the domains.canonical key named by services.dashboard.card @@ -114,7 +119,14 @@ class LookupModule(LookupBase): except Exception as e: raise AnsibleError(f"Error reading '{info_path}': {e}") from e - if not info_data.get("display", True): + dashboard_cfg = get( + applications, + application_id, + f"services.{DASHBOARD_SERVICE}", + strict=False, + default={}, + ) + if not card_is_displayed(application_id, dashboard_cfg): continue logo = info_data.get("logo") or {} @@ -134,14 +146,6 @@ class LookupModule(LookupBase): self._templar.template(domain_url).strip() if domain_url else "" ) - dashboard_cfg = get( - applications, - application_id, - f"services.{DASHBOARD_SERVICE}", - strict=False, - default={}, - ) - url = "" if domain_url: card_key = card_target_key(application_id, dashboard_cfg) diff --git a/roles/web-app-jellyfin/meta/info.yml b/roles/web-app-jellyfin/meta/info.yml index 6bf73058fe..093292613b 100644 --- a/roles/web-app-jellyfin/meta/info.yml +++ b/roles/web-app-jellyfin/meta/info.yml @@ -3,4 +3,3 @@ logo: class: fa-solid fa-film homepage: https://jellyfin.org/ video: https://www.youtube.com/watch?v=0t3lSJL3B_Q -display: true diff --git a/tests/lint/ansible/roles/meta/test_info.py b/tests/lint/ansible/roles/meta/test_info.py index e574b68e1d..7a9a2a97b1 100644 --- a/tests/lint/ansible/roles/meta/test_info.py +++ b/tests/lint/ansible/roles/meta/test_info.py @@ -6,11 +6,10 @@ with no upstream homepage or demo video to name; * file-root convention: the file's content IS the value of ``applications..info`` — there is NO wrapping ``info:`` key; - * allowed top-level keys: ``logo``, ``homepage``, ``video``, ``display``; + * allowed top-level keys: ``logo``, ``homepage``, ``video``; * ``logo`` is a mapping with at least a string ``class:`` field; * ``homepage`` and ``video`` are non-empty strings; - * ``display`` is a bool; - * none of these four fields may reappear under + * none of these three fields may reappear under ``meta/main.yml.galaxy_info``. Caching: parsed YAML comes through the shared process-wide @@ -35,13 +34,11 @@ if TYPE_CHECKING: ROLES_DIR = PROJECT_ROOT / "roles" -_ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video", "display"}) +_ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video"}) _INFO_MEDIA_RULE = "info-media" -_FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset( - {"logo", "homepage", "video", "display"} -) +_FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video"}) def _meta_main_paths() -> list[Path]: @@ -105,9 +102,6 @@ def _validate_meta_info(path: Path) -> list[str]: if not isinstance(value, str) or not value.strip(): problems.append(f"`{str_field}` must be a non-empty string") - if "display" in parsed and not isinstance(parsed["display"], bool): - problems.append("`display` must be a bool (true/false)") - return problems @@ -153,7 +147,7 @@ class TestMetaInfoShape(unittest.TestCase): class TestMetaMainHasNoMigratedFields(unittest.TestCase): - """galaxy_info MUST NOT carry the four fields after.""" + """galaxy_info MUST NOT carry the three meta/info.yml fields.""" def test_no_forbidden_keys_in_galaxy_info(self) -> None: offenders: dict[Path, list[str]] = {} diff --git a/tests/unit/python/cli/administration/inventory/validate/test_applications.py b/tests/unit/python/cli/administration/inventory/validate/test_applications.py index 3f9ed263c2..625357bab1 100644 --- a/tests/unit/python/cli/administration/inventory/validate/test_applications.py +++ b/tests/unit/python/cli/administration/inventory/validate/test_applications.py @@ -105,6 +105,33 @@ class TestCompareApplicationKeys(unittest.TestCase): defaults = {"web-app-cst-demo": {"services": {"port": 8080}}} self.assertEqual(compare_application_keys(apps, defaults, "src"), []) + def test_dashboard_display_is_legal_where_dashboard_is_declared(self): + apps = {"app1": {"services": {"dashboard": {"display": False}}}} + defaults = {"app1": {"services": {"dashboard": {"enabled": False}}}} + self.assertEqual(compare_application_keys(apps, defaults, "src"), []) + + def test_dashboard_display_is_legal_where_a_variant_declares_dashboard(self): + apps = {"app1": {"services": {"dashboard": {"display": False}}}} + defaults = {"app1": {"services": {}}} + variants = {"app1": [{"services": {"dashboard": {"enabled": True}}}]} + self.assertEqual(compare_application_keys(apps, defaults, "src", variants), []) + + def test_dashboard_display_without_a_dashboard_binding_is_flagged(self): + apps = {"app1": {"services": {"dashboard": {"display": False}}}} + defaults = {"app1": {"services": {"port": 8080}}} + result = compare_application_keys(apps, defaults, "src") + self.assertEqual( + sorted(err.rsplit(": ", 1)[1] for err in result), + ["services.dashboard", "services.dashboard.display"], + ) + + def test_other_undeclared_dashboard_keys_stay_flagged(self): + apps = {"app1": {"services": {"dashboard": {"dispaly": False}}}} + defaults = {"app1": {"services": {"dashboard": {"enabled": False}}}} + result = compare_application_keys(apps, defaults, "src") + self.assertEqual(len(result), 1) + self.assertIn("services.dashboard.dispaly", result[0]) + def test_declaration_keys_on_an_in_tree_role_are_flagged(self): apps = {"app1": {"custom": True, "source": {"url": "https://x/y.git"}}} defaults = {"app1": {"services": {}}} diff --git a/tests/unit/python/plugins/lookup/test_docker_cards.py b/tests/unit/python/plugins/lookup/test_docker_cards.py index 5a981df409..d28ee70528 100644 --- a/tests/unit/python/plugins/lookup/test_docker_cards.py +++ b/tests/unit/python/plugins/lookup/test_docker_cards.py @@ -359,6 +359,100 @@ logo: with self.assertRaisesRegex(AnsibleError, "nope"): self._run_lookup(LookupModule(), fake_variables) + def _add_role(self, role_name, application_id, info_yaml): + role_dir = Path(self.test_roles_dir) / role_name + (role_dir / "meta").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) + (role_dir / ROLE_FILE_VARS_MAIN).write_text( + f"application_id: {application_id}\n", encoding="utf-8" + ) + (role_dir / "README.md").write_text(f"# {role_name}\n", encoding="utf-8") + (role_dir / ROLE_FILE_META_MAIN).write_text( + 'galaxy_info:\n description: "Second role."\n', encoding="utf-8" + ) + (role_dir / ROLE_FILE_META_INFO).write_text(info_yaml, encoding="utf-8") + + def _two_role_variables(self): + self._add_role("web-app-other", "other", "logo:\n class: fa-solid fa-cube\n") + fake_variables = self._base_fake_variables() + fake_variables["domains"]["other"] = "other.example.com" + fake_variables["applications"]["other"] = { + "services": {"dashboard": {"enabled": True}} + } + fake_variables["group_names"] = ["portfolio", "other"] + return fake_variables + + def test_display_false_skips_the_card(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "display" + ] = False + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual(result, [[]]) + + def test_absent_display_shows_the_card(self): + fake_variables = self._base_fake_variables() + self.assertNotIn( + "display", + fake_variables["applications"]["portfolio"]["services"]["dashboard"], + ) + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_display_true_shows_the_card(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "display" + ] = True + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_display_false_hides_only_its_own_card(self): + fake_variables = self._two_role_variables() + fake_variables["applications"]["other"]["services"]["dashboard"]["display"] = ( + False + ) + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_both_cards_render_without_display(self): + fake_variables = self._two_role_variables() + + result = self._run_lookup(LookupModule(), fake_variables) + + self.assertEqual( + [c["title"] for c in result[0]], + ["Portfolio Application", "web-app-other"], + ) + + def test_info_display_false_no_longer_hides_the_card(self): + meta_info_path = Path(self.role_dir) / ROLE_FILE_META_INFO + meta_info_path.write_text( + "logo:\n class: fa-solid fa-briefcase\ndisplay: false\n", + encoding="utf-8", + ) + + result = self._run_lookup(LookupModule(), self._base_fake_variables()) + + self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) + + def test_non_bool_display_fails_loudly(self): + fake_variables = self._base_fake_variables() + fake_variables["applications"]["portfolio"]["services"]["dashboard"][ + "display" + ] = "false" + + with self.assertRaisesRegex(AnsibleError, "portfolio"): + self._run_lookup(LookupModule(), fake_variables) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_roles_with_service.py b/tests/unit/python/plugins/lookup/test_roles_with_service.py index d75c1fc3c0..c4ac664f07 100644 --- a/tests/unit/python/plugins/lookup/test_roles_with_service.py +++ b/tests/unit/python/plugins/lookup/test_roles_with_service.py @@ -613,6 +613,37 @@ class RolesWithServiceLookupTests(unittest.TestCase): ("matrix.example.com", "https://web-app-chat.example.com"), ) + def test_dashboard_display_false_drops_the_tile_target(self): + applications = { + "web-app-hidden": { + "services": { + "dashboard": {"enabled": True, "shared": True, "display": False} + }, + "domains": {"canonical": ["hidden.example.com"]}, + }, + "web-app-shown": { + "services": {"dashboard": {"enabled": True, "shared": True}}, + "domains": {"canonical": ["shown.example.com"]}, + }, + } + result = self._run(["dashboard"], applications)[0] + self.assertEqual([r["id"] for r in result], ["web-app-shown"]) + + def test_dashboard_display_true_keeps_the_tile_target(self): + applications = self._card_target_role("dashboard", display=True) + result = self._run(["dashboard"], applications)[0] + self.assertEqual([r["id"] for r in result], ["web-app-chat"]) + + def test_dashboard_non_bool_display_fails_loudly(self): + applications = self._card_target_role("dashboard", display="false") + with self.assertRaisesRegex(AnsibleError, "web-app-chat"): + self._run(["dashboard"], applications) + + def test_other_services_ignore_a_display_key(self): + applications = self._card_target_role("prometheus", display=False) + result = self._run(["prometheus"], applications)[0] + self.assertEqual([r["id"] for r in result], ["web-app-chat"]) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_dashboard.py b/tests/unit/python/utils/roles/applications/test_dashboard.py index 77a6b601a0..d397ea338f 100644 --- a/tests/unit/python/utils/roles/applications/test_dashboard.py +++ b/tests/unit/python/utils/roles/applications/test_dashboard.py @@ -6,7 +6,7 @@ import unittest from ansible.errors import AnsibleError -from utils.roles.applications.dashboard import card_target_key +from utils.roles.applications.dashboard import card_is_displayed, card_target_key class TestCardTargetKey(unittest.TestCase): @@ -42,5 +42,23 @@ class TestCardTargetKey(unittest.TestCase): card_target_key("web-app-foo", {"card": ["element"]}) +class TestCardIsDisplayed(unittest.TestCase): + def test_a_binding_without_the_key_is_displayed(self): + self.assertTrue(card_is_displayed("web-app-foo", {"enabled": True})) + + def test_a_missing_binding_is_displayed(self): + self.assertTrue(card_is_displayed("web-app-foo", None)) + + def test_display_false_hides_the_card(self): + self.assertFalse(card_is_displayed("web-app-foo", {"display": False})) + + def test_display_true_shows_the_card(self): + self.assertTrue(card_is_displayed("web-app-foo", {"display": True})) + + def test_a_string_flag_fails_loudly(self): + with self.assertRaisesRegex(AnsibleError, "web-app-foo"): + card_is_displayed("web-app-foo", {"display": "false"}) + + if __name__ == "__main__": unittest.main() diff --git a/utils/roles/applications/dashboard.py b/utils/roles/applications/dashboard.py index 403df776e5..a18163d2b0 100644 --- a/utils/roles/applications/dashboard.py +++ b/utils/roles/applications/dashboard.py @@ -1,9 +1,12 @@ -"""Target of an application's dashboard card. +"""Target and visibility of an application's dashboard card. A role's ``services.dashboard`` binding MAY name ``card: ``, a key of its ``domains.canonical`` mapping. The card, the Apps menu entry and the dashboard tile-reachability target then point at that domain instead of the role's primary domain. + +``display: false`` on the same binding drops the card, the Apps menu entry and +the tile-reachability target. """ from __future__ import annotations @@ -14,6 +17,33 @@ from ansible.errors import AnsibleError DASHBOARD_SERVICE = "dashboard" CARD_TARGET_KEY = "card" +DISPLAY_KEY = "display" +DISPLAY_PATH = f"services.{DASHBOARD_SERVICE}.{DISPLAY_KEY}" + + +def card_is_displayed(application_id: str, dashboard: Any) -> bool: + """Return whether the application's dashboard card is shown. + + Args: + application_id: the role whose binding is read, named in the error. + dashboard: the role's ``services.dashboard`` binding from the merged + applications. + + Returns: + The ``display`` flag, or ``True`` when the binding sets none. + + Raises: + AnsibleError: the binding sets ``display`` to something other than a + bool. + """ + if not isinstance(dashboard, dict) or DISPLAY_KEY not in dashboard: + return True + display = dashboard[DISPLAY_KEY] + if not isinstance(display, bool): + raise AnsibleError( + f"{application_id}: {DISPLAY_PATH} must be a bool, got {display!r}" + ) + return display def card_target_key(application_id: str, dashboard: Any) -> str: