- 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 7d97afebf2
5 changed files with 65 additions and 14 deletions

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use auth_service::auth::auth_service_server::AuthServiceServer;
use auth_service::database_client::DatabaseClient;
use auth_service::database_client::DatabaseClientTrait;
@@ -38,12 +39,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Register service with Consul
let service_id = consul_registration::generate_service_id();
let tags = vec!["version-1.0".to_string()];
let mut meta = HashMap::new();
consul_registration::register_service(
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_port.parse().unwrap_or(50052),
tags,
meta,
&health_check_url,
)
.await?;
@@ -55,7 +60,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(warp::serve(health_route).run(health_check_endpoint_addr.to_socket_addrs()?.next().unwrap()));
let db_address = db_nodes.get(0).unwrap();
let db_url = format!("http://{}:{}", db_address.0, db_address.1);
let db_url = format!("http://{}:{}", db_address.ServiceAddress, db_address.ServicePort);
let database_client = DatabaseClient::connect(&db_url).await?;
let full_addr = format!("{}:{}", &addr, port);

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use database::database_service_server::DatabaseServiceServer;
use database_service::database;
use database_service::db::Database;
@@ -38,12 +39,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Register service with Consul
let service_id = consul_registration::generate_service_id();
let tags = vec!["version-1.0".to_string()];
let mut meta = HashMap::new();
consul_registration::register_service(
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_port.parse().unwrap_or(50052),
tags,
meta,
&health_check_url,
)
.await?;

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::net::ToSocketAddrs;
@@ -85,12 +86,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Register service with Consul
let service_id = consul_registration::generate_service_id();
let tags = vec!["version-1.0".to_string()];
let mut meta = HashMap::new();
meta.insert("name".to_string(), "Athena".to_string());
consul_registration::register_service(
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_port.parse().unwrap_or(50052),
tags,
meta,
&health_check_url,
)
.await?;
@@ -102,7 +108,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(warp::serve(health_route).run(health_check_endpoint_addr.to_socket_addrs()?.next().unwrap()));
let auth_address = auth_node.get(0).unwrap();
let auth_url = format!("http://{}:{}", auth_address.0, auth_address.1);
let auth_url = format!("http://{}:{}", auth_address.ServiceAddress, auth_address.ServicePort);
let auth_client = Arc::new(Mutex::new(AuthClient::connect(&auth_url).await?));
let full_addr = format!("{}:{}", &addr, port);

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use reqwest::Client;
use serde::Serialize;
use uuid::Uuid;
@@ -8,6 +9,8 @@ struct ConsulRegistration {
name: String,
address: String,
port: u16,
tags: Vec<String>,
meta: HashMap<String, String>,
check: ConsulCheck,
}
@@ -28,6 +31,8 @@ pub async fn register_service(
service_name: &str,
service_address: &str,
service_port: u16,
tags: Vec<String>,
meta: HashMap<String, String>,
health_check_url: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let registration = ConsulRegistration {
@@ -35,6 +40,8 @@ pub async fn register_service(
name: service_name.to_string(),
address: service_address.to_string(),
port: service_port,
tags,
meta,
check: ConsulCheck {
http: health_check_url.to_string(),
interval: "10s".to_string(), // Health check interval

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)
}