This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 2d06c82233 fix(services/redis): use millisecond default_ttl, fix
IPv6/schemeless endpoints, harden stat/range reads, and validate config (#8956)
2d06c82233 is described below
commit 2d06c82233b620f4b68b76211cb5b2692b06d5d2
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 08:51:38 2026 +0800
fix(services/redis): use millisecond default_ttl, fix IPv6/schemeless
endpoints, harden stat/range reads, and validate config (#8956)
* fix(services/redis): use millisecond default_ttl, fix IPv6/schemeless
endpoints, harden stat/range reads, and validate config
* fix(services/redis): tolerate nil GETRANGE replies from Redis-compatible
servers
---
core/services/redis/src/backend.rs | 280 ++++++++++++++++++++++++++++++++-----
core/services/redis/src/config.rs | 44 ++++++
core/services/redis/src/core.rs | 181 ++++++++++++++++++------
core/services/redis/src/docs.md | 5 +-
core/services/redis/src/reader.rs | 117 ++++++++++++----
5 files changed, 513 insertions(+), 114 deletions(-)
diff --git a/core/services/redis/src/backend.rs
b/core/services/redis/src/backend.rs
index bb254b0d21..45a73ce7ef 100644
--- a/core/services/redis/src/backend.rs
+++ b/core/services/redis/src/backend.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use std::borrow::Cow;
use std::path::PathBuf;
use std::sync::Arc;
@@ -118,9 +119,10 @@ impl RedisBuilder {
self
}
- /// Set the default ttl for redis services.
+ /// Set the default TTL for writes without a per-write expiration.
///
- /// If set, we will specify `EX` for write operations.
+ /// Positive durations are rounded up to whole milliseconds and sent via
+ /// `SET ... PX`. A zero duration disables expiration.
pub fn default_ttl(mut self, ttl: Duration) -> Self {
self.default_ttl = Some(ttl);
self
@@ -172,6 +174,14 @@ impl Builder for RedisBuilder {
.with_context("service", REDIS_SCHEME));
}
+ if self.config.connection_pool_max_size == Some(0) {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "connection_pool_max_size must be greater than zero",
+ )
+ .with_context("service", REDIS_SCHEME));
+ }
+
let default_ttl = match self.default_ttl {
Some(ttl) => Some(ttl),
None => self
@@ -180,6 +190,11 @@ impl Builder for RedisBuilder {
.map(signed_duration_to_duration)
.transpose()?,
};
+ if let Some(ttl) = default_ttl
+ && !ttl.is_zero()
+ {
+ encode_expiration(ttl).map_err(|err| err.with_context("service",
REDIS_SCHEME))?;
+ }
let root = normalize_root(
self.config
.root
@@ -223,7 +238,7 @@ impl Builder for RedisBuilder {
Client::open(self.get_connection_info(endpoint.clone())?).map_err(|e| {
Error::new(ErrorKind::ConfigInvalid, "invalid or
unsupported scheme")
.with_context("service", REDIS_SCHEME)
- .with_context("endpoint",
self.config.endpoint.as_ref().unwrap())
+ .with_context("endpoint", endpoint.clone())
.with_context("db", self.config.db.to_string())
.set_source(e)
})?;
@@ -263,45 +278,102 @@ impl Builder for RedisBuilder {
impl RedisBuilder {
fn get_connection_info(&self, endpoint: String) -> Result<ConnectionInfo> {
- let ep_url = endpoint.parse::<Uri>().map_err(|e| {
- Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
- .with_context("service", REDIS_SCHEME)
- .with_context("endpoint", endpoint)
- .set_source(e)
- })?;
-
- let con_addr = match ep_url.scheme_str() {
- Some("tcp") | Some("redis") | None => {
- let host = ep_url
- .host()
- .map(|h| h.to_string())
- .unwrap_or_else(|| "127.0.0.1".to_string());
- let port = ep_url.port_u16().unwrap_or(DEFAULT_REDIS_PORT);
- ConnectionAddr::Tcp(host, port)
+ let con_addr = if let Some(rest) = endpoint
+ .strip_prefix("unix://")
+ .or_else(|| endpoint.strip_prefix("redis+unix://"))
+ {
+ let path = if rest.starts_with('/') {
+ PathBuf::from(rest)
+ } else {
+ let ep_url = endpoint.parse::<Uri>().map_err(|e| {
+ Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
+ .with_context("service", REDIS_SCHEME)
+ .with_context("endpoint", endpoint.clone())
+ .set_source(e)
+ })?;
+ if ep_url.path().is_empty() {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "unix socket path is missing",
+ )
+ .with_context("service", REDIS_SCHEME)
+ .with_context("endpoint", endpoint));
+ }
+ PathBuf::from(ep_url.path())
+ };
+ ConnectionAddr::Unix(path)
+ } else if let Some(path) = endpoint
+ .strip_prefix("unix:")
+ .or_else(|| endpoint.strip_prefix("redis+unix:"))
+ {
+ if path.is_empty() {
+ return Err(
+ Error::new(ErrorKind::ConfigInvalid, "unix socket path is
missing")
+ .with_context("service", REDIS_SCHEME)
+ .with_context("endpoint", endpoint),
+ );
}
- Some("rediss") => {
+ ConnectionAddr::Unix(PathBuf::from(path))
+ } else {
+ let parsed_endpoint = if endpoint.contains("://") {
+ Cow::Borrowed(endpoint.as_str())
+ } else {
+ Cow::Owned(format!("tcp://{endpoint}"))
+ };
+
+ let ep_url = parsed_endpoint.parse::<Uri>().map_err(|e| {
+ Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
+ .with_context("service", REDIS_SCHEME)
+ .with_context("endpoint", endpoint.clone())
+ .set_source(e)
+ })?;
+
+ let extract_host = || -> Result<String> {
let host = ep_url
.host()
- .map(|h| h.to_string())
- .unwrap_or_else(|| "127.0.0.1".to_string());
- let port = ep_url.port_u16().unwrap_or(DEFAULT_REDIS_PORT);
- ConnectionAddr::TcpTls {
- host,
- port,
- insecure: false,
- tls_params: None,
+ .map(|h| {
+ h.strip_prefix('[')
+ .and_then(|s| s.strip_suffix(']'))
+ .unwrap_or(h)
+ })
+ .filter(|h| !h.is_empty())
+ .ok_or_else(|| {
+ Error::new(ErrorKind::ConfigInvalid, "endpoint host is
missing")
+ .with_context("service", REDIS_SCHEME)
+ .with_context("endpoint", endpoint.clone())
+ })?;
+ Ok(host.to_string())
+ };
+
+ match ep_url.scheme_str() {
+ Some("tcp") | Some("redis") => {
+ let host = extract_host()?;
+ let port = ep_url.port_u16().unwrap_or(DEFAULT_REDIS_PORT);
+ ConnectionAddr::Tcp(host, port)
}
- }
- Some("unix") | Some("redis+unix") => {
- let path = PathBuf::from(ep_url.path());
- ConnectionAddr::Unix(path)
- }
- Some(s) => {
- return Err(
- Error::new(ErrorKind::ConfigInvalid, "invalid or
unsupported scheme")
+ Some("rediss") => {
+ let host = extract_host()?;
+ let port = ep_url.port_u16().unwrap_or(DEFAULT_REDIS_PORT);
+ ConnectionAddr::TcpTls {
+ host,
+ port,
+ insecure: false,
+ tls_params: None,
+ }
+ }
+ Some(s) => {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "invalid or unsupported scheme",
+ )
+ .with_context("service", REDIS_SCHEME)
+ .with_context("scheme", s));
+ }
+ None => {
+ return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint
is invalid")
.with_context("service", REDIS_SCHEME)
- .with_context("scheme", s),
- );
+ .with_context("endpoint", endpoint));
+ }
}
};
@@ -507,4 +579,138 @@ mod tests {
);
}
}
+
+ #[test]
+ fn connection_info_handles_ipv6_and_schemeless_endpoints() -> Result<()> {
+ let builder = RedisBuilder::default();
+
+ let tcp_cases = [
+ ("[::1]", "::1", 6379),
+ ("[::1]:6380", "::1", 6380),
+ ("redis://[::1]:6380", "::1", 6380),
+ ("tcp://[::1]:6380", "::1", 6380),
+ ("redis://[::1]", "::1", 6379),
+ ("redis.internal", "redis.internal", 6379),
+ ("redis.internal:6380", "redis.internal", 6380),
+ ("127.0.0.1", "127.0.0.1", 6379),
+ ];
+
+ for (endpoint, expected_host, expected_port) in tcp_cases {
+ let info = builder.get_connection_info(endpoint.to_string())?;
+ assert_eq!(
+ info.addr(),
+ &ConnectionAddr::Tcp(expected_host.to_string(), expected_port),
+ "unexpected address for endpoint {endpoint}"
+ );
+ }
+
+ // Verify the unbracketed IPv6 host actually resolves via
ToSocketAddrs.
+ let ipv6_info =
builder.get_connection_info("redis://[::1]:6380".to_string())?;
+ let ConnectionAddr::Tcp(host, port) = ipv6_info.addr() else {
+ panic!("expected TCP address for IPv6 endpoint");
+ };
+ let addrs: Vec<_> =
std::net::ToSocketAddrs::to_socket_addrs(&(host.as_str(), *port))
+ .expect("unbracketed IPv6 host must resolve")
+ .collect();
+ assert!(
+ addrs
+ .iter()
+ .any(|addr| addr.ip().is_ipv6() && addr.port() == 6380)
+ );
+
+ let tls_cases = [
+ ("rediss://[::1]", "::1", 6379),
+ ("rediss://[::1]:6380", "::1", 6380),
+ ("rediss://redis.internal:6380", "redis.internal", 6380),
+ ];
+
+ for (endpoint, expected_host, expected_port) in tls_cases {
+ let info = builder.get_connection_info(endpoint.to_string())?;
+ assert_eq!(
+ info.addr(),
+ &ConnectionAddr::TcpTls {
+ host: expected_host.to_string(),
+ port: expected_port,
+ insecure: false,
+ tls_params: None,
+ },
+ "unexpected TLS address for endpoint {endpoint}"
+ );
+ }
+
+ for endpoint in [
+ "unix:///tmp/redis.sock",
+ "redis+unix:///tmp/redis.sock",
+ "unix:/tmp/redis.sock",
+ "redis+unix:/tmp/redis.sock",
+ ] {
+ let info = builder.get_connection_info(endpoint.to_string())?;
+ assert_eq!(
+ info.addr(),
+ &ConnectionAddr::Unix(PathBuf::from("/tmp/redis.sock")),
+ "unexpected Unix address for endpoint {endpoint}"
+ );
+ }
+
+ for invalid in [
+ "",
+ "redis://",
+ "tcp://",
+ "rediss://",
+ "unix://",
+ "http://127.0.0.1:6379",
+ ] {
+ let err = builder
+ .get_connection_info(invalid.to_string())
+ .expect_err(&format!("invalid endpoint {invalid:?} must be
rejected"));
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ }
+
+ Ok(())
+ }
+
+ #[test]
+ fn build_validates_connection_pool_max_size_and_default_ttl() {
+ let zero_pool = RedisConfig {
+ endpoint: Some("redis://127.0.0.1:6379".to_string()),
+ connection_pool_max_size: Some(0),
+ ..Default::default()
+ };
+ let err = zero_pool
+ .into_builder()
+ .build()
+ .expect_err("zero pool size must return ConfigInvalid");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+
+ let uri = OperatorUri::new(
+ "redis://127.0.0.1:6379?connection_pool_max_size=0",
+ Vec::<(String, String)>::new(),
+ )
+ .unwrap();
+ let err = RedisConfig::from_uri(&uri)
+ .unwrap()
+ .into_builder()
+ .build()
+ .expect_err("zero pool size from URI must return ConfigInvalid");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+
+ assert!(
+ RedisBuilder::default()
+ .default_ttl(Duration::ZERO)
+ .build()
+ .is_ok()
+ );
+ assert!(
+ RedisBuilder::default()
+ .default_ttl(Duration::from_millis(500))
+ .build()
+ .is_ok()
+ );
+
+ let err = RedisBuilder::default()
+ .default_ttl(Duration::from_millis(i64::MAX as u64) +
Duration::from_nanos(1))
+ .build()
+ .expect_err("overflowing default_ttl must return ConfigInvalid");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ }
}
diff --git a/core/services/redis/src/config.rs
b/core/services/redis/src/config.rs
index 244190dd79..fc3d318fec 100644
--- a/core/services/redis/src/config.rs
+++ b/core/services/redis/src/config.rs
@@ -101,6 +101,15 @@ impl Configurator for RedisConfig {
.with_context("service", REDIS_SCHEME));
}
+ if let Some(username) = uri.username() {
+ map.entry("username".to_string())
+ .or_insert_with(|| username.to_string());
+ }
+ if let Some(password) = uri.password() {
+ map.entry("password".to_string())
+ .or_insert_with(|| password.to_string());
+ }
+
if let Some(path) = uri.root()
&& !path.is_empty()
{
@@ -185,6 +194,41 @@ mod tests {
Ok(())
}
+ #[test]
+ fn from_uri_extracts_credentials() -> Result<()> {
+ let uri = OperatorUri::new(
+ "redis://alice:s%40cret@localhost:6379/0",
+ Vec::<(String, String)>::new(),
+ )?;
+
+ let cfg = RedisConfig::from_uri(&uri)?;
+ assert_eq!(cfg.endpoint.as_deref(), Some("redis://localhost:6379"));
+ assert_eq!(cfg.username.as_deref(), Some("alice"));
+ assert_eq!(cfg.password.as_deref(), Some("s@cret"));
+ assert!(!format!("{cfg:?}").contains("s@cret"));
+
+ let password_only = OperatorUri::new(
+ "redis://:onlypass@localhost:6379/1",
+ Vec::<(String, String)>::new(),
+ )?;
+ let cfg = RedisConfig::from_uri(&password_only)?;
+ assert_eq!(cfg.username, None);
+ assert_eq!(cfg.password.as_deref(), Some("onlypass"));
+ assert_eq!(cfg.db, 1);
+
+ let override_uri = OperatorUri::new(
+ "redis://alice:secret@localhost:6379/0",
+ [
+ ("username".to_string(), "bob".to_string()),
+ ("password".to_string(), "override".to_string()),
+ ],
+ )?;
+ let cfg = RedisConfig::from_uri(&override_uri)?;
+ assert_eq!(cfg.username.as_deref(), Some("bob"));
+ assert_eq!(cfg.password.as_deref(), Some("override"));
+ Ok(())
+ }
+
#[test]
fn from_iter_parses_default_ttl() -> Result<()> {
let cfg = RedisConfig::from_iter([("default_ttl".to_string(),
"5s".to_string())])?;
diff --git a/core/services/redis/src/core.rs b/core/services/redis/src/core.rs
index 141b03c268..a494b7efcf 100644
--- a/core/services/redis/src/core.rs
+++ b/core/services/redis/src/core.rs
@@ -177,66 +177,69 @@ impl RedisCore {
pub async fn len(&self, key: &str) -> Result<Option<usize>> {
let mut conn = self.conn().await?;
- let exists: bool = conn.exists(key).await.map_err(format_redis_error)?;
- if !exists {
- return Ok(None);
- }
-
- let len: usize = redis::cmd("STRLEN")
+ let (len, exists): (usize, bool) = redis::pipe()
+ .cmd("STRLEN")
+ .arg(key)
+ .cmd("EXISTS")
.arg(key)
.query_async(&mut *conn)
.await
.map_err(format_redis_error)?;
- Ok(Some(len))
+ if len > 0 {
+ Ok(Some(len))
+ } else if exists {
+ Ok(Some(0))
+ } else {
+ Ok(None)
+ }
}
- pub async fn get_range(&self, key: &str, start: isize, end: isize) ->
Result<Option<Buffer>> {
+ pub async fn get_range(
+ &self,
+ key: &str,
+ start: i64,
+ end: i64,
+ ) -> Result<Option<(usize, Buffer)>> {
let mut conn = self.conn().await?;
- let result: Option<Bytes> = conn
- .getrange(key, start, end)
+ // Redis-compatible servers such as Kvrocks return RESP nil instead of
+ // an empty bulk string for out-of-range or missing GETRANGE responses.
+ let (bytes, len, exists): (Option<Bytes>, usize, bool) = redis::pipe()
+ .cmd("GETRANGE")
+ .arg(key)
+ .arg(start)
+ .arg(end)
+ .cmd("STRLEN")
+ .arg(key)
+ .cmd("EXISTS")
+ .arg(key)
+ .query_async(&mut *conn)
.await
.map_err(format_redis_error)?;
- Ok(result.map(Buffer::from))
+ let bytes = bytes.unwrap_or_default();
+ if len > 0 {
+ Ok(Some((len, Buffer::from(bytes))))
+ } else if exists {
+ Ok(Some((0, Buffer::from(bytes))))
+ } else {
+ Ok(None)
+ }
}
pub async fn set(&self, key: &str, value: Buffer, expires:
Option<Duration>) -> Result<()> {
- if let Some(expires) = expires {
- let milliseconds =
u64::try_from(expires.as_nanos().div_ceil(1_000_000))
- .ok()
- .filter(|ttl| (1..=i64::MAX as u64).contains(ttl))
- .ok_or_else(|| {
- Error::new(
- ErrorKind::ConfigInvalid,
- "expires must be positive and fit in Redis
milliseconds",
- )
- })?;
- let mut conn = self.conn().await?;
+ let expiration_ms = resolve_expiration(expires, self.default_ttl)?;
+ let mut conn = self.conn().await?;
+ let value = value.to_vec();
+ if let Some(milliseconds) = expiration_ms {
let options =
redis::SetOptions::default().with_expiration(redis::SetExpiry::PX(milliseconds));
- let _: () = conn
- .set_options(key, value.to_vec(), options)
- .await
- .map_err(|err| {
- // Redis also checks whether adding the TTL to its clock
overflows.
- if err.detail() == Some("invalid expire time in 'set'
command") {
- return Error::new(
- ErrorKind::ConfigInvalid,
- "expires is too large for Redis",
- )
+ let _: () = conn.set_options(key, value,
options).await.map_err(|err| {
+ // Redis also checks whether adding the TTL to its clock
overflows.
+ if err.detail() == Some("invalid expire time in 'set'
command") {
+ return Error::new(ErrorKind::ConfigInvalid, "expires is
too large for Redis")
.set_source(err);
- }
- format_redis_error(err)
- })?;
- return Ok(());
- }
-
- let mut conn = self.conn().await?;
- let value = value.to_vec();
- if let Some(dur) = self.default_ttl {
- let _: () = conn
- .set_ex(key, value, dur.as_secs())
- .await
- .map_err(format_redis_error)?;
+ }
+ format_redis_error(err)
+ })?;
} else {
let _: () = conn.set(key,
value).await.map_err(format_redis_error)?;
}
@@ -250,8 +253,96 @@ impl RedisCore {
}
}
+pub(crate) fn encode_expiration(expires: Duration) -> Result<u64> {
+ u64::try_from(expires.as_nanos().div_ceil(1_000_000))
+ .ok()
+ .filter(|ttl| (1..=i64::MAX as u64).contains(ttl))
+ .ok_or_else(|| {
+ Error::new(
+ ErrorKind::ConfigInvalid,
+ "expires must be positive and fit in Redis milliseconds",
+ )
+ })
+}
+
+fn resolve_expiration(
+ expires: Option<Duration>,
+ default_ttl: Option<Duration>,
+) -> Result<Option<u64>> {
+ if let Some(expires) = expires {
+ return encode_expiration(expires).map(Some);
+ }
+
+ match default_ttl {
+ Some(ttl) if !ttl.is_zero() => encode_expiration(ttl).map(Some),
+ _ => Ok(None),
+ }
+}
+
pub fn format_redis_error(e: RedisError) -> Error {
Error::new(ErrorKind::Unexpected, e.category())
.set_source(e)
.set_temporary()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolve_redis_expiration() {
+ assert_eq!(resolve_expiration(None, None).unwrap(), None);
+ assert_eq!(
+ resolve_expiration(None, Some(Duration::ZERO)).unwrap(),
+ None
+ );
+
+ for ttl in [
+ Duration::from_nanos(1),
+ Duration::from_micros(500),
+ Duration::from_millis(1),
+ ] {
+ assert_eq!(resolve_expiration(None, Some(ttl)).unwrap(), Some(1));
+ }
+
+ assert_eq!(
+ resolve_expiration(None,
Some(Duration::from_millis(500))).unwrap(),
+ Some(500)
+ );
+ assert_eq!(
+ resolve_expiration(None,
Some(Duration::from_millis(1500))).unwrap(),
+ Some(1500)
+ );
+ assert_eq!(
+ resolve_expiration(None,
Some(Duration::from_nanos(1_500_000_001))).unwrap(),
+ Some(1501)
+ );
+ assert_eq!(
+ resolve_expiration(
+ Some(Duration::from_secs(2)),
+ Some(Duration::from_millis(500))
+ )
+ .unwrap(),
+ Some(2000)
+ );
+
+ let err =
+ resolve_expiration(Some(Duration::ZERO),
Some(Duration::from_secs(60))).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ }
+
+ #[test]
+ fn encode_redis_expiration_bounds() {
+ let max_ms = Duration::from_millis(i64::MAX as u64);
+ assert_eq!(encode_expiration(max_ms).unwrap(), i64::MAX as u64);
+
+ for ttl in [
+ Duration::ZERO,
+ max_ms + Duration::from_nanos(1),
+ Duration::MAX,
+ ] {
+ let err = encode_expiration(ttl).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ }
+ }
+}
diff --git a/core/services/redis/src/docs.md b/core/services/redis/src/docs.md
index 37c6275185..d6328af5a2 100644
--- a/core/services/redis/src/docs.md
+++ b/core/services/redis/src/docs.md
@@ -46,11 +46,12 @@ Replication lag can cause stale results. For example,
`read` or `stat` can
briefly return `ErrorKind::NotFound` for a just-written key. OpenDAL returns
a replica miss without retrying on the primary.
-## Per-write expiration
+## Expiration
A write with `expires` overrides `default_ttl` for that key. Redis applies
the expiration in the same command that stores the value, rounding positive
-durations up to a whole millisecond.
+durations up to a whole millisecond. An omitted or zero `default_ttl` disables
+expiration, while a zero per-write `expires` is invalid.
## Example
diff --git a/core/services/redis/src/reader.rs
b/core/services/redis/src/reader.rs
index de4c947e75..78b2220fce 100644
--- a/core/services/redis/src/reader.rs
+++ b/core/services/redis/src/reader.rs
@@ -44,48 +44,105 @@ impl oio::StreamRead for RedisReader {
// Full read - use GET
match backend.core.get(&p).await? {
Some(bs) => {
- let metadata = {
- let metadata = MetadataBuilder::file(bs.len() as u64);
- metadata.build()
- };
+ let metadata = MetadataBuilder::file(bs.len() as
u64).build();
(bs, Some(metadata))
}
None => return Err(Error::new(ErrorKind::NotFound, "key not
found in redis")),
}
- } else {
- // Range read - use GETRANGE
- let content_length = match backend.core.len(&p).await? {
+ } else if let Some((start, end)) = redis_getrange_bounds(range) {
+ // Range read - fetch range, length, and existence in one pipeline
+ let (content_length, bs) = match backend.core.get_range(&p, start,
end).await? {
Some(v) => v,
None => return Err(Error::new(ErrorKind::NotFound, "key not
found in redis")),
};
let content_range = range.to_content_range(content_length)?;
-
- let buffer = if content_range.is_empty() {
- Buffer::new()
- } else {
- let start: isize =
content_range.start.try_into().map_err(|err| {
- Error::new(ErrorKind::Unexpected, "range start exceeds
isize::MAX")
- .set_source(err)
- })?;
- let end: isize = (content_range.end -
1).try_into().map_err(|err| {
- Error::new(ErrorKind::Unexpected, "range end exceeds
isize::MAX")
- .set_source(err)
- })?;
- match backend.core.get_range(&p, start, end).await? {
- Some(bs) => bs,
- None => {
- return Err(Error::new(ErrorKind::NotFound, "key not
found in redis"));
- }
- }
- };
- let metadata = {
- let metadata = MetadataBuilder::file(content_length as u64);
- metadata.build()
+ if bs.len() != content_range.len() {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "redis key changed concurrently during range read",
+ )
+ .set_temporary());
+ }
+ let metadata = MetadataBuilder::file(content_length as
u64).build();
+ (bs, Some(metadata))
+ } else {
+ let content_length = match backend.core.len(&p).await? {
+ Some(v) => v,
+ None => return Err(Error::new(ErrorKind::NotFound, "key not
found in redis")),
};
- (buffer, Some(metadata))
+ let _ = range.to_content_range(content_length)?;
+ let metadata = MetadataBuilder::file(content_length as
u64).build();
+ (Buffer::new(), Some(metadata))
};
let rp = metadata.map_or_else(RpRead::default, RpRead::new);
Ok((rp, Box::new(buffer) as Box<dyn oio::ReadStreamDyn>))
}
}
+
+fn redis_getrange_bounds(range: BytesRange) -> Option<(i64, i64)> {
+ match range {
+ BytesRange::Range { size: Some(0), .. } | BytesRange::Suffix { size: 0
} => None,
+ BytesRange::Range { offset, size: None } => {
+ let start = i64::try_from(offset).ok()?;
+ Some((start, -1))
+ }
+ BytesRange::Range {
+ offset,
+ size: Some(size),
+ } => {
+ let start = i64::try_from(offset).ok()?;
+ let end = offset.saturating_add(size - 1).min(i64::MAX as u64) as
i64;
+ Some((start, end))
+ }
+ BytesRange::Suffix { size } => {
+ if size <= i64::MAX as u64 {
+ Some((-(size as i64), -1))
+ } else {
+ Some((0, -1))
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn getrange_bounds_cover_all_range_forms() {
+ assert_eq!(redis_getrange_bounds(BytesRange::new(0, Some(0))), None);
+ assert_eq!(redis_getrange_bounds(BytesRange::new(10, Some(0))), None);
+ assert_eq!(redis_getrange_bounds(BytesRange::suffix(0)), None);
+ assert_eq!(redis_getrange_bounds(BytesRange::new(u64::MAX, None)),
None);
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::new(u64::MAX, Some(5))),
+ None
+ );
+
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::new(5, None)),
+ Some((5, -1))
+ );
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::new(0, Some(10))),
+ Some((0, 9))
+ );
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::new(5, Some(u64::MAX))),
+ Some((5, i64::MAX))
+ );
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::suffix(10)),
+ Some((-10, -1))
+ );
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::suffix(i64::MAX as u64)),
+ Some((-i64::MAX, -1))
+ );
+ assert_eq!(
+ redis_getrange_bounds(BytesRange::suffix(u64::MAX)),
+ Some((0, -1))
+ );
+ }
+}