use pyo3::{exceptions::PyOSError, prelude::*, types::PyBytes};
use std::{io::Read, path::Path, sync::Mutex};
fn error(e: impl std::fmt::Display) -> PyErr {
PyOSError::new_err(e.to_string())
}
#[pyclass]
struct Archive(crate::artifact::RunArchive);
#[pymethods]
impl Archive {
#[new]
fn new(py: Python<'_>, location: &str, run_id: &str) -> PyResult<Self> {
py.detach(|| {
let location = serde_json::from_str(location).map_err(error)?;
Ok(Self(crate::open_run(&location, run_id).map_err(error)?))
})
}
fn manifest(&self, py: Python<'_>) -> PyResult<String> {
py.detach(|| serde_json::to_string(self.0.manifest()).map_err(error))
}
fn verify(&self, py: Python<'_>, key: &str) -> PyResult<()> {
py.detach(|| self.0.verify(key).map_err(error))
}
fn reader(&self, py: Python<'_>, key: &str) -> PyResult<ArtifactReader> {
py.detach(|| {
Ok(ArtifactReader(Mutex::new(
self.0.reader(key).map_err(error)?,
)))
})
}
fn materialize(
&self,
py: Python<'_>,
prefix: &str,
cache: &str,
max_bytes: u64,
) -> PyResult<Lease> {
py.detach(|| {
Ok(Lease(Some(
self.0
.materialize(prefix, Path::new(cache), max_bytes)
.map_err(error)?,
)))
})
}
}
#[pyclass]
struct ArtifactReader(Mutex<Box<dyn Read + Send>>);
#[pymethods]
impl ArtifactReader {
fn read<'py>(&self, py: Python<'py>, size: usize) -> PyResult<Bound<'py, PyBytes>> {
if size > 8 * 1024 * 1024 {
return Err(error("read size exceeds 8 MiB; stream in bounded chunks"));
}
let bytes = py.detach(|| -> PyResult<Vec<u8>> {
let mut bytes = vec![0; size];
let n = self
.0
.lock()
.map_err(error)?
.read(&mut bytes)
.map_err(error)?;
bytes.truncate(n);
Ok(bytes)
})?;
Ok(PyBytes::new(py, &bytes))
}
}
#[pyclass]
struct Lease(Option<crate::artifact::MaterializationLease>);
#[pymethods]
impl Lease {
fn path(&self) -> PyResult<String> {
self.0
.as_ref()
.map(|l| l.path().to_string_lossy().into_owned())
.ok_or_else(|| error("materialization lease is closed"))
}
fn close(&mut self, py: Python<'_>) {
py.detach(|| {
self.0.take();
});
}
}
#[pyfunction]
fn open_reference(py: Python<'_>, location: &str, reference: &str) -> PyResult<ArtifactReader> {
py.detach(|| {
let location = serde_json::from_str(location).map_err(error)?;
let reference = serde_json::from_str(reference).map_err(error)?;
Ok(ArtifactReader(Mutex::new(
crate::artifact::open_reference(&location, &reference).map_err(error)?,
)))
})
}
#[pymodule]
fn _native(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(open_reference, module)?)?;
module.add_class::<Archive>()?;
module.add_class::<ArtifactReader>()?;
module.add_class::<Lease>()?;
Ok(())
}