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): protocol-faithful store capture — binary row images in-band, one canonical redis wire type (#13535)
Uzair Khan42dbb8d45836
diff --git a/Cargo.lock b/Cargo.lockindex 456dc892d3..9074364d41 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1791,6 +1791,9 @@ name = "bytes"version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"+dependencies = [+ "serde",+][[package]]name = "bytes-utils"@@ -2867,13 +2870,16 @@ checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"[[package]]name = "deja"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"+source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"dependencies = ["deja-context","deja-core","deja-derive",+ "deja-diesel","deja-runtime","error-stack 0.4.1",+ "fred",+ "redis","serde","serde_json",]@@ -2881,7 +2887,7 @@ dependencies = [[[package]]name = "deja-context"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"+source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"dependencies = ["pin-project-lite",]@@ -2889,7 +2895,7 @@ dependencies = [[[package]]name = "deja-core"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"+source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"dependencies = ["serde","serde_json",@@ -2899,17 +2905,27 @@ dependencies = [[[package]]name = "deja-derive"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"+source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"dependencies = ["proc-macro2","quote","syn 2.0.101",]+[[package]]+name = "deja-diesel"+version = "0.1.0"+source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"+dependencies = [+ "async-bb8-diesel",+ "deja-runtime",+ "diesel",+]+[[package]]name = "deja-runtime"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"+source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"dependencies = ["async-trait","deja-context",@@ -4744,6 +4760,7 @@ dependencies = ["graphviz-rust","rustc-hash 1.1.0","serde",+ "serde_json","strum 0.25.0","thiserror 1.0.69",]@@ -5510,7 +5527,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"dependencies = ["cfg-if 1.0.0",- "windows-targets 0.53.5",+ "windows-targets 0.48.5",][[package]]@@ -7430,7 +7447,7 @@ version = "0.14.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7"dependencies = [- "heck 0.5.0",+ "heck 0.4.1","itertools 0.11.0","log 0.4.27","multimap",@@ -8380,6 +8397,7 @@ dependencies = ["tokio 1.48.0","totp-rs","tracing-futures",+ "tracing-subscriber","ucs_cards","unicode-segmentation","url 2.5.4",diff --git a/Cargo.toml b/Cargo.tomlindex 9ab0490f01..a52d724dcf 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -50,3 +50,12 @@ option_map_unit_fn = "allow"strip = truelto = truecodegen-units = 1++# Development-cycle build: optimized but without LTO, with parallel codegen and+# symbols kept. Selected via the Dockerfile's CARGO_BUILD_PROFILE build arg;+# never the default.+[profile.release-fast]+inherits = "release"+lto = false+codegen-units = 16+strip = "none"diff --git a/Dockerfile b/Dockerfileindex d5c73cb906..5cd3d4426f 100644--- a/Dockerfile+++ b/Dockerfile@@ -3,6 +3,11 @@ FROM public.ecr.aws/docker/library/rust:trixie as builderARG EXTRA_FEATURES=""ARG VERSION_FEATURE_SET="v1"+# Which cargo profile compiles the binaries: `release` (default, production),+# `release-fast` (optimized, no LTO, for development cycles) or `dev`+# (unoptimized). Features are untouched by this choice.+ARG CARGO_BUILD_PROFILE=release+RUN apt-get update \&& apt-get install -y libpq-dev libssl-dev pkg-config protobuf-compiler@@ -32,12 +37,19 @@ ENV RUST_BACKTRACE="short"COPY . .RUN cargo build \- --release \+ --profile ${CARGO_BUILD_PROFILE} \--no-default-features \--features release \--features ${VERSION_FEATURE_SET} \${EXTRA_FEATURES}+# Stage the binary at a profile-independent path for the runtime stage+# (cargo places the `dev` profile under `target/debug`). BINARY is consumed+# after the build so the build layer stays shared across images.+ARG BINARY=router+RUN mkdir -p /router/out \+ && cp "/router/target/$([ "${CARGO_BUILD_PROFILE}" = "dev" ] && echo debug || echo "${CARGO_BUILD_PROFILE}")/${BINARY}" "/router/out/${BINARY}"+FROM public.ecr.aws/docker/library/debian:trixie@@ -73,7 +85,7 @@ ENV TZ=Etc/UTC \RUN mkdir -p ${BIN_DIR}-COPY --from=builder /router/target/release/${BINARY} ${BIN_DIR}/${BINARY}+COPY --from=builder /router/out/${BINARY} ${BIN_DIR}/${BINARY}# Create the 'app' user and groupRUN useradd --user-group --system --no-create-home --no-log-init appdiff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.tomlindex 9e08b6dfe8..924e95f0ea 100644--- a/crates/common_utils/Cargo.toml+++ b/crates/common_utils/Cargo.toml@@ -30,9 +30,9 @@ async-trait = { version = "0.1.88", optional = true }base64 = "0.22.1"base64-serde = "0.8.0"blake3 = { version = "1.8.2", features = ["serde"] }-bytes = "1.10.1"+bytes = { version = "1.10.1", features = ["serde"] }diesel = "2.2.10"-deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", 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/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rsindex f87a6ea4ef..ec5d76f6fc 100644--- a/crates/common_utils/src/crypto.rs+++ b/crates/common_utils/src/crypto.rs@@ -773,6 +773,86 @@ where}}+/// Lossless two-halves serde for [`Encryptable`], used by deja capture/replay.+/// The type's own impls intentionally drop the ciphertext (API responses must+/// never expose it); this module carries both halves so a substituted value+/// keeps its encrypted half. Applied per field with+/// `#[serde(with = "…encryptable_exact")]` (or `::optional` for an `Option`).+pub mod encryptable_exact {+ use hyperswitch_masking::PeekInterface;+ use serde::{Deserialize, Serialize};++ use super::{Encryptable, Secret};++ #[derive(Serialize, Deserialize)]+ struct Halves<T> {+ inner: T,+ encrypted: Vec<u8>,+ }++ impl<T: Clone> Halves<T> {+ fn of(value: &Encryptable<T>) -> Self {+ Self {+ inner: value.inner.clone(),+ encrypted: value.encrypted.peek().clone(),+ }+ }++ fn into_encryptable(self) -> Encryptable<T> {+ Encryptable {+ inner: self.inner,+ encrypted: Secret::new(self.encrypted),+ }+ }+ }++ /// Serialize both halves — the decrypted value AND the ciphertext.+ pub fn serialize<T, S>(value: &Encryptable<T>, serializer: S) -> Result<S::Ok, S::Error>+ where+ T: Clone + Serialize,+ S: serde::Serializer,+ {+ Halves::of(value).serialize(serializer)+ }++ /// Rebuild from both halves, so the ciphertext survives the round trip.+ pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Encryptable<T>, D::Error>+ where+ T: Clone + serde::de::DeserializeOwned,+ D: serde::Deserializer<'de>,+ {+ Halves::<T>::deserialize(deserializer).map(Halves::into_encryptable)+ }++ /// The same exactness for an `Option<Encryptable<T>>` field.+ pub mod optional {+ use serde::{Deserialize, Serialize};++ use super::{Encryptable, Halves};++ /// Serialize both halves of an optional value.+ pub fn serialize<T, S>(+ value: &Option<Encryptable<T>>,+ serializer: S,+ ) -> Result<S::Ok, S::Error>+ where+ T: Clone + Serialize,+ S: serde::Serializer,+ {+ value.as_ref().map(Halves::of).serialize(serializer)+ }++ /// Rebuild an optional value from both halves.+ pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<Encryptable<T>>, D::Error>+ where+ T: Clone + serde::de::DeserializeOwned,+ D: serde::Deserializer<'de>,+ {+ Ok(Option::<Halves<T>>::deserialize(deserializer)?.map(Halves::into_encryptable))+ }+ }+}+impl<T: Clone> PartialEq for Encryptable<T>whereT: PartialEq,@@ -886,6 +966,157 @@ impl SignMessage for RsaPssSha256 {}}+#[cfg(test)]+mod encryptable_exact_tests {+ use hyperswitch_masking::{PeekInterface, Secret};+ use serde::{Deserialize, Serialize};++ use super::Encryptable;++ #[derive(Serialize, Deserialize)]+ struct Holder {+ #[serde(with = "super::encryptable_exact")]+ required: Encryptable<Secret<String>>,+ #[serde(with = "super::encryptable_exact::optional")]+ optional: Option<Encryptable<Secret<String>>>,+ }++ fn holder(inner: &str, ciphertext: Vec<u8>) -> Holder {+ Holder {+ required: Encryptable::new(Secret::new(inner.to_owned()), Secret::new(ciphertext)),+ optional: None,+ }+ }++ /// The exactness that matters: the CIPHERTEXT survives the round trip.+ ///+ /// `Encryptable`'s own impls drop it on purpose — an API response must+ /// never expose it — so capturing a cached decrypted value through them+ /// yields something the source never held. `into_encrypted()` has callers+ /// on write-back paths (`common_utils::encryption`, the `type_encryption`+ /// conversions), which would persist the empty bytes and call it+ /// reproduction.+ #[test]+ fn both_halves_survive_the_round_trip() {+ let ciphertext = vec![7_u8, 8, 9, 250];+ let subject = Holder {+ required: Encryptable::new(+ Secret::new("plaintext".to_owned()),+ Secret::new(ciphertext.clone()),+ ),+ optional: Some(Encryptable::new(+ Secret::new("other".to_owned()),+ Secret::new(vec![1_u8, 2]),+ )),+ };++ let wire = serde_json::to_value(&subject).expect("serializes");+ let back: Holder = serde_json::from_value(wire).expect("deserializes");++ assert_eq!(back.required.get_inner().peek(), "plaintext");+ assert_eq!(+ back.required.clone().into_encrypted().peek(),+ &ciphertext,+ "the encrypted half must round-trip, not come back empty"+ );+ let optional = back.optional.expect("optional present");+ assert_eq!(optional.get_inner().peek(), "other");+ assert_eq!(optional.into_encrypted().peek(), &vec![1_u8, 2]);+ }++ /// A `None` optional stays `None` rather than becoming an empty value.+ #[test]+ fn an_absent_optional_stays_absent() {+ let subject = holder("x", vec![]);+ let wire = serde_json::to_value(&subject).expect("serializes");+ let back: Holder = serde_json::from_value(wire).expect("deserializes");+ assert!(back.optional.is_none());+ }++ /// The type's own impls stay lossy — this is the contract the helper+ /// exists to work around, and a change to it would silently re-break+ /// capture rather than failing anything.+ #[test]+ fn the_types_own_serde_still_drops_the_ciphertext() {+ let value: Encryptable<Secret<String>> =+ Encryptable::new(Secret::new("v".to_owned()), Secret::new(vec![1_u8, 2, 3]));+ let wire = serde_json::to_value(&value).expect("serializes");+ let back: Encryptable<Secret<String>> = serde_json::from_value(wire).expect("deserializes");+ assert!(+ back.into_encrypted().peek().is_empty(),+ "documented lossiness: the public impls carry only the value"+ );+ }++ /// An EMPTY ciphertext must round-trip as empty, distinguishably.+ ///+ /// Without this, a regression to the lossy path is only caught by cases+ /// that happen to carry bytes: `into_encrypted().peek().is_empty()` would+ /// hold for "the source was empty" and for "the helper dropped it", and+ /// the two are different facts. Pairing this with the non-empty case+ /// pins both directions.+ #[test]+ fn an_empty_ciphertext_round_trips_as_empty() {+ let subject = holder("v", Vec::new());+ let wire = serde_json::to_value(&subject).expect("serializes");+ let back: Holder = serde_json::from_value(wire).expect("deserializes");+ assert!(back.required.into_encrypted().peek().is_empty());+ }++ /// Ciphertext is arbitrary bytes, not text. A NUL, a 0xFF and a long run+ /// must survive unaltered — a transport that ever routed these through a+ /// string would mangle exactly these and nothing else.+ #[test]+ fn arbitrary_ciphertext_bytes_survive_unaltered() {+ let mut ciphertext = vec![0_u8, 255, 1, 254, 128, 127];+ ciphertext.extend(std::iter::repeat_n(0_u8, 64));+ ciphertext.extend([0xDE, 0xAD, 0xBE, 0xEF]);++ let subject = holder("v", ciphertext.clone());+ let wire = serde_json::to_value(&subject).expect("serializes");+ let back: Holder = serde_json::from_value(wire).expect("deserializes");+ assert_eq!(back.required.into_encrypted().peek(), &ciphertext);+ }++ /// The same through a STRING, not only a `Value`.+ ///+ /// `serde_json::Value` is a lenient intermediate; the tape is bytes. A+ /// round trip that only ever goes through `Value` can hide an escaping or+ /// numeric-representation problem that a real serializer would hit.+ #[test]+ fn the_round_trip_holds_through_a_string_too() {+ let ciphertext = vec![0_u8, 34, 92, 10, 255];+ let subject = holder("quote\" and \\ backslash", ciphertext.clone());+ let text = serde_json::to_string(&subject).expect("serializes");+ let back: Holder = serde_json::from_str(&text).expect("deserializes");+ assert_eq!(back.required.get_inner().peek(), "quote\" and \\ backslash");+ assert_eq!(back.required.into_encrypted().peek(), &ciphertext);+ }++ /// The wire shape is part of the contract: both halves, under names the+ /// tape already carries. Pinning it means a rename or a re-shaping is a+ /// failing test rather than a silently unreadable recording.+ #[test]+ fn the_wire_carries_both_halves_under_stable_names() {+ let subject = holder("v", vec![1_u8, 2]);+ let wire = serde_json::to_value(&subject).expect("serializes");+ let required = wire.get("required").expect("required field present");++ assert!(+ required.get("inner").is_some(),+ "the decrypted half must be present as `inner`, got {required}"+ );+ assert_eq!(+ required+ .get("encrypted")+ .and_then(|e| e.as_array())+ .map(Vec::len),+ Some(2),+ "the encrypted half must be present as `encrypted`, got {required}"+ );+ }+}+#[cfg(test)]mod crypto_tests {use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature};diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rsindex 0f52448dec..fcef109359 100644--- a/crates/common_utils/src/custom_serde.rs+++ b/crates/common_utils/src/custom_serde.rs@@ -5,23 +5,17 @@////// [PrimitiveDateTime]: ::time::PrimitiveDateTimepub mod iso8601 {- use std::num::NonZeroU8;-use serde::{ser::Error as _, Deserializer, Serialize, Serializer};- use time::{- format_description::well_known::{- iso8601::{Config, EncodedConfig, TimePrecision},- Iso8601,- },- serde::iso8601,- PrimitiveDateTime, UtcOffset,- };+ use time::{serde::iso8601, PrimitiveDateTime, UtcOffset};- const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT- .set_time_precision(TimePrecision::Second {- decimal_digits: NonZeroU8::new(3),- })- .encode();+ /// The same rendering `Iso8601` with `decimal_digits: 3` produces, but with+ /// the subsecond rendered from the integer nanosecond count. `time` 0.3.41's+ /// well-known formatter routes subseconds through `f64` and can render a+ /// millisecond early (e.g. 938 ms as `.937`); the fixed releases require+ /// Rust 1.88 while this workspace declares 1.85.+ const EXACT_FORMAT: &[time::format_description::FormatItem<'static>] = time::macros::format_description!(+ "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"+ );/// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>@@ -30,7 +24,7 @@ pub mod iso8601 {{date_time.assume_utc()- .format(&Iso8601::<FORMAT_CONFIG>)+ .format(EXACT_FORMAT).map_err(S::Error::custom)?.serialize(serializer)}@@ -52,7 +46,6 @@ pub mod iso8601 {/// [PrimitiveDateTime]: ::time::PrimitiveDateTimepub mod option {use serde::Serialize;- use time::format_description::well_known::Iso8601;use super::*;@@ -65,7 +58,7 @@ pub mod iso8601 {S: Serializer,{date_time- .map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>))+ .map(|date_time| date_time.assume_utc().format(EXACT_FORMAT)).transpose().map_err(S::Error::custom)?.serialize(serializer)@@ -236,32 +229,24 @@ pub mod json_string {pub mod iso8601custom {use serde::{ser::Error as _, Deserializer, Serialize, Serializer};- use time::{- format_description::well_known::{- iso8601::{Config, EncodedConfig, TimePrecision},- Iso8601,- },- serde::iso8601,- PrimitiveDateTime, UtcOffset,- };+ use time::{serde::iso8601, PrimitiveDateTime, UtcOffset};- const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT- .set_time_precision(TimePrecision::Second {- decimal_digits: None,- })- .encode();+ /// `YYYY-MM-DD HH:MM:SS` — the shape this module has always emitted+ /// (previously derived by string surgery on a full ISO 8601 rendering),+ /// stated directly. This format deliberately carries no subsecond, and+ /// `deserialize` below parses ISO 8601 — the two ends serve different wires.+ const WHOLE_SECOND_FORMAT: &[time::format_description::FormatItem<'static>] =+ time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]");- /// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.+ /// Serialize a [`PrimitiveDateTime`] as `YYYY-MM-DD HH:MM:SS`.pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>whereS: Serializer,{date_time.assume_utc()- .format(&Iso8601::<FORMAT_CONFIG>)+ .format(WHOLE_SECOND_FORMAT).map_err(S::Error::custom)?- .replace('T', " ")- .replace('Z', "").serialize(serializer)}diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rsindex b62fee339f..eaa43b0bab 100644--- a/crates/common_utils/src/errors.rs+++ b/crates/common_utils/src/errors.rs@@ -177,6 +177,7 @@ where#[allow(missing_docs)]#[derive(Debug, thiserror::Error)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum KeyManagerClientError {#[error("Failed to construct header from the given value")]FailedtoConstructHeader,diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rsindex 64961ce1a6..287d418ba6 100644--- a/crates/common_utils/src/keymanager.rs+++ b/crates/common_utils/src/keymanager.rs@@ -181,6 +181,28 @@ where/// Generic function to call the Keymanager and parse the response back#[instrument(skip_all)]+// Deja: the one seam every keymanager operation crosses. Substituted on replay+// so recorded ciphertext comes back verbatim and replay does not depend on a+// live keymanager.+#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "km",+ component = "common_utils::keymanager",+ operation = "call_encryption_service",+ replay = Substitute,+ effect = Http,+ codec = deja::codec::ResultCodec::<R, errors::KeyManagerClientError>,+ // Identity is the request body via `ConvertRaw::wire_image`, not a+ // masked `Debug` — a masked capture collapses every encrypt/decrypt of+ // one merchant into a single args_hash.+ args = serde_json::json!({+ "method": method.as_str(),+ "endpoint": endpoint,+ "request": request_body.wire_image(),+ }),+ )+)]pub async fn call_encryption_service<T, R>(state: &KeyManagerState,method: Method,@@ -189,7 +211,7 @@ pub async fn call_encryption_service<T, R>() -> errors::CustomResult<R, errors::KeyManagerClientError>whereT: GetKeymanagerTenant + ConvertRaw + Send + Sync + 'static + Debug,- R: serde::de::DeserializeOwned,+ R: serde::de::DeserializeOwned + serde::Serialize,{let url = format!("{}/{endpoint}", state.url);@@ -269,6 +291,33 @@ pub trait ConvertRaw {type Output: serde::Serialize;/// Function to convert the raw data to the required format for encryption service requestfn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>;+ /// The JSON body this request becomes on the wire, read without consuming+ /// it. Must match `convert_raw`'s output; each impl derives both from one+ /// mapping so they cannot drift.+ fn wire_image(&self) -> serde_json::Value;+}++/// `to_value` at a capture site; a serialization failure names itself so it+/// cannot collide with other failures.+fn capture_json<T: serde::Serialize + ?Sized>(value: &T) -> serde_json::Value {+ serde_json::to_value(value).unwrap_or_else(|error| {+ serde_json::json!({+ "capture_failed": error.to_string(),+ "type": std::any::type_name::<T>(),+ })+ })+}++/// The text form keymanager expects for an already-encrypted payload: the bytes+/// as UTF-8 when they are text, otherwise `{version}:{base64}`.+fn encrypted_payload_text(bytes: &[u8]) -> String {+ match std::str::from_utf8(bytes) {+ Ok(text) => text.to_owned(),+ Err(_) => format!(+ "{DEFAULT_ENCRYPTION_VERSION}:{}",+ BASE64_ENGINE.encode(bytes)+ ),+ }}impl<T: serde::Serialize> ConvertRaw for T {@@ -276,46 +325,59 @@ impl<T: serde::Serialize> ConvertRaw for T {fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> {Ok(self)}+ fn wire_image(&self) -> serde_json::Value {+ capture_json(self)+ }+}++impl TransientDecryptDataRequest {+ /// The wire request this transient form becomes; by reference so+ /// `convert_raw` and `wire_image` share one definition.+ fn to_wire(&self) -> DecryptDataRequest {+ DecryptDataRequest {+ identifier: self.identifier.clone(),+ data: StrongSecret::new(encrypted_payload_text(self.data.peek())),+ }+ }}impl ConvertRaw for TransientDecryptDataRequest {type Output = DecryptDataRequest;fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> {- let data = match String::from_utf8(self.data.peek().clone()) {- Ok(data) => data,- Err(_) => {- let data = BASE64_ENGINE.encode(self.data.peek().clone());- format!("{DEFAULT_ENCRYPTION_VERSION}:{data}")- }- };- Ok(DecryptDataRequest {- identifier: self.identifier,- data: StrongSecret::new(data),- })+ Ok(self.to_wire())+ }+ fn wire_image(&self) -> serde_json::Value {+ capture_json(&self.to_wire())+ }+}++impl TransientBatchDecryptDataRequest {+ /// The wire request this transient form becomes. See+ /// [`TransientDecryptDataRequest::to_wire`].+ fn to_wire(&self) -> BatchDecryptDataRequest {+ BatchDecryptDataRequest {+ identifier: self.identifier.clone(),+ data: self+ .data+ .iter()+ .map(|(key, value)| {+ (+ key.to_owned(),+ StrongSecret::new(encrypted_payload_text(value.peek())),+ )+ })+ .collect(),+ }}}impl ConvertRaw for TransientBatchDecryptDataRequest {type Output = BatchDecryptDataRequest;fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> {- let data = self- .data- .iter()- .map(|(k, v)| {- let value = match String::from_utf8(v.peek().clone()) {- Ok(data) => data,- Err(_) => {- let data = BASE64_ENGINE.encode(v.peek().clone());- format!("{DEFAULT_ENCRYPTION_VERSION}:{data}")- }- };- (k.to_owned(), StrongSecret::new(value))- })- .collect();- Ok(BatchDecryptDataRequest {- data,- identifier: self.identifier,- })+ Ok(self.to_wire())+ }+ fn wire_image(&self) -> serde_json::Value {+ capture_json(&self.to_wire())}}diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.tomlindex 8e7fa3f53d..c06c01f533 100644--- a/crates/diesel_models/Cargo.toml+++ b/crates/diesel_models/Cargo.toml@@ -13,7 +13,7 @@ kv_store = []v1 = ["common_utils/v1", "common_types/v1"]v2 = ["common_utils/v2", "common_types/v2"]tokenization_v2 = []-deja = ["dep:deja"]+deja = ["dep:deja", "deja/diesel-pg"][dependencies]async-bb8-diesel = "0.2.1"@@ -33,7 +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 = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false, features = ["error-stack"] }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false, features = ["error-stack"] }[lints]workspace = truediff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rsindex 7fdad48261..c93d1c113c 100644--- a/crates/diesel_models/src/lib.rs+++ b/crates/diesel_models/src/lib.rs@@ -71,7 +71,17 @@ use diesel_impl::{DieselArray, OptionalDieselArray};use diesel_impl::{RequiredFromNullable, RequiredFromNullableWithDefault};pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>;-pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;++/// The concrete diesel connection type every pg pool in the workspace is built+/// over. Under `deja` it is a delegating wrapper that captures each result+/// row's wire bytes before `FromSql` consumes them; feature-off it is exactly+/// `diesel::PgConnection`.+#[cfg(feature = "deja")]+pub type DejaPgConnection = deja::DejaLoadConnection<diesel::PgConnection>;+#[cfg(not(feature = "deja"))]+pub type DejaPgConnection = diesel::PgConnection;++pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;pub use self::{address::*, api_keys::*, callback_mapper::*, capture::*, cards_info::*, configs::*,customers::*, dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rsindex 95eeedbdc5..b030d549e1 100644--- a/crates/diesel_models/src/query/authentication.rs+++ b/crates/diesel_models/src/query/authentication.rs@@ -31,7 +31,7 @@ impl Authentication {authentication_id: &common_utils::id_type::AuthenticationId,authentication_update: AuthenticationUpdateInternal,) -> StorageResult<Self> {- match generics::generic_update_with_unique_predicate_get_result::<+ match Box::pin(generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,_,_,@@ -42,7 +42,7 @@ impl Authentication {.eq(processor_merchant_id.to_owned()).and(dsl::authentication_id.eq(authentication_id.to_owned())),authentication_update,- )+ )).await{Err(error) => match error.current_context() {@@ -70,7 +70,7 @@ impl Authentication {authentication_id: &common_utils::id_type::AuthenticationId,authentication_update: AuthenticationUpdateInternal,) -> StorageResult<Self> {- match generics::generic_update_with_unique_predicate_get_result::<+ match Box::pin(generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,_,_,@@ -81,7 +81,7 @@ impl Authentication {.eq(merchant_id.to_owned()).and(dsl::authentication_id.eq(authentication_id.to_owned())),authentication_update,- )+ )).await{Err(error) => match error.current_context() {diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rsindex a1a2394f13..1428afcc90 100644--- a/crates/diesel_models/src/query/generics.rs+++ b/crates/diesel_models/src/query/generics.rs@@ -7,7 +7,7 @@ use diesel::{dsl::{count_star, Find, IsNotNull, Limit},helper_types::{Filter, IntoBoxed},insertable::CanInsertInSingleQuery,- pg::{Pg, PgConnection},+ pg::Pg,query_builder::{AsChangeset, AsQuery, DeleteStatement, InsertStatement, IntoUpdateTarget, QueryFragment,QueryId, UpdateStatement,@@ -25,7 +25,7 @@ use hyperswitch_masking::PeekInterface;use hyperswitch_masking::Secret;use router_env::logger;-use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult};+use crate::{errors, query::utils::GetPrimaryKey, DejaPgConnection, PgPooledConn, StorageResult};pub mod db_metrics {#[derive(Debug)]@@ -98,9 +98,14 @@ impl<T> DejaQueryResult for T {}// the shared dispatch seam:// - `codec = ResultCodec<_, DatabaseError>` reconstructs the typed result on// substitution — a recording that threw replays the SAME `DatabaseError`-// context ("recording threw ⇒ replay throws").-// - `result = deja::db::recorded_output(..)` is the explicit state-key /-// row-image / binds-read-key producer (the recorder itself never infers).+// context ("recording threw ⇒ replay throws"). Row-returning executors+// resolve to the `Captured` pair (below) and wrap the codec in+// `WithWireCodec` — same tape envelope, `(value, None)` on substitution.+// - `result = deja::db::recorded_output(..)` /+// `recorded_output_with_wire(..)` is the explicit state-key / row-image /+// binds-read-key producer (the recorder itself never infers). The `_with_wire`+// form receives the physical wire rows IN-BAND from the pair the executor+// returns; nothing ambient carries a capture to a boundary.// - `state_read`/`state_write`/`state_touch` declare the query-fingerprint// fallback key.// - `replay` is the per-op routing knob: writes and row-returning reads@@ -113,6 +118,15 @@ impl<T> DejaQueryResult for T {}// exprs `.peek()` them at the boundary, and the tape keeps full fidelity.// Feature-off, every executor is a plain async fn passthrough.+/// Under `deja`, a row-returning query future resolves to the result paired+/// with the binary wire rows its own connection captured while producing it;+/// the pairing is lexical, riding the future's value to the boundary.+/// Feature-off the alias is the bare result.+#[cfg(feature = "deja")]+type Captured<T> = (T, Option<Vec<deja::db::WireRow>>);+#[cfg(not(feature = "deja"))]+type Captured<T> = T;+#[cfg_attr(feature = "deja",deja::boundary(@@ -123,10 +137,10 @@ impl<T> DejaQueryResult for T {}replay = Execute,effect = Db,returns = Value,- codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<R, errors::DatabaseError>>,args = deja::db::args("generic_insert", table, sql.peek(), inputs.peek()),state_write = deja::db::query_state_key("generic_insert", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Write, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Write, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_insert<F, R>(@@ -134,14 +148,18 @@ async fn execute_generic_insert<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<R>+) -> Captured<StorageResult<R>>where- F: std::future::Future<Output = Result<R, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<R, DieselError>>> + Send,R: Send + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- match fut.await {+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = match result {Ok(value) => Ok(value),Err(err) => match err {DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => {@@ -149,7 +167,10 @@ where}_ => Err(report!(err)).change_context(errors::DatabaseError::Others),},- }+ };+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -192,10 +213,10 @@ wherereplay = Execute,effect = Db,returns = Rows,- codec = deja::codec::ResultCodec::<Vec<R>, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<Vec<R>, errors::DatabaseError>>,args = deja::db::args("generic_update_with_results", table, sql.peek(), inputs.peek()),state_touch = deja::db::query_state_key("generic_update_with_results", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Touch, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_update_with_results<F, R>(@@ -203,21 +224,28 @@ async fn execute_generic_update_with_results<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<Vec<R>>+) -> Captured<StorageResult<Vec<R>>>where- F: std::future::Future<Output = Result<Vec<R>, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<Vec<R>, DieselError>>> + Send,R: Send + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- match fut.await {+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = match result {Ok(result) => Ok(result),Err(DieselError::QueryBuilderError(_)) => {Err(report!(errors::DatabaseError::NoFieldsToUpdate))}Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)),Err(error) => Err(error).change_context(errors::DatabaseError::Others),- }+ };+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -230,10 +258,10 @@ wherereplay = Execute,effect = Db,returns = Value,- codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<R, errors::DatabaseError>>,args = deja::db::args("generic_update_by_id", table, sql.peek(), inputs.peek()),state_touch = deja::db::query_state_key("generic_update_by_id", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Touch, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_update_by_id<F, R>(@@ -241,21 +269,28 @@ async fn execute_generic_update_by_id<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<R>+) -> Captured<StorageResult<R>>where- F: std::future::Future<Output = Result<R, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<R, DieselError>>> + Send,R: Send + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- match fut.await {+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = match result {Ok(result) => Ok(result),Err(DieselError::QueryBuilderError(_)) => {Err(report!(errors::DatabaseError::NoFieldsToUpdate))}Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)),Err(error) => Err(error).change_context(errors::DatabaseError::Others),- }+ };+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -310,10 +345,10 @@ wherereplay = Execute,effect = Db,returns = Value,- codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<R, errors::DatabaseError>>,args = deja::db::args("generic_delete_one_with_result", table, sql.peek(), inputs.peek()),state_touch = deja::db::query_state_key("generic_delete_one_with_result", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Touch, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_delete_one_with_result<F, R>(@@ -321,14 +356,18 @@ async fn execute_generic_delete_one_with_result<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<R>+) -> Captured<StorageResult<R>>where- F: std::future::Future<Output = Result<Vec<R>, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<Vec<R>, DieselError>>> + Send,R: Send + Clone + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- fut.await+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = result.change_context(errors::DatabaseError::Others).attach_printable("Error while deleting").and_then(|result| {@@ -336,7 +375,10 @@ wherereport!(errors::DatabaseError::NotFound).attach_printable("Object to be deleted does not exist")})- })+ });+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -349,10 +391,10 @@ wherereplay = Execute,effect = Db,returns = Value,- codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<R, errors::DatabaseError>>,args = deja::db::args("generic_find_by_id_core", table, sql.peek(), inputs.peek()),state_read = deja::db::query_state_key("generic_find_by_id_core", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Read, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_find_by_id<F, R>(@@ -360,14 +402,18 @@ async fn execute_generic_find_by_id<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<R>+) -> Captured<StorageResult<R>>where- F: std::future::Future<Output = Result<R, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<R, DieselError>>> + Send,R: Send + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- match fut.await {+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = match result {Ok(value) => Ok(value),Err(err) => match err {DieselError::NotFound => {@@ -375,7 +421,10 @@ where}_ => Err(report!(err)).change_context(errors::DatabaseError::Others),},- }+ };+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -388,10 +437,10 @@ wherereplay = Execute,effect = Db,returns = Value,- codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<R, errors::DatabaseError>>,args = deja::db::args("generic_find_one_core", table, sql.peek(), inputs.peek()),state_read = deja::db::query_state_key("generic_find_one_core", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Read, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_find_one<F, R>(@@ -399,19 +448,26 @@ async fn execute_generic_find_one<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<R>+) -> Captured<StorageResult<R>>where- F: std::future::Future<Output = Result<R, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<R, DieselError>>> + Send,R: Send + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- fut.await+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = result.map_err(|err| match err {DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound),_ => report!(err).change_context(errors::DatabaseError::Others),})- .attach_printable("Error finding record by predicate")+ .attach_printable("Error finding record by predicate");+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -424,10 +480,10 @@ wherereplay = Execute,effect = Db,returns = Rows,- codec = deja::codec::ResultCodec::<Vec<R>, errors::DatabaseError>,+ codec = deja::codec::WithWireCodec::<deja::codec::ResultCodec<Vec<R>, errors::DatabaseError>>,args = deja::db::args("generic_filter", table, sql.peek(), inputs.peek()),state_read = deja::db::query_state_key("generic_filter", table, sql.peek(), inputs.peek()),- result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Read, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),))]async fn execute_generic_filter<F, R>(@@ -435,16 +491,23 @@ async fn execute_generic_filter<F, R>(table: &'static str,sql: Secret<String>,inputs: Secret<serde_json::Value>,-) -> StorageResult<Vec<R>>+) -> Captured<StorageResult<Vec<R>>>where- F: std::future::Future<Output = Result<Vec<R>, DieselError>> + Send,+ F: std::future::Future<Output = Captured<Result<Vec<R>, DieselError>>> + Send,R: Send + 'static + DejaQueryResult,{#[cfg(not(feature = "deja"))]let _ = (&table, &sql, &inputs);- fut.await+ #[cfg(feature = "deja")]+ let (result, wire) = fut.await;+ #[cfg(not(feature = "deja"))]+ let result = fut.await;+ let mapped = result.change_context(errors::DatabaseError::Others)- .attach_printable("Error filtering records by predicate")+ .attach_printable("Error filtering records by predicate");+ #[cfg(feature = "deja")]+ let mapped = (mapped, wire);+ mapped}#[cfg_attr(@@ -497,7 +560,7 @@ where<T as QuerySource>::FromClause: QueryFragment<Pg> + Debug,<V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static,InsertStatement<T, <V as Insertable<T>>::Values>:- AsQuery + LoadQuery<'static, PgConnection, R> + Send,+ AsQuery + LoadQuery<'static, DejaPgConnection, R> + Send,R: Send + 'static + DejaQueryResult,{let debug_values = format!("{values:?}");@@ -509,14 +572,25 @@ where"values": { "debug": debug_values.as_str() },});- execute_generic_insert(- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::get_result_captured(conn, query),+ DatabaseOperation::Insert,+ );+ #[cfg(not(feature = "deja"))]+ let fut =+ track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert);++ let output = execute_generic_insert(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await- .attach_printable_lazy(|| format!("Error while inserting {debug_values}"))+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output.attach_printable_lazy(|| format!("Error while inserting {debug_values}"))}pub async fn generic_update<T, V, P>(@@ -567,7 +641,7 @@ where<Filter<T, P> as HasTable>::Table,<Filter<T, P> as IntoUpdateTarget>::WhereClause,<V as AsChangeset>::Changeset,- >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone,+ >: AsQuery + LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + Clone,R: Send + 'static + DejaQueryResult,// For cloning query (UpdateStatement)@@ -586,17 +660,27 @@ where"predicate": { "type": std::any::type_name::<P>() },});- execute_generic_update_with_results(- track_database_call::<T, _, _>(- query.to_owned().get_results_async(conn),- DatabaseOperation::UpdateWithResults,- ),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::get_results_captured(conn, query.to_owned()),+ DatabaseOperation::UpdateWithResults,+ );+ #[cfg(not(feature = "deja"))]+ let fut = track_database_call::<T, _, _>(+ query.to_owned().get_results_async(conn),+ DatabaseOperation::UpdateWithResults,+ );++ let output = execute_generic_update_with_results(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await- .attach_printable_lazy(|| format!("Error while updating {debug_values}"))+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output.attach_printable_lazy(|| format!("Error while updating {debug_values}"))}pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>(@@ -612,7 +696,7 @@ where<Filter<T, P> as HasTable>::Table,<Filter<T, P> as IntoUpdateTarget>::WhereClause,<V as AsChangeset>::Changeset,- >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send,+ >: AsQuery + LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send,R: Send + 'static + DejaQueryResult,// For cloning query (UpdateStatement)@@ -643,14 +727,15 @@ pub async fn generic_update_by_id<T, V, Pk, R>(whereT: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + Debug,- Find<T, Pk>: IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,+ Find<T, Pk>:+ IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<DejaPgConnection> + Send + 'static,UpdateStatement<<Find<T, Pk> as HasTable>::Table,<Find<T, Pk> as IntoUpdateTarget>::WhereClause,<V as AsChangeset>::Changeset,- >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,+ >: AsQuery + LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,Find<T, Pk>: LimitDsl,- Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,+ Limit<Find<T, Pk>>: LoadQuery<'static, DejaPgConnection, R>,R: Send + 'static + DejaQueryResult,Pk: Clone + Debug,@@ -670,17 +755,27 @@ where"values": { "debug": debug_values.as_str() },});- execute_generic_update_by_id(- track_database_call::<T, _, _>(- query.to_owned().get_result_async(conn),- DatabaseOperation::UpdateOne,- ),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::get_result_captured(conn, query.to_owned()),+ DatabaseOperation::UpdateOne,+ );+ #[cfg(not(feature = "deja"))]+ let fut = track_database_call::<T, _, _>(+ query.to_owned().get_result_async(conn),+ DatabaseOperation::UpdateOne,+ );++ let output = execute_generic_update_by_id(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await- .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))}pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool>@@ -718,7 +813,7 @@ whereDeleteStatement<<Filter<T, P> as HasTable>::Table,<Filter<T, P> as IntoUpdateTarget>::WhereClause,- >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,+ >: AsQuery + LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,R: Send + Clone + 'static + DejaQueryResult,{let query = diesel::delete(<T as HasTable>::table().filter(predicate));@@ -728,23 +823,34 @@ where"predicate": { "type": std::any::type_name::<P>() },});- execute_generic_delete_one_with_result(- track_database_call::<T, _, _>(- query.get_results_async(conn),- DatabaseOperation::DeleteWithResult,- ),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::get_results_captured(conn, query),+ DatabaseOperation::DeleteWithResult,+ );+ #[cfg(not(feature = "deja"))]+ let fut = track_database_call::<T, _, _>(+ query.get_results_async(conn),+ DatabaseOperation::DeleteWithResult,+ );++ let output = execute_generic_delete_one_with_result(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output}async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>whereT: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,- Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,- Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,+ Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<DejaPgConnection> + Send + 'static,+ Limit<Find<T, Pk>>: LoadQuery<'static, DejaPgConnection, R>,Pk: Clone + Debug,R: Send + 'static + DejaQueryResult,{@@ -755,21 +861,31 @@ where"id": { "debug": format!("{id:?}") },});- execute_generic_find_by_id(- track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::first_captured(conn, query),+ DatabaseOperation::FindOne,+ );+ #[cfg(not(feature = "deja"))]+ let fut = track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne);++ let output = execute_generic_find_by_id(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await- .attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output.attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))}pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>whereT: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,- Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,- Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,+ Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<DejaPgConnection> + Send + 'static,+ Limit<Find<T, Pk>>: LoadQuery<'static, DejaPgConnection, R>,Pk: Clone + Debug,R: Send + 'static + DejaQueryResult,{@@ -783,8 +899,8 @@ pub async fn generic_find_by_id_optional<T, Pk, R>(whereT: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,<T as HasTable>::Table: FindDsl<Pk>,- Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,- Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,+ Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<DejaPgConnection> + Send + 'static,+ Limit<Find<T, Pk>>: LoadQuery<'static, DejaPgConnection, R>,Pk: Clone + Debug,R: Send + 'static + DejaQueryResult,{@@ -794,7 +910,7 @@ whereasync fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>whereT: FilterDsl<P> + HasTable<Table = T> + Table + 'static,- Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,+ Filter<T, P>: LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,R: Send + 'static + DejaQueryResult,{let query = <T as HasTable>::table().filter(predicate);@@ -804,19 +920,31 @@ where"predicate": { "type": std::any::type_name::<P>() },});- execute_generic_find_one(- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::get_result_captured(conn, query),+ DatabaseOperation::FindOne,+ );+ #[cfg(not(feature = "deja"))]+ let fut =+ track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne);++ let output = execute_generic_find_one(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output}pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>whereT: FilterDsl<P> + HasTable<Table = T> + Table + 'static,- Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,+ Filter<T, P>: LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,R: Send + 'static + DejaQueryResult,{generic_find_one_core::<T, _, _>(conn, predicate).await@@ -828,7 +956,7 @@ pub async fn generic_find_one_optional<T, P, R>() -> StorageResult<Option<R>>whereT: FilterDsl<P> + HasTable<Table = T> + Table + 'static,- Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,+ Filter<T, P>: LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,R: Send + 'static + DejaQueryResult,{to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await)@@ -848,7 +976,7 @@ where+ LimitDsl<Output = IntoBoxed<'static, T, Pg>>+ OffsetDsl<Output = IntoBoxed<'static, T, Pg>>+ OrderDsl<O, Output = IntoBoxed<'static, T, Pg>>- + LoadQuery<'static, PgConnection, R>+ + LoadQuery<'static, DejaPgConnection, R>+ QueryFragment<Pg>+ Send,O: Expression,@@ -879,13 +1007,25 @@ where"order": { "type": std::any::type_name::<O>() },});- execute_generic_filter(- track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter),+ #[cfg(feature = "deja")]+ let fut = track_database_call::<T, _, _>(+ deja::db::get_results_captured(conn, query),+ DatabaseOperation::Filter,+ );+ #[cfg(not(feature = "deja"))]+ let fut =+ track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter);++ let output = execute_generic_filter(+ fut,table_name::<T>(),Secret::new(sql),Secret::new(inputs),)- .await+ .await;+ #[cfg(feature = "deja")]+ let output = output.0;+ output}pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>@@ -893,7 +1033,7 @@ whereT: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static,Filter<T, P>: SelectDsl<count_star>,diesel::dsl::Select<Filter<T, P>, count_star>:- LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static,+ LoadQuery<'static, DejaPgConnection, i64> + QueryFragment<Pg> + Send + 'static,{let query = <T as HasTable>::table().filter(predicate)diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rsindex 0b641217d4..f7e47663ce 100644--- a/crates/diesel_models/src/query/merchant_account.rs+++ b/crates/diesel_models/src/query/merchant_account.rs@@ -17,7 +17,7 @@ use crate::{impl MerchantAccountNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantAccount> {- generics::generic_insert(conn, self).await+ Box::pin(generics::generic_insert(conn, self)).await}}@@ -28,11 +28,12 @@ impl MerchantAccount {conn: &PgPooledConn,merchant_account: MerchantAccountUpdateInternal,) -> StorageResult<Self> {- match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(- conn,- self.get_id().to_owned(),- merchant_account,- )+ match Box::pin(generics::generic_update_by_id::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(conn, self.get_id().to_owned(), merchant_account)).await{Err(error) => match error.current_context() {@@ -48,7 +49,7 @@ impl MerchantAccount {identifier: &common_utils::id_type::MerchantId,merchant_account: MerchantAccountUpdateInternal,) -> StorageResult<Self> {- generics::generic_update_with_unique_predicate_get_result::<+ Box::pin(generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,_,_,@@ -57,7 +58,7 @@ impl MerchantAccount {conn,dsl::merchant_id.eq(identifier.to_owned()),merchant_account,- )+ )).await}@@ -158,11 +159,14 @@ impl MerchantAccount {conn: &PgPooledConn,merchant_account: MerchantAccountUpdateInternal,) -> StorageResult<Vec<Self>> {- generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(- conn,- dsl::merchant_id.ne_all(vec![""]),- merchant_account,- )+ Box::pin(generics::generic_update_with_results::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(+ conn, dsl::merchant_id.ne_all(vec![""]), merchant_account+ )).await}}diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rsindex 31a866c994..37d1adc205 100644--- a/crates/diesel_models/src/query/payment_attempt.rs+++ b/crates/diesel_models/src/query/payment_attempt.rs@@ -75,12 +75,14 @@ impl PaymentAttempt {conn: &PgPooledConn,payment_attempt: PaymentAttemptUpdateInternal,) -> StorageResult<Self> {- match generics::generic_update_with_unique_predicate_get_result::<+ match Box::pin(generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,_,_,_,- >(conn, dsl::id.eq(self.id.to_owned()), payment_attempt)+ >(+ conn, dsl::id.eq(self.id.to_owned()), payment_attempt+ )).await{Err(error) => match error.current_context() {diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rsindex 13490df697..cbe87351a4 100644--- a/crates/diesel_models/src/query/payment_intent.rs+++ b/crates/diesel_models/src/query/payment_intent.rs@@ -64,13 +64,18 @@ impl PaymentIntent {conn: &PgPooledConn,payment_intent: payment_intent::PaymentIntentUpdate,) -> StorageResult<Self> {- match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(+ match Box::pin(generics::generic_update_with_results::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(conn,dsl::payment_id.eq(self.payment_id.to_owned()).and(dsl::processor_merchant_id.eq(self.processor_merchant_id.to_owned())),payment_intent::PaymentIntentUpdateInternal::from(payment_intent),- )+ )).await{Err(error) => match error.current_context() {diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rsindex 9df83469b8..1b89980c94 100644--- a/crates/diesel_models/src/query/payment_method.rs+++ b/crates/diesel_models/src/query/payment_method.rs@@ -19,7 +19,7 @@ use crate::{impl PaymentMethodNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> {- generics::generic_insert(conn, self).await+ Box::pin(generics::generic_insert(conn, self)).await}pub async fn generate_drainer_insert_query(diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rsindex 0baef50aba..a14ee63b58 100644--- a/crates/drainer/src/connection.rs+++ b/crates/drainer/src/connection.rs@@ -1,10 +1,10 @@use bb8::PooledConnection;use common_utils::DbConnectionParams;-use diesel::PgConnection;+use diesel_models::DejaPgConnection;use crate::{settings::Database, Settings};-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;+pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;#[allow(clippy::expect_used)]pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {@@ -24,7 +24,7 @@ pub async fn diesel_make_pg_pool(schema: &str,) -> PgPool {let database_url = database.get_database_url(schema);- let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);+ let manager = async_bb8_diesel::ConnectionManager::<DejaPgConnection>::new(database_url);let pool = bb8::Pool::builder().max_size(database.pool_size).connection_timeout(std::time::Duration::from_secs(database.connection_timeout));@@ -37,7 +37,7 @@ pub async fn diesel_make_pg_pool(#[allow(clippy::expect_used)]pub async fn pg_connection(pool: &PgPool,-) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {+) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>> {pool.get().await.expect("Couldn't retrieve PostgreSQL connection")diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rsindex 95e527aa76..68caf7fa5d 100644--- a/crates/euclid/src/frontend/dir.rs+++ b/crates/euclid/src/frontend/dir.rs@@ -45,7 +45,7 @@ macro_rules! dirval {}};}-#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)]+#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct DirKey {pub kind: DirKeyKind,pub value: Option<String>,@@ -64,6 +64,7 @@ impl DirKey {PartialEq,Eq,serde::Serialize,+ serde::Deserialize,strum::Display,strum::EnumIter,strum::VariantNames,@@ -255,7 +256,9 @@ pub enum DirKeyKind {)]#[serde(rename = "billing_country")]BillingCountry,- #[serde(skip_deserializing, rename = "connector")]+ // No `skip_deserializing`: a recorded constraint graph substituted on+ // replay is read back, and an unreadable variant fails the whole graph.+ #[serde(rename = "connector")]Connector,#[strum(serialize = "business_label",@@ -617,7 +620,15 @@ impl DirKeyKind {}#[derive(- Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames,+ Debug,+ Clone,+ Hash,+ PartialEq,+ Eq,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::VariantNames,)]#[serde(tag = "key", content = "value")]pub enum DirValue {@@ -673,7 +684,9 @@ pub enum DirValue {BusinessCountry(enums::Country),#[serde(rename = "billing_country")]BillingCountry(enums::Country),- #[serde(skip_deserializing, rename = "connector")]+ // No `skip_deserializing`: a recorded constraint graph substituted on+ // replay is read back, and an unreadable variant fails the whole graph.+ #[serde(rename = "connector")]Connector(Box<ast::ConnectorChoice>),#[serde(rename = "business_label")]BusinessLabel(types::StrValue),@@ -1113,3 +1126,71 @@ mod test {assert!(out.is_err())}}+#[cfg(test)]+mod serde_round_trip {+ use strum::IntoEnumIterator;++ use super::{ast, DirKey, DirKeyKind, DirValue};+ use crate::enums as euclid_enums;++ /// Every key kind must survive a serde round trip.+ ///+ /// A variant that serializes under a tag it refuses to deserialize is+ /// invisible to the compiler and silent in every test that only ever+ /// writes. `DirKeyKind::Connector` and `DirValue::Connector` carried+ /// `skip_deserializing` for years, harmlessly, because nothing read these+ /// back — until a recorded constraint graph was substituted on replay,+ /// where reconstruction of the WHOLE graph failed on the one unreadable+ /// variant and took the request down with it. Enumerating the variants+ /// keeps the asymmetry from returning silently for any of them.+ #[test]+ fn every_key_kind_round_trips() {+ for kind in DirKeyKind::iter() {+ let wire = serde_json::to_value(&kind)+ .unwrap_or_else(|e| panic!("{kind:?} does not serialize: {e}"));+ let back: DirKeyKind = serde_json::from_value(wire.clone()).unwrap_or_else(|e| {+ panic!("{kind:?} serializes as {wire} but does not read back: {e}")+ });+ assert_eq!(back, kind, "{kind:?} changed identity across a round trip");+ }+ }++ /// The same for a full key, which is what a graph's key nodes carry.+ #[test]+ fn every_key_round_trips_inside_a_key() {+ for kind in DirKeyKind::iter() {+ let key = DirKey::new(kind.clone(), None);+ let wire = serde_json::to_value(&key).expect("serializes");+ let back: DirKey = serde_json::from_value(wire.clone()).unwrap_or_else(|e| {+ panic!("DirKey({kind:?}) serializes as {wire} but does not read back: {e}")+ });+ assert_eq!(back, key);+ }+ }++ /// `DirValue::Connector` specifically, because it is the variant that was+ /// unreadable and the enumerating tests above cannot reach it.+ ///+ /// `DirValue`'s variants carry data, so it derives `VariantNames` rather+ /// than `EnumIter` and cannot be iterated into values. The one variant the+ /// fix was about therefore needs naming outright, or it is the only part+ /// of the change with no test over it.+ #[test]+ fn the_connector_value_round_trips() {+ let value = DirValue::Connector(Box::new(ast::ConnectorChoice {+ connector: euclid_enums::RoutableConnectors::Adyen,+ }));++ let wire = serde_json::to_value(&value).expect("serializes");+ assert_eq!(+ wire.get("key").and_then(|k| k.as_str()),+ Some("connector"),+ "the tag must stay `connector`; a recorded graph names it that way, got {wire}"+ );++ let back: DirValue = serde_json::from_value(wire.clone()).unwrap_or_else(|e| {+ panic!("DirValue::Connector serializes as {wire} but does not read back: {e}")+ });+ assert_eq!(back, value);+ }+}diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex 983fb65d8c..d3f13d66b9 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -62,7 +62,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 = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }error-stack = "0.4.1"hex = "0.4.3"hyper = "0.14.32"diff --git a/crates/external_services/src/grpc_client/deja_transport.rs b/crates/external_services/src/grpc_client/deja_transport.rsindex 83ac32fb33..4856a17c8e 100644--- a/crates/external_services/src/grpc_client/deja_transport.rs+++ b/crates/external_services/src/grpc_client/deja_transport.rs@@ -297,7 +297,9 @@ fn reconstruct_from_recorded(recorded: serde_json::Value,) -> deja::__private::Reconstructed<Result<http::Response<TonicBody>, BoxError>> {let Ok(envelope) = serde_json::from_value::<GrpcResultEnvelope>(recorded) else {- return deja::__private::Reconstructed::Failed;+ return deja::__private::Reconstructed::Failed(::std::string::String::from(+ "recorded value is not a `GrpcResultEnvelope`",+ ));};match &envelope {GrpcResultEnvelope::Response { .. } => {@@ -305,7 +307,10 @@ fn reconstruct_from_recorded(Some(response) => {deja::__private::Reconstructed::Value(Ok(response.map(TonicBody::new)))}- None => deja::__private::Reconstructed::Failed,+ None => deja::__private::Reconstructed::Failed(::std::string::String::from(+ "recorded gRPC response could not be rebuilt into an http::Response \+ (status line, headers or body frame missing from the envelope)",+ )),}}GrpcResultEnvelope::TransportError { error } => deja::__private::Reconstructed::Value(Err(diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rsindex 2272f66242..08fc8e975c 100644--- a/crates/external_services/src/http_client.rs+++ b/crates/external_services/src/http_client.rs@@ -13,8 +13,14 @@ pub mod metrics;/// request modulepub mod request;+/// Boundary capture/replay for the outgoing HTTP client.+///+/// Public so the tape-conformance gate can reconstruct a recorded response+/// through the SAME codec replay runs, rather than reimplementing what that+/// codec accepts — a second copy of the rule is free to drift from the one that+/// actually decides whether a worker lives.#[cfg(feature = "deja")]-mod boundary;+pub mod boundary;use std::{error::Error, time::Duration};diff --git a/crates/external_services/src/http_client/boundary.rs b/crates/external_services/src/http_client/boundary.rsindex 16dae6ceac..15cd154e07 100644--- a/crates/external_services/src/http_client/boundary.rs+++ b/crates/external_services/src/http_client/boundary.rs@@ -147,7 +147,11 @@ pub(super) fn response_result()}-pub(super) struct HttpResponseCodec;+/// Capture and rebuild a `send_request` outcome on the `http_outgoing`+/// boundary. `reconstruct` returning `None` is what fail-stops a substituted+/// egress call, so the tape-conformance gate calls it directly.+#[derive(Debug)]+pub struct HttpResponseCodec;impl deja::codec::ReplayCodec for HttpResponseCodec {type Value = CustomResult<reqwest::Response, HttpClientError>;diff --git a/crates/external_services/src/superposition.rs b/crates/external_services/src/superposition.rsindex 1db1bbb150..1130dfd6b3 100644--- a/crates/external_services/src/superposition.rs+++ b/crates/external_services/src/superposition.rs@@ -91,7 +91,9 @@ mod deja_boundary {) -> deja::__private::Reconstructed<CustomResult<T, SuperpositionError>> {use deja::__private::Reconstructed;let Some(object) = recorded.as_object() else {- return Reconstructed::Failed;+ return Reconstructed::Failed(format!(+ "superposition envelope is not an object: {recorded}"+ ));};match object.get("result").and_then(serde_json::Value::as_str) {Some("Ok") => match object@@ -100,7 +102,14 @@ mod deja_boundary {.map(serde_json::from_value::<T>){Some(Ok(value)) => Reconstructed::Value(Ok(value)),- _ => Reconstructed::Failed,+ other => Reconstructed::Failed(format!(+ "recorded superposition Ok value will not deserialize into `{}`: {}",+ std::any::type_name::<T>(),+ match other {+ Some(Err(error)) => error.to_string(),+ _ => "envelope carried no `value`".to_owned(),+ }+ )),},Some("Err") => match object.get("error")@@ -108,9 +117,17 @@ mod deja_boundary {.map(serde_json::from_value::<SuperpositionError>){Some(Ok(error)) => Reconstructed::Value(Err(report!(error))),- _ => Reconstructed::Failed,+ other => Reconstructed::Failed(format!(+ "recorded superposition Err will not deserialize into `SuperpositionError`: {}",+ match other {+ Some(Err(error)) => error.to_string(),+ _ => "envelope carried no `error`".to_owned(),+ }+ )),},- _ => Reconstructed::Failed,+ other => Reconstructed::Failed(format!(+ "superposition envelope has no usable `result` discriminant: {other:?}"+ )),}}diff --git a/crates/hyperswitch_constraint_graph/Cargo.toml b/crates/hyperswitch_constraint_graph/Cargo.tomlindex 826615791d..36bbeb6e0c 100644--- a/crates/hyperswitch_constraint_graph/Cargo.toml+++ b/crates/hyperswitch_constraint_graph/Cargo.toml@@ -18,3 +18,6 @@ thiserror = "1.0.69"[lints]workspace = true++[dev-dependencies]+serde_json = "1"diff --git a/crates/hyperswitch_constraint_graph/src/dense_map.rs b/crates/hyperswitch_constraint_graph/src/dense_map.rsindex 682833d65e..218f2c1d8f 100644--- a/crates/hyperswitch_constraint_graph/src/dense_map.rs+++ b/crates/hyperswitch_constraint_graph/src/dense_map.rs@@ -23,6 +23,11 @@ macro_rules! impl_entity {pub(crate) use impl_entity;+#[derive(serde::Serialize, serde::Deserialize)]+#[serde(bound(+ serialize = "V: serde::Serialize",+ deserialize = "V: serde::de::DeserializeOwned"+))]pub struct DenseMap<K, V> {data: Vec<V>,_marker: PhantomData<K>,diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rsindex 8d56406d2a..a84bd0ed6f 100644--- a/crates/hyperswitch_constraint_graph/src/graph.rs+++ b/crates/hyperswitch_constraint_graph/src/graph.rs@@ -25,17 +25,64 @@ struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> {domains: Option<&'a [DomainId]>,}-#[derive(Debug)]+/// Serde carries the evaluation state of a finished graph. `value_map` is not+/// on the wire but is rebuilt on deserialization (see [`ConstraintGraphWire`]);+/// `node_info`/`node_metadata` are diagnostics and stay empty on the way in.+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(bound(+ serialize = "V: serde::Serialize, <V as ValueNode>::Key: serde::Serialize",+ deserialize = "V: serde::de::DeserializeOwned, <V as ValueNode>::Key: serde::de::DeserializeOwned"+))]+#[serde(from = "ConstraintGraphWire<V>")]pub struct ConstraintGraph<V: ValueNode> {pub domain: DenseMap<DomainId, DomainInfo>,pub domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>,pub nodes: DenseMap<NodeId, Node<V>>,pub edges: DenseMap<EdgeId, Edge>,+ #[serde(skip)]pub value_map: FxHashMap<NodeValue<V>, NodeId>,+ #[serde(skip)]pub node_info: DenseMap<NodeId, Option<&'static str>>,+ #[serde(skip)]pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>,}+/// The deserialization shape of [`ConstraintGraph`]. `value_map` is rebuilt+/// from `nodes` rather than serialized: its key is a structured enum no JSON+/// map can key, and the builder inserts an entry iff it creates the value node.+#[derive(serde::Deserialize)]+#[serde(bound(+ deserialize = "V: serde::de::DeserializeOwned, <V as ValueNode>::Key: serde::de::DeserializeOwned"+))]+struct ConstraintGraphWire<V: ValueNode> {+ domain: DenseMap<DomainId, DomainInfo>,+ domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>,+ nodes: DenseMap<NodeId, Node<V>>,+ edges: DenseMap<EdgeId, Edge>,+}++impl<V: ValueNode> From<ConstraintGraphWire<V>> for ConstraintGraph<V> {+ fn from(wire: ConstraintGraphWire<V>) -> Self {+ let value_map = wire+ .nodes+ .iter()+ .filter_map(|(node_id, node)| match &node.node_type {+ NodeType::Value(value) => Some((value.clone(), node_id)),+ _ => None,+ })+ .collect();+ Self {+ domain: wire.domain,+ domain_identifier_map: wire.domain_identifier_map,+ nodes: wire.nodes,+ edges: wire.edges,+ value_map,+ node_info: DenseMap::new(),+ node_metadata: DenseMap::new(),+ }+ }+}+impl<V> ConstraintGraph<V>whereV: ValueNode,diff --git a/crates/hyperswitch_constraint_graph/src/types.rs b/crates/hyperswitch_constraint_graph/src/types.rsindex 0cbecc28f2..6c17f2c768 100644--- a/crates/hyperswitch_constraint_graph/src/types.rs+++ b/crates/hyperswitch_constraint_graph/src/types.rs@@ -22,13 +22,17 @@ pub trait NodeViz {fn viz(&self) -> String;}-#[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)]+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)]#[serde(transparent)]pub struct NodeId(usize);impl_entity!(NodeId);-#[derive(Debug)]+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(bound(+ serialize = "V: serde::Serialize, <V as ValueNode>::Key: serde::Serialize",+ deserialize = "V: serde::de::DeserializeOwned, <V as ValueNode>::Key: serde::de::DeserializeOwned"+))]pub struct Node<V: ValueNode> {pub node_type: NodeType<V>,pub preds: Vec<EdgeId>,@@ -45,7 +49,11 @@ impl<V: ValueNode> Node<V> {}}-#[derive(Debug, PartialEq, Eq)]+#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(bound(+ serialize = "V: serde::Serialize, <V as ValueNode>::Key: serde::Serialize",+ deserialize = "V: serde::de::DeserializeOwned, <V as ValueNode>::Key: serde::de::DeserializeOwned"+))]pub enum NodeType<V: ValueNode> {AllAggregator,AnyAggregator,@@ -53,8 +61,12 @@ pub enum NodeType<V: ValueNode> {Value(NodeValue<V>),}-#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]#[serde(tag = "type", content = "value", rename_all = "snake_case")]+#[serde(bound(+ serialize = "V: serde::Serialize, <V as ValueNode>::Key: serde::Serialize",+ deserialize = "V: serde::de::DeserializeOwned, <V as ValueNode>::Key: serde::de::DeserializeOwned"+))]pub enum NodeValue<V: ValueNode> {Key(<V as ValueNode>::Key),Value(V),@@ -66,13 +78,23 @@ impl<V: ValueNode> From<V> for NodeValue<V> {}}-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]pub struct EdgeId(usize);impl_entity!(EdgeId);#[derive(- Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash, strum::Display, PartialOrd, Ord,+ Debug,+ Clone,+ Copy,+ serde::Serialize,+ serde::Deserialize,+ PartialEq,+ Eq,+ Hash,+ strum::Display,+ PartialOrd,+ Ord,)]pub enum Strength {Weak,@@ -86,7 +108,9 @@ impl Strength {}}-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)]+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize,+)]#[serde(rename_all = "snake_case")]pub enum Relation {Positive,@@ -125,7 +149,7 @@ impl RelationResolution {}}-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct Edge {pub strength: Strength,pub relation: Relation,@@ -134,12 +158,12 @@ pub struct Edge {pub domain: Option<DomainId>,}-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]pub struct DomainId(usize);impl_entity!(DomainId);-#[derive(Debug, Clone, PartialEq, Eq, Hash)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]pub struct DomainIdentifier(String);impl DomainIdentifier {@@ -158,7 +182,7 @@ impl From<String> for DomainIdentifier {}}-#[derive(Debug, Clone, PartialEq, Eq, Hash)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]pub struct DomainInfo {pub domain_identifier: DomainIdentifier,pub domain_description: String,diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rsindex 6e991f9af0..3a3adbea1d 100644--- a/crates/hyperswitch_domain_models/src/business_profile.rs+++ b/crates/hyperswitch_domain_models/src/business_profile.rs@@ -21,7 +21,7 @@ use router_env::logger;use crate::{errors::api_error_response, merchant_key_store::MerchantKeyStore, payments};#[cfg(feature = "v1")]-#[derive(Clone, Debug)]+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]pub struct Profile {profile_id: common_utils::id_type::ProfileId,pub merchant_id: common_utils::id_type::MerchantId,@@ -50,6 +50,7 @@ pub struct Profile {pub use_billing_as_payment_method_billing: Option<bool>,pub collect_shipping_details_from_wallet_connector: Option<bool>,pub collect_billing_details_from_wallet_connector: Option<bool>,+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,pub always_collect_billing_details_from_wallet_connector: Option<bool>,pub always_collect_shipping_details_from_wallet_connector: Option<bool>,@@ -67,6 +68,7 @@ pub struct Profile {pub authentication_product_ids:Option<common_types::payments::AuthenticationConnectorAccountMap>,pub card_testing_guard_config: Option<CardTestingGuardConfig>,+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub card_testing_secret_key: OptionalEncryptableName,pub is_clear_pan_retries_enabled: bool,pub force_3ds_challenge: bool,@@ -84,13 +86,14 @@ pub struct Profile {pub external_vault_details: ExternalVaultDetails,pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,pub surcharge_connector_details: Option<SurchargeConnectorDetails>,+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub network_tokenization_credentials: OptionalEncryptableValue,pub payment_method_blocking: Option<PaymentMethodBlockingConfig>,pub default_fallback_routing: Option<pii::SecretSerdeValue>,}#[cfg(feature = "v1")]-#[derive(Clone, Debug)]+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]pub enum ExternalVaultDetails {ExternalVaultEnabled(ExternalVaultConnectorDetails),Skip,@@ -592,7 +595,7 @@ pub enum ProfileUpdate {}#[cfg(feature = "v2")]-#[derive(Clone, Debug)]+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]pub struct Profile {id: common_utils::id_type::ProfileId,pub merchant_id: common_utils::id_type::MerchantId,@@ -617,6 +620,7 @@ pub struct Profile {pub use_billing_as_payment_method_billing: Option<bool>,pub collect_shipping_details_from_wallet_connector: Option<bool>,pub collect_billing_details_from_wallet_connector: Option<bool>,+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,pub always_collect_billing_details_from_wallet_connector: Option<bool>,pub always_collect_shipping_details_from_wallet_connector: Option<bool>,@@ -637,6 +641,7 @@ pub struct Profile {Option<common_types::payments::AuthenticationConnectorAccountMap>,pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,pub card_testing_guard_config: Option<CardTestingGuardConfig>,+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub card_testing_secret_key: OptionalEncryptableName,pub is_clear_pan_retries_enabled: bool,pub is_debit_routing_enabled: bool,diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rsindex cbaee72045..fb1b2bae99 100644--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs@@ -36,11 +36,12 @@ use crate::{};#[cfg(feature = "v1")]-#[derive(Clone, Debug, router_derive::ToEncryption)]+#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize, serde::Deserialize)]pub struct MerchantConnectorAccount {pub merchant_id: id_type::MerchantId,pub connector_name: String,#[encrypt]+ #[serde(with = "common_utils::crypto::encryptable_exact")]pub connector_account_details: Encryptable<Secret<Value>>,pub test_mode: Option<bool>,pub disabled: Option<bool>,@@ -61,8 +62,10 @@ pub struct MerchantConnectorAccount {pub pm_auth_config: Option<pii::SecretSerdeValue>,pub status: enums::ConnectorStatus,#[encrypt]+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,#[encrypt]+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,pub version: common_enums::ApiVersion,pub connector_webhook_registration_details: Option<Value>,@@ -228,12 +231,13 @@ impl MerchantConnectorAccountTypeDetails {}#[cfg(feature = "v2")]-#[derive(Clone, Debug, router_derive::ToEncryption)]+#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize, serde::Deserialize)]pub struct MerchantConnectorAccount {pub id: id_type::MerchantConnectorAccountId,pub merchant_id: id_type::MerchantId,pub connector_name: common_enums::connector_enums::Connector,#[encrypt]+ #[serde(with = "common_utils::crypto::encryptable_exact")]pub connector_account_details: Encryptable<Secret<Value>>,pub disabled: Option<bool>,pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,@@ -249,8 +253,10 @@ pub struct MerchantConnectorAccount {pub pm_auth_config: Option<pii::SecretSerdeValue>,pub status: enums::ConnectorStatus,#[encrypt]+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,#[encrypt]+ #[serde(with = "common_utils::crypto::encryptable_exact::optional")]pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,pub version: common_enums::ApiVersion,pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,@@ -348,13 +354,13 @@ pub struct PaymentMethodsEnabledForConnector {}#[cfg(feature = "v2")]-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct MerchantConnectorAccountFeatureMetadata {pub revenue_recovery: Option<RevenueRecoveryMetadata>,}#[cfg(feature = "v2")]-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct RevenueRecoveryMetadata {pub max_retry_count: u16,pub billing_connector_retry_threshold: u16,@@ -367,7 +373,7 @@ pub struct ExternalVaultConnectorMetadata {pub certificate: Secret<String>,}#[cfg(feature = "v2")]-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct AccountReferenceMap {pub recovery_to_billing: HashMap<id_type::MerchantConnectorAccountId, String>,pub billing_to_recovery: HashMap<String, id_type::MerchantConnectorAccountId>,diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.tomlindex 3a36cbe45a..cef7142fee 100644--- a/crates/redis_interface/Cargo.toml+++ b/crates/redis_interface/Cargo.toml@@ -9,8 +9,8 @@ license.workspace = true[features]default = ["redis-rs"]-fred = ["dep:fred"]-redis-rs = ["dep:redis"]+fred = ["dep:fred", "deja?/fred"]+redis-rs = ["dep:redis", "deja?/redis-rs"]multitenancy_fallback = []deja = ["common_utils/deja", "dep:deja", "dep:serde_json"]metrics = ["dep:router_env"]@@ -35,7 +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 = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false, features = ["error-stack"] }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false, features = ["error-stack"] }router_env = { version = "0.1.0", path = "../router_env", optional = true }[dev-dependencies]diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rsindex eb23d7df44..fc6844a386 100644--- a/crates/redis_interface/src/module/fred/commands.rs+++ b/crates/redis_interface/src/module/fred/commands.rs@@ -11,6 +11,11 @@ use common_utils::{ext_traits::{AsyncExt, ByteSliceExt, Encode, StringExt},fp_utils,};+// Deja: raw redis replies are captured as `deja::value::RedisWireValue`, the+// one canonical serde-native wire type; the client conversions live in the+// deja crate next to the type (feature `fred` on the deja dependency).+#[cfg(feature = "deja")]+use deja::value::RedisWireValue;use error_stack::{report, ResultExt};use fred::{interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface},@@ -31,76 +36,6 @@ use crate::{},};-// Deja: serde-native proxy mirror of `fred::types::RedisValue`.-//-// The concrete proxy lets replay substitute generic Redis reads without adding-// serde bounds to public `FromRedis` APIs.-#[cfg(feature = "deja")]-#[derive(serde::Serialize, serde::Deserialize)]-enum DejaRedisValue {- Null,- Boolean(bool),- Integer(i64),- Double(f64),- String(String),- Bytes(Vec<u8>),- Array(Vec<Self>),- Map(Vec<(Self, Self)>),- Queued,-}--#[cfg(feature = "deja")]-impl From<RedisValue> for DejaRedisValue {- fn from(v: RedisValue) -> Self {- use fred::types::RedisValue as R;- match v {- R::Null => Self::Null,- R::Boolean(b) => Self::Boolean(b),- R::Integer(i) => Self::Integer(i),- R::Double(d) => Self::Double(d),- R::String(s) => Self::String(s.to_string()),- R::Bytes(b) => Self::Bytes(b.to_vec()),- R::Queued => Self::Queued,- R::Array(a) => Self::Array(a.into_iter().map(Self::from).collect()),- R::Map(m) => Self::Map(- m.inner()- .into_iter()- .map(|(k, val)| (Self::from(R::from(k)), Self::from(val)))- .collect(),- ),- }- }-}--#[cfg(feature = "deja")]-impl TryFrom<DejaRedisValue> for RedisValue {- type Error = fred::error::RedisError;-- fn try_from(v: DejaRedisValue) -> Result<Self, Self::Error> {- match v {- DejaRedisValue::Null => Ok(Self::Null),- DejaRedisValue::Boolean(b) => Ok(Self::Boolean(b)),- DejaRedisValue::Integer(i) => Ok(Self::Integer(i)),- DejaRedisValue::Double(d) => Ok(Self::Double(d)),- DejaRedisValue::String(s) => Ok(Self::String(s.into())),- DejaRedisValue::Bytes(b) => Ok(Self::Bytes(b.into())),- DejaRedisValue::Queued => Ok(Self::Queued),- DejaRedisValue::Array(a) => Ok(Self::Array(- a.into_iter()- .map(Self::try_from)- .collect::<Result<Vec<_>, _>>()?,- )),- DejaRedisValue::Map(m) => {- let pairs = m- .into_iter()- .map(|(k, val)| Ok((Self::try_from(k)?, Self::try_from(val)?)))- .collect::<Result<Vec<_>, Self::Error>>()?;- pairs.try_into().map(Self::Map)- }- }- }-}-impl super::RedisConnectionWithContext {/// Prefix `key` with the tenant key prefix of the underlying pool.pub fn add_prefix(&self, key: &str) -> String {@@ -312,15 +247,15 @@ impl super::RedisConnectionWithContext {// Deja hermetic boundary for GET.//// The boundary lives on this inner method, which fetches the RAW redis reply- // (`fred::types::RedisValue`) and mirrors it into the serde-native- // `DejaRedisValue`. Because the recorded/replayed type is concrete and+ // (`fred::types::RedisValue`) and converts it into the serde-native+ // `RedisWireValue`. Because the recorded/replayed type is concrete and// serde-native, the typed `ResultCodec` works without leaking a serde bound// onto the public `get_key<V>`.#[cfg(feature = "deja")]#[instrument(level = "DEBUG", skip(self))]#[deja::redis(operation = "get_key",- codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ codec = deja::codec::ResultCodec::<RedisWireValue, errors::RedisError>,state_read = key.tenant_aware_key(&self.redis_conn),args = {serde_json::json!({@@ -332,7 +267,7 @@ impl super::RedisConnectionWithContext {async fn get_key_raw(&self,key: &RedisKey,- ) -> CustomResult<DejaRedisValue, errors::RedisError> {+ ) -> CustomResult<RedisWireValue, errors::RedisError> {match track_redis_call(self.request_id.as_deref(),self.redis_conn.event_emitter.as_ref(),@@ -344,7 +279,7 @@ impl super::RedisConnectionWithContext {.await.change_context(errors::RedisError::GetFailed){- Ok(v) => Ok(DejaRedisValue::from(v)),+ Ok(v) => Ok(v.into()),Err(_err) => {#[cfg(not(feature = "multitenancy_fallback"))]{@@ -363,7 +298,7 @@ impl super::RedisConnectionWithContext {).await.change_context(errors::RedisError::GetFailed)- .map(DejaRedisValue::from)+ .map(RedisWireValue::from)}}}@@ -1267,8 +1202,8 @@ impl super::RedisConnectionWithContext {}// Deja hermetic boundary for HGET — same shape as `get_key_raw`: the boundary- // lives on this inner method which fetches the RAW reply and mirrors it into- // the serde-native `DejaRedisValue`, so the typed `ResultCodec` substitutes the field read+ // lives on this inner method which fetches the RAW reply and converts it into+ // the serde-native `RedisWireValue`, so the typed `ResultCodec` substitutes the field read// WITHOUT leaking a serde bound onto the public `get_hash_field<V>`. A// record-only `result={"ok":bool}` capture would record NO value, leaving// replay nothing to reconstruct `V` from — the read would fall through to@@ -1277,7 +1212,7 @@ impl super::RedisConnectionWithContext {#[instrument(level = "DEBUG", skip(self))]#[deja::redis(operation = "get_hash_field",- codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ codec = deja::codec::ResultCodec::<RedisWireValue, errors::RedisError>,state_read = format!("{}:{}", key.tenant_aware_key(&self.redis_conn), field),args = {serde_json::json!({@@ -1291,7 +1226,7 @@ impl super::RedisConnectionWithContext {&self,key: &RedisKey,field: &str,- ) -> CustomResult<DejaRedisValue, errors::RedisError> {+ ) -> CustomResult<RedisWireValue, errors::RedisError> {match track_redis_call(self.request_id.as_deref(),self.redis_conn.event_emitter.as_ref(),@@ -1303,7 +1238,7 @@ impl super::RedisConnectionWithContext {.await.change_context(errors::RedisError::GetHashFieldFailed){- Ok(v) => Ok(DejaRedisValue::from(v)),+ Ok(v) => Ok(v.into()),Err(_err) => {#[cfg(feature = "multitenancy_fallback")]{@@ -1318,7 +1253,7 @@ impl super::RedisConnectionWithContext {).await.change_context(errors::RedisError::GetHashFieldFailed)- .map(DejaRedisValue::from)+ .map(RedisWireValue::from)}#[cfg(not(feature = "multitenancy_fallback"))]@@ -1389,7 +1324,7 @@ impl super::RedisConnectionWithContext {#[instrument(level = "DEBUG", skip(self))]#[deja::redis(operation = "get_hash_fields",- codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ codec = deja::codec::ResultCodec::<RedisWireValue, errors::RedisError>,state_read = key.tenant_aware_key(&self.redis_conn),args = {serde_json::json!({@@ -1401,7 +1336,7 @@ impl super::RedisConnectionWithContext {async fn get_hash_fields_raw(&self,key: &RedisKey,- ) -> CustomResult<DejaRedisValue, errors::RedisError> {+ ) -> CustomResult<RedisWireValue, errors::RedisError> {match track_redis_call(self.request_id.as_deref(),self.redis_conn.event_emitter.as_ref(),@@ -1413,7 +1348,7 @@ impl super::RedisConnectionWithContext {.await.change_context(errors::RedisError::GetHashFieldFailed){- Ok(v) => Ok(DejaRedisValue::from(v)),+ Ok(v) => Ok(v.into()),Err(_err) => {#[cfg(feature = "multitenancy_fallback")]{@@ -1427,7 +1362,7 @@ impl super::RedisConnectionWithContext {).await.change_context(errors::RedisError::GetHashFieldFailed)- .map(DejaRedisValue::from)+ .map(RedisWireValue::from)}#[cfg(not(feature = "multitenancy_fallback"))]diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rsindex 0653b07e2e..3e05a03bc2 100644--- a/crates/redis_interface/src/module/redis_rs/commands.rs+++ b/crates/redis_interface/src/module/redis_rs/commands.rs@@ -11,6 +11,11 @@ use common_utils::{ext_traits::{ByteSliceExt, Encode, StringExt},fp_utils,};+// Deja: raw redis replies are captured as `deja::value::RedisWireValue`, the+// one canonical serde-native wire type; the client conversions live in the+// deja crate next to the type (feature `redis-rs` on the deja dependency).+#[cfg(feature = "deja")]+use deja::value::RedisWireValue;use error_stack::{report, ResultExt};use redis::{streams::StreamReadOptions, AsyncCommands, ExistenceCheck, FromRedisValue, SetExpiry,@@ -32,172 +37,6 @@ use crate::{},};-#[cfg(feature = "deja")]-#[derive(serde::Serialize, serde::Deserialize)]-enum DejaRedisValue {- Null,- Int(i64),- BulkString(Vec<u8>),- Array(Vec<Self>),- SimpleString(String),- Okay,- Map(Vec<(Self, Self)>),- Attribute {- data: Box<Self>,- attributes: Vec<(Self, Self)>,- },- Set(Vec<Self>),- Double(f64),- Boolean(bool),- VerbatimString {- format: String,- text: String,- },- Push {- kind: String,- data: Vec<Self>,- },- UnsupportedSuccessfulValue {- variant: String,- },-}--#[cfg(feature = "deja")]-impl From<redis::Value> for DejaRedisValue {- fn from(value: redis::Value) -> Self {- match value {- redis::Value::Nil => Self::Null,- redis::Value::Int(value) => Self::Int(value),- redis::Value::BulkString(value) => Self::BulkString(value),- redis::Value::Array(values) => {- Self::Array(values.into_iter().map(Self::from).collect())- }- redis::Value::SimpleString(value) => Self::SimpleString(value),- redis::Value::Okay => Self::Okay,- redis::Value::Map(values) => Self::Map(- values- .into_iter()- .map(|(key, value)| (Self::from(key), Self::from(value)))- .collect(),- ),- redis::Value::Attribute { data, attributes } => Self::Attribute {- data: Box::new(Self::from(*data)),- attributes: attributes- .into_iter()- .map(|(key, value)| (Self::from(key), Self::from(value)))- .collect(),- },- redis::Value::Set(values) => Self::Set(values.into_iter().map(Self::from).collect()),- redis::Value::Double(value) => Self::Double(value),- redis::Value::Boolean(value) => Self::Boolean(value),- redis::Value::VerbatimString { format, text } => Self::VerbatimString {- format: format.to_string(),- text,- },- redis::Value::Push { kind, data } => Self::Push {- kind: kind.to_string(),- data: data.into_iter().map(Self::from).collect(),- },- redis::Value::BigNumber(_) => Self::UnsupportedSuccessfulValue {- variant: "BigNumber".to_string(),- },- redis::Value::ServerError(error) => Self::UnsupportedSuccessfulValue {- variant: match error.details() {- Some(details) => format!("ServerError({}: {details})", error.code()),- None => format!("ServerError({})", error.code()),- },- },- _ => Self::UnsupportedSuccessfulValue {- variant: "unknown non-exhaustive redis::Value variant".to_string(),- },- }- }-}--#[cfg(feature = "deja")]-impl DejaRedisValue {- fn into_supported_redis_value(self) -> Result<redis::Value, redis::RedisError> {- match self {- Self::Null => Ok(redis::Value::Nil),- Self::Int(value) => Ok(redis::Value::Int(value)),- Self::BulkString(value) => Ok(redis::Value::BulkString(value)),- Self::Array(values) => Ok(redis::Value::Array(- values- .into_iter()- .map(Self::into_supported_redis_value)- .collect::<Result<Vec<_>, _>>()?,- )),- Self::SimpleString(value) => Ok(redis::Value::SimpleString(value)),- Self::Okay => Ok(redis::Value::Okay),- Self::Map(values) => Ok(redis::Value::Map(- values- .into_iter()- .map(|(key, value)| {- Ok((- key.into_supported_redis_value()?,- value.into_supported_redis_value()?,- ))- })- .collect::<Result<Vec<_>, redis::RedisError>>()?,- )),- Self::Attribute { data, attributes } => Ok(redis::Value::Attribute {- data: Box::new(data.into_supported_redis_value()?),- attributes: attributes- .into_iter()- .map(|(key, value)| {- Ok((- key.into_supported_redis_value()?,- value.into_supported_redis_value()?,- ))- })- .collect::<Result<Vec<_>, redis::RedisError>>()?,- }),- Self::Set(values) => Ok(redis::Value::Set(- values- .into_iter()- .map(Self::into_supported_redis_value)- .collect::<Result<Vec<_>, _>>()?,- )),- Self::Double(value) => Ok(redis::Value::Double(value)),- Self::Boolean(value) => Ok(redis::Value::Boolean(value)),- Self::VerbatimString { format, text } => Ok(redis::Value::VerbatimString {- format: match format.as_str() {- "mkd" => redis::VerbatimFormat::Markdown,- "txt" => redis::VerbatimFormat::Text,- other => redis::VerbatimFormat::Unknown(other.to_string()),- },- text,- }),- Self::Push { kind, data } => Ok(redis::Value::Push {- kind: match kind.as_str() {- "disconnection" => redis::PushKind::Disconnection,- "invalidate" => redis::PushKind::Invalidate,- "message" => redis::PushKind::Message,- "pmessage" => redis::PushKind::PMessage,- "smessage" => redis::PushKind::SMessage,- "unsubscribe" => redis::PushKind::Unsubscribe,- "punsubscribe" => redis::PushKind::PUnsubscribe,- "sunsubscribe" => redis::PushKind::SUnsubscribe,- "subscribe" => redis::PushKind::Subscribe,- "psubscribe" => redis::PushKind::PSubscribe,- "ssubscribe" => redis::PushKind::SSubscribe,- other => redis::PushKind::Other(other.to_string()),- },- data: data- .into_iter()- .map(Self::into_supported_redis_value)- .collect::<Result<Vec<_>, _>>()?,- }),- Self::UnsupportedSuccessfulValue { variant } => Err((- redis::ErrorKind::UnexpectedReturnType,- "unsupported Redis value variant recorded by Deja replay",- variant,- )- .into()),- }- }-}-impl super::RedisConnectionWithContext {/// Prefix `key` with the tenant key prefix of the underlying pool.pub fn add_prefix(&self, key: &str) -> String {@@ -388,7 +227,7 @@ impl super::RedisConnectionWithContext {#[instrument(level = "DEBUG", skip(self))]#[deja::redis(operation = "get_key",- codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ codec = deja::codec::ResultCodec::<RedisWireValue, errors::RedisError>,state_read = key.tenant_aware_key(&self.redis_conn),args = {serde_json::json!({@@ -400,7 +239,7 @@ impl super::RedisConnectionWithContext {async fn get_key_raw(&self,key: &RedisKey,- ) -> CustomResult<DejaRedisValue, errors::RedisError> {+ ) -> CustomResult<RedisWireValue, errors::RedisError> {let mut conn = self.redis_conn.pool.clone();match track_redis_call(self.request_id.as_deref(),@@ -411,7 +250,7 @@ impl super::RedisConnectionWithContext {.await.change_context(errors::RedisError::GetFailed){- Ok(value) => Ok(DejaRedisValue::from(value)),+ Ok(value) => Ok(value.into()),Err(_err) => {#[cfg(not(feature = "multitenancy_fallback"))]{@@ -427,7 +266,7 @@ impl super::RedisConnectionWithContext {conn.get::<_, redis::Value>(key.tenant_unaware_key(&self.redis_conn)),).await- .map(DejaRedisValue::from)+ .map(RedisWireValue::from).change_context(errors::RedisError::GetFailed)}}@@ -441,11 +280,13 @@ impl super::RedisConnectionWithContext {{#[cfg(feature = "deja")]{- let raw_value = self- .get_key_raw(key)- .await?- .into_supported_redis_value()- .map_err(|err| report!(err).change_context(errors::RedisError::GetFailed))?;+ let raw_value: redis::Value =+ self.get_key_raw(key)+ .await?+ .try_into()+ .map_err(|err: redis::RedisError| {+ report!(err).change_context(errors::RedisError::GetFailed)+ })?;return V::from_redis_value(raw_value).map_err(|err| report!(err).change_context(errors::RedisError::GetFailed));}diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 4feb36f96e..9ff458a6ec 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -293,8 +293,8 @@ common_utils = { version = "0.1.0", path = "../common_utils", features = ["keymanager",] }common_types = { version = "0.1.0", path = "../common_types" }-deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }-deja-core = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true }connector_configs = { version = "0.1.0", path = "../connector_configs" }currency_conversion = { version = "0.1.0", path = "../currency_conversion" }diesel_models = { version = "0.1.0", path = "../diesel_models", features = [@@ -336,6 +336,7 @@ rand = "0.8.5"serial_test = "3.2.0"time = { version = "0.3.41", features = ["macros"] }tokio = "1.48.0"+tracing-subscriber = { version = "0.3.19", default-features = false, features = ["registry"] }wiremock = "0.6.3"# First party dev-dependenciesdiff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rsindex 8b9df53c4d..7d27d74f7c 100644--- a/crates/router/src/bin/router.rs+++ b/crates/router/src/bin/router.rs@@ -61,6 +61,22 @@ async fn main() -> ApplicationResult<()> {"deja runtime hook initialized");+ // Record mode fails open to a disabled hook so a broken recorder never+ // takes down the router; make the downgrade loud instead of silent.+ #[cfg(feature = "deja")]+ if matches!(conf.deja.mode, router::configs::settings::DejaMode::Record)+ && deja_install_report.mode != "record"+ {+ router_env::tracing::error!(+ target: "deja",+ configured_mode = "record",+ installed_mode = deja_install_report.mode,+ detail = ?deja_install_report.detail,+ "deja is configured to record but the recording hook did not install; \+ this process will not record anything"+ );+ }+// Spawn a thread for collecting metrics at fixed intervalsmetrics::bg_metrics_collector::spawn_metrics_collector(conf.log.telemetry.bg_metrics_collection_interval_in_secs,diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rsindex 582ca09bf6..7643911867 100644--- a/crates/router/src/connection.rs+++ b/crates/router/src/connection.rs@@ -1,13 +1,13 @@use bb8::PooledConnection;-use diesel::PgConnection;+use diesel_models::DejaPgConnection;use error_stack::ResultExt;use storage_impl::errors as storage_errors;use crate::errors;-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;+pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;-pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;+pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;// Deja replay (R1): the minimal replay DB routing hook. On a just-leased pg// connection during replay, route it to the active correlation's schema so@@ -20,7 +20,7 @@ pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;// built by the library (`deja::replay_search_path_sql_for`).#[cfg(feature = "deja")]async fn deja_route_replay_schema<T: storage_impl::DatabaseStore>(- conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,store: &T,) {use async_bb8_diesel::AsyncConnection;@@ -38,7 +38,7 @@ async fn deja_route_replay_schema<T: storage_impl::DatabaseStore>(pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(store: &T,) -> errors::CustomResult<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,storage_errors::StorageError,> {// If only OLAP is enabled get replica pool.@@ -70,7 +70,7 @@ pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(store: &T,) -> errors::CustomResult<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,storage_errors::StorageError,> {// If only OLAP is enabled get replica pool.@@ -101,7 +101,7 @@ pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(store: &T,) -> errors::CustomResult<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,storage_errors::StorageError,> {// Since all writes should happen to master DB only choose master DB.@@ -120,7 +120,7 @@ pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>(store: &T,) -> errors::CustomResult<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,storage_errors::StorageError,> {// Since all writes should happen to master DB only choose master DB.diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 24e1ea8bc5..f19b19a602 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -1,3 +1,5 @@+#[cfg(any(feature = "v1", all(test, feature = "deja")))]+use std::future::Future;use std::{collections::HashMap, ops::Deref};#[cfg(feature = "v1")]@@ -71,6 +73,20 @@ use crate::{utils,};+#[cfg(any(feature = "v1", all(test, feature = "deja")))]+fn spawn_save_payment_method<F>(future: F)+where+ F: Future<Output = ()> + Send + 'static,+{+ // Under `deja`, the detached tail must keep the request's correlation and+ // sampling decision past ingress teardown; `deja::spawn_fork` carries both.+ #[cfg(feature = "deja")]+ deja::spawn_fork(future);++ #[cfg(not(feature = "deja"))]+ let _task_handle = tokio::spawn(future.in_current_span());+}+#[cfg(feature = "v1")]async fn prepare_pm_update_from_psync(state: &SessionState,@@ -814,78 +830,76 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorlet cloned_platform = platform.clone();let async_dimension = dimensions.clone();logger::info!("Call to save_payment_method in locker");- let _task_handle = tokio::spawn(- async move {- logger::info!("Starting async call to save_payment_method in locker");-- let result = Box::pin(tokenization::save_payment_method(- &state,- connector_name,- save_payment_data,- customer_id,- &cloned_platform,- payment_method_type,- billing_name,- payment_method_billing_address.as_ref(),- &business_profile,- connector_mandate_reference_id,- merchant_connector_id.clone(),- vault_operation.clone(),- payment_method_info.clone(),- payment_method_token.clone(),- customer_details.clone(),- &async_dimension,- ))- .await;+ let save_payment_method_future = async move {+ logger::info!("Starting async call to save_payment_method in locker");++ let result = Box::pin(tokenization::save_payment_method(+ &state,+ connector_name,+ save_payment_data,+ customer_id,+ &cloned_platform,+ payment_method_type,+ billing_name,+ payment_method_billing_address.as_ref(),+ &business_profile,+ connector_mandate_reference_id,+ merchant_connector_id.clone(),+ vault_operation.clone(),+ payment_method_info.clone(),+ payment_method_token.clone(),+ customer_details.clone(),+ &async_dimension,+ ))+ .await;- if let Err(err) = result {- logger::error!("Asynchronously saving card in locker failed : {:?}", err);- } else if let Ok(tokenization::SavePaymentMethodDataResponse {- payment_method_id,- ..- }) = result- {- let payment_attempt_update =- storage::PaymentAttemptUpdate::PaymentMethodDetailsUpdate {- payment_method_id,- updated_by: cloned_platform- .get_processor()- .get_account()- .storage_scheme- .clone()- .to_string(),- };+ if let Err(err) = result {+ logger::error!("Asynchronously saving card in locker failed : {:?}", err);+ } else if let Ok(tokenization::SavePaymentMethodDataResponse {+ payment_method_id,+ ..+ }) = result+ {+ let payment_attempt_update =+ storage::PaymentAttemptUpdate::PaymentMethodDetailsUpdate {+ payment_method_id,+ updated_by: cloned_platform+ .get_processor()+ .get_account()+ .storage_scheme+ .clone()+ .to_string(),+ };- #[cfg(feature = "v1")]- let respond = state- .store- .update_payment_attempt_with_attempt_id(- payment_attempt,- payment_attempt_update,- cloned_platform.get_processor().get_account().storage_scheme,- cloned_platform.get_processor().get_key_store(),- )- .await;+ #[cfg(feature = "v1")]+ let respond = state+ .store+ .update_payment_attempt_with_attempt_id(+ payment_attempt,+ payment_attempt_update,+ cloned_platform.get_processor().get_account().storage_scheme,+ cloned_platform.get_processor().get_key_store(),+ )+ .await;- #[cfg(feature = "v2")]- let respond = state- .store- .update_payment_attempt_with_attempt_id(- &(&state).into(),- &key_store.clone(),- payment_attempt,- payment_attempt_update,- cloned_platform.get_processor().get_account().storage_scheme,- )- .await;+ #[cfg(feature = "v2")]+ let respond = state+ .store+ .update_payment_attempt_with_attempt_id(+ &(&state).into(),+ &key_store.clone(),+ payment_attempt,+ payment_attempt_update,+ cloned_platform.get_processor().get_account().storage_scheme,+ )+ .await;- if let Err(err) = respond {- logger::error!("Error updating payment attempt: {:?}", err);- };- }+ if let Err(err) = respond {+ logger::error!("Error updating payment attempt: {:?}", err);+ };}- .in_current_span(),- );+ };+ spawn_save_payment_method(save_payment_method_future);Ok(())}}diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex ca608125cb..3cb7ce3c38 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -80,6 +80,7 @@ use crate::{SessionState,};+#[derive(serde::Serialize, serde::Deserialize)]pub enum CachedAlgorithm {Single(Box<routing_types::RoutableConnectorChoice>),Priority(Vec<routing_types::RoutableConnectorChoice>),diff --git a/crates/router/src/deja_boot.rs b/crates/router/src/deja_boot.rsindex f3b797beb2..ae0adbbe99 100644--- a/crates/router/src/deja_boot.rs+++ b/crates/router/src/deja_boot.rs@@ -25,19 +25,99 @@ fn non_empty(value: Option<&str>) -> Option<&str> {value.map(str::trim).filter(|value| !value.is_empty())}-fn fallback_run_id() -> String {- let now_ns = std::time::SystemTime::now()+/// The id a recording is known by when nothing configured one:+/// `rec-<short sha>-<MMDDhhmm>-<instance>`, e.g. `rec-dcb9f9e-07291352-a3`.+/// Without a known revision it falls back to the bare-timestamp form (with a+/// warning) rather than claiming a provenance it does not have.+fn fallback_run_id(settings: &DejaSettings) -> String {+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)- .unwrap_or(std::time::Duration::ZERO)- .as_nanos();- format!("run-{now_ns}")+ .unwrap_or(std::time::Duration::ZERO);+ match resolved_code_sha(settings) {+ Some(sha) => format!(+ "rec-{}-{}-{}",+ short_revision(&sha),+ recording_stamp(now.as_secs()),+ instance_discriminator(&resolved_instance_id(settings)),+ ),+ None => {+ router_env::logger::warn!(+ "deja: recording without a code revision — its id will carry no provenance. \+ Set deja.identity.code_sha, or build with VERGEN_GIT_SHA."+ );+ format!("run-{}", now.as_nanos())+ }+ }+}++/// A git sha shortened to the length git itself uses for a short sha.+fn short_revision(sha: &str) -> String {+ sha.chars()+ .filter(char::is_ascii_alphanumeric)+ .take(7)+ .collect::<String>()+ .to_ascii_lowercase()+}++/// `MMDDhhmm` UTC; the instance discriminator separates recorders that start+/// in the same minute.+fn recording_stamp(unix_secs: u64) -> String {+ let (month, day) = civil_month_day(unix_secs / 86_400);+ let today = unix_secs % 86_400;+ format!(+ "{month:02}{day:02}{:02}{:02}",+ today / 3600,+ (today % 3600) / 60+ )+}++/// Two characters standing for the instance, so two pods that start in the+/// same minute do not share a recording id.+fn instance_discriminator(instance_id: &str) -> String {+ // FNV-1a, so the same pod is always the same two characters.+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ for byte in instance_id.as_bytes() {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x100_0000_01b3);+ }+ const ALPHABET: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";+ // `n % 36` always indexes the 36-byte alphabet; spelled out instead of+ // asserted because a boot-time naming helper must not panic.+ let pick = |n: u64| {+ usize::try_from(n % 36)+ .ok()+ .and_then(|i| ALPHABET.get(i))+ .map_or('0', |byte| char::from(*byte))+ };+ let a = pick(hash);+ let b = pick(hash / 36);+ format!("{a}{b}")+}++/// Days since the epoch to (month, day), civil-from-days.+fn civil_month_day(days_since_epoch: u64) -> (i64, i64) {+ // An impossible clock degrades to a valid date instead of panicking.+ let Some(z) = i64::try_from(days_since_epoch)+ .ok()+ .and_then(|days| days.checked_add(719_468))+ else {+ return (1, 1);+ };+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ (m, d)}fn configured_run_id(settings: &DejaSettings) -> String {settings.effective_run_id().map(str::to_owned)- .unwrap_or_else(fallback_run_id)+ .unwrap_or_else(|| fallback_run_id(settings))}fn configured_value(value: Option<&str>) -> Option<String> {@@ -67,7 +147,7 @@ fn resolved_code_sha(settings: &DejaSettings) -> Option<String> {configured_value(settings.identity.code_sha.as_deref()).or_else(|| env_value_named(&settings.identity.git_sha_env)).or_else(|| option_env!("VERGEN_GIT_SHA").map(str::to_owned))- .or_else(|| Some("unknown".to_owned()))+ // No "unknown" placeholder: absence is a fact worth being able to observe.}fn writer_config(settings: &DejaSettings) -> deja::WriterConfig {diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex 0e7950b417..34c57e142e 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -62,8 +62,17 @@ impl router_env::request_id::RequestRecordingSampler for SuperpositionDejaRecord) -> router_env::request_id::RequestRecordingSamplerFuture<'_> {// No sampling source to consult: the configured failure default// decides, exactly as it does for lookup errors and timeouts below.+ // This is a process-lifetime condition, so it warns once.let failure_default = !self.fail_closed;if !self.superposition_enabled {+ static NO_SAMPLING_SOURCE: std::sync::Once = std::sync::Once::new();+ NO_SAMPLING_SOURCE.call_once(|| {+ router_env::logger::warn!(+ failure_default,+ "Deja recording sampler has no sampling source (Superposition is not \+ configured); every request resolves to the configured failure default"+ );+ });return Box::pin(async move { failure_default });}@@ -197,10 +206,21 @@ pub fn mk_app(let deja_recording_sampler: Option<std::sync::Arc<dyn router_env::request_id::RequestRecordingSampler>,> = matches!(state.conf.deja.mode, settings::DejaMode::Record).then(|| {+ // `validate()` is a configuration check, not a reachability one; it+ // catches a record-mode deployment with no sampling source at all.+ let superposition_enabled = state.conf.superposition.get_inner().validate().is_ok();+ if !superposition_enabled {+ router_env::logger::error!(+ fail_closed = state.conf.deja.sampler.fail_closed,+ "Deja is in record mode but Superposition is not configured; the recording \+ sampler has no policy to consult and every request will resolve to the \+ configured failure default"+ );+ }let sampler: std::sync::Arc<dyn router_env::request_id::RequestRecordingSampler> =std::sync::Arc::new(SuperpositionDejaRecordingSampler {superposition_service: state.superposition_service.clone(),- superposition_enabled: state.conf.superposition.get_inner().validate().is_ok(),+ superposition_enabled,record_key: state.conf.dejadiff --git a/crates/router/src/services/authentication/decision.rs b/crates/router/src/services/authentication/decision.rsindex e53f597709..f9fa34f004 100644--- a/crates/router/src/services/authentication/decision.rs+++ b/crates/router/src/services/authentication/decision.rs@@ -191,6 +191,10 @@ pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 {}}+/// Fire the decision-service call as detached background work; the task is+/// deliberately not awaited. Under `deja`, `spawn_fork` keeps the request's+/// correlation and sampling decision alive in the detached child, which a bare+/// `tokio::spawn` would lose.pub fn spawn_tracked_job<E, F>(future: F, request_type: &'static str)whereE: std::fmt::Debug,@@ -198,7 +202,8 @@ where{metrics::API_KEY_REQUEST_INITIATED.add(1, router_env::metric_attributes!(("type", request_type)));- tokio::spawn(async move {++ let tracked = async move {match future.await {Ok(_) => {metrics::API_KEY_REQUEST_COMPLETED@@ -208,5 +213,11 @@ whererouter_env::error!("Error in tracked job: {:?}", e);}}- });+ };++ #[cfg(feature = "deja")]+ deja::spawn_fork(tracked);++ #[cfg(not(feature = "deja"))]+ let _task_handle = tokio::spawn(tracked);}diff --git a/crates/router/src/services/encryption.rs b/crates/router/src/services/encryption.rsindex f600f91e7a..3bdafe47c0 100644--- a/crates/router/src/services/encryption.rs+++ b/crates/router/src/services/encryption.rs@@ -32,6 +32,29 @@ pub enum EncryptionAlgorithm {A256GCM,}+/// deja: josekit generates the CEK and AEAD IV inside `jwe::serialize_compact`+/// with no hook for the IV, so the whole JWE is the reproducible unit —+/// recording it keeps every downstream request body byte-identical on replay.+/// Instrumented here, the one function all call sites share. `public_key` is+/// deliberately not part of the identity (deployment config would reintroduce+/// lookup misses on environments whose keys differ from the recorder's).+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::services::encryption",+ operation = "encrypt_jwe",+ codec = ResultOkCodec,+ // The payload is a digest, never the bytes: the JWS arriving here+ // carries the cleartext card object base64-encoded, which must not+ // reach the tape. The digest is all the lookup needs.+ args = serde_json::json!({+ "algorithm": algorithm.as_ref(),+ "key_id": key_id,+ "payload_blake3": blake3::hash(payload).to_hex().as_str(),+ "payload_len": payload.len(),+ }),+ )+)]pub async fn encrypt_jwe(payload: &[u8],public_key: impl AsRef<[u8]>,diff --git a/crates/router/src/services/kafka/deja_record_sink.rs b/crates/router/src/services/kafka/deja_record_sink.rsindex 9dd219a6bb..cef484be56 100644--- a/crates/router/src/services/kafka/deja_record_sink.rs+++ b/crates/router/src/services/kafka/deja_record_sink.rs@@ -512,6 +512,7 @@ mod tests {parent_id: Some(3),causal_parent_ids: vec![1],sequence: 5,+ correlation_id: Some("c-123".to_string()),recording_run_id: Some("run-abc".to_string()),span_name: "payment.request".to_string(),target: "router".to_string(),diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rsindex 7030c48c35..5b87ce51e8 100644--- a/crates/router/src/types/domain/address.rs+++ b/crates/router/src/types/domain/address.rs@@ -11,7 +11,7 @@ use diesel_models::{address::AddressUpdateInternal, enums};use error_stack::ResultExt;use hyperswitch_masking::{PeekInterface, Secret, SwitchStrategy};use rustc_hash::FxHashMap;-use time::{OffsetDateTime, PrimitiveDateTime};+use time::PrimitiveDateTime;use super::{behaviour, types};@@ -335,7 +335,7 @@ impl From<AddressUpdate> for AddressUpdateInternal {last_name: last_name.map(Encryption::from),phone_number: phone_number.map(Encryption::from),country_code,- modified_at: date_time::convert_to_pdt(OffsetDateTime::now_utc()),+ modified_at: date_time::now(),updated_by,email: email.map(Encryption::from),origin_zip: origin_zip.map(Encryption::from),diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.tomlindex 2fa3478954..026c0623b7 100644--- a/crates/router_env/Cargo.toml+++ b/crates/router_env/Cargo.toml@@ -10,8 +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 = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }-deja-core = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true }error-stack = "0.4.1"gethostname = "0.4.3"# Optional (deja-only): types the captured request/response payloads as `Secret`diff --git a/crates/router_env/src/request_id.rs b/crates/router_env/src/request_id.rsindex c536b06509..a486826709 100644--- a/crates/router_env/src/request_id.rs+++ b/crates/router_env/src/request_id.rs@@ -618,6 +618,22 @@ pub struct RequestRecordingFacts {pub path: String,}+#[cfg(feature = "deja")]+fn instrument_http_incoming<F>(+ future: F,+ request_facts: &RequestRecordingFacts,+) -> impl Future<Output = F::Output>+where+ F: Future,+{+ future.instrument(tracing::info_span!(+ "deja::http_incoming",+ method = %request_facts.method,+ path = %request_facts.path,+ request_id = %request_facts.request_id,+ ))+}+/// Future returned by a Deja request recording sampler.#[cfg(feature = "deja")]pub type RequestRecordingSamplerFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;@@ -1035,7 +1051,20 @@ wherelet should_record_http_incoming = if boundary::process_is_record_mode() {let decision = match recording_sampler {Some(sampler) => sampler.should_record(request_facts.clone()).await,- None => true,+ // No sampler attached means no policy to consult:+ // record nothing, and warn once — this is a wiring+ // defect, not a per-request condition.+ None => {+ static MISSING_SAMPLER: std::sync::Once = std::sync::Once::new();+ MISSING_SAMPLER.call_once(|| {+ tracing::warn!(+ "Deja is in record mode but no recording sampler is attached; \+ skipping every request. Expect an empty tape until a sampler \+ is wired into the application builder."+ );+ });+ false+ }};deja::set_recording_decision(request_id.to_string(), decision);_decision_guard = Some(RecordingDecisionGuard(request_id.to_string()));@@ -1048,22 +1077,35 @@ wherelet (request, incoming_record) =boundary::capture_incoming_request(request, request_id.as_str()).await;let fut = service.call(request);- let request_span = tracing::info_span!(- "deja::http_incoming",- method = %request_facts.method,- path = %request_facts.path,- request_id = %request_id,- );- // Correlation comes from the ingress root span (CustomRootSpanBuilder- // stamps `request_id`) via DejaCorrelationLayer — no explicit scope needed.- let recorded_result = boundary::recorded_incoming(fut, incoming_record)- .instrument(request_span)- .await;+ // Correlation rides the shared ingress span, which stamps+ // `request_id` for DejaCorrelationLayer.+ let recorded_result = instrument_http_incoming(+ boundary::recorded_incoming(fut, incoming_record),+ &request_facts,+ )+ .await;let recorded = recorded_result?;recorded.map_body(|_head, body| EitherBody::left(body))} else {- // Correlation rides the ingress root span via DejaCorrelationLayer.- let response_result = service.call(request).await;+ // Correlation rides the shared ingress span via DejaCorrelationLayer.+ //+ // A Substitute boundary's fail-stop is a panic, and actix+ // has no per-request `catch_unwind` — uncontained it kills+ // the connection with no response. Catch only deja's own+ // fail-stop and turn it into a 5xx carrying its message;+ // any other panic is re-raised, and outside replay the+ // wrapper is a pure passthrough.+ let response_result = match instrument_http_incoming(+ deja::catch_fail_stop_async(service.call(request)),+ &request_facts,+ )+ .await+ {+ Ok(result) => result,+ Err(fail_stop) => Err(actix_web::error::ErrorInternalServerError(+ fail_stop.into_message(),+ )),+ };let response = response_result?;response.map_body(|_head, body| {EitherBody::right(boundary::RecordingBody::passthrough(body))diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.tomlindex 0c3daa7729..61a005e672 100644--- a/crates/storage_impl/Cargo.toml+++ b/crates/storage_impl/Cargo.toml@@ -29,7 +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 = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", 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/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rsindex 78c838c759..b9ddc8cb6f 100644--- a/crates/storage_impl/src/business_profile.rs+++ b/crates/storage_impl/src/business_profile.rs@@ -213,12 +213,12 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {#[cfg(feature = "accounts_cache")]{- cache::get_or_populate_in_memory(+ Box::pin(cache::get_or_populate_in_memory(self,&profile_cache_key(profile_id),fetch_func,&ACCOUNTS_CACHE,- )+ )).await?.convert(state,@@ -261,12 +261,12 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {#[cfg(feature = "accounts_cache")]{- cache::get_or_populate_in_memory(+ Box::pin(cache::get_or_populate_in_memory(self,&profile_cache_key(profile_id),fetch_func,&ACCOUNTS_CACHE,- )+ )).await?.convert(state,diff --git a/crates/storage_impl/src/connection.rs b/crates/storage_impl/src/connection.rsindex 50d7b759df..bc9dc2022f 100644--- a/crates/storage_impl/src/connection.rs+++ b/crates/storage_impl/src/connection.rs@@ -1,16 +1,16 @@use bb8::PooledConnection;use common_utils::errors;-use diesel::PgConnection;+use diesel_models::DejaPgConnection;use error_stack::ResultExt;-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;+pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;-pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;+pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;pub async fn pg_connection_read<T: crate::DatabaseStore>(store: &T,) -> errors::CustomResult<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,crate::errors::StorageError,> {// If only OLAP is enabled get replica pool.@@ -41,7 +41,7 @@ pub async fn pg_connection_read<T: crate::DatabaseStore>(pub async fn pg_connection_write<T: crate::DatabaseStore>(store: &T,) -> errors::CustomResult<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,crate::errors::StorageError,> {// Since all writes should happen to master DB only choose master DB.diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex b249f52db3..7069c9a766 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -739,7 +739,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_write(self).await?;- self.call_database_new(+ Box::pin(self.call_database_new(key_store,diesel_models::Customer::update_by_customer_id_merchant_id(&conn,@@ -747,7 +747,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {merchant_id.clone(),customer_update.foreign_into(),),- )+ )).await}@@ -876,8 +876,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {.construct_new().await.change_context(StorageError::EncryptionError)?;- self.call_database_new(key_store, customer_new.insert(&conn))- .await+ Box::pin(self.call_database_new(key_store, customer_new.insert(&conn))).await}#[cfg(feature = "v1")]@@ -907,14 +906,14 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_write(self).await?;- self.call_database_new(+ Box::pin(self.call_database_new(key_store,diesel_models::Customer::update_by_id(&conn,id.clone(),customer_update.foreign_into(),),- )+ )).await}diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rsindex cf4848a5a9..12c7c4cada 100644--- a/crates/storage_impl/src/database/store.rs+++ b/crates/storage_impl/src/database/store.rs@@ -4,7 +4,7 @@ use common_utils::{types::{keymanager, TenantConfig},DbConnectionParams,};-use diesel::PgConnection;+use diesel_models::DejaPgConnection;use error_stack::ResultExt;use crate::{@@ -12,8 +12,8 @@ use crate::{errors::{StorageError, StorageResult},};-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;-pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;+pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;+pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;#[async_trait::async_trait]pub trait DatabaseStore: Clone + Send + Sync {@@ -164,7 +164,7 @@ pub async fn diesel_make_pg_pool(test_transaction: bool,) -> StorageResult<PgPool> {let database_url = database.get_database_url(schema);- let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);+ let manager = async_bb8_diesel::ConnectionManager::<DejaPgConnection>::new(database_url);let mut pool = bb8::Pool::builder().max_size(database.max_pool_size).min_idle(Some(database.min_idle_pool_size))@@ -177,10 +177,44 @@ pub async fn diesel_make_pg_pool(pool = pool.connection_customizer(Box::new(TestTransaction));}- pool.build(manager)+ let pool = pool+ .build(manager).await.change_context(StorageError::InitializationError)- .attach_printable("Failed to create PostgreSQL connection pool")+ .attach_printable("Failed to create PostgreSQL connection pool")?;++ // Register row identity (primary-key columns) with deja from this+ // database's own catalog. Idempotent; on failure identity stays+ // unregistered, making recorded row keys absent rather than wrong.+ #[cfg(feature = "deja")]+ if !deja::runtime_mode_is_disabled() {+ use async_bb8_diesel::AsyncConnection;+ use diesel::RunQueryDsl;+ if let Ok(connection) = pool.get().await {+ let rows = connection+ .run(|conn| {+ diesel::sql_query(deja::TABLE_IDENTITY_SQL)+ .load::<deja::db::TableIdentityRow>(conn)+ .map(|rows| {+ rows.into_iter()+ .map(|row| (row.table_name, row.column_name))+ .collect::<Vec<(String, String)>>()+ })+ })+ .await;+ match rows {+ Ok(rows) => deja::db::register_table_identity_rows(rows),+ Err(error) => {+ router_env::logger::warn!(+ ?error,+ "deja: could not read row identity from the schema; recorded row keys will fall back to query fingerprints"+ );+ }+ }+ }+ }++ Ok(pool)}#[derive(Debug)]diff --git a/crates/storage_impl/src/invoice.rs b/crates/storage_impl/src/invoice.rsindex 61f667de13..36e5fe9256 100644--- a/crates/storage_impl/src/invoice.rs+++ b/crates/storage_impl/src/invoice.rs@@ -28,7 +28,7 @@ impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> {.await.change_context(StorageError::DecryptionError)?;let conn = connection::pg_connection_write(self).await?;- self.call_database(key_store, inv_new.insert(&conn)).await+ Box::pin(self.call_database(key_store, inv_new.insert(&conn))).await}#[instrument(skip_all)]diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rsindex 3b39058cf2..829065830d 100644--- a/crates/storage_impl/src/merchant_connector_account.rs+++ b/crates/storage_impl/src/merchant_connector_account.rs@@ -866,7 +866,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {#[cfg(feature = "accounts_cache")]{// Redact all caches as any of might be used because of backwards compatibility- cache::publish_and_redact_multiple(+ Box::pin(cache::publish_and_redact_multiple(self,[cache::CacheKind::Accounts(@@ -898,7 +898,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {),],update_call,- )+ )).await}@@ -948,7 +948,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {#[cfg(feature = "accounts_cache")]{// Redact all caches as any of might be used because of backwards compatibility- cache::publish_and_redact_multiple(+ Box::pin(cache::publish_and_redact_multiple(self,[cache::CacheKind::Accounts(@@ -975,7 +975,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {),],update_call,- )+ )).await}diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rsindex 1752ce0d4b..9b058a4ac6 100644--- a/crates/storage_impl/src/payments/payment_intent.rs+++ b/crates/storage_impl/src/payments/payment_intent.rs@@ -387,7 +387,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {let database_call = || async {let conn: bb8::PooledConnection<'_,- async_bb8_diesel::ConnectionManager<diesel::PgConnection>,+ async_bb8_diesel::ConnectionManager<diesel_models::DejaPgConnection>,> = pg_connection_read(self).await?;DieselPaymentIntent::find_by_global_id(&conn, id)diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rsindex 9963cb23a8..2aaf7065c8 100644--- a/crates/storage_impl/src/redis/cache.rs+++ b/crates/storage_impl/src/redis/cache.rs@@ -271,13 +271,46 @@ impl Cache {}}+ // Deja: recorded args-only for population accounting; the real moka insert+ // still runs on replay (`replay = Execute`).+ #[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "imc",+ component = "storage_impl::redis::cache",+ operation = "in_memory_push",+ replay = Execute,+ effect = Imc,+ codec = SerdeCodec,+ args = deja_in_memory_args(self.name, &key),+ )+ )]pub async fn push<T: Cacheable>(&self, key: CacheKey, val: T) {self.inner.insert(in_memory_cache_key(key), Arc::new(val)).await;}- pub async fn get_val<T: Clone + Cacheable>(&self, key: CacheKey) -> Option<T> {+ // Deja: the L1 seam, instrumented on the method itself so no call path can+ // bypass it. A recorded `Some(v)` substitutes on replay; a recorded `None`+ // re-triggers the caller's fallback. The serde bound is deliberately+ // unconditional: a type that cannot be captured cannot be cached.+ #[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "imc",+ component = "storage_impl::redis::cache",+ operation = "in_memory_get",+ replay = Substitute,+ effect = Imc,+ codec = SerdeCodec,+ args = deja_in_memory_args(self.name, &key),+ )+ )]+ pub async fn get_val<T>(&self, key: CacheKey) -> Option<T>+ where+ T: Clone + Cacheable + serde::Serialize + serde::de::DeserializeOwned,+ {let val = self.inner.get::<String>(&in_memory_cache_key(key)).await;// Add cache hit and cache miss metrics@@ -295,10 +328,36 @@ impl Cache {}/// Check if a key exists in cache+ #[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "imc",+ component = "storage_impl::redis::cache",+ operation = "in_memory_exists",+ replay = Substitute,+ effect = Imc,+ codec = SerdeCodec,+ args = deja_in_memory_args(self.name, &key),+ )+ )]pub async fn exists(&self, key: CacheKey) -> bool {self.inner.contains_key::<String>(&in_memory_cache_key(key))}+ // Deja: recorded args-only so a missed or extra invalidation shows up as a+ // call divergence; the real invalidation still runs on replay.+ #[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "imc",+ component = "storage_impl::redis::cache",+ operation = "in_memory_remove",+ replay = Execute,+ effect = Imc,+ codec = SerdeCodec,+ args = deja_in_memory_args(self.name, &key),+ )+ )]pub async fn remove(&self, key: CacheKey) {self.inner.invalidate::<String>(&in_memory_cache_key(key))@@ -372,31 +431,8 @@ where}}-/// Deja boundary for the in-memory (L1) cache lookup. Captures the `Option<T>`-/// outcome on record and Substitutes it per-correlation on replay: a recorded-/// `Some(v)` returns the value; a recorded `None` (absence) returns `None`, so-/// the caller re-runs the redis fallback — the same control flow as record. The-/// `cache` handle is not serialized (args = cache name + physical key); the-/// value round-trips through `SerdeCodec<Option<T>>`. NOT `fall_through_silent`:-/// a novel L1 read on replay is a real divergence, and falling through would-/// read the cross-correlation-shared moka — fail-stop is correct.-#[cfg(feature = "deja")]-#[deja::boundary(- boundary = "imc",- component = "storage_impl::redis::cache",- operation = "in_memory_get",- replay = Substitute,- effect = Imc,- codec = SerdeCodec,- args = deja_in_memory_args(cache.name, &cache_key),-)]-async fn deja_in_memory_get<T>(cache: &Cache, cache_key: CacheKey) -> Option<T>-where- T: Clone + Cacheable + serde::Serialize + serde::de::DeserializeOwned,-{- cache.get_val::<T>(cache_key).await-}-+/// Recorded args for the [`Cache`] boundaries: cache name + un-namespaced+/// physical key, so the args a replay computes match the recording's.#[cfg(feature = "deja")]fn deja_in_memory_args(cache_name: &str, key: &CacheKey) -> serde_json::Value {serde_json::json!({ "cache": cache_name, "key": String::from(key.clone()) })@@ -424,18 +460,6 @@ wherekey: key.to_string(),prefix: redis.redis_conn.key_prefix.clone(),};- // Deja L1 seam: the in-memory (moka) lookup is a process-global cache that- // spans correlations. Instrument the LOOKUP itself (not the surrounding- // populate) so its `Option` outcome is recorded per-correlation and- // Substituted on replay — a recorded `Some(v)` returns the value; a recorded- // `None` re-triggers the (separately instrumented) redis fallback below,- // identically on record and replay. Because the lookup returns BEFORE redis,- // L1 and L2 stay sequential (not nested) → no subsumed/orphan event. Record- // stays a pure observer (the real moka runs); replay never reads the shared- // moka, so cross-correlation contamination is impossible by construction.- #[cfg(feature = "deja")]- let cache_val = deja_in_memory_get::<T>(cache, cache_key).await;- #[cfg(not(feature = "deja"))]let cache_val = cache.get_val::<T>(cache_key).await;if let Some(val) = cache_val {Ok(val)diff --git a/crates/storage_impl/src/subscription.rs b/crates/storage_impl/src/subscription.rsindex f85b396c6a..4bdc3bf58c 100644--- a/crates/storage_impl/src/subscription.rs+++ b/crates/storage_impl/src/subscription.rs@@ -31,7 +31,7 @@ impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> {.await.change_context(StorageError::DecryptionError)?;let conn = connection::pg_connection_write(self).await?;- self.call_database(key_store, sub_new.insert(&conn)).await+ Box::pin(self.call_database(key_store, sub_new.insert(&conn))).await}#[instrument(skip_all)]async fn find_by_merchant_id_subscription_id(diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rsindex be0e0bacd0..5addbde2df 100644--- a/crates/storage_impl/src/utils.rs+++ b/crates/storage_impl/src/utils.rs@@ -1,5 +1,5 @@use bb8::PooledConnection;-use diesel::PgConnection;+use diesel_models::DejaPgConnection;use error_stack::ResultExt;use crate::{@@ -22,7 +22,7 @@ use crate::{#[cfg(feature = "deja")]#[allow(clippy::panic)]pub(crate) async fn deja_route_replay_schema<T: DatabaseStore>(- conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,store: &T,) {use async_bb8_diesel::AsyncConnection;@@ -129,7 +129,7 @@ fn deja_replay_route_warn_no_correlation() {pub async fn pg_connection_read<T: DatabaseStore>(store: &T,) -> error_stack::Result<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,StorageError,> {// If only OLAP is enabled get replica pool.@@ -160,7 +160,7 @@ pub async fn pg_connection_read<T: DatabaseStore>(pub async fn pg_connection_write<T: DatabaseStore>(store: &T,) -> error_stack::Result<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,StorageError,> {// Since all writes should happen to master DB only choose master DB.@@ -179,7 +179,7 @@ pub async fn pg_connection_write<T: DatabaseStore>(pub async fn pg_accounts_connection_read<T: DatabaseStore>(store: &T,) -> error_stack::Result<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,StorageError,> {// If only OLAP is enabled get replica pool.@@ -210,7 +210,7 @@ pub async fn pg_accounts_connection_read<T: DatabaseStore>(pub async fn pg_accounts_connection_write<T: DatabaseStore>(store: &T,) -> error_stack::Result<- PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,StorageError,> {// Since all writes should happen to master DB only choose master DB.diff --git a/scripts/seed_superposition.sh b/scripts/seed_superposition.shindex 71f1b205cc..c863d554d4 100755--- a/scripts/seed_superposition.sh+++ b/scripts/seed_superposition.sh@@ -209,14 +209,17 @@ done# Seed the Deja recording sampler: cohort dimension + override# ------------------------------------------------------------------------------# `deja_dimension` is a LOCAL_COHORT on the `path` dimension: its json-logic-# classifies the RAW request path (substring `in`, so parametric paths like-# /payments/{id}/confirm are covered) into "recordable"/"otherwise". The override+# classifies the RAW request path into "recordable"/"otherwise". The override# records the recordable bucket; `deja_record` defaults to false (seeded above),# so /health and other probe traffic skip. The path -> deja_dimension dependency# graph is derived server-side from the LOCAL_COHORT type.# Posted here as explicit JSON (not via the TOML) because a cohort's# dimension_type + json-logic definitions do not round-trip cleanly through the# TOML conversion.+#+# Each rule anchors the path with `match` (regex) rather than substring `in`,+# so only route prefixes select. Note `match` takes [text, pattern] — the+# opposite argument order from `in`.echo "Seeding Deja recording sampler (deja_dimension cohort + deja_record override)..."post_or_fail "$SUPERPOSITION_URL/dimension" '{"dimension": "deja_dimension",@@ -229,12 +232,15 @@ post_or_fail "$SUPERPOSITION_URL/dimension" '{"enum": ["recordable", "otherwise"],"definitions": {"recordable": { "or": [- { "in": ["/payments", { "var": "path" }] },- { "in": ["/accounts", { "var": "path" }] },- { "in": ["/user/signup", { "var": "path" }] },- { "in": ["/organization", { "var": "path" }] },- { "in": ["/api_keys", { "var": "path" }] },- { "in": ["/configs", { "var": "path" }] }+ { "match": [{ "var": "path" }, "^/payments(/|$)"] },+ { "match": [{ "var": "path" }, "^/accounts(/|$)"] },+ { "match": [{ "var": "path" }, "^/user/signup(/|$)"] },+ { "match": [{ "var": "path" }, "^/organization(/|$)"] },+ { "match": [{ "var": "path" }, "^/api_keys(/|$)"] },+ { "match": [{ "var": "path" }, "^/configs(/|$)"] },+ { "match": [{ "var": "path" }, "^/v2/payments(/|$)"] },+ { "match": [{ "var": "path" }, "^/v2/organizations(/|$)"] },+ { "match": [{ "var": "path" }, "^/v2/configs(/|$)"] }]}}}@@ -250,4 +256,45 @@ put_or_fail "$SUPERPOSITION_URL/context" '{"change_reason": "Deja recording sampler"}' "deja_record override"+# Prove the sampler policy actually resolves: a mis-seeded cohort fails+# silently (`deja_record` just keeps resolving to false), so assert both+# directions here where the answer is still cheap to get.+resolve_deja_record() {+ local path="$1"++ # `has` rather than `//`: jq's alternative operator treats false as empty,+ # which would report a correctly-resolved skip as a missing key.+ curl -sS -X POST "$SUPERPOSITION_URL/config/resolve" \+ -H "Content-Type: application/json" \+ -H "x-org-id: $ORG_ID" \+ -H "x-workspace: $WORKSPACE_ID" \+ -d "{\"context\": {\"path\": \"$path\", \"method\": \"POST\"}}" \+ | jq -r 'if has("deja_record") then (.deja_record | tostring) else "missing" end'+}++# Three probes: a recordable path must record, a probe path must skip, and a+# path merely containing a recordable route must skip (anchored, not substring).+echo "Verifying the Deja recording sampler resolves..."+RECORDABLE_RESOLVED=$(resolve_deja_record "/payments")+PROBE_RESOLVED=$(resolve_deja_record "/health")+EMBEDDED_RESOLVED=$(resolve_deja_record "/foo/payments")++if [ "$RECORDABLE_RESOLVED" != "true" ] \+ || [ "$PROBE_RESOLVED" != "false" ] \+ || [ "$EMBEDDED_RESOLVED" != "false" ]; then+ echo ""+ echo "Error: the Deja recording sampler policy did not seed correctly."+ echo " /payments resolved deja_record=$RECORDABLE_RESOLVED (expected true)"+ echo " /health resolved deja_record=$PROBE_RESOLVED (expected false)"+ echo " /foo/payments resolved deja_record=$EMBEDDED_RESOLVED (expected false)"+ echo ""+ echo "A router in record mode would consult this and silently record the"+ echo "wrong set of requests. Check that the deja_dimension cohort exists and"+ echo "that Superposition derived its dependency on the path dimension:"+ echo " curl -s $SUPERPOSITION_URL/dimension/deja_dimension \\"+ echo " -H 'x-org-id: $ORG_ID' -H 'x-workspace: $WORKSPACE_ID' | jq ."+ exit 1+fi+echo " /payments -> record, /health -> skip, /foo/payments -> skip"+echo "Seeding complete!"