1use std::{
2 fs,
3 io::{self, Read, Write},
4 path::{Component, Path, PathBuf},
5 string::ToString,
6 sync::{Arc, LazyLock, Mutex},
7};
8
9use gen_core::{HashId, Workspace, calculate_hash};
10use opendal::{blocking, services};
11use sha2::{Digest, Sha256};
12use url::{Position, Url};
13
14use crate::{
15 errors::{FileAdditionError, FileStoreError},
16 operations::{FileAddition, calculate_reader_checksum},
17};
18
19static OPENDAL_RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
20 tokio::runtime::Builder::new_multi_thread()
21 .enable_all()
22 .build()
23 .expect("failed to build OpenDAL runtime")
24});
25
26fn with_opendal_runtime<T>(f: impl FnOnce() -> T) -> T {
27 let _guard = OPENDAL_RUNTIME.enter();
28 f()
29}
30
31fn opendal_file_addition_error(err: opendal::Error) -> FileAdditionError {
32 FileAdditionError::FileReadError(io::Error::other(err))
33}
34
35fn opendal_file_store_error(err: opendal::Error) -> FileStoreError {
36 FileStoreError::IoError(io::Error::other(err))
37}
38
39#[doc(hidden)]
40pub struct OpenDalLocation {
41 operator: blocking::Operator,
42 path: String,
43}
44
45struct ChecksumState {
46 hasher: Sha256,
47 checksum: Option<HashId>,
48 complete: bool,
49}
50
51#[derive(Clone)]
52pub struct ChecksumHandle {
53 state: Arc<Mutex<ChecksumState>>,
54}
55
56impl ChecksumHandle {
57 pub fn checksum(&self) -> Option<HashId> {
58 let state = self.state.lock().unwrap();
59 if state.complete { state.checksum } else { None }
60 }
61
62 pub fn finalized_checksum(&self) -> Option<HashId> {
63 self.state.lock().unwrap().checksum
64 }
65}
66
67pub struct ChecksummedReader {
68 inner: Box<dyn Read>,
69 state: Arc<Mutex<ChecksumState>>,
70}
71
72impl ChecksummedReader {
73 fn new(inner: Box<dyn Read>) -> Self {
74 Self {
75 inner,
76 state: Arc::new(Mutex::new(ChecksumState {
77 hasher: Sha256::new(),
78 checksum: None,
79 complete: false,
80 })),
81 }
82 }
83
84 pub fn checksum_handle(&self) -> ChecksumHandle {
85 ChecksumHandle {
86 state: Arc::clone(&self.state),
87 }
88 }
89}
90
91impl Read for ChecksummedReader {
92 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
93 let bytes_read = self.inner.read(buf)?;
94 let mut state = self.state.lock().unwrap();
95 if bytes_read == 0 {
96 if state.checksum.is_none() {
97 let finalized = state.hasher.clone().finalize();
98 state.checksum = Some(HashId(finalized.into()));
99 }
100 state.complete = true;
101 } else {
102 state.hasher.update(&buf[..bytes_read]);
103 }
104 Ok(bytes_read)
105 }
106}
107
108impl Drop for ChecksummedReader {
109 fn drop(&mut self) {
110 let mut state = self.state.lock().unwrap();
111 if state.checksum.is_none() {
112 let finalized = state.hasher.clone().finalize();
113 state.checksum = Some(HashId(finalized.into()));
114 }
115 }
116}
117
118impl OpenDalLocation {
119 fn new_fs(root: &Path, path: &Path) -> Result<Self, opendal::Error> {
120 let path = path
121 .strip_prefix(Path::new("/"))
122 .unwrap_or(path)
123 .to_string_lossy()
124 .to_string();
125 let operator = with_opendal_runtime(|| {
126 let builder = services::Fs::default().root(&root.to_string_lossy());
127 let op = opendal::Operator::new(builder)?.finish();
128 blocking::Operator::new(op)
129 })?;
130
131 Ok(Self { operator, path })
132 }
133
134 fn from_workspace_path(workspace: &Workspace, path: &Path) -> Result<Self, opendal::Error> {
135 let repo_root = workspace.repo_root().map_err(|err| {
136 opendal::Error::new(opendal::ErrorKind::Unexpected, "repo_root failed").set_source(err)
137 })?;
138
139 if path.is_absolute() {
140 Self::new_fs(Path::new("/"), path)
141 } else {
142 Self::new_fs(&repo_root, path)
143 }
144 }
145
146 fn from_absolute_path(path: &Path) -> Result<Self, opendal::Error> {
147 if !path.is_absolute() {
148 return Err(opendal::Error::new(
149 opendal::ErrorKind::Unexpected,
150 "local path must be absolute",
151 ));
152 }
153
154 Self::new_fs(Path::new("/"), path)
155 }
156
157 fn from_remote_uri(asset_uri: &str) -> Result<Self, FileAdditionError> {
158 let url = Url::parse(asset_uri)
159 .map_err(|err| FileAdditionError::FileReadError(io::Error::other(err)))?;
160
161 if url.scheme().eq_ignore_ascii_case("s3") {
162 let bucket = url.host_str().ok_or_else(|| {
163 FileAdditionError::FileReadError(io::Error::new(
164 io::ErrorKind::InvalidInput,
165 format!("s3 uri is missing bucket: {asset_uri}"),
166 ))
167 })?;
168
169 let operator = with_opendal_runtime(|| {
170 let builder = services::S3::default().bucket(bucket).allow_anonymous();
171 let op = opendal::Operator::new(builder)?.finish();
172 blocking::Operator::new(op)
173 })
174 .map_err(opendal_file_addition_error)?;
175
176 return Ok(Self {
177 operator,
178 path: url.path().trim_start_matches('/').to_string(),
179 });
180 }
181
182 let operator_uri = url[..Position::BeforePath].to_string();
183 opendal::init_default_registry();
184 let operator = with_opendal_runtime(|| blocking::Operator::from_uri(operator_uri.as_str()))
185 .map_err(opendal_file_addition_error)?;
186
187 Ok(Self {
188 operator,
189 path: url.path().trim_start_matches('/').to_string(),
190 })
191 }
192
193 fn reader(self) -> Result<ChecksummedReader, FileAdditionError> {
194 let reader = self
195 .operator
196 .reader(&self.path)
197 .map_err(opendal_file_addition_error)?
198 .into_std_read(..)
199 .map_err(opendal_file_addition_error)?;
200 Ok(ChecksummedReader::new(Box::new(reader)))
201 }
202
203 fn checksum(&self, display_path: &str) -> Result<HashId, FileAdditionError> {
204 let reader = match self.operator.reader(&self.path) {
205 Ok(reader) => reader,
206 Err(err) => {
207 return match err.kind() {
208 opendal::ErrorKind::NotFound => Ok(HashId::convert_str("non-existent")),
209 opendal::ErrorKind::PermissionDenied => Err(
210 FileAdditionError::FilePermissionDenied(display_path.to_string()),
211 ),
212 _ => Err(opendal_file_addition_error(err)),
213 };
214 }
215 }
216 .into_std_read(..)
217 .map_err(opendal_file_addition_error)?;
218
219 match calculate_reader_checksum(reader) {
220 Ok(checksum) => Ok(checksum),
221 Err(err) => match err.kind() {
222 io::ErrorKind::NotFound => Ok(HashId::convert_str("non-existent")),
223 io::ErrorKind::PermissionDenied => Err(FileAdditionError::FilePermissionDenied(
224 display_path.to_string(),
225 )),
226 _ => Err(FileAdditionError::FileReadError(err)),
227 },
228 }
229 }
230
231 fn copy_to_local_path(
232 &self,
233 workspace: &Workspace,
234 destination_path: &Path,
235 ) -> io::Result<u64> {
236 let asset_location =
237 Self::from_workspace_path(workspace, destination_path).map_err(io::Error::other)?;
238 let mut reader = self
239 .operator
240 .reader(&self.path)
241 .map_err(io::Error::other)?
242 .into_std_read(..)
243 .map_err(io::Error::other)?;
244 let mut writer = asset_location
245 .operator
246 .writer(&asset_location.path)
247 .map_err(io::Error::other)?
248 .into_std_write();
249 let bytes_copied = io::copy(&mut reader, &mut writer)?;
250 writer.close()?;
251 Ok(bytes_copied)
252 }
253}
254
255pub trait AssetUri {
256 fn uri(&self) -> &str;
257
258 fn reader(&self, workspace: &Workspace) -> Result<ChecksummedReader, FileAdditionError>;
259
260 fn checksum(
261 &self,
262 workspace: &Workspace,
263 checksum_override: Option<HashId>,
264 ) -> Result<HashId, FileAdditionError>;
265
266 fn stored_asset_uri(
267 &self,
268 workspace: &Workspace,
269 checksum: &HashId,
270 ) -> Result<String, FileAdditionError>;
271
272 fn ensure_asset(
273 &self,
274 workspace: &Workspace,
275 checksum: &HashId,
276 ) -> Result<(), FileAdditionError>;
277
278 fn store_file(
279 &self,
280 file_addition: &FileAddition,
281 workspace: &Workspace,
282 ) -> Result<(), FileStoreError>;
283
284 fn hashed_filename(&self, checksum: &HashId) -> String {
285 self.asset_filename(checksum)
286 }
287
288 fn suffix(&self) -> Option<String> {
289 let path = if LocalAssetUri::has_uri_scheme(self.uri()) {
290 Url::parse(self.uri()).ok()?.path().to_string()
291 } else {
292 self.uri().to_string()
293 };
294
295 Path::new(&path)
296 .file_name()
297 .and_then(|name| name.to_str())
298 .and_then(|file_name| {
299 file_name
300 .split_once('.')
301 .map(|(_, suffix)| suffix.to_string())
302 })
303 }
304
305 fn generate_file_addition_id(checksum: &HashId, asset_uri: &str) -> HashId
306 where
307 Self: Sized,
308 {
309 let combined = format!("{checksum};{asset_uri}");
310 HashId(calculate_hash(&combined))
311 }
312
313 fn asset_filename(&self, checksum: &HashId) -> String {
314 let suffix = self.suffix().unwrap_or_default();
315 let suffix = suffix.strip_prefix('.').unwrap_or(&suffix);
316 if suffix.is_empty() {
317 return checksum.to_string();
318 }
319 format!("{checksum}.{suffix}")
320 }
321
322 fn asset_relative_path(
323 workspace: &Workspace,
324 asset_uri: &Self,
325 checksum: &HashId,
326 ) -> Result<String, FileAdditionError>
327 where
328 Self: Sized,
329 {
330 let repo_root = workspace.repo_root()?;
331 let asset_path = workspace
332 .asset_dir()?
333 .join(asset_uri.asset_filename(checksum));
334
335 Ok(asset_path
336 .strip_prefix(&repo_root)
337 .map_err(|_| FileAdditionError::PathOutsideRepo {
338 path: asset_path.clone(),
339 repo_root: repo_root.clone(),
340 })?
341 .to_string_lossy()
342 .to_string())
343 }
344}
345
346impl dyn AssetUri {
347 pub fn new(workspace: &Workspace, uri: &str) -> Box<dyn AssetUri> {
348 let (scheme, _) = uri.split_once("://").unwrap_or(("file", uri));
349 match scheme.to_ascii_lowercase().as_str() {
350 "file" => Box::new(
351 LocalAssetUri::new_for_workspace(workspace, uri)
352 .expect("failed to construct local asset uri"),
353 ),
354 _ => Box::new(RemoteAssetUri::new(uri)),
355 }
356 }
357
358 pub fn from_uri(uri: &str) -> Box<dyn AssetUri> {
359 let (scheme, _) = uri.split_once("://").unwrap_or(("file", uri));
360 match scheme.to_ascii_lowercase().as_str() {
361 "file" => Box::new(LocalAssetUri::new(uri)),
362 _ => Box::new(RemoteAssetUri::new(uri)),
363 }
364 }
365}
366
367pub struct LocalAssetUri {
368 asset_uri: String,
369 source_path: Option<PathBuf>,
370 workspace_root: Option<PathBuf>,
371 read_file: Option<ChecksummedReader>,
372 write_file: Option<opendal::blocking::StdWriter>,
373}
374
375impl AssetUri for LocalAssetUri {
376 fn uri(&self) -> &str {
377 &self.asset_uri
378 }
379
380 fn reader(&self, workspace: &Workspace) -> Result<ChecksummedReader, FileAdditionError> {
381 let source_file_path = self.resolved_source_file_path(workspace)?;
382 OpenDalLocation::from_workspace_path(workspace, &source_file_path)
383 .map_err(opendal_file_addition_error)?
384 .reader()
385 }
386
387 fn checksum(
388 &self,
389 workspace: &Workspace,
390 checksum_override: Option<HashId>,
391 ) -> Result<HashId, FileAdditionError> {
392 if let Some(checksum_override) = checksum_override {
393 return Ok(checksum_override);
394 }
395
396 let source_file_path = self.resolved_source_file_path(workspace)?;
397 let checksum_path = if source_file_path.is_file() {
398 source_file_path
399 } else {
400 PathBuf::from(self.file_path())
401 };
402 OpenDalLocation::from_workspace_path(workspace, &checksum_path)
403 .map_err(opendal_file_addition_error)?
404 .checksum(&checksum_path.to_string_lossy())
405 }
406
407 fn stored_asset_uri(
408 &self,
409 workspace: &Workspace,
410 checksum: &HashId,
411 ) -> Result<String, FileAdditionError> {
412 let source_file_path = self.resolved_source_file_path(workspace)?;
413 let source_asset_uri = Self::new(&source_file_path.to_string_lossy());
414 let relative_file_path = Self::asset_relative_path(workspace, &source_asset_uri, checksum)?;
415 Ok(Self::asset_uri(&relative_file_path))
416 }
417
418 fn ensure_asset(
419 &self,
420 workspace: &Workspace,
421 checksum: &HashId,
422 ) -> Result<(), FileAdditionError> {
423 let source_file_path = self.resolved_source_file_path(workspace)?;
424 if source_file_path.is_file() {
425 Self::ensure_asset_copy(workspace, &source_file_path, checksum)?;
426 }
427 Ok(())
428 }
429
430 fn store_file(
431 &self,
432 file_addition: &FileAddition,
433 workspace: &Workspace,
434 ) -> Result<(), FileStoreError> {
435 Self::store_file(file_addition, workspace)
436 }
437}
438
439impl LocalAssetUri {
440 pub const SCHEME: &'static str = "file://";
441
442 pub fn new(path_or_uri: &str) -> Self {
443 Self {
444 asset_uri: Self::asset_uri(path_or_uri),
445 source_path: None,
446 workspace_root: None,
447 read_file: None,
448 write_file: None,
449 }
450 }
451
452 pub fn new_for_workspace(
453 workspace: &Workspace,
454 path_or_uri: &str,
455 ) -> Result<Self, FileAdditionError> {
456 let source_path = if Self::is_file_uri(path_or_uri) {
457 Self::resolve_source_path(workspace, path_or_uri)?
458 } else {
459 Self::resolve_input_source_path(workspace, path_or_uri)?
460 };
461 let asset_uri = Self::asset_uri(&Self::logical_file_path(workspace, &source_path)?);
462 Ok(Self {
463 asset_uri,
464 source_path: Some(source_path),
465 workspace_root: Some(workspace.repo_root()?),
466 read_file: None,
467 write_file: None,
468 })
469 }
470
471 pub fn is_file_uri(asset_uri: &str) -> bool {
472 asset_uri.starts_with(Self::SCHEME)
473 }
474
475 pub fn has_uri_scheme(path_or_uri: &str) -> bool {
476 path_or_uri.contains("://")
477 }
478
479 pub fn is_local_path_or_file_uri(path_or_uri: &str) -> bool {
480 Self::is_file_uri(path_or_uri) || !Self::has_uri_scheme(path_or_uri)
481 }
482
483 pub fn asset_uri(path: &str) -> String {
484 let path = path.strip_prefix('/').unwrap_or(path);
485 if Self::is_file_uri(path) {
486 path.to_string()
487 } else {
488 format!("{}{path}", Self::SCHEME)
489 }
490 }
491
492 pub fn path_from_uri(asset_uri: &str) -> Option<String> {
493 asset_uri
494 .strip_prefix(Self::SCHEME)
495 .map(ToString::to_string)
496 }
497
498 pub fn operation_file_path(
499 workspace: &Workspace,
500 path_or_uri: &str,
501 checksum: &HashId,
502 ) -> Result<String, FileAdditionError> {
503 let source_path = if Self::is_file_uri(path_or_uri) {
504 Self::resolve_source_path(workspace, path_or_uri)?
505 } else {
506 Self::resolve_input_source_path(workspace, path_or_uri)?
507 };
508 Self::stored_relative_path(workspace, &source_path, checksum)
509 }
510
511 pub fn is_asset_relative_path(
513 workspace: &Workspace,
514 relative_path: &str,
515 ) -> Result<bool, FileAdditionError> {
516 let repo_root = workspace.repo_root()?;
517 let asset_dir = workspace.asset_dir()?;
518 let asset_relative_dir =
519 asset_dir
520 .strip_prefix(&repo_root)
521 .map_err(|_| FileAdditionError::PathOutsideRepo {
522 path: asset_dir.clone(),
523 repo_root: repo_root.clone(),
524 })?;
525
526 let candidate = if relative_path.is_empty() {
527 PathBuf::new()
528 } else {
529 Self::sanitize_relative_path(Path::new(relative_path))?
530 };
531
532 Ok(candidate.starts_with(asset_relative_dir))
533 }
534
535 pub fn repo_relative_destination_path(
538 workspace: &Workspace,
539 relative_path: &str,
540 ) -> Result<PathBuf, FileAdditionError> {
541 let sanitized = if relative_path.is_empty() {
542 PathBuf::new()
543 } else {
544 Self::sanitize_relative_path(Path::new(relative_path))?
545 };
546
547 Ok(workspace.repo_root()?.join(sanitized))
548 }
549
550 fn file_path(&self) -> &str {
551 self.asset_uri
552 .strip_prefix(Self::SCHEME)
553 .unwrap_or(&self.asset_uri)
554 }
555
556 fn io_path(&self) -> PathBuf {
557 self.source_path.clone().unwrap_or_else(|| {
558 let file_path = PathBuf::from(self.file_path());
559 if file_path.is_absolute() {
560 file_path
561 } else if let Some(workspace_root) = &self.workspace_root {
562 workspace_root.join(file_path)
563 } else {
564 file_path
565 }
566 })
567 }
568
569 pub fn close_write(&mut self) -> io::Result<()> {
570 if let Some(mut file) = self.write_file.take() {
571 file.close()?;
572 }
573 Ok(())
574 }
575
576 fn resolved_source_file_path(
577 &self,
578 workspace: &Workspace,
579 ) -> Result<PathBuf, FileAdditionError> {
580 self.source_path
581 .clone()
582 .map(Ok)
583 .unwrap_or_else(|| Self::resolve_source_path(workspace, &self.asset_uri))
584 }
585
586 fn resolve_input_source_path(
587 workspace: &Workspace,
588 file_path_or_uri: &str,
589 ) -> Result<PathBuf, FileAdditionError> {
590 if !Self::is_local_path_or_file_uri(file_path_or_uri) {
591 return Err(FileAdditionError::FileReadError(io::Error::new(
592 io::ErrorKind::InvalidInput,
593 format!("unsupported non-local uri: {file_path_or_uri}"),
594 )));
595 }
596
597 let file_path =
598 Self::path_from_uri(file_path_or_uri).unwrap_or_else(|| file_path_or_uri.to_string());
599 if file_path.is_empty() {
600 return Ok(PathBuf::new());
601 }
602
603 let provided_path = Path::new(&file_path);
604 if provided_path.is_absolute() {
605 Ok(Self::canonicalize_or_normalize(provided_path))
606 } else {
607 Ok(Self::canonicalize_or_normalize(
608 &workspace.repo_root()?.join(provided_path),
609 ))
610 }
611 }
612
613 fn resolve_source_path(
614 workspace: &Workspace,
615 asset_uri: &str,
616 ) -> Result<PathBuf, FileAdditionError> {
617 let file_path = Self::path_from_uri(asset_uri).unwrap_or_else(|| asset_uri.to_string());
618 if file_path.is_empty() {
619 return Ok(PathBuf::new());
620 }
621
622 let provided_path = Path::new(&file_path);
623 if provided_path.is_absolute() {
624 return Err(FileAdditionError::PathOutsideRepo {
625 path: provided_path.to_path_buf(),
626 repo_root: workspace.repo_root()?,
627 });
628 }
629
630 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
631 let joined_path = workspace
632 .repo_root()?
633 .join(Self::sanitize_relative_path(provided_path)?);
634 let normalized_path = Self::canonicalize_or_normalize(&joined_path);
635 if !normalized_path.starts_with(&repo_root) {
636 return Err(FileAdditionError::PathOutsideRepo {
637 path: normalized_path,
638 repo_root,
639 });
640 }
641 Ok(normalized_path)
642 }
643
644 fn logical_file_path(
645 workspace: &Workspace,
646 source_path: &Path,
647 ) -> Result<String, FileAdditionError> {
648 if source_path.as_os_str().is_empty() {
649 return Ok(String::new());
650 }
651
652 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
653 let source_path = Self::canonicalize_or_normalize(source_path);
654 if let Ok(relative_path) = source_path.strip_prefix(&repo_root) {
655 return Ok(relative_path.to_string_lossy().to_string());
656 }
657
658 Ok(source_path
659 .strip_prefix(Path::new("/"))
660 .unwrap_or(&source_path)
661 .to_string_lossy()
662 .to_string())
663 }
664
665 fn stored_relative_path(
666 workspace: &Workspace,
667 source_path: &Path,
668 checksum: &HashId,
669 ) -> Result<String, FileAdditionError> {
670 if source_path.as_os_str().is_empty() {
671 return Ok(String::new());
672 }
673 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
674 let source_path = Self::canonicalize_or_normalize(source_path);
675
676 if source_path.starts_with(&repo_root) {
677 return Ok(source_path
678 .strip_prefix(&repo_root)
679 .map_err(|_| FileAdditionError::PathOutsideRepo {
680 path: source_path.to_path_buf(),
681 repo_root: repo_root.clone(),
682 })?
683 .to_string_lossy()
684 .to_string());
685 }
686
687 if source_path.is_absolute() {
688 let source_asset_uri = Self::new(&source_path.to_string_lossy());
689 return Self::asset_relative_path(workspace, &source_asset_uri, checksum);
690 }
691
692 Err(FileAdditionError::FileReadError(io::Error::new(
693 io::ErrorKind::InvalidInput,
694 format!(
695 "unable to resolve local asset path: {}",
696 source_path.display()
697 ),
698 )))
699 }
700
701 fn sanitize_relative_path(path: &Path) -> Result<PathBuf, FileAdditionError> {
702 let mut sanitized = PathBuf::new();
703 for component in path.components() {
704 match component {
705 Component::Normal(part) => sanitized.push(part),
706 Component::CurDir => {}
707 Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
708 return Err(FileAdditionError::FileReadError(io::Error::new(
709 io::ErrorKind::PermissionDenied,
710 format!("path escapes workspace root: {}", path.display()),
711 )));
712 }
713 }
714 }
715 Ok(sanitized)
716 }
717
718 fn canonicalize_or_normalize(path: &Path) -> PathBuf {
719 let normalized_path = fs::canonicalize(path).unwrap_or_else(|_| Self::normalize_path(path));
720 let cleaned_path = normalized_path
724 .as_path()
725 .strip_prefix("/private")
726 .unwrap_or(&normalized_path);
727 Path::new("/").join(cleaned_path)
728 }
729
730 fn normalize_path(path: &Path) -> PathBuf {
731 let mut normalized = PathBuf::new();
732 for component in path.components() {
733 match component {
734 Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
735 Component::RootDir => normalized.push(Path::new("/")),
736 Component::CurDir => {}
737 Component::ParentDir => {
738 normalized.pop();
739 }
740 Component::Normal(part) => normalized.push(part),
741 }
742 }
743 normalized
744 }
745
746 pub fn ensure_asset_copy(
750 workspace: &Workspace,
751 source_path: &Path,
752 checksum: &HashId,
753 ) -> Result<(), FileAdditionError> {
754 let asset_uri = Self::new(&source_path.to_string_lossy());
755 let asset_path = workspace
756 .asset_dir()?
757 .join(asset_uri.asset_filename(checksum));
758 if asset_path.exists() {
759 return Ok(());
760 }
761
762 OpenDalLocation::from_workspace_path(workspace, source_path)
763 .map_err(opendal_file_addition_error)?
764 .copy_to_local_path(workspace, &asset_path)
765 .map_err(FileAdditionError::FileReadError)?;
766 Ok(())
767 }
768
769 pub fn store_file(
770 file_addition: &FileAddition,
771 workspace: &Workspace,
772 ) -> Result<(), FileStoreError> {
773 let asset_path = workspace
774 .asset_dir()?
775 .join(file_addition.clone().hashed_filename());
776 if asset_path.exists() {
777 return Ok(());
778 }
779
780 let source_path = Self::resolve_source_path(workspace, &file_addition.asset_uri).map_err(
781 |err| match err {
782 FileAdditionError::FileReadError(err) => FileStoreError::IoError(err),
783 other => FileStoreError::IoError(io::Error::other(other)),
784 },
785 )?;
786 if source_path == asset_path {
787 return Ok(());
788 }
789 OpenDalLocation::from_workspace_path(workspace, &source_path)
790 .map_err(opendal_file_store_error)?
791 .copy_to_local_path(workspace, &asset_path)
792 .map_err(FileStoreError::IoError)?;
793 Ok(())
794 }
795}
796
797impl Read for LocalAssetUri {
798 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
799 if self.read_file.is_none() {
800 let io_path = self.io_path();
801 self.read_file = Some(
802 OpenDalLocation::from_absolute_path(&io_path)
803 .map_err(io::Error::other)?
804 .reader()
805 .map_err(io::Error::other)?,
806 );
807 }
808 self.read_file.as_mut().unwrap().read(buf)
809 }
810}
811
812impl Write for LocalAssetUri {
813 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
814 if self.write_file.is_none() {
815 let io_path = self.io_path();
816 let location =
817 OpenDalLocation::from_absolute_path(&io_path).map_err(io::Error::other)?;
818 self.write_file = Some(
819 location
820 .operator
821 .writer(&location.path)
822 .map_err(io::Error::other)?
823 .into_std_write(),
824 );
825 }
826 self.write_file.as_mut().unwrap().write(buf)
827 }
828
829 fn flush(&mut self) -> io::Result<()> {
830 if let Some(file) = self.write_file.as_mut() {
831 file.flush()
832 } else {
833 Ok(())
834 }
835 }
836}
837
838impl Drop for LocalAssetUri {
839 fn drop(&mut self) {
840 let _ = self.close_write();
841 }
842}
843
844pub struct RemoteAssetUri {
845 asset_uri: String,
846}
847
848impl AssetUri for RemoteAssetUri {
849 fn uri(&self) -> &str {
850 &self.asset_uri
851 }
852
853 fn reader(&self, _workspace: &Workspace) -> Result<ChecksummedReader, FileAdditionError> {
854 OpenDalLocation::from_remote_uri(&self.asset_uri)?.reader()
855 }
856
857 fn checksum(
858 &self,
859 _workspace: &Workspace,
860 checksum_override: Option<HashId>,
861 ) -> Result<HashId, FileAdditionError> {
862 Ok(Self::checksum_for_uri(&self.asset_uri, checksum_override))
863 }
864
865 fn stored_asset_uri(
866 &self,
867 _workspace: &Workspace,
868 _checksum: &HashId,
869 ) -> Result<String, FileAdditionError> {
870 Ok(self.asset_uri.clone())
871 }
872
873 fn ensure_asset(
874 &self,
875 _workspace: &Workspace,
876 _checksum: &HashId,
877 ) -> Result<(), FileAdditionError> {
878 Ok(())
879 }
880
881 fn store_file(
882 &self,
883 _file_addition: &FileAddition,
884 _workspace: &Workspace,
885 ) -> Result<(), FileStoreError> {
886 Ok(())
887 }
888}
889
890impl RemoteAssetUri {
891 pub fn new(asset_uri: &str) -> Self {
892 Self {
893 asset_uri: asset_uri.to_string(),
894 }
895 }
896
897 fn checksum_for_uri(asset_uri: &str, checksum_override: Option<HashId>) -> HashId {
898 checksum_override.unwrap_or_else(|| HashId(calculate_hash(asset_uri)))
899 }
900}
901
902#[cfg(test)]
903mod tests {
904 use std::{
905 fs,
906 io::{Read, Write},
907 net::TcpListener,
908 path::PathBuf,
909 thread,
910 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
911 };
912
913 use super::*;
914 use crate::{operations::calculate_file_checksum, test_helpers::setup_gen};
915
916 #[test]
917 fn test_generate_file_addition_id_consistency() {
918 let checksum = HashId([1u8; 32]);
919 let file_path = "/path/to/file.txt";
920
921 let id1 = LocalAssetUri::generate_file_addition_id(&checksum, file_path);
922 let id2 = LocalAssetUri::generate_file_addition_id(&checksum, file_path);
923
924 assert_eq!(id1, id2);
925 }
926
927 #[test]
928 fn test_generate_file_addition_id_uniqueness_different_paths() {
929 let checksum = HashId([1u8; 32]);
930 let file_path1 = "/path/to/file1.txt";
931 let file_path2 = "/path/to/file2.txt";
932
933 let id1 = LocalAssetUri::generate_file_addition_id(&checksum, file_path1);
934 let id2 = LocalAssetUri::generate_file_addition_id(&checksum, file_path2);
935
936 assert_ne!(id1, id2);
937 }
938
939 #[test]
940 fn test_generate_file_addition_id_uniqueness_different_checksums() {
941 let checksum1 = HashId([1u8; 32]);
942 let checksum2 = HashId([2u8; 32]);
943 let file_path = "/path/to/file.txt";
944
945 let id1 = LocalAssetUri::generate_file_addition_id(&checksum1, file_path);
946 let id2 = LocalAssetUri::generate_file_addition_id(&checksum2, file_path);
947
948 assert_ne!(id1, id2);
949 }
950
951 #[test]
952 fn test_resolve_source_path_rejects_absolute_path_from_file_in_repo() {
953 let context = setup_gen();
954 let workspace = context.workspace();
955 let repo_root = workspace.base_dir();
956
957 let absolute_path = repo_root.join("inputs").join("absolute.txt");
958 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
959 fs::write(&absolute_path, b"absolute").unwrap();
960 let absolute_string = absolute_path.to_string_lossy().to_string();
961
962 let err =
963 LocalAssetUri::resolve_source_path(workspace, absolute_string.as_str()).unwrap_err();
964 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
965 }
966
967 #[test]
968 fn test_stored_relative_path_returns_relative_path_from_file_in_repo() {
969 let context = setup_gen();
970 let workspace = context.workspace();
971 let repo_root = workspace.base_dir();
972
973 let absolute_path = repo_root.join("inputs").join("absolute.txt");
974 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
975 fs::write(&absolute_path, b"absolute").unwrap();
976 let relative_string = absolute_path
977 .strip_prefix(repo_root)
978 .unwrap()
979 .to_string_lossy()
980 .to_string();
981
982 let relative = LocalAssetUri::stored_relative_path(
983 workspace,
984 &absolute_path,
985 &calculate_file_checksum(&absolute_path).unwrap(),
986 )
987 .unwrap();
988
989 assert_eq!(relative, relative_string);
990 }
991
992 #[test]
993 fn test_resolve_source_path_returns_absolute_path_from_relative_path_in_repo() {
994 let context = setup_gen();
995 let workspace = context.workspace();
996 let repo_root = workspace.repo_root().unwrap();
997
998 let relative_path = PathBuf::from("relative/path/file.txt");
999 let absolute_path = repo_root.join(&relative_path);
1000 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
1001 fs::write(&absolute_path, b"relative").unwrap();
1002 let relative_string = relative_path.to_string_lossy().to_string();
1003 let absolute_string = absolute_path.to_string_lossy().to_string();
1004
1005 let absolute =
1006 LocalAssetUri::resolve_source_path(workspace, relative_string.as_str()).unwrap();
1007
1008 assert_eq!(absolute, PathBuf::from(absolute_string));
1009 }
1010
1011 #[test]
1012 fn test_stored_relative_path_returns_relative_path_from_relative_path_in_repo() {
1013 let context = setup_gen();
1014 let workspace = context.workspace();
1015 let repo_root = workspace.repo_root().unwrap();
1016
1017 let relative_path = PathBuf::from("relative/path/file.txt");
1018 let absolute_path = repo_root.join(&relative_path);
1019 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
1020 fs::write(&absolute_path, b"relative").unwrap();
1021 let relative_string = relative_path.to_string_lossy().to_string();
1022
1023 let relative = LocalAssetUri::stored_relative_path(
1024 workspace,
1025 &absolute_path,
1026 &calculate_file_checksum(&absolute_path).unwrap(),
1027 )
1028 .unwrap();
1029
1030 assert_eq!(relative, relative_string);
1031 }
1032
1033 #[test]
1034 fn test_resolve_source_path_rejects_absolute_path_outside_repo() {
1035 let context = setup_gen();
1036 let workspace = context.workspace();
1037
1038 let mut outside_file = tempfile::NamedTempFile::new().unwrap();
1039 outside_file.write_all(b"outside repo").unwrap();
1040 outside_file.flush().unwrap();
1041 let outside_string = outside_file.path().to_string_lossy().to_string();
1042
1043 let err =
1044 LocalAssetUri::resolve_source_path(workspace, outside_string.as_str()).unwrap_err();
1045 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
1046 }
1047
1048 #[test]
1049 fn test_stored_relative_path_returns_asset_path_on_file_outside_repo() {
1050 let context = setup_gen();
1051 let workspace = context.workspace();
1052
1053 let mut outside_file = tempfile::NamedTempFile::new().unwrap();
1054 outside_file.write_all(b"outside repo").unwrap();
1055 outside_file.flush().unwrap();
1056 let checksum = calculate_file_checksum(outside_file.path()).unwrap();
1057 let outside_suffix = LocalAssetUri::new(&outside_file.path().to_string_lossy())
1058 .suffix()
1059 .unwrap();
1060
1061 let relative =
1062 LocalAssetUri::stored_relative_path(workspace, outside_file.path(), &checksum).unwrap();
1063
1064 assert_eq!(relative, format!(".gen/assets/{checksum}.{outside_suffix}"));
1065 }
1066
1067 #[test]
1068 fn stored_relative_path_keeps_compression_suffix_for_asset_path() {
1069 let context = setup_gen();
1070 let workspace = context.workspace();
1071 let fixture_path =
1072 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
1073 let outside_dir = tempfile::tempdir().unwrap();
1074 let outside_path = outside_dir.path().join("simple.fa.bgz");
1075 fs::copy(&fixture_path, &outside_path).unwrap();
1076 let checksum = calculate_file_checksum(&outside_path).unwrap();
1077
1078 let relative =
1079 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
1080
1081 assert_eq!(relative, format!(".gen/assets/{checksum}.fa.bgz"));
1082 }
1083
1084 #[test]
1085 fn stored_relative_path_keeps_unknown_file_type_suffix_for_asset_path() {
1086 let context = setup_gen();
1087 let workspace = context.workspace();
1088 let outside_dir = tempfile::tempdir().unwrap();
1089 let outside_path = outside_dir.path().join("sample.custom.gz");
1090 fs::write(&outside_path, b"custom contents").unwrap();
1091 let checksum = calculate_file_checksum(&outside_path).unwrap();
1092
1093 let relative =
1094 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
1095
1096 assert_eq!(relative, format!(".gen/assets/{checksum}.custom.gz"));
1097 }
1098
1099 #[test]
1100 fn stored_relative_path_keeps_full_source_suffix_for_asset_path() {
1101 let context = setup_gen();
1102 let workspace = context.workspace();
1103 let outside_dir = tempfile::tempdir().unwrap();
1104 let outside_path = outside_dir.path().join("sample.fa.unhandled");
1105 fs::write(&outside_path, b"custom contents").unwrap();
1106 let checksum = calculate_file_checksum(&outside_path).unwrap();
1107
1108 let relative =
1109 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
1110
1111 assert_eq!(relative, format!(".gen/assets/{checksum}.fa.unhandled"));
1112 }
1113
1114 #[test]
1115 fn stored_relative_path_omits_suffix_for_source_without_suffix() {
1116 let context = setup_gen();
1117 let workspace = context.workspace();
1118 let outside_dir = tempfile::tempdir().unwrap();
1119 let outside_path = outside_dir.path().join("sample");
1120 fs::write(&outside_path, b"custom contents").unwrap();
1121 let checksum = calculate_file_checksum(&outside_path).unwrap();
1122
1123 let relative =
1124 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
1125
1126 assert_eq!(relative, format!(".gen/assets/{checksum}"));
1127 }
1128
1129 #[test]
1130 fn hashed_filename_uses_http_uri_path_suffix() {
1131 let checksum = HashId::convert_str("remote");
1132 let asset_uri = RemoteAssetUri::new("http://example.com/assets/fasta.fa.gz?download=1");
1133
1134 let filename = asset_uri.hashed_filename(&checksum);
1135
1136 assert_eq!(filename, format!("{checksum}.fa.gz"));
1137 }
1138
1139 #[test]
1140 fn test_resolve_source_path_anchors_relative_paths_to_workspace() {
1141 let context = setup_gen();
1142 let workspace = context.workspace();
1143 let expected = workspace.repo_root().unwrap().join("detached/file.txt");
1144
1145 let absolute = LocalAssetUri::resolve_source_path(workspace, "detached/file.txt").unwrap();
1146 assert_eq!(absolute, expected);
1147 }
1148
1149 #[test]
1150 fn test_resolve_source_path_rejects_parent_traversal() {
1151 let context = setup_gen();
1152 let workspace = context.workspace();
1153
1154 let err = LocalAssetUri::resolve_source_path(workspace, "../detached/file.txt")
1155 .expect_err("expected traversal to be rejected");
1156 assert!(matches!(err, FileAdditionError::FileReadError(_)));
1157 }
1158
1159 mod test_sanitize_relative_path {
1160 use super::*;
1161
1162 #[test]
1163 fn keeps_normal_relative_path() {
1164 let sanitized = LocalAssetUri::sanitize_relative_path(Path::new("nested/file.txt"))
1165 .expect("expected relative path to be allowed");
1166 assert_eq!(sanitized, PathBuf::from("nested/file.txt"));
1167 }
1168
1169 #[test]
1170 fn rejects_parent_dir() {
1171 let err = LocalAssetUri::sanitize_relative_path(Path::new("../nested/file.txt"))
1172 .expect_err("expected parent traversal to be rejected");
1173 assert!(matches!(err, FileAdditionError::FileReadError(_)));
1174 }
1175 }
1176
1177 mod test_normalize_path {
1178 use super::*;
1179
1180 #[test]
1181 fn collapses_dot_and_parent_components() {
1182 let normalized =
1183 LocalAssetUri::normalize_path(Path::new("nested/./deeper/../file.txt"));
1184 assert_eq!(normalized, PathBuf::from("nested/file.txt"));
1185 }
1186 }
1187
1188 mod test_canonicalize_or_normalize {
1189 use super::*;
1190
1191 #[test]
1192 fn normalizes_missing_path() {
1193 let normalized = LocalAssetUri::canonicalize_or_normalize(Path::new(
1194 "/tmp/gen-models-assets-tests/one/../two/file.txt",
1195 ));
1196 assert_eq!(
1197 normalized,
1198 PathBuf::from("/tmp/gen-models-assets-tests/two/file.txt")
1199 );
1200 }
1201
1202 #[test]
1203 fn canonicalizes_existing_path() {
1204 let temp_dir = tempfile::tempdir().unwrap();
1205 let target_dir = temp_dir.path().join("target");
1206 fs::create_dir_all(&target_dir).unwrap();
1207 let file_path = target_dir.join("file.txt");
1208 fs::write(&file_path, b"data").unwrap();
1209
1210 let canonicalized = LocalAssetUri::canonicalize_or_normalize(
1211 &temp_dir.path().join("target/../target/file.txt"),
1212 );
1213
1214 let expected_canonical = fs::canonicalize(&file_path).unwrap();
1218 let cleaned_path = expected_canonical
1219 .strip_prefix("/private")
1220 .unwrap_or(&expected_canonical);
1221 let expected_path = Path::new("/").join(cleaned_path);
1222 assert_eq!(canonicalized, expected_path);
1223 }
1224 }
1225
1226 #[test]
1227 fn test_new_for_workspace_rejects_parent_traversal_file_uri() {
1228 let context = setup_gen();
1229 let workspace = context.workspace();
1230
1231 let err = LocalAssetUri::new_for_workspace(workspace, "file://../detached/file.txt")
1232 .err()
1233 .expect("expected traversal file uri to be rejected");
1234 assert!(matches!(err, FileAdditionError::FileReadError(_)));
1235 }
1236
1237 #[test]
1238 fn test_resolve_source_path_rejects_absolute_asset_uri() {
1239 let context = setup_gen();
1240 let workspace = context.workspace();
1241
1242 let absolute_path = workspace.repo_root().unwrap().join("detached/file.txt");
1243 let err = LocalAssetUri::resolve_source_path(
1244 workspace,
1245 &format!("file://{}", absolute_path.display()),
1246 )
1247 .expect_err("expected absolute asset uri to be rejected");
1248 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
1249 }
1250
1251 #[test]
1252 fn test_new_for_workspace_rejects_non_local_uri() {
1253 let context = setup_gen();
1254 let workspace = context.workspace();
1255
1256 let err = LocalAssetUri::new_for_workspace(workspace, "https://example.com/reference.fa")
1257 .err()
1258 .expect("expected non-local uri to be rejected");
1259 assert!(matches!(err, FileAdditionError::FileReadError(_)));
1260 assert!(
1261 err.to_string()
1262 .contains("unsupported non-local uri: https://example.com/reference.fa")
1263 );
1264 }
1265
1266 #[cfg(unix)]
1267 #[test]
1268 fn test_resolve_source_path_rejects_symlink_escape() {
1269 use std::os::unix::fs::symlink;
1270
1271 let context = setup_gen();
1272 let workspace = context.workspace();
1273 let repo_root = workspace.repo_root().unwrap();
1274 let mut outside_file = tempfile::NamedTempFile::new().unwrap();
1275 outside_file.write_all(b"outside repo").unwrap();
1276 outside_file.flush().unwrap();
1277
1278 let symlink_path = repo_root.join("escape-link.txt");
1279 if symlink_path.exists() || symlink_path.symlink_metadata().is_ok() {
1280 fs::remove_file(&symlink_path).unwrap();
1281 }
1282 symlink(outside_file.path(), &symlink_path).unwrap();
1283
1284 let err = LocalAssetUri::resolve_source_path(workspace, "escape-link.txt")
1285 .expect_err("expected symlink escape to be rejected");
1286 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
1287 }
1288
1289 #[test]
1290 fn test_stored_relative_path_keeps_workspace_relative_paths() {
1291 let context = setup_gen();
1292 let workspace = context.workspace();
1293
1294 let relative = LocalAssetUri::stored_relative_path(
1295 workspace,
1296 &workspace.repo_root().unwrap().join("detached/file.txt"),
1297 &HashId::convert_str("detached"),
1298 )
1299 .unwrap();
1300 assert_eq!(relative, "detached/file.txt");
1301 }
1302
1303 #[test]
1304 fn test_resolve_source_path_empty() {
1305 let context = setup_gen();
1306 let workspace = context.workspace();
1307
1308 let absolute_empty = LocalAssetUri::resolve_source_path(workspace, "").unwrap();
1309 assert_eq!(absolute_empty, PathBuf::new());
1310 }
1311
1312 #[test]
1313 fn test_stored_relative_path_empty() {
1314 let context = setup_gen();
1315 let workspace = context.workspace();
1316
1317 let relative_empty = LocalAssetUri::stored_relative_path(
1318 workspace,
1319 Path::new(""),
1320 &HashId::convert_str("empty"),
1321 )
1322 .unwrap();
1323 assert_eq!(relative_empty, "");
1324 }
1325
1326 #[test]
1327 fn test_local_asset_uri_read_write() {
1328 let context = setup_gen();
1329 let repo_root = context.workspace().repo_root().unwrap();
1330 let path = repo_root.join("asset-uri-io.txt");
1331 fs::write(&path, "initial").unwrap();
1332
1333 let mut reader =
1334 LocalAssetUri::new_for_workspace(context.workspace(), "asset-uri-io.txt").unwrap();
1335 let mut contents = String::new();
1336 reader.read_to_string(&mut contents).unwrap();
1337 assert_eq!(contents, "initial");
1338
1339 let mut writer =
1340 LocalAssetUri::new_for_workspace(context.workspace(), "asset-uri-io.txt").unwrap();
1341 writer.write_all(b"updated").unwrap();
1342 writer.close_write().unwrap();
1343
1344 assert_eq!(fs::read_to_string(path).unwrap(), "updated");
1345 }
1346
1347 #[test]
1348 fn test_remote_asset_uri_reads_http_uri() {
1349 let seed = SystemTime::now()
1350 .duration_since(UNIX_EPOCH)
1351 .unwrap()
1352 .subsec_nanos() as u16;
1353 let base_port = 20_000 + (seed % 20_000);
1354 let listener = (0..32)
1355 .find_map(|offset| {
1356 let port = base_port.saturating_add(offset);
1357 TcpListener::bind(("127.0.0.1", port)).ok()
1358 })
1359 .expect("failed to bind test HTTP listener");
1360 listener.set_nonblocking(true).unwrap();
1361 let addr = listener.local_addr().unwrap();
1362 let handle = thread::spawn(move || {
1363 let started = Instant::now();
1364 let mut served_get = false;
1365 while !served_get && started.elapsed() < Duration::from_secs(5) {
1366 let Ok((mut stream, _)) = listener.accept() else {
1367 thread::sleep(Duration::from_millis(10));
1368 continue;
1369 };
1370 let mut request = [0; 1024];
1371 let len = stream.read(&mut request).unwrap();
1372 let request = String::from_utf8_lossy(&request[..len]);
1373 served_get = request.starts_with("GET ");
1374 if served_get {
1375 stream
1376 .write_all(
1377 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\ninitial",
1378 )
1379 .unwrap();
1380 } else {
1381 stream
1382 .write_all(
1383 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\n",
1384 )
1385 .unwrap();
1386 }
1387 }
1388 assert!(served_get);
1389 });
1390
1391 let context = setup_gen();
1392 let uri = format!("http://{addr}/asset.fa");
1393 let mut reader = RemoteAssetUri::new(&uri)
1394 .reader(context.workspace())
1395 .unwrap();
1396 let mut contents = String::new();
1397 reader.read_to_string(&mut contents).unwrap();
1398
1399 handle.join().unwrap();
1400 assert_eq!(contents, "initial");
1401 }
1402}