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