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(superposition): Enforce Superposition service availability at startup (#11404)

chikke srujan20775cc07214
diff --git a/Cargo.lock b/Cargo.lock
index 30125c38e2..cdd1853f4e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1816,19 +1816,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "cargo_metadata"
-version = "0.14.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa"
-dependencies = [
- "camino",
- "cargo-platform",
- "semver 1.0.26",
- "serde",
- "serde_json",
-]
-
[[package]]
name = "cargo_metadata"
version = "0.18.1"
@@ -2725,19 +2712,6 @@ dependencies = [
"syn 2.0.101",
]
-[[package]]
-name = "dashmap"
-version = "5.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
-dependencies = [
- "cfg-if 1.0.0",
- "hashbrown 0.14.5",
- "lock_api 0.4.12",
- "once_cell",
- "parking_lot_core 0.9.10",
-]
-
[[package]]
name = "data-encoding"
version = "2.6.0"
@@ -3240,15 +3214,6 @@ dependencies = [
"windows-sys 0.59.0",
]
-[[package]]
-name = "error-chain"
-version = "0.12.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc"
-dependencies = [
- "version_check 0.9.5",
-]
-
[[package]]
name = "error-stack"
version = "0.4.1"
@@ -3377,6 +3342,7 @@ dependencies = [
"aws-sdk-sesv2",
"aws-sdk-sts",
"aws-smithy-runtime",
+ "aws-smithy-types",
"base64 0.22.1",
"common_enums",
"common_utils",
@@ -3637,6 +3603,15 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+[[package]]
+name = "fsevent-sys"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "fuchsia-cprng"
version = "0.1.1"
@@ -4918,6 +4893,26 @@ dependencies = [
"url 2.5.4",
]
+[[package]]
+name = "inotify"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199"
+dependencies = [
+ "bitflags 2.9.0",
+ "inotify-sys",
+ "libc",
+]
+
+[[package]]
+name = "inotify-sys"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "into-attr"
version = "0.1.1"
@@ -5212,6 +5207,26 @@ dependencies = [
"syn 2.0.101",
]
+[[package]]
+name = "kqueue"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"
+dependencies = [
+ "kqueue-sys",
+ "libc",
+]
+
+[[package]]
+name = "kqueue-sys"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"
+dependencies = [
+ "bitflags 1.3.2",
+ "libc",
+]
+
[[package]]
name = "language-tags"
version = "0.2.2"
@@ -5614,21 +5629,6 @@ dependencies = [
"unicase 2.7.0",
]
-[[package]]
-name = "mini-moka"
-version = "0.10.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c325dfab65f261f386debee8b0969da215b3fa0037e74c8a1234db7ba986d803"
-dependencies = [
- "crossbeam-channel",
- "crossbeam-utils 0.8.21",
- "dashmap",
- "skeptic",
- "smallvec 1.15.0",
- "tagptr",
- "triomphe",
-]
-
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -5900,6 +5900,33 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "notify"
+version = "8.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
+dependencies = [
+ "bitflags 2.9.0",
+ "fsevent-sys",
+ "inotify",
+ "kqueue",
+ "libc",
+ "log 0.4.27",
+ "mio 1.0.3",
+ "notify-types",
+ "walkdir",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "notify-types"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
+dependencies = [
+ "bitflags 2.9.0",
+]
+
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
@@ -7107,7 +7134,7 @@ dependencies = [
"prettyplease",
"prost 0.14.3",
"prost-types 0.14.3",
- "pulldown-cmark 0.13.3",
+ "pulldown-cmark",
"pulldown-cmark-to-cmark",
"regex",
"syn 2.0.101",
@@ -7187,17 +7214,6 @@ dependencies = [
"syn 1.0.109",
]
-[[package]]
-name = "pulldown-cmark"
-version = "0.9.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b"
-dependencies = [
- "bitflags 2.9.0",
- "memchr",
- "unicase 2.7.0",
-]
-
[[package]]
name = "pulldown-cmark"
version = "0.13.3"
@@ -7215,7 +7231,7 @@ version = "22.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50793def1b900256624a709439404384204a5dc3a6ec580281bfaac35e882e90"
dependencies = [
- "pulldown-cmark 0.13.3",
+ "pulldown-cmark",
]
[[package]]
@@ -8987,21 +9003,6 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
-[[package]]
-name = "skeptic"
-version = "0.13.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "16d23b015676c90a0f01c197bfdc786c20342c73a0afdda9025adb0bc42940a8"
-dependencies = [
- "bytecount",
- "cargo_metadata 0.14.2",
- "error-chain",
- "glob",
- "pulldown-cmark 0.9.6",
- "tempfile",
- "walkdir",
-]
-
[[package]]
name = "slab"
version = "0.4.9"
@@ -9516,59 +9517,48 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "superposition_core"
-version = "0.99.1"
+version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ce785d9bcadebf9cccdbf1962513daaf2522df0e83d70f5a2bb746f12904125"
+checksum = "c8408c05eaa6d5e4ab17769e8a008b7b6908d4cf12995649bad45bd9e4ccac66"
dependencies = [
- "actix-web",
- "anyhow",
"bigdecimal 0.3.1",
"blake3",
"cbindgen",
- "cfg-if 1.0.0",
- "chrono",
- "derive_more 0.99.19",
"itertools 0.10.5",
"jsonschema",
"log 0.4.27",
- "mini-moka",
"num-bigint",
- "once_cell",
- "percent-encoding 2.3.1",
- "rand 0.9.2",
- "reqwest 0.11.27",
"serde",
"serde_json",
- "strum 0.25.0",
- "strum_macros 0.25.3",
"superposition_types",
"thiserror 1.0.69",
- "tokio 1.48.0",
"toml 0.8.22",
"uniffi",
]
[[package]]
name = "superposition_derives"
-version = "0.99.1"
+version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b7babb30f4056937c5be0d93c67694c01a180e5ad4fa60519ffbe06182d96596"
+checksum = "15ce4c755b62951f53d8ba1f686dfebe0a0fb22ea2e1abf437028b14130aabdb"
dependencies = [
- "proc-macro2",
+ "proc-macro-crate 3.2.0",
"quote",
"syn 2.0.101",
]
[[package]]
name = "superposition_provider"
-version = "0.99.1"
+version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "16120fe041ac9457f27caebb78aee364a454ef74802e91415ea91801b3eb4efd"
+checksum = "e0bc4b0c15a02a10d89deb0d4bc9e382193c9d745ac3057feac89f5503f6096b"
dependencies = [
"async-trait",
"aws-smithy-types",
"chrono",
+ "derive_more 0.99.19",
"log 0.4.27",
+ "notify",
"open-feature",
"reqwest 0.11.27",
"serde",
@@ -9584,9 +9574,9 @@ dependencies = [
[[package]]
name = "superposition_sdk"
-version = "0.99.1"
+version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dda16fe320a6a04943eb5ecc9f5477ec64d6ff556ec4802a6c18c6b7de9dce5d"
+checksum = "d53945cde9e454e8bdfe3560646c63556a25ec1242f28215a6fe709269de0126"
dependencies = [
"aws-smithy-async",
"aws-smithy-http 0.62.1",
@@ -9602,9 +9592,9 @@ dependencies = [
[[package]]
name = "superposition_types"
-version = "0.99.1"
+version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4bdc5d336f7ce4a9d78ab431b333bfc5ec49b5bbd9c82719b5c22db2c672c4ab"
+checksum = "0751b1d31773b2dc67adaa208a270b5a5189b435f69f63f32f528878f8c33c72"
dependencies = [
"bigdecimal 0.3.1",
"chrono",
diff --git a/config/config.example.toml b/config/config.example.toml
index 5a9e552877..fc4b3ea206 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1403,13 +1403,14 @@ internal_api_key = "test_internal_api_key" # API key for internal merchant id an
payments_base_url = "http://localhost:8080"
[superposition]
-enabled = false # Enable or disable Superposition integration (default: false)
+enabled = true # Enable or disable Superposition integration (default: false)
endpoint = "http://superposition:8080" # Superposition service endpoint URL
token = "your_superposition_token" # Superposition token
org_id = "your_org_id" # Organization ID in Superposition
workspace_id = "your_workspace_id" # Workspace ID in Superposition
polling_interval = 15 # Polling interval in seconds for configuration updates
request_timeout = 60 # Request timeout in seconds for Superposition API calls (optional, default: none)
+backup_file_path = "./config/superposition_seed.toml" # Path to a local file for fallback configuration. Used when the Superposition HTTP service is unavailable. If set, the client will fall back to reading configuration from this file instead of failing completely. This ensures graceful degradation during network outages or service disruptions.
[micro_services]
# Base URLs for modular microservices
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 4bd60d8a09..c0f6c9f217 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -451,13 +451,14 @@ proxy_connector_http_status_code = false # If enabled, the http status code o
payments_base_url = "http://localhost:8080"
[superposition]
-enabled = false # Enable or disable Superposition integration (default: false)
+enabled = true # Enable or disable Superposition integration (default: false)
endpoint = "http://superposition:8080" # Superposition service endpoint URL
token = "your_superposition_token" # Superposition token
org_id = "your_org_id" # Organization ID in Superposition
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)
+backup_file_path = "./config/superposition_seed.toml" # Path to a local file for fallback configuration. Used when the Superposition HTTP service is unavailable. If set, the client will fall back to reading configuration from this file instead of failing completely. This ensures graceful degradation during network outages or service disruptions.
[trace_header]
header_name = "x-request-id" # HTTP header name for request tracing
diff --git a/config/development.toml b/config/development.toml
index 1ecb9f6215..c2f039a21e 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1523,13 +1523,14 @@ internal_api_key = "test_internal_api_key"
payments_base_url = "http://localhost:8080"
[superposition]
-enabled = false # Enable Superposition integration
+enabled = true # Enable Superposition integration
endpoint = "http://localhost:8081" # Superposition service endpoint
token = "123456" # Superposition token
org_id = "localorg" # Organization ID in Superposition
workspace_id = "dev" # 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)
+backup_file_path = "./config/superposition_seed.toml" # Path to a local file for fallback configuration. Used when the Superposition HTTP service is unavailable. If set, the client will fall back to reading configuration from this file instead of failing completely. This ensures graceful degradation during network outages or service disruptions.
# Merchant Advice Code Configuration
[merchant_advice_codes.visa]
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index f3f812d8cc..def81f620f 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -1402,13 +1402,14 @@ internal_api_key = "test_internal_api_key" # API key for internal merchant id an
payments_base_url = "http://localhost:8080"
[superposition]
-enabled = false # Enable Superposition for dynamic configuration management
+enabled = true # Enable Superposition for dynamic configuration management
endpoint = "http://superposition:8080" # Superposition service endpoint
token = "123456" # Superposition token
org_id = "localorg" # Organization ID in Superposition
workspace_id = "dev" # 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)
+backup_file_path = "./config/superposition_seed.toml" # Path to a local file for fallback configuration. Used when the Superposition HTTP service is unavailable. If set, the client will fall back to reading configuration from this file instead of failing completely. This ensures graceful degradation during network outages or service disruptions.
# Merchant Advice Code Configuration
[merchant_advice_codes.visa]
diff --git a/config/superposition_seed.toml b/config/superposition_seed.toml
new file mode 100644
index 0000000000..2b4ecbca42
--- /dev/null
+++ b/config/superposition_seed.toml
@@ -0,0 +1,63 @@
+# Superposition Seed Configuration for Hyperswitch
+# This file serves dual purpose:
+# 1. Seeding via scripts/seed_superposition.sh (posts to Superposition API)
+# 2. Runtime fallback for FileDataSource via backup_file_path config
+#
+# Extra fields (description, change_reason) are used only by the seeding script
+# and are silently ignored by the FileDataSource parser.
+
+# Empty overrides table - required for FileDataSource backup parsing
+# The seeding script ignores this field; it's only needed for runtime fallback
+overrides = []
+
+[dimensions.organization_id]
+position = 1
+schema = { type = "string" }
+description = "Organization identifier"
+change_reason = "Initial setup"
+
+[dimensions.merchant_id]
+position = 2
+schema = { type = "string" }
+description = "Merchant identifier"
+change_reason = "Initial setup"
+
+[dimensions.profile_id]
+position = 3
+schema = { type = "string" }
+description = "Business profile identifier"
+change_reason = "Initial setup"
+
+[dimensions.connector]
+position = 4
+schema = { type = "string" }
+description = "Payment connector identifier (e.g. stripe, adyen)"
+change_reason = "Initial setup"
+
+[default-configs.requires_cvv]
+value = true
+schema = { type = "boolean" }
+description = "Whether CVV is required for payments"
+change_reason = "Initial setup"
+
+[default-configs.implicit_customer_update]
+value = false
+schema = { type = "boolean" }
+description = "Whether to implicitly update customer details on payment"
+change_reason = "Initial setup"
+
+[default-configs.payout_tracker_mapping]
+schema = { type = "object" }
+description = "Payout sync retry mapping configuration per connector"
+change_reason = "Initial setup"
+
+[default-configs.payout_tracker_mapping.value]
+start_after = 60
+frequencies = [[300, 5]]
+
+[default-configs.client_session_validation_enabled]
+value = true
+schema = { type = "boolean" }
+description = "Whether client session validation is enabled for payments"
+change_reason = "Initial setup"
+
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 2c2e15374f..4227d1a8e5 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -38,7 +38,7 @@ url = { version = "2.5.4", features = ["serde"] }
utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order"] }
nutype = { version = "0.4.3", features = ["serde"] }
deserialize_form_style_query_parameter = "0.2.2"
-superposition_types = "0.99.1"
+superposition_types = "0.102.0"
# First party crates
cards = { version = "0.1.0", path = "../cards" }
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 2efe2eaa8f..fcc3c0ac23 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -44,6 +44,7 @@ aws-sdk-sesv2 = "1.57.0"
aws-sdk-sts = "1.51.0"
aws-sdk-s3 = { version = "1.65.0", optional = true }
aws-smithy-runtime = "1.8.3"
+aws-smithy-types = "1.3.1"
base64 = "0.22.1"
dyn-clone = "1.0.19"
error-stack = "0.4.1"
@@ -74,8 +75,8 @@ url = { version = "2.5.4", features = ["serde"] }
quick-xml = { version = "0.31.0", features = ["serialize"] }
unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "e479d36ac5ead316a6ed6b468260987ac6ec5401", package = "rust-grpc-client" }
open-feature = { version = "0.2.5", optional = true }
-superposition_provider = { version = "0.99.1", optional = true}
-superposition_types = "0.99.1"
+superposition_provider = { version = "0.102.0", optional = true}
+superposition_types = "0.102.0"
# First party crates
diff --git a/crates/external_services/src/superposition.rs b/crates/external_services/src/superposition.rs
index bdbea567c9..41a9d5b7e1 100644
--- a/crates/external_services/src/superposition.rs
+++ b/crates/external_services/src/superposition.rs
@@ -6,9 +6,10 @@ pub mod types;
use std::collections::HashMap;
use common_utils::{errors::CustomResult, id_type::TargetingKey};
-use error_stack::report;
+use error_stack::{report, ResultExt};
use hyperswitch_masking::ExposeInterface;
use serde_json::Map;
+use superposition_provider::traits::AllFeatureProvider;
pub use self::types::{ConfigContext, SuperpositionClientConfig, SuperpositionError};
use crate::config_metrics;
@@ -99,40 +100,67 @@ impl GetValue<serde_json::Value> for open_feature::Client {
#[allow(missing_debug_implementations)]
pub struct SuperpositionClient {
client: open_feature::Client,
- /// Provider for Superposition
- provider: superposition_provider::SuperpositionProvider,
+ /// Provider for Superposition (using LocalResolutionProvider for fallback support)
+ provider: superposition_provider::local_provider::LocalResolutionProvider,
}
impl SuperpositionClient {
/// Create a new Superposition client
pub async fn new(config: SuperpositionClientConfig) -> CustomResult<Self, SuperpositionError> {
- let provider_options = superposition_provider::SuperpositionProviderOptions {
- endpoint: config.endpoint.clone(),
- token: config.token.expose(),
- org_id: config.org_id.clone(),
- workspace_id: config.workspace_id.clone(),
- fallback_config: None,
- evaluation_cache: None,
- refresh_strategy: superposition_provider::RefreshStrategy::Polling(
- superposition_provider::PollingStrategy {
- interval: config.polling_interval,
- timeout: config.request_timeout,
- },
+ let token_value = config.token.expose();
+
+ let refresh_strategy = superposition_provider::RefreshStrategy::Polling(
+ superposition_provider::PollingStrategy {
+ interval: config.polling_interval,
+ timeout: config.request_timeout,
+ },
+ );
+
+ // --- Build HTTP (primary) data source ---
+ let http_source = superposition_provider::data_source::http::HttpDataSource::new(
+ superposition_provider::types::SuperpositionOptions::new(
+ config.endpoint.clone(),
+ token_value.clone(),
+ config.org_id.clone(),
+ config.workspace_id.clone(),
),
- experimentation_options: Some(superposition_provider::types::ExperimentationOptions {
- refresh_strategy: superposition_provider::RefreshStrategy::Polling(
- superposition_provider::PollingStrategy {
- interval: config.polling_interval,
- timeout: config.request_timeout,
- },
- ),
- evaluation_cache: None,
- default_toss: None,
- }),
+ );
+
+ // --- Build File (fallback) data source if backup_file_path is configured ---
+ let fallback_source: Option<
+ Box<dyn superposition_provider::data_source::SuperpositionDataSource>,
+ > = match &config.backup_file_path {
+ Some(backup_path) => {
+ router_env::logger::info!(
+ "Configuring Superposition file fallback: path={:?}",
+ backup_path
+ );
+ Some(Box::new(
+ superposition_provider::data_source::file::FileDataSource::new(
+ backup_path.clone(),
+ ),
+ ))
+ }
+ None => None,
};
- // Create provider and set up OpenFeature
- let provider = superposition_provider::SuperpositionProvider::new(provider_options);
+ // --- Build LocalResolutionProvider with HTTP primary and optional file fallback ---
+ let provider = superposition_provider::local_provider::LocalResolutionProvider::new(
+ Box::new(http_source),
+ fallback_source,
+ refresh_strategy,
+ );
+
+ // Initialize provider - this will try HTTP first, then fallback to file if configured
+ provider
+ .init(open_feature::EvaluationContext::default())
+ .await
+ .change_context(SuperpositionError::ClientInitError(
+ "Failed to initialize Superposition provider".to_string(),
+ ))
+ .attach_printable(
+ "Both HTTP and file fallback (if configured) initialization failed",
+ )?;
// Initialize OpenFeature API and set provider
let mut api = open_feature::OpenFeature::singleton_mut().await;
@@ -215,7 +243,7 @@ impl SuperpositionClient {
) -> CustomResult<Map<String, serde_json::Value>, SuperpositionError> {
let evaluation_context = self.build_evaluation_context(context, targeting_key);
self.provider
- .resolve_full_config(&evaluation_context)
+ .resolve_all_features(evaluation_context)
.await
.map_err(|e| {
report!(SuperpositionError::ProviderError(format!(
@@ -237,14 +265,24 @@ impl SuperpositionClient {
prefix_filter: Option<Vec<String>>,
dimension_filter: Option<Map<String, serde_json::Value>>,
) -> CustomResult<superposition_types::Config, SuperpositionError> {
- self.provider
- .get_cached_config(dimension_filter, prefix_filter)
+ use superposition_provider::data_source::SuperpositionDataSource;
+ let response = self
+ .provider
+ .fetch_filtered_config(dimension_filter, prefix_filter, None)
.await
.map_err(|e| {
report!(SuperpositionError::ProviderError(format!(
"Failed to get cached config: {e:?}"
)))
- })
+ })?;
+ match response {
+ superposition_provider::data_source::FetchResponse::Data(data) => Ok(data.config),
+ superposition_provider::data_source::FetchResponse::NotModified => {
+ Err(report!(SuperpositionError::ProviderError(
+ "Config not modified but no data available".to_string()
+ )))
+ }
+ }
}
}
diff --git a/crates/external_services/src/superposition/types.rs b/crates/external_services/src/superposition/types.rs
index 923c04cdad..b0357a66ac 100644
--- a/crates/external_services/src/superposition/types.rs
+++ b/crates/external_services/src/superposition/types.rs
@@ -1,10 +1,13 @@
//! Type definitions for Superposition integration
-use std::collections::HashMap;
+use std::{collections::HashMap, sync::Arc};
use common_utils::{errors::CustomResult, fp_utils::when};
+use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret};
+use super::SuperpositionClient;
+
/// Wrapper type for JSON values from Superposition
#[derive(Debug, Clone)]
pub struct JsonValue(serde_json::Value);
@@ -53,6 +56,9 @@ pub struct SuperpositionClientConfig {
pub polling_interval: u64,
/// Request timeout in seconds for Superposition API calls (None = no timeout)
pub request_timeout: Option<u64>,
+ /// Path to a TOML backup config file on PVC/EFS.
+ /// Used as fallback if the primary HTTP init fails at startup.
+ pub backup_file_path: Option<std::path::PathBuf>,
}
impl Default for SuperpositionClientConfig {
@@ -65,6 +71,7 @@ impl Default for SuperpositionClientConfig {
workspace_id: String::new(),
polling_interval: 15,
request_timeout: None,
+ backup_file_path: None,
}
}
}
@@ -94,6 +101,18 @@ pub struct ConfigContext {
}
impl SuperpositionClientConfig {
+ /// Create and return a Superposition client
+ pub async fn get_superposition_client(
+ &self,
+ ) -> CustomResult<Arc<SuperpositionClient>, SuperpositionError> {
+ let client = SuperpositionClient::new(self.clone())
+ .await
+ .change_context(SuperpositionError::ClientInitError(
+ "Failed to create Superposition client".to_string(),
+ ))?;
+ Ok(Arc::new(client))
+ }
+
/// Validate the Superposition configuration
pub fn validate(&self) -> Result<(), SuperpositionError> {
if !self.enabled {
diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs
index 5d53868402..0b3604625b 100644
--- a/crates/router/src/core/configs.rs
+++ b/crates/router/src/core/configs.rs
@@ -126,7 +126,7 @@ impl ConfigType for serde_json::Value {
/// This allows configs to be used with pre-defined dimension type aliases like DimensionsWithMerchantId or DimensionsWithMerchantIdAndProfileId.
pub async fn fetch_db_config_for_dimensions<C>(
storage: &dyn db::StorageInterface,
- superposition_client: Option<&superposition::SuperpositionClient>,
+ superposition_client: &superposition::SuperpositionClient,
dimensions: &impl dimension_state::DimensionsBase,
targeting_key: Option<&C::TargetingKey>,
) -> C::Output
@@ -163,7 +163,7 @@ pub trait DatabaseBackedConfig: superposition::Config {
/// that database fallback is used when superposition fetch fails.
pub async fn fetch_db_config<C>(
storage: &dyn db::StorageInterface,
- superposition_client: Option<&superposition::SuperpositionClient>,
+ superposition_client: &superposition::SuperpositionClient,
db_key: Option<&str>,
context: Option<ConfigContext>,
targeting_key: Option<&C::TargetingKey>,
@@ -176,14 +176,7 @@ where
let config_type = C::KEY;
let default_value = C::default_value();
- let superposition_result = match superposition_client {
- Some(client) => C::fetch(client, context, targeting_key).await,
- None => Err(error_stack::report!(
- superposition::SuperpositionError::ClientError(
- "No superposition client available".to_string()
- )
- )),
- };
+ let superposition_result = C::fetch(superposition_client, context, targeting_key).await;
match superposition_result {
Ok(value) => value,
@@ -244,7 +237,7 @@ where
/// Used when Config Output is serde_json::Value but caller wants a specific type.
pub async fn fetch_db_config_object<C, T>(
storage: &dyn db::StorageInterface,
- superposition_client: Option<&superposition::SuperpositionClient>,
+ superposition_client: &superposition::SuperpositionClient,
db_key: Option<&str>,
context: Option<ConfigContext>,
targeting_key: Option<&C::TargetingKey>,
@@ -281,7 +274,7 @@ where
/// Fetch dimension-aware object-type config with JSON deserialization.
pub async fn fetch_db_config_for_objects<C, T>(
storage: &dyn db::StorageInterface,
- superposition_client: Option<&superposition::SuperpositionClient>,
+ superposition_client: &superposition::SuperpositionClient,
dimensions: &impl dimension_state::DimensionsBase,
targeting_key: Option<&C::TargetingKey>,
) -> T
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 2a85da3d71..c10c045690 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -66,7 +66,7 @@ macro_rules! config {
pub async fn [<get_ $key:lower>](
&self,
storage: &dyn StorageInterface,
- superposition_client: Option<&superposition::SuperpositionClient>,
+ superposition_client: &superposition::SuperpositionClient,
targeting_key: Option<&$targeting_type>,
) -> $output {
// Fetch JSON and convert to $output using the conversion function
@@ -109,7 +109,7 @@ macro_rules! config {
pub async fn [<get_ $key:lower>](
&self,
storage: &dyn StorageInterface,
- superposition_client: Option<&superposition::SuperpositionClient>,
+ superposition_client: &superposition::SuperpositionClient,
targeting_key: Option<&$targeting_type>,
) -> $output {
fetch_db_config_for_dimensions::<[<$key:camel>]>(storage, superposition_client, self, targeting_key).await
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 0702d3f1ac..887fa334a9 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -4663,7 +4663,7 @@ pub async fn list_customer_payment_method(
let requires_cvv = dimensions
.get_requires_cvv(
state.store.as_ref(),
- state.superposition_service.as_deref(),
+ state.superposition_service.as_ref(),
Some(customer_id),
)
.await;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 4d6122b143..3366a13f83 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2042,7 +2042,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
let implicit_customer_update = dimensions
.get_implicit_customer_update(
state.store.as_ref(),
- state.superposition_service.as_deref(),
+ state.superposition_service.as_ref(),
Some(&customer_id),
)
.await;
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 97b55b74fd..e1f335c7ff 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -668,7 +668,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
let session_validation_enabled = dimensions
.get_client_session_validation_enabled(
state.store.as_ref(),
- state.superposition_service.as_deref(),
+ state.superposition_service.as_ref(),
None,
)
.await;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 044d33e4cb..bdbb3eb2f5 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -1093,7 +1093,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
let session_validation_enabled = dimensions
.get_client_session_validation_enabled(
state.store.as_ref(),
- state.superposition_service.as_deref(),
+ state.superposition_service.as_ref(),
None,
)
.await;
diff --git a/crates/router/src/core/superposition_sdk_config.rs b/crates/router/src/core/superposition_sdk_config.rs
index 900c64d04b..d74493f434 100644
--- a/crates/router/src/core/superposition_sdk_config.rs
+++ b/crates/router/src/core/superposition_sdk_config.rs
@@ -1,5 +1,4 @@
use api_models::superposition_sdk_config::SuperPositionConfigResponse;
-use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use serde_json::Map;
@@ -43,21 +42,17 @@ pub async fn get_superposition_sdk_config(
let cached_configs = state
.superposition_service
- .as_ref()
- .async_map(|sp| {
- sp.as_ref().get_cached_config(
- Some(vec![DYNAMIC_FIELDS.to_string()]),
- Some(dimension_filter.clone()),
- )
- })
+ .get_cached_config(
+ Some(vec![DYNAMIC_FIELDS.to_string()]),
+ Some(dimension_filter.clone()),
+ )
.await
- .transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get cached superposition sdk config")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
SuperPositionConfigResponse {
- raw_configs: cached_configs,
+ raw_configs: Some(cached_configs),
resolved_configs: None,
context_used: dimension_filter,
},
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 8ef9895e01..b1b2dad037 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -144,7 +144,7 @@ pub struct SessionState {
pub crm_client: Arc<dyn CrmInterface>,
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
- pub superposition_service: Option<Arc<SuperpositionClient>>,
+ pub superposition_service: Arc<SuperpositionClient>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
@@ -224,7 +224,7 @@ pub trait SessionStateInfo {
fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>;
fn session_state(&self) -> SessionState;
fn global_store(&self) -> Box<dyn GlobalStorageInterface>;
- fn superposition_service(&self) -> Option<Arc<SuperpositionClient>>;
+ fn superposition_service(&self) -> Arc<SuperpositionClient>;
}
impl SessionStateInfo for SessionState {
@@ -284,7 +284,7 @@ impl SessionStateInfo for SessionState {
fn global_store(&self) -> Box<dyn GlobalStorageInterface> {
self.global_store.to_owned()
}
- fn superposition_service(&self) -> Option<Arc<SuperpositionClient>> {
+ fn superposition_service(&self) -> Arc<SuperpositionClient> {
self.superposition_service.clone()
}
}
@@ -342,7 +342,7 @@ pub struct AppState {
pub crm_client: Arc<dyn CrmInterface>,
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
- pub superposition_service: Option<Arc<SuperpositionClient>>,
+ pub superposition_service: Arc<SuperpositionClient>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<id_type::TenantId> {
@@ -510,23 +510,13 @@ impl AppState {
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
let infra_component_values = Self::process_env_mappings(conf.infra_values.clone());
let enhancement = conf.enhancement.clone();
- let superposition_service = if conf.superposition.get_inner().enabled {
- match SuperpositionClient::new(conf.superposition.get_inner().clone()).await {
- Ok(client) => {
- router_env::logger::info!("Superposition client initialized successfully");
- Some(Arc::new(client))
- }
- Err(err) => {
- router_env::logger::warn!(
- "Failed to initialize superposition client: {:?}. Continuing without superposition support.",
- err
- );
- None
- }
- }
- } else {
- None
- };
+ #[allow(clippy::expect_used)]
+ let superposition_service = conf
+ .superposition
+ .get_inner()
+ .get_superposition_client()
+ .await
+ .expect("Failed to initialize superposition client");
Self {
flow_name: String::from("default"),
stores,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index c235db6ccc..9c2515e956 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -3445,7 +3445,7 @@ where
let session_validation_enabled = dimensions
.get_client_session_validation_enabled(
state.store().as_ref(),
- state.superposition_service().as_deref(),
+ state.superposition_service().as_ref(),
None,
)
.await;
diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rs
index 808a627128..033e6ef84f 100644
--- a/crates/router/src/workflows/payout_sync.rs
+++ b/crates/router/src/workflows/payout_sync.rs
@@ -226,7 +226,7 @@ impl PayoutSyncWorkFlow {
let value = dimensions
.get_payout_tracker_mapping(
state.store.as_ref(),
- state.superposition_service.as_deref(),
+ &state.superposition_service,
Some(&payout_id),
)
.await;
diff --git a/docker-compose-development.yml b/docker-compose-development.yml
index 5bfb2d230a..0e65f601fa 100644
--- a/docker-compose-development.yml
+++ b/docker-compose-development.yml
@@ -72,8 +72,24 @@ services:
- router_net
environment:
- API_HOSTNAME=http://localhost:8081
- profiles:
- - superposition
+
+ superposition-init:
+ image: alpine:latest
+ depends_on:
+ superposition:
+ condition: service_started
+ networks:
+ - router_net
+ volumes:
+ - ./config/superposition_seed.toml:/seed.toml:ro
+ - ./scripts/seed_superposition.sh:/seed_superposition.sh:ro
+ environment:
+ - SUPERPOSITION_URL=http://superposition:8080
+ - SEED_FILE=/seed.toml
+ - WORKSPACE_ID=dev
+ - ORG_ID=localorg
+ command: sh -c "apk add --no-cache curl jq yq && sh /seed_superposition.sh"
+ restart: "no"
### Application services
hyperswitch-server:
@@ -101,6 +117,8 @@ services:
condition: service_healthy
redis-standalone:
condition: service_healthy
+ superposition-init:
+ condition: service_completed_successfully
labels:
logs: "promtail"
healthcheck:
diff --git a/docker-compose.yml b/docker-compose.yml
index 1717e5db59..26c7dd663b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -77,6 +77,33 @@ services:
# format -> postgresql://DB_USER:DB_PASSWORD@HOST:PORT/DATABASE_NAME
- DATABASE_URL=postgresql://db_user:db_pass@pg:5432/hyperswitch_db
+ superposition:
+ image: ghcr.io/juspay/superposition-demo:latest
+ ports:
+ - "8081:8080"
+ networks:
+ - router_net
+ environment:
+ - API_HOSTNAME=http://localhost:8081
+
+ superposition-init:
+ image: alpine:latest
+ depends_on:
+ superposition:
+ condition: service_started
+ networks:
+ - router_net
+ volumes:
+ - ./config/superposition_seed.toml:/seed.toml:ro
+ - ./scripts/seed_superposition.sh:/seed_superposition.sh:ro
+ environment:
+ - SUPERPOSITION_URL=http://superposition:8080
+ - SEED_FILE=/seed.toml
+ - WORKSPACE_ID=dev
+ - ORG_ID=localorg
+ command: sh -c "apk add --no-cache curl jq yq && sh /seed_superposition.sh"
+ restart: "no"
+
mailhog:
image: docker.io/mailhog/mailhog
networks:
@@ -106,6 +133,8 @@ services:
condition: service_healthy
migration_runner:
condition: service_completed_successfully
+ superposition-init:
+ condition: service_completed_successfully
labels:
logs: "promtail"
healthcheck:
diff --git a/docs/try_local_system.md b/docs/try_local_system.md
index 5feedd4d7c..84f04f930a 100644
--- a/docs/try_local_system.md
+++ b/docs/try_local_system.md
@@ -126,6 +126,8 @@ This will start the following services using `process-compose`
- PostgreSQL
- Creates database and an user to be used by the application
- Redis
+- Superposition
+ - Configuration management service (uses a self-contained demo image)
### Develop in a Nix environment
@@ -528,7 +530,25 @@ Once you're done with configuring the application, proceed with
### Run the application
-1. Compile and run the application using `cargo`:
+1. Start Superposition (configuration service) in Docker and seed it:
+
+ ```shell
+ just superposition-up
+ just superposition-seed
+ ```
+
+ This will start Superposition and seed it with default dimensions
+ (organization_id, merchant_id, profile_id, connector) and default configs
+ (requires_cvv, implicit_customer_update, payout_tracker_mapping).
+
+ > **Note:** If you prefer to run Superposition locally instead of Docker, refer to the [Superposition setup guide](https://juspay.io/superposition/docs/setup).
+
+ Available Superposition commands:
+ - `just superposition-up` - Start Superposition in Docker
+ - `just superposition-down` - Stop Superposition
+ - `just superposition-seed` - Seed dimensions and configs
+
+2. Compile and run the application using `cargo`:
```shell
cargo run
@@ -540,7 +560,7 @@ Once you're done with configuring the application, proceed with
nix run
```
-2. Verify that the server is up and running by hitting the health endpoint:
+3. Verify that the server is up and running by hitting the health endpoint:
```shell
curl --head --request GET 'http://localhost:8080/health'
diff --git a/justfile b/justfile
index ace2d3349d..2cc3514506 100644
--- a/justfile
+++ b/justfile
@@ -240,3 +240,54 @@ resurrect database_name=db_name:
ci_hack:
scripts/ci-checks.sh
+
+# Start superposition in docker (auto-detects docker or podman)
+superposition-up:
+ #! /usr/bin/env bash
+ set -euo pipefail
+
+ # Detect container runtime
+ if command -v docker &> /dev/null; then
+ COMPOSE="docker-compose"
+ elif command -v podman-compose &> /dev/null; then
+ COMPOSE="podman-compose"
+ else
+ echo "Error: Neither docker-compose nor podman-compose found"
+ exit 1
+ fi
+
+ echo "Using $COMPOSE..."
+ $COMPOSE -f docker-compose-development.yml up -d superposition
+
+ echo "Waiting for superposition to be ready..."
+ for i in {1..30}; do
+ if curl -s http://localhost:8081/health > /dev/null 2>&1; then
+ echo "Superposition is ready!"
+ break
+ fi
+ echo "Waiting for superposition... ($i/30)"
+ sleep 2
+ done
+
+# Stop superposition and dependencies
+superposition-down:
+ #! /usr/bin/env bash
+ set -euo pipefail
+
+ if command -v docker &> /dev/null; then
+ docker-compose -f docker-compose-development.yml down
+ elif command -v podman-compose &> /dev/null; then
+ podman-compose -f docker-compose-development.yml down
+ fi
+
+# Seed Superposition with default dimensions and configs
+superposition-seed:
+ #! /usr/bin/env bash
+ set -euo pipefail
+
+ if [ ! -f "./config/superposition_seed.toml" ]; then
+ echo "Error: Seed file not found at ./config/superposition_seed.toml"
+ exit 1
+ fi
+
+ bash ./scripts/seed_superposition.sh
diff --git a/scripts/seed_superposition.sh b/scripts/seed_superposition.sh
new file mode 100755
index 0000000000..97d1200b60
--- /dev/null
+++ b/scripts/seed_superposition.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+# Seed Superposition with default configuration for local development
+
+set -euo pipefail
+
+SUPERPOSITION_URL="${SUPERPOSITION_URL:-http://localhost:8081}"
+SEED_FILE="${SEED_FILE:-./config/superposition_seed.toml}"
+WORKSPACE_ID="${WORKSPACE_ID:-dev}"
+ORG_ID="${ORG_ID:-localorg}"
+
+echo "Seeding Superposition at $SUPERPOSITION_URL"
+echo "Using seed file: $SEED_FILE"
+echo "Workspace: $WORKSPACE_ID, Org: $ORG_ID"
+
+# Wait for superposition to be ready
+echo "Waiting for Superposition to be ready..."
+for i in {1..30}; do
+ if curl -s "$SUPERPOSITION_URL/health" > /dev/null 2>&1; then
+ echo "Superposition is ready!"
+ break
+ fi
+ echo "Waiting for Superposition... ($i/30)"
+ sleep 2
+done
+
+# Check if seed file exists
+if [ ! -f "$SEED_FILE" ]; then
+ echo "Error: Seed file not found at $SEED_FILE"
+ exit 1
+fi
+
+# Convert TOML seed file to JSON for processing
+SEED_JSON=$(yq -p toml -o json '.' "$SEED_FILE")
+
+# Seed dimensions
+# dimensions are stored as a map keyed by dimension name:
+# [dimensions.<name>] with position, schema, description, change_reason
+echo "Seeding dimensions..."
+echo "$SEED_JSON" | jq -c '.dimensions | to_entries[] | {dimension: .key, position: .value.position, schema: .value.schema, description: .value.description, change_reason: .value.change_reason}' | while read -r dimension; do
+ dim_name=$(echo "$dimension" | jq -r '.dimension')
+
+ echo "Creating dimension: $dim_name"
+
+ curl -s -X POST "$SUPERPOSITION_URL/dimension" \
+ -H "Content-Type: application/json" \
+ -H "x-org-id: $ORG_ID" \
+ -H "x-workspace: $WORKSPACE_ID" \
+ -d "$dimension" || echo "Dimension may already exist, continuing..."
+done
+
+# Seed default configs
+# default-configs are stored as a map keyed by config key:
+# [default-configs.<key>] with value, schema, description, change_reason
+echo "Seeding default configurations..."
+echo "$SEED_JSON" | jq -c '."default-configs" | to_entries[] | {key: .key, value: .value.value, schema: .value.schema, description: .value.description, change_reason: .value.change_reason}' | while read -r config; do
+ key=$(echo "$config" | jq -r '.key')
+
+ echo "Setting default config: $key"
+
+ curl -s -X POST "$SUPERPOSITION_URL/default-config" \
+ -H "Content-Type: application/json" \
+ -H "x-org-id: $ORG_ID" \
+ -H "x-workspace: $WORKSPACE_ID" \
+ -d "$config" || echo "Config may already exist, continuing..."
+done
+
+echo "Seeding complete!"
diff --git a/scripts/setup.sh b/scripts/setup.sh
index 1b40d3b555..c5a13f97dc 100755
--- a/scripts/setup.sh
+++ b/scripts/setup.sh
@@ -178,7 +178,7 @@ check_prerequisites() {
echo ""
# Check ports
- required_ports=(8080 9000 9050 5432 6379 9060)
+ required_ports=(8080 8081 9000 9050 5432 6379 9060)
unavailable_ports=()
for port in "${required_ports[@]}"; do