status_example/
common.rs

1//! # Common Utility Module for Cortex Examples
2//!
3//! This module provides shared functionality used across various examples for interacting
4//! with the Cortex API. It handles:
5//!
6//! 1.  **Configuration Setup**: Reads Cortex API endpoint URL and API key from
7//!     environment variables (`CORTEX_ENDPOINT` and `CORTEX_API_KEY`) and
8//!     initializes a `client::apis::configuration::Configuration` object.
9//!
10//! 2.  **Analyzer ID Retrieval**: Fetches all analyzer instances from Cortex and
11//!     allows finding a specific analyzer's instance ID by its unique name. This
12//!     ID is required when creating analyzer jobs.
13//!
14//! ## Environment Variables
15//!
16//! Ensure the following environment variables are set before running examples that use this module:
17//!
18//! -   `CORTEX_ENDPOINT`: The full URL to your Cortex API (e.g., `http://localhost:9000/api`).
19//! -   `CORTEX_API_KEY`: Your API key for authenticating with Cortex.
20//!
21//! ## Usage
22//!
23//! Examples typically call `common::setup_configuration()` at the beginning to get a
24//! `Configuration` object. Then, they might use `common::get_analyzer_id_by_name()`
25//! to resolve an analyzer's name (e.g., "AbuseIPDB_1_0") to its operational ID.
26
27use cortex_client::apis::configuration::Configuration;
28use std::env;
29
30pub fn setup_configuration() -> Result<Configuration, String> {
31    let base_path = env::var("CORTEX_ENDPOINT")
32        .map_err(|_| "CORTEX_ENDPOINT environment variable not set. Please set it to your Cortex API URL (e.g., http://localhost:9000/api).".to_string())?;
33
34    let api_key = env::var("CORTEX_API_KEY").map_err(|_| {
35        "CORTEX_API_KEY environment variable not set. Please set your Cortex API key.".to_string()
36    })?;
37
38    let mut configuration = Configuration::new();
39    configuration.base_path = base_path;
40    configuration.bearer_access_token = Some(api_key);
41
42    Ok(configuration)
43}
44
45pub async fn get_analyzer_id_by_name(
46    config: &Configuration,
47    analyzer_name_to_find: &str,
48) -> Result<Option<String>, Box<dyn std::error::Error>> {
49    println!(
50        "Fetching all analyzer instances to find ID for '{}'...",
51        analyzer_name_to_find
52    );
53
54    let find_request = Some(cortex_client::models::AnalyzerFindRequest::default());
55
56    match cortex_client::apis::analyzer_api::find_analyzers(config, find_request).await {
57        Ok(analyzer_instances) => {
58            // Directly a Vec<Worker>
59            for analyzer_instance in analyzer_instances {
60                if let Some(name) = &analyzer_instance.name {
61                    if name == analyzer_name_to_find {
62                        if let Some(id) = analyzer_instance._id {
63                            println!(
64                                "Found analyzer ID '{}' for name '{}'",
65                                id, analyzer_name_to_find
66                            );
67                            return Ok(Some(id));
68                        }
69                    }
70                }
71            }
72            println!("Analyzer with name '{}' not found.", analyzer_name_to_find);
73            Ok(None)
74        }
75        Err(e) => {
76            eprintln!("Error fetching analyzer instances: {:?}", e);
77            Err(Box::new(e))
78        }
79    }
80}