registry_testkit/
storage.rs

1use crate::config::StorageBackend;
2use crate::error::{RegistryError, Result};
3use async_trait::async_trait;
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::sync::Arc;
7use tokio::fs;
8use tokio::sync::RwLock;
9
10#[derive(Clone)]
11pub struct ManifestEntry {
12    pub data: Vec<u8>,
13    pub content_type: String,
14}
15
16#[async_trait]
17pub trait Storage: Send + Sync {
18    async fn store_manifest(&self, key: String, entry: ManifestEntry) -> Result<()>;
19    async fn get_manifest(&self, key: &str) -> Result<Option<ManifestEntry>>;
20    async fn store_blob(&self, digest: String, data: Vec<u8>) -> Result<()>;
21    async fn get_blob(&self, digest: &str) -> Result<Option<Vec<u8>>>;
22    async fn create_upload(&self, uuid: String) -> Result<()>;
23    async fn append_upload(&self, uuid: &str, data: &[u8]) -> Result<()>;
24    async fn finish_upload(&self, uuid: &str) -> Result<Option<Vec<u8>>>;
25}
26
27#[derive(Default)]
28pub struct MemoryStorage {
29    manifests: Arc<RwLock<HashMap<String, ManifestEntry>>>,
30    blobs: Arc<RwLock<HashMap<String, Vec<u8>>>>,
31    uploads: Arc<RwLock<HashMap<String, Vec<u8>>>>,
32}
33
34impl MemoryStorage {
35    pub fn new() -> Self {
36        Self::default()
37    }
38}
39
40#[async_trait::async_trait]
41impl Storage for MemoryStorage {
42    async fn store_manifest(&self, key: String, entry: ManifestEntry) -> Result<()> {
43        self.manifests.write().await.insert(key, entry);
44        Ok(())
45    }
46
47    async fn get_manifest(&self, key: &str) -> Result<Option<ManifestEntry>> {
48        Ok(self.manifests.read().await.get(key).cloned())
49    }
50
51    async fn store_blob(&self, digest: String, data: Vec<u8>) -> Result<()> {
52        self.blobs.write().await.insert(digest, data);
53        Ok(())
54    }
55
56    async fn get_blob(&self, digest: &str) -> Result<Option<Vec<u8>>> {
57        Ok(self.blobs.read().await.get(digest).cloned())
58    }
59
60    async fn create_upload(&self, uuid: String) -> Result<()> {
61        self.uploads.write().await.insert(uuid, Vec::new());
62        Ok(())
63    }
64
65    async fn append_upload(&self, uuid: &str, data: &[u8]) -> Result<()> {
66        if let Some(upload) = self.uploads.write().await.get_mut(uuid) {
67            upload.extend_from_slice(data);
68            Ok(())
69        } else {
70            Err(RegistryError::UploadNotFound(uuid.to_string()))
71        }
72    }
73
74    async fn finish_upload(&self, uuid: &str) -> Result<Option<Vec<u8>>> {
75        Ok(self.uploads.write().await.remove(uuid))
76    }
77}
78
79pub struct DiskStorage {
80    base_path: PathBuf,
81    _temp_dir: Option<tempfile::TempDir>,
82}
83
84impl DiskStorage {
85    pub async fn new(path: PathBuf) -> Result<Self> {
86        fs::create_dir_all(&path).await?;
87        fs::create_dir_all(path.join("manifests")).await?;
88        fs::create_dir_all(path.join("blobs")).await?;
89        fs::create_dir_all(path.join("uploads")).await?;
90
91        Ok(Self {
92            base_path: path,
93            _temp_dir: None,
94        })
95    }
96
97    pub async fn temp() -> Result<Self> {
98        let temp_dir = tempfile::tempdir()?;
99        let path = temp_dir.path().to_path_buf();
100
101        fs::create_dir_all(path.join("manifests")).await?;
102        fs::create_dir_all(path.join("blobs")).await?;
103        fs::create_dir_all(path.join("uploads")).await?;
104
105        Ok(Self {
106            base_path: path,
107            _temp_dir: Some(temp_dir),
108        })
109    }
110
111    fn manifest_path(&self, key: &str) -> PathBuf {
112        let safe_key = key.replace(['/', ':'], "_");
113        self.base_path
114            .join("manifests")
115            .join(format!("{}.json", safe_key))
116    }
117
118    fn manifest_meta_path(&self, key: &str) -> PathBuf {
119        let safe_key = key.replace(['/', ':'], "_");
120        self.base_path
121            .join("manifests")
122            .join(format!("{}.meta", safe_key))
123    }
124
125    fn blob_path(&self, digest: &str) -> PathBuf {
126        let safe_digest = digest.replace(['/', ':'], "_");
127        self.base_path.join("blobs").join(safe_digest)
128    }
129
130    fn upload_path(&self, uuid: &str) -> PathBuf {
131        self.base_path.join("uploads").join(uuid)
132    }
133}
134
135#[async_trait]
136impl Storage for DiskStorage {
137    async fn store_manifest(&self, key: String, entry: ManifestEntry) -> Result<()> {
138        let manifest_path = self.manifest_path(&key);
139        let meta_path = self.manifest_meta_path(&key);
140
141        fs::write(&manifest_path, &entry.data).await?;
142        fs::write(&meta_path, &entry.content_type).await?;
143
144        Ok(())
145    }
146
147    async fn get_manifest(&self, key: &str) -> Result<Option<ManifestEntry>> {
148        let manifest_path = self.manifest_path(key);
149        let meta_path = self.manifest_meta_path(key);
150
151        if !manifest_path.exists() {
152            return Ok(None);
153        }
154
155        let data = fs::read(&manifest_path).await?;
156        let content_type = fs::read_to_string(&meta_path)
157            .await
158            .unwrap_or_else(|_| "application/vnd.docker.distribution.manifest.v2+json".to_string());
159
160        Ok(Some(ManifestEntry { data, content_type }))
161    }
162
163    async fn store_blob(&self, digest: String, data: Vec<u8>) -> Result<()> {
164        let blob_path = self.blob_path(&digest);
165        fs::write(&blob_path, &data).await?;
166        Ok(())
167    }
168
169    async fn get_blob(&self, digest: &str) -> Result<Option<Vec<u8>>> {
170        let blob_path = self.blob_path(digest);
171
172        if !blob_path.exists() {
173            return Ok(None);
174        }
175
176        let data = fs::read(&blob_path).await?;
177        Ok(Some(data))
178    }
179
180    async fn create_upload(&self, uuid: String) -> Result<()> {
181        let upload_path = self.upload_path(&uuid);
182        fs::write(&upload_path, &[]).await?;
183        Ok(())
184    }
185
186    async fn append_upload(&self, uuid: &str, data: &[u8]) -> Result<()> {
187        let upload_path = self.upload_path(uuid);
188
189        if !upload_path.exists() {
190            return Err(RegistryError::UploadNotFound(uuid.to_string()));
191        }
192
193        let mut existing = fs::read(&upload_path).await?;
194        existing.extend_from_slice(data);
195        fs::write(&upload_path, &existing).await?;
196
197        Ok(())
198    }
199
200    async fn finish_upload(&self, uuid: &str) -> Result<Option<Vec<u8>>> {
201        let upload_path = self.upload_path(uuid);
202
203        if !upload_path.exists() {
204            return Ok(None);
205        }
206
207        let data = fs::read(&upload_path).await?;
208        fs::remove_file(&upload_path).await?;
209
210        Ok(Some(data))
211    }
212}
213
214pub async fn create_storage(backend: &StorageBackend) -> Result<Arc<dyn Storage>> {
215    match backend {
216        StorageBackend::Memory => Ok(Arc::new(MemoryStorage::new())),
217        StorageBackend::TempDir => Ok(Arc::new(DiskStorage::temp().await?)),
218        StorageBackend::Directory(path) => Ok(Arc::new(DiskStorage::new(path.clone()).await?)),
219    }
220}