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
use std::sync::Arc;

use anyhow::Result;
use async_trait::async_trait;
use gaia_stub::{
    recorder::recorder_client::RecorderClient,
    tco_tmiv::{Tco, Tmiv},
};
use prost_types::Timestamp;
use tonic::transport::Channel;
use tracing::error;

use super::Hook;

pub use gaia_stub::recorder::*;

#[derive(Clone)]
pub struct RecordHook {
    recorder_client: RecorderClient<Channel>,
}

impl RecordHook {
    pub fn new(recorder_client: RecorderClient<Channel>) -> Self {
        Self { recorder_client }
    }
}

#[async_trait]
impl Hook<Arc<Tco>> for RecordHook {
    type Output = Arc<Tco>;

    async fn hook(&mut self, tco: Arc<Tco>) -> Result<Self::Output> {
        let now = chrono::Utc::now().naive_utc();
        let timestamp = Timestamp {
            seconds: now.and_utc().timestamp(),
            nanos: now.and_utc().timestamp_subsec_nanos() as i32,
        };
        self.recorder_client
            .post_command(PostCommandRequest {
                tco: Some(tco.as_ref().clone()),
                timestamp: Some(timestamp),
            })
            .await?;
        Ok(tco)
    }
}

#[async_trait]
impl Hook<Arc<Tmiv>> for RecordHook {
    type Output = Arc<Tmiv>;

    async fn hook(&mut self, tmiv: Arc<Tmiv>) -> Result<Self::Output> {
        let ret = self
            .recorder_client
            .post_telemetry(PostTelemetryRequest {
                tmiv: Some(tmiv.as_ref().clone()),
            })
            .await;
        if let Err(e) = ret {
            error!("failed to record TMIV: {}", e);
        }
        Ok(tmiv)
    }
}