1use std::fmt;
6use std::sync::Arc;
7
8use async_trait::async_trait;
9use futures::StreamExt;
10use futures::stream::BoxStream;
11use object_store::path::Path;
12use object_store::{
13 CopyOptions, GetOptions, GetRange, GetResult, GetResultPayload, ListResult, MultipartUpload,
14 ObjectMeta, ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result,
15};
16use serde::{Deserialize, Serialize};
17use tokio::sync::Semaphore;
18
19use crate::error::ItzmaError;
20
21pub const DEFAULT_GATE_MAX_BYTES: u64 = 64 << 20;
23pub const DEFAULT_GATE_MAX_REQUESTS: usize = 256;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[non_exhaustive]
33pub struct GateOptions {
34 pub max_bytes: u64,
37 pub max_requests: usize,
39}
40
41impl Default for GateOptions {
42 fn default() -> Self {
43 Self {
44 max_bytes: DEFAULT_GATE_MAX_BYTES,
45 max_requests: DEFAULT_GATE_MAX_REQUESTS,
46 }
47 }
48}
49
50impl GateOptions {
51 pub fn maintenance() -> Self {
53 Self {
54 max_bytes: DEFAULT_GATE_MAX_BYTES / 4,
55 max_requests: DEFAULT_GATE_MAX_REQUESTS,
56 }
57 }
58
59 pub fn max_bytes(mut self, max_bytes: u64) -> Self {
61 self.max_bytes = max_bytes;
62 self
63 }
64
65 pub fn max_requests(mut self, max_requests: usize) -> Self {
67 self.max_requests = max_requests;
68 self
69 }
70}
71
72pub struct GatedStore {
106 inner: Arc<dyn ObjectStore>,
107 requests: Semaphore,
108 bytes: Semaphore,
109 max_bytes: u32,
110}
111
112impl GatedStore {
113 pub fn new(inner: Arc<dyn ObjectStore>, options: GateOptions) -> crate::Result<Self> {
121 if options.max_requests == 0 || options.max_requests > Semaphore::MAX_PERMITS {
122 return Err(ItzmaError::InvalidConfig(
123 "a gate's max_requests must be at least 1 and fit a semaphore",
124 ));
125 }
126 let max_bytes = u32::try_from(options.max_bytes)
127 .ok()
128 .filter(|&b| b > 0)
129 .ok_or(ItzmaError::InvalidConfig(
130 "a gate's max_bytes must be between 1 and 4 GiB",
131 ))?;
132 Ok(Self {
133 inner,
134 requests: Semaphore::new(options.max_requests),
135 bytes: Semaphore::new(max_bytes as usize),
136 max_bytes,
137 })
138 }
139
140 fn weight(&self, options: &GetOptions) -> Option<u32> {
145 if options.head {
146 return Some(0);
147 }
148 match &options.range {
149 Some(GetRange::Bounded(r)) => Some(self.clamp(r.end.saturating_sub(r.start))),
150 Some(GetRange::Suffix(n)) => Some(self.clamp(*n)),
151 Some(GetRange::Offset(_)) | None => None,
152 }
153 }
154
155 fn clamp(&self, bytes: u64) -> u32 {
158 u32::try_from(bytes.min(u64::from(self.max_bytes))).unwrap_or(self.max_bytes)
159 }
160}
161
162fn closed(_: tokio::sync::AcquireError) -> object_store::Error {
164 object_store::Error::Generic {
165 store: "GatedStore",
166 source: "the gate's semaphore was closed".into(),
167 }
168}
169
170impl fmt::Debug for GatedStore {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 f.debug_struct("GatedStore")
173 .field("inner", &self.inner)
174 .field("max_bytes", &self.max_bytes)
175 .finish_non_exhaustive()
176 }
177}
178
179impl fmt::Display for GatedStore {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 write!(f, "GatedStore({})", self.inner)
182 }
183}
184
185#[async_trait]
186impl ObjectStore for GatedStore {
187 async fn put_opts(
188 &self,
189 location: &Path,
190 payload: PutPayload,
191 opts: PutOptions,
192 ) -> Result<PutResult> {
193 self.inner.put_opts(location, payload, opts).await
194 }
195
196 async fn put_multipart_opts(
197 &self,
198 location: &Path,
199 opts: PutMultipartOptions,
200 ) -> Result<Box<dyn MultipartUpload>> {
201 self.inner.put_multipart_opts(location, opts).await
202 }
203
204 async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
205 let weight = self.weight(&options);
206 let head = options.head;
207 let _request = self.requests.acquire().await.map_err(closed)?;
208 let mut bytes_permit = match weight {
214 Some(weight) => Some(self.bytes.acquire_many(weight).await.map_err(closed)?),
215 None => None,
216 };
217 let result = self.inner.get_opts(location, options).await?;
218 if head {
219 return Ok(result);
220 }
221 if bytes_permit.is_none() {
222 let len = self.clamp(result.range.end.saturating_sub(result.range.start));
223 bytes_permit = Some(self.bytes.acquire_many(len).await.map_err(closed)?);
224 }
225 let _bytes = bytes_permit;
226 let meta = result.meta.clone();
227 let range = result.range.clone();
228 let attributes = result.attributes.clone();
229 let bytes = result.bytes().await?;
230 Ok(GetResult {
231 payload: GetResultPayload::Stream(
232 futures::stream::once(async move { Ok(bytes) }).boxed(),
233 ),
234 meta,
235 range,
236 attributes,
237 extensions: Default::default(),
238 })
239 }
240
241 fn delete_stream(
242 &self,
243 locations: BoxStream<'static, Result<Path>>,
244 ) -> BoxStream<'static, Result<Path>> {
245 self.inner.delete_stream(locations)
246 }
247
248 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
249 self.inner.list(prefix)
250 }
251
252 fn list_with_offset(
253 &self,
254 prefix: Option<&Path>,
255 offset: &Path,
256 ) -> BoxStream<'static, Result<ObjectMeta>> {
257 self.inner.list_with_offset(prefix, offset)
258 }
259
260 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
261 self.inner.list_with_delimiter(prefix).await
262 }
263
264 async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
265 self.inner.copy_opts(from, to, options).await
266 }
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272 use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
273
274 use futures::FutureExt;
275 use object_store::ObjectStoreExt;
276 use object_store::memory::InMemory;
277 use tokio::sync::Notify;
278
279 #[derive(Debug, Default)]
282 struct Recording {
283 inner: InMemory,
284 in_flight: AtomicUsize,
285 max_in_flight: AtomicUsize,
286 bytes_in_flight: AtomicU64,
287 max_bytes_in_flight: AtomicU64,
288 park: AtomicBool,
289 parked: Notify,
290 entered: Notify,
291 }
292
293 impl fmt::Display for Recording {
294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295 write!(f, "Recording")
296 }
297 }
298
299 #[async_trait]
300 impl ObjectStore for Recording {
301 async fn put_opts(&self, l: &Path, p: PutPayload, o: PutOptions) -> Result<PutResult> {
302 self.inner.put_opts(l, p, o).await
303 }
304 async fn put_multipart_opts(
305 &self,
306 l: &Path,
307 o: PutMultipartOptions,
308 ) -> Result<Box<dyn MultipartUpload>> {
309 self.inner.put_multipart_opts(l, o).await
310 }
311 async fn get_opts(&self, l: &Path, o: GetOptions) -> Result<GetResult> {
312 let len = match &o.range {
313 Some(GetRange::Bounded(r)) => r.end - r.start,
314 _ => 0,
315 };
316 let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
317 self.max_in_flight.fetch_max(now, Ordering::SeqCst);
318 let bytes = self.bytes_in_flight.fetch_add(len, Ordering::SeqCst) + len;
319 self.max_bytes_in_flight.fetch_max(bytes, Ordering::SeqCst);
320 let parking = self.park.load(Ordering::SeqCst);
323 self.entered.notify_one();
324 if parking {
325 self.parked.notified().await;
326 }
327 for _ in 0..4 {
328 tokio::task::yield_now().await;
329 }
330 let got = self.inner.get_opts(l, o).await;
331 self.in_flight.fetch_sub(1, Ordering::SeqCst);
332 self.bytes_in_flight.fetch_sub(len, Ordering::SeqCst);
333 got
334 }
335 fn delete_stream(
336 &self,
337 l: BoxStream<'static, Result<Path>>,
338 ) -> BoxStream<'static, Result<Path>> {
339 self.inner.delete_stream(l)
340 }
341 fn list(&self, p: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
342 self.inner.list(p)
343 }
344 async fn list_with_delimiter(&self, p: Option<&Path>) -> Result<ListResult> {
345 self.inner.list_with_delimiter(p).await
346 }
347 async fn copy_opts(&self, f: &Path, t: &Path, o: CopyOptions) -> Result<()> {
348 self.inner.copy_opts(f, t, o).await
349 }
350 }
351
352 fn obj() -> Path {
353 Path::from("obj")
354 }
355
356 async fn setup(size: usize, options: GateOptions) -> (Arc<Recording>, Arc<GatedStore>) {
357 let inner = Arc::new(Recording::default());
358 inner
359 .put(&obj(), vec![7u8; size].into())
360 .await
361 .expect("put");
362 let gate = GatedStore::new(inner.clone(), options).expect("gate");
363 (inner, Arc::new(gate))
364 }
365
366 async fn read_all(gate: &Arc<GatedStore>, ranges: Vec<std::ops::Range<u64>>) {
367 let reads = ranges.into_iter().map(|r| {
368 let gate = gate.clone();
369 tokio::spawn(async move { gate.get_range(&obj(), r).await.expect("read") })
370 });
371 for read in futures::future::join_all(reads).await {
372 read.expect("join");
373 }
374 }
375
376 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
377 async fn never_more_requests_in_flight_than_the_gate_allows() {
378 let (inner, gate) = setup(1000, GateOptions::default().max_requests(3)).await;
379 read_all(&gate, (0..50).map(|i| i * 10..i * 10 + 10).collect()).await;
380 let max = inner.max_in_flight.load(Ordering::SeqCst);
381 assert!(max <= 3, "max in flight {max}");
382 }
383
384 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
385 async fn never_more_bytes_in_flight_than_the_gate_allows() {
386 let (inner, gate) = setup(4000, GateOptions::default().max_bytes(100)).await;
387 read_all(&gate, (0..50).map(|i| i * 40..i * 40 + 40).collect()).await;
388 let max = inner.max_bytes_in_flight.load(Ordering::SeqCst);
389 assert!(max <= 100, "max bytes in flight {max}");
390 }
391
392 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
393 async fn a_read_bigger_than_the_gate_is_admitted_alone() {
394 let (inner, gate) = setup(5000, GateOptions::default().max_bytes(100)).await;
395 let mut ranges: Vec<_> = (0..20).map(|i| i * 10..i * 10 + 10).collect();
396 ranges.insert(10, 0..1000);
397 read_all(&gate, ranges).await;
398 assert_eq!(inner.max_bytes_in_flight.load(Ordering::SeqCst), 1000);
399 assert_eq!(gate.bytes.available_permits(), 100);
400 }
401
402 #[tokio::test]
403 async fn the_body_is_read_before_the_permit_is_released() {
404 let (_inner, gate) = setup(100, GateOptions::default().max_requests(1)).await;
405 let got = gate
406 .get_opts(&obj(), GetOptions::default())
407 .await
408 .expect("get");
409 assert_eq!(
410 gate.requests.available_permits(),
411 1,
412 "permit held past the call"
413 );
414 assert_eq!(got.bytes().await.expect("body").len(), 100);
415 }
416
417 #[tokio::test]
418 async fn a_failed_read_releases_its_permits() {
419 let (_inner, gate) = setup(10, GateOptions::default().max_requests(1).max_bytes(10)).await;
420 let missing = gate.get(&Path::from("missing")).await;
421 assert!(matches!(missing, Err(object_store::Error::NotFound { .. })));
422 assert_eq!(gate.requests.available_permits(), 1);
423 assert_eq!(gate.bytes.available_permits(), 10);
424 }
425
426 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
427 async fn a_dropped_read_releases_its_permits() {
428 let (inner, gate) = setup(10, GateOptions::default().max_requests(1).max_bytes(10)).await;
429 inner.park.store(true, Ordering::SeqCst);
430 let held = {
431 let gate = gate.clone();
432 tokio::spawn(async move { gate.get_range(&obj(), 0..10).await })
433 };
434 inner.entered.notified().await;
435 assert_eq!(gate.requests.available_permits(), 0);
436 held.abort();
437 let _ = held.await;
438 assert_eq!(gate.requests.available_permits(), 1);
439 assert_eq!(gate.bytes.available_permits(), 10);
440 }
441
442 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
443 async fn a_small_read_queued_behind_a_full_gate_runs_once_it_frees() {
444 let (inner, gate) = setup(100, GateOptions::default().max_bytes(10)).await;
445 inner.park.store(true, Ordering::SeqCst);
446 let big = {
447 let gate = gate.clone();
448 tokio::spawn(async move { gate.get_range(&obj(), 0..100).await })
449 };
450 inner.entered.notified().await;
451 inner.park.store(false, Ordering::SeqCst);
452 let small = {
453 let gate = gate.clone();
454 tokio::spawn(async move { gate.get_range(&obj(), 0..1).await })
455 };
456 for _ in 0..1_000 {
459 tokio::task::yield_now().await;
460 }
461 assert_eq!(
462 inner.in_flight.load(Ordering::SeqCst),
463 1,
464 "a full gate let a read past"
465 );
466 assert!(!small.is_finished());
467 inner.parked.notify_one();
468 assert_eq!(big.await.expect("join").expect("big").len(), 100);
469 assert_eq!(small.await.expect("join").expect("small").len(), 1);
470 }
471
472 #[tokio::test]
473 async fn a_whole_object_bigger_than_the_gate_is_read_whole() {
474 let (_inner, gate) = setup(64 * 1024, GateOptions::default().max_bytes(1024)).await;
475 let got = gate
476 .get(&obj())
477 .await
478 .expect("get")
479 .bytes()
480 .await
481 .expect("body");
482 assert_eq!(got.len(), 64 * 1024);
483 }
484
485 #[tokio::test]
486 async fn a_local_file_body_is_read_inside_the_permit() {
487 let dir = tempfile::tempdir().expect("tempdir");
488 let local = object_store::local::LocalFileSystem::new_with_prefix(dir.path()).expect("fs");
489 local.put(&obj(), vec![1u8; 300].into()).await.expect("put");
490 let gate =
491 GatedStore::new(Arc::new(local), GateOptions::default().max_requests(1)).expect("gate");
492 let got = gate
493 .get_opts(&obj(), GetOptions::default())
494 .await
495 .expect("get");
496 assert_eq!(gate.requests.available_permits(), 1);
497 assert_eq!(got.bytes().await.expect("body").len(), 300);
498 assert_eq!(gate.head(&obj()).await.expect("head").size, 300);
499 }
500
501 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
502 async fn writes_deletes_copies_and_listings_bypass_the_gate() {
503 let (inner, gate) = setup(10, GateOptions::default().max_requests(1)).await;
504 inner.park.store(true, Ordering::SeqCst);
505 let held = {
506 let gate = gate.clone();
507 tokio::spawn(async move { gate.get_range(&obj(), 0..1).await })
508 };
509 inner.entered.notified().await;
510 let other = Path::from("other");
511 assert!(gate.put(&other, vec![1u8].into()).now_or_never().is_some());
512 assert!(
513 gate.copy(&other, &Path::from("copy"))
514 .now_or_never()
515 .is_some()
516 );
517 assert!(gate.delete(&other).now_or_never().is_some());
518 assert!(gate.list_with_delimiter(None).now_or_never().is_some());
519 let listed: Vec<_> = gate.list(None).collect().now_or_never().expect("list");
520 assert_eq!(listed.len(), 2);
521 inner.parked.notify_one();
522 held.await.expect("join").expect("read");
523 }
524
525 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
526 async fn small_reads_of_unknown_length_run_together() {
527 let (inner, gate) = setup(100, GateOptions::default().max_bytes(1000)).await;
530 inner.park.store(true, Ordering::SeqCst);
531 let reads: Vec<_> = (0..5)
532 .map(|_| {
533 let gate = gate.clone();
534 tokio::spawn(async move { gate.get(&obj()).await?.bytes().await })
535 })
536 .collect();
537 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
540 while inner.in_flight.load(Ordering::SeqCst) < 5 {
541 assert!(
542 std::time::Instant::now() < deadline,
543 "the reads never ran together"
544 );
545 tokio::task::yield_now().await;
546 }
547 assert_eq!(inner.in_flight.load(Ordering::SeqCst), 5);
548 while !reads.iter().all(|r| r.is_finished()) {
552 assert!(
553 std::time::Instant::now() < deadline,
554 "a parked read never woke"
555 );
556 inner.parked.notify_waiters();
557 tokio::task::yield_now().await;
558 }
559 for read in reads {
560 assert_eq!(read.await.expect("join").expect("read").len(), 100);
561 }
562 assert_eq!(gate.bytes.available_permits(), 1000);
563 }
564
565 #[test]
566 fn weights_follow_the_range() {
567 let gate = GatedStore::new(
568 Arc::new(InMemory::new()),
569 GateOptions::default().max_bytes(16 << 20),
570 )
571 .expect("gate");
572 let with = |range: Option<GetRange>| GetOptions::new().with_range(range);
573 assert_eq!(
574 gate.weight(&with(Some(GetRange::Bounded(10..30)))),
575 Some(20)
576 );
577 assert_eq!(gate.weight(&with(Some(GetRange::Suffix(64)))), Some(64));
578 assert_eq!(gate.weight(&with(Some(GetRange::Offset(5)))), None);
579 assert_eq!(gate.weight(&with(None)), None);
580 assert_eq!(gate.weight(&GetOptions::new().with_head(true)), Some(0));
581 let small = GatedStore::new(
582 Arc::new(InMemory::new()),
583 GateOptions::default().max_bytes(100),
584 )
585 .expect("gate");
586 assert_eq!(small.clamp(8 << 20), 100, "clamped to the gate");
587 assert_eq!(
588 small.weight(&with(Some(GetRange::Bounded(0..1000)))),
589 Some(100)
590 );
591 }
592
593 #[test]
594 fn options_out_of_range_are_refused() {
595 let store = || -> Arc<dyn ObjectStore> { Arc::new(InMemory::new()) };
596 for options in [
597 GateOptions::default().max_requests(0),
598 GateOptions::default().max_bytes(0),
599 GateOptions::default().max_bytes(u64::from(u32::MAX) + 1),
600 GateOptions::default().max_requests(Semaphore::MAX_PERMITS + 1),
601 ] {
602 assert!(matches!(
603 GatedStore::new(store(), options),
604 Err(ItzmaError::InvalidConfig(_))
605 ));
606 }
607 assert_eq!(
608 GateOptions::maintenance().max_bytes,
609 DEFAULT_GATE_MAX_BYTES / 4
610 );
611 }
612}