scuffle_batching/
dataloader.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;

/// A trait for fetching data in batches
pub trait DataLoaderFetcher {
    /// The incoming key type
    type Key: Clone + Eq + std::hash::Hash + Send + Sync;
    /// The outgoing value type
    type Value: Clone + Send + Sync;

    /// Load a batch of keys
    fn load(&self, keys: HashSet<Self::Key>) -> impl Future<Output = Option<HashMap<Self::Key, Self::Value>>> + Send;
}

/// A builder for a [`DataLoader`]
#[derive(Clone, Copy, Debug)]
#[must_use = "builders must be used to create a dataloader"]
pub struct DataLoaderBuilder<E> {
    batch_size: usize,
    concurrency: usize,
    delay: std::time::Duration,
    _phantom: std::marker::PhantomData<E>,
}

impl<E> Default for DataLoaderBuilder<E> {
    fn default() -> Self {
        Self::new()
    }
}

impl<E> DataLoaderBuilder<E> {
    /// Create a new builder
    pub const fn new() -> Self {
        Self {
            batch_size: 1000,
            concurrency: 50,
            delay: std::time::Duration::from_millis(5),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Set the batch size
    #[inline]
    pub const fn batch_size(mut self, batch_size: usize) -> Self {
        self.with_batch_size(batch_size);
        self
    }

    /// Set the delay
    #[inline]
    pub const fn delay(mut self, delay: std::time::Duration) -> Self {
        self.with_delay(delay);
        self
    }

    /// Set the concurrency
    #[inline]
    pub const fn concurrency(mut self, concurrency: usize) -> Self {
        self.with_concurrency(concurrency);
        self
    }

    /// Set the batch size
    #[inline]
    pub const fn with_batch_size(&mut self, batch_size: usize) -> &mut Self {
        self.batch_size = batch_size;
        self
    }

    /// Set the delay
    #[inline]
    pub const fn with_delay(&mut self, delay: std::time::Duration) -> &mut Self {
        self.delay = delay;
        self
    }

    /// Set the concurrency
    #[inline]
    pub const fn with_concurrency(&mut self, concurrency: usize) -> &mut Self {
        self.concurrency = concurrency;
        self
    }

    /// Build the dataloader
    #[inline]
    pub fn build(self, executor: E) -> DataLoader<E>
    where
        E: DataLoaderFetcher + Send + Sync + 'static,
    {
        DataLoader::new(executor, self.batch_size, self.concurrency, self.delay)
    }
}

/// A dataloader used to batch requests to a [`DataLoaderFetcher`]
#[must_use = "dataloaders must be used to load data"]
pub struct DataLoader<E>
where
    E: DataLoaderFetcher + Send + Sync + 'static,
{
    _auto_spawn: tokio::task::JoinHandle<()>,
    executor: Arc<E>,
    semaphore: Arc<tokio::sync::Semaphore>,
    current_batch: Arc<tokio::sync::Mutex<Option<Batch<E>>>>,
    batch_size: usize,
}

impl<E> DataLoader<E>
where
    E: DataLoaderFetcher + Send + Sync + 'static,
{
    /// Create a new dataloader
    pub fn new(executor: E, batch_size: usize, concurrency: usize, delay: std::time::Duration) -> Self {
        let semaphore = Arc::new(tokio::sync::Semaphore::new(concurrency.max(1)));
        let current_batch = Arc::new(tokio::sync::Mutex::new(None));
        let executor = Arc::new(executor);

        let join_handle = tokio::spawn(batch_loop(executor.clone(), current_batch.clone(), delay));

        Self {
            executor,
            _auto_spawn: join_handle,
            semaphore,
            current_batch,
            batch_size: batch_size.max(1),
        }
    }

    /// Create a builder for a [`DataLoader`]
    #[inline]
    pub const fn builder() -> DataLoaderBuilder<E> {
        DataLoaderBuilder::new()
    }

    /// Load a single key
    /// Can return an error if the underlying [`DataLoaderFetcher`] returns an
    /// error
    ///
    /// Returns `None` if the key is not found
    pub async fn load(&self, items: E::Key) -> Result<Option<E::Value>, ()> {
        Ok(self.load_many(std::iter::once(items)).await?.into_values().next())
    }

    /// Load many keys
    /// Can return an error if the underlying [`DataLoaderFetcher`] returns an
    /// error
    ///
    /// Returns a map of keys to values which may be incomplete if any of the
    /// keys were not found
    pub async fn load_many<I>(&self, items: I) -> Result<HashMap<E::Key, E::Value>, ()>
    where
        I: IntoIterator<Item = E::Key> + Send,
    {
        struct BatchWaiting<K, V> {
            keys: HashSet<K>,
            result: Arc<BatchResult<K, V>>,
        }

        let mut waiters = Vec::<BatchWaiting<E::Key, E::Value>>::new();

        let mut count = 0;

        {
            let mut new_batch = true;
            let mut batch = self.current_batch.lock().await;

            for item in items {
                if batch.is_none() {
                    batch.replace(Batch::new(self.semaphore.clone()));
                    new_batch = true;
                }

                let batch_mut = batch.as_mut().unwrap();
                batch_mut.items.insert(item.clone());

                if new_batch {
                    new_batch = false;
                    waiters.push(BatchWaiting {
                        keys: HashSet::new(),
                        result: batch_mut.result.clone(),
                    });
                }

                let waiting = waiters.last_mut().unwrap();
                waiting.keys.insert(item);

                count += 1;

                if batch_mut.items.len() >= self.batch_size {
                    tokio::spawn(batch.take().unwrap().spawn(self.executor.clone()));
                }
            }
        }

        let mut results = HashMap::with_capacity(count);
        for waiting in waiters {
            let result = waiting.result.wait().await?;
            results.extend(waiting.keys.into_iter().filter_map(|key| {
                let value = result.get(&key)?.clone();
                Some((key, value))
            }));
        }

        Ok(results)
    }
}

async fn batch_loop<E>(
    executor: Arc<E>,
    current_batch: Arc<tokio::sync::Mutex<Option<Batch<E>>>>,
    delay: std::time::Duration,
) where
    E: DataLoaderFetcher + Send + Sync + 'static,
{
    let mut delay_delta = delay;
    loop {
        tokio::time::sleep(delay_delta).await;

        let mut batch = current_batch.lock().await;
        let Some(created_at) = batch.as_ref().map(|b| b.created_at) else {
            delay_delta = delay;
            continue;
        };

        let remaining = delay.saturating_sub(created_at.elapsed());
        if remaining == std::time::Duration::ZERO {
            tokio::spawn(batch.take().unwrap().spawn(executor.clone()));
            delay_delta = delay;
        } else {
            delay_delta = remaining;
        }
    }
}

struct BatchResult<K, V> {
    values: tokio::sync::OnceCell<Option<HashMap<K, V>>>,
    token: tokio_util::sync::CancellationToken,
}

impl<K, V> BatchResult<K, V> {
    fn new() -> Self {
        Self {
            values: tokio::sync::OnceCell::new(),
            token: tokio_util::sync::CancellationToken::new(),
        }
    }

    async fn wait(&self) -> Result<&HashMap<K, V>, ()> {
        if !self.token.is_cancelled() {
            self.token.cancelled().await;
        }

        self.values.get().ok_or(())?.as_ref().ok_or(())
    }
}

struct Batch<E>
where
    E: DataLoaderFetcher + Send + Sync + 'static,
{
    items: HashSet<E::Key>,
    result: Arc<BatchResult<E::Key, E::Value>>,
    semaphore: Arc<tokio::sync::Semaphore>,
    created_at: std::time::Instant,
}

impl<E> Batch<E>
where
    E: DataLoaderFetcher + Send + Sync + 'static,
{
    fn new(semaphore: Arc<tokio::sync::Semaphore>) -> Self {
        Self {
            items: HashSet::new(),
            result: Arc::new(BatchResult::new()),
            semaphore,
            created_at: std::time::Instant::now(),
        }
    }

    async fn spawn(self, executor: Arc<E>) {
        let _drop_guard = self.result.token.clone().drop_guard();
        let _ticket = self.semaphore.acquire_owned().await.unwrap();
        let result = executor.load(self.items).await;

        #[cfg_attr(all(coverage_nightly, test), coverage(off))]
        fn unknwown_error<E>(_: E) -> ! {
            unreachable!(
                "batch result already set, this is a bug please report it https://github.com/scufflecloud/scuffle/issues"
            )
        }

        self.result.values.set(result).map_err(unknwown_error).unwrap();
    }
}

#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[cfg(test)]
mod tests {
    use std::sync::atomic::AtomicUsize;

    use super::*;

    struct TestFetcher<K, V> {
        values: HashMap<K, V>,
        delay: std::time::Duration,
        requests: Arc<AtomicUsize>,
        capacity: usize,
    }

    impl<K, V> DataLoaderFetcher for TestFetcher<K, V>
    where
        K: Clone + Eq + std::hash::Hash + Send + Sync,
        V: Clone + Send + Sync,
    {
        type Key = K;
        type Value = V;

        async fn load(&self, keys: HashSet<Self::Key>) -> Option<HashMap<Self::Key, Self::Value>> {
            assert!(keys.len() <= self.capacity);
            tokio::time::sleep(self.delay).await;
            self.requests.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Some(
                keys.into_iter()
                    .filter_map(|k| {
                        let value = self.values.get(&k)?.clone();
                        Some((k, value))
                    })
                    .collect(),
            )
        }
    }

    #[tokio::test]
    async fn basic() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 2,
        };

        let loader = DataLoader::builder().batch_size(2).concurrency(1).build(fetcher);

        let start = std::time::Instant::now();
        let a = loader.load("a").await.unwrap();
        assert_eq!(a, Some(1));
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 1);

        let start = std::time::Instant::now();
        let b = loader.load("b").await.unwrap();
        assert_eq!(b, Some(2));
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 2);
        let start = std::time::Instant::now();
        let c = loader.load("c").await.unwrap();
        assert_eq!(c, Some(3));
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 3);

        let start = std::time::Instant::now();
        let ab = loader.load_many(vec!["a", "b"]).await.unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1), ("b", 2)]));
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 4);

        let start = std::time::Instant::now();
        let unknown = loader.load("unknown").await.unwrap();
        assert_eq!(unknown, None);
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 5);
    }

    #[tokio::test]
    async fn concurrency_high() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 2,
        };

        let loader = DataLoader::builder().batch_size(2).concurrency(10).build(fetcher);

        let start = std::time::Instant::now();
        let ab = loader
            .load_many(vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"])
            .await
            .unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]));
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 5);
    }

    #[tokio::test]
    async fn delay_low() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 2,
        };

        let loader = DataLoader::builder()
            .batch_size(2)
            .concurrency(1)
            .delay(std::time::Duration::from_millis(10))
            .build(fetcher);

        let start = std::time::Instant::now();
        let ab = loader
            .load_many(vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"])
            .await
            .unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]));
        assert!(start.elapsed() < std::time::Duration::from_millis(35));
        assert!(start.elapsed() >= std::time::Duration::from_millis(25));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 5);
    }

    #[tokio::test]
    async fn batch_size() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 100,
        };

        let loader = DataLoaderBuilder::default()
            .batch_size(100)
            .concurrency(1)
            .delay(std::time::Duration::from_millis(10))
            .build(fetcher);

        let start = std::time::Instant::now();
        let ab = loader
            .load_many(vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"])
            .await
            .unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]));
        assert!(start.elapsed() >= std::time::Duration::from_millis(10));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn high_concurrency() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter((0..1134).map(|i| (i, i * 2 + 5))),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 100,
        };

        let loader = DataLoaderBuilder::default()
            .batch_size(100)
            .concurrency(10)
            .delay(std::time::Duration::from_millis(10))
            .build(fetcher);

        let start = std::time::Instant::now();
        let ab = loader.load_many(0..1134).await.unwrap();
        assert_eq!(ab, HashMap::from_iter((0..1134).map(|i| (i, i * 2 + 5))));
        assert!(start.elapsed() >= std::time::Duration::from_millis(15));
        assert!(start.elapsed() < std::time::Duration::from_millis(25));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 1134 / 100 + 1);
    }

    #[tokio::test]
    async fn delayed_start() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 2,
        };

        let loader = DataLoader::builder()
            .batch_size(2)
            .concurrency(100)
            .delay(std::time::Duration::from_millis(10))
            .build(fetcher);

        tokio::time::sleep(std::time::Duration::from_millis(20)).await;

        let start = std::time::Instant::now();
        let ab = loader
            .load_many(vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"])
            .await
            .unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]));
        assert!(start.elapsed() >= std::time::Duration::from_millis(5));
        assert!(start.elapsed() < std::time::Duration::from_millis(25));
    }

    #[tokio::test]
    async fn delayed_start_single() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 2,
        };

        let loader = DataLoader::builder()
            .batch_size(2)
            .concurrency(100)
            .delay(std::time::Duration::from_millis(10))
            .build(fetcher);

        tokio::time::sleep(std::time::Duration::from_millis(5)).await;

        let start = std::time::Instant::now();
        let ab = loader.load_many(vec!["a"]).await.unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1)]));
        assert!(start.elapsed() >= std::time::Duration::from_millis(15));
        assert!(start.elapsed() < std::time::Duration::from_millis(20));
    }

    #[tokio::test]
    async fn deduplication() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 4,
        };

        let loader = DataLoader::builder()
            .batch_size(4)
            .concurrency(1)
            .delay(std::time::Duration::from_millis(10))
            .build(fetcher);

        let start = std::time::Instant::now();
        let ab = loader.load_many(vec!["a", "a", "b", "b", "c", "c"]).await.unwrap();
        assert_eq!(ab, HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert!(start.elapsed() >= std::time::Duration::from_millis(5));
        assert!(start.elapsed() < std::time::Duration::from_millis(20));
    }

    #[tokio::test]
    async fn already_batch() {
        let requests = Arc::new(AtomicUsize::new(0));

        let fetcher = TestFetcher {
            values: HashMap::from_iter(vec![("a", 1), ("b", 2), ("c", 3)]),
            delay: std::time::Duration::from_millis(5),
            requests: requests.clone(),
            capacity: 2,
        };

        let loader = DataLoader::builder().batch_size(10).concurrency(1).build(fetcher);

        let start = std::time::Instant::now();
        let (a, b) = tokio::join!(loader.load("a"), loader.load("b"));
        assert_eq!(a, Ok(Some(1)));
        assert_eq!(b, Ok(Some(2)));
        assert!(start.elapsed() < std::time::Duration::from_millis(15));
        assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 1);
    }
}