-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathlib.rs
224 lines (199 loc) · 6.62 KB
/
lib.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
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
extern crate aw_models;
extern crate chrono;
extern crate gethostname;
extern crate reqwest;
extern crate serde_json;
extern crate tokio;
pub mod blocking;
use std::vec::Vec;
use std::{collections::HashMap, error::Error};
use chrono::{DateTime, Utc};
use serde_json::{json, Map};
pub use aw_models::{Bucket, BucketMetadata, Event};
pub struct AwClient {
client: reqwest::Client,
pub baseurl: reqwest::Url,
pub name: String,
pub hostname: String,
}
impl std::fmt::Debug for AwClient {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "AwClient(baseurl={:?})", self.baseurl)
}
}
fn get_hostname() -> String {
return gethostname::gethostname().to_string_lossy().to_string();
}
impl AwClient {
pub fn new(host: &str, port: u16, name: &str) -> Result<AwClient, Box<dyn Error>> {
let baseurl = reqwest::Url::parse(&format!("http://{}:{}", host, port))?;
let hostname = get_hostname();
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.build()?;
Ok(AwClient {
client,
baseurl,
name: name.to_string(),
hostname,
})
}
pub async fn get_bucket(&self, bucketname: &str) -> Result<Bucket, reqwest::Error> {
let url = format!("{}/api/0/buckets/{}", self.baseurl, bucketname);
let bucket = self
.client
.get(url)
.send()
.await?
.error_for_status()?
.json()
.await?;
Ok(bucket)
}
pub async fn get_buckets(&self) -> Result<HashMap<String, Bucket>, reqwest::Error> {
let url = format!("{}/api/0/buckets/", self.baseurl);
self.client.get(url).send().await?.json().await
}
pub async fn create_bucket(&self, bucket: &Bucket) -> Result<(), reqwest::Error> {
let url = format!("{}/api/0/buckets/{}", self.baseurl, bucket.id);
self.client.post(url).json(bucket).send().await?;
Ok(())
}
pub async fn create_bucket_simple(
&self,
bucketname: &str,
buckettype: &str,
) -> Result<(), reqwest::Error> {
let bucket = Bucket {
bid: None,
id: bucketname.to_string(),
client: self.name.clone(),
_type: buckettype.to_string(),
hostname: self.hostname.clone(),
data: Map::default(),
metadata: BucketMetadata::default(),
events: None,
created: None,
last_updated: None,
};
self.create_bucket(&bucket).await
}
pub async fn delete_bucket(&self, bucketname: &str) -> Result<(), reqwest::Error> {
let url = format!("{}/api/0/buckets/{}", self.baseurl, bucketname);
self.client.delete(url).send().await?;
Ok(())
}
pub async fn query(
&self,
query: &str,
timeperiods: Vec<(DateTime<Utc>, DateTime<Utc>)>,
) -> Result<serde_json::Value, reqwest::Error> {
let url = reqwest::Url::parse(format!("{}/api/0/query", self.baseurl).as_str()).unwrap();
// Format timeperiods as ISO8601 strings, separated by /
let timeperiods_str: Vec<String> = timeperiods
.iter()
.map(|(start, stop)| (start.to_rfc3339(), stop.to_rfc3339()))
.map(|(start, stop)| format!("{}/{}", start, stop))
.collect();
self.client
.post(url)
.json(&json!({
"query": query.split('\n').collect::<Vec<&str>>(),
"timeperiods": timeperiods_str,
}))
.send()
.await?
.json()
.await
}
pub async fn get_events(
&self,
bucketname: &str,
start: Option<DateTime<Utc>>,
stop: Option<DateTime<Utc>>,
limit: Option<u64>,
) -> Result<Vec<Event>, reqwest::Error> {
let mut url = reqwest::Url::parse(
format!("{}/api/0/buckets/{}/events", self.baseurl, bucketname).as_str(),
)
.unwrap();
// Must be a better way to build URLs
if let Some(s) = start {
url.query_pairs_mut()
.append_pair("start", s.to_rfc3339().as_str());
};
if let Some(s) = stop {
url.query_pairs_mut()
.append_pair("end", s.to_rfc3339().as_str());
};
if let Some(s) = limit {
url.query_pairs_mut()
.append_pair("limit", s.to_string().as_str());
};
self.client.get(url).send().await?.json().await
}
pub async fn insert_event(
&self,
bucketname: &str,
event: &Event,
) -> Result<(), reqwest::Error> {
let url = format!("{}/api/0/buckets/{}/events", self.baseurl, bucketname);
let eventlist = vec![event.clone()];
self.client.post(url).json(&eventlist).send().await?;
Ok(())
}
pub async fn insert_events(
&self,
bucketname: &str,
events: Vec<Event>,
) -> Result<(), reqwest::Error> {
let url = format!("{}/api/0/buckets/{}/events", self.baseurl, bucketname);
self.client.post(url).json(&events).send().await?;
Ok(())
}
pub async fn heartbeat(
&self,
bucketname: &str,
event: &Event,
pulsetime: f64,
) -> Result<(), reqwest::Error> {
let url = format!(
"{}/api/0/buckets/{}/heartbeat?pulsetime={}",
self.baseurl, bucketname, pulsetime
);
self.client.post(url).json(&event).send().await?;
Ok(())
}
pub async fn delete_event(
&self,
bucketname: &str,
event_id: i64,
) -> Result<(), reqwest::Error> {
let url = format!(
"{}/api/0/buckets/{}/events/{}",
self.baseurl, bucketname, event_id
);
self.client.delete(url).send().await?;
Ok(())
}
pub async fn get_event_count(&self, bucketname: &str) -> Result<i64, reqwest::Error> {
let url = format!("{}/api/0/buckets/{}/events/count", self.baseurl, bucketname);
let res = self
.client
.get(url)
.send()
.await?
.error_for_status()?
.text()
.await?;
let count: i64 = match res.trim().parse() {
Ok(count) => count,
Err(err) => panic!("could not parse get_event_count response: {err:?}"),
};
Ok(count)
}
pub async fn get_info(&self) -> Result<aw_models::Info, reqwest::Error> {
let url = format!("{}/api/0/info", self.baseurl);
self.client.get(url).send().await?.json().await
}
}