2020-05-21 21:04:21 +00:00
|
|
|
use std::collections::HashMap;
|
2021-08-25 15:20:31 +00:00
|
|
|
|
2021-09-20 09:30:00 +00:00
|
|
|
use anyhow::{anyhow, Result};
|
|
|
|
use serde::{Deserialize, Serialize};
|
2020-05-21 21:04:21 +00:00
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct ServiceEntry {
|
2021-09-20 09:30:00 +00:00
|
|
|
pub Tags: Vec<String>,
|
2020-05-21 21:04:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct CatalogNode {
|
2021-09-20 09:30:00 +00:00
|
|
|
pub Services: HashMap<String, ServiceEntry>,
|
2020-05-21 21:04:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Consul {
|
|
|
|
client: reqwest::Client,
|
2020-05-22 08:33:09 +00:00
|
|
|
url: String,
|
2021-09-20 09:30:00 +00:00
|
|
|
idx: Option<u64>,
|
2020-05-21 21:04:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Consul {
|
|
|
|
pub fn new(url: &str) -> Self {
|
|
|
|
return Self {
|
|
|
|
client: reqwest::Client::new(),
|
2020-05-22 08:33:09 +00:00
|
|
|
url: url.to_string(),
|
2021-09-20 09:30:00 +00:00
|
|
|
idx: None,
|
2021-09-20 14:07:58 +00:00
|
|
|
}
|
2020-05-21 21:04:21 +00:00
|
|
|
}
|
|
|
|
|
2021-09-20 14:07:58 +00:00
|
|
|
pub fn watch_node_reset(&mut self) -> () { self.idx = None; }
|
2020-05-22 13:19:49 +00:00
|
|
|
|
2020-05-22 08:33:09 +00:00
|
|
|
pub async fn watch_node(&mut self, host: &str) -> Result<CatalogNode> {
|
|
|
|
let url = match self.idx {
|
|
|
|
Some(i) => format!("{}/v1/catalog/node/{}?index={}", self.url, host, i),
|
2021-09-20 09:30:00 +00:00
|
|
|
None => format!("{}/v1/catalog/node/{}", self.url, host),
|
2020-05-22 08:33:09 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let http = self.client.get(&url).send().await?;
|
|
|
|
self.idx = match http.headers().get("X-Consul-Index") {
|
|
|
|
Some(v) => Some(v.to_str()?.parse::<u64>()?),
|
2021-09-20 09:30:00 +00:00
|
|
|
None => return Err(anyhow!("X-Consul-Index header not found")),
|
2020-05-22 08:33:09 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let resp: CatalogNode = http.json().await?;
|
2021-09-20 14:07:58 +00:00
|
|
|
return Ok(resp)
|
2020-05-21 21:04:21 +00:00
|
|
|
}
|
|
|
|
}
|