use crate::digest::ManifestDigest;
use crate::error::{PackageError, Result};
use oci_spec::image::{
Descriptor, ImageIndex, ImageIndexBuilder, ImageManifest, MediaType, SCHEMA_VERSION,
};
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
const OCI_LAYOUT_FILE_CONTENTS: &str = r#"{"imageLayoutVersion":"1.0.0"}"#;
#[derive(Debug, Clone)]
pub struct OciLayout {
root: PathBuf,
}
impl OciLayout {
pub fn create(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
fs::create_dir_all(blobs_sha256_dir(&root))?;
let layout = Self { root };
fs::write(layout.root.join("oci-layout"), OCI_LAYOUT_FILE_CONTENTS)?;
let empty_index = ImageIndexBuilder::default()
.schema_version(SCHEMA_VERSION)
.manifests(Vec::<Descriptor>::new())
.build()
.map_err(|e| PackageError::Layout {
reason: format!("failed to build empty ImageIndex: {e}"),
})?;
layout.write_index(&empty_index)?;
Ok(layout)
}
pub fn open(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn describe_blob(media_type: MediaType, bytes: &[u8]) -> Descriptor {
let digest = ManifestDigest::from_bytes(bytes);
Descriptor::new(media_type, bytes.len() as u64, oci_digest(&digest))
}
pub fn write_blob(&self, media_type: MediaType, bytes: &[u8]) -> Result<Descriptor> {
let descriptor = Self::describe_blob(media_type, bytes);
let digest = ManifestDigest::try_from(descriptor.digest())?;
let path = self.blob_path(&digest)?;
fs::write(&path, bytes)?;
Ok(descriptor)
}
pub fn read_blob(&self, descriptor: &Descriptor) -> Result<Vec<u8>> {
let digest = ManifestDigest::try_from(descriptor.digest())?;
let path = self.blob_path(&digest)?;
let bytes = fs::read(&path).map_err(|e| PackageError::Layout {
reason: format!("failed to read blob {}: {e}", path.display()),
})?;
Ok(bytes)
}
pub fn write_index(&self, index: &ImageIndex) -> Result<()> {
let bytes = serde_json::to_vec(index)?;
fs::write(self.root.join("index.json"), bytes)?;
Ok(())
}
pub fn read_index(&self) -> Result<ImageIndex> {
let bytes = fs::read(self.root.join("index.json")).map_err(|e| PackageError::Layout {
reason: format!("failed to read index.json: {e}"),
})?;
let index = serde_json::from_slice(&bytes)?;
Ok(index)
}
pub fn write_manifest(&self, manifest_bytes: &[u8]) -> Result<Descriptor> {
self.write_blob(MediaType::ImageManifest, manifest_bytes)
}
pub fn read_manifest(&self, descriptor: &Descriptor) -> Result<ImageManifest> {
let bytes = self.read_blob(descriptor)?;
let manifest = serde_json::from_slice(&bytes)?;
Ok(manifest)
}
fn blob_path(&self, digest: &ManifestDigest) -> Result<PathBuf> {
let hex = digest
.as_str()
.strip_prefix("sha256:")
.ok_or_else(|| PackageError::Layout {
reason: format!("expected a sha256 digest, got: {digest}"),
})?;
let dir = blobs_sha256_dir(&self.root);
let path = dir.join(hex);
if !path.starts_with(&dir) {
return Err(PackageError::Layout {
reason: format!("blob path {path:?} escaped layout root {dir:?}"),
});
}
Ok(path)
}
}
fn blobs_sha256_dir(root: &Path) -> PathBuf {
root.join("blobs").join("sha256")
}
fn oci_digest(digest: &ManifestDigest) -> oci_spec::image::Digest {
oci_spec::image::Digest::from_str(digest.as_str())
.expect("ManifestDigest always parses as a valid oci_spec::image::Digest")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::oci::media_types::{EMPTY_CONFIG_BLOB, EMPTY_CONFIG_DIGEST, MT_EMPTY_CONFIG};
#[test]
fn create_writes_oci_layout_marker_file_and_empty_index() {
let dir = tempfile::tempdir().unwrap();
let layout = OciLayout::create(dir.path()).unwrap();
let oci_layout_contents = fs::read_to_string(dir.path().join("oci-layout")).unwrap();
assert_eq!(oci_layout_contents, OCI_LAYOUT_FILE_CONTENTS);
let index = layout.read_index().unwrap();
assert_eq!(index.manifests().len(), 0);
assert_eq!(index.schema_version(), SCHEMA_VERSION);
assert!(dir.path().join("blobs").join("sha256").is_dir());
}
#[test]
fn write_blob_then_read_blob_round_trips_byte_identical() {
let dir = tempfile::tempdir().unwrap();
let layout = OciLayout::create(dir.path()).unwrap();
let bytes = b"hello oci layout";
let descriptor = layout
.write_blob(
MediaType::Other("application/vnd.pmcp.test.v1+json".to_string()),
bytes,
)
.unwrap();
let expected_digest = ManifestDigest::from_bytes(bytes);
let hex = expected_digest.as_str().strip_prefix("sha256:").unwrap();
let blob_path = dir.path().join("blobs").join("sha256").join(hex);
assert!(
blob_path.is_file(),
"blob must be written under blobs/sha256/<hex>"
);
let read_back = layout.read_blob(&descriptor).unwrap();
assert_eq!(read_back, bytes);
assert_eq!(descriptor.digest().to_string(), expected_digest.as_str());
assert_eq!(descriptor.size(), bytes.len() as u64);
}
#[test]
fn describe_blob_returns_the_same_descriptor_write_blob_does() {
let dir = tempfile::tempdir().unwrap();
let layout = OciLayout::create(dir.path()).unwrap();
let media_type = MediaType::Other("application/vnd.pmcp.test.v1+json".to_string());
let bytes = b"the pure and the writing path must agree";
let described = OciLayout::describe_blob(media_type.clone(), bytes);
let written = layout.write_blob(media_type, bytes).unwrap();
assert_eq!(
described, written,
"describe_blob and write_blob must return equal descriptors for equal inputs"
);
}
#[test]
fn write_manifest_then_read_manifest_round_trips() {
let dir = tempfile::tempdir().unwrap();
let layout = OciLayout::create(dir.path()).unwrap();
let config = layout
.write_blob(MediaType::from(MT_EMPTY_CONFIG), EMPTY_CONFIG_BLOB)
.unwrap();
let layer = layout
.write_blob(
MediaType::Other("application/vnd.pmcp.test.v1+json".to_string()),
b"{}",
)
.unwrap();
let manifest = oci_spec::image::ImageManifestBuilder::default()
.schema_version(SCHEMA_VERSION)
.config(config)
.layers(vec![layer])
.build()
.unwrap();
let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
let manifest_descriptor = layout.write_manifest(&manifest_bytes).unwrap();
let read_back = layout.read_manifest(&manifest_descriptor).unwrap();
assert_eq!(read_back, manifest);
}
#[test]
fn empty_config_blob_digest_constant_matches_from_bytes_hash() {
let digest = ManifestDigest::from_bytes(EMPTY_CONFIG_BLOB);
assert_eq!(digest.as_str(), EMPTY_CONFIG_DIGEST);
}
}