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