aboutsummaryrefslogblamecommitdiff
path: root/src/consul.rs
blob: 1bb30aae1d78b84205a239fc1030bbd5d20d8bdf (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11

                                    
                             


                                        
                       



                                        
                                             



                          

                  





                                     

                           


      



                                            












                                                                              


                   
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use anyhow::{Result, anyhow};

#[derive(Serialize, Deserialize, Debug)]
pub struct ServiceEntry {
  pub Tags: Vec<String>
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CatalogNode {
  pub Services: HashMap<String, ServiceEntry>
}

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<CatalogNode> {
    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: CatalogNode = http.json().await?;
    return Ok(resp)
  }
}