use std::fmt;
use relate_core::Error;
use super::errors::byte_limit_exceeded;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RemoteFailure {
Status(u16),
ExceededLimit,
Timeout,
Redirect,
Unreachable,
}
pub trait CsvRemote: Send + Sync + fmt::Debug {
fn fetch(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>, RemoteFailure>;
}
pub(super) struct RemoteUrl<'a> {
scheme: &'a str,
authority: &'a str,
rest: &'a str,
}
impl<'a> RemoteUrl<'a> {
pub(super) fn parse(source: &'a str) -> Option<Self> {
let (scheme, after) = source.split_once("://")?;
if !(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) {
return None;
}
let after = after.split_once('#').map_or(after, |(url, _)| url);
let end = after.find(['/', '?']).unwrap_or(after.len());
let (authority, rest) = after.split_at(end);
Some(Self {
scheme,
authority,
rest,
})
}
pub(super) fn carries_credentials(&self) -> bool {
self.authority.contains('@')
}
pub(super) fn is_well_formed(&self) -> bool {
[self.scheme, self.authority, self.rest]
.iter()
.all(|part| !part.chars().any(|c| c.is_ascii_control() || c == ' '))
}
pub(super) fn canonical(&self) -> String {
format!(
"{}://{}{}",
self.scheme.to_ascii_lowercase(),
self.authority.to_ascii_lowercase(),
self.rest
)
}
}
impl RemoteFailure {
pub(super) fn into_error(self) -> Error {
match self {
Self::Status(status) => {
Error::execution(format!("LOAD CSV remote source returned HTTP {status}"))
}
Self::ExceededLimit => byte_limit_exceeded(),
Self::Timeout => Error::execution("LOAD CSV remote source timed out"),
Self::Redirect => Error::execution("LOAD CSV remote redirect refused"),
Self::Unreachable => Error::execution("LOAD CSV remote source unreachable"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn canonical(source: &str) -> Option<String> {
RemoteUrl::parse(source).map(|url| url.canonical())
}
#[test]
fn only_http_and_https_sources_are_remote() {
for (source, url) in [
("https://example.org/a.csv", "https://example.org/a.csv"),
("http://example.org/a.csv", "http://example.org/a.csv"),
("HTTPS://Example.org/A.csv", "https://example.org/A.csv"),
("Http://EXAMPLE.org:8080/a", "http://example.org:8080/a"),
("https://example.org/a.csv#top", "https://example.org/a.csv"),
(
"https://example.org/a.csv?sig=1#x",
"https://example.org/a.csv?sig=1",
),
("HTTPS://Example.ORG", "https://example.org"),
] {
assert_eq!(canonical(source).as_deref(), Some(url), "{source}");
}
for source in [
"rows.csv",
"dir/rows.csv",
"file:///tmp/rows.csv",
"ftp://example.org/a.csv",
"s3://bucket/a.csv",
"https:/example.org/a.csv",
"httpsx://example.org/a.csv",
"//example.org/a.csv",
"",
] {
assert!(RemoteUrl::parse(source).is_none(), "{source}");
}
}
#[test]
fn credentials_are_found_in_the_authority_only() {
let carries = |url: &str| RemoteUrl::parse(url).unwrap().carries_credentials();
for url in [
"https://user@example.org/a.csv",
"https://user:secret@example.org/a.csv",
"http://:secret@example.org/",
"https://user@example.org",
] {
assert!(carries(url), "{url}");
}
for url in [
"https://example.org/a.csv",
"https://example.org:8443/a.csv",
"https://example.org/a@b.csv",
"https://example.org/a.csv?mail=a@b.org",
"https://example.org/a.csv#x@y",
] {
assert!(!carries(url), "{url}");
}
}
#[test]
fn control_characters_and_spaces_make_a_url_malformed() {
let well_formed = |url: &str| RemoteUrl::parse(url).unwrap().is_well_formed();
for url in [
"https://example.org/a\r\nX-Injected: 1",
"https://example.org/a\nb",
"https://example.org/a\tb",
"https://example.org/a\0b",
"https://example.org/a b.csv",
"https://example.org/a\x7fb",
"https://exam ple.org/",
"https://example.org/?q=a b",
] {
assert!(!well_formed(url), "{url:?}");
}
for url in [
"https://example.org/a%20b.csv",
"https://example.org/a.csv?x=1&y=2",
"https://example.org/caf\u{e9}.csv",
"https://example.org/a.csv#frag ment",
] {
assert!(well_formed(url), "{url:?}");
}
}
#[test]
fn every_failure_has_one_generic_wording_without_the_url() {
for (failure, message) in [
(
RemoteFailure::Status(404),
"LOAD CSV remote source returned HTTP 404",
),
(
RemoteFailure::ExceededLimit,
"LOAD CSV file exceeds byte limit",
),
(RemoteFailure::Timeout, "LOAD CSV remote source timed out"),
(RemoteFailure::Redirect, "LOAD CSV remote redirect refused"),
(
RemoteFailure::Unreachable,
"LOAD CSV remote source unreachable",
),
] {
assert_eq!(failure.into_error(), Error::execution(message));
}
}
}