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
9use anyhow::Context;
10use hyper::http::uri;
11use serde::de::Error;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13use std::sync::{Mutex, MutexGuard};
14use std::{borrow::Cow, ops::Deref, path::PathBuf, str::FromStr};
15
16pub mod azure_app_services;
17pub mod cc_utils;
18pub mod connector;
19#[cfg(feature = "reqwest")]
20pub mod dump_server;
21pub mod entity_id;
22#[macro_use]
23pub mod cstr;
24pub mod config;
25pub mod error;
26pub mod http_common;
27pub mod rate_limiter;
28pub mod tag;
29#[cfg(any(test, feature = "test-utils"))]
30pub mod test_utils;
31pub mod threading;
32pub mod timeout;
33pub mod unix_utils;
34pub mod worker;
35
36/// Extension trait for `Mutex` to provide a method that acquires a lock, panicking if the lock is
37/// poisoned.
38///
39/// This helper function is intended to be used to avoid having to add many
40/// `#[allow(clippy::unwrap_used)]` annotations if there are a lot of usages of `Mutex`.
41///
42/// # Arguments
43///
44/// * `self` - A reference to the `Mutex` to lock.
45///
46/// # Returns
47///
48/// A `MutexGuard` that provides access to the locked data.
49///
50/// # Panics
51///
52/// This function will panic if the `Mutex` is poisoned.
53///
54/// # Examples
55///
56/// ```
57/// use libdd_common::MutexExt;
58/// use std::sync::{Arc, Mutex};
59///
60/// let data = Arc::new(Mutex::new(5));
61/// let data_clone = Arc::clone(&data);
62///
63/// std::thread::spawn(move || {
64///     let mut num = data_clone.lock_or_panic();
65///     *num += 1;
66/// })
67/// .join()
68/// .expect("Thread panicked");
69///
70/// assert_eq!(*data.lock_or_panic(), 6);
71/// ```
72pub trait MutexExt<T> {
73    fn lock_or_panic(&self) -> MutexGuard<'_, T>;
74}
75
76impl<T> MutexExt<T> for Mutex<T> {
77    #[inline(always)]
78    #[track_caller]
79    fn lock_or_panic(&self) -> MutexGuard<'_, T> {
80        #[allow(clippy::unwrap_used)]
81        self.lock().unwrap()
82    }
83}
84
85pub mod header {
86    #![allow(clippy::declare_interior_mutable_const)]
87    use hyper::{header::HeaderName, http::HeaderValue};
88
89    pub const APPLICATION_MSGPACK_STR: &str = "application/msgpack";
90    pub const APPLICATION_PROTOBUF_STR: &str = "application/x-protobuf";
91
92    pub const DATADOG_CONTAINER_ID: HeaderName = HeaderName::from_static("datadog-container-id");
93    pub const DATADOG_ENTITY_ID: HeaderName = HeaderName::from_static("datadog-entity-id");
94    pub const DATADOG_EXTERNAL_ENV: HeaderName = HeaderName::from_static("datadog-external-env");
95    pub const DATADOG_TRACE_COUNT: HeaderName = HeaderName::from_static("x-datadog-trace-count");
96    /// Signal to the agent to send 429 responses when a payload is dropped
97    /// If this is not set then the agent will always return a 200 regardless if the payload is
98    /// dropped.
99    pub const DATADOG_SEND_REAL_HTTP_STATUS: HeaderName =
100        HeaderName::from_static("datadog-send-real-http-status");
101    pub const DATADOG_API_KEY: HeaderName = HeaderName::from_static("dd-api-key");
102    pub const APPLICATION_JSON: HeaderValue = HeaderValue::from_static("application/json");
103    pub const APPLICATION_MSGPACK: HeaderValue = HeaderValue::from_static(APPLICATION_MSGPACK_STR);
104    pub const APPLICATION_PROTOBUF: HeaderValue =
105        HeaderValue::from_static(APPLICATION_PROTOBUF_STR);
106    pub const X_DATADOG_TEST_SESSION_TOKEN: HeaderName =
107        HeaderName::from_static("x-datadog-test-session-token");
108}
109
110pub type HttpClient = http_common::GenericHttpClient<connector::Connector>;
111pub type GenericHttpClient<C> = http_common::GenericHttpClient<C>;
112pub type HttpResponse = http_common::HttpResponse;
113pub type HttpRequestBuilder = hyper::http::request::Builder;
114pub trait Connect:
115    hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static
116{
117}
118impl<C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static> Connect
119    for C
120{
121}
122
123// Used by tag! macro
124pub use const_format;
125
126#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
127pub struct Endpoint {
128    #[serde(serialize_with = "serialize_uri", deserialize_with = "deserialize_uri")]
129    pub url: hyper::Uri,
130    pub api_key: Option<Cow<'static, str>>,
131    pub timeout_ms: u64,
132    /// Sets X-Datadog-Test-Session-Token header on any request
133    pub test_token: Option<Cow<'static, str>>,
134    /// Use the system DNS resolver when building the HTTP client. If false, the default
135    /// in-process resolver is used.
136    #[serde(default)]
137    pub use_system_resolver: bool,
138}
139
140impl Default for Endpoint {
141    fn default() -> Self {
142        Endpoint {
143            url: hyper::Uri::default(),
144            api_key: None,
145            timeout_ms: Self::DEFAULT_TIMEOUT,
146            test_token: None,
147            use_system_resolver: false,
148        }
149    }
150}
151
152#[derive(serde::Deserialize, serde::Serialize)]
153struct SerializedUri<'a> {
154    scheme: Option<Cow<'a, str>>,
155    authority: Option<Cow<'a, str>>,
156    path_and_query: Option<Cow<'a, str>>,
157}
158
159fn serialize_uri<S>(uri: &hyper::Uri, serializer: S) -> Result<S::Ok, S::Error>
160where
161    S: Serializer,
162{
163    let parts = uri.clone().into_parts();
164    let uri = SerializedUri {
165        scheme: parts.scheme.as_ref().map(|s| Cow::Borrowed(s.as_str())),
166        authority: parts.authority.as_ref().map(|s| Cow::Borrowed(s.as_str())),
167        path_and_query: parts
168            .path_and_query
169            .as_ref()
170            .map(|s| Cow::Borrowed(s.as_str())),
171    };
172    uri.serialize(serializer)
173}
174
175fn deserialize_uri<'de, D>(deserializer: D) -> Result<hyper::Uri, D::Error>
176where
177    D: Deserializer<'de>,
178{
179    let uri = SerializedUri::deserialize(deserializer)?;
180    let mut builder = hyper::Uri::builder();
181    if let Some(v) = uri.authority {
182        builder = builder.authority(v.deref());
183    }
184    if let Some(v) = uri.scheme {
185        builder = builder.scheme(v.deref());
186    }
187    if let Some(v) = uri.path_and_query {
188        builder = builder.path_and_query(v.deref());
189    }
190
191    builder.build().map_err(Error::custom)
192}
193
194/// TODO: we should properly handle malformed urls
195/// * For windows and unix schemes:
196///     * For compatibility reasons with existing implementation this parser stores the encoded path
197///       in authority section as there is no existing standard [see](https://github.com/whatwg/url/issues/577)
198///       that covers this. We need to pick one hack or another
199///     * For windows, interprets everything after windows: as path
200///     * For unix, interprets everything after unix:// as path
201/// * For file scheme implementation will simply backfill missing authority section
202pub fn parse_uri(uri: &str) -> anyhow::Result<hyper::Uri> {
203    if let Some(path) = uri.strip_prefix("unix://") {
204        encode_uri_path_in_authority("unix", path)
205    } else if let Some(path) = uri.strip_prefix("windows:") {
206        encode_uri_path_in_authority("windows", path)
207    } else if let Some(path) = uri.strip_prefix("file://") {
208        encode_uri_path_in_authority("file", path)
209    } else {
210        Ok(hyper::Uri::from_str(uri)?)
211    }
212}
213
214fn encode_uri_path_in_authority(scheme: &str, path: &str) -> anyhow::Result<hyper::Uri> {
215    let mut parts = uri::Parts::default();
216    parts.scheme = uri::Scheme::from_str(scheme).ok();
217
218    let path = hex::encode(path);
219
220    parts.authority = uri::Authority::from_str(path.as_str()).ok();
221    parts.path_and_query = Some(uri::PathAndQuery::from_static(""));
222    Ok(hyper::Uri::from_parts(parts)?)
223}
224
225pub fn decode_uri_path_in_authority(uri: &hyper::Uri) -> anyhow::Result<PathBuf> {
226    let path = hex::decode(uri.authority().context("missing uri authority")?.as_str())?;
227    #[cfg(unix)]
228    {
229        use std::os::unix::ffi::OsStringExt;
230        Ok(PathBuf::from(std::ffi::OsString::from_vec(path)))
231    }
232    #[cfg(not(unix))]
233    {
234        match String::from_utf8(path) {
235            Ok(s) => Ok(PathBuf::from(s.as_str())),
236            _ => Err(anyhow::anyhow!("file uri should be utf-8")),
237        }
238    }
239}
240
241impl Endpoint {
242    /// Default value for the timeout field in milliseconds.
243    pub const DEFAULT_TIMEOUT: u64 = 3_000;
244
245    /// Returns an iterator of optional endpoint-specific headers (api-key, test-token)
246    /// as (header_name, header_value) string tuples for any that are available.
247    pub fn get_optional_headers(&self) -> impl Iterator<Item = (&'static str, &str)> {
248        [
249            self.api_key.as_ref().map(|v| ("dd-api-key", v.as_ref())),
250            self.test_token
251                .as_ref()
252                .map(|v| ("x-datadog-test-session-token", v.as_ref())),
253        ]
254        .into_iter()
255        .flatten()
256    }
257
258    /// Return a request builder with the following headers:
259    /// - User agent
260    /// - Api key
261    /// - Container Id/Entity Id
262    pub fn to_request_builder(&self, user_agent: &str) -> anyhow::Result<HttpRequestBuilder> {
263        let mut builder = hyper::Request::builder()
264            .uri(self.url.clone())
265            .header(hyper::header::USER_AGENT, user_agent);
266
267        // Add optional endpoint headers (api-key, test-token)
268        for (name, value) in self.get_optional_headers() {
269            builder = builder.header(name, value);
270        }
271
272        // Add entity-related headers (container-id, entity-id, external-env)
273        for (name, value) in entity_id::get_entity_headers() {
274            builder = builder.header(name, value);
275        }
276
277        Ok(builder)
278    }
279
280    #[inline]
281    pub fn from_slice(url: &str) -> Endpoint {
282        Endpoint {
283            #[allow(clippy::unwrap_used)]
284            url: parse_uri(url).unwrap(),
285            ..Default::default()
286        }
287    }
288
289    #[inline]
290    pub fn from_url(url: hyper::Uri) -> Endpoint {
291        Endpoint {
292            url,
293            ..Default::default()
294        }
295    }
296
297    pub fn is_file_endpoint(&self) -> bool {
298        self.url.scheme_str() == Some("file")
299    }
300
301    /// Set a custom timeout for this endpoint.
302    /// If not called, uses the default timeout of 3000ms.
303    ///
304    /// # Arguments
305    /// * `timeout_ms` - Timeout in milliseconds. Pass 0 to use the default timeout (3000ms).
306    ///
307    /// # Returns
308    /// Self with the timeout set, allowing for method chaining
309    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
310        self.timeout_ms = if timeout_ms == 0 {
311            Self::DEFAULT_TIMEOUT
312        } else {
313            timeout_ms
314        };
315        self
316    }
317
318    /// Use the system DNS resolver when building the reqwest client. Only has effect for
319    /// HTTP(S) endpoints.
320    pub fn with_system_resolver(mut self, use_system_resolver: bool) -> Self {
321        self.use_system_resolver = use_system_resolver;
322        self
323    }
324
325    /// Creates a reqwest ClientBuilder configured for this endpoint.
326    ///
327    /// This method handles various endpoint schemes:
328    /// - `http`/`https`: Standard HTTP(S) endpoints
329    /// - `unix`: Unix domain sockets (Unix only)
330    /// - `windows`: Windows named pipes (Windows only)
331    /// - `file`: File dump endpoints for debugging (spawns a local server to capture requests)
332    ///
333    /// The default in-process resolver is used for DNS (fork-safe). To use the system DNS resolver
334    /// instead (less fork-safe), set [`Endpoint::use_system_resolver`] to true via
335    /// [`Endpoint::with_system_resolver`].
336    ///
337    /// # Returns
338    /// A tuple of (ClientBuilder, request_url) where:
339    /// - ClientBuilder is configured with the appropriate transport and timeout
340    /// - request_url is the URL string to use for HTTP requests
341    ///
342    /// # Errors
343    /// Returns an error if:
344    /// - The endpoint scheme is unsupported
345    /// - Path decoding fails
346    /// - The dump server fails to start (for file:// scheme)
347    #[cfg(feature = "reqwest")]
348    pub fn to_reqwest_client_builder(&self) -> anyhow::Result<(reqwest::ClientBuilder, String)> {
349        use anyhow::Context;
350
351        let mut builder = reqwest::Client::builder()
352            .timeout(std::time::Duration::from_millis(self.timeout_ms))
353            .hickory_dns(!self.use_system_resolver);
354
355        let request_url = match self.url.scheme_str() {
356            // HTTP/HTTPS endpoints
357            Some("http") | Some("https") => self.url.to_string(),
358
359            // File dump endpoint (debugging) - uses platform-specific local transport
360            Some("file") => {
361                let output_path = decode_uri_path_in_authority(&self.url)
362                    .context("Failed to decode file path from URI")?;
363                let socket_or_pipe_path = dump_server::spawn_dump_server(output_path)?;
364
365                // Configure the client to use the local socket/pipe
366                #[cfg(unix)]
367                {
368                    builder = builder.unix_socket(socket_or_pipe_path);
369                }
370                #[cfg(windows)]
371                {
372                    builder = builder
373                        .windows_named_pipe(socket_or_pipe_path.to_string_lossy().to_string());
374                }
375
376                "http://localhost/".to_string()
377            }
378
379            // Unix domain sockets
380            #[cfg(unix)]
381            Some("unix") => {
382                use connector::uds::socket_path_from_uri;
383                let socket_path = socket_path_from_uri(&self.url)?;
384                builder = builder.unix_socket(socket_path);
385                format!("http://localhost{}", self.url.path())
386            }
387
388            // Windows named pipes
389            #[cfg(windows)]
390            Some("windows") => {
391                use connector::named_pipe::named_pipe_path_from_uri;
392                let pipe_path = named_pipe_path_from_uri(&self.url)?;
393                builder = builder.windows_named_pipe(pipe_path.to_string_lossy().to_string());
394                format!("http://localhost{}", self.url.path())
395            }
396
397            // Unsupported schemes
398            scheme => anyhow::bail!("Unsupported endpoint scheme: {:?}", scheme),
399        };
400
401        Ok((builder, request_url))
402    }
403}