-
Notifications
You must be signed in to change notification settings - Fork 8
/
detach.rs
80 lines (65 loc) · 2.28 KB
/
detach.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
// Copyright 2023 RisingWave Labs
//
// 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.
//! This example shows how a span can be detached from and remounted to the tree.
use std::time::Duration;
use await_tree::{Config, InstrumentAwait, Registry};
use futures::channel::oneshot::{self, Receiver};
use futures::future::{pending, select};
use futures::FutureExt;
use tokio::time::sleep;
async fn work(rx: Receiver<()>) {
let mut fut = pending().instrument_await("fut");
// poll `fut` under the `select` span
let _ = select(
sleep(Duration::from_millis(500))
.instrument_await("sleep")
.boxed(),
&mut fut,
)
.instrument_await("select")
.await;
// `select` span closed so `fut` is detached
// the elapsed time of `fut` should be preserved
// wait for the signal to continue
rx.instrument_await("rx").await.unwrap();
// poll `fut` under the root `work` span, and it'll be remounted
fut.await
}
#[tokio::main]
async fn main() {
let registry = Registry::new(Config::default());
let root = registry.register((), "work");
let (tx, rx) = oneshot::channel();
tokio::spawn(root.instrument(work(rx)));
sleep(Duration::from_millis(100)).await;
let tree = registry.get(()).unwrap().to_string();
// work [106.290ms]
// select [106.093ms]
// sleep [106.093ms]
// fut [106.093ms]
println!("{tree}");
sleep(Duration::from_secs(1)).await;
let tree = registry.get(()).unwrap().to_string();
// work [1.112s]
// rx [606.944ms]
// [Detached 4]
// fut [1.112s]
println!("{tree}");
tx.send(()).unwrap();
sleep(Duration::from_secs(1)).await;
let tree = registry.get(()).unwrap().to_string();
// work [2.117s]
// fut [2.117s]
println!("{tree}");
}