validate_desired_state.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import argparse
  2. import sys
  3. from pathlib import Path, PurePosixPath
  4. import yaml
  5. def safe_relative_path(value):
  6. if not isinstance(value, str) or not value:
  7. return False
  8. path = PurePosixPath(value)
  9. return not path.is_absolute() and ".." not in path.parts
  10. def validate_mod_host_chain(routing, source_by_id):
  11. errors = []
  12. chains = routing.get("mod_host_chains")
  13. if not isinstance(chains, dict):
  14. return ["routing.mod_host_chains must be a mapping"]
  15. if set(chains) != {"guitar"}:
  16. errors.append("routing.mod_host_chains must declare the guitar chain exactly once")
  17. chain = chains.get("guitar")
  18. if not isinstance(chain, dict):
  19. return errors + ["routing.mod_host_chains.guitar must be a mapping"]
  20. guitar = source_by_id.get("guitar")
  21. source_port = guitar.get("capture_port") if isinstance(guitar, dict) else None
  22. if chain.get("source_port") != source_port:
  23. errors.append("routing.mod_host_chains.guitar.source_port must match the guitar capture port")
  24. bypass = chain.get("bypass_link")
  25. mix_input = chain.get("mix_input")
  26. if not isinstance(bypass, dict):
  27. errors.append("routing.mod_host_chains.guitar.bypass_link must be a mapping")
  28. elif bypass != {"from": source_port, "to": mix_input}:
  29. errors.append("routing.mod_host_chains.guitar.bypass_link must identify the direct capture-to-mix edge")
  30. if mix_input != "rigforge.direct-mix.input:playback_AUX0":
  31. errors.append("routing.mod_host_chains.guitar.mix_input must be the guitar mixer's AUX0 input")
  32. processors = chain.get("processors")
  33. if not isinstance(processors, list) or len(processors) != 2:
  34. return errors + ["routing.mod_host_chains.guitar.processors must contain NAM followed by one cabinet IR"]
  35. expected_processors = (
  36. {
  37. "id": "amp-head",
  38. "instance": 0,
  39. "plugin_uri": "http://github.com/mikeoliphant/neural-amp-modeler-lv2",
  40. "bundle_path": ".lv2/neural_amp_modeler.lv2",
  41. "file_property": "http://github.com/mikeoliphant/neural-amp-modeler-lv2#model",
  42. "asset_path": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam",
  43. "input_port": "effect_0:input",
  44. "output_port": "effect_0:output",
  45. },
  46. {
  47. "id": "cabinet-ir",
  48. "instance": 1,
  49. "plugin_uri": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono",
  50. "bundle_path": ".lv2/lsp-plugins.lv2",
  51. "file_property": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono/ports#ifn",
  52. "asset_path": "amp_emul/cabinet/VOX_AC30_1964/VOX_AC30_1964_celestion.wav",
  53. "input_port": "effect_1:in",
  54. "output_port": "effect_1:out",
  55. },
  56. )
  57. for index, (processor, expected) in enumerate(zip(processors, expected_processors)):
  58. location = f"routing.mod_host_chains.guitar.processors[{index}]"
  59. if not isinstance(processor, dict):
  60. errors.append(f"{location} must be a mapping")
  61. continue
  62. for key, value in expected.items():
  63. if processor.get(key) != value:
  64. errors.append(f"{location}.{key} must be {value}")
  65. for key in ("bundle_path", "asset_path"):
  66. if not safe_relative_path(processor.get(key)):
  67. errors.append(f"{location}.{key} must be a safe relative path")
  68. if isinstance(processors[0], dict):
  69. parameters = processors[0].get("parameters")
  70. if not isinstance(parameters, dict):
  71. errors.append("routing.mod_host_chains.guitar.processors[0].parameters must be a mapping")
  72. else:
  73. output_level = parameters.get("output_level")
  74. if (
  75. not isinstance(output_level, (int, float))
  76. or isinstance(output_level, bool)
  77. or not -20.0 <= output_level <= 20.0
  78. ):
  79. errors.append("NAM output_level must be between -20 and 20 dB")
  80. links = routing.get("managed_links")
  81. if isinstance(links, list) and len(processors) == 2:
  82. actual_edges = {
  83. (link.get("from"), link.get("to"))
  84. for link in links
  85. if (
  86. isinstance(link, dict)
  87. and isinstance(link.get("from"), str)
  88. and isinstance(link.get("to"), str)
  89. )
  90. }
  91. if isinstance(processors[0], dict) and isinstance(processors[1], dict):
  92. expected_candidates = (
  93. (source_port, processors[0].get("input_port")),
  94. (processors[0].get("output_port"), processors[1].get("input_port")),
  95. (processors[1].get("output_port"), mix_input),
  96. )
  97. for edge in expected_candidates:
  98. if not all(isinstance(endpoint, str) for endpoint in edge):
  99. continue
  100. if edge not in actual_edges:
  101. errors.append(f"mod-host guitar chain link must be declared: {edge[0]} -> {edge[1]}")
  102. if isinstance(bypass, dict):
  103. bypass_edge = (bypass.get("from"), bypass.get("to"))
  104. if all(isinstance(endpoint, str) for endpoint in bypass_edge) and bypass_edge in actual_edges:
  105. errors.append("the guitar capture-to-mix bypass must not be a managed link")
  106. return errors
  107. def validate_state(state):
  108. errors = []
  109. if not isinstance(state, dict):
  110. return ["document root must be a mapping"]
  111. # Establish the declared source map before validating looper references.
  112. sources = state.get("sources")
  113. if not isinstance(sources, list):
  114. return ["sources must be a list"]
  115. source_by_id = {}
  116. physical_inputs = set()
  117. capture_ports = set()
  118. for index, source in enumerate(sources):
  119. location = f"sources[{index}]"
  120. if not isinstance(source, dict):
  121. errors.append(f"{location} must be a mapping")
  122. continue
  123. source_id = source.get("id")
  124. if not isinstance(source_id, str) or not source_id:
  125. errors.append(f"{location}.id must be a non-empty string")
  126. elif source_id in source_by_id:
  127. errors.append(f"duplicate source id: {source_id}")
  128. else:
  129. source_by_id[source_id] = source
  130. physical_input = source.get("physical_input")
  131. if not isinstance(physical_input, int) or isinstance(physical_input, bool):
  132. errors.append(f"{location}.physical_input must be an integer")
  133. elif physical_input in physical_inputs:
  134. errors.append(f"duplicate physical input: {physical_input}")
  135. else:
  136. physical_inputs.add(physical_input)
  137. capture_port = source.get("capture_port")
  138. if not isinstance(capture_port, str) or not capture_port:
  139. errors.append(f"{location}.capture_port must be a non-empty string")
  140. elif capture_port in capture_ports:
  141. errors.append(f"duplicate capture port: {capture_port}")
  142. else:
  143. capture_ports.add(capture_port)
  144. # Keep the first four-channel milestone tied to its four named instruments.
  145. expected_source_ids = {"guitar", "bass", "voice", "synth"}
  146. if set(source_by_id) != expected_source_ids:
  147. errors.append("source ids must be guitar, bass, voice, and synth exactly once")
  148. if len(sources) != 4:
  149. errors.append(f"exactly four sources are required, got {len(sources)}")
  150. if physical_inputs != {1, 2, 3, 4}:
  151. errors.append("physical inputs must cover 1 through 4 exactly once")
  152. # The required looper is one instance containing one four-channel loop.
  153. system = state.get("system")
  154. components = system.get("components") if isinstance(system, dict) else None
  155. if not isinstance(components, list):
  156. errors.append("system.components must be a list")
  157. components = []
  158. loopers = [item for item in components if isinstance(item, dict) and item.get("id") == "looper"]
  159. if len(loopers) != 1:
  160. errors.append(f"exactly one looper component is required, got {len(loopers)}")
  161. elif loopers[0].get("instance_count") != 1:
  162. errors.append("looper.instance_count must be 1")
  163. elif loopers[0].get("loop_count") != 1:
  164. errors.append("looper.loop_count must be 1")
  165. elif loopers[0].get("channels_per_loop") != 4:
  166. errors.append("looper.channels_per_loop must be 4")
  167. routing = state.get("routing")
  168. if not isinstance(routing, dict):
  169. errors.append("routing must be a mapping")
  170. return errors
  171. looper_inputs = routing.get("looper_inputs")
  172. if not isinstance(looper_inputs, list):
  173. errors.append("routing.looper_inputs must be a list")
  174. looper_inputs = []
  175. # Check that each source is assigned exactly once across all loop channels.
  176. input_channels = set()
  177. input_sources = set()
  178. for index, loop_input in enumerate(looper_inputs):
  179. location = f"routing.looper_inputs[{index}]"
  180. if not isinstance(loop_input, dict):
  181. errors.append(f"{location} must be a mapping")
  182. continue
  183. source_id = loop_input.get("source")
  184. channel = loop_input.get("channel")
  185. if source_id not in source_by_id:
  186. errors.append(f"{location}.source references unknown source: {source_id}")
  187. if source_id in input_sources:
  188. errors.append(f"source is assigned to multiple looper inputs: {source_id}")
  189. input_sources.add(source_id)
  190. if not isinstance(channel, int) or isinstance(channel, bool) or channel not in range(1, 5):
  191. errors.append(f"{location}.channel must be an integer from 1 through 4")
  192. elif channel in input_channels:
  193. errors.append(f"duplicate looper input channel: {channel}")
  194. else:
  195. input_channels.add(channel)
  196. if len(looper_inputs) != 4 or input_channels != {1, 2, 3, 4}:
  197. errors.append("looper inputs must cover channels 1 through 4 exactly once")
  198. if input_sources != set(source_by_id):
  199. errors.append("each declared source must map to exactly one looper input")
  200. mix = routing.get("mix")
  201. if not isinstance(mix, dict):
  202. errors.append("routing.mix must be a mapping")
  203. else:
  204. output_port = mix.get("output_port")
  205. if not isinstance(output_port, str) or not output_port:
  206. errors.append("routing.mix.output_port must be a non-empty string")
  207. mix_id = mix.get("id")
  208. if not isinstance(mix_id, str) or not mix_id:
  209. errors.append("routing.mix.id must be a non-empty string")
  210. includes = mix.get("includes")
  211. if not isinstance(includes, list) or "looper_returns" not in includes:
  212. errors.append("routing.mix.includes must include looper_returns")
  213. # Loop returns join the output mix but must never feed the loop inputs.
  214. returns = routing.get("looper_returns")
  215. if not isinstance(returns, dict):
  216. errors.append("routing.looper_returns must be a mapping")
  217. elif returns.get("feed_looper_inputs") is not False:
  218. errors.append("routing.looper_returns.feed_looper_inputs must be false")
  219. errors.extend(validate_mod_host_chain(routing, source_by_id))
  220. connections = state.get("connections", [])
  221. if not isinstance(connections, list):
  222. errors.append("connections must be a list")
  223. connections = []
  224. # An explicitly-forbidden connection documents policy; any other status is actionable.
  225. for index, connection in enumerate(connections):
  226. if not isinstance(connection, dict):
  227. errors.append(f"connections[{index}] must be a mapping")
  228. continue
  229. if (
  230. connection.get("from") == "looper_returns"
  231. and connection.get("to") in {
  232. "looper_inputs",
  233. "looper_input_1",
  234. "looper_input_2",
  235. "looper_input_3",
  236. "looper_input_4",
  237. }
  238. and connection.get("status") != "explicitly-forbidden"
  239. ):
  240. errors.append(f"connections[{index}] routes looper returns into looper inputs")
  241. deployment = state.get("deployment")
  242. if not isinstance(deployment, dict):
  243. errors.append("deployment must be a mapping")
  244. else:
  245. for component, repository, asset, archive_format, bundle_paths in (
  246. (
  247. "lsp",
  248. "lsp-plugins/lsp-plugins",
  249. "lsp-plugins-{tag}-Linux-aarch64.7z",
  250. "7z",
  251. {"lsp-plugins.lv2": "lsp-plugins-{tag}-Linux-aarch64/LV2/lsp-plugins.lv2"},
  252. ),
  253. (
  254. "dragonfly_reverb",
  255. "michaelwillis/dragonfly-reverb",
  256. "dragonfly-reverb-{tag}-linux-arm64.tar.xz",
  257. "tar.xz",
  258. {
  259. "DragonflyEarlyReflections.lv2": "dragonfly-reverb-{tag}/DragonflyEarlyReflections.lv2",
  260. "DragonflyHallReverb.lv2": "dragonfly-reverb-{tag}/DragonflyHallReverb.lv2",
  261. "DragonflyPlateReverb.lv2": "dragonfly-reverb-{tag}/DragonflyPlateReverb.lv2",
  262. "DragonflyRoomReverb.lv2": "dragonfly-reverb-{tag}/DragonflyRoomReverb.lv2",
  263. },
  264. ),
  265. ):
  266. plugin = deployment.get(component)
  267. if not isinstance(plugin, dict):
  268. errors.append(f"deployment.{component} must be a mapping")
  269. continue
  270. tag = plugin.get("tag")
  271. if not isinstance(tag, str) or not tag or any(
  272. character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
  273. for character in tag
  274. ):
  275. errors.append(f"deployment.{component}.tag must be a simple version tag")
  276. expected_url = f"https://github.com/{repository}/releases/download/{tag}/{asset.format(tag=tag)}"
  277. if plugin.get("archive_url") != expected_url:
  278. errors.append(f"deployment.{component}.archive_url must match its tag and approved release asset")
  279. if plugin.get("archive_format") != archive_format:
  280. errors.append(f"deployment.{component}.archive_format must be {archive_format}")
  281. expected_paths = {
  282. name: path.format(tag=tag) for name, path in bundle_paths.items()
  283. }
  284. if plugin.get("bundle_paths") != expected_paths:
  285. errors.append(f"deployment.{component}.bundle_paths are invalid")
  286. for bundle_name, bundle_path in expected_paths.items():
  287. if bundle_name not in bundle_path:
  288. errors.append(f"deployment.{component}.bundle_paths keys must name their bundle directories")
  289. namlv2 = deployment.get("namlv2")
  290. if not isinstance(namlv2, dict):
  291. errors.append("deployment.namlv2 must be a mapping")
  292. else:
  293. tag = namlv2.get("tag")
  294. allowed_tag_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
  295. if not isinstance(tag, str) or not tag or any(
  296. character not in allowed_tag_characters for character in tag
  297. ):
  298. errors.append("deployment.namlv2.tag must be a simple version tag")
  299. archive_url = namlv2.get("archive_url")
  300. expected_url = (
  301. f"https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/{tag}/"
  302. "neural_amp_modeler_lv2_rpi5.tgz"
  303. )
  304. if archive_url != expected_url:
  305. errors.append("deployment.namlv2.archive_url must match its tag and approved RPi 5 release asset")
  306. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  307. errors.append("deployment.namlv2.bundle_directory must be neural_amp_modeler.lv2")
  308. sooperlooper = deployment.get("sooperlooper")
  309. if not isinstance(sooperlooper, dict):
  310. errors.append("deployment.sooperlooper must be a mapping")
  311. else:
  312. source_url = sooperlooper.get("source_url")
  313. if source_url != "https://github.com/abarker/sooperlooper-mods":
  314. errors.append("deployment.sooperlooper.source_url must match the approved GitHub repository")
  315. tag = sooperlooper.get("tag")
  316. if not isinstance(tag, str) or not tag or any(
  317. character not in allowed_tag_characters for character in tag
  318. ):
  319. errors.append("deployment.sooperlooper.tag must be a simple version tag")
  320. mod_host = deployment.get("mod_host")
  321. if not isinstance(mod_host, dict):
  322. errors.append("deployment.mod_host must be a mapping")
  323. else:
  324. source_url = mod_host.get("source_url")
  325. if source_url != "https://github.com/mod-audio/mod-host":
  326. errors.append("deployment.mod_host.source_url must match the approved GitHub repository")
  327. tag = mod_host.get("tag")
  328. if not isinstance(tag, str) or not tag or any(
  329. character not in allowed_tag_characters for character in tag
  330. ):
  331. errors.append("deployment.mod_host.tag must be a simple version tag")
  332. for key, expected in (
  333. ("binary_source", "artifacts/mod-host/arm64/current/mod-host"),
  334. ("service_source", "config/systemd/user/rigforge-mod-host.service.in"),
  335. ("service_destination", ".config/systemd/user/rigforge-mod-host.service"),
  336. ("user_service", "rigforge-mod-host.service"),
  337. ("configure_script", "scripts/configure_mod_host.py"),
  338. ("pw_jack_path", "/usr/bin/pw-jack"),
  339. ("python_path", "/usr/bin/python3"),
  340. ):
  341. if mod_host.get(key) != expected:
  342. errors.append(f"deployment.mod_host.{key} must be {expected}")
  343. socket_port = mod_host.get("socket_port")
  344. if (
  345. not isinstance(socket_port, int)
  346. or isinstance(socket_port, bool)
  347. or not 1 <= socket_port <= 65535
  348. ):
  349. errors.append("deployment.mod_host.socket_port must be a valid TCP port")
  350. pipewire = deployment.get("pipewire")
  351. if not isinstance(pipewire, dict):
  352. errors.append("deployment.pipewire must be a mapping")
  353. else:
  354. expected_fragment_source = "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
  355. if pipewire.get("fragment_source") != expected_fragment_source:
  356. errors.append("deployment.pipewire.fragment_source must name the managed repository fragment")
  357. expected_fragment_destination = ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
  358. if pipewire.get("fragment_destination") != expected_fragment_destination:
  359. errors.append("deployment.pipewire.fragment_destination must be the user filter-chain fragment path")
  360. if pipewire.get("user_service") != "filter-chain.service":
  361. errors.append("deployment.pipewire.user_service must be filter-chain.service")
  362. return errors
  363. def main(argv=None):
  364. parser = argparse.ArgumentParser()
  365. parser.add_argument(
  366. "state_file",
  367. nargs="?",
  368. type=Path,
  369. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  370. )
  371. args = parser.parse_args(argv)
  372. try:
  373. with args.state_file.open(encoding="utf-8") as state_stream:
  374. state = yaml.safe_load(state_stream)
  375. except (OSError, yaml.YAMLError) as error:
  376. print(f"Unable to load {args.state_file}: {error}", file=sys.stderr)
  377. return 2
  378. errors = validate_state(state)
  379. if errors:
  380. for error in errors:
  381. print(f"ERROR: {error}", file=sys.stderr)
  382. return 1
  383. print(f"Valid desired state: {args.state_file}")
  384. return 0
  385. if __name__ == "__main__":
  386. raise SystemExit(main())