1use std::{
2 collections::HashMap,
3 fs,
4 io::{self, BufReader, Read, Write},
5 path::{Component, Path, PathBuf},
6 string::ToString,
7 sync::{Arc, LazyLock, Mutex},
8};
9
10use gen_core::{DoltHashId, HashId, Sha256Hash, Workspace, calculate_hash};
11use indexmap::IndexMap;
12use opendal::{blocking, services};
13use rusqlite::{
14 ToSql, named_params, params,
15 types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef},
16};
17use sha2::{Digest, Sha256};
18use tempfile::NamedTempFile;
19use url::{Position, Url};
20
21use crate::{
22 Direction, ModelSelect,
23 db::GraphConnection,
24 errors::{FileAdditionError, FileStoreError, QueryError},
25 file_types::FileTypes,
26 history::dolt::hash_of,
27 operations::FileAddition,
28};
29
30mod compression;
31pub use compression::CompressionType;
32pub(crate) use compression::stage_bgzf_asset_copy;
33
34static OPENDAL_RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
35 tokio::runtime::Builder::new_multi_thread()
36 .enable_all()
37 .build()
38 .expect("failed to build OpenDAL runtime")
39});
40
41#[derive(Clone, Debug, Eq, Hash, PartialEq)]
42pub enum OperationKind {
43 AddFile,
44 AnnotationFile,
45 HistoryCommit,
46 Other(String),
47}
48
49impl OperationKind {
50 pub fn as_str(&self) -> &str {
51 match self {
52 OperationKind::AddFile => "add-file",
53 OperationKind::AnnotationFile => "annotation-file",
54 OperationKind::HistoryCommit => "history-commit",
55 OperationKind::Other(kind) => kind.as_str(),
56 }
57 }
58}
59
60impl From<&str> for OperationKind {
61 fn from(kind: &str) -> Self {
62 match kind {
63 "add-file" => OperationKind::AddFile,
64 "annotation-file" => OperationKind::AnnotationFile,
65 "history-commit" => OperationKind::HistoryCommit,
66 other => OperationKind::Other(other.to_string()),
67 }
68 }
69}
70
71impl From<String> for OperationKind {
72 fn from(kind: String) -> Self {
73 match kind.as_str() {
74 "add-file" => OperationKind::AddFile,
75 "annotation-file" => OperationKind::AnnotationFile,
76 "history-commit" => OperationKind::HistoryCommit,
77 _ => OperationKind::Other(kind),
78 }
79 }
80}
81
82impl core::fmt::Display for OperationKind {
83 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
84 formatter.write_str(self.as_str())
85 }
86}
87
88impl ToSql for OperationKind {
89 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
90 Ok(self.as_str().into())
91 }
92}
93
94impl FromSql for OperationKind {
95 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
96 value.as_str().map(OperationKind::from)
97 }
98}
99
100fn with_opendal_runtime<T>(f: impl FnOnce() -> T) -> T {
101 let _guard = OPENDAL_RUNTIME.enter();
102 f()
103}
104
105fn opendal_file_addition_error(err: opendal::Error) -> FileAdditionError {
106 FileAdditionError::FileReadError(io::Error::other(err))
107}
108
109#[derive(Clone, Debug, Eq, Hash, PartialEq)]
110pub enum AssetRole {
111 Input,
112 SequenceIndex,
113 Annotation,
114 AnnotationIndex,
115 Other(String),
116}
117
118impl AssetRole {
119 pub fn as_str(&self) -> &str {
120 match self {
121 AssetRole::Input => "input",
122 AssetRole::SequenceIndex => "sequence-index",
123 AssetRole::Annotation => "annotation",
124 AssetRole::AnnotationIndex => "annotation-index",
125 AssetRole::Other(role) => role.as_str(),
126 }
127 }
128}
129
130impl From<&str> for AssetRole {
131 fn from(role: &str) -> Self {
132 match role {
133 "input" => AssetRole::Input,
134 "sequence-index" => AssetRole::SequenceIndex,
135 "annotation" => AssetRole::Annotation,
136 "annotation-index" => AssetRole::AnnotationIndex,
137 other => AssetRole::Other(other.to_string()),
138 }
139 }
140}
141
142impl From<String> for AssetRole {
143 fn from(role: String) -> Self {
144 match role.as_str() {
145 "input" => AssetRole::Input,
146 "sequence-index" => AssetRole::SequenceIndex,
147 "annotation" => AssetRole::Annotation,
148 "annotation-index" => AssetRole::AnnotationIndex,
149 _ => AssetRole::Other(role),
150 }
151 }
152}
153
154impl core::fmt::Display for AssetRole {
155 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
156 formatter.write_str(self.as_str())
157 }
158}
159
160impl ToSql for AssetRole {
161 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
162 Ok(self.as_str().into())
163 }
164}
165
166impl FromSql for AssetRole {
167 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
168 value.as_str().map(AssetRole::from)
169 }
170}
171
172#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
186#[model_select(table = "gen_asset_refs")]
187pub struct AssetRef {
188 pub id: HashId,
189 pub uri: String,
190 pub file_type: String,
191 pub checksum: Option<Sha256Hash>,
192 pub size: Option<i64>,
193 pub role: AssetRole,
194 pub logical_path: Option<String>,
196 pub name: Option<String>,
197 pub created_on: i64,
198 pub upstream_asset_ref_id: Option<HashId>,
200 pub materialized_checksum: Option<Sha256Hash>,
207}
208
209pub struct Assets;
210
211#[derive(Clone, Copy, Debug, Eq, PartialEq)]
213pub enum AssetView {
214 Cumulative,
216 Materialized,
218}
219
220#[derive(Clone, Debug, Eq, PartialEq)]
221pub struct AnnotationFileAssets {
222 pub log_id: HashId,
223 pub annotation: AssetRef,
224 pub index: Option<AssetRef>,
225}
226
227#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
228#[model_select(table = "gen_operation_log")]
229pub struct OperationLog {
230 pub id: HashId,
231 pub operation_kind: OperationKind,
232 pub command: String,
233 pub created_on: i64,
234}
235
236#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
237#[model_select(
238 table = "gen_operation_assets",
239 default_sort(log_id = "asc", asset_ref_id = "asc", role = "asc")
240)]
241pub struct OperationAsset {
242 #[model_select(primary_key)]
243 pub log_id: HashId,
244 #[model_select(primary_key)]
245 pub asset_ref_id: HashId,
246 #[model_select(primary_key)]
247 pub role: AssetRole,
248}
249
250impl AssetRef {
251 pub fn materialized_compression_type(&self) -> CompressionType {
256 if self.materialized_checksum.is_some() {
257 return CompressionType::Plain;
258 }
259
260 self.logical_path
261 .as_deref()
262 .filter(|logical_path| !logical_path.is_empty())
263 .map(|logical_path| <dyn AssetUri>::from_uri(logical_path).compression_type())
264 .unwrap_or(CompressionType::Plain)
265 }
266
267 pub fn versioned_store_path(
273 &self,
274 workspace: &Workspace,
275 ) -> Result<PathBuf, FileAdditionError> {
276 let checksum = self.checksum.ok_or_else(|| {
277 FileAdditionError::ChecksumError(format!(
278 "asset {} has no checksum for repository lookup",
279 self.id
280 ))
281 })?;
282 let repo_root = LocalAssetUri::canonicalize_or_normalize(&workspace.repo_root()?);
283 let asset_path = workspace
284 .asset_dir()?
285 .join(<dyn AssetUri>::from_uri(&self.uri).hashed_filename(&checksum));
286 if !asset_path.exists() {
287 return Err(FileAdditionError::FileNotFound(
288 asset_path.display().to_string(),
289 ));
290 }
291 let resolved_path = LocalAssetUri::canonicalize_or_normalize(&asset_path);
292 if !resolved_path.starts_with(&repo_root) {
293 return Err(FileAdditionError::PathOutsideRepo {
294 path: resolved_path,
295 repo_root,
296 });
297 }
298 Ok(resolved_path)
299 }
300
301 pub fn reader(
306 &self,
307 workspace: &Workspace,
308 ) -> Result<BufReader<blocking::StdReader>, FileAdditionError> {
309 let reader = if LocalAssetUri::is_local_path_or_file_uri(&self.uri) {
310 let asset_path = self.versioned_store_path(workspace)?;
311 OpenDalLocation::from_absolute_path(&asset_path)
312 .map_err(opendal_file_addition_error)?
313 .reader()?
314 } else {
315 <dyn AssetUri>::from_uri(&self.uri).reader(workspace)?
316 };
317
318 Ok(BufReader::new(reader))
319 }
320
321 pub fn id_hash(
323 file_addition: &FileAddition,
324 role: &AssetRole,
325 logical_path: Option<&str>,
326 name: Option<&str>,
327 upstream_asset_ref_id: Option<&HashId>,
328 ) -> HashId {
329 let checksum = file_addition
330 .checksum
331 .map(|checksum| checksum.to_string())
332 .unwrap_or_default();
333 let materialized_checksum = file_addition
334 .materialized_checksum
335 .map(|checksum| checksum.to_string())
336 .unwrap_or_default();
337 let mut identity = format!(
338 "{uri}:{file_type}:{checksum}:{materialized_checksum}:{role}:{logical_path}:{name}",
339 uri = file_addition.asset_uri,
340 file_type = file_addition.file_type.as_str(),
341 role = role.as_str(),
342 logical_path = logical_path.unwrap_or_default(),
343 name = name.unwrap_or_default(),
344 );
345 if let Some(upstream_asset_ref_id) = upstream_asset_ref_id {
346 identity.push(':');
347 identity.push_str(&upstream_asset_ref_id.to_string());
348 }
349 HashId(calculate_hash(&identity))
350 }
351
352 pub fn from_file_addition(
354 file_addition: &FileAddition,
355 role: AssetRole,
356 logical_path: Option<&str>,
357 name: Option<&str>,
358 upstream_asset_ref_id: Option<&HashId>,
359 created_on: i64,
360 ) -> Self {
361 let file_type = file_addition.file_type.as_str();
362 Self {
363 id: Self::id_hash(
364 file_addition,
365 &role,
366 logical_path,
367 name,
368 upstream_asset_ref_id,
369 ),
370 uri: file_addition.asset_uri.clone(),
371 file_type: file_type.to_string(),
372 checksum: file_addition.checksum,
373 size: None,
374 role,
375 logical_path: logical_path.map(str::to_string),
376 name: name.map(str::to_string),
377 created_on,
378 upstream_asset_ref_id: upstream_asset_ref_id.copied(),
379 materialized_checksum: file_addition.materialized_checksum,
380 }
381 }
382
383 pub fn create(conn: &GraphConnection, asset_ref: &AssetRef) -> rusqlite::Result<()> {
384 conn.execute(
385 "INSERT OR IGNORE INTO gen_asset_refs \
386 (id, uri, file_type, checksum, size, role, logical_path, name, created_on, \
387 upstream_asset_ref_id, materialized_checksum) \
388 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
389 params![
390 asset_ref.id,
391 asset_ref.uri,
392 asset_ref.file_type,
393 asset_ref.checksum,
394 asset_ref.size,
395 &asset_ref.role,
396 asset_ref.logical_path,
397 asset_ref.name,
398 asset_ref.created_on,
399 asset_ref.upstream_asset_ref_id,
400 asset_ref.materialized_checksum
401 ],
402 )?;
403 Ok(())
404 }
405
406 pub fn get_derived_assets(
413 conn: &GraphConnection,
414 upstream_asset_ref_id: &HashId,
415 history_ref: Option<&str>,
416 ) -> Vec<Self> {
417 let select = Self::select(conn)
418 .upstream_asset_ref_id(*upstream_asset_ref_id)
419 .order_by(AssetRefSelect::Role, Direction::Asc)
420 .order_by(AssetRefSelect::LogicalPath, Direction::Asc)
421 .order_by(AssetRefSelect::Id, Direction::Asc)
422 .with_ref(history_ref);
423 select.load().expect("should load derived assets")
424 }
425
426 pub fn get_assets_by_commit(
430 conn: &GraphConnection,
431 from_hash: Option<&DoltHashId>,
432 to_hash: Option<&DoltHashId>,
433 view: AssetView,
434 ) -> Result<IndexMap<DoltHashId, Vec<Self>>, QueryError> {
435 let (ancestry_boundary, view_query) = match view {
436 AssetView::Cumulative => (
437 "AND (:from_hash IS NULL OR ancestry.commit_hash <> :from_hash)",
438 "SELECT bounded_ancestry.commit_hash, \
439 asset_versions.id, \
440 asset_versions.uri, \
441 asset_versions.file_type, \
442 asset_versions.checksum, \
443 asset_versions.size, \
444 asset_versions.role, \
445 asset_versions.logical_path, \
446 asset_versions.name, \
447 asset_versions.created_on, \
448 asset_versions.upstream_asset_ref_id, \
449 asset_versions.materialized_checksum \
450 FROM bounded_ancestry \
451 LEFT JOIN asset_versions \
452 ON asset_versions.introduction_commit = bounded_ancestry.commit_hash \
453 ORDER BY bounded_ancestry.depth DESC, \
454 asset_versions.id",
455 ),
456 AssetView::Materialized => (
457 "",
458 ", /* Keep only assets present at the upper bound, then rank each logical path by \
459 its introduction order in first-parent history. Null paths remain \
460 independent because they are partitioned by asset ID. */ \
461 materialized_assets AS ( \
462 SELECT asset_versions.*, \
463 ROW_NUMBER() OVER ( \
464 PARTITION BY asset_versions.logical_path, \
465 CASE \
466 WHEN asset_versions.logical_path IS NULL \
467 THEN asset_versions.id \
468 END \
469 ORDER BY asset_versions.introduction_depth, \
470 asset_versions.id \
471 ) AS materialized_rank \
472 FROM asset_versions \
473 JOIN dolt_at_gen_asset_refs( \
474 COALESCE(:to_hash, dolt_hashof('HEAD')) \
475 ) AS current_assets \
476 ON current_assets.id = asset_versions.id \
477 ) \
478 SELECT bounded_ancestry.commit_hash, \
479 materialized_assets.id, \
480 materialized_assets.uri, \
481 materialized_assets.file_type, \
482 materialized_assets.checksum, \
483 materialized_assets.size, \
484 materialized_assets.role, \
485 materialized_assets.logical_path, \
486 materialized_assets.name, \
487 materialized_assets.created_on, \
488 materialized_assets.upstream_asset_ref_id, \
489 materialized_assets.materialized_checksum \
490 FROM bounded_ancestry \
491 LEFT JOIN materialized_assets \
492 ON materialized_assets.introduction_commit = bounded_ancestry.commit_hash \
493 AND materialized_assets.materialized_rank = 1 \
494 ORDER BY bounded_ancestry.depth DESC, \
495 materialized_assets.id",
496 ),
497 };
498 let query = format!(
499 "WITH RECURSIVE \
500 /* Walk first-parent history from the upper bound. Cumulative queries stop at \
501 the inclusive lower bound; materialized queries continue to the root so \
502 version precedence comes from commit order rather than wall-clock time. */ \
503 ancestry(commit_hash, depth) AS ( \
504 SELECT COALESCE(:to_hash, dolt_hashof('HEAD')), 0 \
505 UNION ALL \
506 SELECT parents.parent_hash, ancestry.depth + 1 \
507 FROM ancestry \
508 JOIN dolt_commit_ancestors AS parents \
509 ON parents.commit_hash = ancestry.commit_hash \
510 AND parents.parent_index = 0 \
511 WHERE parents.parent_hash IS NOT NULL \
512 {ancestry_boundary} \
513 ), \
514 /* If from_hash is not in the walk, reject the entire range instead of \
515 returning history from an unrelated commit. */ \
516 bounded_ancestry AS ( \
517 SELECT commit_hash, depth \
518 FROM ancestry \
519 WHERE :from_hash IS NULL \
520 OR EXISTS ( \
521 SELECT 1 FROM ancestry \
522 WHERE commit_hash = :from_hash \
523 ) \
524 ), \
525 /* Start Dolt's history walk at the upper bound, join the selected commits to \
526 its repeated table snapshots, keep local files, and collapse each immutable \
527 asset ID. SQLite associates the bare commit hash with the row supplying \
528 MAX(depth), identifying the version's introduction in first-parent history. */ \
529 asset_versions AS ( \
530 SELECT historical_assets.id, \
531 historical_assets.uri, \
532 historical_assets.file_type, \
533 historical_assets.checksum, \
534 historical_assets.size, \
535 historical_assets.role, \
536 historical_assets.logical_path, \
537 historical_assets.name, \
538 historical_assets.created_on, \
539 historical_assets.upstream_asset_ref_id, \
540 historical_assets.materialized_checksum, \
541 bounded_ancestry.commit_hash AS introduction_commit, \
542 MAX(bounded_ancestry.depth) AS introduction_depth \
543 FROM bounded_ancestry \
544 JOIN dolt_history_gen_asset_refs( \
545 COALESCE(:to_hash, dolt_hashof('HEAD')) \
546 ) AS historical_assets \
547 ON historical_assets.commit_hash = bounded_ancestry.commit_hash \
548 WHERE historical_assets.uri LIKE 'file://%' \
549 GROUP BY historical_assets.id \
550 ) \
551 {view_query}"
552 );
553 let mut statement = conn.prepare(&query)?;
554 let rows = statement.query_map(
555 named_params! {
556 ":from_hash": from_hash,
557 ":to_hash": to_hash,
558 },
559 |row| {
560 let id = row.get::<_, Option<HashId>>("id")?;
561 let asset = if let Some(id) = id {
562 Some(Self {
563 id,
564 uri: row.get("uri")?,
565 file_type: row.get("file_type")?,
566 checksum: row.get("checksum")?,
567 size: row.get("size")?,
568 role: row.get("role")?,
569 logical_path: row.get("logical_path")?,
570 name: row.get("name")?,
571 created_on: row.get("created_on")?,
572 upstream_asset_ref_id: row.get("upstream_asset_ref_id")?,
573 materialized_checksum: row.get("materialized_checksum")?,
574 })
575 } else {
576 None
577 };
578 Ok((row.get::<_, DoltHashId>("commit_hash")?, asset))
579 },
580 )?;
581 let mut assets_by_commit = IndexMap::<DoltHashId, Vec<Self>>::new();
582 for row in rows {
583 let (commit_hash, asset) = row?;
584 let assets = assets_by_commit.entry(commit_hash).or_default();
585 if let Some(asset) = asset {
586 assets.push(asset);
587 }
588 }
589 Ok(assets_by_commit)
590 }
591
592 fn get_assets_at(
597 conn: &GraphConnection,
598 from_hash: Option<&DoltHashId>,
599 to_hash: Option<&DoltHashId>,
600 view: AssetView,
601 ) -> Result<Vec<Self>, QueryError> {
602 let mut assets = Self::get_assets_by_commit(conn, from_hash, to_hash, view)?
603 .into_values()
604 .flatten()
605 .collect::<Vec<_>>();
606 assets.sort_by(|left, right| {
607 left.logical_path
608 .cmp(&right.logical_path)
609 .then_with(|| left.id.cmp(&right.id))
610 });
611 Ok(assets)
612 }
613
614 pub fn get_cumulative_assets_at(
622 conn: &GraphConnection,
623 from_hash: Option<&DoltHashId>,
624 to_hash: Option<&DoltHashId>,
625 ) -> Result<Vec<Self>, QueryError> {
626 Self::get_assets_at(conn, from_hash, to_hash, AssetView::Cumulative)
627 }
628
629 pub fn get_materialized_assets_at(
637 conn: &GraphConnection,
638 from_hash: Option<&DoltHashId>,
639 to_hash: Option<&DoltHashId>,
640 ) -> Result<Vec<Self>, QueryError> {
641 Self::get_assets_at(conn, from_hash, to_hash, AssetView::Materialized)
642 }
643}
644
645impl Assets {
646 pub fn get_branch_assets(
653 conn: &GraphConnection,
654 branch: &str,
655 ) -> Result<HashMap<HashId, AssetRef>, QueryError> {
656 let commit_hash = hash_of(conn, branch)?;
657 Ok(
658 AssetRef::get_materialized_assets_at(conn, None, Some(&commit_hash))?
659 .into_iter()
660 .map(|asset| (asset.id, asset))
661 .collect(),
662 )
663 }
664
665 pub fn get_annotation_files(
666 conn: &GraphConnection,
667 history_ref: Option<&str>,
668 ) -> Result<Vec<AnnotationFileAssets>, QueryError> {
669 let operation_logs_table = OperationLog::table_name_with_history_ref(history_ref);
670 let operation_assets_table = OperationAsset::table_name_with_history_ref(history_ref);
671 let asset_refs_table = AssetRef::table_name_with_history_ref(history_ref);
672 let query = format!(
673 "SELECT operation_logs.id AS log_id, \
674 annotation_assets.id AS annotation_id, \
675 annotation_assets.uri AS annotation_uri, \
676 annotation_assets.file_type AS annotation_file_type, \
677 annotation_assets.checksum AS annotation_checksum, \
678 annotation_assets.size AS annotation_size, \
679 annotation_assets.role AS annotation_role, \
680 annotation_assets.logical_path AS annotation_logical_path, \
681 annotation_assets.name AS annotation_name, \
682 annotation_assets.created_on AS annotation_created_on, \
683 annotation_assets.upstream_asset_ref_id AS annotation_upstream_asset_ref_id, \
684 annotation_assets.materialized_checksum AS annotation_materialized_checksum, \
685 index_assets.id AS index_id, \
686 index_assets.uri AS index_uri, \
687 index_assets.file_type AS index_file_type, \
688 index_assets.checksum AS index_checksum, \
689 index_assets.size AS index_size, \
690 index_assets.role AS index_role, \
691 index_assets.logical_path AS index_logical_path, \
692 index_assets.name AS index_name, \
693 index_assets.created_on AS index_created_on, \
694 index_assets.upstream_asset_ref_id AS index_upstream_asset_ref_id, \
695 index_assets.materialized_checksum AS index_materialized_checksum \
696 FROM {operation_logs_table} operation_logs \
697 JOIN {operation_assets_table} annotation_operation_assets \
698 ON annotation_operation_assets.log_id = operation_logs.id \
699 AND annotation_operation_assets.role = :annotation_role \
700 JOIN {asset_refs_table} annotation_assets \
701 ON annotation_assets.id = annotation_operation_assets.asset_ref_id \
702 LEFT JOIN {operation_assets_table} index_operation_assets \
703 ON index_operation_assets.log_id = operation_logs.id \
704 AND index_operation_assets.role = :index_role \
705 LEFT JOIN {asset_refs_table} index_assets \
706 ON index_assets.id = index_operation_assets.asset_ref_id \
707 AND index_assets.upstream_asset_ref_id = annotation_assets.id \
708 WHERE operation_logs.operation_kind = :operation_kind \
709 ORDER BY operation_logs.created_on, annotation_assets.created_on, \
710 annotation_assets.name"
711 );
712 let operation_kind = OperationKind::AnnotationFile;
713 let annotation_role = AssetRole::Annotation;
714 let index_role = AssetRole::AnnotationIndex;
715 let mut query_params: Vec<(&str, &dyn ToSql)> = vec![
716 (":operation_kind", &operation_kind),
717 (":annotation_role", &annotation_role),
718 (":index_role", &index_role),
719 ];
720 if let Some(history_ref) = history_ref.as_ref() {
721 query_params.push((":history_ref", history_ref));
722 }
723 let mut statement = conn.prepare(&query)?;
724 let rows = statement.query_map(&query_params[..], |row| {
725 let index = match row.get::<_, Option<HashId>>("index_id")? {
726 Some(id) => Some(AssetRef {
727 id,
728 uri: row.get("index_uri")?,
729 file_type: row.get("index_file_type")?,
730 checksum: row.get("index_checksum")?,
731 size: row.get("index_size")?,
732 role: row.get("index_role")?,
733 logical_path: row.get("index_logical_path")?,
734 name: row.get("index_name")?,
735 created_on: row.get("index_created_on")?,
736 upstream_asset_ref_id: row.get("index_upstream_asset_ref_id")?,
737 materialized_checksum: row.get("index_materialized_checksum")?,
738 }),
739 None => None,
740 };
741 Ok(AnnotationFileAssets {
742 log_id: row.get("log_id")?,
743 annotation: AssetRef {
744 id: row.get("annotation_id")?,
745 uri: row.get("annotation_uri")?,
746 file_type: row.get("annotation_file_type")?,
747 checksum: row.get("annotation_checksum")?,
748 size: row.get("annotation_size")?,
749 role: row.get("annotation_role")?,
750 logical_path: row.get("annotation_logical_path")?,
751 name: row.get("annotation_name")?,
752 created_on: row.get("annotation_created_on")?,
753 upstream_asset_ref_id: row.get("annotation_upstream_asset_ref_id")?,
754 materialized_checksum: row.get("annotation_materialized_checksum")?,
755 },
756 index,
757 })
758 })?;
759 rows.collect::<rusqlite::Result<Vec<_>>>()
760 .map_err(QueryError::from)
761 }
762}
763
764impl OperationLog {
765 pub fn id_hash(operation_kind: &OperationKind, command: &str, created_on: i64) -> HashId {
766 HashId(calculate_hash(&format!(
767 "{operation_kind}:{command}:{created_on}"
768 )))
769 }
770
771 pub fn create(conn: &GraphConnection, operation_log: &OperationLog) -> rusqlite::Result<()> {
772 conn.execute(
773 "INSERT OR IGNORE INTO gen_operation_log (id, operation_kind, command, created_on) \
774 VALUES (?1, ?2, ?3, ?4)",
775 params![
776 operation_log.id,
777 &operation_log.operation_kind,
778 operation_log.command,
779 operation_log.created_on
780 ],
781 )?;
782 Ok(())
783 }
784}
785
786impl OperationAsset {
787 pub fn create(
788 conn: &GraphConnection,
789 operation_asset: &OperationAsset,
790 ) -> rusqlite::Result<()> {
791 conn.execute(
792 "INSERT OR IGNORE INTO gen_operation_assets (log_id, asset_ref_id, role) \
793 VALUES (?1, ?2, ?3)",
794 params![
795 operation_asset.log_id,
796 operation_asset.asset_ref_id,
797 &operation_asset.role
798 ],
799 )?;
800 Ok(())
801 }
802
803 pub fn by_log_id(conn: &GraphConnection, log_id: &HashId) -> Vec<Self> {
804 Self::select(conn)
805 .log_id(*log_id)
806 .load()
807 .expect("should load operation assets")
808 }
809}
810
811#[doc(hidden)]
812pub struct OpenDalLocation {
813 operator: blocking::Operator,
814 path: String,
815}
816
817struct ChecksumState {
818 hasher: Sha256,
819 checksum: Option<Sha256Hash>,
820 complete: bool,
821}
822
823#[derive(Clone)]
824pub struct ChecksumHandle {
825 state: Arc<Mutex<ChecksumState>>,
826}
827
828impl ChecksumHandle {
829 pub fn checksum(&self) -> Option<Sha256Hash> {
834 let state = self.state.lock().unwrap();
835 if state.complete { state.checksum } else { None }
836 }
837}
838
839pub struct ChecksummedReader {
844 inner: Box<dyn Read>,
845 state: Arc<Mutex<ChecksumState>>,
846}
847
848impl ChecksummedReader {
849 pub fn new(inner: impl Read + 'static) -> Self {
851 Self {
852 inner: Box::new(inner),
853 state: Arc::new(Mutex::new(ChecksumState {
854 hasher: Sha256::new(),
855 checksum: None,
856 complete: false,
857 })),
858 }
859 }
860
861 pub fn checksum_handle(&self) -> ChecksumHandle {
862 ChecksumHandle {
863 state: Arc::clone(&self.state),
864 }
865 }
866
867 fn finish(&self) {
870 let mut state = self.state.lock().unwrap();
871 if state.checksum.is_none() {
872 let finalized = state.hasher.clone().finalize();
873 state.checksum = Some(Sha256Hash(finalized.into()));
874 }
875 state.complete = true;
876 }
877}
878
879pub struct ChecksummedWriter<W> {
881 inner: W,
882 hasher: Sha256,
883}
884
885impl<W> ChecksummedWriter<W> {
886 pub fn new(inner: W) -> Self {
888 Self {
889 inner,
890 hasher: Sha256::new(),
891 }
892 }
893
894 pub fn checksum(&self) -> Sha256Hash {
898 Sha256Hash(self.hasher.clone().finalize().into())
899 }
900}
901
902impl<W: Write> Write for ChecksummedWriter<W> {
903 fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
904 let written = self.inner.write(buffer)?;
905 self.hasher.update(&buffer[..written]);
906 Ok(written)
907 }
908
909 fn flush(&mut self) -> io::Result<()> {
910 self.inner.flush()
911 }
912}
913
914impl Read for ChecksummedReader {
915 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
916 let bytes_read = self.inner.read(buf)?;
917 if bytes_read == 0 {
918 if !buf.is_empty() {
919 self.finish();
920 }
921 } else {
922 self.state.lock().unwrap().hasher.update(&buf[..bytes_read]);
923 }
924 Ok(bytes_read)
925 }
926}
927
928impl OpenDalLocation {
929 fn new_fs(root: &Path, path: &Path) -> Result<Self, opendal::Error> {
930 let path = path
931 .strip_prefix(Path::new("/"))
932 .unwrap_or(path)
933 .to_string_lossy()
934 .to_string();
935 let operator = with_opendal_runtime(|| {
936 let builder = services::Fs::default().root(&root.to_string_lossy());
937 let op = opendal::Operator::new(builder)?;
938 blocking::Operator::new(op)
939 })?;
940
941 Ok(Self { operator, path })
942 }
943
944 fn from_workspace_path(workspace: &Workspace, path: &Path) -> Result<Self, opendal::Error> {
945 let repo_root = workspace.repo_root().map_err(|err| {
946 opendal::Error::new(opendal::ErrorKind::Unexpected, "repo_root failed").set_source(err)
947 })?;
948
949 if path.is_absolute() {
950 Self::new_fs(Path::new("/"), path)
951 } else {
952 Self::new_fs(&repo_root, path)
953 }
954 }
955
956 fn from_absolute_path(path: &Path) -> Result<Self, opendal::Error> {
957 if !path.is_absolute() {
958 return Err(opendal::Error::new(
959 opendal::ErrorKind::Unexpected,
960 "local path must be absolute",
961 ));
962 }
963
964 Self::new_fs(Path::new("/"), path)
965 }
966
967 fn from_remote_uri(asset_uri: &str) -> Result<blocking::StdReader, FileAdditionError> {
968 let url = Url::parse(asset_uri)
969 .map_err(|err| FileAdditionError::FileReadError(io::Error::other(err)))?;
970 let backend_uri = &url[..Position::BeforePath];
973 let object_path = url.path().trim_start_matches('/').to_string();
974 let anonymous_access_configured = url
975 .query_pairs()
976 .any(|(key, _)| key.eq_ignore_ascii_case("allow_anonymous"));
977 opendal::init_default_registry();
978
979 let open_reader = |allow_anonymous: Option<&str>| {
980 let mut options = url
982 .query_pairs()
983 .map(|(key, value)| (key.into_owned(), value.into_owned()))
984 .collect::<HashMap<_, _>>();
985 if let Some(value) = allow_anonymous {
986 options.insert("allow_anonymous".to_string(), value.to_string());
987 }
988 let operator =
989 with_opendal_runtime(|| blocking::Operator::from_uri((backend_uri, options)))
990 .map_err(opendal_file_addition_error)?;
991 Self {
992 operator,
993 path: object_path.clone(),
994 }
995 .reader()
996 };
997
998 match open_reader(None) {
1001 Ok(reader) => Ok(reader),
1002 Err(_) if url.scheme().eq_ignore_ascii_case("s3") && !anonymous_access_configured => {
1003 open_reader(Some("true"))
1004 }
1005 Err(error) => Err(error),
1006 }
1007 }
1008
1009 fn reader(self) -> Result<blocking::StdReader, FileAdditionError> {
1010 self.operator
1011 .reader(&self.path)
1012 .map_err(opendal_file_addition_error)?
1013 .into_std_read(..)
1014 .map_err(opendal_file_addition_error)
1015 }
1016}
1017
1018pub trait AssetUri {
1019 fn uri(&self) -> &str;
1020
1021 fn reader(&self, workspace: &Workspace) -> Result<blocking::StdReader, FileAdditionError>;
1022
1023 fn prepare_asset(
1029 &self,
1030 workspace: &Workspace,
1031 checksum_override: Option<Sha256Hash>,
1032 ) -> Result<Option<Sha256Hash>, FileAdditionError>;
1033
1034 fn stored_asset_uri(
1035 &self,
1036 workspace: &Workspace,
1037 checksum: &Sha256Hash,
1038 ) -> Result<String, FileAdditionError>;
1039
1040 fn store_file(
1041 &self,
1042 file_addition: &FileAddition,
1043 workspace: &Workspace,
1044 ) -> Result<(), FileStoreError>;
1045
1046 fn hashed_filename(&self, checksum: &Sha256Hash) -> String {
1047 self.asset_filename(checksum)
1048 }
1049
1050 fn suffix(&self) -> Option<String> {
1051 let path = if LocalAssetUri::is_file_uri(self.uri()) {
1052 LocalAssetUri::path_from_uri(self.uri())?
1053 } else if LocalAssetUri::has_uri_scheme(self.uri()) {
1054 Url::parse(self.uri()).ok()?.path().to_string()
1055 } else {
1056 self.uri().to_string()
1057 };
1058
1059 Path::new(&path)
1060 .file_name()
1061 .and_then(|name| name.to_str())
1062 .and_then(|file_name| {
1063 file_name
1064 .split_once('.')
1065 .map(|(_, suffix)| suffix.to_string())
1066 })
1067 }
1068
1069 fn compression_type(&self) -> CompressionType {
1073 let Some(suffix) = self.suffix() else {
1074 return CompressionType::Plain;
1075 };
1076 let suffix = suffix.split(['?', '#']).next().unwrap_or_default();
1077 let extension = suffix.rsplit('.').next().unwrap_or(suffix);
1078
1079 if extension.eq_ignore_ascii_case("gz") {
1080 CompressionType::Gzip
1081 } else if ["bgz", "bgzf", "bam"]
1082 .iter()
1083 .any(|compressed_extension| extension.eq_ignore_ascii_case(compressed_extension))
1084 {
1085 CompressionType::Bgzf
1086 } else {
1087 CompressionType::Plain
1088 }
1089 }
1090
1091 fn generate_file_addition_id(checksum: Option<&Sha256Hash>, asset_uri: &str) -> HashId
1092 where
1093 Self: Sized,
1094 {
1095 let checksum = checksum.map(Sha256Hash::to_string).unwrap_or_default();
1098 let combined = format!("{checksum};{asset_uri}");
1099 HashId(calculate_hash(&combined))
1100 }
1101
1102 fn asset_filename(&self, checksum: &Sha256Hash) -> String {
1103 let suffix = self.suffix().unwrap_or_default();
1104 let suffix = suffix.strip_prefix('.').unwrap_or(&suffix);
1105 if suffix.is_empty() {
1106 return checksum.to_string();
1107 }
1108 format!("{checksum}.{suffix}")
1109 }
1110
1111 fn asset_relative_path(
1112 workspace: &Workspace,
1113 asset_uri: &Self,
1114 checksum: &Sha256Hash,
1115 ) -> Result<String, FileAdditionError>
1116 where
1117 Self: Sized,
1118 {
1119 let repo_root = workspace.repo_root()?;
1120 let asset_path = workspace
1121 .asset_dir()?
1122 .join(asset_uri.asset_filename(checksum));
1123
1124 Ok(asset_path
1125 .strip_prefix(&repo_root)
1126 .map_err(|_| FileAdditionError::PathOutsideRepo {
1127 path: asset_path.clone(),
1128 repo_root: repo_root.clone(),
1129 })?
1130 .to_string_lossy()
1131 .to_string())
1132 }
1133}
1134
1135impl dyn AssetUri {
1136 pub fn new(workspace: &Workspace, uri: &str) -> Box<dyn AssetUri> {
1137 let (scheme, _) = uri.split_once("://").unwrap_or(("file", uri));
1138 match scheme.to_ascii_lowercase().as_str() {
1139 "file" => Box::new(
1140 LocalAssetUri::new_for_workspace(workspace, uri)
1141 .expect("failed to construct local asset uri"),
1142 ),
1143 _ => Box::new(RemoteAssetUri::new(uri)),
1144 }
1145 }
1146
1147 pub fn from_uri(uri: &str) -> Box<dyn AssetUri> {
1148 let (scheme, _) = uri.split_once("://").unwrap_or(("file", uri));
1149 match scheme.to_ascii_lowercase().as_str() {
1150 "file" => Box::new(LocalAssetUri::new(uri)),
1151 _ => Box::new(RemoteAssetUri::new(uri)),
1152 }
1153 }
1154}
1155
1156pub fn materialization_destination_path(
1161 workspace: &Workspace,
1162 asset_uri: &str,
1163 checksum: Option<&Sha256Hash>,
1164 logical_path: Option<&str>,
1165) -> Result<PathBuf, FileAdditionError> {
1166 if let Some(logical_path) = logical_path.filter(|path| !path.is_empty()) {
1167 return LocalAssetUri::repo_relative_destination_path(workspace, logical_path);
1168 }
1169
1170 let checksum = checksum.ok_or_else(|| {
1171 FileAdditionError::FileReadError(io::Error::new(
1172 io::ErrorKind::InvalidInput,
1173 format!("cannot materialize asset without checksum: {asset_uri}"),
1174 ))
1175 })?;
1176 Ok(workspace
1177 .asset_dir()?
1178 .join(<dyn AssetUri>::from_uri(asset_uri).hashed_filename(checksum)))
1179}
1180
1181pub struct LocalAssetUri {
1182 asset_uri: String,
1183 source_path: Option<PathBuf>,
1184 workspace_root: Option<PathBuf>,
1185 read_file: Option<blocking::StdReader>,
1186 write_file: Option<opendal::blocking::StdWriter>,
1187}
1188
1189impl AssetUri for LocalAssetUri {
1190 fn uri(&self) -> &str {
1191 &self.asset_uri
1192 }
1193
1194 fn reader(&self, workspace: &Workspace) -> Result<blocking::StdReader, FileAdditionError> {
1195 let source_file_path = self.resolved_source_file_path(workspace)?;
1196 OpenDalLocation::from_workspace_path(workspace, &source_file_path)
1197 .map_err(opendal_file_addition_error)?
1198 .reader()
1199 }
1200
1201 fn prepare_asset(
1202 &self,
1203 workspace: &Workspace,
1204 checksum_override: Option<Sha256Hash>,
1205 ) -> Result<Option<Sha256Hash>, FileAdditionError> {
1206 self.stage_asset_copy(workspace, checksum_override)
1209 .map(Some)
1210 }
1211
1212 fn stored_asset_uri(
1213 &self,
1214 workspace: &Workspace,
1215 checksum: &Sha256Hash,
1216 ) -> Result<String, FileAdditionError> {
1217 let source_file_path = self.resolved_source_file_path(workspace)?;
1218 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
1219 if !source_file_path.starts_with(&repo_root) {
1220 return Ok(self.asset_uri.clone());
1221 }
1222
1223 let source_asset_uri = Self::new(&source_file_path.to_string_lossy());
1224 let relative_file_path = Self::asset_relative_path(workspace, &source_asset_uri, checksum)?;
1225 Ok(Self::asset_uri(&relative_file_path))
1226 }
1227
1228 fn store_file(
1229 &self,
1230 file_addition: &FileAddition,
1231 workspace: &Workspace,
1232 ) -> Result<(), FileStoreError> {
1233 Self::store_file(file_addition, workspace)
1234 }
1235}
1236
1237impl LocalAssetUri {
1238 pub const OUTSIDE_ROOT_DIRECTORY: &'static str = ".gen/outside_root";
1239 pub const SCHEME: &'static str = "file://";
1240
1241 pub fn new(path_or_uri: &str) -> Self {
1242 Self {
1243 asset_uri: Self::asset_uri(path_or_uri),
1244 source_path: None,
1245 workspace_root: None,
1246 read_file: None,
1247 write_file: None,
1248 }
1249 }
1250
1251 pub fn new_for_workspace(
1252 workspace: &Workspace,
1253 path_or_uri: &str,
1254 ) -> Result<Self, FileAdditionError> {
1255 let source_path = if Self::is_file_uri(path_or_uri) {
1256 Self::resolve_source_path(workspace, path_or_uri)?
1257 } else {
1258 Self::resolve_input_source_path(workspace, path_or_uri)?
1259 };
1260 let asset_uri = Self::asset_uri(&Self::logical_file_path(workspace, &source_path)?);
1261 Ok(Self {
1262 asset_uri,
1263 source_path: Some(source_path),
1264 workspace_root: Some(workspace.repo_root()?),
1265 read_file: None,
1266 write_file: None,
1267 })
1268 }
1269
1270 pub(crate) fn is_index_path(path_or_uri: &str) -> bool {
1271 let path = path_or_uri.split(['?', '#']).next().unwrap_or(path_or_uri);
1272 Path::new(path)
1273 .extension()
1274 .and_then(|extension| extension.to_str())
1275 .is_some_and(|extension| {
1276 matches!(
1277 extension.to_ascii_lowercase().as_str(),
1278 "fai" | "gzi" | "tbi" | "csi" | "bai"
1279 )
1280 })
1281 }
1282
1283 pub fn is_file_uri(asset_uri: &str) -> bool {
1284 asset_uri.starts_with(Self::SCHEME)
1285 }
1286
1287 pub fn has_uri_scheme(path_or_uri: &str) -> bool {
1288 path_or_uri.contains("://")
1289 }
1290
1291 pub fn is_local_path_or_file_uri(path_or_uri: &str) -> bool {
1292 Self::is_file_uri(path_or_uri) || !Self::has_uri_scheme(path_or_uri)
1293 }
1294
1295 pub fn asset_uri(path: &str) -> String {
1296 let path = path.strip_prefix('/').unwrap_or(path);
1297 if Self::is_file_uri(path) {
1298 path.to_string()
1299 } else {
1300 format!("{}{path}", Self::SCHEME)
1301 }
1302 }
1303
1304 pub fn path_from_uri(asset_uri: &str) -> Option<String> {
1305 asset_uri
1306 .strip_prefix(Self::SCHEME)
1307 .map(ToString::to_string)
1308 }
1309
1310 pub fn operation_file_path(
1311 workspace: &Workspace,
1312 path_or_uri: &str,
1313 checksum: &Sha256Hash,
1314 ) -> Result<String, FileAdditionError> {
1315 let source_path = if Self::is_file_uri(path_or_uri) {
1316 Self::resolve_source_path(workspace, path_or_uri)?
1317 } else {
1318 Self::resolve_input_source_path(workspace, path_or_uri)?
1319 };
1320 Self::stored_relative_path(workspace, &source_path, checksum)
1321 }
1322
1323 pub fn is_asset_relative_path(
1325 workspace: &Workspace,
1326 relative_path: &str,
1327 ) -> Result<bool, FileAdditionError> {
1328 let repo_root = workspace.repo_root()?;
1329 let asset_dir = workspace.asset_dir()?;
1330 let asset_relative_dir =
1331 asset_dir
1332 .strip_prefix(&repo_root)
1333 .map_err(|_| FileAdditionError::PathOutsideRepo {
1334 path: asset_dir.clone(),
1335 repo_root: repo_root.clone(),
1336 })?;
1337
1338 let candidate = if relative_path.is_empty() {
1339 PathBuf::new()
1340 } else {
1341 Self::sanitize_relative_path(Path::new(relative_path))?
1342 };
1343
1344 Ok(candidate.starts_with(asset_relative_dir))
1345 }
1346
1347 pub fn repo_relative_destination_path(
1350 workspace: &Workspace,
1351 relative_path: &str,
1352 ) -> Result<PathBuf, FileAdditionError> {
1353 let sanitized = if relative_path.is_empty() {
1354 PathBuf::new()
1355 } else {
1356 Self::sanitize_relative_path(Path::new(relative_path))?
1357 };
1358
1359 Ok(workspace.repo_root()?.join(sanitized))
1360 }
1361
1362 fn file_path(&self) -> &str {
1363 self.asset_uri
1364 .strip_prefix(Self::SCHEME)
1365 .unwrap_or(&self.asset_uri)
1366 }
1367
1368 fn io_path(&self) -> PathBuf {
1369 self.source_path.clone().unwrap_or_else(|| {
1370 let file_path = PathBuf::from(self.file_path());
1371 if file_path.is_absolute() {
1372 file_path
1373 } else if let Some(workspace_root) = &self.workspace_root {
1374 workspace_root.join(file_path)
1375 } else {
1376 file_path
1377 }
1378 })
1379 }
1380
1381 pub fn close_write(&mut self) -> io::Result<()> {
1382 if let Some(mut file) = self.write_file.take() {
1383 file.close()?;
1384 }
1385 Ok(())
1386 }
1387
1388 fn resolved_source_file_path(
1389 &self,
1390 workspace: &Workspace,
1391 ) -> Result<PathBuf, FileAdditionError> {
1392 self.source_path
1393 .clone()
1394 .map(Ok)
1395 .unwrap_or_else(|| Self::resolve_source_path(workspace, &self.asset_uri))
1396 }
1397
1398 pub fn resolve_input_source_path(
1400 workspace: &Workspace,
1401 file_path_or_uri: &str,
1402 ) -> Result<PathBuf, FileAdditionError> {
1403 if !Self::is_local_path_or_file_uri(file_path_or_uri) {
1404 return Err(FileAdditionError::FileReadError(io::Error::new(
1405 io::ErrorKind::InvalidInput,
1406 format!("unsupported non-local uri: {file_path_or_uri}"),
1407 )));
1408 }
1409
1410 let file_path =
1411 Self::path_from_uri(file_path_or_uri).unwrap_or_else(|| file_path_or_uri.to_string());
1412 if file_path.is_empty() {
1413 return Ok(PathBuf::new());
1414 }
1415
1416 let provided_path = Path::new(&file_path);
1417 if provided_path.is_absolute() {
1418 Ok(Self::canonicalize_or_normalize(provided_path))
1419 } else {
1420 Ok(Self::canonicalize_or_normalize(
1421 &workspace.repo_root()?.join(provided_path),
1422 ))
1423 }
1424 }
1425
1426 fn resolve_source_path(
1427 workspace: &Workspace,
1428 asset_uri: &str,
1429 ) -> Result<PathBuf, FileAdditionError> {
1430 let file_path = Self::path_from_uri(asset_uri).unwrap_or_else(|| asset_uri.to_string());
1431 if file_path.is_empty() {
1432 return Ok(PathBuf::new());
1433 }
1434
1435 let provided_path = Path::new(&file_path);
1436 if provided_path.is_absolute() {
1437 return Err(FileAdditionError::PathOutsideRepo {
1438 path: provided_path.to_path_buf(),
1439 repo_root: workspace.repo_root()?,
1440 });
1441 }
1442
1443 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
1444 let joined_path = workspace
1445 .repo_root()?
1446 .join(Self::sanitize_relative_path(provided_path)?);
1447 let normalized_path = Self::canonicalize_or_normalize(&joined_path);
1448 if !normalized_path.starts_with(&repo_root) {
1449 return Err(FileAdditionError::PathOutsideRepo {
1450 path: normalized_path,
1451 repo_root,
1452 });
1453 }
1454 Ok(normalized_path)
1455 }
1456
1457 pub(crate) fn logical_file_path(
1458 workspace: &Workspace,
1459 source_path: &Path,
1460 ) -> Result<String, FileAdditionError> {
1461 if source_path.as_os_str().is_empty() {
1462 return Ok(String::new());
1463 }
1464
1465 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
1466 let source_path = Self::canonicalize_or_normalize(source_path);
1467 if let Ok(relative_path) = source_path.strip_prefix(&repo_root) {
1468 return Ok(relative_path.to_string_lossy().to_string());
1469 }
1470
1471 source_path
1472 .file_name()
1473 .map(|file_name| {
1474 format!(
1475 "{}/{}",
1476 Self::OUTSIDE_ROOT_DIRECTORY,
1477 file_name.to_string_lossy()
1478 )
1479 })
1480 .ok_or_else(|| {
1481 FileAdditionError::FileReadError(io::Error::new(
1482 io::ErrorKind::InvalidInput,
1483 format!("asset path has no filename: {}", source_path.display()),
1484 ))
1485 })
1486 }
1487
1488 fn stored_relative_path(
1489 workspace: &Workspace,
1490 source_path: &Path,
1491 checksum: &Sha256Hash,
1492 ) -> Result<String, FileAdditionError> {
1493 if source_path.as_os_str().is_empty() {
1494 return Ok(String::new());
1495 }
1496 let repo_root = Self::canonicalize_or_normalize(&workspace.repo_root()?);
1497 let source_path = Self::canonicalize_or_normalize(source_path);
1498
1499 if source_path.starts_with(&repo_root) {
1500 return Ok(source_path
1501 .strip_prefix(&repo_root)
1502 .map_err(|_| FileAdditionError::PathOutsideRepo {
1503 path: source_path.to_path_buf(),
1504 repo_root: repo_root.clone(),
1505 })?
1506 .to_string_lossy()
1507 .to_string());
1508 }
1509
1510 if source_path.is_absolute() {
1511 let source_asset_uri = Self::new(&source_path.to_string_lossy());
1512 return Self::asset_relative_path(workspace, &source_asset_uri, checksum);
1513 }
1514
1515 Err(FileAdditionError::FileReadError(io::Error::new(
1516 io::ErrorKind::InvalidInput,
1517 format!(
1518 "unable to resolve local asset path: {}",
1519 source_path.display()
1520 ),
1521 )))
1522 }
1523
1524 fn stage_asset_copy(
1527 &self,
1528 workspace: &Workspace,
1529 checksum_override: Option<Sha256Hash>,
1530 ) -> Result<Sha256Hash, FileAdditionError> {
1531 let asset_dir = workspace.asset_dir()?;
1532 fs::create_dir_all(&asset_dir).map_err(FileAdditionError::FileReadError)?;
1533 if let Some(checksum) = checksum_override {
1534 let asset_path = asset_dir.join(self.asset_filename(&checksum));
1535 if asset_path.exists() {
1536 return Ok(checksum);
1537 }
1538 }
1539
1540 let mut reader = ChecksummedReader::new(self.reader(workspace)?);
1541 let checksum_handle = reader.checksum_handle();
1542 let mut staged_file =
1543 NamedTempFile::new_in(&asset_dir).map_err(FileAdditionError::FileReadError)?;
1544 io::copy(&mut reader, &mut staged_file).map_err(FileAdditionError::FileReadError)?;
1545 staged_file
1546 .flush()
1547 .map_err(FileAdditionError::FileReadError)?;
1548 let checksum = checksum_handle.checksum().ok_or_else(|| {
1549 FileAdditionError::ChecksumError(format!(
1550 "local asset stream did not reach EOF: {}",
1551 self.uri()
1552 ))
1553 })?;
1554 if let Some(expected_checksum) = checksum_override
1555 && checksum != expected_checksum
1556 {
1557 return Err(FileAdditionError::ChecksumError(format!(
1558 "local asset checksum does not match the provided checksum: {}",
1559 self.uri()
1560 )));
1561 }
1562
1563 let asset_path = asset_dir.join(self.asset_filename(&checksum));
1564 match staged_file.persist_noclobber(&asset_path) {
1565 Ok(_) => {}
1566 Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
1567 Err(error) => return Err(FileAdditionError::FileReadError(error.error)),
1568 }
1569 Ok(checksum)
1570 }
1571
1572 fn sanitize_relative_path(path: &Path) -> Result<PathBuf, FileAdditionError> {
1573 let mut sanitized = PathBuf::new();
1574 for component in path.components() {
1575 match component {
1576 Component::Normal(part) => sanitized.push(part),
1577 Component::CurDir => {}
1578 Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
1579 return Err(FileAdditionError::FileReadError(io::Error::new(
1580 io::ErrorKind::PermissionDenied,
1581 format!("path escapes workspace root: {}", path.display()),
1582 )));
1583 }
1584 }
1585 }
1586 Ok(sanitized)
1587 }
1588
1589 fn canonicalize_or_normalize(path: &Path) -> PathBuf {
1590 let normalized_path = fs::canonicalize(path).unwrap_or_else(|_| Self::normalize_path(path));
1591 let cleaned_path = normalized_path
1595 .as_path()
1596 .strip_prefix("/private")
1597 .unwrap_or(&normalized_path);
1598 Path::new("/").join(cleaned_path)
1599 }
1600
1601 fn normalize_path(path: &Path) -> PathBuf {
1602 let mut normalized = PathBuf::new();
1603 for component in path.components() {
1604 match component {
1605 Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
1606 Component::RootDir => normalized.push(Path::new("/")),
1607 Component::CurDir => {}
1608 Component::ParentDir => {
1609 normalized.pop();
1610 }
1611 Component::Normal(part) => normalized.push(part),
1612 }
1613 }
1614 normalized
1615 }
1616
1617 pub fn store_file(
1618 file_addition: &FileAddition,
1619 workspace: &Workspace,
1620 ) -> Result<(), FileStoreError> {
1621 let checksum = file_addition.checksum.ok_or_else(|| {
1622 FileStoreError::IoError(io::Error::new(
1623 io::ErrorKind::InvalidInput,
1624 format!(
1625 "cannot store local asset without checksum: {}",
1626 file_addition.asset_uri
1627 ),
1628 ))
1629 })?;
1630 let asset_uri = Self::new(&file_addition.asset_uri);
1631 let asset_path = workspace
1632 .asset_dir()?
1633 .join(asset_uri.asset_filename(&checksum));
1634 if asset_path.exists() {
1635 return Ok(());
1636 }
1637
1638 asset_uri
1639 .stage_asset_copy(workspace, Some(checksum))
1640 .map(|_| ())
1641 .map_err(|error| match error {
1642 FileAdditionError::ConfigError(error) => FileStoreError::ConfigError(error),
1643 FileAdditionError::FileReadError(error) => FileStoreError::IoError(error),
1644 other => FileStoreError::IoError(io::Error::other(other)),
1645 })
1646 }
1647}
1648
1649impl Read for LocalAssetUri {
1650 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1651 if self.read_file.is_none() {
1652 let io_path = self.io_path();
1653 self.read_file = Some(
1654 OpenDalLocation::from_absolute_path(&io_path)
1655 .map_err(io::Error::other)?
1656 .reader()
1657 .map_err(io::Error::other)?,
1658 );
1659 }
1660 self.read_file.as_mut().unwrap().read(buf)
1661 }
1662}
1663
1664impl Write for LocalAssetUri {
1665 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1666 if self.write_file.is_none() {
1667 let io_path = self.io_path();
1668 let location =
1669 OpenDalLocation::from_absolute_path(&io_path).map_err(io::Error::other)?;
1670 self.write_file = Some(
1671 location
1672 .operator
1673 .writer(&location.path)
1674 .map_err(io::Error::other)?
1675 .into_std_write(),
1676 );
1677 }
1678 self.write_file.as_mut().unwrap().write(buf)
1679 }
1680
1681 fn flush(&mut self) -> io::Result<()> {
1682 if let Some(file) = self.write_file.as_mut() {
1683 file.flush()
1684 } else {
1685 Ok(())
1686 }
1687 }
1688}
1689
1690impl Drop for LocalAssetUri {
1691 fn drop(&mut self) {
1692 let _ = self.close_write();
1693 }
1694}
1695
1696pub struct RemoteAssetUri {
1697 asset_uri: String,
1698}
1699
1700impl AssetUri for RemoteAssetUri {
1701 fn uri(&self) -> &str {
1702 &self.asset_uri
1703 }
1704
1705 fn reader(&self, _workspace: &Workspace) -> Result<blocking::StdReader, FileAdditionError> {
1706 OpenDalLocation::from_remote_uri(&self.asset_uri)
1707 }
1708
1709 fn prepare_asset(
1710 &self,
1711 _workspace: &Workspace,
1712 checksum_override: Option<Sha256Hash>,
1713 ) -> Result<Option<Sha256Hash>, FileAdditionError> {
1714 Ok(checksum_override)
1717 }
1718
1719 fn stored_asset_uri(
1720 &self,
1721 _workspace: &Workspace,
1722 _checksum: &Sha256Hash,
1723 ) -> Result<String, FileAdditionError> {
1724 Ok(self.asset_uri.clone())
1725 }
1726
1727 fn store_file(
1728 &self,
1729 _file_addition: &FileAddition,
1730 _workspace: &Workspace,
1731 ) -> Result<(), FileStoreError> {
1732 Ok(())
1733 }
1734}
1735
1736impl RemoteAssetUri {
1737 pub fn new(asset_uri: &str) -> Self {
1738 Self {
1739 asset_uri: asset_uri.to_string(),
1740 }
1741 }
1742}
1743
1744#[cfg(test)]
1745mod tests {
1746 use std::{
1747 fs,
1748 io::{Read, Seek, SeekFrom, Write},
1749 net::TcpListener,
1750 path::PathBuf,
1751 thread,
1752 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
1753 };
1754
1755 use super::*;
1756 use crate::{
1757 history::dolt::commit_all,
1758 operations::{FileAddition, calculate_file_checksum, calculate_reader_checksum},
1759 test_helpers::setup_gen,
1760 };
1761
1762 #[test]
1763 fn test_asset_uri_compression_type_infers_known_suffixes() {
1764 for (uri, expected) in [
1765 ("reference.GZ", CompressionType::Gzip),
1766 ("reference.fa.Gz?download=1#fragment", CompressionType::Gzip),
1767 (
1768 "file://reference.vcf.Gz?download=1#fragment",
1769 CompressionType::Gzip,
1770 ),
1771 (
1772 "https://example.test/reference.vcf.BGZ?download=1#fragment",
1773 CompressionType::Bgzf,
1774 ),
1775 (
1776 "https://example.test/reference.BgZf?token=1",
1777 CompressionType::Bgzf,
1778 ),
1779 ("s3://bucket/sample.BaM#fragment", CompressionType::Bgzf),
1780 (
1781 "https://example.test/reference.vcf?download=1",
1782 CompressionType::Plain,
1783 ),
1784 ] {
1785 assert_eq!(
1786 <dyn AssetUri>::from_uri(uri).compression_type(),
1787 expected,
1788 "unexpected compression inference for {uri}"
1789 );
1790 }
1791 }
1792
1793 #[test]
1794 fn test_materialized_asset_compression_type_respects_workspace_bytes() {
1795 let asset = |logical_path: Option<&str>, materialized_checksum| AssetRef {
1796 id: HashId::convert_str("compression-type-test"),
1797 uri: "file://.gen/assets/archive.bgz".to_string(),
1798 file_type: FileTypes::None.as_str().to_string(),
1799 checksum: Some(Sha256Hash::convert_str("archive-checksum")),
1800 materialized_checksum,
1801 size: None,
1802 role: AssetRole::Input,
1803 logical_path: logical_path.map(str::to_string),
1804 name: None,
1805 created_on: 1,
1806 upstream_asset_ref_id: None,
1807 };
1808
1809 assert_eq!(
1810 asset(Some("reads.bam"), None).materialized_compression_type(),
1811 CompressionType::Bgzf
1812 );
1813 assert_eq!(
1814 asset(
1815 Some("ordinary.fa.gz"),
1816 Some(Sha256Hash::convert_str("materialized-checksum"))
1817 )
1818 .materialized_compression_type(),
1819 CompressionType::Plain,
1820 "materialized workspace bytes are plain even when their logical path ends in .gz"
1821 );
1822 assert_eq!(
1823 asset(None, None).materialized_compression_type(),
1824 CompressionType::Plain
1825 );
1826 assert_eq!(
1827 asset(Some(""), None).materialized_compression_type(),
1828 CompressionType::Plain
1829 );
1830 }
1831
1832 fn test_asset_id_hash(
1833 checksum: Option<Sha256Hash>,
1834 materialized_checksum: Option<Sha256Hash>,
1835 upstream_asset_ref_id: Option<&HashId>,
1836 ) -> HashId {
1837 let file_addition = FileAddition {
1838 id: HashId::convert_str("asset-id-test"),
1839 asset_uri: "https://example.test/reference.fa".to_string(),
1840 file_type: FileTypes::Fasta,
1841 checksum,
1842 materialized_checksum,
1843 };
1844 AssetRef::id_hash(
1845 &file_addition,
1846 &AssetRole::Input,
1847 Some("reference.fa"),
1848 Some("reference.fa"),
1849 upstream_asset_ref_id,
1850 )
1851 }
1852
1853 #[test]
1854 fn test_asset_id_hash_includes_optional_checksums_and_upstream() {
1855 let upstream = None;
1860 let id = test_asset_id_hash(None, None, upstream);
1861 let expected_identity =
1862 "https://example.test/reference.fa:fasta:::input:reference.fa:reference.fa";
1863 assert_eq!(
1864 id,
1865 HashId(calculate_hash(expected_identity)),
1866 "None checksums should occupy their fields in the unified identity"
1867 );
1868
1869 assert_eq!(
1871 id,
1872 test_asset_id_hash(None, None, upstream),
1873 "the same asset identity should hash deterministically"
1874 );
1875
1876 assert_ne!(
1878 id,
1879 test_asset_id_hash(
1880 Some(Sha256Hash::convert_str("archived-content")),
1881 None,
1882 None,
1883 ),
1884 "an archive checksum should change the identity"
1885 );
1886
1887 assert_ne!(
1889 id,
1890 test_asset_id_hash(
1891 None,
1892 Some(Sha256Hash::convert_str("materialized-content")),
1893 None,
1894 ),
1895 "a materialized checksum should change the identity"
1896 );
1897
1898 assert_ne!(
1900 test_asset_id_hash(
1901 None,
1902 Some(Sha256Hash::convert_str("materialized-content")),
1903 None,
1904 ),
1905 test_asset_id_hash(
1906 None,
1907 Some(Sha256Hash::convert_str("different-materialized-content")),
1908 None,
1909 ),
1910 "different materialized bytes should have different identities"
1911 );
1912
1913 let both_checksums_id = test_asset_id_hash(
1915 Some(Sha256Hash::convert_str("archived-content")),
1916 Some(Sha256Hash::convert_str("materialized-content")),
1917 None,
1918 );
1919
1920 assert_ne!(
1922 both_checksums_id,
1923 test_asset_id_hash(
1924 Some(Sha256Hash::convert_str("different-archived-content")),
1925 Some(Sha256Hash::convert_str("materialized-content")),
1926 None,
1927 ),
1928 "different archived bytes should change identity with materialized bytes fixed"
1929 );
1930
1931 assert_ne!(
1933 both_checksums_id,
1934 test_asset_id_hash(
1935 Some(Sha256Hash::convert_str("archived-content")),
1936 Some(Sha256Hash::convert_str("different-materialized-content")),
1937 None,
1938 ),
1939 "different materialized bytes should change identity with archived bytes fixed"
1940 );
1941
1942 let first_upstream = HashId::convert_str("first-upstream");
1944 let second_upstream = HashId::convert_str("second-upstream");
1945 assert_ne!(
1946 test_asset_id_hash(None, None, Some(&first_upstream),),
1947 test_asset_id_hash(None, None, Some(&second_upstream),),
1948 "the upstream asset should remain part of the identity"
1949 );
1950 }
1951
1952 #[test]
1953 fn test_asset_reference_tables_round_trip() {
1954 let context = setup_gen();
1955 let conn = context.graph().conn();
1956 let asset_ref = AssetRef {
1957 id: HashId::convert_str("asset-ref"),
1958 uri: "s3://bucket/reference.fa".to_string(),
1959 file_type: "fasta".to_string(),
1960 checksum: Some(Sha256Hash::convert_str("checksum")),
1961 size: Some(1024),
1962 role: AssetRole::Input,
1963 logical_path: Some("refs/reference.fa".to_string()),
1964 name: Some("reference.fa".to_string()),
1965 created_on: 1,
1966 upstream_asset_ref_id: None,
1967 materialized_checksum: Some(Sha256Hash::convert_str("materialized-checksum")),
1968 };
1969 let operation_log = OperationLog {
1970 id: HashId::convert_str("log"),
1971 operation_kind: OperationKind::Other("import".to_string()),
1972 command: "gen import fasta".to_string(),
1973 created_on: 1,
1974 };
1975 let operation_asset = OperationAsset {
1976 log_id: operation_log.id,
1977 asset_ref_id: asset_ref.id,
1978 role: AssetRole::Input,
1979 };
1980
1981 OperationLog::create(conn, &operation_log).expect("should insert operation log");
1982 AssetRef::create(conn, &asset_ref).expect("should insert asset ref");
1983 OperationAsset::create(conn, &operation_asset).expect("should insert operation asset");
1984
1985 let asset_refs = AssetRef::all(conn).expect("should load asset references");
1986 let operation_logs = OperationLog::all(conn).expect("should load operation logs");
1987 let operation_assets = OperationAsset::all(conn).expect("should load operation assets");
1988
1989 assert_eq!(asset_refs, vec![asset_ref]);
1990 assert_eq!(operation_logs, vec![operation_log]);
1991 assert_eq!(operation_assets, vec![operation_asset]);
1992 }
1993
1994 #[test]
1995 fn test_asset_reference_supports_multiple_derived_assets() {
1996 let context = setup_gen();
1997 let conn = context.graph().conn();
1998 let upstream = AssetRef {
1999 id: HashId::convert_str("sequence-asset"),
2000 uri: "file://reference.fa.bgz".to_string(),
2001 file_type: "fasta".to_string(),
2002 checksum: Some(Sha256Hash::convert_str("sequence-checksum")),
2003 size: None,
2004 role: AssetRole::Input,
2005 logical_path: Some("reference.fa.bgz".to_string()),
2006 name: Some("reference.fa.bgz".to_string()),
2007 created_on: 1,
2008 upstream_asset_ref_id: None,
2009 materialized_checksum: None,
2010 };
2011 let first_index = AssetRef {
2012 id: HashId::convert_str("first-index"),
2013 uri: "file://reference.fa.bgz.fai".to_string(),
2014 file_type: "none".to_string(),
2015 checksum: Some(Sha256Hash::convert_str("first-index-checksum")),
2016 size: None,
2017 role: AssetRole::Other("index".to_string()),
2018 logical_path: Some("reference.fa.bgz.fai".to_string()),
2019 name: Some("reference.fa.bgz.fai".to_string()),
2020 created_on: 1,
2021 upstream_asset_ref_id: Some(upstream.id),
2022 materialized_checksum: None,
2023 };
2024 let second_index = AssetRef {
2025 id: HashId::convert_str("second-index"),
2026 uri: "file://reference.fa.bgz.gzi".to_string(),
2027 checksum: Some(Sha256Hash::convert_str("second-index-checksum")),
2028 logical_path: Some("reference.fa.bgz.gzi".to_string()),
2029 name: Some("reference.fa.bgz.gzi".to_string()),
2030 ..first_index.clone()
2031 };
2032 AssetRef::create(conn, &upstream).expect("should insert upstream asset");
2033 AssetRef::create(conn, &first_index).expect("should insert first derived asset");
2034 AssetRef::create(conn, &second_index).expect("should insert second derived asset");
2035 let commit = commit_all(conn, "add derived assets").expect("should commit derived assets");
2036
2037 assert_eq!(
2038 AssetRef::get_derived_assets(conn, &upstream.id, None),
2039 vec![first_index.clone(), second_index.clone()],
2040 "current lookup should return every derived asset"
2041 );
2042 assert_eq!(
2043 AssetRef::get_derived_assets(conn, &upstream.id, Some(&commit.to_string())),
2044 vec![first_index, second_index],
2045 "historical lookup should return every derived asset"
2046 );
2047 }
2048
2049 #[test]
2050 fn test_get_annotation_files_pairs_annotation_and_index_in_one_query() {
2051 let context = setup_gen();
2052 let conn = context.graph().conn();
2053 let log = OperationLog {
2054 id: HashId::convert_str("annotation-log"),
2055 operation_kind: OperationKind::AnnotationFile,
2056 command: "add annotation".to_string(),
2057 created_on: 1,
2058 };
2059 let annotation = AssetRef {
2060 id: HashId::convert_str("annotation-asset"),
2061 uri: "file://annotation.gff".to_string(),
2062 file_type: "gff3".to_string(),
2063 checksum: Some(Sha256Hash::convert_str("annotation-checksum")),
2064 size: None,
2065 role: AssetRole::Annotation,
2066 logical_path: Some("annotation.gff".to_string()),
2067 name: Some("genes".to_string()),
2068 created_on: 1,
2069 upstream_asset_ref_id: None,
2070 materialized_checksum: Some(Sha256Hash::convert_str("annotation-materialized")),
2071 };
2072 let index = AssetRef {
2073 id: HashId::convert_str("annotation-index-asset"),
2074 uri: "file://annotation.gff.tbi".to_string(),
2075 file_type: "tabix".to_string(),
2076 checksum: Some(Sha256Hash::convert_str("annotation-index-checksum")),
2077 size: None,
2078 role: AssetRole::AnnotationIndex,
2079 logical_path: Some("annotation.gff.tbi".to_string()),
2080 name: Some("genes".to_string()),
2081 created_on: 1,
2082 upstream_asset_ref_id: Some(annotation.id),
2083 materialized_checksum: None,
2084 };
2085 OperationLog::create(conn, &log).expect("should insert annotation log");
2086 AssetRef::create(conn, &annotation).expect("should insert annotation asset");
2087 AssetRef::create(conn, &index).expect("should insert annotation index asset");
2088 OperationAsset::create(
2089 conn,
2090 &OperationAsset {
2091 log_id: log.id,
2092 asset_ref_id: annotation.id,
2093 role: AssetRole::Annotation,
2094 },
2095 )
2096 .expect("should associate annotation asset");
2097 OperationAsset::create(
2098 conn,
2099 &OperationAsset {
2100 log_id: log.id,
2101 asset_ref_id: index.id,
2102 role: AssetRole::AnnotationIndex,
2103 },
2104 )
2105 .expect("should associate annotation index asset");
2106 let commit = commit_all(conn, "add annotation assets").expect("should commit assets");
2107
2108 let expected = vec![AnnotationFileAssets {
2109 log_id: log.id,
2110 annotation,
2111 index: Some(index),
2112 }];
2113 assert_eq!(
2114 Assets::get_annotation_files(conn, None).expect("should query current annotations"),
2115 expected
2116 );
2117 assert_eq!(
2118 Assets::get_annotation_files(conn, Some(&commit.to_string()))
2119 .expect("should query historical annotations"),
2120 expected
2121 );
2122 }
2123
2124 mod asset_history {
2125 use gen_core::{DoltHashId, HashId, Sha256Hash};
2126
2127 use super::{AssetRef, AssetRole, AssetView};
2128 use crate::{
2129 db::{DbContext, GraphConnection},
2130 history::dolt::{checkout, commit_all, create_branch},
2131 test_helpers::setup_gen,
2132 };
2133
2134 struct AssetHistoryFixture {
2141 context: DbContext,
2142 first_alpha: AssetRef,
2143 second_alpha: AssetRef,
2144 beta: AssetRef,
2145 zeta: AssetRef,
2146 first_commit: DoltHashId,
2147 second_commit: DoltHashId,
2148 deletion_commit: DoltHashId,
2149 latest_commit: DoltHashId,
2150 }
2151
2152 impl AssetHistoryFixture {
2153 fn new() -> Self {
2154 let context = setup_gen();
2155 let conn = context.graph().conn();
2156 let first_alpha = AssetRef {
2157 id: HashId::convert_str("first-alpha"),
2158 uri: "file://assets/first-alpha.fa".to_string(),
2159 file_type: "fasta".to_string(),
2160 checksum: Some(Sha256Hash::convert_str("first-alpha-checksum")),
2161 size: Some(4),
2162 role: AssetRole::Input,
2163 logical_path: Some("alpha.fa".to_string()),
2164 name: Some("alpha.fa".to_string()),
2165 created_on: 1,
2166 upstream_asset_ref_id: None,
2167 materialized_checksum: None,
2168 };
2169 let zeta = AssetRef {
2170 id: HashId::convert_str("zeta"),
2171 uri: "file://assets/zeta.fa".to_string(),
2172 checksum: Some(Sha256Hash::convert_str("zeta-checksum")),
2173 logical_path: Some("zeta.fa".to_string()),
2174 name: Some("zeta.fa".to_string()),
2175 ..first_alpha.clone()
2176 };
2177 let remote_asset = AssetRef {
2178 id: HashId::convert_str("remote-asset"),
2179 uri: "https://example.com/reference.fa".to_string(),
2180 logical_path: Some("remote.fa".to_string()),
2181 name: Some("remote.fa".to_string()),
2182 ..first_alpha.clone()
2183 };
2184 AssetRef::create(conn, &zeta).expect("should insert zeta asset");
2185 AssetRef::create(conn, &first_alpha).expect("should insert first alpha asset");
2186 AssetRef::create(conn, &remote_asset).expect("should insert remote asset");
2187 let first_commit =
2188 commit_all(conn, "add first assets").expect("should commit first assets");
2189
2190 let second_alpha = AssetRef {
2191 id: HashId::convert_str("second-alpha"),
2192 uri: "file://assets/second-alpha.fa".to_string(),
2193 checksum: Some(Sha256Hash::convert_str("second-alpha-checksum")),
2194 created_on: 0,
2195 ..first_alpha.clone()
2196 };
2197 AssetRef::create(conn, &second_alpha).expect("should insert second alpha asset");
2198 let second_commit = commit_all(conn, "replace alpha asset")
2199 .expect("should commit replacement asset");
2200
2201 conn.execute("DELETE FROM gen_asset_refs WHERE id = ?1", [first_alpha.id])
2202 .expect("should delete superseded alpha asset");
2203 let deletion_commit = commit_all(conn, "delete superseded asset")
2204 .expect("should commit asset deletion");
2205
2206 let beta = AssetRef {
2207 id: HashId::convert_str("beta"),
2208 uri: "file://assets/beta.fa".to_string(),
2209 checksum: Some(Sha256Hash::convert_str("beta-checksum")),
2210 logical_path: Some("beta.fa".to_string()),
2211 name: Some("beta.fa".to_string()),
2212 created_on: 3,
2213 ..first_alpha.clone()
2214 };
2215 AssetRef::create(conn, &beta).expect("should insert beta asset");
2216 let latest_commit =
2217 commit_all(conn, "add later beta asset").expect("should commit later asset");
2218
2219 Self {
2220 context,
2221 first_alpha,
2222 second_alpha,
2223 beta,
2224 zeta,
2225 first_commit,
2226 second_commit,
2227 deletion_commit,
2228 latest_commit,
2229 }
2230 }
2231
2232 fn conn(&self) -> &GraphConnection {
2233 self.context.graph().conn()
2234 }
2235 }
2236
2237 fn sorted_assets(mut assets: Vec<AssetRef>) -> Vec<AssetRef> {
2238 assets.sort_by(|left, right| {
2239 left.logical_path
2240 .cmp(&right.logical_path)
2241 .then_with(|| left.id.cmp(&right.id))
2242 });
2243 assets
2244 }
2245
2246 #[test]
2247 fn test_materialized_assets_at_selects_latest_version_per_path() {
2248 let fixture = AssetHistoryFixture::new();
2249
2250 assert_eq!(
2251 AssetRef::get_materialized_assets_at(
2252 fixture.conn(),
2253 None,
2254 Some(&fixture.second_commit),
2255 )
2256 .expect("should materialize second commit"),
2257 vec![fixture.second_alpha.clone(), fixture.zeta.clone()]
2258 );
2259 }
2260
2261 #[test]
2262 fn test_materialized_assets_at_uses_commit_order_in_a_bounded_range() {
2263 let fixture = AssetHistoryFixture::new();
2264
2265 assert_eq!(
2266 AssetRef::get_materialized_assets_at(
2267 fixture.conn(),
2268 Some(&fixture.second_commit),
2269 Some(&fixture.second_commit),
2270 )
2271 .expect("should materialize using commit order"),
2272 vec![fixture.second_alpha.clone(), fixture.zeta.clone()]
2273 );
2274 }
2275
2276 #[test]
2277 fn test_materialized_assets_at_excludes_deleted_versions() {
2278 let fixture = AssetHistoryFixture::new();
2279
2280 assert_eq!(
2281 AssetRef::get_materialized_assets_at(
2282 fixture.conn(),
2283 None,
2284 Some(&fixture.deletion_commit),
2285 )
2286 .expect("should materialize deletion commit"),
2287 vec![fixture.second_alpha.clone(), fixture.zeta.clone()]
2288 );
2289 }
2290
2291 #[test]
2292 fn test_materialized_assets_at_reads_non_current_branch_by_hash() {
2293 let context = setup_gen();
2296 let conn = context.graph().conn();
2297 let main_asset = AssetRef {
2298 id: HashId::convert_str("main-asset"),
2299 uri: "file://assets/main.fa".to_string(),
2300 file_type: "fasta".to_string(),
2301 checksum: Some(Sha256Hash::convert_str("main-checksum")),
2302 size: Some(4),
2303 role: AssetRole::Input,
2304 logical_path: Some("reference.fa".to_string()),
2305 name: Some("reference.fa".to_string()),
2306 created_on: 1,
2307 upstream_asset_ref_id: None,
2308 materialized_checksum: Some(Sha256Hash::convert_str("main-materialized")),
2309 };
2310 AssetRef::create(conn, &main_asset).expect("should insert main asset");
2311 commit_all(conn, "add main asset").expect("should commit main asset");
2312 create_branch(conn, "feature").expect("should create feature branch");
2313 checkout(conn, "feature").expect("should checkout feature branch");
2314
2315 let feature_asset = AssetRef {
2316 id: HashId::convert_str("feature-asset"),
2317 uri: "file://assets/feature.fa".to_string(),
2318 checksum: Some(Sha256Hash::convert_str("feature-checksum")),
2319 created_on: 2,
2320 ..main_asset
2321 };
2322 AssetRef::create(conn, &feature_asset).expect("should insert feature asset");
2323 let feature_commit =
2324 commit_all(conn, "add feature asset").expect("should commit feature asset");
2325 checkout(conn, "main").expect("should restore main branch");
2326
2327 assert_eq!(
2328 AssetRef::get_materialized_assets_at(conn, None, Some(&feature_commit))
2329 .expect("should read assets from the non-current feature commit"),
2330 vec![feature_asset],
2331 "the history range should start at the requested feature commit"
2332 );
2333 }
2334
2335 #[test]
2336 fn test_cumulative_assets_at_retains_superseded_and_deleted_versions() {
2337 let fixture = AssetHistoryFixture::new();
2338 let expected = sorted_assets(vec![
2339 fixture.first_alpha.clone(),
2340 fixture.second_alpha.clone(),
2341 fixture.zeta.clone(),
2342 ]);
2343
2344 assert_eq!(
2345 AssetRef::get_cumulative_assets_at(
2346 fixture.conn(),
2347 None,
2348 Some(&fixture.deletion_commit),
2349 )
2350 .expect("should read cumulative assets at deletion commit"),
2351 expected
2352 );
2353 }
2354
2355 #[test]
2356 fn test_asset_queries_respect_commit_range() {
2357 let fixture = AssetHistoryFixture::new();
2358 let expected = vec![
2359 fixture.second_alpha.clone(),
2360 fixture.beta.clone(),
2361 fixture.zeta.clone(),
2362 ];
2363
2364 assert_eq!(
2365 AssetRef::get_materialized_assets_at(
2366 fixture.conn(),
2367 Some(&fixture.deletion_commit),
2368 Some(&fixture.latest_commit),
2369 )
2370 .expect("should materialize bounded range"),
2371 expected
2372 );
2373 assert_eq!(
2374 AssetRef::get_cumulative_assets_at(
2375 fixture.conn(),
2376 Some(&fixture.deletion_commit),
2377 Some(&fixture.latest_commit),
2378 )
2379 .expect("should accumulate bounded range"),
2380 sorted_assets(vec![
2381 fixture.second_alpha.clone(),
2382 fixture.beta.clone(),
2383 fixture.zeta.clone(),
2384 ])
2385 );
2386 }
2387
2388 #[test]
2389 fn test_asset_queries_default_missing_upper_bound_to_head() {
2390 let fixture = AssetHistoryFixture::new();
2391
2392 assert_eq!(
2393 AssetRef::get_materialized_assets_at(
2394 fixture.conn(),
2395 Some(&fixture.deletion_commit),
2396 None,
2397 )
2398 .expect("should materialize through HEAD"),
2399 vec![
2400 fixture.second_alpha.clone(),
2401 fixture.beta.clone(),
2402 fixture.zeta.clone(),
2403 ]
2404 );
2405 }
2406
2407 #[test]
2408 fn test_cumulative_assets_without_bounds_reads_full_head_history() {
2409 let fixture = AssetHistoryFixture::new();
2410 let expected = sorted_assets(vec![
2411 fixture.first_alpha.clone(),
2412 fixture.second_alpha.clone(),
2413 fixture.beta.clone(),
2414 fixture.zeta.clone(),
2415 ]);
2416
2417 assert_eq!(
2418 AssetRef::get_cumulative_assets_at(fixture.conn(), None, None)
2419 .expect("should read full history through HEAD"),
2420 expected
2421 );
2422 }
2423
2424 #[test]
2425 fn test_assets_by_commit_orders_commits_and_preserves_empty_entries() {
2426 let fixture = AssetHistoryFixture::new();
2427 let assets_by_commit = AssetRef::get_assets_by_commit(
2428 fixture.conn(),
2429 Some(&fixture.first_commit),
2430 Some(&fixture.latest_commit),
2431 AssetView::Cumulative,
2432 )
2433 .expect("should group assets by introduction commit");
2434 let assets = sorted_assets(
2435 assets_by_commit
2436 .values()
2437 .flatten()
2438 .cloned()
2439 .collect::<Vec<_>>(),
2440 );
2441
2442 assert_eq!(
2443 assets,
2444 AssetRef::get_cumulative_assets_at(
2445 fixture.conn(),
2446 Some(&fixture.first_commit),
2447 Some(&fixture.latest_commit),
2448 )
2449 .expect("should preserve the cumulative asset-only view")
2450 );
2451 assert_eq!(
2452 assets_by_commit.keys().copied().collect::<Vec<_>>(),
2453 vec![
2454 fixture.first_commit,
2455 fixture.second_commit,
2456 fixture.deletion_commit,
2457 fixture.latest_commit,
2458 ]
2459 );
2460 assert_eq!(
2461 assets_by_commit
2462 .get(&fixture.second_commit)
2463 .expect("should contain second commit")
2464 .as_slice(),
2465 core::slice::from_ref(&fixture.second_alpha)
2466 );
2467 assert!(
2468 assets_by_commit
2469 .get(&fixture.deletion_commit)
2470 .expect("should contain deletion commit")
2471 .is_empty(),
2472 "commits without introduced assets should retain empty entries"
2473 );
2474 }
2475 }
2476
2477 #[test]
2478 fn test_get_branch_assets_uses_materialized_assets_at_branch_head() {
2479 let context = setup_gen();
2480 let conn = context.graph().conn();
2481 let first_asset = AssetRef {
2482 id: HashId::convert_str("first-asset"),
2483 uri: "file://assets/first.fa".to_string(),
2484 file_type: "fasta".to_string(),
2485 checksum: Some(Sha256Hash::convert_str("first-checksum")),
2486 size: Some(4),
2487 role: AssetRole::Input,
2488 logical_path: Some("reference.fa".to_string()),
2489 name: Some("reference.fa".to_string()),
2490 created_on: 1,
2491 upstream_asset_ref_id: None,
2492 materialized_checksum: None,
2493 };
2494 AssetRef::create(conn, &first_asset).expect("should insert first asset");
2495 commit_all(conn, "add first asset").expect("should commit first asset");
2496
2497 let replacement_asset = AssetRef {
2498 id: HashId::convert_str("replacement-asset"),
2499 uri: "file://assets/replacement.fa".to_string(),
2500 checksum: Some(Sha256Hash::convert_str("replacement-checksum")),
2501 created_on: 2,
2502 ..first_asset
2503 };
2504 AssetRef::create(conn, &replacement_asset).expect("should insert replacement asset");
2505 commit_all(conn, "replace asset").expect("should commit replacement asset");
2506
2507 let assets =
2508 Assets::get_branch_assets(conn, "main").expect("should read assets from branch head");
2509
2510 assert_eq!(
2511 assets,
2512 HashMap::from([(replacement_asset.id, replacement_asset)])
2513 );
2514 }
2515
2516 #[test]
2517 fn test_generate_file_addition_id_consistency() {
2518 let checksum = Sha256Hash([1u8; 32]);
2519 let file_path = "/path/to/file.txt";
2520
2521 let id1 = LocalAssetUri::generate_file_addition_id(Some(&checksum), file_path);
2522 let id2 = LocalAssetUri::generate_file_addition_id(Some(&checksum), file_path);
2523
2524 assert_eq!(id1, id2);
2525 }
2526
2527 #[test]
2528 fn test_generate_file_addition_id_uniqueness_different_paths() {
2529 let checksum = Sha256Hash([1u8; 32]);
2530 let file_path1 = "/path/to/file1.txt";
2531 let file_path2 = "/path/to/file2.txt";
2532
2533 let id1 = LocalAssetUri::generate_file_addition_id(Some(&checksum), file_path1);
2534 let id2 = LocalAssetUri::generate_file_addition_id(Some(&checksum), file_path2);
2535
2536 assert_ne!(id1, id2);
2537 }
2538
2539 #[test]
2540 fn test_generate_file_addition_id_uniqueness_different_checksums() {
2541 let checksum1 = Sha256Hash([1u8; 32]);
2542 let checksum2 = Sha256Hash([2u8; 32]);
2543 let file_path = "/path/to/file.txt";
2544
2545 let id1 = LocalAssetUri::generate_file_addition_id(Some(&checksum1), file_path);
2546 let id2 = LocalAssetUri::generate_file_addition_id(Some(&checksum2), file_path);
2547
2548 assert_ne!(id1, id2);
2549 }
2550
2551 #[test]
2552 fn test_resolve_source_path_rejects_absolute_path_from_file_in_repo() {
2553 let context = setup_gen();
2554 let workspace = context.workspace();
2555 let repo_root = workspace.base_dir();
2556
2557 let absolute_path = repo_root.join("inputs").join("absolute.txt");
2558 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
2559 fs::write(&absolute_path, b"absolute").unwrap();
2560 let absolute_string = absolute_path.to_string_lossy().to_string();
2561
2562 let err =
2563 LocalAssetUri::resolve_source_path(workspace, absolute_string.as_str()).unwrap_err();
2564 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
2565 }
2566
2567 #[test]
2568 fn test_stored_relative_path_returns_relative_path_from_file_in_repo() {
2569 let context = setup_gen();
2570 let workspace = context.workspace();
2571 let repo_root = workspace.base_dir();
2572
2573 let absolute_path = repo_root.join("inputs").join("absolute.txt");
2574 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
2575 fs::write(&absolute_path, b"absolute").unwrap();
2576 let relative_string = absolute_path
2577 .strip_prefix(repo_root)
2578 .unwrap()
2579 .to_string_lossy()
2580 .to_string();
2581
2582 let relative = LocalAssetUri::stored_relative_path(
2583 workspace,
2584 &absolute_path,
2585 &calculate_file_checksum(&absolute_path).unwrap(),
2586 )
2587 .unwrap();
2588
2589 assert_eq!(relative, relative_string);
2590 }
2591
2592 #[test]
2593 fn test_resolve_source_path_returns_absolute_path_from_relative_path_in_repo() {
2594 let context = setup_gen();
2595 let workspace = context.workspace();
2596 let repo_root = workspace.repo_root().unwrap();
2597
2598 let relative_path = PathBuf::from("relative/path/file.txt");
2599 let absolute_path = repo_root.join(&relative_path);
2600 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
2601 fs::write(&absolute_path, b"relative").unwrap();
2602 let relative_string = relative_path.to_string_lossy().to_string();
2603 let absolute_string = absolute_path.to_string_lossy().to_string();
2604
2605 let absolute =
2606 LocalAssetUri::resolve_source_path(workspace, relative_string.as_str()).unwrap();
2607
2608 assert_eq!(absolute, PathBuf::from(absolute_string));
2609 }
2610
2611 #[test]
2612 fn test_stored_relative_path_returns_relative_path_from_relative_path_in_repo() {
2613 let context = setup_gen();
2614 let workspace = context.workspace();
2615 let repo_root = workspace.repo_root().unwrap();
2616
2617 let relative_path = PathBuf::from("relative/path/file.txt");
2618 let absolute_path = repo_root.join(&relative_path);
2619 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
2620 fs::write(&absolute_path, b"relative").unwrap();
2621 let relative_string = relative_path.to_string_lossy().to_string();
2622
2623 let relative = LocalAssetUri::stored_relative_path(
2624 workspace,
2625 &absolute_path,
2626 &calculate_file_checksum(&absolute_path).unwrap(),
2627 )
2628 .unwrap();
2629
2630 assert_eq!(relative, relative_string);
2631 }
2632
2633 #[test]
2634 fn test_resolve_source_path_rejects_absolute_path_outside_repo() {
2635 let context = setup_gen();
2636 let workspace = context.workspace();
2637
2638 let mut outside_file = tempfile::NamedTempFile::new().unwrap();
2639 outside_file.write_all(b"outside repo").unwrap();
2640 outside_file.flush().unwrap();
2641 let outside_string = outside_file.path().to_string_lossy().to_string();
2642
2643 let err =
2644 LocalAssetUri::resolve_source_path(workspace, outside_string.as_str()).unwrap_err();
2645 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
2646 }
2647
2648 #[test]
2649 fn test_stored_relative_path_returns_asset_path_on_file_outside_repo() {
2650 let context = setup_gen();
2651 let workspace = context.workspace();
2652
2653 let mut outside_file = tempfile::NamedTempFile::new().unwrap();
2654 outside_file.write_all(b"outside repo").unwrap();
2655 outside_file.flush().unwrap();
2656 let checksum = calculate_file_checksum(outside_file.path()).unwrap();
2657 let outside_suffix = LocalAssetUri::new(&outside_file.path().to_string_lossy())
2658 .suffix()
2659 .unwrap();
2660
2661 let relative =
2662 LocalAssetUri::stored_relative_path(workspace, outside_file.path(), &checksum).unwrap();
2663
2664 assert_eq!(relative, format!(".gen/assets/{checksum}.{outside_suffix}"));
2665 }
2666
2667 #[test]
2668 fn test_new_for_workspace_namespaces_path_outside_workspace() {
2669 let context = setup_gen();
2670 let outside_dir = tempfile::tempdir().unwrap();
2671 let outside_path = outside_dir.path().join("simple.fa");
2672 fs::write(&outside_path, b">seq\nACGT\n").unwrap();
2673
2674 let asset_uri =
2675 LocalAssetUri::new_for_workspace(context.workspace(), &outside_path.to_string_lossy())
2676 .unwrap();
2677
2678 assert_eq!(asset_uri.uri(), "file://.gen/outside_root/simple.fa");
2679 assert_eq!(asset_uri.suffix().as_deref(), Some("fa"));
2680 }
2681
2682 #[test]
2683 fn test_new_for_workspace_distinguishes_external_file_from_workspace_root_file() {
2684 let context = setup_gen();
2685 let workspace_path = context.workspace().repo_root().unwrap().join("simple.fa");
2686 fs::write(&workspace_path, b"workspace file").unwrap();
2687 let outside_dir = tempfile::tempdir().unwrap();
2688 let outside_path = outside_dir.path().join("simple.fa");
2689 fs::write(&outside_path, b"external file").unwrap();
2690
2691 let workspace_asset = LocalAssetUri::new_for_workspace(
2692 context.workspace(),
2693 &workspace_path.to_string_lossy(),
2694 )
2695 .unwrap();
2696 let outside_asset =
2697 LocalAssetUri::new_for_workspace(context.workspace(), &outside_path.to_string_lossy())
2698 .unwrap();
2699
2700 assert_eq!(workspace_asset.uri(), "file://simple.fa");
2701 assert_eq!(outside_asset.uri(), "file://.gen/outside_root/simple.fa");
2702 assert_ne!(workspace_asset.uri(), outside_asset.uri());
2703 }
2704
2705 #[test]
2706 fn stored_relative_path_keeps_compression_suffix_for_asset_path() {
2707 let context = setup_gen();
2708 let workspace = context.workspace();
2709 let fixture_path =
2710 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
2711 let outside_dir = tempfile::tempdir().unwrap();
2712 let outside_path = outside_dir.path().join("simple.fa.bgz");
2713 fs::copy(&fixture_path, &outside_path).unwrap();
2714 let checksum = calculate_file_checksum(&outside_path).unwrap();
2715
2716 let relative =
2717 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
2718
2719 assert_eq!(relative, format!(".gen/assets/{checksum}.fa.bgz"));
2720 }
2721
2722 #[test]
2723 fn stored_relative_path_keeps_unknown_file_type_suffix_for_asset_path() {
2724 let context = setup_gen();
2725 let workspace = context.workspace();
2726 let outside_dir = tempfile::tempdir().unwrap();
2727 let outside_path = outside_dir.path().join("sample.custom.gz");
2728 fs::write(&outside_path, b"custom contents").unwrap();
2729 let checksum = calculate_file_checksum(&outside_path).unwrap();
2730
2731 let relative =
2732 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
2733
2734 assert_eq!(relative, format!(".gen/assets/{checksum}.custom.gz"));
2735 }
2736
2737 #[test]
2738 fn stored_relative_path_keeps_full_source_suffix_for_asset_path() {
2739 let context = setup_gen();
2740 let workspace = context.workspace();
2741 let outside_dir = tempfile::tempdir().unwrap();
2742 let outside_path = outside_dir.path().join("sample.fa.unhandled");
2743 fs::write(&outside_path, b"custom contents").unwrap();
2744 let checksum = calculate_file_checksum(&outside_path).unwrap();
2745
2746 let relative =
2747 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
2748
2749 assert_eq!(relative, format!(".gen/assets/{checksum}.fa.unhandled"));
2750 }
2751
2752 #[test]
2753 fn stored_relative_path_omits_suffix_for_source_without_suffix() {
2754 let context = setup_gen();
2755 let workspace = context.workspace();
2756 let outside_dir = tempfile::tempdir().unwrap();
2757 let outside_path = outside_dir.path().join("sample");
2758 fs::write(&outside_path, b"custom contents").unwrap();
2759 let checksum = calculate_file_checksum(&outside_path).unwrap();
2760
2761 let relative =
2762 LocalAssetUri::stored_relative_path(workspace, &outside_path, &checksum).unwrap();
2763
2764 assert_eq!(relative, format!(".gen/assets/{checksum}"));
2765 }
2766
2767 #[test]
2768 fn hashed_filename_uses_http_uri_path_suffix() {
2769 let checksum = Sha256Hash::convert_str("remote");
2770 let asset_uri = RemoteAssetUri::new("http://example.com/assets/fasta.fa.gz?download=1");
2771
2772 let filename = asset_uri.hashed_filename(&checksum);
2773
2774 assert_eq!(filename, format!("{checksum}.fa.gz"));
2775 }
2776
2777 #[test]
2778 fn test_resolve_source_path_anchors_relative_paths_to_workspace() {
2779 let context = setup_gen();
2780 let workspace = context.workspace();
2781 let expected = workspace.repo_root().unwrap().join("detached/file.txt");
2782
2783 let absolute = LocalAssetUri::resolve_source_path(workspace, "detached/file.txt").unwrap();
2784 assert_eq!(absolute, expected);
2785 }
2786
2787 #[test]
2788 fn test_resolve_source_path_rejects_parent_traversal() {
2789 let context = setup_gen();
2790 let workspace = context.workspace();
2791
2792 let err = LocalAssetUri::resolve_source_path(workspace, "../detached/file.txt")
2793 .expect_err("expected traversal to be rejected");
2794 assert!(matches!(err, FileAdditionError::FileReadError(_)));
2795 }
2796
2797 mod test_sanitize_relative_path {
2798 use super::*;
2799
2800 #[test]
2801 fn keeps_normal_relative_path() {
2802 let sanitized = LocalAssetUri::sanitize_relative_path(Path::new("nested/file.txt"))
2803 .expect("expected relative path to be allowed");
2804 assert_eq!(sanitized, PathBuf::from("nested/file.txt"));
2805 }
2806
2807 #[test]
2808 fn rejects_parent_dir() {
2809 let err = LocalAssetUri::sanitize_relative_path(Path::new("../nested/file.txt"))
2810 .expect_err("expected parent traversal to be rejected");
2811 assert!(matches!(err, FileAdditionError::FileReadError(_)));
2812 }
2813 }
2814
2815 mod test_normalize_path {
2816 use super::*;
2817
2818 #[test]
2819 fn collapses_dot_and_parent_components() {
2820 let normalized =
2821 LocalAssetUri::normalize_path(Path::new("nested/./deeper/../file.txt"));
2822 assert_eq!(normalized, PathBuf::from("nested/file.txt"));
2823 }
2824 }
2825
2826 mod test_canonicalize_or_normalize {
2827 use super::*;
2828
2829 #[test]
2830 fn normalizes_missing_path() {
2831 let normalized = LocalAssetUri::canonicalize_or_normalize(Path::new(
2832 "/tmp/gen-models-assets-tests/one/../two/file.txt",
2833 ));
2834 assert_eq!(
2835 normalized,
2836 PathBuf::from("/tmp/gen-models-assets-tests/two/file.txt")
2837 );
2838 }
2839
2840 #[test]
2841 fn canonicalizes_existing_path() {
2842 let temp_dir = tempfile::tempdir().unwrap();
2843 let target_dir = temp_dir.path().join("target");
2844 fs::create_dir_all(&target_dir).unwrap();
2845 let file_path = target_dir.join("file.txt");
2846 fs::write(&file_path, b"data").unwrap();
2847
2848 let canonicalized = LocalAssetUri::canonicalize_or_normalize(
2849 &temp_dir.path().join("target/../target/file.txt"),
2850 );
2851
2852 let expected_canonical = fs::canonicalize(&file_path).unwrap();
2856 let cleaned_path = expected_canonical
2857 .strip_prefix("/private")
2858 .unwrap_or(&expected_canonical);
2859 let expected_path = Path::new("/").join(cleaned_path);
2860 assert_eq!(canonicalized, expected_path);
2861 }
2862 }
2863
2864 #[test]
2865 fn test_new_for_workspace_rejects_parent_traversal_file_uri() {
2866 let context = setup_gen();
2867 let workspace = context.workspace();
2868
2869 let err = LocalAssetUri::new_for_workspace(workspace, "file://../detached/file.txt")
2870 .err()
2871 .expect("expected traversal file uri to be rejected");
2872 assert!(matches!(err, FileAdditionError::FileReadError(_)));
2873 }
2874
2875 #[test]
2876 fn test_resolve_source_path_rejects_absolute_asset_uri() {
2877 let context = setup_gen();
2878 let workspace = context.workspace();
2879
2880 let absolute_path = workspace.repo_root().unwrap().join("detached/file.txt");
2881 let err = LocalAssetUri::resolve_source_path(
2882 workspace,
2883 &format!("file://{}", absolute_path.display()),
2884 )
2885 .expect_err("expected absolute asset uri to be rejected");
2886 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
2887 }
2888
2889 #[test]
2890 fn test_new_for_workspace_rejects_non_local_uri() {
2891 let context = setup_gen();
2892 let workspace = context.workspace();
2893
2894 let err = LocalAssetUri::new_for_workspace(workspace, "https://example.com/reference.fa")
2895 .err()
2896 .expect("expected non-local uri to be rejected");
2897 assert!(matches!(err, FileAdditionError::FileReadError(_)));
2898 assert!(
2899 err.to_string()
2900 .contains("unsupported non-local uri: https://example.com/reference.fa")
2901 );
2902 }
2903
2904 #[cfg(unix)]
2905 #[test]
2906 fn test_resolve_source_path_rejects_symlink_escape() {
2907 use std::os::unix::fs::symlink;
2908
2909 let context = setup_gen();
2910 let workspace = context.workspace();
2911 let repo_root = workspace.repo_root().unwrap();
2912 let mut outside_file = tempfile::NamedTempFile::new().unwrap();
2913 outside_file.write_all(b"outside repo").unwrap();
2914 outside_file.flush().unwrap();
2915
2916 let symlink_path = repo_root.join("escape-link.txt");
2917 if symlink_path.exists() || symlink_path.symlink_metadata().is_ok() {
2918 fs::remove_file(&symlink_path).unwrap();
2919 }
2920 symlink(outside_file.path(), &symlink_path).unwrap();
2921
2922 let err = LocalAssetUri::resolve_source_path(workspace, "escape-link.txt")
2923 .expect_err("expected symlink escape to be rejected");
2924 assert!(matches!(err, FileAdditionError::PathOutsideRepo { .. }));
2925 }
2926
2927 #[test]
2928 fn test_stored_relative_path_keeps_workspace_relative_paths() {
2929 let context = setup_gen();
2930 let workspace = context.workspace();
2931
2932 let relative = LocalAssetUri::stored_relative_path(
2933 workspace,
2934 &workspace.repo_root().unwrap().join("detached/file.txt"),
2935 &Sha256Hash::convert_str("detached"),
2936 )
2937 .unwrap();
2938 assert_eq!(relative, "detached/file.txt");
2939 }
2940
2941 #[test]
2942 fn test_resolve_source_path_empty() {
2943 let context = setup_gen();
2944 let workspace = context.workspace();
2945
2946 let absolute_empty = LocalAssetUri::resolve_source_path(workspace, "").unwrap();
2947 assert_eq!(absolute_empty, PathBuf::new());
2948 }
2949
2950 #[test]
2951 fn test_stored_relative_path_empty() {
2952 let context = setup_gen();
2953 let workspace = context.workspace();
2954
2955 let relative_empty = LocalAssetUri::stored_relative_path(
2956 workspace,
2957 Path::new(""),
2958 &Sha256Hash::convert_str("empty"),
2959 )
2960 .unwrap();
2961 assert_eq!(relative_empty, "");
2962 }
2963
2964 #[test]
2965 fn test_local_asset_uri_read_write() {
2966 let context = setup_gen();
2967 let repo_root = context.workspace().repo_root().unwrap();
2968 let path = repo_root.join("asset-uri-io.txt");
2969 fs::write(&path, "initial").unwrap();
2970
2971 let mut reader =
2972 LocalAssetUri::new_for_workspace(context.workspace(), "asset-uri-io.txt").unwrap();
2973 let mut contents = String::new();
2974 reader.read_to_string(&mut contents).unwrap();
2975 assert_eq!(contents, "initial");
2976
2977 let mut writer =
2978 LocalAssetUri::new_for_workspace(context.workspace(), "asset-uri-io.txt").unwrap();
2979 writer.write_all(b"updated").unwrap();
2980 writer.close_write().unwrap();
2981
2982 assert_eq!(fs::read_to_string(path).unwrap(), "updated");
2983 }
2984
2985 #[test]
2986 fn test_remote_asset_uri_checksums_streamed_http_content() {
2987 let seed = SystemTime::now()
2988 .duration_since(UNIX_EPOCH)
2989 .unwrap()
2990 .subsec_nanos() as u16;
2991 let base_port = 20_000 + (seed % 20_000);
2992 let listener = (0..32)
2993 .find_map(|offset| {
2994 let port = base_port.saturating_add(offset);
2995 TcpListener::bind(("127.0.0.1", port)).ok()
2996 })
2997 .expect("failed to bind test HTTP listener");
2998 listener.set_nonblocking(true).unwrap();
2999 let addr = listener.local_addr().unwrap();
3000 let handle = thread::spawn(move || {
3001 let started = Instant::now();
3002 let mut served_get_count = 0;
3003 while served_get_count < 1 && started.elapsed() < Duration::from_secs(5) {
3004 let Ok((mut stream, _)) = listener.accept() else {
3005 thread::sleep(Duration::from_millis(10));
3006 continue;
3007 };
3008 let mut request = [0; 1024];
3009 let len = stream.read(&mut request).unwrap();
3010 let request = String::from_utf8_lossy(&request[..len]);
3011 if request.starts_with("GET ") {
3012 served_get_count += 1;
3013 stream
3014 .write_all(
3015 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\ninitial",
3016 )
3017 .unwrap();
3018 } else {
3019 stream
3020 .write_all(
3021 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\n",
3022 )
3023 .unwrap();
3024 }
3025 }
3026 assert_eq!(served_get_count, 1);
3027 });
3028
3029 let context = setup_gen();
3030 let uri = format!("http://{addr}/asset.fa");
3031 let asset_uri = RemoteAssetUri::new(&uri);
3032 assert_eq!(
3033 asset_uri.prepare_asset(context.workspace(), None).unwrap(),
3034 None
3035 );
3036 let mut reader = ChecksummedReader::new(asset_uri.reader(context.workspace()).unwrap());
3037 let checksum_handle = reader.checksum_handle();
3038 let mut contents = String::new();
3039 reader.read_to_string(&mut contents).unwrap();
3040
3041 handle.join().unwrap();
3042 let expected_checksum = calculate_reader_checksum(contents.as_bytes()).unwrap();
3043 assert_eq!(checksum_handle.checksum(), Some(expected_checksum));
3044 assert_ne!(expected_checksum, Sha256Hash::convert_str(&uri));
3045 }
3046
3047 #[test]
3048 fn test_remote_asset_uri_reader_uses_range_request() {
3049 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("should bind test HTTP listener");
3050 listener
3051 .set_nonblocking(true)
3052 .expect("should configure test HTTP listener");
3053 let address = listener.local_addr().expect("should read listener address");
3054 let handle = thread::spawn(move || {
3055 let started = Instant::now();
3056 let mut served_range = false;
3057 while !served_range && started.elapsed() < Duration::from_secs(5) {
3058 let Ok((mut stream, _)) = listener.accept() else {
3059 thread::sleep(Duration::from_millis(10));
3060 continue;
3061 };
3062 let mut request = [0; 1024];
3063 let length = stream.read(&mut request).expect("should read request");
3064 let request = String::from_utf8_lossy(&request[..length]).to_lowercase();
3065 if request.starts_with("get ") {
3066 assert!(
3067 request.contains("\r\nrange: bytes=2-6\r\n"),
3068 "remote reader should resume at the seek position: {request}"
3069 );
3070 stream
3071 .write_all(
3072 b"HTTP/1.1 206 Partial Content\r\nContent-Length: 5\r\nContent-Range: bytes 2-6/7\r\nAccept-Ranges: bytes\r\nConnection: close\r\n\r\nitial",
3073 )
3074 .expect("should write ranged response");
3075 served_range = true;
3076 } else {
3077 stream
3078 .write_all(
3079 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nAccept-Ranges: bytes\r\nConnection: close\r\n\r\n",
3080 )
3081 .expect("should write metadata response");
3082 }
3083 }
3084 assert!(served_range, "should serve a ranged GET request");
3085 });
3086
3087 let mut reader = OpenDalLocation::from_remote_uri(&format!("http://{address}/asset.fa"))
3088 .expect("should open seekable remote reader");
3089 reader
3090 .seek(SeekFrom::Start(2))
3091 .expect("should seek within remote asset");
3092 let mut bytes = [0; 3];
3093 let bytes_read = reader
3094 .read(&mut bytes)
3095 .expect("should read requested remote range");
3096 handle.join().expect("should finish HTTP server");
3097
3098 assert_eq!(bytes_read, bytes.len());
3099 assert_eq!(&bytes, b"iti");
3100 }
3101
3102 #[test]
3103 fn test_remote_s3_uri_retries_anonymously_after_authenticated_read_fails() {
3104 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("should bind test HTTP listener");
3105 listener
3106 .set_nonblocking(true)
3107 .expect("should configure test HTTP listener");
3108 let address = listener.local_addr().expect("should read listener address");
3109 let handle = thread::spawn(move || {
3110 let started = Instant::now();
3111 let mut saw_signed_request = false;
3112 let mut saw_anonymous_request = false;
3113 let mut served_content = false;
3114 while !served_content && started.elapsed() < Duration::from_secs(5) {
3115 let Ok((mut stream, _)) = listener.accept() else {
3116 thread::sleep(Duration::from_millis(10));
3117 continue;
3118 };
3119 let mut request = [0; 4096];
3120 let length = stream.read(&mut request).expect("should read request");
3121 let request = String::from_utf8_lossy(&request[..length]).to_lowercase();
3122 if request.contains("\r\nauthorization:") {
3123 saw_signed_request = true;
3124 let body = "<Error><Code>AccessDenied</Code><Message>signed request rejected</Message></Error>";
3125 write!(
3126 stream,
3127 "HTTP/1.1 403 Forbidden\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
3128 body.len()
3129 )
3130 .expect("should reject signed request");
3131 } else if request.starts_with("head ") {
3132 saw_anonymous_request = true;
3133 stream
3134 .write_all(
3135 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nAccept-Ranges: bytes\r\nConnection: close\r\n\r\n",
3136 )
3137 .expect("should accept anonymous metadata request");
3138 } else if request.starts_with("get ") {
3139 saw_anonymous_request = true;
3140 stream
3141 .write_all(
3142 b"HTTP/1.1 206 Partial Content\r\nContent-Length: 7\r\nContent-Range: bytes 0-6/7\r\nAccept-Ranges: bytes\r\nConnection: close\r\n\r\ninitial",
3143 )
3144 .expect("should serve anonymous content request");
3145 served_content = true;
3146 }
3147 }
3148 (saw_signed_request, saw_anonymous_request, served_content)
3149 });
3150
3151 let mut url = Url::parse("s3://public-bucket/annotations/genes.gff3")
3152 .expect("should parse test S3 URI");
3153 url.query_pairs_mut()
3154 .append_pair("endpoint", &format!("http://{address}"))
3155 .append_pair("region", "us-east-1")
3156 .append_pair("access_key_id", "other-account-key")
3157 .append_pair("secret_access_key", "other-account-secret")
3158 .append_pair("disable_config_load", "true")
3159 .append_pair("disable_ec2_metadata", "true");
3160
3161 let mut reader =
3162 OpenDalLocation::from_remote_uri(url.as_str()).expect("should retry anonymously");
3163 let mut contents = String::new();
3164 reader
3165 .read_to_string(&mut contents)
3166 .expect("should read public S3 content anonymously");
3167 let (saw_signed_request, saw_anonymous_request, served_content) =
3168 handle.join().expect("should finish HTTP server");
3169
3170 assert!(
3171 saw_signed_request,
3172 "should try configured credentials first"
3173 );
3174 assert!(
3175 saw_anonymous_request,
3176 "should retry without credentials after the signed read fails"
3177 );
3178 assert!(
3179 served_content,
3180 "should serve the anonymously readable object"
3181 );
3182 assert_eq!(contents, "initial");
3183 }
3184
3185 #[test]
3186 fn test_remote_s3_uri_respects_explicit_signed_only_access() {
3187 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("should bind test HTTP listener");
3188 listener
3189 .set_nonblocking(true)
3190 .expect("should configure test HTTP listener");
3191 let address = listener.local_addr().expect("should read listener address");
3192 let handle = thread::spawn(move || {
3193 let started = Instant::now();
3194 let mut signed_request_at = None;
3195 let mut saw_signed_request = false;
3196 let mut saw_anonymous_request = false;
3197 while started.elapsed() < Duration::from_secs(5)
3198 && signed_request_at
3199 .is_none_or(|time: Instant| time.elapsed() < Duration::from_millis(200))
3200 {
3201 let Ok((mut stream, _)) = listener.accept() else {
3202 thread::sleep(Duration::from_millis(10));
3203 continue;
3204 };
3205 let mut request = [0; 4096];
3206 let length = stream.read(&mut request).expect("should read request");
3207 let request = String::from_utf8_lossy(&request[..length]).to_lowercase();
3208 if request.contains("\r\nauthorization:") {
3209 saw_signed_request = true;
3210 signed_request_at = Some(Instant::now());
3211 let body = "<Error><Code>AccessDenied</Code><Message>signed request rejected</Message></Error>";
3212 write!(
3213 stream,
3214 "HTTP/1.1 403 Forbidden\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
3215 body.len()
3216 )
3217 .expect("should reject signed request");
3218 } else {
3219 saw_anonymous_request = true;
3220 stream
3221 .write_all(
3222 b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nAccept-Ranges: bytes\r\nConnection: close\r\n\r\n",
3223 )
3224 .expect("should accept anonymous metadata request");
3225 break;
3226 }
3227 }
3228 (saw_signed_request, saw_anonymous_request)
3229 });
3230
3231 let mut url = Url::parse("s3://public-bucket/annotations/genes.gff3")
3232 .expect("should parse test S3 URI");
3233 url.query_pairs_mut()
3234 .append_pair("endpoint", &format!("http://{address}"))
3235 .append_pair("region", "us-east-1")
3236 .append_pair("access_key_id", "other-account-key")
3237 .append_pair("secret_access_key", "other-account-secret")
3238 .append_pair("allow_anonymous", "false")
3239 .append_pair("disable_config_load", "true")
3240 .append_pair("disable_ec2_metadata", "true");
3241
3242 let result = OpenDalLocation::from_remote_uri(url.as_str());
3243 let (saw_signed_request, saw_anonymous_request) =
3244 handle.join().expect("should finish HTTP server");
3245
3246 assert!(
3247 result.is_err(),
3248 "should return the authenticated read error"
3249 );
3250 assert!(saw_signed_request, "should try configured credentials");
3251 assert!(
3252 !saw_anonymous_request,
3253 "should not override an explicit signed-only policy"
3254 );
3255 }
3256}