Skip to main content

gen_models/
operations.rs

1//! Models and persistence helpers for Gen operations.
2//!
3//! An operation is a user-visible change committed to the Dolt-backed graph database. The Dolt
4//! commit is the authoritative history entry and records every changed graph row. Gen also writes
5//! a `gen_operation_log` row into that database to describe the semantic operation: its kind, the
6//! command or summary that produced it, and when it was created. Because this row is committed
7//! with the graph changes, it follows branches and can be queried at historical refs.
8//!
9//! Files used by an operation are tracked as metadata rather than stored in Dolt. A
10//! `gen_asset_refs` row identifies each asset by its URI, content checksum, file type, logical
11//! path, display name, and role. A `gen_operation_assets` row links an operation-log ID to an
12//! asset-reference ID and records the asset's role in that operation, allowing one operation to
13//! use multiple assets and one content-addressed asset reference to be reused by multiple
14//! operations. These rows are included in the same Dolt commit as the operation, while the file
15//! contents live in the workspace asset store or remote object storage addressed by the URI.
16
17use std::{
18    fs,
19    io::{self, BufReader, Read},
20    path::{Path, PathBuf},
21};
22
23use gen_core::{DoltHashId, HashId, Sha256Hash, Workspace, calculate_hash};
24use itertools::Itertools;
25use rusqlite::{
26    OptionalExtension, Result as SQLResult, ToSql, params,
27    types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef},
28};
29use serde::{Deserialize, Serialize};
30use sha2::{Digest, Sha256};
31use uuid::Uuid;
32
33use crate::{
34    Direction, ModelSelect, ModelSelectError,
35    assets::{
36        AssetRef, AssetRole, AssetUri, CompressionType, LocalAssetUri, OperationAsset,
37        OperationKind, OperationLog, stage_bgzf_asset_copy,
38    },
39    db::{ConfigConnection, DbContext},
40    errors::{
41        AddFilesOperationError, FileAdditionError, FileStoreError, OperationError, RemoteError,
42    },
43    file_types::FileTypes,
44    history::{
45        HistoryStore,
46        dolt::{DoltHistoryStore, is_current_branch_dirty},
47    },
48    select::ModelSelectRow,
49};
50
51pub const GEN_DEFAULT_COMMITTER_NAME: &str = "gen";
52pub const DEFAULT_COMMITTER_EMAIL: &str = "gen@genhub.bio";
53
54#[derive(Clone, Debug, Eq, PartialEq)]
55pub struct OperationFile {
56    pub filename: String,
57    pub file_path: String,
58    pub file_type: FileTypes,
59    pub checksum_override: Option<Sha256Hash>,
60    pub role: AssetRole,
61    pub upstream_asset_ref_id: Option<HashId>,
62}
63
64#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
65pub struct OperationFileInfo {
66    pub id: HashId,
67    pub filename: String,
68    pub file_path: String,
69    pub asset_uri: String,
70    pub file_type: FileTypes,
71    pub checksum: Option<Sha256Hash>,
72    #[serde(default)]
73    pub materialized_checksum: Option<Sha256Hash>,
74}
75
76/// Describes a file source that can be prepared as a content-addressed operation asset.
77pub enum FileSource {
78    /// A classified stream that will be archived with the existing BGZF staging path.
79    Reader {
80        /// Stream containing the source bytes.
81        reader: Box<dyn Read>,
82        /// Compression format already detected for the source stream.
83        compression: CompressionType,
84        /// Expected SHA-256 of the original source bytes, if supplied by the caller.
85        checksum_override: Option<Sha256Hash>,
86    },
87    /// A finalized BGZF file with checksums calculated while it was produced.
88    StagedBgzf {
89        /// Path to the staged BGZF file.
90        path: PathBuf,
91        /// SHA-256 of the exact compressed BGZF bytes.
92        archive_checksum: Sha256Hash,
93        /// SHA-256 of the decoded BGZF content.
94        materialized_checksum: Sha256Hash,
95    },
96}
97
98impl OperationFile {
99    pub fn new(file_path: impl Into<String>) -> Self {
100        let file_path = file_path.into();
101        let file_type = FileTypes::infer_from_path(&file_path);
102        let filename = Path::new(&file_path)
103            .file_name()
104            .and_then(|name| name.to_str())
105            .unwrap_or(&file_path)
106            .to_string();
107        Self {
108            filename,
109            file_path,
110            file_type,
111            checksum_override: None,
112            role: AssetRole::Input,
113            upstream_asset_ref_id: None,
114        }
115    }
116
117    pub fn set_file_type(mut self, file_type: FileTypes) -> Self {
118        self.file_type = file_type;
119        self
120    }
121
122    pub fn set_checksum_override(mut self, checksum: Sha256Hash) -> Self {
123        self.checksum_override = Some(checksum);
124        self
125    }
126
127    pub fn set_role(mut self, role: AssetRole) -> Self {
128        self.role = role;
129        self
130    }
131
132    pub fn set_upstream_asset_ref_id(mut self, upstream_asset_ref_id: &HashId) -> Self {
133        self.upstream_asset_ref_id = Some(*upstream_asset_ref_id);
134        self
135    }
136
137    /// Construct the AssetRef from an OperationFile
138    pub fn prepare_asset_ref(
139        &self,
140        workspace: &Workspace,
141        created_on: i64,
142    ) -> Result<AssetRef, FileAdditionError> {
143        let file_addition = FileAddition::prepare(
144            workspace,
145            &self.file_path,
146            self.file_type,
147            self.checksum_override,
148        )?;
149        let logical_path =
150            Self::storage_file_path(workspace, &self.file_path, file_addition.checksum.as_ref())?;
151        let file_type = file_addition.file_type.as_str();
152        Ok(AssetRef {
153            id: AssetRef::id_hash(
154                &file_addition,
155                &self.role,
156                Some(&logical_path),
157                Some(&self.filename),
158                self.upstream_asset_ref_id.as_ref(),
159            ),
160            uri: file_addition.asset_uri,
161            file_type: file_type.to_string(),
162            checksum: file_addition.checksum,
163            materialized_checksum: file_addition.materialized_checksum,
164            size: None,
165            role: self.role.clone(),
166            logical_path: Some(logical_path),
167            name: Some(self.filename.clone()),
168            created_on,
169            upstream_asset_ref_id: self.upstream_asset_ref_id,
170        })
171    }
172
173    /// Resolves the path stored in operation metadata without materializing remote assets.
174    ///
175    /// Local inputs keep their original logical path, and remote inputs keep their URI for lazy
176    /// access.
177    pub fn storage_file_path(
178        workspace: &Workspace,
179        path_or_uri: &str,
180        checksum: Option<&Sha256Hash>,
181    ) -> Result<String, FileAdditionError> {
182        if LocalAssetUri::is_local_path_or_file_uri(path_or_uri) {
183            if !LocalAssetUri::is_index_path(path_or_uri) {
184                let source_path = LocalAssetUri::resolve_input_source_path(workspace, path_or_uri)?;
185                return LocalAssetUri::logical_file_path(workspace, &source_path);
186            }
187            let checksum = checksum.ok_or_else(|| {
188                FileAdditionError::ChecksumError(format!(
189                    "local operation file has no checksum: {path_or_uri}"
190                ))
191            })?;
192            LocalAssetUri::operation_file_path(workspace, path_or_uri, checksum)
193        } else {
194            Ok(path_or_uri.to_string())
195        }
196    }
197}
198
199#[derive(Clone, Debug, Eq, PartialEq)]
200pub struct OperationInfo {
201    pub files: Vec<OperationFile>,
202    pub description: String,
203}
204
205#[derive(Clone, Debug, Eq, PartialEq)]
206pub struct OperationSummary {
207    pub operation_info: OperationInfo,
208    pub summary: String,
209    /// Exact asset references prepared while an operation consumed its source streams.
210    ///
211    /// When present, commit tracks these references directly instead of preparing the original
212    /// descriptors again. This is used by imports that transform a source while streaming it.
213    pub prepared_asset_refs: Option<Vec<AssetRef>>,
214}
215
216impl OperationSummary {
217    pub fn new(operation_info: OperationInfo, summary: impl Into<String>) -> Self {
218        Self {
219            operation_info,
220            summary: summary.into(),
221            prepared_asset_refs: None,
222        }
223    }
224
225    /// Uses the already-prepared asset references when this operation is committed.
226    pub fn with_prepared_asset_refs(mut self, asset_refs: Vec<AssetRef>) -> Self {
227        self.prepared_asset_refs = Some(asset_refs);
228        self
229    }
230}
231
232#[cfg_attr(
233    feature = "profiling",
234    tracing::instrument(skip(context, operation_summary))
235)]
236pub fn commit_operation_summary(
237    context: &DbContext,
238    operation_summary: &OperationSummary,
239) -> Result<DoltHashId, OperationError> {
240    let workspace = context.workspace();
241    let graph_conn = context.graph().conn();
242    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
243    let operation_info = &operation_summary.operation_info;
244
245    if !is_current_branch_dirty(graph_conn)? {
246        return Err(OperationError::NoChanges);
247    }
248
249    let created_on = chrono::Utc::now()
250        .timestamp_nanos_opt()
251        .expect("should create operation asset timestamp");
252    let prepared_assets = match &operation_summary.prepared_asset_refs {
253        Some(asset_refs) => asset_refs.clone(),
254        None => operation_info
255            .files
256            .iter()
257            .map(|operation_file| operation_file.prepare_asset_ref(workspace, created_on))
258            .collect::<Result<Vec<_>, _>>()
259            .map_err(|err| match err {
260                FileAdditionError::ConfigError(config_error) => {
261                    OperationError::ConfigError(config_error)
262                }
263                other => OperationError::SQLError(other.to_string()),
264            })?,
265    };
266    let operation_kind = OperationKind::Other(operation_info.description.clone());
267    track_asset_refs(
268        graph_conn,
269        None,
270        &operation_kind,
271        &operation_summary.summary,
272        &prepared_assets,
273    )?;
274
275    let commit_result = history_store.commit_all(&operation_summary.summary);
276    commit_result.map_err(OperationError::from)
277}
278
279#[cfg_attr(
280    feature = "profiling",
281    tracing::instrument(skip(graph_conn, log_id, assets))
282)]
283pub(crate) fn track_asset_refs(
284    graph_conn: &crate::db::GraphConnection,
285    log_id: Option<&HashId>,
286    operation_kind: &OperationKind,
287    command: &str,
288    assets: &[AssetRef],
289) -> Result<(), rusqlite::Error> {
290    let created_on = chrono::Utc::now()
291        .timestamp_nanos_opt()
292        .expect("should create operation asset timestamp");
293    let log_id = log_id
294        .copied()
295        .unwrap_or_else(|| OperationLog::id_hash(operation_kind, command, created_on));
296    OperationLog::create(
297        graph_conn,
298        &OperationLog {
299            id: log_id,
300            operation_kind: operation_kind.clone(),
301            command: command.to_string(),
302            created_on,
303        },
304    )?;
305
306    for asset_ref in assets {
307        AssetRef::create(graph_conn, asset_ref)?;
308        OperationAsset::create(
309            graph_conn,
310            &OperationAsset {
311                log_id,
312                asset_ref_id: asset_ref.id,
313                role: asset_ref.role.clone(),
314            },
315        )?;
316    }
317
318    Ok(())
319}
320
321#[cfg_attr(
322    all(debug_assertions, feature = "profiling"),
323    tracing::instrument(skip(context, files, message))
324)]
325/// Records files used by an operation, retaining local content and preserving remote URIs.
326///
327/// Checksum overrides are propagated from callers that already streamed remote content, avoiding
328/// a credentials-dependent read whose only purpose would be hashing.
329pub fn add_files_operation(
330    context: &DbContext,
331    files: &[OperationFile],
332    message: Option<&str>,
333) -> Result<DoltHashId, AddFilesOperationError> {
334    let workspace = context.workspace();
335    let graph_conn = context.graph().conn();
336
337    let file_additions = files
338        .iter()
339        .map(|operation_file| {
340            let file_addition = FileAddition::prepare(
341                workspace,
342                &operation_file.file_path,
343                operation_file.file_type,
344                operation_file.checksum_override,
345            )?;
346            let operation_file_path = OperationFile::storage_file_path(
347                workspace,
348                &operation_file.file_path,
349                file_addition.checksum.as_ref(),
350            )?;
351            Ok::<(FileAddition, String, String), FileAdditionError>((
352                file_addition,
353                operation_file.filename.clone(),
354                operation_file_path,
355            ))
356        })
357        .collect::<Result<Vec<_>, _>>()?;
358
359    let unique_file_additions = file_additions
360        .into_iter()
361        .unique_by(|(file_addition, filename, file_path)| {
362            (file_addition.id, filename.clone(), file_path.clone())
363        })
364        .collect::<Vec<_>>();
365
366    let log_id = HashId(calculate_hash(
367        &unique_file_additions
368            .iter()
369            .map(|(file_addition, filename, file_path)| {
370                format!("{}:{filename}:{file_path}", file_addition.id)
371            })
372            .sorted()
373            .join(":"),
374    ));
375
376    let summary = message.map(str::to_string).unwrap_or_else(|| {
377        if files.len() == 1 {
378            format!("Add file {}", files[0].file_path)
379        } else {
380            format!("Add {} files", files.len())
381        }
382    });
383    let created_on = chrono::Utc::now()
384        .timestamp_nanos_opt()
385        .expect("should create operation asset timestamp");
386    let asset_refs = unique_file_additions
387        .iter()
388        .map(|(file_addition, filename, file_path)| {
389            AssetRef::from_file_addition(
390                file_addition,
391                AssetRole::Input,
392                Some(file_path),
393                Some(filename),
394                None,
395                created_on,
396            )
397        })
398        .collect::<Vec<_>>();
399    track_asset_refs(
400        graph_conn,
401        Some(&log_id),
402        &OperationKind::AddFile,
403        &summary,
404        &asset_refs,
405    )?;
406    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
407    if history_store.status()?.is_empty() {
408        return Err(AddFilesOperationError::OperationError(
409            OperationError::NoChanges,
410        ));
411    }
412
413    history_store
414        .commit_all(&summary)
415        .map_err(AddFilesOperationError::from)
416}
417
418pub fn calculate_file_checksum<P: AsRef<Path>>(file_path: P) -> Result<Sha256Hash, std::io::Error> {
419    let file = std::fs::File::open(file_path)?;
420    let reader = BufReader::new(file);
421    calculate_reader_checksum(reader)
422}
423
424pub fn calculate_reader_checksum<R: std::io::Read>(
425    reader: R,
426) -> Result<Sha256Hash, std::io::Error> {
427    let hash_bytes = calculate_stream_hash(reader)?;
428    Ok(Sha256Hash(hash_bytes))
429}
430
431fn calculate_stream_hash<R: std::io::Read>(mut reader: R) -> Result<[u8; 32], std::io::Error> {
432    let mut hasher = Sha256::new();
433    io::copy(&mut reader, &mut hasher)?;
434    let result = hasher.finalize();
435    let mut hash_array = [0u8; 32];
436    hash_array.copy_from_slice(&result);
437    Ok(hash_array)
438}
439
440#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize, ModelSelect)]
441#[model_select(table = "file_additions")]
442pub struct FileAddition {
443    pub id: HashId,
444    pub asset_uri: String,
445    pub file_type: FileTypes,
446    pub checksum: Option<Sha256Hash>,
447    /// SHA-256 of the workspace bytes when they differ from the retained archive bytes.
448    #[serde(default)]
449    pub materialized_checksum: Option<Sha256Hash>,
450}
451
452impl FileAddition {
453    pub fn file_path(&self) -> &str {
454        self.asset_uri
455            .strip_prefix(LocalAssetUri::SCHEME)
456            .unwrap_or(&self.asset_uri)
457    }
458
459    #[cfg_attr(
460        feature = "profiling",
461        tracing::instrument(skip(workspace, checksum_override))
462    )]
463    /// Retains local source content and validates any supplied checksum against it.
464    ///
465    /// Local assets are retained as BGZF compressed assets; plain inputs record their source checksum separately,
466    /// and ordinary gzip inputs are recompressed as bgzf. Native BGZF is stored unchanged. Index sidecars remain
467    /// unchanged for direct access by index readers. Remote content remains a lazy URI and can carry an
468    /// optional checksum supplied by a caller that already streamed it for useful work; preparation
469    /// does not download or verify remote bytes.
470    pub fn prepare(
471        workspace: &Workspace,
472        file_path: &str,
473        file_type: FileTypes,
474        checksum_override: Option<Sha256Hash>,
475    ) -> Result<FileAddition, FileAdditionError> {
476        let asset_uri = <dyn AssetUri>::new(workspace, file_path);
477        let is_local = LocalAssetUri::is_local_path_or_file_uri(file_path);
478        if is_local && !LocalAssetUri::is_index_path(file_path) {
479            let source_reader = asset_uri.reader(workspace)?;
480            let (compression_type, replayed_reader) =
481                CompressionType::sniff(source_reader).map_err(FileAdditionError::FileReadError)?;
482            return Self::prepare_from_source(
483                workspace,
484                file_path,
485                file_type,
486                FileSource::Reader {
487                    reader: Box::new(replayed_reader),
488                    compression: compression_type,
489                    checksum_override,
490                },
491                false,
492            );
493        }
494
495        let checksum = asset_uri.prepare_asset(workspace, checksum_override)?;
496        let stored_asset_uri = match checksum.as_ref() {
497            Some(checksum) => asset_uri.stored_asset_uri(workspace, checksum)?,
498            None => asset_uri.uri().to_string(),
499        };
500
501        Ok(FileAddition {
502            id: LocalAssetUri::generate_file_addition_id(checksum.as_ref(), &stored_asset_uri),
503            asset_uri: stored_asset_uri,
504            file_type,
505            checksum,
506            materialized_checksum: None,
507        })
508    }
509
510    /// Prepares a source as a retained BGZF asset.
511    ///
512    /// Reader sources use the established streaming archive path. For staged BGZF sources,
513    /// Staged BGZF files are moved when `move_file` is true and copied otherwise. Reader sources
514    /// always use the streaming archive path regardless of `move_file`.
515    pub fn prepare_from_source(
516        workspace: &Workspace,
517        source_uri: &str,
518        file_type: FileTypes,
519        source: FileSource,
520        move_file: bool,
521    ) -> Result<FileAddition, FileAdditionError> {
522        if LocalAssetUri::is_index_path(source_uri) {
523            return Err(FileAdditionError::FileReadError(io::Error::new(
524                io::ErrorKind::InvalidInput,
525                format!("index sources cannot be retained as BGZF assets: {source_uri}"),
526            )));
527        }
528
529        let (archive_checksum, materialized_checksum, staged_path) = match source {
530            FileSource::Reader {
531                reader,
532                compression,
533                checksum_override,
534            } => {
535                let (archive_checksum, source_checksum) = stage_bgzf_asset_copy(
536                    workspace,
537                    file_type,
538                    reader,
539                    compression,
540                    checksum_override,
541                )
542                .map_err(|error| match error {
543                    FileAdditionError::ChecksumError(message) => {
544                        FileAdditionError::ChecksumError(format!("{message}: {source_uri}"))
545                    }
546                    error => error,
547                })?;
548                let materialized_checksum =
549                    (compression == CompressionType::Plain).then_some(source_checksum);
550                (archive_checksum, materialized_checksum, None)
551            }
552            FileSource::StagedBgzf {
553                path,
554                archive_checksum,
555                materialized_checksum,
556            } => (archive_checksum, Some(materialized_checksum), Some(path)),
557        };
558
559        let asset_dir = workspace.asset_dir()?;
560        let asset_path = asset_dir.join(format!(
561            "{archive_checksum}.{}.bgz",
562            FileTypes::suffix(file_type)
563        ));
564        if let Some(staged_path) = staged_path {
565            fs::create_dir_all(&asset_dir).map_err(FileAdditionError::FileReadError)?;
566            let same_asset_path = staged_path == asset_path
567                || (asset_path.exists()
568                    && fs::canonicalize(&staged_path).map_err(FileAdditionError::FileReadError)?
569                        == fs::canonicalize(&asset_path)
570                            .map_err(FileAdditionError::FileReadError)?);
571            if !same_asset_path {
572                if move_file {
573                    fs::rename(staged_path, &asset_path)
574                        .map_err(FileAdditionError::FileReadError)?;
575                } else {
576                    fs::copy(staged_path, &asset_path).map_err(FileAdditionError::FileReadError)?;
577                }
578            }
579        }
580
581        let repo_root = workspace.repo_root()?;
582        let relative_path = asset_path
583            .strip_prefix(&repo_root)
584            .map_err(|_| FileAdditionError::PathOutsideRepo {
585                path: asset_path.clone(),
586                repo_root,
587            })?
588            .to_string_lossy();
589        let stored_asset_uri = LocalAssetUri::asset_uri(&relative_path);
590        let checksum = Some(archive_checksum);
591
592        Ok(FileAddition {
593            id: LocalAssetUri::generate_file_addition_id(checksum.as_ref(), &stored_asset_uri),
594            asset_uri: stored_asset_uri,
595            file_type,
596            checksum,
597            materialized_checksum,
598        })
599    }
600
601    #[cfg_attr(
602        all(debug_assertions, feature = "profiling"),
603        tracing::instrument(skip(self, workspace))
604    )]
605    pub fn store_file(&self, workspace: &Workspace) -> Result<(), FileStoreError> {
606        let asset_uri = <dyn AssetUri>::new(workspace, &self.asset_uri);
607        asset_uri.store_file(self, workspace)
608    }
609
610    /// Returns the content-addressed filename when this asset has a verified checksum.
611    ///
612    /// Checksumless remote references do not live under `.gen/assets`, so they have no hashed
613    /// storage filename.
614    pub fn hashed_filename(&self) -> Option<String> {
615        self.checksum
616            .as_ref()
617            .map(|checksum| <dyn AssetUri>::from_uri(&self.asset_uri).hashed_filename(checksum))
618    }
619}
620
621#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ModelSelect)]
622#[model_select(table = "remotes", history = false)]
623pub struct Remote {
624    #[model_select(primary_key)]
625    pub name: String,
626    pub url: String,
627}
628
629impl Remote {
630    /// Validate remote name - no spaces or special characters except hyphens and underscores
631    pub fn validate_name(name: &str) -> Result<(), RemoteError> {
632        if name.is_empty() {
633            return Err(RemoteError::EmptyName);
634        }
635
636        if name
637            .chars()
638            .any(|c| !c.is_alphanumeric() && c != '-' && c != '_')
639        {
640            return Err(RemoteError::InvalidNameCharacters);
641        }
642
643        Ok(())
644    }
645
646    /// Validate URL format
647    pub fn validate_url(url: &str) -> Result<(), RemoteError> {
648        if url.is_empty() {
649            return Err(RemoteError::EmptyUrl);
650        }
651
652        // Check if it looks like a URL with a scheme
653        if url.contains("://") {
654            match url::Url::parse(url) {
655                Ok(parsed_url) => {
656                    // Only allow http, https, and ssh schemes
657                    match parsed_url.scheme() {
658                        "http" | "https" | "ssh" | "file" => Ok(()),
659                        _ => Err(RemoteError::UnsupportedUrlScheme),
660                    }
661                }
662                Err(_) => Err(RemoteError::InvalidUrl("Invalid URL format".to_string())),
663            }
664        } else if url.starts_with('/') || url.contains(':') {
665            // Assume it's a file path or SSH-style path (like user@host:path)
666            Ok(())
667        } else {
668            Err(RemoteError::UnsupportedUrlScheme)
669        }
670    }
671
672    /// Create a new remote with the given name and URL
673    /// Validates input and handles constraint violations gracefully
674    pub fn create(conn: &ConfigConnection, name: &str, url: &str) -> Result<Remote, RemoteError> {
675        // Validate input
676        Self::validate_name(name)?;
677        Self::validate_url(url)?;
678
679        let query = "INSERT INTO remotes (name, url) VALUES (?1, ?2)";
680        let mut stmt = conn.prepare(query)?;
681
682        match stmt.execute(params![name, url]) {
683            Ok(_) => Ok(Remote {
684                name: name.to_string(),
685                url: url.to_string(),
686            }),
687            Err(rusqlite::Error::SqliteFailure(err, _))
688                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
689            {
690                Err(RemoteError::RemoteAlreadyExists(name.to_string()))
691            }
692            Err(e) => Err(RemoteError::DatabaseError(e)),
693        }
694    }
695
696    /// Get a remote by name
697    pub fn get_by_name(conn: &ConfigConnection, name: &str) -> Result<Remote, RemoteError> {
698        Remote::select(conn)
699            .name(name)
700            .load()?
701            .into_iter()
702            .next()
703            .ok_or_else(|| RemoteError::RemoteNotFound(name.to_string()))
704    }
705
706    /// Get a remote by name, returning None if not found (for backward compatibility)
707    pub fn get_by_name_optional(conn: &ConfigConnection, name: &str) -> Option<Remote> {
708        Self::get_by_name(conn, name).ok()
709    }
710
711    /// List all remotes
712    pub fn list_all(conn: &ConfigConnection) -> Vec<Remote> {
713        Remote::select(conn)
714            .order_by(RemoteSelect::Name, Direction::Asc)
715            .load()
716            .expect("should load remotes")
717    }
718
719    /// Delete a remote by name
720    pub fn delete(conn: &ConfigConnection, name: &str) -> Result<(), RemoteError> {
721        // Check if remote exists first
722        Self::get_by_name(conn, name)?;
723        RemoteBranch::clear_by_remote(conn, name)?;
724
725        let query = "DELETE FROM remotes WHERE name = ?1";
726        let mut stmt = conn.prepare(query)?;
727        stmt.execute(params![name])?;
728        Ok(())
729    }
730
731    /// Check if a remote exists
732    pub fn exists(conn: &ConfigConnection, name: &str) -> bool {
733        Self::get_by_name_optional(conn, name).is_some()
734    }
735}
736
737#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
738#[model_select(table = "remote_branch", history = false)]
739pub struct RemoteBranch {
740    pub remote_name: Option<String>,
741    #[model_select(primary_key)]
742    pub name: String,
743}
744
745impl RemoteBranch {
746    pub fn set_remote_validated(
747        conn: &ConfigConnection,
748        branch_name: &str,
749        remote_name: Option<&str>,
750    ) -> Result<(), RemoteError> {
751        if let Some(name) = remote_name {
752            Remote::get_by_name(conn, name)?;
753            conn.execute(
754                "DELETE FROM remote_branch WHERE name = ?1",
755                params![branch_name],
756            )?;
757            conn.execute(
758                "INSERT INTO remote_branch (name, remote_name) VALUES (?1, ?2)",
759                params![branch_name, name],
760            )?;
761        } else {
762            conn.execute(
763                "DELETE FROM remote_branch WHERE name = ?1",
764                params![branch_name],
765            )?;
766        }
767        Ok(())
768    }
769
770    pub fn get_remote(conn: &ConfigConnection, branch_name: &str) -> Option<String> {
771        RemoteBranch::select(conn)
772            .name(branch_name)
773            .only(RemoteBranchSelect::RemoteName)
774            .load()
775            .ok()?
776            .into_iter()
777            .next()
778            .flatten()
779    }
780
781    pub fn clear_by_remote(conn: &ConfigConnection, remote_name: &str) -> Result<(), RemoteError> {
782        conn.execute(
783            "DELETE FROM remote_branch WHERE remote_name = ?1",
784            params![remote_name],
785        )?;
786        Ok(())
787    }
788}
789
790/// A remote operation whose graph and asset phases must complete together.
791#[derive(Clone, Copy, Debug, Eq, PartialEq)]
792pub enum RemoteOperationKind {
793    /// Initializes a workspace from a remote repository.
794    Clone,
795    /// Advances an existing local branch from a remote repository.
796    Pull,
797    /// Advances a remote branch from the local repository.
798    Push,
799}
800
801impl RemoteOperationKind {
802    const fn as_str(self) -> &'static str {
803        match self {
804            Self::Clone => "clone",
805            Self::Pull => "pull",
806            Self::Push => "push",
807        }
808    }
809}
810
811impl FromSql for RemoteOperationKind {
812    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
813        value.as_str().map(|operation| match operation {
814            "clone" => Self::Clone,
815            "pull" => Self::Pull,
816            "push" => Self::Push,
817            _ => unreachable!("remote operation should satisfy its database constraint"),
818        })
819    }
820}
821
822impl ToSql for RemoteOperationKind {
823    fn to_sql(&self) -> SQLResult<ToSqlOutput<'_>> {
824        Ok(self.as_str().into())
825    }
826}
827
828/// Tracks a remote operation until its graph and asset phases are complete.
829#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
830#[model_select(table = "remote_operations", history = false)]
831pub struct RemoteOperationRecord {
832    /// Config database row identifier.
833    pub id: i64,
834    /// Configured remote participating in the operation.
835    pub remote_name: String,
836    /// Branch transferred by the operation.
837    pub branch_name: String,
838    /// Direction of the remote graph transfer.
839    pub operation: RemoteOperationKind,
840    /// Local branch commit from before the graph transfer.
841    pub from_commit: Option<DoltHashId>,
842    /// Last commit whose complete asset batch was verified locally.
843    pub assets_transfer_checkpoint: Option<DoltHashId>,
844    /// Destination graph commit whose assets must be transferred.
845    pub to_commit: Option<DoltHashId>,
846    /// GenHub push lease retained by a pending operation.
847    pub transfer_id: Option<Uuid>,
848    /// Client-owned session UUID for the intended graph publication scope.
849    pub push_session_id: Option<Uuid>,
850    /// Target commit selected for the intended session, distinct from the last published commit.
851    pub push_session_target_commit: Option<DoltHashId>,
852    /// Whether the intended session may overwrite a divergent remote branch.
853    pub push_session_force: Option<bool>,
854    /// Unix timestamp after which GenHub will reject the retained push lease.
855    pub transfer_expires_at: Option<i64>,
856    /// Time at which the operation began.
857    pub started_at: String,
858    /// Time at which both graph and asset transfer completed.
859    pub completed_at: Option<String>,
860    /// Time at which the operation became unrecoverable.
861    pub failed_at: Option<String>,
862}
863
864impl RemoteOperationRecord {
865    /// Resumes an incomplete operation or starts one from the supplied local commit.
866    pub fn begin_or_resume(
867        conn: &ConfigConnection,
868        remote_name: &str,
869        branch_name: &str,
870        operation: RemoteOperationKind,
871        from_commit: Option<&DoltHashId>,
872    ) -> SQLResult<Self> {
873        let pending = conn
874            .query_row(
875                "SELECT * FROM remote_operations \
876                 WHERE remote_name = ?1 AND branch_name = ?2 \
877                   AND completed_at IS NULL AND failed_at IS NULL \
878                   -- This is confusing, but this checks whether a clone operation is followed by a pull.
879                   -- If a clone fails to download assets, a pull can finish the operation even though the
880                   -- persisted operation is clone and the requested operation is pull.
881                   AND (operation = ?3 OR operation = 'clone' AND ?3 = 'pull') \
882                 ORDER BY id LIMIT 1",
883                params![remote_name, branch_name, operation.as_str()],
884                Self::process_row,
885            )
886            .optional()?;
887        if let Some(pending) = pending {
888            return Ok(pending);
889        }
890
891        let assets_transfer_checkpoint = conn
892            .query_row(
893                "SELECT assets_transfer_checkpoint FROM remote_operations \
894                 WHERE remote_name = ?1 AND branch_name = ?2 AND completed_at IS NOT NULL \
895                 ORDER BY id DESC LIMIT 1",
896                params![remote_name, branch_name],
897                |row| row.get::<_, DoltHashId>(0),
898            )
899            .optional()?;
900        let push_session_id = (operation == RemoteOperationKind::Push).then(Uuid::new_v4);
901        conn.execute(
902            "INSERT INTO remote_operations \
903             (remote_name, branch_name, operation, from_commit, assets_transfer_checkpoint, push_session_id) \
904             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
905            params![
906                remote_name,
907                branch_name,
908                operation.as_str(),
909                from_commit,
910                assets_transfer_checkpoint,
911                push_session_id
912            ],
913        )?;
914        Self::select(conn)
915            .get_by_id(conn.last_insert_rowid())
916            .map_err(|error| match error {
917                ModelSelectError::DatabaseError(error) => error,
918                ModelSelectError::MultipleResults => rusqlite::Error::QueryReturnedMoreThanOneRow,
919                ModelSelectError::InvalidSelector(_)
920                | ModelSelectError::HistoryNotSupported { .. }
921                | ModelSelectError::ProjectionSourceNotSelected { .. } => {
922                    rusqlite::Error::InvalidQuery
923                }
924            })?
925            .ok_or(rusqlite::Error::QueryReturnedNoRows)
926    }
927
928    /// Persists the graph session's intended publication scope before opening its remote server.
929    ///
930    /// Keeping the intended destination separate from the published destination lets retries reuse
931    /// one UUID while a newer graph is still uploading. Rotating that UUID clears the retired
932    /// session's lease but preserves the last published destination and asset checkpoint, so a
933    /// same-commit force change cannot mistake the prior publication for the new session.
934    pub fn prepare_push_session(
935        &mut self,
936        conn: &ConfigConnection,
937        destination: &DoltHashId,
938        force: bool,
939    ) -> SQLResult<()> {
940        let replacement_session_id = Uuid::new_v4();
941        let (push_session_id, transfer_id, transfer_expires_at) = conn.query_row(
942            "UPDATE remote_operations \
943             SET push_session_id = CASE \
944                 WHEN push_session_target_commit = ?1 AND push_session_force = ?2 \
945                     THEN push_session_id \
946                 WHEN push_session_target_commit IS NULL AND push_session_force IS NULL \
947                     AND to_commit IS NULL \
948                     THEN push_session_id \
949                 ELSE ?3 \
950             END, transfer_id = CASE \
951                 WHEN push_session_target_commit = ?1 AND push_session_force = ?2 \
952                     THEN transfer_id \
953                 ELSE NULL \
954             END, transfer_expires_at = CASE \
955                 WHEN push_session_target_commit = ?1 AND push_session_force = ?2 \
956                     THEN transfer_expires_at \
957                 ELSE NULL \
958             END, push_session_target_commit = ?1, push_session_force = ?2 \
959             WHERE id = ?4 AND operation = 'push' \
960               AND completed_at IS NULL AND failed_at IS NULL \
961             RETURNING push_session_id, transfer_id, transfer_expires_at",
962            params![destination, force, replacement_session_id, self.id],
963            |row| {
964                Ok((
965                    row.get::<_, Uuid>(0)?,
966                    row.get::<_, Option<Uuid>>(1)?,
967                    row.get::<_, Option<i64>>(2)?,
968                ))
969            },
970        )?;
971        self.push_session_id = Some(push_session_id);
972        self.push_session_target_commit = Some(*destination);
973        self.push_session_force = Some(force);
974        self.transfer_id = transfer_id;
975        self.transfer_expires_at = transfer_expires_at;
976        Ok(())
977    }
978
979    /// Replaces a confirmed stale graph session and clears only its unpublished graph lease.
980    ///
981    /// The asset checkpoint and operation history remain attached to this push so the next graph
982    /// session can resume the same operation.
983    pub fn reset_stale_push_session(
984        &mut self,
985        conn: &ConfigConnection,
986        push_session_id: Uuid,
987    ) -> SQLResult<()> {
988        let updated = conn.execute(
989            "UPDATE remote_operations \
990             SET push_session_id = ?1, to_commit = NULL, transfer_id = NULL, \
991                 transfer_expires_at = NULL \
992             WHERE id = ?2 AND operation = 'push' \
993               AND completed_at IS NULL AND failed_at IS NULL",
994            params![push_session_id, self.id],
995        )?;
996        if updated != 1 {
997            return Err(rusqlite::Error::InvalidQuery);
998        }
999        self.push_session_id = Some(push_session_id);
1000        self.to_commit = None;
1001        self.transfer_id = None;
1002        self.transfer_expires_at = None;
1003        Ok(())
1004    }
1005
1006    /// Records the desired end commit an operation is tracking.
1007    pub fn set_destination(
1008        &mut self,
1009        conn: &ConfigConnection,
1010        to_commit: &DoltHashId,
1011    ) -> SQLResult<()> {
1012        conn.execute(
1013            "UPDATE remote_operations SET to_commit = ?1 WHERE id = ?2",
1014            params![to_commit, self.id],
1015        )?;
1016        self.to_commit = Some(*to_commit);
1017        Ok(())
1018    }
1019
1020    /// After transferring assets for a commit, mark it in the database so subsequent transfers for
1021    /// resumes can restart from there.
1022    pub fn advance_assets_transfer_checkpoint(
1023        &mut self,
1024        conn: &ConfigConnection,
1025        commit: &DoltHashId,
1026    ) -> SQLResult<()> {
1027        conn.execute(
1028            "UPDATE remote_operations SET assets_transfer_checkpoint = ?1 WHERE id = ?2",
1029            params![commit, self.id],
1030        )?;
1031        self.assets_transfer_checkpoint = Some(*commit);
1032        Ok(())
1033    }
1034
1035    /// Records the successful push graph transfer and its capability-scoped lease.
1036    pub fn set_push_destination(
1037        &mut self,
1038        conn: &ConfigConnection,
1039        to_commit: &DoltHashId,
1040        transfer_id: Uuid,
1041        transfer_expires_at: i64,
1042    ) -> SQLResult<()> {
1043        let updated = conn.execute(
1044            "UPDATE remote_operations \
1045             SET to_commit = ?1, transfer_id = ?2, transfer_expires_at = ?3, \
1046                 push_session_target_commit = COALESCE(push_session_target_commit, ?1), \
1047                 push_session_force = COALESCE(push_session_force, 0) \
1048             WHERE id = ?4 AND operation = 'push' AND push_session_id IS NOT NULL \
1049               AND (push_session_target_commit IS NULL OR push_session_target_commit = ?1)",
1050            params![to_commit, transfer_id, transfer_expires_at, self.id],
1051        )?;
1052        if updated != 1 {
1053            return Err(rusqlite::Error::InvalidQuery);
1054        }
1055        self.to_commit = Some(*to_commit);
1056        self.transfer_id = Some(transfer_id);
1057        self.transfer_expires_at = Some(transfer_expires_at);
1058        if self.push_session_target_commit.is_none() {
1059            self.push_session_target_commit = Some(*to_commit);
1060        }
1061        if self.push_session_force.is_none() {
1062            self.push_session_force = Some(false);
1063        }
1064        Ok(())
1065    }
1066
1067    /// Marks the operation complete only after its graph and asset phases succeed.
1068    pub fn complete(&self, conn: &ConfigConnection) -> SQLResult<()> {
1069        if self.to_commit.is_none() || self.to_commit != self.assets_transfer_checkpoint {
1070            self.fail(conn)?;
1071            return Err(rusqlite::Error::InvalidQuery);
1072        }
1073        conn.execute(
1074            "UPDATE remote_operations SET completed_at = CURRENT_TIMESTAMP WHERE id = ?1",
1075            [self.id],
1076        )?;
1077        Ok(())
1078    }
1079
1080    pub fn fail(&self, conn: &ConfigConnection) -> SQLResult<()> {
1081        conn.execute(
1082            "UPDATE remote_operations SET failed_at = CURRENT_TIMESTAMP WHERE id = ?1",
1083            [self.id],
1084        )?;
1085        Ok(())
1086    }
1087}
1088
1089#[derive(Clone, Debug, Serialize, Deserialize, ModelSelect)]
1090#[model_select(table = "defaults", history = false)]
1091pub struct Defaults {
1092    pub id: i64,
1093    pub collection_name: Option<String>,
1094    pub remote_name: Option<String>,
1095    pub current_branch_name: Option<String>,
1096    pub default_committer_name: String,
1097    pub default_committer_email: String,
1098}
1099
1100impl Defaults {
1101    /// Set the default remote by name
1102    pub fn set_default_remote(
1103        conn: &ConfigConnection,
1104        remote_name: Option<&str>,
1105    ) -> Result<(), RemoteError> {
1106        // If setting a remote name, validate that it exists
1107        if let Some(name) = remote_name {
1108            Remote::get_by_name(conn, name)?;
1109        }
1110
1111        let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
1112        let mut stmt = conn.prepare(query)?;
1113        stmt.execute(params![remote_name])?;
1114        Ok(())
1115    }
1116
1117    pub fn set_default_remote_compat(
1118        conn: &ConfigConnection,
1119        remote_name: Option<&str>,
1120    ) -> SQLResult<()> {
1121        let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
1122        let mut stmt = conn.prepare(query)?;
1123        stmt.execute(params![remote_name])?;
1124        Ok(())
1125    }
1126
1127    /// Get the default remote name
1128    pub fn get_default_remote(conn: &ConfigConnection) -> Option<String> {
1129        Defaults::select(conn)
1130            .id(1)
1131            .only(DefaultsSelect::RemoteName)
1132            .load()
1133            .ok()?
1134            .into_iter()
1135            .next()
1136            .flatten()
1137    }
1138
1139    /// Helper method to get the default remote URL by resolving the remote name
1140    pub fn get_default_remote_url(conn: &ConfigConnection) -> Option<String> {
1141        if let Some(remote_name) = Self::get_default_remote(conn) {
1142            if let Some(remote) = Remote::get_by_name_optional(conn, &remote_name) {
1143                Some(remote.url)
1144            } else {
1145                None
1146            }
1147        } else {
1148            None
1149        }
1150    }
1151
1152    pub fn set_current_branch(conn: &ConfigConnection, branch_name: Option<&str>) -> SQLResult<()> {
1153        let query = "UPDATE defaults SET current_branch_name = ?1 WHERE id = 1";
1154        let mut stmt = conn.prepare(query)?;
1155        stmt.execute(params![branch_name])?;
1156        Ok(())
1157    }
1158
1159    pub fn get_current_branch(conn: &ConfigConnection) -> Option<String> {
1160        Defaults::select(conn)
1161            .id(1)
1162            .only(DefaultsSelect::CurrentBranchName)
1163            .load()
1164            .ok()?
1165            .into_iter()
1166            .next()
1167            .flatten()
1168    }
1169
1170    pub fn set_default_committer_name(conn: &ConfigConnection, name: &str) -> SQLResult<()> {
1171        let query = "UPDATE defaults SET default_committer_name = ?1 WHERE id = 1";
1172        let mut stmt = conn.prepare(query)?;
1173        stmt.execute(params![name])?;
1174        Ok(())
1175    }
1176
1177    pub fn get_default_committer_name(conn: &ConfigConnection) -> String {
1178        Defaults::select(conn)
1179            .id(1)
1180            .only(DefaultsSelect::DefaultCommitterName)
1181            .load()
1182            .ok()
1183            .and_then(|names| names.into_iter().next())
1184            .unwrap_or_else(|| GEN_DEFAULT_COMMITTER_NAME.to_string())
1185    }
1186
1187    pub fn set_default_committer_email(conn: &ConfigConnection, email: &str) -> SQLResult<()> {
1188        let query = "UPDATE defaults SET default_committer_email = ?1 WHERE id = 1";
1189        let mut stmt = conn.prepare(query)?;
1190        stmt.execute(params![email])?;
1191        Ok(())
1192    }
1193
1194    pub fn get_default_committer_email(conn: &ConfigConnection) -> String {
1195        Defaults::select(conn)
1196            .id(1)
1197            .only(DefaultsSelect::DefaultCommitterEmail)
1198            .load()
1199            .ok()
1200            .and_then(|emails| emails.into_iter().next())
1201            .unwrap_or_else(|| DEFAULT_COMMITTER_EMAIL.to_string())
1202    }
1203
1204    /// Get the defaults record
1205    pub fn get(conn: &ConfigConnection) -> Option<Defaults> {
1206        Self::select(conn).id(1).load().ok()?.into_iter().next()
1207    }
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212    use std::{
1213        fs,
1214        io::{Cursor, Write},
1215        path::PathBuf,
1216        slice::from_ref,
1217    };
1218
1219    use tempfile::NamedTempFile;
1220
1221    use super::*;
1222    use crate::{
1223        assets::{AssetRef, AssetRole, OperationAsset, OperationLog},
1224        file_types::FileTypes,
1225        history::{HistoryStore, dolt::DoltHistoryStore},
1226        test_helpers::setup_gen,
1227    };
1228
1229    #[cfg(test)]
1230    mod defaults {
1231        use super::*;
1232
1233        #[test]
1234        fn test_default_remote_functionality() {
1235            let context = setup_gen();
1236            let config_conn = context.config().conn();
1237
1238            // Create test remotes
1239            Remote::create(config_conn, "origin", "https://example.com/repo.gen").unwrap();
1240            Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
1241
1242            // Test getting default remote when none is set
1243            assert_eq!(Defaults::get_default_remote(config_conn), None);
1244            assert_eq!(Defaults::get_default_remote_url(config_conn), None);
1245
1246            // Test setting default remote
1247            Defaults::set_default_remote(config_conn, Some("origin")).unwrap();
1248            assert_eq!(
1249                Defaults::get_default_remote(config_conn),
1250                Some("origin".to_string())
1251            );
1252            assert_eq!(
1253                Defaults::get_default_remote_url(config_conn),
1254                Some("https://example.com/repo.gen".to_string())
1255            );
1256
1257            // Test changing default remote
1258            Defaults::set_default_remote(config_conn, Some("upstream")).unwrap();
1259            assert_eq!(
1260                Defaults::get_default_remote(config_conn),
1261                Some("upstream".to_string())
1262            );
1263            assert_eq!(
1264                Defaults::get_default_remote_url(config_conn),
1265                Some("https://upstream.com/repo.gen".to_string())
1266            );
1267
1268            // Test clearing default remote
1269            Defaults::set_default_remote(config_conn, None).unwrap();
1270            assert_eq!(Defaults::get_default_remote(config_conn), None);
1271            assert_eq!(Defaults::get_default_remote_url(config_conn), None);
1272
1273            // Test getting URL for non-existent remote (using the compat method to bypass validation)
1274            Defaults::set_default_remote_compat(config_conn, Some("nonexistent")).unwrap();
1275            assert_eq!(
1276                Defaults::get_default_remote(config_conn),
1277                Some("nonexistent".to_string())
1278            );
1279            assert_eq!(Defaults::get_default_remote_url(config_conn), None);
1280        }
1281
1282        #[test]
1283        fn test_defaults_get() {
1284            let context = setup_gen();
1285            let config_conn = context.config().conn();
1286
1287            // Test getting defaults record
1288            let defaults = Defaults::get(config_conn).unwrap();
1289            assert_eq!(defaults.id, 1);
1290            assert_eq!(defaults.collection_name, None);
1291            assert_eq!(defaults.remote_name, None);
1292            assert_eq!(defaults.current_branch_name, None);
1293            assert_eq!(defaults.default_committer_name, GEN_DEFAULT_COMMITTER_NAME);
1294            assert_eq!(defaults.default_committer_email, DEFAULT_COMMITTER_EMAIL);
1295
1296            // Set a default remote and test again (using compat method to bypass validation)
1297            Defaults::set_default_remote_compat(config_conn, Some("test-remote")).unwrap();
1298            let defaults = Defaults::get(config_conn).unwrap();
1299            assert_eq!(defaults.remote_name, Some("test-remote".to_string()));
1300        }
1301
1302        #[test]
1303        fn test_current_branch_round_trip() {
1304            let context = setup_gen();
1305            let config_conn = context.config().conn();
1306
1307            assert_eq!(Defaults::get_current_branch(config_conn), None);
1308
1309            Defaults::set_current_branch(config_conn, Some("feature")).unwrap();
1310            assert_eq!(
1311                Defaults::get_current_branch(config_conn),
1312                Some("feature".to_string())
1313            );
1314
1315            Defaults::set_current_branch(config_conn, None).unwrap();
1316            assert_eq!(Defaults::get_current_branch(config_conn), None);
1317        }
1318
1319        #[test]
1320        fn test_default_committer_round_trip() {
1321            let context = setup_gen();
1322            let config_conn = context.config().conn();
1323
1324            assert_eq!(
1325                Defaults::get_default_committer_name(config_conn),
1326                GEN_DEFAULT_COMMITTER_NAME
1327            );
1328            assert_eq!(
1329                Defaults::get_default_committer_email(config_conn),
1330                DEFAULT_COMMITTER_EMAIL
1331            );
1332
1333            Defaults::set_default_committer_name(config_conn, "Test User").unwrap();
1334            Defaults::set_default_committer_email(config_conn, "test@example.com").unwrap();
1335
1336            assert_eq!(
1337                Defaults::get_default_committer_name(config_conn),
1338                "Test User".to_string()
1339            );
1340            assert_eq!(
1341                Defaults::get_default_committer_email(config_conn),
1342                "test@example.com".to_string()
1343            );
1344            let defaults = Defaults::get(config_conn).expect("should load defaults");
1345            assert_eq!(defaults.default_committer_name, "Test User");
1346            assert_eq!(defaults.default_committer_email, "test@example.com");
1347        }
1348    }
1349
1350    #[cfg(test)]
1351    mod remote_operations {
1352        use gen_core::DoltHashId;
1353        use uuid::Uuid;
1354
1355        use crate::{
1356            operations::{Remote, RemoteOperationKind, RemoteOperationRecord},
1357            test_helpers::setup_gen,
1358        };
1359
1360        #[test]
1361        fn test_remote_operation_resumes_until_completed() {
1362            let context = setup_gen();
1363            let config = context.config().conn();
1364            Remote::create(config, "origin", "https://example.com/repo")
1365                .expect("should create remote");
1366            let original_commit = DoltHashId([1_u8; 20]);
1367            let advanced_commit = DoltHashId([2_u8; 20]);
1368
1369            let mut baseline = RemoteOperationRecord::begin_or_resume(
1370                config,
1371                "origin",
1372                "main",
1373                RemoteOperationKind::Clone,
1374                Some(&original_commit),
1375            )
1376            .expect("should begin clone operation");
1377            assert_eq!(baseline.from_commit, Some(original_commit));
1378            assert_eq!(baseline.assets_transfer_checkpoint, None);
1379            baseline
1380                .set_destination(config, &original_commit)
1381                .expect("should record clone destination");
1382            baseline
1383                .advance_assets_transfer_checkpoint(config, &original_commit)
1384                .expect("should record clone asset checkpoint");
1385            baseline
1386                .complete(config)
1387                .expect("should complete clone operation");
1388
1389            let operation = RemoteOperationRecord::begin_or_resume(
1390                config,
1391                "origin",
1392                "main",
1393                RemoteOperationKind::Pull,
1394                Some(&original_commit),
1395            )
1396            .expect("should begin pull operation");
1397            let mut resumed = RemoteOperationRecord::begin_or_resume(
1398                config,
1399                "origin",
1400                "main",
1401                RemoteOperationKind::Pull,
1402                Some(&advanced_commit),
1403            )
1404            .expect("should resume pull operation");
1405
1406            assert_eq!(resumed, operation);
1407            assert_eq!(resumed.from_commit, Some(original_commit));
1408            assert_eq!(resumed.assets_transfer_checkpoint, Some(original_commit));
1409
1410            resumed
1411                .set_destination(config, &advanced_commit)
1412                .expect("should record pull destination");
1413            resumed
1414                .advance_assets_transfer_checkpoint(config, &advanced_commit)
1415                .expect("should record pull asset checkpoint");
1416            resumed
1417                .complete(config)
1418                .expect("should complete pull operation");
1419            let completed = RemoteOperationRecord::select(config)
1420                .get_by_id(resumed.id)
1421                .expect("should query completed pull operation")
1422                .expect("should refetch completed pull operation");
1423            assert!(
1424                completed.completed_at.is_some(),
1425                "completed_at should be set"
1426            );
1427            assert_eq!(completed.failed_at, None, "failed_at should remain unset");
1428
1429            let next = RemoteOperationRecord::begin_or_resume(
1430                config,
1431                "origin",
1432                "main",
1433                RemoteOperationKind::Pull,
1434                Some(&advanced_commit),
1435            )
1436            .expect("should begin the next pull operation");
1437            assert_ne!(next.id, operation.id);
1438            assert_eq!(next.from_commit, Some(advanced_commit));
1439            assert_eq!(next.assets_transfer_checkpoint, Some(advanced_commit));
1440        }
1441
1442        #[test]
1443        fn test_failed_graph_operation_does_not_resume() {
1444            let context = setup_gen();
1445            let config = context.config().conn();
1446            Remote::create(config, "origin", "https://example.com/repo")
1447                .expect("should create remote");
1448            let original_commit = DoltHashId([1_u8; 20]);
1449
1450            let failed = RemoteOperationRecord::begin_or_resume(
1451                config,
1452                "origin",
1453                "main",
1454                RemoteOperationKind::Pull,
1455                Some(&original_commit),
1456            )
1457            .expect("should begin pull operation");
1458            failed.fail(config).expect("should fail pull operation");
1459            let next = RemoteOperationRecord::begin_or_resume(
1460                config,
1461                "origin",
1462                "main",
1463                RemoteOperationKind::Pull,
1464                Some(&original_commit),
1465            )
1466            .expect("should begin replacement pull operation");
1467
1468            assert_ne!(next.id, failed.id);
1469        }
1470
1471        #[test]
1472        fn test_remote_operation_cannot_complete_before_asset_checkpoint() {
1473            let context = setup_gen();
1474            let config = context.config().conn();
1475            Remote::create(config, "origin", "https://example.com/repo")
1476                .expect("should create remote");
1477            let destination_commit = DoltHashId([1_u8; 20]);
1478            let mut operation = RemoteOperationRecord::begin_or_resume(
1479                config,
1480                "origin",
1481                "main",
1482                RemoteOperationKind::Clone,
1483                None,
1484            )
1485            .expect("should begin clone operation");
1486            operation
1487                .set_destination(config, &destination_commit)
1488                .expect("should record graph destination");
1489
1490            operation
1491                .complete(config)
1492                .expect_err("should require assets to reach graph destination");
1493            let failed = RemoteOperationRecord::select(config)
1494                .get_by_id(operation.id)
1495                .expect("should query failed clone operation")
1496                .expect("should refetch failed clone operation");
1497            assert!(failed.failed_at.is_some(), "failed_at should be set");
1498        }
1499
1500        #[test]
1501        fn test_push_operation_resumes_transfer_lease() {
1502            let context = setup_gen();
1503            let config = context.config().conn();
1504            Remote::create(config, "origin", "https://example.com/repo")
1505                .expect("should create remote");
1506            let destination_commit = DoltHashId([3_u8; 20]);
1507            let transfer_id = Uuid::from_u128(7);
1508            let transfer_expires_at = 1_900_000_000;
1509            let mut operation = RemoteOperationRecord::begin_or_resume(
1510                config,
1511                "origin",
1512                "main",
1513                RemoteOperationKind::Push,
1514                None,
1515            )
1516            .expect("should begin push operation");
1517            let push_session_id = operation
1518                .push_session_id
1519                .expect("should allocate a stable push session UUID");
1520            let pending_resume = RemoteOperationRecord::begin_or_resume(
1521                config,
1522                "origin",
1523                "main",
1524                RemoteOperationKind::Push,
1525                None,
1526            )
1527            .expect("should resume push session before graph publication");
1528            assert_eq!(pending_resume.push_session_id, Some(push_session_id));
1529            operation
1530                .set_push_destination(
1531                    config,
1532                    &destination_commit,
1533                    transfer_id,
1534                    transfer_expires_at,
1535                )
1536                .expect("should record push destination and lease");
1537
1538            let mut resumed = RemoteOperationRecord::begin_or_resume(
1539                config,
1540                "origin",
1541                "main",
1542                RemoteOperationKind::Push,
1543                None,
1544            )
1545            .expect("should resume push operation");
1546
1547            assert_eq!(resumed.to_commit.as_ref(), Some(&destination_commit));
1548            assert_eq!(resumed.transfer_id, Some(transfer_id));
1549            assert_eq!(resumed.transfer_expires_at, Some(transfer_expires_at));
1550            assert_eq!(resumed.push_session_id, Some(push_session_id));
1551            assert_eq!(resumed.push_session_target_commit, Some(destination_commit));
1552            assert_eq!(resumed.push_session_force, Some(false));
1553            let replacement_session_id = Uuid::new_v4();
1554            resumed
1555                .advance_assets_transfer_checkpoint(config, &destination_commit)
1556                .expect("should retain the same operation asset checkpoint");
1557            resumed
1558                .reset_stale_push_session(config, replacement_session_id)
1559                .expect("should replace a server-confirmed stale graph session");
1560            assert_ne!(resumed.push_session_id, Some(push_session_id));
1561            assert_eq!(resumed.to_commit, None);
1562            assert_eq!(resumed.transfer_id, None);
1563            assert_eq!(resumed.transfer_expires_at, None);
1564            assert_eq!(resumed.push_session_target_commit, Some(destination_commit));
1565            assert_eq!(resumed.push_session_force, Some(false));
1566            assert_eq!(
1567                resumed.assets_transfer_checkpoint.as_ref(),
1568                Some(&destination_commit),
1569                "stale graph recovery should preserve the in-flight operation's asset history"
1570            );
1571            resumed
1572                .set_push_destination(
1573                    config,
1574                    &destination_commit,
1575                    transfer_id,
1576                    transfer_expires_at,
1577                )
1578                .expect("should record the replacement graph session after it is published");
1579            resumed
1580                .complete(config)
1581                .expect("should complete push operation");
1582        }
1583
1584        #[test]
1585        fn test_push_intended_destination_is_stable_while_new_graph_upload_retries() {
1586            let context = setup_gen();
1587            let config = context.config().conn();
1588            Remote::create(config, "origin", "https://example.com/repo")
1589                .expect("should create remote");
1590            let published_commit = DoltHashId([3_u8; 20]);
1591            let intended_commit = DoltHashId([4_u8; 20]);
1592            let published_transfer_id = Uuid::from_u128(8);
1593            let published_transfer_expires_at = 1_900_000_001;
1594            let mut operation = RemoteOperationRecord::begin_or_resume(
1595                config,
1596                "origin",
1597                "main",
1598                RemoteOperationKind::Push,
1599                None,
1600            )
1601            .expect("should begin push operation");
1602            operation
1603                .prepare_push_session(config, &published_commit, true)
1604                .expect("should persist the force scope used for the published graph");
1605            operation
1606                .set_push_destination(
1607                    config,
1608                    &published_commit,
1609                    published_transfer_id,
1610                    published_transfer_expires_at,
1611                )
1612                .expect("should seed the published graph and lease");
1613            let initial_session_id = operation
1614                .push_session_id
1615                .expect("should keep the operation session ID");
1616
1617            operation
1618                .prepare_push_session(config, &published_commit, true)
1619                .expect("should preserve the lease for the unchanged published scope");
1620            assert_eq!(operation.push_session_id, Some(initial_session_id));
1621            assert_eq!(operation.transfer_id, Some(published_transfer_id));
1622            assert_eq!(
1623                operation.transfer_expires_at,
1624                Some(published_transfer_expires_at)
1625            );
1626
1627            operation
1628                .prepare_push_session(config, &intended_commit, false)
1629                .expect("should persist the new graph upload intent");
1630            let intended_session_id = operation
1631                .push_session_id
1632                .expect("should select the intended session ID");
1633            assert_ne!(intended_session_id, initial_session_id);
1634            assert_eq!(operation.to_commit, Some(published_commit));
1635            assert_eq!(operation.transfer_id, None);
1636            assert_eq!(operation.transfer_expires_at, None);
1637
1638            let mut retry = RemoteOperationRecord::begin_or_resume(
1639                config,
1640                "origin",
1641                "main",
1642                RemoteOperationKind::Push,
1643                None,
1644            )
1645            .expect("should resume the pending push operation");
1646            retry
1647                .prepare_push_session(config, &intended_commit, false)
1648                .expect("should resume the same intended graph session");
1649
1650            assert_eq!(retry.push_session_id, Some(intended_session_id));
1651            assert_eq!(retry.push_session_target_commit, Some(intended_commit));
1652            assert_eq!(retry.push_session_force, Some(false));
1653            assert_eq!(retry.to_commit, Some(published_commit));
1654            assert_eq!(retry.transfer_id, None);
1655            assert_eq!(retry.transfer_expires_at, None);
1656        }
1657
1658        #[test]
1659        fn test_fresh_push_scope_keeps_its_initial_session_for_each_force_value() {
1660            let context = setup_gen();
1661            let config = context.config().conn();
1662            Remote::create(config, "origin", "https://example.com/repo")
1663                .expect("should create remote");
1664
1665            for (branch, force) in [("main", false), ("forced", true)] {
1666                let mut operation = RemoteOperationRecord::begin_or_resume(
1667                    config,
1668                    "origin",
1669                    branch,
1670                    RemoteOperationKind::Push,
1671                    None,
1672                )
1673                .expect("should begin a fresh push operation");
1674                let initial_session_id = operation
1675                    .push_session_id
1676                    .expect("should initialize a session for a fresh push");
1677                assert_eq!(operation.to_commit, None);
1678
1679                let destination = DoltHashId([if force { 10_u8 } else { 9_u8 }; 20]);
1680                operation
1681                    .prepare_push_session(config, &destination, force)
1682                    .expect("should prepare the requested fresh push scope");
1683                assert_eq!(operation.push_session_id, Some(initial_session_id));
1684                assert_eq!(operation.push_session_target_commit, Some(destination));
1685                assert_eq!(operation.push_session_force, Some(force));
1686
1687                operation
1688                    .prepare_push_session(config, &destination, force)
1689                    .expect("should preserve the UUID while retrying the same fresh scope");
1690                assert_eq!(operation.push_session_id, Some(initial_session_id));
1691            }
1692        }
1693
1694        #[test]
1695        fn test_push_intended_scope_rotates_session_only_when_scope_changes() {
1696            let context = setup_gen();
1697            let config = context.config().conn();
1698            Remote::create(config, "origin", "https://example.com/repo")
1699                .expect("should create remote");
1700            let first_destination = DoltHashId([5_u8; 20]);
1701            let second_destination = DoltHashId([6_u8; 20]);
1702            let mut operation = RemoteOperationRecord::begin_or_resume(
1703                config,
1704                "origin",
1705                "main",
1706                RemoteOperationKind::Push,
1707                None,
1708            )
1709            .expect("should begin push operation");
1710
1711            operation
1712                .prepare_push_session(config, &first_destination, false)
1713                .expect("should prepare the first intended scope");
1714            let initial_session_id = operation.push_session_id;
1715            operation
1716                .prepare_push_session(config, &first_destination, false)
1717                .expect("should retain the session for an unchanged scope");
1718            assert_eq!(operation.push_session_id, initial_session_id);
1719
1720            operation
1721                .prepare_push_session(config, &first_destination, true)
1722                .expect("should rotate when force authorization changes");
1723            let forced_session_id = operation.push_session_id;
1724            assert_ne!(forced_session_id, initial_session_id);
1725            operation
1726                .prepare_push_session(config, &first_destination, true)
1727                .expect("should retain the session for the same forced scope");
1728            assert_eq!(operation.push_session_id, forced_session_id);
1729
1730            operation
1731                .prepare_push_session(config, &second_destination, true)
1732                .expect("should rotate when the intended destination changes");
1733            assert_ne!(operation.push_session_id, forced_session_id);
1734            assert_eq!(
1735                operation.push_session_target_commit,
1736                Some(second_destination)
1737            );
1738            assert_eq!(operation.push_session_force, Some(true));
1739        }
1740    }
1741
1742    #[cfg(test)]
1743    mod remote {
1744        use super::*;
1745
1746        #[test]
1747        fn test_validate_remote_name() {
1748            // Valid names
1749            assert!(Remote::validate_name("origin").is_ok());
1750            assert!(Remote::validate_name("my-remote").is_ok());
1751            assert!(Remote::validate_name("remote_1").is_ok());
1752            assert!(Remote::validate_name("test123").is_ok());
1753
1754            // Invalid names
1755            assert!(Remote::validate_name("").is_err());
1756            assert!(Remote::validate_name("remote with spaces").is_err());
1757            assert!(Remote::validate_name("remote@special").is_err());
1758            assert!(Remote::validate_name("remote.dot").is_err());
1759        }
1760
1761        #[test]
1762        fn test_validate_url() {
1763            // Valid URLs
1764            assert!(Remote::validate_url("https://genhub.bio/user/repo.gen").is_ok());
1765            assert!(Remote::validate_url("http://example.com/repo").is_ok());
1766            assert!(Remote::validate_url("ssh://git@genhub.bio/user/repo.gen").is_ok());
1767            assert!(Remote::validate_url("/path/to/local/repo").is_ok());
1768            assert!(Remote::validate_url("user@host:path/to/repo").is_ok());
1769
1770            // Invalid URLs
1771            assert!(Remote::validate_url("").is_err());
1772            assert!(Remote::validate_url("not-a-url").is_err());
1773
1774            assert!(Remote::validate_url("ftp://invalid-protocol.com").is_err());
1775        }
1776    }
1777
1778    mod remote_branch {
1779        use super::*;
1780
1781        #[test]
1782        fn test_remote_branch_set_remote_valid() {
1783            let context = setup_gen();
1784            let config_conn = context.config().conn();
1785
1786            Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1787            let result =
1788                RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("origin"));
1789            assert!(result.is_ok());
1790            assert_eq!(
1791                RemoteBranch::get_remote(config_conn, "test_branch"),
1792                Some("origin".to_string())
1793            );
1794        }
1795
1796        #[test]
1797        fn test_remote_branch_set_remote_nonexistent() {
1798            let context = setup_gen();
1799            let config_conn = context.config().conn();
1800
1801            let result =
1802                RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("nonexistent"));
1803            assert_eq!(
1804                result,
1805                Err(RemoteError::RemoteNotFound("nonexistent".to_string()))
1806            );
1807            assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
1808        }
1809
1810        #[test]
1811        fn test_remote_branch_clear_remote() {
1812            let context = setup_gen();
1813            let config_conn = context.config().conn();
1814
1815            Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1816            RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("origin")).unwrap();
1817            assert_eq!(
1818                RemoteBranch::get_remote(config_conn, "test_branch"),
1819                Some("origin".to_string())
1820            );
1821            RemoteBranch::set_remote_validated(config_conn, "test_branch", None).unwrap();
1822            assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
1823        }
1824
1825        #[test]
1826        fn test_remote_branch_clears_on_remote_delete() {
1827            let context = setup_gen();
1828            let config_conn = context.config().conn();
1829
1830            Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1831            RemoteBranch::set_remote_validated(config_conn, "test_branch_cascade", Some("origin"))
1832                .unwrap();
1833            assert_eq!(
1834                RemoteBranch::get_remote(config_conn, "test_branch_cascade"),
1835                Some("origin".to_string())
1836            );
1837
1838            Remote::delete(config_conn, "origin").unwrap();
1839            assert_eq!(
1840                RemoteBranch::get_remote(config_conn, "test_branch_cascade"),
1841                None
1842            );
1843        }
1844    }
1845
1846    #[test]
1847    fn test_remote_create() {
1848        let context = setup_gen();
1849        let config_conn = context.config().conn();
1850
1851        // Test successful remote creation
1852        let remote = Remote::create(config_conn, "origin", "https://example.com/repo.gen").unwrap();
1853        assert_eq!(remote.name, "origin");
1854        assert_eq!(remote.url, "https://example.com/repo.gen");
1855
1856        // Test duplicate name constraint violation
1857        let result = Remote::create(config_conn, "origin", "https://different.com/repo.gen");
1858        assert!(result.is_err());
1859    }
1860
1861    #[test]
1862    fn test_remote_get_by_name() {
1863        let context = setup_gen();
1864        let config_conn = context.config().conn();
1865
1866        // Test getting non-existent remote
1867        let result = Remote::get_by_name_optional(config_conn, "nonexistent");
1868        assert!(result.is_none());
1869
1870        // Create a remote and test retrieval
1871        Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
1872        let result = Remote::get_by_name_optional(config_conn, "upstream");
1873        assert!(result.is_some());
1874        let remote = result.unwrap();
1875        assert_eq!(remote.name, "upstream");
1876        assert_eq!(remote.url, "https://upstream.com/repo.gen");
1877    }
1878
1879    #[test]
1880    fn test_remote_list_all() {
1881        let context = setup_gen();
1882        let config_conn = context.config().conn();
1883
1884        // Test empty list
1885        let remotes = Remote::list_all(config_conn);
1886        assert!(remotes.is_empty());
1887
1888        // Create multiple remotes
1889        Remote::create(config_conn, "origin", "https://origin.com/repo.gen").unwrap();
1890        Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
1891        Remote::create(config_conn, "fork", "https://fork.com/repo.gen").unwrap();
1892
1893        // Test list returns all remotes in alphabetical order
1894        let remotes = Remote::list_all(config_conn);
1895        assert_eq!(remotes.len(), 3);
1896        assert_eq!(remotes[0].name, "fork");
1897        assert_eq!(remotes[1].name, "origin");
1898        assert_eq!(remotes[2].name, "upstream");
1899    }
1900
1901    #[test]
1902    fn test_remote_delete() {
1903        let context = setup_gen();
1904        let config_conn = context.config().conn();
1905
1906        // Create a remote
1907        Remote::create(config_conn, "temp", "https://temp.com/repo.gen").unwrap();
1908
1909        // Verify it exists
1910        let remote = Remote::get_by_name_optional(config_conn, "temp");
1911        assert!(remote.is_some());
1912
1913        // Delete the remote
1914        let result = Remote::delete(config_conn, "temp");
1915        assert!(result.is_ok());
1916
1917        // Verify it's gone
1918        let remote = Remote::get_by_name_optional(config_conn, "temp");
1919        assert!(remote.is_none());
1920
1921        // Test deleting non-existent remote (should return error)
1922        let result = Remote::delete(config_conn, "nonexistent");
1923        assert!(result.is_err());
1924    }
1925
1926    #[test]
1927    fn test_remote_delete_with_remote_branch_associations() {
1928        let context = setup_gen();
1929        let config_conn = context.config().conn();
1930
1931        Remote::create(config_conn, "test_remote", "https://test.com/repo.gen").unwrap();
1932        RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("test_remote"))
1933            .unwrap();
1934        assert_eq!(
1935            RemoteBranch::get_remote(config_conn, "test_branch"),
1936            Some("test_remote".to_string())
1937        );
1938
1939        let result = Remote::delete(config_conn, "test_remote");
1940        assert!(result.is_ok());
1941        assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
1942        let remote = Remote::get_by_name_optional(config_conn, "test_remote");
1943        assert!(remote.is_none());
1944    }
1945
1946    #[test]
1947    fn test_calculate_stream_hash() {
1948        let content = b"Hello, World!";
1949        let cursor = Cursor::new(content);
1950        let hash = calculate_stream_hash(cursor).unwrap();
1951
1952        assert_eq!(hash.len(), 32);
1953
1954        // Test consistency - same content should produce same hash
1955        let cursor2 = Cursor::new(content);
1956        let hash2 = calculate_stream_hash(cursor2).unwrap();
1957        assert_eq!(hash, hash2);
1958
1959        // Test different content produces different hash
1960        let different_content = b"Hello, World!!";
1961        let cursor3 = Cursor::new(different_content);
1962        let hash3 = calculate_stream_hash(cursor3).unwrap();
1963        assert_ne!(hash, hash3);
1964    }
1965
1966    #[test]
1967    fn test_calculate_file_checksum() {
1968        let mut temp_file = NamedTempFile::new().unwrap();
1969        let content = b"Test file content for checksum calculation";
1970        temp_file.write_all(content).unwrap();
1971        temp_file.flush().unwrap();
1972
1973        let checksum = calculate_file_checksum(temp_file.path()).unwrap();
1974
1975        assert_eq!(checksum.0.len(), 32);
1976
1977        // Test consistency - same file should produce same checksum
1978        let checksum2 = calculate_file_checksum(temp_file.path()).unwrap();
1979        assert_eq!(checksum, checksum2);
1980
1981        // Test with different file content
1982        let mut temp_file2 = NamedTempFile::new().unwrap();
1983        let different_content = b"Different test file content";
1984        temp_file2.write_all(different_content).unwrap();
1985        temp_file2.flush().unwrap();
1986
1987        let checksum3 = calculate_file_checksum(temp_file2.path()).unwrap();
1988        assert_ne!(checksum, checksum3);
1989    }
1990
1991    #[test]
1992    fn test_calculate_file_checksum_nonexistent_file() {
1993        let result = calculate_file_checksum("/nonexistent/file/path");
1994        assert!(result.is_err());
1995        assert!(matches!(
1996            result.unwrap_err().kind(),
1997            std::io::ErrorKind::NotFound
1998        ));
1999    }
2000
2001    #[test]
2002    fn test_operation_file_new_infers_file_type_from_path() {
2003        let operation_file = OperationFile::new("fixtures/sample.gb");
2004
2005        assert_eq!(operation_file.filename, "sample.gb");
2006        assert_eq!(operation_file.file_path, "fixtures/sample.gb");
2007        assert_eq!(operation_file.file_type, FileTypes::GenBank);
2008        assert_eq!(operation_file.checksum_override, None);
2009    }
2010
2011    #[test]
2012    fn test_operation_file_storage_path_normalizes_absolute_repo_path() {
2013        let context = setup_gen();
2014        let repo_root = context.workspace().repo_root().unwrap();
2015        let absolute_path = repo_root.join("nested").join("sample.fa");
2016
2017        fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
2018        fs::write(&absolute_path, b"sample").unwrap();
2019
2020        let checksum = calculate_file_checksum(&absolute_path).unwrap();
2021        let storage_path = OperationFile::storage_file_path(
2022            context.workspace(),
2023            &absolute_path.to_string_lossy(),
2024            Some(&checksum),
2025        )
2026        .unwrap();
2027
2028        assert_eq!(storage_path, "nested/sample.fa");
2029    }
2030
2031    #[test]
2032    fn test_native_bgzf_generic_asset_keeps_bytes_and_source_path() {
2033        let context = setup_gen();
2034        let fixture_path =
2035            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
2036        let outside_dir = tempfile::tempdir().unwrap();
2037        let outside_path = outside_dir.path().join("opaque.bin");
2038        fs::copy(&fixture_path, &outside_path).unwrap();
2039        let outside_path_string = outside_path.to_string_lossy().to_string();
2040
2041        let file_addition = FileAddition::prepare(
2042            context.workspace(),
2043            &outside_path_string,
2044            FileTypes::None,
2045            None,
2046        )
2047        .unwrap();
2048        let storage_path = OperationFile::storage_file_path(
2049            context.workspace(),
2050            &outside_path_string,
2051            file_addition.checksum.as_ref(),
2052        )
2053        .unwrap();
2054        let checksum = file_addition
2055            .checksum
2056            .expect("local file addition should have a checksum");
2057        let archived_path = context
2058            .workspace()
2059            .asset_dir()
2060            .unwrap()
2061            .join(file_addition.hashed_filename().unwrap());
2062
2063        assert_eq!(storage_path, ".gen/outside_root/opaque.bin");
2064        assert_eq!(
2065            fs::read(archived_path).unwrap(),
2066            fs::read(fixture_path).unwrap()
2067        );
2068        assert_eq!(
2069            file_addition.asset_uri,
2070            LocalAssetUri::asset_uri(&format!(".gen/assets/{checksum}.none.bgz")),
2071        );
2072    }
2073
2074    #[test]
2075    fn test_file_addition_prepare() {
2076        let context = setup_gen();
2077        let repo_root = context.workspace().repo_root().unwrap();
2078
2079        let file1_path = repo_root.join("test_file.bin");
2080        let file_contents = b"\x00\xffgeneric binary asset\x80";
2081        fs::write(&file1_path, file_contents).unwrap();
2082        let file1_path_str = file1_path.to_string_lossy().to_string();
2083        let fa1 =
2084            FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::None, None)
2085                .expect("should prepare file addition");
2086
2087        let archive_checksum = fa1.checksum.expect("should checksum generic BGZF asset");
2088        let materialized_checksum = fa1
2089            .materialized_checksum
2090            .expect("should checksum original generic bytes");
2091        let expected_asset_path = format!(".gen/assets/{archive_checksum}.none.bgz");
2092        assert_eq!(
2093            fa1.asset_uri,
2094            LocalAssetUri::asset_uri(&expected_asset_path)
2095        );
2096        assert_eq!(fa1.file_path(), expected_asset_path);
2097        assert_eq!(
2098            calculate_file_checksum(&file1_path).unwrap(),
2099            materialized_checksum
2100        );
2101        let archive_path = context.workspace().asset_dir().unwrap().join(
2102            fa1.hashed_filename()
2103                .expect("should derive generic BGZF filename"),
2104        );
2105        let mut decoded = noodles::bgzf::io::Reader::new(
2106            fs::File::open(archive_path).expect("should open generic BGZF asset"),
2107        );
2108        let mut decoded_contents = Vec::new();
2109        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
2110            .expect("should decode generic BGZF asset");
2111        assert_eq!(decoded_contents, file_contents);
2112
2113        for (file_type, filename) in [
2114            (FileTypes::Changeset, "generic_changeset.dat"),
2115            (FileTypes::Tabix, "generic_tabix.dat"),
2116        ] {
2117            let source_path = repo_root.join(filename);
2118            fs::write(&source_path, file_contents).expect("should write generic binary asset");
2119            let addition = FileAddition::prepare(
2120                context.workspace(),
2121                source_path
2122                    .to_str()
2123                    .expect("should encode generic asset path"),
2124                file_type,
2125                None,
2126            )
2127            .expect("should archive formerly excluded file type as BGZF");
2128            let archive_path = context.workspace().asset_dir().unwrap().join(
2129                addition
2130                    .hashed_filename()
2131                    .expect("should derive generic archive filename"),
2132            );
2133            let mut decoded = noodles::bgzf::io::Reader::new(
2134                fs::File::open(archive_path).expect("should open generic BGZF asset"),
2135            );
2136            let mut decoded_contents = Vec::new();
2137            std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
2138                .expect("should decode generic BGZF asset");
2139
2140            assert!(
2141                addition
2142                    .asset_uri
2143                    .ends_with(&format!(".{}.bgz", FileTypes::suffix(file_type))),
2144                "{file_type:?} should use its BGZF archive suffix"
2145            );
2146            assert_eq!(decoded_contents, file_contents);
2147        }
2148
2149        let relative1_id =
2150            LocalAssetUri::generate_file_addition_id(Some(&archive_checksum), &fa1.asset_uri);
2151
2152        assert_eq!(fa1.id, relative1_id);
2153        assert!(
2154            context
2155                .workspace()
2156                .asset_dir()
2157                .unwrap()
2158                .join(
2159                    fa1.hashed_filename()
2160                        .expect("local file addition should have a checksum"),
2161                )
2162                .exists()
2163        );
2164
2165        // Second call with same file should return the same FileAddition
2166        let fa2 =
2167            FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::None, None)
2168                .expect("should prepare same file addition");
2169
2170        assert_eq!(fa1, fa2);
2171
2172        let file2_path = repo_root.join("nested").join("file2.txt");
2173        fs::create_dir_all(file2_path.parent().unwrap()).unwrap();
2174        fs::write(&file2_path, file_contents).unwrap();
2175        let file2_path_str = file2_path.to_string_lossy().to_string();
2176
2177        let fa3 =
2178            FileAddition::prepare(context.workspace(), &file2_path_str, FileTypes::None, None)
2179                .expect("should prepare matching file addition");
2180
2181        assert_eq!(fa1.id, fa3.id);
2182
2183        fs::write(&file1_path, b"new content").unwrap();
2184        let fa1_new =
2185            FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::None, None)
2186                .expect("should prepare updated file addition");
2187
2188        assert_ne!(fa1.id, fa1_new.id);
2189
2190        let outside_dir = tempfile::tempdir().unwrap();
2191        let outside_file = outside_dir.path().join("opaque.bin");
2192        fs::write(&outside_file, file_contents).unwrap();
2193        let outside_path = outside_file.to_string_lossy().to_string();
2194
2195        let outside =
2196            FileAddition::prepare(context.workspace(), &outside_path, FileTypes::None, None)
2197                .expect("should prepare external file addition");
2198
2199        assert!(outside.asset_uri.ends_with(".none.bgz"));
2200        assert!(
2201            context
2202                .workspace()
2203                .asset_dir()
2204                .unwrap()
2205                .join(
2206                    outside
2207                        .hashed_filename()
2208                        .expect("local file addition should have a checksum"),
2209                )
2210                .exists()
2211        );
2212    }
2213
2214    #[test]
2215    fn test_plain_local_file_is_archived_as_bgzf_with_both_checksums() {
2216        let context = setup_gen();
2217        let repo_root = context.workspace().repo_root().unwrap();
2218        let source_path = repo_root.join("input.vcf");
2219        let source_contents = b"##fileformat=VCFv4.3\n#CHROM\tPOS\tID\nchr1\t1\t.\n";
2220        fs::write(&source_path, source_contents).expect("should write plain VCF source");
2221
2222        let file_addition = FileAddition::prepare(
2223            context.workspace(),
2224            source_path.to_str().expect("should encode VCF source path"),
2225            FileTypes::VCF,
2226            None,
2227        )
2228        .expect("should archive plain VCF as BGZF");
2229        let archive_checksum = file_addition
2230            .checksum
2231            .expect("should calculate archive checksum");
2232        let materialized_checksum = file_addition
2233            .materialized_checksum
2234            .expect("should calculate source checksum");
2235        let asset_dir = context.workspace().asset_dir().unwrap();
2236        let archive_path = asset_dir.join(
2237            file_addition
2238                .hashed_filename()
2239                .expect("should derive content-addressed archive filename"),
2240        );
2241
2242        assert_eq!(
2243            file_addition.asset_uri,
2244            LocalAssetUri::asset_uri(&format!(".gen/assets/{archive_checksum}.vcf.bgz"))
2245        );
2246        assert_eq!(
2247            calculate_file_checksum(&source_path).unwrap(),
2248            materialized_checksum
2249        );
2250        assert_eq!(
2251            calculate_file_checksum(&archive_path).unwrap(),
2252            archive_checksum
2253        );
2254        assert_ne!(archive_checksum, materialized_checksum);
2255        assert_eq!(fs::read(&source_path).unwrap(), source_contents);
2256        let verified_addition = FileAddition::prepare(
2257            context.workspace(),
2258            source_path.to_str().expect("should encode VCF source path"),
2259            FileTypes::VCF,
2260            Some(materialized_checksum),
2261        )
2262        .expect("should verify the supplied checksum against the plain source bytes");
2263        assert_eq!(verified_addition.checksum, Some(archive_checksum));
2264
2265        let mut decoded = noodles::bgzf::io::Reader::new(
2266            fs::File::open(&archive_path).expect("should open retained BGZF archive"),
2267        );
2268        let mut decoded_contents = Vec::new();
2269        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
2270            .expect("should decode retained BGZF archive");
2271        assert_eq!(decoded_contents, source_contents);
2272    }
2273
2274    #[test]
2275    fn test_file_addition_prepare_from_source_copies_staged_bgzf_independently() {
2276        let context = setup_gen();
2277        let asset_dir = context.workspace().asset_dir().unwrap();
2278        fs::create_dir_all(&asset_dir).expect("should create asset directory");
2279        let fixture_path =
2280            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
2281        let bgzf_contents = fs::read(fixture_path).expect("should read BGZF fixture");
2282        let staged_path = asset_dir.join("staged-source.fa.bgz");
2283        fs::write(&staged_path, &bgzf_contents).expect("should write ordinary staged file");
2284        let archive_checksum = calculate_reader_checksum(bgzf_contents.as_slice())
2285            .expect("should checksum compressed BGZF bytes");
2286        let materialized_checksum =
2287            calculate_reader_checksum(noodles::bgzf::io::Reader::new(Cursor::new(&bgzf_contents)))
2288                .expect("should checksum decoded BGZF contents");
2289
2290        let addition = FileAddition::prepare_from_source(
2291            context.workspace(),
2292            "sorted-source.fa",
2293            FileTypes::Fasta,
2294            FileSource::StagedBgzf {
2295                path: staged_path.clone(),
2296                archive_checksum,
2297                materialized_checksum,
2298            },
2299            false,
2300        )
2301        .expect("should copy a regular staged BGZF path");
2302        let asset_path = asset_dir.join(
2303            addition
2304                .hashed_filename()
2305                .expect("should derive content-addressed BGZF filename"),
2306        );
2307
2308        assert_eq!(addition.checksum, Some(archive_checksum));
2309        assert_eq!(addition.materialized_checksum, Some(materialized_checksum));
2310        assert_eq!(fs::read(&asset_path).unwrap(), bgzf_contents);
2311        assert_eq!(fs::read(&staged_path).unwrap(), bgzf_contents);
2312
2313        fs::write(&staged_path, b"modified staged source")
2314            .expect("should modify the retained source after copying");
2315        assert_eq!(
2316            fs::read(&asset_path).unwrap(),
2317            bgzf_contents,
2318            "the retained copy should not share the source file"
2319        );
2320    }
2321
2322    #[test]
2323    fn test_file_addition_prepare_from_source_moves_staged_bgzf() {
2324        let context = setup_gen();
2325        let asset_dir = context.workspace().asset_dir().unwrap();
2326        fs::create_dir_all(&asset_dir).expect("should create asset directory");
2327        let fixture_path =
2328            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
2329        let bgzf_contents = fs::read(fixture_path).expect("should read BGZF fixture");
2330        let staged_path = asset_dir.join("staged-source.fa.bgz");
2331        fs::write(&staged_path, &bgzf_contents).expect("should write ordinary staged file");
2332        let archive_checksum = calculate_reader_checksum(bgzf_contents.as_slice())
2333            .expect("should checksum compressed BGZF bytes");
2334        let materialized_checksum =
2335            calculate_reader_checksum(noodles::bgzf::io::Reader::new(Cursor::new(&bgzf_contents)))
2336                .expect("should checksum decoded BGZF contents");
2337
2338        let addition = FileAddition::prepare_from_source(
2339            context.workspace(),
2340            "sorted-source.fa",
2341            FileTypes::Fasta,
2342            FileSource::StagedBgzf {
2343                path: staged_path.clone(),
2344                archive_checksum,
2345                materialized_checksum,
2346            },
2347            true,
2348        )
2349        .expect("should move a regular staged BGZF path");
2350        let asset_path = asset_dir.join(
2351            addition
2352                .hashed_filename()
2353                .expect("should derive content-addressed BGZF filename"),
2354        );
2355
2356        assert!(
2357            !staged_path.exists(),
2358            "moving should consume the source path"
2359        );
2360        assert_eq!(fs::read(&asset_path).unwrap(), bgzf_contents);
2361
2362        let addition_from_asset_path = FileAddition::prepare_from_source(
2363            context.workspace(),
2364            "sorted-source.fa",
2365            FileTypes::Fasta,
2366            FileSource::StagedBgzf {
2367                path: asset_path.clone(),
2368                archive_checksum,
2369                materialized_checksum,
2370            },
2371            false,
2372        )
2373        .expect("should copy an already-canonical staged path without truncating it");
2374        assert_eq!(addition, addition_from_asset_path);
2375        assert!(
2376            asset_path.exists(),
2377            "same-path move should preserve the asset"
2378        );
2379    }
2380
2381    #[test]
2382    fn test_index_suffixes_remain_raw_for_direct_index_readers() {
2383        let context = setup_gen();
2384        let repo_root = context.workspace().repo_root().unwrap();
2385        let asset_dir = context.workspace().asset_dir().unwrap();
2386        let index_contents = b"index bytes\n";
2387
2388        for (index, extension) in ["fai", "gzi", "tbi", "csi", "bai", "BAI"]
2389            .iter()
2390            .enumerate()
2391        {
2392            // Distinct stems keep case variants separate on case-insensitive filesystems.
2393            let filename = format!("reference_{index}.fa.{extension}");
2394            let source_path = repo_root.join(&filename);
2395            fs::write(&source_path, index_contents).expect("should write raw index file");
2396
2397            let addition = FileAddition::prepare(
2398                context.workspace(),
2399                source_path.to_str().expect("should encode index path"),
2400                FileTypes::Fasta,
2401                None,
2402            )
2403            .expect("should retain index bytes without BGZF encoding");
2404            let archived_path = asset_dir.join(
2405                addition
2406                    .hashed_filename()
2407                    .expect("should derive retained index filename"),
2408            );
2409            let source_checksum = calculate_file_checksum(&source_path).unwrap();
2410            let archived_checksum = calculate_file_checksum(&archived_path).unwrap();
2411            let storage_path = OperationFile::storage_file_path(
2412                context.workspace(),
2413                source_path.to_str().expect("should encode index path"),
2414                addition.checksum.as_ref(),
2415            )
2416            .expect("should preserve the index sidecar path");
2417
2418            assert_eq!(addition.materialized_checksum, None);
2419            assert_eq!(addition.checksum.as_ref(), Some(&source_checksum));
2420            assert_eq!(archived_checksum, source_checksum);
2421            assert_eq!(fs::read(archived_path).unwrap(), index_contents);
2422            assert!(addition.asset_uri.ends_with(&format!(".fa.{extension}")));
2423            assert_eq!(storage_path, filename);
2424        }
2425    }
2426
2427    #[test]
2428    fn test_bam_bgzf_asset_is_retained_byte_identically() {
2429        let context = setup_gen();
2430        let repo_root = context.workspace().repo_root().unwrap();
2431        let source_path = repo_root.join("minimal.bam");
2432
2433        let mut bam_contents = b"BAM\x01".to_vec();
2434        bam_contents.extend_from_slice(&0_i32.to_le_bytes());
2435        bam_contents.extend_from_slice(&0_i32.to_le_bytes());
2436
2437        let mut bgzf_writer = noodles::bgzf::io::writer::Builder::default()
2438            .set_compression_level(noodles::bgzf::io::writer::CompressionLevel::NONE)
2439            .build_from_writer(Vec::new());
2440        bgzf_writer
2441            .write_all(&bam_contents)
2442            .expect("should write minimal BAM bytes");
2443        let bam_bgzf_contents = bgzf_writer
2444            .finish()
2445            .expect("should finish BGZF-compressed BAM bytes");
2446        fs::write(&source_path, &bam_bgzf_contents).expect("should write BGZF BAM asset");
2447
2448        let addition = FileAddition::prepare(
2449            context.workspace(),
2450            source_path.to_str().expect("should encode BAM path"),
2451            FileTypes::None,
2452            None,
2453        )
2454        .expect("should retain BGZF-compressed BAM bytes");
2455        let checksum = addition
2456            .checksum
2457            .as_ref()
2458            .expect("should checksum the retained BAM asset");
2459        let archived_path = context
2460            .workspace()
2461            .asset_dir()
2462            .unwrap()
2463            .join(addition.hashed_filename().unwrap());
2464        let storage_path = OperationFile::storage_file_path(
2465            context.workspace(),
2466            source_path.to_str().expect("should encode BAM path"),
2467            Some(checksum),
2468        )
2469        .expect("should preserve the BAM logical path");
2470
2471        assert_eq!(addition.materialized_checksum, None);
2472        assert_eq!(calculate_file_checksum(&source_path).unwrap(), *checksum);
2473        assert_eq!(calculate_file_checksum(&archived_path).unwrap(), *checksum);
2474        assert_eq!(fs::read(archived_path).unwrap(), bam_bgzf_contents);
2475        assert_eq!(storage_path, "minimal.bam");
2476
2477        let mut decoded = noodles::bgzf::io::Reader::new(Cursor::new(bam_bgzf_contents));
2478        let mut decoded_contents = Vec::new();
2479        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
2480            .expect("should decode the retained BAM bytes");
2481        assert_eq!(decoded_contents, bam_contents);
2482    }
2483
2484    #[test]
2485    fn test_existing_gzip_generic_file_is_normalized_as_bgzf() {
2486        let context = setup_gen();
2487        let repo_root = context.workspace().repo_root().unwrap();
2488        let asset_dir = context.workspace().asset_dir().unwrap();
2489        let source_path = repo_root.join("opaque.bin.gz");
2490        let decoded_source_contents = b"\x00\xffgeneric gzip asset\x80";
2491        let mut gzip_encoder =
2492            flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2493        gzip_encoder
2494            .write_all(decoded_source_contents)
2495            .expect("should write gzip asset content");
2496        let gzip_contents = gzip_encoder
2497            .finish()
2498            .expect("should finish gzip asset content");
2499        fs::write(&source_path, &gzip_contents).expect("should write compressed generic bytes");
2500
2501        let source_checksum = calculate_file_checksum(&source_path).unwrap();
2502        let addition = FileAddition::prepare(
2503            context.workspace(),
2504            source_path
2505                .to_str()
2506                .expect("should encode compressed generic path"),
2507            FileTypes::None,
2508            Some(source_checksum),
2509        )
2510        .expect("should normalize ordinary gzip generic asset as BGZF");
2511        let archive_checksum = addition.checksum.expect("should checksum BGZF archive");
2512        let archived_path = asset_dir.join(
2513            addition
2514                .hashed_filename()
2515                .expect("should derive compressed generic filename"),
2516        );
2517        let mut decoded = noodles::bgzf::io::Reader::new(
2518            fs::File::open(&archived_path).expect("should open normalized generic archive"),
2519        );
2520        let mut decoded_contents = Vec::new();
2521        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
2522            .expect("should decode normalized generic archive");
2523
2524        assert_eq!(addition.materialized_checksum, None);
2525        assert_eq!(
2526            calculate_file_checksum(archived_path).unwrap(),
2527            archive_checksum
2528        );
2529        assert_eq!(decoded_contents, decoded_source_contents);
2530        assert_eq!(fs::read(source_path).unwrap(), gzip_contents);
2531        assert!(addition.asset_uri.ends_with(".none.bgz"));
2532    }
2533
2534    #[test]
2535    fn test_file_addition_prepare_http_uri() {
2536        let context = setup_gen();
2537        let asset_uri = "https://example.com/assets/reference.fa";
2538
2539        let addition =
2540            FileAddition::prepare(context.workspace(), asset_uri, FileTypes::Fasta, None)
2541                .expect("should prepare HTTP file addition");
2542
2543        assert_eq!(addition.asset_uri, asset_uri);
2544        assert_eq!(addition.file_path(), asset_uri);
2545        assert_eq!(addition.checksum, None);
2546        assert!(
2547            fs::read_dir(context.workspace().asset_dir().unwrap())
2548                .unwrap()
2549                .next()
2550                .is_none()
2551        );
2552    }
2553
2554    #[test]
2555    fn test_file_addition_prepare_remote_uri() {
2556        let context = setup_gen();
2557        let asset_uri = "s3://bucket/reference.fa";
2558        let checksum = Sha256Hash::convert_str("remote S3 contents");
2559
2560        let addition = FileAddition::prepare(
2561            context.workspace(),
2562            asset_uri,
2563            FileTypes::Fasta,
2564            Some(checksum),
2565        )
2566        .expect("should prepare remote file addition");
2567
2568        assert_eq!(addition.asset_uri, asset_uri);
2569        assert_eq!(addition.file_path(), asset_uri);
2570        assert_eq!(addition.checksum, Some(checksum));
2571    }
2572
2573    #[test]
2574    fn test_file_addition_rejects_incorrect_local_checksum_override() {
2575        let context = setup_gen();
2576        let path = context.workspace().repo_root().unwrap().join("asset.fa");
2577        fs::write(&path, "actual contents").expect("should write local asset");
2578        let file_path = path.to_str().expect("should encode local asset path");
2579
2580        let error = FileAddition::prepare(
2581            context.workspace(),
2582            file_path,
2583            FileTypes::Fasta,
2584            Some(Sha256Hash::convert_str("different contents")),
2585        )
2586        .expect_err("should reject incorrect checksum override");
2587
2588        assert!(
2589            matches!(error, FileAdditionError::ChecksumError(_)),
2590            "should report a checksum error: {error}"
2591        );
2592        assert!(
2593            error.to_string().contains(file_path),
2594            "checksum error should include the source path: {error}"
2595        );
2596        assert_eq!(
2597            fs::read_dir(context.workspace().asset_dir().unwrap())
2598                .expect("should read asset directory")
2599                .count(),
2600            0
2601        );
2602    }
2603
2604    #[test]
2605    fn test_add_files_operation_does_not_read_remote_asset() {
2606        let context = setup_gen();
2607        let asset_uri = "http://127.0.0.1:1/asset.fa".to_string();
2608        let operation_file = OperationFile::new(&asset_uri);
2609
2610        add_files_operation(
2611            &context,
2612            from_ref(&operation_file),
2613            Some("track remote reference"),
2614        )
2615        .expect("should track remote asset");
2616
2617        let asset_refs =
2618            AssetRef::all(context.graph().conn()).expect("should load asset references");
2619        assert_eq!(asset_refs.len(), 1);
2620        assert_eq!(asset_refs[0].uri, asset_uri);
2621        assert_eq!(asset_refs[0].checksum, None);
2622    }
2623
2624    #[test]
2625    fn test_add_files_operation_passes_remote_checksum_override() {
2626        let context = setup_gen();
2627        let asset_uri = "http://127.0.0.1:1/asset.fa";
2628        let checksum = Sha256Hash::convert_str("known remote contents");
2629        let operation_file = OperationFile::new(asset_uri).set_checksum_override(checksum);
2630
2631        add_files_operation(
2632            &context,
2633            from_ref(&operation_file),
2634            Some("track checksummed remote reference"),
2635        )
2636        .expect("should track remote asset without reading it");
2637
2638        let asset_refs =
2639            AssetRef::all(context.graph().conn()).expect("should load asset references");
2640        assert_eq!(asset_refs.len(), 1);
2641        assert_eq!(asset_refs[0].uri, asset_uri);
2642        assert_eq!(asset_refs[0].checksum, Some(checksum));
2643    }
2644
2645    #[test]
2646    fn test_add_files_operation_stores_shared_unmodified_asset_once_across_operations() {
2647        let context = setup_gen();
2648        let graph_conn = context.graph().conn();
2649        let workspace = context.workspace();
2650
2651        let repo_root = workspace.repo_root().unwrap();
2652        fs::write(repo_root.join("shared.txt"), "shared contents").unwrap();
2653        fs::write(repo_root.join("unique.txt"), "unique contents").unwrap();
2654
2655        let _operation_1_hash =
2656            add_files_operation(&context, &[OperationFile::new("shared.txt")], Some("first"))
2657                .unwrap();
2658        let _operation_2_hash = add_files_operation(
2659            &context,
2660            &[
2661                OperationFile::new("shared.txt"),
2662                OperationFile::new("unique.txt"),
2663            ],
2664            Some("second"),
2665        )
2666        .unwrap();
2667
2668        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
2669        operation_logs.sort_by_key(|operation_log| operation_log.created_on);
2670        let mut first_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
2671        first_assets.sort_by_key(|asset| asset.asset_ref_id);
2672        let mut second_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[1].id);
2673        second_assets.sort_by_key(|asset| asset.asset_ref_id);
2674
2675        assert_eq!(operation_logs[0].command, "first");
2676        assert_eq!(operation_logs[1].command, "second");
2677        assert_eq!(first_assets.len(), 1);
2678        assert_eq!(second_assets.len(), 2);
2679        assert!(
2680            second_assets
2681                .iter()
2682                .any(|asset| asset.asset_ref_id == first_assets[0].asset_ref_id)
2683        );
2684
2685        let shared_asset = AssetRef::select(graph_conn)
2686            .get_by_id(first_assets[0].asset_ref_id)
2687            .expect("should query shared asset ref")
2688            .expect("should load shared asset ref");
2689        let unique_asset = second_assets
2690            .iter()
2691            .find(|asset| asset.asset_ref_id != first_assets[0].asset_ref_id)
2692            .and_then(|asset| {
2693                AssetRef::select(graph_conn)
2694                    .get_by_id(asset.asset_ref_id)
2695                    .expect("should query unique asset ref")
2696            })
2697            .expect("should load unique asset ref");
2698
2699        let assets_dir = workspace.asset_dir().unwrap();
2700        let asset_names = fs::read_dir(&assets_dir)
2701            .unwrap()
2702            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
2703            .collect::<Vec<_>>();
2704
2705        assert_eq!(asset_names.len(), 2);
2706        let shared_asset_name = <dyn AssetUri>::from_uri(&shared_asset.uri)
2707            .hashed_filename(&shared_asset.checksum.unwrap());
2708        let unique_asset_name = <dyn AssetUri>::from_uri(&unique_asset.uri)
2709            .hashed_filename(&unique_asset.checksum.unwrap());
2710        assert!(asset_names.contains(&shared_asset_name));
2711        assert!(asset_names.contains(&unique_asset_name));
2712    }
2713
2714    #[test]
2715    fn test_add_files_operation_tracks_distinct_filenames_for_same_asset()
2716    -> Result<(), Box<dyn std::error::Error>> {
2717        let context = setup_gen();
2718        let graph_conn = context.graph().conn();
2719
2720        let outside_dir = tempfile::tempdir()?;
2721        let alpha_path = outside_dir.path().join("alpha.fa");
2722        let beta_path = outside_dir.path().join("beta.fa");
2723        fs::write(&alpha_path, "shared contents")?;
2724        fs::write(&beta_path, "shared contents")?;
2725
2726        add_files_operation(
2727            &context,
2728            &[
2729                OperationFile::new(alpha_path.to_string_lossy()),
2730                OperationFile::new(beta_path.to_string_lossy()),
2731            ],
2732            Some("same asset, different filenames"),
2733        )?;
2734
2735        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
2736        asset_refs.sort_by(|left, right| left.name.cmp(&right.name));
2737
2738        assert_eq!(
2739            asset_refs
2740                .iter()
2741                .map(|asset| asset.name.clone().unwrap_or_default())
2742                .collect::<Vec<_>>(),
2743            vec!["alpha.fa".to_string(), "beta.fa".to_string()],
2744        );
2745        assert_ne!(asset_refs[0].id, asset_refs[1].id);
2746        assert_eq!(asset_refs[0].checksum, asset_refs[1].checksum);
2747        Ok(())
2748    }
2749
2750    #[test]
2751    fn test_add_files_operation_tracks_graph_asset_refs() {
2752        let context = setup_gen();
2753        let graph_conn = context.graph().conn();
2754
2755        let repo_root = context.workspace().repo_root().unwrap();
2756        fs::write(repo_root.join("alpha.fa"), "AAAA").unwrap();
2757        fs::write(repo_root.join("beta.fa"), "BBBB").unwrap();
2758
2759        let _operation_hash = add_files_operation(
2760            &context,
2761            &[
2762                OperationFile::new("alpha.fa"),
2763                OperationFile::new("beta.fa"),
2764            ],
2765            Some("import references"),
2766        )
2767        .unwrap();
2768
2769        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
2770        asset_refs.sort_by(|left, right| left.logical_path.cmp(&right.logical_path));
2771        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
2772        operation_logs.sort_by_key(|operation_log| operation_log.created_on);
2773
2774        assert_eq!(asset_refs.len(), 2);
2775        assert_eq!(asset_refs[0].logical_path.as_deref(), Some("alpha.fa"));
2776        assert_eq!(asset_refs[0].name.as_deref(), Some("alpha.fa"));
2777        assert_eq!(asset_refs[0].role, AssetRole::Input);
2778        assert_eq!(asset_refs[1].logical_path.as_deref(), Some("beta.fa"));
2779        assert_eq!(asset_refs[1].name.as_deref(), Some("beta.fa"));
2780        assert_eq!(asset_refs[1].role, AssetRole::Input);
2781        assert_eq!(operation_logs.len(), 1);
2782        assert_eq!(operation_logs[0].operation_kind, OperationKind::AddFile);
2783        assert_eq!(operation_logs[0].command, "import references");
2784        let mut operation_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
2785        operation_assets.sort_by(|left, right| {
2786            left.role
2787                .as_str()
2788                .cmp(right.role.as_str())
2789                .then_with(|| left.asset_ref_id.cmp(&right.asset_ref_id))
2790        });
2791        assert_eq!(operation_assets.len(), 2);
2792        assert!(
2793            operation_assets
2794                .iter()
2795                .all(|asset| asset.role == AssetRole::Input)
2796        );
2797    }
2798
2799    #[test]
2800    fn test_add_files_operation_records_history_without_config_db_rows() {
2801        let context = setup_gen();
2802        let graph_conn = context.graph().conn();
2803        let config_conn = context.config().conn();
2804
2805        let repo_root = context.workspace().repo_root().unwrap();
2806        fs::write(repo_root.join("alpha.fa"), "AAAA").unwrap();
2807
2808        let operation_hash = add_files_operation(
2809            &context,
2810            &[OperationFile::new("alpha.fa")],
2811            Some("import reference"),
2812        )
2813        .unwrap();
2814
2815        let history_store = DoltHistoryStore::new(graph_conn);
2816        assert_eq!(
2817            history_store.current_head().unwrap(),
2818            Some(operation_hash),
2819            "add-file should commit through Dolt history"
2820        );
2821        let operation_count: i64 = config_conn
2822            .query_row(
2823                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'operations'",
2824                [],
2825                |row| row.get(0),
2826            )
2827            .unwrap();
2828        assert_eq!(operation_count, 0);
2829    }
2830}