Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(framework): implement centralized request ID management framework (#9554)

Uzair Khan1a7a43ac116f
diff --git a/Cargo.lock b/Cargo.lock
index e4a9185d18..87b646ef92 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7370,6 +7370,7 @@ dependencies = [
name = "router_env"
version = "0.1.0"
dependencies = [
+ "actix-web",
"cargo_metadata 0.18.1",
"config",
"error-stack 0.4.1",
@@ -7391,6 +7392,7 @@ dependencies = [
"tracing-attributes",
"tracing-opentelemetry",
"tracing-subscriber",
+ "uuid",
"vergen",
]
diff --git a/config/config.example.toml b/config/config.example.toml
index 5f0ac87a94..02ddd7825f 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1300,6 +1300,10 @@ enabled = false # Enable or disable chat features
hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host
encryption_key = "" # Key to encrypt and decrypt chats
+[trace_header]
+header_name = "x-request-id" # HTTP header name for request tracing (can be x-trace-id, x-correlation-id, etc.)
+id_reuse_strategy = "ignore_incoming" # Options: "ignore_incoming" (default) or "use_incoming"
+
[proxy_status_mapping]
proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response
[list_dispute_supported_connectors]
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index d14cb4f562..091c27d96c 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -442,3 +442,7 @@ org_id = "your_org_id" # Organization ID in Superpositi
workspace_id = "your_workspace_id" # Workspace ID in Superposition
polling_interval = 15 # Polling interval in seconds for configuration updates
# request_timeout = # Request timeout in seconds for Superposition API calls (optional, default: none)
+
+[trace_header]
+header_name = "x-request-id" # HTTP header name for request tracing
+id_reuse = "ignore_incoming" # Policy for handling incoming request IDs: "use_incoming" or "ignore_incoming"
diff --git a/config/development.toml b/config/development.toml
index 5f065c8f23..c688e68a6d 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -52,6 +52,9 @@ default_command_timeout = 30
unresponsive_timeout = 10
max_feed_count = 200
+[trace_header]
+header_name = "x-request-id"
+id_reuse_strategy = "ignore_incoming" # Options: "ignore_incoming" (default) or "use_incoming"
[server]
# HTTP Request body limit. Defaults to 32kB
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index d386c8fa53..36865997a4 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -1309,6 +1309,9 @@ connector_names = "stripe, adyen" # Comma-separated list of allowe
cluster = "CLUSTER" # value of CLUSTER from deployment
version = "HOSTNAME" # value of HOSTNAME from deployment which tells its version
+[trace_header]
+header_name = "x-request-id" # HTTP header name for request tracing
+
[proxy_status_mapping]
proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response
[list_dispute_supported_connectors]
diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs
index 0dc05b22fd..a21eaa918b 100644
--- a/crates/common_utils/src/keymanager.rs
+++ b/crates/common_utils/src/keymanager.rs
@@ -114,11 +114,11 @@ where
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
));
#[cfg(feature = "km_forward_x_request_id")]
- if let Some(request_id) = state.request_id {
+ if let Some(ref request_id) = state.request_id {
header.push((
HeaderName::from_str(X_REQUEST_ID)
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
- HeaderValue::from_str(request_id.as_hyphenated().to_string().as_str())
+ HeaderValue::from_str(request_id.as_str())
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
))
}
diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs
index 993eb9d211..7271cf988b 100644
--- a/crates/common_utils/src/types/keymanager.rs
+++ b/crates/common_utils/src/types/keymanager.rs
@@ -7,7 +7,7 @@ use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret};
#[cfg(feature = "encryption_service")]
use router_env::logger;
#[cfg(feature = "km_forward_x_request_id")]
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use rustc_hash::FxHashMap;
use serde::{
de::{self, Unexpected, Visitor},
diff --git a/crates/events/src/actix.rs b/crates/events/src/actix.rs
index 094336640e..5ce63097fc 100644
--- a/crates/events/src/actix.rs
+++ b/crates/events/src/actix.rs
@@ -1,4 +1,4 @@
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use crate::EventInfo;
@@ -6,7 +6,7 @@ impl EventInfo for RequestId {
type Data = String;
fn data(&self) -> error_stack::Result<String, crate::EventsError> {
- Ok(self.as_hyphenated().to_string())
+ Ok(self.to_string())
}
fn key(&self) -> String {
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs
index 49e1e054a3..d23be13dbf 100644
--- a/crates/external_services/src/grpc_client.rs
+++ b/crates/external_services/src/grpc_client.rs
@@ -23,6 +23,7 @@ use health_check_client::HealthCheckClient;
use hyper_util::client::legacy::connect::HttpConnector;
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
use router_env::logger;
+use router_env::RequestId;
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
use tonic::body::Body;
use typed_builder::TypedBuilder;
@@ -155,6 +156,8 @@ pub struct GrpcHeaders {
pub struct GrpcHeadersUcs {
/// Tenant id
tenant_id: String,
+ /// Request id
+ request_id: Option<RequestId>,
/// Lineage ids
lineage_ids: LineageIds,
/// External vault proxy metadata
@@ -162,21 +165,19 @@ pub struct GrpcHeadersUcs {
/// Merchant Reference Id
merchant_reference_id: Option<ucs_types::UcsReferenceId>,
- request_id: Option<String>,
-
shadow_mode: Option<bool>,
}
/// Type aliase for GrpcHeaders builder in initial stage
pub type GrpcHeadersUcsBuilderInitial =
- GrpcHeadersUcsBuilder<((String,), (), (), (), (Option<String>,), (Option<bool>,))>;
+ GrpcHeadersUcsBuilder<((String,), (Option<RequestId>,), (), (), (), (Option<bool>,))>;
/// Type aliase for GrpcHeaders builder in intermediate stage
pub type GrpcHeadersUcsBuilderFinal = GrpcHeadersUcsBuilder<(
(String,),
+ (Option<RequestId>,),
(LineageIds,),
(Option<String>,),
(Option<ucs_types::UcsReferenceId>,),
- (Option<String>,),
(Option<bool>,),
)>;
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index 15798c637f..1bec8d3491 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -604,10 +604,10 @@ pub fn build_unified_connector_service_grpc_headers(
);
};
- if let Some(request_id) = grpc_headers.request_id {
+ if let Some(ref request_id) = grpc_headers.request_id {
metadata.append(
common_utils_consts::X_REQUEST_ID,
- parse(common_utils_consts::X_REQUEST_ID, &request_id)?,
+ parse(common_utils_consts::X_REQUEST_ID, request_id.as_str())?,
);
};
diff --git a/crates/hyperswitch_interfaces/src/api_client.rs b/crates/hyperswitch_interfaces/src/api_client.rs
index 5c47dac6a5..6f55cc4a6a 100644
--- a/crates/hyperswitch_interfaces/src/api_client.rs
+++ b/crates/hyperswitch_interfaces/src/api_client.rs
@@ -17,7 +17,7 @@ use hyperswitch_domain_models::{
};
use masking::Maskable;
use reqwest::multipart::Form;
-use router_env::{instrument, logger, tracing, tracing_actix_web::RequestId};
+use router_env::{instrument, logger, tracing, RequestId};
use serde_json::json;
use crate::{
diff --git a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
index bf9eafe5aa..9642092c5d 100644
--- a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
+++ b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
@@ -1,7 +1,7 @@
//! Connector API logs interface
use common_utils::request::Method;
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use serde::Serialize;
use serde_json::json;
use time::OffsetDateTime;
@@ -63,7 +63,7 @@ impl ConnectorEvent {
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id
- .map(|i| i.as_hyphenated().to_string())
+ .map(|i| i.to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
latency,
refund_id,
diff --git a/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs b/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
index efeefc851b..4ec8aed79c 100644
--- a/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
+++ b/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
@@ -4,7 +4,7 @@ use std::fmt;
use api_models::routing::RoutableConnectorChoice;
use common_utils::request::Method;
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use serde::Serialize;
use serde_json::json;
use time::OffsetDateTime;
@@ -91,7 +91,7 @@ impl RoutingEvent {
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),
status_code: None,
request_id: request_id
- .map(|i| i.as_hyphenated().to_string())
+ .map(|i| i.to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
routing_engine,
payment_connector: None,
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 0f59774c6d..8cf32ca456 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -589,6 +589,7 @@ pub(crate) async fn fetch_raw_secrets(
infra_values: conf.infra_values,
enhancement: conf.enhancement,
proxy_status_mapping: conf.proxy_status_mapping,
+ trace_header: conf.trace_header,
internal_services: conf.internal_services,
superposition,
comparison_service: conf.comparison_service,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 6f8ab80b6b..0f7a66c01d 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -178,6 +178,7 @@ pub struct Settings<S: SecretState> {
pub enhancement: Option<HashMap<String, String>>,
pub superposition: SecretStateContainer<SuperpositionClientConfig, S>,
pub proxy_status_mapping: ProxyStatusMapping,
+ pub trace_header: TraceHeaderConfig,
pub internal_services: InternalServicesConfig,
pub comparison_service: Option<ComparisonServiceConfig>,
}
@@ -819,6 +820,22 @@ pub struct ProxyStatusMapping {
pub proxy_connector_http_status_code: bool,
}
+#[derive(Debug, Clone, Deserialize)]
+#[serde(default)]
+pub struct TraceHeaderConfig {
+ pub header_name: String,
+ pub id_reuse_strategy: router_env::IdReuse,
+}
+
+impl Default for TraceHeaderConfig {
+ fn default() -> Self {
+ Self {
+ header_name: common_utils::consts::X_REQUEST_ID.to_string(),
+ id_reuse_strategy: router_env::IdReuse::IgnoreIncoming,
+ }
+ }
+}
+
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct WebhooksSettings {
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d2f7b97db6..bfef7fe9b6 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2106,7 +2106,7 @@ pub async fn get_payment_method_from_hs_locker<'a>(
payment_method_reference,
locker_choice,
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)
@@ -2160,7 +2160,7 @@ pub async fn add_card_to_hs_locker(
payload,
locker_choice,
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
)
.await?;
call_locker_api::<payment_methods::StoreCardResp>(
@@ -2343,7 +2343,7 @@ pub async fn get_card_from_hs_locker<'a>(
card_reference,
Some(locker_choice),
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
)
.await
.change_context(errors::VaultError::FetchCardFailed)
@@ -2389,7 +2389,7 @@ pub async fn delete_card_from_hs_locker<'a>(
merchant_id,
card_reference,
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 53c0765050..8b0516c08e 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -12,7 +12,7 @@ use error_stack::ResultExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data;
use josekit::jwe;
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
@@ -400,10 +400,7 @@ pub async fn mk_add_locker_request_hs(
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
- request.add_header(
- headers::X_REQUEST_ID,
- req_id.as_hyphenated().to_string().into(),
- );
+ request.add_header(headers::X_REQUEST_ID, req_id.to_string().into());
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
@@ -642,10 +639,7 @@ pub async fn mk_get_card_request_hs(
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
- request.add_header(
- headers::X_REQUEST_ID,
- req_id.as_hyphenated().to_string().into(),
- );
+ request.add_header(headers::X_REQUEST_ID, req_id.to_string().into());
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
@@ -724,10 +718,7 @@ pub async fn mk_delete_card_request_hs(
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
- request.add_header(
- headers::X_REQUEST_ID,
- req_id.as_hyphenated().to_string().into(),
- );
+ request.add_header(headers::X_REQUEST_ID, req_id.to_string().into());
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
@@ -773,10 +764,7 @@ pub async fn mk_delete_card_request_hs_by_id(
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
- request.add_header(
- headers::X_REQUEST_ID,
- req_id.as_hyphenated().to_string().into(),
- );
+ request.add_header(headers::X_REQUEST_ID, req_id.to_string().into());
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
@@ -867,10 +855,7 @@ pub fn mk_crud_locker_request(
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
- request.add_header(
- headers::X_REQUEST_ID,
- req_id.as_hyphenated().to_string().into(),
- );
+ request.add_header(headers::X_REQUEST_ID, req_id.to_string().into());
}
request.set_body(RequestContent::Json(Box::new(req)));
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 5e0f0eb1b8..cfc6621ca6 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -1742,7 +1742,7 @@ where
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
@@ -1932,7 +1932,7 @@ where
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
@@ -2033,7 +2033,7 @@ pub async fn update_gateway_score_with_open_router(
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
@@ -2163,7 +2163,7 @@ where
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
@@ -2349,7 +2349,7 @@ pub async fn perform_elimination_routing(
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
@@ -2561,7 +2561,7 @@ where
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs
index d1998d0e51..fa44c71599 100644
--- a/crates/router/src/core/payments/routing/utils.rs
+++ b/crates/router/src/core/payments/routing/utils.rs
@@ -30,7 +30,7 @@ use euclid::{
use external_services::grpc_client::dynamic_routing as ir_client;
use hyperswitch_domain_models::business_profile;
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use serde::{Deserialize, Serialize};
use super::RoutingResult;
@@ -399,7 +399,7 @@ pub async fn decision_engine_routing(
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let routing_events_wrapper = RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_id,
business_profile.get_id().to_owned(),
business_profile.merchant_id.to_owned(),
@@ -1615,7 +1615,7 @@ where
wrapper.payment_id.clone(),
wrapper.profile_id.clone(),
wrapper.merchant_id.clone(),
- wrapper.request_id,
+ wrapper.request_id.clone(),
routing_engine,
);
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index e19e661343..989a21bdab 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -1103,7 +1103,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
@@ -1290,7 +1290,7 @@ pub async fn update_window_for_elimination_routing(
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
@@ -1481,7 +1481,7 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing(
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
- state.request_id,
+ state.request_id.clone(),
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 8375debf84..cecb869573 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -24,7 +24,7 @@ use hyperswitch_domain_models::{
};
use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails};
use masking::{ExposeInterface, PeekInterface};
-use router_env::{instrument, tracing, tracing_actix_web::RequestId};
+use router_env::{instrument, tracing, RequestId};
use unified_connector_service_client::payments as payments_grpc;
use super::{types, utils, MERCHANT_ID};
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index 975a6ea3b8..ba892ccc39 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -12,7 +12,7 @@ use hyperswitch_domain_models::{
router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
};
use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails;
-use router_env::{instrument, tracing, tracing_actix_web::RequestId};
+use router_env::{instrument, tracing, RequestId};
use super::{types, utils, MERCHANT_ID};
#[cfg(feature = "revenue_recovery")]
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs
index 01c7323686..0906ce992f 100644
--- a/crates/router/src/events/api_logs.rs
+++ b/crates/router/src/events/api_logs.rs
@@ -1,7 +1,7 @@
use actix_web::HttpRequest;
pub use common_utils::events::{ApiEventMetric, ApiEventsType};
use common_utils::impl_api_event_type;
-use router_env::{tracing_actix_web::RequestId, types::FlowMetric};
+use router_env::{types::FlowMetric, RequestId};
use serde::Serialize;
use time::OffsetDateTime;
@@ -72,7 +72,7 @@ impl ApiEvent {
merchant_id,
api_flow: api_flow.to_string(),
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
- request_id: request_id.as_hyphenated().to_string(),
+ request_id: request_id.to_string(),
latency,
status_code,
request: request.to_string(),
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 679ef8aff3..8e64f5daf4 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -123,7 +123,11 @@ pub fn mk_app(
InitError = (),
>,
> {
- let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone());
+ let mut server_app = get_application_builder(
+ request_body_limit,
+ state.conf.cors.clone(),
+ state.conf.trace_header.clone(),
+ );
#[cfg(feature = "dummy_connector")]
{
@@ -374,6 +378,7 @@ impl Stop for mpsc::Sender<()> {
pub fn get_application_builder(
request_body_limit: usize,
cors: settings::CorsSettings,
+ trace_header: settings::TraceHeaderConfig,
) -> actix_web::App<
impl ServiceFactory<
ServiceRequest,
@@ -399,12 +404,17 @@ pub fn get_application_builder(
errors::error_handlers::custom_error_handlers,
))
.wrap(middleware::default_response_headers())
- .wrap(middleware::RequestId)
.wrap(cors::cors(cors))
// this middleware works only for Http1.1 requests
.wrap(middleware::Http400RequestDetailsLogger)
.wrap(middleware::AddAcceptLanguageHeader)
.wrap(middleware::RequestResponseMetrics)
.wrap(middleware::LogSpanInitializer)
- .wrap(router_env::tracing_actix_web::TracingLogger::default())
+ .wrap(router_env::tracing_actix_web::TracingLogger::<
+ router_env::CustomRootSpanBuilder,
+ >::new())
+ .wrap(
+ router_env::RequestIdentifier::new(&trace_header.header_name)
+ .use_incoming_id(trace_header.id_reuse_strategy),
+ )
}
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index c87a774c1c..de618b9837 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -1,5 +1,7 @@
use common_utils::consts::TENANT_HEADER;
use futures::StreamExt;
+// Re-export RequestId from router_env for convenience
+pub use router_env::RequestId;
use router_env::{
logger,
tracing::{field::Empty, Instrument},
@@ -7,76 +9,6 @@ use router_env::{
use crate::{headers, routes::metrics};
-/// Middleware to include request ID in response header.
-pub struct RequestId;
-
-impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestId
-where
- S: actix_web::dev::Service<
- actix_web::dev::ServiceRequest,
- Response = actix_web::dev::ServiceResponse<B>,
- Error = actix_web::Error,
- >,
- S::Future: 'static,
- B: 'static,
-{
- type Response = actix_web::dev::ServiceResponse<B>;
- type Error = actix_web::Error;
- type Transform = RequestIdMiddleware<S>;
- type InitError = ();
- type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
-
- fn new_transform(&self, service: S) -> Self::Future {
- std::future::ready(Ok(RequestIdMiddleware { service }))
- }
-}
-
-pub struct RequestIdMiddleware<S> {
- service: S,
-}
-
-impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestIdMiddleware<S>
-where
- S: actix_web::dev::Service<
- actix_web::dev::ServiceRequest,
- Response = actix_web::dev::ServiceResponse<B>,
- Error = actix_web::Error,
- >,
- S::Future: 'static,
- B: 'static,
-{
- type Response = actix_web::dev::ServiceResponse<B>;
- type Error = actix_web::Error;
- type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
-
- actix_web::dev::forward_ready!(service);
-
- fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future {
- let old_x_request_id = req.headers().get("x-request-id").cloned();
- let mut req = req;
- let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>();
- let response_fut = self.service.call(req);
-
- Box::pin(
- async move {
- let request_id = request_id_fut.await?;
- let request_id = request_id.as_hyphenated().to_string();
- if let Some(upstream_request_id) = old_x_request_id {
- router_env::logger::info!(?upstream_request_id);
- }
- let mut response = response_fut.await?;
- response.headers_mut().append(
- http::header::HeaderName::from_static("x-request-id"),
- http::HeaderValue::from_str(&request_id)?,
- );
-
- Ok(response)
- }
- .in_current_span(),
- )
- }
-}
-
/// Middleware for attaching default response headers. Headers with the same key already set in a
/// response will not be overwritten.
pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders {
@@ -257,7 +189,7 @@ where
fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future {
let svc = self.service.clone();
- let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>();
+ let request_id_fut = req.extract::<RequestId>();
Box::pin(async move {
let (http_req, payload) = req.into_parts();
let result_payload: Vec<Result<bytes::Bytes, actix_web::error::PayloadError>> =
@@ -280,7 +212,7 @@ where
let response = response_fut.await?;
// Log the request_details when we receive 400 status from the application
if response.status() == 400 {
- let request_id = request_id_fut.await?.as_hyphenated().to_string();
+ let request_id = request_id_fut.await?.to_string();
let content_length_header_string = content_length_header
.map(|content_length_header| {
content_length_header.to_str().map(ToOwned::to_owned)
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index a530956fcd..10892dbd67 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -25,7 +25,7 @@ use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
};
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use scheduler::SchedulerInterface;
use storage_impl::{redis::RedisStore, MockDb};
use tokio::sync::oneshot;
@@ -154,7 +154,7 @@ impl SessionState {
pub fn get_grpc_headers(&self) -> GrpcHeaders {
GrpcHeaders {
tenant_id: self.tenant.tenant_id.get_string_repr().to_string(),
- request_id: self.request_id.map(|req_id| (*req_id).to_string()),
+ request_id: self.request_id.as_ref().map(|req_id| req_id.to_string()),
}
}
pub fn get_grpc_headers_ucs(
@@ -162,7 +162,7 @@ impl SessionState {
unified_connector_service_execution_mode: ExecutionMode,
) -> GrpcHeadersUcsBuilderInitial {
let tenant_id = self.tenant.tenant_id.get_string_repr().to_string();
- let request_id = self.request_id.map(|req_id| (*req_id).to_string());
+ let request_id = self.request_id.clone();
let shadow_mode = match unified_connector_service_execution_mode {
ExecutionMode::Primary => false,
ExecutionMode::Shadow => true,
@@ -175,7 +175,7 @@ impl SessionState {
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders {
GrpcRecoveryHeaders {
- request_id: self.request_id.map(|req_id| (*req_id).to_string()),
+ request_id: self.request_id.as_ref().map(|req_id| req_id.to_string()),
}
}
}
@@ -206,7 +206,7 @@ impl SessionStateInfo for SessionState {
self.api_client.get_request_id_str()
}
fn add_request_id(&mut self, request_id: RequestId) {
- self.api_client.add_request_id(request_id);
+ self.api_client.add_request_id(request_id.clone());
self.store.add_request_id(request_id.to_string());
self.request_id.replace(request_id);
}
@@ -259,11 +259,10 @@ impl hyperswitch_interfaces::api_client::ApiClientWrapper for SessionState {
self.conf.proxy.clone()
}
fn get_request_id(&self) -> Option<RequestId> {
- self.request_id
+ self.request_id.clone()
}
fn get_request_id_str(&self) -> Option<String> {
- self.request_id
- .map(|req_id| req_id.as_hyphenated().to_string())
+ self.request_id.as_ref().map(|req_id| req_id.to_string())
}
fn get_tenant(&self) -> Tenant {
self.tenant.clone()
@@ -334,7 +333,7 @@ impl AppStateInfo for AppState {
self.event_handler.clone()
}
fn add_request_id(&mut self, request_id: RequestId) {
- self.api_client.add_request_id(request_id);
+ self.api_client.add_request_id(request_id.clone());
self.request_id.replace(request_id);
}
@@ -589,7 +588,7 @@ impl AppState {
#[cfg(feature = "olap")]
pool: self.pools.get(tenant).ok_or_else(err)?.clone(),
file_storage_client: self.file_storage_client.clone(),
- request_id: self.request_id,
+ request_id: self.request_id.clone(),
base_url: tenant_conf.base_url.clone(),
tenant: tenant_conf.clone(),
#[cfg(feature = "email")]
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index c72f5dba64..d5b4514625 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -49,7 +49,7 @@ pub use hyperswitch_interfaces::{
},
};
use masking::{Maskable, PeekInterface};
-use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
+use router_env::{instrument, tracing, RequestId, Tag};
use serde::Serialize;
use tera::{Context, Error as TeraError, Tera};
@@ -228,10 +228,10 @@ where
}
.switch()
})?;
- session_state.add_request_id(request_id);
+ session_state.add_request_id(request_id.clone());
let mut request_state = session_state.get_req_state();
- request_state.event_context.record_info(request_id);
+ request_state.event_context.record_info(request_id.clone());
request_state
.event_context
.record_info(("flow".to_string(), flow.to_string()));
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index fd736d9fe0..6bc2e4860e 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -10,7 +10,7 @@ pub use hyperswitch_interfaces::{
};
use masking::PeekInterface;
use reqwest::multipart::Form;
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use super::{request::Maskable, Request};
use crate::core::errors::{ApiClientError, CustomResult};
@@ -151,11 +151,11 @@ impl ApiClient for ProxyClient {
}
fn get_request_id(&self) -> Option<RequestId> {
- self.request_id
+ self.request_id.clone()
}
fn get_request_id_str(&self) -> Option<String> {
- self.request_id.map(|id| id.as_hyphenated().to_string())
+ self.request_id.as_ref().map(|id| id.to_string())
}
fn add_flow_name(&mut self, _flow_name: String) {}
diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs
index 909369901c..6488a061bd 100644
--- a/crates/router/src/types/domain/types.rs
+++ b/crates/router/src/types/domain/types.rs
@@ -16,7 +16,7 @@ impl From<&app::SessionState> for KeyManagerState {
url: conf.url.clone(),
client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "km_forward_x_request_id")]
- request_id: state.request_id,
+ request_id: state.request_id.clone(),
#[cfg(feature = "keymanager_mtls")]
cert: conf.cert.clone(),
#[cfg(feature = "keymanager_mtls")]
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 90cec730ae..0b0b64fe63 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -24,11 +24,13 @@ strum = { version = "0.26.3", features = ["derive"] }
time = { version = "0.3.41", default-features = false, features = ["formatting"] }
tokio = { version = "1.48.0" }
tracing = { workspace = true }
+actix-web = { version = "4.11.0", optional = true }
tracing-actix-web = { version = "0.7.18", features = ["opentelemetry_0_27", "uuid_v7"], optional = true }
tracing-appender = { version = "0.2.3" }
tracing-attributes = "0.1.28"
tracing-opentelemetry = { version = "0.28.0", default-features = false }
tracing-subscriber = { version = "0.3.19", default-features = true, features = ["env-filter", "json", "registry"] }
+uuid = { version = "1.17.0", features = ["v7"], optional = true }
vergen = { version = "8.3.2", optional = true, features = ["cargo", "git", "git2", "rustc"] }
[dev-dependencies]
@@ -40,7 +42,7 @@ vergen = { version = "8.3.2", features = ["cargo", "git", "git2", "rustc"], opti
[features]
default = ["actix_web", "payouts"]
-actix_web = ["tracing-actix-web"]
+actix_web = ["dep:actix-web", "tracing-actix-web", "dep:uuid"]
log_custom_entries_to_extra = []
log_extra_implicit_fields = []
log_active_span_json = []
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index 7d67dfc14f..1fc93471b5 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -9,6 +9,10 @@ pub mod cargo_workspace;
pub mod env;
pub mod logger;
pub mod metrics;
+#[cfg(feature = "actix_web")]
+pub mod request_id;
+#[cfg(feature = "actix_web")]
+pub mod root_span;
/// `cargo` build instructions generation for obtaining information about the application
/// environment.
#[cfg(feature = "vergen")]
@@ -18,6 +22,11 @@ pub mod vergen;
#[doc(inline)]
pub use logger::*;
pub use opentelemetry;
+// Re-export our internal request_id module for easier migration
+#[cfg(feature = "actix_web")]
+pub use request_id::{IdReuse, RequestId, RequestIdentifier};
+#[cfg(feature = "actix_web")]
+pub use root_span::CustomRootSpanBuilder;
pub use tracing;
#[cfg(feature = "actix_web")]
pub use tracing_actix_web;
diff --git a/crates/router_env/src/request_id.rs b/crates/router_env/src/request_id.rs
new file mode 100644
index 0000000000..e3ee0087ee
--- /dev/null
+++ b/crates/router_env/src/request_id.rs
@@ -0,0 +1,358 @@
+#![warn(unused, missing_docs)]
+//! Request ID middleware for Actix Web applications.
+//!
+//! This module provides middleware to associate every HTTP request with a unique identifier.
+//! The request ID can be used for distributed tracing, error tracking, and request correlation
+//! across microservices.
+//!
+//! # Features
+//!
+//! - **Automatic UUID v7 generation**: Uses time-ordered UUIDs for better performance
+//! - **Header reuse**: Respects incoming request ID headers for request correlation
+//! - **Configurable headers**: Custom header names supported for any request ID header
+//! - **Request extraction**: RequestId can be extracted in route handlers
+//! - **Response headers**: Automatically adds request ID to response headers
+//! - **Upstream logging**: Logs incoming request IDs for debugging
+//!
+//! # Examples
+//!
+//! ```rust
+//! use router_env::{RequestIdentifier, IdReuse};
+//! use actix_web::{web, App, HttpServer};
+//!
+//! let app = App::new()
+//! .wrap(
+//! RequestIdentifier::new("x-request-id")
+//! .use_incoming_id(IdReuse::UseIncoming)
+//! );
+//! ```
+
+use std::{
+ fmt::{self, Display, Formatter},
+ future::{ready, Future, Ready},
+ pin::Pin,
+ str::FromStr,
+ sync::Arc,
+ task::{Context, Poll},
+};
+
+use actix_web::{
+ dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
+ error::ResponseError,
+ http::header::{HeaderName, HeaderValue},
+ Error as ActixError, FromRequest, HttpMessage, HttpRequest,
+};
+use error_stack::{report, ResultExt};
+use uuid::Uuid;
+
+/// Custom result type for request ID operations.
+pub type RequestIdResult<T> = Result<T, error_stack::Report<RequestIdError>>;
+
+/// Errors that can occur when working with request IDs.
+#[derive(Debug, Clone)]
+pub enum RequestIdError {
+ /// No request ID is associated with the current request.
+ NoAssociatedId,
+ /// Failed to convert header value to request ID.
+ InvalidHeaderValue {
+ /// The invalid header value that caused the error.
+ value: String,
+ },
+}
+
+impl error_stack::Context for RequestIdError {}
+
+impl ResponseError for RequestIdError {}
+
+impl Display for RequestIdError {
+ fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::NoAssociatedId => write!(fmt, "No request ID associated with this request"),
+ Self::InvalidHeaderValue { value } => write!(fmt, "Invalid header value: {}", value),
+ }
+ }
+}
+
+/// Configuration for handling incoming request ID headers.
+#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum IdReuse {
+ /// Reuse the incoming request ID if present, otherwise generate a new one.
+ UseIncoming,
+ /// Always generate a new request ID, ignoring any incoming headers.
+ #[default]
+ IgnoreIncoming,
+}
+
+/// Generate a new UUID v7 request ID.
+fn generate_uuid_v7() -> String {
+ Uuid::now_v7().to_string()
+}
+
+/// Request ID middleware that takes a configurable header name
+/// and determines how to handle incoming request IDs.
+#[derive(Clone, Debug)]
+pub struct RequestIdentifier {
+ header_name: String,
+ use_incoming_id: IdReuse,
+}
+
+/// Request ID value that can be extracted in route handlers.
+///
+/// Wraps an `Arc<str>` for optimal performance in web middleware.
+#[derive(Clone, PartialEq, Eq, Debug, Hash)]
+pub struct RequestId(Arc<str>);
+
+/// The middleware implementation that processes requests.
+#[derive(Debug)]
+pub struct RequestIdMiddleware<S> {
+ service: S,
+ header_name: HeaderName,
+ use_incoming_id: IdReuse,
+}
+
+impl Display for RequestId {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.as_str())
+ }
+}
+
+impl FromStr for RequestId {
+ type Err = error_stack::Report<RequestIdError>;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ if s.is_empty() {
+ Err(report!(RequestIdError::InvalidHeaderValue {
+ value: s.to_string(),
+ }))
+ } else {
+ Ok(Self(s.into()))
+ }
+ }
+}
+
+impl TryFrom<HeaderValue> for RequestId {
+ type Error = error_stack::Report<RequestIdError>;
+
+ fn try_from(value: HeaderValue) -> Result<Self, Self::Error> {
+ let s = value
+ .to_str()
+ .change_context(RequestIdError::InvalidHeaderValue {
+ value: format!("{:?}", value),
+ })?;
+ Self::from_str(s)
+ }
+}
+
+impl From<RequestId> for String {
+ fn from(request_id: RequestId) -> Self {
+ request_id.0.to_string()
+ }
+}
+
+impl TryFrom<String> for RequestId {
+ type Error = error_stack::Report<RequestIdError>;
+
+ fn try_from(s: String) -> Result<Self, Self::Error> {
+ Self::from_str(s.as_str())
+ }
+}
+
+impl TryFrom<&str> for RequestId {
+ type Error = error_stack::Report<RequestIdError>;
+
+ fn try_from(s: &str) -> Result<Self, Self::Error> {
+ Self::from_str(s)
+ }
+}
+
+impl RequestId {
+ /// Extract request ID from ServiceRequest header or generate UUID v7.
+ ///
+ /// This is the core logic: try to extract from the specified header,
+ /// if not possible or not desired, generate a new UUID v7.
+ pub fn extract_or_generate(
+ request: &ServiceRequest,
+ header_name: &HeaderName,
+ use_incoming_id: IdReuse,
+ ) -> Self {
+ let request_id_string = match use_incoming_id {
+ IdReuse::UseIncoming => {
+ // Try to extract from incoming header
+ if let Some(existing_header) = request.headers().get(header_name) {
+ Self::try_from(existing_header.clone())
+ .map(|id| id.0.to_string())
+ .unwrap_or_else(|e| {
+ tracing::warn!(
+ error = %e,
+ "Invalid request ID header, generating new UUID v7"
+ );
+ generate_uuid_v7()
+ })
+ } else {
+ // No header found, generate new UUID v7
+ generate_uuid_v7()
+ }
+ }
+ IdReuse::IgnoreIncoming => {
+ // Always generate new UUID v7
+ generate_uuid_v7()
+ }
+ };
+
+ Self(request_id_string.into())
+ }
+
+ /// Convert this request ID to a `HeaderValue`.
+ pub fn to_header_value(&self) -> RequestIdResult<HeaderValue> {
+ HeaderValue::from_str(&self.0).change_context(RequestIdError::InvalidHeaderValue {
+ value: self.0.to_string(),
+ })
+ }
+
+ /// Get a string representation of this request ID.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl RequestIdentifier {
+ /// Create a request ID middleware with a custom header name.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use router_env::RequestIdentifier;
+ ///
+ /// // Use any custom header name for request ID extraction
+ /// let middleware = RequestIdentifier::new("x-request-id");
+ /// ```
+ #[must_use]
+ pub fn new(header_name: &str) -> Self {
+ Self {
+ header_name: header_name.to_string(),
+ use_incoming_id: IdReuse::default(),
+ }
+ }
+
+ /// Configure how incoming request ID headers should be handled.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use router_env::{RequestIdentifier, IdReuse};
+ ///
+ /// let middleware = RequestIdentifier::new("x-request-id")
+ /// .use_incoming_id(IdReuse::IgnoreIncoming);
+ /// ```
+ #[must_use]
+ pub fn use_incoming_id(self, use_incoming_id: IdReuse) -> Self {
+ Self {
+ use_incoming_id,
+ ..self
+ }
+ }
+}
+
+impl<S, B> Transform<S, ServiceRequest> for RequestIdentifier
+where
+ S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
+ S::Future: 'static,
+ B: 'static,
+{
+ type Response = S::Response;
+ type Error = S::Error;
+ type Transform = RequestIdMiddleware<S>;
+ type InitError = ();
+ type Future = Ready<Result<Self::Transform, Self::InitError>>;
+
+ fn new_transform(&self, service: S) -> Self::Future {
+ let header_name = HeaderName::from_str(&self.header_name).unwrap_or_else(|_| {
+ tracing::error!(
+ "Invalid header name '{}', using fallback 'x-request-id'",
+ self.header_name
+ );
+ HeaderName::from_static("x-request-id")
+ });
+
+ ready(Ok(RequestIdMiddleware {
+ service,
+ header_name,
+ use_incoming_id: self.use_incoming_id,
+ }))
+ }
+}
+
+#[allow(clippy::type_complexity)]
+impl<S, B> Service<ServiceRequest> for RequestIdMiddleware<S>
+where
+ S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
+ S::Future: 'static,
+ B: 'static,
+{
+ type Response = S::Response;
+ type Error = S::Error;
+ type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
+
+ fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+ self.service.poll_ready(ctx)
+ }
+
+ fn call(&self, request: ServiceRequest) -> Self::Future {
+ let header_name = self.header_name.clone();
+
+ // Capture incoming request ID for logging
+ let incoming_request_id = request.headers().get(&header_name).cloned();
+
+ // Extract request ID from header or generate new UUID v7
+ let request_id =
+ RequestId::extract_or_generate(&request, &header_name, self.use_incoming_id);
+
+ // Create header value for response
+ let header_value = request_id.to_header_value().unwrap_or_else(|e| {
+ tracing::error!(
+ error = %e,
+ request_id = %request_id,
+ "Failed to convert request ID to header value"
+ );
+ HeaderValue::from_static("invalid-request-id")
+ });
+
+ // Store request ID for extraction in handlers
+ request.extensions_mut().insert(request_id.clone());
+
+ let fut = self.service.call(request);
+
+ Box::pin(async move {
+ // Log incoming request IDs for correlation
+ if let Some(upstream_request_id) = incoming_request_id {
+ tracing::debug!(
+ ?upstream_request_id,
+ generated_request_id = %request_id,
+ "Received upstream request ID for correlation"
+ );
+ }
+
+ let mut response = fut.await?;
+
+ // Add request ID to response headers
+ response.headers_mut().insert(header_name, header_value);
+
+ Ok(response)
+ })
+ }
+}
+
+impl FromRequest for RequestId {
+ type Error = RequestIdError;
+ type Future = Ready<Result<Self, Self::Error>>;
+
+ fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
+ ready(
+ req.extensions()
+ .get::<Self>()
+ .cloned()
+ .ok_or(RequestIdError::NoAssociatedId),
+ )
+ }
+}
diff --git a/crates/router_env/src/root_span.rs b/crates/router_env/src/root_span.rs
new file mode 100644
index 0000000000..62ab4fa9b4
--- /dev/null
+++ b/crates/router_env/src/root_span.rs
@@ -0,0 +1,70 @@
+//! Custom RootSpanBuilder tracing-actix-web
+
+use actix_web::{
+ body::MessageBody,
+ dev::{ServiceRequest, ServiceResponse},
+ http::StatusCode,
+ Error, HttpMessage, ResponseError,
+};
+use tracing::Span;
+use tracing_actix_web::{root_span, RootSpanBuilder};
+
+use crate::request_id::RequestId;
+
+/// Custom RootSpanBuilder that captures x-request-id header in spans
+#[derive(Debug)]
+pub struct CustomRootSpanBuilder;
+
+impl RootSpanBuilder for CustomRootSpanBuilder {
+ fn on_request_start(request: &ServiceRequest) -> Span {
+ // Extract the RequestId from extensions (set by RequestIdentifier middleware)
+ // We clone the string to avoid lifetime issues with the temporary Ref guard
+ let request_id = request
+ .extensions()
+ .get::<RequestId>()
+ .map(|id| id.to_string())
+ .unwrap_or_default();
+
+ root_span!(
+ level = crate::Level::INFO,
+ request,
+ request_id = request_id.as_str()
+ )
+ }
+
+ fn on_request_end<B: MessageBody>(span: Span, outcome: &Result<ServiceResponse<B>, Error>) {
+ match &outcome {
+ Ok(response) => {
+ if let Some(error) = response.response().error() {
+ // use the status code already constructed for the outgoing HTTP response
+ handle_error(span, response.status(), error.as_response_error());
+ } else {
+ let code: i32 = response.response().status().as_u16().into();
+ span.record("http.status_code", code);
+ span.record("otel.status_code", "OK");
+ }
+ }
+ Err(error) => {
+ let response_error = error.as_response_error();
+ handle_error(span, response_error.status_code(), response_error);
+ }
+ };
+ }
+}
+
+fn handle_error(span: Span, status_code: StatusCode, response_error: &dyn ResponseError) {
+ // pre-formatting errors is a workaround for https://github.com/tokio-rs/tracing/issues/1565
+ let display = format!("{response_error}");
+ let debug = format!("{response_error:?}");
+ span.record("exception.message", tracing::field::display(display));
+ span.record("exception.details", tracing::field::display(debug));
+ let code: i32 = status_code.as_u16().into();
+
+ span.record("http.status_code", code);
+
+ if status_code.is_client_error() {
+ span.record("otel.status_code", "OK");
+ } else {
+ span.record("otel.status_code", "ERROR");
+ }
+}
diff --git a/crates/subscriptions/src/state.rs b/crates/subscriptions/src/state.rs
index 0bfe80857d..9d2a74f8ba 100644
--- a/crates/subscriptions/src/state.rs
+++ b/crates/subscriptions/src/state.rs
@@ -5,7 +5,7 @@ use hyperswitch_domain_models::{
subscription as subscription_domain,
};
use hyperswitch_interfaces::configs;
-use router_env::tracing_actix_web::RequestId;
+use router_env::RequestId;
use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore};
#[async_trait::async_trait]
@@ -84,7 +84,7 @@ impl hyperswitch_interfaces::api_client::ApiClientWrapper for SubscriptionState
fn get_request_id_str(&self) -> Option<String> {
self.api_client
.get_request_id()
- .map(|req_id| req_id.as_hyphenated().to_string())
+ .map(|req_id| req_id.to_string())
}
fn get_tenant(&self) -> configs::Tenant {
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 18d5376da8..6438112eee 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -876,6 +876,10 @@ max_retry_count_for_thirty_day = 20
max_retries_per_day = 20
max_retry_count_for_thirty_day = 20
+[trace_header]
+header_name = "x-request-id"
+id_reuse_strategy = "ignore_incoming" # Options: "ignore_incoming" (default) or "use_incoming"
+
# Authentication to communicate between internal services using common_api_key, merchant id and profile id
[internal_merchant_id_profile_id_auth]
enabled = false # Enable or disable internal api key, merchant id and profile id based authentication