robotrt-cli 0.1.0-beta.1

RobotRT modular robotics runtime and middleware components.
use super::*;

pub(super) fn load_status_snapshot(
    args: &[String],
) -> Result<(StatusSnapshot, SnapshotSource), String> {
    if let Some(raw_endpoint) = option_value(args, "--endpoint") {
        let timeout_ms = parse_u64_option(args, "--timeout-ms", 1000)?;
        let (snapshot, endpoint) = fetch_remote_status_snapshot(&raw_endpoint, timeout_ms)?;
        let source = SnapshotSource {
            label: format!("remote:{endpoint}"),
            json: serde_json::json!({
                "mode": "remote_service",
                "service": STATUS_SERVICE_NAME,
                "endpoint": endpoint,
                "timeout_ms": timeout_ms,
            }),
        };
        return Ok((snapshot, source));
    }

    let report_path = parse_report_path(args, DEFAULT_STATUS_REPORT_PATH)?;
    if has_flag(args, "--refresh-demo") {
        capture_demo_status_report(&report_path).map_err(|err| {
            format!(
                "refresh demo status report to {} failed: {err}",
                report_path.display()
            )
        })?;
    }

    let snapshot = read_status_snapshot(&report_path).map_err(|err| {
        format!(
            "read status snapshot from {} failed: {err}. Hint: run `cargo run -p local-loop` first, or pass --refresh-demo.",
            report_path.display()
        )
    })?;

    let source = SnapshotSource {
        label: report_path.display().to_string(),
        json: serde_json::json!({
            "mode": "file",
            "report": report_path,
        }),
    };
    Ok((snapshot, source))
}

fn fetch_remote_status_snapshot(
    endpoint: &str,
    timeout_ms: u64,
) -> Result<(StatusSnapshot, String), String> {
    let endpoint = normalize_udp_endpoint(endpoint)?;
    let client = make_udp_service_client(endpoint.clone(), timeout_ms)?;

    let request_id = next_request_id();
    let request = build_snapshot_request(request_id);
    let response: StatusServiceResponse =
        call_status_service(&client, request_id, &request, &endpoint)?;

    validate_response(&response, request_id)?;
    Ok((response.snapshot, endpoint))
}

fn call_status_service(
    client: &core_api::UdpServiceClient,
    request_id: ServiceRequestId,
    request: &crate::status_api::StatusServiceRequest,
    endpoint: &str,
) -> Result<StatusServiceResponse, String> {
    client
        .call_json(STATUS_SERVICE_NAME, request_id, request)
        .map_err(|err| format!("status query to {endpoint} failed: {err}"))
}

fn normalize_udp_endpoint(raw: &str) -> Result<String, String> {
    if let Some(rest) = raw.strip_prefix("udp://") {
        if rest.is_empty() {
            return Err(String::from("invalid --endpoint value: udp://"));
        }
        return Ok(rest.to_string());
    }
    if raw.contains("://") {
        return Err(format!("unsupported endpoint scheme: {raw}"));
    }
    Ok(raw.to_string())
}