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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(deja): [1/5] optional dependency, feature flags, typed settings + feature-off purity proof (#13285)
Uzair Khan55d30a82a4a9
diff --git a/Cargo.lock b/Cargo.lockindex 5023ef0295..4fadc860b6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2188,6 +2188,7 @@ dependencies = ["blake3","bytes 1.10.1","common_enums",+ "deja","diesel","error-stack 0.4.1","fake",@@ -2853,6 +2854,63 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"+[[package]]+name = "deja"+version = "0.1.0"+source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+dependencies = [+ "deja-context",+ "deja-core",+ "deja-derive",+ "deja-runtime",+ "serde",+ "serde_json",+]++[[package]]+name = "deja-context"+version = "0.1.0"+source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+dependencies = [+ "pin-project-lite",+]++[[package]]+name = "deja-core"+version = "0.1.0"+source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+dependencies = [+ "serde",+ "serde_json",+ "thiserror 1.0.69",+]++[[package]]+name = "deja-derive"+version = "0.1.0"+source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.101",+]++[[package]]+name = "deja-runtime"+version = "0.1.0"+source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+dependencies = [+ "async-trait",+ "deja-context",+ "deja-core",+ "deja-derive",+ "serde",+ "serde_json",+ "tokio 1.48.0",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "der"version = "0.6.1"@@ -3038,6 +3096,7 @@ dependencies = ["common_enums","common_types","common_utils",+ "deja","diesel","error-stack 0.4.1","hyperswitch_masking",@@ -3478,8 +3537,10 @@ dependencies = ["aws-smithy-runtime-api","aws-smithy-types","base64 0.22.1",+ "bytes 1.10.1","common_enums","common_utils",+ "deja","dyn-clone","error-stack 0.4.1","hex",@@ -7885,12 +7946,14 @@ name = "redis_interface"version = "0.1.0"dependencies = ["common_utils",+ "deja","error-stack 0.4.1","fred","futures 0.3.31","redis","router_env","serde",+ "serde_json","thiserror 1.0.69","tokio 1.48.0","tokio-stream",@@ -8213,6 +8276,8 @@ dependencies = ["cookie 0.18.1","csv","currency_conversion",+ "deja",+ "deja-core","derive_deref","diesel","diesel_models",@@ -8318,8 +8383,11 @@ name = "router_env"version = "0.1.0"dependencies = ["actix-web",+ "bytes 1.10.1","cargo_metadata 0.18.1","config",+ "deja",+ "deja-core","error-stack 0.4.1","gethostname","opentelemetry",@@ -9654,6 +9722,7 @@ dependencies = ["common_utils","config","crc32fast",+ "deja","diesel","diesel_models","dyn-clone",diff --git a/config/config.example.toml b/config/config.example.tomlindex e606f92e12..90c4d880d4 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -104,6 +104,7 @@ redis_lock_timeout_in_seconds = 100 # Redis remains write locked for 100# Logging configuration. Logging can be either to file or console or both.+# Logging configuration for file logging[log.file]enabled = false # Toggle [true or false]@@ -147,6 +148,48 @@ use_xray_generator = false # Set this to true for AWSroute_to_trace = ["*/confirm"]bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread+# Deja recording/replay configuration. Disabled by default in checked-in examples.+[deja]+mode = "disabled" # allowed values: "disabled", "record", "replay"+run_id = "" # stable run identifier; empty lets the runtime choose a safe default++[deja.recording]+graph = "disabled" # allowed values: "disabled", "enabled" — execution-graph nodes on the recording stream++[deja.recording.kafka]+brokers = []+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+enabled = false+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000++# This section provides some secret values.[secrets]master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long.diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 2ecab191c0..8b4921926b 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -142,6 +142,7 @@ redis_temp_locker_encryption_key = "redis_temp_locker_encryption_key" # Encryptittl_for_storage_in_secs = 220752000 # Time to live for storage entries in locker+[log.console]enabled = truelevel = "DEBUG"@@ -164,6 +165,47 @@ use_xray_generator = false # Set this to true for AWSroute_to_trace = ["*/confirm"]bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread++[deja]+mode = "disabled"+run_id = ""++[deja.recording]+graph = "disabled"++[deja.recording.kafka]+brokers = []+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+enabled = false+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000+[lock_settings]delay_between_retries_in_milliseconds = 500 # Delay between retries in millisecondsredis_lock_expiry_seconds = 180 # Seconds before the redis lock expiresdiff --git a/config/development.toml b/config/development.tomlindex 9d4269ef2e..6636deded7 100644--- a/config/development.toml+++ b/config/development.toml@@ -1,5 +1,6 @@application_source = "main"+[log.file]enabled = false@@ -14,6 +15,47 @@ metrics_enabled = falseuse_xray_generator = falsebg_metrics_collection_interval_in_secs = 15+[deja]+mode = "disabled"+run_id = ""++[deja.recording]+graph = "disabled"++[deja.recording.kafka]+brokers = ["localhost:9092"]+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router-dev"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+enabled = false+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000++[key_manager]enabled = falseuse_legacy_key_store_decryption = falsediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 203d7a718d..80cf7f2812 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -8,6 +8,7 @@ port = 8080host = "0.0.0.0"request_body_limit = 16_384 # Post request body is limited to 16k.+[log.file]enabled = false # Whether you want to store log in log files.path = "logs" # Where to store log files.@@ -26,6 +27,47 @@ otel_exporter_otlp_endpoint = "https://otel-collector:4317" # Endpoint to send muse_xray_generator = false # Set this to true for AWS X-ray compatible tracesbg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread+[deja]+mode = "disabled"+run_id = ""++[deja.recording]+graph = "disabled"++[deja.recording.kafka]+brokers = ["kafka0:29092"]+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router-docker"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+enabled = false+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000++[master_database]username = "db_user"password = "db_pass"diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex ab31bd2fe4..98ca28653f 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -10,6 +10,13 @@# The seeding script ignores this field; it's only needed for runtime fallbackoverrides = []+[default-configs.deja_record]+value = true+schema = { type = "boolean" }+description = "Whether Deja request recording is enabled for matching request contexts (inert unless deja.sampler.enabled is set)"+change_reason = "Initial setup"++[dimensions.connector]position = 1schema = { type = "string" }diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rsindex 61941078f7..65575c7dc9 100644--- a/crates/api_models/src/admin.rs+++ b/crates/api_models/src/admin.rs@@ -2213,7 +2213,7 @@ pub struct MerchantConnectorDetailsWrap {#[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{"connector_account_details": {"auth_type": "HeaderKey",- "api_key":"sk_test_xxxxxexamplexxxxxx12345"+ "api_key":"<stripe_test_secret_key>"},"metadata": {"user_defined_field_1": "sample_1",diff --git a/crates/common_types/src/domain.rs b/crates/common_types/src/domain.rsindex bacb17db18..4960950478 100644--- a/crates/common_types/src/domain.rs+++ b/crates/common_types/src/domain.rs@@ -160,7 +160,7 @@ pub struct MerchantConnectorAuthDetails {#[schema(value_type = Object, example = r#"{"merchant_connector_creds": {"auth_type": "HeaderKey",- "api_key":"sk_test_xxxxxexamplexxxxxx12345"+ "api_key":"<stripe_test_secret_key>"},}"#)]pub merchant_connector_creds: common_utils::pii::SecretSerdeValue,diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.tomlindex 51a51dc47b..73de9f0f36 100644--- a/crates/common_utils/Cargo.toml+++ b/crates/common_utils/Cargo.toml@@ -22,6 +22,7 @@ v1 = []v2 = []crypto_openssl = ["dep:openssl"]tokenization_v2 = []+deja = ["dep:deja"][dependencies]async-trait = { version = "0.1.88", optional = true }@@ -30,6 +31,7 @@ base64-serde = "0.8.0"blake3 = { version = "1.8.2", features = ["serde"] }bytes = "1.10.1"diesel = "2.2.10"+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }error-stack = "0.4.1"futures = { version = "0.3.31", optional = true }globset = "0.4.16"diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.tomlindex 807c247e24..ff43dc73f0 100644--- a/crates/diesel_models/Cargo.toml+++ b/crates/diesel_models/Cargo.toml@@ -13,6 +13,7 @@ kv_store = []v1 = ["common_utils/v1", "common_types/v1"]v2 = ["common_utils/v2", "common_types/v2"]tokenization_v2 = []+deja = ["dep:deja"][dependencies]async-bb8-diesel = "0.2.1"@@ -32,6 +33,7 @@ common_types = { version = "0.1.0", path = "../common_types" }hyperswitch_masking = "0.0.1"router_derive = { version = "0.1.0", path = "../router_derive" }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }[lints]workspace = truediff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex e671caa36c..6073fcaf0f 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -20,6 +20,7 @@ superposition = []v1 = ["hyperswitch_interfaces/v1", "common_utils/v1"]v2 = ["hyperswitch_interfaces/v2", "common_utils/v2"]+deja = ["dep:bytes", "dep:deja"]revenue_recovery = ["dep:prost","dep:router_env",@@ -55,6 +56,7 @@ aws-smithy-runtime-api = { version = "1.7", features = ["client"] }aws-smithy-types = "1.3.1"base64 = "0.22.1"dyn-clone = "1.0.19"+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }error-stack = "0.4.1"hex = "0.4.3"hyper = "0.14.32"@@ -84,6 +86,7 @@ quick-xml = { version = "0.31.0", features = ["serialize"] }unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.07.10.1", package = "rust-grpc-client" }open-feature = { version = "0.2.5", optional = true }+bytes = { version = "1.10.1", optional = true }superposition_provider = { version = "0.114.0", optional = true}superposition_types = "0.114.0"superposition_sdk = { version = "0.114.0", optional = true }diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rsindex 94f58f44af..c9ee6127f0 100644--- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs@@ -510,7 +510,7 @@ pub enum StripebillingChargeStatus {#[cfg(all(feature = "v2", feature = "revenue_recovery"))]// This is the default hard coded mca Id to find the stripe account associated with the stripe biliing// Context : Since we dont have the concept of connector_reference_id in stripebilling because payments always go through stripe.-// While creating stripebilling we will hard code the stripe account id to string "stripebilling" in mca featrue metadata. So we have to pass the same as account_reference_id here in response.+// While creating stripebilling we will hard code the stripe account id to string "stripebilling" in mca feature metadata. So we have to pass the same as account_reference_id here in response.const MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA: &str = "stripebilling";#[cfg(all(feature = "v2", feature = "revenue_recovery"))]diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.tomlindex 5a117b3e09..22ded2e4b2 100644--- a/crates/hyperswitch_domain_models/Cargo.toml+++ b/crates/hyperswitch_domain_models/Cargo.toml@@ -18,6 +18,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1", "common_types/v1",tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2"]dummy_connector = []revenue_recovery= []+deja = ["diesel_models/deja"][dependencies]# First party depsdiff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.tomlindex 6e10f23134..81aae32952 100644--- a/crates/redis_interface/Cargo.toml+++ b/crates/redis_interface/Cargo.toml@@ -12,12 +12,14 @@ default = ["redis-rs"]fred = ["dep:fred"]redis-rs = ["dep:redis"]multitenancy_fallback = []+deja = ["common_utils/deja", "dep:deja", "dep:serde_json"]metrics = ["dep:router_env"][dependencies]error-stack = "0.4.1"futures = "0.3"serde = { version = "1.0.219", features = ["derive"] }+serde_json = { version = "1.0.140", optional = true }thiserror = "1.0.69"tokio = "1.48.0"tokio-stream = { version = "0.1.17", features = ["sync"] }@@ -33,6 +35,7 @@ fred = { version = "8.0.6", optional = true, features = [# First party cratescommon_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }router_env = { version = "0.1.0", path = "../router_env", optional = true }[dev-dependencies]diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 126b051574..02c7d3e882 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -36,6 +36,7 @@ v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domaindynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"]revenue_recovery = ["api_models/revenue_recovery", "hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery", "hyperswitch_connectors/revenue_recovery", "external_services/revenue_recovery", "dep:prost-types"]tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"]+deja = ["dep:deja", "dep:deja-core", "v1", "common_utils/deja", "router_env/deja", "external_services/deja", "diesel_models/deja", "redis_interface/deja", "hyperswitch_domain_models/deja", "storage_impl/deja"]# Partial Auth# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.# This is named as partial-auth because the router will still try to authenticate if the `x-merchant-id` header is not present.@@ -125,6 +126,8 @@ cards = { version = "0.1.0", path = "../cards" }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager"] }common_types = { version = "0.1.0", path = "../common_types" }+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true }currency_conversion = { version = "0.1.0", path = "../currency_conversion" }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store", "tokenization_v2"], default-features = false }euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] }diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex deca61bbf6..883db6efac 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -566,6 +566,8 @@ pub(crate) async fn fetch_raw_secrets(master_database,redis: conf.redis,log: conf.log,+ #[cfg(feature = "deja")]+ deja: conf.deja,#[cfg(feature = "kv_store")]drainer: conf.drainer,encryption_management: conf.encryption_management,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex aee9aed800..e9988ca08f 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -89,6 +89,9 @@ pub struct Settings<S: SecretState> {pub replica_database: SecretStateContainer<Database, S>,pub redis: RedisSettings,pub log: Log,+ #[cfg(feature = "deja")]+ #[serde(default)]+ pub deja: DejaSettings,pub secrets: SecretStateContainer<Secrets, S>,pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>,pub locker: Locker,@@ -197,6 +200,187 @@ pub struct Settings<S: SecretState> {pub save_payment_method_on_session: OnSessionConfig,}+#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Default)]+#[serde(rename_all = "snake_case")]+pub enum DejaMode {+ #[default]+ Disabled,+ Record,+ Replay,+}++#[cfg(feature = "deja")]+impl DejaMode {+ pub fn is_disabled(&self) -> bool {+ matches!(self, Self::Disabled)+ }++ pub fn is_record(&self) -> bool {+ matches!(self, Self::Record)+ }++ pub fn is_replay(&self) -> bool {+ matches!(self, Self::Replay)+ }+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone, Default)]+#[serde(default)]+pub struct DejaSettings {+ pub mode: DejaMode,+ pub run_id: Option<String>,+ pub recording: DejaRecordingSettings,+ pub replay: DejaReplaySettings,+ pub sampler: DejaSamplerSettings,+ pub identity: DejaIdentitySettings,+ pub writer: DejaWriterSettings,+}++#[cfg(feature = "deja")]+impl DejaSettings {+ pub fn effective_run_id(&self) -> Option<&str> {+ self.run_id.as_deref().filter(|run_id| !run_id.is_empty())+ }+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone, Default)]+#[serde(default)]+pub struct DejaRecordingSettings {+ pub graph: DejaGraphMode,+ pub kafka: DejaRecordingKafkaSettings,+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq, Default)]+#[serde(rename_all = "snake_case")]+pub enum DejaGraphMode {+ #[default]+ Disabled,+ Enabled,+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone)]+#[serde(default)]+pub struct DejaRecordingKafkaSettings {+ pub topic: Option<String>,+ pub brokers: Vec<String>,+ pub client_id: Option<String>,+ pub acks: String,+ pub idempotence: bool,+ pub compression: Option<String>,+ pub linger: Option<u64>,+ pub message_timeout: Option<u64>,+ /// rdkafka producer send-buffer depth — the loss-budget knob. A full buffer+ /// surfaces as enqueue errors the writer accounts as dropped (never memory+ /// growth); tune per environment. Default matches the former hardcoded cap.+ pub queue_buffering_max_messages: usize,+}++#[cfg(feature = "deja")]+impl DejaRecordingKafkaSettings {+ pub fn effective_topic(&self) -> Option<&str> {+ self.topic.as_deref().filter(|topic| !topic.is_empty())+ }+}++#[cfg(feature = "deja")]+impl Default for DejaRecordingKafkaSettings {+ fn default() -> Self {+ Self {+ topic: None,+ brokers: Vec::new(),+ client_id: None,+ acks: "all".to_owned(),+ idempotence: true,+ compression: None,+ linger: None,+ message_timeout: Some(30_000),+ queue_buffering_max_messages: 100_000,+ }+ }+}++#[cfg(feature = "deja")]+#[derive(Debug, Default, Deserialize, Clone)]+#[serde(default)]+pub struct DejaReplaySettings {+ pub source: Option<String>,+ pub lookup_dir: Option<PathBuf>,+ pub observed_sink: Option<String>,+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone)]+#[serde(default)]+pub struct DejaSamplerSettings {+ pub enabled: bool,+ pub record_key: Option<String>,+ pub timeout_ms: u64,+ pub fail_closed: bool,+}++#[cfg(feature = "deja")]+impl Default for DejaSamplerSettings {+ fn default() -> Self {+ Self {+ enabled: false,+ record_key: None,+ timeout_ms: 25,+ fail_closed: true,+ }+ }+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone)]+#[serde(default)]+pub struct DejaIdentitySettings {+ pub pod_name_env: String,+ pub git_sha_env: String,+ pub instance_id: Option<String>,+ pub code_sha: Option<String>,+}++#[cfg(feature = "deja")]+impl Default for DejaIdentitySettings {+ fn default() -> Self {+ Self {+ pod_name_env: "POD_NAME".to_owned(),+ git_sha_env: "VERGEN_GIT_SHA".to_owned(),+ instance_id: None,+ code_sha: None,+ }+ }+}++#[cfg(feature = "deja")]+#[derive(Debug, Deserialize, Clone)]+#[serde(default)]+pub struct DejaWriterSettings {+ pub queue_capacity: usize,+ pub batch_size: usize,+ pub flush_after_records: usize,+ pub flush_interval_ms: u64,+ pub shutdown_flush_ms: u64,+}++#[cfg(feature = "deja")]+impl Default for DejaWriterSettings {+ fn default() -> Self {+ Self {+ queue_capacity: 8_192,+ batch_size: 500,+ flush_after_records: 500,+ flush_interval_ms: 1_000,+ shutdown_flush_ms: 5_000,+ }+ }+}+#[derive(Debug, Deserialize, Clone, Default)]pub struct OnSessionConfig {#[serde(default, deserialize_with = "deserialize_hashmap")]@@ -1171,19 +1355,22 @@ impl Settings<SecuredSecret> {config.add_source(File::from(required_fields_config_file).required(false))};- let config = config- .add_source(- Environment::with_prefix("ROUTER")- .try_parsing(true)- .separator("__")- .list_separator(",")- .with_list_parse_key("log.telemetry.route_to_trace")- .with_list_parse_key("redis.cluster_urls")- .with_list_parse_key("events.kafka.brokers")- .with_list_parse_key("connectors.supported.wallets")- .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"),+ let environment_source = Environment::with_prefix("ROUTER")+ .try_parsing(true)+ .separator("__")+ .list_separator(",")+ .with_list_parse_key("log.telemetry.route_to_trace")+ .with_list_parse_key("redis.cluster_urls")+ .with_list_parse_key("events.kafka.brokers")+ .with_list_parse_key("connectors.supported.wallets")+ .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id");- )+ #[cfg(feature = "deja")]+ let environment_source =+ environment_source.with_list_parse_key("deja.recording.kafka.brokers");++ let config = config+ .add_source(environment_source).build().change_context(ApplicationError::ConfigurationError)?;diff --git a/crates/router/tests/feature_off_config_purity.rs b/crates/router/tests/feature_off_config_purity.rsnew file mode 100644index 0000000000..08bec3684e--- /dev/null+++ b/crates/router/tests/feature_off_config_purity.rs@@ -0,0 +1,253 @@+#![cfg(not(feature = "deja"))]+// Integration test: assertions use panic!/expect(); allow the production-code+// lints the v2 clippy profile denies.+#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]++use std::{+ fs,+ io::ErrorKind,+ path::{Path, PathBuf},+ sync::atomic::{AtomicU64, Ordering},+ time::{SystemTime, UNIX_EPOCH},+};++use router::configs::settings::Settings;++static NEXT_TEMP_ID: AtomicU64 = AtomicU64::new(0);++fn table_header_name(trimmed: &str) -> Option<&str> {+ let table = trimmed.strip_prefix('[')?.strip_suffix(']')?.trim();+ Some(+ table+ .strip_prefix('[')+ .and_then(|inner| inner.strip_suffix(']'))+ .unwrap_or(table)+ .trim(),+ )+}++fn strip_deja_tables(input: &str) -> String {+ let mut output = String::new();+ let mut in_deja_section = false;++ for line in input.lines() {+ if let Some(table) = table_header_name(line.trim()) {+ in_deja_section = table == "deja" || table.starts_with("deja.");+ }+ if in_deja_section {+ continue;+ }+ output.push_str(line);+ output.push('\n');+ }++ output+}++const INJECTED_DEJA_TABLES: &str = r#"+[deja]+mode = "record"+run_id = "feature-off-ignored"++[deja.recording]+graph = "disabled"++[deja.recording.kafka]+brokers = ["ignored:9092"]+topic = "ignored"+client_id = "ignored"++[deja.replay]+source = "ignored"+lookup_dir = "ignored"+observed_sink = "ignored"++[deja.sampler]+enabled = true+record_key = "ignored"+timeout_ms = 1+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = "ignored"+code_sha = "ignored"++[deja.writer]+queue_capacity = 1+batch_size = 1+flush_after_records = 1+flush_interval_ms = 1+shutdown_flush_ms = 1+"#;++fn is_debug_block_close(trimmed: &str) -> bool {+ trimmed.starts_with('}') || trimmed.starts_with(']') || trimmed.starts_with(')')+}++fn canonicalize_debug_block(lines: &[&str], index: &mut usize, sort_entries: bool) -> Vec<String> {+ let mut output = Vec::new();+ let mut entries = Vec::<Vec<String>>::new();++ while let Some(line) = lines.get(*index) {+ let line = (*line).to_owned();+ let trimmed = line.trim();+ let is_block_close = is_debug_block_close(trimmed);+ let opens_child_block =+ trimmed.ends_with('{') || trimmed.ends_with('[') || trimmed.ends_with('(');+ // Sort the entries of any `{ ... }` block (maps/sets are unordered, and+ // sorting a struct's fields is harmless because it is applied to both+ // sides). Newtype `( ... )` and array `[ ... ]` blocks preserve order.+ // This makes the comparison independent of HashMap iteration order,+ // which otherwise leaks through fields like `supported_payment_methods`.+ let child_sorts_map_entries = trimmed.ends_with('{');+ *index += 1;++ if is_block_close {+ if sort_entries {+ entries.sort();+ output.extend(entries.into_iter().flatten());+ }+ output.push(line);+ return output;+ }++ let chunk = if opens_child_block {+ let mut chunk = vec![line];+ chunk.extend(canonicalize_debug_block(+ lines,+ index,+ child_sorts_map_entries,+ ));+ chunk+ } else {+ vec![line]+ };++ if sort_entries {+ entries.push(chunk);+ } else {+ output.extend(chunk);+ }+ }++ if sort_entries {+ entries.sort();+ output.extend(entries.into_iter().flatten());+ }+ output+}++fn canonicalize_settings_debug(debug: &str) -> String {+ let lines = debug.lines().collect::<Vec<_>>();+ let mut index = 0;+ canonicalize_debug_block(&lines, &mut index, false).join("\n")+}++fn settings_debug(path: PathBuf) -> String {+ fs::read_to_string(&path)+ .unwrap_or_else(|err| panic!("required config file {path:?} must be readable: {err}"));++ std::env::set_var("RUN_ENV", "development");+ for key in [+ "ROUTER__DEJA__MODE",+ "ROUTER__DEJA__RUN_ID",+ "ROUTER__DEJA__RECORDING__KAFKA__BROKERS",+ "ROUTER__DEJA__RECORDING__KAFKA__TOPIC",+ "ROUTER__DEJA__REPLAY__SOURCE",+ "ROUTER__DEJA__REPLAY__LOOKUP_DIR",+ "ROUTER__DEJA__REPLAY__OBSERVED_SINK",+ "ROUTER__DEJA__SAMPLER__ENABLED",+ "ROUTER__DEJA__WRITER__QUEUE_CAPACITY",+ ] {+ std::env::remove_var(key);+ }+ let settings = Settings::with_config_path(Some(path)).expect("settings deserialize");+ canonicalize_settings_debug(&format!("{settings:#?}"))+}++fn with_injected_deja_tables(base: &str) -> String {+ let mut output = base.to_owned();+ if !output.ends_with('\n') {+ output.push('\n');+ }+ output.push_str(INJECTED_DEJA_TABLES);+ output+}++struct CleanupDir {+ path: PathBuf,+}++impl CleanupDir {+ fn new() -> Self {+ let unique_nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("system clock before unix epoch")+ .as_nanos();++ for _ in 0..100 {+ let unique = NEXT_TEMP_ID.fetch_add(1, Ordering::Relaxed);+ let path = std::env::temp_dir().join(format!(+ "feature_off_config_purity-{}-{unique_nanos}-{unique}",+ std::process::id()+ ));+ match fs::create_dir(&path) {+ Ok(()) => return Self { path },+ Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,+ Err(err) => panic!("create temp config dir {path:?}: {err}"),+ }+ }++ panic!("create unique temp config dir after 100 attempts");+ }++ fn path(&self) -> &Path {+ &self.path+ }+}++impl Drop for CleanupDir {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.path);+ }+}++#[test]+fn feature_off_config_bytes_ignore_deja_surfaces() {+ let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(|path| path.parent())+ .expect("repo root")+ .to_path_buf();+ let real_parseable_configs = ["config/development.toml", "config/docker_compose.toml"];+ let temp = CleanupDir::new();++ for rel in real_parseable_configs {+ let original = fs::read_to_string(repo.join(rel)).expect("read config");+ let without_deja = strip_deja_tables(&original);+ let with_deja = with_injected_deja_tables(&without_deja);+ let without_path = temp.path().join(rel.replace('/', "__") + "__without_deja");+ let with_path = temp.path().join(rel.replace('/', "__") + "__with_deja");+ fs::write(&without_path, without_deja).expect("write config without deja");+ fs::write(&with_path, with_deja).expect("write config with injected deja");++ assert_eq!(+ settings_debug(with_path),+ settings_debug(without_path),+ "feature-off Settings shape changed after injecting only [deja] tables into {rel}"+ );+ }++ let synthetic_without = temp.path().join("synthetic_minimal_without_deja.toml");+ let synthetic_with = temp.path().join("synthetic_minimal_with_deja.toml");+ fs::write(&synthetic_without, "\n").expect("write synthetic config without deja");+ fs::write(&synthetic_with, with_injected_deja_tables("\n"))+ .expect("write synthetic config with injected deja");+ assert_eq!(+ settings_debug(synthetic_with),+ settings_debug(synthetic_without),+ "feature-off Settings shape changed after injecting [deja] tables into a synthetic minimal config"+ );+}diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.tomlindex 0b0b64fe63..7f6451838c 100644--- a/crates/router_env/Cargo.toml+++ b/crates/router_env/Cargo.toml@@ -10,6 +10,8 @@ license.workspace = true[dependencies]cargo_metadata = "0.18.1"config = { version = "0.14.1", features = ["toml"] }+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true }error-stack = "0.4.1"gethostname = "0.4.3"opentelemetry = { version = "0.27.1", default-features = false, features = ["internal-logs", "metrics", "trace"] }@@ -18,6 +20,7 @@ opentelemetry-otlp = { version = "0.27.0", default-features = false, features =opentelemetry_sdk = { version = "0.27.1", default-features = false, features = ["rt-tokio-current-thread", "metrics", "trace"] }rustc-hash = "1.1"serde = { version = "1.0.219", features = ["derive"] }+bytes = { version = "1.10.1", optional = true }serde_json = "1.0.140"serde_path_to_error = "0.1.17"strum = { version = "0.26.3", features = ["derive"] }@@ -46,6 +49,7 @@ actix_web = ["dep:actix-web", "tracing-actix-web", "dep:uuid"]log_custom_entries_to_extra = []log_extra_implicit_fields = []log_active_span_json = []+deja = ["dep:bytes", "dep:deja", "dep:deja-core"]payouts = [][lints]diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.tomlindex 02c35b3cf6..a9711a6675 100644--- a/crates/storage_impl/Cargo.toml+++ b/crates/storage_impl/Cargo.toml@@ -9,6 +9,9 @@ license.workspace = true[features]default = ["olap", "oltp", "accounts_cache", "redis-rs"]+# Deja replay (R1): feature-gate the replay DB routing hook so default/prod builds+# are byte-for-byte unaffected.+deja = ["dep:deja", "diesel_models/deja"]dynamic_routing = []oltp = []accounts_cache = []@@ -26,6 +29,7 @@ api_models = { version = "0.1.0", path = "../api_models" }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils" }common_types = { version = "0.1.0", path = "../common_types" }+deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }diesel_models = { version = "0.1.0", path = "../diesel_models", default-features = false }hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }hyperswitch_masking = "0.0.1"diff --git a/justfile b/justfileindex b378f05640..00ada46573 100644--- a/justfile+++ b/justfile@@ -44,7 +44,7 @@ clippy_v2 redis_interface_backend="redis-rs" *FLAGS:jq -r '[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates- | del( .[] | select( . == ("default", "v1", "fred", "redis-rs") ) ) # Exclude default, v1, and both backend flags+ | del( .[] | select( . == ("default", "v1", "deja", "fred", "redis-rs") ) ) # Exclude default, v1, deja (v1-only feature), and both backend flags| join(",") # Construct a comma-separated string of features for passing to `cargo`')"FEATURES="${FEATURES},{{ redis_interface_backend }}"@@ -62,7 +62,7 @@ check_v2 redis_interface_backend="redis-rs" *FLAGS:jq -r '[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates- | del( .[] | select( . == ("default", "v1", "fred", "redis-rs") ) ) # Exclude default, v1, and both backend flags+ | del( .[] | select( . == ("default", "v1", "deja", "fred", "redis-rs") ) ) # Exclude default, v1, deja (v1-only feature), and both backend flags| join(",") # Construct a comma-separated string of features for passing to `cargo`')"FEATURES="${FEATURES},{{ redis_interface_backend }}"