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 834cfd0710 feat(layers/aimd): add adaptive HTTP request pacing (#8329)
834cfd0710 is described below
commit 834cfd0710410b189cebd86d0d8703aa489e8fe9
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 20:59:48 2026 +0800
feat(layers/aimd): add adaptive HTTP request pacing (#8329)
* feat(layers/aimd): add adaptive HTTP request pacing
* fix(ci): recognize AIMD as a technical term
* fix(ci): sort AIMD spelling dictionary entry
* Refine the AIMD layer builder and use a portable monotonic clock
* chore(layers/aimd): sync Cargo.lock and add crate license symlinks
---
.typos.toml | 1 +
core/Cargo.lock | 12 ++
core/Cargo.toml | 2 +
core/layers/aimd/Cargo.toml | 44 ++++++
core/layers/aimd/LICENSE | 1 +
core/layers/aimd/NOTICE | 1 +
core/layers/aimd/README.md | 97 +++++++++++++
core/layers/aimd/src/bucket.rs | 274 +++++++++++++++++++++++++++++++++++
core/layers/aimd/src/config.rs | 209 +++++++++++++++++++++++++++
core/layers/aimd/src/lib.rs | 178 +++++++++++++++++++++++
core/layers/aimd/src/service.rs | 313 ++++++++++++++++++++++++++++++++++++++++
core/layers/aimd/src/tests.rs | 277 +++++++++++++++++++++++++++++++++++
core/src/lib.rs | 2 +
13 files changed, 1411 insertions(+)
diff --git a/.typos.toml b/.typos.toml
index 8902e29716..59cbf87516 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -29,6 +29,7 @@
"fpr" = "fpr"
# Tech words
"WRONLY" = "WRONLY"
+"aimd" = "aimd"
"typ" = "typ"
[files]
diff --git a/core/Cargo.lock b/core/Cargo.lock
index 21b5bc2798..406aba40f0 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -7344,6 +7344,7 @@ dependencies = [
"opendal-executor-tokio",
"opendal-http-transport-cyper",
"opendal-http-transport-reqwest",
+ "opendal-layer-aimd",
"opendal-layer-async-backtrace",
"opendal-layer-await-tree",
"opendal-layer-cache",
@@ -7601,6 +7602,17 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "opendal-layer-aimd"
+version = "0.59.5"
+dependencies = [
+ "asyncband",
+ "futures",
+ "http 1.5.0",
+ "opendal-core",
+ "tokio",
+]
+
[[package]]
name = "opendal-layer-async-backtrace"
version = "0.59.5"
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 68a2cea02a..4d53a19abc 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -133,6 +133,7 @@ http-transport-reqwest-rustls-no-provider = [
"opendal-http-transport-reqwest/rustls-no-provider",
]
internal-tokio-rt = ["opendal-core/internal-tokio-rt"]
+layers-aimd = ["dep:opendal-layer-aimd"]
layers-async-backtrace = ["dep:opendal-layer-async-backtrace"]
layers-await-tree = ["dep:opendal-layer-await-tree"]
layers-cache = ["dep:opendal-layer-cache"]
@@ -269,6 +270,7 @@ opendal-core = { path = "core", version = "0.59.5",
default-features = false }
opendal-executor-tokio = { path = "executors/tokio", version = "0.59.5",
optional = true }
opendal-http-transport-cyper = { path = "http-transports/cyper", version =
"0.59.5", optional = true, default-features = false }
opendal-http-transport-reqwest = { path = "http-transports/reqwest", version =
"0.59.5", optional = true, default-features = false }
+opendal-layer-aimd = { path = "layers/aimd", version = "0.59.5", optional =
true, default-features = false }
opendal-layer-async-backtrace = { path = "layers/async-backtrace", version =
"0.59.5", optional = true, default-features = false }
opendal-layer-await-tree = { path = "layers/await-tree", version = "0.59.5",
optional = true, default-features = false }
opendal-layer-cache = { path = "layers/cache", version = "0.59.5", optional =
true, default-features = false }
diff --git a/core/layers/aimd/Cargo.toml b/core/layers/aimd/Cargo.toml
new file mode 100644
index 0000000000..4fbbaa3fc5
--- /dev/null
+++ b/core/layers/aimd/Cargo.toml
@@ -0,0 +1,44 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+description = "Apache OpenDAL adaptive request-rate layer"
+name = "opendal-layer-aimd"
+readme = "README.md"
+
+authors = { workspace = true }
+edition = { workspace = true }
+homepage = { workspace = true }
+license = { workspace = true }
+repository = { workspace = true }
+rust-version = { workspace = true }
+version = { workspace = true }
+
+[package.metadata.docs.rs]
+all-features = true
+
+[dependencies]
+asyncband = { workspace = true, features = ["event", "mutex"] }
+futures = { workspace = true }
+http = { workspace = true }
+opendal-core = { path = "../../core", version = "0.59.5", default-features =
false }
+
+tokio = { workspace = true, features = ["time"] }
+
+[dev-dependencies]
+futures = { workspace = true, features = ["executor"] }
+tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/core/layers/aimd/LICENSE b/core/layers/aimd/LICENSE
new file mode 120000
index 0000000000..5853aaea53
--- /dev/null
+++ b/core/layers/aimd/LICENSE
@@ -0,0 +1 @@
+../../../LICENSE
\ No newline at end of file
diff --git a/core/layers/aimd/NOTICE b/core/layers/aimd/NOTICE
new file mode 120000
index 0000000000..295f6bdb3a
--- /dev/null
+++ b/core/layers/aimd/NOTICE
@@ -0,0 +1 @@
+../../../NOTICE
\ No newline at end of file
diff --git a/core/layers/aimd/README.md b/core/layers/aimd/README.md
new file mode 100644
index 0000000000..2978ccb0b0
--- /dev/null
+++ b/core/layers/aimd/README.md
@@ -0,0 +1,97 @@
+# Apache OpenDALâ„¢ AIMD Layer
+
+`AimdLayer` adapts HTTP request rates to storage-service throttling. It
combines
+an additive-increase/multiplicative-decrease controller with a token bucket for
+each of four independent categories: read (including stat), write (including
+copy, compose, create_dir, rename, and restore), delete, and list.
+
+## Usage
+
+Enable the facade feature `layers-aimd` and use
+`opendal::layers::AimdLayer`. With split crates, add
+`opendal-layer-aimd` alongside `opendal-core`:
+
+```rust
+use opendal_core::{Operator, Result};
+use opendal_layer_aimd::AimdLayer;
+
+fn configure(operator: Operator) -> Result<Operator> {
+ let aimd = AimdLayer::builder()
+ .max_rate(10.0)
+ .initial_rate(2.0)
+ .additive_increment(1.0)
+ .burst(1)
+ .build()?;
+
+ Ok(operator.layer(aimd))
+}
+```
+
+This example starts each category at 2 requests/s and grows by 1 request/s per
+active, unthrottled window up to 10 requests/s. A burst of 1 admits one request
+immediately. If you set only the rate bounds, the initial rate defaults to 2000
+clamped to those bounds. Burst capacity and additive increment have independent
+defaults.
+
+Add AIMD before retry so it observes each attempt's errors. AIMD does not own
+retries, modify errors, or replace bandwidth and concurrency limits. Place a
+bandwidth throttle outside AIMD so locally generated `RateLimited` errors do
+not reduce the backend budget.
+
+When using an HTTP concurrency limit, add `ConcurrentLimitLayer` first, then
+`AimdLayer`, then `RetryLayer`. Requests then wait for AIMD admission before
+acquiring an HTTP concurrency permit. To exclude this wait from HTTP latency
+metrics, also add the HTTP metrics layer before AIMD.
+
+Cloning a layer shares its budgets across operators. Construct separate layers
+for independent quotas. Each category receives the configured rate and burst;
+`max_rate` is not a combined ceiling across all four categories.
+
+## Admission and feedback
+
+The HTTP wrapper takes one token before forwarding each request with an OpenDAL
+`Operation` extension. Pages, multipart parts, and batch-delete requests each
+consume their own tokens. Response chunks and entries buffered from a page do
+not consume extra tokens. Requests without this extension, presigning, and
+non-HTTP I/O bypass admission. Requests hidden inside a custom transport, such
+as automatic retries or redirects, are outside this boundary.
+
+Parsed `ErrorKind::RateLimited` errors observed by the service and I/O wrappers
+mark a feedback window as throttled. At the next window transition, its rate is
+multiplied by `decrease_factor`, bounded by `min_rate`. Otherwise, a window
with
+HTTP responses adds `additive_increment`, bounded by `max_rate`. Empty windows
+do not change the rate. Defaults are 2000 requests/s initially, a range of
+1–5000 requests/s, a one-second window, an increment of 300 requests/s, a
+multiplier of 0.5, and a burst of 100 requests per category.
+
+HTTP completion and parsed errors occur at different boundaries. Feedback may
+be delayed until an operation propagates its error, and errors consumed by an
+inner layer are not visible. The controller uses the presence of a throttle
+signal, not a ratio of HTTP requests to operation errors. Other errors do not
+reduce the rate; an HTTP error response still establishes activity. A failed
+connection alone does not establish activity.
+
+Feedback belongs to the enclosing storage operation's budget. A composite
+operation may send requests in other categories, such as stat requests during
+a copy. Admission follows each request's marker, while semantic feedback
follows
+the enclosing operation; errors are not correlated with individual HTTP
requests.
+
+Waiters use a FIFO queue. Cancelling a waiter removes its queue position
without
+leaving token debt, and rate changes update pending waits. Buckets start full;
+only a request admitted to the next transport consumes a token. The layer does
+not spawn background tasks. Waiting uses Tokio timers by default and requires
+an active Tokio runtime with time enabled. Use `with_sleep` on the builder to
+supply a function that accepts a `Duration` and returns a future completing
+after that duration. A custom sleep allows admission to run without a Tokio
+runtime. Rate calculations use the platform's monotonic clock independently of
+the sleep function.
+
+Services sign requests before transport admission. Bound operation duration
+when a queue could outlive the service's signature validity period. Configure
+transport wrappers to forward to their inner transport, preserving this layer.
+This mechanism provides local adaptive pacing, not a distributed quota or a
+promise of fair sharing between processes.
+
+## License
+
+Licensed under the Apache License, Version 2.0.
diff --git a/core/layers/aimd/src/bucket.rs b/core/layers/aimd/src/bucket.rs
new file mode 100644
index 0000000000..c00dd03f6f
--- /dev/null
+++ b/core/layers/aimd/src/bucket.rs
@@ -0,0 +1,274 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use opendal_core::raw::Instant;
+use std::future::Future;
+use std::sync::Mutex;
+use std::time::Duration;
+
+use asyncband::event::ManualResetEvent;
+use asyncband::mutex::Mutex as AsyncMutex;
+use futures::future::select;
+use opendal_core::{ErrorKind, Result};
+
+use crate::AimdConfig;
+
+/// One feedback window and token bucket share a lock so rate changes cannot
+/// race with token refill or overwrite a newer rate.
+#[derive(Debug)]
+pub(crate) struct Bucket {
+ config: AimdConfig,
+ state: Mutex<State>,
+ // The FIFO lock owns the waiting queue. Cancelling an acquire drops
+ // its queue position without reserving tokens or leaving token debt.
+ admission: AsyncMutex<()>,
+ changed: ManualResetEvent,
+}
+
+#[derive(Debug)]
+struct State {
+ rate: f64,
+ tokens: f64,
+ last_refill: Instant,
+ window_start: Instant,
+ active: bool,
+ throttled: bool,
+}
+
+impl State {
+ fn advance(&mut self, config: &AimdConfig, now: Instant) {
+ // Settle elapsed time at the old rate before adjusting it.
+ self.tokens = (self.tokens
+ + now.duration_since(self.last_refill).as_secs_f64() * self.rate)
+ .min(f64::from(config.burst));
+ self.last_refill = now;
+
+ if now.duration_since(self.window_start) >= config.window {
+ if self.throttled {
+ self.rate = (self.rate *
config.decrease_factor).max(config.min_rate);
+ } else if self.active {
+ self.rate = (self.rate +
config.additive_increment).min(config.max_rate);
+ }
+ // Do not replay empty windows after an idle period.
+ self.window_start = now;
+ self.active = false;
+ self.throttled = false;
+ }
+ }
+}
+
+impl Bucket {
+ pub(crate) fn new(config: AimdConfig, initial_rate: f64) -> Self {
+ let now = Instant::now();
+ Self {
+ state: Mutex::new(State {
+ rate: initial_rate,
+ tokens: f64::from(config.burst),
+ last_refill: now,
+ window_start: now,
+ active: false,
+ throttled: false,
+ }),
+ config,
+ admission: AsyncMutex::new(()),
+ changed: ManualResetEvent::new(),
+ }
+ }
+
+ pub(crate) async fn acquire<F, Fut>(&self, sleep: F)
+ where
+ F: Fn(Duration) -> Fut,
+ Fut: Future<Output = ()>,
+ {
+ let _turn = self.admission.lock().await;
+ loop {
+ // Only the queue head waits on this event. Reset before reading
+ // state so feedback between the read and the wait remains
signalled.
+ self.changed.reset();
+ let wait = {
+ let mut state = self.state.lock().expect("AIMD state
poisoned");
+ let now = Instant::now();
+ state.advance(&self.config, now);
+ if state.tokens >= 1.0 {
+ state.tokens -= 1.0;
+ return;
+ }
+ let mut wait = Duration::from_secs_f64((1.0 - state.tokens) /
state.rate)
+ .max(Duration::from_nanos(1));
+ if state.active || state.throttled {
+ // Revisit a pending feedback window even if the next token
+ // would otherwise arrive later than the window boundary.
+ wait = wait.min(self.config.window -
now.duration_since(state.window_start));
+ }
+ wait
+ };
+ let changed = std::pin::pin!(self.changed.wait());
+ let timer = std::pin::pin!(sleep(wait));
+ select(timer, changed).await;
+ }
+ }
+
+ pub(crate) fn complete_http(&self) {
+ let mut state = self.state.lock().expect("AIMD state poisoned");
+ state.advance(&self.config, Instant::now());
+ state.active = true;
+ drop(state);
+ self.changed.set();
+ }
+
+ pub(crate) fn observe<T>(&self, result: &Result<T>) {
+ if result
+ .as_ref()
+ .is_err_and(|err| err.kind() == ErrorKind::RateLimited)
+ {
+ let mut state = self.state.lock().expect("AIMD state poisoned");
+ state.advance(&self.config, Instant::now());
+ state.throttled = true;
+ drop(state);
+ self.changed.set();
+ }
+ }
+}
+
+#[cfg(test)]
+impl Bucket {
+ pub(crate) fn rate(&self) -> f64 {
+ self.state.lock().unwrap().rate
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use futures::{executor::block_on, poll};
+ use opendal_core::Error;
+
+ fn config() -> AimdConfig {
+ AimdConfig {
+ min_rate: 1.0,
+ max_rate: 8.0,
+ additive_increment: 2.0,
+ window: Duration::from_secs(1),
+ burst: 1,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn active_windows_grow_empty_windows_do_not_and_bounds_hold() {
+ let config = config();
+ let mut state = Bucket::new(config.clone(),
4.0).state.into_inner().unwrap();
+ let mut now = state.window_start;
+ for expected in [6.0, 8.0, 8.0] {
+ state.active = true;
+ now += config.window;
+ state.advance(&config, now);
+ assert_eq!(state.rate, expected);
+ }
+ for expected in [4.0, 2.0, 1.0, 1.0] {
+ state.active = true;
+ state.throttled = true;
+ now += config.window;
+ state.advance(&config, now);
+ assert_eq!(state.rate, expected);
+ state.advance(&config, now);
+ assert_eq!(state.rate, expected, "a window must be applied only
once");
+ }
+ now += Duration::from_secs(100);
+ state.advance(&config, now);
+ assert_eq!(state.rate, 1.0);
+ state.active = true;
+ now += Duration::from_secs(100);
+ state.advance(&config, now);
+ assert_eq!(state.rate, 3.0, "idle windows must not be replayed");
+ }
+
+ #[test]
+ fn only_rate_limited_errors_trigger_decrease() {
+ let bucket = Bucket::new(config(), 4.0);
+ bucket.observe::<()>(&Err(
+ Error::new(ErrorKind::Unexpected, "retryable").set_temporary()
+ ));
+ bucket.observe::<()>(&Err(Error::new(ErrorKind::NotFound, "missing")));
+ assert!(!bucket.state.lock().unwrap().throttled);
+ assert!(!bucket.state.lock().unwrap().active);
+ bucket.observe::<()>(&Err(Error::new(ErrorKind::RateLimited,
"limited")));
+ assert!(bucket.state.lock().unwrap().throttled);
+ }
+
+ #[test]
+ fn refill_uses_old_rate_before_applying_window_feedback() {
+ let config = AimdConfig {
+ window: Duration::from_millis(100),
+ ..config()
+ };
+ for (throttled, expected_rate, remaining) in [
+ (true, 2.0, Duration::from_millis(300)),
+ (false, 6.0, Duration::from_millis(100)),
+ ] {
+ let mut state = Bucket::new(config.clone(),
4.0).state.into_inner().unwrap();
+ state.tokens = 0.0;
+ state.active = true;
+ state.throttled = throttled;
+ let now = state.window_start + config.window;
+ state.advance(&config, now);
+ assert_eq!(state.rate, expected_rate);
+ assert!((state.tokens - 0.4).abs() < 1e-9);
+ state.advance(&config, now + remaining);
+ assert!((state.tokens - 1.0).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn fifo_admission_and_cancellation_leave_no_token_debt() {
+ block_on(async {
+ let bucket = Bucket::new(
+ AimdConfig {
+ min_rate: 0.001,
+ ..config()
+ },
+ 0.001,
+ );
+ bucket.acquire(|_| std::future::pending::<()>()).await;
+ let mut head = Box::pin(bucket.acquire(|_|
std::future::pending::<()>()));
+ let mut cancelled = Box::pin(bucket.acquire(|_|
std::future::pending::<()>()));
+ let mut tail = Box::pin(bucket.acquire(|_|
std::future::pending::<()>()));
+ assert!(poll!(&mut head).is_pending());
+ assert!(poll!(&mut cancelled).is_pending());
+ assert!(poll!(&mut tail).is_pending());
+ drop(cancelled);
+ bucket.state.lock().unwrap().tokens = 1.0;
+ bucket.changed.set();
+ assert!(poll!(&mut tail).is_pending(), "the queue head goes
first");
+ assert!(poll!(&mut head).is_ready());
+ assert!(
+ poll!(&mut tail).is_pending(),
+ "only one token was available"
+ );
+ drop(tail);
+
+ let mut cancelled_head = Box::pin(bucket.acquire(|_|
std::future::pending::<()>()));
+ let mut next = Box::pin(bucket.acquire(|_|
std::future::pending::<()>()));
+ assert!(poll!(&mut cancelled_head).is_pending());
+ assert!(poll!(&mut next).is_pending());
+ drop(cancelled_head);
+ bucket.state.lock().unwrap().tokens = 1.0;
+ bucket.changed.set();
+ assert!(poll!(&mut next).is_ready());
+ });
+ }
+}
diff --git a/core/layers/aimd/src/config.rs b/core/layers/aimd/src/config.rs
new file mode 100644
index 0000000000..b57a7ea362
--- /dev/null
+++ b/core/layers/aimd/src/config.rs
@@ -0,0 +1,209 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::{AimdLayer, Bucket, Buckets, SleepFn};
+use opendal_core::raw::{Instant, MaybeSend};
+use opendal_core::{Error, ErrorKind, Result};
+
+/// Configures the four independent request budgets of an [`AimdLayer`].
+/// Each budget receives the same settings and tracks its own rate.
+#[derive(Clone)]
+pub struct AimdLayerBuilder {
+ config: AimdConfig,
+ initial_rate: Option<f64>,
+ sleep: SleepFn,
+}
+
+impl Default for AimdLayerBuilder {
+ fn default() -> Self {
+ Self {
+ config: AimdConfig::default(),
+ initial_rate: None,
+ sleep: Arc::new(|duration| Box::pin(tokio::time::sleep(duration))),
+ }
+ }
+}
+
+impl AimdLayerBuilder {
+ /// Set the initial requests per second for each budget. Defaults to 2000,
+ /// limited to the configured range. An explicit value must be in range.
+ pub fn initial_rate(mut self, initial_rate: f64) -> Self {
+ self.initial_rate = Some(initial_rate);
+ self
+ }
+
+ /// Set the minimum requests per second for each budget. Defaults to 1.
+ pub fn min_rate(mut self, min_rate: f64) -> Self {
+ self.config.min_rate = min_rate;
+ self
+ }
+
+ /// Set the maximum requests per second for each budget. Defaults to 5000.
+ pub fn max_rate(mut self, max_rate: f64) -> Self {
+ self.config.max_rate = max_rate;
+ self
+ }
+
+ /// Set the rate multiplier after a throttled window. Defaults to 0.5.
+ pub fn decrease_factor(mut self, decrease_factor: f64) -> Self {
+ self.config.decrease_factor = decrease_factor;
+ self
+ }
+
+ /// Set the requests per second added after an active window without
throttling. Defaults to 300.
+ pub fn additive_increment(mut self, additive_increment: f64) -> Self {
+ self.config.additive_increment = additive_increment;
+ self
+ }
+
+ /// Set the feedback window duration. Defaults to one second.
+ pub fn window(mut self, window: Duration) -> Self {
+ self.config.window = window;
+ self
+ }
+
+ /// Set the token capacity for each budget. Buckets start full. Defaults
to 100.
+ pub fn burst(mut self, burst: u32) -> Self {
+ self.config.burst = burst;
+ self
+ }
+
+ /// Replace the function that creates timers for admission waits.
+ ///
+ /// The function must return a nonblocking future that completes after the
+ /// supplied duration. Waiting may be cancelled when feedback changes or a
+ /// request is dropped, so dropping the future must safely cancel the wait.
+ /// The future must be `Send` on non-Wasm targets.
+ ///
+ /// Rate calculations use a monotonic clock independently of the sleep
function.
+ ///
+ /// ```
+ /// use opendal_layer_aimd::AimdLayer;
+ ///
+ /// let layer =
AimdLayer::builder().with_sleep(tokio::time::sleep).build()?;
+ /// # Ok::<(), opendal_core::Error>(())
+ /// ```
+ pub fn with_sleep<F, Fut>(mut self, sleep: F) -> Self
+ where
+ F: Fn(Duration) -> Fut + Send + Sync + 'static,
+ Fut: Future<Output = ()> + MaybeSend + 'static,
+ {
+ self.sleep = Arc::new(move |duration| Box::pin(sleep(duration)));
+ self
+ }
+
+ /// Create a layer with four independent budgets using these settings.
+ ///
+ /// Returns [`ErrorKind::ConfigInvalid`] for nonpositive or non-finite
rates,
+ /// inconsistent rate bounds, a nonpositive or non-finite additive
increment,
+ /// a decrease factor outside `(0, 1)`, a zero burst
+ /// or window, or a window or token interval outside the timer range.
+ pub fn build(self) -> Result<AimdLayer> {
+ let config = self.config;
+ let initial_rate = self
+ .initial_rate
+ .unwrap_or_else(||
2000.0_f64.max(config.min_rate).min(config.max_rate));
+ config.validate(initial_rate)?;
+ Ok(AimdLayer {
+ sleep: self.sleep,
+ buckets: Arc::new(Buckets {
+ read: Arc::new(Bucket::new(config.clone(), initial_rate)),
+ write: Arc::new(Bucket::new(config.clone(), initial_rate)),
+ delete: Arc::new(Bucket::new(config.clone(), initial_rate)),
+ list: Arc::new(Bucket::new(config, initial_rate)),
+ }),
+ })
+ }
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct AimdConfig {
+ pub(crate) min_rate: f64,
+ pub(crate) max_rate: f64,
+ pub(crate) decrease_factor: f64,
+ pub(crate) additive_increment: f64,
+ pub(crate) window: Duration,
+ pub(crate) burst: u32,
+}
+
+impl Default for AimdConfig {
+ fn default() -> Self {
+ Self {
+ min_rate: 1.0,
+ max_rate: 5000.0,
+ decrease_factor: 0.5,
+ additive_increment: 300.0,
+ window: Duration::from_secs(1),
+ burst: 100,
+ }
+ }
+}
+
+impl AimdConfig {
+ fn validate(&self, initial_rate: f64) -> Result<()> {
+ for (name, value) in [
+ ("initial_rate", initial_rate),
+ ("min_rate", self.min_rate),
+ ("max_rate", self.max_rate),
+ ("decrease_factor", self.decrease_factor),
+ ("additive_increment", self.additive_increment),
+ ] {
+ if !value.is_finite() || value <= 0.0 {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "AIMD parameter must be finite and positive",
+ )
+ .with_context("parameter", name));
+ }
+ }
+ if self.min_rate > initial_rate || initial_rate > self.max_rate {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "AIMD rates must satisfy min_rate <= initial_rate <= max_rate",
+ ));
+ }
+ if self.decrease_factor >= 1.0 {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "AIMD decrease_factor must be less than one",
+ ));
+ }
+ if self.window.is_zero() || self.burst == 0 {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "AIMD window and burst must be nonzero",
+ ));
+ }
+ let now = Instant::now();
+ let interval = Duration::try_from_secs_f64(1.0 / self.min_rate).ok();
+ if now.checked_add(self.window).is_none()
+ || interval
+ .and_then(|duration| now.checked_add(duration))
+ .is_none()
+ {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "AIMD window and token interval must fit the timer range",
+ ));
+ }
+ Ok(())
+ }
+}
diff --git a/core/layers/aimd/src/lib.rs b/core/layers/aimd/src/lib.rs
new file mode 100644
index 0000000000..10b5813b5c
--- /dev/null
+++ b/core/layers/aimd/src/lib.rs
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![doc = include_str!("../README.md")]
+#![cfg_attr(docsrs, feature(doc_cfg))]
+#![cfg_attr(docsrs, doc(auto_cfg))]
+#![deny(missing_docs)]
+
+use std::fmt::{Debug, Formatter};
+use std::sync::Arc;
+use std::time::Duration;
+
+use opendal_core::raw::{BoxedStaticFuture, Layer, Operation, Servicer};
+use opendal_core::{Buffer, HttpBody, HttpTransport, HttpTransporter,
OperationContext, Result};
+
+mod bucket;
+mod config;
+mod service;
+
+use bucket::Bucket;
+use config::AimdConfig;
+pub use config::AimdLayerBuilder;
+
+/// Adaptively pace HTTP storage requests using additive increase and
+/// multiplicative decrease (AIMD).
+///
+/// Each request carrying an OpenDAL [`Operation`] consumes one token from its
+/// read, write, delete, or list budget. Read and stat share the read budget;
+/// create_dir, write, copy, compose, rename, and restore share the write
budget.
+/// Unmarked requests, presigning, and non-HTTP I/O are not paced.
+///
+/// A window with an observed [`opendal_core::ErrorKind::RateLimited`]
multiplies
+/// its rate by `decrease_factor`. Otherwise, a window with HTTP responses adds
+/// `additive_increment`. Empty windows leave the rate unchanged. Changes are
+/// applied lazily at the next admission or feedback event, at most once per
+/// window. Rates remain between `min_rate` and `max_rate`.
+///
+/// HTTP responses establish activity; service and I/O wrappers observe parsed
+/// errors. Feedback can therefore arrive after the corresponding HTTP response
+/// and only includes errors propagated to those wrappers. HTTP status codes
and
+/// error messages are not interpreted by this layer. Other errors pass through
+/// unchanged and do not trigger a decrease.
+/// Feedback is attributed to the enclosing storage operation's budget. A
+/// composite operation can also send requests in other categories, such as
+/// stat requests during a copy; this layer does not correlate an error with
+/// the individual HTTP request that produced it.
+///
+/// This layer does not retry. Add it before a retry layer so it observes
errors
+/// from each attempt. Add layers that produce local rate-limit errors, such as
+/// a bandwidth throttle, outside it to avoid treating those errors as backend
+/// congestion. An inner layer that consumes errors can hide feedback.
+/// Add a layer that limits HTTP concurrency before AIMD so queued requests
+/// wait for admission before acquiring an HTTP concurrency permit.
+///
+/// Clones share all four budgets, including across operators and context
+/// replacement. Separately constructed layers have independent budgets. Choose
+/// sharing boundaries that match the backend's quota scope; this layer does
not
+/// discover quotas or coordinate across processes.
+///
+/// Waiting uses Tokio timers by default. Use [`AimdLayerBuilder::with_sleep`]
to supply a timer.
+/// Pacing happens after the service builds and signs a request. Bound
operation
+/// duration when queued requests could outlive a backend's signature validity
period. This layer
+/// limits dispatches to the next transport, not redirects or retries hidden
+/// inside that transport. Transport wrappers must forward to their inner
+/// transport to preserve pacing.
+#[derive(Clone)]
+pub struct AimdLayer {
+ buckets: Arc<Buckets>,
+ sleep: SleepFn,
+}
+
+type SleepFn = Arc<dyn Fn(Duration) -> BoxedStaticFuture<()> + Send + Sync>;
+
+impl Debug for AimdLayer {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("AimdLayer")
+ .field("buckets", &self.buckets)
+ .finish_non_exhaustive()
+ }
+}
+
+impl AimdLayer {
+ /// Configure the rates, burst capacity, feedback window, and admission
timer.
+ pub fn builder() -> AimdLayerBuilder {
+ AimdLayerBuilder::default()
+ }
+}
+
+impl Default for AimdLayer {
+ fn default() -> Self {
+ Self::builder()
+ .build()
+ .expect("default AIMD configuration is valid")
+ }
+}
+
+impl Layer for AimdLayer {
+ fn apply_service(&self, inner: Servicer) -> Servicer {
+ Arc::new(service::AimdService {
+ inner,
+ buckets: self.buckets.clone(),
+ })
+ }
+
+ fn apply_context(&self, _: Servicer, inner: OperationContext) ->
OperationContext {
+ inner.with_http_transport(HttpTransporter::new(AimdTransport {
+ inner: inner.http_transport().clone(),
+ sleep: self.sleep.clone(),
+ buckets: self.buckets.clone(),
+ }))
+ }
+}
+
+#[derive(Debug)]
+struct Buckets {
+ read: Arc<Bucket>,
+ write: Arc<Bucket>,
+ delete: Arc<Bucket>,
+ list: Arc<Bucket>,
+}
+
+impl Buckets {
+ fn for_operation(&self, op: Operation) -> Option<&Arc<Bucket>> {
+ match op {
+ Operation::Read | Operation::Stat => Some(&self.read),
+ Operation::Write
+ | Operation::Copy
+ | Operation::Compose
+ | Operation::Rename
+ | Operation::CreateDir
+ | Operation::Restore => Some(&self.write),
+ Operation::Delete => Some(&self.delete),
+ Operation::List => Some(&self.list),
+ _ => None,
+ }
+ }
+}
+
+struct AimdTransport {
+ inner: HttpTransporter,
+ sleep: SleepFn,
+ buckets: Arc<Buckets>,
+}
+
+impl HttpTransport for AimdTransport {
+ async fn fetch(&self, req: http::Request<Buffer>) ->
Result<http::Response<HttpBody>> {
+ let bucket = req
+ .extensions()
+ .get::<Operation>()
+ .and_then(|op| self.buckets.for_operation(*op));
+ let Some(bucket) = bucket else {
+ return self.inner.fetch(req).await;
+ };
+ bucket.acquire(&*self.sleep).await;
+ let result = self.inner.fetch(req).await;
+ if result.is_ok() {
+ bucket.complete_http();
+ }
+ result
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/core/layers/aimd/src/service.rs b/core/layers/aimd/src/service.rs
new file mode 100644
index 0000000000..ee8ad1e700
--- /dev/null
+++ b/core/layers/aimd/src/service.rs
@@ -0,0 +1,313 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use opendal_core::raw::*;
+use opendal_core::*;
+
+use crate::{Bucket, Buckets};
+
+#[derive(Debug)]
+pub(crate) struct AimdService {
+ pub(crate) inner: Servicer,
+ pub(crate) buckets: Arc<Buckets>,
+}
+
+impl Service for AimdService {
+ type Reader = Observed<oio::Reader>;
+ type Writer = Observed<oio::Writer>;
+ type Lister = Observed<oio::Lister>;
+ type Deleter = Observed<oio::Deleter>;
+ type Copier = Observed<oio::Copier>;
+ type Composer = Observed<oio::Composer>;
+
+ fn info(&self) -> ServiceInfo {
+ self.inner.info()
+ }
+
+ fn capability(&self) -> Capability {
+ self.inner.capability()
+ }
+
+ async fn create_dir(
+ &self,
+ ctx: &OperationContext,
+ path: &str,
+ args: OpCreateDir,
+ ) -> Result<RpCreateDir> {
+ let result = self.inner.create_dir(ctx, path, args).await;
+ self.buckets.write.observe(&result);
+ result
+ }
+
+ async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) ->
Result<RpStat> {
+ let result = self.inner.stat(ctx, path, args).await;
+ self.buckets.read.observe(&result);
+ result
+ }
+
+ async fn rename(
+ &self,
+ ctx: &OperationContext,
+ from: &str,
+ to: &str,
+ args: OpRename,
+ ) -> Result<RpRename> {
+ let result = self.inner.rename(ctx, from, to, args).await;
+ self.buckets.write.observe(&result);
+ result
+ }
+
+ async fn restore(
+ &self,
+ ctx: &OperationContext,
+ path: &str,
+ args: OpRestore,
+ ) -> Result<RpRestore> {
+ let result = self.inner.restore(ctx, path, args).await;
+ self.buckets.write.observe(&result);
+ result
+ }
+
+ fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) ->
Result<Self::Reader> {
+ let result = self.inner.read(ctx, path, args);
+ self.buckets.read.observe(&result);
+ result.map(|inner| Observed {
+ inner,
+ bucket: self.buckets.read.clone(),
+ })
+ }
+
+ fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) ->
Result<Self::Writer> {
+ let result = self.inner.write(ctx, path, args);
+ self.buckets.write.observe(&result);
+ result.map(|inner| Observed {
+ inner,
+ bucket: self.buckets.write.clone(),
+ })
+ }
+
+ fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
+ let result = self.inner.delete(ctx);
+ self.buckets.delete.observe(&result);
+ result.map(|inner| Observed {
+ inner,
+ bucket: self.buckets.delete.clone(),
+ })
+ }
+
+ fn list(&self, ctx: &OperationContext, path: &str, args: OpList) ->
Result<Self::Lister> {
+ let result = self.inner.list(ctx, path, args);
+ self.buckets.list.observe(&result);
+ result.map(|inner| Observed {
+ inner,
+ bucket: self.buckets.list.clone(),
+ })
+ }
+
+ fn copy(
+ &self,
+ ctx: &OperationContext,
+ from: &str,
+ to: &str,
+ args: OpCopy,
+ ) -> Result<Self::Copier> {
+ let result = self.inner.copy(ctx, from, to, args);
+ self.buckets.write.observe(&result);
+ result.map(|inner| Observed {
+ inner,
+ bucket: self.buckets.write.clone(),
+ })
+ }
+
+ fn compose(&self, ctx: &OperationContext, to: &str, args: OpCompose) ->
Result<Self::Composer> {
+ let result = self.inner.compose(ctx, to, args);
+ self.buckets.write.observe(&result);
+ result.map(|inner| Observed {
+ inner,
+ bucket: self.buckets.write.clone(),
+ })
+ }
+
+ async fn presign(
+ &self,
+ ctx: &OperationContext,
+ path: &str,
+ args: OpPresign,
+ ) -> Result<RpPresign> {
+ self.inner.presign(ctx, path, args).await
+ }
+}
+
+pub(crate) struct Observed<T> {
+ inner: T,
+ bucket: Arc<Bucket>,
+}
+
+impl<T: oio::Read> oio::Read for Observed<T> {
+ async fn open(&self, range: BytesRange) -> Result<(RpRead, Box<dyn
oio::ReadStreamDyn>)> {
+ let result = self.inner.open(range).await;
+ self.bucket.observe(&result);
+ result.map(|(rp, inner)| {
+ (
+ rp,
+ Box::new(Observed {
+ inner,
+ bucket: self.bucket.clone(),
+ }) as Box<dyn oio::ReadStreamDyn>,
+ )
+ })
+ }
+
+ async fn read(&self, range: BytesRange) -> Result<(RpRead, Buffer)> {
+ let result = self.inner.read(range).await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+impl<T: oio::ReadStream> oio::ReadStream for Observed<T> {
+ async fn read(&mut self) -> Result<Buffer> {
+ let result = self.inner.read().await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn read_all(&mut self) -> Result<Buffer> {
+ let result = self.inner.read_all().await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+impl<T: oio::Write> oio::Write for Observed<T> {
+ async fn write(&mut self, bs: Buffer) -> Result<()> {
+ let result = self.inner.write(bs).await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn copy_from(&mut self, path: &str, args: OpRead, range: BytesRange)
-> Result<()> {
+ let result = self.inner.copy_from(path, args, range).await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn close(&mut self) -> Result<Metadata> {
+ let result = self.inner.close().await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn abort(&mut self) -> Result<()> {
+ let result = self.inner.abort().await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+impl<T: oio::List> oio::List for Observed<T> {
+ async fn next(&mut self) -> Result<Option<oio::Entry>> {
+ let result = self.inner.next().await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+impl<T: oio::Delete> oio::Delete for Observed<T> {
+ async fn delete(&mut self, path: &str, args: OpDelete) -> Result<()> {
+ let result = self.inner.delete(path, args).await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn close(&mut self) -> Result<()> {
+ let result = self.inner.close().await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+impl<T: oio::Copy> oio::Copy for Observed<T> {
+ async fn next(&mut self) -> Result<Option<usize>> {
+ let result = self.inner.next().await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn close(&mut self) -> Result<Metadata> {
+ let result = self.inner.close().await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn abort(&mut self) -> Result<()> {
+ let result = self.inner.abort().await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+impl<T: oio::Compose> oio::Compose for Observed<T> {
+ async fn compose(&mut self, path: &str, args: OpRead) -> Result<()> {
+ let result = self.inner.compose(path, args).await;
+ self.bucket.observe(&result);
+ result
+ }
+
+ async fn close(&mut self) -> Result<Metadata> {
+ let result = self.inner.close().await;
+ self.bucket.observe(&result);
+ result
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::AimdLayer;
+ use oio::List;
+ use std::time::Duration;
+
+ struct LimitedLister;
+
+ impl oio::List for LimitedLister {
+ async fn next(&mut self) -> Result<Option<oio::Entry>> {
+ Err(Error::new(ErrorKind::RateLimited, "limited").set_temporary())
+ }
+ }
+
+ #[tokio::test]
+ async fn deferred_errors_preserve_retry_status_and_feed_the_budget() {
+ let layer = AimdLayer::builder()
+ .window(Duration::from_millis(10))
+ .build()
+ .unwrap();
+ let bucket = layer.buckets.list.clone();
+ let mut lister = Observed {
+ inner: LimitedLister,
+ bucket: bucket.clone(),
+ };
+ let error = lister.next().await.unwrap_err();
+ assert_eq!(error.kind(), ErrorKind::RateLimited);
+ assert!(error.is_temporary());
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ bucket.acquire(tokio::time::sleep).await;
+ assert_eq!(bucket.rate(), 1000.0);
+ }
+}
diff --git a/core/layers/aimd/src/tests.rs b/core/layers/aimd/src/tests.rs
new file mode 100644
index 0000000000..f186d67ba1
--- /dev/null
+++ b/core/layers/aimd/src/tests.rs
@@ -0,0 +1,277 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use futures::{executor::block_on, poll, stream};
+use http::{Request, Response};
+use opendal_core::raw::oio::ReadStream;
+use opendal_core::*;
+
+use super::*;
+
+#[test]
+fn invalid_configuration_is_rejected() {
+ let builder = AimdLayer::builder();
+ let mut configs = vec![
+ builder.clone().initial_rate(0.0),
+ builder.clone().min_rate(-1.0),
+ builder.clone().initial_rate(6000.0),
+ builder.clone().initial_rate(2000.0).min_rate(3000.0),
+ builder.clone().min_rate(10.0).max_rate(1.0),
+ builder.clone().decrease_factor(1.0),
+ builder.clone().additive_increment(0.0),
+ builder.clone().burst(0),
+ builder.clone().window(Duration::ZERO),
+ builder.clone().window(Duration::MAX),
+ builder.clone().min_rate(f64::MIN_POSITIVE),
+ ];
+ for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ configs.extend([
+ builder.clone().initial_rate(value),
+ builder.clone().min_rate(value),
+ builder.clone().max_rate(value),
+ builder.clone().additive_increment(value),
+ builder.clone().decrease_factor(value),
+ ]);
+ }
+ for config in configs {
+ assert_eq!(config.build().unwrap_err().kind(),
ErrorKind::ConfigInvalid);
+ }
+}
+
+#[test]
+fn implicit_initial_rate_respects_the_configured_range() {
+ let layer = AimdLayer::builder().max_rate(10.0).build().unwrap();
+ assert_eq!(layer.buckets.read.rate(), 10.0);
+ let layer = AimdLayer::builder().min_rate(3000.0).build().unwrap();
+ assert_eq!(layer.buckets.read.rate(), 3000.0);
+}
+
+fn builder() -> AimdLayerBuilder {
+ AimdLayer::builder()
+ .initial_rate(0.001)
+ .min_rate(0.001)
+ .max_rate(100.0)
+ .additive_increment(10.0)
+ .burst(1)
+ .window(Duration::from_secs(3600))
+ .with_sleep(|_| std::future::pending::<()>())
+}
+
+#[derive(Clone, Default)]
+struct CountingTransport(Arc<std::sync::atomic::AtomicUsize>);
+
+impl HttpTransport for CountingTransport {
+ async fn fetch(&self, _: Request<Buffer>) -> Result<Response<HttpBody>> {
+ self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ Ok(Response::new(HttpBody::new(
+ stream::iter([Ok(Buffer::from("a")), Ok(Buffer::from("b"))]),
+ Some(2),
+ )))
+ }
+}
+
+#[test]
+fn unmarked_and_presign_requests_bypass_admission() {
+ block_on(async {
+ let layer = builder().build().unwrap();
+ let counting = CountingTransport::default();
+ let transport = AimdTransport {
+ inner: HttpTransporter::new(counting.clone()),
+ buckets: layer.buckets.clone(),
+ sleep: layer.sleep.clone(),
+ };
+ layer.buckets.read.acquire(&*layer.sleep).await;
+ layer.buckets.write.acquire(&*layer.sleep).await;
+ layer.buckets.delete.acquire(&*layer.sleep).await;
+ layer.buckets.list.acquire(&*layer.sleep).await;
+ transport.fetch(Request::new(Buffer::new())).await.unwrap();
+ transport
+ .fetch(
+ Request::builder()
+ .extension(Operation::Presign)
+ .body(Buffer::new())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(counting.0.load(std::sync::atomic::Ordering::Relaxed), 2);
+ });
+}
+
+#[test]
+fn every_operation_uses_its_expected_budget() {
+ block_on(async {
+ let layer = builder().build().unwrap();
+ let transport = AimdTransport {
+ inner: HttpTransporter::new(CountingTransport::default()),
+ buckets: layer.buckets.clone(),
+ sleep: layer.sleep.clone(),
+ };
+ for (bucket, operations) in [
+ (&layer.buckets.read, vec![Operation::Read, Operation::Stat]),
+ (
+ &layer.buckets.write,
+ vec![
+ Operation::Write,
+ Operation::Copy,
+ Operation::Compose,
+ Operation::Rename,
+ Operation::Restore,
+ Operation::CreateDir,
+ ],
+ ),
+ (&layer.buckets.delete, vec![Operation::Delete]),
+ (&layer.buckets.list, vec![Operation::List]),
+ ] {
+ bucket.acquire(&*layer.sleep).await;
+ for operation in operations {
+ let req = Request::builder()
+ .extension(operation)
+ .body(Buffer::new())
+ .unwrap();
+ let mut pending = Box::pin(transport.fetch(req));
+ assert!(
+ poll!(&mut pending).is_pending(),
+ "{operation} must use this budget"
+ );
+ }
+ }
+ });
+}
+
+#[test]
+fn memory_operations_are_not_paced() {
+ block_on(async {
+ let layer = builder().build().unwrap();
+ layer.buckets.read.acquire(&*layer.sleep).await;
+ layer.buckets.write.acquire(&*layer.sleep).await;
+ let op = Operator::new(opendal_core::services::Memory::default())
+ .unwrap()
+ .layer(layer);
+ op.write("file", "value").await.unwrap();
+ assert_eq!(op.read("file").await.unwrap().to_bytes().as_ref(),
b"value");
+ });
+}
+
+#[test]
+fn cloned_layers_and_context_replay_share_request_admission() {
+ block_on(async {
+ let sleeps = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let calls = sleeps.clone();
+ let layer = builder()
+ .with_sleep(move |duration| {
+ assert!(duration > Duration::ZERO);
+ calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ std::future::pending::<()>()
+ })
+ .build()
+ .unwrap();
+ let counting = CountingTransport::default();
+ let context =
+
OperationContext::new().with_http_transport(HttpTransporter::new(counting.clone()));
+ let first = Operator::new(opendal_core::services::Memory::default())
+ .unwrap()
+ .with_context(context.clone())
+ .layer(layer.clone());
+ let second = Operator::new(opendal_core::services::Memory::default())
+ .unwrap()
+ .layer(layer.clone())
+ .with_context(context.clone());
+ let mut response = first
+ .context()
+ .http_transport()
+ .fetch(
+ Request::builder()
+ .extension(Operation::Read)
+ .body(Buffer::new())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response
+ .body_mut()
+ .read_all()
+ .await
+ .unwrap()
+ .to_bytes()
+ .as_ref(),
+ b"ab"
+ );
+
+ let mut blocked = Box::pin(
+ second.context().http_transport().fetch(
+ Request::builder()
+ .extension(Operation::Read)
+ .body(Buffer::new())
+ .unwrap(),
+ ),
+ );
+ assert!(poll!(&mut blocked).is_pending());
+ drop(blocked);
+
+ let replayed = first.with_context(context);
+ let mut blocked = Box::pin(
+ replayed.context().http_transport().fetch(
+ Request::builder()
+ .extension(Operation::Read)
+ .body(Buffer::new())
+ .unwrap(),
+ ),
+ );
+ assert!(
+ poll!(&mut blocked).is_pending(),
+ "replay must not reset the bucket"
+ );
+ assert_eq!(counting.0.load(std::sync::atomic::Ordering::Relaxed), 1);
+ assert_eq!(sleeps.load(std::sync::atomic::Ordering::Relaxed), 2);
+ });
+}
+
+#[tokio::test]
+async fn default_timer_wakes_request_admission() {
+ let start = opendal_core::raw::Instant::now();
+ let layer = AimdLayer::builder()
+ .initial_rate(100.0)
+ .max_rate(100.0)
+ .burst(1)
+ .build()
+ .unwrap();
+ let counting = CountingTransport::default();
+ let context =
+
OperationContext::new().with_http_transport(HttpTransporter::new(counting.clone()));
+ let op = Operator::new(opendal_core::services::Memory::default())
+ .unwrap()
+ .with_context(context)
+ .layer(layer);
+ for _ in 0..2 {
+ op.context()
+ .http_transport()
+ .fetch(
+ Request::builder()
+ .extension(Operation::Read)
+ .body(Buffer::new())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ }
+ assert!(start.elapsed() >= Duration::from_millis(10));
+ assert_eq!(counting.0.load(std::sync::atomic::Ordering::Relaxed), 2);
+}
diff --git a/core/src/lib.rs b/core/src/lib.rs
index ee15190397..455be081f4 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -483,6 +483,8 @@ pub mod services {
/// combining retries, timeouts, caching, or observability.
pub mod layers {
pub use opendal_core::layers::*;
+ #[cfg(feature = "layers-aimd")]
+ pub use opendal_layer_aimd::*;
#[cfg(feature = "layers-async-backtrace")]
pub use opendal_layer_async_backtrace::*;
#[cfg(feature = "layers-await-tree")]