gemini_genai_rs/telemetry/
gcp.rs1use std::sync::{Arc, PoisonError, RwLock};
13use std::time::Duration;
14
15use gcloud_sdk::tonic;
16use gcloud_sdk::{GoogleAuthHeaders, GoogleEnvironment, HeaderMap};
17use opentelemetry::{Key, KeyValue};
18use opentelemetry_sdk::Resource;
19
20pub(crate) const TELEMETRY_ENDPOINT: &str = "https://telemetry.googleapis.com";
22
23const AUTH_POLL: Duration = Duration::from_secs(30);
27
28const METADATA_TIMEOUT: Duration = Duration::from_secs(2);
31
32const LOCATION_KEYS: [&str; 3] = ["location", "cloud.availability_zone", "cloud.region"];
35
36const INSTANCE_KEYS: [&str; 5] = [
38 "instance",
39 "service.instance.id",
40 "faas.instance",
41 "k8s.pod.name",
42 "host.id",
43];
44
45#[derive(Debug, thiserror::Error)]
47#[non_exhaustive]
48pub enum GcpExportError {
49 #[error(
52 "no Google Cloud project for metric export: set `otel_gcp_project` \
53 or GOOGLE_CLOUD_PROJECT"
54 )]
55 NoProject,
56 #[error(
59 "no Google Cloud region for metric export: set \
60 OTEL_RESOURCE_ATTRIBUTES=cloud.region=<region> (for example \
61 us-central1); on Cloud Run, GCE and GKE it is read from the \
62 metadata server"
63 )]
64 NoLocation,
65 #[error("Google Cloud credentials for metric export: {0}")]
67 Credentials(String),
68 #[error("Telemetry API channel: {0}")]
70 Channel(String),
71}
72
73#[derive(Clone)]
78pub(crate) struct AuthInterceptor {
79 headers: Arc<RwLock<Arc<HeaderMap>>>,
80}
81
82impl AuthInterceptor {
83 fn new(headers: Arc<HeaderMap>) -> Self {
84 Self {
85 headers: Arc::new(RwLock::new(headers)),
86 }
87 }
88
89 fn set(&self, headers: Arc<HeaderMap>) {
90 *self.headers.write().unwrap_or_else(PoisonError::into_inner) = headers;
91 }
92}
93
94impl tonic::service::Interceptor for AuthInterceptor {
95 fn call(
96 &mut self,
97 mut request: tonic::Request<()>,
98 ) -> Result<tonic::Request<()>, tonic::Status> {
99 let auth = Arc::clone(&self.headers.read().unwrap_or_else(PoisonError::into_inner));
100 let mut headers = std::mem::take(request.metadata_mut()).into_headers();
101 for (name, value) in auth.iter() {
102 headers.insert(name.clone(), value.clone());
103 }
104 *request.metadata_mut() = tonic::metadata::MetadataMap::from_headers(headers);
105 Ok(request)
106 }
107}
108
109pub(crate) struct AuthRefresh(tokio::task::AbortHandle);
111
112impl Drop for AuthRefresh {
113 fn drop(&mut self) {
114 self.0.abort();
115 }
116}
117
118pub(crate) async fn auth() -> Result<(AuthInterceptor, AuthRefresh), GcpExportError> {
121 let credentials = GoogleAuthHeaders::from_adc()
122 .await
123 .map_err(|e| GcpExportError::Credentials(e.to_string()))?;
124 let first = credentials
125 .headers()
126 .await
127 .map_err(|e| GcpExportError::Credentials(e.to_string()))?;
128 let interceptor = AuthInterceptor::new(first);
129 let cache = interceptor.clone();
130 let task = tokio::spawn(async move {
131 let mut tick = tokio::time::interval(AUTH_POLL);
132 tick.tick().await;
133 loop {
134 tick.tick().await;
135 match credentials.headers().await {
136 Ok(headers) => cache.set(headers),
137 Err(e) => tracing::warn!(error = %e, "refreshing Google Cloud credentials failed"),
140 }
141 }
142 });
143 Ok((interceptor, AuthRefresh(task.abort_handle())))
144}
145
146pub(crate) async fn channel() -> Result<tonic::transport::Channel, GcpExportError> {
148 GoogleEnvironment::init_google_services_channel(TELEMETRY_ENDPOINT)
149 .await
150 .map_err(|e| GcpExportError::Channel(e.to_string()))
151}
152
153pub(crate) async fn project(configured: Option<&str>) -> Result<String, GcpExportError> {
155 match configured {
156 Some(project) => Ok(project.to_string()),
157 None => GoogleEnvironment::detect_google_project_id()
158 .await
159 .ok_or(GcpExportError::NoProject),
160 }
161}
162
163pub(crate) async fn metadata_location() -> Option<String> {
166 let host = std::env::var("GCE_METADATA_HOST")
167 .ok()
168 .filter(|h| !h.trim().is_empty())
169 .unwrap_or_else(|| "metadata.google.internal".to_string());
170 let client = reqwest::Client::builder()
171 .timeout(METADATA_TIMEOUT)
172 .build()
173 .ok()?;
174 for path in ["instance/region", "instance/zone"] {
175 let url = format!("http://{host}/computeMetadata/v1/{path}");
176 let Ok(response) = client
177 .get(&url)
178 .header("Metadata-Flavor", "Google")
179 .send()
180 .await
181 else {
182 return None;
184 };
185 if !response.status().is_success() {
186 continue;
187 }
188 if let Some(location) = response.text().await.ok().as_deref().and_then(last_segment) {
189 return Some(location);
190 }
191 }
192 None
193}
194
195fn last_segment(path: &str) -> Option<String> {
197 path.trim()
198 .rsplit('/')
199 .next()
200 .filter(|s| !s.is_empty())
201 .map(str::to_string)
202}
203
204fn has_any(resource: &Resource, keys: &[&'static str]) -> bool {
205 keys.iter().any(|k| {
206 resource
207 .get(&Key::from_static_str(k))
208 .is_some_and(|v| !v.as_str().trim().is_empty())
209 })
210}
211
212pub(crate) fn has_location(resource: &Resource) -> bool {
214 has_any(resource, &LOCATION_KEYS)
215}
216
217pub(crate) fn metrics_resource(
222 env: &Resource,
223 service_name: &str,
224 project: &str,
225 location: Option<String>,
226) -> Result<Resource, GcpExportError> {
227 let mut defaults = vec![KeyValue::new("gcp.project_id", project.to_string())];
228 if !has_location(env) {
229 let location = location.ok_or(GcpExportError::NoLocation)?;
230 defaults.push(KeyValue::new("cloud.region", location));
231 }
232 if !has_any(env, &INSTANCE_KEYS) {
233 defaults.push(KeyValue::new(
234 "service.instance.id",
235 uuid::Uuid::new_v4().to_string(),
236 ));
237 }
238 let explicit = env
240 .iter()
241 .filter(|(_, v)| !v.as_str().trim().is_empty())
242 .map(|(k, v)| KeyValue::new(k.clone(), v.clone()));
243 Ok(Resource::builder_empty()
244 .with_attributes(defaults)
245 .with_attributes(explicit)
246 .with_service_name(service_name.to_string())
247 .build())
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253 use tonic::service::Interceptor as _;
254
255 fn resource(attrs: &[(&'static str, &'static str)]) -> Resource {
256 Resource::builder_empty()
257 .with_attributes(attrs.iter().map(|(k, v)| KeyValue::new(*k, *v)))
258 .build()
259 }
260
261 fn get(resource: &Resource, key: &'static str) -> Option<String> {
262 resource
263 .get(&Key::from_static_str(key))
264 .map(|v| v.as_str().into_owned())
265 }
266
267 #[test]
268 fn resource_fills_the_labels_cloud_monitoring_requires() {
269 let r = metrics_resource(&resource(&[]), "svc", "proj", Some("us-central1".into()))
270 .expect("resource");
271 assert_eq!(get(&r, "gcp.project_id").as_deref(), Some("proj"));
272 assert_eq!(get(&r, "cloud.region").as_deref(), Some("us-central1"));
273 assert_eq!(get(&r, "service.name").as_deref(), Some("svc"));
274 let instance = get(&r, "service.instance.id").expect("instance id");
275 assert!(uuid::Uuid::parse_str(&instance).is_ok(), "{instance}");
276 }
277
278 #[test]
279 fn resource_keeps_what_the_environment_sets() {
280 let env = resource(&[
281 ("location", "europe-west1-b"),
282 ("k8s.pod.name", "pod-7"),
283 ("gcp.project_id", "from-env"),
284 ]);
285 let r = metrics_resource(&env, "svc", "proj", None).expect("resource");
286 assert_eq!(get(&r, "location").as_deref(), Some("europe-west1-b"));
287 assert_eq!(
288 get(&r, "cloud.region"),
289 None,
290 "no default over an explicit location"
291 );
292 assert_eq!(
293 get(&r, "service.instance.id"),
294 None,
295 "the pod name is the instance"
296 );
297 assert_eq!(get(&r, "gcp.project_id").as_deref(), Some("from-env"));
298 }
299
300 #[test]
301 fn resource_without_any_location_is_an_error() {
302 let err = metrics_resource(&resource(&[]), "svc", "proj", None).unwrap_err();
303 assert!(matches!(err, GcpExportError::NoLocation), "{err}");
304 assert!(err.to_string().contains("cloud.region"), "{err}");
305 }
306
307 #[test]
308 fn blank_location_does_not_count() {
309 let env = resource(&[("cloud.region", " ")]);
310 assert!(!has_location(&env));
311 let r =
312 metrics_resource(&env, "svc", "proj", Some("asia-south1".into())).expect("resource");
313 assert_eq!(get(&r, "cloud.region").as_deref(), Some("asia-south1"));
314 }
315
316 #[test]
317 fn metadata_paths_reduce_to_their_last_segment() {
318 assert_eq!(
319 last_segment("projects/123/regions/us-central1\n").as_deref(),
320 Some("us-central1")
321 );
322 assert_eq!(
323 last_segment("projects/123/zones/us-east1-b").as_deref(),
324 Some("us-east1-b")
325 );
326 assert_eq!(last_segment("projects/123/zones/"), None);
327 }
328
329 #[test]
330 fn interceptor_adds_the_current_headers_and_keeps_the_request_metadata() {
331 let headers = |token: &str| {
332 let mut h = HeaderMap::new();
333 h.insert(
334 "authorization",
335 format!("Bearer {token}").parse().expect("value"),
336 );
337 h.insert("x-goog-user-project", "quota".parse().expect("value"));
338 Arc::new(h)
339 };
340 let mut interceptor = AuthInterceptor::new(headers("one"));
341 let mut request = tonic::Request::new(());
342 request
343 .metadata_mut()
344 .insert("x-custom", "kept".parse().expect("value"));
345 let out = interceptor.call(request).expect("intercepted");
346 let md = out.metadata();
347 assert_eq!(
348 md.get("authorization").and_then(|v| v.to_str().ok()),
349 Some("Bearer one")
350 );
351 assert_eq!(
352 md.get("x-goog-user-project").and_then(|v| v.to_str().ok()),
353 Some("quota")
354 );
355 assert_eq!(
356 md.get("x-custom").and_then(|v| v.to_str().ok()),
357 Some("kept")
358 );
359
360 interceptor.set(headers("two"));
362 let out = interceptor
363 .call(tonic::Request::new(()))
364 .expect("intercepted");
365 let values: Vec<_> = out
366 .metadata()
367 .get_all("authorization")
368 .iter()
369 .map(|v| v.to_str().unwrap_or("<not ascii>").to_string())
370 .collect();
371 assert_eq!(values, vec!["Bearer two".to_string()]);
372 }
373}