Skip to main content

synesthetic_fixtures/
lib.rs

1//! Embedded Synesthetic fixtures for integration tests and examples.
2
3use serde::de::DeserializeOwned;
4use serde_json::Error as SerdeError;
5use synesthetic_schema::synesthetic::{graph::v1::Graph, operator::v1::OperatorDef};
6
7const OPERATORS: &[(&str, &str)] = &[
8    (
9        "test/source",
10        include_str!("../data/operators/signal_source.json"),
11    ),
12    (
13        "test/processor",
14        include_str!("../data/operators/signal_processor.json"),
15    ),
16];
17
18const GRAPHS: &[(&str, &str)] = &[(
19    "signal_chain",
20    include_str!("../data/graphs/signal_chain.json"),
21)];
22
23/// Return the raw JSON for a fixture operator by ID (e.g., `test/source`).
24pub fn operator_json(id: &str) -> Option<&'static str> {
25    OPERATORS
26        .iter()
27        .find(|(fixture_id, _)| *fixture_id == id)
28        .map(|(_, json)| *json)
29}
30
31/// Return the raw JSON for a fixture graph by ID (e.g., `signal_chain`).
32pub fn graph_json(id: &str) -> Option<&'static str> {
33    GRAPHS
34        .iter()
35        .find(|(fixture_id, _)| *fixture_id == id)
36        .map(|(_, json)| *json)
37}
38
39/// Deserialize a fixture operator into an [`OperatorDef`].
40pub fn operator(id: &str) -> Result<OperatorDef, FixtureError> {
41    parse_fixture(operator_json(id), id)
42}
43
44/// Deserialize a fixture graph into a [`Graph`].
45pub fn graph(id: &str) -> Result<Graph, FixtureError> {
46    parse_fixture(graph_json(id), id)
47}
48
49fn parse_fixture<T: DeserializeOwned>(
50    json: Option<&'static str>,
51    id: &str,
52) -> Result<T, FixtureError> {
53    let json = json.ok_or_else(|| FixtureError::Missing { id: id.to_owned() })?;
54    serde_json::from_str(json).map_err(|err| FixtureError::Deserialize {
55        id: id.to_owned(),
56        source: err,
57    })
58}
59
60/// Error returned when fixtures cannot be loaded.
61#[derive(Debug, thiserror::Error)]
62pub enum FixtureError {
63    #[error("fixture '{id}' not found")]
64    Missing { id: String },
65    #[error("failed to deserialize fixture '{id}': {source}")]
66    Deserialize {
67        id: String,
68        #[source]
69        source: SerdeError,
70    },
71}
72
73/// Iterator over all (id, json) operator fixtures.
74pub fn iter_operator_json() -> impl Iterator<Item = (&'static str, &'static str)> {
75    OPERATORS.iter().copied()
76}
77
78/// Iterator over all (id, json) graph fixtures.
79pub fn iter_graph_json() -> impl Iterator<Item = (&'static str, &'static str)> {
80    GRAPHS.iter().copied()
81}