Files
osirose-new/utils/src/consul_registration.rs
raven 4046f56191 - removed: api-service
- removed: session-service
- updated: moved health check out of consul registration
- updated: get service info to pull the service from the default namespace for the service account
- updated: the rest of the services to be able to handle the new database tables
2025-03-20 22:53:49 -04:00

107 lines
3.0 KiB
Rust

use reqwest::Client;
use serde_json::json;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
use uuid::Uuid;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn generate_service_id() -> String {
Uuid::new_v4().to_string()
}
pub fn get_or_generate_service_id(package_name: &str) -> String {
// let package_name = env!("CARGO_PKG_NAME");
let file_name = format!("/services/{}_service_id.txt", package_name);
let path = Path::new(&file_name);
let _ = fs::create_dir_all("/services"); // make sure the folders exist
if path.exists() {
// Read the service ID from the file
if let Ok(service_id) = fs::read_to_string(path) {
return service_id.trim().to_string();
}
}
// Generate a new service ID and save it to disk
let service_id = generate_service_id();
if let Err(err) = fs::write(path, &service_id) {
eprintln!("Failed to write service ID to disk: {}", err);
}
service_id
}
pub async fn register_service(
consul_url: &str,
service_id: &str,
service_name: &str,
service_address: &str,
service_port: u16,
tags: Vec<String>,
mut meta: HashMap<String, String>,
health_check_protocol: Option<&str>,
health_check_address: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
meta.insert("version".to_string(), VERSION.to_string());
let mut check_protocol = "grpc".to_string();
let mut check_address = format!("{}:{}", service_name, service_port);
if health_check_protocol.is_some() {
check_protocol = health_check_protocol.unwrap().to_string();
}
if health_check_address.is_some() {
check_address = health_check_address.unwrap().to_string();
}
let registration = json!({
"id": format!("{}-{}", service_name, service_id),
"name": service_name.to_string(),
"address": service_address.to_string(),
"port": service_port,
"tags": tags,
"meta": meta,
"tagged_addresses": {
"lan": {
"address": service_address.to_string(),
"port": service_port,
}
},
"check": {
check_protocol: check_address,
"interval": "10s",
"timeout": "2s"
}
});
let client = Client::new();
let consul_register_url = format!("{}/v1/agent/service/register", consul_url);
client
.put(&consul_register_url)
.json(&registration)
.send()
.await?
.error_for_status()?; // Ensure response is successful
Ok(())
}
pub async fn deregister_service(
consul_url: &str,
service_id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let consul_deregister_url =
format!("{}/v1/agent/service/deregister/{}", consul_url, service_id);
client
.put(&consul_deregister_url)
.send()
.await?
.error_for_status()?; // Ensure response is successful
Ok(())
}