stalls/
lib.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::num::TryFromIntError;
6use std::sync::Arc;
7
8#[derive(Default)]
9pub struct MemoryStallMetrics {
10    pub some: std::time::Duration,
11    pub full: std::time::Duration,
12}
13
14impl TryFrom<zx::MemoryStall> for MemoryStallMetrics {
15    type Error = TryFromIntError;
16
17    fn try_from(stall: zx::MemoryStall) -> Result<Self, Self::Error> {
18        Ok(Self {
19            some: std::time::Duration::from_nanos(stall.stall_time_some.try_into()?),
20            full: std::time::Duration::from_nanos(stall.stall_time_full.try_into()?),
21        })
22    }
23}
24
25pub trait StallProvider: Sync + Send + 'static {
26    /// Return the current memory stall values from the kernel.
27    fn get_stall_info(&self) -> Result<MemoryStallMetrics, anyhow::Error>;
28}
29
30pub struct StallProviderImpl {
31    /// Memory stall kernel resource, for issuing queries.
32    stall_resource: Arc<dyn StallResource>,
33}
34
35/// Trait for a resource exposing memory stall information. Used for dependency injection in unit
36/// tests.
37pub trait StallResource: Sync + Send {
38    fn get_memory_stall(&self) -> Result<zx::MemoryStall, zx::Status>;
39}
40
41impl StallResource for zx::Resource {
42    fn get_memory_stall(&self) -> Result<zx::MemoryStall, zx::Status> {
43        self.memory_stall()
44    }
45}
46
47impl StallProviderImpl {
48    /// Create a new [StallProviderImpl], wrapping a [StallResource].
49    pub fn new(stall_resource: Arc<dyn StallResource>) -> Result<StallProviderImpl, anyhow::Error> {
50        Ok(StallProviderImpl { stall_resource: stall_resource })
51    }
52}
53
54impl StallProvider for StallProviderImpl {
55    fn get_stall_info(&self) -> Result<MemoryStallMetrics, anyhow::Error> {
56        Ok(self.stall_resource.get_memory_stall()?.try_into()?)
57    }
58}