Skip to main content

tsurara_plugin/
lib.rs

1//! Write tsurara plugins in Rust. A plugin is a binary that calls [`run`] with its stages;
2//! tsurara runs it once per run (for example `runtime: [cargo, run, --quiet, --manifest-path]` with
3//! the plugin's `Cargo.toml` as the module) and calls the stages it declares over the session protocol
4//! (`tsurara_backend::session`, design.md 11.2). The inputs use the real types of the model and the
5//! manifest. Embedders of tsurara as a library implement `tsurara_backend::plugin::Plugin` instead.
6
7use serde_json::{Value, json};
8use std::io::{BufRead, Write};
9pub use tsurara_backend::OutputFile;
10pub use tsurara_backend::manifest::Manifest;
11use tsurara_backend::session::{SESSION_PROTOCOL, SessionRequest, Stage};
12pub use tsurara_sem::Model;
13
14/// What the extend stage receives, owned.
15#[derive(Debug, Clone, serde::Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct ExtendInput {
18    pub language: String,
19    pub model: Model,
20    pub manifest: Option<Manifest>,
21    /// The common options of the target (`Options` in its JSON form).
22    pub common: Value,
23    /// The options of the language (for TypeScript the import extension, layout and client module).
24    pub options: Value,
25    /// The first line every added file must start with.
26    pub marker: String,
27}
28
29type Stage1<I, O> = Box<dyn Fn(I) -> Result<O, String>>;
30
31/// A plugin: a name and any of the stages. `transform_document` and `transform_model` work on JSON
32/// values, so that nothing a newer tsurara adds is lost.
33#[derive(Default)]
34pub struct Plugin {
35    pub name: String,
36    pub transform_document: Option<Stage1<Value, Value>>,
37    pub transform_model: Option<Stage1<Value, Value>>,
38    pub extend: Option<Stage1<ExtendInput, Vec<OutputFile>>>,
39    pub transform_files: Option<Stage1<Vec<OutputFile>, Vec<OutputFile>>>,
40}
41
42impl Plugin {
43    pub fn new(name: impl Into<String>) -> Self {
44        Self {
45            name: name.into(),
46            ..Self::default()
47        }
48    }
49
50    fn stages(&self) -> Vec<Stage> {
51        let mut out = Vec::new();
52        if self.transform_document.is_some() {
53            out.push(Stage::TransformDocument);
54        }
55        if self.transform_model.is_some() {
56            out.push(Stage::TransformModel);
57        }
58        if self.extend.is_some() {
59            out.push(Stage::Extend);
60        }
61        if self.transform_files.is_some() {
62            out.push(Stage::TransformFiles);
63        }
64        out
65    }
66
67    fn call(&self, stage: Stage, input: Value) -> Result<Value, String> {
68        let missing = || format!("the plugin has no {} stage", stage.as_str());
69        match stage {
70            Stage::TransformDocument => {
71                (self.transform_document.as_ref().ok_or_else(missing)?)(input)
72            }
73            Stage::TransformModel => (self.transform_model.as_ref().ok_or_else(missing)?)(input),
74            Stage::Extend => {
75                let f = self.extend.as_ref().ok_or_else(missing)?;
76                let input = serde_json::from_value(input).map_err(|e| e.to_string())?;
77                Ok(serde_json::to_value(f(input)?).expect("files serialize"))
78            }
79            Stage::TransformFiles => {
80                let f = self.transform_files.as_ref().ok_or_else(missing)?;
81                let input = serde_json::from_value(input).map_err(|e| e.to_string())?;
82                Ok(serde_json::to_value(f(input)?).expect("files serialize"))
83            }
84        }
85    }
86}
87
88/// Serves the plugin on stdin and stdout until stdin closes.
89pub fn run(plugin: Plugin) {
90    let stdin = std::io::stdin();
91    let mut stdout = std::io::stdout();
92    if let Err(e) = serve(&plugin, stdin.lock(), &mut stdout) {
93        eprintln!("{e}");
94        std::process::exit(1);
95    }
96}
97
98/// Serves the plugin on `input` and `output` until `input` ends.
99pub fn serve(plugin: &Plugin, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
100    for line in input.lines() {
101        let line = line?;
102        if line.trim().is_empty() {
103            continue;
104        }
105        let request: SessionRequest = serde_json::from_str(&line)
106            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
107        let answer = match request {
108            SessionRequest::Hello { .. } => json!({
109                "type": "hello",
110                "protocol": SESSION_PROTOCOL,
111                "name": plugin.name,
112                "stages": plugin.stages(),
113            }),
114            SessionRequest::Call { stage, input } => match plugin.call(stage, input) {
115                Ok(out) => json!({ "type": "result", "output": out }),
116                Err(message) => json!({ "type": "error", "message": message }),
117            },
118        };
119        writeln!(output, "{answer}")?;
120        output.flush()?;
121    }
122    Ok(())
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn serves_hello_and_calls() {
131        let mut plugin = Plugin::new("files");
132        plugin.transform_files = Some(Box::new(|mut files| {
133            files.push(OutputFile {
134                path: "a.txt".into(),
135                contents: "x".into(),
136            });
137            Ok(files)
138        }));
139        let input = "{\"type\":\"hello\",\"protocol\":1}\n{\"type\":\"call\",\"stage\":\"transformFiles\",\"input\":[]}\n{\"type\":\"call\",\"stage\":\"extend\",\"input\":{}}\n";
140        let mut out = Vec::new();
141        serve(&plugin, input.as_bytes(), &mut out).unwrap();
142        let lines: Vec<Value> = String::from_utf8(out)
143            .unwrap()
144            .lines()
145            .map(|l| serde_json::from_str(l).unwrap())
146            .collect();
147        assert_eq!(lines[0]["stages"], json!(["transformFiles"]));
148        assert_eq!(lines[1]["output"][0]["path"], "a.txt");
149        assert_eq!(lines[2]["type"], "error");
150    }
151}