1use 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, LocalAssetUri, OperationAsset, OperationKind, OperationLog,
36 },
37 db::{ConfigConnection, DbContext},
38 errors::{
39 AddFilesOperationError, FileAdditionError, FileStoreError, OperationError, RemoteError,
40 },
41 file_types::FileTypes,
42 history::{
43 HistoryStore,
44 dolt::{DoltHistoryStore, is_current_branch_dirty},
45 },
46 select::ModelSelectRow,
47};
48
49pub const GEN_DEFAULT_COMMITTER_NAME: &str = "gen";
50pub const DEFAULT_COMMITTER_EMAIL: &str = "gen@genhub.bio";
51
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct OperationFile {
54 pub filename: String,
55 pub file_path: String,
56 pub file_type: FileTypes,
57 pub checksum_override: Option<Sha256Hash>,
58 pub role: AssetRole,
59 pub upstream_asset_ref_id: Option<HashId>,
60}
61
62#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
63pub struct OperationFileInfo {
64 pub id: HashId,
65 pub filename: String,
66 pub file_path: String,
67 pub asset_uri: String,
68 pub file_type: FileTypes,
69 pub checksum: Option<Sha256Hash>,
70}
71
72impl OperationFile {
73 pub fn new(file_path: impl Into<String>) -> Self {
74 let file_path = file_path.into();
75 let file_type = FileTypes::infer_from_path(&file_path);
76 let filename = Path::new(&file_path)
77 .file_name()
78 .and_then(|name| name.to_str())
79 .unwrap_or(&file_path)
80 .to_string();
81 Self {
82 filename,
83 file_path,
84 file_type,
85 checksum_override: None,
86 role: AssetRole::Input,
87 upstream_asset_ref_id: None,
88 }
89 }
90
91 pub fn set_file_type(mut self, file_type: FileTypes) -> Self {
92 self.file_type = file_type;
93 self
94 }
95
96 pub fn set_checksum_override(mut self, checksum: Sha256Hash) -> Self {
97 self.checksum_override = Some(checksum);
98 self
99 }
100
101 pub fn set_role(mut self, role: AssetRole) -> Self {
102 self.role = role;
103 self
104 }
105
106 pub fn set_upstream_asset_ref_id(mut self, upstream_asset_ref_id: &HashId) -> Self {
107 self.upstream_asset_ref_id = Some(*upstream_asset_ref_id);
108 self
109 }
110
111 pub fn prepare_asset_ref(
113 &self,
114 workspace: &Workspace,
115 created_on: i64,
116 ) -> Result<AssetRef, FileAdditionError> {
117 let file_addition = FileAddition::prepare(
118 workspace,
119 &self.file_path,
120 self.file_type,
121 self.checksum_override,
122 )?;
123 let logical_path =
124 Self::storage_file_path(workspace, &self.file_path, file_addition.checksum.as_ref())?;
125 let file_type = file_addition.file_type.as_str();
126 Ok(AssetRef {
127 id: AssetRef::id_hash(
128 &file_addition.asset_uri,
129 file_type,
130 file_addition.checksum.as_ref(),
131 &self.role,
132 Some(&logical_path),
133 Some(&self.filename),
134 self.upstream_asset_ref_id.as_ref(),
135 ),
136 uri: file_addition.asset_uri,
137 file_type: file_type.to_string(),
138 checksum: file_addition.checksum,
139 size: None,
140 role: self.role.clone(),
141 logical_path: Some(logical_path),
142 name: Some(self.filename.clone()),
143 created_on,
144 upstream_asset_ref_id: self.upstream_asset_ref_id,
145 })
146 }
147
148 pub fn storage_file_path(
153 workspace: &Workspace,
154 path_or_uri: &str,
155 checksum: Option<&Sha256Hash>,
156 ) -> Result<String, FileAdditionError> {
157 if LocalAssetUri::is_local_path_or_file_uri(path_or_uri) {
158 let checksum = checksum.ok_or_else(|| {
159 FileAdditionError::ChecksumError(format!(
160 "local operation file has no checksum: {path_or_uri}"
161 ))
162 })?;
163 LocalAssetUri::operation_file_path(workspace, path_or_uri, checksum)
164 } else {
165 Ok(path_or_uri.to_string())
166 }
167 }
168}
169
170#[derive(Clone, Debug, Eq, PartialEq)]
171pub struct OperationInfo {
172 pub files: Vec<OperationFile>,
173 pub description: String,
174}
175
176#[derive(Clone, Debug, Eq, PartialEq)]
177pub struct OperationSummary {
178 pub operation_info: OperationInfo,
179 pub summary: String,
180}
181
182impl OperationSummary {
183 pub fn new(operation_info: OperationInfo, summary: impl Into<String>) -> Self {
184 Self {
185 operation_info,
186 summary: summary.into(),
187 }
188 }
189}
190
191#[cfg_attr(
192 feature = "profiling",
193 tracing::instrument(skip(context, operation_summary))
194)]
195pub fn commit_operation_summary(
196 context: &DbContext,
197 operation_summary: &OperationSummary,
198) -> Result<DoltHashId, OperationError> {
199 let workspace = context.workspace();
200 let graph_conn = context.graph().conn();
201 let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
202 let operation_info = &operation_summary.operation_info;
203
204 if !is_current_branch_dirty(graph_conn)? {
205 return Err(OperationError::NoChanges);
206 }
207
208 let created_on = chrono::Utc::now()
209 .timestamp_nanos_opt()
210 .expect("should create operation asset timestamp");
211 let prepared_assets = operation_info
212 .files
213 .iter()
214 .map(|operation_file| operation_file.prepare_asset_ref(workspace, created_on))
215 .collect::<Result<Vec<_>, _>>()
216 .map_err(|err| match err {
217 FileAdditionError::ConfigError(config_error) => {
218 OperationError::ConfigError(config_error)
219 }
220 other => OperationError::SQLError(other.to_string()),
221 })?;
222 let operation_kind = OperationKind::Other(operation_info.description.clone());
223 track_asset_refs(
224 graph_conn,
225 None,
226 &operation_kind,
227 &operation_summary.summary,
228 &prepared_assets,
229 )?;
230
231 let commit_result = history_store.commit_all(&operation_summary.summary);
232 commit_result.map_err(OperationError::from)
233}
234
235#[cfg_attr(
236 feature = "profiling",
237 tracing::instrument(skip(graph_conn, log_id, assets))
238)]
239pub(crate) fn track_asset_refs(
240 graph_conn: &crate::db::GraphConnection,
241 log_id: Option<&HashId>,
242 operation_kind: &OperationKind,
243 command: &str,
244 assets: &[AssetRef],
245) -> Result<(), rusqlite::Error> {
246 let created_on = chrono::Utc::now()
247 .timestamp_nanos_opt()
248 .expect("should create operation asset timestamp");
249 let log_id = log_id
250 .copied()
251 .unwrap_or_else(|| OperationLog::id_hash(operation_kind, command, created_on));
252 OperationLog::create(
253 graph_conn,
254 &OperationLog {
255 id: log_id,
256 operation_kind: operation_kind.clone(),
257 command: command.to_string(),
258 created_on,
259 },
260 )?;
261
262 for asset_ref in assets {
263 AssetRef::create(graph_conn, asset_ref)?;
264 OperationAsset::create(
265 graph_conn,
266 &OperationAsset {
267 log_id,
268 asset_ref_id: asset_ref.id,
269 role: asset_ref.role.clone(),
270 },
271 )?;
272 }
273
274 Ok(())
275}
276
277#[cfg_attr(
278 all(debug_assertions, feature = "profiling"),
279 tracing::instrument(skip(context, files, message))
280)]
281pub fn add_files_operation(
286 context: &DbContext,
287 files: &[OperationFile],
288 message: Option<&str>,
289) -> Result<DoltHashId, AddFilesOperationError> {
290 let workspace = context.workspace();
291 let graph_conn = context.graph().conn();
292
293 let file_additions = files
294 .iter()
295 .map(|operation_file| {
296 let file_addition = FileAddition::prepare(
297 workspace,
298 &operation_file.file_path,
299 operation_file.file_type,
300 operation_file.checksum_override,
301 )?;
302 let operation_file_path = OperationFile::storage_file_path(
303 workspace,
304 &operation_file.file_path,
305 file_addition.checksum.as_ref(),
306 )?;
307 Ok::<(FileAddition, String, String), FileAdditionError>((
308 file_addition,
309 operation_file.filename.clone(),
310 operation_file_path,
311 ))
312 })
313 .collect::<Result<Vec<_>, _>>()?;
314
315 let unique_file_additions = file_additions
316 .into_iter()
317 .unique_by(|(file_addition, filename, file_path)| {
318 (file_addition.id, filename.clone(), file_path.clone())
319 })
320 .collect::<Vec<_>>();
321
322 let log_id = HashId(calculate_hash(
323 &unique_file_additions
324 .iter()
325 .map(|(file_addition, filename, file_path)| {
326 format!("{}:{filename}:{file_path}", file_addition.id)
327 })
328 .sorted()
329 .join(":"),
330 ));
331
332 let summary = message.map(str::to_string).unwrap_or_else(|| {
333 if files.len() == 1 {
334 format!("Add file {}", files[0].file_path)
335 } else {
336 format!("Add {} files", files.len())
337 }
338 });
339 let created_on = chrono::Utc::now()
340 .timestamp_nanos_opt()
341 .expect("should create operation asset timestamp");
342 let asset_refs = unique_file_additions
343 .iter()
344 .map(|(file_addition, filename, file_path)| {
345 AssetRef::from_file_addition(
346 file_addition,
347 AssetRole::Input,
348 Some(file_path),
349 Some(filename),
350 None,
351 created_on,
352 )
353 })
354 .collect::<Vec<_>>();
355 track_asset_refs(
356 graph_conn,
357 Some(&log_id),
358 &OperationKind::AddFile,
359 &summary,
360 &asset_refs,
361 )?;
362 let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
363 if history_store.status()?.is_empty() {
364 return Err(AddFilesOperationError::OperationError(
365 OperationError::NoChanges,
366 ));
367 }
368
369 history_store
370 .commit_all(&summary)
371 .map_err(AddFilesOperationError::from)
372}
373
374pub fn calculate_file_checksum<P: AsRef<Path>>(file_path: P) -> Result<Sha256Hash, std::io::Error> {
375 let file = std::fs::File::open(file_path)?;
376 let reader = BufReader::new(file);
377 calculate_reader_checksum(reader)
378}
379
380pub fn calculate_reader_checksum<R: std::io::Read>(
381 reader: R,
382) -> Result<Sha256Hash, std::io::Error> {
383 let hash_bytes = calculate_stream_hash(reader)?;
384 Ok(Sha256Hash(hash_bytes))
385}
386
387fn calculate_stream_hash<R: std::io::Read>(mut reader: R) -> Result<[u8; 32], std::io::Error> {
388 let mut hasher = Sha256::new();
389 io::copy(&mut reader, &mut hasher)?;
390 let result = hasher.finalize();
391 let mut hash_array = [0u8; 32];
392 hash_array.copy_from_slice(&result);
393 Ok(hash_array)
394}
395
396#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize, ModelSelect)]
397#[model_select(table = "file_additions")]
398pub struct FileAddition {
399 pub id: HashId,
400 pub asset_uri: String,
401 pub file_type: FileTypes,
402 pub checksum: Option<Sha256Hash>,
403}
404
405impl FileAddition {
406 pub fn file_path(&self) -> &str {
407 self.asset_uri
408 .strip_prefix(LocalAssetUri::SCHEME)
409 .unwrap_or(&self.asset_uri)
410 }
411
412 #[cfg_attr(
413 feature = "profiling",
414 tracing::instrument(skip(workspace, checksum_override))
415 )]
416 pub fn prepare(
421 workspace: &Workspace,
422 file_path: &str,
423 file_type: FileTypes,
424 checksum_override: Option<Sha256Hash>,
425 ) -> Result<FileAddition, FileAdditionError> {
426 let asset_uri = <dyn AssetUri>::new(workspace, file_path);
427 let checksum = asset_uri.prepare_asset(workspace, checksum_override)?;
428 let stored_asset_uri = match checksum.as_ref() {
429 Some(checksum) => asset_uri.stored_asset_uri(workspace, checksum)?,
430 None => asset_uri.uri().to_string(),
431 };
432 Ok(FileAddition {
433 id: LocalAssetUri::generate_file_addition_id(checksum.as_ref(), &stored_asset_uri),
434 asset_uri: stored_asset_uri,
435 file_type,
436 checksum,
437 })
438 }
439
440 #[cfg_attr(
441 all(debug_assertions, feature = "profiling"),
442 tracing::instrument(skip(self, workspace))
443 )]
444 pub fn store_file(&self, workspace: &Workspace) -> Result<(), FileStoreError> {
445 let asset_uri = <dyn AssetUri>::new(workspace, &self.asset_uri);
446 asset_uri.store_file(self, workspace)
447 }
448
449 pub fn hashed_filename(&self) -> Option<String> {
454 self.checksum
455 .as_ref()
456 .map(|checksum| <dyn AssetUri>::from_uri(&self.asset_uri).hashed_filename(checksum))
457 }
458}
459
460#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ModelSelect)]
461#[model_select(table = "remotes", history = false)]
462pub struct Remote {
463 #[model_select(primary_key)]
464 pub name: String,
465 pub url: String,
466}
467
468impl Remote {
469 pub fn validate_name(name: &str) -> Result<(), RemoteError> {
471 if name.is_empty() {
472 return Err(RemoteError::EmptyName);
473 }
474
475 if name
476 .chars()
477 .any(|c| !c.is_alphanumeric() && c != '-' && c != '_')
478 {
479 return Err(RemoteError::InvalidNameCharacters);
480 }
481
482 Ok(())
483 }
484
485 pub fn validate_url(url: &str) -> Result<(), RemoteError> {
487 if url.is_empty() {
488 return Err(RemoteError::EmptyUrl);
489 }
490
491 if url.contains("://") {
493 match url::Url::parse(url) {
494 Ok(parsed_url) => {
495 match parsed_url.scheme() {
497 "http" | "https" | "ssh" | "file" => Ok(()),
498 _ => Err(RemoteError::UnsupportedUrlScheme),
499 }
500 }
501 Err(_) => Err(RemoteError::InvalidUrl("Invalid URL format".to_string())),
502 }
503 } else if url.starts_with('/') || url.contains(':') {
504 Ok(())
506 } else {
507 Err(RemoteError::UnsupportedUrlScheme)
508 }
509 }
510
511 pub fn create(conn: &ConfigConnection, name: &str, url: &str) -> Result<Remote, RemoteError> {
514 Self::validate_name(name)?;
516 Self::validate_url(url)?;
517
518 let query = "INSERT INTO remotes (name, url) VALUES (?1, ?2)";
519 let mut stmt = conn.prepare(query)?;
520
521 match stmt.execute(params![name, url]) {
522 Ok(_) => Ok(Remote {
523 name: name.to_string(),
524 url: url.to_string(),
525 }),
526 Err(rusqlite::Error::SqliteFailure(err, _))
527 if err.code == rusqlite::ErrorCode::ConstraintViolation =>
528 {
529 Err(RemoteError::RemoteAlreadyExists(name.to_string()))
530 }
531 Err(e) => Err(RemoteError::DatabaseError(e)),
532 }
533 }
534
535 pub fn get_by_name(conn: &ConfigConnection, name: &str) -> Result<Remote, RemoteError> {
537 Remote::select(conn)
538 .name(name)
539 .load()?
540 .into_iter()
541 .next()
542 .ok_or_else(|| RemoteError::RemoteNotFound(name.to_string()))
543 }
544
545 pub fn get_by_name_optional(conn: &ConfigConnection, name: &str) -> Option<Remote> {
547 Self::get_by_name(conn, name).ok()
548 }
549
550 pub fn list_all(conn: &ConfigConnection) -> Vec<Remote> {
552 Remote::select(conn)
553 .order_by(RemoteSelect::Name, Direction::Asc)
554 .load()
555 .expect("should load remotes")
556 }
557
558 pub fn delete(conn: &ConfigConnection, name: &str) -> Result<(), RemoteError> {
560 Self::get_by_name(conn, name)?;
562 RemoteBranch::clear_by_remote(conn, name)?;
563
564 let query = "DELETE FROM remotes WHERE name = ?1";
565 let mut stmt = conn.prepare(query)?;
566 stmt.execute(params![name])?;
567 Ok(())
568 }
569
570 pub fn exists(conn: &ConfigConnection, name: &str) -> bool {
572 Self::get_by_name_optional(conn, name).is_some()
573 }
574}
575
576#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
577#[model_select(table = "remote_branch", history = false)]
578pub struct RemoteBranch {
579 pub remote_name: Option<String>,
580 #[model_select(primary_key)]
581 pub name: String,
582}
583
584impl RemoteBranch {
585 pub fn set_remote_validated(
586 conn: &ConfigConnection,
587 branch_name: &str,
588 remote_name: Option<&str>,
589 ) -> Result<(), RemoteError> {
590 if let Some(name) = remote_name {
591 Remote::get_by_name(conn, name)?;
592 conn.execute(
593 "DELETE FROM remote_branch WHERE name = ?1",
594 params![branch_name],
595 )?;
596 conn.execute(
597 "INSERT INTO remote_branch (name, remote_name) VALUES (?1, ?2)",
598 params![branch_name, name],
599 )?;
600 } else {
601 conn.execute(
602 "DELETE FROM remote_branch WHERE name = ?1",
603 params![branch_name],
604 )?;
605 }
606 Ok(())
607 }
608
609 pub fn get_remote(conn: &ConfigConnection, branch_name: &str) -> Option<String> {
610 RemoteBranch::select(conn)
611 .name(branch_name)
612 .only(RemoteBranchSelect::RemoteName)
613 .load()
614 .ok()?
615 .into_iter()
616 .next()
617 .flatten()
618 }
619
620 pub fn clear_by_remote(conn: &ConfigConnection, remote_name: &str) -> Result<(), RemoteError> {
621 conn.execute(
622 "DELETE FROM remote_branch WHERE remote_name = ?1",
623 params![remote_name],
624 )?;
625 Ok(())
626 }
627}
628
629#[derive(Clone, Copy, Debug, Eq, PartialEq)]
631pub enum RemoteOperationKind {
632 Clone,
634 Pull,
636 Push,
638}
639
640impl RemoteOperationKind {
641 const fn as_str(self) -> &'static str {
642 match self {
643 Self::Clone => "clone",
644 Self::Pull => "pull",
645 Self::Push => "push",
646 }
647 }
648}
649
650impl FromSql for RemoteOperationKind {
651 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
652 value.as_str().map(|operation| match operation {
653 "clone" => Self::Clone,
654 "pull" => Self::Pull,
655 "push" => Self::Push,
656 _ => unreachable!("remote operation should satisfy its database constraint"),
657 })
658 }
659}
660
661impl ToSql for RemoteOperationKind {
662 fn to_sql(&self) -> SQLResult<ToSqlOutput<'_>> {
663 Ok(self.as_str().into())
664 }
665}
666
667#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
669#[model_select(table = "remote_operations", history = false)]
670pub struct RemoteOperationRecord {
671 pub id: i64,
673 pub remote_name: String,
675 pub branch_name: String,
677 pub operation: RemoteOperationKind,
679 pub from_commit: Option<DoltHashId>,
681 pub assets_transfer_checkpoint: Option<DoltHashId>,
683 pub to_commit: Option<DoltHashId>,
685 pub transfer_id: Option<Uuid>,
687 pub transfer_expires_at: Option<i64>,
689 pub started_at: String,
691 pub completed_at: Option<String>,
693 pub failed_at: Option<String>,
695}
696
697impl RemoteOperationRecord {
698 pub fn begin_or_resume(
700 conn: &ConfigConnection,
701 remote_name: &str,
702 branch_name: &str,
703 operation: RemoteOperationKind,
704 from_commit: Option<&DoltHashId>,
705 ) -> SQLResult<Self> {
706 let pending = conn
707 .query_row(
708 "SELECT * FROM remote_operations \
709 WHERE remote_name = ?1 AND branch_name = ?2 \
710 AND completed_at IS NULL AND failed_at IS NULL \
711 -- This is confusing, but this checks whether a clone operation is followed by a pull.
712 -- If a clone fails to download assets, a pull can finish the operation even though the
713 -- persisted operation is clone and the requested operation is pull.
714 AND (operation = ?3 OR operation = 'clone' AND ?3 = 'pull') \
715 ORDER BY id LIMIT 1",
716 params![remote_name, branch_name, operation.as_str()],
717 Self::process_row,
718 )
719 .optional()?;
720 if let Some(pending) = pending {
721 return Ok(pending);
722 }
723
724 let assets_transfer_checkpoint = conn
725 .query_row(
726 "SELECT assets_transfer_checkpoint FROM remote_operations \
727 WHERE remote_name = ?1 AND branch_name = ?2 AND completed_at IS NOT NULL \
728 ORDER BY id DESC LIMIT 1",
729 params![remote_name, branch_name],
730 |row| row.get::<_, DoltHashId>(0),
731 )
732 .optional()?;
733 conn.execute(
734 "INSERT INTO remote_operations \
735 (remote_name, branch_name, operation, from_commit, assets_transfer_checkpoint) \
736 VALUES (?1, ?2, ?3, ?4, ?5)",
737 params![
738 remote_name,
739 branch_name,
740 operation.as_str(),
741 from_commit,
742 assets_transfer_checkpoint
743 ],
744 )?;
745 Self::select(conn)
746 .get_by_id(conn.last_insert_rowid())
747 .map_err(|error| match error {
748 ModelSelectError::DatabaseError(error) => error,
749 ModelSelectError::MultipleResults => rusqlite::Error::QueryReturnedMoreThanOneRow,
750 ModelSelectError::InvalidSelector(_)
751 | ModelSelectError::HistoryNotSupported { .. }
752 | ModelSelectError::ProjectionSourceNotSelected { .. } => {
753 rusqlite::Error::InvalidQuery
754 }
755 })?
756 .ok_or(rusqlite::Error::QueryReturnedNoRows)
757 }
758
759 pub fn set_destination(
761 &mut self,
762 conn: &ConfigConnection,
763 to_commit: &DoltHashId,
764 ) -> SQLResult<()> {
765 conn.execute(
766 "UPDATE remote_operations SET to_commit = ?1 WHERE id = ?2",
767 params![to_commit, self.id],
768 )?;
769 self.to_commit = Some(*to_commit);
770 Ok(())
771 }
772
773 pub fn advance_assets_transfer_checkpoint(
776 &mut self,
777 conn: &ConfigConnection,
778 commit: &DoltHashId,
779 ) -> SQLResult<()> {
780 conn.execute(
781 "UPDATE remote_operations SET assets_transfer_checkpoint = ?1 WHERE id = ?2",
782 params![commit, self.id],
783 )?;
784 self.assets_transfer_checkpoint = Some(*commit);
785 Ok(())
786 }
787
788 pub fn set_push_destination(
790 &mut self,
791 conn: &ConfigConnection,
792 to_commit: &DoltHashId,
793 transfer_id: Uuid,
794 transfer_expires_at: i64,
795 ) -> SQLResult<()> {
796 conn.execute(
797 "UPDATE remote_operations \
798 SET to_commit = ?1, transfer_id = ?2, transfer_expires_at = ?3 WHERE id = ?4",
799 params![to_commit, transfer_id, transfer_expires_at, self.id],
800 )?;
801 self.to_commit = Some(*to_commit);
802 self.transfer_id = Some(transfer_id);
803 self.transfer_expires_at = Some(transfer_expires_at);
804 Ok(())
805 }
806
807 pub fn complete(&self, conn: &ConfigConnection) -> SQLResult<()> {
809 if self.to_commit.is_none() || self.to_commit != self.assets_transfer_checkpoint {
810 self.fail(conn)?;
811 return Err(rusqlite::Error::InvalidQuery);
812 }
813 conn.execute(
814 "UPDATE remote_operations SET completed_at = CURRENT_TIMESTAMP WHERE id = ?1",
815 [self.id],
816 )?;
817 Ok(())
818 }
819
820 pub fn fail(&self, conn: &ConfigConnection) -> SQLResult<()> {
821 conn.execute(
822 "UPDATE remote_operations SET failed_at = CURRENT_TIMESTAMP WHERE id = ?1",
823 [self.id],
824 )?;
825 Ok(())
826 }
827}
828
829#[derive(Clone, Debug, Serialize, Deserialize, ModelSelect)]
830#[model_select(table = "defaults", history = false)]
831pub struct Defaults {
832 pub id: i64,
833 pub collection_name: Option<String>,
834 pub remote_name: Option<String>,
835 pub current_branch_name: Option<String>,
836 pub default_committer_name: String,
837 pub default_committer_email: String,
838}
839
840impl Defaults {
841 pub fn set_default_remote(
843 conn: &ConfigConnection,
844 remote_name: Option<&str>,
845 ) -> Result<(), RemoteError> {
846 if let Some(name) = remote_name {
848 Remote::get_by_name(conn, name)?;
849 }
850
851 let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
852 let mut stmt = conn.prepare(query)?;
853 stmt.execute(params![remote_name])?;
854 Ok(())
855 }
856
857 pub fn set_default_remote_compat(
858 conn: &ConfigConnection,
859 remote_name: Option<&str>,
860 ) -> SQLResult<()> {
861 let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
862 let mut stmt = conn.prepare(query)?;
863 stmt.execute(params![remote_name])?;
864 Ok(())
865 }
866
867 pub fn get_default_remote(conn: &ConfigConnection) -> Option<String> {
869 Defaults::select(conn)
870 .id(1)
871 .only(DefaultsSelect::RemoteName)
872 .load()
873 .ok()?
874 .into_iter()
875 .next()
876 .flatten()
877 }
878
879 pub fn get_default_remote_url(conn: &ConfigConnection) -> Option<String> {
881 if let Some(remote_name) = Self::get_default_remote(conn) {
882 if let Some(remote) = Remote::get_by_name_optional(conn, &remote_name) {
883 Some(remote.url)
884 } else {
885 None
886 }
887 } else {
888 None
889 }
890 }
891
892 pub fn set_current_branch(conn: &ConfigConnection, branch_name: Option<&str>) -> SQLResult<()> {
893 let query = "UPDATE defaults SET current_branch_name = ?1 WHERE id = 1";
894 let mut stmt = conn.prepare(query)?;
895 stmt.execute(params![branch_name])?;
896 Ok(())
897 }
898
899 pub fn get_current_branch(conn: &ConfigConnection) -> Option<String> {
900 Defaults::select(conn)
901 .id(1)
902 .only(DefaultsSelect::CurrentBranchName)
903 .load()
904 .ok()?
905 .into_iter()
906 .next()
907 .flatten()
908 }
909
910 pub fn set_default_committer_name(conn: &ConfigConnection, name: &str) -> SQLResult<()> {
911 let query = "UPDATE defaults SET default_committer_name = ?1 WHERE id = 1";
912 let mut stmt = conn.prepare(query)?;
913 stmt.execute(params![name])?;
914 Ok(())
915 }
916
917 pub fn get_default_committer_name(conn: &ConfigConnection) -> String {
918 Defaults::select(conn)
919 .id(1)
920 .only(DefaultsSelect::DefaultCommitterName)
921 .load()
922 .ok()
923 .and_then(|names| names.into_iter().next())
924 .unwrap_or_else(|| GEN_DEFAULT_COMMITTER_NAME.to_string())
925 }
926
927 pub fn set_default_committer_email(conn: &ConfigConnection, email: &str) -> SQLResult<()> {
928 let query = "UPDATE defaults SET default_committer_email = ?1 WHERE id = 1";
929 let mut stmt = conn.prepare(query)?;
930 stmt.execute(params![email])?;
931 Ok(())
932 }
933
934 pub fn get_default_committer_email(conn: &ConfigConnection) -> String {
935 Defaults::select(conn)
936 .id(1)
937 .only(DefaultsSelect::DefaultCommitterEmail)
938 .load()
939 .ok()
940 .and_then(|emails| emails.into_iter().next())
941 .unwrap_or_else(|| DEFAULT_COMMITTER_EMAIL.to_string())
942 }
943
944 pub fn get(conn: &ConfigConnection) -> Option<Defaults> {
946 Self::select(conn).id(1).load().ok()?.into_iter().next()
947 }
948}
949
950#[cfg(test)]
951mod tests {
952 use std::{
953 fs,
954 io::{Cursor, Write},
955 path::PathBuf,
956 slice::from_ref,
957 };
958
959 use tempfile::NamedTempFile;
960
961 use super::*;
962 use crate::{
963 assets::{AssetRef, AssetRole, OperationAsset, OperationLog},
964 history::{HistoryStore, dolt::DoltHistoryStore},
965 test_helpers::setup_gen,
966 };
967
968 #[cfg(test)]
969 mod defaults {
970 use super::*;
971
972 #[test]
973 fn test_default_remote_functionality() {
974 let context = setup_gen();
975 let config_conn = context.config().conn();
976
977 Remote::create(config_conn, "origin", "https://example.com/repo.gen").unwrap();
979 Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
980
981 assert_eq!(Defaults::get_default_remote(config_conn), None);
983 assert_eq!(Defaults::get_default_remote_url(config_conn), None);
984
985 Defaults::set_default_remote(config_conn, Some("origin")).unwrap();
987 assert_eq!(
988 Defaults::get_default_remote(config_conn),
989 Some("origin".to_string())
990 );
991 assert_eq!(
992 Defaults::get_default_remote_url(config_conn),
993 Some("https://example.com/repo.gen".to_string())
994 );
995
996 Defaults::set_default_remote(config_conn, Some("upstream")).unwrap();
998 assert_eq!(
999 Defaults::get_default_remote(config_conn),
1000 Some("upstream".to_string())
1001 );
1002 assert_eq!(
1003 Defaults::get_default_remote_url(config_conn),
1004 Some("https://upstream.com/repo.gen".to_string())
1005 );
1006
1007 Defaults::set_default_remote(config_conn, None).unwrap();
1009 assert_eq!(Defaults::get_default_remote(config_conn), None);
1010 assert_eq!(Defaults::get_default_remote_url(config_conn), None);
1011
1012 Defaults::set_default_remote_compat(config_conn, Some("nonexistent")).unwrap();
1014 assert_eq!(
1015 Defaults::get_default_remote(config_conn),
1016 Some("nonexistent".to_string())
1017 );
1018 assert_eq!(Defaults::get_default_remote_url(config_conn), None);
1019 }
1020
1021 #[test]
1022 fn test_defaults_get() {
1023 let context = setup_gen();
1024 let config_conn = context.config().conn();
1025
1026 let defaults = Defaults::get(config_conn).unwrap();
1028 assert_eq!(defaults.id, 1);
1029 assert_eq!(defaults.collection_name, None);
1030 assert_eq!(defaults.remote_name, None);
1031 assert_eq!(defaults.current_branch_name, None);
1032 assert_eq!(defaults.default_committer_name, GEN_DEFAULT_COMMITTER_NAME);
1033 assert_eq!(defaults.default_committer_email, DEFAULT_COMMITTER_EMAIL);
1034
1035 Defaults::set_default_remote_compat(config_conn, Some("test-remote")).unwrap();
1037 let defaults = Defaults::get(config_conn).unwrap();
1038 assert_eq!(defaults.remote_name, Some("test-remote".to_string()));
1039 }
1040
1041 #[test]
1042 fn test_current_branch_round_trip() {
1043 let context = setup_gen();
1044 let config_conn = context.config().conn();
1045
1046 assert_eq!(Defaults::get_current_branch(config_conn), None);
1047
1048 Defaults::set_current_branch(config_conn, Some("feature")).unwrap();
1049 assert_eq!(
1050 Defaults::get_current_branch(config_conn),
1051 Some("feature".to_string())
1052 );
1053
1054 Defaults::set_current_branch(config_conn, None).unwrap();
1055 assert_eq!(Defaults::get_current_branch(config_conn), None);
1056 }
1057
1058 #[test]
1059 fn test_default_committer_round_trip() {
1060 let context = setup_gen();
1061 let config_conn = context.config().conn();
1062
1063 assert_eq!(
1064 Defaults::get_default_committer_name(config_conn),
1065 GEN_DEFAULT_COMMITTER_NAME
1066 );
1067 assert_eq!(
1068 Defaults::get_default_committer_email(config_conn),
1069 DEFAULT_COMMITTER_EMAIL
1070 );
1071
1072 Defaults::set_default_committer_name(config_conn, "Test User").unwrap();
1073 Defaults::set_default_committer_email(config_conn, "test@example.com").unwrap();
1074
1075 assert_eq!(
1076 Defaults::get_default_committer_name(config_conn),
1077 "Test User".to_string()
1078 );
1079 assert_eq!(
1080 Defaults::get_default_committer_email(config_conn),
1081 "test@example.com".to_string()
1082 );
1083 let defaults = Defaults::get(config_conn).expect("should load defaults");
1084 assert_eq!(defaults.default_committer_name, "Test User");
1085 assert_eq!(defaults.default_committer_email, "test@example.com");
1086 }
1087 }
1088
1089 #[cfg(test)]
1090 mod remote_operations {
1091 use gen_core::DoltHashId;
1092 use uuid::Uuid;
1093
1094 use crate::{
1095 operations::{Remote, RemoteOperationKind, RemoteOperationRecord},
1096 test_helpers::setup_gen,
1097 };
1098
1099 #[test]
1100 fn test_remote_operation_resumes_until_completed() {
1101 let context = setup_gen();
1102 let config = context.config().conn();
1103 Remote::create(config, "origin", "https://example.com/repo")
1104 .expect("should create remote");
1105 let original_commit = DoltHashId([1_u8; 20]);
1106 let advanced_commit = DoltHashId([2_u8; 20]);
1107
1108 let mut baseline = RemoteOperationRecord::begin_or_resume(
1109 config,
1110 "origin",
1111 "main",
1112 RemoteOperationKind::Clone,
1113 Some(&original_commit),
1114 )
1115 .expect("should begin clone operation");
1116 assert_eq!(baseline.from_commit, Some(original_commit));
1117 assert_eq!(baseline.assets_transfer_checkpoint, None);
1118 baseline
1119 .set_destination(config, &original_commit)
1120 .expect("should record clone destination");
1121 baseline
1122 .advance_assets_transfer_checkpoint(config, &original_commit)
1123 .expect("should record clone asset checkpoint");
1124 baseline
1125 .complete(config)
1126 .expect("should complete clone operation");
1127
1128 let operation = RemoteOperationRecord::begin_or_resume(
1129 config,
1130 "origin",
1131 "main",
1132 RemoteOperationKind::Pull,
1133 Some(&original_commit),
1134 )
1135 .expect("should begin pull operation");
1136 let mut resumed = RemoteOperationRecord::begin_or_resume(
1137 config,
1138 "origin",
1139 "main",
1140 RemoteOperationKind::Pull,
1141 Some(&advanced_commit),
1142 )
1143 .expect("should resume pull operation");
1144
1145 assert_eq!(resumed, operation);
1146 assert_eq!(resumed.from_commit, Some(original_commit));
1147 assert_eq!(resumed.assets_transfer_checkpoint, Some(original_commit));
1148
1149 resumed
1150 .set_destination(config, &advanced_commit)
1151 .expect("should record pull destination");
1152 resumed
1153 .advance_assets_transfer_checkpoint(config, &advanced_commit)
1154 .expect("should record pull asset checkpoint");
1155 resumed
1156 .complete(config)
1157 .expect("should complete pull operation");
1158 let completed = RemoteOperationRecord::select(config)
1159 .get_by_id(resumed.id)
1160 .expect("should query completed pull operation")
1161 .expect("should refetch completed pull operation");
1162 assert!(
1163 completed.completed_at.is_some(),
1164 "completed_at should be set"
1165 );
1166 assert_eq!(completed.failed_at, None, "failed_at should remain unset");
1167
1168 let next = RemoteOperationRecord::begin_or_resume(
1169 config,
1170 "origin",
1171 "main",
1172 RemoteOperationKind::Pull,
1173 Some(&advanced_commit),
1174 )
1175 .expect("should begin the next pull operation");
1176 assert_ne!(next.id, operation.id);
1177 assert_eq!(next.from_commit, Some(advanced_commit));
1178 assert_eq!(next.assets_transfer_checkpoint, Some(advanced_commit));
1179 }
1180
1181 #[test]
1182 fn test_failed_graph_operation_does_not_resume() {
1183 let context = setup_gen();
1184 let config = context.config().conn();
1185 Remote::create(config, "origin", "https://example.com/repo")
1186 .expect("should create remote");
1187 let original_commit = DoltHashId([1_u8; 20]);
1188
1189 let failed = RemoteOperationRecord::begin_or_resume(
1190 config,
1191 "origin",
1192 "main",
1193 RemoteOperationKind::Pull,
1194 Some(&original_commit),
1195 )
1196 .expect("should begin pull operation");
1197 failed.fail(config).expect("should fail pull operation");
1198 let next = RemoteOperationRecord::begin_or_resume(
1199 config,
1200 "origin",
1201 "main",
1202 RemoteOperationKind::Pull,
1203 Some(&original_commit),
1204 )
1205 .expect("should begin replacement pull operation");
1206
1207 assert_ne!(next.id, failed.id);
1208 }
1209
1210 #[test]
1211 fn test_remote_operation_cannot_complete_before_asset_checkpoint() {
1212 let context = setup_gen();
1213 let config = context.config().conn();
1214 Remote::create(config, "origin", "https://example.com/repo")
1215 .expect("should create remote");
1216 let destination_commit = DoltHashId([1_u8; 20]);
1217 let mut operation = RemoteOperationRecord::begin_or_resume(
1218 config,
1219 "origin",
1220 "main",
1221 RemoteOperationKind::Clone,
1222 None,
1223 )
1224 .expect("should begin clone operation");
1225 operation
1226 .set_destination(config, &destination_commit)
1227 .expect("should record graph destination");
1228
1229 operation
1230 .complete(config)
1231 .expect_err("should require assets to reach graph destination");
1232 let failed = RemoteOperationRecord::select(config)
1233 .get_by_id(operation.id)
1234 .expect("should query failed clone operation")
1235 .expect("should refetch failed clone operation");
1236 assert!(failed.failed_at.is_some(), "failed_at should be set");
1237 }
1238
1239 #[test]
1240 fn test_push_operation_resumes_transfer_lease() {
1241 let context = setup_gen();
1242 let config = context.config().conn();
1243 Remote::create(config, "origin", "https://example.com/repo")
1244 .expect("should create remote");
1245 let destination_commit = DoltHashId([3_u8; 20]);
1246 let transfer_id = Uuid::from_u128(7);
1247 let transfer_expires_at = 1_900_000_000;
1248 let mut operation = RemoteOperationRecord::begin_or_resume(
1249 config,
1250 "origin",
1251 "main",
1252 RemoteOperationKind::Push,
1253 None,
1254 )
1255 .expect("should begin push operation");
1256 operation
1257 .set_push_destination(
1258 config,
1259 &destination_commit,
1260 transfer_id,
1261 transfer_expires_at,
1262 )
1263 .expect("should record push destination and lease");
1264
1265 let mut resumed = RemoteOperationRecord::begin_or_resume(
1266 config,
1267 "origin",
1268 "main",
1269 RemoteOperationKind::Push,
1270 None,
1271 )
1272 .expect("should resume push operation");
1273
1274 assert_eq!(resumed.to_commit.as_ref(), Some(&destination_commit));
1275 assert_eq!(resumed.transfer_id, Some(transfer_id));
1276 assert_eq!(resumed.transfer_expires_at, Some(transfer_expires_at));
1277 resumed
1278 .advance_assets_transfer_checkpoint(config, &destination_commit)
1279 .expect("should record completed push assets");
1280 resumed
1281 .complete(config)
1282 .expect("should complete push operation");
1283 }
1284 }
1285
1286 #[cfg(test)]
1287 mod remote {
1288 use super::*;
1289
1290 #[test]
1291 fn test_validate_remote_name() {
1292 assert!(Remote::validate_name("origin").is_ok());
1294 assert!(Remote::validate_name("my-remote").is_ok());
1295 assert!(Remote::validate_name("remote_1").is_ok());
1296 assert!(Remote::validate_name("test123").is_ok());
1297
1298 assert!(Remote::validate_name("").is_err());
1300 assert!(Remote::validate_name("remote with spaces").is_err());
1301 assert!(Remote::validate_name("remote@special").is_err());
1302 assert!(Remote::validate_name("remote.dot").is_err());
1303 }
1304
1305 #[test]
1306 fn test_validate_url() {
1307 assert!(Remote::validate_url("https://genhub.bio/user/repo.gen").is_ok());
1309 assert!(Remote::validate_url("http://example.com/repo").is_ok());
1310 assert!(Remote::validate_url("ssh://git@genhub.bio/user/repo.gen").is_ok());
1311 assert!(Remote::validate_url("/path/to/local/repo").is_ok());
1312 assert!(Remote::validate_url("user@host:path/to/repo").is_ok());
1313
1314 assert!(Remote::validate_url("").is_err());
1316 assert!(Remote::validate_url("not-a-url").is_err());
1317
1318 assert!(Remote::validate_url("ftp://invalid-protocol.com").is_err());
1319 }
1320 }
1321
1322 mod remote_branch {
1323 use super::*;
1324
1325 #[test]
1326 fn test_remote_branch_set_remote_valid() {
1327 let context = setup_gen();
1328 let config_conn = context.config().conn();
1329
1330 Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1331 let result =
1332 RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("origin"));
1333 assert!(result.is_ok());
1334 assert_eq!(
1335 RemoteBranch::get_remote(config_conn, "test_branch"),
1336 Some("origin".to_string())
1337 );
1338 }
1339
1340 #[test]
1341 fn test_remote_branch_set_remote_nonexistent() {
1342 let context = setup_gen();
1343 let config_conn = context.config().conn();
1344
1345 let result =
1346 RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("nonexistent"));
1347 assert_eq!(
1348 result,
1349 Err(RemoteError::RemoteNotFound("nonexistent".to_string()))
1350 );
1351 assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
1352 }
1353
1354 #[test]
1355 fn test_remote_branch_clear_remote() {
1356 let context = setup_gen();
1357 let config_conn = context.config().conn();
1358
1359 Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1360 RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("origin")).unwrap();
1361 assert_eq!(
1362 RemoteBranch::get_remote(config_conn, "test_branch"),
1363 Some("origin".to_string())
1364 );
1365 RemoteBranch::set_remote_validated(config_conn, "test_branch", None).unwrap();
1366 assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
1367 }
1368
1369 #[test]
1370 fn test_remote_branch_clears_on_remote_delete() {
1371 let context = setup_gen();
1372 let config_conn = context.config().conn();
1373
1374 Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1375 RemoteBranch::set_remote_validated(config_conn, "test_branch_cascade", Some("origin"))
1376 .unwrap();
1377 assert_eq!(
1378 RemoteBranch::get_remote(config_conn, "test_branch_cascade"),
1379 Some("origin".to_string())
1380 );
1381
1382 Remote::delete(config_conn, "origin").unwrap();
1383 assert_eq!(
1384 RemoteBranch::get_remote(config_conn, "test_branch_cascade"),
1385 None
1386 );
1387 }
1388 }
1389
1390 #[test]
1391 fn test_remote_create() {
1392 let context = setup_gen();
1393 let config_conn = context.config().conn();
1394
1395 let remote = Remote::create(config_conn, "origin", "https://example.com/repo.gen").unwrap();
1397 assert_eq!(remote.name, "origin");
1398 assert_eq!(remote.url, "https://example.com/repo.gen");
1399
1400 let result = Remote::create(config_conn, "origin", "https://different.com/repo.gen");
1402 assert!(result.is_err());
1403 }
1404
1405 #[test]
1406 fn test_remote_get_by_name() {
1407 let context = setup_gen();
1408 let config_conn = context.config().conn();
1409
1410 let result = Remote::get_by_name_optional(config_conn, "nonexistent");
1412 assert!(result.is_none());
1413
1414 Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
1416 let result = Remote::get_by_name_optional(config_conn, "upstream");
1417 assert!(result.is_some());
1418 let remote = result.unwrap();
1419 assert_eq!(remote.name, "upstream");
1420 assert_eq!(remote.url, "https://upstream.com/repo.gen");
1421 }
1422
1423 #[test]
1424 fn test_remote_list_all() {
1425 let context = setup_gen();
1426 let config_conn = context.config().conn();
1427
1428 let remotes = Remote::list_all(config_conn);
1430 assert!(remotes.is_empty());
1431
1432 Remote::create(config_conn, "origin", "https://origin.com/repo.gen").unwrap();
1434 Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
1435 Remote::create(config_conn, "fork", "https://fork.com/repo.gen").unwrap();
1436
1437 let remotes = Remote::list_all(config_conn);
1439 assert_eq!(remotes.len(), 3);
1440 assert_eq!(remotes[0].name, "fork");
1441 assert_eq!(remotes[1].name, "origin");
1442 assert_eq!(remotes[2].name, "upstream");
1443 }
1444
1445 #[test]
1446 fn test_remote_delete() {
1447 let context = setup_gen();
1448 let config_conn = context.config().conn();
1449
1450 Remote::create(config_conn, "temp", "https://temp.com/repo.gen").unwrap();
1452
1453 let remote = Remote::get_by_name_optional(config_conn, "temp");
1455 assert!(remote.is_some());
1456
1457 let result = Remote::delete(config_conn, "temp");
1459 assert!(result.is_ok());
1460
1461 let remote = Remote::get_by_name_optional(config_conn, "temp");
1463 assert!(remote.is_none());
1464
1465 let result = Remote::delete(config_conn, "nonexistent");
1467 assert!(result.is_err());
1468 }
1469
1470 #[test]
1471 fn test_remote_delete_with_remote_branch_associations() {
1472 let context = setup_gen();
1473 let config_conn = context.config().conn();
1474
1475 Remote::create(config_conn, "test_remote", "https://test.com/repo.gen").unwrap();
1476 RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("test_remote"))
1477 .unwrap();
1478 assert_eq!(
1479 RemoteBranch::get_remote(config_conn, "test_branch"),
1480 Some("test_remote".to_string())
1481 );
1482
1483 let result = Remote::delete(config_conn, "test_remote");
1484 assert!(result.is_ok());
1485 assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
1486 let remote = Remote::get_by_name_optional(config_conn, "test_remote");
1487 assert!(remote.is_none());
1488 }
1489
1490 #[test]
1491 fn test_calculate_stream_hash() {
1492 let content = b"Hello, World!";
1493 let cursor = Cursor::new(content);
1494 let hash = calculate_stream_hash(cursor).unwrap();
1495
1496 assert_eq!(hash.len(), 32);
1497
1498 let cursor2 = Cursor::new(content);
1500 let hash2 = calculate_stream_hash(cursor2).unwrap();
1501 assert_eq!(hash, hash2);
1502
1503 let different_content = b"Hello, World!!";
1505 let cursor3 = Cursor::new(different_content);
1506 let hash3 = calculate_stream_hash(cursor3).unwrap();
1507 assert_ne!(hash, hash3);
1508 }
1509
1510 #[test]
1511 fn test_calculate_file_checksum() {
1512 let mut temp_file = NamedTempFile::new().unwrap();
1513 let content = b"Test file content for checksum calculation";
1514 temp_file.write_all(content).unwrap();
1515 temp_file.flush().unwrap();
1516
1517 let checksum = calculate_file_checksum(temp_file.path()).unwrap();
1518
1519 assert_eq!(checksum.0.len(), 32);
1520
1521 let checksum2 = calculate_file_checksum(temp_file.path()).unwrap();
1523 assert_eq!(checksum, checksum2);
1524
1525 let mut temp_file2 = NamedTempFile::new().unwrap();
1527 let different_content = b"Different test file content";
1528 temp_file2.write_all(different_content).unwrap();
1529 temp_file2.flush().unwrap();
1530
1531 let checksum3 = calculate_file_checksum(temp_file2.path()).unwrap();
1532 assert_ne!(checksum, checksum3);
1533 }
1534
1535 #[test]
1536 fn test_calculate_file_checksum_nonexistent_file() {
1537 let result = calculate_file_checksum("/nonexistent/file/path");
1538 assert!(result.is_err());
1539 assert!(matches!(
1540 result.unwrap_err().kind(),
1541 std::io::ErrorKind::NotFound
1542 ));
1543 }
1544
1545 #[test]
1546 fn test_operation_file_new_infers_file_type_from_path() {
1547 let operation_file = OperationFile::new("fixtures/sample.gb");
1548
1549 assert_eq!(operation_file.filename, "sample.gb");
1550 assert_eq!(operation_file.file_path, "fixtures/sample.gb");
1551 assert_eq!(operation_file.file_type, FileTypes::GenBank);
1552 assert_eq!(operation_file.checksum_override, None);
1553 }
1554
1555 #[test]
1556 fn test_operation_file_storage_path_normalizes_absolute_repo_path() {
1557 let context = setup_gen();
1558 let repo_root = context.workspace().repo_root().unwrap();
1559 let absolute_path = repo_root.join("nested").join("sample.fa");
1560
1561 fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
1562 fs::write(&absolute_path, b"sample").unwrap();
1563
1564 let checksum = calculate_file_checksum(&absolute_path).unwrap();
1565 let storage_path = OperationFile::storage_file_path(
1566 context.workspace(),
1567 &absolute_path.to_string_lossy(),
1568 Some(&checksum),
1569 )
1570 .unwrap();
1571
1572 assert_eq!(storage_path, "nested/sample.fa");
1573 }
1574
1575 #[test]
1576 fn operation_add_file_keeps_compression_suffix_for_asset_path() {
1577 let context = setup_gen();
1578 let fixture_path =
1579 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
1580 let outside_dir = tempfile::tempdir().unwrap();
1581 let outside_path = outside_dir.path().join("simple.fa.bgz");
1582 fs::copy(&fixture_path, &outside_path).unwrap();
1583 let outside_path_string = outside_path.to_string_lossy().to_string();
1584
1585 let file_addition = FileAddition::prepare(
1586 context.workspace(),
1587 &outside_path_string,
1588 FileTypes::Fasta,
1589 None,
1590 )
1591 .unwrap();
1592 let storage_path = OperationFile::storage_file_path(
1593 context.workspace(),
1594 &outside_path_string,
1595 file_addition.checksum.as_ref(),
1596 )
1597 .unwrap();
1598 let checksum = file_addition
1599 .checksum
1600 .expect("local file addition should have a checksum");
1601
1602 assert_eq!(storage_path, format!(".gen/assets/{checksum}.fa.bgz"));
1603 assert_eq!(
1604 file_addition.asset_uri,
1605 LocalAssetUri::asset_uri(".gen/outside_root/simple.fa.bgz"),
1606 );
1607 }
1608
1609 #[test]
1610 fn test_file_addition_prepare() {
1611 let context = setup_gen();
1612 let repo_root = context.workspace().repo_root().unwrap();
1613
1614 let file1_path = repo_root.join("test_file.txt");
1615 fs::write(&file1_path, b"Test file content").unwrap();
1616 let file1_path_str = file1_path.to_string_lossy().to_string();
1617 let fa1 =
1618 FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::Fasta, None)
1619 .expect("should prepare file addition");
1620
1621 let checksum = calculate_file_checksum(&file1_path_str).unwrap();
1622 let expected_asset_path = format!(".gen/assets/{checksum}.txt");
1623 assert_eq!(
1624 fa1.asset_uri,
1625 LocalAssetUri::asset_uri(&expected_asset_path)
1626 );
1627 assert_eq!(fa1.file_path(), expected_asset_path);
1628
1629 let relative1_id = LocalAssetUri::generate_file_addition_id(
1630 Some(&checksum),
1631 &LocalAssetUri::asset_uri(&expected_asset_path),
1632 );
1633
1634 assert_eq!(fa1.id, relative1_id);
1635 assert!(
1636 context
1637 .workspace()
1638 .asset_dir()
1639 .unwrap()
1640 .join(
1641 fa1.hashed_filename()
1642 .expect("local file addition should have a checksum"),
1643 )
1644 .exists()
1645 );
1646
1647 let fa2 =
1649 FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::Fasta, None)
1650 .expect("should prepare same file addition");
1651
1652 assert_eq!(fa1, fa2);
1653
1654 let file2_path = repo_root.join("nested").join("file2.txt");
1655 fs::create_dir_all(file2_path.parent().unwrap()).unwrap();
1656 fs::write(&file2_path, b"Test file content").unwrap();
1657 let file2_path_str = file2_path.to_string_lossy().to_string();
1658
1659 let fa3 =
1660 FileAddition::prepare(context.workspace(), &file2_path_str, FileTypes::Fasta, None)
1661 .expect("should prepare matching file addition");
1662
1663 assert_eq!(fa1.id, fa3.id);
1664
1665 fs::write(&file1_path, b"new content").unwrap();
1666 let fa1_new =
1667 FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::Fasta, None)
1668 .expect("should prepare updated file addition");
1669
1670 assert_ne!(fa1.id, fa1_new.id);
1671
1672 let outside_dir = tempfile::tempdir().unwrap();
1673 let outside_file = outside_dir.path().join("simple.fa");
1674 fs::write(&outside_file, b"Outside repo file").unwrap();
1675 let outside_path = outside_file.to_string_lossy().to_string();
1676
1677 let outside =
1678 FileAddition::prepare(context.workspace(), &outside_path, FileTypes::Fasta, None)
1679 .expect("should prepare external file addition");
1680
1681 assert_eq!(
1682 outside.asset_uri,
1683 LocalAssetUri::asset_uri(".gen/outside_root/simple.fa")
1684 );
1685 assert_eq!(outside.file_path(), ".gen/outside_root/simple.fa");
1686 assert!(
1687 context
1688 .workspace()
1689 .asset_dir()
1690 .unwrap()
1691 .join(
1692 outside
1693 .hashed_filename()
1694 .expect("local file addition should have a checksum"),
1695 )
1696 .exists()
1697 );
1698 }
1699
1700 #[test]
1701 fn test_file_addition_prepare_http_uri() {
1702 let context = setup_gen();
1703 let asset_uri = "https://example.com/assets/reference.fa";
1704
1705 let addition =
1706 FileAddition::prepare(context.workspace(), asset_uri, FileTypes::Fasta, None)
1707 .expect("should prepare HTTP file addition");
1708
1709 assert_eq!(addition.asset_uri, asset_uri);
1710 assert_eq!(addition.file_path(), asset_uri);
1711 assert_eq!(addition.checksum, None);
1712 assert!(
1713 fs::read_dir(context.workspace().asset_dir().unwrap())
1714 .unwrap()
1715 .next()
1716 .is_none()
1717 );
1718 }
1719
1720 #[test]
1721 fn test_file_addition_prepare_remote_uri() {
1722 let context = setup_gen();
1723 let asset_uri = "s3://bucket/reference.fa";
1724 let checksum = Sha256Hash::convert_str("remote S3 contents");
1725
1726 let addition = FileAddition::prepare(
1727 context.workspace(),
1728 asset_uri,
1729 FileTypes::Fasta,
1730 Some(checksum),
1731 )
1732 .expect("should prepare remote file addition");
1733
1734 assert_eq!(addition.asset_uri, asset_uri);
1735 assert_eq!(addition.file_path(), asset_uri);
1736 assert_eq!(addition.checksum, Some(checksum));
1737 }
1738
1739 #[test]
1740 fn test_file_addition_rejects_incorrect_local_checksum_override() {
1741 let context = setup_gen();
1742 let path = context.workspace().repo_root().unwrap().join("asset.fa");
1743 fs::write(&path, "actual contents").expect("should write local asset");
1744
1745 let error = FileAddition::prepare(
1746 context.workspace(),
1747 path.to_str().expect("should encode local asset path"),
1748 FileTypes::Fasta,
1749 Some(Sha256Hash::convert_str("different contents")),
1750 )
1751 .expect_err("should reject incorrect checksum override");
1752
1753 assert!(
1754 matches!(error, FileAdditionError::ChecksumError(_)),
1755 "should report a checksum error: {error}"
1756 );
1757 assert_eq!(
1758 fs::read_dir(context.workspace().asset_dir().unwrap())
1759 .expect("should read asset directory")
1760 .count(),
1761 0
1762 );
1763 }
1764
1765 #[test]
1766 fn test_add_files_operation_does_not_read_remote_asset() {
1767 let context = setup_gen();
1768 let asset_uri = "http://127.0.0.1:1/asset.fa".to_string();
1769 let operation_file = OperationFile::new(&asset_uri);
1770
1771 add_files_operation(
1772 &context,
1773 from_ref(&operation_file),
1774 Some("track remote reference"),
1775 )
1776 .expect("should track remote asset");
1777
1778 let asset_refs =
1779 AssetRef::all(context.graph().conn()).expect("should load asset references");
1780 assert_eq!(asset_refs.len(), 1);
1781 assert_eq!(asset_refs[0].uri, asset_uri);
1782 assert_eq!(asset_refs[0].checksum, None);
1783 }
1784
1785 #[test]
1786 fn test_add_files_operation_passes_remote_checksum_override() {
1787 let context = setup_gen();
1788 let asset_uri = "http://127.0.0.1:1/asset.fa";
1789 let checksum = Sha256Hash::convert_str("known remote contents");
1790 let operation_file = OperationFile::new(asset_uri).set_checksum_override(checksum);
1791
1792 add_files_operation(
1793 &context,
1794 from_ref(&operation_file),
1795 Some("track checksummed remote reference"),
1796 )
1797 .expect("should track remote asset without reading it");
1798
1799 let asset_refs =
1800 AssetRef::all(context.graph().conn()).expect("should load asset references");
1801 assert_eq!(asset_refs.len(), 1);
1802 assert_eq!(asset_refs[0].uri, asset_uri);
1803 assert_eq!(asset_refs[0].checksum, Some(checksum));
1804 }
1805
1806 #[test]
1807 fn test_add_files_operation_stores_shared_unmodified_asset_once_across_operations() {
1808 let context = setup_gen();
1809 let graph_conn = context.graph().conn();
1810 let workspace = context.workspace();
1811
1812 let repo_root = workspace.repo_root().unwrap();
1813 fs::write(repo_root.join("shared.txt"), "shared contents").unwrap();
1814 fs::write(repo_root.join("unique.txt"), "unique contents").unwrap();
1815
1816 let _operation_1_hash =
1817 add_files_operation(&context, &[OperationFile::new("shared.txt")], Some("first"))
1818 .unwrap();
1819 let _operation_2_hash = add_files_operation(
1820 &context,
1821 &[
1822 OperationFile::new("shared.txt"),
1823 OperationFile::new("unique.txt"),
1824 ],
1825 Some("second"),
1826 )
1827 .unwrap();
1828
1829 let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
1830 operation_logs.sort_by_key(|operation_log| operation_log.created_on);
1831 let mut first_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
1832 first_assets.sort_by_key(|asset| asset.asset_ref_id);
1833 let mut second_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[1].id);
1834 second_assets.sort_by_key(|asset| asset.asset_ref_id);
1835
1836 assert_eq!(operation_logs[0].command, "first");
1837 assert_eq!(operation_logs[1].command, "second");
1838 assert_eq!(first_assets.len(), 1);
1839 assert_eq!(second_assets.len(), 2);
1840 assert!(
1841 second_assets
1842 .iter()
1843 .any(|asset| asset.asset_ref_id == first_assets[0].asset_ref_id)
1844 );
1845
1846 let shared_asset = AssetRef::select(graph_conn)
1847 .get_by_id(first_assets[0].asset_ref_id)
1848 .expect("should query shared asset ref")
1849 .expect("should load shared asset ref");
1850 let unique_asset = second_assets
1851 .iter()
1852 .find(|asset| asset.asset_ref_id != first_assets[0].asset_ref_id)
1853 .and_then(|asset| {
1854 AssetRef::select(graph_conn)
1855 .get_by_id(asset.asset_ref_id)
1856 .expect("should query unique asset ref")
1857 })
1858 .expect("should load unique asset ref");
1859
1860 let assets_dir = workspace.asset_dir().unwrap();
1861 let asset_names = fs::read_dir(&assets_dir)
1862 .unwrap()
1863 .map(|entry| entry.unwrap().file_name().into_string().unwrap())
1864 .collect::<Vec<_>>();
1865
1866 assert_eq!(asset_names.len(), 2);
1867 let shared_asset_name = <dyn AssetUri>::from_uri(&shared_asset.uri)
1868 .hashed_filename(&shared_asset.checksum.unwrap());
1869 let unique_asset_name = <dyn AssetUri>::from_uri(&unique_asset.uri)
1870 .hashed_filename(&unique_asset.checksum.unwrap());
1871 assert!(asset_names.contains(&shared_asset_name));
1872 assert!(asset_names.contains(&unique_asset_name));
1873 }
1874
1875 #[test]
1876 fn test_add_files_operation_tracks_distinct_filenames_for_same_asset()
1877 -> Result<(), Box<dyn std::error::Error>> {
1878 let context = setup_gen();
1879 let graph_conn = context.graph().conn();
1880
1881 let outside_dir = tempfile::tempdir()?;
1882 let alpha_path = outside_dir.path().join("alpha.fa");
1883 let beta_path = outside_dir.path().join("beta.fa");
1884 fs::write(&alpha_path, "shared contents")?;
1885 fs::write(&beta_path, "shared contents")?;
1886
1887 add_files_operation(
1888 &context,
1889 &[
1890 OperationFile::new(alpha_path.to_string_lossy()),
1891 OperationFile::new(beta_path.to_string_lossy()),
1892 ],
1893 Some("same asset, different filenames"),
1894 )?;
1895
1896 let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
1897 asset_refs.sort_by(|left, right| left.name.cmp(&right.name));
1898
1899 assert_eq!(
1900 asset_refs
1901 .iter()
1902 .map(|asset| asset.name.clone().unwrap_or_default())
1903 .collect::<Vec<_>>(),
1904 vec!["alpha.fa".to_string(), "beta.fa".to_string()],
1905 );
1906 assert_ne!(asset_refs[0].id, asset_refs[1].id);
1907 assert_eq!(asset_refs[0].checksum, asset_refs[1].checksum);
1908 Ok(())
1909 }
1910
1911 #[test]
1912 fn test_add_files_operation_tracks_graph_asset_refs() {
1913 let context = setup_gen();
1914 let graph_conn = context.graph().conn();
1915
1916 let repo_root = context.workspace().repo_root().unwrap();
1917 fs::write(repo_root.join("alpha.fa"), "AAAA").unwrap();
1918 fs::write(repo_root.join("beta.fa"), "BBBB").unwrap();
1919
1920 let _operation_hash = add_files_operation(
1921 &context,
1922 &[
1923 OperationFile::new("alpha.fa"),
1924 OperationFile::new("beta.fa"),
1925 ],
1926 Some("import references"),
1927 )
1928 .unwrap();
1929
1930 let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
1931 asset_refs.sort_by(|left, right| left.logical_path.cmp(&right.logical_path));
1932 let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
1933 operation_logs.sort_by_key(|operation_log| operation_log.created_on);
1934
1935 assert_eq!(asset_refs.len(), 2);
1936 assert_eq!(asset_refs[0].logical_path.as_deref(), Some("alpha.fa"));
1937 assert_eq!(asset_refs[0].name.as_deref(), Some("alpha.fa"));
1938 assert_eq!(asset_refs[0].role, AssetRole::Input);
1939 assert_eq!(asset_refs[1].logical_path.as_deref(), Some("beta.fa"));
1940 assert_eq!(asset_refs[1].name.as_deref(), Some("beta.fa"));
1941 assert_eq!(asset_refs[1].role, AssetRole::Input);
1942 assert_eq!(operation_logs.len(), 1);
1943 assert_eq!(operation_logs[0].operation_kind, OperationKind::AddFile);
1944 assert_eq!(operation_logs[0].command, "import references");
1945 let mut operation_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
1946 operation_assets.sort_by(|left, right| {
1947 left.role
1948 .as_str()
1949 .cmp(right.role.as_str())
1950 .then_with(|| left.asset_ref_id.cmp(&right.asset_ref_id))
1951 });
1952 assert_eq!(operation_assets.len(), 2);
1953 assert!(
1954 operation_assets
1955 .iter()
1956 .all(|asset| asset.role == AssetRole::Input)
1957 );
1958 }
1959
1960 #[test]
1961 fn test_add_files_operation_records_history_without_config_db_rows() {
1962 let context = setup_gen();
1963 let graph_conn = context.graph().conn();
1964 let config_conn = context.config().conn();
1965
1966 let repo_root = context.workspace().repo_root().unwrap();
1967 fs::write(repo_root.join("alpha.fa"), "AAAA").unwrap();
1968
1969 let operation_hash = add_files_operation(
1970 &context,
1971 &[OperationFile::new("alpha.fa")],
1972 Some("import reference"),
1973 )
1974 .unwrap();
1975
1976 let history_store = DoltHistoryStore::new(graph_conn);
1977 assert_eq!(
1978 history_store.current_head().unwrap(),
1979 Some(operation_hash),
1980 "add-file should commit through Dolt history"
1981 );
1982 let operation_count: i64 = config_conn
1983 .query_row(
1984 "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'operations'",
1985 [],
1986 |row| row.get(0),
1987 )
1988 .unwrap();
1989 assert_eq!(operation_count, 0);
1990 }
1991}