- add: consul tags and metadata

- update: login reply now requests for the character services from consul to build the server list
This commit is contained in:
2024-12-10 15:45:35 -05:00
parent a7af7f1b9e
commit 9121b7f88b
6 changed files with 93 additions and 16 deletions

View File

@@ -1,12 +1,15 @@
use std::collections::HashMap;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct ServiceNode {
ServiceAddress: String,
ServicePort: u16,
pub struct ServiceNode {
pub ServiceAddress: String,
pub ServicePort: u16,
pub ServiceTags: Vec<String>,
pub ServiceMeta: HashMap<String, String>,
}
pub async fn get_service_address(consul_url: &str, service_name: &str) -> Result<Vec<(String, u16)>, Box<dyn std::error::Error>> {
pub async fn get_service_address(consul_url: &str, service_name: &str) -> Result<Vec<ServiceNode>, Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let consul_service_url = format!("{}/v1/catalog/service/{}", consul_url, service_name);
@@ -26,15 +29,40 @@ pub async fn get_service_address(consul_url: &str, service_name: &str) -> Result
// Deserialize the response into a Vec<ServiceNode>
let nodes: Vec<ServiceNode> = response.json().await?;
// Map the nodes to (address, port) tuples
let addresses: Vec<(String, u16)> = nodes
.into_iter()
.map(|node| (node.ServiceAddress, node.ServicePort))
.collect();
if addresses.is_empty() {
if nodes.is_empty() {
Err(format!("No nodes found for service '{}'", service_name).into())
} else {
Ok(addresses)
Ok(nodes)
}
}
// Example of filtering services with a specific tag
async fn get_services_with_tag(
service_name: &str,
tag: &str,
consul_url: &str,
) -> Result<Vec<ServiceNode>, Box<dyn std::error::Error>> {
let url = format!("{}/v1/catalog/service/{}", consul_url, service_name);
let client = reqwest::Client::new();
let response = client.get(&url).send().await?;
if !response.status().is_success() {
return Err(format!(
"Failed to fetch service nodes for '{}': {}",
service_name, response.status()
)
.into());
}
// Deserialize the response into a Vec<ServiceNode>
let nodes: Vec<ServiceNode> = response.json().await?;
// Filter nodes that include the specified tag
let filtered_nodes = nodes
.into_iter()
.filter(|node| node.ServiceTags.contains(&tag.to_string()))
.collect();
Ok(filtered_nodes)
}