Browse Source

deployment service midi bridge

Johan Le Baut 2 weeks ago
parent
commit
c69a3dfbde

+ 10 - 2
README.md

@@ -153,7 +153,15 @@ Run the bridge in the foreground for manual use:
 python3 scripts/midi_action_bridge.py
 ```
 
-The bridge connects to mod-host over loopback and issues only `patch_set` for the configured NAM processor. It does not alter PipeWire links or start automatically; a dedicated user service and target verification are future work. The current mod-host startup model remains the declared `Crunch_TB`; Crystal Clean is the runtime fallback for a selected model whose file is absent.
+The bridge connects to mod-host over loopback and issues only `patch_set` for the configured NAM processor. It does not alter PipeWire links. To install and enable its user service explicitly:
+
+```sh
+./scripts/deploy.sh install midi-bridge
+systemctl --user status rigforge-midi-bridge.service
+journalctl --user -u rigforge-midi-bridge.service -f
+```
+
+The service retries MIDI-port discovery if the UMC is not yet available and restarts after an unexpected process failure. It is deliberately excluded from `install all`; it does not install or start mod-host. Model selection requires the mod-host guitar chain to be running. The user systemd manager must be active for the service to run; unattended boot startup without a login also requires user lingering. Remove it with `./scripts/deploy.sh uninstall midi-bridge`, or restart it after local configuration changes with `./scripts/deploy.sh reload midi-bridge`. The current mod-host startup model remains the declared `Crunch_TB`; Crystal Clean is the runtime fallback for a selected model whose file is absent.
 
 ### Rigforge graph reconciliation
 
@@ -207,7 +215,7 @@ The remaining target checks are:
 2. Later, test inputs 2 and 4 with sources when available; they are included in the mixer but not verified with instruments.
 3. Measure sustained stability and headroom at 48 kHz / 128 frames with all active sources; the current `ERR = 0` observation was brief.
 4. Re-test mod-host startup after installing the new port-readiness guard, then verify reboot with lingering enabled, startup resource limits, and recovery when an LV2 plugin fails to load.
-5. The owner has manually verified FCB notes 6–9 switching the guitar NAM models through the bridge, with near-instant reported transitions. Still verify the supplied FCB1010 bindings with the eventual SooperLooper build, OSC port readiness, and the effect and persistence of `discrete_prefader 0` separately. Automatic bridge startup and USB reconnect recovery also remain unverified.
+5. The owner has manually verified FCB notes 6–9 switching the guitar NAM models through the bridge, with near-instant reported transitions. The `midi-bridge` user service is now installable locally; still install and verify unattended startup and UMC unplug/replug recovery on the target. Also verify the supplied FCB1010 bindings with the eventual SooperLooper build, OSC port readiness, and the effect and persistence of `discrete_prefader 0` separately.
 
 Do not treat planned packages, commands, ports, or service settings as target-validated until these checks have been performed.
 

+ 6 - 0
config/desired-state.yaml

@@ -79,6 +79,12 @@ deployment:
     user_timer: rigforge-pipewire-reconcile.timer
     python_path: /usr/bin/python3
     interval_seconds: 15
+  midi_bridge:
+    bridge_script: scripts/midi_action_bridge.py
+    service_source: config/systemd/user/rigforge-midi-bridge.service.in
+    service_destination: .config/systemd/user/rigforge-midi-bridge.service
+    user_service: rigforge-midi-bridge.service
+    python_path: /usr/bin/python3
   pipewire:
     fragment_source: config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
     fragment_destination: .config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf

+ 13 - 0
config/systemd/user/rigforge-midi-bridge.service.in

@@ -0,0 +1,13 @@
+[Unit]
+Description=Rigforge MIDI action bridge
+After=rigforge-mod-host.service
+
+[Service]
+Type=simple
+ExecStart=@PYTHON@ -u @BRIDGE_SCRIPT@ --state @DESIRED_STATE@ --repo-root @REPOSITORY_ROOT@
+Restart=on-failure
+RestartSec=2
+TimeoutStopSec=10
+
+[Install]
+WantedBy=default.target

+ 219 - 2
scripts/deploy.py

@@ -38,12 +38,17 @@ def load_deployment():
     namlv2 = deployment.get("namlv2")
     pipewire = deployment.get("pipewire")
     reconcile = deployment.get("reconcile")
+    midi_bridge = deployment.get("midi_bridge")
     if (
         not isinstance(namlv2, dict)
         or not isinstance(pipewire, dict)
         or not isinstance(reconcile, dict)
+        or not isinstance(midi_bridge, dict)
     ):
-        raise ValueError("deployment.namlv2, deployment.pipewire, and deployment.reconcile must be mappings")
+        raise ValueError(
+            "deployment.namlv2, deployment.pipewire, deployment.reconcile, "
+            "and deployment.midi_bridge must be mappings"
+        )
     for component, archive_format in PLUGIN_ARCHIVES.items():
         plugin = deployment.get(component)
         if not isinstance(plugin, dict):
@@ -879,6 +884,36 @@ def render_reconcile_units(config):
     }
 
 
+def render_midi_bridge_service(config):
+    repository_root = ROOT.resolve()
+    state_file = repository_root / "config" / "desired-state.yaml"
+    bridge_script = repository_root / config["bridge_script"]
+    service_template = repository_root / config["service_source"]
+    for description, path in (
+        ("MIDI action bridge script", bridge_script),
+        ("MIDI bridge service template", service_template),
+    ):
+        if not path.is_file():
+            raise RuntimeError(f"{description} is missing: {path}")
+
+    replacements = {
+        "@PYTHON@": systemd_quote(config["python_path"]),
+        "@BRIDGE_SCRIPT@": systemd_quote(bridge_script),
+        "@DESIRED_STATE@": systemd_quote(state_file),
+        "@REPOSITORY_ROOT@": systemd_quote(repository_root),
+    }
+    content = service_template.read_text(encoding="utf-8")
+    for placeholder, replacement in replacements.items():
+        content = content.replace(placeholder, replacement)
+    if re.search(r"@[A-Z_]+@", content):
+        raise RuntimeError("unexpanded placeholder remains in MIDI bridge service template")
+    return {
+        "name": config["user_service"],
+        "destination": Path.home() / config["service_destination"],
+        "content": content.encode("utf-8"),
+    }
+
+
 def atomic_install_bytes(content, destination):
     destination.parent.mkdir(parents=True, exist_ok=True)
     fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
@@ -892,6 +927,178 @@ def atomic_install_bytes(content, destination):
             os.unlink(temporary_name)
 
 
+def deploy_midi_bridge(action, config, registry):
+    unit = render_midi_bridge_service(config)
+    destination = unit["destination"]
+    service_name = unit["name"]
+    validate_user_destination(destination)
+    if destination.exists() and not destination.is_file():
+        raise RuntimeError(f"MIDI bridge service destination has the wrong type: {destination}")
+    managed = registry.get("midi_bridge")
+
+    if action == "reload":
+        if managed is None:
+            raise RuntimeError("MIDI bridge is not managed; install midi-bridge before reloading it")
+        if managed.get("pending_uninstall"):
+            raise RuntimeError("MIDI bridge uninstall is incomplete; retry uninstall midi-bridge first")
+        if not destination.is_file():
+            raise RuntimeError(f"managed MIDI bridge service file is missing: {destination}")
+        if file_sha256(destination) != managed.get("installed_sha256"):
+            raise RuntimeError(f"managed MIDI bridge service file changed locally: {destination}")
+        run(["systemctl", "--user", "restart", service_name])
+        run(["systemctl", "--user", "is-active", "--quiet", service_name])
+        print("Rigforge MIDI bridge user service restarted.")
+        return
+
+    if action == "uninstall":
+        if managed is None:
+            print("No managed MIDI bridge service to uninstall.")
+            return
+        backup_path = validate_backup_path(managed.get("backup"), destination)
+        backup_digest = managed.get("backup_sha256")
+        if backup_path is not None and backup_path.exists():
+            if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
+                raise RuntimeError(f"recorded MIDI bridge service backup changed locally: {backup_path}")
+        elif backup_path is not None and not managed.get("pending_uninstall"):
+            raise RuntimeError(f"recorded MIDI bridge service backup is missing: {backup_path}")
+        if (backup_path is None) != (backup_digest is None):
+            raise RuntimeError("invalid MIDI bridge service backup record")
+
+        current_digest = file_sha256(destination)
+        recoverable_digests = {managed.get("installed_sha256"), backup_digest, None}
+        if managed.get("pending_uninstall"):
+            if current_digest not in recoverable_digests:
+                raise RuntimeError(f"unexpected file blocks MIDI bridge uninstall: {destination}")
+        elif current_digest != managed.get("installed_sha256"):
+            raise RuntimeError(
+                f"managed MIDI bridge service file changed locally; refusing removal: {destination}"
+            )
+        if (
+            backup_path is not None
+            and not backup_path.exists()
+            and current_digest == managed.get("installed_sha256")
+        ):
+            raise RuntimeError(
+                f"recorded MIDI bridge service backup is missing; refusing removal: {backup_path}"
+            )
+
+        managed["pending_uninstall"] = True
+        registry["midi_bridge"] = managed
+        write_registry(registry)
+        run(["systemctl", "--user", "disable", "--now", service_name])
+        if backup_path is not None and current_digest == backup_digest:
+            if backup_path.exists():
+                backup_path.unlink()
+        else:
+            if current_digest == managed.get("installed_sha256"):
+                destination.unlink()
+            elif current_digest is not None:
+                raise RuntimeError(f"unexpected file blocks MIDI bridge uninstall: {destination}")
+            if backup_path is not None:
+                if backup_path.exists():
+                    os.replace(backup_path, destination)
+                elif file_sha256(destination) != backup_digest:
+                    raise RuntimeError(f"recorded MIDI bridge service backup is missing: {backup_path}")
+        run(["systemctl", "--user", "daemon-reload"])
+        registry.pop("midi_bridge")
+        write_registry(registry)
+        print("Rigforge MIDI bridge user service removed; prior unit restored if present.")
+        return
+
+    content = unit["content"]
+    installed_digest = hashlib.sha256(content).hexdigest()
+    if managed is not None and managed.get("pending_uninstall"):
+        raise RuntimeError("MIDI bridge uninstall is incomplete; retry uninstall midi-bridge first")
+    if managed is None:
+        if user_unit_is_active(service_name) or user_unit_is_enabled(service_name):
+            raise RuntimeError(
+                f"an unmanaged {service_name} is already active or enabled; "
+                "inspect it before installing Rigforge's unit"
+            )
+        backup_path = (
+            destination.with_name(destination.name + ".rigforge-backup")
+            if destination.is_file()
+            else None
+        )
+        if backup_path is not None and (backup_path.exists() or backup_path.is_symlink()):
+            raise RuntimeError(f"backup path already exists: {backup_path}")
+        backup = str(backup_path) if destination.is_file() else None
+        backup_digest = file_sha256(destination)
+        previous_digest = None
+        pending_install = True
+    else:
+        if managed.get("destination") != str(destination):
+            raise RuntimeError("recorded MIDI bridge service path changed")
+        backup_path = validate_backup_path(managed.get("backup"), destination)
+        backup = str(backup_path) if backup_path is not None else None
+        backup_digest = managed.get("backup_sha256")
+        if (backup_path is None) != (backup_digest is None):
+            raise RuntimeError("invalid MIDI bridge service backup record")
+        if backup_path is not None and backup_path.exists():
+            if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
+                raise RuntimeError(f"recorded MIDI bridge service backup changed locally: {backup_path}")
+        elif backup_path is not None and not managed.get("pending_install"):
+            raise RuntimeError(f"recorded MIDI bridge service backup is missing: {backup_path}")
+        previous_digest = (
+            managed.get("previous_installed_sha256")
+            if managed.get("pending_install")
+            else managed.get("installed_sha256")
+        )
+        current_digest = file_sha256(destination)
+        if managed.get("pending_install"):
+            if current_digest not in {previous_digest, backup_digest, None}:
+                raise RuntimeError(f"MIDI bridge service changed locally during interrupted install: {destination}")
+        elif current_digest != previous_digest:
+            raise RuntimeError(f"managed MIDI bridge service file changed locally: {destination}")
+        pending_install = current_digest != installed_digest
+
+    unit_changed = file_sha256(destination) != installed_digest
+    restart_required = managed is None or unit_changed or bool(
+        managed and managed.get("pending_activation")
+    )
+    managed = managed or {}
+    managed.update({
+        "destination": str(destination),
+        "installed_sha256": installed_digest,
+        "previous_installed_sha256": previous_digest,
+        "backup": backup,
+        "backup_sha256": backup_digest,
+        "pending_install": pending_install,
+        "pending_activation": True,
+    })
+    registry["midi_bridge"] = managed
+    write_registry(registry)
+
+    if backup_path is not None:
+        if backup_path.exists():
+            if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
+                raise RuntimeError(f"recorded MIDI bridge service backup changed locally: {backup_path}")
+        elif file_sha256(destination) == backup_digest:
+            shutil.copy2(destination, backup_path)
+        else:
+            raise RuntimeError(f"recorded MIDI bridge service backup is missing: {backup_path}")
+    if unit_changed:
+        atomic_install_bytes(content, destination)
+
+    managed.pop("previous_installed_sha256", None)
+    managed.pop("pending_install", None)
+    registry["midi_bridge"] = managed
+    write_registry(registry)
+    run(["systemctl", "--user", "daemon-reload"])
+    run(["systemctl", "--user", "enable", service_name])
+    run([
+        "systemctl",
+        "--user",
+        "restart" if restart_required else "start",
+        service_name,
+    ])
+    run(["systemctl", "--user", "is-active", "--quiet", service_name])
+    managed.pop("pending_activation", None)
+    registry["midi_bridge"] = managed
+    write_registry(registry)
+    print(f"Installed and activated Rigforge MIDI bridge user service at {destination}.")
+
+
 def file_sha256(path):
     return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
 
@@ -1372,7 +1579,15 @@ def main(argv=None):
     parser.add_argument("action", choices=("install", "uninstall", "reload"))
     parser.add_argument(
         "target",
-        choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire", "mod-host", "reconcile"),
+        choices=(
+            "namlv2",
+            "lsp",
+            "dragonfly-reverb",
+            "pipewire",
+            "mod-host",
+            "reconcile",
+            "midi-bridge",
+        ),
     )
     args = parser.parse_args(argv)
     try:
@@ -1390,6 +1605,8 @@ def main(argv=None):
             deploy_mod_host(args.action, deployment["mod_host"], registry)
         elif args.target == "reconcile":
             deploy_reconcile(args.action, deployment["reconcile"], registry)
+        elif args.target == "midi-bridge":
+            deploy_midi_bridge(args.action, deployment["midi_bridge"], registry)
         else:
             component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
             deploy_lv2_archives(args.action, component, deployment[component], registry)

+ 2 - 2
scripts/deploy.sh

@@ -2,7 +2,7 @@
 set -u
 
 usage() {
-    printf 'Usage: %s install|uninstall|reload all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile\n' "$0" >&2
+    printf 'Usage: %s install|uninstall|reload all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile|midi-bridge\n' "$0" >&2
     exit 2
 }
 
@@ -15,7 +15,7 @@ case "$action" in
 esac
 case "$target" in
     all) targets=(pipewire namlv2 lsp dragonfly-reverb) ;;
-    namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile) targets=("$target") ;;
+    namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile|midi-bridge) targets=("$target") ;;
     *) usage ;;
 esac
 

+ 20 - 0
scripts/validate_desired_state.py

@@ -486,6 +486,26 @@ def validate_state(state):
                     "deployment.reconcile.interval_seconds must be between 5 and 300"
                 )
 
+        midi_bridge = deployment.get("midi_bridge")
+        if not isinstance(midi_bridge, dict):
+            errors.append("deployment.midi_bridge must be a mapping")
+        else:
+            for key, expected in (
+                ("bridge_script", "scripts/midi_action_bridge.py"),
+                (
+                    "service_source",
+                    "config/systemd/user/rigforge-midi-bridge.service.in",
+                ),
+                (
+                    "service_destination",
+                    ".config/systemd/user/rigforge-midi-bridge.service",
+                ),
+                ("user_service", "rigforge-midi-bridge.service"),
+                ("python_path", "/usr/bin/python3"),
+            ):
+                if midi_bridge.get(key) != expected:
+                    errors.append(f"deployment.midi_bridge.{key} must be {expected}")
+
         pipewire = deployment.get("pipewire")
         if not isinstance(pipewire, dict):
             errors.append("deployment.pipewire must be a mapping")

+ 76 - 0
tests/test_deploy.py

@@ -108,6 +108,9 @@ class DeploymentTests(unittest.TestCase):
     def reconcile_config(self):
         return deploy.load_deployment()["reconcile"]
 
+    def midi_bridge_config(self):
+        return deploy.load_deployment()["midi_bridge"]
+
     def make_archive(self, destination, files=None):
         files = files or {"manifest.ttl": b"<urn:nam> a <urn:Plugin> .\n", "plugin.so": b"binary"}
         with tarfile.open(destination, "w:gz") as archive:
@@ -386,6 +389,79 @@ class DeploymentTests(unittest.TestCase):
             ],
         )
 
+    def test_midi_bridge_install_and_uninstall_manage_only_user_service(self):
+        config = self.midi_bridge_config()
+        destination = self.home / config["service_destination"]
+        destination.parent.mkdir(parents=True)
+        destination.write_text("prior MIDI unit", encoding="utf-8")
+
+        deploy.deploy_midi_bridge("install", config, deploy.read_registry())
+
+        installed = destination.read_text(encoding="utf-8")
+        self.assertIn("Description=Rigforge MIDI action bridge", installed)
+        self.assertIn("midi_action_bridge.py\" --state", installed)
+        self.assertIn("After=rigforge-mod-host.service", installed)
+        self.assertIn("Restart=on-failure", installed)
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-midi-bridge.service"],
+                ["systemctl", "--user", "restart", "rigforge-midi-bridge.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"],
+            ],
+        )
+        self.assertIn("midi_bridge", deploy.read_registry())
+
+        self.commands.clear()
+        deploy.deploy_midi_bridge("uninstall", config, deploy.read_registry())
+        self.assertEqual(destination.read_text(encoding="utf-8"), "prior MIDI unit")
+        self.assertNotIn("midi_bridge", deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "disable", "--now", "rigforge-midi-bridge.service"],
+                ["systemctl", "--user", "daemon-reload"],
+            ],
+        )
+
+    def test_midi_bridge_install_is_idempotent_and_reload_restarts_only_bridge(self):
+        config = self.midi_bridge_config()
+        deploy.deploy_midi_bridge("install", config, deploy.read_registry())
+        self.commands.clear()
+        deploy.deploy_midi_bridge("install", config, deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-midi-bridge.service"],
+                ["systemctl", "--user", "start", "rigforge-midi-bridge.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"],
+            ],
+        )
+        self.commands.clear()
+        deploy.deploy_midi_bridge("reload", config, deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "restart", "rigforge-midi-bridge.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"],
+            ],
+        )
+
+    def test_midi_bridge_uninstall_refuses_local_unit_edits(self):
+        config = self.midi_bridge_config()
+        deploy.deploy_midi_bridge("install", config, deploy.read_registry())
+        destination = self.home / config["service_destination"]
+        destination.write_text("local change", encoding="utf-8")
+        self.commands.clear()
+
+        with self.assertRaisesRegex(RuntimeError, "changed locally"):
+            deploy.deploy_midi_bridge("uninstall", config, deploy.read_registry())
+
+        self.assertEqual(destination.read_text(encoding="utf-8"), "local change")
+        self.assertEqual(self.commands, [])
+
     def test_mod_host_install_and_uninstall_do_not_manage_reconcile_timer(self):
         reconcile_config = self.reconcile_config()
         mod_host_config = self.mod_host_config()

+ 16 - 0
tests/test_desired_state.py

@@ -208,6 +208,22 @@ class DesiredStateValidationTests(unittest.TestCase):
         del state["deployment"]["reconcile"]
         self.assertIn("deployment.reconcile must be a mapping", validate_state(state))
 
+        state = copy.deepcopy(self.state)
+        self.assertEqual(
+            state["deployment"]["midi_bridge"]["user_service"],
+            "rigforge-midi-bridge.service",
+        )
+        state["deployment"]["midi_bridge"]["service_destination"] = "../unsafe.service"
+        self.assertIn(
+            "deployment.midi_bridge.service_destination must be "
+            ".config/systemd/user/rigforge-midi-bridge.service",
+            validate_state(state),
+        )
+
+        state = copy.deepcopy(self.state)
+        del state["deployment"]["midi_bridge"]
+        self.assertIn("deployment.midi_bridge must be a mapping", validate_state(state))
+
     def test_return_exclusion_marker_is_not_an_active_connection(self):
         self.assertEqual(validate_state(self.state), [])