Skip to main content

rig_evals/
sink.rs

1//! Where reports go.
2
3use std::io::Write as _;
4use std::path::{Path, PathBuf};
5
6use rig_core::error::BoxError;
7use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
8
9use crate::Report;
10
11/// Receives an experiment's report when it finishes.
12pub trait Sink: WasmCompatSend + WasmCompatSync {
13    /// Record `report`.
14    fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>>;
15}
16
17/// Why a sink could not record a report.
18#[derive(Debug, thiserror::Error)]
19#[non_exhaustive]
20pub enum SinkError {
21    /// A file could not be written.
22    #[error("cannot write {path}: {source}")]
23    Write {
24        /// The file.
25        path: PathBuf,
26        /// The I/O error.
27        source: std::io::Error,
28    },
29    /// Standard output could not be written.
30    #[error("cannot write to stdout: {0}")]
31    Stdout(std::io::Error),
32    /// The report could not be serialized.
33    #[error("cannot serialize the report: {0}")]
34    Serialize(#[from] serde_json::Error),
35    /// Any other failure, such as a remote service's.
36    #[error(transparent)]
37    Other(BoxError),
38}
39
40/// Write `contents` to `path`, creating its directory.
41fn write(path: &Path, contents: &str) -> Result<(), SinkError> {
42    let written = match path.parent() {
43        Some(dir) if !dir.as_os_str().is_empty() => std::fs::create_dir_all(dir),
44        _ => Ok(()),
45    }
46    .and_then(|()| std::fs::write(path, contents));
47    written.map_err(|source| SinkError::Write {
48        path: path.to_owned(),
49        source,
50    })
51}
52
53/// Writes the report as JSON ([`Report::to_json`]) to a file.
54#[derive(Debug, Clone)]
55pub struct JsonFile(PathBuf);
56
57impl JsonFile {
58    /// Write to `path`, creating its directory.
59    pub fn new(path: impl Into<PathBuf>) -> Self {
60        Self(path.into())
61    }
62}
63
64impl Sink for JsonFile {
65    fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>> {
66        Box::pin(async move { write(&self.0, &report.to_json()?) })
67    }
68}
69
70/// Writes the report as JUnit XML ([`Report::to_junit`]) to a file, for CI
71/// test reports.
72#[derive(Debug, Clone)]
73pub struct JunitFile(PathBuf);
74
75impl JunitFile {
76    /// Write to `path`, creating its directory.
77    pub fn new(path: impl Into<PathBuf>) -> Self {
78        Self(path.into())
79    }
80}
81
82impl Sink for JunitFile {
83    fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>> {
84        Box::pin(async move { write(&self.0, &report.to_junit()) })
85    }
86}
87
88/// Writes the report as Markdown ([`Report::to_markdown`]) to a file (such as
89/// `$GITHUB_STEP_SUMMARY`) or to standard output.
90#[derive(Debug, Clone)]
91pub struct Markdown(Option<PathBuf>);
92
93impl Markdown {
94    /// Write to `path`, creating its directory.
95    pub fn file(path: impl Into<PathBuf>) -> Self {
96        Self(Some(path.into()))
97    }
98
99    /// Print to standard output.
100    pub fn stdout() -> Self {
101        Self(None)
102    }
103}
104
105impl Sink for Markdown {
106    fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>> {
107        Box::pin(async move {
108            let markdown = report.to_markdown();
109            match &self.0 {
110                Some(path) => write(path, &markdown),
111                None => std::io::stdout()
112                    .lock()
113                    .write_all(markdown.as_bytes())
114                    .map_err(SinkError::Stdout),
115            }
116        })
117    }
118}