From 44d2bb31bf00caebc25197c06e8c902683222331 Mon Sep 17 00:00:00 2001 From: Alex Wicks Date: Wed, 28 Oct 2026 11:45:41 +0000 Subject: [PATCH 1/3] redis: add configurable IO timeouts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A stalled Redis connection can keep a disk-cache miss waiting for the pool even though the compiler could run locally. Install an OpenDAL TimeoutLayer for Redis reads and writes only when a positive deadline is configured. Read it from the same source as the endpoint; unset preserves the existing behavior. Use a silent listener and a paused clock to distinguish the configured IO deadline from the cluster client’s own connection timeout. --- Cargo.lock | 11 ++++ Cargo.toml | 9 +++- docs/Configuration.md | 4 ++ docs/Redis.md | 9 ++++ src/cache/cache.rs | 10 +++- src/cache/redis.rs | 73 ++++++++++++++++++++++--- src/config.rs | 123 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 230 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 92016a9fc1..3eedc11cc7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2254,6 +2254,16 @@ dependencies = [ "opendal-core", ] +[[package]] +name = "opendal-layer-timeout" +version = "0.58.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a704141924500f3803c05ed871b53305d2a2f11cb5ef20160c3ee688a1857f66" +dependencies = [ + "opendal-core", + "tokio", +] + [[package]] name = "opendal-service-azblob" version = "0.58.2" @@ -3474,6 +3484,7 @@ dependencies = [ "opendal-http-transport-reqwest", "opendal-layer-logging", "opendal-layer-retry", + "opendal-layer-timeout", "openssl", "predicates", "rand 0.8.8", diff --git a/Cargo.toml b/Cargo.toml index 21bcc8005d..d213ef6509 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,7 @@ opendal = { version = "0.58.1", optional = true, default-features = false } opendal-http-transport-reqwest = { version = "0.58.1", optional = true } opendal-layer-logging = { version = "0.58.1", optional = true } opendal-layer-retry = { version = "0.58.1", optional = true } +opendal-layer-timeout = { version = "0.58.1", optional = true } openssl = { version = "0.10.75", optional = true } rand = "0.8.4" regex = "1.10.3" @@ -157,6 +158,7 @@ thirtyfour = { version = "0.38.1", default-features = false, features = [ "reqwest", "rustls", ] } +tokio = { version = "1", features = ["test-util"] } [target.'cfg(unix)'.dependencies] daemonix = "0.1" @@ -225,7 +227,12 @@ oss = [ "opendal-http-transport-reqwest", "reqwest", ] -redis = ["url", "opendal/services-redis", "opendal-layer-logging"] +redis = [ + "url", + "opendal/services-redis", + "opendal-layer-logging", + "opendal-layer-timeout", +] reqwest = ["dep:reqwest", "dep:webpki-root-certs"] s3 = [ "opendal/services-s3", diff --git a/docs/Configuration.md b/docs/Configuration.md index 50970fd4e7..2b5e36c7b3 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -135,6 +135,9 @@ db = 1 # Entry expiration time in seconds. Default is 0 (never expire) expiration = 3600 key_prefix = "/custom/prefix/if/need" +# Optional positive IO deadline in seconds, including connection-pool acquisition. +# Unset preserves the Redis backend's existing timeouts. +# io_timeout_secs = 2 [cache.s3] bucket = "name" @@ -286,6 +289,7 @@ will default to `us-east-1`. * `SCCACHE_REDIS_DB` redis database (optional, default is 0). * `SCCACHE_REDIS_EXPIRATION` / `SCCACHE_REDIS_TTL` ttl for redis cache, don't set for default behavior. * `SCCACHE_REDIS_KEY_PREFIX` key prefix (optional). +* `SCCACHE_REDIS_IO_TIMEOUT_SECS` optional positive integer deadline in seconds for Redis read/write IO, including connection-pool acquisition. Unset preserves existing backend timeouts; see [Redis.md](Redis.md). * `SCCACHE_REDIS_RW_MODE` allows to use redis backend in read-only mode if set to `READ_ONLY` The full url appears then as `redis://user:passwd@1.2.3.4:6379/?db=1`. diff --git a/docs/Redis.md b/docs/Redis.md index 103169fdb4..cb03159ea8 100644 --- a/docs/Redis.md +++ b/docs/Redis.md @@ -23,6 +23,15 @@ Set `SCCACHE_REDIS_EXPIRATION` in seconds if you don't want your cache to live f Set `SCCACHE_REDIS_KEY_PREFIX` if you want to prefix all cache keys. This can be useful when sharing a Redis instance with another application or cache. +Set `SCCACHE_REDIS_IO_TIMEOUT_SECS` to a positive integer number of seconds to +limit Redis read/write IO, including connection-pool acquisition. For example, +`SCCACHE_REDIS_IO_TIMEOUT_SECS=2` makes an unavailable Redis tier fail faster. +If the Redis endpoint is configured in a file, set `io_timeout_secs` in the +same `[cache.redis]` section instead. +When unset, existing Redis backend timeouts are unchanged. The deadline applies +to each IO operation, not to the total compilation or the entire multilevel +lookup. Restart the sccache server after changing it. + `SCCACHE_REDIS` is deprecated for security reasons, use `SCCACHE_REDIS_ENDPOINT` instead. See mozilla/sccache#2083 for details. If you really want to use `SCCACHE_REDIS`, you should URL in format `redis://[[]:@][:port][/?db=]`. diff --git a/src/cache/cache.rs b/src/cache/cache.rs index c0143ed59d..380d1dd998 100644 --- a/src/cache/cache.rs +++ b/src/cache/cache.rs @@ -39,6 +39,8 @@ use crate::config::Config; use crate::config::{self, CacheType}; use std::sync::Arc; +#[cfg(feature = "redis")] +use std::time::Duration; use crate::errors::*; @@ -141,8 +143,10 @@ pub fn build_single_cache( url, ttl, key_prefix, + io_timeout_secs, rw_mode, }) => { + let io_timeout = io_timeout_secs.map(|secs| Duration::from_secs(secs.get())); let storage = match (endpoint, cluster_endpoints, url) { (Some(url), None, None) => { debug!("Init redis single-node cache with url {url}"); @@ -153,6 +157,7 @@ pub fn build_single_cache( *db, key_prefix, *ttl, + io_timeout, ) } (None, Some(urls), None) => { @@ -164,6 +169,7 @@ pub fn build_single_cache( *db, key_prefix, *ttl, + io_timeout, ) } (None, None, Some(url)) => { @@ -172,7 +178,7 @@ pub fn build_single_cache( bail!("`username`, `password` and `db` has no effect when `url` is set. Please use `endpoint` or `cluster_endpoints` for new API accessing"); } - RedisCache::build_from_url(url, key_prefix, *ttl) + RedisCache::build_from_url(url, key_prefix, *ttl, io_timeout) } _ => bail!("Only one of `endpoint`, `cluster_endpoints`, `url` must be set"), } @@ -470,6 +476,7 @@ mod test { 0, "test-prefix", 0, + None, ) .expect("Failed to create Redis cache operator"); @@ -496,6 +503,7 @@ mod test { 0, "test-prefix", 0, + None, ) .expect("Failed to create Redis cache operator"); diff --git a/src/cache/redis.rs b/src/cache/redis.rs index eb2e6b9ad5..2e3606755c 100644 --- a/src/cache/redis.rs +++ b/src/cache/redis.rs @@ -17,6 +17,7 @@ use crate::errors::*; use opendal::Operator; use opendal::services::Redis; use opendal_layer_logging::LoggingLayer; +use opendal_layer_timeout::TimeoutLayer; use std::collections::HashMap; use std::time::Duration; use url::Url; @@ -26,7 +27,12 @@ pub struct RedisCache; impl RedisCache { /// Create a new `RedisCache` for the given URL. - pub fn build_from_url(url: &str, key_prefix: &str, ttl: u64) -> Result { + pub fn build_from_url( + url: &str, + key_prefix: &str, + ttl: u64, + io_timeout: Option, + ) -> Result { let parsed = Url::parse(url)?; let mut builder = Redis::default() @@ -47,8 +53,7 @@ impl RedisCache { .map(|v| v.parse().unwrap_or_default()) .unwrap_or_default()); - let op = Operator::new(builder)?.layer(LoggingLayer::default()); - Ok(op) + Self::build_operator(builder, io_timeout) } /// Create a new `RedisCache` for the given single instance. @@ -59,10 +64,11 @@ impl RedisCache { db: u32, key_prefix: &str, ttl: u64, + io_timeout: Option, ) -> Result { let builder = Redis::default().endpoint(endpoint); - Self::build_common(builder, username, password, db, key_prefix, ttl) + Self::build_common(builder, username, password, db, key_prefix, ttl, io_timeout) } /// Create a new `RedisCache` for the given cluster. @@ -73,10 +79,11 @@ impl RedisCache { db: u32, key_prefix: &str, ttl: u64, + io_timeout: Option, ) -> Result { let builder = Redis::default().cluster_endpoints(endpoints); - Self::build_common(builder, username, password, db, key_prefix, ttl) + Self::build_common(builder, username, password, db, key_prefix, ttl, io_timeout) } fn build_common( @@ -86,6 +93,7 @@ impl RedisCache { db: u32, key_prefix: &str, ttl: u64, + io_timeout: Option, ) -> Result { builder = builder .username(username.unwrap_or_default()) @@ -96,7 +104,58 @@ impl RedisCache { builder = builder.default_ttl(Duration::from_secs(ttl)); } - let op = Operator::new(builder)?.layer(LoggingLayer::default()); - Ok(op) + Self::build_operator(builder, io_timeout) + } + + fn build_operator(builder: Redis, io_timeout: Option) -> Result { + let mut op = Operator::new(builder)?; + if let Some(io_timeout) = io_timeout { + op = op.layer(TimeoutLayer::new().with_io_timeout(io_timeout)); + } + Ok(op.layer(LoggingLayer::default())) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[tokio::test(start_paused = true)] + async fn test_io_timeout_bounds_connection_acquisition() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("redis://{}", listener.local_addr().unwrap()); + let stalled_server = tokio::spawn(async move { + let mut connections = Vec::new(); + loop { + connections.push(listener.accept().await.unwrap().0); + } + }); + + let timeout = Some(Duration::from_millis(50)); + // Shorter than the cluster client's own one-second connection timeout. + let watchdog = Duration::from_millis(100); + let operators = [ + RedisCache::build_single(&endpoint, None, None, 0, "", 0, timeout).unwrap(), + RedisCache::build_cluster(&endpoint, None, None, 0, "", 0, timeout).unwrap(), + RedisCache::build_from_url(&endpoint, "", 0, timeout).unwrap(), + ]; + + for operator in operators { + let error = tokio::time::timeout(watchdog, operator.read("missing")) + .await + .expect("Redis read exceeded the configured IO deadline") + .unwrap_err(); + assert_eq!(error.kind(), opendal::ErrorKind::Unexpected); + assert!(error.is_temporary()); + + let error = tokio::time::timeout(watchdog, operator.write("key", "value")) + .await + .expect("Redis write exceeded the configured IO deadline") + .unwrap_err(); + assert_eq!(error.kind(), opendal::ErrorKind::Unexpected); + assert!(error.is_temporary()); + } + + stalled_server.abort(); } } diff --git a/src/config.rs b/src/config.rs index 3a3a03d521..fabc2b49ad 100644 --- a/src/config.rs +++ b/src/config.rs @@ -28,6 +28,7 @@ use serde::{ use serial_test::serial; use std::env; use std::io::{Read, Write}; +use std::num::NonZeroU64; use std::path::{Path, PathBuf}; use std::result::Result as StdResult; use std::str::FromStr; @@ -442,6 +443,8 @@ pub struct RedisCacheConfig { #[serde(default, alias = "expiration")] pub ttl: u64, + pub io_timeout_secs: Option, + #[serde(default)] pub key_prefix: String, @@ -954,6 +957,9 @@ fn config_from_env() -> Result { .transpose()? .unwrap_or(DEFAULT_REDIS_CACHE_TTL); + let io_timeout_secs = + number_from_env_var("SCCACHE_REDIS_IO_TIMEOUT_SECS").transpose()?; + let key_prefix = key_prefix_from_env_var("SCCACHE_REDIS_KEY_PREFIX"); let rw_mode = cache_mode_from_env_var("SCCACHE_REDIS_RW_MODE") @@ -967,6 +973,7 @@ fn config_from_env() -> Result { password, db, ttl, + io_timeout_secs, key_prefix, rw_mode, }) @@ -1728,6 +1735,120 @@ fn test_skip_cache_check_from_env() { ); } +#[test] +fn test_redis_io_timeout_from_file() { + for (setting, expected) in [ + ("", None), + ("io_timeout_secs = 1", Some(1)), + ("io_timeout_secs = 37", Some(37)), + ] { + let config: FileConfig = toml::from_str(&format!( + "[cache.redis]\nendpoint = \"redis://localhost:6379\"\n{setting}" + )) + .unwrap(); + assert_eq!( + config.cache.redis.unwrap().io_timeout_secs, + expected.and_then(NonZeroU64::new) + ); + } +} + +#[test] +fn test_redis_io_timeout_from_file_invalid() { + for value in ["0", "-1", "\"invalid\"", "\"1\"", "1.5"] { + let result = toml::from_str::(&format!( + "[cache.redis]\nendpoint = \"redis://localhost:6379\"\nio_timeout_secs = {value}" + )); + assert!(result.is_err(), "accepted io_timeout_secs = {value}"); + } +} + +#[test] +#[serial(config_from_env)] +fn test_redis_io_timeout_from_env() { + for (value, expected) in [ + (None, None), + (Some(""), None), + (Some("1"), Some(1)), + (Some("37"), Some(37)), + (Some("18446744073709551615"), Some(u64::MAX)), + ] { + unsafe { + env::set_var("SCCACHE_REDIS_ENDPOINT", "redis://localhost:6379"); + match value { + Some(value) => env::set_var("SCCACHE_REDIS_IO_TIMEOUT_SECS", value), + None => env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"), + } + } + let result = config_from_env(); + unsafe { + env::remove_var("SCCACHE_REDIS_ENDPOINT"); + env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"); + } + assert_eq!( + result.unwrap().cache.redis.unwrap().io_timeout_secs, + expected.and_then(NonZeroU64::new) + ); + } + + for value in ["0", "invalid", "-1", "18446744073709551616"] { + unsafe { + env::set_var("SCCACHE_REDIS_ENDPOINT", "redis://localhost:6379"); + env::set_var("SCCACHE_REDIS_IO_TIMEOUT_SECS", value); + } + let result = config_from_env(); + unsafe { + env::remove_var("SCCACHE_REDIS_ENDPOINT"); + env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"); + } + assert!(result.is_err(), "accepted Redis IO timeout {value:?}"); + } +} + +#[test] +#[serial(config_from_env)] +fn test_redis_io_timeout_env_file_precedence() { + for endpoint in [None, Some("redis://env:6379")] { + for timeout in [None, Some("7")] { + unsafe { + env::remove_var("SCCACHE_REDIS"); + env::remove_var("SCCACHE_REDIS_CLUSTER_ENDPOINTS"); + match endpoint { + Some(value) => env::set_var("SCCACHE_REDIS_ENDPOINT", value), + None => env::remove_var("SCCACHE_REDIS_ENDPOINT"), + } + match timeout { + Some(value) => env::set_var("SCCACHE_REDIS_IO_TIMEOUT_SECS", value), + None => env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"), + } + } + let result = config_from_env(); + unsafe { + env::remove_var("SCCACHE_REDIS_ENDPOINT"); + env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"); + } + let file_config: FileConfig = toml::from_str( + "[cache.redis]\nendpoint = \"redis://file:6379\"\nio_timeout_secs = 9", + ) + .unwrap(); + let config = Config::from_env_and_file_configs(result.unwrap(), file_config).unwrap(); + let redis = config.cache_configs.redis.unwrap(); + assert_eq!( + redis.endpoint.as_deref(), + Some(endpoint.unwrap_or("redis://file:6379")) + ); + assert_eq!( + redis.io_timeout_secs, + if endpoint.is_some() { + timeout.map(|_| NonZeroU64::new(7).unwrap()) + } else { + NonZeroU64::new(9) + } + ); + } + } +} + #[test] fn config_overrides() { let env_conf = EnvConfig { @@ -1779,6 +1900,7 @@ fn config_overrides() { redis: Some(RedisCacheConfig { url: Some("myredisurl".to_owned()), ttl: 25 * 3600, + io_timeout_secs: NonZeroU64::new(9), key_prefix: String::new(), ..Default::default() }), @@ -2859,6 +2981,7 @@ key_prefix = "cosprefix" password: Some("new_passwd".to_owned()), db: 12, ttl: 24 * 3600, + io_timeout_secs: None, key_prefix: "/my/redis/cache".into(), rw_mode: CacheModeConfig::ReadWrite, }), From eb321c6ad74127572f3675f2e41879a3a9d98092 Mon Sep 17 00:00:00 2001 From: Alex Wicks Date: Thu, 29 Oct 2026 22:39:30 +0000 Subject: [PATCH 2/3] redis: deduplicate timeout test environment setup --- src/config.rs | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/config.rs b/src/config.rs index fabc2b49ad..d9e55f0079 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1766,6 +1766,16 @@ fn test_redis_io_timeout_from_file_invalid() { #[test] #[serial(config_from_env)] fn test_redis_io_timeout_from_env() { + fn parse_with_timeout(value: Option<&str>) -> Result { + temp_env::with_vars( + [ + ("SCCACHE_REDIS_ENDPOINT", Some("redis://localhost:6379")), + ("SCCACHE_REDIS_IO_TIMEOUT_SECS", value), + ], + config_from_env, + ) + } + for (value, expected) in [ (None, None), (Some(""), None), @@ -1773,18 +1783,7 @@ fn test_redis_io_timeout_from_env() { (Some("37"), Some(37)), (Some("18446744073709551615"), Some(u64::MAX)), ] { - unsafe { - env::set_var("SCCACHE_REDIS_ENDPOINT", "redis://localhost:6379"); - match value { - Some(value) => env::set_var("SCCACHE_REDIS_IO_TIMEOUT_SECS", value), - None => env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"), - } - } - let result = config_from_env(); - unsafe { - env::remove_var("SCCACHE_REDIS_ENDPOINT"); - env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"); - } + let result = parse_with_timeout(value); assert_eq!( result.unwrap().cache.redis.unwrap().io_timeout_secs, expected.and_then(NonZeroU64::new) @@ -1792,15 +1791,7 @@ fn test_redis_io_timeout_from_env() { } for value in ["0", "invalid", "-1", "18446744073709551616"] { - unsafe { - env::set_var("SCCACHE_REDIS_ENDPOINT", "redis://localhost:6379"); - env::set_var("SCCACHE_REDIS_IO_TIMEOUT_SECS", value); - } - let result = config_from_env(); - unsafe { - env::remove_var("SCCACHE_REDIS_ENDPOINT"); - env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"); - } + let result = parse_with_timeout(Some(value)); assert!(result.is_err(), "accepted Redis IO timeout {value:?}"); } } From 4b4c8381e1af88fe8fe0021e11c6c07d3922bcb1 Mon Sep 17 00:00:00 2001 From: Alex Wicks Date: Thu, 29 Oct 2026 22:39:57 +0000 Subject: [PATCH 3/3] redis: drop redundant timeout precedence test --- src/config.rs | 44 -------------------------------------------- 1 file changed, 44 deletions(-) diff --git a/src/config.rs b/src/config.rs index d9e55f0079..a0a2e67fe4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1796,50 +1796,6 @@ fn test_redis_io_timeout_from_env() { } } -#[test] -#[serial(config_from_env)] -fn test_redis_io_timeout_env_file_precedence() { - for endpoint in [None, Some("redis://env:6379")] { - for timeout in [None, Some("7")] { - unsafe { - env::remove_var("SCCACHE_REDIS"); - env::remove_var("SCCACHE_REDIS_CLUSTER_ENDPOINTS"); - match endpoint { - Some(value) => env::set_var("SCCACHE_REDIS_ENDPOINT", value), - None => env::remove_var("SCCACHE_REDIS_ENDPOINT"), - } - match timeout { - Some(value) => env::set_var("SCCACHE_REDIS_IO_TIMEOUT_SECS", value), - None => env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"), - } - } - let result = config_from_env(); - unsafe { - env::remove_var("SCCACHE_REDIS_ENDPOINT"); - env::remove_var("SCCACHE_REDIS_IO_TIMEOUT_SECS"); - } - let file_config: FileConfig = toml::from_str( - "[cache.redis]\nendpoint = \"redis://file:6379\"\nio_timeout_secs = 9", - ) - .unwrap(); - let config = Config::from_env_and_file_configs(result.unwrap(), file_config).unwrap(); - let redis = config.cache_configs.redis.unwrap(); - assert_eq!( - redis.endpoint.as_deref(), - Some(endpoint.unwrap_or("redis://file:6379")) - ); - assert_eq!( - redis.io_timeout_secs, - if endpoint.is_some() { - timeout.map(|_| NonZeroU64::new(7).unwrap()) - } else { - NonZeroU64::new(9) - } - ); - } - } -} - #[test] fn config_overrides() { let env_conf = EnvConfig {