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