diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index 7827e87ef5..31be9e32da 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -350,7 +350,7 @@ jobs: timeout-minutes: 350 shell: bash env: - apps: ${{ matrix.apps }} + apps: ${{ matrix.instructions != '' && format('{0},web-app-docs', matrix.apps) || matrix.apps }} variant: ${{ matrix.variant }} disable: ${{ matrix.disable || inputs.disable }} ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log @@ -446,17 +446,3 @@ jobs: timeout-minutes: 15 run: scripts/tests/deploy/swarm/utils/clean/teardown.sh - - name: "📖 Replay the ${{ matrix.apps }} README instructions" - if: ${{ matrix.instructions != '' }} - env: - GUIDE_ROLE: ${{ matrix.apps }} - GUIDE_MODE: ${{ matrix.instructions }} - run: ./scripts/tests/deploy/distros.sh scripts/github/guide/one.sh - - - name: "⬆️ Upload instructions rescue diagnostics" - if: ${{ always() && matrix.instructions != '' && !env.ACT }} - uses: actions/upload-artifact@v7 - with: - name: rescue-diagnostics-instructions-${{ matrix.artifact }} - path: ${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/ - if-no-files-found: ignore diff --git a/cli/administration/deploy/development/inventory/__init__.py b/cli/administration/deploy/development/inventory/__init__.py index a5cea95d12..46022ed2cc 100644 --- a/cli/administration/deploy/development/inventory/__init__.py +++ b/cli/administration/deploy/development/inventory/__init__.py @@ -45,7 +45,8 @@ from .legacy_resolver import ( ) from .payload import _bake_overrides, _resolve_variant_payloads from .planner import filter_plan_to_variants, plan_dev_inventory_matrix -from .spec import DevInventorySpec, PlanEntry +from .spec import DevInventorySpec as DevInventorySpec +from .spec import PlanEntry __all__ = [ "PlanEntry", diff --git a/cli/build/docs/readme/production.py b/cli/build/docs/readme/production.py deleted file mode 100644 index 0f4c5c5f41..0000000000 --- a/cli/build/docs/readme/production.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Print the bash block a role's Quick Setup documents for production. - -The block is not committed: the documentation build renders Quick Setup into -its scratch checkout. CI replays the very same render, so what it executes is -by construction what a reader is told to run. - -Usage: - python -m cli.build.docs.readme.production [--roles-dir DIR] -""" - -from __future__ import annotations - -import argparse -import re -from pathlib import Path - -from cli.build.docs.readme.generate import _app_name, _is_invokable, _managed_blocks -from cli.build.docs.readme.sections import parse_readme -from utils.cache.files import PROJECT_ROOT, read_text -from utils.roles.mapping import ROLE_FILE_README - -HEADING = "### Production" -_BLOCK = re.compile(rf"^{re.escape(HEADING)}$.*?^```bash$\n(.*?)^```$", re.M | re.S) - - -def production_block(role_dir: Path, role_name: str) -> str: - """Return the role's rendered production bash block. - - Args: - role_dir: the role's directory. - role_name: the role id. - - Returns: - The block's body, without the fences. - - Raises: - ValueError: the render carries no Quick Setup production block. - """ - readme = role_dir / ROLE_FILE_README - preamble = parse_readme(read_text(str(readme))).preamble if readme.is_file() else "" - quick_setup = _managed_blocks( - role_dir, - role_name, - _app_name(preamble, role_name), - invokable=_is_invokable(role_name), - ).get("Quick Setup") - match = _BLOCK.search(quick_setup or "") - if match is None: - raise ValueError(f"{role_name}: Quick Setup has no {HEADING} bash block") - return match.group(1) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("role") - parser.add_argument("--roles-dir", default=str(PROJECT_ROOT / "roles")) - args = parser.parse_args(argv) - - role_dir = Path(args.roles_dir) / args.role - if not role_dir.is_dir(): - parser.error(f"Unknown role: {role_dir}") - print(production_block(role_dir, args.role), end="") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/docs/contributing/artefact/files/role/readme_md.md b/docs/contributing/artefact/files/role/readme_md.md index c9474c08b5..1735a476df 100644 --- a/docs/contributing/artefact/files/role/readme_md.md +++ b/docs/contributing/artefact/files/role/readme_md.md @@ -90,7 +90,7 @@ Link text MUST be a descriptive label or the domain name. Never use the full URL | Quick Setup | the role's invokability in `categories.yml`, plus `meta/services.yml` `guide_companions` | | Credits | `galaxy_info.author` in `meta/main.yml` | -To read one without a full build, render it: `python -m cli.build.docs.readme.production ` prints the Production block CI replays. +CI replays the Production block off the published page rather than off this file, so the instructions that are tested are the ones a reader sees. See [instructions.md](../../../tools/github/actions/instructions.md). ## Formatting Rules 📏 diff --git a/docs/contributing/tools/github/actions/instructions.md b/docs/contributing/tools/github/actions/instructions.md index ff2ed50334..8dc2235e4f 100644 --- a/docs/contributing/tools/github/actions/instructions.md +++ b/docs/contributing/tools/github/actions/instructions.md @@ -1,27 +1,45 @@ # Instructions replay 📖 -How CI proves that a role README's `### Production` block still deploys the role. +How CI proves that the `### Production` block a role's documentation publishes still deploys that role. For the workflow catalog see [workflows.md](workflows.md). ## Where it runs 🏗️ -The replay rides along on a deploy row of the sweep instead of holding a job of its own. `utils/roles/guide.py` marks one row per role: +The replay rides along on a deploy row of the sweep instead of holding a job of its own. [guide.py](../../../../../utils/roles/guide.py) marks one row per role: -- the role's **smallest variant**, the one whose `meta/variants.yml` overlay enables the fewest services, because that is the shape the README describes; -- only when the README carries a `### Production` heading; +- the role's **smallest variant**, the one whose `meta/variants.yml` overlay enables the fewest services, because that is the shape the instructions describe; +- only when the role is invokable, because that is what makes the documentation build emit a Production block for it; - only when the guide's own mode (`compose` for a role shipping a container stack, `host` otherwise) is enabled in `meta/services.yml` and not listed under `skip` in `meta/tests.yml`. The marked row carries `instructions: ` in the matrix JSON and a 📖 in its job title, between the variant number and the ⭐ of a priority row. ## What the row does 🚀 -`.github/workflows/call-test-deploy.yml` runs the replay as the job's last step, after the row's own deploy and after the swarm teardown: the replay deploys the role a second time and needs the runner's ports. It calls `scripts/tests/deploy/distros.sh scripts/github/guide/one.sh` with `GUIDE_ROLE` set to the row's app and `GUIDE_MODE` to the mode the marker carries, which is independent of the deploy mode the rotation gave the row. A swarm row therefore still replays a `compose` guide. +The marker adds `web-app-docs` to that row's `apps`, so the documentation is deployed beside the role under test. Its own CLI test then reads the role's page, takes the Production block out of the rendered HTML, and runs it. -A red deploy skips the replay: the step carries no `always()`, so the runner state a failed deploy leaves behind never reaches the guide. +Reading the block off the page rather than out of the tree is the point: a reader copies from the site, so that is what has to work. Nothing in the repository is consulted at replay time. + +## The machine 🐳 + +Placeholders (``, ``, ``) are filled from the deployment's own values, `HOST` is forced to `localhost`, and `-it` is dropped. + +The block then runs inside a throwaway machine, never on the stack host itself. [machine.sh](../../../../../roles/web-app-docs/files/test/machine.sh) brings it up through [files/test/compose.yml](../../../../../roles/web-app-docs/files/test/compose.yml) under the project `docs-guide-`, and tears it down with `down -v --rmi local`. + +The machine starts from the **distribution base image**, not from an image this project publishes, so the replay also exercises the installation. `MACHINE_BASE_IMAGE` is read as `INFINITO_PARENT_IMAGE` out of the `.env` of the mounted checkout, where the env layer has already composed it from the [meta/distros.yml](../../../../../meta/distros.yml) SPOT and honoured any `custom.env` override. A missing `.env` fails the test with a pointer to `make dotenv`. The one build step of [files/test/Dockerfile](../../../../../roles/web-app-docs/files/test/Dockerfile) runs [init.sh](../../../../../roles/web-app-docs/files/test/init.sh), which returns immediately when the base already carries `/sbin/init`. + +Once the machine is up, the repository checkout mounted into it is prepared with [scripts/tests/workspace/base/01_install.sh](../../../../../scripts/tests/workspace/base/01_install.sh), the same step the workspace suite uses: system packages through `INFINITO_PACKAGE_INSTALL_SCRIPT`, then `make install`. Only then is the block replayed, so it meets a machine prepared exactly the way the documentation tells a reader to prepare one. + +One service serves both block shapes, because the demands of the two overlap: a host install needs `/sbin/init` as the entrypoint and the cgroup mount to deploy systemd units, and it needs the daemon socket too, since a role without a compose template of its own still pulls in containerised dependencies. A containerised block needs that socket to nest its `docker run` one level below the machine, and a work directory mounted at the same absolute path on both sides so the bind sources it names resolve on the daemon. The union is the machine, and the block decides what it does with it. + +The block is replayed once systemd reports `running` or `degraded`. A block that opens with `git clone` is a host install: those two lines are dropped and the mounted checkout is used instead, so the replay runs against the tree under test. ## Reading a failure 🔍 -The replay writes its rescue snapshots under `INFINITO_RESCUE_DIAGNOSTICS_BASE//`, uploaded as `rescue-diagnostics-instructions-`. The deploy's own snapshots live in `rescue-diagnostics-`. +The CLI test prints the block it fetched and the output of the replay. The role's own deploy snapshots live in `rescue-diagnostics-`. -To reproduce one locally, export `GUIDE_ROLE`, `GUIDE_MODE`, `INFINITO_DISTRO` and run `scripts/github/guide/one.sh`. +To reproduce one locally, deploy the role together with the documentation and let the CLI test run: + +```bash +make compose-deploy mode=reinstall apps=,web-app-docs full_cycle=false +``` diff --git a/plugins/lookup/deployment.py b/plugins/lookup/deployment.py index b74d65abac..a10931a144 100644 --- a/plugins/lookup/deployment.py +++ b/plugins/lookup/deployment.py @@ -25,6 +25,16 @@ def _coerce_to_list(raw: Any) -> list[str]: return [str(item) for item in raw] +def running_apps(vars_: dict[str, Any]) -> list[str]: + """Return the apps the operator asked for, the round's groups otherwise. + + Args: + vars_: the task variables the lookup was called with. + """ + whitelist = _coerce_to_list(vars_.get("APPLICATIONS_WHITELIST")) + return whitelist or _coerce_to_list(vars_.get("group_names")) + + class LookupModule(LookupBase): def run( self, @@ -48,7 +58,7 @@ class LookupModule(LookupBase): if cached is not None: return [cached] - running = whitelist or groups + running = running_apps(vars_) deployed = list(running) if runtime in _EPHEMERAL_RUNTIMES else list(groups) result = { "whitelist": whitelist, diff --git a/plugins/lookup/guide_role.py b/plugins/lookup/guide_role.py new file mode 100644 index 0000000000..6388a1c188 --- /dev/null +++ b/plugins/lookup/guide_role.py @@ -0,0 +1,43 @@ +"""Which deployed role's published guide a replay should read. + +``lookup('guide_role', application_id)`` picks the first invokable app the round +deployed beside ``application_id``. Invokability comes from +:func:`utils.roles.validation.invokable.list_invokable_app_ids`, so no caller +re-derives it from role-name prefixes. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.plugins.lookup import LookupBase + +from plugins.lookup.deployment import running_apps +from utils.roles.validation.invokable import list_invokable_app_ids + + +def guide_role( + application_id: str, running: list[str], invokable: list[str] +) -> str: + """Return the app whose guide is replayed, ``application_id`` when it is alone. + + Args: + application_id: the role asking, which is skipped as its own peer. + running: the apps this round deploys. + invokable: every app that publishes a guide. + """ + known = set(invokable) + peers = [app for app in running if app != application_id and app in known] + return peers[0] if peers else application_id + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any], + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + application_id = str(terms[0]) if terms else str(vars_.get("application_id", "")) + return [guide_role(application_id, running_apps(vars_), list_invokable_app_ids())] diff --git a/roles/web-app-docs/files/python/infinito_docs/build_queue.py b/roles/web-app-docs/files/python/infinito_docs/build_queue.py new file mode 100644 index 0000000000..8456c8ad5c --- /dev/null +++ b/roles/web-app-docs/files/python/infinito_docs/build_queue.py @@ -0,0 +1,110 @@ +"""The build queue, the cross-replica builder lock and the daemon loop. + +``Queue`` is a mixin of :class:`infinito_docs.library.Library`. A marker is a +file named ``version`` or ``version:code``; the background lane holds the +languages nobody is waiting on. +""" + +from __future__ import annotations + +import fcntl +import subprocess +import sys +import time + +from infinito_docs.builder import DEPLOYED, QUEUE_SEPARATOR + +POLL_SECONDS = 2 +BACKGROUND_LANE = "background" + + +class Queue: + def request(self, version, code=None, background=False): + """Queue a build of ``version``, or of one of its translated sites. + + Args: + version: ``latest`` or a release tag. + code: ISO 639-1 code to build instead of the version's own site. + background: queue behind every language a visitor asked for. + """ + head, _ = self.refs() + if not head and version != DEPLOYED: + return + if code is None: + if self._current(version, head): + return + marker = version + elif not self.translates(version, code) or self._translation_current( + version, code, head + ): + return + else: + marker = f"{version}{QUEUE_SEPARATOR}{code}" + lane = self.queue / BACKGROUND_LANE if background else self.queue + lane.mkdir(parents=True, exist_ok=True) + if background and (self.queue / marker).exists(): + return + (lane / marker).touch(exist_ok=True) + + def _dequeue(self, marker): + """Drop ``marker`` from both lanes. + + Args: + marker: queue file name, ``version`` or ``version:code``. + """ + (self.queue / marker).unlink(missing_ok=True) + (self.queue / BACKGROUND_LANE / marker).unlink(missing_ok=True) + + def next_queued(self): + """Return the oldest marker a visitor is waiting on, else the oldest background one.""" + for lane in (self.queue, self.queue / BACKGROUND_LANE): + if not lane.is_dir(): + continue + waiting = sorted( + (marker for marker in lane.iterdir() if marker.is_file()), + key=lambda marker: marker.stat().st_mtime, + ) + if waiting: + return waiting[0].name + return None + + def acquire_builder(self): + """Try to become the builder of all replicas without blocking. + + Returns: + ``True`` while this process holds the builder lock. + """ + if self._lock_handle is not None: + return True + self.lock_file.parent.mkdir(parents=True, exist_ok=True) + handle = self.lock_file.open("a+") + try: + fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + handle.close() + return False + self._lock_handle = handle + return True + + def run_builder(self, interval): + while not self.acquire_builder(): + time.sleep(POLL_SECONDS) + if self.snapshot.is_dir(): + self.request(DEPLOYED) + next_fetch = 0.0 + while True: + if time.monotonic() >= next_fetch: + try: + self.fetch() + except (OSError, subprocess.CalledProcessError) as exc: + print(f"fetch of {self.repository} failed: {exc}", file=sys.stderr) + next_fetch = time.monotonic() + interval + marker = self.next_queued() + if marker is None: + time.sleep(POLL_SECONDS) + continue + version, separator, code = marker.partition(QUEUE_SEPARATOR) + if separator: + self.build_language(version, code) + else: + self.build(version) diff --git a/roles/web-app-docs/files/python/infinito_docs/builder.py b/roles/web-app-docs/files/python/infinito_docs/builder.py index 68c7470b75..bff78f9500 100644 --- a/roles/web-app-docs/files/python/infinito_docs/builder.py +++ b/roles/web-app-docs/files/python/infinito_docs/builder.py @@ -1,10 +1,8 @@ """Build execution for :class:`infinito_docs.library.Library`. -Split out of ``library.py`` to keep both files under the repository's Python -line cap. ``Builder`` is a mixin: it owns the sphinx runs, the checkout and the -atomic publish, and reaches the queue, state and path helpers through ``self``. -The constants and the two catalog helpers live here so the import runs one way, -from ``library`` to ``builder``. +``Builder`` is a mixin: it owns the sphinx runs, the checkout and the atomic +publish, and reaches the queue, state and path helpers through ``self``. The +constants live here so the import runs one way, from ``library`` to ``builder``. """ from __future__ import annotations @@ -16,10 +14,8 @@ import subprocess import tarfile import threading -from babel.messages.pofile import read_po - +from infinito_docs.catalogs import translated_languages from infinito_docs.commands import generate_commands, progress_of -from utils.cache.yaml import load_yaml_str LATEST = "latest" DEPLOYED = "deployed" @@ -27,37 +23,6 @@ LOG_TAIL = 40 QUEUE_SEPARATOR = ":" -def translated_languages(src): - """Return the languages of ``src`` and those its ``docs`` catalogs translate. - - Args: - src: checkout of the version to document. - - Returns: - ``(known, translated)``: every language of ``meta/languages.yml`` - mapped to its native name, and the codes whose ``docs.po`` holds at - least one translation. - """ - languages_file = src / "meta" / "languages.yml" - if not languages_file.is_file(): - return {}, [] - known = { - str(code): str((entry or {}).get("native", code)) - for code, entry in ( - load_yaml_str(languages_file.read_text(encoding="utf-8")) or {} - ).items() - } - translated = [] - for code in sorted(known): - catalog = src / "locale" / code / "LC_MESSAGES" / "docs.po" - if not catalog.is_file(): - continue - with catalog.open("rb") as handle: - if any(m.id and m.string and not m.fuzzy for m in read_po(handle)): - translated.append(code) - return known, translated - - def write_json(path, payload): staging = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}") staging.write_text(json.dumps(payload), encoding="utf-8") @@ -65,6 +30,16 @@ def write_json(path, payload): class Builder: + def _append_log(self, state, line): + state["log"] = [*state["log"][-(LOG_TAIL - 1) :], line] + + def _ready(self, marker): + self._save_state(marker, state="ready", phase="", progress=100, log=[]) + + def _failed(self, marker, state, exc): + self._append_log(state, str(exc)) + self._save_state(marker, **{**state, "state": "failed"}) + def _run(self, version, state, command, env, cwd): with subprocess.Popen( command, @@ -76,7 +51,7 @@ class Builder: ) as process: for line in process.stdout: progress = progress_of(line, state["progress"]) - state["log"] = [*state["log"][-(LOG_TAIL - 1) :], line.rstrip()] + self._append_log(state, line.rstrip()) if progress != state["progress"]: state["progress"] = progress self._save_state(version, **state) @@ -97,7 +72,7 @@ class Builder: if self._current(version, head): self._dequeue(version) return - ref = {LATEST: head, DEPLOYED: self.snapshot_ref()}.get(version, version) + ref = self._wanted_ref(version, head) work = self.scratch / version src, conf, out = work / "src", work / "conf", work / "out" tooling = str(self.package_dir.parent) @@ -143,12 +118,11 @@ class Builder: {"known": known, "translated": translated}, ) self._publish(version, out / "html", ref) - self._save_state(version, state="ready", phase="", progress=100, log=[]) + self._ready(version) for code in translated: self.request(version, code, background=True) except (OSError, subprocess.CalledProcessError, tarfile.TarError) as exc: - state["log"] = [*state["log"][-(LOG_TAIL - 1) :], str(exc)] - self._save_state(version, **{**state, "state": "failed"}) + self._failed(version, state, exc) finally: self._dequeue(version) shutil.rmtree(work, ignore_errors=True) @@ -199,7 +173,7 @@ class Builder: self._dequeue(marker) self.request(version) return - ref = {LATEST: head, DEPLOYED: self.snapshot_ref()}.get(version, version) + ref = self._wanted_ref(version, head) work = self.scratch / f"{version}{QUEUE_SEPARATOR}{code}" src, conf = work / "src", work / "conf" target = work / "out" @@ -234,10 +208,9 @@ class Builder: work, ) self._publish_site(self.translations / version, code, target / "html", ref) - self._save_state(marker, state="ready", phase="", progress=100, log=[]) + self._ready(marker) except (OSError, subprocess.CalledProcessError, tarfile.TarError) as exc: - state["log"] = [*state["log"][-(LOG_TAIL - 1) :], str(exc)] - self._save_state(marker, **{**state, "state": "failed"}) + self._failed(marker, state, exc) finally: shutil.rmtree(work, ignore_errors=True) self._dequeue(marker) diff --git a/roles/web-app-docs/files/python/infinito_docs/catalogs.py b/roles/web-app-docs/files/python/infinito_docs/catalogs.py new file mode 100644 index 0000000000..3ab62385dc --- /dev/null +++ b/roles/web-app-docs/files/python/infinito_docs/catalogs.py @@ -0,0 +1,38 @@ +"""Which languages a documented checkout declares, and which it translates.""" + +from __future__ import annotations + +from babel.messages.pofile import read_po + +from utils.cache.yaml import load_yaml_str + + +def translated_languages(src): + """Return the languages of ``src`` and those its ``docs`` catalogs translate. + + Args: + src: checkout of the version to document. + + Returns: + ``(known, translated)``: every language of ``meta/languages.yml`` + mapped to its native name, and the codes whose ``docs.po`` holds at + least one translation. + """ + languages_file = src / "meta" / "languages.yml" + if not languages_file.is_file(): + return {}, [] + known = { + str(code): str((entry or {}).get("native", code)) + for code, entry in ( + load_yaml_str(languages_file.read_text(encoding="utf-8")) or {} + ).items() + } + translated = [] + for code in sorted(known): + catalog = src / "locale" / code / "LC_MESSAGES" / "docs.po" + if not catalog.is_file(): + continue + with catalog.open("rb") as handle: + if any(m.id and m.string and not m.fuzzy for m in read_po(handle)): + translated.append(code) + return known, translated diff --git a/roles/web-app-docs/files/python/infinito_docs/library.py b/roles/web-app-docs/files/python/infinito_docs/library.py index 340278b510..88c32b0a34 100644 --- a/roles/web-app-docs/files/python/infinito_docs/library.py +++ b/roles/web-app-docs/files/python/infinito_docs/library.py @@ -1,30 +1,27 @@ from __future__ import annotations -import fcntl import hashlib import json import re import subprocess -import sys import threading import time from pathlib import Path +from .build_queue import Queue from .builder import ( DEPLOYED, LATEST, - QUEUE_SEPARATOR, Builder, write_json, ) +from .sites import Sites -POLL_SECONDS = 2 -BACKGROUND_LANE = "background" REFS_TTL_SECONDS = 10 TAG = re.compile(r"^v(\d+)\.(\d+)\.(\d+)$") -class Library(Builder): +class Library(Sites, Queue, Builder): """Mirror of the documented repository and the site of every version. Args: @@ -109,13 +106,6 @@ class Library(Builder): self._snapshot_ref = digest.hexdigest() return self._snapshot_ref - def built_ref(self, version): - stamp = self.sites / version / "ref" - return stamp.read_text(encoding="utf-8").strip() if stamp.is_file() else "" - - def servable(self, version): - return (self.sites / version / "html" / "index.html").is_file() - def _wanted_ref(self, version, head): """Return the ref ``version`` should have been built from. @@ -136,41 +126,10 @@ class Library(Builder): and self._language_index_is_current(version) ) - def translation_ref(self, version, code): - """Return the ref the translated site of ``code`` was built from. - - Args: - version: ``latest`` or a release tag. - code: ISO 639-1 code. - """ - stamp = self.translations / version / code / "ref" - return stamp.read_text(encoding="utf-8").strip() if stamp.is_file() else "" - def _translation_current(self, version, code, head): - return ( - self.translation_servable(version, code) - and self.translation_ref(version, code) - == self._wanted_ref(version, head) - ) - - def _language_index_is_current(self, version) -> bool: - """Whether the version's language index was written by this code. - - An index from before the split lists only the known languages, so the - translated ones are unknown and no language can be requested. Calling - that version current would leave it in that state forever, because only - a build rewrites the index. - - Args: - version: ``latest`` or a release tag. - """ - path = self.translations / version / "languages.json" - if not path.is_file(): - return True - try: - return "translated" in json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return False + return self.translation_servable(version, code) and self.translation_ref( + version, code + ) == self._wanted_ref(version, head) def _state(self, version): path = self.states / f"{version}.json" @@ -211,73 +170,6 @@ class Library(Builder): ) return report - def request(self, version, code=None, background=False): - """Queue a build of ``version``, or of one of its translated sites. - - Args: - version: ``latest`` or a release tag. - code: ISO 639-1 code to build instead of the version's own site. - background: queue behind every language a visitor asked for. - """ - head, _ = self.refs() - if not head and version != DEPLOYED: - return - if code is None: - if self._current(version, head): - return - marker = version - elif not self.translates(version, code) or self._translation_current( - version, code, head - ): - return - else: - marker = f"{version}{QUEUE_SEPARATOR}{code}" - lane = self.queue / BACKGROUND_LANE if background else self.queue - lane.mkdir(parents=True, exist_ok=True) - if background and (self.queue / marker).exists(): - return - (lane / marker).touch(exist_ok=True) - - def _dequeue(self, marker): - """Drop ``marker`` from both lanes. - - Args: - marker: queue file name, ``version`` or ``version:code``. - """ - (self.queue / marker).unlink(missing_ok=True) - (self.queue / BACKGROUND_LANE / marker).unlink(missing_ok=True) - - def next_queued(self): - """Return the oldest marker a visitor is waiting on, else the oldest background one.""" - for lane in (self.queue, self.queue / BACKGROUND_LANE): - if not lane.is_dir(): - continue - waiting = sorted( - (marker for marker in lane.iterdir() if marker.is_file()), - key=lambda marker: marker.stat().st_mtime, - ) - if waiting: - return waiting[0].name - return None - - def acquire_builder(self): - """Try to become the builder of all replicas without blocking. - - Returns: - ``True`` while this process holds the builder lock. - """ - if self._lock_handle is not None: - return True - self.lock_file.parent.mkdir(parents=True, exist_ok=True) - handle = self.lock_file.open("a+") - try: - fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: - handle.close() - return False - self._lock_handle = handle - return True - def fetch(self): if (self.mirror / "HEAD").is_file(): self._git("remote", "update", "--prune") @@ -309,92 +201,3 @@ class Library(Builder): for version in self.versions(): if self.servable(version): self.request(version) - - def run_builder(self, interval): - while not self.acquire_builder(): - time.sleep(POLL_SECONDS) - if self.snapshot.is_dir(): - self.request(DEPLOYED) - next_fetch = 0.0 - while True: - if time.monotonic() >= next_fetch: - try: - self.fetch() - except (OSError, subprocess.CalledProcessError) as exc: - print(f"fetch of {self.repository} failed: {exc}", file=sys.stderr) - next_fetch = time.monotonic() + interval - marker = self.next_queued() - if marker is None: - time.sleep(POLL_SECONDS) - continue - version, separator, code = marker.partition(QUEUE_SEPARATOR) - if separator: - self.build_language(version, code) - else: - self.build(version) - - def resolve(self, version, rest): - """Return the file a request for ``rest`` in ``version`` maps to. - - Args: - version: a built version. - rest: the request path below the version, already unquoted. - - Returns: - The file inside the version's site, or ``None`` when the site has - no such file or the path escapes it. - """ - return self._resolve(self.sites / version / "html", rest) - - def _language_index(self, version): - try: - payload = json.loads( - (self.translations / version / "languages.json").read_text( - encoding="utf-8" - ) - ) - except (OSError, ValueError): - return {} - if isinstance(payload.get("known"), dict): - return payload - return {"known": payload, "translated": []} - - def languages(self, version): - """Return the languages of ``version`` and the ones with a built site. - - Args: - version: ``latest`` or a release tag. - - Returns: - ``(known, built)``: every language code of the version mapped to - its native name, and the codes whose translated site is servable. - """ - known = self._language_index(version).get("known") or {} - built = [ - code for code in sorted(known) if self.translation_servable(version, code) - ] - return known, built - - def translates(self, version, code): - """Return whether ``version`` carries translations for ``code``. - - Args: - version: ``latest`` or a release tag. - code: ISO 639-1 code. - """ - return code in (self._language_index(version).get("translated") or []) - - def translation_servable(self, version, code): - return (self.translations / version / code / "html" / "index.html").is_file() - - def resolve_translation(self, version, code, rest): - return self._resolve(self.translations / version / code / "html", rest) - - def _resolve(self, site, rest): - root = site.resolve() - target = (root / rest).resolve() - if target != root and root not in target.parents: - return None - if target.is_dir(): - target /= "index.html" - return target if target.is_file() else None diff --git a/roles/web-app-docs/files/python/infinito_docs/sites.py b/roles/web-app-docs/files/python/infinito_docs/sites.py new file mode 100644 index 0000000000..fb95af4fe9 --- /dev/null +++ b/roles/web-app-docs/files/python/infinito_docs/sites.py @@ -0,0 +1,114 @@ +"""The built site trees on disk: what exists, what it was built from, and +which file a request maps to. + +``Sites`` is a mixin of :class:`infinito_docs.library.Library` and reads only +``self.sites`` and ``self.translations``. +""" + +from __future__ import annotations + +import json + + +class Sites: + def built_ref(self, version): + stamp = self.sites / version / "ref" + return stamp.read_text(encoding="utf-8").strip() if stamp.is_file() else "" + + def servable(self, version): + return (self.sites / version / "html" / "index.html").is_file() + + def translation_ref(self, version, code): + """Return the ref the translated site of ``code`` was built from. + + Args: + version: ``latest`` or a release tag. + code: ISO 639-1 code. + """ + stamp = self.translations / version / code / "ref" + return stamp.read_text(encoding="utf-8").strip() if stamp.is_file() else "" + + def translation_servable(self, version, code): + return (self.translations / version / code / "html" / "index.html").is_file() + + def _language_index(self, version): + try: + payload = json.loads( + (self.translations / version / "languages.json").read_text( + encoding="utf-8" + ) + ) + except (OSError, ValueError): + return {} + if isinstance(payload.get("known"), dict): + return payload + return {"known": payload, "translated": []} + + def _language_index_is_current(self, version) -> bool: + """Whether the version's language index was written by this code. + + An index from before the split lists only the known languages, so the + translated ones are unknown and no language can be requested. Calling + that version current would leave it in that state forever, because only + a build rewrites the index. + + Args: + version: ``latest`` or a release tag. + """ + path = self.translations / version / "languages.json" + if not path.is_file(): + return True + try: + return "translated" in json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + + def languages(self, version): + """Return the languages of ``version`` and the ones with a built site. + + Args: + version: ``latest`` or a release tag. + + Returns: + ``(known, built)``: every language code of the version mapped to + its native name, and the codes whose translated site is servable. + """ + known = self._language_index(version).get("known") or {} + built = [ + code for code in sorted(known) if self.translation_servable(version, code) + ] + return known, built + + def translates(self, version, code): + """Return whether ``version`` carries translations for ``code``. + + Args: + version: ``latest`` or a release tag. + code: ISO 639-1 code. + """ + return code in (self._language_index(version).get("translated") or []) + + def resolve(self, version, rest): + """Return the file a request for ``rest`` in ``version`` maps to. + + Args: + version: a built version. + rest: the request path below the version, already unquoted. + + Returns: + The file inside the version's site, or ``None`` when the site has + no such file or the path escapes it. + """ + return self._resolve(self.sites / version / "html", rest) + + def resolve_translation(self, version, code, rest): + return self._resolve(self.translations / version / code / "html", rest) + + def _resolve(self, site, rest): + root = site.resolve() + target = (root / rest).resolve() + if target != root and root not in target.parents: + return None + if target.is_dir(): + target /= "index.html" + return target if target.is_file() else None diff --git a/roles/web-app-docs/files/test/.dockerignore b/roles/web-app-docs/files/test/.dockerignore new file mode 100644 index 0000000000..2b1d91ce21 --- /dev/null +++ b/roles/web-app-docs/files/test/.dockerignore @@ -0,0 +1,3 @@ +* +!Dockerfile +!init.sh diff --git a/roles/web-app-docs/files/test/.nocheck b/roles/web-app-docs/files/test/.nocheck new file mode 100644 index 0000000000..a0fdb0bf8c --- /dev/null +++ b/roles/web-app-docs/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; the CLI runner stages roles//files/test/ by path. diff --git a/roles/web-app-docs/files/test/Dockerfile b/roles/web-app-docs/files/test/Dockerfile new file mode 100644 index 0000000000..3fe1cf46bb --- /dev/null +++ b/roles/web-app-docs/files/test/Dockerfile @@ -0,0 +1,7 @@ +ARG MACHINE_BASE_IMAGE +FROM ${MACHINE_BASE_IMAGE} + +COPY init.sh /tmp/docs-guide-init.sh +RUN /bin/sh /tmp/docs-guide-init.sh && rm -f /tmp/docs-guide-init.sh + +ENTRYPOINT ["/sbin/init"] diff --git a/roles/web-app-docs/files/test/compose.yml b/roles/web-app-docs/files/test/compose.yml new file mode 100644 index 0000000000..979686e064 --- /dev/null +++ b/roles/web-app-docs/files/test/compose.yml @@ -0,0 +1,17 @@ +services: + machine: + build: + context: . + args: + MACHINE_BASE_IMAGE: ${MACHINE_BASE_IMAGE} + init: false + privileged: true + cgroup: host + tmpfs: + - /run + - /run/lock + volumes: + - ${DOCS_TEST_SRC_DIR}:${DOCS_TEST_SRC_DIR} + - ${DOCS_TEST_WORK}:${DOCS_TEST_WORK} + - /sys/fs/cgroup:/sys/fs/cgroup:rw + - /var/run/docker.sock:/var/run/docker.sock diff --git a/roles/web-app-docs/files/test/extract.py b/roles/web-app-docs/files/test/extract.py new file mode 100644 index 0000000000..62d63dbade --- /dev/null +++ b/roles/web-app-docs/files/test/extract.py @@ -0,0 +1,141 @@ +"""Read a role's production instructions off the documentation site. + +Standard library only: this is staged onto the stack host, which carries no +repository and no virtualenv. + +The site builds a version on first request and answers 202 until it is ready, +so the fetch polls. The block is taken from the first ``
`` after the
+Production heading, which is what a reader copies.
+
+Usage:
+  extract.py   [--timeout SECONDS]
+"""
+
+from __future__ import annotations
+
+import argparse
+import html
+import sys
+import time
+import urllib.error
+import urllib.request
+from html.parser import HTMLParser
+
+VERSION = "latest"
+HEADING = "production"
+BUILDING = 202
+
+
+class Block(HTMLParser):
+    """Collect the text of the first ``
`` after the Production heading."""
+
+    def __init__(self) -> None:
+        super().__init__(convert_charrefs=True)
+        self.reached = False
+        self.inside = False
+        self.done = False
+        self.parts: list[str] = []
+        self._depth = 0
+
+    def handle_starttag(self, tag, attrs):
+        if self.done:
+            return
+        if not self.reached and dict(attrs).get("id") == HEADING:
+            self.reached = True
+        elif self.reached and tag == "pre":
+            self.inside = True
+            self._depth = 0
+        elif self.inside:
+            self._depth += 1
+
+    def handle_endtag(self, tag):
+        if self.inside and tag == "pre" and self._depth == 0:
+            self.inside = False
+            self.done = True
+        elif self.inside:
+            self._depth = max(0, self._depth - 1)
+
+    def handle_data(self, data):
+        if self.inside:
+            self.parts.append(data)
+
+    @property
+    def text(self) -> str:
+        return html.unescape("".join(self.parts))
+
+
+def page_url(base: str, role: str) -> str:
+    """Return the address of ``role``'s documentation page.
+
+    Args:
+        base: scheme, host and port of the documentation service.
+        role: the role whose page to read.
+    """
+    return f"{base.rstrip('/')}/{VERSION}/roles/{role}/README.html"
+
+
+def fetch(url: str, timeout: float, poll: float = 15.0) -> str:
+    """Return the page body, waiting while the site builds the version.
+
+    Args:
+        url: the page to read.
+        timeout: seconds to keep waiting for the build.
+        poll: seconds between attempts.
+
+    Raises:
+        TimeoutError: the site kept answering 202 until the deadline.
+    """
+    deadline = time.monotonic() + timeout
+    while True:
+        try:
+            with urllib.request.urlopen(url, timeout=60) as response:  # noqa: S310 — http to the local stack
+                if response.status != BUILDING:
+                    return response.read().decode("utf-8", errors="replace")
+        except urllib.error.HTTPError as exc:
+            if exc.code != BUILDING:
+                raise
+        except urllib.error.URLError as exc:
+            print(
+                f"  {url} not answering yet ({exc.reason})", file=sys.stderr, flush=True
+            )
+        if time.monotonic() >= deadline:
+            raise TimeoutError(f"{url}: still unavailable after {timeout:.0f}s")
+        print(
+            f"  waiting for the page; retrying in {poll:.0f}s",
+            file=sys.stderr,
+            flush=True,
+        )
+        time.sleep(poll)
+
+
+def block(base: str, role: str, timeout: float) -> str:
+    """Return the production commands ``role``'s published page shows.
+
+    Args:
+        base: documentation service URL.
+        role: the role whose instructions to read.
+        timeout: seconds to wait for an on-demand build.
+
+    Raises:
+        ValueError: the page carries no production block.
+    """
+    parser = Block()
+    parser.feed(fetch(page_url(base, role), timeout))
+    if not parser.text.strip():
+        raise ValueError(f"{role}: the published page shows no {HEADING} block")
+    return parser.text
+
+
+def main(argv: list[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+    parser.add_argument("base")
+    parser.add_argument("role")
+    parser.add_argument("--timeout", type=float, default=2400)
+    args = parser.parse_args(argv)
+
+    print(block(args.base, args.role, args.timeout), end="")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/roles/web-app-docs/files/test/init.sh b/roles/web-app-docs/files/test/init.sh
new file mode 100644
index 0000000000..3b5bd176f0
--- /dev/null
+++ b/roles/web-app-docs/files/test/init.sh
@@ -0,0 +1,33 @@
+#!/bin/sh
+# shellcheck shell=sh
+#
+# Installs systemd into whatever it runs in: the Dockerfile beside it RUNs it
+# in a build stage, never run it on a host.
+
+set -e
+
+[ -e /sbin/init ] && exit 0
+
+APT_OPTS="-o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30"
+
+if command -v apt-get >/dev/null 2>&1; then
+	# shellcheck disable=SC2086
+	apt-get $APT_OPTS update
+	# shellcheck disable=SC2086
+	DEBIAN_FRONTEND=noninteractive apt-get $APT_OPTS install -y --no-install-recommends \
+		systemd systemd-sysv libnss-myhostname
+	rm -rf /var/lib/apt/lists/*
+elif command -v dnf >/dev/null 2>&1; then
+	dnf install -y systemd
+	dnf clean all
+elif command -v pacman >/dev/null 2>&1; then
+	pacman -Sy --noconfirm --needed archlinux-keyring
+	pacman -Syu --noconfirm --needed systemd
+	rm -rf /var/cache/pacman/pkg/*
+else
+	echo "no supported package manager to install an init with" >&2
+	exit 1
+fi
+
+grep -q myhostname /etc/nsswitch.conf || sed -i "s/^hosts:.*/& myhostname/" /etc/nsswitch.conf
+[ -e /sbin/init ] || ln -sf /lib/systemd/systemd /sbin/init
diff --git a/roles/web-app-docs/files/test/machine.sh b/roles/web-app-docs/files/test/machine.sh
new file mode 100644
index 0000000000..52bc55d41a
--- /dev/null
+++ b/roles/web-app-docs/files/test/machine.sh
@@ -0,0 +1,81 @@
+#!/usr/bin/env bash
+# shellcheck shell=bash
+#
+# Args:
+#   $1  the prepared production block
+#
+# Env (test.env):
+#   DOCS_TEST_ROLE       role under replay, names the compose project
+#   DOCS_TEST_SRC_DIR    repository checkout, mounted into the machine
+
+set -euo pipefail
+
+BLOCK="${1:?}"
+: "${DOCS_TEST_ROLE:?}"
+: "${DOCS_TEST_SRC_DIR:?}"
+
+STAGE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT="docs-guide-${DOCS_TEST_ROLE}"
+PREPARE="scripts/tests/workspace/base/01_install.sh"
+SYSTEMD_TRIES=40
+SYSTEMD_DELAY=3
+
+export DOCS_TEST_WORK="${STAGE}/work"
+mkdir -p "${DOCS_TEST_WORK}"
+
+machine() {
+	docker compose --project-directory "${STAGE}" -p "${PROJECT}" "$@"
+}
+
+in_machine() {
+	machine exec -T -w "${DOCS_TEST_SRC_DIR}" machine "$@"
+}
+
+cleanup() {
+	machine down -v --rmi local --remove-orphans >/dev/null 2>&1
+	return 0
+}
+
+base_image() {
+	local env_file="${DOCS_TEST_SRC_DIR}/.env"
+	if [ ! -r "${env_file}" ]; then
+		echo "${env_file} is missing; run 'make dotenv' so the machine knows its base image" >&2
+		return 1
+	fi
+	# shellcheck source=/dev/null
+	source <(grep -h '^INFINITO_PARENT_IMAGE=' "${env_file}")
+	printf '%s' "${INFINITO_PARENT_IMAGE:?}"
+}
+
+await_systemd() {
+	local state=""
+	for _ in $(seq 1 "${SYSTEMD_TRIES}"); do
+		state="$(machine exec -T machine systemctl is-system-running 2>/dev/null || true)"
+		case "${state}" in running | degraded) return 0 ;; esac
+		sleep "${SYSTEMD_DELAY}"
+	done
+	echo "systemd never came up in the ${DOCS_TEST_ROLE} machine (last: ${state:-unknown})" >&2
+	return 1
+}
+
+if grep -q '^git clone ' "${BLOCK}"; then
+	echo "=== Dropping the clone; ${DOCS_TEST_SRC_DIR} is the tree under test ==="
+	sed -i -E '/^git clone /d; /^cd core$/d' "${BLOCK}"
+	workdir="${DOCS_TEST_SRC_DIR}"
+else
+	workdir="${DOCS_TEST_WORK}"
+fi
+
+MACHINE_BASE_IMAGE="$(base_image)"
+export MACHINE_BASE_IMAGE
+
+echo "=== Machine: ${MACHINE_BASE_IMAGE} ==="
+trap cleanup EXIT
+machine up -d --build --pull always
+await_systemd
+
+echo "=== Preparing it for Infinito.Nexus (${PREPARE}) ==="
+in_machine bash "${PREPARE}"
+
+echo "=== Replaying the instructions in that machine ==="
+machine exec -T -w "${workdir}" machine bash -s <"${BLOCK}"
diff --git a/roles/web-app-docs/files/test/test.sh b/roles/web-app-docs/files/test/test.sh
new file mode 100644
index 0000000000..8003aca2b4
--- /dev/null
+++ b/roles/web-app-docs/files/test/test.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+# shellcheck shell=bash
+#
+# Env (templates/test.env.j2):
+#   DOCS_TEST_BASE_URL   documentation service on this host
+#   DOCS_TEST_DNS        value for the  placeholder
+#   DOCS_TEST_DOMAIN     value for the  placeholder
+#   DOCS_TEST_MODE       deployment mode; the instructions describe compose
+#   DOCS_TEST_ROLE       role whose page carries the instructions
+#   DOCS_TEST_SRC_DIR    repository checkout, mounted into the machine
+#   DOCS_TEST_TIMEOUT    seconds to wait for the on-demand build
+
+set -euo pipefail
+
+: "${DOCS_TEST_BASE_URL:?}"
+: "${DOCS_TEST_ROLE:?}"
+: "${DOCS_TEST_MODE:?}"
+: "${DOCS_TEST_TIMEOUT:?}"
+: "${DOCS_TEST_DOMAIN:?}"
+
+DUMMY_KEY="ssh-ed25519 AAAA_TEST_DUMMY_KEY docs-guide@infinito"
+
+if [ "${DOCS_TEST_MODE}" != "compose" ]; then
+	echo "SKIP: the published instructions describe a compose deployment;"
+	echo "      this stack runs ${DOCS_TEST_MODE}."
+	exit 0
+fi
+
+STAGE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+BLOCK="${STAGE}/block.sh"
+
+echo "=== Reading the published instructions for ${DOCS_TEST_ROLE} ==="
+python3 "${STAGE}/extract.py" "${DOCS_TEST_BASE_URL}" "${DOCS_TEST_ROLE}" \
+	--timeout "${DOCS_TEST_TIMEOUT}" >"${BLOCK}"
+
+if [ ! -s "${BLOCK}" ]; then
+	echo "ERROR: the page for ${DOCS_TEST_ROLE} shows an empty Production block." >&2
+	exit 1
+fi
+
+echo "=== Checking they parse as bash ==="
+bash -n "${BLOCK}"
+
+sed -i "s##${DUMMY_KEY}#g" "${BLOCK}"
+sed -i "s##${DOCS_TEST_DOMAIN}#g" "${BLOCK}"
+sed -i "s##${DOCS_TEST_DNS:-}#g" "${BLOCK}"
+sed -i "s#^HOST=.*#HOST=localhost#" "${BLOCK}"
+sed -i "s#--rm -it #--rm #" "${BLOCK}"
+
+if grep -q '&2
+	grep -o '' "${BLOCK}" | sort -u >&2
+	exit 1
+fi
+
+bash "${STAGE}/machine.sh" "${BLOCK}"
diff --git a/roles/web-app-docs/templates/test.env.j2 b/roles/web-app-docs/templates/test.env.j2
new file mode 100644
index 0000000000..a3e9a4d6a4
--- /dev/null
+++ b/roles/web-app-docs/templates/test.env.j2
@@ -0,0 +1,7 @@
+DOCS_TEST_BASE_URL=http://{{ DOCKER_BIND_HOST }}:{{ lookup('config', application_id, 'services.docs.ports.local.http') }}
+DOCS_TEST_DNS={{ networks.internet.dns }}
+DOCS_TEST_DOMAIN={{ DOMAIN_PRIMARY }}
+DOCS_TEST_MODE={{ DEPLOYMENT_MODE }}
+DOCS_TEST_ROLE={{ lookup('guide_role', application_id) }}
+DOCS_TEST_SRC_DIR={{ lookup('path_absolute') }}
+DOCS_TEST_TIMEOUT={{ lookup('timeout', 2400) | int }}
diff --git a/scripts/github/guide/compose_deploy.sh b/scripts/github/guide/compose_deploy.sh
deleted file mode 100755
index 1319efdb81..0000000000
--- a/scripts/github/guide/compose_deploy.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env bash
-# Render the role's "### Production" bash block and replay it against the
-# running compose server, exactly as the guide instructs a human to.
-# Env: GUIDE_ROLE; INFINITO_CONTAINER comes from scripts/meta/env/load.sh.
-set -euo pipefail
-
-: "${GUIDE_ROLE:?}"
-
-python3 -m cli.build.docs.readme.production "${GUIDE_ROLE}" >/tmp/deploy.sh
-sed -n '1,/docker run/p' /tmp/deploy.sh | grep -E '^[A-Z_]+=' |
-	sed 's#^HOST=.*#HOST=localhost#' >/tmp/run.sh
-perl -0777 -ne "print \$1 if /bash -c '(.*)'/s" /tmp/deploy.sh >>/tmp/run.sh
-test -s /tmp/run.sh
-# shellcheck source=/dev/null
-source scripts/meta/env/load.sh
-sed -i "s##ssh-ed25519 AAAA_TEST_DUMMY_KEY github-ci-dummy@infinito#" /tmp/run.sh
-sed -i "s##${INFINITO_DOMAIN}#" /tmp/run.sh
-sed -i "s##${INFINITO_DNS_IP}#" /tmp/run.sh
-docker exec -i "${INFINITO_CONTAINER}" bash -s /tmp/host-deploy.sh
-test -s /tmp/host-deploy.sh
-
-# shellcheck source=/dev/null
-source scripts/meta/env/load.sh
-sed -i "s##ssh-ed25519 AAAA_TEST_DUMMY_KEY github-ci-dummy@infinito#" /tmp/host-deploy.sh
-sed -i "s##${INFINITO_DOMAIN}#" /tmp/host-deploy.sh
-
-docker pull "${GUIDE_RUNTIME_IMAGE}"
-
-# Exception: the pkgmgr base image ships no init of its own.
-PREP="$(docker run -d --entrypoint sleep "${GUIDE_RUNTIME_IMAGE}" infinity)"
-docker exec "${PREP}" sh -c '
-	set -e
-	if command -v apt-get >/dev/null 2>&1; then
-		APT_TIMEOUT=10m
-		APT_OPTS="-o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30"
-		timeout -k 30 "$APT_TIMEOUT" apt-get $APT_OPTS update
-		DEBIAN_FRONTEND=noninteractive timeout -k 30 "$APT_TIMEOUT" apt-get $APT_OPTS install -y systemd systemd-sysv libnss-myhostname
-	elif command -v dnf >/dev/null 2>&1; then
-		dnf install -y systemd
-	elif command -v pacman >/dev/null 2>&1; then
-		pacman -Sy --noconfirm --needed archlinux-keyring
-		pacman -Syu --noconfirm --needed systemd
-		rm -rf /var/cache/pacman/pkg/*
-	fi
-	grep -q myhostname /etc/nsswitch.conf || sed -i "s/^hosts:.*/& myhostname/" /etc/nsswitch.conf
-	[ -e /sbin/init ] || ln -sf /lib/systemd/systemd /sbin/init
-'
-BOOT_IMAGE="guide-boot:${GUIDE_ROLE}"
-docker commit "${PREP}" "${BOOT_IMAGE}" >/dev/null
-docker rm -f "${PREP}" >/dev/null 2>&1 || true # nocheck: shell-or-true -- cleanup of a possibly already-removed container
-
-python3 -c 'from pathlib import Path; from cli.administration.deploy.development.coredns import CoreDNSCorefileRenderer; CoreDNSCorefileRenderer(repo_root=Path(".")).render(show_preview=False)'
-docker compose up -d coredns
-GUIDE_NET="$(docker inspect -f '{{range $k, $v := .NetworkSettings.Networks}}{{$k}}{{end}}' "${INFINITO_RUNNER_PREFIX}-coredns")"
-
-CID="$(docker run -d --privileged --cgroupns=host \
-	--network "${GUIDE_NET}" --ip "${INFINITO_IP4}" --dns "${INFINITO_DNS_IP}" \
-	-v /sys/fs/cgroup:/sys/fs/cgroup:rw \
-	--tmpfs /run --tmpfs /run/lock \
-	-v /srv \
-	-v "${PWD}:${PWD}" \
-	--entrypoint /sbin/init \
-	"${BOOT_IMAGE}")"
-# shellcheck disable=SC2154
-trap 'rc=$?; if [ "${rc}" -ne 0 ]; then _rescue="${INFINITO_RESCUE_DIAGNOSTICS_BASE}/${INFINITO_DISTRO}/${GUIDE_ROLE}"; INFINITO_RESCUE_DIAGNOSTICS_DIR="${_rescue}" python3 utils/diagnostics/container.py "${GUIDE_ROLE}" "guide host boot failure" || true; bash scripts/tests/deploy/utils/rescue_index.sh "${_rescue}"; fi; docker rm -f -v "${CID}" >/dev/null 2>&1 || true; docker compose down >/dev/null 2>&1 || true; docker rmi -f "${BOOT_IMAGE}" >/dev/null 2>&1 || true' EXIT # nocheck: shell-or-true -- best-effort diagnostics + teardown in the EXIT trap
-
-for _ in $(seq 1 40); do
-	state="$(docker exec "${CID}" systemctl is-system-running 2>/dev/null || true)"
-	case "${state}" in running | degraded) break ;; esac
-	sleep 3
-done
-state="$(docker exec "${CID}" systemctl is-system-running 2>/dev/null || true)"
-case "${state}" in
-running | degraded) ;;
-*)
-	echo "systemd never reached a running state (last: ${state:-unknown})" >&2
-	docker exec "${CID}" systemctl --no-pager status 2>/dev/null | head -n 20 >&2 || true # nocheck: shell-or-true -- diagnostics dump on the failure path
-	exit 1
-	;;
-esac
-docker exec "${CID}" bash -lc 'systemctl unmask systemd-logind && systemctl start systemd-logind && loginctl enable-linger root && systemctl start user@0.service'
-docker exec -i -w "${PWD}" "${CID}" bash -s  list[str]:
-    paths = _get_invokable_paths()
-    return [
-        role_dir.name
-        for role_dir in sorted(ROLES_DIR.iterdir())
-        if role_dir.is_dir() and _is_role_invokable(role_dir.name, paths)
-    ]
-
-
-class TestProductionBlock(unittest.TestCase):
-    """CI executes this block, so every invokable role must render one."""
-
-    def test_every_invokable_role_renders_a_block(self) -> None:
-        roles = _invokable()
-        self.assertTrue(roles)
-
-        for role in roles:
-            with self.subTest(role=role):
-                block = production_block(ROLES_DIR / role, role)
-                self.assertTrue(block.strip())
-                self.assertNotIn("```", block)
-                self.assertNotIn(HEADING, block)
-
-    def test_a_non_invokable_role_has_no_block(self) -> None:
-        paths = _get_invokable_paths()
-        role = next(
-            role_dir.name
-            for role_dir in sorted(ROLES_DIR.iterdir())
-            if role_dir.is_dir() and not _is_role_invokable(role_dir.name, paths)
-        )
-
-        with self.assertRaises(ValueError):
-            production_block(ROLES_DIR / role, role)
-
-
-if __name__ == "__main__":
-    unittest.main()
diff --git a/tests/unit/python/plugins/lookup/test_guide_role.py b/tests/unit/python/plugins/lookup/test_guide_role.py
new file mode 100644
index 0000000000..3a6d0705e0
--- /dev/null
+++ b/tests/unit/python/plugins/lookup/test_guide_role.py
@@ -0,0 +1,84 @@
+import unittest
+from unittest.mock import patch
+
+from plugins.lookup.guide_role import LookupModule, guide_role
+
+INVOKABLE = ["web-app-docs", "web-app-nextcloud", "svc-db-postgres", "dsk-gnt-claude"]
+
+
+class TestGuideRole(unittest.TestCase):
+    def test_the_first_invokable_peer_wins(self):
+        self.assertEqual(
+            guide_role("web-app-docs", ["web-app-docs", "web-app-nextcloud"], INVOKABLE),
+            "web-app-nextcloud",
+        )
+
+    def test_a_non_invokable_peer_is_no_peer(self):
+        self.assertEqual(
+            guide_role("web-app-docs", ["web-app-docs", "sys-svc-proxy"], INVOKABLE),
+            "web-app-docs",
+        )
+
+    def test_the_asking_role_alone_names_itself(self):
+        self.assertEqual(guide_role("web-app-docs", ["web-app-docs"], INVOKABLE), "web-app-docs")
+
+    def test_an_empty_round_names_the_asking_role(self):
+        self.assertEqual(guide_role("web-app-docs", [], INVOKABLE), "web-app-docs")
+
+    def test_the_round_order_decides_between_two_peers(self):
+        self.assertEqual(
+            guide_role("web-app-docs", ["svc-db-postgres", "dsk-gnt-claude"], INVOKABLE),
+            "svc-db-postgres",
+        )
+
+    def test_a_peer_outside_the_invokable_set_is_skipped_for_a_later_one(self):
+        self.assertEqual(
+            guide_role(
+                "web-app-docs",
+                ["sys-svc-proxy", "user-administrator", "dsk-gnt-claude"],
+                INVOKABLE,
+            ),
+            "dsk-gnt-claude",
+        )
+
+
+class TestGuideRoleLookup(unittest.TestCase):
+    @patch("plugins.lookup.guide_role.list_invokable_app_ids")
+    def test_the_whitelist_outranks_the_round_groups(self, invokable):
+        invokable.return_value = INVOKABLE
+        result = LookupModule().run(
+            ["web-app-docs"],
+            variables={
+                "APPLICATIONS_WHITELIST": ["web-app-docs", "svc-db-postgres"],
+                "group_names": ["web-app-docs", "web-app-nextcloud"],
+            },
+        )
+        self.assertEqual(result, ["svc-db-postgres"])
+
+    @patch("plugins.lookup.guide_role.list_invokable_app_ids")
+    def test_without_a_whitelist_the_round_groups_decide(self, invokable):
+        invokable.return_value = INVOKABLE
+        result = LookupModule().run(
+            ["web-app-docs"],
+            variables={
+                "APPLICATIONS_WHITELIST": [],
+                "group_names": ["web-app-docs", "web-app-nextcloud"],
+            },
+        )
+        self.assertEqual(result, ["web-app-nextcloud"])
+
+    @patch("plugins.lookup.guide_role.list_invokable_app_ids")
+    def test_the_asking_role_falls_back_to_the_variable(self, invokable):
+        invokable.return_value = INVOKABLE
+        result = LookupModule().run(
+            [],
+            variables={
+                "application_id": "web-app-docs",
+                "group_names": ["web-app-docs", "sys-svc-proxy"],
+            },
+        )
+        self.assertEqual(result, ["web-app-docs"])
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py
new file mode 100644
index 0000000000..05e881235c
--- /dev/null
+++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_build_queue.py
@@ -0,0 +1,150 @@
+"""Unit tests for the build queue and its two lanes.
+
+``Queue`` is a mixin with no life of its own, so every case here drives it
+through :class:`Library`, on the fixture its sibling module owns.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import unittest
+
+from .test_library import LibraryFixture
+
+BACKGROUND = "background"
+
+HOLDER = """\
+import fcntl
+import sys
+
+handle = open(sys.argv[1], "a+")
+fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
+print("locked", flush=True)
+sys.stdin.readline()
+"""
+
+
+class QueueFixture(LibraryFixture):
+    def _queued(self, lane: str = "") -> list[str]:
+        directory = self.library.queue / lane if lane else self.library.queue
+        if not directory.is_dir():
+            return []
+        return sorted(entry.name for entry in directory.iterdir() if entry.is_file())
+
+    def _serve(self, version: str, code: str | None = None) -> None:
+        """Publish a site so the freshness check reports it as current."""
+        head = self.library.refs()[0]
+        root = (
+            self.library.translations / version / code
+            if code
+            else self.library.sites / version
+        )
+        (root / "html").mkdir(parents=True)
+        (root / "html" / "index.html").write_text("

ok

", encoding="utf-8") + (root / "ref").write_text(head, encoding="utf-8") + + def _index(self, version: str, translated: list[str]) -> None: + directory = self.library.translations / version + directory.mkdir(parents=True, exist_ok=True) + (directory / "languages.json").write_text( + json.dumps({"known": {code: code for code in translated}, "translated": translated}), + encoding="utf-8", + ) + + +class TestRequest(QueueFixture, unittest.TestCase): + def test_the_fetch_queues_latest(self) -> None: + self.assertIn("latest", self._queued()) + + def test_a_current_version_is_not_queued_again(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", []) + + self.library.request("latest") + + self.assertEqual(self._queued(), []) + + def test_a_language_the_version_does_not_translate_is_refused(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", []) + + self.library.request("latest", "de") + + self.assertEqual(self._queued(), []) + + def test_a_translated_language_is_queued_with_its_separator(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", ["de"]) + + self.library.request("latest", "de") + + self.assertEqual(self._queued(), ["latest:de"]) + + def test_the_background_lane_yields_to_a_waiting_visitor(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", ["de"]) + + self.library.request("latest", "de") + self.library.request("latest", "de", background=True) + + self.assertEqual(self._queued(), ["latest:de"]) + self.assertEqual(self._queued(BACKGROUND), []) + + +class TestDrain(QueueFixture, unittest.TestCase): + def test_a_visitor_marker_outranks_an_older_background_one(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", ["de", "fr"]) + self.library.request("latest", "fr", background=True) + self.library.request("latest", "de") + + self.assertEqual(self.library.next_queued(), "latest:de") + + def test_the_background_lane_is_drained_once_the_front_is_empty(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", ["fr"]) + self.library.request("latest", "fr", background=True) + + self.assertEqual(self.library.next_queued(), "latest:fr") + + def test_dequeue_clears_both_lanes(self) -> None: + self.library._dequeue("latest") + self._serve("latest") + self._index("latest", ["de"]) + self.library.request("latest", "de", background=True) + self.library.request("latest", "de") + + self.library._dequeue("latest:de") + + self.assertIsNone(self.library.next_queued()) + + +class TestBuilderLock(QueueFixture, unittest.TestCase): + def test_a_replica_in_another_process_is_locked_out(self) -> None: + self.library.lock_file.parent.mkdir(parents=True, exist_ok=True) + holder = subprocess.Popen( + [sys.executable, "-c", HOLDER, str(self.library.lock_file)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + self.addCleanup(holder.kill) + self.assertEqual(holder.stdout.readline().strip(), "locked") + + self.assertFalse(self.library.acquire_builder()) + + def test_the_holder_keeps_it_across_calls(self) -> None: + self.assertTrue(self.library.acquire_builder()) + self.assertTrue(self.library.acquire_builder()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_catalogs.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_catalogs.py new file mode 100644 index 0000000000..dc4e7eaf2a --- /dev/null +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_catalogs.py @@ -0,0 +1,84 @@ +"""Unit tests for the language declaration a documented checkout carries.""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from infinito_docs.catalogs import translated_languages + +CATALOG = """\ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\\n" + +msgid "Overview" +msgstr "%s" +""" + +FUZZY = """\ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\\n" + +#, fuzzy +msgid "Overview" +msgstr "Aperçu" +""" + + +class TestTranslatedLanguages(unittest.TestCase): + def setUp(self) -> None: + self._tmp = TemporaryDirectory(prefix="infinito-catalogs-") + self.src = Path(self._tmp.name) + self.addCleanup(self._tmp.cleanup) + + def _declare(self, body: str) -> None: + (self.src / "meta").mkdir(parents=True, exist_ok=True) + (self.src / "meta" / "languages.yml").write_text(body, encoding="utf-8") + + def _catalog(self, code: str, body: str) -> None: + directory = self.src / "locale" / code / "LC_MESSAGES" + directory.mkdir(parents=True, exist_ok=True) + (directory / "docs.po").write_text(body, encoding="utf-8") + + def test_a_checkout_without_the_declaration_knows_no_language(self) -> None: + self.assertEqual(translated_languages(self.src), ({}, [])) + + def test_the_native_name_is_read_and_a_missing_one_falls_back_to_the_code( + self, + ) -> None: + self._declare("de:\n native: Deutsch\nfr:\n") + + known, translated = translated_languages(self.src) + + self.assertEqual(known, {"de": "Deutsch", "fr": "fr"}) + self.assertEqual(translated, []) + + def test_a_declared_language_without_a_catalog_is_not_translated(self) -> None: + self._declare("de:\n native: Deutsch\n") + + self.assertEqual(translated_languages(self.src)[1], []) + + def test_one_filled_entry_makes_a_language_translated(self) -> None: + self._declare("de:\n native: Deutsch\n") + self._catalog("de", CATALOG % "Übersicht") + + self.assertEqual(translated_languages(self.src)[1], ["de"]) + + def test_an_empty_catalog_does_not_count(self) -> None: + self._declare("de:\n native: Deutsch\n") + self._catalog("de", CATALOG % "") + + self.assertEqual(translated_languages(self.src)[1], []) + + def test_a_fuzzy_entry_does_not_count(self) -> None: + self._declare("fr:\n native: Français\n") + self._catalog("fr", FUZZY) + + self.assertEqual(translated_languages(self.src)[1], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_sites.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_sites.py new file mode 100644 index 0000000000..4c5683d894 --- /dev/null +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/test_sites.py @@ -0,0 +1,107 @@ +"""Unit tests for the on-disk view of the built sites. + +``Sites`` is a mixin with no life of its own, so every case here drives it +through :class:`Library`, on the fixture its sibling module owns. +""" + +from __future__ import annotations + +import json +import unittest + +from .test_library import LibraryFixture + + +class SitesFixture(LibraryFixture): + def _publish(self, version: str, code: str | None = None) -> None: + parent = self.library.translations / version / code if code else None + root = parent or self.library.sites / version + (root / "html").mkdir(parents=True) + (root / "html" / "index.html").write_text("

ok

", encoding="utf-8") + (root / "ref").write_text("deadbeef", encoding="utf-8") + + def _index(self, version: str, payload: object) -> None: + directory = self.library.translations / version + directory.mkdir(parents=True, exist_ok=True) + (directory / "languages.json").write_text(json.dumps(payload), encoding="utf-8") + + +class TestServable(SitesFixture, unittest.TestCase): + def test_a_version_without_an_index_page_is_not_servable(self) -> None: + self.assertFalse(self.library.servable("latest")) + self.assertEqual(self.library.built_ref("latest"), "") + + def test_a_published_version_reports_its_ref(self) -> None: + self._publish("latest") + + self.assertTrue(self.library.servable("latest")) + self.assertEqual(self.library.built_ref("latest"), "deadbeef") + + def test_a_translation_is_tracked_per_code(self) -> None: + self._publish("latest", "de") + + self.assertTrue(self.library.translation_servable("latest", "de")) + self.assertFalse(self.library.translation_servable("latest", "fr")) + self.assertEqual(self.library.translation_ref("latest", "de"), "deadbeef") + self.assertEqual(self.library.translation_ref("latest", "fr"), "") + + +class TestLanguageIndex(SitesFixture, unittest.TestCase): + def test_a_missing_index_counts_as_current(self) -> None: + self.assertTrue(self.library._language_index_is_current("latest")) + self.assertEqual(self.library.languages("latest"), ({}, [])) + + def test_the_old_flat_shape_is_read_as_known_only(self) -> None: + self._index("latest", {"de": "Deutsch"}) + + self.assertEqual(self.library.languages("latest"), ({"de": "Deutsch"}, [])) + self.assertFalse(self.library.translates("latest", "de")) + self.assertFalse(self.library._language_index_is_current("latest")) + + def test_the_split_shape_carries_the_translated_codes(self) -> None: + self._index("latest", {"known": {"de": "Deutsch"}, "translated": ["de"]}) + self._publish("latest", "de") + + self.assertEqual(self.library.languages("latest"), ({"de": "Deutsch"}, ["de"])) + self.assertTrue(self.library.translates("latest", "de")) + self.assertTrue(self.library._language_index_is_current("latest")) + + def test_a_corrupt_index_is_neither_current_nor_readable(self) -> None: + directory = self.library.translations / "latest" + directory.mkdir(parents=True) + (directory / "languages.json").write_text("{not json", encoding="utf-8") + + self.assertFalse(self.library._language_index_is_current("latest")) + self.assertEqual(self.library.languages("latest"), ({}, [])) + + +class TestResolve(SitesFixture, unittest.TestCase): + def test_a_directory_resolves_to_its_index_page(self) -> None: + self._publish("latest") + + self.assertEqual( + self.library.resolve("latest", ""), + self.library.sites / "latest" / "html" / "index.html", + ) + + def test_a_path_escaping_the_site_resolves_to_nothing(self) -> None: + self._publish("latest") + + self.assertIsNone(self.library.resolve("latest", "../../etc/passwd")) + + def test_a_missing_file_resolves_to_nothing(self) -> None: + self._publish("latest") + + self.assertIsNone(self.library.resolve("latest", "absent.html")) + + def test_a_translation_resolves_inside_its_own_site(self) -> None: + self._publish("latest", "de") + + self.assertEqual( + self.library.resolve_translation("latest", "de", ""), + self.library.translations / "latest" / "de" / "html" / "index.html", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-docs/files/test/__init__.py b/tests/unit/python/roles/web-app-docs/files/test/__init__.py new file mode 100644 index 0000000000..86efabd459 --- /dev/null +++ b/tests/unit/python/roles/web-app-docs/files/test/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] diff --git a/tests/unit/python/roles/web-app-docs/files/test/test_extract.py b/tests/unit/python/roles/web-app-docs/files/test/test_extract.py new file mode 100644 index 0000000000..cc18d51916 --- /dev/null +++ b/tests/unit/python/roles/web-app-docs/files/test/test_extract.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +import importlib.util +import unittest +import urllib.error +from unittest import mock + +from . import PROJECT_ROOT + +_SOURCE = PROJECT_ROOT / "roles" / "web-app-docs" / "files" / "test" / "extract.py" +_spec = importlib.util.spec_from_file_location("docs_test_extract", _SOURCE) +extract = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(extract) + +PAGE = """\ +

Quick Setup

+

Development

+
\
+make onboard
+
+
+

Production

+
\
+APP=web-app-x
+echo "a & b"
+
+
+""" + +WITHOUT = '

Overview

No setup here.

' + + +class TestBlock(unittest.TestCase): + def _parsed(self, page: str) -> str: + parser = extract.Block() + parser.feed(page) + return parser.text + + def test_it_takes_the_block_below_the_production_heading(self) -> None: + text = self._parsed(PAGE) + + self.assertIn("APP=web-app-x", text) + self.assertNotIn("make onboard", text) + + def test_entities_come_back_as_characters(self) -> None: + self.assertIn('"a & b"', self._parsed(PAGE)) + + def test_highlight_markup_does_not_reach_the_commands(self) -> None: + self.assertNotIn(" None: + self.assertEqual(self._parsed(WITHOUT).strip(), "") + + +class TestPageUrl(unittest.TestCase): + def test_it_addresses_the_latest_version(self) -> None: + self.assertEqual( + extract.page_url("http://host:8036/", "web-app-x"), + "http://host:8036/latest/roles/web-app-x/README.html", + ) + + +class TestFetch(unittest.TestCase): + def _response(self, status: int, body: bytes = b""): + response = mock.MagicMock() + response.status = status + response.read.return_value = body + response.__enter__.return_value = response + return response + + def test_a_ready_page_is_returned_at_once(self) -> None: + with mock.patch.object(extract.urllib.request, "urlopen") as opener: + opener.return_value = self._response(200, b"

ok

") + + self.assertEqual(extract.fetch("http://x/", timeout=1), "

ok

") + + def test_it_waits_while_the_version_is_building(self) -> None: + answers = [self._response(202), self._response(200, b"

ok

")] + with ( + mock.patch.object(extract.urllib.request, "urlopen", side_effect=answers), + mock.patch.object(extract.time, "sleep"), + ): + self.assertEqual(extract.fetch("http://x/", timeout=60, poll=0), "

ok

") + + def test_a_build_that_never_finishes_times_out(self) -> None: + with ( + mock.patch.object(extract.urllib.request, "urlopen") as opener, + mock.patch.object(extract.time, "sleep"), + ): + opener.return_value = self._response(202) + with self.assertRaises(TimeoutError): + extract.fetch("http://x/", timeout=0, poll=0) + + def test_an_error_other_than_building_is_raised(self) -> None: + failure = urllib.error.HTTPError("http://x/", 404, "gone", {}, None) + with ( + mock.patch.object(extract.urllib.request, "urlopen", side_effect=failure), + self.assertRaises(urllib.error.HTTPError), + ): + extract.fetch("http://x/", timeout=1) + + +class TestBlockEntry(unittest.TestCase): + def test_a_page_without_instructions_is_an_error(self) -> None: + with ( + mock.patch.object(extract, "fetch", return_value=WITHOUT), + self.assertRaises(ValueError), + ): + extract.block("http://x/", "web-app-x", timeout=1) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/i18n/damage.py b/utils/i18n/damage.py new file mode 100644 index 0000000000..3f493d3514 --- /dev/null +++ b/utils/i18n/damage.py @@ -0,0 +1,187 @@ +"""Whether a translation broke something its source carried. + +:func:`harms` is the single predicate both ends of the pipeline ask; the rest +of this module are the criteria it folds together. +""" + +from __future__ import annotations + +import re +from collections import Counter + +from utils.i18n import names +from utils.i18n.repairs import resegment, tighten +from utils.i18n.spans import mask, matches, prose + +MARKUP = '[]`*{}()"' +STRUCTURE = "[]{}`*()" +TRUNCATION_FLOOR = 120 +TRUNCATION_RATIO = 0.5 +ECHO_FLOOR = 30 +STUTTER = re.compile(r"\b(\w+)(?:\s+\1\b){2,}", re.IGNORECASE | re.UNICODE) +WORDS = re.compile(r"[^\W\d_]{2,}", re.UNICODE) +LATIN_FLOOR = 6 +LATIN_SHARE = 0.9 +NON_LATIN_SCRIPTS = frozenset( + { + "am", + "ar", + "be", + "bg", + "bn", + "dv", + "dz", + "el", + "fa", + "gu", + "he", + "hi", + "hy", + "ja", + "ka", + "km", + "kn", + "ko", + "ky", + "lo", + "mk", + "ml", + "mn", + "mr", + "my", + "ne", + "or", + "pa", + "ps", + "ru", + "si", + "sr", + "ta", + "te", + "th", + "ti", + "ug", + "uk", + "ur", + "yi", + "zh", + } +) + + +def protected_spans(text: str) -> Counter: + """Return the protected spans of ``text`` with their multiplicity. + + Args: + text: a source message or its translation. + """ + return Counter(text[start:end] for start, end in matches(text, with_names=False)) + + +def missing_names(source: str, translation: str) -> set[str]: + """Return the names ``source`` carries that ``translation`` dropped. + + Args: + source: the source message. + translation: what came back for it. + """ + carried = {source[start:end] for start, end in names.spans(source)} + return {name for name in carried if name not in translation} + + +def untranslated(translation: str, language: str) -> bool: + """Return whether a non-Latin language came back written in Latin letters. + + The server answers with its input, lightly reworded, often enough that the + result keeps every span and every markup character while still being + English. Comparing scripts catches it wherever the target does not use the + Latin one; for a Latin-script target it would need a language detector. + + Args: + translation: what came back for the entry. + language: ISO 639-1 code of the catalog being filled. + """ + if language not in NON_LATIN_SCRIPTS: + return False + words = WORDS.findall(prose(translation)) + if len(words) < LATIN_FLOOR: + return False + latin = sum(1 for word in words if word.isascii()) + return latin / len(words) >= LATIN_SHARE + + +def stutters(source: str, translation: str) -> bool: + """Return whether ``translation`` repeats a word the source does not. + + A server that loses its way answers ``Cloud`` with ``Cloud Cloud Cloud``. + Every other rule passes it: the spans survive, the markup count survives, + it is no echo, and ``truncated`` only watches the short side. + + Args: + source: the source message. + translation: what came back for it. + """ + return bool(STUTTER.search(prose(translation))) and not STUTTER.search( + prose(source) + ) + + +def truncated(source: str, translation: str) -> bool: + """Return whether ``translation`` kept too little of ``source`` to be one. + + The floor keeps a short entry out: ``Situation`` becomes ``Lage`` and loses + half its characters while saying the same thing. A passage past it that + comes back halved has dropped a clause. + + Args: + source: the source message. + translation: what came back for it. + """ + return ( + len(source) > TRUNCATION_FLOOR + and len(translation) < len(source) * TRUNCATION_RATIO + ) + + +def structure(text: str) -> Counter: + """Return the markup characters of ``text`` with their multiplicity. + + Args: + text: a source message or its translation. + """ + return Counter(character for character in text if character in STRUCTURE) + + +def harms(source: str, translation: str, language: str = "") -> bool: + """Return whether ``translation`` broke something ``source`` carried. + + Single source of truth for both ends of the pipeline: the client drops a + translation this rejects, and the release gate reports one that survived + anyway. A check on one side only lets every run rewrite what the other + side then condemns, which never converges. + + A translation identical to its source changed nothing and so damaged + nothing, except when the source is a sentence: the server answers with its + input when it fails, and the client seeds every entry with the source, so + an echoed sentence is a failure that would otherwise count as translated + and never be retried. + + Args: + source: the source message. + translation: what came back for it. + language: ISO 639-1 code of the catalog, when the caller knows it. The + script comparison is the one check that needs it; every other + criterion reads both strings alone. + """ + if translation == source: + return sum(character.isalpha() for character in prose(source)) >= ECHO_FLOOR + return bool( + protected_spans(translation) != protected_spans(source) + or missing_names(source, translation) + or stutters(source, translation) + or untranslated(translation, language) + or truncated(source, translation) + or structure(translation) != structure(source) + or tighten(translation) != translation + or resegment(translation, mask(source).spans, source) != translation + ) diff --git a/utils/i18n/placeholders.py b/utils/i18n/placeholders.py index 429c6ba4d7..f6a5baf1ce 100644 --- a/utils/i18n/placeholders.py +++ b/utils/i18n/placeholders.py @@ -1,374 +1,52 @@ -"""Protection of the parts of a message that machine translation must not touch.""" +"""Protection of the parts of a message that machine translation must not touch. + +The public entry point of three layers, each importable on its own: + +* :mod:`utils.i18n.spans` which parts are protected, and how they are masked +* :mod:`utils.i18n.repairs` the cosmetic repairs a restored string goes through +* :mod:`utils.i18n.damage` whether what came back broke any of them +""" from __future__ import annotations import html -import re -from collections import Counter -from dataclasses import dataclass -from functools import lru_cache -from utils.i18n import names - -PRINTF = r"%\([A-Za-z_]\w*\)[sdif]|%[sdif]" -PLACEHOLDER = re.compile(PRINTF) - -PROTECTED = re.compile( - r"``.+?``" - r"|:[\w.+-]+:`[^`]+`" - r"|`[^`]+`_{0,2}" - r"|\{\{.+?\}\}" - r"|\{%.+?%\}" - r"|\{\{.*" - r"|\{[A-Za-z_]\w*\}" - rf"|{PRINTF}" - r"|https?://(?:[^\s<>\"'`()\[\]]|\([^\s<>\"'`()]*\))+" - r"|<[^<>\s]+>" - r"|(?<=\])\((?:[^\s()]|\([^\s()]*\))+\)" - r"|(?\s]*>[\w.-]*)*\"|'[\w.-]*(?:<[^>\s]*>[\w.-]*)*'" - r"|\d+(?:[.,]\d+)*" - r"|\*\*|\*|`|\[|\]|\{|\}|\(|\)|\"" -) - - -def carries_placeholder(message_id: str | tuple[str, ...]) -> bool: - """Return whether ``message_id`` holds a printf placeholder a translation must keep. - - Args: - message_id: a catalog message id, singular or a plural tuple. - """ - forms = message_id if isinstance(message_id, tuple) else (message_id,) - return any(PLACEHOLDER.search(form) for form in forms) - - -EXTRA = re.compile( - r"[\U0001F300-\U0001FAFF☀-➿️]" - r"|[\w.+-]+@[\w-]+\.[\w.]+" -) - - -@lru_cache(maxsize=1 << 17) -def _claimed(text: str, with_names: bool) -> tuple[tuple[int, int], ...]: - found = [(m.start(), m.end()) for m in PROTECTED.finditer(text)] - found += [(m.start(), m.end()) for m in EXTRA.finditer(text)] - if with_names: - found += names.spans(text) - kept: list[tuple[int, int]] = [] - reach = 0 - for start, end in sorted(found): - if start < reach: - continue - kept.append((start, end)) - reach = end - return tuple(kept) - - -def matches(text: str, with_names: bool = True) -> list[tuple[int, int]]: - """Return the non-overlapping offsets every protection rule claims. - - The scan is cached behind a fresh list, because one source message is - scanned once per target language and callers may sort or trim the result. - - Args: - text: a source message or its translation. - with_names: whether role names and titles take part. They do when a - request is masked, so the translator never sees them, and they do - not when two texts are compared: German capitalises every noun, so - the lowercase ``shell extensions`` becomes ``Shell-Erweiterungen`` - and a set comparison would read the capital as a surplus span. - """ - return list(_claimed(text, with_names)) - - -MARKUP = '[]`*{}()"' -STRUCTURE = "[]{}`*()" -TRUNCATION_FLOOR = 120 -TRUNCATION_RATIO = 0.5 -ECHO_FLOOR = 30 -STUTTER = re.compile(r"\b(\w+)(?:\s+\1\b){2,}", re.IGNORECASE | re.UNICODE) -WORDS = re.compile(r"[^\W\d_]{2,}", re.UNICODE) -LATIN_FLOOR = 6 -LATIN_SHARE = 0.9 -NON_LATIN_SCRIPTS = frozenset( - { - "am", "ar", "be", "bg", "bn", "dv", "dz", "el", "fa", "gu", "he", "hi", - "hy", "ja", "ka", "km", "kn", "ko", "ky", "lo", "mk", "ml", "mn", "mr", - "my", "ne", "or", "pa", "ps", "ru", "si", "sr", "ta", "te", "th", "ti", - "ug", "uk", "ur", "yi", "zh", - } -) -EMPHASIS = re.compile(r"(\*\*)[ \t]*([^\s]|[^\s].*?[^\s])[ \t]*\1", re.DOTALL) - - -def resegment(restored: str, spans: tuple[str, ...], source: str) -> str: - """Put back the sentence boundary a translator dropped behind a protected span. - - A name is skipped. Every other protected span ends in a delimiter, so a - letter right behind it can only be the text the boundary was lost from, but - a name ends in a word character and an agglutinative language suffixes it: - ``Baserow`` is found inside the Bengali ``Baserowo`` and the punctuation - would land inside the word. - - Args: - restored: the translation with every protected span put back. - spans: the protected spans of the source. - source: the source message, which holds the boundary that went missing. - """ - named = {source[start:end] for start, end in names.spans(source)} - for span in spans: - if span in named: - continue - start = source.find(span) - if start < 0: - continue - boundary = source[start + len(span) : start + len(span) + 2] - if len(boundary) != 2 or boundary[0] not in ".,;:" or not boundary[1].isspace(): - continue - follows = restored.find(span) + len(span) - if follows > len(span) - 1 and restored[follows : follows + 1].isalpha(): - restored = restored[:follows] + boundary[0] + " " + restored[follows:] - return restored - - -def tighten(restored: str) -> str: - """Return ``restored`` with the whitespace a translator set inside emphasis removed. - - Args: - restored: the translation with every protected span put back. - """ - return EMPHASIS.sub( - lambda pair: pair.group(1) + pair.group(2) + pair.group(1), restored - ) - - -TERMINATORS = ".!?" -RUN_OF_SPACES = re.compile(r"[ \t]{2,}") - - -def collapse(restored: str, source: str) -> str: - """Return ``restored`` without the space runs the translator opened. - - A run the source carries itself is left alone, because an aligned block in a - code sample means its spacing. - - Args: - restored: the translation with every protected span put back. - source: the source message. - """ - if " " in source or "\t" in source: - return restored - return RUN_OF_SPACES.sub(" ", restored) - - -def terminate(restored: str, source: str) -> str: - """Return ``restored`` with the sentence end the translator lost. - - A closing bracket that moves in front of a protected span takes the full - stop behind it with it, which leaves the sentence running on. - - Args: - restored: the translation with every protected span put back. - source: the source message. - """ - end = source.rstrip()[-1:] - if end not in TERMINATORS or restored.rstrip().endswith(tuple(TERMINATORS)): - return restored - return restored.rstrip() + end - - -def recapitalise(restored: str, source: str) -> str: - """Return ``restored`` with the capital its opening word lost. - - Args: - restored: the translation with every protected span put back. - source: the source message. - """ - if not source[:1].isupper() or not restored[:1].islower(): - return restored - return restored[0].upper() + restored[1:] - - -TOKEN = re.compile(r'(?:\s*)?') - - -@dataclass(frozen=True) -class Masked: - """A message prepared for an HTML-mode translation request. - - Args: - text: HTML with every protected span replaced by an ```` token. - spans: the protected spans, indexed by token id. - """ - - text: str - spans: tuple[str, ...] - - -def protected_spans(text: str) -> Counter: - """Return the protected spans of ``text`` with their multiplicity. - - Args: - text: a source message or its translation. - """ - return Counter(text[start:end] for start, end in matches(text, with_names=False)) - - -def missing_names(source: str, translation: str) -> set[str]: - """Return the names ``source`` carries that ``translation`` dropped. - - Args: - source: the source message. - translation: what came back for it. - """ - carried = {source[start:end] for start, end in names.spans(source)} - return {name for name in carried if name not in translation} - - -def untranslated(translation: str, language: str) -> bool: - """Return whether a non-Latin language came back written in Latin letters. - - The server answers with its input, lightly reworded, often enough that the - result keeps every span and every markup character while still being - English. Comparing scripts catches it wherever the target does not use the - Latin one; for a Latin-script target it would need a language detector. - - Args: - translation: what came back for the entry. - language: ISO 639-1 code of the catalog being filled. - """ - if language not in NON_LATIN_SCRIPTS: - return False - words = WORDS.findall(prose(translation)) - if len(words) < LATIN_FLOOR: - return False - latin = sum(1 for word in words if word.isascii()) - return latin / len(words) >= LATIN_SHARE - - -def stutters(source: str, translation: str) -> bool: - """Return whether ``translation`` repeats a word the source does not. - - A server that loses its way answers ``Cloud`` with ``Cloud Cloud Cloud``. - Every other rule passes it: the spans survive, the markup count survives, - it is no echo, and ``truncated`` only watches the short side. - - Args: - source: the source message. - translation: what came back for it. - """ - return bool(STUTTER.search(prose(translation))) and not STUTTER.search( - prose(source) - ) - - -def truncated(source: str, translation: str) -> bool: - """Return whether ``translation`` kept too little of ``source`` to be one. - - The floor keeps a short entry out: ``Situation`` becomes ``Lage`` and loses - half its characters while saying the same thing. A passage past it that - comes back halved has dropped a clause. - - Args: - source: the source message. - translation: what came back for it. - """ - return ( - len(source) > TRUNCATION_FLOOR - and len(translation) < len(source) * TRUNCATION_RATIO - ) - - -def structure(text: str) -> Counter: - """Return the markup characters of ``text`` with their multiplicity. - - Args: - text: a source message or its translation. - """ - return Counter(character for character in text if character in STRUCTURE) - - -def harms(source: str, translation: str, language: str = "") -> bool: - """Return whether ``translation`` broke something ``source`` carried. - - Single source of truth for both ends of the pipeline: the client drops a - translation this rejects, and the release gate reports one that survived - anyway. A check on one side only lets every run rewrite what the other - side then condemns, which never converges. - - A translation identical to its source changed nothing and so damaged - nothing, except when the source is a sentence: the server answers with its - input when it fails, and the client seeds every entry with the source, so - an echoed sentence is a failure that would otherwise count as translated - and never be retried. - - Args: - source: the source message. - translation: what came back for it. - language: ISO 639-1 code of the catalog, when the caller knows it. The - script comparison is the one check that needs it; every other - criterion reads both strings alone. - """ - if translation == source: - return sum(character.isalpha() for character in prose(source)) >= ECHO_FLOOR - return bool( - protected_spans(translation) != protected_spans(source) - or missing_names(source, translation) - or stutters(source, translation) - or untranslated(translation, language) - or truncated(source, translation) - or structure(translation) != structure(source) - or tighten(translation) != translation - or resegment(translation, mask(source).spans, source) != translation - ) - - -def prose(text: str) -> str: - """Return ``text`` with every protected span removed. - - Args: - text: a source message. - """ - plain, position = [], 0 - for start, end in matches(text): - plain.append(text[position:start]) - position = end - plain.append(text[position:]) - return "".join(plain) - - -def has_words(text: str) -> bool: - """Return whether ``text`` holds any letter outside its protected spans. - - Args: - text: a source message. - """ - return any(character.isalpha() for character in prose(text)) - - -@lru_cache(maxsize=1 << 16) -def mask(text: str) -> Masked: - """Return ``text`` escaped for HTML with its protected spans tokenised. - - The result is immutable and one source message is masked once per target - language, so the same string arrives dozens of times per run. - - Args: - text: the source message. - """ - spans: list[str] = [] - parts: list[str] = [] - position = 0 - for start, end in matches(text): - parts.append(html.escape(text[position:start], quote=False)) - parts.append(f'') - spans.append(text[start:end]) - position = end - parts.append(html.escape(text[position:], quote=False)) - return Masked("".join(parts), tuple(spans)) +from utils.i18n.damage import ECHO_FLOOR as ECHO_FLOOR +from utils.i18n.damage import LATIN_FLOOR as LATIN_FLOOR +from utils.i18n.damage import LATIN_SHARE as LATIN_SHARE +from utils.i18n.damage import MARKUP as MARKUP +from utils.i18n.damage import NON_LATIN_SCRIPTS as NON_LATIN_SCRIPTS +from utils.i18n.damage import STRUCTURE as STRUCTURE +from utils.i18n.damage import STUTTER as STUTTER +from utils.i18n.damage import TRUNCATION_FLOOR as TRUNCATION_FLOOR +from utils.i18n.damage import TRUNCATION_RATIO as TRUNCATION_RATIO +from utils.i18n.damage import WORDS as WORDS +from utils.i18n.damage import harms as harms +from utils.i18n.damage import missing_names as missing_names +from utils.i18n.damage import protected_spans as protected_spans +from utils.i18n.damage import structure as structure +from utils.i18n.damage import stutters as stutters +from utils.i18n.damage import truncated as truncated +from utils.i18n.damage import untranslated as untranslated +from utils.i18n.repairs import EMPHASIS as EMPHASIS +from utils.i18n.repairs import RUN_OF_SPACES as RUN_OF_SPACES +from utils.i18n.repairs import TERMINATORS as TERMINATORS +from utils.i18n.repairs import collapse as collapse +from utils.i18n.repairs import recapitalise as recapitalise +from utils.i18n.repairs import resegment as resegment +from utils.i18n.repairs import terminate as terminate +from utils.i18n.repairs import tighten as tighten +from utils.i18n.spans import EXTRA as EXTRA +from utils.i18n.spans import PLACEHOLDER as PLACEHOLDER +from utils.i18n.spans import PRINTF as PRINTF +from utils.i18n.spans import PROTECTED as PROTECTED +from utils.i18n.spans import TOKEN as TOKEN +from utils.i18n.spans import Masked as Masked +from utils.i18n.spans import carries_placeholder as carries_placeholder +from utils.i18n.spans import has_words as has_words +from utils.i18n.spans import mask as mask +from utils.i18n.spans import matches as matches +from utils.i18n.spans import prose as prose def unmask( diff --git a/utils/i18n/repairs.py b/utils/i18n/repairs.py new file mode 100644 index 0000000000..cfe7a9c2c5 --- /dev/null +++ b/utils/i18n/repairs.py @@ -0,0 +1,100 @@ +"""Cosmetic repairs a restored translation goes through. + +Each one undoes a shape a translator produced and the source did not ask for. +They read the source only to decide whether something was lost, never to change +what the translation says. +""" + +from __future__ import annotations + +import re + +from utils.i18n import names + +EMPHASIS = re.compile(r"(\*\*)[ \t]*([^\s]|[^\s].*?[^\s])[ \t]*\1", re.DOTALL) +TERMINATORS = ".!?" +RUN_OF_SPACES = re.compile(r"[ \t]{2,}") + + +def resegment(restored: str, spans: tuple[str, ...], source: str) -> str: + """Put back the sentence boundary a translator dropped behind a protected span. + + A name is skipped. Every other protected span ends in a delimiter, so a + letter right behind it can only be the text the boundary was lost from, but + a name ends in a word character and an agglutinative language suffixes it: + ``Baserow`` is found inside the Bengali ``Baserowo`` and the punctuation + would land inside the word. + + Args: + restored: the translation with every protected span put back. + spans: the protected spans of the source. + source: the source message, which holds the boundary that went missing. + """ + named = {source[start:end] for start, end in names.spans(source)} + for span in spans: + if span in named: + continue + start = source.find(span) + if start < 0: + continue + boundary = source[start + len(span) : start + len(span) + 2] + if len(boundary) != 2 or boundary[0] not in ".,;:" or not boundary[1].isspace(): + continue + follows = restored.find(span) + len(span) + if follows > len(span) - 1 and restored[follows : follows + 1].isalpha(): + restored = restored[:follows] + boundary[0] + " " + restored[follows:] + return restored + + +def tighten(restored: str) -> str: + """Return ``restored`` with the whitespace a translator set inside emphasis removed. + + Args: + restored: the translation with every protected span put back. + """ + return EMPHASIS.sub( + lambda pair: pair.group(1) + pair.group(2) + pair.group(1), restored + ) + + +def collapse(restored: str, source: str) -> str: + """Return ``restored`` without the space runs the translator opened. + + A run the source carries itself is left alone, because an aligned block in a + code sample means its spacing. + + Args: + restored: the translation with every protected span put back. + source: the source message. + """ + if " " in source or "\t" in source: + return restored + return RUN_OF_SPACES.sub(" ", restored) + + +def terminate(restored: str, source: str) -> str: + """Return ``restored`` with the sentence end the translator lost. + + A closing bracket that moves in front of a protected span takes the full + stop behind it with it, which leaves the sentence running on. + + Args: + restored: the translation with every protected span put back. + source: the source message. + """ + end = source.rstrip()[-1:] + if end not in TERMINATORS or restored.rstrip().endswith(tuple(TERMINATORS)): + return restored + return restored.rstrip() + end + + +def recapitalise(restored: str, source: str) -> str: + """Return ``restored`` with the capital its opening word lost. + + Args: + restored: the translation with every protected span put back. + source: the source message. + """ + if not source[:1].isupper() or not restored[:1].islower(): + return restored + return restored[0].upper() + restored[1:] diff --git a/utils/i18n/spans.py b/utils/i18n/spans.py new file mode 100644 index 0000000000..1baf58e4c7 --- /dev/null +++ b/utils/i18n/spans.py @@ -0,0 +1,147 @@ +"""Which parts of a message are protected, and how they are masked for a request. + +The base layer of :mod:`utils.i18n.placeholders`: it knows the protection rules +and nothing about damage or repair, so :mod:`utils.i18n.damage` can build on it +without an import cycle. +""" + +from __future__ import annotations + +import html +import re +from dataclasses import dataclass +from functools import lru_cache + +from utils.i18n import names + +PRINTF = r"%\([A-Za-z_]\w*\)[sdif]|%[sdif]" +PLACEHOLDER = re.compile(PRINTF) + +PROTECTED = re.compile( + r"``.+?``" + r"|:[\w.+-]+:`[^`]+`" + r"|`[^`]+`_{0,2}" + r"|\{\{.+?\}\}" + r"|\{%.+?%\}" + r"|\{\{.*" + r"|\{[A-Za-z_]\w*\}" + rf"|{PRINTF}" + r"|https?://(?:[^\s<>\"'`()\[\]]|\([^\s<>\"'`()]*\))+" + r"|<[^<>\s]+>" + r"|(?<=\])\((?:[^\s()]|\([^\s()]*\))+\)" + r"|(?\s]*>[\w.-]*)*\"|'[\w.-]*(?:<[^>\s]*>[\w.-]*)*'" + r"|\d+(?:[.,]\d+)*" + r"|\*\*|\*|`|\[|\]|\{|\}|\(|\)|\"" +) + +EXTRA = re.compile( + r"[\U0001F300-\U0001FAFF☀-➿️]" + r"|[\w.+-]+@[\w-]+\.[\w.]+" +) + +TOKEN = re.compile(r'(?:\s*)?') + + +def carries_placeholder(message_id: str | tuple[str, ...]) -> bool: + """Return whether ``message_id`` holds a printf placeholder a translation must keep. + + Args: + message_id: a catalog message id, singular or a plural tuple. + """ + forms = message_id if isinstance(message_id, tuple) else (message_id,) + return any(PLACEHOLDER.search(form) for form in forms) + + +@lru_cache(maxsize=1 << 17) +def _claimed(text: str, with_names: bool) -> tuple[tuple[int, int], ...]: + found = [(m.start(), m.end()) for m in PROTECTED.finditer(text)] + found += [(m.start(), m.end()) for m in EXTRA.finditer(text)] + if with_names: + found += names.spans(text) + kept: list[tuple[int, int]] = [] + reach = 0 + for start, end in sorted(found): + if start < reach: + continue + kept.append((start, end)) + reach = end + return tuple(kept) + + +def matches(text: str, with_names: bool = True) -> list[tuple[int, int]]: + """Return the non-overlapping offsets every protection rule claims. + + The scan is cached behind a fresh list, because one source message is + scanned once per target language and callers may sort or trim the result. + + Args: + text: a source message or its translation. + with_names: whether role names and titles take part. They do when a + request is masked, so the translator never sees them, and they do + not when two texts are compared: German capitalises every noun, so + the lowercase ``shell extensions`` becomes ``Shell-Erweiterungen`` + and a set comparison would read the capital as a surplus span. + """ + return list(_claimed(text, with_names)) + + +def prose(text: str) -> str: + """Return ``text`` with every protected span removed. + + Args: + text: a source message. + """ + plain, position = [], 0 + for start, end in matches(text): + plain.append(text[position:start]) + position = end + plain.append(text[position:]) + return "".join(plain) + + +def has_words(text: str) -> bool: + """Return whether ``text`` holds any letter outside its protected spans. + + Args: + text: a source message. + """ + return any(character.isalpha() for character in prose(text)) + + +@dataclass(frozen=True) +class Masked: + """A message prepared for an HTML-mode translation request. + + Args: + text: HTML with every protected span replaced by an ```` token. + spans: the protected spans, indexed by token id. + """ + + text: str + spans: tuple[str, ...] + + +@lru_cache(maxsize=1 << 16) +def mask(text: str) -> Masked: + """Return ``text`` escaped for HTML with its protected spans tokenised. + + The result is immutable and one source message is masked once per target + language, so the same string arrives dozens of times per run. + + Args: + text: the source message. + """ + spans: list[str] = [] + parts: list[str] = [] + position = 0 + for start, end in matches(text): + parts.append(html.escape(text[position:start], quote=False)) + parts.append(f'') + spans.append(text[start:end]) + position = end + parts.append(html.escape(text[position:], quote=False)) + return Masked("".join(parts), tuple(spans)) diff --git a/utils/roles/required_by_coverage.py b/utils/roles/required_by_coverage.py index 1d342dfcc3..ff88b29e8b 100644 --- a/utils/roles/required_by_coverage.py +++ b/utils/roles/required_by_coverage.py @@ -8,10 +8,12 @@ from __future__ import annotations import re from pathlib import Path +from plugins.filter.invokable_paths import get_invokable_paths from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.roles.categories import categories_file from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.roles.validation.invokable import _is_role_invokable from . import PROJECT_ROOT @@ -21,21 +23,16 @@ def _default_roles_dir(roles_dir: str | Path | None) -> Path: def role_is_invokable(role_id: str, roles_dir: str | Path | None = None) -> bool: - """True when any node along `role_id`'s category path has `invokable: true`.""" + """True when `role_id` sits at or below a category marked ``invokable: true``. + + Args: + role_id: the role to classify. + roles_dir: the roles directory whose sibling ``categories.yml`` decides. + """ if not role_id: return False spot = categories_file(_default_roles_dir(roles_dir).parent) - tree_doc = load_yaml_any(str(spot), default_if_missing={}) - tree = tree_doc.get("roles") or {} if isinstance(tree_doc, dict) else {} - - node = tree - for seg in str(role_id).split("-"): - if not seg or not isinstance(node, dict) or seg not in node: - break - node = node[seg] - if isinstance(node, dict) and node.get("invokable") is True: - return True - return False + return _is_role_invokable(role_id, [str(p) for p in get_invokable_paths(str(spot))]) def role_has_required_by(role_id: str, roles_dir: str | Path | None = None) -> bool: