Skip to main content

common_runtime/
runtime_default.rs

1// Copyright 2023 Greptime Team
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::future::Future;
16use std::sync::Arc;
17
18use tokio::runtime::Handle;
19pub use tokio::task::JoinHandle;
20
21use crate::Builder;
22use crate::runtime::{Dropper, RuntimeTrait};
23
24/// A runtime to run future tasks
25#[derive(Clone, Debug)]
26pub struct DefaultRuntime {
27    name: String,
28    handle: Handle,
29    // Used to receive a drop signal when dropper is dropped, inspired by databend
30    _dropper: Arc<Dropper>,
31}
32
33impl DefaultRuntime {
34    pub(crate) fn new(name: &str, handle: Handle, dropper: Arc<Dropper>) -> Self {
35        Self {
36            name: name.to_string(),
37            handle,
38            _dropper: dropper,
39        }
40    }
41
42    pub(crate) fn handle(&self) -> tokio::runtime::Handle {
43        self.handle.clone()
44    }
45}
46
47impl RuntimeTrait for DefaultRuntime {
48    fn builder() -> Builder {
49        Builder::default()
50    }
51
52    /// Spawn a future and execute it in this thread pool
53    ///
54    /// Similar to tokio::runtime::Runtime::spawn()
55    fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
56    where
57        F: Future + Send + 'static,
58        F::Output: Send + 'static,
59    {
60        self.handle.spawn(future)
61    }
62
63    /// Run the provided function on an executor dedicated to blocking
64    /// operations.
65    fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
66    where
67        F: FnOnce() -> R + Send + 'static,
68        R: Send + 'static,
69    {
70        self.handle.spawn_blocking(func)
71    }
72
73    /// Run a future to complete, this is the runtime's entry point
74    fn block_on<F: Future>(&self, future: F) -> F::Output {
75        self.handle.block_on(future)
76    }
77
78    fn name(&self) -> &str {
79        &self.name
80    }
81}