Skip to main content

gen_models/
assets.rs

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