1#![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
36pub 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 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
123pub 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 pub test_token: Option<Cow<'static, str>>,
134 #[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
194pub 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 pub const DEFAULT_TIMEOUT: u64 = 3_000;
244
245 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 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 for (name, value) in self.get_optional_headers() {
269 builder = builder.header(name, value);
270 }
271
272 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 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 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 #[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 Some("http") | Some("https") => self.url.to_string(),
358
359 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 #[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 #[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 #[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 scheme => anyhow::bail!("Unsupported endpoint scheme: {:?}", scheme),
399 };
400
401 Ok((builder, request_url))
402 }
403}