about summary refs log tree commit diff
path: root/src/plot.rs
blob: 79edabceabbd48ba3829d423426e945505e42a83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//! Running the plotter scripts (`scripts/plot-rqtl.py`,
//! `scripts/plot-gemma.py`) over a mapping response.
//!
//! The plotters take the **saved JSON response** of a mapping and write
//! an SVG, so this writes the envelope the compute endpoint just built to
//! a scratch file, runs the configured script over it, and hands back the
//! SVG text. Nothing is cached: a plot is cheap next to the mapping that
//! produced it, and the mapping itself is what gets cached.

use std::path::Path;

/// Why a plot could not be produced.
#[derive(Debug)]
pub enum PlotError {
    /// Writing the response, or reading the SVG, failed.
    Io(String),
    /// The interpreter or script is missing, or the script failed.
    Failed(String),
}

impl std::fmt::Display for PlotError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PlotError::Io(what) => write!(f, "{what}"),
            PlotError::Failed(what) => write!(f, "{what}"),
        }
    }
}

/// A plot, and the one-line summary the script printed.
#[derive(Debug)]
pub struct Plot {
    pub svg: String,
    pub summary: String,
}

/// Run `script` over `response` (the JSON envelope of a mapping) and
/// return the SVG it wrote.
pub async fn render(
    python: &str,
    script: &str,
    scratch_dir: &Path,
    response: &serde_json::Value,
    trait_label: &str,
    extra_args: &[&str],
) -> Result<Plot, PlotError> {
    std::fs::create_dir_all(scratch_dir)
        .map_err(|e| PlotError::Io(format!("{}: {e}", scratch_dir.display())))?;
    let unique = format!(
        "{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );
    let json_path = scratch_dir.join(format!("{unique}-plot.json"));
    let svg_path = scratch_dir.join(format!("{unique}-plot.svg"));
    std::fs::write(
        &json_path,
        serde_json::to_vec(response).map_err(|e| PlotError::Io(e.to_string()))?,
    )
    .map_err(|e| PlotError::Io(format!("{}: {e}", json_path.display())))?;

    let mut command = tokio::process::Command::new(python);
    command
        .arg(script)
        .arg(&json_path)
        .arg("-o")
        .arg(&svg_path)
        .arg("--trait")
        .arg(trait_label)
        .args(extra_args);
    let output = command.output().await.map_err(|e| {
        PlotError::Failed(format!(
            "could not run {python} {script} (is the plotter configured? see PLOT_PYTHON, \
             RQTL_PLOTTER, GEMMA_PLOTTER): {e}"
        ))
    })?;
    let summary = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let svg = if output.status.success() {
        std::fs::read_to_string(&svg_path)
            .map_err(|e| PlotError::Io(format!("{}: {e}", svg_path.display())))?
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(PlotError::Failed(format!(
            "{script} failed: {}",
            stderr.trim()
        )));
    };
    let _ = std::fs::remove_file(&json_path);
    let _ = std::fs::remove_file(&svg_path);
    Ok(Plot { svg, summary })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_missing_script_is_a_failed_plot_not_a_panic() {
        let dir = std::env::temp_dir().join(format!("gn4-plot-{}", std::process::id()));
        let error = render(
            "python3",
            "scripts/does-not-exist.py",
            &dir,
            &serde_json::json!({"data": {}}),
            "t",
            &[],
        )
        .await
        .unwrap_err();
        assert!(matches!(error, PlotError::Failed(_)), "{error}");
        assert!(error.to_string().contains("failed"), "{error}");
        let _ = std::fs::remove_dir_all(&dir);
    }
}