Skip to main content

libdd_common/
lib.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3#![cfg_attr(not(test), deny(clippy::panic))]
4#![cfg_attr(not(test), deny(clippy::unwrap_used))]
5#![cfg_attr(not(test), deny(clippy::expect_used))]
6#![cfg_attr(not(test), deny(clippy::todo))]
7#![cfg_attr(not(test), deny(clippy::unimplemented))]
8
9extern crate alloc;
10
11use alloc::borrow::Cow;
12use anyhow::Context;
13use core::{ops::Deref, str::FromStr};
14use http::uri;
15use serde::de::Error;
16use serde::{Deserialize, Deserializer, Serialize, Serializer};
17use std::path::PathBuf;
18use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
19
20pub mod azure_app_services;
21#[cfg(not(target_arch = "wasm32"))]
22pub mod cc_utils;
23#[cfg(not(target_arch = "wasm32"))]
24pub mod connector;
25#[cfg(feature = "reqwest")]
26pub mod dump_server;
27pub mod entity_id;
28pub mod machine_id;
29pub mod regex_engine;
30#[macro_use]
31pub mod cstr;
32#[cfg(feature = "bench-utils")]
33pub mod bench_utils;
34pub mod config;
35pub mod error;
36pub mod http_common;
37pub mod multipart;
38#[cfg(not(target_arch = "wasm32"))]
39pub mod rate_limiter;
40pub mod tag;
41#[cfg(any(test, feature = "test-utils"))]
42pub mod test_utils;
43#[cfg(not(target_arch = "wasm32"))]
44pub mod threading;
45#[cfg(not(target_arch = "wasm32"))]
46pub mod timeout;
47pub mod unix_utils;
48
49/// Extension trait for `Mutex` to provide a method that acquires a lock, panicking if the lock is
50/// poisoned.
51///
52/// This helper function is intended to be used to avoid having to add many
53/// `#[allow(clippy::unwrap_used)]` annotations if there are a lot of usages of `Mutex`.
54///
55/// # Arguments
56///
57/// * `self` - A reference to the `Mutex` to lock.
58///
59/// # Returns
60///
61/// A `MutexGuard` that provides access to the locked data.
62///
63/// # Panics
64///
65/// This function will panic if the `Mutex` is poisoned.
66///
67/// # Examples
68///
69/// ```
70/// use libdd_common::MutexExt;
71/// use std::sync::{Arc, Mutex};
72///
73/// let data = Arc::new(Mutex::new(5));
74/// let data_clone = Arc::clone(&data);
75///
76/// std::thread::spawn(move || {
77///     let mut num = data_clone.lock_or_panic();
78///     *num += 1;
79/// })
80/// .join()
81/// .expect("Thread panicked");
82///
83/// assert_eq!(*data.lock_or_panic(), 6);
84/// ```
85pub trait MutexExt<T> {
86    fn lock_or_panic(&self) -> MutexGuard<'_, T>;
87}
88
89impl<T> MutexExt<T> for Mutex<T> {
90    #[inline(always)]
91    #[track_caller]
92    fn lock_or_panic(&self) -> MutexGuard<'_, T> {
93        #[allow(clippy::unwrap_used)]
94        self.lock().unwrap()
95    }
96}
97
98/// Extension trait for `RwLock` to provide methods that acquire read/write locks, panicking if
99/// the lock is poisoned.
100///
101/// Mirrors [`MutexExt`] for `RwLock` so callers avoid `#[allow(clippy::unwrap_used)]` at each
102/// lock site.
103///
104/// # Examples
105///
106/// ```
107/// use libdd_common::RwLockExt;
108/// use std::sync::{Arc, RwLock};
109///
110/// let data = Arc::new(RwLock::new(5));
111/// let data_clone = Arc::clone(&data);
112///
113/// std::thread::spawn(move || {
114///     let mut num = data_clone.write_or_panic();
115///     *num += 1;
116/// })
117/// .join()
118/// .expect("Thread panicked");
119///
120/// assert_eq!(*data.read_or_panic(), 6);
121/// ```
122pub trait RwLockExt<T> {
123    fn read_or_panic(&self) -> RwLockReadGuard<'_, T>;
124    fn write_or_panic(&self) -> RwLockWriteGuard<'_, T>;
125}
126
127impl<T> RwLockExt<T> for RwLock<T> {
128    #[inline(always)]
129    #[track_caller]
130    fn read_or_panic(&self) -> RwLockReadGuard<'_, T> {
131        #[allow(clippy::unwrap_used)]
132        self.read().unwrap()
133    }
134
135    #[inline(always)]
136    #[track_caller]
137    fn write_or_panic(&self) -> RwLockWriteGuard<'_, T> {
138        #[allow(clippy::unwrap_used)]
139        self.write().unwrap()
140    }
141}
142
143/// Extension trait that extracts the value from a `Result` whose error type is uninhabited.
144///
145/// The signature constrains callers at compile time: the method is only available when the
146/// error type is [`core::convert::Infallible`]. No panics — the compiler proves the `Err`
147/// arm unreachable from the type.
148///
149/// # Examples
150///
151/// ```
152/// use libdd_common::ResultInfallibleExt;
153/// use std::convert::Infallible;
154///
155/// let result: Result<i32, Infallible> = Ok(42);
156/// assert_eq!(result.unwrap_infallible(), 42);
157/// ```
158pub trait ResultInfallibleExt<T>: sealed::Sealed {
159    fn unwrap_infallible(self) -> T;
160}
161
162impl<T> ResultInfallibleExt<T> for Result<T, core::convert::Infallible> {
163    #[inline(always)]
164    fn unwrap_infallible(self) -> T {
165        match self {
166            Ok(value) => value,
167            Err(never) => match never {},
168        }
169    }
170}
171
172mod sealed {
173    pub trait Sealed {}
174    impl<T> Sealed for Result<T, core::convert::Infallible> {}
175}
176
177pub mod header {
178    #![allow(clippy::declare_interior_mutable_const)]
179    use http::{header::HeaderName, HeaderValue};
180
181    pub const APPLICATION_MSGPACK_STR: &str = "application/msgpack";
182    pub const APPLICATION_PROTOBUF_STR: &str = "application/x-protobuf";
183
184    pub const DATADOG_CONTAINER_ID: HeaderName = HeaderName::from_static("datadog-container-id");
185    pub const DATADOG_ENTITY_ID: HeaderName = HeaderName::from_static("datadog-entity-id");
186    pub const DATADOG_EXTERNAL_ENV: HeaderName = HeaderName::from_static("datadog-external-env");
187    pub const DATADOG_TRACE_COUNT: HeaderName = HeaderName::from_static("x-datadog-trace-count");
188    /// Signal to the agent to send 429 responses when a payload is dropped
189    /// If this is not set then the agent will always return a 200 regardless if the payload is
190    /// dropped.
191    pub const DATADOG_SEND_REAL_HTTP_STATUS: HeaderName =
192        HeaderName::from_static("datadog-send-real-http-status");
193    pub const DATADOG_API_KEY: HeaderName = HeaderName::from_static("dd-api-key");
194    pub const APPLICATION_JSON: HeaderValue = HeaderValue::from_static("application/json");
195    pub const APPLICATION_MSGPACK: HeaderValue = HeaderValue::from_static(APPLICATION_MSGPACK_STR);
196    pub const APPLICATION_PROTOBUF: HeaderValue =
197        HeaderValue::from_static(APPLICATION_PROTOBUF_STR);
198    pub const X_DATADOG_TEST_SESSION_TOKEN: HeaderName =
199        HeaderName::from_static("x-datadog-test-session-token");
200}
201
202#[cfg(not(target_arch = "wasm32"))]
203pub type HttpClient = http_common::GenericHttpClient<connector::Connector>;
204#[cfg(not(target_arch = "wasm32"))]
205pub type HttpResponse = http_common::HttpResponse;
206pub type HttpRequestBuilder = http::request::Builder;
207#[cfg(not(target_arch = "wasm32"))]
208pub trait Connect:
209    hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static
210{
211}
212#[cfg(not(target_arch = "wasm32"))]
213impl<C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static> Connect
214    for C
215{
216}
217
218// Used by tag! macro
219pub use const_format;
220
221#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
222pub struct Endpoint {
223    #[serde(serialize_with = "serialize_uri", deserialize_with = "deserialize_uri")]
224    pub url: http::Uri,
225    pub api_key: Option<Cow<'static, str>>,
226    pub timeout_ms: u64,
227    /// Sets X-Datadog-Test-Session-Token header on any request
228    pub test_token: Option<Cow<'static, str>>,
229    /// Use the system DNS resolver when building the HTTP client. If false, the default
230    /// in-process resolver is used.
231    #[serde(default)]
232    pub use_system_resolver: bool,
233}
234
235impl Default for Endpoint {
236    fn default() -> Self {
237        Endpoint {
238            url: http::Uri::default(),
239            api_key: None,
240            timeout_ms: Self::DEFAULT_TIMEOUT,
241            test_token: None,
242            use_system_resolver: false,
243        }
244    }
245}
246
247#[derive(serde::Deserialize, serde::Serialize)]
248struct SerializedUri<'a> {
249    scheme: Option<Cow<'a, str>>,
250    authority: Option<Cow<'a, str>>,
251    path_and_query: Option<Cow<'a, str>>,
252}
253
254fn serialize_uri<S>(uri: &http::Uri, serializer: S) -> Result<S::Ok, S::Error>
255where
256    S: Serializer,
257{
258    let parts = uri.clone().into_parts();
259    let uri = SerializedUri {
260        scheme: parts.scheme.as_ref().map(|s| Cow::Borrowed(s.as_str())),
261        authority: parts.authority.as_ref().map(|s| Cow::Borrowed(s.as_str())),
262        path_and_query: parts
263            .path_and_query
264            .as_ref()
265            .map(|s| Cow::Borrowed(s.as_str())),
266    };
267    uri.serialize(serializer)
268}
269
270fn deserialize_uri<'de, D>(deserializer: D) -> Result<http::Uri, D::Error>
271where
272    D: Deserializer<'de>,
273{
274    let uri = SerializedUri::deserialize(deserializer)?;
275    let mut builder = http::Uri::builder();
276    if let Some(v) = uri.authority {
277        builder = builder.authority(v.deref());
278    }
279    if let Some(v) = uri.scheme {
280        builder = builder.scheme(v.deref());
281    }
282    if let Some(v) = uri.path_and_query {
283        builder = builder.path_and_query(v.deref());
284    }
285
286    builder.build().map_err(Error::custom)
287}
288
289/// TODO: we should properly handle malformed urls
290/// * For windows and unix schemes:
291///     * For compatibility reasons with existing implementation this parser stores the encoded path
292///       in authority section as there is no existing standard [see](https://github.com/whatwg/url/issues/577)
293///       that covers this. We need to pick one hack or another
294///     * For windows, interprets everything after windows: as path
295///     * For unix, interprets everything after unix:// as path
296/// * For file scheme implementation will simply backfill missing authority section
297pub fn parse_uri(uri: &str) -> anyhow::Result<http::Uri> {
298    if let Some(path) = uri.strip_prefix("unix://") {
299        encode_uri_path_in_authority("unix", path)
300    } else if let Some(path) = uri.strip_prefix("windows:") {
301        encode_uri_path_in_authority("windows", path)
302    } else if let Some(path) = uri.strip_prefix("file://") {
303        encode_uri_path_in_authority("file", path)
304    } else {
305        Ok(http::Uri::from_str(uri)?)
306    }
307}
308
309fn encode_uri_path_in_authority(scheme: &str, path: &str) -> anyhow::Result<http::Uri> {
310    let mut parts = uri::Parts::default();
311    parts.scheme = uri::Scheme::from_str(scheme).ok();
312
313    let path = hex::encode(path);
314
315    parts.authority = uri::Authority::from_str(path.as_str()).ok();
316    parts.path_and_query = Some(uri::PathAndQuery::from_static("/"));
317    Ok(http::Uri::from_parts(parts)?)
318}
319
320pub fn decode_uri_path_in_authority(uri: &http::Uri) -> anyhow::Result<PathBuf> {
321    let path = hex::decode(uri.authority().context("missing uri authority")?.as_str())?;
322    #[cfg(unix)]
323    {
324        use std::os::unix::ffi::OsStringExt;
325        Ok(PathBuf::from(std::ffi::OsString::from_vec(path)))
326    }
327    #[cfg(not(unix))]
328    {
329        match String::from_utf8(path) {
330            Ok(s) => Ok(PathBuf::from(s.as_str())),
331            _ => Err(anyhow::anyhow!("file uri should be utf-8")),
332        }
333    }
334}
335
336impl Endpoint {
337    /// Default value for the timeout field in milliseconds.
338    pub const DEFAULT_TIMEOUT: u64 = 3_000;
339
340    /// Returns an iterator of optional endpoint-specific headers (api-key, test-token)
341    /// as (header_name, header_value) string tuples for any that are available.
342    pub fn get_optional_headers(&self) -> impl Iterator<Item = (&'static str, &str)> {
343        [
344            self.api_key.as_ref().map(|v| ("dd-api-key", v.as_ref())),
345            self.test_token
346                .as_ref()
347                .map(|v| ("x-datadog-test-session-token", v.as_ref())),
348        ]
349        .into_iter()
350        .flatten()
351    }
352
353    /// Apply standard headers (user-agent, api-key, test-token, entity headers) to an
354    /// [`http::request::Builder`].
355    pub fn set_standard_headers(
356        &self,
357        mut builder: http::request::Builder,
358        user_agent: &str,
359    ) -> http::request::Builder {
360        builder = builder.header("user-agent", user_agent);
361        for (name, value) in self.get_optional_headers() {
362            builder = builder.header(name, value);
363        }
364        for (name, value) in entity_id::get_entity_headers() {
365            builder = builder.header(name, value);
366        }
367        builder
368    }
369
370    /// Return a request builder with the following headers:
371    /// - User agent
372    /// - Api key
373    /// - Container Id/Entity Id
374    pub fn to_request_builder(&self, user_agent: &str) -> anyhow::Result<HttpRequestBuilder> {
375        let mut builder = http::Request::builder()
376            .uri(self.url.clone())
377            .header(http::header::USER_AGENT, user_agent);
378
379        // Add optional endpoint headers (api-key, test-token)
380        for (name, value) in self.get_optional_headers() {
381            builder = builder.header(name, value);
382        }
383
384        // Add entity-related headers (container-id, entity-id, external-env)
385        for (name, value) in entity_id::get_entity_headers() {
386            builder = builder.header(name, value);
387        }
388
389        Ok(builder)
390    }
391
392    #[inline]
393    pub fn from_slice(url: &str) -> Endpoint {
394        Endpoint {
395            #[allow(clippy::unwrap_used)]
396            url: parse_uri(url).unwrap(),
397            ..Default::default()
398        }
399    }
400
401    #[inline]
402    pub fn from_url(url: http::Uri) -> Endpoint {
403        Endpoint {
404            url,
405            ..Default::default()
406        }
407    }
408
409    pub fn is_file_endpoint(&self) -> bool {
410        self.url.scheme_str() == Some("file")
411    }
412
413    /// Set a custom timeout for this endpoint.
414    /// If not called, uses the default timeout of 3000ms.
415    ///
416    /// # Arguments
417    /// * `timeout_ms` - Timeout in milliseconds. Pass 0 to use the default timeout (3000ms).
418    ///
419    /// # Returns
420    /// Self with the timeout set, allowing for method chaining
421    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
422        self.timeout_ms = if timeout_ms == 0 {
423            Self::DEFAULT_TIMEOUT
424        } else {
425            timeout_ms
426        };
427        self
428    }
429
430    /// Use the system DNS resolver when building the reqwest client. Only has effect for
431    /// HTTP(S) endpoints.
432    pub fn with_system_resolver(mut self, use_system_resolver: bool) -> Self {
433        self.use_system_resolver = use_system_resolver;
434        self
435    }
436
437    /// Creates a reqwest ClientBuilder configured for this endpoint.
438    ///
439    /// This method handles various endpoint schemes:
440    /// - `http`/`https`: Standard HTTP(S) endpoints
441    /// - `unix`: Unix domain sockets (Unix only)
442    /// - `windows`: Windows named pipes (Windows only)
443    /// - `file`: File dump endpoints for debugging (spawns a local server to capture requests)
444    ///
445    /// The default in-process resolver is used for DNS (fork-safe). To use the system DNS resolver
446    /// instead (less fork-safe), set [`Endpoint::use_system_resolver`] to true via
447    /// [`Endpoint::with_system_resolver`].
448    ///
449    /// # Returns
450    /// A tuple of (ClientBuilder, request_url) where:
451    /// - ClientBuilder is configured with the appropriate transport and timeout
452    /// - request_url is the URL string to use for HTTP requests
453    ///
454    /// # Errors
455    /// Returns an error if:
456    /// - The endpoint scheme is unsupported
457    /// - Path decoding fails
458    /// - The dump server fails to start (for file:// scheme)
459    #[cfg(feature = "reqwest")]
460    pub fn to_reqwest_client_builder(&self) -> anyhow::Result<(reqwest::ClientBuilder, String)> {
461        use anyhow::Context;
462
463        // Don't use proxies, as this calls `getenv` which is unsafe and not
464        // just in theory. It can cause crashes with PHP where php-fpm's env
465        // configuration will mutate the system environment (it doesn't pass
466        // it as part of the SAPI env, it changes the actual system env).
467        let mut builder = reqwest::Client::builder()
468            .timeout(core::time::Duration::from_millis(self.timeout_ms))
469            .hickory_dns(!self.use_system_resolver)
470            .no_proxy();
471
472        let request_url = match self.url.scheme_str() {
473            // HTTP/HTTPS endpoints
474            Some("http") | Some("https") => self.url.to_string(),
475
476            // File dump endpoint (debugging) - uses platform-specific local transport
477            Some("file") => {
478                let output_path = decode_uri_path_in_authority(&self.url)
479                    .context("Failed to decode file path from URI")?;
480                let socket_or_pipe_path = dump_server::spawn_dump_server(output_path)?;
481
482                // Configure the client to use the local socket/pipe
483                #[cfg(unix)]
484                {
485                    builder = builder.unix_socket(socket_or_pipe_path);
486                }
487                #[cfg(windows)]
488                {
489                    builder = builder
490                        .windows_named_pipe(socket_or_pipe_path.to_string_lossy().to_string());
491                }
492
493                "http://localhost/".to_string()
494            }
495
496            // Unix domain sockets
497            #[cfg(unix)]
498            Some("unix") => {
499                use connector::uds::socket_path_from_uri;
500                let socket_path = socket_path_from_uri(&self.url)?;
501                builder = builder.unix_socket(socket_path);
502                format!("http://localhost{}", self.url.path())
503            }
504
505            // Windows named pipes
506            #[cfg(windows)]
507            Some("windows") => {
508                use connector::named_pipe::named_pipe_path_from_uri;
509                let pipe_path = named_pipe_path_from_uri(&self.url)?;
510                builder = builder.windows_named_pipe(pipe_path.to_string_lossy().to_string());
511                format!("http://localhost{}", self.url.path())
512            }
513
514            // Unsupported schemes
515            scheme => anyhow::bail!("Unsupported endpoint scheme: {:?}", scheme),
516        };
517
518        Ok((builder, request_url))
519    }
520}
521
522#[cfg(test)]
523mod tests {
524    use super::parse_uri;
525
526    /// A scheme prefix with an empty path produces an empty (and therefore
527    /// dropped) authority. parsing must reject these as malformed rather
528    /// than accept them.
529    #[test]
530    fn empty_authority_uris_are_rejected() {
531        for input in ["unix://", "windows:", "file://"] {
532            let result = parse_uri(input);
533            assert!(
534                result.is_err(),
535                "expected {input:?} to be rejected, got {result:?}"
536            );
537        }
538    }
539}