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 http::uri;
11use serde::de::Error;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
14use std::{borrow::Cow, ops::Deref, path::PathBuf, str::FromStr};
15
16pub mod azure_app_services;
17#[cfg(not(target_arch = "wasm32"))]
18pub mod cc_utils;
19#[cfg(not(target_arch = "wasm32"))]
20pub mod connector;
21#[cfg(feature = "reqwest")]
22pub mod dump_server;
23pub mod entity_id;
24pub mod regex_engine;
25#[macro_use]
26pub mod cstr;
27#[cfg(feature = "bench-utils")]
28pub mod bench_utils;
29pub mod config;
30pub mod error;
31pub mod http_common;
32pub mod multipart;
33#[cfg(not(target_arch = "wasm32"))]
34pub mod rate_limiter;
35pub mod tag;
36#[cfg(any(test, feature = "test-utils"))]
37pub mod test_utils;
38#[cfg(not(target_arch = "wasm32"))]
39pub mod threading;
40#[cfg(not(target_arch = "wasm32"))]
41pub mod timeout;
42pub mod unix_utils;
43
44pub trait MutexExt<T> {
81 fn lock_or_panic(&self) -> MutexGuard<'_, T>;
82}
83
84impl<T> MutexExt<T> for Mutex<T> {
85 #[inline(always)]
86 #[track_caller]
87 fn lock_or_panic(&self) -> MutexGuard<'_, T> {
88 #[allow(clippy::unwrap_used)]
89 self.lock().unwrap()
90 }
91}
92
93pub trait RwLockExt<T> {
118 fn read_or_panic(&self) -> RwLockReadGuard<'_, T>;
119 fn write_or_panic(&self) -> RwLockWriteGuard<'_, T>;
120}
121
122impl<T> RwLockExt<T> for RwLock<T> {
123 #[inline(always)]
124 #[track_caller]
125 fn read_or_panic(&self) -> RwLockReadGuard<'_, T> {
126 #[allow(clippy::unwrap_used)]
127 self.read().unwrap()
128 }
129
130 #[inline(always)]
131 #[track_caller]
132 fn write_or_panic(&self) -> RwLockWriteGuard<'_, T> {
133 #[allow(clippy::unwrap_used)]
134 self.write().unwrap()
135 }
136}
137
138pub mod header {
139 #![allow(clippy::declare_interior_mutable_const)]
140 use http::{header::HeaderName, HeaderValue};
141
142 pub const APPLICATION_MSGPACK_STR: &str = "application/msgpack";
143 pub const APPLICATION_PROTOBUF_STR: &str = "application/x-protobuf";
144
145 pub const DATADOG_CONTAINER_ID: HeaderName = HeaderName::from_static("datadog-container-id");
146 pub const DATADOG_ENTITY_ID: HeaderName = HeaderName::from_static("datadog-entity-id");
147 pub const DATADOG_EXTERNAL_ENV: HeaderName = HeaderName::from_static("datadog-external-env");
148 pub const DATADOG_TRACE_COUNT: HeaderName = HeaderName::from_static("x-datadog-trace-count");
149 pub const DATADOG_SEND_REAL_HTTP_STATUS: HeaderName =
153 HeaderName::from_static("datadog-send-real-http-status");
154 pub const DATADOG_API_KEY: HeaderName = HeaderName::from_static("dd-api-key");
155 pub const APPLICATION_JSON: HeaderValue = HeaderValue::from_static("application/json");
156 pub const APPLICATION_MSGPACK: HeaderValue = HeaderValue::from_static(APPLICATION_MSGPACK_STR);
157 pub const APPLICATION_PROTOBUF: HeaderValue =
158 HeaderValue::from_static(APPLICATION_PROTOBUF_STR);
159 pub const X_DATADOG_TEST_SESSION_TOKEN: HeaderName =
160 HeaderName::from_static("x-datadog-test-session-token");
161}
162
163#[cfg(not(target_arch = "wasm32"))]
164pub type HttpClient = http_common::GenericHttpClient<connector::Connector>;
165#[cfg(not(target_arch = "wasm32"))]
166pub type HttpResponse = http_common::HttpResponse;
167pub type HttpRequestBuilder = http::request::Builder;
168#[cfg(not(target_arch = "wasm32"))]
169pub trait Connect:
170 hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static
171{
172}
173#[cfg(not(target_arch = "wasm32"))]
174impl<C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static> Connect
175 for C
176{
177}
178
179pub use const_format;
181
182#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
183pub struct Endpoint {
184 #[serde(serialize_with = "serialize_uri", deserialize_with = "deserialize_uri")]
185 pub url: http::Uri,
186 pub api_key: Option<Cow<'static, str>>,
187 pub timeout_ms: u64,
188 pub test_token: Option<Cow<'static, str>>,
190 #[serde(default)]
193 pub use_system_resolver: bool,
194}
195
196impl Default for Endpoint {
197 fn default() -> Self {
198 Endpoint {
199 url: http::Uri::default(),
200 api_key: None,
201 timeout_ms: Self::DEFAULT_TIMEOUT,
202 test_token: None,
203 use_system_resolver: false,
204 }
205 }
206}
207
208#[derive(serde::Deserialize, serde::Serialize)]
209struct SerializedUri<'a> {
210 scheme: Option<Cow<'a, str>>,
211 authority: Option<Cow<'a, str>>,
212 path_and_query: Option<Cow<'a, str>>,
213}
214
215fn serialize_uri<S>(uri: &http::Uri, serializer: S) -> Result<S::Ok, S::Error>
216where
217 S: Serializer,
218{
219 let parts = uri.clone().into_parts();
220 let uri = SerializedUri {
221 scheme: parts.scheme.as_ref().map(|s| Cow::Borrowed(s.as_str())),
222 authority: parts.authority.as_ref().map(|s| Cow::Borrowed(s.as_str())),
223 path_and_query: parts
224 .path_and_query
225 .as_ref()
226 .map(|s| Cow::Borrowed(s.as_str())),
227 };
228 uri.serialize(serializer)
229}
230
231fn deserialize_uri<'de, D>(deserializer: D) -> Result<http::Uri, D::Error>
232where
233 D: Deserializer<'de>,
234{
235 let uri = SerializedUri::deserialize(deserializer)?;
236 let mut builder = http::Uri::builder();
237 if let Some(v) = uri.authority {
238 builder = builder.authority(v.deref());
239 }
240 if let Some(v) = uri.scheme {
241 builder = builder.scheme(v.deref());
242 }
243 if let Some(v) = uri.path_and_query {
244 builder = builder.path_and_query(v.deref());
245 }
246
247 builder.build().map_err(Error::custom)
248}
249
250pub fn parse_uri(uri: &str) -> anyhow::Result<http::Uri> {
259 if let Some(path) = uri.strip_prefix("unix://") {
260 encode_uri_path_in_authority("unix", path)
261 } else if let Some(path) = uri.strip_prefix("windows:") {
262 encode_uri_path_in_authority("windows", path)
263 } else if let Some(path) = uri.strip_prefix("file://") {
264 encode_uri_path_in_authority("file", path)
265 } else {
266 Ok(http::Uri::from_str(uri)?)
267 }
268}
269
270fn encode_uri_path_in_authority(scheme: &str, path: &str) -> anyhow::Result<http::Uri> {
271 let mut parts = uri::Parts::default();
272 parts.scheme = uri::Scheme::from_str(scheme).ok();
273
274 let path = hex::encode(path);
275
276 parts.authority = uri::Authority::from_str(path.as_str()).ok();
277 parts.path_and_query = Some(uri::PathAndQuery::from_static(""));
278 Ok(http::Uri::from_parts(parts)?)
279}
280
281pub fn decode_uri_path_in_authority(uri: &http::Uri) -> anyhow::Result<PathBuf> {
282 let path = hex::decode(uri.authority().context("missing uri authority")?.as_str())?;
283 #[cfg(unix)]
284 {
285 use std::os::unix::ffi::OsStringExt;
286 Ok(PathBuf::from(std::ffi::OsString::from_vec(path)))
287 }
288 #[cfg(not(unix))]
289 {
290 match String::from_utf8(path) {
291 Ok(s) => Ok(PathBuf::from(s.as_str())),
292 _ => Err(anyhow::anyhow!("file uri should be utf-8")),
293 }
294 }
295}
296
297impl Endpoint {
298 pub const DEFAULT_TIMEOUT: u64 = 3_000;
300
301 pub fn get_optional_headers(&self) -> impl Iterator<Item = (&'static str, &str)> {
304 [
305 self.api_key.as_ref().map(|v| ("dd-api-key", v.as_ref())),
306 self.test_token
307 .as_ref()
308 .map(|v| ("x-datadog-test-session-token", v.as_ref())),
309 ]
310 .into_iter()
311 .flatten()
312 }
313
314 pub fn set_standard_headers(
317 &self,
318 mut builder: http::request::Builder,
319 user_agent: &str,
320 ) -> http::request::Builder {
321 builder = builder.header("user-agent", user_agent);
322 for (name, value) in self.get_optional_headers() {
323 builder = builder.header(name, value);
324 }
325 for (name, value) in entity_id::get_entity_headers() {
326 builder = builder.header(name, value);
327 }
328 builder
329 }
330
331 pub fn to_request_builder(&self, user_agent: &str) -> anyhow::Result<HttpRequestBuilder> {
336 let mut builder = http::Request::builder()
337 .uri(self.url.clone())
338 .header(http::header::USER_AGENT, user_agent);
339
340 for (name, value) in self.get_optional_headers() {
342 builder = builder.header(name, value);
343 }
344
345 for (name, value) in entity_id::get_entity_headers() {
347 builder = builder.header(name, value);
348 }
349
350 Ok(builder)
351 }
352
353 #[inline]
354 pub fn from_slice(url: &str) -> Endpoint {
355 Endpoint {
356 #[allow(clippy::unwrap_used)]
357 url: parse_uri(url).unwrap(),
358 ..Default::default()
359 }
360 }
361
362 #[inline]
363 pub fn from_url(url: http::Uri) -> Endpoint {
364 Endpoint {
365 url,
366 ..Default::default()
367 }
368 }
369
370 pub fn is_file_endpoint(&self) -> bool {
371 self.url.scheme_str() == Some("file")
372 }
373
374 pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
383 self.timeout_ms = if timeout_ms == 0 {
384 Self::DEFAULT_TIMEOUT
385 } else {
386 timeout_ms
387 };
388 self
389 }
390
391 pub fn with_system_resolver(mut self, use_system_resolver: bool) -> Self {
394 self.use_system_resolver = use_system_resolver;
395 self
396 }
397
398 #[cfg(feature = "reqwest")]
421 pub fn to_reqwest_client_builder(&self) -> anyhow::Result<(reqwest::ClientBuilder, String)> {
422 use anyhow::Context;
423
424 let mut builder = reqwest::Client::builder()
429 .timeout(std::time::Duration::from_millis(self.timeout_ms))
430 .hickory_dns(!self.use_system_resolver)
431 .no_proxy();
432
433 let request_url = match self.url.scheme_str() {
434 Some("http") | Some("https") => self.url.to_string(),
436
437 Some("file") => {
439 let output_path = decode_uri_path_in_authority(&self.url)
440 .context("Failed to decode file path from URI")?;
441 let socket_or_pipe_path = dump_server::spawn_dump_server(output_path)?;
442
443 #[cfg(unix)]
445 {
446 builder = builder.unix_socket(socket_or_pipe_path);
447 }
448 #[cfg(windows)]
449 {
450 builder = builder
451 .windows_named_pipe(socket_or_pipe_path.to_string_lossy().to_string());
452 }
453
454 "http://localhost/".to_string()
455 }
456
457 #[cfg(unix)]
459 Some("unix") => {
460 use connector::uds::socket_path_from_uri;
461 let socket_path = socket_path_from_uri(&self.url)?;
462 builder = builder.unix_socket(socket_path);
463 format!("http://localhost{}", self.url.path())
464 }
465
466 #[cfg(windows)]
468 Some("windows") => {
469 use connector::named_pipe::named_pipe_path_from_uri;
470 let pipe_path = named_pipe_path_from_uri(&self.url)?;
471 builder = builder.windows_named_pipe(pipe_path.to_string_lossy().to_string());
472 format!("http://localhost{}", self.url.path())
473 }
474
475 scheme => anyhow::bail!("Unsupported endpoint scheme: {:?}", scheme),
477 };
478
479 Ok((builder, request_url))
480 }
481}