diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e5ead2..ac6e9b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ Notable changes are recorded from 0.5.0 onward. - Added `SyncWebSocketTableReader` and `SyncWebSocketTableWriter` under the `websocket` feature for blocking plaintext WebSocket feeds, with the same wire format, `DecodeLimits` and `Compression` options as the async types. - Added `SyncWebSocketTransport`, `SyncWsRead` and `SyncWsWrite` for blocking WebSocket I/O, including complete text and binary message reads. - 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. ### Breaking Changes diff --git a/rust/src/lib.rs b/rust/src/lib.rs index ee344dd..2e7de89 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -566,6 +566,9 @@ pub mod models { #[cfg(feature = "object_storage")] pub mod object_storage; +/// The Tokio runtime that object storage requests run on. +pub mod runtime; + /// FlatBuffers-compiled Arrow IPC metadata support. pub mod arrow { /// Flatbuffers Arrow file metadata diff --git a/rust/src/models/readers/object_storage.rs b/rust/src/models/readers/object_storage.rs index cc3bb83..1cfd3d1 100644 --- a/rust/src/models/readers/object_storage.rs +++ b/rust/src/models/readers/object_storage.rs @@ -45,9 +45,9 @@ use futures_util::TryStreamExt; use object_store::{ObjectMeta, ObjectStoreExt}; #[cfg(feature = "object_storage")] -use crate::object_storage::{ - ObjectLocation, current_handle, io_error, object_url, resolve, run_task, -}; +use crate::object_storage::{ObjectLocation, io_error, object_url, resolve, run_task}; +#[cfg(feature = "object_storage")] +use crate::runtime; /// Sequential reader over a local file or a fetched object. /// @@ -69,7 +69,7 @@ impl StorageReader { #[cfg(feature = "object_storage")] if let Some(url) = object_url(path.as_ref()) { let ObjectLocation { store, path, .. } = resolve(&url)?; - let bytes = run_task(¤t_handle()?, async move { + let bytes = run_task(&runtime::handle()?, async move { store.get(&path).await?.bytes().await })? .map_err(io_error)?; @@ -162,7 +162,7 @@ impl StorageSource { let location = resolve(&url)?; let store = Arc::clone(&location.store); let object = location.path.clone(); - let meta = run_task(¤t_handle()?, async move { store.head(&object).await })? + let meta = run_task(&runtime::handle()?, async move { store.head(&object).await })? .map_err(io_error)?; return Ok(Self::Object { location, @@ -195,7 +195,7 @@ impl StorageSource { let range = offset..offset + buf.len() as u64; let store = Arc::clone(&location.store); let object = location.path.clone(); - let bytes = run_task(¤t_handle()?, async move { + let bytes = run_task(&runtime::handle()?, async move { store.get_range(&object, range).await })? .map_err(io_error)?; @@ -232,7 +232,7 @@ pub fn list_dir>(dir: P) -> io::Result> { #[cfg(feature = "object_storage")] if let Some(url) = object_url(dir.as_ref()) { let ObjectLocation { store, path, .. } = resolve(&url)?; - let listing = run_task(¤t_handle()?, async move { + let listing = run_task(&runtime::handle()?, async move { store.list_with_delimiter(Some(&path)).await })? .map_err(io_error)?; @@ -261,7 +261,7 @@ pub fn list_files>(dir: P) -> io::Result> { let location = resolve(&url)?; let store = Arc::clone(&location.store); let prefix = location.path.clone(); - let objects: Vec = run_task(¤t_handle()?, async move { + let objects: Vec = run_task(&runtime::handle()?, async move { store.list(Some(&prefix)).try_collect().await })? .map_err(io_error)?; diff --git a/rust/src/object_storage/connection.rs b/rust/src/object_storage/connection.rs index f423079..dd44ba1 100644 --- a/rust/src/object_storage/connection.rs +++ b/rust/src/object_storage/connection.rs @@ -35,10 +35,10 @@ use object_store::path::Path as ObjectPath; #[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))] use object_store::{ClientConfigKey, ClientOptions}; use object_store::{ObjectStore, ObjectStoreScheme}; -use tokio::runtime::Handle; use url::{Position, Url}; use crate::object_storage::error::io_error; +use crate::runtime; /// Default size of each multipart upload part, in bytes. S3 requires every /// part except the last to be at least this size, and it is the minimum @@ -180,10 +180,10 @@ pub(crate) fn resolve(url: &str) -> io::Result { }); } - let runtime = Handle::try_current() - .map(|handle| handle.id().to_string()) - .unwrap_or_default(); - let key = format!("{}|{prefix}|{runtime}", &parsed[..Position::BeforePath]); + // Requests made through the store run on the runtime from + // `runtime::handle`, and the key holds that runtime's identifier. + let runtime_id = runtime::handle()?.id().to_string(); + let key = format!("{}|{prefix}|{runtime_id}", &parsed[..Position::BeforePath]); let mut stores = STORES.lock().expect("object storage store cache lock"); let store = match stores.get(&key) { diff --git a/rust/src/object_storage/mod.rs b/rust/src/object_storage/mod.rs index 6f191d3..fc57497 100644 --- a/rust/src/object_storage/mod.rs +++ b/rust/src/object_storage/mod.rs @@ -54,15 +54,15 @@ //! still bounded by the client's `connect_timeout`. //! //! ## Runtime -//! Object storage requests run as Tokio tasks on the caller's multi-thread -//! runtime, and the runtime's worker threads perform the I/O. +//! Object storage requests run as Tokio tasks on a multi-thread runtime, and +//! the runtime's worker threads perform the I/O. //! //! - The async adapters in `models::streams::object_store` await their //! requests within the caller's task. //! - The synchronous readers and writers spawn each request as a task and -//! wait for its result. They find the runtime with `Handle::try_current`, -//! which requires the calling thread to be within the runtime's context, -//! for example after `Handle::enter`. +//! wait for its result. The task runs on the runtime current on the +//! calling thread, or on the process runtime otherwise, see +//! [`crate::runtime`]. //! - Async code uses the async adapters. A synchronous call made from async //! code holds one of the runtime's workers until its request completes. //! - The parallel chunked reads and writes enter the caller's runtime on @@ -86,4 +86,4 @@ pub use upload::ObjectUpload; pub(crate) use connection::{object_url, resolve}; pub(crate) use error::io_error; -pub(crate) use runtime::{current_handle, run_task}; +pub(crate) use runtime::run_task; diff --git a/rust/src/object_storage/runtime.rs b/rust/src/object_storage/runtime.rs index a5d87ec..9debae5 100644 --- a/rust/src/object_storage/runtime.rs +++ b/rust/src/object_storage/runtime.rs @@ -4,20 +4,17 @@ // 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 on the caller's runtime +//! # Object storage on the IO runtime //! -//! Object storage requests run as Tokio tasks on the caller's multi-thread -//! runtime. The synchronous readers and writers spawn each request with -//! [`run_task`] and wait for its result, and multipart uploads spawn their -//! part uploads on the same runtime. +//! Object storage requests run as Tokio tasks on the runtime from +//! [`crate::runtime::handle`]: the runtime current on the calling thread, or +//! the process runtime otherwise. The synchronous readers and +//! writers spawn each request with [`run_task`] and wait for its result, and +//! multipart uploads spawn their part uploads on the same runtime. //! -//! The runtime is the one current on the calling thread, found with -//! `Handle::try_current`. Synchronous calls therefore come from a thread -//! within the runtime's context, for example after `Handle::enter`, and -//! [`current_handle`] reports an error otherwise. Async code uses the async -//! adapters in `models::streams::object_store`, because a synchronous call -//! from async code holds one of the runtime's workers until its request -//! completes. +//! Async code uses the async adapters in `models::streams::object_store`, +//! because a synchronous call from async code holds one of the runtime's +//! workers until its request completes. use std::future::Future; use std::io; @@ -25,20 +22,6 @@ use std::sync::mpsc; use tokio::runtime::Handle; -/// Handle to the caller's Tokio runtime. -/// -/// ## Errors -/// Returns `ErrorKind::Other` when the calling thread is outside a Tokio -/// runtime context. -pub(crate) fn current_handle() -> io::Result { - Handle::try_current().map_err(|_| { - io::Error::new( - io::ErrorKind::Other, - "object storage URLs require a Tokio runtime context on the calling thread", - ) - }) -} - /// Runs `future` as a task on `runtime` and returns its output to the /// calling thread, which waits on a channel while the runtime's workers run /// the task. diff --git a/rust/src/object_storage/upload.rs b/rust/src/object_storage/upload.rs index f41269e..fb887a1 100644 --- a/rust/src/object_storage/upload.rs +++ b/rust/src/object_storage/upload.rs @@ -28,7 +28,8 @@ use tokio::task::JoinHandle; use crate::object_storage::connection::ObjectLocation; use crate::object_storage::error::io_error; -use crate::object_storage::runtime::{current_handle, run_task}; +use crate::object_storage::runtime::run_task; +use crate::runtime; /// Upload of one object, driven by synchronous writes. /// @@ -59,7 +60,7 @@ impl ObjectUpload { pub(crate) fn new(location: ObjectLocation) -> io::Result { Ok(Self { location, - runtime: current_handle()?, + runtime: runtime::handle()?, pending: Vec::new(), multipart: None, parts: VecDeque::new(), diff --git a/rust/src/runtime.rs b/rust/src/runtime.rs new file mode 100644 index 0000000..74c02f4 --- /dev/null +++ b/rust/src/runtime.rs @@ -0,0 +1,115 @@ +// 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/. + +//! # Runtime +//! +//! The Tokio runtime that object storage requests run on. +//! +//! ## Context +//! Object storage requests are async network IO through `object_store`, and +//! run as Tokio tasks. `StorageReader` and `StorageWriter` wait for the +//! results of their requests. The requests run on the runtime current on the +//! calling thread when there is one, and on the process runtime otherwise. +//! Lightstream and the application share the process runtime, and one +//! multi-thread runtime therefore performs the IO of both. +//! +//! ## Details +//! - Applications that build their own runtime install it with [`init_with`] +//! before their first IO. +//! - Without an installed runtime, [`handle`] initialises a default +//! multi-thread runtime on its first call, with its worker threads named +//! `lightstream-io`. +//! - The process runtime lives for the lifetime of the process. +//! - WebAssembly targets have no default runtime, and their applications +//! install one with [`init_with`]. + +use std::io; +use std::sync::{Mutex, OnceLock}; + +use tokio::runtime::{Handle, Runtime}; + +/// The process runtime, initialised once by `init_with` or `handle`. +static PROCESS_RUNTIME: OnceLock = OnceLock::new(); + +/// Serialises the initialisation of `PROCESS_RUNTIME` across threads, +/// ensuring that `init` runs once. +static INITIALISING: Mutex<()> = Mutex::new(()); + +/// Returns the handle of the process runtime, initialising it with `init` +/// when it does not exist. +/// +/// `init` runs once in the process, and only when no runtime has been +/// installed. A runtime installed earlier, including the default runtime +/// from [`handle`], is returned unchanged and `init` does not run. +/// +/// ## Errors +/// Returns the error from `init`. +pub fn init_with(init: impl FnOnce() -> io::Result) -> io::Result { + if let Some(runtime) = PROCESS_RUNTIME.get() { + return Ok(runtime.handle().clone()); + } + let _initialising = INITIALISING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = PROCESS_RUNTIME.get() { + return Ok(runtime.handle().clone()); + } + let runtime = init()?; + let runtime = PROCESS_RUNTIME.get_or_init(|| runtime); + Ok(runtime.handle().clone()) +} + +/// Returns the handle of the runtime that object storage requests run on. +/// +/// The runtime current on the calling thread is returned first, followed by +/// the process runtime. Without either, the default process runtime is +/// initialised. +/// +/// ## Errors +/// Returns `ErrorKind::Other` when the default runtime fails to build, or on +/// WebAssembly targets when no runtime has been installed. +pub fn handle() -> io::Result { + if let Ok(current) = Handle::try_current() { + return Ok(current); + } + init_with(default_runtime) +} + +/// Builds the default multi-thread runtime. +#[cfg(not(target_family = "wasm"))] +fn default_runtime() -> io::Result { + tokio::runtime::Builder::new_multi_thread() + .thread_name("lightstream-io") + .enable_all() + .build() +} + +#[cfg(all(test, not(target_family = "wasm")))] +mod tests { + use super::*; + + #[test] + fn processes_install_one_runtime() { + let first = init_with(default_runtime).unwrap(); + let second = init_with(|| panic!("the process runtime is already installed")).unwrap(); + assert_eq!(first.id(), second.id()); + assert_eq!(handle().unwrap().id(), first.id()); + } + + #[test] + fn runtimes_current_on_the_calling_thread_come_first() { + let current = tokio::runtime::Builder::new_current_thread().build().unwrap(); + let _entered = current.enter(); + assert_eq!(handle().unwrap().id(), current.handle().id()); + } +} + +/// WebAssembly targets have no default runtime. +#[cfg(target_family = "wasm")] +fn default_runtime() -> io::Result { + Err(io::Error::new( + io::ErrorKind::Other, + "Lightstream IO on WebAssembly requires a runtime installed with `runtime::init_with`", + )) +} diff --git a/rust/tests/object_storage_roundtrip.rs b/rust/tests/object_storage_roundtrip.rs index 1a2005a..792c53c 100644 --- a/rust/tests/object_storage_roundtrip.rs +++ b/rust/tests/object_storage_roundtrip.rs @@ -28,14 +28,19 @@ fn run(check: fn(&str)) { } #[test] -fn object_urls_outside_a_runtime_context_report_an_error() { - let err = StorageReader::open(format!("{BASE}/no-runtime/a.bin")) - .err() - .expect("no runtime context"); - assert!( - err.to_string().contains("Tokio runtime context"), - "got {err}" - ); +fn object_urls_outside_a_runtime_context_run_on_the_process_runtime() { + use std::io::{Read, Write}; + + use lightstream::models::writers::object_storage::StorageWriter; + + let url = format!("{BASE}/no-runtime/a.bin"); + let mut writer = StorageWriter::create(&url).unwrap(); + writer.write_all(b"process runtime").unwrap(); + writer.flush().unwrap(); + + let mut read = Vec::new(); + StorageReader::open(&url).unwrap().read_to_end(&mut read).unwrap(); + assert_eq!(read, b"process runtime"); } #[test]