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