aboutsummaryrefslogtreecommitdiff
path: root/src/consul.rs
blob: 81074f4182abc8b5e21b6aaa313184d11c6633db (plain) (blame)
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
use std::collections::HashMap;

use anyhow::Result;
use log::*;
use serde::{Deserialize, Serialize};

// ---- Watch and retrieve Consul catalog ----

#[derive(Serialize, Deserialize, Debug)]
pub struct ConsulServiceEntry {
	#[serde(rename = "Address")]
	pub address: String,

	#[serde(rename = "Port")]
	pub port: u16,

	#[serde(rename = "Tags")]
	pub tags: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ConsulNodeCatalog {
	#[serde(rename = "Services")]
	pub services: HashMap<String, ConsulServiceEntry>,
}

#[derive(Clone)]
pub struct Consul {
	client: reqwest::Client,
	url: String,
	idx: Option<u64>,
}

impl Consul {
	pub fn new(url: &str) -> Self {
		return Self {
			client: reqwest::Client::new(),
			url: url.to_string(),
			idx: None,
		};
	}

	pub fn watch_node_reset(&mut self) -> () {
		self.idx = None;
	}

	pub async fn watch_node(&mut self, host: &str) -> Result<ConsulNodeCatalog> {
		let url = match self.idx {
			Some(i) => format!("{}/v1/catalog/node/{}?index={}", self.url, host, i),
			None => format!("{}/v1/catalog/node/{}", self.url, host),
		};

		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>()?),
			None => return Err(anyhow!("X-Consul-Index header not found")),
		};

		let resp: ConsulNodeCatalog = http.json().await?;
		return Ok(resp);
	}
}