diff --git a/CHANGELOG.md b/CHANGELOG.md index ac6e9b7..17c8f28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ Notable changes are recorded from 0.5.0 onward. - Added `WsFrameDecoder` and `WsFrameEncoder` for shared protocol handling across synchronous and asynchronous adapters. Existing `WsRead` and `WsWrite` APIs and behaviour are unchanged. - Added the `runtime` module with a process-wide Tokio runtime for object storage requests. Applications install their own runtime with `runtime::init_with`, and Lightstream otherwise initialises a default multi-thread runtime on first use. - Object storage requests from `StorageReader` and `StorageWriter` run on the runtime current on the calling thread, or on the process runtime otherwise. Callers no longer enter a runtime first. +- Added file reads over `http://` and `https://` paths behind the `https` feature. File readers accept these URLs in place of paths and read them through the object storage HTTP backend. ### Breaking Changes diff --git a/rust/Cargo.toml b/rust/Cargo.toml index de8f3ed..195d6c4 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -216,6 +216,9 @@ aws = ["object_storage", "object_store/aws"] gcp = ["object_storage", "object_store/gcp"] # Azure Blob Storage azure = ["object_storage", "object_store/azure"] +# File reads over `http://` and `https://` paths through the object storage +# HTTP backend. Separate from the `http` transport feature. +https = ["object_storage", "object_store/http"] # Lightstream protocol multiplexing protocol = [] diff --git a/rust/src/object_storage/connection.rs b/rust/src/object_storage/connection.rs index dd44ba1..c5db83b 100644 --- a/rust/src/object_storage/connection.rs +++ b/rust/src/object_storage/connection.rs @@ -32,7 +32,7 @@ use std::sync::{Arc, LazyLock, Mutex, RwLock}; use object_store::memory::InMemory; use object_store::path::Path as ObjectPath; -#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))] +#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "https"))] use object_store::{ClientConfigKey, ClientOptions}; use object_store::{ObjectStore, ObjectStoreScheme}; use url::{Position, Url}; @@ -57,7 +57,7 @@ const MAX_CONCURRENT_PARTS_KEY: &str = "max_concurrent_parts"; /// URL schemes routed to object storage. Every other path is a local path. const OBJECT_SCHEMES: &[&str] = &[ - "s3", "s3a", "gs", "az", "adl", "azure", "abfs", "abfss", "memory", + "s3", "s3a", "gs", "az", "adl", "azure", "abfs", "abfss", "memory", "http", "https", ]; /// Options registered per URL prefix, as `(prefix, options)`. @@ -168,7 +168,16 @@ pub(crate) fn resolve(url: &str) -> io::Result { format!("invalid object storage URL '{url}': {e}"), ) })?; - let (scheme, path) = ObjectStoreScheme::parse(&parsed).map_err(|e| io_error(e.into()))?; + // `http` and `https` URLs resolve to the HTTP store for every host, + // including cloud storage hosts that `ObjectStoreScheme::parse` assigns + // to their cloud backends. + let (scheme, path) = match parsed.scheme() { + "http" | "https" => ( + ObjectStoreScheme::Http, + ObjectPath::from_url_path(parsed.path()).map_err(|e| io_error(e.into()))?, + ), + _ => ObjectStoreScheme::parse(&parsed).map_err(|e| io_error(e.into()))?, + }; let (prefix, options) = registered_options(url); let (part_size, max_concurrent_parts) = upload_settings(&options)?; if scheme == ObjectStoreScheme::Memory { @@ -267,9 +276,11 @@ fn registered_options(url: &str) -> (String, Vec<(String, String)>) { /// /// The HTTP client starts with no limit on total request time. The /// backend's environment variables and then `options` are applied over that -/// default, and either can set a `timeout`. +/// default, and either can set a `timeout`. The HTTP store doesn't read any +/// environment variables, and allows plaintext connections for `http` URLs +/// only. #[cfg_attr( - not(any(feature = "aws", feature = "gcp", feature = "azure")), + not(any(feature = "aws", feature = "gcp", feature = "azure", feature = "https")), allow(unused_variables) )] fn build( @@ -335,10 +346,27 @@ fn build( let store = builder.build().map_err(io_error)?; Ok(Arc::new(store)) } + #[cfg(feature = "https")] + ObjectStoreScheme::Http => { + use object_store::http::HttpBuilder; + let mut builder = HttpBuilder::new() + .with_url(&url[..Position::BeforePath]) + .with_client_options( + ClientOptions::new() + .with_timeout_disabled() + .with_allow_http(url.scheme() == "http"), + ); + for (key, value) in options { + let key: ClientConfigKey = key.parse().map_err(io_error)?; + builder = builder.with_config(key, value); + } + let store = builder.build().map_err(io_error)?; + Ok(Arc::new(store)) + } _ => Err(io::Error::new( io::ErrorKind::Unsupported, format!( - "object storage URL '{url}' requires the lightstream `aws`, `gcp` or `azure` feature for its scheme" + "object storage URL '{url}' requires the lightstream `aws`, `gcp`, `azure` or `https` feature for its scheme" ), )), } @@ -422,7 +450,8 @@ mod tests { assert!(object_url(Path::new("/tmp/data/a.csv")).is_none()); assert!(object_url(Path::new("relative/a.csv")).is_none()); assert!(object_url(Path::new("C:\\data\\a.csv")).is_none()); - assert!(object_url(Path::new("https://host/a.csv")).is_none()); + assert!(object_url(Path::new("https://host/a.csv")).is_some()); + assert!(object_url(Path::new("http://host/a.csv")).is_some()); } #[test] @@ -471,6 +500,27 @@ mod tests { assert_eq!(err.kind(), io::ErrorKind::Unsupported); } + #[cfg(not(feature = "https"))] + #[test] + fn http_urls_without_their_feature_are_unsupported() { + let err = resolve("https://host/a.csv").unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::Unsupported); + } + + #[cfg(feature = "https")] + #[test] + fn https_urls_on_cloud_storage_hosts_resolve_to_the_http_store() { + for url in [ + "https://bucket.s3.amazonaws.com/data/a.parquet", + "https://account.blob.core.windows.net/container/a.parquet", + ] { + let location = resolve(url).unwrap(); + assert_eq!(location.store.to_string(), "HttpStore", "{url}"); + } + let location = resolve("https://bucket.s3.amazonaws.com/data/a.parquet").unwrap(); + assert_eq!(location.path.as_ref(), "data/a.parquet"); + } + #[cfg(feature = "azure")] #[test] fn containers_in_the_url_user_part_resolve_to_separate_stores() { diff --git a/rust/src/object_storage/mod.rs b/rust/src/object_storage/mod.rs index fc57497..b360c30 100644 --- a/rust/src/object_storage/mod.rs +++ b/rust/src/object_storage/mod.rs @@ -34,10 +34,16 @@ //! | `s3://bucket/path`, `s3a://` | Amazon S3 and S3-compatible stores | `aws` | //! | `gs://bucket/path` | Google Cloud Storage | `gcp` | //! | `az://container/path`, `abfs://`, `abfss://`, `adl://`, `azure://` | Azure Blob Storage | `azure` | +//! | `http://host/path`, `https://host/path` | HTTP and HTTPS servers | `https` | //! //! Paths without one of these schemes, including Windows drive paths, are //! local file paths as before. //! +//! The HTTP backend is for reads, and resolves every `http` and `https` URL, +//! including URLs on cloud storage hosts, without credentials. Query strings +//! are not sent to the server, and directory listing works only against +//! WebDAV servers. `https` URLs are not redirected to plaintext `http`. +//! //! ## Credentials //! Each backend reads its standard environment variables (`AWS_*`, //! `GOOGLE_*`, `AZURE_*`), falling back to instance or workload identity diff --git a/rust/tests/object_storage_http.rs b/rust/tests/object_storage_http.rs new file mode 100644 index 0000000..9c93976 --- /dev/null +++ b/rust/tests/object_storage_http.rs @@ -0,0 +1,152 @@ +// Copyright Peter G. Bower 2025-2026. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Object storage read tests against the HTTP backend. +//! +//! Files are served over `http://` by an HTTP/1.1 server on a loopback port +//! within the test process. The server answers `GET` and `HEAD` requests, +//! ranged `GET` requests with `206 Partial Content`, and `404 Not Found` for +//! paths it doesn't serve. + +#![cfg(feature = "https")] + +mod object_storage_checks; + +use std::collections::HashMap; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::thread; + +use lightstream::models::readers::ipc::file_table::FileTableReader; +use lightstream::models::readers::object_storage::StorageReader; +use lightstream::models::writers::ipc::sync_table::write_tables_to_file_sync; +use minarrow::Table; +use object_storage_checks as checks; + +/// Serve `files`, keyed by request path, on a loopback port, and return the +/// server's base URL. +fn serve(files: HashMap>) -> String { + let listener = TcpListener::bind("127.0.0.1:0").expect("loopback port binds"); + let base = format!("http://{}", listener.local_addr().unwrap()); + let files = Arc::new(files); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + let files = Arc::clone(&files); + thread::spawn(move || respond(stream, &files)); + } + }); + base +} + +/// Answer one request on `stream` and close the connection. +fn respond(stream: TcpStream, files: &HashMap>) { + let mut reader = BufReader::new(&stream); + let mut request_line = String::new(); + if reader.read_line(&mut request_line).is_err() { + return; + } + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap_or_default().to_string(); + let path = parts.next().unwrap_or_default().to_string(); + + // Read the headers up to the blank line, keeping the inclusive byte + // range of a `Range: bytes=start-end` header. + let mut range: Option<(usize, usize)> = None; + loop { + let mut line = String::new(); + match reader.read_line(&mut line) { + Ok(0) | Err(_) => break, + Ok(_) if line == "\r\n" => break, + Ok(_) => {} + } + if let Some((name, value)) = line.split_once(':') + && name.eq_ignore_ascii_case("range") + { + range = value + .trim() + .strip_prefix("bytes=") + .and_then(|bounds| bounds.split_once('-')) + .map(|(start, end)| (start.parse().unwrap(), end.parse().unwrap())); + } + } + + let mut stream = &stream; + let Some(file) = files.get(&path) else { + let _ = write!( + stream, + "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + return; + }; + let (status, content_range, body) = match range { + Some((start, end)) => { + let end = end.min(file.len() - 1); + ( + "206 Partial Content", + format!("Content-Range: bytes {start}-{end}/{}\r\n", file.len()), + &file[start..=end], + ) + } + None => ("200 OK", String::new(), &file[..]), + }; + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Length: {}\r\n{content_range}Connection: close\r\n\r\n", + body.len() + ); + if method != "HEAD" { + let _ = stream.write_all(body); + } +} + +/// Arrow IPC file bytes holding two tables with ids 0 to 14. +fn ipc_file_bytes() -> Vec { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("trades.arrow"); + let first = checks::sample_table(0, 10); + let schema = checks::schema_of(&first); + write_tables_to_file_sync(&path, &[first, checks::sample_table(10, 5)], schema).unwrap(); + std::fs::read(&path).unwrap() +} + +#[test] +fn storage_reader_fetches_a_whole_file_over_http() { + let contents: Vec = (0..200_000u32).flat_map(|i| i.to_le_bytes()).collect(); + let base = serve(HashMap::from([("/data/a.bin".to_string(), contents.clone())])); + let runtime = checks::runtime(); + let _entered = runtime.enter(); + + let mut read = Vec::new(); + StorageReader::open(format!("{base}/data/a.bin")) + .unwrap() + .read_to_end(&mut read) + .unwrap(); + assert!(read == contents, "file contents match what was served"); +} + +#[test] +fn ipc_file_reader_reads_batches_with_ranged_requests_over_http() { + let base = serve(HashMap::from([( + "/ipc/trades.arrow".to_string(), + ipc_file_bytes(), + )])); + let runtime = checks::runtime(); + let _entered = runtime.enter(); + + let reader = FileTableReader::open(format!("{base}/ipc/trades.arrow")).unwrap(); + assert_eq!(reader.num_batches(), 2); + let tables: Vec = (0..2).map(|i| reader.read_batch(i).unwrap()).collect(); + assert_eq!(checks::ids(&tables), (0..15).collect::>()); +} + +#[test] +fn a_missing_path_reports_not_found() { + let base = serve(HashMap::new()); + let runtime = checks::runtime(); + let _entered = runtime.enter(); + checks::a_missing_object_reports_not_found(&base); +}