diff --git a/.cargo/audit.toml b/.cargo/audit.toml index fea4fe1..c2b945b 100644 --- a/.cargo/audit.toml +++ b/.cargo/audit.toml @@ -52,4 +52,13 @@ ignore = [ # a compatible bump; the affected methods are not exercised by our stack. "RUSTSEC-2026-0002", "RUSTSEC-2026-0253", + + # RUSTSEC-2026-0620 — curve25519-dalek 4.1.3, scalar-multiplication bug in the AVX-512 backend. The fix is + # only in curve25519-dalek 5.1.0, which needs ed25519-dalek 3 and x25519-dalek 3 (direct dependencies of + # transferd-crypto, both 2.x now): a major bump with API changes, not a lockfile bump. The bug is reached only + # when the crate is compiled on nightly on an AVX-512 CPU (runtime backend selection), so stable builds and the + # release binaries are not affected. The nightly fuzz smoke job is the one to watch. Time-boxed: remove by + # 2026-12-31 through the ed25519-dalek 3 / x25519-dalek 3 migration of transferd-crypto. Deadline tracked by the + # maintainer. + "RUSTSEC-2026-0620", ] \ No newline at end of file diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..9e5aa7c --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,20 @@ +#!/bin/sh +# Runs the fast local checks before each commit: preflight (tools, lockfile, line endings, staged changes, +# secrets) and the pipeline's own tests. Full reference: docs/LOCAL_CI.md. +# Skip once with: git commit --no-verify +set -eu + +PY="" +for candidate in python3 python "py -3"; do + if $candidate -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' >/dev/null 2>&1; then + PY=$candidate + break + fi +done +if [ -z "$PY" ]; then + echo "pre-commit: Python 3.11 or newer is needed for the local checks (skip once: git commit --no-verify)" >&2 + exit 1 +fi + +cd "$(git rev-parse --show-toplevel)" +exec $PY ci/ci.py run --profile precommit diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..0ae3502 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,20 @@ +#!/bin/sh +# Runs the checks before each push: the workflow's Rust checks (fmt, clippy, tests), the Python tests with +# interop, and the pipeline's own tests. The full profile (GUI, TypeScript, audit) runs nightly or by hand. +# Full reference: docs/LOCAL_CI.md. Skip once with: git push --no-verify +set -eu + +PY="" +for candidate in python3 python "py -3"; do + if $candidate -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' >/dev/null 2>&1; then + PY=$candidate + break + fi +done +if [ -z "$PY" ]; then + echo "pre-push: Python 3.11 or newer is needed for the local checks (skip once: git push --no-verify)" >&2 + exit 1 +fi + +cd "$(git rev-parse --show-toplevel)" +exec $PY ci/ci.py run --profile prepush diff --git a/.github/workflows/core-ci.yml b/.github/workflows/core-ci.yml index 4d6de2c..30b6675 100644 --- a/.github/workflows/core-ci.yml +++ b/.github/workflows/core-ci.yml @@ -12,12 +12,18 @@ env: CARGO_TERM_COLOR: always RUSTFLAGS: -D warnings +# Every job runs on the project's own self-hosted runners, never on a GitHub-hosted machine: Linux, plus the +# Windows leg of the build. The repository is public, so a pull request from a fork must never run on a +# self-hosted runner: each job below checks that the pull request comes from this repository. Runners must be +# registered before any job starts; until one is, jobs stay queued. +# # Everything in this workflow builds from this repository alone. No GUI toolkit, # no daemon, no system libraries beyond the Rust toolchain. jobs: check: name: format, clippy, tests - runs-on: ubuntu-latest + runs-on: [self-hosted, Linux, X64] + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable @@ -32,20 +38,33 @@ jobs: - run: cargo test --workspace --all-features build: - name: build relay binaries (${{ matrix.os }}) + name: build relay binaries (${{ matrix.label }}) strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - runs-on: ${{ matrix.os }} + include: + - label: Linux + artifact: linux + runs_on: '["self-hosted", "Linux", "X64"]' + # The Windows leg needs the MSVC toolchain (Visual Studio Build Tools, C++ workload), which only the msvc runners have. + - label: Windows + artifact: windows + runs_on: '["self-hosted", "Windows", "X64", "msvc"]' + # macOS is not built here: there is no macOS self-hosted runner yet. Add it back when one is registered. + runs-on: ${{ fromJSON(matrix.runs_on) }} + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 + # The Windows runner shares this PC's memory: two parallel compile jobs stay inside the paging file. + - if: runner.os == 'Windows' + shell: pwsh + run: echo "CARGO_BUILD_JOBS=2" >> $env:GITHUB_ENV - run: cargo build --release -p relayd -p transferd-relay -p transferd-cat - uses: actions/upload-artifact@v4 with: - name: transferd-core-${{ matrix.os }} + name: transferd-core-${{ matrix.artifact }} path: | target/release/relayd* target/release/relayd-ws* @@ -54,7 +73,8 @@ jobs: fuzz: name: fuzz smoke (relay protocol parser) - runs-on: ubuntu-latest + runs-on: [self-hosted, Linux, X64] + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly @@ -64,7 +84,8 @@ jobs: python: name: python (tests, including interop with the reference) - runs-on: ubuntu-latest + runs-on: [self-hosted, Linux, X64] + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable @@ -82,7 +103,8 @@ jobs: typescript: name: typescript (tests, including interop with the reference) - runs-on: ubuntu-latest + runs-on: [self-hosted, Linux, X64] + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable @@ -102,8 +124,8 @@ jobs: audit: name: dependency audit - runs-on: ubuntu-latest - if: github.event_name != 'pull_request' + runs-on: [self-hosted, Linux, X64] + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable diff --git a/ci/checks.py b/ci/checks.py new file mode 100644 index 0000000..836b88e --- /dev/null +++ b/ci/checks.py @@ -0,0 +1,291 @@ +"""Preflight checks: the tools the pipeline needs, the lockfile, line endings, and what is being committed. + +Every check returns Finding values and takes what it inspects as arguments, so the tests can feed it +text and fake command results without touching git or the toolchain. +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Callable, List, Optional, Sequence, Tuple + +MIN_PYTHON = (3, 11) +MIN_NODE = 20 +BIG_FILE_BYTES = 5 * 1024 * 1024 +ALLOW_MARK = "ci:allow-secret" +CRLF_OK_SUFFIXES = (".ps1", ".bat", ".cmd") + +# Written so that this file does not match its own patterns: each one needs more than the text shown here. +SECRET_PATTERNS = { + "private key": re.compile(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY"), + "AWS access key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"), + "GitHub token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"), + "Slack token": re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}"), +} + +EOL_LINE = re.compile(r"^i/(\S+)\s+w/(\S+)\s+attr/.*?\t(.+)$") + + +@dataclass(frozen=True) +class Finding: + level: str # "error" fails the stage; "warning" is reported and the stage still passes + message: str + fix: str = "" + + +def git(root: Path, *args: str) -> Tuple[int, str]: + """Run git in the repository and return its exit code and standard output.""" + try: + done = subprocess.run( + ["git", *args], + cwd=root, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except FileNotFoundError: + return 127, "" + return done.returncode, done.stdout + + +# ----- the toolchain ---------------------------------------------------------------------------------- + + +def _node_major(node: str) -> Optional[int]: + try: + text = subprocess.run([node, "--version"], capture_output=True, text=True, check=False).stdout + return int(text.strip().lstrip("v").split(".")[0]) + except (OSError, ValueError): + return None + + +def _rustup_components() -> Optional[str]: + try: + done = subprocess.run( + ["rustup", "component", "list", "--installed"], capture_output=True, text=True, check=False + ) + except FileNotFoundError: + return None + return done.stdout if done.returncode == 0 else None + + +def tool_findings( + which: Callable[[str], Optional[str]] = shutil.which, + components: Callable[[], Optional[str]] = _rustup_components, + node_major: Callable[[str], Optional[int]] = _node_major, +) -> List[Finding]: + found: List[Finding] = [] + for exe in ("git", "cargo", "rustc"): + if which(exe) is None: + found.append(Finding("error", f"{exe} is not on PATH", "install it and open a new terminal")) + if sys.version_info < MIN_PYTHON: + found.append( + Finding( + "error", + f"Python {sys.version_info.major}.{sys.version_info.minor} is too old; {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is needed", + "run the pipeline with a newer Python", + ) + ) + node = which("node") + if node is None: + found.append( + Finding( + "warning", + "Node.js is not on PATH, so the typescript stage is skipped", + "install Node.js 22, the version CI uses", + ) + ) + else: + major = node_major(node) + if major is not None and major < MIN_NODE: + found.append( + Finding("warning", f"Node.js {major} is older than {MIN_NODE}", "install Node.js 22") + ) + if which("cargo-audit") is None: + found.append( + Finding( + "warning", + "cargo-audit is not installed, so the audit stage is skipped", + "cargo install cargo-audit --locked", + ) + ) + listing = components() + if listing is None: + found.append(Finding("warning", "rustup is not available, so clippy and rustfmt cannot be checked")) + else: + installed = [line.split(" ")[0] for line in listing.splitlines()] + if not any(name.startswith("clippy") for name in installed): + found.append(Finding("error", "the clippy component is not installed", "rustup component add clippy")) + if not any(name.startswith("rustfmt") for name in installed): + found.append(Finding("warning", "the rustfmt component is not installed", "rustup component add rustfmt")) + return found + + +# ----- the lockfile ----------------------------------------------------------------------------------- + + +def lockfile_findings(root: Path, run: Callable = subprocess.run) -> List[Finding]: + """Cargo must be able to use Cargo.lock as it is: `--locked` fails when the lock would need to change.""" + if not (root / "Cargo.lock").exists(): + return [Finding("error", "Cargo.lock is missing", "run cargo generate-lockfile and commit it")] + try: + done = run( + ["cargo", "metadata", "--locked", "--format-version", "1"], + cwd=root, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except FileNotFoundError: + return [] # cargo itself is reported by tool_findings + if done.returncode != 0: + lines = (done.stderr or "").strip().splitlines() + reason = lines[-1] if lines else "cargo metadata --locked failed" + return [ + Finding( + "error", + f"Cargo.lock does not match the manifests: {reason}", + "run cargo metadata --format-version 1 >/dev/null, review the Cargo.lock change, and commit it", + ) + ] + return [] + + +# ----- line endings ----------------------------------------------------------------------------------- + + +def parse_eol(output: str) -> List[Tuple[str, str, str]]: + """Entries of `git ls-files --eol`: (path, line endings in the index, line endings in the working tree).""" + entries = [] + for line in output.splitlines(): + match = EOL_LINE.match(line) + if match: + entries.append((match.group(3), match.group(1), match.group(2))) + return entries + + +def is_script(path: str) -> bool: + return path.endswith(".sh") or path.startswith(".githooks/") + + +def eol_findings(entries: Sequence[Tuple[str, str, str]]) -> List[Finding]: + found: List[Finding] = [] + for path, index_eol, worktree_eol in entries: + if index_eol == "crlf" and not path.endswith(CRLF_OK_SUFFIXES): + found.append( + Finding("error", f"{path} is committed with CRLF line endings", f"git add --renormalize {path}") + ) + if is_script(path) and worktree_eol == "crlf": + found.append( + Finding( + "error", + f"{path} has CRLF line endings in the working tree, which sh cannot run", + f"git checkout -- {path}", + ) + ) + return found + + +def eol_entries(root: Path) -> List[Tuple[str, str, str]]: + code, out = git(root, "ls-files", "--eol") + return parse_eol(out) if code == 0 else [] + + +# ----- git hooks -------------------------------------------------------------------------------------- + + +def hooks_findings(root: Path) -> List[Finding]: + _code, out = git(root, "config", "--get", "core.hooksPath") + if out.strip() == ".githooks": + return [] + return [ + Finding( + "warning", + "git hooks are not installed, so commits and pushes are not checked here", + "python ci/ci.py hooks install", + ) + ] + + +# ----- what is being committed ------------------------------------------------------------------------ + + +def secret_findings(diff: str) -> List[Finding]: + """Scan the added lines of a diff (git diff -U0) for credentials. A line with ALLOW_MARK is exempt.""" + found: List[Finding] = [] + path = "?" + for line in diff.splitlines(): + if line.startswith("+++ "): + path = line[6:] if line.startswith("+++ b/") else line[4:] + continue + if not line.startswith("+") or line.startswith("+++"): + continue + text = line[1:] + if ALLOW_MARK in text: + continue + for label, pattern in SECRET_PATTERNS.items(): + if pattern.search(text): + found.append( + Finding( + "error", + f"{label} added to {path}", + f"remove it, or if it is a test fixture, mark that line with {ALLOW_MARK}", + ) + ) + return found + + +def staged_findings(root: Path, limit: int = BIG_FILE_BYTES) -> List[Finding]: + found: List[Finding] = [] + code, text = git(root, "diff", "--cached", "--check") + if code != 0: + first = "; ".join(text.strip().splitlines()[:3]) or "whitespace problems or conflict markers" + found.append(Finding("error", f"staged changes have problems: {first}", "fix the lines git lists")) + _code, diff = git(root, "diff", "--cached", "-U0", "--no-color") + found += secret_findings(diff) + _code, names = git(root, "diff", "--cached", "--name-only", "--diff-filter=AM", "-z") + for name in filter(None, names.split("\0")): + path = root / name + if path.is_file() and path.stat().st_size > limit: + megabytes = path.stat().st_size / (1024 * 1024) + found.append( + Finding( + "error", + f"{name} is {megabytes:.1f} MB and staged", + "keep build output out of git: git rm --cached it, then add it to .gitignore", + ) + ) + return found + + +def core_checkout(root: Path) -> Optional[Path]: + """The TransferDaemon checkout that shares the core files: $TRANSFERD_CORE_CHECKOUT, or the sibling folder.""" + configured = os.environ.get("TRANSFERD_CORE_CHECKOUT") + candidate = Path(configured) if configured else root.parent / "TransferDaemon" + return candidate if (candidate / "core.manifest").is_file() else None + + +def git_bash(which: Callable[[str], Optional[str]] = shutil.which, windows: bool = os.name == "nt") -> Optional[str]: + """A bash that runs the POSIX scripts. On Windows it is the bash of the Git for Windows install that provides + `git`, found by walking up from git.exe. The WSL launcher in System32 is never used.""" + if not windows: + return which("bash") + git_exe = which("git") + if git_exe is None: + return None + for ancestor in Path(git_exe).resolve().parents[:4]: + for relative in ("bin/bash.exe", "usr/bin/bash.exe"): + candidate = ancestor / relative + if candidate.is_file(): + return str(candidate) + return None diff --git a/ci/ci.py b/ci/ci.py new file mode 100644 index 0000000..4cb8245 --- /dev/null +++ b/ci/ci.py @@ -0,0 +1,519 @@ +#!/usr/bin/env python3 +"""Local CI for Transferd: the checks the GitHub workflow runs, the desktop app's tests, and preflight checks, +all run on this machine. See docs/LOCAL_CI.md for the stages, the profiles and the git hooks. + + python ci/ci.py run the full profile + python ci/ci.py run --profile prepush the checks before a push + python ci/ci.py run --only clippy,test rerun chosen stages (their dependencies run too) + python ci/ci.py check [--staged] preflight only; --staged also checks what is about to be committed + python ci/ci.py list the stages, their profiles and dependencies + python ci/ci.py last the summary of the last run + python ci/ci.py hooks install|uninstall|status + +Exit codes: 0 the run passed (warnings allowed), 1 a stage failed or was blocked, 2 misuse or a broken definition. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path +from typing import List, Optional, Sequence, Tuple + +from checks import ( + Finding, + core_checkout, + eol_entries, + eol_findings, + git, + git_bash, + hooks_findings, + lockfile_findings, + staged_findings, + tool_findings, +) +from engine import ( + BLOCKED, + FAIL, + PASS, + SKIP, + WARN, + ConfigError, + Context, + Pipeline, + Record, + Result, + Stage, + Step, + now_iso, + overall, + run_steps, + save_report, +) + +ROOT = Path(__file__).resolve().parent.parent +PROFILES = ("precommit", "prepush", "full", "nightly") +CI_RUSTFLAGS: Tuple[Tuple[str, str], ...] = (("RUSTFLAGS", "-D warnings"),) # the same as the GitHub workflow +STALE_LOCK_SECONDS = 6 * 3600 + + +def default_jobs() -> int: + return max(1, min(4, os.cpu_count() or 2)) + + +def base_env() -> dict: + env = dict(os.environ) + env.update( + { + "CARGO_TERM_COLOR": "never", + "CARGO_TERM_PROGRESS_WHEN": "never", + "PYTHONUTF8": "1", + "CI_LOCAL": "1", + } + ) + return env + + +def cargo(*args: str, env: Tuple[Tuple[str, str], ...] = (), timeout: Optional[float] = None) -> Step: + return Step(("cargo", *args), env=env, timeout=timeout) + + +def venv_python(venv: Path) -> Path: + return venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + + +def interop_env(ctx: Context) -> Tuple[Tuple[str, str], ...]: + """The reference binaries the Python and TypeScript interop tests and the GUI tests need.""" + return ( + ("TRANSFERD_INTEROP_PEER", str(ctx.exe("target/debug/examples/interop_peer"))), + ("TRANSFERD_RELAYD", str(ctx.exe("target/debug/relayd"))), + ) + + +def findings_result(ctx: Context, stage: str, findings: Sequence[Finding]) -> Result: + for finding in findings: + text = f"{finding.level.upper()}: {finding.message}" + if finding.fix: + text += f"\n fix: {finding.fix}" + ctx.note(stage, text) + if not findings: + ctx.note(stage, "no findings") + errors = [f for f in findings if f.level == "error"] + where = f" (log: {Context.log_name(stage)})" + if errors: + shown = "; ".join(f.message for f in errors[:2]) + more = f" (+{len(errors) - 2} more)" if len(errors) > 2 else "" + return Result(FAIL, shown + more + where) + warnings = [f for f in findings if f.level == "warning"] + if warnings: + return Result(WARN, "; ".join(w.message for w in warnings[:2])) + return Result(PASS, "all checks clear") + + +def fingerprint(*parts: object) -> str: + """A stamp for an install: changes when any file or version it depends on changes.""" + digest = hashlib.sha256() + for part in parts: + if isinstance(part, Path): + digest.update(part.read_bytes()) + else: + digest.update(str(part).encode("utf-8")) + digest.update(b"\0") + return digest.hexdigest() + + +def ensure_venv(ctx: Context, stage: str, venv: Path, source: Path, requirement: str) -> Optional[Result]: + """Create the stage's virtual environment and install `requirement` into it, only when its stamp is stale.""" + python = venv_python(venv) + if not python.exists(): + if ctx.run(stage, Step((sys.executable, "-m", "venv", str(venv)), timeout=300)) != 0: + return Result(FAIL, f"could not create the virtual environment in {venv} (log: {Context.log_name(stage)})") + stamp_value = fingerprint(source, sys.version, requirement) + stamp = venv / ".ci-stamp" + if stamp.exists() and stamp.read_text(encoding="utf-8") == stamp_value: + ctx.note(stage, "dependencies are up to date; the install is skipped") + return None + install = Step((str(python), "-m", "pip", "install", "--quiet", "-e", requirement), timeout=900) + if ctx.run(stage, install) != 0: + return Result(FAIL, f"pip install -e {requirement} failed (log: {Context.log_name(stage)})") + stamp.write_text(stamp_value, encoding="utf-8") + return None + + +# ----- the stages ------------------------------------------------------------------------------------- + + +def _preflight(ctx: Context) -> Result: + findings: List[Finding] = [] + findings += tool_findings() + findings += lockfile_findings(ctx.root) + findings += eol_findings(eol_entries(ctx.root)) + findings += hooks_findings(ctx.root) + if ctx.profile == "precommit": + findings += staged_findings(ctx.root) + return findings_result(ctx, "preflight", findings) + + +def _fmt(ctx: Context) -> Result: + result = run_steps(ctx, "fmt", [cargo("fmt", "--all", "--", "--check")], "every file is rustfmt-clean") + if result.status == FAIL: + return Result(FAIL, f"files are not rustfmt-clean (log: {Context.log_name('fmt')})") + return result + + +def _clippy(ctx: Context) -> Result: + step = cargo("clippy", "--workspace", "--all-features", "--", "-D", "warnings", env=CI_RUSTFLAGS) + return run_steps(ctx, "clippy", [step], "no warnings") + + +def _test(ctx: Context) -> Result: + step = cargo("test", "--workspace", "--all-features", env=CI_RUSTFLAGS, timeout=3600) + return run_steps(ctx, "test", [step], "every Rust test passed") + + +def _interop_bins(ctx: Context) -> Result: + return run_steps( + ctx, + "interop-bins", + [ + cargo("build", "-p", "transferd-overlay", "--example", "interop_peer", env=CI_RUSTFLAGS), + cargo("build", "-p", "relayd", "--bin", "relayd", env=CI_RUSTFLAGS), + ], + "interop_peer and relayd are built", + ) + + +def _relay_build(ctx: Context) -> Result: + step = cargo("build", "--release", "-p", "relayd", "-p", "transferd-relay", "-p", "transferd-cat", env=CI_RUSTFLAGS) + return run_steps(ctx, "relay-build", [step], "release relay binaries are built") + + +def _python(ctx: Context) -> Result: + venv = ctx.root / "target" / "ci" / "venv-python" + failure = ensure_venv(ctx, "python", venv, ctx.root / "python" / "pyproject.toml", "python[test]") + if failure is not None: + return failure + step = Step((str(venv_python(venv)), "-m", "pytest", "python/tests", "-q"), env=interop_env(ctx), timeout=1200) + return run_steps(ctx, "python", [step], "pytest passed, including interop") + + +def _typescript(ctx: Context) -> Result: + node, npm = shutil.which("node"), shutil.which("npm") + if node is None or npm is None: + return Result(SKIP, "needs Node.js 20 or newer with npm (CI uses 22)") + typescript = ctx.root / "typescript" + lock = typescript / "package-lock.json" + stamp_value = fingerprint(lock, subprocess.run([node, "--version"], capture_output=True, text=True).stdout) + stamp = typescript / "node_modules" / ".ci-stamp" + if not (stamp.exists() and stamp.read_text(encoding="utf-8") == stamp_value): + result = run_steps(ctx, "typescript", [Step((npm, "--prefix", "typescript", "ci"), timeout=900)]) + if result.status == FAIL: + return result + stamp.write_text(stamp_value, encoding="utf-8") + else: + ctx.note("typescript", "dependencies are up to date; npm ci is skipped") + step = Step((npm, "--prefix", "typescript", "test"), env=interop_env(ctx), timeout=900) + return run_steps(ctx, "typescript", [step], "node tests passed, including interop") + + +def _gui(ctx: Context) -> Result: + gui = ctx.root / "gui" + python = venv_python(gui / ".venv") + if not python.exists(): + return Result(SKIP, "no GUI virtual environment: create it as gui/README.md describes") + env = (("TRANSFERD_RELAYD", str(ctx.exe("target/debug/relayd"))),) + return run_steps( + ctx, + "gui", + [ + Step((str(python), "-m", "pytest", "tests", "-q"), cwd="gui", env=env, timeout=1800), + Step((str(python), "-m", "pyflakes", "transferd_gui", "tests", "run.py"), cwd="gui", timeout=300), + ], + "desktop app tests and pyflakes passed", + ) + + +def _audit(ctx: Context) -> Result: + if shutil.which("cargo-audit") is None: + return Result(SKIP, "cargo-audit is not installed: cargo install cargo-audit --locked") + return run_steps(ctx, "audit", [Step(("cargo", "audit"), timeout=900)], "no vulnerabilities (warnings allowed)") + + +def _core_sync(ctx: Context) -> Result: + checkout = core_checkout(ctx.root) + if checkout is None: + return Result(SKIP, "no TransferDaemon checkout beside this one (set TRANSFERD_CORE_CHECKOUT)") + bash = git_bash() + if bash is None: + return Result(SKIP, "no bash found; Git for Windows provides one") + step = Step((bash, "scripts/sync-core.sh", checkout.as_posix(), "--check"), timeout=300) + result = run_steps(ctx, "core-sync", [step], "core files match TransferDaemon") + if result.status == FAIL: + # The script's own hint names the wrong direction when run from here. The copy goes from Transferd + # into TransferDaemon, so the command runs in the TransferDaemon checkout, pointing at this one. + return Result( + FAIL, + f"core files differ from TransferDaemon (log: {Context.log_name('core-sync')}); fix: run " + f"scripts/sync-core.sh {ctx.root.as_posix()} inside {checkout.as_posix()}", + ) + return result + + +def _selftest(ctx: Context) -> Result: + step = Step((sys.executable, "-m", "unittest", "discover", "-s", "ci/tests", "-q"), timeout=300) + return run_steps(ctx, "selftest", [step], "the pipeline's own tests passed") + + +def _fuzz(ctx: Context) -> Result: + if shutil.which("cargo-fuzz") is None: + return Result(SKIP, "cargo-fuzz is not installed: cargo install cargo-fuzz --locked") + listing = subprocess.run(["rustup", "toolchain", "list"], capture_output=True, text=True, check=False).stdout + if "nightly" not in listing: + return Result(SKIP, "no nightly toolchain: rustup toolchain install nightly") + step = cargo("+nightly", "fuzz", "run", "fuzz_relay_protocol", "--", "-max_total_time=120", timeout=900) + return run_steps(ctx, "fuzz", [step], "fuzz smoke passed") + + +def build_stages(*, strict_fmt: bool = False) -> List[Stage]: + """Declaration order is the order in which the cargo lane runs stages that are ready at the same time.""" + everything = ("prepush", "full", "nightly") + return [ + Stage("preflight", "tools, lockfile, line endings, staged changes", _preflight, + profiles=("precommit", *everything)), + Stage("fmt", "rustfmt check", _fmt, needs=("preflight",), lane="cargo", + profiles=everything, informational=not strict_fmt), + Stage("clippy", "clippy, warnings are errors", _clippy, needs=("preflight",), lane="cargo", + profiles=everything), + Stage("test", "cargo test, whole workspace", _test, needs=("clippy",), lane="cargo", profiles=everything), + Stage("interop-bins", "build interop_peer and relayd", _interop_bins, needs=("test",), lane="cargo", + profiles=everything), + Stage("relay-build", "release relay binaries", _relay_build, needs=("test",), lane="cargo", + profiles=("full", "nightly")), + Stage("python", "Python tests, including interop", _python, needs=("interop-bins",), + profiles=everything), + Stage("typescript", "TypeScript tests, including interop", _typescript, needs=("interop-bins",), + profiles=("full", "nightly")), + Stage("gui", "desktop app tests and pyflakes", _gui, needs=("interop-bins",), profiles=("full", "nightly")), + Stage("audit", "cargo audit", _audit, needs=("preflight",), profiles=("full", "nightly")), + Stage("core-sync", "core files match TransferDaemon", _core_sync, needs=("preflight",), + profiles=("full", "nightly")), + Stage("selftest", "tests of this pipeline", _selftest, profiles=("precommit", *everything)), + Stage("fuzz", "fuzz smoke on the nightly toolchain", _fuzz, needs=("test",), lane="cargo", + profiles=("nightly",)), + ] + + +# ----- running ---------------------------------------------------------------------------------------- + + +class RunLock: + """One run at a time: a hook and a manual run must not both drive cargo. A lock older than + STALE_LOCK_SECONDS is taken over, since its run cannot still be going.""" + + def __init__(self, path: Path) -> None: + self.path = path + + def __enter__(self) -> "RunLock": + self.path.parent.mkdir(parents=True, exist_ok=True) + if self.path.exists(): + age = time.time() - self.path.stat().st_mtime + if age < STALE_LOCK_SECONDS: + raise RuntimeError( + f"another run is in progress ({self.path}, {age / 60:.0f} min old). " + "If no run is going, delete that file." + ) + self.path.write_text(f"{os.getpid()} {now_iso()}\n", encoding="utf-8") + return self + + def __exit__(self, *exc: object) -> None: + self.path.unlink(missing_ok=True) + + +def new_run_id() -> str: + _code, sha = git(ROOT, "rev-parse", "--short", "HEAD") + stamp = time.strftime("%Y%m%d-%H%M%S") + return f"{stamp}-{sha.strip() or 'nogit'}" + + +def repo_state() -> dict: + _code, commit = git(ROOT, "rev-parse", "HEAD") + _code, branch = git(ROOT, "rev-parse", "--abbrev-ref", "HEAD") + _code, status = git(ROOT, "status", "--porcelain") + return { + "commit": commit.strip() or None, + "branch": branch.strip() or None, + "dirty": bool(status.strip()), + } + + +def execute( + pipeline: Pipeline, + selected: Sequence[Stage], + label: str, + *, + jobs: int, + fail_fast: bool, + extra: dict, +) -> int: + run_id = new_run_id() + run_dir = ROOT / "target" / "ci" / "runs" / run_id + ctx = Context(ROOT, run_dir, label, base_env()) + names = [stage.name for stage in selected] + print(f"Transferd local CI profile={label} run={run_id}") + print(f"stages ({len(names)}): {', '.join(names)} jobs={jobs}") + meta = { + "run_id": run_id, + "profile": label, + "started": now_iso(), + "jobs": jobs, + "fail_fast": fail_fast, + "python": sys.version.split()[0], + "platform": sys.platform, + "stages": names, + **repo_state(), + **extra, + } + began = time.monotonic() + with RunLock(ROOT / "target" / "ci" / "run.lock"): + records = pipeline.run(selected, ctx, jobs=jobs, fail_fast=fail_fast) + wall = time.monotonic() - began + meta["finished"] = now_iso() + meta["wall_seconds"] = round(wall, 1) + report = save_report(ROOT, run_dir, meta, records) + print_summary(records, wall, report) + return 1 if overall(records) == FAIL else 0 + + +def print_summary(records: Sequence[Record], wall: float, report: Path) -> None: + print() + print(f"{'stage':<14}{'status':<9}{'time':>8} detail") + for record in records: + print(f"{record.name:<14}{record.status.upper():<9}{record.seconds:>7.1f}s {record.detail}") + verdict = overall(records).upper() + failed = [r.name for r in records if r.status in (FAIL, BLOCKED)] + tail = f" failed: {', '.join(failed)}" if failed else "" + print(f"\nResult: {verdict} in {wall:.1f}s{tail}") + try: + shown = report.relative_to(ROOT) + except ValueError: + shown = report + print(f"report: {shown}") + + +def cmd_run(args: argparse.Namespace) -> int: + pipeline = Pipeline(build_stages(strict_fmt=args.strict_fmt)) + if args.only: + selected = pipeline.select(only=args.only) + label = "custom" + else: + label = args.profile or "full" + selected = pipeline.select(profile=label) + return execute(pipeline, selected, label, jobs=args.jobs, fail_fast=args.fail_fast, extra={}) + + +def cmd_check(args: argparse.Namespace) -> int: + label = "precommit" if args.staged else "custom" + pipeline = Pipeline(build_stages()) + selected = pipeline.select(only=["preflight"]) + return execute(pipeline, selected, label, jobs=1, fail_fast=True, extra={"check_only": True}) + + +def cmd_list(_args: argparse.Namespace) -> int: + stages = build_stages() + print(f"{'stage':<13}{'lane':<7}{'profiles':<40}{'needs':<16}title") + for stage in stages: + print( + f"{stage.name:<13}{(stage.lane or '-'):<7}{','.join(stage.profiles):<40}" + f"{(','.join(stage.needs) or '-'):<16}{stage.title}" + ) + return 0 + + +def cmd_last(_args: argparse.Namespace) -> int: + path = ROOT / "target" / "ci" / "latest.json" + if not path.exists(): + print("no runs yet: python ci/ci.py run") + return 0 + data = json.loads(path.read_text(encoding="utf-8")) + meta = data.get("meta", {}) + print(f"{meta.get('run_id')} profile={meta.get('profile')} commit={str(meta.get('commit'))[:10]} " + f"{data.get('status', '?').upper()}") + for stage in data.get("stages", []): + print(f" {stage['status'].upper():<8}{stage['name']:<14}{stage['seconds']:>7.1f}s {stage['detail']}") + return 1 if data.get("status") == FAIL else 0 + + +def cmd_hooks(args: argparse.Namespace) -> int: + hooks = ROOT / ".githooks" + if args.action == "install": + if not (hooks / "pre-commit").is_file(): + print("error: .githooks/pre-commit is missing", file=sys.stderr) + return 2 + for name in ("pre-commit", "pre-push"): + path = hooks / name + if path.is_file(): + os.chmod(path, 0o755) + subprocess.run(["git", "config", "core.hooksPath", ".githooks"], cwd=ROOT, check=True) + print("hooks installed: pre-commit runs the precommit profile, pre-push runs prepush.") + print("bypass once with: git commit --no-verify / git push --no-verify") + return 0 + if args.action == "uninstall": + subprocess.run(["git", "config", "--unset", "core.hooksPath"], cwd=ROOT, check=False) + print("hooks removed: git runs no pipeline hooks now.") + return 0 + _code, value = git(ROOT, "config", "--get", "core.hooksPath") + print(f"core.hooksPath = {value.strip() or '(not set)'}") + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="ci.py", description="Local CI for Transferd.") + sub = parser.add_subparsers(dest="command", required=True) + + run = sub.add_parser("run", help="run the stages of a profile, or the stages named with --only") + group = run.add_mutually_exclusive_group() + group.add_argument("--profile", choices=PROFILES, help="default: full") + group.add_argument("--only", type=lambda text: [name for name in text.split(",") if name], metavar="STAGES") + run.add_argument("--jobs", type=int, default=default_jobs(), help="stages that may run at once") + run.add_argument("--fail-fast", action="store_true", help="stop starting stages after the first failure") + run.add_argument("--strict-fmt", action="store_true", help="fail on rustfmt differences (CI only warns)") + + check = sub.add_parser("check", help="preflight checks only") + check.add_argument("--staged", action="store_true", help="also check what is staged for the next commit") + + sub.add_parser("list", help="show the stages") + sub.add_parser("last", help="show the last run") + hooks = sub.add_parser("hooks", help="install, remove or show the git hooks") + hooks.add_argument("action", choices=["install", "uninstall", "status"]) + return parser + + +def main(argv: Optional[Sequence[str]] = None) -> int: + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(errors="replace") + arguments = list(sys.argv[1:] if argv is None else argv) + if not arguments or arguments[0].startswith("-"): + arguments = ["run", *arguments] + args = build_parser().parse_args(arguments) + handlers = {"run": cmd_run, "check": cmd_check, "list": cmd_list, "last": cmd_last, "hooks": cmd_hooks} + try: + return handlers[args.command](args) + except ConfigError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + except RuntimeError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + print("interrupted", file=sys.stderr) + return 130 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ci/engine.py b/ci/engine.py new file mode 100644 index 0000000..ae44bf6 --- /dev/null +++ b/ci/engine.py @@ -0,0 +1,318 @@ +"""The engine of the local pipeline. + +It runs stages in dependency order. Stages that use the cargo target directory share one lane, so +they never wait on cargo's lock; every other stage can overlap with them. Each stage writes its own +log, and each run is saved as a JSON report. The engine knows nothing about Rust or Python: ci.py +defines the stages. +""" + +from __future__ import annotations + +import concurrent.futures as futures +import datetime as dt +import json +import os +import shutil +import subprocess +import threading +import time +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Callable, Dict, List, Optional, Sequence, Tuple + +PASS, WARN, FAIL, SKIP, BLOCKED = "pass", "warn", "fail", "skip", "blocked" +NOT_FOUND = 127 +TIMED_OUT = 124 +KEEP_RUNS = 20 +TAIL_LINES = 25 + + +class ConfigError(Exception): + """A stage definition is wrong: a duplicate name, an unknown dependency or a cycle. A bug in ci.py.""" + + +@dataclass(frozen=True) +class Step: + """One command. `cwd` is relative to the repository root; `env` is added to the run's environment.""" + + argv: Tuple[str, ...] + cwd: str = "." + env: Tuple[Tuple[str, str], ...] = () + timeout: Optional[float] = None + + +@dataclass(frozen=True) +class Result: + status: str + detail: str = "" + + +@dataclass(frozen=True) +class Stage: + name: str + title: str + body: Callable[["Context"], Result] + needs: Tuple[str, ...] = () + lane: str = "" + profiles: Tuple[str, ...] = () + informational: bool = False + + +@dataclass +class Record: + name: str + title: str + status: str + detail: str + seconds: float + log: str + + +class Context: + """What a stage body receives: the repository, this run's folder, the profile and the environment.""" + + def __init__(self, root: Path, run_dir: Path, profile: str, env: Dict[str, str]) -> None: + self.root = root + self.run_dir = run_dir + self.profile = profile + self.env = env + (run_dir / "logs").mkdir(parents=True, exist_ok=True) + + @staticmethod + def log_name(stage: str) -> str: + return f"logs/{stage}.log" + + def logfile(self, stage: str) -> Path: + return self.run_dir / self.log_name(stage) + + def note(self, stage: str, text: str) -> None: + with open(self.logfile(stage), "a", encoding="utf-8", errors="replace") as log: + log.write(text.rstrip() + "\n") + + def exe(self, relative: str) -> Path: + """A file built into the repository, with the platform's executable suffix.""" + return self.root / (relative + (".exe" if os.name == "nt" else "")) + + def run(self, stage: str, step: Step) -> int: + """Run one step with its output appended to the stage's log. Returns the exit code.""" + env = dict(self.env) + env.update(dict(step.env)) + resolved = shutil.which(step.argv[0], path=env.get("PATH")) + with open(self.logfile(stage), "a", encoding="utf-8", errors="replace") as log: + log.write(f"\n$ {subprocess.list2cmdline(list(step.argv))}\n in {step.cwd}\n") + log.flush() + if resolved is None: + log.write(f" not found on PATH: {step.argv[0]}\n") + return NOT_FOUND + try: + done = subprocess.run( + [resolved, *step.argv[1:]], + cwd=self.root / step.cwd, + env=env, + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + timeout=step.timeout, + check=False, + ) + except subprocess.TimeoutExpired: + log.write(f" timed out after {step.timeout:g} s\n") + return TIMED_OUT + return done.returncode + + +def run_steps(ctx: Context, stage: str, steps: Sequence[Step], ok_detail: str = "") -> Result: + """Run the steps in order. The first one that fails ends the stage with a pointer to its log.""" + for step in steps: + code = ctx.run(stage, step) + if code != 0: + if code == NOT_FOUND: + why = "not found" + elif code == TIMED_OUT: + why = "timed out" + else: + why = f"exit code {code}" + name = " ".join([os.path.basename(step.argv[0]), *step.argv[1:2]]) + return Result(FAIL, f"{name}: {why} (log: {Context.log_name(stage)})") + return Result(PASS, ok_detail) + + +class Pipeline: + def __init__(self, stages: Sequence[Stage]) -> None: + self.by_name: Dict[str, Stage] = {} + for stage in stages: + if stage.name in self.by_name: + raise ConfigError(f"stage {stage.name} is defined twice") + self.by_name[stage.name] = stage + for stage in stages: + for dep in stage.needs: + if dep not in self.by_name: + raise ConfigError(f"stage {stage.name} needs {dep}, which is not defined") + self._check_acyclic() + + def _check_acyclic(self) -> None: + state: Dict[str, int] = {} + + def visit(name: str, path: List[str]) -> None: + if state.get(name) == 2: + return + if state.get(name) == 1: + raise ConfigError("dependency cycle: " + " -> ".join(path + [name])) + state[name] = 1 + for dep in self.by_name[name].needs: + visit(dep, path + [name]) + state[name] = 2 + + for name in self.by_name: + visit(name, []) + + def select(self, *, profile: Optional[str] = None, only: Sequence[str] = ()) -> List[Stage]: + """The stages to run: those named, or those in a profile, plus everything they need. Declaration order.""" + if only: + unknown = [name for name in only if name not in self.by_name] + if unknown: + raise ConfigError("unknown stage: " + ", ".join(unknown)) + wanted = set(only) + elif profile: + wanted = {name for name, stage in self.by_name.items() if profile in stage.profiles} + if not wanted: + raise ConfigError(f"no stage belongs to the profile {profile}") + else: + raise ConfigError("choose a profile or name the stages to run") + pending = list(wanted) + while pending: + for dep in self.by_name[pending.pop()].needs: + if dep not in wanted: + wanted.add(dep) + pending.append(dep) + return [stage for name, stage in self.by_name.items() if name in wanted] + + def run( + self, + selected: Sequence[Stage], + ctx: Context, + *, + jobs: int, + fail_fast: bool, + emit: Callable[[str], None] = print, + ) -> List[Record]: + names = [stage.name for stage in selected] + jobs = max(1, jobs) + lanes: Dict[str, threading.Lock] = {} + for stage in selected: + if stage.lane and stage.lane not in lanes: + lanes[stage.lane] = threading.Lock() + results: Dict[str, Record] = {} + pending = list(names) + running: Dict[futures.Future, str] = {} + stop = threading.Event() + print_lock = threading.Lock() + + def say(line: str) -> None: + with print_lock: + emit(line) + + def execute(stage: Stage) -> Record: + lane = lanes.get(stage.lane) + if lane is not None: + lane.acquire() + try: + say(f" start {stage.name}") + began = time.monotonic() + try: + result = stage.body(ctx) + except Exception as exc: # a broken stage fails by itself; the rest of the run goes on + result = Result(FAIL, f"internal error: {exc!r}") + seconds = time.monotonic() - began + finally: + if lane is not None: + lane.release() + status = result.status + if stage.informational and status == FAIL: + status = WARN + record = Record(stage.name, stage.title, status, result.detail, seconds, Context.log_name(stage.name)) + say(format_line(record)) + if status == FAIL: + for line in tail(ctx.logfile(stage.name), TAIL_LINES): + say(" | " + line) + return record + + with futures.ThreadPoolExecutor(max_workers=max(1, jobs), thread_name_prefix="ci") as pool: + while pending or running: + progressed = True + while progressed: + progressed = False + for name in list(pending): + stage = self.by_name[name] + if any(dep not in results for dep in stage.needs): + continue + failed = [d for d in stage.needs if results[d].status in (FAIL, BLOCKED)] + skipped = [d for d in stage.needs if results[d].status == SKIP] + if failed or skipped or stop.is_set(): + if failed or skipped: + status = BLOCKED if failed else SKIP + detail = f"needs {', '.join(failed or skipped)}" + else: + status, detail = BLOCKED, "not started: an earlier stage failed" + pending.remove(name) + progressed = True + record = Record(name, stage.title, status, detail, 0.0, "") + results[name] = record + say(format_line(record)) + continue + if len(running) >= jobs: + continue # ready, but every job slot is busy; it starts when one frees up + pending.remove(name) + progressed = True + running[pool.submit(execute, stage)] = name + if not running: + break + done, _ = futures.wait(list(running), return_when=futures.FIRST_COMPLETED) + for future in done: + name = running.pop(future) + record = future.result() + results[name] = record + if fail_fast and record.status == FAIL: + stop.set() + return [results[name] for name in names] + + +def format_line(record: Record) -> str: + seconds = f"{record.seconds:6.1f}s" if record.seconds else " " + return f" {record.status.upper():<8}{record.name:<14}{seconds} {record.detail}" + + +def tail(path: Path, count: int) -> List[str]: + try: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return [] + return lines[-count:] + + +def overall(records: Sequence[Record]) -> str: + if any(r.status in (FAIL, BLOCKED) for r in records): + return FAIL + if any(r.status == WARN for r in records): + return WARN + return PASS + + +def save_report(root: Path, run_dir: Path, meta: dict, records: Sequence[Record]) -> Path: + """Write the run's report, copy it to target/ci/latest.json, and keep only the newest KEEP_RUNS runs.""" + report = {"meta": meta, "status": overall(records), "stages": [asdict(r) for r in records]} + text = json.dumps(report, indent=2) + report_path = run_dir / "report.json" + report_path.write_text(text, encoding="utf-8") + latest = root / "target" / "ci" / "latest.json" + latest.parent.mkdir(parents=True, exist_ok=True) + latest.write_text(text, encoding="utf-8") + runs = sorted((d for d in run_dir.parent.iterdir() if d.is_dir()), key=lambda d: d.name) + for old in runs[: max(0, len(runs) - KEEP_RUNS)]: + if old != run_dir: + shutil.rmtree(old, ignore_errors=True) + return report_path + + +def now_iso() -> str: + return dt.datetime.now().astimezone().isoformat(timespec="seconds") diff --git a/ci/install-nightly.ps1 b/ci/install-nightly.ps1 new file mode 100644 index 0000000..bd40def --- /dev/null +++ b/ci/install-nightly.ps1 @@ -0,0 +1,52 @@ +<# +.SYNOPSIS + Registers, or removes, a nightly run of the full local pipeline in Windows Task Scheduler. + +.DESCRIPTION + The task runs `python ci/ci.py run --profile full` in this repository each night. It writes the run's + report to target\ci\latest.json, and the summary can be read with `python ci/ci.py last`. If the + computer was off at the time, the task runs at the next start (StartWhenAvailable). A run that is still + going when the next one is due is not started twice (IgnoreNew). + + Nothing is registered until this script is run. It changes the scheduler of the current user only. + +.PARAMETER At + The daily start time, 24-hour, for example 03:00. + +.PARAMETER Remove + Unregister the task instead of creating it. + +.EXAMPLE + pwsh -File ci\install-nightly.ps1 -At 03:00 + +.EXAMPLE + pwsh -File ci\install-nightly.ps1 -Remove +#> +[CmdletBinding()] +param( + [string]$At = '03:00', + [string]$TaskName = 'Transferd local CI (nightly)', + [switch]$Remove +) + +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot + +if ($Remove) { + Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue + Write-Host "Removed the task '$TaskName' if it existed." + return +} + +$python = (Get-Command python -ErrorAction SilentlyContinue).Source +if (-not $python) { + throw 'python is not on PATH. Install Python 3.11 or newer, then run this again.' +} + +$action = New-ScheduledTaskAction -Execute $python -Argument 'ci\ci.py run --profile full' -WorkingDirectory $root +$trigger = New-ScheduledTaskTrigger -Daily -At $At +$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Hours 4) +Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings ` + -Description 'Nightly full local CI for Transferd. Summary: python ci/ci.py last' -Force | Out-Null +Write-Host "Registered '$TaskName' to run daily at $At in $root." +Write-Host 'Check it with: python ci/ci.py last' diff --git a/ci/tests/test_checks.py b/ci/tests/test_checks.py new file mode 100644 index 0000000..f91e5ff --- /dev/null +++ b/ci/tests/test_checks.py @@ -0,0 +1,218 @@ +"""Tests of the preflight checks, fed with text and fake command results. Two use a real git repository.""" + +from __future__ import annotations + +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from checks import ( # noqa: E402 + eol_findings, + git_bash, + hooks_findings, + is_script, + lockfile_findings, + parse_eol, + secret_findings, + staged_findings, + tool_findings, +) + +# Built from pieces so that this file holds no complete credential header or token. +KEY_HEADER = "-----BEGIN " + "RSA PRIVATE KEY-----" +GITHUB_TOKEN = "ghp_" + "a" * 36 + + +def messages(findings): + return [f.message for f in findings] + + +class EndOfLine(unittest.TestCase): + def test_the_eol_listing_is_parsed_into_index_and_working_tree(self): + out = "i/lf w/lf attr/text eol=lf\tCargo.toml\ni/crlf w/crlf attr/\tscripts/old.sh\n" + self.assertEqual(parse_eol(out), [("Cargo.toml", "lf", "lf"), ("scripts/old.sh", "crlf", "crlf")]) + + def test_committed_crlf_is_an_error_except_for_windows_scripts(self): + entries = [("a.py", "crlf", "lf"), ("b.ps1", "crlf", "crlf"), ("ok.rs", "lf", "lf")] + found = eol_findings(entries) + self.assertEqual(len(found), 1) + self.assertIn("a.py is committed with CRLF", found[0].message) + + def test_a_shell_script_or_hook_with_crlf_on_disk_is_an_error(self): + entries = [("scripts/x.sh", "lf", "crlf"), (".githooks/pre-commit", "lf", "crlf"), ("README.md", "lf", "crlf")] + found = eol_findings(entries) + self.assertEqual(len(found), 2) + self.assertTrue(all("sh cannot run" in f.message for f in found)) + + def test_is_script_covers_shell_files_and_hooks_only(self): + self.assertTrue(is_script("scripts/a.sh")) + self.assertTrue(is_script(".githooks/pre-push")) + self.assertFalse(is_script("crates/a.rs")) + + +class Secrets(unittest.TestCase): + def diff(self, *lines): + return "\n".join(["+++ b/config/settings.txt", "@@ -0,0 +1 @@", *lines]) + "\n" + + def test_a_private_key_header_added_to_a_file_is_an_error(self): + found = secret_findings(self.diff("+" + KEY_HEADER)) + self.assertEqual(len(found), 1) + self.assertIn("private key added to config/settings.txt", found[0].message) + + def test_removed_lines_are_not_scanned(self): + self.assertEqual(secret_findings("+++ b/x.txt\n-" + KEY_HEADER + "\n"), []) + + def test_a_marked_line_is_exempt_as_a_test_fixture(self): + diff = "+++ b/tests/fixture.py\n+" + KEY_HEADER + " # ci:allow-secret\n" + self.assertEqual(secret_findings(diff), []) + + def test_a_github_token_is_an_error(self): + self.assertEqual(len(secret_findings(self.diff("+token = " + GITHUB_TOKEN))), 1) + + def test_an_ordinary_line_is_clean(self): + self.assertEqual(secret_findings(self.diff("+def f(): return 1")), []) + + +class Tools(unittest.TestCase): + ALL = {"cargo", "rustc", "git", "node", "cargo-audit"} + + def which(self, missing=()): + present = self.ALL - set(missing) + return lambda name: f"/usr/bin/{name}" if name in present else None + + def run_tools(self, missing=(), components="clippy-x86_64-pc-windows-msvc\nrustfmt-x86_64-pc-windows-msvc\n", node=22): + return tool_findings( + which=self.which(missing), + components=lambda: components, + node_major=lambda _node: node, + ) + + def test_everything_present_has_no_findings(self): + self.assertEqual(self.run_tools(), []) + + def test_missing_cargo_is_an_error(self): + found = self.run_tools(missing=("cargo",)) + self.assertTrue(any(f.level == "error" and "cargo is not on PATH" in f.message for f in found)) + + def test_missing_clippy_is_an_error_and_missing_rustfmt_is_a_warning(self): + found = self.run_tools(components="rustfmt-x86_64-pc-windows-msvc\n") + self.assertTrue(any(f.level == "error" and "clippy" in f.message for f in found)) + found = self.run_tools(components="clippy-x86_64-pc-windows-msvc\n") + self.assertTrue(any(f.level == "warning" and "rustfmt" in f.message for f in found)) + + def test_an_old_node_and_a_missing_cargo_audit_are_warnings(self): + found = self.run_tools(node=18, missing=("cargo-audit",)) + self.assertTrue(any(f.level == "warning" and "older than 20" in f.message for f in found)) + self.assertTrue(any(f.level == "warning" and "cargo-audit" in f.message for f in found)) + self.assertFalse(any(f.level == "error" for f in found)) + + +class Lockfile(unittest.TestCase): + def fake_run(self, code, stderr=""): + return lambda *a, **k: subprocess.CompletedProcess(args=a, returncode=code, stdout="", stderr=stderr) + + def repo_with_lock(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + (root / "Cargo.lock").write_text("version = 4\n", encoding="utf-8") + return root + + def test_a_lock_that_matches_the_manifests_passes(self): + self.assertEqual(lockfile_findings(self.repo_with_lock(), run=self.fake_run(0)), []) + + def test_a_stale_lock_is_an_error_with_the_reason(self): + found = lockfile_findings(self.repo_with_lock(), run=self.fake_run(101, "error: the lock file needs to be updated")) + self.assertEqual(len(found), 1) + self.assertIn("does not match the manifests", found[0].message) + self.assertIn("needs to be updated", found[0].message) + + def test_a_missing_lock_is_an_error(self): + with tempfile.TemporaryDirectory() as tmp: + found = lockfile_findings(Path(tmp), run=self.fake_run(0)) + self.assertIn("Cargo.lock is missing", found[0].message) + + def test_a_missing_cargo_is_left_to_the_tool_check(self): + def not_found(*a, **k): + raise FileNotFoundError("cargo") + + self.assertEqual(lockfile_findings(self.repo_with_lock(), run=not_found), []) + + +class Hooks(unittest.TestCase): + def test_a_configured_hooks_path_passes(self): + with mock.patch("checks.git", return_value=(0, ".githooks\n")): + self.assertEqual(hooks_findings(Path(".")), []) + + def test_unset_hooks_are_a_warning_with_the_command(self): + with mock.patch("checks.git", return_value=(1, "")): + found = hooks_findings(Path(".")) + self.assertEqual(found[0].level, "warning") + self.assertIn("hooks install", found[0].fix) + + +class GitBash(unittest.TestCase): + def install(self, *, git_under_mingw=True, bash_at_root=True): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + base = Path(tmp.name) / "Git" + git_dir = base / "mingw64" / "bin" if git_under_mingw else base / "cmd" + git_dir.mkdir(parents=True) + (git_dir / "git.exe").write_bytes(b"") + if bash_at_root: + (base / "bin").mkdir() + (base / "bin" / "bash.exe").write_bytes(b"") + return base, str(git_dir / "git.exe") + + def test_the_bash_of_the_git_that_is_found_is_used(self): + base, git_exe = self.install(git_under_mingw=True) + found = git_bash(which=lambda name: git_exe, windows=True) + self.assertEqual(Path(found).resolve(), (base / "bin" / "bash.exe").resolve()) + + def test_without_a_git_there_is_no_bash(self): + self.assertIsNone(git_bash(which=lambda name: None, windows=True)) + + def test_off_windows_bash_comes_from_the_path(self): + self.assertEqual(git_bash(which=lambda name: "/usr/bin/bash", windows=False), "/usr/bin/bash") + + +@unittest.skipUnless(shutil.which("git"), "git is needed for the staged-change checks") +class StagedChanges(unittest.TestCase): + def repo(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + return root + + def test_a_staged_key_and_trailing_whitespace_are_found(self): + root = self.repo() + (root / "keys.txt").write_text(KEY_HEADER + "\n", encoding="utf-8") + (root / "notes.txt").write_text("trailing \n", encoding="utf-8") + subprocess.run(["git", "add", "-A"], cwd=root, check=True) + found = messages(staged_findings(root)) + self.assertTrue(any("private key added to keys.txt" in m for m in found), found) + self.assertTrue(any("staged changes have problems" in m for m in found), found) + + def test_a_large_staged_file_is_an_error(self): + root = self.repo() + (root / "big.bin").write_bytes(b"x" * 2048) + subprocess.run(["git", "add", "-A"], cwd=root, check=True) + found = staged_findings(root, limit=1024) + self.assertTrue(any("big.bin" in m and "staged" in m for m in messages(found))) + + def test_a_clean_stage_has_no_findings(self): + root = self.repo() + (root / "ok.txt").write_text("plain text\n", encoding="utf-8") + subprocess.run(["git", "add", "-A"], cwd=root, check=True) + self.assertEqual(staged_findings(root), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_engine.py b/ci/tests/test_engine.py new file mode 100644 index 0000000..11d2494 --- /dev/null +++ b/ci/tests/test_engine.py @@ -0,0 +1,280 @@ +"""Tests of the engine: order, lanes, keep-going, fail-fast, failures in a stage, processes, and reports.""" + +from __future__ import annotations + +import json +import os +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import engine # noqa: E402 +from engine import ( # noqa: E402 + BLOCKED, + FAIL, + PASS, + SKIP, + WARN, + ConfigError, + Context, + Pipeline, + Result, + Stage, + Step, + overall, + run_steps, + save_report, +) + + +def ok(_ctx): + return Result(PASS, "fine") + + +def bad(_ctx): + return Result(FAIL, "broken") + + +class Workspace: + """A temporary repository root and run folder for one test.""" + + def __enter__(self): + self._dir = tempfile.TemporaryDirectory() + base = Path(self._dir.name) + self.root = base / "repo" + self.root.mkdir() + self.run_dir = base / "runs" / "1" + return Context(self.root, self.run_dir, "test", dict(os.environ)) + + def __exit__(self, *exc): + self._dir.cleanup() + + +def quiet(_line): + pass + + +class PipelineShape(unittest.TestCase): + def test_duplicate_stage_names_are_refused(self): + with self.assertRaisesRegex(ConfigError, "defined twice"): + Pipeline([Stage("a", "", ok), Stage("a", "", ok)]) + + def test_unknown_dependency_is_refused(self): + with self.assertRaisesRegex(ConfigError, "not defined"): + Pipeline([Stage("a", "", ok, needs=("missing",))]) + + def test_a_cycle_is_refused_with_its_path(self): + with self.assertRaisesRegex(ConfigError, "a -> b -> a"): + Pipeline([Stage("a", "", ok, needs=("b",)), Stage("b", "", ok, needs=("a",))]) + + def test_selecting_a_profile_also_selects_what_it_needs(self): + pipeline = Pipeline( + [ + Stage("base", "", ok, profiles=()), + Stage("mid", "", ok, needs=("base",), profiles=()), + Stage("top", "", ok, needs=("mid",), profiles=("p",)), + Stage("other", "", ok, profiles=("p",)), + ] + ) + names = [s.name for s in pipeline.select(profile="p")] + self.assertEqual(names, ["base", "mid", "top", "other"]) + + def test_naming_stages_selects_their_dependencies(self): + pipeline = Pipeline([Stage("base", "", ok), Stage("top", "", ok, needs=("base",)), Stage("x", "", ok)]) + self.assertEqual([s.name for s in pipeline.select(only=["top"])], ["base", "top"]) + + def test_unknown_names_and_empty_profiles_are_refused(self): + pipeline = Pipeline([Stage("a", "", ok, profiles=("p",))]) + with self.assertRaisesRegex(ConfigError, "unknown stage"): + pipeline.select(only=["nope"]) + with self.assertRaisesRegex(ConfigError, "no stage belongs"): + pipeline.select(profile="empty") + + +class PipelineRuns(unittest.TestCase): + def test_a_stage_runs_after_what_it_needs(self): + order = [] + lock = threading.Lock() + + def record(name): + def body(_ctx): + with lock: + order.append(name) + return Result(PASS) + + return body + + pipeline = Pipeline( + [ + Stage("first", "", record("first")), + Stage("second", "", record("second"), needs=("first",)), + Stage("third", "", record("third"), needs=("second",)), + ] + ) + with Workspace() as ctx: + pipeline.run(pipeline.select(profile=None, only=["third"]), ctx, jobs=4, fail_fast=False, emit=quiet) + self.assertEqual(order, ["first", "second", "third"]) + + def test_failure_blocks_dependents_but_independent_stages_still_run(self): + pipeline = Pipeline( + [ + Stage("broken", "", bad), + Stage("after", "", ok, needs=("broken",)), + Stage("unrelated", "", ok), + ] + ) + with Workspace() as ctx: + records = pipeline.run(pipeline.select(only=["after", "unrelated"]), ctx, jobs=1, fail_fast=False, emit=quiet) + status = {r.name: r.status for r in records} + self.assertEqual(status["after"], BLOCKED) + self.assertEqual(status["unrelated"], PASS) + + def test_fail_fast_stops_stages_that_have_not_started(self): + pipeline = Pipeline([Stage("broken", "", bad), Stage("later", "", ok)]) + with Workspace() as ctx: + records = pipeline.run(pipeline.select(only=["broken", "later"]), ctx, jobs=1, fail_fast=True, emit=quiet) + status = {r.name: r.status for r in records} + self.assertEqual(status, {"broken": FAIL, "later": BLOCKED}) + + def test_a_skipped_dependency_skips_its_dependents(self): + pipeline = Pipeline([Stage("absent", "", lambda _c: Result(SKIP, "no tool")), Stage("user", "", ok, needs=("absent",))]) + with Workspace() as ctx: + records = pipeline.run(pipeline.select(only=["user"]), ctx, jobs=2, fail_fast=False, emit=quiet) + self.assertEqual({r.name: r.status for r in records}, {"absent": SKIP, "user": SKIP}) + + def test_an_informational_failure_is_a_warning_and_does_not_fail_the_run(self): + pipeline = Pipeline([Stage("fmt", "", bad, informational=True)]) + with Workspace() as ctx: + records = pipeline.run(pipeline.select(only=["fmt"]), ctx, jobs=1, fail_fast=False, emit=quiet) + self.assertEqual(records[0].status, WARN) + self.assertEqual(overall(records), WARN) + + def test_a_stage_that_raises_fails_alone(self): + def explode(_ctx): + raise RuntimeError("boom") + + pipeline = Pipeline([Stage("explode", "", explode), Stage("fine", "", ok)]) + with Workspace() as ctx: + records = pipeline.run(pipeline.select(only=["explode", "fine"]), ctx, jobs=2, fail_fast=False, emit=quiet) + status = {r.name: r for r in records} + self.assertEqual(status["explode"].status, FAIL) + self.assertIn("boom", status["explode"].detail) + self.assertEqual(status["fine"].status, PASS) + + def test_stages_in_one_lane_never_overlap_and_other_stages_do(self): + active = {"lane": 0, "lane_max": 0, "all": 0, "all_max": 0} + guard = threading.Lock() + + def body(lane): + def run(_ctx): + with guard: + active["all"] += 1 + active["all_max"] = max(active["all_max"], active["all"]) + if lane: + active["lane"] += 1 + active["lane_max"] = max(active["lane_max"], active["lane"]) + time.sleep(0.15) + with guard: + active["all"] -= 1 + if lane: + active["lane"] -= 1 + return Result(PASS) + + return run + + pipeline = Pipeline( + [ + Stage("c1", "", body(True), lane="cargo"), + Stage("c2", "", body(True), lane="cargo"), + Stage("c3", "", body(True), lane="cargo"), + Stage("n1", "", body(False)), + Stage("n2", "", body(False)), + ] + ) + with Workspace() as ctx: + pipeline.run(pipeline.select(only=["c1", "c2", "c3", "n1", "n2"]), ctx, jobs=4, fail_fast=False, emit=quiet) + self.assertEqual(active["lane_max"], 1) + self.assertGreaterEqual(active["all_max"], 2) + + +class Processes(unittest.TestCase): + def test_output_goes_to_the_stage_log(self): + with Workspace() as ctx: + code = ctx.run("probe", Step((sys.executable, "-c", "print('hello from the step')"))) + self.assertEqual(code, 0) + self.assertIn("hello from the step", ctx.logfile("probe").read_text(encoding="utf-8")) + + def test_a_missing_program_is_reported_not_raised(self): + with Workspace() as ctx: + code = ctx.run("probe", Step(("definitely-not-a-real-program-xyz",))) + self.assertEqual(code, engine.NOT_FOUND) + result = run_steps(ctx, "probe", [Step(("definitely-not-a-real-program-xyz",))]) + self.assertEqual(result.status, FAIL) + self.assertIn("not found", result.detail) + + def test_an_exit_code_fails_the_stage_and_names_the_log(self): + with Workspace() as ctx: + result = run_steps(ctx, "probe", [Step((sys.executable, "-c", "import sys; sys.exit(3)"))]) + self.assertEqual(result.status, FAIL) + self.assertIn("exit code 3", result.detail) + self.assertIn("logs/probe.log", result.detail) + + def test_a_step_past_its_timeout_is_stopped(self): + with Workspace() as ctx: + code = ctx.run("probe", Step((sys.executable, "-c", "import time; time.sleep(10)"), timeout=0.5)) + self.assertEqual(code, engine.TIMED_OUT) + + def test_the_steps_of_a_stage_stop_at_the_first_failure(self): + steps = [Step((sys.executable, "-c", "import sys; sys.exit(0)")), + Step((sys.executable, "-c", "import sys; sys.exit(1)")), + Step((sys.executable, "-c", "print('never reached')"))] + with Workspace() as ctx: + run_steps(ctx, "probe", steps) + self.assertNotIn("never reached", ctx.logfile("probe").read_text(encoding="utf-8")) + + +class Reports(unittest.TestCase): + def test_overall_status_is_fail_if_anything_failed_or_was_blocked(self): + def rec(status): + return engine.Record("s", "", status, "", 0.0, "") + + self.assertEqual(overall([rec(PASS), rec(BLOCKED)]), FAIL) + self.assertEqual(overall([rec(PASS), rec(WARN)]), WARN) + self.assertEqual(overall([rec(PASS), rec(SKIP)]), PASS) + + def test_a_report_is_written_and_copied_to_latest(self): + with Workspace() as ctx: + record = engine.Record("s", "t", PASS, "ok", 1.5, "logs/s.log") + path = save_report(ctx.root, ctx.run_dir, {"run_id": "1"}, [record]) + data = json.loads(path.read_text(encoding="utf-8")) + self.assertEqual(data["status"], PASS) + self.assertEqual(data["stages"][0]["name"], "s") + latest = json.loads((ctx.root / "target" / "ci" / "latest.json").read_text(encoding="utf-8")) + self.assertEqual(latest["meta"]["run_id"], "1") + + def test_old_runs_are_pruned_and_the_newest_is_kept(self): + original = engine.KEEP_RUNS + engine.KEEP_RUNS = 3 + try: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + runs = root / "target" / "ci" / "runs" + for index in range(5): + (runs / f"2026010{index}-000000-abc").mkdir(parents=True) + newest = runs / "20260109-000000-abc" + newest.mkdir(parents=True) + save_report(root, newest, {}, []) + remaining = sorted(d.name for d in runs.iterdir()) + self.assertEqual(len(remaining), 3) + self.assertIn(newest.name, remaining) + finally: + engine.KEEP_RUNS = original + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_pipeline.py b/ci/tests/test_pipeline.py new file mode 100644 index 0000000..db546a3 --- /dev/null +++ b/ci/tests/test_pipeline.py @@ -0,0 +1,163 @@ +"""Tests of the stage definitions, the profiles, the git hooks, the run lock, and the finding summaries. + +The parity tests keep the local stages in step with .github/workflows/core-ci.yml: when a command changes +there, these tests fail until the local stage is changed too. +""" + +from __future__ import annotations + +import os +import sys +import tempfile +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import ci as pipeline_cli # noqa: E402 +from ci import CI_RUSTFLAGS, PROFILES, RunLock, build_stages, fingerprint, findings_result # noqa: E402 +from checks import Finding # noqa: E402 +from engine import FAIL, PASS, WARN, Context, Pipeline # noqa: E402 + +ROOT = pipeline_cli.ROOT + + +def names(profile): + return {stage.name for stage in Pipeline(build_stages()).select(profile=profile)} + + +class Stages(unittest.TestCase): + def test_the_stage_definitions_form_a_valid_pipeline(self): + Pipeline(build_stages()) # raises on duplicates, unknown dependencies or cycles + + def test_every_profile_selects_something(self): + for profile in PROFILES: + self.assertTrue(names(profile), profile) + + def test_precommit_runs_only_the_fast_checks(self): + self.assertEqual(names("precommit"), {"preflight", "selftest"}) + + def test_prepush_runs_the_workflow_checks_for_rust_and_python_without_the_slow_ones(self): + selected = names("prepush") + self.assertTrue({"preflight", "fmt", "clippy", "test", "interop-bins", "python", "selftest"} <= selected) + self.assertFalse({"gui", "typescript", "relay-build", "audit", "fuzz"} & selected) + + def test_full_covers_the_workflow_the_app_and_the_audit(self): + selected = names("full") + required = {"preflight", "fmt", "clippy", "test", "interop-bins", "relay-build", "python", "typescript", + "gui", "audit", "core-sync", "selftest"} + self.assertTrue(required <= selected, required - selected) + self.assertNotIn("fuzz", selected) + + def test_nightly_adds_the_fuzz_smoke_to_full(self): + self.assertTrue(names("full") < names("nightly")) + self.assertIn("fuzz", names("nightly")) + + def test_the_cargo_stages_share_one_lane(self): + lanes = {stage.name: stage.lane for stage in build_stages()} + for name in ("fmt", "clippy", "test", "interop-bins", "relay-build", "fuzz"): + self.assertEqual(lanes[name], "cargo", name) + self.assertEqual(lanes["python"], "") + + def test_the_rust_stages_deny_warnings_as_the_workflow_does(self): + self.assertEqual(CI_RUSTFLAGS, (("RUSTFLAGS", "-D warnings"),)) + + def test_fmt_only_warns_unless_strict(self): + fmt = next(s for s in build_stages() if s.name == "fmt") + strict = next(s for s in build_stages(strict_fmt=True) if s.name == "fmt") + self.assertTrue(fmt.informational) + self.assertFalse(strict.informational) + + +class WorkflowParity(unittest.TestCase): + """The local clippy and test commands are the ones the GitHub workflow runs.""" + + def setUp(self): + self.workflow = (ROOT / ".github" / "workflows" / "core-ci.yml").read_text(encoding="utf-8") + + def test_clippy_is_the_same_command(self): + self.assertIn("cargo clippy --workspace --all-features -- -D warnings", self.workflow) + + def test_tests_are_the_same_command(self): + self.assertIn("cargo test --workspace --all-features", self.workflow) + + def test_the_relay_build_is_the_same_command(self): + self.assertIn("cargo build --release -p relayd -p transferd-relay -p transferd-cat", self.workflow) + + def test_the_interop_binaries_are_built_as_the_workflow_builds_them(self): + self.assertIn("cargo build -p transferd-overlay --example interop_peer", self.workflow) + self.assertIn("cargo build -p relayd --bin relayd", self.workflow) + + +class Hooks(unittest.TestCase): + def read(self, name): + return (ROOT / ".githooks" / name).read_bytes().decode("utf-8") + + def test_pre_commit_runs_the_precommit_profile(self): + self.assertIn("ci/ci.py run --profile precommit", self.read("pre-commit")) + + def test_pre_push_runs_the_prepush_profile(self): + self.assertIn("ci/ci.py run --profile prepush", self.read("pre-push")) + + def test_hooks_use_lf_line_endings_so_sh_can_run_them(self): + for name in ("pre-commit", "pre-push"): + self.assertNotIn("\r", self.read(name), name) + + +class Findings(unittest.TestCase): + def context(self, tmp): + return Context(Path(tmp), Path(tmp) / "run", "test", dict(os.environ)) + + def test_errors_fail_the_stage_and_point_at_its_log(self): + with tempfile.TemporaryDirectory() as tmp: + ctx = self.context(tmp) + result = findings_result(ctx, "preflight", [Finding("error", "x is bad", "fix it")]) + self.assertEqual(result.status, FAIL) + self.assertIn("logs/preflight.log", result.detail) + self.assertIn("fix: fix it", ctx.logfile("preflight").read_text(encoding="utf-8")) + + def test_warnings_pass_with_a_warning(self): + with tempfile.TemporaryDirectory() as tmp: + result = findings_result(self.context(tmp), "preflight", [Finding("warning", "soft")]) + self.assertEqual(result.status, WARN) + + def test_no_findings_pass(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(findings_result(self.context(tmp), "preflight", []).status, PASS) + + +class Locking(unittest.TestCase): + def test_a_second_run_is_refused_while_the_first_holds_the_lock(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "run.lock" + with RunLock(path): + with self.assertRaisesRegex(RuntimeError, "another run is in progress"): + with RunLock(path): + pass + self.assertFalse(path.exists()) + + def test_a_stale_lock_is_taken_over(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "run.lock" + path.write_text("1 old\n", encoding="utf-8") + old = time.time() - 7 * 3600 + os.utime(path, (old, old)) + with RunLock(path): + self.assertTrue(path.exists()) + + +class Fingerprints(unittest.TestCase): + def test_a_fingerprint_changes_when_the_file_changes(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "lock.json" + path.write_text("one", encoding="utf-8") + first = fingerprint(path, "3.11") + self.assertEqual(first, fingerprint(path, "3.11")) + path.write_text("two", encoding="utf-8") + self.assertNotEqual(first, fingerprint(path, "3.11")) + self.assertNotEqual(first, fingerprint(path, "3.12")) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/transferd-overlay/src/dns.rs b/crates/transferd-overlay/src/dns.rs index 75a35d7..a99810e 100644 --- a/crates/transferd-overlay/src/dns.rs +++ b/crates/transferd-overlay/src/dns.rs @@ -36,7 +36,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::tcp::OwnedWriteHalf; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::sync::oneshot; -use tokio::task::JoinHandle; +use tokio::task::{JoinHandle, JoinSet}; use crate::error::{OverlayError, Result}; use crate::node::OverlayNode; @@ -147,6 +147,9 @@ pub struct MeshDns { listen: SocketAddr, failed: Mutex, tasks: Mutex>>, + /// One task per UDP query in flight. Each holds a clone of the listening socket until it has + /// answered, so the address is free only once these have ended too. + queries: Arc>>, } impl Drop for MeshDns { @@ -154,6 +157,7 @@ impl Drop for MeshDns { for task in self.tasks.lock().drain(..) { task.abort(); } + self.queries.lock().abort_all(); } } @@ -189,8 +193,10 @@ impl MeshDns { listen, failed: Mutex::new(0), tasks: Mutex::new(Vec::new()), + queries: Arc::new(Mutex::new(JoinSet::new())), }); let udp = Arc::new(udp); + let queries = dns.queries.clone(); let weak = Arc::downgrade(&dns); let serve_udp = tokio::spawn(async move { let mut buf = vec![0u8; MAX_MESSAGE]; @@ -201,7 +207,10 @@ impl MeshDns { let Some(dns) = weak.upgrade() else { break }; let query = buf[..n].to_vec(); let socket = udp.clone(); - tokio::spawn(async move { + let mut in_flight = queries.lock(); + // Reap the queries that have answered, so finished tasks do not pile up. + while in_flight.try_join_next().is_some() {} + in_flight.spawn(async move { if let Some(answer) = dns.answer(&query).await { let _ = socket.send_to(&fit_for_udp(&query, answer), from).await; } @@ -236,6 +245,23 @@ impl MeshDns { self.listen } + /// Stop answering, and wait until every task holding a listening socket has ended, so the + /// address is free again when this returns. Dropping only aborts the tasks, and an abort + /// takes effect later, so a bind right after a drop can still find the port taken. + pub async fn shutdown(&self) { + let listeners: Vec> = self.tasks.lock().drain(..).collect(); + for task in &listeners { + task.abort(); + } + for task in listeners { + let _ = task.await; + } + // The listeners have ended, so no new query can start. Now the ones still in flight. + let mut queries = std::mem::take(&mut *self.queries.lock()); + queries.abort_all(); + while queries.join_next().await.is_some() {} + } + /// Everything `overlay.dns_status` reports. pub fn status(&self) -> Value { let now = Instant::now(); diff --git a/crates/transferd-overlay/src/node.rs b/crates/transferd-overlay/src/node.rs index b61bf48..f6a39e9 100644 --- a/crates/transferd-overlay/src/node.rs +++ b/crates/transferd-overlay/src/node.rs @@ -1766,9 +1766,12 @@ impl OverlayNode { &self, config: Option, ) -> Result { - // Stop the old one first: the new one usually wants the same port. + // Stop the old one first, and wait for it to let go of the port: the new one usually + // wants the same port. let old = self.inner.mesh_dns.lock().take(); - drop(old); + if let Some(old) = old { + old.shutdown().await; + } let Some(config) = config else { *self.inner.mesh_dns_config.lock() = None; self.emit(OverlayEvent::new("dns.off", self.node_id(), "")); diff --git a/crates/transferd-overlay/src/proxy.rs b/crates/transferd-overlay/src/proxy.rs index cdf1e7e..e75be20 100644 --- a/crates/transferd-overlay/src/proxy.rs +++ b/crates/transferd-overlay/src/proxy.rs @@ -218,6 +218,9 @@ async fn open(node: &OverlayNode, host: &str) -> Result { /// close would tell the application that a stream cut short was complete. pub async fn splice(client: TcpStream, local: SocketAddr) { let Ok(server) = TcpStream::connect(local).await else { + // The overlay side is gone before the stream starts. That is a failure on that side, so reset the client + // rather than close it cleanly. + reset(client); return; }; let (client_read, mut client_write) = tokio::io::split(client); @@ -314,6 +317,29 @@ mod tests { assert!(outcome.is_err(), "a reset, not the end of the stream: {outcome:?}"); } + /// The overlay side refuses before the stream starts: the application's socket is reset, not closed. + #[tokio::test] + async fn a_refused_overlay_side_resets_the_client() { + let front = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let front_addr = front.local_addr().expect("address"); + let gone = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let gone_addr = gone.local_addr().expect("address"); + drop(gone); + let client = + tokio::spawn(async move { TcpStream::connect(front_addr).await.expect("connect") }); + let (accepted, _) = front.accept().await.expect("accept"); + let mut app = client.await.expect("join"); + splice(accepted, gone_addr).await; + let mut buf = [0u8; 16]; + let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), app.read(&mut buf)) + .await + .expect("the reset arrives"); + assert!( + outcome.is_err(), + "a reset, not the end of the stream: {outcome:?}" + ); + } + #[test] fn an_overlay_host_splits_into_a_service_and_a_node() { assert_eq!( diff --git a/docs/LOCAL_CI.md b/docs/LOCAL_CI.md new file mode 100644 index 0000000..cdeca8d --- /dev/null +++ b/docs/LOCAL_CI.md @@ -0,0 +1,140 @@ +# Local CI + +The local pipeline runs on the computer you work on the checks that `.github/workflows/core-ci.yml` runs, plus +the desktop app's tests, the preflight checks, and the pipeline's own tests. GitHub stays the record: the workflow runs +on the project's self-hosted Linux and Windows runners. The local pipeline is the fast loop, and it runs the same commands the +workflow runs. + +It is a single script, `ci/ci.py`, with the Python standard library only (Python 3.11 or newer). Nothing is +installed for it except the per-stage environments it makes under `target/ci`. + +## Quick start + +```bash +python ci/ci.py check # preflight checks only +python ci/ci.py check --staged # preflight, plus what is staged for the next commit +python ci/ci.py run --profile prepush +python ci/ci.py # the full profile +python ci/ci.py run --only clippy,test # named stages, with the stages they need +python ci/ci.py last # summary of the last run +python ci/ci.py list # stages, profiles and dependencies +``` + +## Profiles + +| Profile | When | Runs | +|------------|-----------------------|----------------------------------------------------------------------------------------------| +| `precommit`| each commit (hook) | preflight, the pipeline's own tests. A few seconds. | +| `prepush` | each push (hook) | preflight, fmt, clippy, tests, interop binaries, Python tests, the pipeline's own tests. | +| `full` | by hand, nightly | everything in `prepush`, plus relay release build, TypeScript, the desktop app, cargo audit, core-sync. | +| `nightly` | by hand, nightly | `full`, plus the fuzz smoke test (needs the nightly toolchain and `cargo-fuzz`). | + +## Stages + +| Stage | Lane | Needs | What it does | +|--------------|-------|-------------------|-----------------------------------------------------------------------------------| +| preflight | | | Tools, `Cargo.lock` against the manifests, line endings, hooks; staged changes with `--staged`. | +| fmt | cargo | preflight | `cargo fmt --check`. Informational, as in CI, until the sweep lands; `--strict-fmt` fails on it. | +| clippy | cargo | preflight | `cargo clippy --workspace --all-features -- -D warnings`. | +| test | cargo | clippy | `cargo test --workspace --all-features`. | +| interop-bins | cargo | test | Builds `interop_peer` and `relayd`, which the interop tests need. | +| relay-build | cargo | test | `cargo build --release` for the relay binaries. | +| python | | interop-bins | `python/tests` in its own venv under `target/ci`, with interop. | +| typescript | | interop-bins | `npm ci` (only when the lockfile changes), then `npm test`, with interop. | +| gui | | interop-bins | The desktop app's tests and pyflakes, in `gui/.venv`. | +| audit | | preflight | `cargo audit` with the repo's `.cargo/audit.toml`. | +| core-sync | | preflight | `scripts/sync-core.sh --check` against the TransferDaemon checkout beside this one. | +| selftest | | | The pipeline's own unit tests in `ci/tests`. | +| fuzz | cargo | test | `cargo +nightly fuzz run fuzz_relay_protocol`, 120 seconds. | + +Stages in the same **lane** never run together. Every stage that uses cargo is in the `cargo` lane, because cargo +serializes on the target directory anyway; running them one at a time avoids the wait. The other stages overlap with +them, so the Python, TypeScript, GUI and audit stages run while cargo is still working. + +A stage that is **skipped** says why: a missing tool, or a missing checkout. A stage whose needed stage **failed** is +**blocked**. A stage that **warns** does not fail the run. + +## Preflight + +These run first, and they fail the run when they find a problem: + +- `git`, `cargo`, `rustc` are on PATH; Python is 3.11 or newer; the `clippy` component is installed. +- `Cargo.lock` matches the manifests (`cargo metadata --locked`). +- No file is committed with CRLF line endings (except `.ps1` and `.bat`), and no shell script or hook has CRLF on disk. +- With `--staged` (the commit hook): no whitespace errors or conflict markers, no private keys or known token formats + added (`ci:allow-secret` on a line exempts a test fixture), and no staged file larger than 5 MB. + +These warn: Node.js missing or older than 20, `cargo-audit` missing, `rustfmt` missing, git hooks not installed. + +## Git hooks + +```bash +python ci/ci.py hooks install # sets core.hooksPath to .githooks in this repository +python ci/ci.py hooks status +python ci/ci.py hooks uninstall +``` + +`pre-commit` runs the `precommit` profile and `pre-push` runs `prepush`. Either one can be skipped once with +`git commit --no-verify` or `git push --no-verify`. The hooks use the first of `python3`, `python` or `py -3` that is +Python 3.11 or newer. + +## Nightly automation + +`ci/install-nightly.ps1` registers a daily Windows scheduled task for the `full` profile. It is not registered +until you run it: + +```powershell +pwsh -File ci\install-nightly.ps1 -At 03:00 +pwsh -File ci\install-nightly.ps1 -Remove +``` + +## Reports and logs + +Everything a run writes is under `target\ci`, which git ignores with `target/`: + +- `runs//report.json`: the profile, commit, branch, dirty flag, timings and each stage's status and detail. +- `runs//logs/.log`: the full output of each stage, with every command it ran. +- `latest.json`: a copy of the newest report. `python ci/ci.py last` prints it. +- `run.lock`: held while a run is going. A second run refuses to start while it is there; a lock older than six hours + is taken over. Delete the file if no run is going. +- `venv-python/`: the Python environment for the Python stage. It is reinstalled only when `python/pyproject.toml` or + the Python version changes; the stamp is in `.ci-stamp`. + +The newest 20 runs are kept. + +## Design notes + +- **One cargo lane.** Stages that use cargo run one at a time, in declaration order, and everything else runs beside + them. `--jobs` caps how many stages run at once (default 4). +- **The workflow's flags.** The Rust stages set `RUSTFLAGS=-D warnings`, as the workflow does. The first build after + switching to this pipeline therefore recompiles the workspace, and a plain `cargo build` without the flag rebuilds + it again. This is deliberate: it keeps the local result the same as CI's. +- **Stamped installs.** The Python venv and the TypeScript `node_modules` are reinstalled only when their inputs change. +- **Dependencies on selection.** `--only` runs the named stages and everything they need. +- **Crash isolation.** A stage that raises fails alone, and the rest of the run goes on. A step that hangs is stopped at + its timeout. +- **Fail fast, or keep going.** The default keeps going: independent stages still run after a failure. `--fail-fast` + stops starting new stages after the first failure. + +## What it does not cover + +- **No macOS in CI.** The workflow builds the relay on Linux and Windows, and runs the fuzz target on Linux. It does + not build for macOS: there is no macOS runner yet. The local pipeline runs on this computer only. Linux-only code (the `cfg(target_os = "linux")` eventfd path in `ring-channel`) + is compiled only on Linux, so a local Windows run does not compile it. The workflow does. +- **The fuzz smoke test** runs only when the nightly toolchain and `cargo-fuzz` are installed; otherwise it is skipped + with the reason. +- **The desktop app on a display.** Its tests run offscreen, as `gui/README.md` describes. +- **The older runners.** `scripts/test-core.ps1` and `scripts/test-core.sh` are the earlier sequential runners. They + stay as they are; this pipeline does their job with preflight, parallel stages, hooks and reports. + +## Changing the pipeline + +Stages are defined in `build_stages()` in `ci/ci.py`; the engine is `ci/engine.py`; the checks are `ci/checks.py`. +After a change, run the pipeline's own tests: + +```bash +python ci/ci.py run --only selftest +``` + +`ci/tests/test_pipeline.py` also checks that the local clippy, test and relay-build commands still match the workflow. +If the workflow's commands change, those tests fail until the local stages change with them.