use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scheme {
Sra,
Ncbi,
Ensembl,
Https,
}
impl Scheme {
#[must_use]
pub const fn prefix(self) -> &'static str {
match self {
Self::Sra => "sra:",
Self::Ncbi => "ncbi:",
Self::Ensembl => "ensembl:",
Self::Https => "https:",
}
}
}
pub const SCHEMES: [Scheme; 4] = [Scheme::Sra, Scheme::Ncbi, Scheme::Ensembl, Scheme::Https];
fn the_four() -> String {
let names: Vec<&str> = SCHEMES.iter().map(|scheme| scheme.prefix()).collect();
crate::dim::english_list(&names)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LocatorError {
UnknownScheme {
locator: String,
scheme: String,
},
NoScheme {
locator: String,
},
Empty {
locator: String,
},
Unresolvable {
locator: String,
why: String,
},
}
impl fmt::Display for LocatorError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownScheme { locator, scheme } => write!(
f,
"`{locator}` names the scheme `{scheme}`, which Ligase does \
not have. The schemes are {}",
the_four()
),
Self::NoScheme { locator } => write!(
f,
"`{locator}` names no scheme, so there is nothing to say \
which archive it is in. Write one of {}",
the_four()
),
Self::Empty { locator } => write!(
f,
"`{locator}` names a scheme and no resource, so there is \
nothing to fetch"
),
Self::Unresolvable { locator, why } => {
write!(f, "`{locator}` cannot be resolved: {why}")
}
}
}
}
impl std::error::Error for LocatorError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Locator {
written: String,
scheme: Scheme,
body: String,
}
impl Locator {
pub fn parse(written: &str) -> Result<Self, LocatorError> {
let written = written.trim();
if written.is_empty() {
return Err(LocatorError::NoScheme {
locator: written.to_owned(),
});
}
if let Some(body) = written.strip_prefix("https://") {
return Self::finish(written, Scheme::Https, body);
}
if let Some(body) = written.strip_prefix("http://")
&& is_loopback(body)
{
return Self::finish(written, Scheme::Https, body);
}
let Some((scheme, body)) = written.split_once(':') else {
return Err(LocatorError::NoScheme {
locator: written.to_owned(),
});
};
let found = SCHEMES.iter().copied().find(|known| {
known
.prefix()
.trim_end_matches(':')
.eq_ignore_ascii_case(scheme)
});
match found {
Some(Scheme::Https) => Self::finish(written, Scheme::Https, ""),
Some(scheme) => Self::finish(written, scheme, body),
None => Err(LocatorError::UnknownScheme {
locator: written.to_owned(),
scheme: scheme.to_owned(),
}),
}
}
fn finish(written: &str, scheme: Scheme, body: &str) -> Result<Self, LocatorError> {
if body.trim().is_empty() {
return Err(LocatorError::Empty {
locator: written.to_owned(),
});
}
Ok(Self {
written: written.to_owned(),
scheme,
body: body.trim().to_owned(),
})
}
#[must_use]
pub const fn scheme(&self) -> Scheme {
self.scheme
}
#[must_use]
pub fn body(&self) -> &str {
&self.body
}
pub fn urls(&self) -> Result<Vec<String>, LocatorError> {
match self.scheme {
Scheme::Sra => self.ena_urls(),
Scheme::Ncbi => {
self.require_plain_accession()?;
Ok(vec![format!(
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi\
?db=nuccore&id={}&rettype=fasta&retmode=text",
self.body
)])
}
Scheme::Ensembl => {
self.require_safe_path()?;
Ok(vec![format!("https://ftp.ensembl.org/pub/{}", self.body)])
}
Scheme::Https => Ok(vec![self.written.clone()]),
}
}
#[must_use]
pub fn suffixes(&self) -> Vec<String> {
match self.scheme {
Scheme::Sra => vec![".fastq.gz".to_owned(), ".fastq.gz".to_owned()],
Scheme::Ncbi => vec![".fasta".to_owned()],
Scheme::Ensembl | Scheme::Https => {
vec![suffix_of_url(&self.body)]
}
}
}
fn ena_urls(&self) -> Result<Vec<String>, LocatorError> {
self.require_plain_accession()?;
let accession = &self.body;
let subdirectory = match accession.len() {
9 => String::new(),
10 => format!("00{}/", &accession[accession.len() - 1..]),
11 => format!("0{}/", &accession[accession.len() - 2..]),
12 => format!("{}/", &accession[accession.len() - 3..]),
length => {
return Err(LocatorError::Unresolvable {
locator: self.written.clone(),
why: format!(
"an SRA run accession is 9 to 12 characters and this \
one is {length}, so ENA's directory layout cannot \
place it"
),
});
}
};
let prefix = &accession[..6];
Ok((1..=2)
.map(|mate| {
format!(
"https://ftp.sra.ebi.ac.uk/vol1/fastq/{prefix}/{subdirectory}\
{accession}/{accession}_{mate}.fastq.gz"
)
})
.collect())
}
fn require_plain_accession(&self) -> Result<(), LocatorError> {
let plain = self
.body
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-');
if plain {
return Ok(());
}
Err(LocatorError::Unresolvable {
locator: self.written.clone(),
why: "an accession is letters, digits, dots, dashes and \
underscores. This one has something else in it, and a \
locator may not carry a path or a query into a URL the \
engine builds"
.to_owned(),
})
}
fn require_safe_path(&self) -> Result<(), LocatorError> {
let safe = !self.body.starts_with('/')
&& !self.body.split('/').any(|segment| segment == "..")
&& !self.body.contains("//")
&& !self.body.contains(':');
if safe {
return Ok(());
}
Err(LocatorError::Unresolvable {
locator: self.written.clone(),
why: "a path is relative to the archive's own tree and may not \
climb out of it, so `..`, a leading `/` and a second \
scheme are all refused"
.to_owned(),
})
}
}
impl fmt::Display for Locator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.written)
}
}
fn is_loopback(after_scheme: &str) -> bool {
let authority = after_scheme
.split(['/', '?', '#'])
.next()
.unwrap_or(after_scheme);
let host = authority
.rsplit_once(':')
.map_or(authority, |(host, _)| host)
.trim_start_matches('[')
.trim_end_matches(']');
matches!(host, "127.0.0.1" | "::1" | "localhost")
}
fn suffix_of_url(url: &str) -> String {
let path = url.split(['?', '#']).next().unwrap_or(url);
path.rsplit('/')
.next()
.and_then(|name| name.find('.').map(|at| name[at..].to_owned()))
.unwrap_or_default()
}