validate_desired_state.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. managed_unlinks = routing.get("managed_unlinks")
  107. unlink_edges = {
  108. (item.get("from"), item.get("to"))
  109. for item in managed_unlinks
  110. if isinstance(item, dict)
  111. } if isinstance(managed_unlinks, list) else set()
  112. if (
  113. all(isinstance(endpoint, str) for endpoint in bypass_edge)
  114. and bypass_edge not in unlink_edges
  115. ):
  116. errors.append("the guitar capture-to-mix bypass must be declared in routing.managed_unlinks")
  117. return errors
  118. def validate_state(state):
  119. errors = []
  120. if not isinstance(state, dict):
  121. return ["document root must be a mapping"]
  122. # Establish the declared source map before validating looper references.
  123. sources = state.get("sources")
  124. if not isinstance(sources, list):
  125. return ["sources must be a list"]
  126. source_by_id = {}
  127. physical_inputs = set()
  128. capture_ports = set()
  129. for index, source in enumerate(sources):
  130. location = f"sources[{index}]"
  131. if not isinstance(source, dict):
  132. errors.append(f"{location} must be a mapping")
  133. continue
  134. source_id = source.get("id")
  135. if not isinstance(source_id, str) or not source_id:
  136. errors.append(f"{location}.id must be a non-empty string")
  137. elif source_id in source_by_id:
  138. errors.append(f"duplicate source id: {source_id}")
  139. else:
  140. source_by_id[source_id] = source
  141. physical_input = source.get("physical_input")
  142. if not isinstance(physical_input, int) or isinstance(physical_input, bool):
  143. errors.append(f"{location}.physical_input must be an integer")
  144. elif physical_input in physical_inputs:
  145. errors.append(f"duplicate physical input: {physical_input}")
  146. else:
  147. physical_inputs.add(physical_input)
  148. capture_port = source.get("capture_port")
  149. if not isinstance(capture_port, str) or not capture_port:
  150. errors.append(f"{location}.capture_port must be a non-empty string")
  151. elif capture_port in capture_ports:
  152. errors.append(f"duplicate capture port: {capture_port}")
  153. else:
  154. capture_ports.add(capture_port)
  155. # Keep the first four-channel milestone tied to its four named instruments.
  156. expected_source_ids = {"guitar", "bass", "voice", "synth"}
  157. if set(source_by_id) != expected_source_ids:
  158. errors.append("source ids must be guitar, bass, voice, and synth exactly once")
  159. if len(sources) != 4:
  160. errors.append(f"exactly four sources are required, got {len(sources)}")
  161. if physical_inputs != {1, 2, 3, 4}:
  162. errors.append("physical inputs must cover 1 through 4 exactly once")
  163. # The required looper is one instance containing one four-channel loop.
  164. system = state.get("system")
  165. components = system.get("components") if isinstance(system, dict) else None
  166. if not isinstance(components, list):
  167. errors.append("system.components must be a list")
  168. components = []
  169. loopers = [item for item in components if isinstance(item, dict) and item.get("id") == "looper"]
  170. if len(loopers) != 1:
  171. errors.append(f"exactly one looper component is required, got {len(loopers)}")
  172. elif loopers[0].get("instance_count") != 1:
  173. errors.append("looper.instance_count must be 1")
  174. elif loopers[0].get("loop_count") != 1:
  175. errors.append("looper.loop_count must be 1")
  176. elif loopers[0].get("channels_per_loop") != 4:
  177. errors.append("looper.channels_per_loop must be 4")
  178. routing = state.get("routing")
  179. if not isinstance(routing, dict):
  180. errors.append("routing must be a mapping")
  181. return errors
  182. looper_inputs = routing.get("looper_inputs")
  183. if not isinstance(looper_inputs, list):
  184. errors.append("routing.looper_inputs must be a list")
  185. looper_inputs = []
  186. # Check that each source is assigned exactly once across all loop channels.
  187. input_channels = set()
  188. input_sources = set()
  189. for index, loop_input in enumerate(looper_inputs):
  190. location = f"routing.looper_inputs[{index}]"
  191. if not isinstance(loop_input, dict):
  192. errors.append(f"{location} must be a mapping")
  193. continue
  194. source_id = loop_input.get("source")
  195. channel = loop_input.get("channel")
  196. if source_id not in source_by_id:
  197. errors.append(f"{location}.source references unknown source: {source_id}")
  198. if source_id in input_sources:
  199. errors.append(f"source is assigned to multiple looper inputs: {source_id}")
  200. input_sources.add(source_id)
  201. if not isinstance(channel, int) or isinstance(channel, bool) or channel not in range(1, 5):
  202. errors.append(f"{location}.channel must be an integer from 1 through 4")
  203. elif channel in input_channels:
  204. errors.append(f"duplicate looper input channel: {channel}")
  205. else:
  206. input_channels.add(channel)
  207. if len(looper_inputs) != 4 or input_channels != {1, 2, 3, 4}:
  208. errors.append("looper inputs must cover channels 1 through 4 exactly once")
  209. if input_sources != set(source_by_id):
  210. errors.append("each declared source must map to exactly one looper input")
  211. mix = routing.get("mix")
  212. if not isinstance(mix, dict):
  213. errors.append("routing.mix must be a mapping")
  214. else:
  215. output_port = mix.get("output_port")
  216. if not isinstance(output_port, str) or not output_port:
  217. errors.append("routing.mix.output_port must be a non-empty string")
  218. mix_id = mix.get("id")
  219. if not isinstance(mix_id, str) or not mix_id:
  220. errors.append("routing.mix.id must be a non-empty string")
  221. includes = mix.get("includes")
  222. if not isinstance(includes, list) or "looper_returns" not in includes:
  223. errors.append("routing.mix.includes must include looper_returns")
  224. # Loop returns join the output mix but must never feed the loop inputs.
  225. returns = routing.get("looper_returns")
  226. if not isinstance(returns, dict):
  227. errors.append("routing.looper_returns must be a mapping")
  228. elif returns.get("feed_looper_inputs") is not False:
  229. errors.append("routing.looper_returns.feed_looper_inputs must be false")
  230. errors.extend(validate_mod_host_chain(routing, source_by_id))
  231. connections = state.get("connections", [])
  232. if not isinstance(connections, list):
  233. errors.append("connections must be a list")
  234. connections = []
  235. # An explicitly-forbidden connection documents policy; any other status is actionable.
  236. for index, connection in enumerate(connections):
  237. if not isinstance(connection, dict):
  238. errors.append(f"connections[{index}] must be a mapping")
  239. continue
  240. if (
  241. connection.get("from") == "looper_returns"
  242. and connection.get("to") in {
  243. "looper_inputs",
  244. "looper_input_1",
  245. "looper_input_2",
  246. "looper_input_3",
  247. "looper_input_4",
  248. }
  249. and connection.get("status") != "explicitly-forbidden"
  250. ):
  251. errors.append(f"connections[{index}] routes looper returns into looper inputs")
  252. deployment = state.get("deployment")
  253. if not isinstance(deployment, dict):
  254. errors.append("deployment must be a mapping")
  255. else:
  256. for component, repository, asset, archive_format, bundle_paths in (
  257. (
  258. "lsp",
  259. "lsp-plugins/lsp-plugins",
  260. "lsp-plugins-{tag}-Linux-aarch64.7z",
  261. "7z",
  262. {"lsp-plugins.lv2": "lsp-plugins-{tag}-Linux-aarch64/LV2/lsp-plugins.lv2"},
  263. ),
  264. (
  265. "dragonfly_reverb",
  266. "michaelwillis/dragonfly-reverb",
  267. "dragonfly-reverb-{tag}-linux-arm64.tar.xz",
  268. "tar.xz",
  269. {
  270. "DragonflyEarlyReflections.lv2": "dragonfly-reverb-{tag}/DragonflyEarlyReflections.lv2",
  271. "DragonflyHallReverb.lv2": "dragonfly-reverb-{tag}/DragonflyHallReverb.lv2",
  272. "DragonflyPlateReverb.lv2": "dragonfly-reverb-{tag}/DragonflyPlateReverb.lv2",
  273. "DragonflyRoomReverb.lv2": "dragonfly-reverb-{tag}/DragonflyRoomReverb.lv2",
  274. },
  275. ),
  276. ):
  277. plugin = deployment.get(component)
  278. if not isinstance(plugin, dict):
  279. errors.append(f"deployment.{component} must be a mapping")
  280. continue
  281. tag = plugin.get("tag")
  282. if not isinstance(tag, str) or not tag or any(
  283. character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
  284. for character in tag
  285. ):
  286. errors.append(f"deployment.{component}.tag must be a simple version tag")
  287. expected_url = f"https://github.com/{repository}/releases/download/{tag}/{asset.format(tag=tag)}"
  288. if plugin.get("archive_url") != expected_url:
  289. errors.append(f"deployment.{component}.archive_url must match its tag and approved release asset")
  290. if plugin.get("archive_format") != archive_format:
  291. errors.append(f"deployment.{component}.archive_format must be {archive_format}")
  292. expected_paths = {
  293. name: path.format(tag=tag) for name, path in bundle_paths.items()
  294. }
  295. if plugin.get("bundle_paths") != expected_paths:
  296. errors.append(f"deployment.{component}.bundle_paths are invalid")
  297. for bundle_name, bundle_path in expected_paths.items():
  298. if bundle_name not in bundle_path:
  299. errors.append(f"deployment.{component}.bundle_paths keys must name their bundle directories")
  300. namlv2 = deployment.get("namlv2")
  301. if not isinstance(namlv2, dict):
  302. errors.append("deployment.namlv2 must be a mapping")
  303. else:
  304. tag = namlv2.get("tag")
  305. allowed_tag_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
  306. if not isinstance(tag, str) or not tag or any(
  307. character not in allowed_tag_characters for character in tag
  308. ):
  309. errors.append("deployment.namlv2.tag must be a simple version tag")
  310. archive_url = namlv2.get("archive_url")
  311. expected_url = (
  312. f"https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/{tag}/"
  313. "neural_amp_modeler_lv2_rpi5.tgz"
  314. )
  315. if archive_url != expected_url:
  316. errors.append("deployment.namlv2.archive_url must match its tag and approved RPi 5 release asset")
  317. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  318. errors.append("deployment.namlv2.bundle_directory must be neural_amp_modeler.lv2")
  319. sooperlooper = deployment.get("sooperlooper")
  320. if not isinstance(sooperlooper, dict):
  321. errors.append("deployment.sooperlooper must be a mapping")
  322. else:
  323. source_url = sooperlooper.get("source_url")
  324. if source_url != "https://github.com/abarker/sooperlooper-mods":
  325. errors.append("deployment.sooperlooper.source_url must match the approved GitHub repository")
  326. tag = sooperlooper.get("tag")
  327. if not isinstance(tag, str) or not tag or any(
  328. character not in allowed_tag_characters for character in tag
  329. ):
  330. errors.append("deployment.sooperlooper.tag must be a simple version tag")
  331. mod_host = deployment.get("mod_host")
  332. if not isinstance(mod_host, dict):
  333. errors.append("deployment.mod_host must be a mapping")
  334. else:
  335. source_url = mod_host.get("source_url")
  336. if source_url != "https://github.com/mod-audio/mod-host":
  337. errors.append("deployment.mod_host.source_url must match the approved GitHub repository")
  338. tag = mod_host.get("tag")
  339. if not isinstance(tag, str) or not tag or any(
  340. character not in allowed_tag_characters for character in tag
  341. ):
  342. errors.append("deployment.mod_host.tag must be a simple version tag")
  343. for key, expected in (
  344. ("binary_source", "artifacts/mod-host/arm64/current/mod-host"),
  345. ("service_source", "config/systemd/user/rigforge-mod-host.service.in"),
  346. ("service_destination", ".config/systemd/user/rigforge-mod-host.service"),
  347. ("user_service", "rigforge-mod-host.service"),
  348. ("configure_script", "scripts/configure_mod_host.py"),
  349. ("pw_jack_path", "/usr/bin/pw-jack"),
  350. ("python_path", "/usr/bin/python3"),
  351. ):
  352. if mod_host.get(key) != expected:
  353. errors.append(f"deployment.mod_host.{key} must be {expected}")
  354. socket_port = mod_host.get("socket_port")
  355. if (
  356. not isinstance(socket_port, int)
  357. or isinstance(socket_port, bool)
  358. or not 1 <= socket_port <= 65535
  359. ):
  360. errors.append("deployment.mod_host.socket_port must be a valid TCP port")
  361. pipewire = deployment.get("pipewire")
  362. if not isinstance(pipewire, dict):
  363. errors.append("deployment.pipewire must be a mapping")
  364. else:
  365. expected_fragment_source = "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
  366. if pipewire.get("fragment_source") != expected_fragment_source:
  367. errors.append("deployment.pipewire.fragment_source must name the managed repository fragment")
  368. expected_fragment_destination = ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
  369. if pipewire.get("fragment_destination") != expected_fragment_destination:
  370. errors.append("deployment.pipewire.fragment_destination must be the user filter-chain fragment path")
  371. if pipewire.get("user_service") != "filter-chain.service":
  372. errors.append("deployment.pipewire.user_service must be filter-chain.service")
  373. return errors
  374. def main(argv=None):
  375. parser = argparse.ArgumentParser()
  376. parser.add_argument(
  377. "state_file",
  378. nargs="?",
  379. type=Path,
  380. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  381. )
  382. args = parser.parse_args(argv)
  383. try:
  384. with args.state_file.open(encoding="utf-8") as state_stream:
  385. state = yaml.safe_load(state_stream)
  386. except (OSError, yaml.YAMLError) as error:
  387. print(f"Unable to load {args.state_file}: {error}", file=sys.stderr)
  388. return 2
  389. errors = validate_state(state)
  390. if errors:
  391. for error in errors:
  392. print(f"ERROR: {error}", file=sys.stderr)
  393. return 1
  394. print(f"Valid desired state: {args.state_file}")
  395. return 0
  396. if __name__ == "__main__":
  397. raise SystemExit(main())