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
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.

use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use crate::coprocessor::tracker::Tracker as CopTracker;
use crate::storage::kv::PerfStatisticsInstant;

pub fn track<'a, F: Future + 'a>(
    fut: F,
    cop_tracker: &'a mut CopTracker,
) -> impl Future<Output = F::Output> + 'a {
    Tracker::new(fut, cop_tracker)
}

#[pin_project]
struct Tracker<'a, F>
where
    F: Future,
{
    #[pin]
    fut: F,
    cop_tracker: &'a mut CopTracker,
}

impl<'a, F> Tracker<'a, F>
where
    F: Future,
{
    fn new(fut: F, cop_tracker: &'a mut CopTracker) -> Self {
        Tracker { fut, cop_tracker }
    }
}

impl<'a, F: Future> Future for Tracker<'a, F>
where
    F: Future,
{
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = self.project();

        this.cop_tracker.on_begin_item();
        let perf_statistics_instant = PerfStatisticsInstant::new();

        let res = this.fut.poll(cx);

        let perf_statistics = perf_statistics_instant.delta();
        this.cop_tracker.on_finish_item(None, perf_statistics);

        res
    }
}