common_runtime/
runtime_throttleable.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
// Copyright 2023 Greptime Team
//
// Licensed 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::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;

use futures::FutureExt;
use ratelimit::Ratelimiter;
use snafu::ResultExt;
use tokio::runtime::Handle;
pub use tokio::task::JoinHandle;
use tokio::time::Sleep;

use crate::error::{BuildRuntimeRateLimiterSnafu, Result};
use crate::runtime::{Dropper, Priority, RuntimeTrait};
use crate::Builder;

struct RuntimeRateLimiter {
    pub ratelimiter: Option<Ratelimiter>,
}

impl Debug for RuntimeRateLimiter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RuntimeThrottleShareWithFuture")
            .field(
                "ratelimiter_max_tokens",
                &self.ratelimiter.as_ref().map(|v| v.max_tokens()),
            )
            .field(
                "ratelimiter_refill_amount",
                &self.ratelimiter.as_ref().map(|v| v.refill_amount()),
            )
            .finish()
    }
}

/// A runtime to run future tasks
#[derive(Clone, Debug)]
pub struct ThrottleableRuntime {
    name: String,
    handle: Handle,
    shared_with_future: Arc<RuntimeRateLimiter>,
    // Used to receive a drop signal when dropper is dropped, inspired by databend
    _dropper: Arc<Dropper>,
}

impl ThrottleableRuntime {
    pub(crate) fn new(
        name: &str,
        priority: Priority,
        handle: Handle,
        dropper: Arc<Dropper>,
    ) -> Result<Self> {
        Ok(Self {
            name: name.to_string(),
            handle,
            shared_with_future: Arc::new(RuntimeRateLimiter {
                ratelimiter: priority.ratelimiter_count()?,
            }),
            _dropper: dropper,
        })
    }
}

impl RuntimeTrait for ThrottleableRuntime {
    fn builder() -> Builder {
        Builder::default()
    }

    /// Spawn a future and execute it in this thread pool
    ///
    /// Similar to tokio::runtime::Runtime::spawn()
    fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        self.handle
            .spawn(ThrottleFuture::new(self.shared_with_future.clone(), future))
    }

    /// Run the provided function on an executor dedicated to blocking
    /// operations.
    fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        self.handle.spawn_blocking(func)
    }

    /// Run a future to complete, this is the runtime's entry point
    fn block_on<F: Future>(&self, future: F) -> F::Output {
        self.handle.block_on(future)
    }

    fn name(&self) -> &str {
        &self.name
    }
}

enum State {
    Pollable,
    Throttled(Pin<Box<Sleep>>),
}

impl State {
    fn unwrap_backoff(&mut self) -> &mut Pin<Box<Sleep>> {
        match self {
            State::Throttled(sleep) => sleep,
            _ => panic!("unwrap_backoff failed"),
        }
    }
}

#[pin_project::pin_project]
pub struct ThrottleFuture<F: Future + Send + 'static> {
    #[pin]
    future: F,

    /// RateLimiter of this future
    handle: Arc<RuntimeRateLimiter>,

    state: State,
}

impl<F> ThrottleFuture<F>
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    fn new(handle: Arc<RuntimeRateLimiter>, future: F) -> Self {
        Self {
            future,
            handle,
            state: State::Pollable,
        }
    }
}

impl<F> Future for ThrottleFuture<F>
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    type Output = F::Output;

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();

        match this.state {
            State::Pollable => {}
            State::Throttled(ref mut sleep) => match sleep.poll_unpin(cx) {
                Poll::Ready(_) => {
                    *this.state = State::Pollable;
                }
                Poll::Pending => return Poll::Pending,
            },
        };

        if let Some(ratelimiter) = &this.handle.ratelimiter {
            if let Err(wait) = ratelimiter.try_wait() {
                *this.state = State::Throttled(Box::pin(tokio::time::sleep(wait)));
                match this.state.unwrap_backoff().poll_unpin(cx) {
                    Poll::Ready(_) => {
                        *this.state = State::Pollable;
                    }
                    Poll::Pending => {
                        return Poll::Pending;
                    }
                }
            }
        }

        let poll_res = this.future.poll(cx);

        match poll_res {
            Poll::Ready(r) => Poll::Ready(r),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Priority {
    fn ratelimiter_count(&self) -> Result<Option<Ratelimiter>> {
        let max = 8000;
        let gen_per_10ms = match self {
            Priority::VeryLow => Some(2000),
            Priority::Low => Some(4000),
            Priority::Middle => Some(6000),
            Priority::High => Some(8000),
            Priority::VeryHigh => None,
        };
        if let Some(gen_per_10ms) = gen_per_10ms {
            Ratelimiter::builder(gen_per_10ms, Duration::from_millis(10)) // generate poll count per 10ms
                .max_tokens(max) // reserved token for batch request
                .build()
                .context(BuildRuntimeRateLimiterSnafu)
                .map(Some)
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod tests {

    use tokio::fs::File;
    use tokio::io::AsyncWriteExt;
    use tokio::time::Duration;

    use super::*;
    use crate::runtime::BuilderBuild;

    #[tokio::test]
    async fn test_throttleable_runtime_spawn_simple() {
        for p in [
            Priority::VeryLow,
            Priority::Low,
            Priority::Middle,
            Priority::High,
            Priority::VeryHigh,
        ] {
            let runtime: ThrottleableRuntime = Builder::default()
                .runtime_name("test")
                .thread_name("test")
                .worker_threads(8)
                .priority(p)
                .build()
                .expect("Fail to create runtime");

            // Spawn a simple future that returns 42
            let handle = runtime.spawn(async {
                tokio::time::sleep(Duration::from_millis(10)).await;
                42
            });
            let result = handle.await.expect("Task panicked");
            assert_eq!(result, 42);
        }
    }

    #[tokio::test]
    async fn test_throttleable_runtime_spawn_complex() {
        let tempdir = tempfile::tempdir().unwrap();
        for p in [
            Priority::VeryLow,
            Priority::Low,
            Priority::Middle,
            Priority::High,
            Priority::VeryHigh,
        ] {
            let runtime: ThrottleableRuntime = Builder::default()
                .runtime_name("test")
                .thread_name("test")
                .worker_threads(8)
                .priority(p)
                .build()
                .expect("Fail to create runtime");
            let tempdirpath = tempdir.path().to_path_buf();
            let handle = runtime.spawn(async move {
                let mut file = File::create(tempdirpath.join("test.txt")).await.unwrap();
                file.write_all(b"Hello, world!").await.unwrap();
                42
            });
            let result = handle.await.expect("Task panicked");
            assert_eq!(result, 42);
        }
    }
}