Skip to main content

mprobe_diagnostics/
metadata.rs

1//! Defines an API for reading the metadata associated with the diagnostic metrics.
2
3use bson::Document;
4
5use crate::error::KeyAccessError;
6use crate::error::ValueAccessResultExt;
7
8/// `Metadata` defines the metadata associated with the diagnostic metrics.
9#[derive(Debug, Clone)]
10pub struct Metadata {
11    /// Specifies the host name of the node that generated the diagnostic metrics.
12    pub host: String,
13
14    /// Specifies the process, e.g. mongod or mongos, that generated
15    /// the diagnostic metrics.
16    pub process: String,
17
18    /// Specifies the database version on the node.
19    pub version: String,
20}
21
22impl Metadata {
23    const COMMON_KEY: &str = "common";
24    const SERVER_STATUS_KEY: &str = "serverStatus";
25    const HOST_KEY: &str = "host";
26    const PROCESS_KEY: &str = "process";
27    const VERSION_KEY: &str = "version";
28
29    pub(crate) fn from_reference_document(doc: &Document) -> Result<Metadata, KeyAccessError> {
30        // In MongoDB 8.0 a new nested field, common, was introduced,
31        // and we have to account for it as well until all the previous
32        // versions are no longer supported.
33        let common = match doc.get_document(Self::COMMON_KEY) {
34            Ok(common) => common,
35            Err(_) => doc,
36        };
37
38        let server_status = common
39            .get_document(Self::SERVER_STATUS_KEY)
40            .map_value_access_err(Self::SERVER_STATUS_KEY)?;
41
42        let metadata = Self {
43            host: server_status
44                .get_str(Self::HOST_KEY)
45                .map_value_access_err(Self::HOST_KEY)?
46                .to_owned(),
47            process: server_status
48                .get_str(Self::PROCESS_KEY)
49                .map_value_access_err(Self::PROCESS_KEY)?
50                .to_owned(),
51            version: server_status
52                .get_str(Self::VERSION_KEY)
53                .map_value_access_err(Self::VERSION_KEY)?
54                .to_owned(),
55        };
56
57        Ok(metadata)
58    }
59}