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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
use std::{borrow::Cow, cell::RefCell, mem, sync::Arc};
use arc_swap::ArcSwapOption;
use im::Vector;
use crate::util::PhantomNotSend;
type GroupTags = &'static [(&'static str, &'static str)];
type TokenRegistry = Vector<Option<GroupTags>>;
// Holds the token registry, which maps allocation tokens to a set of static tags that describe who
// or what the allocations tied to that token belong to.
static TOKEN_REGISTRY: ArcSwapOption<TokenRegistry> = ArcSwapOption::const_empty();
thread_local! {
    /// The currently executing allocation token.
    ///
    /// Any allocations which occur on this thread will be associated with whichever token is
    /// present at the time of the allocation.
    static CURRENT_ALLOCATION_TOKEN: RefCell<Option<usize>> = RefCell::new(None);
}
/// A token that uniquely identifies an allocation group.
///
/// Allocation groups are the core grouping mechanism of `tracking-allocator` and drive much of its
/// behavior.  While the allocator must be overridden, and a global track provided, no allocations
/// are tracked unless a group is associated with the current thread making the allocation.
///
/// Practically speaking, allocation groups are simply an internal identifier that is used to
/// identify the "owner" of an allocation.  Additional tags can be provided when acquire an
/// allocation group token, which is provided to [`AllocationTracker`][crate::AllocationTracker]
/// whenever an allocation occurs.
///
/// ## Usage
///
/// In order for an allocation group to be attached to an allocation, its must be "entered."
/// [`AllocationGroupToken`] functions similarly to something like a mutex, where "entering" the
/// token conumes the token and provides a guard: [`AllocationGuard`].  This guard is tied to the
/// allocation group being active: if the guard is dropped, or if it is exited manually, the
/// allocation group is no longer active.
///
/// [`AllocationGuard`] also tracks if another allocation group was active prior to entering, and
/// ensures it is set back as the active allocation group when the guard is dropped.  This allows
/// allocation groups to be nested within each other.
pub struct AllocationGroupToken(usize);
impl AllocationGroupToken {
    /// Acquires an allocation group token.
    pub fn acquire() -> AllocationGroupToken {
        let mut id = 0;
        TOKEN_REGISTRY.rcu(|registry| {
            let mut registry = registry
                .as_ref()
                .map(|inner| inner.as_ref().clone())
                .unwrap_or_default();
            id = registry.len();
            registry.push_back(None);
            Some(Arc::new(registry))
        });
        AllocationGroupToken(id)
    }
    /// Acquires an allocation group token, with tags.
    ///
    /// While allocation groups are primarily represented by their [`AllocationGroupToken`], users can
    /// use this method to attach specific tags -- or key/value string pairs -- to the group.  These
    /// tags will be provided to the global tracker whenever an allocation event is associated with
    /// the allocation group.
    ///
    /// ## Memory usage
    ///
    /// In order to minimize any allocations while in the process of tracking normal allocations, we
    /// rely on utilizing only static references to data.  If the tags given are not already
    /// `'static` references, they will be leaked in order to make them `'static`.  Thus, callers
    /// should take care to avoid registering tokens on an ongoing basis when utilizing owned tags as
    /// this could create a persistent and ever-growing memory leak over the life of the process.
    pub fn acquire_with_tags<K, V>(tags: &[(K, V)]) -> AllocationGroupToken
    where
        K: Into<Cow<'static, str>> + Clone,
        V: Into<Cow<'static, str>> + Clone,
    {
        let tags = tags
            .iter()
            .map(|tag| {
                let (k, v) = tag;
                let sk = match k.clone().into() {
                    Cow::Borrowed(rs) => rs,
                    Cow::Owned(os) => Box::leak(os.into_boxed_str()),
                };
                let sv = match v.clone().into() {
                    Cow::Borrowed(rs) => rs,
                    Cow::Owned(os) => Box::leak(os.into_boxed_str()),
                };
                (sk, sv)
            })
            .collect::<Vec<_>>();
        let tags = &*Box::leak(tags.into_boxed_slice());
        let mut id = 0;
        TOKEN_REGISTRY.rcu(|registry| {
            let mut registry = registry
                .as_ref()
                .map(|inner| inner.as_ref().clone())
                .unwrap_or_default();
            id = registry.len();
            registry.push_back(Some(tags));
            Some(Arc::new(registry))
        });
        AllocationGroupToken(id)
    }
    pub(crate) fn into_unsafe(self) -> UnsafeAllocationGroupToken {
        UnsafeAllocationGroupToken::new(self.0)
    }
    /// Marks the associated allocation group as the active allocation group on this thread.
    ///
    /// If another allocation group is currently active, it is replaced, and restored either when
    /// this allocation guard is dropped, or when [`AllocationGuard::exit`] is called.
    pub fn enter(self) -> AllocationGuard {
        AllocationGuard::enter(self)
    }
}
#[cfg(feature = "tracing-compat")]
#[cfg_attr(docsrs, doc(cfg(feature = "tracing-compat")))]
impl AllocationGroupToken {
    /// Attaches this allocation group to a tracing [`Span`][tracing::Span].
    ///
    /// When the span is entered or exited, the allocation group will also transition from idle to
    /// active, or active to idle.  In effect, all allocations that occur while the span is entered
    /// will be associated with the allocation group.
    pub fn attach_to_span(self, span: &tracing::Span) {
        use crate::tracing::WithAllocationGroup;
        let mut unsafe_token = Some(self.into_unsafe());
        tracing::dispatcher::get_default(move |dispatch| {
            if let Some(id) = span.id() {
                if let Some(ctx) = dispatch.downcast_ref::<WithAllocationGroup>() {
                    let unsafe_token = unsafe_token.take().expect("token already consumed");
                    return ctx.with_allocation_group(dispatch, &id, unsafe_token);
                }
            }
        });
    }
}
enum GuardState {
    // Guard is idle.  We aren't the active allocation group.
    Idle(usize),
    // Guard is active.  We're the active allocation group, so we hold on to the previous
    // allocation group ID, if there was one, so we can switch back to it when we transition to
    // being idle.
    Active(Option<usize>),
}
impl GuardState {
    fn idle(id: usize) -> Self {
        Self::Idle(id)
    }
    fn transition_to_active(&mut self) {
        let new_state = match self {
            Self::Idle(id) => {
                // Set the current allocation token to the new token, keeping the previous.
                let previous = CURRENT_ALLOCATION_TOKEN.with(|current| current.replace(Some(*id)));
                Self::Active(previous)
            }
            Self::Active(_) => panic!("transitioning active->active is invalid"),
        };
        *self = new_state;
    }
    fn transition_to_idle(&mut self) -> usize {
        let (id, new_state) = match self {
            Self::Idle(_) => panic!("transitioning idle->idle is invalid"),
            Self::Active(previous) => {
                // Reset the current allocation token to the previous one.
                let current = CURRENT_ALLOCATION_TOKEN.with(|current| {
                    let old = mem::replace(&mut *current.borrow_mut(), previous.take());
                    old.expect("transitioned to idle state with empty CURRENT_ALLOCATION_TOKEN")
                });
                (current, Self::Idle(current))
            }
        };
        *self = new_state;
        id
    }
}
/// Guard that updates the current thread to track allocations for the associated allocation group.
///
/// ## Drop behavior
///
/// This guard has a [`Drop`] implementation that resets the active allocation group back to the
/// previous allocation group.
///
/// ## Moving across threads
///
/// [`AllocationGuard`] is specifically marked as `!Send` as the active allocation group is tracked
/// at a per-thread level.  If you acquire an `AllocationGuard` and need to resume computation on
/// another thread, such as across an await point or when simply sending objects to another thread,
/// you must first [`exit`][exit] the guard and move the resulting [`AllocationGroupToken`].  Once
/// on the new thread, you can then reacquire the guard.
///
/// [exit]: AllocationGuard::exit
pub struct AllocationGuard {
    state: GuardState,
    /// ```compile_fail
    /// use tracking_allocator::AllocationGuard;
    /// trait AssertSend: Send {}
    ///
    /// impl AssertSend for AllocationGuard {}
    /// ```
    _ns: PhantomNotSend,
}
impl AllocationGuard {
    pub(crate) fn enter(token: AllocationGroupToken) -> AllocationGuard {
        let mut state = GuardState::idle(token.0);
        state.transition_to_active();
        AllocationGuard {
            state,
            _ns: PhantomNotSend::default(),
        }
    }
    /// Unmarks this allocation group as the active allocation group on this thread, resetting the
    /// active allocation group to the previous value.
    pub fn exit(mut self) -> AllocationGroupToken {
        self.exit_inner()
    }
    fn exit_inner(&mut self) -> AllocationGroupToken {
        // Reset the current allocation token to the previous one.
        let current = self.state.transition_to_idle();
        AllocationGroupToken(current)
    }
}
impl Drop for AllocationGuard {
    fn drop(&mut self) {
        let _ = self.exit_inner();
    }
}
/// Unmanaged allocation group token used specifically with `tracing`.
///
/// ## Safety
/// While normally users would work directly with [`AllocationGroupToken`] and [`AllocationGuard`],
/// we cannot store [`AllocationGuard`] in span data as it is `!Send`, and tracing spans can be sent
/// across threads.
///
/// However, `tracing` itself employs a guard for entering spans.  The guard is `!Send`, which
/// ensures that the guard cannot be sent across threads.  Since the same guard is used to know when
/// a span has been exited, `tracing` ensures that between a span being entered and exited, it
/// cannot move threads.
///
/// Thus, we build off of that invariant, and use this stripped down token to manually enter and
/// exit the allocation group in a specialized `tracing_subscriber` layer that we control.
pub(crate) struct UnsafeAllocationGroupToken {
    state: GuardState,
}
impl UnsafeAllocationGroupToken {
    /// Creates a new `UnsafeAllocationGroupToken`.
    pub fn new(id: usize) -> Self {
        Self {
            state: GuardState::idle(id),
        }
    }
    /// Marks the associated allocation group as the active allocation group on this thread.
    ///
    /// If another allocation group is currently active, it is replaced, and restored either when
    /// this allocation guard is dropped, or when [`AllocationGuard::exit`] is called.
    ///
    /// Functionally equivalent to [`AllocationGroupToken::enter`].
    pub fn enter(&mut self) {
        self.state.transition_to_active();
    }
    /// Unmarks this allocation group as the active allocation group on this thread, resetting the
    /// active allocation group to the previous value.
    ///
    /// Functionally equivalent to [`AllocationGuard::exit`].
    pub fn exit(&mut self) {
        let _ = self.state.transition_to_idle();
    }
}
pub(crate) struct AllocationGroupMetadata {
    id: usize,
    tags: Option<GroupTags>,
}
impl AllocationGroupMetadata {
    pub fn id(&self) -> usize {
        self.id
    }
    pub fn tags(&self) -> Option<GroupTags> {
        self.tags
    }
}
/// Gets the current allocation group, if one isactive, and any metadata associated with it.
#[inline(always)]
pub(crate) fn get_active_allocation_group() -> Option<AllocationGroupMetadata> {
    // See if there's an active allocation token on this thread.
    CURRENT_ALLOCATION_TOKEN
        .with(|current| *current.borrow())
        .map(|id| {
            // Try and grab the tags from the registry.  This shouldn't ever failed since we wrap
            // registry IDs in AllocationToken which only we can create.
            let registry_guard = TOKEN_REGISTRY.load();
            let registry = registry_guard
                .as_ref()
                .expect("allocation token cannot be set unless registry has been created");
            let tags = registry.get(id).copied().flatten();
            AllocationGroupMetadata { id, tags }
        })
}