qualia_core_db/medical/dicom_source/
storage.rs1use std::{
2 fs::{self, File},
3 io::{self, Read, Write},
4 path::{Path, PathBuf},
5};
6
7#[derive(Clone, Copy, Debug)]
10pub struct DicomSourceBudget {
11 pub max_source_bytes: usize,
12}
13impl Default for DicomSourceBudget {
14 fn default() -> Self {
15 Self {
16 max_source_bytes: 256 * 1024 * 1024,
17 }
18 }
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct DicomSourceArtifact {
23 pub blake3: [u8; 32],
25 pub byte_length: u64,
26 pub path: PathBuf,
27}
28
29#[derive(Debug)]
30pub enum DicomSourceError {
31 Io(io::Error),
32 BudgetExceeded,
33 Conflict,
34 InvalidPath,
35 InvalidAssociation,
36 NotPart10,
37}
38impl From<io::Error> for DicomSourceError {
39 fn from(e: io::Error) -> Self {
40 Self::Io(e)
41 }
42}
43impl std::fmt::Display for DicomSourceError {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 Self::Io(e) => write!(f, "DICOM source IO: {e}"),
47 Self::BudgetExceeded => write!(f, "DICOM source exceeds admission budget"),
48 Self::Conflict => write!(f, "DICOM source artifact conflicts with existing bytes"),
49 Self::InvalidPath => write!(f, "DICOM source path escapes or redirects storage root"),
50 Self::InvalidAssociation => write!(f, "invalid DICOM source association"),
51 Self::NotPart10 => write!(f, "DICOM source lacks the Part-10 DICM marker"),
52 }
53 }
54}
55impl std::error::Error for DicomSourceError {}
56
57pub(super) fn read_source(
58 path: &Path,
59 budget: DicomSourceBudget,
60) -> Result<Vec<u8>, DicomSourceError> {
61 let mut file = File::open(path)?;
62 let len =
63 usize::try_from(file.metadata()?.len()).map_err(|_| DicomSourceError::BudgetExceeded)?;
64 if len > budget.max_source_bytes {
65 return Err(DicomSourceError::BudgetExceeded);
66 }
67 let mut bytes = Vec::new();
68 bytes
69 .try_reserve_exact(len)
70 .map_err(|_| DicomSourceError::BudgetExceeded)?;
71 let mut chunk = [0u8; 64 * 1024];
72 loop {
73 let read = file.read(&mut chunk)?;
74 if read == 0 {
75 break;
76 }
77 let total = bytes
78 .len()
79 .checked_add(read)
80 .ok_or(DicomSourceError::BudgetExceeded)?;
81 if total > budget.max_source_bytes {
82 return Err(DicomSourceError::BudgetExceeded);
83 }
84 bytes
85 .try_reserve_exact(read)
86 .map_err(|_| DicomSourceError::BudgetExceeded)?;
87 bytes.extend_from_slice(&chunk[..read]);
88 }
89 Ok(bytes)
90}
91
92pub(super) fn directory(root: &Path, name: &str) -> Result<PathBuf, DicomSourceError> {
94 fs::create_dir_all(root)?;
95 let root = root.canonicalize()?;
96 let imaging = checked_child(&root, "Imaging")?;
97 checked_child(&imaging, name)
98}
99fn checked_child(parent: &Path, name: &str) -> Result<PathBuf, DicomSourceError> {
100 let path = parent.join(name);
101 match fs::create_dir(&path) {
102 Ok(()) => {}
103 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
104 Err(e) => return Err(e.into()),
105 }
106 let meta = fs::symlink_metadata(&path)?;
107 if meta.file_type().is_symlink() || !meta.is_dir() {
108 return Err(DicomSourceError::InvalidPath);
109 }
110 let canonical = path.canonicalize()?;
111 if canonical.parent() != Some(parent) {
112 return Err(DicomSourceError::InvalidPath);
113 }
114 Ok(canonical)
115}
116
117pub(super) fn object_path(root: &Path, digest: &[u8; 32]) -> Result<PathBuf, DicomSourceError> {
118 let name = blake3::Hash::from(*digest).to_hex();
119 Ok(directory(root, "dicom_sources")?.join(format!("{name}.dcm")))
120}
121
122fn regular_file(path: &Path) -> Result<File, DicomSourceError> {
123 let meta = fs::symlink_metadata(path)?;
124 if meta.file_type().is_symlink() || !meta.is_file() {
125 return Err(DicomSourceError::InvalidPath);
126 }
127 Ok(File::open(path)?)
128}
129
130pub(super) fn publish_exact(path: &Path, bytes: &[u8]) -> Result<(), DicomSourceError> {
133 let parent = path.parent().ok_or(DicomSourceError::InvalidPath)?;
134 let mut staging = tempfile::NamedTempFile::new_in(parent)?;
135 staging.write_all(bytes)?;
136 staging.as_file().sync_all()?;
137 match staging.persist_noclobber(path) {
138 Ok(_) => Ok(()),
139 Err(e) if e.error.kind() == io::ErrorKind::AlreadyExists => {
140 let mut file = regular_file(path)?;
142 if file.metadata()?.len() != bytes.len() as u64 {
143 return Err(DicomSourceError::Conflict);
144 }
145 let mut chunk = [0u8; 64 * 1024];
146 for expected in bytes.chunks(chunk.len()) {
147 file.read_exact(&mut chunk[..expected.len()])?;
148 if &chunk[..expected.len()] != expected {
149 return Err(DicomSourceError::Conflict);
150 }
151 }
152 if file.read(&mut chunk[..1])? != 0 {
153 return Err(DicomSourceError::Conflict);
154 }
155 Ok(())
156 }
157 Err(e) => Err(e.error.into()),
158 }
159}
160
161pub(super) fn preserve(
162 root: &Path,
163 bytes: &[u8],
164 budget: DicomSourceBudget,
165) -> Result<DicomSourceArtifact, DicomSourceError> {
166 if bytes.len() > budget.max_source_bytes {
167 return Err(DicomSourceError::BudgetExceeded);
168 }
169 let digest = *blake3::hash(bytes).as_bytes();
170 let path = object_path(root, &digest)?;
171 publish_exact(&path, bytes)?;
172 verify(root, digest, bytes.len() as u64, budget)
173}
174
175pub(super) fn verify(
176 root: &Path,
177 digest: [u8; 32],
178 length: u64,
179 budget: DicomSourceBudget,
180) -> Result<DicomSourceArtifact, DicomSourceError> {
181 if length > budget.max_source_bytes as u64 {
182 return Err(DicomSourceError::BudgetExceeded);
183 }
184 let path = object_path(root, &digest)?;
185 let mut file = regular_file(&path)?;
186 if file.metadata()?.len() != length {
187 return Err(DicomSourceError::Conflict);
188 }
189 let mut hasher = blake3::Hasher::new();
190 let mut chunk = [0u8; 64 * 1024];
191 let mut total = 0u64;
192 loop {
193 let n = file.read(&mut chunk)?;
194 if n == 0 {
195 break;
196 }
197 total = total
198 .checked_add(n as u64)
199 .ok_or(DicomSourceError::BudgetExceeded)?;
200 if total > length {
201 return Err(DicomSourceError::Conflict);
202 }
203 hasher.update(&chunk[..n]);
204 }
205 if total != length || hasher.finalize().as_bytes() != &digest {
206 return Err(DicomSourceError::Conflict);
207 }
208 Ok(DicomSourceArtifact {
209 blake3: digest,
210 byte_length: length,
211 path,
212 })
213}
214
215pub(super) fn read_association(path: &Path) -> Result<Vec<u8>, DicomSourceError> {
216 let file = regular_file(path)?;
217 if file.metadata()?.len() > 2048 {
219 return Err(DicomSourceError::InvalidAssociation);
220 }
221 let mut bytes = Vec::new();
222 file.take(2049).read_to_end(&mut bytes)?;
223 if bytes.len() > 2048 {
224 return Err(DicomSourceError::InvalidAssociation);
225 }
226 Ok(bytes)
227}
228
229pub fn archive_part10_source(
234 storage_root: &Path,
235 source_path: &Path,
236 budget: DicomSourceBudget,
237) -> Result<DicomSourceArtifact, DicomSourceError> {
238 let bytes = read_source(source_path, budget)?;
239 if !crate::dicom::is_dicom_part10(&bytes) {
240 return Err(DicomSourceError::NotPart10);
241 }
242 preserve(storage_root, &bytes, budget)
243}