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::runtime::{Dropper, RuntimeTrait};
22use crate::Builder;
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
43impl RuntimeTrait for DefaultRuntime {
44 fn builder() -> Builder {
45 Builder::default()
46 }
47
48 /// Spawn a future and execute it in this thread pool
49 ///
50 /// Similar to tokio::runtime::Runtime::spawn()
51 fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
52 where
53 F: Future + Send + 'static,
54 F::Output: Send + 'static,
55 {
56 self.handle.spawn(future)
57 }
58
59 /// Run the provided function on an executor dedicated to blocking
60 /// operations.
61 fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
62 where
63 F: FnOnce() -> R + Send + 'static,
64 R: Send + 'static,
65 {
66 self.handle.spawn_blocking(func)
67 }
68
69 /// Run a future to complete, this is the runtime's entry point
70 fn block_on<F: Future>(&self, future: F) -> F::Output {
71 self.handle.block_on(future)
72 }
73
74 fn name(&self) -> &str {
75 &self.name
76 }
77}