Skip to main content

gen_models/
sequence.rs

1use std::{collections::HashMap, fs, str, sync};
2
3use cached::proc_macro::cached;
4use gen_core::{HashId, traits::Capnp};
5use noodles::{
6    bgzf::{self, gzi},
7    core::Region,
8    fasta::{self, fai, io::indexed_reader::Builder as IndexBuilder},
9};
10use rusqlite::{Row, params};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use thiserror::Error;
14
15use crate::{db::GraphConnection, gen_models_capnp::sequence, traits::*};
16
17#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
18pub struct Sequence {
19    pub hash: HashId,
20    pub sequence_type: String,
21    sequence: String,
22    // these 2 fields are only relevant when the sequence is stored externally
23    pub name: String,
24    pub file_path: String,
25    pub length: i64,
26    // indicates whether the sequence is stored externally, a quick flag instead of having to
27    // check sequence or file_path and do the logic in function calls.
28    pub external_sequence: bool,
29}
30
31#[derive(Debug, Error, PartialEq)]
32pub enum SequenceError {
33    #[error("Database error: {0}")]
34    DatabaseError(#[from] rusqlite::Error),
35    #[error("Sequence or file_path must be set.")]
36    NoSequence(),
37    #[error("A filepath must have an accompanying sequence name.")]
38    FilepathMissingSequenceName(),
39    #[error("Sequence length must be specified.")]
40    MissingSequenceLength(),
41    #[error("Sequence cache lock poisoned: {0}")]
42    CachePoisoned(String),
43    #[error("Invalid indexed sequence region '{name}': {reason}")]
44    InvalidRegion { name: String, reason: String },
45    #[error("Sequence I/O error: {0}")]
46    Io(String),
47    #[error("Invalid UTF-8 while reading sequence data: {0}")]
48    Utf8(String),
49    #[error("Sequence id '{name}' not found in fasta file {file_path}")]
50    IdMissing { file_path: String, name: String },
51    #[error("Sequence bounds out of range: start={start}, end={end}, length={length}")]
52    BoundsError { start: i64, end: i64, length: i64 },
53}
54
55impl<'a> Capnp<'a> for Sequence {
56    type Builder = sequence::Builder<'a>;
57    type Reader = sequence::Reader<'a>;
58
59    fn write_capnp(&self, builder: &mut Self::Builder) {
60        builder.set_hash(&self.hash.0).unwrap();
61        builder.set_sequence_type(&self.sequence_type);
62        builder.set_sequence(&self.sequence);
63        builder.set_name(&self.name);
64        builder.set_file_path(&self.file_path);
65        builder.set_length(self.length);
66        builder.set_external_sequence(self.external_sequence);
67    }
68
69    fn read_capnp(reader: Self::Reader) -> Self {
70        let hash = reader
71            .get_hash()
72            .unwrap()
73            .as_slice()
74            .unwrap()
75            .try_into()
76            .unwrap();
77        let sequence_type = reader.get_sequence_type().unwrap().to_string().unwrap();
78        let sequence = reader.get_sequence().unwrap().to_string().unwrap();
79        let name = reader.get_name().unwrap().to_string().unwrap();
80        let file_path = reader.get_file_path().unwrap().to_string().unwrap();
81        let length = reader.get_length();
82        let external_sequence = reader.get_external_sequence();
83
84        Sequence {
85            hash,
86            sequence_type,
87            sequence,
88            name,
89            file_path,
90            length,
91            external_sequence,
92        }
93    }
94}
95
96#[derive(Default, Debug)]
97pub struct NewSequence<'a> {
98    sequence_type: Option<&'a str>,
99    sequence: Option<&'a str>,
100    name: Option<&'a str>,
101    file_path: Option<&'a str>,
102    length: Option<i64>,
103    shallow: bool,
104}
105
106impl<'a> From<&'a Sequence> for NewSequence<'a> {
107    fn from(value: &'a Sequence) -> NewSequence<'a> {
108        NewSequence::new()
109            .sequence_type(&value.sequence_type)
110            .sequence(&value.sequence)
111            .name(&value.name)
112            .file_path(&value.file_path)
113            .length(value.length)
114    }
115}
116
117impl<'a> NewSequence<'a> {
118    pub fn new() -> NewSequence<'static> {
119        NewSequence {
120            shallow: false,
121            ..NewSequence::default()
122        }
123    }
124
125    pub fn shallow(mut self, setting: bool) -> Self {
126        self.shallow = setting;
127        self
128    }
129
130    pub fn sequence_type(mut self, seq_type: &'a str) -> Self {
131        self.sequence_type = Some(seq_type);
132        self
133    }
134
135    pub fn sequence(mut self, sequence: &'a str) -> Self {
136        self.sequence = Some(sequence);
137        self.length = Some(sequence.len() as i64);
138        self
139    }
140
141    pub fn name(mut self, name: &'a str) -> Self {
142        self.name = Some(name);
143        self
144    }
145
146    pub fn file_path(mut self, path: &'a str) -> Self {
147        if !path.is_empty() {
148            self.file_path = Some(path);
149            self.shallow = true;
150        }
151        self
152    }
153
154    pub fn length(mut self, length: i64) -> Self {
155        self.length = Some(length);
156        self
157    }
158
159    pub fn hash(&self) -> HashId {
160        let mut hasher = Sha256::new();
161        hasher.update(self.sequence_type.expect("Sequence type must be defined."));
162        hasher.update(";");
163        if let Some(v) = self.sequence {
164            hasher.update(v);
165        } else {
166            hasher.update("");
167        }
168        hasher.update(";");
169        if let Some(v) = self.name {
170            hasher.update(v);
171        } else {
172            hasher.update("");
173        }
174        hasher.update(";");
175        if let Some(v) = self.file_path {
176            hasher.update(v);
177        } else {
178            hasher.update("");
179        }
180        hasher.update(";");
181
182        HashId(hasher.finalize().into())
183    }
184
185    pub fn build(self) -> Sequence {
186        let file_path = self.file_path.unwrap_or("").to_string();
187        let external_sequence = !file_path.is_empty();
188        Sequence {
189            hash: self.hash(),
190            sequence_type: self.sequence_type.unwrap().to_string(),
191            sequence: self.sequence.unwrap_or("").to_string(),
192            name: self.name.unwrap_or("").to_string(),
193            file_path,
194            length: self.length.unwrap(),
195            external_sequence,
196        }
197    }
198
199    #[cfg_attr(
200        all(debug_assertions, feature = "profiling"),
201        tracing::instrument(skip(self, conn))
202    )]
203    pub fn save(self, conn: &GraphConnection) -> Result<Sequence, SequenceError> {
204        let mut length = 0;
205        if self.sequence.is_none() && self.file_path.is_none() {
206            return Err(SequenceError::NoSequence());
207        }
208        if self.file_path.is_some() && self.name.is_none() {
209            return Err(SequenceError::FilepathMissingSequenceName());
210        }
211        if self.length.is_none() {
212            if let Some(v) = self.sequence {
213                length = v.len() as i64;
214            } else {
215                // TODO: if name/path specified, grab length automatically
216                return Err(SequenceError::MissingSequenceLength());
217            }
218        }
219        let hash = self.hash();
220        match conn.query_row(
221            "SELECT hash from sequences where hash = ?1;",
222            [hash],
223            |row| row.get::<_, HashId>(0),
224        ) {
225            Ok(_) => {}
226            Err(rusqlite::Error::QueryReturnedNoRows) => {
227                let mut stmt = conn.prepare("INSERT INTO sequences (hash, sequence_type, sequence, name, file_path, length) VALUES (?1, ?2, ?3, ?4, ?5, ?6);")?;
228                match stmt.execute(params![
229                    hash,
230                    self.sequence_type.unwrap().to_string(),
231                    if self.shallow {
232                        ""
233                    } else {
234                        self.sequence.unwrap()
235                    },
236                    self.name.unwrap_or(""),
237                    self.file_path.unwrap_or(""),
238                    self.length.unwrap_or(length)
239                ]) {
240                    Ok(_) => {}
241                    Err(err) => return Err(SequenceError::DatabaseError(err)),
242                }
243            }
244            Err(err) => return Err(SequenceError::DatabaseError(err)),
245        };
246
247        Ok(Sequence {
248            hash,
249            sequence_type: self.sequence_type.unwrap().to_string(),
250            sequence: self.sequence.unwrap_or("").to_string(),
251            name: self.name.unwrap_or("").to_string(),
252            file_path: self.file_path.unwrap_or("").to_string(),
253            length: self.length.unwrap_or(length),
254            external_sequence: !self.file_path.unwrap_or("").is_empty(),
255        })
256    }
257}
258
259#[cached(key = "String", convert = r#"{ format!("{}", path) }"#)]
260fn fasta_index(path: &str) -> Option<fai::Index> {
261    let index_path = format!("{path}.fai");
262    if fs::metadata(&index_path).is_ok() {
263        return Some(fai::fs::read(&index_path).unwrap());
264    }
265    None
266}
267
268#[cached(key = "String", convert = r#"{ format!("{}", path) }"#)]
269fn fasta_gzi_index(path: &str) -> Option<gzi::Index> {
270    let index_path = format!("{path}.gzi");
271    if fs::metadata(&index_path).is_ok() {
272        return Some(gzi::fs::read(&index_path).unwrap());
273    }
274    None
275}
276
277fn validate_sequence_bounds(
278    start: i64,
279    end: i64,
280    length: i64,
281) -> Result<(usize, usize), SequenceError> {
282    if start < 0 || end < 0 || start > length || end > length {
283        return Err(SequenceError::BoundsError { start, end, length });
284    }
285
286    Ok((start as usize, end as usize))
287}
288
289fn circular_sequence_slice(sequence: &str, start: i64, end: i64) -> Result<String, SequenceError> {
290    let length = sequence.len() as i64;
291    if length == 0 {
292        if start == 0 && end == 0 {
293            return Ok(String::new());
294        }
295        return Err(SequenceError::BoundsError { start, end, length });
296    }
297
298    let (start, end) = validate_sequence_bounds(start, end, length)?;
299    if start <= end {
300        return Ok(sequence[start..end].to_string());
301    }
302
303    let mut result = String::with_capacity((length as usize - start) + end);
304    result.push_str(&sequence[start..]);
305    result.push_str(&sequence[..end]);
306
307    Ok(result)
308}
309
310fn sequence_slice(
311    sequence: &str,
312    start: i64,
313    end: i64,
314    circular: bool,
315) -> Result<String, SequenceError> {
316    if circular {
317        return circular_sequence_slice(sequence, start, end);
318    }
319
320    let length = sequence.len() as i64;
321    let (start, end) = validate_sequence_bounds(start, end, length)?;
322    if start <= end {
323        return Ok(sequence[start..end].to_string());
324    }
325
326    Err(SequenceError::BoundsError {
327        start: start as i64,
328        end: end as i64,
329        length,
330    })
331}
332
333pub fn cached_sequence(
334    file_path: &str,
335    name: &str,
336    start: i64,
337    end: i64,
338    circular: bool,
339) -> Result<String, SequenceError> {
340    static SEQUENCE_CACHE: sync::LazyLock<sync::RwLock<HashMap<String, Option<String>>>> =
341        sync::LazyLock::new(|| sync::RwLock::new(HashMap::new()));
342    let key = format!("{file_path}-{name}");
343
344    {
345        let cache = SEQUENCE_CACHE
346            .read()
347            .map_err(|err| SequenceError::CachePoisoned(err.to_string()))?;
348        if let Some(cached_sequence) = cache.get(&key) {
349            if let Some(sequence) = cached_sequence {
350                return sequence_slice(sequence, start, end, circular);
351            }
352            return Err(SequenceError::IdMissing {
353                file_path: file_path.to_string(),
354                name: name.to_string(),
355            });
356        }
357    }
358
359    let mut cache = SEQUENCE_CACHE
360        .write()
361        .map_err(|err| SequenceError::CachePoisoned(err.to_string()))?;
362
363    let mut sequence: Option<String> = None;
364    if let Some(index) = fasta_index(file_path) {
365        let region = name
366            .parse::<Region>()
367            .map_err(|err| SequenceError::InvalidRegion {
368                name: name.to_string(),
369                reason: err.to_string(),
370            })?;
371        let builder = IndexBuilder::default().set_index(index);
372        if let Some(gzi_index) = fasta_gzi_index(file_path) {
373            let bgzf_reader = bgzf::io::indexed_reader::Builder::default()
374                .set_index(gzi_index)
375                .build_from_path(file_path)
376                .map_err(|err| SequenceError::Io(err.to_string()))?;
377            let mut reader = builder
378                .build_from_reader(bgzf_reader)
379                .map_err(|err| SequenceError::Io(err.to_string()))?;
380            sequence = Some(
381                str::from_utf8(
382                    reader
383                        .query(&region)
384                        .map_err(|err| SequenceError::Io(err.to_string()))?
385                        .sequence()
386                        .as_ref(),
387                )
388                .map_err(|err| SequenceError::Utf8(err.to_string()))?
389                .to_string(),
390            )
391        } else {
392            let mut reader = builder
393                .build_from_path(file_path)
394                .map_err(|err| SequenceError::Io(err.to_string()))?;
395            sequence = Some(
396                str::from_utf8(
397                    reader
398                        .query(&region)
399                        .map_err(|err| SequenceError::Io(err.to_string()))?
400                        .sequence()
401                        .as_ref(),
402                )
403                .map_err(|err| SequenceError::Utf8(err.to_string()))?
404                .to_string(),
405            );
406        }
407    } else {
408        let mut reader = fasta::io::reader::Builder
409            .build_from_path(file_path)
410            .map_err(|err| SequenceError::Io(err.to_string()))?;
411        for result in reader.records() {
412            let record = result.map_err(|err| SequenceError::Io(err.to_string()))?;
413            if String::from_utf8(record.name().to_vec())
414                .map_err(|err| SequenceError::Utf8(err.to_string()))?
415                == name
416            {
417                sequence = Some(
418                    str::from_utf8(record.sequence().as_ref())
419                        .map_err(|err| SequenceError::Utf8(err.to_string()))?
420                        .to_string(),
421                );
422                break;
423            }
424        }
425    }
426    // this is a LRU cache setup, we just keep the last sequence we fetched so we don't end up loading
427    // plant genomes into memory.
428    cache.clear();
429    cache.insert(key.clone(), sequence);
430    // we do this to avoid a clone of potentially large data.
431    if let Some(seq) = &cache[&key] {
432        return sequence_slice(seq, start, end, circular);
433    }
434    Err(SequenceError::IdMissing {
435        file_path: file_path.to_string(),
436        name: name.to_string(),
437    })
438}
439
440impl Sequence {
441    #[allow(clippy::new_ret_no_self)]
442    pub fn new() -> NewSequence<'static> {
443        NewSequence::new()
444    }
445
446    fn is_circular(&self) -> bool {
447        self.sequence_type
448            .split_whitespace()
449            .any(|part| part.eq_ignore_ascii_case("circular"))
450    }
451
452    pub fn get_sequence(
453        &self,
454        start: impl Into<Option<i64>>,
455        end: impl Into<Option<i64>>,
456    ) -> Result<String, SequenceError> {
457        // todo: handle circles
458
459        let start: Option<i64> = start.into();
460        let end: Option<i64> = end.into();
461        let start = start.unwrap_or(0);
462        let end = end.unwrap_or(self.length);
463        if self.external_sequence {
464            return cached_sequence(&self.file_path, &self.name, start, end, self.is_circular());
465        }
466        if start == 0 && end == self.length {
467            return Ok(self.sequence.clone());
468        }
469        sequence_slice(&self.sequence, start, end, self.is_circular())
470    }
471
472    pub fn delete_by_hash(conn: &GraphConnection, hash: &HashId) {
473        let mut stmt = conn
474            .prepare("delete from sequences where hash = ?1;")
475            .unwrap();
476        stmt.execute(params![hash]).unwrap();
477    }
478
479    pub fn query_by_blockgroup(conn: &GraphConnection, block_group_id: &HashId) -> Vec<Sequence> {
480        Sequence::query(
481            conn,
482            "select sequences.* from block_group_edges bge left join edges on bge.edge_id = edges.id left join nodes on (edges.source_node_id = nodes.id or edges.target_node_id = nodes.id) left join sequences on (nodes.sequence_hash = sequences.hash) where bge.block_group_id = ?1;",
483            params![block_group_id],
484        )
485    }
486}
487
488impl Query for Sequence {
489    type Model = Sequence;
490
491    const PRIMARY_KEY: &'static str = "hash";
492    const TABLE_NAME: &'static str = "sequences";
493
494    fn process_row(row: &Row) -> Self::Model {
495        let file_path: String = row.get(4).unwrap();
496        let mut external_sequence = false;
497        if !file_path.is_empty() {
498            external_sequence = true;
499        }
500        let hash: HashId = row.get(0).unwrap();
501        let sequence = row.get(2).unwrap();
502        Sequence {
503            hash,
504            sequence_type: row.get(1).unwrap(),
505            sequence,
506            name: row.get(3).unwrap(),
507            file_path,
508            length: row.get(5).unwrap(),
509            external_sequence,
510        }
511    }
512}
513
514pub fn reverse_complement(seq: &[u8]) -> Vec<u8> {
515    seq.iter()
516        .rev()
517        .map(|&base| match base.to_ascii_uppercase() {
518            b'A' => b'T',
519            b'T' => b'A',
520            b'C' => b'G',
521            b'G' => b'C',
522            b'U' => b'A',
523            b'N' => b'N',
524            b'R' => b'Y',
525            b'Y' => b'R',
526            b'S' => b'S',
527            b'W' => b'W',
528            b'K' => b'M',
529            b'M' => b'K',
530            b'B' => b'V',
531            b'V' => b'B',
532            b'D' => b'H',
533            b'H' => b'D',
534            _ => base,
535        })
536        .collect()
537}
538
539#[cfg(test)]
540mod tests {
541    // Note this useful idiom: importing names from outer (for mod tests) scope.
542    #[allow(unused_imports)]
543    use std::time;
544    use std::{fs::OpenOptions, io::Write};
545
546    use rand::RngExt;
547
548    use super::*;
549    use crate::test_helpers::get_connection;
550
551    #[test]
552    fn test_builder() {
553        let sequence = Sequence::new()
554            .sequence_type("DNA")
555            .sequence("ATCG")
556            .build();
557        assert_eq!(sequence.length, 4);
558        assert_eq!(sequence.sequence, "ATCG");
559    }
560
561    #[test]
562    fn test_builder_with_from_disk() {
563        let sequence = Sequence::new()
564            .sequence_type("DNA")
565            .name("chr1")
566            .file_path("/foo/bar")
567            .length(50)
568            .build();
569        assert_eq!(sequence.length, 50);
570        assert_eq!(sequence.sequence, "");
571    }
572
573    #[test]
574    fn test_create_sequence_in_db() {
575        let conn = &get_connection(None).unwrap();
576        let sequence = Sequence::new()
577            .sequence_type("DNA")
578            .sequence("AACCTT")
579            .save(conn)
580            .unwrap();
581        assert_eq!(&sequence.sequence, "AACCTT");
582        assert_eq!(sequence.sequence_type, "DNA");
583        assert!(!sequence.external_sequence);
584    }
585
586    #[test]
587    fn test_delete_sequence_by_hash() {
588        let conn = &get_connection(None).unwrap();
589        let before_count = Sequence::all(conn).len();
590        let sequence = Sequence::new()
591            .sequence_type("DNA")
592            .sequence("AACCTT")
593            .save(conn)
594            .unwrap();
595        let sequence2 = Sequence::new()
596            .sequence_type("DNA")
597            .sequence("AACCTTAA")
598            .save(conn)
599            .unwrap();
600
601        let sequences = Sequence::all(conn);
602        assert_eq!(sequences.len(), before_count + 2);
603
604        Sequence::delete_by_hash(conn, &sequence.hash);
605
606        let sequences = Sequence::all(conn);
607        assert_eq!(sequences.len(), before_count + 1);
608        assert!(sequences.iter().any(|s| s.hash == sequence2.hash));
609    }
610
611    #[test]
612    fn test_create_sequence_on_disk() {
613        let conn = &get_connection(None).unwrap();
614        let sequence = Sequence::new()
615            .sequence_type("DNA")
616            .name("chr1")
617            .file_path("/some/path.fa")
618            .length(10)
619            .save(conn)
620            .unwrap();
621        assert_eq!(sequence.sequence_type, "DNA");
622        assert_eq!(&sequence.sequence, "");
623        assert_eq!(sequence.name, "chr1");
624        assert_eq!(sequence.file_path, "/some/path.fa");
625        assert_eq!(sequence.length, 10);
626        assert!(sequence.external_sequence);
627    }
628
629    #[test]
630    fn test_get_sequence() {
631        let conn = &get_connection(None).unwrap();
632        let sequence = Sequence::new()
633            .sequence_type("DNA")
634            .sequence("ATCGATCGATCGATCGATCGGGAACACACAGAGA")
635            .save(conn)
636            .unwrap();
637        assert_eq!(
638            sequence.get_sequence(None, None).unwrap(),
639            "ATCGATCGATCGATCGATCGGGAACACACAGAGA"
640        );
641        assert_eq!(sequence.get_sequence(0, 5).unwrap(), "ATCGA");
642        assert_eq!(sequence.get_sequence(10, 15).unwrap(), "CGATC");
643        assert_eq!(
644            sequence.get_sequence(3, None).unwrap(),
645            "GATCGATCGATCGATCGGGAACACACAGAGA"
646        );
647        assert_eq!(sequence.get_sequence(None, 5).unwrap(), "ATCGA");
648        assert_eq!(
649            sequence.get_sequence(0, 100),
650            Err(SequenceError::BoundsError {
651                start: 0,
652                end: 100,
653                length: 34,
654            })
655        );
656        assert_eq!(
657            sequence.get_sequence(5, 2),
658            Err(SequenceError::BoundsError {
659                start: 5,
660                end: 2,
661                length: 34,
662            })
663        );
664    }
665
666    #[test]
667    fn test_get_sequence_circular() {
668        let conn = &get_connection(None).unwrap();
669        let sequence = Sequence::new()
670            .sequence_type("circular")
671            .sequence("AAACCCTTT")
672            .save(conn)
673            .unwrap();
674        assert_eq!(sequence.get_sequence(4, 2).unwrap(), "CCTTTAA");
675        assert_eq!(
676            sequence.get_sequence(0, 10),
677            Err(SequenceError::BoundsError {
678                start: 0,
679                end: 10,
680                length: 9,
681            })
682        );
683    }
684
685    #[test]
686    fn test_get_sequence_from_disk() {
687        let conn = &get_connection(None).unwrap();
688        let temp_dir = tempfile::tempdir().unwrap();
689        let temp_file_path = temp_dir.path().join("simple.fa");
690        fs::write(
691            &temp_file_path,
692            ">m123\nATCGATCGATCGATCGATCGGGAACACACAGAGA\n",
693        )
694        .unwrap();
695        let seq = Sequence::new()
696            .sequence_type("DNA")
697            .name("m123")
698            .file_path(temp_file_path.to_str().unwrap())
699            .length(34)
700            .save(conn)
701            .unwrap();
702        assert_eq!(
703            seq.get_sequence(None, None).unwrap(),
704            "ATCGATCGATCGATCGATCGGGAACACACAGAGA"
705        );
706        assert_eq!(seq.get_sequence(0, 5).unwrap(), "ATCGA");
707        assert_eq!(seq.get_sequence(10, 15).unwrap(), "CGATC");
708        assert_eq!(
709            seq.get_sequence(3, None).unwrap(),
710            "GATCGATCGATCGATCGGGAACACACAGAGA"
711        );
712        assert_eq!(seq.get_sequence(None, 5).unwrap(), "ATCGA");
713    }
714
715    #[test]
716    fn test_get_sequence_from_disk_circular() {
717        let conn = &get_connection(None).unwrap();
718        let temp_dir = tempfile::tempdir().unwrap();
719        let temp_file_path = temp_dir.path().join("simple.fa");
720        fs::write(&temp_file_path, ">m123\nAAACCCTTT\n").unwrap();
721        let seq = Sequence::new()
722            .sequence_type("circular")
723            .name("m123")
724            .file_path(temp_file_path.to_str().unwrap())
725            .length(9)
726            .save(conn)
727            .unwrap();
728        assert_eq!(seq.get_sequence(4, 2).unwrap(), "CCTTTAA");
729        assert_eq!(
730            seq.get_sequence(0, 10),
731            Err(SequenceError::BoundsError {
732                start: 0,
733                end: 10,
734                length: 9,
735            })
736        );
737    }
738
739    #[test]
740    // #[cfg(feature = "benchmark")]
741    fn test_cached_sequence_performance() {
742        let conn = &get_connection(None).unwrap();
743        let temp_dir = tempfile::tempdir().unwrap();
744        let temp_file_path = temp_dir.path().join("large.fa");
745        let mut file = OpenOptions::new()
746            .append(true)
747            .create(true)
748            .open(&temp_file_path)
749            .unwrap();
750        writeln!(file, ">chr22").unwrap();
751        for _ in 1..3_000_000 {
752            writeln!(
753                file,
754                "ATCGATCGATCGATCGATCGGGAACACACAGAGAATCGATCGATCGATCGATCGGGAACACACAGAGA"
755            )
756            .unwrap();
757        }
758        // write index
759        let index_path = temp_dir.path().join("large.fa.fai");
760        fs::write(&index_path, "chr22	203999932	7	68	69\n").unwrap();
761        let sequence = Sequence::new()
762            .sequence_type("DNA")
763            .file_path(temp_file_path.to_str().unwrap())
764            .name("chr22")
765            .length(203_999_932)
766            .save(conn)
767            .unwrap();
768        let s = time::Instant::now();
769        for _ in 1..1_000_000 {
770            let start = rand::rng().random_range(1..200_000_000);
771
772            sequence.get_sequence(start, start + 20).unwrap();
773        }
774        let elapsed = s.elapsed().as_secs();
775        assert!(
776            elapsed < 5,
777            "Cached sequence benchmark failed: {elapsed}s elapsed"
778        );
779    }
780
781    #[test]
782    fn test_capnp_serialization() {
783        use capnp::message::TypedBuilder;
784
785        let sequence = Sequence {
786            hash: HashId::convert_str("test_hash"),
787            sequence_type: "DNA".to_string(),
788            sequence: "ATCG".to_string(),
789            name: "test_seq".to_string(),
790            file_path: "/path/to/file".to_string(),
791            length: 4,
792            external_sequence: false,
793        };
794
795        let mut message = TypedBuilder::<sequence::Owned>::new_default();
796        let mut root = message.init_root();
797        sequence.write_capnp(&mut root);
798
799        let deserialized = Sequence::read_capnp(root.into_reader());
800        assert_eq!(sequence, deserialized);
801    }
802}