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