rsiot/components/cmp_influxdb/
fn_process.rs

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
use std::time::Duration;

use reqwest::{Client, StatusCode};
use tokio::time::sleep;
use tracing::{error, info, trace, warn};

use crate::{
    executor::{CmpInOut, ComponentError},
    message::{MsgDataBound, ServiceBound},
};

use super::{
    config::{Config, LineProtocolItem},
    error::Error,
};

pub async fn fn_process<TMsg, TService>(
    in_out: CmpInOut<TMsg, TService>,
    config: Config<TMsg>,
) -> Result<(), ComponentError>
where
    TMsg: MsgDataBound + 'static,
    TService: ServiceBound + 'static,
{
    info!("Starting influxdb client, configuration: {:?}", config);

    loop {
        let res = task_main(in_out.clone(), config.clone()).await;
        match res {
            Ok(_) => (),
            Err(err) => {
                error!("Error in influxdb-client: {:?}", err);
            }
        }
        info!("Restarting...");
        sleep(Duration::from_secs(2)).await;
    }
}

async fn task_main<TMsg, TService>(
    mut input: CmpInOut<TMsg, TService>,
    config: Config<TMsg>,
) -> super::Result<()>
where
    TMsg: MsgDataBound + 'static,
    TService: ServiceBound + 'static,
{
    while let Ok(msg) = input.recv_input().await {
        let datapoints = (config.fn_input)(&msg);
        let datapoints = match datapoints {
            Some(datapoints) => datapoints,
            None => continue,
        };
        handle_request(datapoints, config.clone()).await?;
    }
    Err(super::Error::TaskEndInput)
}

async fn handle_request<TMsg>(
    datapoints: Vec<LineProtocolItem>,
    config: Config<TMsg>,
) -> super::Result<()>
where
    TMsg: MsgDataBound,
{
    trace!("New request to InfluxDB");
    let url = format!(
        "http://{host}:{port}/api/v2/write",
        host = config.host,
        port = config.port,
    );

    let lines = datapoints
        .iter()
        .map(String::try_from)
        .collect::<std::result::Result<Vec<String>, _>>()
        .map_err(super::Error::Config)?
        .join("\n");

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Token {}", config.token))
        .header("Accept", "application/json")
        .header("Content-Type", "text/plain; charset=utf-8")
        .query(&[
            ("org", config.org),
            ("bucket", config.bucket),
            ("precision", "ns".to_string()),
        ])
        .body(lines)
        .send()
        .await?;

    let status = response.status();
    if status == StatusCode::NO_CONTENT {
        return Ok(());
    }
    warn!("{status}");
    let text = response.text().await?;
    Err(Error::RequestParameters {
        status,
        message: text,
    })
}