settings_storage/
stash_logger.rs

1// Copyright 2021 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 fuchsia_inspect::{self as inspect, Node, NumericProperty};
6use fuchsia_inspect_derive::Inspect;
7use settings_inspect_utils::managed_inspect_map::ManagedInspectMap;
8
9const STASH_INSPECT_NODE_NAME: &str = "stash_failures";
10
11pub struct StashInspectLogger {
12    /// Map from a setting's device storage key to its inspect data.
13    flush_failure_counts: ManagedInspectMap<StashInspectInfo>,
14}
15
16/// Contains the node and property used to record the number of stash failures for a given
17/// setting.
18///
19/// Inspect nodes are not used, but need to be held as they're deleted from inspect once they go
20/// out of scope.
21#[derive(Default, Inspect)]
22struct StashInspectInfo {
23    /// Node of this info.
24    inspect_node: inspect::Node,
25
26    /// Number of write failures.
27    count: inspect::UintProperty,
28}
29
30impl StashInspectLogger {
31    pub fn new(node: &Node) -> Self {
32        let inspect_node = node.create_child(STASH_INSPECT_NODE_NAME);
33        Self {
34            flush_failure_counts: ManagedInspectMap::<StashInspectInfo>::with_node(inspect_node),
35        }
36    }
37
38    /// Records a write failure for the given setting.
39    pub fn record_flush_failure(&mut self, key: String) {
40        let stash_inspect_info =
41            self.flush_failure_counts.get_or_insert_with(key, StashInspectInfo::default);
42        let _ = stash_inspect_info.count.add(1u64);
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use diagnostics_assertions::assert_data_tree;
50    use fuchsia_inspect::component;
51
52    // Verify that the StashInspectLogger accumulates failure counts to inspect.
53    #[fuchsia::test]
54    fn test_stash_logger() {
55        let inspector = component::inspector();
56        let mut logger = StashInspectLogger::new(inspector.root());
57
58        logger.record_flush_failure("test_key".to_string());
59        logger.record_flush_failure("test_key2".to_string());
60        logger.record_flush_failure("test_key2".to_string());
61
62        assert_data_tree!(inspector, root: {
63            stash_failures: {
64                "test_key": {
65                    "count": 1u64,
66                },
67                "test_key2": {
68                    "count": 2u64,
69                }
70            }
71        });
72    }
73}