use crate::config::OtelConfig;
use crate::node_identity::{RUSTFS_NODE_ATTRIBUTE, local_node_identity};
use opentelemetry::KeyValue;
use opentelemetry_sdk::Resource;
use opentelemetry_semantic_conventions::{
SCHEMA_URL,
attribute::{
DEPLOYMENT_ENVIRONMENT_NAME, NETWORK_LOCAL_ADDRESS, SERVICE_INSTANCE_ID as OTEL_SERVICE_INSTANCE_ID,
SERVICE_VERSION as OTEL_SERVICE_VERSION,
},
};
use rustfs_config::{APP_NAME, ENVIRONMENT, SERVICE_VERSION};
use rustfs_utils::get_local_ip_with_default;
use std::borrow::Cow;
pub(super) fn build_resource(config: &OtelConfig) -> Resource {
let local_ip = get_local_ip_with_default();
let node_identity = local_node_identity(&local_ip);
Resource::builder()
.with_service_name(Cow::Borrowed(config.service_name.as_deref().unwrap_or(APP_NAME)).to_string())
.with_schema_url(
[
KeyValue::new(
OTEL_SERVICE_VERSION,
Cow::Borrowed(config.service_version.as_deref().unwrap_or(SERVICE_VERSION)).to_string(),
),
KeyValue::new(
DEPLOYMENT_ENVIRONMENT_NAME,
Cow::Borrowed(config.environment.as_deref().unwrap_or(ENVIRONMENT)).to_string(),
),
KeyValue::new(RUSTFS_NODE_ATTRIBUTE, node_identity.clone()),
KeyValue::new(OTEL_SERVICE_INSTANCE_ID, node_identity),
KeyValue::new(NETWORK_LOCAL_ADDRESS, local_ip),
],
SCHEMA_URL,
)
.build()
}
#[cfg(test)]
mod tests {
use super::*;
use opentelemetry::Key;
#[tokio::test]
async fn build_resource_uses_stable_local_node_identity() {
let _guard = crate::node_identity::local_node_identity_test_guard().await;
let previous = rustfs_common::get_global_local_node_name().await;
rustfs_common::set_global_local_node_name("node1:9000").await;
let resource = build_resource(&OtelConfig::default());
assert_eq!(
resource
.get(&Key::from_static_str(RUSTFS_NODE_ATTRIBUTE))
.map(|value| value.to_string()),
Some("node1:9000".to_string())
);
assert_eq!(
resource
.get(&Key::from_static_str(OTEL_SERVICE_INSTANCE_ID))
.map(|value| value.to_string()),
Some("node1:9000".to_string())
);
rustfs_common::set_global_local_node_name(&previous).await;
}
}