Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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`.
Expand Down
9 changes: 9 additions & 0 deletions docs/Redis.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://[[<username>]:<passwd>@]<hostname>[:port][/?db=<db>]`.

Expand Down
10 changes: 9 additions & 1 deletion src/cache/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;

Expand Down Expand Up @@ -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}");
Expand All @@ -153,6 +157,7 @@ pub fn build_single_cache(
*db,
key_prefix,
*ttl,
io_timeout,
)
}
(None, Some(urls), None) => {
Expand All @@ -164,6 +169,7 @@ pub fn build_single_cache(
*db,
key_prefix,
*ttl,
io_timeout,
)
}
(None, None, Some(url)) => {
Expand All @@ -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"),
}
Expand Down Expand Up @@ -470,6 +476,7 @@ mod test {
0,
"test-prefix",
0,
None,
)
.expect("Failed to create Redis cache operator");

Expand All @@ -496,6 +503,7 @@ mod test {
0,
"test-prefix",
0,
None,
)
.expect("Failed to create Redis cache operator");

Expand Down
73 changes: 66 additions & 7 deletions src/cache/redis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Operator> {
pub fn build_from_url(
url: &str,
key_prefix: &str,
ttl: u64,
io_timeout: Option<Duration>,
) -> Result<Operator> {
let parsed = Url::parse(url)?;

let mut builder = Redis::default()
Expand All @@ -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.
Expand All @@ -59,10 +64,11 @@ impl RedisCache {
db: u32,
key_prefix: &str,
ttl: u64,
io_timeout: Option<Duration>,
) -> Result<Operator> {
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.
Expand All @@ -73,10 +79,11 @@ impl RedisCache {
db: u32,
key_prefix: &str,
ttl: u64,
io_timeout: Option<Duration>,
) -> Result<Operator> {
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(
Expand All @@ -86,6 +93,7 @@ impl RedisCache {
db: u32,
key_prefix: &str,
ttl: u64,
io_timeout: Option<Duration>,
) -> Result<Operator> {
builder = builder
.username(username.unwrap_or_default())
Expand All @@ -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<Duration>) -> Result<Operator> {
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();
}
}
70 changes: 70 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -442,6 +443,8 @@ pub struct RedisCacheConfig {
#[serde(default, alias = "expiration")]
pub ttl: u64,

pub io_timeout_secs: Option<NonZeroU64>,

#[serde(default)]
pub key_prefix: String,

Expand Down Expand Up @@ -954,6 +957,9 @@ fn config_from_env() -> Result<EnvConfig> {
.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")
Expand All @@ -967,6 +973,7 @@ fn config_from_env() -> Result<EnvConfig> {
password,
db,
ttl,
io_timeout_secs,
key_prefix,
rw_mode,
})
Expand Down Expand Up @@ -1728,6 +1735,67 @@ 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::<FileConfig>(&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() {
fn parse_with_timeout(value: Option<&str>) -> Result<EnvConfig> {
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),
(Some("1"), Some(1)),
(Some("37"), Some(37)),
(Some("18446744073709551615"), Some(u64::MAX)),
] {
let result = parse_with_timeout(value);
assert_eq!(
result.unwrap().cache.redis.unwrap().io_timeout_secs,
expected.and_then(NonZeroU64::new)
);
}

for value in ["0", "invalid", "-1", "18446744073709551616"] {
Comment thread
aw1cks marked this conversation as resolved.
Resolved
let result = parse_with_timeout(Some(value));
assert!(result.is_err(), "accepted Redis IO timeout {value:?}");
}
}

#[test]
fn config_overrides() {
let env_conf = EnvConfig {
Expand Down Expand Up @@ -1779,6 +1847,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()
}),
Expand Down Expand Up @@ -2859,6 +2928,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,
}),
Expand Down
Loading