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
8pub mod refaults;
9
10#[derive(Default)]
11pub struct MemoryStallMetrics {
12    pub some: std::time::Duration,
13    pub full: std::time::Duration,
14}
15
16impl TryFrom<zx::MemoryStall> for MemoryStallMetrics {
17    type Error = TryFromIntError;
18
19    fn try_from(stall: zx::MemoryStall) -> Result<Self, Self::Error> {
20        Ok(Self {
21            some: std::time::Duration::from_nanos(stall.stall_time_some.try_into()?),
22            full: std::time::Duration::from_nanos(stall.stall_time_full.try_into()?),
23        })
24    }
25}
26
27pub trait StallProvider: Clone + Sync + Send + 'static {
28    /// Return the current memory stall values from the kernel.
29    fn get_stall_info(&self) -> Result<MemoryStallMetrics, anyhow::Error>;
30}
31
32#[derive(Clone)]
33pub struct StallProviderImpl {
34    /// Memory stall kernel resource, for issuing queries.
35    stall_resource: Arc<dyn StallResource>,
36}
37
38/// Trait for a resource exposing memory stall information. Used for dependency injection in unit
39/// tests.
40pub trait StallResource: Sync + Send {
41    fn get_memory_stall(&self) -> Result<zx::MemoryStall, zx::Status>;
42}
43
44impl StallResource for zx::Resource {
45    fn get_memory_stall(&self) -> Result<zx::MemoryStall, zx::Status> {
46        self.memory_stall()
47    }
48}
49
50impl StallProviderImpl {
51    /// Create a new [StallProviderImpl], wrapping a [StallResource].
52    pub fn new(stall_resource: Arc<dyn StallResource>) -> Result<StallProviderImpl, anyhow::Error> {
53        Ok(StallProviderImpl { stall_resource: stall_resource })
54    }
55}
56
57impl StallProvider for StallProviderImpl {
58    fn get_stall_info(&self) -> Result<MemoryStallMetrics, anyhow::Error> {
59        Ok(self.stall_resource.get_memory_stall()?.try_into()?)
60    }
61}