zenoh_flow_commons/
utils.rs

1//
2// Copyright (c) 2021 - 2024 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13//
14
15use crate::{IMergeOverwrite, Result, Vars};
16use anyhow::{bail, Context};
17use handlebars::Handlebars;
18use serde::Deserialize;
19use std::io::Read;
20use std::path::{Path, PathBuf};
21
22/// Given the [Path] of a file, return the function we should call to deserialize an instance of `N`.
23///
24/// This function will look at the extension of the [Path] to decide on a deserializer.
25///
26/// # Errors
27///
28/// This function will fail if the extension of the [Path] is not supported. For now, the only supported extensions are:
29/// - ".yml"
30/// - ".yaml"
31/// - ".json"
32pub(crate) fn deserializer<N>(path: &PathBuf) -> Result<fn(&str) -> Result<N>>
33where
34    N: for<'a> Deserialize<'a>,
35{
36    match path.extension().and_then(|ext| ext.to_str()) {
37        Some("json") => Ok(|buf| {
38            serde_json::from_str::<N>(buf)
39                .context(format!("Failed to deserialize from JSON:\n{}", buf))
40        }),
41        Some("yml") | Some("yaml") => Ok(|buf| {
42            serde_yaml::from_str::<N>(buf)
43                .context(format!("Failed to deserialize from YAML:\n{}", buf))
44        }),
45        Some(extension) => bail!(
46            r#"
47Unsupported file extension < {} > in:
48   {:?}
49
50Currently supported file extensions are:
51- .json
52- .yml
53- .yaml
54"#,
55            extension,
56            path
57        ),
58        None => bail!("Missing file extension in path:\n{}", path.display()),
59    }
60}
61
62/// Attempts to parse an instance of `N` from the content of the file located at `path`, overwriting (or complementing)
63/// the [Vars] declared in said file with the provided `vars`.
64///
65/// This function is notably used to parse a data flow descriptor. Two file types are supported, identified by their
66/// extension:
67/// - JSON (`.json` file extension)
68/// - YAML (`.yaml` or `.yml` extensions)
69///
70/// This function does not impose writing *all* descriptor file(s), within the same data flow, in the same format.
71///
72/// # Errors
73///
74/// The parsing can fail for several reasons (listed in sequential order):
75/// - the OS failed to [canonicalize](std::fs::canonicalize()) the path of the file,
76/// - the OS failed to open (in read mode) the file,
77/// - the extension of the file is not supported by Zenoh-Flow (i.e. it's neither a YAML file or a JSON file),
78/// - parsing the [Vars] section failed (if there is one),
79/// - expanding the variables located in the [Vars] section failed (if there are any) --- see the documentation
80///   [handlebars] for a more complete list of reasons,
81/// - parsing an instance of `N` failed.
82pub fn try_parse_from_file<N>(path: impl AsRef<Path>, vars: Vars) -> Result<(N, Vars)>
83where
84    N: for<'a> Deserialize<'a>,
85{
86    let path_buf = std::fs::canonicalize(path.as_ref()).context(format!(
87        "Failed to canonicalize path (did you put an absolute path?):\n{}",
88        path.as_ref().to_string_lossy()
89    ))?;
90
91    let mut buf = String::default();
92    std::fs::File::open(&path_buf)
93        .context(format!("Failed to open file:\n{}", path_buf.display()))?
94        .read_to_string(&mut buf)
95        .context(format!(
96            "Failed to read the content of file:\n{}",
97            path_buf.display()
98        ))?;
99
100    let merged_vars = vars.merge_overwrite(
101        deserializer::<Vars>(&path_buf)?(&buf).context("Failed to deserialize Vars")?,
102    );
103
104    let mut handlebars = Handlebars::new();
105    handlebars.set_strict_mode(true);
106
107    let rendered_descriptor = handlebars
108        // NOTE: We have to dereference `merged_vars` (this: `&(*merged_vars)`) and pass the contained `HashMap` such
109        // that `handlebars` can correctly manipulate it.
110        //
111        // We have to have this indirection in the structure such that `serde` can correctly deserialise the descriptor.
112        .render_template(buf.as_str(), &(*merged_vars))
113        .context("Failed to expand descriptor")?;
114
115    Ok((
116        (deserializer::<N>(&path_buf))?(&rendered_descriptor)
117            .context(format!("Failed to deserialize {}", &path_buf.display()))?,
118        merged_vars,
119    ))
120}