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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::common_utils::common::macros::{fx_err_and_bail, with_line};
use crate::power::types;
use anyhow::Error;
use fidl_fuchsia_power_metrics::{Metric, Power, RecorderMarker, RecorderProxy, StatisticsArgs};
use fuchsia_component::client::connect_to_protocol;
use serde_json::Value;

const CLIENT_ID: &'static str = "sl4f";

#[derive(Debug)]
pub struct PowerFacade {
    /// Optional logger proxy for testing.
    logger_proxy: Option<RecorderProxy>,
}

impl PowerFacade {
    pub fn new() -> PowerFacade {
        PowerFacade { logger_proxy: None }
    }

    fn get_logger_proxy(&self) -> Result<RecorderProxy, Error> {
        if let Some(proxy) = &self.logger_proxy {
            Ok(proxy.clone())
        } else {
            match connect_to_protocol::<RecorderMarker>() {
                Ok(proxy) => Ok(proxy),
                Err(e) => fx_err_and_bail!(
                    &with_line!("PowerFacade::get_logger_proxy"),
                    format_err!("Failed to create proxy: {:?}", e)
                ),
            }
        }
    }

    /// Initiates fixed-duration logging with the Recorder service.
    ///
    /// # Arguments
    /// * `args`: JSON value containing the StartLoggingRequest information:
    ///   Key `sampling_interval_ms` specifies the interval for polling the sensors.
    ///   Key `duration_ms` specifies the duration of logging.
    ///   Key `statistics_interval_ms` specifies the interval for summarizing statistics; if
    ///   omitted, statistics is disabled. Refer to `fuchsia.power.metrics` for more details.
    pub async fn start_logging(&self, args: Value) -> Result<types::RecorderResult, Error> {
        let req: types::StartLoggingRequest = serde_json::from_value(args)?;
        let statistics_args = req
            .statistics_interval_ms
            .map(|i| Box::new(StatisticsArgs { statistics_interval_ms: i }));
        let proxy = self.get_logger_proxy()?;
        // Calls into `fuchsia.power.metrics.Recorder`.
        proxy
            .start_logging(
                CLIENT_ID,
                &[Metric::Power(Power {
                    sampling_interval_ms: req.sampling_interval_ms,
                    statistics_args,
                })],
                req.duration_ms,
                /* output_samples_to_syslog */ false,
                /* output_stats_to_syslog */ false,
            )
            .await?
            .map_err(|e| format_err!("Received RecorderError: {:?}", e))?;
        Ok(types::RecorderResult::Success)
    }

    /// Initiates durationless logging with the Recorder service.
    ///
    /// # Arguments
    /// * `args`: JSON value containing the StartLoggingRequest information:
    ///   Key `sampling_interval_ms` specifies the interval for polling the sensors.
    ///   Key `statistics_interval_ms` specifies the interval for summarizing statistics; if
    ///   omitted, statistics is disabled. Refer to `fuchsia.power.metrics` for more details.
    pub async fn start_logging_forever(&self, args: Value) -> Result<types::RecorderResult, Error> {
        let req: types::StartLoggingForeverRequest = serde_json::from_value(args)?;
        let statistics_args = req
            .statistics_interval_ms
            .map(|i| Box::new(StatisticsArgs { statistics_interval_ms: i }));
        let proxy = self.get_logger_proxy()?;
        // Calls into `fuchsia.power.metrics.Recorder`.
        proxy
            .start_logging_forever(
                CLIENT_ID,
                &[Metric::Power(Power {
                    sampling_interval_ms: req.sampling_interval_ms,
                    statistics_args,
                })],
                /* output_samples_to_syslog */ false,
                /* output_stats_to_syslog */ false,
            )
            .await?
            .map_err(|e| format_err!("Received RecorderError: {:?}", e))?;
        Ok(types::RecorderResult::Success)
    }

    /// Terminates logging by the Recorder service.
    pub async fn stop_logging(&self) -> Result<types::RecorderResult, Error> {
        self.get_logger_proxy()?.stop_logging(CLIENT_ID).await?;
        Ok(types::RecorderResult::Success)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use fidl::endpoints::create_proxy_and_stream;
    use fidl_fuchsia_power_metrics::RecorderRequest;
    use fuchsia_async as fasync;
    use futures::prelude::*;
    use serde_json::json;

    /// Tests that the `start_logging` method correctly queries the logger.
    #[fasync::run_singlethreaded(test)]
    async fn test_start_logging() {
        let query_sampling_interval_ms = 500;
        let query_duration_ms = 10_000;
        let query_statitics_interval_ms = 1_000;

        let (proxy, mut stream) = create_proxy_and_stream::<RecorderMarker>().unwrap();

        let _stream_task = fasync::Task::local(async move {
            match stream.try_next().await {
                Ok(Some(RecorderRequest::StartLogging {
                    client_id,
                    metrics,
                    duration_ms,
                    output_samples_to_syslog,
                    output_stats_to_syslog,
                    responder,
                })) => {
                    assert_eq!(String::from("sl4f"), client_id);
                    assert_eq!(metrics.len(), 1);
                    assert_eq!(
                        metrics[0],
                        Metric::Power(Power {
                            sampling_interval_ms: query_sampling_interval_ms,
                            statistics_args: Some(Box::new(StatisticsArgs {
                                statistics_interval_ms: query_statitics_interval_ms,
                            })),
                        }),
                    );
                    assert_eq!(output_samples_to_syslog, false);
                    assert_eq!(output_stats_to_syslog, false);
                    assert_eq!(duration_ms, query_duration_ms);

                    responder.send(Ok(())).unwrap();
                }
                other => panic!("Unexpected stream item: {:?}", other),
            }
        });

        let facade = PowerFacade { logger_proxy: Some(proxy) };

        assert_matches!(
            facade
                .start_logging(json!({
                    "sampling_interval_ms": query_sampling_interval_ms,
                    "statistics_interval_ms": query_statitics_interval_ms,
                    "duration_ms": query_duration_ms
                }))
                .await,
            Ok(types::RecorderResult::Success)
        );
    }

    /// Tests that the `start_logging_forever` method correctly queries the logger.
    #[fasync::run_singlethreaded(test)]
    async fn test_start_logging_forever() {
        let query_sampling_interval_ms = 500;

        let (proxy, mut stream) = create_proxy_and_stream::<RecorderMarker>().unwrap();

        let _stream_task = fasync::Task::local(async move {
            match stream.try_next().await {
                Ok(Some(RecorderRequest::StartLoggingForever {
                    client_id,
                    metrics,
                    output_samples_to_syslog,
                    output_stats_to_syslog,
                    responder,
                })) => {
                    assert_eq!(String::from("sl4f"), client_id);
                    assert_eq!(metrics.len(), 1);
                    assert_eq!(
                        metrics[0],
                        Metric::Power(Power {
                            sampling_interval_ms: query_sampling_interval_ms,
                            statistics_args: None,
                        }),
                    );
                    assert_eq!(output_samples_to_syslog, false);
                    assert_eq!(output_stats_to_syslog, false);

                    responder.send(Ok(())).unwrap();
                }
                other => panic!("Unexpected stream item: {:?}", other),
            }
        });

        let facade = PowerFacade { logger_proxy: Some(proxy) };

        assert_matches!(
            facade
                .start_logging_forever(json!({
                    "sampling_interval_ms": query_sampling_interval_ms
                }))
                .await,
            Ok(types::RecorderResult::Success)
        );
    }

    /// Tests that the `stop_logging` method correctly queries the logger.
    #[fasync::run_singlethreaded(test)]
    async fn test_stop_logging() {
        let (proxy, mut stream) = create_proxy_and_stream::<RecorderMarker>().unwrap();

        let _stream_task = fasync::Task::local(async move {
            match stream.try_next().await {
                Ok(Some(RecorderRequest::StopLogging { client_id, responder })) => {
                    assert_eq!(String::from("sl4f"), client_id);
                    responder.send(true).unwrap()
                }
                other => panic!("Unexpected stream item: {:?}", other),
            }
        });

        let facade = PowerFacade { logger_proxy: Some(proxy) };

        assert_matches!(facade.stop_logging().await, Ok(types::RecorderResult::Success));
    }
}