hdp-worker 0.1.9

Base worker implementation for HDP ecosystem
Documentation
use crate::proto::worker::common;
use crate::publisher::Publisher;
use async_nats::{service::ServiceExt, Client, HeaderMap};
use bytes::Bytes;
use futures::StreamExt;
use prost::Message;
use std::{collections::HashMap, time::Duration};
use ulid::Ulid;
use std::path::PathBuf;
use std::fs;

#[derive(Clone)]
pub struct WorkerConfig {
    pub worker_id: String,
    pub worker_type: common::worker::Type,
    pub heartbeat_interval: Duration,
}

const CONFIG_DIR: &str = "config";
const WORKER_ID_FILE: &str = "worker_id";

impl WorkerConfig {
    fn get_worker_id_path() -> PathBuf {
        let mut path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        path.push(CONFIG_DIR);
        path.push(WORKER_ID_FILE);
        path
    }

    fn ensure_config_dir() -> std::io::Result<()> {
        let mut path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        path.push(CONFIG_DIR);
        fs::create_dir_all(path)
    }

    fn load_or_generate_id() -> String {
        let _ = Self::ensure_config_dir();
        let path = Self::get_worker_id_path();

        if let Ok(existing_id) = fs::read_to_string(&path) {
            if !existing_id.trim().is_empty() {
                return existing_id.trim().to_string();
            }
        }

        let new_id = Ulid::new().to_string();
        let _ = fs::write(&path, &new_id);
        new_id
    }

    pub fn new(worker_type: common::worker::Type) -> Self {
        Self {
            worker_id: Self::load_or_generate_id(),
            worker_type,
            heartbeat_interval: Duration::from_secs(5),
        }
    }
}

pub struct Worker {
    client: Client,
    config: WorkerConfig,
    publisher: Publisher,
}

impl Worker {
    pub fn new(client: Client, config: WorkerConfig) -> Self {
        let publisher = Publisher::new(client.clone(), config.worker_id.clone());
        Self {
            client,
            config,
            publisher,
        }
    }

    pub fn get_publisher(&self) -> &Publisher {
        &self.publisher
    }

    async fn setup_endpoint(&mut self) -> Result<(), String> {
        let mut metadata = HashMap::new();
        metadata.insert("worker_id".to_string(), self.config.worker_id.clone());

        let service = self.client
            .service_builder()
            .description("HDP Worker Service")
            .metadata(metadata)
            .start(
                "HDP",  // Simple service name with only allowed characters
                &String::from("1.0.0")
            )
            .await
            .map_err(|e| e.to_string())?;

        let service_group = service.group(format!("worker.{}", format!("{:?}", self.config.worker_type).to_lowercase()));
        let config_endpoint = service_group.endpoint("config").await.map_err(|e| e.to_string())?;


        tokio::spawn(async move {
            let mut endpoint = config_endpoint;
            while let Some(request) = endpoint.next().await {
                println!("Received config update: {:?}", request);
                let _ = request.respond(Ok(Bytes::new())).await;
            }
        });

        Ok(())
    }

    async fn start_heartbeat(&self) {
        let client = self.client.clone();
        let worker_id = self.config.worker_id.clone();
        let interval = self.config.heartbeat_interval;

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(interval);
            loop {
                interval.tick().await;
                let mut headers = HeaderMap::new();
                headers.insert("worker_id", worker_id.as_str());

                if let Err(e) = client
                    .request_with_headers("worker.core.heartbeat", headers, Bytes::new())
                    .await
                {
                    println!("Failed to send heartbeat: {}", e);
                }
            }
        });
    }

    async fn register(&self) -> Result<(), String> {
        let registration = common::Worker {
            id: self.config.worker_id.clone(),
            name: None,
            r#type: self.config.worker_type as i32,
            inventory: None,
            last_seen: None,
        };
        let data = registration.encode_to_vec();
        self
            .client
            .request("worker.core.register", data.into())
            .await
            .map_err(|e| e.to_string())?;
        println!("Registered with server");
        Ok(())
    }

    pub async fn setup(&mut self) -> Result<(), String> {
        println!("Setting up endpoints...");
        self.setup_endpoint().await?;
        println!("Registering worker...");
        self.register().await?;
        println!("Starting heartbeat...");
        self.start_heartbeat().await;
        Ok(())
    }

    pub fn get_client(&self) -> Client {
        self.client.clone()
    }

    pub fn get_config(&self) -> &WorkerConfig {
        &self.config
    }
}