Skip to main content

risingwave_object_store/object/opendal_engine/
concurrent_limit.rs

1// Copyright 2026 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use opendal::layers::{
18    ConcurrentLimitLayer as OpendalConcurrentLimitLayer, ConcurrentLimitSemaphore,
19};
20use opendal::raw::{
21    Layer, OpCompose, OpCopy, OpCreateDir, OpList, OpPresign, OpRead, OpRename, OpRestore, OpStat,
22    OpWrite, RpCreateDir, RpPresign, RpRename, RpRestore, RpStat, Service, ServiceInfo, Servicer,
23    oio,
24};
25use opendal::{Capability, OperationContext, Result};
26use tokio::sync::{OwnedSemaphorePermit, Semaphore};
27
28#[derive(Clone, Debug)]
29struct SharedSemaphore(Arc<Semaphore>);
30
31impl SharedSemaphore {
32    fn new(permits: usize) -> Self {
33        Self(Arc::new(Semaphore::new(permits)))
34    }
35}
36
37impl ConcurrentLimitSemaphore for SharedSemaphore {
38    type Permit = OwnedSemaphorePermit;
39
40    async fn acquire(&self) -> Self::Permit {
41        self.0
42            .clone()
43            .acquire_owned()
44            .await
45            .expect("semaphore is never closed")
46    }
47}
48
49/// `OpenDAL`'s concurrency limiter, with list permits scoped to each `next` call.
50/// Keeping a lister alive between GC batches must not prevent stat or delete from
51/// acquiring the same operation permit. Other operations and HTTP bodies retain
52/// `OpenDAL`'s existing permit lifetimes.
53#[derive(Clone, Debug)]
54pub(super) struct ConcurrentLimitLayer {
55    inner: OpendalConcurrentLimitLayer<SharedSemaphore>,
56    semaphore: SharedSemaphore,
57}
58
59impl ConcurrentLimitLayer {
60    pub(super) fn new(permits: usize) -> Self {
61        let semaphore = SharedSemaphore::new(permits);
62        Self {
63            inner: OpendalConcurrentLimitLayer::with_semaphore(semaphore.clone()),
64            semaphore,
65        }
66    }
67
68    pub(super) fn with_http_concurrent_limit(mut self, permits: usize) -> Self {
69        self.inner = self
70            .inner
71            .with_http_semaphore(SharedSemaphore::new(permits));
72        self
73    }
74}
75
76impl Layer for ConcurrentLimitLayer {
77    fn apply_service(&self, inner: Servicer) -> Servicer {
78        Arc::new(ConcurrentLimitService {
79            limited: self.inner.apply_service(inner.clone()),
80            inner,
81            semaphore: self.semaphore.clone(),
82        })
83    }
84
85    fn apply_context(&self, srv: Servicer, inner: OperationContext) -> OperationContext {
86        self.inner.apply_context(srv, inner)
87    }
88}
89
90#[derive(Debug)]
91struct ConcurrentLimitService {
92    inner: Servicer,
93    limited: Servicer,
94    semaphore: SharedSemaphore,
95}
96
97impl Service for ConcurrentLimitService {
98    type Composer = oio::Composer;
99    type Copier = oio::Copier;
100    type Deleter = oio::Deleter;
101    type Lister = ConcurrentLimitLister;
102    type Reader = oio::Reader;
103    type Writer = oio::Writer;
104
105    fn info(&self) -> ServiceInfo {
106        self.limited.info()
107    }
108
109    fn capability(&self) -> Capability {
110        self.limited.capability()
111    }
112
113    async fn create_dir(
114        &self,
115        ctx: &OperationContext,
116        path: &str,
117        args: OpCreateDir,
118    ) -> Result<RpCreateDir> {
119        self.limited.create_dir(ctx, path, args).await
120    }
121
122    async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> {
123        self.limited.stat(ctx, path, args).await
124    }
125
126    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
127        self.limited.read(ctx, path, args)
128    }
129
130    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
131        self.limited.write(ctx, path, args)
132    }
133
134    fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
135        self.limited.delete(ctx)
136    }
137
138    fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
139        // Bypass only the upstream list wrapper, which holds a permit until drop.
140        // The replacement uses the very same semaphore as all other operations.
141        Ok(ConcurrentLimitLister {
142            inner: self.inner.list(ctx, path, args)?,
143            semaphore: self.semaphore.clone(),
144        })
145    }
146
147    fn copy(
148        &self,
149        ctx: &OperationContext,
150        from: &str,
151        to: &str,
152        args: OpCopy,
153    ) -> Result<Self::Copier> {
154        self.limited.copy(ctx, from, to, args)
155    }
156
157    // Forward compose and restore so they match capability(); the defaults return Unsupported.
158    fn compose(&self, ctx: &OperationContext, to: &str, args: OpCompose) -> Result<Self::Composer> {
159        self.limited.compose(ctx, to, args)
160    }
161
162    async fn restore(
163        &self,
164        ctx: &OperationContext,
165        path: &str,
166        args: OpRestore,
167    ) -> Result<RpRestore> {
168        self.limited.restore(ctx, path, args).await
169    }
170
171    async fn rename(
172        &self,
173        ctx: &OperationContext,
174        from: &str,
175        to: &str,
176        args: OpRename,
177    ) -> Result<RpRename> {
178        self.limited.rename(ctx, from, to, args).await
179    }
180
181    async fn presign(
182        &self,
183        ctx: &OperationContext,
184        path: &str,
185        args: OpPresign,
186    ) -> Result<RpPresign> {
187        self.limited.presign(ctx, path, args).await
188    }
189}
190
191struct ConcurrentLimitLister {
192    inner: oio::Lister,
193    semaphore: SharedSemaphore,
194}
195
196impl oio::List for ConcurrentLimitLister {
197    async fn next(&mut self) -> Result<Option<oio::Entry>> {
198        let _permit = self.semaphore.acquire().await;
199        self.inner.next().await
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use std::time::Duration;
206
207    use futures::{StreamExt, poll};
208    use opendal::Operator;
209    use opendal::raw::oio::List;
210    use opendal::services::Memory;
211
212    use super::*;
213
214    #[tokio::test]
215    async fn test_list_shares_operation_limit() {
216        let layer = ConcurrentLimitLayer::new(1);
217        let op = Operator::new(Memory::default())
218            .unwrap()
219            .layer(layer.clone());
220        op.write("file", "data").await.unwrap();
221        let mut objects = op.lister_with("").recursive(true).await.unwrap();
222        let permit = layer.semaphore.acquire().await;
223        let mut next = Box::pin(objects.next());
224        let mut stat = Box::pin(op.stat("file"));
225        assert!(poll!(next.as_mut()).is_pending());
226        assert!(poll!(stat.as_mut()).is_pending());
227        drop(permit);
228        tokio::time::timeout(Duration::from_secs(5), async {
229            assert_eq!(next.await.unwrap().unwrap().path(), "file");
230            stat.await.unwrap();
231        })
232        .await
233        .unwrap();
234        assert_eq!(layer.semaphore.0.available_permits(), 1);
235    }
236
237    struct PendingLister;
238
239    impl oio::List for PendingLister {
240        async fn next(&mut self) -> Result<Option<oio::Entry>> {
241            std::future::pending().await
242        }
243    }
244
245    struct FailingLister;
246
247    impl oio::List for FailingLister {
248        async fn next(&mut self) -> Result<Option<oio::Entry>> {
249            Err(opendal::Error::new(
250                opendal::ErrorKind::Unexpected,
251                "listing failed",
252            ))
253        }
254    }
255
256    #[tokio::test]
257    async fn test_list_releases_permit_on_cancellation_and_error() {
258        let layer = ConcurrentLimitLayer::new(1);
259        let op = Operator::new(Memory::default())
260            .unwrap()
261            .layer(layer.clone());
262        op.write("file", "data").await.unwrap();
263        let mut objects = ConcurrentLimitLister {
264            inner: Box::new(PendingLister),
265            semaphore: layer.semaphore.clone(),
266        };
267        let mut next = Box::pin(objects.next());
268        assert!(poll!(next.as_mut()).is_pending());
269        assert_eq!(layer.semaphore.0.available_permits(), 0);
270        let mut stat = Box::pin(op.stat("file"));
271        assert!(poll!(stat.as_mut()).is_pending());
272        drop(next);
273        tokio::time::timeout(Duration::from_secs(5), stat)
274            .await
275            .unwrap()
276            .unwrap();
277        assert_eq!(layer.semaphore.0.available_permits(), 1);
278
279        let mut objects = ConcurrentLimitLister {
280            inner: Box::new(FailingLister),
281            semaphore: layer.semaphore.clone(),
282        };
283        assert!(objects.next().await.is_err());
284        assert_eq!(layer.semaphore.0.available_permits(), 1);
285    }
286}