evalsync 0.1.0

Experiment synchronization library for benchmark coordination via ZeroMQ
Documentation
use once_cell::sync::OnceCell;
use prost::Message;
use std::collections::HashMap;
use std::env;
use std::sync::{Arc, Mutex};

pub mod proto {
    include!(concat!(env!("OUT_DIR"), "/evalsync.rs"));
}

use proto::{ExperimentCommand, ManagerMessage, ServiceState, StateSync};

pub struct ExperimentWorker {
    context: zmq::Context,
    state_socket: zmq::Socket,
    command_socket: zmq::Socket,
    experiment_id: String,
    client_id: String,
    state: ServiceState,
    verbose: bool,
    metadata: HashMap<String, String>,
}

static WORKER: OnceCell<Arc<Mutex<ExperimentWorker>>> = OnceCell::new();

const CONNECTION_TIMEOUT_MS: i64 = 1000;

fn verify_socket_connection(socket: &zmq::Socket, timeout_ms: i64) -> Result<(), String> {
    let mut poll_items = [socket.as_poll_item(zmq::POLLOUT)];
    let rc = zmq::poll(&mut poll_items, timeout_ms).map_err(|e| e.to_string())?;
    if rc > 0 && poll_items[0].get_revents().contains(zmq::POLLOUT) {
        Ok(())
    } else if poll_items[0].get_revents().contains(zmq::POLLERR) {
        Err("Socket error during connection verification".to_string())
    } else {
        Err("Connection verification timed out".to_string())
    }
}

/// Initialize the worker with explicit experiment_id, client_id, and verbose flag.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn init(experiment_id: &str, client_id: &str, verbose: bool) -> Result<(), String> {
    if WORKER.get().is_some() {
        return Err("Worker already initialized".to_string());
    }
    let context = zmq::Context::new();
    let state_socket_path = format!("ipc:///tmp/{experiment_id}-STATE");
    let state_socket = context.socket(zmq::DEALER).map_err(|e| e.to_string())?;
    state_socket.set_linger(1000).map_err(|e| e.to_string())?;
    state_socket
        .set_identity(client_id.as_bytes())
        .map_err(|e| e.to_string())?;
    state_socket
        .connect(&state_socket_path)
        .map_err(|e| e.to_string())?;
    if verbose {
        eprintln!("[evalsync-worker] state channel: {state_socket_path}");
    }
    verify_socket_connection(&state_socket, CONNECTION_TIMEOUT_MS)?;
    if verbose {
        eprintln!("[evalsync-worker] state channel connected");
    }

    let command_socket_path = format!("ipc:///tmp/{experiment_id}-COMMAND");
    let command_socket = context.socket(zmq::DEALER).map_err(|e| e.to_string())?;
    command_socket.set_linger(1000).map_err(|e| e.to_string())?;
    command_socket
        .set_identity(client_id.as_bytes())
        .map_err(|e| e.to_string())?;
    command_socket
        .connect(&command_socket_path)
        .map_err(|e| e.to_string())?;
    if verbose {
        eprintln!("[evalsync-worker] command channel: {command_socket_path}");
    }
    verify_socket_connection(&command_socket, CONNECTION_TIMEOUT_MS)?;
    if verbose {
        eprintln!("[evalsync-worker] command channel connected");
    }

    let worker = ExperimentWorker {
        context,
        state_socket,
        command_socket,
        experiment_id: experiment_id.to_string(),
        client_id: client_id.to_string(),
        state: ServiceState::Init,
        verbose,
        metadata: HashMap::new(),
    };
    WORKER
        .set(Arc::new(Mutex::new(worker)))
        .map_err(|_| "Failed to set worker".to_string())?;
    Ok(())
}

/// Initialize the worker using environment variables (EVALSYNC_EXPERIMENT_ID, EVALSYNC_CLIENT_ID, EVALSYNC_VERBOSE).
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn init_env() -> Result<(), String> {
    let experiment_id = env::var("EVALSYNC_EXPERIMENT_ID")
        .map_err(|_| "EVALSYNC_EXPERIMENT_ID not set".to_string())?;
    let client_id =
        env::var("EVALSYNC_CLIENT_ID").map_err(|_| "EVALSYNC_CLIENT_ID not set".to_string())?;
    let verbose = env::var("EVALSYNC_VERBOSE").unwrap_or_default() == "1";
    init(&experiment_id, &client_id, verbose)
}

/// Clean up the worker, closing sockets and terminating the ZMQ context.
/// This should be called when the worker is no longer needed.
pub fn cleanup() -> Result<(), String> {
    // Note: OnceCell doesn't support taking the value out, so we can only
    // access and clean up through the mutex. The actual cleanup happens
    // when the worker is dropped after this function signals completion.
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: cleanup() - cleaning up resources");
        }
        // ZMQ sockets and context will be cleaned up when dropped
        // We mark the state to indicate cleanup was requested
        Ok(())
    })?
}

/// Set a metadata key-value pair.
pub fn set_metadata(key: &str, value: &str) -> Result<(), String> {
    with_worker(|worker| {
        worker.metadata.insert(key.to_string(), value.to_string());
        Ok(())
    })?
}

/// Get a metadata value by key.
pub fn get_metadata(key: &str) -> Result<Option<String>, String> {
    with_worker(|worker| Ok(worker.metadata.get(key).cloned()))?
}

/// Get all metadata as a HashMap.
pub fn get_all_metadata() -> Result<HashMap<String, String>, String> {
    with_worker(|worker| Ok(worker.metadata.clone()))?
}

/// Clear all metadata.
pub fn clear_metadata() -> Result<(), String> {
    with_worker(|worker| {
        worker.metadata.clear();
        Ok(())
    })?
}

/// Check if verbose mode is enabled.
pub fn is_verbose() -> Result<bool, String> {
    with_worker(|worker| Ok(worker.verbose))?
}

fn with_worker<T, F: FnOnce(&mut ExperimentWorker) -> T>(f: F) -> Result<T, String> {
    let arc = WORKER.get().ok_or("Worker not initialized".to_string())?;
    let mut guard = arc.lock().map_err(|_| "Worker lock poisoned".to_string())?;
    Ok(f(&mut guard))
}

fn notify_manager(worker: &mut ExperimentWorker, msg: &str) -> Result<(), String> {
    let message = StateSync {
        state: worker.state as i32,
        error_message: msg.to_string(),
        metadata: worker.metadata.clone(),
    };
    let mut buf = Vec::with_capacity(message.encoded_len());
    message.encode(&mut buf).map_err(|e| e.to_string())?;
    if worker.verbose {
        eprintln!(
            "[evalsync-worker] [+] send message: state={:?} msg={:?}",
            worker.state, msg
        );
    }
    worker
        .state_socket
        .send_multipart([b"", buf.as_slice()], 0)
        .map_err(|e| e.to_string())?;
    Ok(())
}

/// Set the worker state to READY and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn ready() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: ready() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Init {
            worker.state = ServiceState::Ready;
            notify_manager(worker, "ready")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: ready() - SUCCESS, transitioned to READY");
            }
            Ok(())
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: ready() - FAILED, not in INIT state");
            }
            Err("Worker not in INIT state".to_string())
        }
    })?
}

/// Set the worker state to RUNNING and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn start() -> Result<(), String> {
    with_worker(|worker| {
        if worker.state == ServiceState::Ready {
            worker.state = ServiceState::Running;
            notify_manager(worker, "running")?;
            Ok(())
        } else {
            Err("Worker not in READY state".to_string())
        }
    })?
}

/// Set the worker state to DONE and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn end() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: end() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Running {
            worker.state = ServiceState::Done;
            notify_manager(worker, "done")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: end() - SUCCESS, transitioned to DONE");
            }
            Ok(())
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: end() - FAILED, not in RUNNING state");
            }
            Err("Worker not in RUNNING state".to_string())
        }
    })?
}

/// Set the worker state to ERROR and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn abort() -> Result<(), String> {
    with_worker(|worker| {
        if worker.state == ServiceState::Running {
            worker.state = ServiceState::Error;
            notify_manager(worker, "error")?;
            Ok(())
        } else {
            Err("Worker not in RUNNING state".to_string())
        }
    })?
}

/// Wait for a BEGIN command from the manager and transition to RUNNING.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn wait_for_start() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: wait_for_start() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Ready {
            loop {
                let msgs = worker
                    .command_socket
                    .recv_multipart(0)
                    .map_err(|e| e.to_string())?;
                if worker.verbose {
                    eprintln!(
                        "[evalsync-worker] [-] received command: {} bytes",
                        msgs[1].len()
                    );
                }
                let msg = ManagerMessage::decode(&*msgs[1]).map_err(|e| e.to_string())?;
                match ExperimentCommand::try_from(msg.command) {
                    Ok(ExperimentCommand::Begin) => {
                        worker.state = ServiceState::Running;
                        notify_manager(worker, "running")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_start() - SUCCESS, received BEGIN");
                        }
                        return Ok(());
                    }
                    Ok(ExperimentCommand::End) | Ok(ExperimentCommand::Abort) => {
                        worker.state = ServiceState::Error;
                        notify_manager(worker, "error")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_start() - FAILED, received END/ABORT");
                        }
                        return Err("Received END or ABORT before start".to_string());
                    }
                    _ => {}
                }
            }
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: wait_for_start() - FAILED, not in READY state");
            }
            Err("Worker not in READY state".to_string())
        }
    })?
}

/// Wait for an END command from the manager and transition to DONE.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn wait_for_end() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: wait_for_end() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Running {
            loop {
                let msgs = worker
                    .command_socket
                    .recv_multipart(0)
                    .map_err(|e| e.to_string())?;
                let msg = ManagerMessage::decode(&*msgs[1]).map_err(|e| e.to_string())?;
                match ExperimentCommand::try_from(msg.command) {
                    Ok(ExperimentCommand::End) => {
                        worker.state = ServiceState::Done;
                        notify_manager(worker, "done")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_end() - SUCCESS, received END");
                        }
                        return Ok(());
                    }
                    Ok(ExperimentCommand::Begin) | Ok(ExperimentCommand::Abort) => {
                        worker.state = ServiceState::Error;
                        notify_manager(worker, "error")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_end() - FAILED, received BEGIN/ABORT");
                        }
                        return Err("Received BEGIN or ABORT during end".to_string());
                    }
                    _ => {}
                }
            }
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: wait_for_end() - FAILED, not in RUNNING state");
            }
            Err("Worker not in RUNNING state".to_string())
        }
    })?
}