1use core::hash::{Hash, Hasher};
2use std::{io::BufReader, ops::Range, rc::Rc, str, sync};
3
4use cached::proc_macro::cached;
5use flate2::read::MultiGzDecoder;
6use gen_core::{HashId, Sha256Hash, Workspace, traits::Capnp};
7use indexmap::IndexMap;
8use noodles::{
9 bgzf::{self, gzi},
10 core::Region,
11 fasta::{self, fai, io::indexed_reader::Builder as IndexBuilder},
12};
13use rusqlite::{Result as SqlResult, Row, ToSql, params, types::Value};
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16use thiserror::Error;
17
18use crate::{
19 ModelSelect, ModelSelectError,
20 assets::{AssetRef, AssetUri, LocalAssetUri},
21 db::{GraphConnection, max_rows_per_batch},
22 file_types::FileTypes,
23 gen_models_capnp::sequence,
24 select::ModelSelectRow,
25};
26
27#[derive(Clone, Debug, Deserialize, Serialize, ModelSelect)]
28#[model_select(table = "sequences", from_row = sequence_from_row)]
29pub struct Sequence {
30 #[model_select(primary_key)]
31 pub hash: Sha256Hash,
32 pub sequence_type: String,
33 sequence: String,
34 pub name: String,
36 pub asset_ref_id: Option<HashId>,
37 pub length: i64,
38 #[model_select(skip)]
41 pub external_sequence: bool,
42 #[serde(skip)]
43 #[model_select(skip)]
44 asset_ref: Option<AssetRef>,
45 #[serde(skip)]
46 #[model_select(skip)]
47 index_asset_refs: Vec<AssetRef>,
48 #[serde(skip)]
49 #[model_select(skip)]
50 workspace: Option<Workspace>,
51 #[serde(skip)]
52 #[model_select(skip)]
53 asset_resolution_error: Option<String>,
54}
55
56fn sequence_from_row(row: &Row) -> SqlResult<Sequence> {
57 let asset_ref_id: Option<HashId> = row.get(4)?;
58 let hash: Sha256Hash = row.get(0)?;
59 let sequence = row.get(2)?;
60 Ok(Sequence {
61 hash,
62 sequence_type: row.get(1)?,
63 sequence,
64 name: row.get(3)?,
65 asset_ref_id,
66 length: row.get(5)?,
67 external_sequence: asset_ref_id.is_some(),
68 asset_ref: None,
69 index_asset_refs: Vec::new(),
70 workspace: None,
71 asset_resolution_error: None,
72 })
73}
74
75impl PartialEq for Sequence {
76 fn eq(&self, other: &Self) -> bool {
77 self.hash == other.hash
78 && self.sequence_type == other.sequence_type
79 && self.sequence == other.sequence
80 && self.name == other.name
81 && self.asset_ref_id == other.asset_ref_id
82 && self.length == other.length
83 && self.external_sequence == other.external_sequence
84 }
85}
86
87impl Eq for Sequence {}
88
89impl Hash for Sequence {
90 fn hash<H: Hasher>(&self, state: &mut H) {
91 self.hash.hash(state);
92 self.sequence_type.hash(state);
93 self.sequence.hash(state);
94 self.name.hash(state);
95 self.asset_ref_id.hash(state);
96 self.length.hash(state);
97 self.external_sequence.hash(state);
98 }
99}
100
101#[derive(Debug, Error, PartialEq)]
102pub enum SequenceError {
103 #[error("Database error: {0}")]
104 DatabaseError(#[from] rusqlite::Error),
105 #[error("Selector error: {0}")]
106 ModelSelect(#[from] ModelSelectError),
107 #[error("Sequence or asset_ref_id must be set.")]
108 NoSequence(),
109 #[error("An asset reference must have an accompanying sequence name.")]
110 AssetMissingSequenceName(),
111 #[error("Sequence length must be specified.")]
112 MissingSequenceLength(),
113 #[error("Sequence cache lock poisoned: {0}")]
114 CachePoisoned(String),
115 #[error("Invalid indexed sequence region '{name}': {reason}")]
116 InvalidRegion { name: String, reason: String },
117 #[error("Sequence I/O error: {0}")]
118 Io(String),
119 #[error("Invalid UTF-8 while reading sequence data: {0}")]
120 Utf8(String),
121 #[error("Sequence id '{name}' not found in fasta file {file_path}")]
122 IdMissing { file_path: String, name: String },
123 #[error("Sequence bounds out of range: start={start}, end={end}, length={length}")]
124 BoundsError { start: i64, end: i64, length: i64 },
125 #[error("Unable to resolve sequence asset: {0}")]
126 AssetResolution(String),
127}
128
129impl<'a> Capnp<'a> for Sequence {
130 type Builder = sequence::Builder<'a>;
131 type Reader = sequence::Reader<'a>;
132
133 fn write_capnp(&self, builder: &mut Self::Builder) {
134 builder.set_hash(&self.hash.0).unwrap();
135 builder.set_sequence_type(&self.sequence_type);
136 builder.set_sequence(&self.sequence);
137 builder.set_name(&self.name);
138 builder.set_length(self.length);
139 builder.set_external_sequence(self.external_sequence);
140 if let Some(asset_ref_id) = self.asset_ref_id {
141 builder.set_asset_ref_id(&asset_ref_id.0).unwrap();
142 }
143 }
144
145 fn read_capnp(reader: Self::Reader) -> Self {
146 let hash = reader
147 .get_hash()
148 .unwrap()
149 .as_slice()
150 .unwrap()
151 .try_into()
152 .unwrap();
153 let sequence_type = reader.get_sequence_type().unwrap().to_string().unwrap();
154 let sequence = reader.get_sequence().unwrap().to_string().unwrap();
155 let name = reader.get_name().unwrap().to_string().unwrap();
156 let length = reader.get_length();
157 let asset_ref_id = reader.get_asset_ref_id().ok().and_then(|value| {
158 value
159 .as_slice()
160 .and_then(|bytes| bytes.try_into().ok())
161 .map(HashId)
162 });
163 let external_sequence = asset_ref_id.is_some();
164
165 Sequence {
166 hash,
167 sequence_type,
168 sequence,
169 name,
170 asset_ref_id,
171 length,
172 external_sequence,
173 asset_ref: None,
174 index_asset_refs: Vec::new(),
175 workspace: None,
176 asset_resolution_error: None,
177 }
178 }
179}
180
181#[derive(Default, Debug)]
182pub struct NewSequence<'a> {
183 sequence_type: Option<&'a str>,
184 sequence: Option<&'a str>,
185 name: Option<&'a str>,
186 asset_ref_id: Option<&'a HashId>,
187 length: Option<i64>,
188 shallow: bool,
189}
190
191impl<'a> From<&'a Sequence> for NewSequence<'a> {
192 fn from(value: &'a Sequence) -> NewSequence<'a> {
193 NewSequence::new()
194 .sequence_type(&value.sequence_type)
195 .sequence(&value.sequence)
196 .name(&value.name)
197 .asset_ref_id(value.asset_ref_id.as_ref())
198 .length(value.length)
199 }
200}
201
202impl<'a> NewSequence<'a> {
203 pub fn new() -> NewSequence<'static> {
204 NewSequence {
205 shallow: false,
206 ..NewSequence::default()
207 }
208 }
209
210 pub fn shallow(mut self, setting: bool) -> Self {
211 self.shallow = setting;
212 self
213 }
214
215 pub fn sequence_type(mut self, seq_type: &'a str) -> Self {
216 self.sequence_type = Some(seq_type);
217 self
218 }
219
220 pub fn sequence(mut self, sequence: &'a str) -> Self {
221 self.sequence = Some(sequence);
222 self.length = Some(sequence.len() as i64);
223 self
224 }
225
226 pub fn name(mut self, name: &'a str) -> Self {
227 self.name = Some(name);
228 self
229 }
230
231 pub fn asset_ref_id(mut self, asset_ref_id: Option<&'a HashId>) -> Self {
232 if asset_ref_id.is_some() {
233 self.asset_ref_id = asset_ref_id;
234 self.shallow = true;
235 }
236 self
237 }
238
239 pub fn length(mut self, length: i64) -> Self {
240 self.length = Some(length);
241 self
242 }
243
244 pub fn hash(&self) -> Sha256Hash {
245 let mut hasher = Sha256::new();
246 hasher.update(self.sequence_type.expect("Sequence type must be defined."));
247 hasher.update(";");
248 if let Some(v) = self.sequence {
249 hasher.update(v);
250 } else {
251 hasher.update("");
252 }
253 hasher.update(";");
254 if let Some(v) = self.name {
255 hasher.update(v);
256 } else {
257 hasher.update("");
258 }
259 hasher.update(";");
260 if let Some(value) = self.asset_ref_id {
261 hasher.update(value.0);
262 } else {
263 hasher.update("");
264 }
265 hasher.update(";");
266 Sha256Hash(hasher.finalize().into())
267 }
268
269 pub fn build(self) -> Sequence {
270 let external_sequence = self.asset_ref_id.is_some();
271 Sequence {
272 hash: self.hash(),
273 sequence_type: self.sequence_type.unwrap().to_string(),
274 sequence: self.sequence.unwrap_or("").to_string(),
275 name: self.name.unwrap_or("").to_string(),
276 asset_ref_id: self.asset_ref_id.copied(),
277 length: self.length.unwrap(),
278 external_sequence,
279 asset_ref: None,
280 index_asset_refs: Vec::new(),
281 workspace: None,
282 asset_resolution_error: None,
283 }
284 }
285
286 #[cfg_attr(
287 all(debug_assertions, feature = "profiling"),
288 tracing::instrument(skip(self, conn))
289 )]
290 pub fn save(self, conn: &GraphConnection) -> Result<Sequence, SequenceError> {
291 let mut length = 0;
292 if self.sequence.is_none() && self.asset_ref_id.is_none() {
293 return Err(SequenceError::NoSequence());
294 }
295 if self.asset_ref_id.is_some() && self.name.is_none() {
296 return Err(SequenceError::AssetMissingSequenceName());
297 }
298 if self.length.is_none() {
299 if let Some(v) = self.sequence {
300 length = v.len() as i64;
301 } else {
302 return Err(SequenceError::MissingSequenceLength());
304 }
305 }
306 let hash = self.hash();
307 let existing = Sequence::select(conn)
308 .hash(hash)
309 .only(SequenceSelect::Hash)
310 .load()?;
311 if existing.is_empty() {
312 let mut stmt = conn.prepare("INSERT INTO sequences (hash, sequence_type, sequence, name, asset_ref_id, length) VALUES (?1, ?2, ?3, ?4, ?5, ?6);")?;
313 match stmt.execute(params![
314 hash,
315 self.sequence_type.unwrap().to_string(),
316 if self.shallow {
317 ""
318 } else {
319 self.sequence.unwrap()
320 },
321 self.name.unwrap_or(""),
322 self.asset_ref_id,
323 self.length.unwrap_or(length)
324 ]) {
325 Ok(_) => {}
326 Err(err) => return Err(SequenceError::DatabaseError(err)),
327 }
328 }
329
330 Ok(Sequence {
331 hash,
332 sequence_type: self.sequence_type.unwrap().to_string(),
333 sequence: self.sequence.unwrap_or("").to_string(),
334 name: self.name.unwrap_or("").to_string(),
335 asset_ref_id: self.asset_ref_id.copied(),
336 length: self.length.unwrap_or(length),
337 external_sequence: self.asset_ref_id.is_some(),
338 asset_ref: None,
339 index_asset_refs: Vec::new(),
340 workspace: None,
341 asset_resolution_error: None,
342 })
343 }
344}
345
346#[cached(
347 key = "String",
348 convert = r#"{ format!("{}:{}", workspace.base_dir().display(), asset_ref.id) }"#
349)]
350fn fasta_index(workspace: &Workspace, asset_ref: &AssetRef) -> Option<fai::Index> {
351 let reader = asset_ref.reader(workspace).ok()?;
352 fai::io::Reader::new(reader).read_index().ok()
353}
354
355#[cached(
356 key = "String",
357 convert = r#"{ format!("{}:{}", workspace.base_dir().display(), asset_ref.id) }"#
358)]
359fn fasta_gzi_index(workspace: &Workspace, asset_ref: &AssetRef) -> Option<gzi::Index> {
360 let reader = asset_ref.reader(workspace).ok()?;
361 gzi::io::Reader::new(reader).read_index().ok()
362}
363
364fn asset_extension(asset_ref: &AssetRef) -> Option<String> {
365 <dyn AssetUri>::from_uri(&asset_ref.uri)
366 .suffix()
367 .and_then(|suffix| suffix.rsplit('.').next().map(str::to_ascii_lowercase))
368}
369
370fn validate_sequence_bounds(
371 start: i64,
372 end: i64,
373 length: i64,
374) -> Result<(usize, usize), SequenceError> {
375 if start < 0 || end < 0 || start > length || end > length {
376 return Err(SequenceError::BoundsError { start, end, length });
377 }
378
379 Ok((start as usize, end as usize))
380}
381
382fn circular_sequence_slice(sequence: &str, start: i64, end: i64) -> Result<String, SequenceError> {
383 let length = sequence.len() as i64;
384 if length == 0 {
385 if start == 0 && end == 0 {
386 return Ok(String::new());
387 }
388 return Err(SequenceError::BoundsError { start, end, length });
389 }
390
391 let (start, end) = validate_sequence_bounds(start, end, length)?;
392 if start <= end {
393 return Ok(sequence[start..end].to_string());
394 }
395
396 let mut result = String::with_capacity((length as usize - start) + end);
397 result.push_str(&sequence[start..]);
398 result.push_str(&sequence[..end]);
399
400 Ok(result)
401}
402
403fn sequence_slice(
404 sequence: &str,
405 start: i64,
406 end: i64,
407 circular: bool,
408) -> Result<String, SequenceError> {
409 if circular {
410 return circular_sequence_slice(sequence, start, end);
411 }
412
413 let length = sequence.len() as i64;
414 let (start, end) = validate_sequence_bounds(start, end, length)?;
415 if start <= end {
416 return Ok(sequence[start..end].to_string());
417 }
418
419 Err(SequenceError::BoundsError {
420 start: start as i64,
421 end: end as i64,
422 length,
423 })
424}
425
426type SequenceCache = sync::RwLock<Option<((HashId, String), Option<String>)>>;
427
428pub fn cached_sequence(
429 workspace: &Workspace,
430 sequence_asset: &AssetRef,
431 index_assets: &[AssetRef],
432 name: &str,
433 range: Range<i64>,
434 circular: bool,
435) -> Result<String, SequenceError> {
436 static SEQUENCE_CACHE: sync::LazyLock<SequenceCache> =
437 sync::LazyLock::new(|| sync::RwLock::new(None));
438 let cache_key = (sequence_asset.id, name.to_string());
439
440 {
441 let cache = SEQUENCE_CACHE
442 .read()
443 .map_err(|err| SequenceError::CachePoisoned(err.to_string()))?;
444 if let Some((cached_key, cached_sequence)) = cache.as_ref()
445 && cached_key == &cache_key
446 {
447 if let Some(sequence) = cached_sequence {
448 return sequence_slice(sequence, range.start, range.end, circular);
449 }
450 return Err(SequenceError::IdMissing {
451 file_path: sequence_asset.uri.clone(),
452 name: name.to_string(),
453 });
454 }
455 }
456
457 let mut cache = SEQUENCE_CACHE
458 .write()
459 .map_err(|err| SequenceError::CachePoisoned(err.to_string()))?;
460
461 let mut sequence: Option<String> = None;
462 let fasta_index_asset = index_assets
463 .iter()
464 .find(|asset_ref| asset_ref.file_type == FileTypes::FastaIndex.as_str())
465 .or_else(|| {
466 index_assets.iter().find(|asset_ref| {
467 asset_ref.file_type == FileTypes::None.as_str()
468 && asset_extension(asset_ref).as_deref() == Some("fai")
469 })
470 });
471 let gzip_index_asset = index_assets
472 .iter()
473 .find(|asset_ref| asset_ref.file_type == FileTypes::BgzfIndex.as_str())
474 .or_else(|| {
475 index_assets.iter().find(|asset_ref| {
476 asset_ref.file_type == FileTypes::None.as_str()
477 && asset_extension(asset_ref).as_deref() == Some("gzi")
478 })
479 });
480 let sequence_extension = asset_extension(sequence_asset);
481 let compressed = matches!(sequence_extension.as_deref(), Some("gz" | "bgz"));
482 if let Some(index) = fasta_index_asset.and_then(|asset_ref| fasta_index(workspace, asset_ref)) {
483 let region = name
484 .parse::<Region>()
485 .map_err(|err| SequenceError::InvalidRegion {
486 name: name.to_string(),
487 reason: err.to_string(),
488 })?;
489 let builder = IndexBuilder::default().set_index(index);
490 if let Some(gzi_index) =
491 gzip_index_asset.and_then(|asset_ref| fasta_gzi_index(workspace, asset_ref))
492 {
493 let sequence_reader = sequence_asset
494 .reader(workspace)
495 .map_err(|err| SequenceError::Io(err.to_string()))?;
496 let bgzf_reader = bgzf::io::indexed_reader::Builder::default()
497 .set_index(gzi_index)
498 .build_from_reader(sequence_reader)
499 .map_err(|err| SequenceError::Io(err.to_string()))?;
500 let mut reader = builder
501 .build_from_reader(bgzf_reader)
502 .map_err(|err| SequenceError::Io(err.to_string()))?;
503 sequence = Some(
504 str::from_utf8(
505 reader
506 .query(®ion)
507 .map_err(|err| SequenceError::Io(err.to_string()))?
508 .sequence()
509 .as_ref(),
510 )
511 .map_err(|err| SequenceError::Utf8(err.to_string()))?
512 .to_string(),
513 )
514 } else if !compressed {
515 let sequence_reader = sequence_asset
516 .reader(workspace)
517 .map_err(|err| SequenceError::Io(err.to_string()))?;
518 let mut reader = builder
519 .build_from_reader(sequence_reader)
520 .map_err(|err| SequenceError::Io(err.to_string()))?;
521 sequence = Some(
522 str::from_utf8(
523 reader
524 .query(®ion)
525 .map_err(|err| SequenceError::Io(err.to_string()))?
526 .sequence()
527 .as_ref(),
528 )
529 .map_err(|err| SequenceError::Utf8(err.to_string()))?
530 .to_string(),
531 );
532 }
533 }
534 if sequence.is_none() {
535 let sequence_reader = sequence_asset
536 .reader(workspace)
537 .map_err(|err| SequenceError::Io(err.to_string()))?;
538 let reader_stream: Box<dyn std::io::BufRead> = match sequence_extension.as_deref() {
539 Some("gz") => Box::new(BufReader::new(MultiGzDecoder::new(sequence_reader))),
540 Some("bgz") => Box::new(bgzf::io::Reader::new(sequence_reader)),
541 _ => Box::new(sequence_reader),
542 };
543 let mut reader = fasta::io::reader::Builder
544 .build_from_reader(reader_stream)
545 .map_err(|err| SequenceError::Io(err.to_string()))?;
546 for result in reader.records() {
547 let record = result.map_err(|err| SequenceError::Io(err.to_string()))?;
548 if String::from_utf8(record.name().to_vec())
549 .map_err(|err| SequenceError::Utf8(err.to_string()))?
550 == name
551 {
552 sequence = Some(
553 str::from_utf8(record.sequence().as_ref())
554 .map_err(|err| SequenceError::Utf8(err.to_string()))?
555 .to_string(),
556 );
557 break;
558 }
559 }
560 }
561 *cache = Some((cache_key, sequence));
564 if let Some((_, Some(seq))) = cache.as_ref() {
566 return sequence_slice(seq, range.start, range.end, circular);
567 }
568 Err(SequenceError::IdMissing {
569 file_path: sequence_asset.uri.clone(),
570 name: name.to_string(),
571 })
572}
573
574impl Sequence {
575 #[cfg_attr(feature = "profiling", tracing::instrument(skip(conn, sequences)))]
577 pub fn bulk_save(conn: &GraphConnection, sequences: &[Sequence]) -> Result<(), SequenceError> {
578 let batch_size = max_rows_per_batch(conn, 6);
579
580 for chunk in sequences.chunks(batch_size) {
581 let mut sql = String::from(
582 "INSERT OR IGNORE INTO sequences
583 (hash, sequence_type, sequence, name, asset_ref_id, length) VALUES ",
584 );
585 for row_index in 0..chunk.len() {
586 if row_index > 0 {
587 sql.push(',');
588 }
589 sql.push_str("(?, ?, ?, ?, ?, ?)");
590 }
591 sql.push(';');
592
593 let mut values = Vec::with_capacity(chunk.len() * 6);
594 for sequence in chunk {
595 values.push(Value::from(sequence.hash));
596 values.push(Value::from(sequence.sequence_type.clone()));
597 values.push(Value::from(sequence.sequence.clone()));
598 values.push(Value::from(sequence.name.clone()));
599 values.push(Value::from(sequence.asset_ref_id));
600 values.push(Value::from(sequence.length));
601 }
602 let mut statement = conn.prepare_cached(&sql)?;
603 statement.execute(rusqlite::params_from_iter(values))?;
604 }
605
606 Ok(())
607 }
608
609 #[allow(clippy::new_ret_no_self)]
610 pub fn new() -> NewSequence<'static> {
611 NewSequence::new()
612 }
613
614 fn is_circular(&self) -> bool {
615 self.sequence_type
616 .split_whitespace()
617 .any(|part| part.eq_ignore_ascii_case("circular"))
618 }
619
620 pub fn query_by_ids<T>(
621 conn: &GraphConnection,
622 workspace: &Workspace,
623 ids: &[T],
624 history_ref: Option<&str>,
625 ) -> Vec<Self>
626 where
627 T: Clone,
628 rusqlite::types::Value: From<T>,
629 {
630 let sequence_table = Self::table_name_with_history_ref(history_ref);
631 let asset_table = AssetRef::table_name_with_history_ref(history_ref);
632 let query = format!(
633 "WITH arr AS (
634 SELECT value, rowid AS pos FROM rarray(:ids)
635 )
636 SELECT sequences.*, asset_refs.*, index_assets.*
637 FROM {sequence_table} AS sequences
638 LEFT JOIN {asset_table} AS asset_refs
639 ON sequences.asset_ref_id = asset_refs.id
640 LEFT JOIN {asset_table} AS index_assets
641 ON asset_refs.id = index_assets.upstream_asset_ref_id
642 AND index_assets.role = 'sequence-index'
643 JOIN arr ON sequences.hash = arr.value
644 ORDER BY arr.pos;"
645 );
646 let values: Vec<Value> = ids.iter().map(|id| Value::from(id.clone())).collect();
647 let id_values = Rc::new(values);
648 let mut query_params: Vec<(&str, &dyn ToSql)> = vec![(":ids", &id_values)];
649 if let Some(history_ref) = history_ref.as_ref() {
650 query_params.push((":history_ref", history_ref));
651 }
652 let mut statement = conn.prepare(&query).unwrap();
653 let mut sequences: IndexMap<Sha256Hash, Self> = IndexMap::new();
654 for row in statement
655 .query_map(&query_params[..], |row| {
656 Self::process_joined_row(row, workspace)
657 })
658 .unwrap()
659 {
660 let sequence = row.unwrap();
661 let sequence_hash = sequence.hash;
662 if let Some(existing) = sequences.get_mut(&sequence_hash) {
663 existing.index_asset_refs.extend(sequence.index_asset_refs);
664 } else {
665 sequences.insert(sequence_hash, sequence);
666 }
667 }
668 sequences.into_values().collect()
669 }
670
671 fn process_joined_row(row: &Row, workspace: &Workspace) -> SqlResult<Self> {
672 let mut sequence = <Self as ModelSelectRow>::process_row(row)?;
673 if let Some(asset_ref_id) = sequence.asset_ref_id {
674 let Some(joined_asset_ref_id): Option<HashId> = row.get(6)? else {
675 sequence.asset_resolution_error =
676 Some(format!("asset reference {asset_ref_id} does not exist"));
677 return Ok(sequence);
678 };
679 let asset_ref = AssetRef {
680 id: joined_asset_ref_id,
681 uri: row.get(7)?,
682 file_type: row.get(8)?,
683 checksum: row.get(9)?,
684 size: row.get(10)?,
685 role: row.get(11)?,
686 logical_path: row.get(12)?,
687 name: row.get(13)?,
688 created_on: row.get(14)?,
689 upstream_asset_ref_id: row.get(15)?,
690 materialized_checksum: row.get(16)?,
691 };
692 if LocalAssetUri::is_local_path_or_file_uri(&asset_ref.uri)
693 && let Err(error) = asset_ref.versioned_store_path(workspace)
694 {
695 sequence.asset_resolution_error = Some(error.to_string());
696 return Ok(sequence);
697 }
698 sequence.asset_ref = Some(asset_ref);
699 sequence.workspace = Some(workspace.clone());
700
701 let index_asset_ref_id: Option<HashId> = row.get(17)?;
702 if let Some(index_asset_ref_id) = index_asset_ref_id {
703 let index_asset = AssetRef {
704 id: index_asset_ref_id,
705 uri: row.get(18)?,
706 file_type: row.get(19)?,
707 checksum: row.get(20)?,
708 size: row.get(21)?,
709 role: row.get(22)?,
710 logical_path: row.get(23)?,
711 name: row.get(24)?,
712 created_on: row.get(25)?,
713 upstream_asset_ref_id: row.get(26)?,
714 materialized_checksum: row.get(27)?,
715 };
716 if !LocalAssetUri::is_local_path_or_file_uri(&index_asset.uri)
717 || index_asset.versioned_store_path(workspace).is_ok()
718 {
719 sequence.index_asset_refs.push(index_asset);
720 }
721 }
722 }
723 Ok(sequence)
724 }
725
726 pub fn get_sequence(
727 &self,
728 start: impl Into<Option<i64>>,
729 end: impl Into<Option<i64>>,
730 ) -> Result<String, SequenceError> {
731 let start: Option<i64> = start.into();
734 let end: Option<i64> = end.into();
735 let start = start.unwrap_or(0);
736 let end = end.unwrap_or(self.length);
737 if self.external_sequence {
738 if let Some(error) = self.asset_resolution_error.as_ref() {
739 return Err(SequenceError::AssetResolution(error.clone()));
740 }
741 let asset_ref = self.asset_ref.as_ref().ok_or_else(|| {
742 SequenceError::AssetResolution(
743 "sequence asset was loaded without repository context".to_string(),
744 )
745 })?;
746 let workspace = self.workspace.as_ref().ok_or_else(|| {
747 SequenceError::AssetResolution(
748 "sequence asset was loaded without repository context".to_string(),
749 )
750 })?;
751 return cached_sequence(
752 workspace,
753 asset_ref,
754 &self.index_asset_refs,
755 &self.name,
756 start..end,
757 self.is_circular(),
758 );
759 }
760 if start == 0 && end == self.length {
761 return Ok(self.sequence.clone());
762 }
763 sequence_slice(&self.sequence, start, end, self.is_circular())
764 }
765
766 pub fn delete_by_hash(conn: &GraphConnection, hash: &Sha256Hash) {
767 let mut stmt = conn
768 .prepare("delete from sequences where hash = ?1;")
769 .unwrap();
770 stmt.execute(params![hash]).unwrap();
771 }
772
773 pub fn query_by_blockgroup(
774 conn: &GraphConnection,
775 workspace: &Workspace,
776 block_group_id: &HashId,
777 ) -> Vec<Sequence> {
778 let asset_table = AssetRef::table_name_with_history_ref(None);
779 let query = format!(
780 "SELECT sequences.*, asset_refs.*, index_assets.*
781 FROM block_group_edges bge
782 LEFT JOIN edges ON bge.edge_id = edges.id
783 LEFT JOIN nodes ON (edges.source_node_id = nodes.id OR edges.target_node_id = nodes.id)
784 LEFT JOIN sequences ON (nodes.sequence_hash = sequences.hash)
785 LEFT JOIN {asset_table} AS asset_refs ON sequences.asset_ref_id = asset_refs.id
786 LEFT JOIN {asset_table} AS index_assets
787 ON asset_refs.id = index_assets.upstream_asset_ref_id
788 AND index_assets.role = 'sequence-index'
789 WHERE bge.block_group_id = ?1;"
790 );
791 let mut statement = conn.prepare(&query).unwrap();
792 let mut sequences: IndexMap<Sha256Hash, Self> = IndexMap::new();
793 for row in statement
794 .query_map(params![block_group_id], |row| {
795 Self::process_joined_row(row, workspace)
796 })
797 .unwrap()
798 {
799 let sequence = row.unwrap();
800 let sequence_hash = sequence.hash;
801 if let Some(existing) = sequences.get_mut(&sequence_hash) {
802 existing.index_asset_refs.extend(sequence.index_asset_refs);
803 } else {
804 sequences.insert(sequence_hash, sequence);
805 }
806 }
807 sequences.into_values().collect()
808 }
809}
810
811pub fn reverse_complement(seq: &[u8]) -> Vec<u8> {
812 seq.iter()
813 .rev()
814 .map(|&base| match base.to_ascii_uppercase() {
815 b'A' => b'T',
816 b'T' => b'A',
817 b'C' => b'G',
818 b'G' => b'C',
819 b'U' => b'A',
820 b'N' => b'N',
821 b'R' => b'Y',
822 b'Y' => b'R',
823 b'S' => b'S',
824 b'W' => b'W',
825 b'K' => b'M',
826 b'M' => b'K',
827 b'B' => b'V',
828 b'V' => b'B',
829 b'D' => b'H',
830 b'H' => b'D',
831 _ => base,
832 })
833 .collect()
834}
835
836#[cfg(test)]
837mod tests {
838 use std::{fs, fs::OpenOptions, io::Write, time};
839
840 use gen_core::traits::Capnp as _;
841 use rand::RngExt;
842 use sha2::Digest as _;
843
844 use super::{Sequence, SequenceError};
845 use crate::{
846 assets::{AssetRef, AssetRole},
847 file_types::FileTypes,
848 gen_models_capnp::sequence,
849 operations::{FileAddition, OperationFile},
850 test_helpers::{get_connection, setup_gen_on_disk},
851 };
852
853 fn prepare_asset(context: &crate::db::DbContext, path: &str, role: AssetRole) -> AssetRef {
854 let operation_file = OperationFile::new(path).set_role(role);
855 let asset_ref = operation_file
856 .prepare_asset_ref(context.workspace(), 1)
857 .expect("should retain test asset");
858 AssetRef::create(context.graph().conn(), &asset_ref)
859 .expect("should create test asset reference");
860 asset_ref
861 }
862
863 fn prepare_derived_asset(
864 context: &crate::db::DbContext,
865 path: &str,
866 role: AssetRole,
867 upstream_asset_ref_id: &gen_core::HashId,
868 ) -> AssetRef {
869 let operation_file = OperationFile::new(path)
870 .set_role(role)
871 .set_upstream_asset_ref_id(upstream_asset_ref_id);
872 let asset_ref = operation_file
873 .prepare_asset_ref(context.workspace(), 1)
874 .expect("should retain derived test asset");
875 AssetRef::create(context.graph().conn(), &asset_ref)
876 .expect("should create derived test asset reference");
877 asset_ref
878 }
879
880 #[test]
881 fn test_builder() {
882 let sequence = Sequence::new()
883 .sequence_type("DNA")
884 .sequence("ATCG")
885 .build();
886 assert_eq!(sequence.length, 4);
887 assert_eq!(sequence.sequence, "ATCG");
888 assert_eq!(
889 sequence.hash.to_string(),
890 "4ab41cf208e5a797ed0052a3fc5f87bed18f94fc1fc7fdd6ed3199b4e1c34ace"
891 );
892 }
893
894 #[test]
895 fn test_builder_with_asset_ref() {
896 let asset_ref_id = gen_core::HashId::convert_str("asset");
897 let sequence = Sequence::new()
898 .sequence_type("DNA")
899 .name("chr1")
900 .asset_ref_id(Some(&asset_ref_id))
901 .length(50)
902 .build();
903 assert_eq!(sequence.length, 50);
904 assert_eq!(sequence.sequence, "");
905 }
906
907 #[test]
908 fn test_create_sequence_in_db() {
909 let conn = &get_connection(None).unwrap();
910 let sequence = Sequence::new()
911 .sequence_type("DNA")
912 .sequence("AACCTT")
913 .save(conn)
914 .unwrap();
915 assert_eq!(&sequence.sequence, "AACCTT");
916 assert_eq!(sequence.sequence_type, "DNA");
917 assert!(!sequence.external_sequence);
918 }
919
920 #[test]
921 fn test_delete_sequence_by_hash() {
922 let conn = &get_connection(None).unwrap();
923 let before_count = Sequence::all(conn).expect("should load sequences").len();
924 let sequence = Sequence::new()
925 .sequence_type("DNA")
926 .sequence("AACCTT")
927 .save(conn)
928 .unwrap();
929 let sequence2 = Sequence::new()
930 .sequence_type("DNA")
931 .sequence("AACCTTAA")
932 .save(conn)
933 .unwrap();
934
935 let sequences = Sequence::all(conn).expect("should load sequences");
936 assert_eq!(sequences.len(), before_count + 2);
937
938 Sequence::delete_by_hash(conn, &sequence.hash);
939
940 let sequences = Sequence::all(conn).expect("should load sequences");
941 assert_eq!(sequences.len(), before_count + 1);
942 assert!(sequences.iter().any(|s| s.hash == sequence2.hash));
943 }
944
945 #[test]
946 fn test_create_sequence_on_disk() {
947 let context = setup_gen_on_disk();
948 let fasta_path = context
949 .workspace()
950 .repo_root()
951 .unwrap()
952 .join("reference.fa");
953 fs::write(&fasta_path, ">chr1\nAACCGGTTAA\n").unwrap();
954 let asset_ref = prepare_asset(&context, fasta_path.to_str().unwrap(), AssetRole::Input);
955 let sequence = Sequence::new()
956 .sequence_type("DNA")
957 .name("chr1")
958 .asset_ref_id(Some(&asset_ref.id))
959 .length(10)
960 .save(context.graph().conn())
961 .unwrap();
962 assert_eq!(sequence.sequence_type, "DNA");
963 assert_eq!(&sequence.sequence, "");
964 assert_eq!(sequence.name, "chr1");
965 assert_eq!(sequence.asset_ref_id, Some(asset_ref.id));
966 assert_eq!(sequence.length, 10);
967 assert!(sequence.external_sequence);
968 }
969
970 #[test]
971 fn test_get_sequence() {
972 let conn = &get_connection(None).unwrap();
973 let sequence = Sequence::new()
974 .sequence_type("DNA")
975 .sequence("ATCGATCGATCGATCGATCGGGAACACACAGAGA")
976 .save(conn)
977 .unwrap();
978 assert_eq!(
979 sequence.get_sequence(None, None).unwrap(),
980 "ATCGATCGATCGATCGATCGGGAACACACAGAGA"
981 );
982 assert_eq!(sequence.get_sequence(0, 5).unwrap(), "ATCGA");
983 assert_eq!(sequence.get_sequence(10, 15).unwrap(), "CGATC");
984 assert_eq!(
985 sequence.get_sequence(3, None).unwrap(),
986 "GATCGATCGATCGATCGGGAACACACAGAGA"
987 );
988 assert_eq!(sequence.get_sequence(None, 5).unwrap(), "ATCGA");
989 assert_eq!(
990 sequence.get_sequence(0, 100),
991 Err(SequenceError::BoundsError {
992 start: 0,
993 end: 100,
994 length: 34,
995 })
996 );
997 assert_eq!(
998 sequence.get_sequence(5, 2),
999 Err(SequenceError::BoundsError {
1000 start: 5,
1001 end: 2,
1002 length: 34,
1003 })
1004 );
1005 }
1006
1007 #[test]
1008 fn test_get_sequence_circular() {
1009 let conn = &get_connection(None).unwrap();
1010 let sequence = Sequence::new()
1011 .sequence_type("circular")
1012 .sequence("AAACCCTTT")
1013 .save(conn)
1014 .unwrap();
1015 assert_eq!(sequence.get_sequence(4, 2).unwrap(), "CCTTTAA");
1016 assert_eq!(
1017 sequence.get_sequence(0, 10),
1018 Err(SequenceError::BoundsError {
1019 start: 0,
1020 end: 10,
1021 length: 9,
1022 })
1023 );
1024 }
1025
1026 #[test]
1027 fn test_get_sequence_from_disk() {
1028 let context = setup_gen_on_disk();
1029 let temp_file_path = context.workspace().repo_root().unwrap().join("simple.fa");
1030 fs::write(
1031 &temp_file_path,
1032 ">m123\nATCGATCGATCGATCGATCGGGAACACACAGAGA\n",
1033 )
1034 .unwrap();
1035 let asset_ref = prepare_asset(&context, temp_file_path.to_str().unwrap(), AssetRole::Input);
1036 let sequence = Sequence::new()
1037 .sequence_type("DNA")
1038 .name("m123")
1039 .asset_ref_id(Some(&asset_ref.id))
1040 .length(34)
1041 .save(context.graph().conn())
1042 .unwrap();
1043 let seq = Sequence::query_by_ids(
1044 context.graph().conn(),
1045 context.workspace(),
1046 &[sequence.hash],
1047 None,
1048 )
1049 .remove(0);
1050 fs::write(
1053 &temp_file_path,
1054 ">m123\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n",
1055 )
1056 .unwrap();
1057 assert_eq!(
1058 seq.get_sequence(None, None).unwrap(),
1059 "ATCGATCGATCGATCGATCGGGAACACACAGAGA"
1060 );
1061 assert_eq!(seq.get_sequence(0, 5).unwrap(), "ATCGA");
1062 assert_eq!(seq.get_sequence(10, 15).unwrap(), "CGATC");
1063 assert_eq!(
1064 seq.get_sequence(3, None).unwrap(),
1065 "GATCGATCGATCGATCGGGAACACACAGAGA"
1066 );
1067 assert_eq!(seq.get_sequence(None, 5).unwrap(), "ATCGA");
1068 }
1069
1070 #[cfg(unix)]
1071 #[test]
1072 fn test_on_disk_sequence_rejects_asset_outside_repository() {
1073 use std::os::unix::fs::symlink;
1074
1075 let context = setup_gen_on_disk();
1076 let outside_directory = tempfile::tempdir().unwrap();
1077 let outside_path = outside_directory.path().join("secret.fa");
1078 let contents = b">secret\nPRIVATE\n";
1079 fs::write(&outside_path, contents).unwrap();
1080 let checksum = gen_core::Sha256Hash(sha2::Sha256::digest(contents).into());
1081 let uri = format!("file://{}", outside_path.display());
1082 let file_addition = FileAddition {
1083 id: gen_core::HashId::convert_str("outside-secret"),
1084 asset_uri: uri.clone(),
1085 file_type: FileTypes::Fasta,
1086 checksum: Some(checksum),
1087 materialized_checksum: None,
1088 };
1089 let asset_ref = AssetRef {
1090 id: AssetRef::id_hash(
1091 &file_addition,
1092 &AssetRole::Input,
1093 outside_path.to_str(),
1094 Some("secret.fa"),
1095 None,
1096 ),
1097 uri,
1098 file_type: "fasta".to_string(),
1099 checksum: Some(checksum),
1100 size: None,
1101 role: AssetRole::Input,
1102 logical_path: Some(outside_path.to_string_lossy().to_string()),
1103 name: Some("secret.fa".to_string()),
1104 created_on: 1,
1105 upstream_asset_ref_id: None,
1106 materialized_checksum: None,
1107 };
1108 AssetRef::create(context.graph().conn(), &asset_ref).unwrap();
1109 let asset_filename =
1110 <dyn crate::assets::AssetUri>::from_uri(&asset_ref.uri).hashed_filename(&checksum);
1111 symlink(
1112 &outside_path,
1113 context
1114 .workspace()
1115 .asset_dir()
1116 .unwrap()
1117 .join(asset_filename),
1118 )
1119 .unwrap();
1120 let unresolved_sequence = Sequence::new()
1121 .sequence_type("DNA")
1122 .name("secret")
1123 .asset_ref_id(Some(&asset_ref.id))
1124 .length(7)
1125 .save(context.graph().conn())
1126 .unwrap();
1127 let sequence = Sequence::query_by_ids(
1128 context.graph().conn(),
1129 context.workspace(),
1130 &[unresolved_sequence.hash],
1131 None,
1132 )
1133 .remove(0);
1134
1135 let error = sequence
1136 .get_sequence(None, None)
1137 .expect_err("should not read an asset outside the repository");
1138 assert!(
1139 matches!(&error, SequenceError::AssetResolution(reason) if reason.contains("not within repo root")),
1140 "should report the repository boundary: {error}"
1141 );
1142 }
1143
1144 #[test]
1145 fn test_get_sequence_from_disk_circular() {
1146 let context = setup_gen_on_disk();
1147 let temp_file_path = context.workspace().repo_root().unwrap().join("simple.fa");
1148 fs::write(&temp_file_path, ">m123\nAAACCCTTT\n").unwrap();
1149 let asset_ref = prepare_asset(&context, temp_file_path.to_str().unwrap(), AssetRole::Input);
1150 let sequence = Sequence::new()
1151 .sequence_type("circular")
1152 .name("m123")
1153 .asset_ref_id(Some(&asset_ref.id))
1154 .length(9)
1155 .save(context.graph().conn())
1156 .unwrap();
1157 let seq = Sequence::query_by_ids(
1158 context.graph().conn(),
1159 context.workspace(),
1160 &[sequence.hash],
1161 None,
1162 )
1163 .remove(0);
1164 assert_eq!(seq.get_sequence(4, 2).unwrap(), "CCTTTAA");
1165 assert_eq!(
1166 seq.get_sequence(0, 10),
1167 Err(SequenceError::BoundsError {
1168 start: 0,
1169 end: 10,
1170 length: 9,
1171 })
1172 );
1173 }
1174
1175 #[test]
1176 fn test_on_disk_sequence_uses_retained_index_asset() {
1177 let context = setup_gen_on_disk();
1178 let repo_root = context.workspace().repo_root().unwrap();
1179 let fasta_path = repo_root.join("indexed.fa");
1180 let index_path = repo_root.join("indexed.fa.fai");
1181 fs::write(&fasta_path, ">chr1\nACGTACGT\n").unwrap();
1182 fs::write(&index_path, "chr1\t8\t6\t8\t9\n").unwrap();
1183 let asset_ref = prepare_asset(&context, fasta_path.to_str().unwrap(), AssetRole::Input);
1184 let index_asset_ref = prepare_derived_asset(
1185 &context,
1186 index_path.to_str().unwrap(),
1187 AssetRole::SequenceIndex,
1188 &asset_ref.id,
1189 );
1190 let unresolved_sequence = Sequence::new()
1191 .sequence_type("DNA")
1192 .name("chr1")
1193 .asset_ref_id(Some(&asset_ref.id))
1194 .length(8)
1195 .save(context.graph().conn())
1196 .unwrap();
1197 let sequence = Sequence::query_by_ids(
1198 context.graph().conn(),
1199 context.workspace(),
1200 &[unresolved_sequence.hash],
1201 None,
1202 )
1203 .remove(0);
1204 fs::remove_file(&fasta_path).unwrap();
1205 fs::remove_file(&index_path).unwrap();
1206
1207 assert_eq!(
1208 sequence.get_sequence(2, 6).unwrap(),
1209 "GTAC",
1210 "should read the retained sequence through its index"
1211 );
1212 assert!(
1213 sequence
1214 .index_asset_refs
1215 .iter()
1216 .any(|asset_ref| asset_ref.id == index_asset_ref.id),
1217 "resolved sequence should include its retained index AssetRef"
1218 );
1219 assert_eq!(
1220 index_asset_ref.upstream_asset_ref_id,
1221 Some(asset_ref.id),
1222 "index AssetRef should link to the immutable sequence AssetRef"
1223 );
1224 }
1225
1226 #[test]
1227 fn test_cached_sequence_performance() {
1229 let context = setup_gen_on_disk();
1230 let temp_file_path = context.workspace().repo_root().unwrap().join("large.fa");
1231 let mut file = OpenOptions::new()
1232 .append(true)
1233 .create(true)
1234 .open(&temp_file_path)
1235 .unwrap();
1236 writeln!(file, ">chr22").unwrap();
1237 for _ in 1..3_000_000 {
1238 writeln!(
1239 file,
1240 "ATCGATCGATCGATCGATCGGGAACACACAGAGAATCGATCGATCGATCGATCGGGAACACACAGAGA"
1241 )
1242 .unwrap();
1243 }
1244 let index_path = context
1246 .workspace()
1247 .repo_root()
1248 .unwrap()
1249 .join("large.fa.fai");
1250 fs::write(&index_path, "chr22 203999932 7 68 69\n").unwrap();
1251 let asset_ref = prepare_asset(&context, temp_file_path.to_str().unwrap(), AssetRole::Input);
1252 prepare_derived_asset(
1253 &context,
1254 index_path.to_str().unwrap(),
1255 AssetRole::SequenceIndex,
1256 &asset_ref.id,
1257 );
1258 let unresolved_sequence = Sequence::new()
1259 .sequence_type("DNA")
1260 .asset_ref_id(Some(&asset_ref.id))
1261 .name("chr22")
1262 .length(203_999_932)
1263 .save(context.graph().conn())
1264 .unwrap();
1265 let sequence = Sequence::query_by_ids(
1266 context.graph().conn(),
1267 context.workspace(),
1268 &[unresolved_sequence.hash],
1269 None,
1270 )
1271 .remove(0);
1272 assert_eq!(
1275 sequence.get_sequence(0, 20).unwrap(),
1276 "ATCGATCGATCGATCGATCG"
1277 );
1278 let s = time::Instant::now();
1279 for _ in 1..1_000_000 {
1280 let start = rand::rng().random_range(1..200_000_000);
1281
1282 sequence.get_sequence(start, start + 20).unwrap();
1283 }
1284 let elapsed = s.elapsed().as_secs();
1285 assert!(
1286 elapsed < 5,
1287 "Cached sequence benchmark failed: {elapsed}s elapsed"
1288 );
1289 }
1290
1291 #[test]
1292 fn test_capnp_serialization() {
1293 use capnp::message::TypedBuilder;
1294
1295 let sequence = Sequence {
1296 hash: gen_core::Sha256Hash::convert_str("test_hash"),
1297 sequence_type: "DNA".to_string(),
1298 sequence: "ATCG".to_string(),
1299 name: "test_seq".to_string(),
1300 asset_ref_id: Some(gen_core::HashId::convert_str("asset")),
1301 length: 4,
1302 external_sequence: true,
1303 asset_ref: None,
1304 index_asset_refs: Vec::new(),
1305 workspace: None,
1306 asset_resolution_error: None,
1307 };
1308
1309 let mut message = TypedBuilder::<sequence::Owned>::new_default();
1310 let mut root = message.init_root();
1311 sequence.write_capnp(&mut root);
1312
1313 let deserialized = Sequence::read_capnp(root.into_reader());
1314 assert_eq!(sequence, deserialized);
1315 }
1316}