File size: 4,770 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use std::{
    borrow::Cow,
    cell::RefCell,
    fmt::Display,
    future::Future,
    panic,
    pin::Pin,
    task::{Context, Poll},
    time::{Duration, Instant},
};

use anyhow::Result;
use pin_project_lite::pin_project;
use serde::{Deserialize, Serialize};
use turbo_tasks_malloc::{AllocationInfo, TurboMalloc};

use crate::{backend::TurboTasksExecutionErrorMessage, panic_hooks::LAST_ERROR_LOCATION};

struct ThreadLocalData {
    duration: Duration,
    allocations: usize,
    deallocations: usize,
}

thread_local! {
    static EXTRA: RefCell<Option<*mut ThreadLocalData>> = const { RefCell::new(None) };
}

pin_project! {
    pub struct CaptureFuture<T, F: Future<Output = T>> {
        #[pin]
        future: F,
        duration: Duration,
        allocations: usize,
        deallocations: usize,
    }
}

impl<T, F: Future<Output = T>> CaptureFuture<T, F> {
    pub fn new(future: F) -> Self {
        Self {
            future,
            duration: Duration::ZERO,
            allocations: 0,
            deallocations: 0,
        }
    }
}

fn try_with_thread_local_data(f: impl FnOnce(&mut ThreadLocalData)) {
    EXTRA.with_borrow(|cell| {
        if let Some(data) = cell {
            // Safety: This data is thread local and only accessed in this thread
            unsafe {
                f(&mut **data);
            }
        }
    });
}

pub fn add_duration(duration: Duration) {
    try_with_thread_local_data(|data| {
        data.duration += duration;
    });
}

pub fn add_allocation_info(alloc_info: AllocationInfo) {
    try_with_thread_local_data(|data| {
        data.allocations += alloc_info.allocations;
        data.deallocations += alloc_info.deallocations;
    });
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TurboTasksPanic {
    pub message: TurboTasksExecutionErrorMessage,
    pub location: Option<String>,
}

impl Display for TurboTasksPanic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl<T, F: Future<Output = T>> Future for CaptureFuture<T, F> {
    type Output = (Result<T, TurboTasksPanic>, Duration, usize);

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let start = Instant::now();
        let start_allocations = TurboMalloc::allocation_counters();
        let guard = ThreadLocalDataDropGuard;
        let mut data = ThreadLocalData {
            duration: Duration::ZERO,
            allocations: 0,
            deallocations: 0,
        };
        EXTRA.with_borrow_mut(|cell| {
            *cell = Some(&mut data as *mut ThreadLocalData);
        });

        let result =
            panic::catch_unwind(panic::AssertUnwindSafe(|| this.future.poll(cx))).map_err(|err| {
                let message = match err.downcast_ref::<&'static str>() {
                    Some(s) => TurboTasksExecutionErrorMessage::PIISafe(Cow::Borrowed(s)),
                    None => match err.downcast_ref::<String>() {
                        Some(s) => TurboTasksExecutionErrorMessage::NonPIISafe(s.clone()),
                        None => {
                            let error_message = err
                                .downcast_ref::<Box<dyn Display>>()
                                .map(|e| e.to_string())
                                .unwrap_or_else(|| String::from("<unknown panic>"));

                            TurboTasksExecutionErrorMessage::NonPIISafe(error_message)
                        }
                    },
                };

                LAST_ERROR_LOCATION.with_borrow(|loc| TurboTasksPanic {
                    message,
                    location: loc.clone(),
                })
            });

        drop(guard);
        let elapsed = start.elapsed();
        let allocations = start_allocations.until_now();
        *this.duration += elapsed + data.duration;
        *this.allocations += allocations.allocations + data.allocations;
        *this.deallocations += allocations.deallocations + data.deallocations;
        match result {
            Err(err) => {
                let memory_usage = this.allocations.saturating_sub(*this.deallocations);
                Poll::Ready((Err(err), *this.duration, memory_usage))
            }
            Ok(Poll::Ready(r)) => {
                let memory_usage = this.allocations.saturating_sub(*this.deallocations);
                Poll::Ready((Ok(r), *this.duration, memory_usage))
            }
            Ok(Poll::Pending) => Poll::Pending,
        }
    }
}

struct ThreadLocalDataDropGuard;

impl Drop for ThreadLocalDataDropGuard {
    fn drop(&mut self) {
        EXTRA.with_borrow_mut(|cell| {
            *cell = None;
        });
    }
}