await_tree/
root.rs

1// Copyright 2023 RisingWave Labs
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 crate::context::TreeContext;
19use crate::registry::WeakRegistry;
20use crate::Registry;
21
22/// The root of an await-tree.
23pub struct TreeRoot {
24    pub(crate) context: Arc<TreeContext>,
25    pub(crate) registry: WeakRegistry,
26}
27
28tokio::task_local! {
29    pub(crate) static ROOT: TreeRoot
30}
31
32pub(crate) fn current_context() -> Option<Arc<TreeContext>> {
33    ROOT.try_with(|r| r.context.clone()).ok()
34}
35
36pub(crate) fn current_registry() -> Option<Registry> {
37    ROOT.try_with(|r| r.registry.upgrade()).ok().flatten()
38}
39
40impl TreeRoot {
41    /// Instrument the given future with the context of this tree root.
42    pub async fn instrument<F: Future>(self, future: F) -> F::Output {
43        ROOT.scope(self, future).await
44    }
45}