Skip to content

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

refactor(deja): move the pin to deja main and port the seams onto the miss arm (#14311)

Uzair Khan97b1f042c529
diff --git a/Cargo.lock b/Cargo.lock
index 330ea36116..ce26da0b46 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -359,13 +359,16 @@ dependencies = [
"common_enums",
"common_utils",
"currency_conversion",
+ "deja",
"diesel_models",
"error-stack 0.4.1",
"futures 0.3.31",
+ "http 1.3.1",
"hyperswitch_interfaces",
"hyperswitch_masking",
"opensearch",
"reqwest 0.11.27",
+ "reqwest 0.12.7",
"router_env",
"rust_decimal",
"serde",
@@ -2872,7 +2875,7 @@ checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
[[package]]
name = "deja"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510#ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510"
+source = "git+https://github.com/juspay/deja?rev=9230641b943a469ef4b506c05e3e9201363f3d10#9230641b943a469ef4b506c05e3e9201363f3d10"
dependencies = [
"deja-context",
"deja-core",
@@ -2889,7 +2892,7 @@ dependencies = [
[[package]]
name = "deja-context"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510#ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510"
+source = "git+https://github.com/juspay/deja?rev=9230641b943a469ef4b506c05e3e9201363f3d10#9230641b943a469ef4b506c05e3e9201363f3d10"
dependencies = [
"pin-project-lite",
]
@@ -2897,7 +2900,7 @@ dependencies = [
[[package]]
name = "deja-core"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510#ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510"
+source = "git+https://github.com/juspay/deja?rev=9230641b943a469ef4b506c05e3e9201363f3d10#9230641b943a469ef4b506c05e3e9201363f3d10"
dependencies = [
"serde",
"serde_json",
@@ -2907,7 +2910,7 @@ dependencies = [
[[package]]
name = "deja-derive"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510#ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510"
+source = "git+https://github.com/juspay/deja?rev=9230641b943a469ef4b506c05e3e9201363f3d10#9230641b943a469ef4b506c05e3e9201363f3d10"
dependencies = [
"proc-macro2",
"quote",
@@ -2917,17 +2920,18 @@ dependencies = [
[[package]]
name = "deja-diesel"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510#ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510"
+source = "git+https://github.com/juspay/deja?rev=9230641b943a469ef4b506c05e3e9201363f3d10#9230641b943a469ef4b506c05e3e9201363f3d10"
dependencies = [
"async-bb8-diesel",
"deja-runtime",
"diesel",
+ "serde_json",
]
[[package]]
name = "deja-runtime"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510#ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510"
+source = "git+https://github.com/juspay/deja?rev=9230641b943a469ef4b506c05e3e9201363f3d10#9230641b943a469ef4b506c05e3e9201363f3d10"
dependencies = [
"async-trait",
"deja-context",
@@ -2935,6 +2939,7 @@ dependencies = [
"deja-derive",
"serde",
"serde_json",
+ "siphasher 1.0.1",
"tokio 1.48.0",
"tracing",
"tracing-subscriber",
@@ -3576,6 +3581,7 @@ dependencies = [
"deja",
"dyn-clone",
"error-stack 0.4.1",
+ "futures 0.3.31",
"google-cloud-kms",
"hex",
"http 0.2.12",
@@ -8271,6 +8277,7 @@ dependencies = [
"url 2.5.4",
"wasm-bindgen",
"wasm-bindgen-futures",
+ "wasm-streams",
"web-sys",
"webpki-roots 0.25.4",
"winreg",
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index edd711940d..ace7068490 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -9,6 +9,7 @@ license.workspace = true
[features]
v1 = ["api_models/v1", "diesel_models/v1", "storage_impl/v1", "common_utils/v1"]
v2 = ["api_models/v2", "diesel_models/v2", "storage_impl/v2", "common_utils/v2"]
+deja = ["dep:deja", "dep:opensearch_http", "dep:opensearch_reqwest", "common_utils/deja", "diesel_models/deja", "storage_impl/deja"]
[dependencies]
# First party crates
@@ -18,6 +19,7 @@ common_utils = { version = "0.1.0", path = "../common_utils" }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
hyperswitch_masking = "0.0.1"
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false, features = ["error-stack"] }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
currency_conversion = { version = "0.1.0", path = "../currency_conversion" }
@@ -32,6 +34,9 @@ bigdecimal = { version = "0.4.8", features = ["serde"] }
error-stack = "0.4.1"
futures = "0.3.31"
opensearch = { version = "2.3.0", features = ["aws-auth"] }
+# The versions opensearch builds its `Response` from, to rebuild a recorded one.
+opensearch_http = { package = "http", version = "1.3.1", optional = true }
+opensearch_reqwest = { package = "reqwest", version = "0.12.7", default-features = false, features = ["stream"], optional = true }
reqwest = { version = "0.11.27", features = ["serde_json"] }
rust_decimal = "1.37"
serde = { version = "1.0.219", features = ["derive", "rc"] }
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 18eb2685a5..14f2b09be5 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -30,6 +30,9 @@ use time::PrimitiveDateTime;
use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError};
use crate::{enums::AuthInfo, query::QueryBuildingError};
+#[cfg(feature = "deja")]
+mod recording;
+
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(tag = "auth")]
#[serde(rename_all = "lowercase")]
@@ -101,7 +104,8 @@ impl Default for OpenSearchConfig {
}
}
-#[derive(Debug, thiserror::Error)]
+// Serialisable so the deja seam can record and replay a failed search.
+#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)]
pub enum OpenSearchError {
#[error("Opensearch is not enabled")]
NotEnabled,
@@ -254,6 +258,23 @@ impl OpenSearchClient {
}
}
+ /// The OpenSearch round trip, recorded as its status and body. `Http`, not `Db`: the
+ /// index is external state. A miss answers with an empty result set.
+ #[cfg_attr(
+ feature = "deja",
+ deja::boundary(
+ boundary = "opensearch",
+ component = "analytics::opensearch",
+ operation = "execute",
+ op = Read,
+ replay = Substitute,
+ effect = Http,
+ returns = Value,
+ owned_codec = recording::ResponseCodec,
+ args = query_builder.deja_args(),
+ on_miss = Ok(recording::ResponseCodec::missed_query()),
+ )
+ )]
pub async fn execute(
&self,
query_builder: OpenSearchQueryBuilder,
diff --git a/crates/analytics/src/opensearch/recording.rs b/crates/analytics/src/opensearch/recording.rs
new file mode 100644
index 0000000000..fba7befba4
--- /dev/null
+++ b/crates/analytics/src/opensearch/recording.rs
@@ -0,0 +1,501 @@
+//! What deja records of an OpenSearch query, and how a replay rebuilds it.
+
+use common_utils::errors::CustomResult;
+use opensearch::http::{response::Response, Url};
+use serde_json::{json, Value};
+
+use super::{OpenSearchError, OpenSearchQueryBuilder};
+
+/// Records a response as its status and body; `read` only reads and rebuilds.
+pub(super) struct ResponseCodec;
+
+type ResponseEnvelope = deja::codec::ResultCodec<Value, OpenSearchError>;
+
+impl deja::codec::OwnedReplayCodec for ResponseCodec {
+ type Value = CustomResult<Response, OpenSearchError>;
+ /// The body as read, or why reading failed.
+ type Read = Result<opensearch_reqwest::Body, String>;
+
+ async fn read(value: Self::Value) -> (Self::Value, Result<Self::Read, String>) {
+ let response = match value {
+ Ok(response) => response,
+ Err(report) => return (Err(report), Ok(Ok(opensearch_reqwest::Body::from("")))),
+ };
+ let status = response.status_code();
+ let headers = response.headers().clone();
+ let url = response.url().clone();
+ let method = response.method();
+ // Sized only if the original knew its length.
+ let sized = response.content_length().is_some();
+ let (body, read) = match response.bytes().await {
+ Ok(bytes) => {
+ let read = opensearch_reqwest::Body::from(bytes.clone());
+ let body = if sized {
+ opensearch_reqwest::Body::from(bytes)
+ } else {
+ opensearch_reqwest::Body::wrap_stream(futures::stream::once(
+ futures::future::ready(Ok::<_, std::convert::Infallible>(bytes)),
+ ))
+ };
+ (body, Ok(read))
+ }
+ Err(error) => {
+ let reason = error.to_string();
+ let body = opensearch_reqwest::Body::wrap_stream(futures::stream::once(
+ futures::future::ready(Err::<Vec<u8>, _>(error)),
+ ));
+ (body, Err(reason))
+ }
+ };
+ (Ok(rebuilt(status, headers, url, method, body)), Ok(read))
+ }
+
+ /// A failed read records its status and why; replay fails the body the same way.
+ fn record(read: Self::Read, value: &Self::Value) -> (Value, bool) {
+ match value {
+ Ok(response) => {
+ let status = response.status_code().as_u16();
+ let recorded = match read {
+ Ok(body) => {
+ let body = String::from_utf8_lossy(body.as_bytes().unwrap_or_default());
+ json!({ "status": status, "body": body })
+ }
+ Err(reason) => json!({ "status": status, "read_error": reason }),
+ };
+ (ResponseEnvelope::ok_envelope(&recorded), false)
+ }
+ Err(report) => (ResponseEnvelope::err_envelope(report), true),
+ }
+ }
+
+ fn reconstruct(recorded: Value) -> Option<Self::Value> {
+ use deja::codec::ReplayCodec;
+ match ResponseEnvelope::reconstruct(recorded)? {
+ Ok(recorded) => {
+ let status = opensearch_http::StatusCode::from_u16(
+ u16::try_from(recorded.get("status")?.as_u64()?).ok()?,
+ )
+ .ok()?;
+ if let Some(reason) = recorded.get("read_error").and_then(Value::as_str) {
+ let failure = std::io::Error::other(reason.to_owned());
+ let body = opensearch_reqwest::Body::wrap_stream(futures::stream::once(
+ futures::future::ready(Err::<Vec<u8>, _>(failure)),
+ ));
+ return Some(Ok(Self::replayed(status, body)));
+ }
+ let body = recorded.get("body")?.as_str()?.to_owned();
+ Some(Ok(Self::replayed(status, body.into())))
+ }
+ Err(report) => Some(Err(report)),
+ }
+ }
+}
+
+impl ResponseCodec {
+ /// A missed query's answer: an empty result set both callers read, as
+ /// `OpensearchOutput::Success` and as an `OpenMsearchOutput` with no responses.
+ pub(super) fn missed_query() -> Response {
+ Self::replayed(
+ opensearch_http::StatusCode::OK,
+ Self::missed_query_body().into(),
+ )
+ }
+
+ fn missed_query_body() -> String {
+ json!({
+ "hits": {"total": {"value": 0}, "hits": []},
+ "responses": [],
+ })
+ .to_string()
+ }
+
+ /// A response rebuilt from the tape, which holds its status and body.
+ fn replayed(status: opensearch_http::StatusCode, body: opensearch_reqwest::Body) -> Response {
+ let mut response = opensearch_http::Response::new(body);
+ *response.status_mut() = status;
+ Response::new(
+ opensearch_reqwest::Response::from(response),
+ opensearch::http::Method::Post,
+ )
+ }
+}
+
+/// The client's own `Response` from the original's parts and a body.
+fn rebuilt(
+ status: opensearch_http::StatusCode,
+ headers: opensearch_http::HeaderMap,
+ url: Url,
+ method: opensearch::http::Method,
+ body: opensearch_reqwest::Body,
+) -> Response {
+ use opensearch_reqwest::ResponseBuilderExt;
+ let mut response = match opensearch_http::Response::builder().url(url).body(()) {
+ Ok(response) => response.map(|()| body),
+ Err(_) => opensearch_http::Response::new(body),
+ };
+ *response.status_mut() = status;
+ *response.headers_mut() = headers;
+ Response::new(opensearch_reqwest::Response::from(response), method)
+}
+
+impl OpenSearchQueryBuilder {
+ /// Args for the OpenSearch seam, built field by field because the builder's `Debug`
+ /// renders a `HashSet` in random order.
+ pub fn deja_args(&self) -> Value {
+ let mut auth_scope = self.build_auth_array();
+ // Auth fragments and the IDs in `terms` are sets: sort the args, not the query.
+ for fragment in &mut auth_scope {
+ for field in [
+ "merchant_id.keyword",
+ "processor_merchant_id.keyword",
+ "profile_id.keyword",
+ ] {
+ if let Some(values) = fragment
+ .pointer_mut("/bool/must")
+ .and_then(Value::as_array_mut)
+ .and_then(|clauses| {
+ clauses.iter_mut().find_map(|clause| {
+ clause
+ .get_mut("terms")
+ .and_then(|terms| terms.get_mut(field))
+ .and_then(Value::as_array_mut)
+ })
+ })
+ {
+ values.sort_by_cached_key(Value::to_string);
+ }
+ }
+ }
+ auth_scope.sort_by_cached_key(Value::to_string);
+
+ serde_json::json!({
+ "query": self.query,
+ "indexes": format!("{:?}", self.query_type),
+ "offset": self.offset,
+ "count": self.count,
+ "filters": format!("{:?}", self.filters),
+ "time_range": format!("{:?}", self.time_range),
+ "amount_range": format!("{:?}", self.amount_range),
+ "order": format!("{:?}", self.order),
+ "auth_scope": auth_scope,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use api_models::analytics::search::SearchIndex;
+
+ use crate::{
+ enums::AuthInfo,
+ opensearch::{OpenSearchQuery, OpenSearchQueryBuilder},
+ };
+
+ #[allow(
+ clippy::expect_used,
+ reason = "test helper: a free fn, so allow-expect-in-tests does not cover it; a fixture whose org id will not parse should fail the test loudly"
+ )]
+ fn org_scope(org_id: &str) -> AuthInfo {
+ AuthInfo::OrgLevel {
+ org_id: common_utils::id_type::OrganizationId::try_from(std::borrow::Cow::Owned(
+ org_id.to_owned(),
+ ))
+ .expect("valid organization id"),
+ }
+ }
+
+ fn builder(search_params: Vec<AuthInfo>) -> OpenSearchQueryBuilder {
+ OpenSearchQueryBuilder::new(
+ OpenSearchQuery::Search(SearchIndex::PaymentIntents),
+ "example".to_string(),
+ search_params,
+ None,
+ )
+ }
+
+ /// The missed-query body deserializes for both callers; the miss arm cannot tell which asked.
+ #[test]
+ fn the_missed_query_body_deserializes_for_both_callers() {
+ let body = super::ResponseCodec::missed_query_body();
+
+ let single = serde_json::from_str::<api_models::analytics::search::OpensearchOutput>(&body)
+ .expect("the single-index caller must be able to read the missed-query body");
+ match single {
+ api_models::analytics::search::OpensearchOutput::Success(success) => {
+ assert_eq!(success.hits.total.value, 0);
+ assert!(success.hits.hits.is_empty());
+ }
+ api_models::analytics::search::OpensearchOutput::Error(error) => {
+ panic!("the untagged enum matched Error, not Success: {error:?}")
+ }
+ }
+
+ let multi = serde_json::from_str::<api_models::analytics::search::OpenMsearchOutput>(&body)
+ .expect("the multi-index caller must be able to read the missed-query body");
+ assert!(
+ multi.responses.is_empty(),
+ "the multi-index caller zips responses against its index list"
+ );
+ assert!(multi.error.is_none());
+ }
+
+ #[test]
+ fn query_args_include_stable_auth_scope_identity() {
+ let first = builder(vec![org_scope("org_a"), org_scope("org_b")]);
+ let same = builder(vec![org_scope("org_a"), org_scope("org_b")]);
+ let reversed = builder(vec![org_scope("org_b"), org_scope("org_a")]);
+ let different = builder(vec![org_scope("org_a"), org_scope("org_c")]);
+
+ let make_merchant_scope =
+ |merchant_ids: Vec<common_utils::id_type::MerchantId>| AuthInfo::MerchantLevel {
+ org_id: common_utils::id_type::OrganizationId::try_from(
+ std::borrow::Cow::Borrowed("org_a"),
+ )
+ .expect("valid organization id"),
+ merchant_ids,
+ processor_merchant_ids: None,
+ };
+ let merchant_ids_reordered = builder(vec![make_merchant_scope(vec![
+ common_utils::id_type::MerchantId::try_from(std::borrow::Cow::Borrowed("merchant_a"))
+ .expect("valid merchant id"),
+ common_utils::id_type::MerchantId::try_from(std::borrow::Cow::Borrowed("merchant_b"))
+ .expect("valid merchant id"),
+ ])]);
+ let merchant_ids_sorted = builder(vec![make_merchant_scope(vec![
+ common_utils::id_type::MerchantId::try_from(std::borrow::Cow::Borrowed("merchant_b"))
+ .expect("valid merchant id"),
+ common_utils::id_type::MerchantId::try_from(std::borrow::Cow::Borrowed("merchant_a"))
+ .expect("valid merchant id"),
+ ])]);
+
+ assert_eq!(
+ merchant_ids_reordered.deja_args(),
+ merchant_ids_sorted.deja_args()
+ );
+ let expected = first.deja_args();
+ assert_eq!(expected, same.deja_args());
+ assert_eq!(expected, reversed.deja_args());
+ assert_ne!(expected, different.deja_args());
+ }
+
+ /// The seam on `execute` names the `on_miss` and `args` helpers the tests above exercise.
+ #[test]
+ fn the_seam_names_the_helpers_the_tests_exercise() {
+ let source = include_str!("../opensearch.rs");
+ // Built from parts so this test's own text is not a match.
+ let start = source
+ .find(&["deja::", "boundary("].concat())
+ .expect("the seam attribute is present");
+ let end = source[start..]
+ .find(&["pub async fn ", "execute("].concat())
+ .expect("the seam is declared on execute");
+ let declaration = &source[start..start + end];
+ for expected in [
+ "owned_codec = recording::ResponseCodec",
+ "on_miss = Ok(recording::ResponseCodec::missed_query())",
+ "args = query_builder.deja_args()",
+ ] {
+ assert!(
+ declaration.contains(expected),
+ "the seam must name `{expected}`: {declaration}"
+ );
+ }
+ }
+
+ const GZIPPED: [u8; 52] = [
+ 31, 139, 8, 0, 0, 0, 0, 0, 2, 255, 171, 86, 202, 200, 44, 41, 86, 178, 170, 86, 42, 201,
+ 47, 73, 204, 1, 49, 202, 18, 115, 74, 83, 149, 172, 12, 107, 117, 160, 114, 209, 177, 181,
+ 181, 0, 3, 122, 183, 221, 40, 0, 0, 0,
+ ];
+
+ /// Serves `reply` to every connection, so one fixture can be fetched twice.
+ #[allow(
+ clippy::expect_used,
+ reason = "test helper: a free fn, so allow-expect-in-tests does not cover it; a fixture that cannot serve should fail the test loudly"
+ )]
+ fn serve(reply: Vec<u8>) -> String {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
+ let url = format!(
+ "http://{}/idx/_search",
+ listener.local_addr().expect("addr")
+ );
+ std::thread::spawn(move || {
+ for mut stream in listener.incoming().flatten() {
+ let mut request = [0u8; 4096];
+ let _ = stream.read(&mut request);
+ let _ = stream.write_all(&reply);
+ }
+ });
+ url
+ }
+
+ fn reply(head: &str, body: &[u8]) -> Vec<u8> {
+ [head.as_bytes(), b"\r\n", body].concat()
+ }
+
+ #[allow(
+ clippy::expect_used,
+ reason = "test helper: a free fn, so allow-expect-in-tests does not cover it; a fixture that cannot serve should fail the test loudly"
+ )]
+ async fn fetch(url: &str) -> opensearch::http::response::Response {
+ let response = opensearch_reqwest::Client::new()
+ .post(url)
+ .send()
+ .await
+ .expect("the fixture server answers");
+ opensearch::http::response::Response::new(response, opensearch::http::Method::Post)
+ }
+
+ /// What a caller can observe: parts, `content_length`, then the body.
+ async fn observed(
+ response: opensearch::http::response::Response,
+ ) -> (String, Option<u64>, Result<String, String>) {
+ let parts = format!(
+ "{:?} {:?} {:?} {} {:?} {:?}",
+ response.status_code(),
+ response.headers(),
+ response.content_type(),
+ response.url(),
+ response.method(),
+ response.warning_headers().collect::<Vec<_>>(),
+ );
+ let length = response.content_length();
+ (
+ parts,
+ length,
+ response.text().await.map_err(|error| error.to_string()),
+ )
+ }
+
+ /// Every accessor reads the same through the codec for sized, chunked, gzip and truncated
+ /// bodies, except a truncated body's `content_length` (reqwest has no sized failing body).
+ #[tokio::test]
+ async fn the_caller_observes_the_same_response_through_the_codec() {
+ use deja::codec::OwnedReplayCodec;
+ let body = br#"{"hits":{"total":{"value":1},"hits":[]}}"#;
+ let fixtures = [
+ (
+ "sized",
+ reply(
+ &format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json; charset=UTF-8\r\n\
+ warning: 299 OpenSearch \"deprecated\"\r\ncontent-length: {}\r\n",
+ body.len()
+ ),
+ body,
+ ),
+ true,
+ ),
+ (
+ "chunked",
+ reply(
+ &format!(
+ "HTTP/1.1 404 Not Found\r\ncontent-type: application/json\r\n\
+ transfer-encoding: chunked\r\n\r\n{:x}",
+ body.len()
+ ),
+ &[&body[..], b"\r\n0\r\n\r\n"].concat(),
+ ),
+ true,
+ ),
+ (
+ "gzip",
+ reply(
+ &format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
+ content-encoding: gzip\r\ncontent-length: {}\r\n",
+ GZIPPED.len()
+ ),
+ &GZIPPED,
+ ),
+ true,
+ ),
+ (
+ "truncated",
+ reply(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 400\r\n",
+ body,
+ ),
+ false,
+ ),
+ ];
+ for (name, fixture, reads) in fixtures {
+ let url = serve(fixture);
+ let (direct_parts, direct_length, direct_body) = observed(fetch(&url).await).await;
+ let (rebuilt, read) = super::ResponseCodec::read(Ok(fetch(&url).await)).await;
+ assert_eq!(matches!(read, Ok(Ok(_))), reads, "{name}: {read:?}");
+ let (rebuilt_parts, rebuilt_length, rebuilt_body) =
+ observed(rebuilt.expect("an Ok stays Ok")).await;
+ assert_eq!(direct_parts, rebuilt_parts, "{name}: the parts differ");
+ assert_eq!(direct_body.is_ok(), reads, "{name}: {direct_body:?}");
+ if reads {
+ assert_eq!(direct_length, rebuilt_length, "{name}: the length differs");
+ assert_eq!(direct_body, rebuilt_body, "{name}: the body differs");
+ } else {
+ assert_eq!(
+ (direct_length, rebuilt_length),
+ (Some(400), None),
+ "{name}: the one known difference, a failed body's length"
+ );
+ assert!(rebuilt_body.is_err(), "{name}: the read failure survives");
+ }
+ }
+ }
+
+ /// What `read` saw goes on the tape and rebuilds on replay, error arm too.
+ #[tokio::test]
+ async fn a_recorded_response_replays_as_what_the_caller_read() {
+ use deja::codec::OwnedReplayCodec;
+ use error_stack::report;
+ let url = serve(reply(
+ "HTTP/1.1 404 Not Found\r\ncontent-length: 15\r\n",
+ br#"{"found":false}"#,
+ ));
+ let (value, read) = super::ResponseCodec::read(Ok(fetch(&url).await)).await;
+ let (recorded, is_error) =
+ super::ResponseCodec::record(read.expect("the body reads"), &value);
+ assert!(!is_error);
+ let replayed = super::ResponseCodec::reconstruct(recorded)
+ .expect("the envelope rebuilds")
+ .expect("an Ok envelope");
+ assert_eq!(replayed.status_code().as_u16(), 404);
+ assert_eq!(
+ replayed.text().await.expect("the replayed body reads"),
+ r#"{"found":false}"#
+ );
+
+ // A failed read replays as a failing body at the recorded status.
+ let url = serve(reply(
+ "HTTP/1.1 503 Service Unavailable\r\ncontent-length: 400\r\n",
+ br#"{"partial":"#,
+ ));
+ let (value, read) = super::ResponseCodec::read(Ok(fetch(&url).await)).await;
+ let (recorded, is_error) =
+ super::ResponseCodec::record(read.expect("the read always reports"), &value);
+ assert!(!is_error, "the call returned its response");
+ assert!(
+ recorded.pointer("/value/read_error").is_some(),
+ "the tape names the failed read: {recorded}"
+ );
+ let replayed = super::ResponseCodec::reconstruct(recorded)
+ .expect("the envelope rebuilds")
+ .expect("an Ok envelope");
+ assert_eq!(replayed.status_code().as_u16(), 503);
+ assert!(replayed.text().await.is_err(), "the replayed body fails");
+
+ let failed: common_utils::errors::CustomResult<
+ opensearch::http::response::Response,
+ super::OpenSearchError,
+ > = Err(report!(super::OpenSearchError::ConnectionError));
+ let (value, read) = super::ResponseCodec::read(failed).await;
+ let (recorded, is_error) =
+ super::ResponseCodec::record(read.expect("an error arm reads nothing"), &value);
+ assert!(is_error);
+ let replayed = super::ResponseCodec::reconstruct(recorded).expect("the envelope rebuilds");
+ assert!(matches!(
+ replayed.map(|_| ()).map_err(|report| report.current_context().to_string()),
+ Err(message) if message == super::OpenSearchError::ConnectionError.to_string()
+ ));
+ }
+}
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index 0dfea39e5f..4ddbbc3060 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -32,7 +32,7 @@ base64-serde = "0.8.0"
blake3 = { version = "1.8.2", features = ["serde"] }
bytes = { version = "1.10.1", features = ["serde"] }
diesel = "2.2.10"
-deja = { git = "https://github.com/juspay/deja", rev = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false, features = ["error-stack"] }
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.rs
index 93f84fe2fa..7f64acd677 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -72,7 +72,13 @@ impl NonceSequence {
deja::id(
component = "common_utils::crypto",
operation = "GcmAes256::nonce",
+ // Ok-only: `ring::error::Unspecified` is not serializable, and a
+ // recorded `Err` fail-stops replay.
codec = ResultOkCodec,
+ // Exactly `NONCE_LEN` bytes, matching the low 96 bits `current` reads.
+ on_miss = Ok(Self::from_bytes(deja::synth::bytes::<{ aead::NONCE_LEN }>(
+ &__deja_miss,
+ ))),
)
)]
fn new() -> Result<Self, ring::error::Unspecified> {
@@ -653,6 +659,8 @@ impl EncodeMessage for TripleDesEde3CBC {
deja::id(
component = "common_utils::crypto",
operation = "generate_cryptographically_secure_random_string",
+ // Same `[A-Za-z0-9]` alphabet as `rand::distributions::Alphanumeric`.
+ on_miss = { use crate::synth_shape::Synthesize as _; __deja_miss.alphanumeric(length) },
codec = SerdeCodec,
)
)]
@@ -920,6 +928,8 @@ pub fn extract_rsa_public_key_components(
deja::id(
component = "common_utils::crypto",
operation = "secure_random_bytes",
+ // Exactly `length` bytes: `SeamedOsRng` turns a short vector into zeros.
+ on_miss = { use crate::synth_shape::Synthesize as _; __deja_miss.byte_vec(length) },
codec = SerdeCodec,
)
)]
@@ -1459,3 +1469,23 @@ mod crypto_tests {
assert!(right_verified);
}
}
+
+#[cfg(all(test, feature = "deja"))]
+mod deja_tests {
+ /// The nonce seam captures the `Ok` side only, read from its declaration
+ /// since the codec is not observable at run time.
+ #[test]
+ fn the_seam_selects_the_ok_only_codec() {
+ let source = include_str!("crypto.rs");
+ let (_, after_operation) = source
+ .split_once("operation = \"GcmAes256::nonce\",")
+ .expect("the seam must declare its operation");
+ let (declaration, _) = after_operation
+ .split_once(")]")
+ .expect("the seam's attribute must be closed");
+ assert!(
+ declaration.contains("codec = ResultOkCodec"),
+ "the nonce seam captures the Ok side only: {declaration}"
+ );
+ }
+}
diff --git a/crates/common_utils/src/elapsed.rs b/crates/common_utils/src/elapsed.rs
new file mode 100644
index 0000000000..af5fac0305
--- /dev/null
+++ b/crates/common_utils/src/elapsed.rs
@@ -0,0 +1,53 @@
+//! Elapsed-time readings that reach a request the candidate builds.
+
+#[cfg(feature = "deja")]
+use crate::synth_shape::Synthesize;
+
+/// Milliseconds since `started`, as a value a recording can serve back.
+///
+/// Seamed so a measured duration written into a request replays as recorded.
+/// `skip_all` because an `Instant` differs on every call; a miss derives a value
+/// rather than reading the clock.
+#[cfg_attr(feature = "deja", track_caller)]
+#[cfg_attr(
+ feature = "deja",
+ deja::time(
+ component = "common_utils::elapsed",
+ operation = "millis_since",
+ codec = SerdeCodec,
+ skip_all,
+ on_miss = __deja_miss.elapsed_millis(),
+ )
+)]
+pub fn millis_since(started: std::time::Instant) -> u128 {
+ started.elapsed().as_millis()
+}
+
+#[cfg(all(test, feature = "deja"))]
+mod tests {
+ use crate::synth_shape::Synthesize;
+
+ /// The miss arm's `u128` survives a serde_json round trip.
+ #[test]
+ fn the_miss_arms_own_output_round_trips_through_the_codec() {
+ let miss = |occurrence: u32| deja::SubstituteMiss {
+ boundary: "time",
+ component: "common_utils::elapsed",
+ method: "millis_since",
+ args: serde_json::json!({}),
+ occurrence,
+ correlation_id: None,
+ };
+ let derived: Vec<u128> = (0..4_u32).map(|n| miss(n).elapsed_millis()).collect();
+ assert_eq!(
+ derived,
+ vec![0, 1, 2, 3],
+ "the arm must advance by one per occurrence"
+ );
+ for value in derived.into_iter().chain([890, 4004, u128::from(u64::MAX)]) {
+ let encoded = serde_json::to_string(&value).expect("a reading serializes");
+ let decoded: u128 = serde_json::from_str(&encoded).expect("and comes back");
+ assert_eq!(decoded, value, "a reading must survive the tape unchanged");
+ }
+ }
+}
diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs
index 22e9fa1ea4..1e2e4ac509 100644
--- a/crates/common_utils/src/errors.rs
+++ b/crates/common_utils/src/errors.rs
@@ -93,7 +93,8 @@ pub struct IntegrityCheckError {
}
/// Cryptographic algorithm errors
-#[derive(Debug, thiserror::Error)]
+// Serializable so a `ResultCodec` can replay a recorded crypto failure.
+#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)]
pub enum CryptoError {
/// The cryptographic algorithm was unable to encode the message
#[error("Failed to encode given message")]
diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs
index 2c7df849bc..ca0df6db13 100644
--- a/crates/common_utils/src/keymanager.rs
+++ b/crates/common_utils/src/keymanager.rs
@@ -183,6 +183,8 @@ where
// 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.
+// A miss answers with a transport failure: no response body can be synthesized
+// honestly, and callers already handle the error.
#[cfg_attr(
feature = "deja",
deja::boundary(
@@ -200,6 +202,11 @@ where
"endpoint": endpoint,
"request": request_body.wire_image(),
}),
+ on_miss = Err(errors::KeyManagerClientError::RequestNotSent(format!(
+ "deja: no recorded key manager response for {endpoint} (occurrence {})",
+ __deja_miss.occurrence,
+ ))
+ .into()),
)
)]
pub async fn call_encryption_service<T, R>(
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index c7f3133221..2a05899d8b 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -3,10 +3,14 @@
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
+#[cfg(feature = "deja")]
+use crate::synth_shape::Synthesize;
+
pub mod access_token;
pub mod consts;
pub mod crypto;
pub mod custom_serde;
+pub mod elapsed;
#[allow(missing_docs)] // Todo: add docs
pub mod encryption;
pub mod errors;
@@ -33,6 +37,8 @@ pub mod request;
pub mod request_context;
#[cfg(feature = "signals")]
pub mod signals;
+#[cfg(feature = "deja")]
+pub mod synth_shape;
pub mod transformers;
pub mod types;
/// Unified Connector Service (UCS) interface definitions.
@@ -60,6 +66,9 @@ pub mod date_time {
OffsetDateTime, PrimitiveDateTime,
};
+ #[cfg(feature = "deja")]
+ use crate::synth_shape::Synthesize;
+
/// Enum to represent date formats
#[derive(Debug)]
pub enum DateFormat {
@@ -77,7 +86,8 @@ pub mod date_time {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::time(component = "common_utils", operation = "date_time::now", codec = SerdeCodec,)
+ deja::time(component = "common_utils", operation = "date_time::now", codec = SerdeCodec,
+ on_miss = { let synthetic = __deja_miss.instant(); PrimitiveDateTime::new(synthetic.date(), synthetic.time()) },)
)]
pub fn now() -> PrimitiveDateTime {
#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]
@@ -97,6 +107,7 @@ pub mod date_time {
deja::time(
component = "common_utils",
operation = "date_time::now_unix_timestamp",
+ on_miss = __deja_miss.instant_at_second_resolution().unix_timestamp(),
codec = SerdeCodec,
)
)]
@@ -126,6 +137,7 @@ pub mod date_time {
deja::time(
component = "common_utils",
operation = "date_time::now_unix_timestamp_millis",
+ on_miss = __deja_miss.instant().unix_timestamp_nanos() / 1_000_000,
codec = SerdeCodec,
)
)]
@@ -164,6 +176,19 @@ pub mod date_time {
deja::time(
component = "common_utils",
operation = "date_time::date_as_yyyymmddthhmmssmmmz",
+ // `time::error::Format` is not `Serialize`, so capture the Ok side only;
+ // the `Err` arm is unreachable for this constant config.
+ codec = ResultOkCodec,
+ on_miss = {
+ const SYNTH_ISO: EncodedConfig = Config::DEFAULT
+ .set_time_precision(TimePrecision::Second {
+ decimal_digits: NonZeroU8::new(3),
+ })
+ .encode();
+ convert_to_pdt(__deja_miss.instant())
+ .assume_utc()
+ .format(&Iso8601::<SYNTH_ISO>)
+ },
)
)]
pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> {
@@ -187,6 +212,13 @@ pub mod date_time {
deja::time(
component = "common_utils",
operation = "date_time::now_rfc7231_http_date",
+ // Ok-only, as above; the `Err` arm is unreachable for a constant format.
+ codec = ResultOkCodec,
+ on_miss = __deja_miss.instant_at_second_resolution().format(
+ &time::macros::format_description!(
+ "[weekday repr:short], [day padding:zero] [month repr:short] [year repr:full] [hour padding:zero repr:24]:[minute padding:zero]:[second padding:zero] GMT"
+ )
+ ),
)
)]
pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> {
@@ -306,7 +338,8 @@ pub mod date_time {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::id(component = "common_utils", operation = "generate_uuid_v4", codec = SerdeCodec,)
+ deja::id(component = "common_utils", operation = "generate_uuid_v4", codec = SerdeCodec,
+ on_miss = __deja_miss.uuid(),)
)]
#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]
pub fn generate_uuid_v4() -> uuid::Uuid {
@@ -329,6 +362,7 @@ pub fn generate_uuid_v4() -> uuid::Uuid {
deja::id(
component = "common_utils",
operation = "generate_random_alphanumeric_string",
+ on_miss = __deja_miss.alphanumeric(length),
codec = SerdeCodec,
)
)]
@@ -352,6 +386,7 @@ pub fn generate_random_alphanumeric_string(length: usize) -> String {
deja::id(
component = "common_utils",
operation = "generate_random_numeric_string",
+ on_miss = __deja_miss.digits(length),
codec = SerdeCodec,
)
)]
@@ -376,7 +411,8 @@ pub fn generate_random_numeric_string(length: usize) -> String {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::id(component = "common_utils", operation = "generate_uuid_v7", codec = SerdeCodec,)
+ deja::id(component = "common_utils", operation = "generate_uuid_v7", codec = SerdeCodec,
+ on_miss = __deja_miss.uuid(),)
)]
#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]
pub fn generate_uuid_v7() -> uuid::Uuid {
@@ -397,6 +433,7 @@ pub fn generate_uuid_v7() -> uuid::Uuid {
deja::id(
component = "common_utils",
operation = "generate_nanoid_with_default_alphabet",
+ on_miss = __deja_miss.over(&nanoid::alphabet::SAFE, length),
codec = SerdeCodec,
)
)]
@@ -418,6 +455,7 @@ pub fn generate_nanoid_with_default_alphabet(length: usize) -> String {
deja::id(
component = "common_utils",
operation = "generate_random_f64_unit",
+ on_miss = __deja_miss.unit_f64(),
codec = SerdeCodec,
)
)]
@@ -440,6 +478,7 @@ pub fn generate_random_f64_unit() -> f64 {
deja::id(
component = "common_utils",
operation = "generate_random_number_in_range",
+ on_miss = __deja_miss.in_range(min, max),
codec = SerdeCodec,
)
)]
@@ -462,6 +501,7 @@ pub fn generate_random_number_in_range(min: i64, max: i64) -> i64 {
deja::id(
component = "common_utils",
operation = "generate_random_index",
+ on_miss = __deja_miss.index(length),
codec = SerdeCodec,
)
)]
@@ -487,7 +527,8 @@ pub fn generate_random_index(length: usize) -> Option<usize> {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::id(component = "common_utils", operation = "process_id", codec = SerdeCodec,)
+ deja::id(component = "common_utils", operation = "process_id", codec = SerdeCodec,
+ on_miss = __deja_miss.opaque_u32(),)
)]
#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]
pub fn process_id() -> u32 {
@@ -512,7 +553,8 @@ pub fn process_id() -> u32 {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::id(component = "common_utils", operation = "hostname", codec = SerdeCodec,)
+ deja::id(component = "common_utils", operation = "hostname", codec = SerdeCodec,
+ on_miss = Some(__deja_miss.alphanumeric(12)),)
)]
pub fn hostname() -> Option<String> {
std::env::var("HOSTNAME")
@@ -532,6 +574,7 @@ pub fn hostname() -> Option<String> {
deja::id(
component = "common_utils",
operation = "generate_random_permutation",
+ on_miss = __deja_miss.permutation(length),
codec = SerdeCodec,
)
)]
@@ -558,6 +601,7 @@ pub fn generate_random_permutation(length: usize) -> Vec<usize> {
deja::id(
component = "common_utils",
operation = "generate_random_bytes",
+ on_miss = __deja_miss.byte_vec(length),
codec = SerdeCodec,
)
)]
@@ -574,7 +618,8 @@ pub fn generate_random_bytes(length: usize) -> Vec<u8> {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::id(component = "common_utils", operation = "generate_id", codec = SerdeCodec,)
+ deja::id(component = "common_utils", operation = "generate_id", codec = SerdeCodec,
+ on_miss = __deja_miss.prefixed(prefix, length),)
)]
#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]
pub fn generate_id(length: usize, prefix: &str) -> String {
@@ -645,6 +690,7 @@ pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcqui
deja::id(
component = "common_utils",
operation = "generate_id_with_default_len",
+ on_miss = __deja_miss.prefixed(prefix, consts::ID_LENGTH),
codec = SerdeCodec,
)
)]
@@ -662,6 +708,7 @@ pub fn generate_id_with_default_len(prefix: &str) -> String {
deja::id(
component = "common_utils",
operation = "generate_time_ordered_id",
+ on_miss = format!("{prefix}_{}", __deja_miss.uuid().as_simple()),
codec = SerdeCodec,
)
)]
@@ -678,6 +725,7 @@ pub fn generate_time_ordered_id(prefix: &str) -> String {
deja::id(
component = "common_utils",
operation = "generate_time_ordered_id_without_prefix",
+ on_miss = __deja_miss.uuid().as_simple().to_string(),
codec = SerdeCodec,
)
)]
@@ -691,7 +739,8 @@ pub fn generate_time_ordered_id_without_prefix() -> String {
#[cfg_attr(feature = "deja", track_caller)]
#[cfg_attr(
feature = "deja",
- deja::id(component = "common_utils", operation = "generate_id_with_len", codec = SerdeCodec,)
+ deja::id(component = "common_utils", operation = "generate_id_with_len", codec = SerdeCodec,
+ on_miss = __deja_miss.alphanumeric(length),)
)]
#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]
pub fn generate_id_with_len(length: usize) -> String {
diff --git a/crates/common_utils/src/synth_shape.rs b/crates/common_utils/src/synth_shape.rs
new file mode 100644
index 0000000000..b617e6e821
--- /dev/null
+++ b/crates/common_utils/src/synth_shape.rs
@@ -0,0 +1,455 @@
+//! Deterministic, panic-free stand-ins for a generator's output on a replay miss.
+//!
+//! Unlike [`deja::synth::id`], these honour the caller's alphabet and length, so the
+//! service accepts the value, and each is a function of the miss alone.
+
+/// Decimal digits, for the generators that promise only these.
+const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
+
+/// Step of a synthesized clock between misses at one site: one millisecond, in nanos.
+const CLOCK_STEP_NS: i64 = 1_000_000;
+
+/// The shapes a miss arm can synthesize, as methods on the miss itself.
+///
+/// An inherent method of the same name on `SubstituteMiss` would silently win;
+/// the golden-value tests below catch that.
+pub trait Synthesize {
+ /// `length` characters drawn from `alphabet`; empty for an empty alphabet.
+ fn over(&self, alphabet: &[char], length: usize) -> String;
+
+ /// `length` characters over `consts::ALPHABETS`, as `generate_id_with_len` promises.
+ fn alphanumeric(&self, length: usize) -> String;
+
+ /// `prefix`, an underscore, then [`Self::alphanumeric`] of `length`.
+ fn prefixed(&self, prefix: &str, length: usize) -> String;
+
+ /// `count` distinct alphanumeric words of `length` characters, carved from one
+ /// draw, since repeated calls on one miss return the same value.
+ fn alphanumeric_words(&self, count: usize, length: usize) -> Vec<String>;
+
+ /// `length` decimal digits, for the generators that promise only these.
+ fn digits(&self, length: usize) -> String;
+
+ /// A deterministic `f64` in `[0, 1)`, never `1.0`, matching the live generator.
+ fn unit_f64(&self) -> f64;
+
+ /// A deterministic value in `min..=max`, inclusive, matching `gen_range`.
+ fn in_range(&self, min: i64, max: i64) -> i64;
+
+ /// A deterministic index into `0..length`; `None` for an empty range.
+ fn index(&self, length: usize) -> Option<usize>;
+
+ /// `length` deterministic bytes, with the length chosen at runtime.
+ fn byte_vec(&self, length: usize) -> Vec<u8>;
+
+ /// A deterministic permutation of `0..length` (Fisher-Yates).
+ fn permutation(&self, length: usize) -> Vec<usize>;
+
+ /// A deterministic v8 UUID, disjoint from the v4 and v7 values real code produces.
+ fn uuid(&self) -> uuid::Uuid;
+
+ /// A deterministic `u32` with no marker; use only where nothing derives from it.
+ fn opaque_u32(&self) -> u32;
+
+ /// Nanoseconds since the Unix epoch, starting at zero and advancing per occurrence.
+ fn epoch_nanos(&self) -> i64;
+
+ /// A deterministic UTC instant for this miss, advancing by [`CLOCK_STEP_NS`].
+ fn instant(&self) -> time::OffsetDateTime;
+
+ /// A deterministic UTC instant advancing by a whole second per miss, for
+ /// consumers that render only whole seconds.
+ fn instant_at_second_resolution(&self) -> time::OffsetDateTime;
+
+ /// Elapsed milliseconds, advancing by one per miss.
+ fn elapsed_millis(&self) -> u128;
+}
+
+impl Synthesize for deja::SubstituteMiss {
+ fn over(&self, alphabet: &[char], length: usize) -> String {
+ let span = match u64::try_from(alphabet.len()) {
+ Ok(span) if span > 0 => span,
+ _ => return String::new(),
+ };
+ let seed = deja::synth::u64(self);
+ (0..length)
+ .filter_map(|index| {
+ let index = u64::try_from(index).ok()?;
+ let pick = usize::try_from(mix(seed, index) % span).ok()?;
+ alphabet.get(pick).copied()
+ })
+ .collect()
+ }
+
+ fn alphanumeric(&self, length: usize) -> String {
+ self.over(&crate::consts::ALPHABETS, length)
+ }
+
+ fn prefixed(&self, prefix: &str, length: usize) -> String {
+ format!("{}_{}", prefix, self.alphanumeric(length))
+ }
+
+ fn alphanumeric_words(&self, count: usize, length: usize) -> Vec<String> {
+ if length == 0 {
+ return vec![String::new(); count];
+ }
+ let drawn = self.alphanumeric(count.saturating_mul(length));
+ // ASCII alphabet, so byte chunks are character chunks.
+ drawn
+ .as_bytes()
+ .chunks(length)
+ .take(count)
+ .map(|chunk| String::from_utf8_lossy(chunk).into_owned())
+ .collect()
+ }
+
+ fn digits(&self, length: usize) -> String {
+ self.over(&DIGITS, length)
+ }
+
+ fn unit_f64(&self) -> f64 {
+ // Via u32 so the conversion is a lossless `f64::from`.
+ let span = f64::from(u32::MAX) + 1.0;
+ let draw = u32::try_from(deja::synth::u64(self) >> 32).unwrap_or(0);
+ f64::from(draw) / span
+ }
+
+ fn in_range(&self, min: i64, max: i64) -> i64 {
+ if min >= max {
+ return min;
+ }
+ // `i128` so a full-`i64` range cannot overflow.
+ let span = i128::from(max) - i128::from(min) + 1;
+ let draw = i128::from(deja::synth::u64(self)) % span;
+ i64::try_from(i128::from(min) + draw).unwrap_or(min)
+ }
+
+ fn index(&self, length: usize) -> Option<usize> {
+ let span = u64::try_from(length).ok().filter(|n| *n > 0)?;
+ usize::try_from(deja::synth::u64(self) % span).ok()
+ }
+
+ fn byte_vec(&self, length: usize) -> Vec<u8> {
+ let seed = deja::synth::u64(self);
+ (0..length)
+ .filter_map(|position| {
+ let position = u64::try_from(position).ok()?;
+ u8::try_from(mix(seed, position) & 0xff).ok()
+ })
+ .collect()
+ }
+
+ fn permutation(&self, length: usize) -> Vec<usize> {
+ let seed = deja::synth::u64(self);
+ let mut out: Vec<usize> = (0..length).collect();
+ for position in (1..length).rev() {
+ let Ok(cursor) = u64::try_from(position) else {
+ continue;
+ };
+ let Ok(span) = u64::try_from(position + 1) else {
+ continue;
+ };
+ if let Ok(pick) = usize::try_from(mix(seed, cursor) % span) {
+ out.swap(position, pick);
+ }
+ }
+ out
+ }
+
+ fn uuid(&self) -> uuid::Uuid {
+ uuid::Uuid::parse_str(&deja::synth::uuid_v8(self)).unwrap_or(uuid::Uuid::nil())
+ }
+
+ fn opaque_u32(&self) -> u32 {
+ u32::try_from(deja::synth::u64(self) % u64::from(u32::MAX)).unwrap_or(1)
+ }
+
+ fn epoch_nanos(&self) -> i64 {
+ deja::synth::monotonic(self, 0, CLOCK_STEP_NS)
+ }
+
+ fn instant(&self) -> time::OffsetDateTime {
+ time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(self.epoch_nanos()))
+ .unwrap_or(time::OffsetDateTime::UNIX_EPOCH)
+ }
+
+ fn instant_at_second_resolution(&self) -> time::OffsetDateTime {
+ time::OffsetDateTime::from_unix_timestamp(deja::synth::monotonic(self, 0, 1))
+ .unwrap_or(time::OffsetDateTime::UNIX_EPOCH)
+ }
+
+ fn elapsed_millis(&self) -> u128 {
+ u128::try_from(deja::synth::monotonic(self, 0, 1)).unwrap_or(0)
+ }
+}
+
+/// One digest per position, so extending the length keeps earlier characters.
+fn mix(seed: u64, index: u64) -> u64 {
+ // splitmix64's finalizer; not cryptographic, by design.
+ let mut state = seed ^ index.wrapping_mul(0x9E37_79B9_7F4A_7C15);
+ state = (state ^ (state >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ state = (state ^ (state >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ state ^ (state >> 31)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const HEX: [char; 16] = [
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
+ ];
+ const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
+
+ fn miss(args: serde_json::Value) -> deja::SubstituteMiss {
+ deja::SubstituteMiss {
+ boundary: "id",
+ component: "test",
+ method: "generate",
+ args,
+ occurrence: 0,
+ correlation_id: None,
+ }
+ }
+
+ /// One miss always synthesizes the same value.
+ #[test]
+ fn the_same_miss_gives_the_same_string() {
+ let first = miss(serde_json::json!({"len": 12})).over(&HEX, 12);
+ let second = miss(serde_json::json!({"len": 12})).over(&HEX, 12);
+ assert_eq!(first, second, "one miss must synthesize one value");
+ assert!(!first.is_empty(), "and it must not be vacuously equal");
+ }
+
+ /// Different misses synthesize different values.
+ #[test]
+ fn a_different_miss_gives_a_different_string() {
+ let first = miss(serde_json::json!({"len": 12})).over(&HEX, 12);
+ let second = miss(serde_json::json!({"len": 13})).over(&HEX, 12);
+ assert_ne!(first, second, "different args must synthesize differently");
+ }
+
+ /// The value uses the caller's alphabet and length.
+ #[test]
+ fn the_value_honours_the_alphabet_and_the_length() {
+ for length in [1_usize, 8, 32, 64] {
+ let value = miss(serde_json::json!({"n": length})).over(&DIGITS, length);
+ assert_eq!(
+ value.chars().count(),
+ length,
+ "length is part of the promise"
+ );
+ assert!(
+ value.chars().all(|c| DIGITS.contains(&c)),
+ "a numeric generator must not return {value}"
+ );
+ }
+ }
+
+ /// A longer draw extends a shorter one.
+ #[test]
+ fn extending_the_length_keeps_the_earlier_characters() {
+ let short = miss(serde_json::json!({})).over(&HEX, 8);
+ let long = miss(serde_json::json!({})).over(&HEX, 40);
+ assert!(
+ long.starts_with(&short),
+ "extending rewrote earlier positions: {short} then {long}"
+ );
+ }
+
+ #[test]
+ fn an_empty_alphabet_yields_an_empty_string_rather_than_a_panic() {
+ assert_eq!(miss(serde_json::json!({})).over(&[], 8), "");
+ }
+
+ /// Positions vary; catches a `mix` that ignores its index.
+ #[test]
+ fn positions_do_not_all_collapse_to_one_character() {
+ let value = miss(serde_json::json!({})).over(&HEX, 32);
+ let distinct: std::collections::BTreeSet<char> = value.chars().collect();
+ assert!(
+ distinct.len() > 4,
+ "32 characters over a 16-symbol alphabet collapsed to {}: {value}",
+ distinct.len()
+ );
+ }
+}
+
+/// Golden values: every synthesized shape pinned to its exact output, since a moved
+/// value makes a replay diverge from its own recording.
+#[cfg(test)]
+mod golden {
+ use std::num::NonZeroU8;
+
+ use time::format_description::well_known::iso8601::{
+ Config, EncodedConfig, Iso8601, TimePrecision,
+ };
+
+ use super::*;
+ use crate::consts;
+
+ /// One fixed miss, varied only by occurrence.
+ fn miss(occurrence: u32) -> deja::SubstituteMiss {
+ deja::SubstituteMiss {
+ boundary: "id",
+ component: "common_utils",
+ method: "golden",
+ args: serde_json::json!({"len": 12}),
+ occurrence,
+ correlation_id: None,
+ }
+ }
+
+ const SYNTH_ISO: EncodedConfig = Config::DEFAULT
+ .set_time_precision(TimePrecision::Second {
+ decimal_digits: NonZeroU8::new(3),
+ })
+ .encode();
+
+ #[test]
+ fn over_an_alphabet_is_pinned() {
+ assert_eq!(miss(0).over(&consts::ALPHABETS, 12), "77z992CVQZxg");
+ assert_eq!(miss(0).alphanumeric(12), "77z992CVQZxg");
+ assert_eq!(miss(0).prefixed("pay", 12), "pay_77z992CVQZxg");
+ assert_eq!(miss(0).digits(10), "7133908345");
+ assert_eq!(
+ miss(0).over(&nanoid::alphabet::SAFE, 21),
+ "DDBnXeIlmxl2UqmnXe2EI"
+ );
+ assert_eq!(miss(0).alphanumeric(0), "");
+ assert_eq!(
+ miss(0).alphanumeric_words(4, 4),
+ ["77z9", "92CV", "QZxg", "68YZ"]
+ );
+ assert_eq!(miss(0).alphanumeric_words(0, 4), Vec::<String>::new());
+ assert_eq!(miss(0).alphanumeric_words(2, 0), ["", ""]);
+ }
+
+ /// Words from one miss are mutually distinct.
+ #[test]
+ fn the_words_differ_from_one_another() {
+ let words = miss(0).alphanumeric_words(8, 8);
+ let distinct: std::collections::BTreeSet<&String> = words.iter().collect();
+ assert_eq!(distinct.len(), words.len(), "words collapsed: {words:?}");
+ assert!(words.iter().all(|word| word.chars().count() == 8));
+ }
+
+ #[test]
+ fn the_numeric_draws_are_pinned() {
+ assert_eq!(miss(0).unit_f64(), 0.400_051_809_847_354_9);
+ assert_eq!(miss(0).in_range(-5, 5), -2);
+ assert_eq!(
+ miss(0).in_range(i64::MIN, i64::MAX),
+ -1_843_718_680_693_841_055
+ );
+ assert_eq!(miss(0).in_range(7, 7), 7);
+ assert_eq!(miss(0).index(10), Some(3));
+ assert_eq!(miss(0).index(0), None);
+ assert_eq!(miss(0).byte_vec(8), [105, 41, 231, 89, 125, 16, 174, 23]);
+ assert_eq!(miss(0).permutation(6), [0, 3, 5, 1, 4, 2]);
+ assert_eq!(miss(0).opaque_u32(), 1_105_702_658);
+ }
+
+ #[test]
+ fn the_uuid_shapes_are_pinned() {
+ assert_eq!(
+ miss(0).uuid().to_string(),
+ "c41247c7-5493-8f37-9a15-cd1ff03594e9"
+ );
+ assert_eq!(
+ miss(0).uuid().simple().to_string(),
+ "c41247c754938f379a15cd1ff03594e9"
+ );
+ }
+
+ /// The v8 uuid always parses, so the nil fallback is unreachable.
+ #[test]
+ fn stripping_the_hyphens_and_parsing_agree() {
+ for occurrence in 0..512_u32 {
+ let stripped = deja::synth::uuid_v8(&miss(occurrence)).replace('-', "");
+ assert_eq!(
+ miss(occurrence).uuid().as_simple().to_string(),
+ stripped,
+ "the parse moved a value at occurrence {occurrence}"
+ );
+ assert_ne!(
+ stripped,
+ uuid::Uuid::nil().as_simple().to_string(),
+ "and it must not be vacuously equal through the nil fallback"
+ );
+ }
+ }
+
+ /// The clock shapes, read as each arm reads them, at two occurrences.
+ #[test]
+ fn the_clock_arms_are_pinned() {
+ let rfc7231 = time::macros::format_description!(
+ "[weekday repr:short], [day padding:zero] [month repr:short] [year repr:full] [hour padding:zero repr:24]:[minute padding:zero]:[second padding:zero] GMT"
+ );
+ let render = |occurrence: u32| {
+ let at = miss(occurrence).instant();
+ let per_second = miss(occurrence).instant_at_second_resolution();
+ (
+ miss(occurrence).epoch_nanos(),
+ time::PrimitiveDateTime::new(at.date(), at.time()).to_string(),
+ per_second.unix_timestamp(),
+ at.unix_timestamp_nanos() / 1_000_000,
+ crate::date_time::convert_to_pdt(at)
+ .assume_utc()
+ .format(&Iso8601::<SYNTH_ISO>)
+ .expect("the synthesized instant formats"),
+ per_second
+ .format(&rfc7231)
+ .expect("and renders as an HTTP date"),
+ )
+ };
+
+ assert_eq!(
+ render(0),
+ (
+ 0,
+ "1970-01-01 0:00:00.0".to_string(),
+ 0,
+ 0,
+ "1970-01-01T00:00:00.000Z".to_string(),
+ "Thu, 01 Jan 1970 00:00:00 GMT".to_string(),
+ )
+ );
+ assert_eq!(
+ render(1),
+ (
+ 1_000_000,
+ "1970-01-01 0:00:00.001".to_string(),
+ 1,
+ 1,
+ "1970-01-01T00:00:00.001Z".to_string(),
+ "Thu, 01 Jan 1970 00:00:01 GMT".to_string(),
+ )
+ );
+ }
+
+ /// Consecutive misses at a clock arm synthesize different values.
+ #[test]
+ fn consecutive_misses_at_a_clock_arm_differ() {
+ for occurrence in [0_u32, 1, 998, 12_345] {
+ let (here, next) = (miss(occurrence), miss(occurrence + 1));
+ assert_ne!(
+ here.instant(),
+ next.instant(),
+ "the nanosecond clock held still across occurrence {occurrence}"
+ );
+ assert_ne!(
+ here.instant_at_second_resolution().unix_timestamp(),
+ next.instant_at_second_resolution().unix_timestamp(),
+ "the second clock held still across occurrence {occurrence}"
+ );
+ }
+ }
+
+ /// The counter behind `elapsed::millis_since`, stepping one millisecond.
+ #[test]
+ fn the_elapsed_counter_is_pinned() {
+ let derived: Vec<u128> = (0..4_u32).map(|n| miss(n).elapsed_millis()).collect();
+ assert_eq!(derived, vec![0, 1, 2, 3]);
+ }
+}
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index 9827d20004..4ed5a11998 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -34,7 +34,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 = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false, features = ["error-stack"] }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false, features = ["error-stack"] }
[lints]
workspace = true
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs
index a87f424dce..8a90374338 100644
--- a/crates/diesel_models/src/query/generics.rs
+++ b/crates/diesel_models/src/query/generics.rs
@@ -185,9 +185,8 @@ impl<T> DejaQueryResult for T {}
// shadow-compare), the read-only scalar `count` `Substitute`s (a count is
// a non-seedable scalar; re-running it against a partially-seeded schema
// would only measure seed incompleteness).
-// `sql`/`inputs` are `Secret`-wrapped so their `Debug` output is redacted
-// (bind values / changeset debug strings can carry PII); the deja attribute
-// exprs `.peek()` them at the boundary, and the tape keeps full fidelity.
+// Args are `sql` plus `inputs.binds` as JSON; `debug_sql` only feeds read keys.
+// All three are `Secret`-wrapped so `Debug` redacts them.
// Feature-off, every executor is a plain async fn passthrough.
/// Under `deja`, a row-returning query future resolves to the result paired
@@ -199,6 +198,37 @@ type Captured<T> = (T, Option<Vec<deja::db::WireRow>>);
#[cfg(not(feature = "deja"))]
type Captured<T> = T;
+/// The statement and its binds as JSON, captured only while observation is active.
+#[cfg(feature = "deja")]
+fn capture<Q: QueryFragment<Pg>>(query: &Q) -> (String, serde_json::Value) {
+ if deja::__private::observation_is_active() {
+ capture_statement(query)
+ } else {
+ (String::new(), serde_json::Value::Null)
+ }
+}
+
+/// What an observing call records.
+#[cfg(feature = "deja")]
+fn capture_statement<Q: QueryFragment<Pg>>(query: &Q) -> (String, serde_json::Value) {
+ let captured = deja::db::capture_query(query);
+ (captured.sql, captured.binds)
+}
+#[cfg(not(feature = "deja"))]
+fn capture<Q>(_query: &Q) -> (String, serde_json::Value) {
+ (String::new(), serde_json::Value::Null)
+}
+
+/// A unique violation writes no row, so replay serves the recorded error
+/// instead of inserting into a store that lacks the conflicting row.
+#[cfg(feature = "deja")]
+fn is_unique_violation<R>(out: &Captured<StorageResult<R>>) -> bool {
+ matches!(
+ &out.0,
+ Err(err) if matches!(err.current_context(), errors::DatabaseError::UniqueViolation)
+ )
+}
+
#[cfg_attr(
feature = "deja",
deja::boundary(
@@ -212,13 +242,15 @@ type Captured<T> = T;
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_with_wire(deja::db::StateAxis::Write, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Write, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ neutral_error = is_unique_violation::<R>,
)
)]
async fn execute_generic_insert<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<R>>
where
@@ -226,7 +258,7 @@ where
R: Send + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -258,20 +290,21 @@ where
codec = deja::codec::ResultCodec::<usize, errors::DatabaseError>,
args = deja::db::args("generic_update", table, sql.peek(), inputs.peek()),
state_touch = deja::db::query_state_key("generic_update", table, sql.peek(), inputs.peek()),
- result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),
+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, debug_sql.peek(), __deja_result),
)
)]
async fn execute_generic_update<F>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> StorageResult<usize>
where
F: std::future::Future<Output = Result<usize, DieselError>> + Send,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
fut.await.change_context(errors::DatabaseError::Others)
}
@@ -288,13 +321,14 @@ where
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_with_wire(deja::db::StateAxis::Touch, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Touch, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
)
)]
async fn execute_generic_update_with_results<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<Vec<R>>>
where
@@ -302,7 +336,7 @@ where
R: Send + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -333,13 +367,14 @@ where
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_with_wire(deja::db::StateAxis::Touch, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Touch, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
)
)]
async fn execute_generic_update_by_id<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<R>>
where
@@ -347,7 +382,7 @@ where
R: Send + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -378,20 +413,21 @@ where
codec = deja::codec::ResultCodec::<bool, errors::DatabaseError>,
args = deja::db::args("generic_delete", table, sql.peek(), inputs.peek()),
state_touch = deja::db::query_state_key("generic_delete", table, sql.peek(), inputs.peek()),
- result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),
+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, debug_sql.peek(), __deja_result),
)
)]
async fn execute_generic_delete<F>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> StorageResult<bool>
where
F: std::future::Future<Output = Result<usize, DieselError>> + Send,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
fut.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
@@ -420,13 +456,14 @@ where
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_with_wire(deja::db::StateAxis::Touch, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Touch, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
)
)]
async fn execute_generic_delete_one_with_result<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<R>>
where
@@ -434,7 +471,7 @@ where
R: Send + Clone + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -466,13 +503,14 @@ where
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_with_wire(deja::db::StateAxis::Read, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Read, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
)
)]
async fn execute_generic_find_by_id<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<R>>
where
@@ -480,7 +518,7 @@ where
R: Send + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -512,13 +550,14 @@ where
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_with_wire(deja::db::StateAxis::Read, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Read, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
)
)]
async fn execute_generic_find_one<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<R>>
where
@@ -526,7 +565,7 @@ where
R: Send + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -555,13 +594,14 @@ where
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_with_wire(deja::db::StateAxis::Read, table, sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
+ result = deja::db::recorded_output_with_wire(deja::db::StateAxis::Read, table, debug_sql.peek(), &__deja_result.0, __deja_result.1.as_deref()),
)
)]
async fn execute_generic_filter<F, R>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> Captured<StorageResult<Vec<R>>>
where
@@ -569,7 +609,7 @@ where
R: Send + 'static + DejaQueryResult,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
#[cfg(feature = "deja")]
let (result, wire) = fut.await;
#[cfg(not(feature = "deja"))]
@@ -582,6 +622,8 @@ where
mapped
}
+// Deja: no `on_miss`. A sync miss arm cannot run the count, and a made-up count
+// would be treated as fact.
#[cfg_attr(
feature = "deja",
deja::boundary(
@@ -595,20 +637,21 @@ where
codec = deja::codec::ResultCodec::<usize, errors::DatabaseError>,
args = deja::db::args("generic_count", table, sql.peek(), inputs.peek()),
state_read = deja::db::query_state_key("generic_count", table, sql.peek(), inputs.peek()),
- result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),
+ result = deja::db::recorded_output(deja::db::StateAxis::Read, table, debug_sql.peek(), __deja_result),
)
)]
async fn execute_generic_count<F>(
fut: F,
table: &'static str,
sql: Secret<String>,
+ debug_sql: Secret<String>,
inputs: Secret<serde_json::Value>,
) -> StorageResult<usize>
where
F: std::future::Future<Output = Result<i64, DieselError>> + Send,
{
#[cfg(not(feature = "deja"))]
- let _ = (&table, &sql, &inputs);
+ let _ = (&table, &sql, &debug_sql, &inputs);
let count_i64: i64 = fut
.await
.change_context(errors::DatabaseError::Others)
@@ -641,10 +684,11 @@ where
let debug_values = format!("{values:?}");
let query = diesel::insert_into(<T as HasTable>::table()).values(values);
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
- "values": { "debug": debug_values.as_str() },
+ "binds": binds,
});
#[cfg(feature = "deja")]
@@ -666,6 +710,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -692,10 +737,11 @@ where
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
- "values": { "debug": debug_values.as_str() },
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
});
@@ -708,6 +754,7 @@ where
),
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await
@@ -739,10 +786,11 @@ where
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
- "values": { "debug": debug_values.as_str() },
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
});
@@ -765,6 +813,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -838,11 +887,11 @@ where
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values);
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
- "id": { "debug": format!("{id:?}") },
- "values": { "debug": debug_values.as_str() },
+ "binds": binds,
});
#[cfg(feature = "deja")]
@@ -864,6 +913,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -885,9 +935,11 @@ where
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
});
@@ -900,6 +952,7 @@ where
),
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await
@@ -919,9 +972,11 @@ where
R: Send + Clone + 'static + DejaQueryResult,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
});
@@ -944,6 +999,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -964,10 +1020,11 @@ where
R: Send + 'static + DejaQueryResult,
{
let query = <T as HasTable>::table().find(id.to_owned());
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
- "id": { "debug": format!("{id:?}") },
+ "binds": binds,
});
#[cfg(feature = "deja")]
@@ -989,6 +1046,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -1036,9 +1094,11 @@ where
R: Send + 'static + DejaQueryResult,
{
let query = <T as HasTable>::table().filter(predicate);
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
});
@@ -1061,6 +1121,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -1129,9 +1190,11 @@ where
query = query.order(order);
}
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
"limit": limit,
"offset": offset,
@@ -1157,6 +1220,7 @@ where
fut,
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await;
@@ -1179,9 +1243,11 @@ where
.filter(predicate)
.select(count_star());
- let sql = debug_query::<Pg, _>(&query).to_string();
- logger::debug!(query = %sql);
+ let debug_sql = debug_query::<Pg, _>(&query).to_string();
+ logger::debug!(query = %debug_sql);
+ let (sql, binds) = capture(&query);
let inputs = serde_json::json!({
+ "binds": binds,
"predicate": { "type": std::any::type_name::<P>() },
});
@@ -1194,6 +1260,7 @@ where
),
table_name::<T>(),
Secret::new(sql),
+ Secret::new(debug_sql),
Secret::new(inputs),
)
.await
@@ -1208,3 +1275,84 @@ fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> {
},
}
}
+
+#[cfg(all(test, feature = "deja", feature = "v1"))]
+mod capture_tests {
+ use diesel::{debug_query, pg::Pg, ExpressionMethods, QueryDsl};
+
+ use super::{capture, capture_statement};
+ use crate::schema::payment_attempt;
+
+ /// A routing document with its keys inserted in `order`.
+ fn routing(order: [&str; 2]) -> serde_json::Value {
+ let mut inner = serde_json::Map::new();
+ for method in order {
+ inner.insert(
+ method.to_owned(),
+ serde_json::json!({ "connector": "adyen", "merchant_connector_id": "mca_1" }),
+ );
+ }
+ serde_json::json!({ "algorithm": null, "pre_routing_results": inner })
+ }
+
+ fn update(value: serde_json::Value) -> impl diesel::query_builder::QueryFragment<Pg> {
+ diesel::update(payment_attempt::table.filter(payment_attempt::attempt_id.eq("att_1")))
+ .set(payment_attempt::straight_through_algorithm.eq(Some(value)))
+ }
+
+ /// The same map in two key orders captures identical args.
+ #[test]
+ fn one_routing_map_in_two_orders_records_the_same_args() {
+ let (forward, backward) = (
+ update(routing(["przelewy24", "ach"])),
+ update(routing(["ach", "przelewy24"])),
+ );
+ assert_ne!(
+ debug_query::<Pg, _>(&forward).to_string(),
+ debug_query::<Pg, _>(&backward).to_string(),
+ "premise: diesel renders the map in its iteration order"
+ );
+ let (left, right) = (capture_statement(&forward), capture_statement(&backward));
+ assert_eq!(left, right);
+ assert!(!left.0.contains("-- binds"), "{}", left.0);
+ assert_eq!(
+ left.1
+ .pointer("/$1/pre_routing_results/ach/merchant_connector_id"),
+ Some(&serde_json::json!("mca_1")),
+ "the bound document is captured as a document: {}",
+ left.1
+ );
+ }
+
+ /// With nothing observing, `capture` returns the empty pair.
+ #[test]
+ fn an_unobserved_query_builds_no_statement() {
+ let query = update(routing(["ach", "przelewy24"]));
+ let idle = (String::new(), serde_json::Value::Null);
+ assert_eq!(capture(&query), idle);
+ assert_ne!(capture_statement(&query), idle);
+ }
+}
+
+#[cfg(all(test, feature = "deja"))]
+mod neutral_error_tests {
+ use error_stack::report;
+
+ use super::{errors, is_unique_violation, Captured, StorageResult};
+
+ fn out(result: StorageResult<()>) -> Captured<StorageResult<()>> {
+ (result, None)
+ }
+
+ /// Only a unique violation is state-neutral.
+ #[test]
+ fn only_a_unique_violation_is_state_neutral() {
+ assert!(is_unique_violation(&out(Err(report!(
+ errors::DatabaseError::UniqueViolation
+ )))));
+ assert!(!is_unique_violation(&out(Err(report!(
+ errors::DatabaseError::NotFound
+ )))));
+ assert!(!is_unique_violation(&out(Ok(()))));
+ }
+}
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs
index b0df3afb70..946e0cb5fb 100644
--- a/crates/diesel_models/src/query/merchant_connector_account.rs
+++ b/crates/diesel_models/src/query/merchant_connector_account.rs
@@ -30,11 +30,16 @@ impl MerchantConnectorAccount {
conn: &DatabaseConnectionWithContext<'_>,
merchant_connector_account: MerchantConnectorAccountUpdateInternal,
) -> StorageResult<Self> {
- match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
+ match Box::pin(generics::generic_update_by_id::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
conn,
self.merchant_connector_id.to_owned(),
merchant_connector_account,
- )
+ ))
.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.rs
index a4912c86c4..c4a1c84926 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -243,7 +243,7 @@ impl PaymentMethod {
conn: &DatabaseConnectionWithContext<'_>,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> 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,
_,
_,
@@ -252,7 +252,7 @@ impl PaymentMethod {
conn,
dsl::payment_method_id.eq(self.payment_method_id.to_owned()),
payment_method,
- )
+ ))
.await
{
Err(error) => match error.current_context() {
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index 34800f5e77..2de2dae88f 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -44,7 +44,7 @@ impl PayoutAttempt {
conn: &DatabaseConnectionWithContext<'_>,
payout_attempt_update: PayoutAttemptUpdate,
) -> 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,
_,
_,
@@ -55,7 +55,7 @@ impl PayoutAttempt {
.eq(self.payout_attempt_id.to_owned())
.and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
PayoutAttemptUpdateInternal::from(payout_attempt_update),
- )
+ ))
.await
{
Err(error) => match error.current_context() {
@@ -152,13 +152,18 @@ impl PayoutAttempt {
payout_id: &common_utils::id_type::PayoutId,
payout: PayoutAttemptUpdate,
) -> StorageResult<Self> {
- generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
+ Box::pin(generics::generic_update_with_results::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_id.eq(payout_id.to_owned())),
PayoutAttemptUpdateInternal::from(payout),
- )
+ ))
.await?
.first()
.cloned()
@@ -173,13 +178,18 @@ impl PayoutAttempt {
payout_attempt_id: &str,
payout: PayoutAttemptUpdate,
) -> StorageResult<Self> {
- generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
+ Box::pin(generics::generic_update_with_results::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())),
PayoutAttemptUpdateInternal::from(payout),
- )
+ ))
.await?
.first()
.cloned()
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index a750e35abf..67c8a30324 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -25,6 +25,8 @@ v2 = ["hyperswitch_interfaces/v2", "common_utils/v2"]
deja = [
"dep:bytes",
"dep:deja",
+ "dep:futures",
+ "reqwest/stream",
"dep:http-body",
"dep:http-body-util",
"dep:prost-reflect",
@@ -65,7 +67,7 @@ aws-smithy-types = "1.3.1"
base64 = "0.22.1"
dyn-clone = "1.0.19"
google-cloud-kms = { version = "0.6.0", optional = true }
-deja = { git = "https://github.com/juspay/deja", rev = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false }
error-stack = "0.4.1"
hex = "0.4.3"
hyper = "0.14.32"
@@ -99,6 +101,7 @@ quick-xml = { version = "0.31.0", features = ["serialize"] }
unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.10.09.0", package = "rust-grpc-client" }
open-feature = { version = "0.2.5", optional = true }
bytes = { version = "1.10.1", optional = true }
+futures = { version = "0.3.31", optional = true }
superposition_provider = { version = "0.115.5", optional = true }
superposition_types = "0.115.5"
superposition_sdk = { version = "0.115.5", optional = true }
diff --git a/crates/external_services/src/grpc_client/deja_transport.rs b/crates/external_services/src/grpc_client/deja_transport.rs
index f6c145aaf6..6eddd0db1b 100644
--- a/crates/external_services/src/grpc_client/deja_transport.rs
+++ b/crates/external_services/src/grpc_client/deja_transport.rs
@@ -99,12 +99,6 @@ impl std::fmt::Display for AbsentTransportError {
impl std::error::Error for AbsentTransportError {}
-/// Envelope smuggled through `http::Extensions` from the buffering `run`
-/// closure to the recording `extract` closure — the same trick the HTTP
-/// boundary uses for its response body (`CapturedResponseBody`).
-#[derive(Clone)]
-struct CapturedEnvelope(GrpcResultEnvelope);
-
/// A substituted transport error: the recorded display chain of the original
/// failure. Approximate by design (the original error struct is gone); tonic
/// maps it through `Status::from_error` exactly as it would a live failure.
@@ -266,6 +260,7 @@ where
lexical_path: Some(scope.clone()),
syntax_hash: Some(deja::__private::stable_callsite_hash(&scope)),
span_path: deja::__private::current_span_path(),
+ span_instance: deja::__private::current_span_instance(),
};
// Egress routing is hardcoded: never re-issued on replay.
@@ -290,12 +285,15 @@ where
// Transport present: a miss may be a genuine novel call, so this keeps
// `dispatch_async`'s default substitute-miss fail-stop.
Some(inner) => {
- deja::__private::dispatch_async(
+ deja::__private::owned_dispatch_async(
observation,
move || args_value,
- move || run_and_capture(inner, rebuilt_request),
+ move || passthrough(inner, rebuilt_request),
reconstruct_from_recorded,
- extract_envelope,
+ read_response,
+ record_envelope,
+ deja::__private::round_trip!(Result<http::Response<TonicBody>, BoxError>),
+ None::<fn(&Result<http::Response<TonicBody>, BoxError>) -> bool>,
)
.await
}
@@ -304,88 +302,91 @@ where
// here (replay + Substitute neither runs nor re-runs); an error rather
// than an `unreachable!` so a broken invariant stays legible.
None => {
- deja::__private::dispatch_async_or_miss(
+ deja::__private::owned_dispatch_async(
observation,
move || args_value,
move || async { Err(BoxError::from(AbsentTransportError)) },
- reconstruct_from_recorded,
- extract_envelope,
- // `FailStop` because that is what the thunk below does; the
- // `on_miss` only names the stop. `Absorb` would tell the
- // scorecard a request survived that in fact died here.
- deja::MissPolicy::FailStop,
- // The absent-EXECUTOR fail-stop, not `fail_stop_substitute_miss`:
- // that one offers `replay_strategy = Execute` as the remedy, and
- // with nothing beneath the boundary there is nothing to run. The
- // target names the rpc and authority because `BOUNDARY` and
- // `OPERATION` are module constants shared by every transport this
- // wrapper is installed on.
- move || {
- let target = match authority.as_deref() {
- Some(authority) => format!("{rpc} at {authority}"),
- None => rpc.to_string(),
- };
- deja::__private::fail_stop_absent_executor(BOUNDARY, OPERATION, &target)
+ move |input| match input {
+ deja::__private::ReconstructInput::Hit(recorded) => reconstruct_hit(recorded),
+ // Absent-executor stop: with no transport there is nothing to execute.
+ // The target names the rpc and authority; `BOUNDARY` is shared.
+ deja::__private::ReconstructInput::Miss(_) => {
+ let target = match authority.as_deref() {
+ Some(authority) => format!("{rpc} at {authority}"),
+ None => rpc.to_string(),
+ };
+ deja::__private::fail_stop_absent_executor(BOUNDARY, OPERATION, &target)
+ }
},
+ read_response,
+ record_envelope,
+ deja::__private::round_trip!(Result<http::Response<TonicBody>, BoxError>),
+ None::<fn(&Result<http::Response<TonicBody>, BoxError>) -> bool>,
)
.await
}
}
}
-/// The `run` thunk: forward to the real transport, buffer the response
-/// verbatim (data frames + trailers), and hand tonic a response rebuilt over
-/// the SAME buffer the tape captures — byte-identical parity. The envelope
-/// rides `http::Extensions` to the extractor.
-async fn run_and_capture<S, RB>(
- mut inner: S,
- request: http::Request<TonicBody>,
-) -> Result<http::Response<TonicBody>, BoxError>
-where
- S: tonic::codegen::Service<http::Request<TonicBody>, Response = http::Response<RB>>,
- S::Error: Into<BoxError>,
- RB: http_body::Body<Data = bytes::Bytes> + Send + 'static,
- RB::Error: Into<BoxError>,
-{
- let response = match inner.call(request).await {
+/// The data and trailers as read, or why the body could not be read.
+type ReadResponse = Result<(bytes::Bytes, Option<http::HeaderMap>), String>;
+
+/// Reads the body frame by frame and rebuilds one yielding the same frames, errors included.
+async fn read_response(
+ result: Result<http::Response<TonicBody>, BoxError>,
+) -> (
+ Result<http::Response<TonicBody>, BoxError>,
+ Result<ReadResponse, String>,
+) {
+ let response = match result {
Ok(response) => response,
- Err(error) => return Err(error.into()),
+ Err(error) => return (Err(error), Ok(Ok((bytes::Bytes::new(), None)))),
};
- let (parts, body) = response.into_parts();
- let collected = match http_body_util::BodyExt::collect(body).await {
- Ok(collected) => collected,
- Err(error) => return Err(error.into()),
+ let (parts, mut body) = response.into_parts();
+ let mut frames = Vec::new();
+ let mut data = bytes::BytesMut::new();
+ let mut trailers = None;
+ let failure = loop {
+ match http_body_util::BodyExt::frame(&mut body).await {
+ None => break None,
+ Some(Ok(frame)) => {
+ if let Some(chunk) = frame.data_ref() {
+ data.extend_from_slice(chunk);
+ }
+ if let Some(frame_trailers) = frame.trailers_ref() {
+ trailers = Some(frame_trailers.clone());
+ }
+ frames.push(Ok(frame));
+ }
+ Some(Err(error)) => break Some(error),
+ }
};
- let trailers = collected.trailers().cloned();
- let data = collected.to_bytes();
-
- let envelope = GrpcResultEnvelope::from_response_parts(
- parts.status.as_u16(),
- &parts.headers,
- &data,
- trailers.as_ref(),
- );
- let mut rebuilt =
- http::Response::from_parts(parts, TonicBody::new(BufferedBody::new(data, trailers)));
- rebuilt.extensions_mut().insert(CapturedEnvelope(envelope));
- Ok(rebuilt)
+ let read = match &failure {
+ None => Ok((data.freeze(), trailers)),
+ Some(error) => Err(error.to_string()),
+ };
+ frames.extend(failure.map(Err));
+ let body = http_body_util::StreamBody::new(futures::stream::iter(frames));
+ (
+ Ok(http::Response::from_parts(parts, TonicBody::new(body))),
+ Ok(read),
+ )
}
-/// The `extract` closure: envelope out of the extensions (record path), or a
-/// transport-error envelope from the `Err` arm.
-fn extract_envelope(
+/// The envelope of what was read; a failed read records as a transport error.
+fn record_envelope(
+ read: ReadResponse,
result: &Result<http::Response<TonicBody>, BoxError>,
) -> (serde_json::Value, bool) {
- let envelope = match result {
- Ok(response) => match response.extensions().get::<CapturedEnvelope>() {
- Some(CapturedEnvelope(envelope)) => envelope.clone(),
- // Unreachable on the record path (run_and_capture always stamps
- // it); recorded loudly rather than silently if it ever happens.
- None => GrpcResultEnvelope::TransportError {
- error: "deja: response envelope was not captured".to_owned(),
- },
- },
- Err(error) => GrpcResultEnvelope::TransportError {
+ let envelope = match (result, read) {
+ (Ok(response), Ok((data, trailers))) => GrpcResultEnvelope::from_response_parts(
+ response.status().as_u16(),
+ response.headers(),
+ &data,
+ trailers.as_ref(),
+ ),
+ (Ok(_), Err(reason)) => GrpcResultEnvelope::TransportError { error: reason },
+ (Err(error), _) => GrpcResultEnvelope::TransportError {
error: format!("{error}"),
},
};
@@ -396,9 +397,27 @@ fn extract_envelope(
(value, is_error)
}
-/// The `reconstruct` closure: recorded envelope → the identical wire response
-/// through tonic's own decoder, or the recorded transport failure.
+/// A hit goes to [`reconstruct_hit`]; a miss becomes a transport failure naming the call.
fn reconstruct_from_recorded(
+ input: deja::__private::ReconstructInput<'_>,
+) -> deja::__private::Reconstructed<Result<http::Response<TonicBody>, BoxError>> {
+ match input {
+ deja::__private::ReconstructInput::Hit(recorded) => reconstruct_hit(recorded),
+ // A novel call answers as a transport error, not a stop: no peer answered,
+ // and callers already handle it, so later calls stay observable.
+ deja::__private::ReconstructInput::Miss(miss) => {
+ deja::__private::Reconstructed::Synthesized(Err(format!(
+ "deja: no recorded gRPC response for {}::{} (occurrence {})",
+ miss.component, miss.method, miss.occurrence,
+ )
+ .into()))
+ }
+ }
+}
+
+/// The hit path: recorded envelope -> the identical wire response through
+/// tonic's own decoder, or the recorded transport failure.
+fn reconstruct_hit(
recorded: serde_json::Value,
) -> deja::__private::Reconstructed<Result<http::Response<TonicBody>, BoxError>> {
let Ok(envelope) = serde_json::from_value::<GrpcResultEnvelope>(recorded) else {
@@ -483,6 +502,116 @@ mod tests {
}
}
+ /// The frames tonic polls from `body`, errors as their text.
+ async fn frames(mut body: TonicBody) -> Vec<Result<String, String>> {
+ let mut seen = Vec::new();
+ while let Some(frame) = http_body_util::BodyExt::frame(&mut body).await {
+ seen.push(match frame {
+ Ok(frame) => Ok(format!("{frame:?}")),
+ Err(status) => Err(format!("{:?} {}", status.code(), status.message())),
+ });
+ }
+ seen
+ }
+
+ fn response(
+ frames: Vec<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>,
+ ) -> http::Response<TonicBody> {
+ let body = http_body_util::StreamBody::new(futures::stream::iter(frames));
+ let mut response = http::Response::new(TonicBody::new(body));
+ response.headers_mut().insert(
+ "content-type",
+ http::HeaderValue::from_static("application/grpc"),
+ );
+ response
+ }
+
+ /// The rebuilt body yields the same frames, a mid-stream error at the same frame.
+ #[tokio::test]
+ async fn the_read_body_yields_the_frames_tonic_would_have_seen() {
+ let mut trailers = http::HeaderMap::new();
+ trailers.insert("grpc-status", http::HeaderValue::from_static("0"));
+ let fixtures = || {
+ [
+ vec![
+ Ok(http_body::Frame::data(bytes::Bytes::from_static(
+ b"\0\0\0\0\x02ab",
+ ))),
+ Ok(http_body::Frame::data(bytes::Bytes::from_static(b"cd"))),
+ Ok(http_body::Frame::trailers(trailers.clone())),
+ ],
+ vec![
+ Ok(http_body::Frame::data(bytes::Bytes::from_static(b"\0\0\0"))),
+ Err(tonic::Status::unavailable("connection reset")),
+ ],
+ ]
+ };
+ for (original, through) in fixtures().into_iter().zip(fixtures()) {
+ let fails = original.iter().any(Result::is_err);
+ let direct = frames(response(original).into_body()).await;
+ let (rebuilt, read) = read_response(Ok(response(through))).await;
+ assert_eq!(matches!(read, Ok(Err(_))), fails, "{read:?}");
+ let rebuilt = rebuilt.expect("an Ok stays Ok");
+ assert_eq!(rebuilt.headers()["content-type"], "application/grpc");
+ assert_eq!(frames(rebuilt.into_body()).await, direct);
+ }
+ }
+
+ /// What was read becomes the envelope, a transport error included.
+ #[tokio::test]
+ async fn the_recorded_envelope_is_what_was_read() {
+ let mut trailers = http::HeaderMap::new();
+ trailers.insert("grpc-status", http::HeaderValue::from_static("0"));
+ let data = bytes::Bytes::from_static(b"\0\0\0\0\x02ab");
+ let (value, read) = read_response(Ok(response(vec![
+ Ok(http_body::Frame::data(data.clone())),
+ Ok(http_body::Frame::trailers(trailers.clone())),
+ ])))
+ .await;
+ let (recorded, is_error) = record_envelope(read.expect("the body reads"), &value);
+ let response = value.expect("an Ok stays Ok");
+ let expected = GrpcResultEnvelope::from_response_parts(
+ response.status().as_u16(),
+ response.headers(),
+ &data,
+ Some(&trailers),
+ );
+ assert_eq!(
+ recorded,
+ serde_json::to_value(&expected).expect("serializes")
+ );
+ assert_eq!(is_error, expected.is_err());
+
+ let (value, read) = read_response(Err(BoxError::from("dns error"))).await;
+ let (recorded, is_error) = record_envelope(read.expect("nothing to read"), &value);
+ assert!(is_error);
+ assert_eq!(
+ recorded,
+ serde_json::to_value(GrpcResultEnvelope::TransportError {
+ error: "dns error".to_owned()
+ })
+ .expect("serializes")
+ );
+ }
+
+ /// A body failing mid-read records as a transport error.
+ #[tokio::test]
+ async fn a_body_that_fails_records_as_a_transport_error() {
+ let (value, read) = read_response(Ok(response(vec![
+ Ok(http_body::Frame::data(bytes::Bytes::from_static(b"\0\0\0"))),
+ Err(tonic::Status::unavailable("connection reset")),
+ ])))
+ .await;
+ let (recorded, is_error) = record_envelope(read.expect("the read always reports"), &value);
+ assert!(is_error);
+ let Ok(GrpcResultEnvelope::TransportError { error }) =
+ serde_json::from_value::<GrpcResultEnvelope>(recorded)
+ else {
+ panic!("a failed read records a transport error");
+ };
+ assert!(error.contains("connection reset"), "{error}");
+ }
+
/// Inactive-hook passthrough: real tonic server + wrapped hyper pool,
/// traffic must be untouched in both arms. (The RECORD side needs a
/// separate process, because the global hook OnceLock latches on first
diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rs
index e57cef9ec2..dabddd88a5 100644
--- a/crates/external_services/src/http_client.rs
+++ b/crates/external_services/src/http_client.rs
@@ -88,7 +88,22 @@ pub fn serialize_to_xml_bytes<T: serde::Serialize>(
// outgoing call (e.g. Stripe) is served from the lookup table with no
// network. A recorded value this build cannot reconstruct fail-stops the
// request; it is not a silent fallback to a live call.
- codec = boundary::HttpResponseCodec,
+ owned_codec = boundary::HttpResponseCodec,
+ // A miss answers as a send failure: nobody answered, and a fabricated status
+ // could report a payment outcome that never happened. The url comes from the
+ // recorded args because the real call moves `request`.
+ on_miss = Err(HttpClientError::RequestNotSent(
+ format!(
+ "deja: no recorded response for this outbound call (url {}, occurrence {})",
+ __deja_miss
+ .args
+ .get("url")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("unknown"),
+ __deja_miss.occurrence,
+ ),
+ )
+ .into()),
)
)]
#[instrument(skip_all)]
@@ -250,20 +265,7 @@ pub async fn send_request(
response => response,
};
- #[cfg(feature = "deja")]
- {
- match response {
- Ok(response) if boundary::is_active() => {
- boundary::response_with_captured_body(response).await
- }
- response => response,
- }
- }
-
- #[cfg(not(feature = "deja"))]
- {
- response
- }
+ response
}
fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool {
diff --git a/crates/external_services/src/http_client/boundary.rs b/crates/external_services/src/http_client/boundary.rs
index 6fcc5e07d7..b64759eb41 100644
--- a/crates/external_services/src/http_client/boundary.rs
+++ b/crates/external_services/src/http_client/boundary.rs
@@ -2,58 +2,11 @@ use common_utils::{
errors::CustomResult,
request::{Request, RequestContent},
};
-use deja::DejaHook;
-use error_stack::ResultExt;
use hyperswitch_interfaces::errors::HttpClientError;
use hyperswitch_masking::{ExposeInterface, Maskable, PeekInterface, Secret};
use reqwest::ResponseBuilderExt;
use serde_json::json;
-/// Extension key used to smuggle the captured response body out of the
-/// `send_request` function so that the boundary codec can report it without
-/// consuming the response stream.
-pub(super) struct CapturedResponseBody(pub(super) bytes::Bytes);
-
-pub(super) fn is_active() -> bool {
- deja::global_hook_from_env().is_some_and(|hook| hook.is_active())
-}
-
-pub(super) async fn response_with_captured_body(
- response: reqwest::Response,
-) -> CustomResult<reqwest::Response, HttpClientError> {
- // Eagerly read the response body so the boundary result extractor can
- // report it without consuming the stream a second time. The body is then
- // cloned: one copy is rebuilt into a new reqwest::Response as a reusable
- // Body, the other is stashed in http::Extensions so `response_result` can
- // read it.
- let status = response.status();
- let headers = response.headers().clone();
- let version = response.version();
- let url = response.url().clone();
- let body_bytes = response
- .bytes()
- .await
- .change_context(HttpClientError::ResponseDecodingFailed)
- .attach_printable("Failed to read response body for boundary capture")?;
-
- let mut builder = http::Response::builder()
- .status(status)
- .version(version)
- .url(url);
- for (key, value) in &headers {
- builder = builder.header(key, value);
- }
- let mut http_response = builder.body(body_bytes.clone()).map_err(|_| {
- error_stack::report!(HttpClientError::UnexpectedState)
- .attach_printable("Failed to rebuild HTTP response")
- })?;
- http_response
- .extensions_mut()
- .insert(CapturedResponseBody(body_bytes));
-
- Ok(reqwest::Response::from(http_response))
-}
-
pub(super) fn request_id(request: &Request) -> Option<String> {
request.headers.iter().find_map(|(key, value)| {
if key.eq_ignore_ascii_case(common_utils::consts::X_REQUEST_ID) {
@@ -105,13 +58,6 @@ pub(super) fn request_args(
// their `Debug` output is redacted (response bodies/headers can carry PII or
// credentials); they are `.expose()`d only at the deja handoff, where the tape
// keeps full fidelity.
-fn captured_body_json(response: &reqwest::Response) -> Secret<serde_json::Value> {
- Secret::new(match response.extensions().get::<CapturedResponseBody>() {
- Some(CapturedResponseBody(bytes)) => deja::http::body(bytes),
- None => deja::http::missing_body("response body not captured (missing extension)"),
- })
-}
-
/// Captures response headers, keeping every value under a repeated name.
///
/// This used to `insert` one value per name, so a response carrying three
@@ -134,6 +80,7 @@ fn response_headers_json(response: &reqwest::Response) -> Secret<serde_json::Val
pub(super) fn response_result(
result: &CustomResult<reqwest::Response, HttpClientError>,
+ body: Result<&[u8], &str>,
) -> (Secret<serde_json::Value>, bool) {
(
Secret::new(match result {
@@ -141,10 +88,18 @@ pub(super) fn response_result(
"status": response.status().as_u16(),
"reason": response.status().canonical_reason(),
"response_headers": response_headers_json(response).expose(),
- "response_body": captured_body_json(response).expose(),
+ // A failed read records why; replay fails the body the same way.
+ "response_body": match body {
+ Ok(body) => deja::http::body(body),
+ Err(reason) => json!({ "captured": false, "read_error": reason }),
+ },
}),
+ // The typed variant, not report text: callers branch on it, and report
+ // text varies per build.
Err(error) => json!({
- "error": format!("{error:?}"),
+ "version": 1,
+ "result": "Err",
+ "kind": error.current_context(),
"response_body": {
"captured": false,
},
@@ -160,30 +115,88 @@ pub(super) fn response_result(
#[derive(Debug)]
pub struct HttpResponseCodec;
-impl deja::codec::ReplayCodec for HttpResponseCodec {
+impl deja::codec::OwnedReplayCodec for HttpResponseCodec {
type Value = CustomResult<reqwest::Response, HttpClientError>;
+ /// The body as read, or why reading it failed.
+ type Read = Result<bytes::Bytes, String>;
+
+ /// Reads the body and rebuilds the response from the original's parts.
+ async fn read(value: Self::Value) -> (Self::Value, Result<Self::Read, String>) {
+ let response = match value {
+ Ok(response) => response,
+ Err(report) => return (Err(report), Ok(Ok(bytes::Bytes::new()))),
+ };
+ let status = response.status();
+ let version = response.version();
+ let headers = response.headers().clone();
+ let url = response.url().clone();
+ // Sized only if the original knew its length.
+ let sized = response.content_length().is_some();
+ let (body, read) = match response.bytes().await {
+ Ok(bytes) => {
+ let body =
+ if sized {
+ reqwest::Body::from(bytes.clone())
+ } else {
+ reqwest::Body::wrap_stream(futures::stream::once(futures::future::ready(
+ Ok::<_, std::convert::Infallible>(bytes.clone()),
+ )))
+ };
+ (body, Ok(bytes))
+ }
+ Err(error) => {
+ let reason = error.to_string();
+ let body = reqwest::Body::wrap_stream(futures::stream::once(
+ futures::future::ready(Err::<bytes::Bytes, _>(error)),
+ ));
+ (body, Err(reason))
+ }
+ };
+ let mut response = match http::Response::builder().url(url).body(()) {
+ Ok(response) => response.map(|()| body),
+ Err(_) => http::Response::new(body),
+ };
+ *response.status_mut() = status;
+ *response.version_mut() = version;
+ *response.headers_mut() = headers;
+ (Ok(reqwest::Response::from(response)), Ok(read))
+ }
- fn capture(value: &Self::Value) -> (serde_json::Value, bool) {
- let (payload, is_error) = response_result(value);
+ fn record(read: Self::Read, value: &Self::Value) -> (serde_json::Value, bool) {
+ let (payload, is_error) = response_result(value, read.as_deref().map_err(String::as_str));
// The deja handoff: the tape records the full-fidelity value.
(payload.expose(), is_error)
}
fn reconstruct(recorded: serde_json::Value) -> Option<Self::Value> {
+ if recorded.get("result").and_then(serde_json::Value::as_str) == Some("Err") {
+ return replay_error(&recorded).map(Err);
+ }
replay_response(&recorded).map(Ok)
}
}
+/// Rebuilds a recorded `send_request` error from its typed variant.
+fn replay_error(recorded: &serde_json::Value) -> Option<error_stack::Report<HttpClientError>> {
+ let kind = recorded.get("kind")?.clone();
+ serde_json::from_value::<HttpClientError>(kind)
+ .ok()
+ .map(|error| error_stack::report!(error))
+}
+
/// Rebuilds a `reqwest::Response` from a recorded `response_result` payload, so
/// a replayed connector call is served from the tape and touches no network.
///
/// Headers are read as an array of values per name; any other shape is a
-/// pre-fix recording that had already lost its repeats, so it is refused.
-/// `None` fail-stops with a named reason — never a fallback to a live call.
+/// recording that lost its repeats, so it returns `None`, which fail-stops the call.
pub(super) fn replay_response(recorded: &serde_json::Value) -> Option<reqwest::Response> {
let status_code = u16::try_from(recorded.get("status")?.as_u64()?).ok()?;
let status = http::StatusCode::from_u16(status_code).ok()?;
+ let read_error = recorded
+ .get("response_body")
+ .and_then(|body| body.get("read_error"))
+ .and_then(serde_json::Value::as_str);
let raw_bytes: Vec<u8> = recorded
.get("response_body")
.and_then(|body| body.get("raw_bytes"))
@@ -201,7 +214,18 @@ pub(super) fn replay_response(recorded: &serde_json::Value) -> Option<reqwest::R
}
}
}
- let http_response = builder.body(bytes::Bytes::from(raw_bytes)).ok()?;
+ let body = match read_error {
+ Some(reason) => {
+ reqwest::Body::wrap_stream(futures::stream::once(futures::future::ready(Err::<
+ bytes::Bytes,
+ _,
+ >(
+ std::io::Error::other(reason.to_owned()),
+ ))))
+ }
+ None => reqwest::Body::from(bytes::Bytes::from(raw_bytes)),
+ };
+ let http_response = builder.body(body).ok()?;
Some(reqwest::Response::from(http_response))
}
@@ -267,7 +291,7 @@ mod tests {
);
let result: CustomResult<reqwest::Response, HttpClientError> = Ok(source);
- let (captured, _) = response_result(&result);
+ let (captured, _) = response_result(&result, Ok(b"{}"));
let captured = captured.expose();
let reconstructed =
@@ -302,4 +326,266 @@ mod tests {
"a pre-fix recording must refuse rather than replay with its headers dropped"
);
}
+
+ /// Recording a reconstructed response reproduces the whole recorded payload.
+ #[test]
+ fn capturing_a_reconstructed_response_reproduces_the_recording() {
+ use deja::codec::OwnedReplayCodec;
+ const BODY: &[u8] = b"{\"ok\":true}";
+
+ let mut builder = http::Response::builder().status(200);
+ for (name, value) in [("content-type", "application/json"), ("set-cookie", "a=1")] {
+ builder = builder.header(name, value);
+ }
+ let source = builder
+ .body(bytes::Bytes::from_static(BODY))
+ .expect("failed to build the test response");
+ let (first, read) = block_on(HttpResponseCodec::read(Ok(reqwest::Response::from(source))));
+ let captured = HttpResponseCodec::record(read.expect("the body reads"), &first).0;
+
+ let reconstructed = HttpResponseCodec::reconstruct(captured.clone())
+ .expect("a captured response must reconstruct");
+ let (second, read) = block_on(HttpResponseCodec::read(reconstructed));
+ let recaptured = HttpResponseCodec::record(read.expect("the body reads"), &second).0;
+
+ assert_eq!(
+ recaptured, captured,
+ "record(read(reconstruct(v))) must equal v"
+ );
+ }
+
+ const GZIPPED: [u8; 52] = [
+ 31, 139, 8, 0, 0, 0, 0, 0, 2, 255, 171, 86, 202, 200, 44, 41, 86, 178, 170, 86, 42, 201,
+ 47, 73, 204, 1, 49, 202, 18, 115, 74, 83, 149, 172, 12, 107, 117, 160, 114, 209, 177, 181,
+ 181, 0, 3, 122, 183, 221, 40, 0, 0, 0,
+ ];
+
+ /// Serves `reply` to every connection, so one fixture can be fetched twice.
+ #[allow(
+ clippy::expect_used,
+ reason = "test helper: a free fn, so allow-expect-in-tests does not cover it; a fixture that cannot serve should fail the test loudly"
+ )]
+ fn serve(reply: Vec<u8>) -> String {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
+ let url = format!("http://{}/charge", listener.local_addr().expect("addr"));
+ std::thread::spawn(move || {
+ for mut stream in listener.incoming().flatten() {
+ let mut request = [0u8; 4096];
+ let _ = stream.read(&mut request);
+ let _ = stream.write_all(&reply);
+ }
+ });
+ url
+ }
+
+ /// What a caller can observe: parts, length, remote address, then the body.
+ async fn observed(
+ response: reqwest::Response,
+ ) -> (String, Option<u64>, bool, Result<bytes::Bytes, String>) {
+ let parts = format!(
+ "{:?} {:?} {:?} {}",
+ response.status(),
+ response.version(),
+ response.headers(),
+ response.url(),
+ );
+ let length = response.content_length();
+ let has_remote = response.remote_addr().is_some();
+ let body = response.bytes().await.map_err(|error| error.to_string());
+ (parts, length, has_remote, body)
+ }
+
+ /// Every accessor reads the same through the codec for sized, chunked, gzip and truncated
+ /// bodies, except `remote_addr` (private to reqwest) and a truncated body's `content_length`.
+ #[test]
+ fn the_caller_observes_the_same_response_through_the_codec() {
+ use deja::codec::OwnedReplayCodec;
+ let body = br#"{"id":"ch_1","status":"succeeded"}"#;
+ let reply = |head: String, payload: &[u8]| [head.as_bytes(), b"\r\n", payload].concat();
+ let fixtures = [
+ (
+ "sized",
+ reply(
+ format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
+ set-cookie: a=1\r\nset-cookie: b=2\r\ncontent-length: {}\r\n",
+ body.len()
+ ),
+ body,
+ ),
+ true,
+ ),
+ (
+ "chunked",
+ reply(
+ format!(
+ "HTTP/1.1 402 Payment Required\r\ntransfer-encoding: chunked\r\n\r\n{:x}",
+ body.len()
+ ),
+ &[&body[..], b"\r\n0\r\n\r\n"].concat(),
+ ),
+ true,
+ ),
+ (
+ "gzip",
+ reply(
+ format!(
+ "HTTP/1.1 200 OK\r\ncontent-encoding: gzip\r\ncontent-length: {}\r\n",
+ GZIPPED.len()
+ ),
+ &GZIPPED,
+ ),
+ true,
+ ),
+ (
+ "truncated",
+ reply(
+ "HTTP/1.1 200 OK\r\ncontent-length: 400\r\n".to_owned(),
+ body,
+ ),
+ false,
+ ),
+ ];
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("a test runtime");
+ runtime.block_on(async {
+ let client = reqwest::Client::new();
+ for (name, fixture, reads) in fixtures {
+ let url = serve(fixture);
+ let fetch = || async {
+ client
+ .post(&url)
+ .send()
+ .await
+ .expect("the fixture server answers")
+ };
+ let (direct_parts, direct_length, direct_remote, direct_body) =
+ observed(fetch().await).await;
+ let (rebuilt, read) = HttpResponseCodec::read(Ok(fetch().await)).await;
+ assert_eq!(matches!(read, Ok(Ok(_))), reads, "{name}: {read:?}");
+ let (parts, length, remote, rebuilt_body) =
+ observed(rebuilt.expect("an Ok stays Ok")).await;
+ assert_eq!(direct_parts, parts, "{name}: the parts differ");
+ assert_eq!(
+ (direct_remote, remote),
+ (true, false),
+ "{name}: the known difference, remote_addr"
+ );
+ assert_eq!(direct_body.is_ok(), reads, "{name}: {direct_body:?}");
+ if reads {
+ assert_eq!(direct_length, length, "{name}: the length differs");
+ assert_eq!(direct_body, rebuilt_body, "{name}: the body differs");
+ } else {
+ assert_eq!(
+ (direct_length, length),
+ (Some(400), None),
+ "{name}: the known difference, a failed body's length"
+ );
+ assert!(rebuilt_body.is_err(), "{name}: the read failure survives");
+ }
+ }
+ });
+ }
+
+ /// A failed read records status, headers and why, and replays as a failing body.
+ #[test]
+ fn a_failed_read_replays_as_a_body_that_fails() {
+ use deja::codec::OwnedReplayCodec;
+ let url = serve(
+ b"HTTP/1.1 502 Bad Gateway\r\nx-request-id: r-1\r\ncontent-length: 400\r\n\r\n{\"partial\":"
+ .to_vec(),
+ );
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("a test runtime");
+ runtime.block_on(async {
+ let response = reqwest::Client::new()
+ .post(&url)
+ .send()
+ .await
+ .expect("the fixture server answers");
+ let (value, read) = HttpResponseCodec::read(Ok(response)).await;
+ let (recorded, is_error) =
+ HttpResponseCodec::record(read.expect("the read always reports"), &value);
+ assert!(!is_error, "the call returned its response");
+ assert!(
+ recorded.pointer("/response_body/read_error").is_some(),
+ "the tape names the failed read: {recorded}"
+ );
+ let replayed = HttpResponseCodec::reconstruct(recorded)
+ .expect("a failed read rebuilds")
+ .expect("as a response");
+ assert_eq!(replayed.status().as_u16(), 502);
+ assert_eq!(replayed.headers()["x-request-id"], "r-1");
+ assert!(replayed.bytes().await.is_err(), "the replayed body fails");
+ });
+ }
+
+ /// The codec's futures here never wait on I/O.
+ fn block_on<F: std::future::Future>(future: F) -> F::Output {
+ let mut context = std::task::Context::from_waker(std::task::Waker::noop());
+ let mut future = std::pin::pin!(future);
+ loop {
+ if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut context) {
+ return output;
+ }
+ }
+ }
+
+ /// A recorded error rebuilds as the same variant and re-records identically.
+ #[test]
+ fn a_recorded_error_rebuilds_its_variant() {
+ for error in [
+ HttpClientError::RequestNotSent("error sending request".to_string()),
+ HttpClientError::RequestTimeoutReceived,
+ ] {
+ let first: CustomResult<reqwest::Response, HttpClientError> =
+ Err(error_stack::report!(error.clone()));
+ let (captured, is_error) = response_result(&first, Ok(&[]));
+ let captured = captured.expose();
+ assert!(is_error);
+
+ let rebuilt =
+ <HttpResponseCodec as deja::codec::OwnedReplayCodec>::reconstruct(captured.clone())
+ .expect("a typed error must reconstruct");
+ let Err(report) = &rebuilt else {
+ panic!("a recorded error must rebuild as an error");
+ };
+ assert_eq!(report.current_context(), &error);
+ assert_eq!(response_result(&rebuilt, Ok(&[])).0.expose(), captured);
+ }
+ }
+
+ /// A typed DNS failure, as recorded for an unreachable internal service, rebuilds.
+ #[test]
+ fn the_recorded_dns_failure_rebuilds() {
+ let recorded = serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": {"RequestNotSent": "error sending request for url (http://service.internal/rule): error trying to connect: dns error: failed to lookup address information: Name or service not known"},
+ "response_body": {"captured": false},
+ });
+ let rebuilt = <HttpResponseCodec as deja::codec::OwnedReplayCodec>::reconstruct(recorded)
+ .expect("the recorded dns failure must reconstruct");
+ assert!(matches!(
+ rebuilt.as_ref().map_err(|report| report.current_context()),
+ Err(HttpClientError::RequestNotSent(message)) if message.contains("dns error")
+ ));
+ }
+
+ /// A text-only error recording has no variant to rebuild, so it is refused.
+ #[test]
+ fn a_text_only_error_recording_is_refused() {
+ let recorded = serde_json::json!({
+ "error": "Failed to send request to connector error sending request for url (http://service.internal/rule): error trying to connect: dns error: failed to lookup address information: Name or service not known",
+ "response_body": {"captured": false},
+ });
+ assert!(
+ <HttpResponseCodec as deja::codec::OwnedReplayCodec>::reconstruct(recorded).is_none()
+ );
+ }
}
diff --git a/crates/external_services/src/superposition.rs b/crates/external_services/src/superposition.rs
index 769cacf004..654233b1f1 100644
--- a/crates/external_services/src/superposition.rs
+++ b/crates/external_services/src/superposition.rs
@@ -46,7 +46,7 @@ use crate::config_metrics;
// the tape on replay — no live Superposition service is consulted in replay. The
// WHOLE `CustomResult<T, SuperpositionError>` round-trips ("recording threw ⇒
// replay throws"). Identity is rank-2 span-path (no call-site id). A genuine tape
-// MISS returns `Err(SuperpositionError)` (via `dispatch_async_or_miss`) so the
+// MISS returns `Err(SuperpositionError)` (the `Miss` arm of `reconstruct`) so the
// caller's `fetch_db_config` ladder degrades to DB/default and replay progresses,
// instead of the egress fail-stop. Reads are deja's per-request business config;
// writes are deliberately NOT wrapped (they are leaving the OLTP path).
@@ -87,9 +87,23 @@ mod deja_boundary {
/// Rebuild the typed `CustomResult` from a recorded tape value. A recorded
/// `Err` replays as `Err(report!(E))` carrying the SAME typed context.
pub(super) fn reconstruct<T: serde::de::DeserializeOwned>(
- recorded: serde_json::Value,
+ input: deja::__private::ReconstructInput<'_>,
) -> deja::__private::Reconstructed<CustomResult<T, SuperpositionError>> {
- use deja::__private::Reconstructed;
+ use deja::__private::{ReconstructInput, Reconstructed};
+ // A miss returns an error the caller survives via its DB/default fallback.
+ // `Synthesized` keeps the miss scored; the message depends only on the miss.
+ let recorded = match input {
+ ReconstructInput::Hit(recorded) => recorded,
+ ReconstructInput::Miss(miss) => {
+ return Reconstructed::Synthesized(Err(report!(SuperpositionError::NotFound(
+ format!(
+ "deja replay: no recorded Superposition value for `{}` (novel config \
+ read); caller falls back to DB/default",
+ miss.method
+ )
+ ))));
+ }
+ };
let Some(object) = recorded.as_object() else {
return Reconstructed::Failed(format!(
"superposition envelope is not an object: {recorded}"
@@ -186,6 +200,7 @@ mod deja_boundary {
lexical_path: Some(scope.clone()),
syntax_hash: Some(deja::__private::stable_callsite_hash(&scope)),
span_path: deja::__private::current_span_path(),
+ span_instance: deja::__private::current_span_instance(),
};
let semantics = deja::__private::BoundarySemantics {
@@ -205,22 +220,13 @@ mod deja_boundary {
correlation,
);
- deja::__private::dispatch_async_or_miss(
+ deja::__private::dispatch_async(
observation,
move || args,
run,
reconstruct::<T>,
capture::<T>,
- // `Absorb`: the thunk hands back an error the caller survives —
- // the DB->default fallback runs and the correlation continues. The
- // miss is still scored, only named as survivable.
- deja::MissPolicy::Absorb,
- move || {
- Err(report!(SuperpositionError::NotFound(format!(
- "deja replay: no recorded Superposition value for `{operation}` (novel \
- config read); caller falls back to DB/default"
- ))))
- },
+ deja::__private::round_trip!(CustomResult<T, SuperpositionError>),
)
.await
}
diff --git a/crates/hyperswitch_interfaces/src/api_client.rs b/crates/hyperswitch_interfaces/src/api_client.rs
index becce081ac..f3302d6e3c 100644
--- a/crates/hyperswitch_interfaces/src/api_client.rs
+++ b/crates/hyperswitch_interfaces/src/api_client.rs
@@ -295,7 +295,7 @@ where
None,
)
.await;
- let external_latency = current_time.elapsed().as_millis();
+ let external_latency = common_utils::elapsed::millis_since(current_time);
logger::info!(raw_connector_request=?masked_request_body);
let status_code = response
.as_ref()
diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs
index aaa7a41c09..ce76d51133 100644
--- a/crates/hyperswitch_interfaces/src/errors.rs
+++ b/crates/hyperswitch_interfaces/src/errors.rs
@@ -173,7 +173,7 @@ impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
// http client errors
#[allow(missing_docs, missing_debug_implementations)]
-#[derive(Debug, Clone, thiserror::Error, PartialEq)]
+#[derive(Debug, Clone, thiserror::Error, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum HttpClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml
index b150fad04f..ef89f88caf 100644
--- a/crates/redis_interface/Cargo.toml
+++ b/crates/redis_interface/Cargo.toml
@@ -35,7 +35,7 @@ fred = { version = "8.0.6", optional = true, features = [
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }
-deja = { git = "https://github.com/juspay/deja", rev = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false, features = ["error-stack"] }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false, features = ["error-stack", "fred"] }
hyperswitch_masking = "0.0.1"
router_env = { version = "0.1.0", path = "../router_env", optional = true }
diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rs
index 787b2505d6..8a443297d9 100644
--- a/crates/redis_interface/src/module/fred/commands.rs
+++ b/crates/redis_interface/src/module/fred/commands.rs
@@ -1042,6 +1042,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "increment_fields_in_hash",
+ codec = deja::codec::ResultCodec::<Vec<usize>, errors::RedisError>,
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1466,6 +1467,8 @@ impl super::RedisConnectionWithContext {
.change_context(errors::RedisError::DeleteHashFieldFailed)
}
+ // Deja: no `on_miss`, unlike the redis-rs twin. A miss arm must answer with the
+ // member count, and this identity carries only the key.
#[cfg_attr(
feature = "deja",
deja::redis(
@@ -1509,6 +1512,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "stream_append_entry",
+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -1560,6 +1564,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "stream_delete_entries",
+ codec = deja::codec::ResultCodec::<usize, errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -1592,6 +1597,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "stream_trim_entries",
+ codec = deja::codec::ResultCodec::<usize, errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -1626,6 +1632,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "stream_acknowledge_entries",
+ codec = deja::codec::ResultCodec::<usize, errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -1848,6 +1855,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "append_elements_to_list",
+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1942,6 +1950,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "lpop_list_elements",
+ codec = deja::codec::ResultCodec::<Vec<String>, errors::RedisError>,
args = {
serde_json::json!({
"key": key.as_str(),
@@ -1976,6 +1985,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "consumer_group_create",
+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -2020,6 +2030,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "consumer_group_destroy",
+ codec = deja::codec::ResultCodec::<crate::types::ConsumerGroupDestroyReply, errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -2054,6 +2065,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "consumer_group_delete_consumer",
+ codec = deja::codec::ResultCodec::<usize, errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -2090,6 +2102,7 @@ impl super::RedisConnectionWithContext {
deja::redis(
replay = Substitute,
operation = "consumer_group_set_last_id",
+ codec = deja::codec::ResultCodec::<String, errors::RedisError>,
args = {
serde_json::json!({
"key": stream.as_str(),
@@ -2121,47 +2134,33 @@ impl super::RedisConnectionWithContext {
Ok(id_str)
}
+ // Records the raw wire reply; the public method converts it to `R`, so callers
+ // need no serde bounds.
+ #[cfg(feature = "deja")]
#[instrument(level = "DEBUG", skip(self))]
- #[cfg_attr(
- feature = "deja",
- deja::redis(
- replay = Substitute,
- operation = "consumer_group_set_message_owner",
- args = {
- serde_json::json!({
- "key": stream.as_str(),
- "command": "XCLAIM",
- "group": group,
- "consumer": consumer,
- })
- },
- // Generic `R: FromRedis` is NOT `Debug`, so the default `result_debug`
- // capture would not compile. Record only the ok/err verdict (record-only
- // leaf — no replay reconstruction needed).
- result = {
- (
- match &__deja_result {
- Ok(_) => serde_json::json!({"ok": true}),
- Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),
- },
- __deja_result.is_err(),
- )
- },
- )
+ #[deja::redis(
+ replay = Substitute,
+ operation = "consumer_group_set_message_owner",
+ codec = deja::codec::ResultCodec::<RedisWireValue, errors::RedisError>,
+ args = {
+ serde_json::json!({
+ "key": stream.as_str(),
+ "command": "XCLAIM",
+ "group": group,
+ "consumer": consumer,
+ })
+ },
)]
- pub async fn consumer_group_set_message_owner<R>(
+ async fn consumer_group_set_message_owner_raw(
&self,
stream: &RedisKey,
group: &str,
consumer: &str,
min_idle_time: u64,
ids: Vec<String>,
- ) -> CustomResult<R, errors::RedisError>
- where
- R: FromRedis + Unpin + Send + 'static,
- {
+ ) -> CustomResult<RedisWireValue, errors::RedisError> {
let fred_ids: MultipleIDs = ids.into();
- track_redis_call(
+ let value: RedisValue = track_redis_call(
self.request_id.as_deref(),
self.redis_conn.event_emitter.as_ref(),
RedisOperation::ConsumerGroupSetMessageOwner,
@@ -2179,47 +2178,83 @@ impl super::RedisConnectionWithContext {
),
)
.await
- .change_context(errors::RedisError::ConsumerGroupClaimFailed)
+ .change_context(errors::RedisError::ConsumerGroupClaimFailed)?;
+ Ok(value.into())
}
#[instrument(level = "DEBUG", skip(self))]
- #[cfg_attr(
- feature = "deja",
- deja::redis(
- replay = Substitute,
- operation = "evaluate_redis_script",
- args = {
- serde_json::json!({
- "command": "EVAL",
- "key_count": key.len(),
- })
- },
- // Generic `T` is NOT `Debug`, so the default `result_debug` capture
- // would not compile. Record only the ok/err verdict (record-only leaf —
- // an EVAL result is never reconstructed without an explicit override).
- result = {
- (
- match &__deja_result {
- Ok(_) => serde_json::json!({"ok": true}),
- Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),
- },
- __deja_result.is_err(),
- )
- },
- )
+ pub async fn consumer_group_set_message_owner<R>(
+ &self,
+ stream: &RedisKey,
+ group: &str,
+ consumer: &str,
+ min_idle_time: u64,
+ ids: Vec<String>,
+ ) -> CustomResult<R, errors::RedisError>
+ where
+ R: FromRedis + Unpin + Send + 'static,
+ {
+ #[cfg(feature = "deja")]
+ {
+ let raw = self
+ .consumer_group_set_message_owner_raw(stream, group, consumer, min_idle_time, ids)
+ .await?;
+ let value: RedisValue = raw.try_into().map_err(|err: fred::error::RedisError| {
+ report!(err).change_context(errors::RedisError::ConsumerGroupClaimFailed)
+ })?;
+ R::from_value(value).change_context(errors::RedisError::ConsumerGroupClaimFailed)
+ }
+
+ #[cfg(not(feature = "deja"))]
+ {
+ let fred_ids: MultipleIDs = ids.into();
+ track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::ConsumerGroupSetMessageOwner,
+ self.redis_conn.pool.xclaim(
+ stream.tenant_aware_key(&self.redis_conn),
+ group,
+ consumer,
+ min_idle_time,
+ fred_ids,
+ None,
+ None,
+ None,
+ false,
+ false,
+ ),
+ )
+ .await
+ .change_context(errors::RedisError::ConsumerGroupClaimFailed)
+ }
+ }
+
+ // Records the raw wire reply; `T` is converted through fred after substitution.
+ #[cfg(feature = "deja")]
+ #[instrument(level = "DEBUG", skip(self))]
+ #[deja::redis(
+ replay = Substitute,
+ operation = "evaluate_redis_script",
+ codec = deja::codec::ResultCodec::<RedisWireValue, errors::RedisError>,
+ args = {
+ serde_json::json!({
+ "command": "EVAL",
+ "key_count": key.len(),
+ })
+ },
)]
- pub async fn evaluate_redis_script<V, T>(
+ async fn evaluate_redis_script_raw<V>(
&self,
lua_script: &'static str,
key: Vec<String>,
values: V,
- ) -> CustomResult<T, errors::RedisError>
+ ) -> CustomResult<RedisWireValue, errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
- T: serde::de::DeserializeOwned + FromRedis,
{
- let val: T = track_redis_call(
+ let value: RedisValue = track_redis_call(
self.request_id.as_deref(),
self.redis_conn.event_emitter.as_ref(),
RedisOperation::EvaluateRedisScript,
@@ -2227,7 +2262,44 @@ impl super::RedisConnectionWithContext {
)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?;
- Ok(val)
+ Ok(value.into())
+ }
+
+ #[instrument(level = "DEBUG", skip(self))]
+ pub async fn evaluate_redis_script<V, T>(
+ &self,
+ lua_script: &'static str,
+ key: Vec<String>,
+ values: V,
+ ) -> CustomResult<T, errors::RedisError>
+ where
+ V: TryInto<MultipleValues> + Debug + Send + Sync,
+ V::Error: Into<fred::error::RedisError> + Send + Sync,
+ T: serde::de::DeserializeOwned + FromRedis,
+ {
+ #[cfg(feature = "deja")]
+ {
+ let raw = self
+ .evaluate_redis_script_raw(lua_script, key, values)
+ .await?;
+ let value: RedisValue = raw.try_into().map_err(|err: fred::error::RedisError| {
+ report!(err).change_context(errors::RedisError::IncrementHashFieldFailed)
+ })?;
+ T::from_value(value).change_context(errors::RedisError::IncrementHashFieldFailed)
+ }
+
+ #[cfg(not(feature = "deja"))]
+ {
+ let val: T = track_redis_call(
+ self.request_id.as_deref(),
+ self.redis_conn.event_emitter.as_ref(),
+ RedisOperation::EvaluateRedisScript,
+ self.redis_conn.pool.eval(lua_script, key, values),
+ )
+ .await
+ .change_context(errors::RedisError::IncrementHashFieldFailed)?;
+ Ok(val)
+ }
}
#[instrument(level = "DEBUG", skip(self))]
diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rs
index 771aae7933..63fb8f70dd 100644
--- a/crates/redis_interface/src/module/redis_rs/commands.rs
+++ b/crates/redis_interface/src/module/redis_rs/commands.rs
@@ -1172,16 +1172,39 @@ impl super::RedisConnectionWithContext {
#[cfg_attr(
feature = "deja",
deja::redis(
+ // Substitute: the reply is the collision verdict, and the seeded replay set
+ // starts empty, so re-running SADD would always report "no collision".
replay = Substitute,
operation = "sadd",
codec = deja::codec::ResultCodec::<SaddReply, errors::RedisError>,
state_write = key.tenant_aware_key(&self.redis_conn),
args = {
+ // `members` decides the reply, so it is part of the identity. Sorted
+ // because SADD is a set but `args_hash` is order-dependent for arrays.
+ let mut members_captured: Vec<String> =
+ redis::ToRedisArgs::to_redis_args(&members)
+ .into_iter()
+ .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
+ .collect();
+ members_captured.sort();
serde_json::json!({
"key": key.as_str(),
"command": "SADD",
+ "members": members_captured,
})
},
+ // A novel SADD answers "every member was new". This can hide a real
+ // collision, but the miss is already reported as a divergence and a
+ // fail-stop would blind every later call.
+ on_miss = Ok(SaddReply::KeySet(
+ __deja_miss
+ .args
+ .get("members")
+ .and_then(serde_json::Value::as_array)
+ .map(Vec::len)
+ .and_then(|count| i64::try_from(count).ok())
+ .unwrap_or(0),
+ )),
)
)]
#[instrument(level = "DEBUG", skip(self))]
diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs
index 0a4c7286e7..57ee508f47 100644
--- a/crates/redis_interface/src/types.rs
+++ b/crates/redis_interface/src/types.rs
@@ -335,6 +335,7 @@ pub enum SaddReply {
/// Reply from `XGROUP DESTROY`.
#[derive(Debug, Eq, PartialEq)]
+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]
pub enum ConsumerGroupDestroyReply {
Destroyed,
NotFound,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index fbd464d33f..462295474c 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -165,6 +165,10 @@ deja = [
"redis_interface/deja",
"hyperswitch_domain_models/deja",
"storage_impl/deja",
+ # analytics is an optional dependency, but `release` and `v1` each enable it
+ # through several of their features, so this seam is present in every
+ # shipped build. The `?` matters only for a build that enables none of them.
+ "analytics?/deja",
]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
@@ -303,8 +307,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 = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false }
-deja-core = { git = "https://github.com/juspay/deja", rev = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false, features = ["error-stack"] }
+deja-core = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", 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 = [
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 04e3ba9c23..0cc7e8f8f7 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -73,6 +73,14 @@ use crate::{
deja::id(
component = "router::admin",
operation = "create_merchant_publishable_key",
+ on_miss = {
+ use common_utils::synth_shape::Synthesize as _;
+ format!(
+ "pk_{}_{}",
+ router_env::env::prefix_for_env(),
+ __deja_miss.uuid().simple()
+ )
+ },
codec = SerdeCodec,
)
)]
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index a4c8c9d85a..7ec9306a3b 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -92,7 +92,8 @@ macro_rules! unimplemented_payment_method {
macro_rules! impl_error_type {
($name: ident, $arg: tt) => {
- #[derive(Debug)]
+ // Serializable so `ResultCodec` can replay a recorded failure as itself.
+ #[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct $name;
impl_error_display!($name, $arg);
@@ -274,7 +275,9 @@ pub enum GooglePayDecryptionError {
InvalidGatewayMerchantId,
}
+// Serializable under `deja` so a recorded error replays as the same variant.
#[derive(Debug, Clone, thiserror::Error)]
+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]
pub enum RoutingError {
#[error("Merchant routing algorithm not found in cache")]
CacheMiss,
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index ed60343cfb..54fade8a98 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -6,7 +6,9 @@ pub type UserResult<T> = CustomResult<T, UserErrors>;
pub type UserResponse<T> = CustomResult<ApplicationResponse<T>, UserErrors>;
pub mod sample_data;
+// Serializable under `deja` so a recorded error replays as the same variant.
#[derive(Debug, thiserror::Error)]
+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]
pub enum UserErrors {
#[error("User InternalServerError")]
InternalServerError,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index e6ac806bb7..6f9db970d3 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -3806,9 +3806,10 @@ pub async fn network_tokenize_and_vault_the_pmd(
})
})?;
- let (resp, network_token_req_ref_id) =
- network_tokenization::make_card_network_tokenization_request(state, card_data, customer_id)
- .await?;
+ let (resp, network_token_req_ref_id) = Box::pin(
+ network_tokenization::make_card_network_tokenization_request(state, card_data, customer_id),
+ )
+ .await?;
let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp);
let vaulting_resp = vault::add_payment_method_to_vault(
@@ -3879,7 +3880,7 @@ pub async fn generate_network_token_for_payment_method(
// The per-payment-method opt-in was recorded when the task was scheduled and is not persisted
// on the payment method, so request tokenization with the toggle enabled here. The
// profile-level flag is still passed through and re-checked by the callee.
- let network_tokenization_resp = network_tokenize_and_vault_the_pmd(
+ let network_tokenization_resp = Box::pin(network_tokenize_and_vault_the_pmd(
state,
&vault_data,
platform,
@@ -3888,7 +3889,7 @@ pub async fn generate_network_token_for_payment_method(
}),
profile.is_network_tokenization_enabled,
&customer_id,
- )
+ ))
.await;
match network_tokenization_resp {
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 01b2c03d6f..186f3e0f8e 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1136,7 +1136,7 @@ impl PaymentMethodsController for PmCards<'_> {
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
metrics::DELETE_FROM_LOCKER.add(1, &[]);
- common_utils::metrics::utils::record_operation_time(
+ Box::pin(common_utils::metrics::utils::record_operation_time(
async move {
delete_card_from_vault(self.state, customer_id, merchant_id, card_reference)
.await
@@ -1152,7 +1152,7 @@ impl PaymentMethodsController for PmCards<'_> {
},
&metrics::CARD_DELETE_TIME,
&[],
- )
+ ))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deleting card from locker")
@@ -1221,7 +1221,7 @@ impl PaymentMethodsController for PmCards<'_> {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
- Some(get_card_details_from_locker(self.state, pm).await?)
+ Some(Box::pin(get_card_details_from_locker(self.state, pm)).await?)
})
}
@@ -1247,7 +1247,7 @@ impl PaymentMethodsController for PmCards<'_> {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
- get_card_details_from_locker(self.state, pm).await?
+ Box::pin(get_card_details_from_locker(self.state, pm)).await?
})
}
@@ -1485,7 +1485,7 @@ impl PaymentMethodsController for PmCards<'_> {
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- get_card_details_from_locker(self.state, pm).await
+ Box::pin(get_card_details_from_locker(self.state, pm)).await
}
#[cfg(feature = "v1")]
@@ -1634,12 +1634,12 @@ impl PaymentMethodsController for PmCards<'_> {
let (card, locker_metadata) =
if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let (card_detail, locker_metadata) = if self.state.conf.locker.locker_enabled {
- let locker_card_response = get_card_from_locker(
+ let locker_card_response = Box::pin(get_card_from_locker(
self.state,
&pm.customer_id.clone().get_required_value("customer_id")?,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
- )
+ ))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting card from card vault")?;
@@ -2818,12 +2818,12 @@ pub async fn update_customer_payment_method(
let response = if is_card_updation_required {
// Fetch the existing card data from locker for getting card number
- let locker_card_response = get_card_from_locker(
+ let locker_card_response = Box::pin(get_card_from_locker(
&state,
&customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
- )
+ ))
.await
.attach_printable("Error getting card from locker")?;
@@ -3418,31 +3418,35 @@ pub async fn get_card_from_locker(
) -> errors::RouterResult<LockerCardResponse> {
metrics::GET_FROM_LOCKER.add(1, &[]);
- let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
- async {
- get_card_from_vault(state, customer_id, merchant_id, card_reference)
- .await
- .map_err(|err| match err.current_context() {
- errors::VaultError::FetchCardFailed => {
- err.change_context(errors::ApiErrorResponse::GenericNotFoundError {
- message: "Card not found in vault".to_string(),
- })
- }
- _ => err
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error getting card from card vault"),
- })
- .inspect_err(|_| {
- metrics::CARD_LOCKER_FAILURES.add(
- 1,
- router_env::metric_attributes!(("locker", "rust"), ("operation", "get")),
- );
- })
- },
- &metrics::CARD_GET_TIME,
- router_env::metric_attributes!(("locker", "rust")),
- )
- .await?;
+ let get_card_from_rs_locker_resp =
+ Box::pin(common_utils::metrics::utils::record_operation_time(
+ async {
+ get_card_from_vault(state, customer_id, merchant_id, card_reference)
+ .await
+ .map_err(|err| match err.current_context() {
+ errors::VaultError::FetchCardFailed => {
+ err.change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Card not found in vault".to_string(),
+ })
+ }
+ _ => err
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error getting card from card vault"),
+ })
+ .inspect_err(|_| {
+ metrics::CARD_LOCKER_FAILURES.add(
+ 1,
+ router_env::metric_attributes!(
+ ("locker", "rust"),
+ ("operation", "get")
+ ),
+ );
+ })
+ },
+ &metrics::CARD_GET_TIME,
+ router_env::metric_attributes!(("locker", "rust")),
+ ))
+ .await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
@@ -6853,12 +6857,12 @@ pub async fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- let card = get_card_from_locker(
+ let card = Box::pin(get_card_from_locker(
state,
&pm.customer_id.clone().get_required_value("customer_id")?,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
- )
+ ))
.await
.attach_printable("Error getting card from card vault")?
.get_card();
@@ -6875,7 +6879,7 @@ pub async fn get_lookup_key_from_locker(
pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- let card_detail = get_card_details_from_locker(state, pm).await?;
+ let card_detail = Box::pin(get_card_details_from_locker(state, pm)).await?;
let card = card_detail.clone();
let resp = TempLockerCardSupport::create_payment_method_data_in_temp_locker(
@@ -7706,12 +7710,12 @@ pub async fn execute_payment_method_tokenization(
})?;
// Fetch card from locker
- let card_details = get_card_from_locker(
+ let card_details = Box::pin(get_card_from_locker(
executor.state,
customer_id,
executor.merchant_account.get_id(),
&locker_id,
- )
+ ))
.await?
.get_card();
diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rs
index 19f971e844..53b3cf6df5 100644
--- a/crates/router/src/core/payment_methods/network_tokenization.rs
+++ b/crates/router/src/core/payment_methods/network_tokenization.rs
@@ -417,7 +417,7 @@ pub async fn make_card_network_tokenization_request(
let payload_bytes = payload.as_bytes();
if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {
- record_operation_time(
+ Box::pin(record_operation_time(
async {
mk_tokenization_req(
state,
@@ -432,7 +432,7 @@ pub async fn make_card_network_tokenization_request(
},
&metrics::GENERATE_NETWORK_TOKEN_TIME,
router_env::metric_attributes!(("locker", "rust")),
- )
+ ))
.await
} else {
Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
@@ -469,7 +469,7 @@ pub async fn make_card_network_tokenization_request(
)),
}?;
- let (resp, network_token_req_ref_id) = record_operation_time(
+ let (resp, network_token_req_ref_id) = Box::pin(record_operation_time(
async {
generate_network_token(
state,
@@ -482,7 +482,7 @@ pub async fn make_card_network_tokenization_request(
},
&metrics::GENERATE_NETWORK_TOKEN_TIME,
router_env::metric_attributes!(("locker", "rust")),
- )
+ ))
.await?;
let network_token_details = NetworkTokenDetails {
@@ -1294,7 +1294,7 @@ pub async fn get_altid_for_card(
auth_ref_number,
};
- let altid_response = record_operation_time(
+ let altid_response = Box::pin(record_operation_time(
async {
fetch_altid_and_cryptogram(
state,
@@ -1307,7 +1307,7 @@ pub async fn get_altid_for_card(
},
&metrics::FETCH_ALTID_TIME,
router_env::metric_attributes!(("service", "altid")),
- )
+ ))
.await?;
Ok(altid_response.into())
@@ -1332,11 +1332,13 @@ pub async fn evaluate_and_fetch_altid(
(payment_method_data, currency, is_guest_checkout)
{
match AltIdDecision::evaluate(state, card, business_profile, *connector) {
- AltIdDecision::Proceed => get_altid_for_card(state, card, amount, currency, None)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch Alt-ID for guest checkout")
- .map(Some),
+ AltIdDecision::Proceed => {
+ Box::pin(get_altid_for_card(state, card, amount, currency, None))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch Alt-ID for guest checkout")
+ .map(Some)
+ }
AltIdDecision::Skip => Ok(None),
AltIdDecision::Error => Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable(
diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs
index 8ac165d16f..b87b4a862d 100644
--- a/crates/router/src/core/payment_methods/tokenize.rs
+++ b/crates/router/src/core/payment_methods/tokenize.rs
@@ -366,11 +366,13 @@ where
card: &domain::CardDetail,
optional_cvc: Option<Secret<String>>,
) -> RouterResult<NetworkTokenizationResponse> {
- network_tokenization::make_card_network_tokenization_request(
- self.state,
- card,
- optional_cvc,
- customer_id,
+ Box::pin(
+ network_tokenization::make_card_network_tokenization_request(
+ self.state,
+ card,
+ optional_cvc,
+ customer_id,
+ ),
)
.await
.map_err(|err| {
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 8a9e3398a9..0d669af3ab 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -6512,7 +6512,7 @@ where
}
}
- if let Some(network_token_data) = network_tokenization::evaluate_and_fetch_altid(
+ if let Some(network_token_data) = Box::pin(network_tokenization::evaluate_and_fetch_altid(
state,
payment_data.get_payment_method_data(),
payment_data.get_payment_intent().currency,
@@ -6523,7 +6523,7 @@ where
.is_none(),
payment_data.get_payment_intent().amount,
business_profile,
- )
+ ))
.await?
{
payment_data.set_payment_method_data(Some(domain::PaymentMethodData::NetworkToken(
@@ -13705,16 +13705,17 @@ pub async fn payment_external_authentication<F: Clone + Sync>(
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching authentication record")?;
- let payment_method_details = helpers::get_payment_method_details_from_payment_token(
- &state,
- &payment_attempt,
- &payment_intent,
- &platform,
- storage_scheme,
- )
- .await?
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("missing payment_method_details")?;
+ let payment_method_details =
+ Box::pin(helpers::get_payment_method_details_from_payment_token(
+ &state,
+ &payment_attempt,
+ &payment_intent,
+ &platform,
+ storage_scheme,
+ ))
+ .await?
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("missing payment_method_details")?;
Box::pin(authentication_core::perform_authentication(
&state,
business_profile.merchant_id,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 5858dee3fe..69a0867bb1 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -919,12 +919,12 @@ pub async fn get_token_for_recurring_mandate(
if let Some(enums::PaymentMethod::Card) = payment_method.get_payment_method_type() {
if state.conf.locker.locker_enabled {
- let _ = cards::get_lookup_key_from_locker(
+ let _ = Box::pin(cards::get_lookup_key_from_locker(
state,
&token,
&payment_method,
platform.get_processor().get_key_store(),
- )
+ ))
.await?;
}
@@ -3033,12 +3033,12 @@ pub async fn retrieve_payment_method_data_with_permanent_token(
Ok(domain::PaymentMethodData::Card(card))
}
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => {
- fetch_card_details_for_network_transaction_flow_from_locker(
+ Box::pin(fetch_card_details_for_network_transaction_flow_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
- )
+ ))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")
@@ -3093,13 +3093,13 @@ pub async fn retrieve_payment_method_data_with_permanent_token(
.and_then(|vault_data| vault_data.get_network_token_data())
.map(Ok)
.async_unwrap_or_else(|| async {
- fetch_network_token_details_from_locker(
+ Box::pin(fetch_network_token_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
network_token_locker_id,
nt_data,
- )
+ ))
.await
})
.await?;
@@ -3132,14 +3132,14 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication(
message: "no customer id provided for the payment".to_string(),
})?;
Ok(domain::PaymentMethodData::Card(
- fetch_card_details_from_internal_locker(
+ Box::pin(fetch_card_details_from_internal_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
None,
- )
+ ))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?,
@@ -3173,14 +3173,14 @@ pub async fn fetch_card_details_from_locker(
.await
}
domain::PaymentMethodVaultSourceDetails::InternalVault => {
- fetch_card_details_from_internal_locker(
+ Box::pin(fetch_card_details_from_internal_locker(
state,
customer_id,
platform.get_provider().get_account().get_id(),
locker_id,
card_token_data,
co_badged_card_data,
- )
+ ))
.await
}
}
@@ -3272,11 +3272,16 @@ pub async fn fetch_card_details_from_internal_locker(
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
) -> RouterResult<domain::Card> {
logger::debug!("Fetching card details from locker");
- let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card information from the permanent locker")?
- .get_card();
+ let card = Box::pin(cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ locker_id,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to fetch card information from the permanent locker")?
+ .get_card();
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
@@ -3405,14 +3410,16 @@ pub async fn fetch_network_token_details_from_locker(
network_token_locker_id: &str,
network_transaction_data: mandates::NetworkTokenWithNTIRef,
) -> RouterResult<domain::NetworkTokenData> {
- let mut token_data =
- cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "failed to fetch network token information from the permanent locker",
- )?
- .get_card();
+ let mut token_data = Box::pin(cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ network_token_locker_id,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to fetch network token information from the permanent locker")?
+ .get_card();
let expiry = network_transaction_data
.token_exp_month
.zip(network_transaction_data.token_exp_year);
@@ -3455,12 +3462,16 @@ pub async fn fetch_card_details_for_network_transaction_flow_from_locker(
merchant_id: &id_type::MerchantId,
locker_id: &str,
) -> RouterResult<domain::PaymentMethodData> {
- let card_details_from_locker =
- cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card details from locker")?
- .get_card();
+ let card_details_from_locker = Box::pin(cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ locker_id,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to fetch card details from locker")?
+ .get_card();
let card_network = card_details_from_locker
.card_brand
@@ -4741,6 +4752,7 @@ pub fn generate_mandate(
.get_required_value("customer_acceptance")?;
new_mandate
.set_mandate_id(mandate_id)
+ .set_created_at(Some(common_utils::date_time::now()))
.set_customer_id(cus_id.clone())
.set_merchant_id(merchant_id)
.set_original_payment_id(Some(payment_id))
@@ -4796,6 +4808,61 @@ pub fn generate_mandate(
}
}
+#[cfg(test)]
+mod generate_mandate_tests {
+ use std::borrow::Cow;
+
+ use common_types::payments::{AcceptanceType, CustomerAcceptance};
+ use common_utils::{id_type, types::MinorUnit};
+ use hyperswitch_domain_models::mandates::{MandateAmountData, MandateData, MandateDataType};
+
+ use super::generate_mandate;
+
+ /// A new mandate sets its own `created_at` rather than taking the database default.
+ #[test]
+ fn a_new_mandate_carries_its_own_created_at() {
+ let mandate_data = MandateData {
+ update_mandate_id: None,
+ customer_acceptance: Some(CustomerAcceptance {
+ acceptance_type: AcceptanceType::Offline,
+ accepted_at: None,
+ online: None,
+ }),
+ mandate_type: Some(MandateDataType::SingleUse(MandateAmountData {
+ amount: MinorUnit::new(100),
+ currency: common_enums::Currency::USD,
+ start_date: None,
+ end_date: None,
+ metadata: None,
+ })),
+ };
+ let customer_id = Some(id_type::CustomerId::try_from(Cow::Borrowed("cus_1")).unwrap());
+
+ let before = common_utils::date_time::now();
+ let mandate = generate_mandate(
+ id_type::MerchantId::default(),
+ id_type::PaymentId::try_from(Cow::Borrowed("pay_1")).unwrap(),
+ "stripe".to_owned(),
+ Some(mandate_data),
+ &customer_id,
+ "pm_1".to_owned(),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+ .unwrap()
+ .expect("a mandate for mandate data and a customer");
+
+ let after = common_utils::date_time::now();
+
+ let created_at = mandate.created_at.expect("created_at is set");
+ assert!(before <= created_at && created_at <= after, "{created_at}");
+ }
+}
+
#[cfg(feature = "v1")]
// A function to manually authenticate the client secret with intent fulfillment time
pub fn authenticate_client_secret(
@@ -9048,7 +9115,7 @@ pub async fn get_payment_method_details_from_payment_token(
.await
}
- storage::PaymentTokenData::Permanent(card_token) => {
+ storage::PaymentTokenData::Permanent(card_token) => Box::pin(
retrieve_card_with_permanent_token_for_external_authentication(
state,
&card_token.token,
@@ -9056,12 +9123,12 @@ pub async fn get_payment_method_details_from_payment_token(
None,
platform.get_provider().get_key_store(),
storage_scheme,
- )
- .await
- .map(|card| Some((card, enums::PaymentMethod::Card)))
- }
+ ),
+ )
+ .await
+ .map(|card| Some((card, enums::PaymentMethod::Card))),
- storage::PaymentTokenData::PermanentCard(card_token) => {
+ storage::PaymentTokenData::PermanentCard(card_token) => Box::pin(
retrieve_card_with_permanent_token_for_external_authentication(
state,
&card_token.token,
@@ -9069,10 +9136,10 @@ pub async fn get_payment_method_details_from_payment_token(
None,
platform.get_provider().get_key_store(),
storage_scheme,
- )
- .await
- .map(|card| Some((card, enums::PaymentMethod::Card)))
- }
+ ),
+ )
+ .await
+ .map(|card| Some((card, enums::PaymentMethod::Card))),
storage::PaymentTokenData::AuthBankDebit(auth_token) => {
retrieve_payment_method_from_auth_service(
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 9bf6875272..a58f14f2ce 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -2341,12 +2341,12 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to call authentication sync flow")?
} else {
- let resp = crate::core::unified_authentication_service::authentication_sync_core(
+ let resp = Box::pin(crate::core::unified_authentication_service::authentication_sync_core(
state.clone(),
platform.clone(),
services::api::AuthFlow::Merchant,
sync_req,
- )
+ ))
.await?
.get_json_body()
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 82939d0980..edb8d1457c 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -2278,7 +2278,9 @@ pub fn perform_dynamic_routing_volume_split(
deja::id(
component = "router::routing",
operation = "volume_split_index",
- codec = ResultOkCodec,
+ on_miss = { use common_utils::synth_shape::Synthesize as _; Ok(__deja_miss.index(weights.len()).unwrap_or(0)) },
+ // Typed codec so a recorded `RoutingError` replays as the same error.
+ codec = deja::codec::ResultCodec::<usize, errors::RoutingError>,
)
)]
fn sample_volume_split_index(weights: &[u8]) -> RoutingResult<usize> {
@@ -4602,3 +4604,115 @@ pub async fn get_active_mca_ids_for_session(
}
}
}
+
+#[cfg(all(test, feature = "deja"))]
+mod deja_tests {
+ use super::{errors, oss_errors};
+
+ type Seam = deja::codec::ResultCodec<usize, errors::RoutingError>;
+
+ fn capture(
+ value: &oss_errors::CustomResult<usize, errors::RoutingError>,
+ ) -> (serde_json::Value, bool) {
+ <Seam as deja::codec::ReplayCodec>::capture(value)
+ }
+
+ fn reconstruct(
+ recorded: serde_json::Value,
+ ) -> Option<oss_errors::CustomResult<usize, errors::RoutingError>> {
+ <Seam as deja::codec::ReplayCodec>::reconstruct(recorded)
+ }
+
+ /// Pins the `Ok` envelope existing recordings hold, including `type_name`.
+ #[test]
+ fn the_ok_envelope_records_a_bare_index() {
+ let (recorded, is_error) = capture(&Ok(3));
+ assert!(!is_error, "an Ok must not be captured as an error");
+ assert_eq!(
+ recorded.get("result").and_then(serde_json::Value::as_str),
+ Some("Ok")
+ );
+ assert_eq!(recorded.get("value"), Some(&serde_json::json!(3)));
+ assert_eq!(
+ recorded
+ .get("type_name")
+ .and_then(serde_json::Value::as_str),
+ Some("usize"),
+ "the Ok envelope's type_name must stay `usize`: {recorded}"
+ );
+ }
+
+ /// A captured `Err` records its variant as `kind` and reconstructs as it.
+ #[test]
+ fn a_captured_error_round_trips_as_its_variant() {
+ let (recorded, is_error) = capture(&Err(errors::RoutingError::VolumeSplitFailed.into()));
+ assert!(is_error, "an Err must be captured as an error");
+ assert_eq!(
+ recorded.get("kind").and_then(serde_json::Value::as_str),
+ Some("VolumeSplitFailed"),
+ "the recorded kind must name the variant: {recorded}"
+ );
+ let Some(Err(report)) = reconstruct(recorded) else {
+ panic!("a captured error must reconstruct as an error");
+ };
+ assert!(matches!(
+ report.current_context(),
+ errors::RoutingError::VolumeSplitFailed
+ ));
+ }
+
+ /// A recorded error rebuilds as its variant; a sentinel or unknown `kind` refuses.
+ #[test]
+ fn a_recorded_error_rebuilds_its_variant() {
+ let rebuilt = reconstruct(serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": "VolumeSplitFailed",
+ "message": "Volume split failed",
+ }))
+ .expect("a typed error must reconstruct");
+ let Err(report) = &rebuilt else {
+ panic!("a recorded error must rebuild as an error");
+ };
+ assert!(
+ matches!(
+ report.current_context(),
+ errors::RoutingError::VolumeSplitFailed
+ ),
+ "the rebuilt error must carry the recorded variant"
+ );
+
+ assert!(
+ reconstruct(serde_json::json!({"deja_err": "VolumeSplitFailed"})).is_none(),
+ "the Ok-only sentinel names no variant and must refuse"
+ );
+ assert!(
+ reconstruct(serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": "NotAVariant",
+ "message": "",
+ }))
+ .is_none(),
+ "a kind naming no variant must refuse rather than fabricate one"
+ );
+ }
+
+ /// The seam's attribute selects the typed codec; read from source, since the
+ /// macro expansion is not observable at run time.
+ #[test]
+ fn the_seam_selects_the_typed_result_codec() {
+ let source = include_str!("routing.rs");
+ let (_, after_operation) = source
+ .split_once("operation = \"volume_split_index\",")
+ .expect("the seam must declare its operation");
+ let (declaration, _) = after_operation
+ .split_once(")]")
+ .expect("the seam's attribute must be closed");
+ assert!(
+ declaration.contains("codec = deja::codec::ResultCodec::<usize, errors::RoutingError>"),
+ "the volume-split seam must select the typed result codec, or a \
+ recorded failure replays as an unreconstructable sentinel: {declaration}"
+ );
+ }
+}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index c2322d31e8..7d667816e9 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -1242,11 +1242,13 @@ pub async fn pre_payment_tokenization(
{
let optional_card_cvc = Some(card.card_cvc.clone());
let card_detail = payment_method_data::CardDetail::from(card);
- match network_tokenization::make_card_network_tokenization_request(
- state,
- &card_detail,
- optional_card_cvc,
- &customer_id,
+ match Box::pin(
+ network_tokenization::make_card_network_tokenization_request(
+ state,
+ &card_detail,
+ optional_card_cvc,
+ &customer_id,
+ ),
)
.await
{
@@ -1695,11 +1697,13 @@ pub async fn save_network_token_in_locker(
// empty one.
let optional_card_cvc =
(!card_data.card_cvc.peek().is_empty()).then(|| card_data.card_cvc.clone());
- match network_tokenization::make_card_network_tokenization_request(
- state,
- &domain::CardDetail::from(card_data),
- optional_card_cvc,
- &customer_id,
+ match Box::pin(
+ network_tokenization::make_card_network_tokenization_request(
+ state,
+ &domain::CardDetail::from(card_data),
+ optional_card_cvc,
+ &customer_id,
+ ),
)
.await
{
@@ -2480,12 +2484,12 @@ pub async fn generate_network_token_for_payment_method(
.unwrap_or(&payment_method.payment_method_id);
// Fetch the raw card from the locker
- let card_from_locker = payment_methods::cards::get_card_from_locker(
+ let card_from_locker = Box::pin(payment_methods::cards::get_card_from_locker(
state,
customer_id,
&tracking_data.merchant_id,
locker_id,
- )
+ ))
.await
.inspect_err(|err| {
logger::error!(
@@ -2512,7 +2516,7 @@ pub async fn generate_network_token_for_payment_method(
let payment_method_data = domain::PaymentMethodData::Card(card_data);
- generate_network_token_and_update_payment_method(
+ Box::pin(generate_network_token_and_update_payment_method(
state,
platform,
&payment_method_data,
@@ -2522,6 +2526,6 @@ pub async fn generate_network_token_for_payment_method(
tracking_data.billing_name.clone(),
None,
Some(payment_method),
- )
+ ))
.await
}
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index f27c172844..27da571013 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -703,7 +703,7 @@ pub async fn payouts_create_core(
.customer_id
.clone()
.get_required_value("customer_id when payout_method_data is provided")?;
- payout_data.payout_method_data = helpers::make_payout_method_data(
+ payout_data.payout_method_data = Box::pin(helpers::make_payout_method_data(
&state,
req.payout_method_data.as_ref(),
payout_attempt.payout_token.as_deref(),
@@ -713,7 +713,7 @@ pub async fn payouts_create_core(
platform.get_processor().get_key_store(),
Some(&mut payout_data),
platform.get_processor().get_account().storage_scheme,
- )
+ ))
.await?;
}
@@ -851,7 +851,7 @@ pub async fn payouts_update_core(
.customer_id
.clone()
.get_required_value("customer_id when payout_method_data is provided")?;
- payout_data.payout_method_data = helpers::make_payout_method_data(
+ payout_data.payout_method_data = Box::pin(helpers::make_payout_method_data(
&state,
req.payout_method_data.as_ref(),
payout_attempt.payout_token.as_deref(),
@@ -861,7 +861,7 @@ pub async fn payouts_update_core(
platform.get_processor().get_key_store(),
Some(&mut payout_data),
platform.get_processor().get_account().storage_scheme,
- )
+ ))
.await?;
}
@@ -1097,7 +1097,13 @@ pub async fn payouts_fulfill_core(
.attach_printable("Connector not found for payout fulfillment")?,
};
- helpers::fetch_payout_method_data(&state, &mut payout_data, &connector_data, &platform).await?;
+ Box::pin(helpers::fetch_payout_method_data(
+ &state,
+ &mut payout_data,
+ &connector_data,
+ &platform,
+ ))
+ .await?;
// Fetch source_bank_data if not present
if payout_data.source_bank_data.is_none() {
@@ -1579,7 +1585,13 @@ pub async fn call_connector_payout(
// Fetch / store payout_method_data
if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {
- helpers::fetch_payout_method_data(state, payout_data, connector_data, platform).await?;
+ Box::pin(helpers::fetch_payout_method_data(
+ state,
+ payout_data,
+ connector_data,
+ platform,
+ ))
+ .await?;
}
#[cfg(feature = "v1")]
@@ -3900,7 +3912,7 @@ pub async fn make_payout_data(
.as_ref()
.map(|cd| cd.get_id().to_owned())
.get_required_value("customer_id when payout_token is sent")?;
- helpers::make_payout_method_data(
+ Box::pin(helpers::make_payout_method_data(
state,
None,
Some(&payout_token),
@@ -3910,7 +3922,7 @@ pub async fn make_payout_data(
platform.get_processor().get_key_store(),
None,
platform.get_processor().get_account().storage_scheme,
- )
+ ))
.await?
}
None => None,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 68a1441dde..2152e954ca 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -146,12 +146,12 @@ pub async fn make_payout_method_data(
)?;
Ok(pm)
} else {
- let resp = cards::get_card_from_locker(
+ let resp = Box::pin(cards::get_card_from_locker(
state,
customer_id,
merchant_id,
payout_token.as_ref(),
- )
+ ))
.await
.attach_printable("Payout method [card] could not be fetched from HS locker")?
.get_card();
@@ -352,7 +352,7 @@ pub async fn fetch_payout_method_data(
let merchant_id = payout_data.payout_attempt.merchant_id.clone();
let payout_type = payout_data.payouts.payout_type;
- let payout_method_data = make_payout_method_data(
+ let payout_method_data = Box::pin(make_payout_method_data(
state,
payout_method_data_clone.as_ref(),
payout_token.as_deref(),
@@ -362,7 +362,7 @@ pub async fn fetch_payout_method_data(
platform.get_processor().get_key_store(),
Some(payout_data),
platform.get_processor().get_account().storage_scheme,
- )
+ ))
.await?
.get_required_value("payout_method_data")?;
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index c6218ac760..5063200d14 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -268,7 +268,7 @@ pub async fn validate_create_request(
field_name: "customer or customer_id when payout_token is provided".into()
})),
(Some(payout_token), Some(customer), _) => {
- helpers::make_payout_method_data(
+ Box::pin(helpers::make_payout_method_data(
state,
req.payout_method_data.as_ref(),
Some(payout_token),
@@ -278,7 +278,7 @@ pub async fn validate_create_request(
platform.get_processor().get_key_store(),
None,
platform.get_processor().get_account().storage_scheme,
- )
+ ))
.await
}
(_, Some(_), Some(payment_method)) => {
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index e463730a07..8d9cebceec 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -1145,12 +1145,12 @@ pub async fn link_routing_config(
Ok(routing_algorithm) => routing_algorithm,
Err(error) => {
// DE-only rule ids (e.g. created on the DE dashboard) activate directly on the DE.
- if let Some((business_profile, record)) = find_de_record_for_algorithm(
+ if let Some((business_profile, record)) = Box::pin(find_de_record_for_algorithm(
&state,
&platform,
authentication_profile_id.clone(),
&algorithm_id,
- )
+ ))
.await?
{
utils::when(record.algorithm_for != transaction_type, || {
@@ -1665,12 +1665,12 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
Ok(routing_algorithm) => routing_algorithm,
Err(error) => {
// DE-only rules have no HS row; serve them from the DE.
- if let Some((_business_profile, record)) = find_de_record_for_algorithm(
+ if let Some((_business_profile, record)) = Box::pin(find_de_record_for_algorithm(
&state,
&platform,
authentication_profile_id.clone(),
&algorithm_id,
- )
+ ))
.await?
{
let response = de_record_to_merchant_routing_algorithm(record)?;
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index c240639eb0..16f2b0417c 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -3955,7 +3955,7 @@ where
// Box::pin the handler to reduce the monomorphized future size and prevent stack overflow
let start_time = Instant::now();
let result = Box::pin(handler(router_data, grpc_request, grpc_header)).await;
- let external_latency = start_time.elapsed().as_millis();
+ let external_latency = common_utils::elapsed::millis_since(start_time);
// Create and emit connector event after UCS call
let (status_code, response_body, router_result) = match result {
@@ -4196,7 +4196,7 @@ where
// Box::pin the handler to reduce the monomorphized future size and prevent stack overflow
let start_time = Instant::now();
let result = Box::pin(handler(router_data, grpc_request, grpc_header)).await;
- let external_latency = start_time.elapsed().as_millis();
+ let external_latency = common_utils::elapsed::millis_since(start_time);
// Create and emit connector event after UCS call
let (status_code, response_body, router_result) = match result {
@@ -4406,7 +4406,7 @@ where
let start_time = Instant::now();
let result = handler(grpc_request, grpc_header).await;
- let external_latency = start_time.elapsed().as_millis();
+ let external_latency = common_utils::elapsed::millis_since(start_time);
match result {
Ok(grpc_response) => {
diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
index 2b78d3f243..1f1b06e0e6 100644
--- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs
+++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
@@ -268,11 +268,16 @@ pub async fn handle_metadata_update(
})
}
true => {
- let mut card = cards::get_card_from_locker(state, customer_id, merchant_id, &locker_id)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch token information from the locker")?
- .get_card();
+ let mut card = Box::pin(cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ &locker_id,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch token information from the locker")?
+ .get_card();
card.card_exp_year = metadata.expiry_year.clone();
card.card_exp_month = metadata.expiry_month.clone();
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index f2780bff5d..da1f154e46 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -138,14 +138,17 @@ pub async fn get_cache_store(
// deja: the per-merchant data-encryption key (DEK) is random. It is stored
// (master-key-encrypted) in merchant_key_store AND used to encrypt the merchant's
// own columns, so it must replay to the recorded value or the substituted DB rows
-// and the response body diverge. Ok-only: the ring error type is non-serializable.
+// and the response body diverge.
#[inline]
#[cfg_attr(
feature = "deja",
deja::id(
component = "router::services",
operation = "generate_aes256_key",
- codec = ResultOkCodec,
+ codec = deja::codec::ResultCodec::<[u8; 32], common_utils::errors::CryptoError>,
+ // A synthesized key diverges the ciphertext it encrypts, attributably;
+ // a fail-stop here would blind every later column encryption.
+ on_miss = Ok(deja::synth::bytes::<32>(&__deja_miss)),
)
)]
pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> {
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index bf62b05148..230ed7e4b3 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -6256,8 +6256,9 @@ fn token_digest(token: &str) -> String {
/// business-profile and decrypt calls that follow it, which are exactly the
/// calls a replay exists to compare.
///
-/// A token absent from the recording does not decode silently: the substitute
-/// misses and the boundary fail-stops, the same as any other missed substitute.
+/// A token absent from the recording is decoded with only `validate_exp` off;
+/// the signature and required claims are still checked. Only a replay miss
+/// reaches this arm, so live traffic never accepts an expired token.
///
/// `pub` only so the boundary can be exercised from an integration test:
/// `set_global_runtime_hook` is a one-shot `OnceLock`, so record and replay
@@ -6278,6 +6279,14 @@ fn token_digest(token: &str) -> String {
"claims_type": std::any::type_name::<T>(),
})
},
+ on_miss = {
+ let mut without_the_clock = Validation::new(Algorithm::HS256);
+ without_the_clock.validate_exp = false;
+ let key = DecodingKey::from_secret(secret);
+ decode::<T>(token, &key, &without_the_clock)
+ .map(|decoded| decoded.claims)
+ .map_err(|_| report!(JwtDecodeOutcome::Invalid))
+ },
)
)]
pub fn decode_jwt_verified<T>(
diff --git a/crates/router/src/services/encryption.rs b/crates/router/src/services/encryption.rs
index 3bdafe47c0..2cad6d252f 100644
--- a/crates/router/src/services/encryption.rs
+++ b/crates/router/src/services/encryption.rs
@@ -43,7 +43,8 @@ pub enum EncryptionAlgorithm {
deja::id(
component = "router::services::encryption",
operation = "encrypt_jwe",
- codec = ResultOkCodec,
+ // A recorded failure is one the caller degrades on, so it replays as one.
+ codec = deja::codec::ResultCodec::<String, errors::EncryptionError>,
// 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.
@@ -53,6 +54,42 @@ pub enum EncryptionAlgorithm {
"payload_blake3": blake3::hash(payload).to_hex().as_str(),
"payload_len": payload.len(),
}),
+ // Callers index all five JWE segments, so build them in josekit's order:
+ // the real protected header, then opaque bytes at the encrypter's lengths,
+ // carved from one draw so the segments are not prefixes of each other.
+ on_miss = {
+ use base64::Engine as _;
+ use common_utils::synth_shape::Synthesize as _;
+
+ const WRAPPED_KEY_BYTES: usize = 256;
+ const GCM_IV_BYTES: usize = 12;
+ const GCM_TAG_BYTES: usize = 16;
+
+ let drawn = __deja_miss.byte_vec(
+ WRAPPED_KEY_BYTES + GCM_IV_BYTES + payload.len() + GCM_TAG_BYTES,
+ );
+ let (wrapped_key, drawn) = drawn.split_at(WRAPPED_KEY_BYTES);
+ let (iv, drawn) = drawn.split_at(GCM_IV_BYTES);
+ let (ciphertext, tag) = drawn.split_at(payload.len());
+
+ let mut header = serde_json::Map::new();
+ header.insert("alg".to_string(), "RSA-OAEP-256".into());
+ header.insert("enc".to_string(), algorithm.as_ref().into());
+ header.insert("typ".to_string(), "JWT".into());
+ if let Some(key_id) = key_id {
+ header.insert("kid".to_string(), key_id.into());
+ }
+
+ let engine = common_utils::consts::BASE64_ENGINE_URL_SAFE_NO_PAD;
+ Ok(format!(
+ "{}.{}.{}.{}.{}",
+ engine.encode(serde_json::Value::Object(header).to_string()),
+ engine.encode(wrapped_key),
+ engine.encode(iv),
+ engine.encode(ciphertext),
+ engine.encode(tag),
+ ))
+ },
)
)]
pub async fn encrypt_jwe(
diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs
index 99ecb9a87f..6e8dd6abf0 100644
--- a/crates/router/src/services/jwt.rs
+++ b/crates/router/src/services/jwt.rs
@@ -7,11 +7,25 @@ use crate::{configs::Settings, core::errors::UserErrors};
// deja: JWT expiry uses a raw SystemTime::now() that bypasses the instrumented
// date_time::now boundary, so the `exp` claim (and thus the whole signed token)
-// diverges on replay. Record/replay the absolute expiry (Ok-only) to reproduce
+// diverges on replay. Record/replay the absolute expiry to reproduce
// byte-identical JWTs.
#[cfg_attr(
feature = "deja",
- deja::id(component = "router::jwt", operation = "generate_exp", codec = ResultOkCodec,)
+ deja::id(
+ component = "router::jwt",
+ operation = "generate_exp",
+ // Typed codec so a recorded `UserErrors` replays as the same error.
+ codec = deja::codec::ResultCodec::<std::time::Duration, UserErrors>,
+ on_miss = {
+ use common_utils::synth_shape::Synthesize as _;
+ Ok(
+ std::time::Duration::from_nanos(
+ u64::try_from(__deja_miss.epoch_nanos()).unwrap_or(0),
+ )
+ .saturating_add(exp_duration),
+ )
+ },
+ )
)]
#[allow(
clippy::disallowed_methods,
@@ -42,3 +56,94 @@ where
)
.change_context(UserErrors::InternalServerError)
}
+
+#[cfg(all(test, feature = "deja"))]
+mod deja_tests {
+ use super::UserErrors;
+
+ type Seam = deja::codec::ResultCodec<std::time::Duration, UserErrors>;
+
+ fn capture(
+ value: &common_utils::errors::CustomResult<std::time::Duration, UserErrors>,
+ ) -> (serde_json::Value, bool) {
+ <Seam as deja::codec::ReplayCodec>::capture(value)
+ }
+
+ fn reconstruct(
+ recorded: serde_json::Value,
+ ) -> Option<common_utils::errors::CustomResult<std::time::Duration, UserErrors>> {
+ <Seam as deja::codec::ReplayCodec>::reconstruct(recorded)
+ }
+
+ /// A captured `Err` records its variant as `kind` and reconstructs as it.
+ #[test]
+ fn a_captured_error_round_trips_as_its_variant() {
+ let (recorded, is_error) = capture(&Err(UserErrors::InternalServerError.into()));
+ assert!(is_error, "an Err must be captured as an error");
+ assert_eq!(
+ recorded.get("kind").and_then(serde_json::Value::as_str),
+ Some("InternalServerError"),
+ "the recorded kind must name the variant: {recorded}"
+ );
+ let Some(Err(report)) = reconstruct(recorded) else {
+ panic!("a captured error must reconstruct as an error");
+ };
+ assert!(matches!(
+ report.current_context(),
+ UserErrors::InternalServerError
+ ));
+ }
+
+ /// A recorded error rebuilds as its variant; a sentinel or unknown `kind` refuses.
+ #[test]
+ fn a_recorded_error_rebuilds_its_variant() {
+ let rebuilt = reconstruct(serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": "InternalServerError",
+ "message": "User InternalServerError",
+ }))
+ .expect("a typed error must reconstruct");
+ let Err(report) = &rebuilt else {
+ panic!("a recorded error must rebuild as an error");
+ };
+ assert!(
+ matches!(report.current_context(), UserErrors::InternalServerError),
+ "the rebuilt error must carry the recorded variant"
+ );
+
+ assert!(
+ reconstruct(serde_json::json!({"deja_err": "InternalServerError"})).is_none(),
+ "the Ok-only sentinel names no variant and must refuse"
+ );
+ assert!(
+ reconstruct(serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": "NotAVariant",
+ "message": "",
+ }))
+ .is_none(),
+ "a kind naming no variant must refuse rather than fabricate one"
+ );
+ }
+
+ /// The seam's attribute selects the typed codec; read from source, since the
+ /// macro expansion is not observable at run time.
+ #[test]
+ fn the_seam_selects_the_typed_result_codec() {
+ let source = include_str!("jwt.rs");
+ let (_, after_operation) = source
+ .split_once("operation = \"generate_exp\",")
+ .expect("the seam must declare its operation");
+ let (declaration, _) = after_operation
+ .split_once(")]")
+ .expect("the seam's attribute must be closed");
+ assert!(
+ declaration
+ .contains("codec = deja::codec::ResultCodec::<std::time::Duration, UserErrors>"),
+ "the expiry seam must select the typed result codec, or a recorded \
+ failure replays as an unreconstructable sentinel: {declaration}"
+ );
+ }
+}
diff --git a/crates/router/src/services/kafka/deja_record_sink.rs b/crates/router/src/services/kafka/deja_record_sink.rs
index 5d0f87e461..4327efe300 100644
--- a/crates/router/src/services/kafka/deja_record_sink.rs
+++ b/crates/router/src/services/kafka/deja_record_sink.rs
@@ -409,10 +409,10 @@ mod tests {
call_line: 10,
call_column: 5,
receiver: None,
- request: serde_json::Value::Null,
- args: serde_json::json!({"key": "foo"}),
- response: serde_json::Value::Null,
- result: serde_json::json!("bar"),
+ request: serde_json::Value::Null.into(),
+ args: serde_json::json!({"key": "foo"}).into(),
+ response: serde_json::Value::Null.into(),
+ result: serde_json::json!("bar").into(),
is_error: false,
duration_us: 42,
event_schema_version: deja::CURRENT_EVENT_SCHEMA_VERSION,
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index bd20704426..624bf75104 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -68,7 +68,7 @@ impl MandateResponseExt for MandateResponse {
let card = if pm == storage_enums::PaymentMethod::Card {
// if locker is disabled , decrypt the payment method data
let card_details = if state.conf.locker.locker_enabled {
- let card = payment_methods::cards::get_card_from_locker(
+ let card = Box::pin(payment_methods::cards::get_card_from_locker(
state,
&customer_id,
&payment_method.merchant_id,
@@ -76,7 +76,7 @@ impl MandateResponseExt for MandateResponse {
.locker_id
.as_ref()
.unwrap_or(payment_method.get_id()),
- )
+ ))
.await?
.get_card();
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 2458dd9b0b..24fcb411ec 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -997,7 +997,8 @@ impl NewUser {
// runs live (collides with the record-phase user, rolling signup back).
#[cfg_attr(
feature = "deja",
- deja::id(component = "router::user", operation = "generate_user_id", codec = SerdeCodec,)
+ deja::id(component = "router::user", operation = "generate_user_id", codec = SerdeCodec,
+ on_miss = { use common_utils::synth_shape::Synthesize as _; __deja_miss.uuid().to_string() },)
)]
fn generate_user_id() -> String {
common_utils::generate_uuid_v4().to_string()
@@ -1403,6 +1404,23 @@ impl RecoveryCodes {
component = "router::user",
operation = "generate_recovery_codes",
codec = SerdeCodec,
+ // Codes shaped as the body builds them: two alphanumeric halves joined
+ // by a hyphen. One carved draw keeps the codes distinct.
+ on_miss = {
+ use common_utils::synth_shape::Synthesize as _;
+ __deja_miss
+ .alphanumeric_words(
+ consts::user::RECOVERY_CODES_COUNT,
+ consts::user::RECOVERY_CODE_LENGTH,
+ )
+ .into_iter()
+ .map(|word| {
+ let (head, tail) =
+ word.split_at(consts::user::RECOVERY_CODE_LENGTH / 2);
+ format!("{head}-{tail}")
+ })
+ .collect()
+ },
)
)]
fn generate_new_inner() -> Vec<String> {
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index e8169a88ed..1f4880c7af 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -122,7 +122,8 @@ pub mod error_parser {
#[inline]
#[cfg_attr(
feature = "deja",
- deja::id(component = "router::utils", operation = "generate_id", codec = SerdeCodec,)
+ deja::id(component = "router::utils", operation = "generate_id", codec = SerdeCodec,
+ on_miss = { use common_utils::synth_shape::Synthesize as _; __deja_miss.prefixed(prefix, length) },)
)]
#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]
pub fn generate_id(length: usize, prefix: &str) -> String {
diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rs
index 289a638c8c..4e52ef3db3 100644
--- a/crates/router/src/utils/user/password.rs
+++ b/crates/router/src/utils/user/password.rs
@@ -26,13 +26,31 @@ pub fn generate_password_hash(
// serializes lossily to "***", which would record/replay a useless masked value;
// the plain String records the real hash losslessly. The `password` arg still
// masks to "***" in the recorded args — that's fine, it's consistent across
-// record/replay and avoids leaking the secret. Uses the Ok-only codec for the Result.
+// record/replay and avoids leaking the secret.
#[cfg_attr(
feature = "deja",
deja::id(
component = "router::user::password",
operation = "generate_password_hash",
- codec = ResultOkCodec,
+ // Typed codec so a recorded `UserErrors` replays as the same error.
+ codec = deja::codec::ResultCodec::<String, UserErrors>,
+ // `is_correct_password` must parse a PHC string, so real Argon2 hashes
+ // derived material; a later check then answers `Ok(false)`, not an error.
+ on_miss = {
+ use common_utils::synth_shape::Synthesize as _;
+ let material = __deja_miss.alphanumeric(32);
+ match SaltString::encode_b64(&deja::synth::bytes::<16>(&__deja_miss)).and_then(
+ |salt| {
+ Argon2::default()
+ .hash_password(material.as_bytes(), &salt)
+ .map(|hash| hash.to_string())
+ },
+ ) {
+ Ok(hash) => Ok(hash),
+ // Unreachable for a well-formed 16-byte salt; keeps the arm total.
+ Err(_) => Err(UserErrors::InternalServerError.into()),
+ }
+ },
)
)]
fn generate_password_hash_inner(password: Secret<String>) -> CustomResult<String, UserErrors> {
@@ -88,6 +106,7 @@ pub fn get_temp_password() -> Secret<String> {
deja::id(
component = "router::user::password",
operation = "get_temp_password",
+ on_miss = { use common_utils::synth_shape::Synthesize as _; __deja_miss.uuid().to_string() },
codec = SerdeCodec,
)
)]
@@ -112,3 +131,93 @@ fn get_temp_password_inner() -> String {
rng.gen_range('0'..='9'),
)
}
+
+#[cfg(all(test, feature = "deja"))]
+mod deja_tests {
+ use super::UserErrors;
+
+ type Seam = deja::codec::ResultCodec<String, UserErrors>;
+
+ fn capture(
+ value: &common_utils::errors::CustomResult<String, UserErrors>,
+ ) -> (serde_json::Value, bool) {
+ <Seam as deja::codec::ReplayCodec>::capture(value)
+ }
+
+ fn reconstruct(
+ recorded: serde_json::Value,
+ ) -> Option<common_utils::errors::CustomResult<String, UserErrors>> {
+ <Seam as deja::codec::ReplayCodec>::reconstruct(recorded)
+ }
+
+ /// A captured `Err` records its variant as `kind` and reconstructs as it.
+ #[test]
+ fn a_captured_error_round_trips_as_its_variant() {
+ let (recorded, is_error) = capture(&Err(UserErrors::InternalServerError.into()));
+ assert!(is_error, "an Err must be captured as an error");
+ assert_eq!(
+ recorded.get("kind").and_then(serde_json::Value::as_str),
+ Some("InternalServerError"),
+ "the recorded kind must name the variant: {recorded}"
+ );
+ let Some(Err(report)) = reconstruct(recorded) else {
+ panic!("a captured error must reconstruct as an error");
+ };
+ assert!(matches!(
+ report.current_context(),
+ UserErrors::InternalServerError
+ ));
+ }
+
+ /// A recorded error rebuilds as its variant; a sentinel or unknown `kind` refuses.
+ #[test]
+ fn a_recorded_error_rebuilds_its_variant() {
+ let rebuilt = reconstruct(serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": "InternalServerError",
+ "message": "User InternalServerError",
+ }))
+ .expect("a typed error must reconstruct");
+ let Err(report) = &rebuilt else {
+ panic!("a recorded error must rebuild as an error");
+ };
+ assert!(
+ matches!(report.current_context(), UserErrors::InternalServerError),
+ "the rebuilt error must carry the recorded variant"
+ );
+
+ assert!(
+ reconstruct(serde_json::json!({"deja_err": "InternalServerError"})).is_none(),
+ "the Ok-only sentinel names no variant and must refuse"
+ );
+ assert!(
+ reconstruct(serde_json::json!({
+ "version": 1,
+ "result": "Err",
+ "kind": "NotAVariant",
+ "message": "",
+ }))
+ .is_none(),
+ "a kind naming no variant must refuse rather than fabricate one"
+ );
+ }
+
+ /// The seam's attribute selects the typed codec; read from source, since the
+ /// macro expansion is not observable at run time.
+ #[test]
+ fn the_seam_selects_the_typed_result_codec() {
+ let source = include_str!("password.rs");
+ let (_, after_operation) = source
+ .split_once("operation = \"generate_password_hash\",")
+ .expect("the seam must declare its operation");
+ let (declaration, _) = after_operation
+ .split_once(")]")
+ .expect("the seam's attribute must be closed");
+ assert!(
+ declaration.contains("codec = deja::codec::ResultCodec::<String, UserErrors>"),
+ "the password-hash seam must select the typed result codec, or a \
+ recorded failure replays as an unreconstructable sentinel: {declaration}"
+ );
+ }
+}
diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
index c8e5b2e473..26af6c46de 100644
--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
@@ -632,12 +632,12 @@ impl BackwardCompatWorkflowBuilder<BackwardDbCompatPrepared> {
.get_string_repr()
.to_owned();
- let legacy_card_exists = match cards::get_card_from_locker(
+ let legacy_card_exists = match Box::pin(cards::get_card_from_locker(
state,
&customer_id,
platform.get_provider().get_account().get_id(),
&card_reference,
- )
+ ))
.await
{
Ok(_) => {
@@ -859,12 +859,14 @@ pub async fn run_payment_method_modular_backward_compat_backfill(
"Skipping modular backward compatibility backfill because legacy PM is not forward compatible"
);
} else {
- workflow
- .prepare_db_compat()?
- .apply_locker_compat(state, db, process_id)
- .await?
- .mark_complete(db)
- .await?;
+ Box::pin(
+ workflow
+ .prepare_db_compat()?
+ .apply_locker_compat(state, db, process_id),
+ )
+ .await?
+ .mark_complete(db)
+ .await?;
}
Ok(())
diff --git a/crates/router/src/workflows/payment_method_modular_forward_compat.rs b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
index 0d422b4ce7..5ae1471ba6 100644
--- a/crates/router/src/workflows/payment_method_modular_forward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
@@ -557,12 +557,14 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW
"Finished payment method modular compatibility PT; already forward compatible"
);
} else {
- workflow
- .prepare_db_compat()?
- .apply_locker_compat(state, &process.id)
- .await?
- .mark_complete(db)
- .await?;
+ Box::pin(
+ workflow
+ .prepare_db_compat()?
+ .apply_locker_compat(state, &process.id),
+ )
+ .await?
+ .mark_complete(db)
+ .await?;
db.as_scheduler()
.finish_process_with_business_status(process, "COMPLETED_BY_PT")
diff --git a/crates/router/tests/deja_elapsed_args_are_site_stable.rs b/crates/router/tests/deja_elapsed_args_are_site_stable.rs
new file mode 100644
index 0000000000..cbcf17e6b2
--- /dev/null
+++ b/crates/router/tests/deja_elapsed_args_are_site_stable.rs
@@ -0,0 +1,62 @@
+// Integration test: allow the panic/expect lints the v2 clippy profile denies.
+#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]
+//! The elapsed seam addresses itself by site: its `Instant` argument, captured
+//! via `Debug`, differs per call and would re-key the site every time.
+//!
+//! Own test binary: `set_global_runtime_hook` is a one-shot `OnceLock`.
+#![cfg(feature = "deja")]
+
+#[test]
+fn two_readings_from_different_instants_share_one_address() {
+ let table = deja::LookupTable {
+ recording_id: "elapsed-args-test".to_string(),
+ policy_version: deja::POLICY_VERSION,
+ event_schema_version: Some(deja::CURRENT_EVENT_SCHEMA_VERSION),
+ entries: vec![],
+ identity_entries: vec![],
+ };
+ let dir = tempfile::tempdir().expect("tempdir");
+ let path = dir.path().join("lookup.json");
+ std::fs::write(&path, serde_json::to_vec(&table).expect("serialize")).expect("write table");
+
+ let sink = deja::InMemoryObservedSink::new();
+ let observed = sink.handle();
+ let hook = deja::LookupTableHook::from_source(deja::LocalFileLookupSource::new(path), sink)
+ .expect("hook");
+ deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook)))
+ .expect("install replay hook");
+
+ let first_start = std::time::Instant::now();
+ // Spin until the clock has moved, so the two origins cannot coincide.
+ while first_start.elapsed().as_nanos() == 0 {}
+ let second_start = std::time::Instant::now();
+ assert_ne!(
+ format!("{first_start:?}"),
+ format!("{second_start:?}"),
+ "the two origins must differ, or this proves nothing"
+ );
+
+ let _ = common_utils::elapsed::millis_since(first_start);
+ let _ = common_utils::elapsed::millis_since(second_start);
+
+ let calls = observed.lock().expect("observed calls");
+ let readings: Vec<&deja::ObservedCall> = calls
+ .iter()
+ .filter(|call| call.method_name == "millis_since")
+ .collect();
+ let [first, second] = readings.as_slice() else {
+ panic!(
+ "both readings must be observed, or the assertions below are vacuous; got {}",
+ readings.len()
+ );
+ };
+ assert_eq!(
+ first.args, second.args,
+ "two readings taken from different origins must address the same site"
+ );
+ assert_eq!(
+ first.args,
+ serde_json::json!({}),
+ "and the site carries no arguments at all: its identity is positional"
+ );
+}
diff --git a/crates/router/tests/deja_jwt_novel_token_drops_only_the_clock.rs b/crates/router/tests/deja_jwt_novel_token_drops_only_the_clock.rs
new file mode 100644
index 0000000000..8f2571eb3b
--- /dev/null
+++ b/crates/router/tests/deja_jwt_novel_token_drops_only_the_clock.rs
@@ -0,0 +1,100 @@
+// Integration test: allow the panic/expect lints the v2 clippy profile denies.
+#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]
+//! A token absent from the recording is decoded with its signature verified and
+//! its expiry ignored, since `jsonwebtoken` reads a clock replay cannot hold.
+//!
+//! An empty lookup table makes every call a miss. Own test binary:
+//! `set_global_runtime_hook` is a one-shot `OnceLock`.
+#![cfg(feature = "deja")]
+
+use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
+use router::services::authentication::{decode_jwt_verified, JwtDecodeOutcome};
+
+/// The secret the caller holds. The forged token is signed with another one.
+const SECRET: &[u8] = b"test-secret";
+
+/// Fixed in the past, so the token stays expired.
+const EXPIRED_AT: u64 = 1_600_000_000;
+
+/// A subject only a real decode of the token can produce.
+const SUBJECT: &str = "deja-replay-expired-but-correctly-signed";
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+struct Claims {
+ sub: String,
+ exp: u64,
+}
+
+#[allow(
+ clippy::expect_used,
+ reason = "test helper: a free fn, so allow-expect-in-tests does not cover it; a fixture that will not sign should fail the test loudly"
+)]
+fn signed_with(secret: &[u8]) -> String {
+ encode(
+ &Header::new(Algorithm::HS256),
+ &Claims {
+ sub: SUBJECT.to_string(),
+ exp: EXPIRED_AT,
+ },
+ &EncodingKey::from_secret(secret),
+ )
+ .expect("sign the token")
+}
+
+#[test]
+fn a_token_absent_from_the_recording_drops_only_the_clock() {
+ let expired_but_signed = signed_with(SECRET);
+
+ // Guard: a default decode rejects the token for its expiry alone.
+ assert_eq!(
+ decode::<Claims>(
+ &expired_but_signed,
+ &DecodingKey::from_secret(SECRET),
+ &Validation::new(Algorithm::HS256),
+ )
+ .expect_err("the token must be expired, or this test proves nothing")
+ .kind(),
+ &jsonwebtoken::errors::ErrorKind::ExpiredSignature,
+ "the token must be rejected for its expiry and nothing else"
+ );
+
+ let table = deja::LookupTable {
+ recording_id: "jwt-novel-token-test".to_string(),
+ policy_version: deja::POLICY_VERSION,
+ event_schema_version: Some(deja::CURRENT_EVENT_SCHEMA_VERSION),
+ entries: vec![],
+ identity_entries: vec![],
+ };
+ let dir = tempfile::tempdir().expect("tempdir");
+ let path = dir.path().join("lookup.json");
+ std::fs::write(&path, serde_json::to_vec(&table).expect("serialize")).expect("write table");
+
+ let hook = deja::LookupTableHook::from_source(
+ deja::LocalFileLookupSource::new(path),
+ deja::InMemoryObservedSink::new(),
+ )
+ .expect("hook");
+ deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook)))
+ .expect("install replay hook");
+
+ let claims = decode_jwt_verified::<Claims>(&expired_but_signed, SECRET)
+ .expect("an expired but correctly signed token absent from the recording must decode");
+ assert_eq!(
+ claims.sub, SUBJECT,
+ "the claims must come from the token and nowhere else"
+ );
+ assert_eq!(
+ claims.exp, EXPIRED_AT,
+ "the expiry the decode ignored must survive it unchanged"
+ );
+
+ // Same claims, different key: only the signature differs.
+ let forged = signed_with(b"not-the-secret-the-caller-holds");
+ assert_eq!(
+ decode_jwt_verified::<Claims>(&forged, SECRET)
+ .expect_err("a token signed with the wrong secret must not decode")
+ .current_context(),
+ &JwtDecodeOutcome::Invalid,
+ "ignoring the expiry must not become ignoring the signature"
+ );
+}
diff --git a/crates/router/tests/deja_jwt_novel_token_fail_stops.rs b/crates/router/tests/deja_jwt_novel_token_fail_stops.rs
deleted file mode 100644
index 10012a5afe..0000000000
--- a/crates/router/tests/deja_jwt_novel_token_fail_stops.rs
+++ /dev/null
@@ -1,62 +0,0 @@
-// Integration test: assertions use panic!/expect(); allow the production-code
-// lints the v2 clippy profile denies.
-#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]
-//! A token the recording has never seen must not decode silently on replay.
-//!
-//! Substituting the decode outcome is what takes the clock out of the replay
-//! path, but it must not become a way for an unknown credential to be accepted.
-//! An empty lookup table guarantees a miss for any call, so this is decisive
-//! without constructing a matching key: the boundary fail-stops, and the real
-//! `jsonwebtoken` decode never runs.
-//!
-//! Own test binary: `set_global_runtime_hook` is a one-shot `OnceLock`.
-#![cfg(feature = "deja")]
-
-use router::services::authentication::decode_jwt_verified;
-
-// `Debug` because `expect_err` requires it on the Ok type.
-#[derive(Debug, serde::Serialize, serde::Deserialize)]
-struct Claims {
- sub: String,
-}
-
-#[test]
-fn a_token_absent_from_the_recording_fail_stops() {
- let table = deja::LookupTable {
- recording_id: "jwt-novel-token-test".to_string(),
- policy_version: 1,
- entries: vec![],
- };
- let dir = tempfile::tempdir().expect("tempdir");
- let path = dir.path().join("lookup.json");
- std::fs::write(&path, serde_json::to_vec(&table).expect("serialize")).expect("write table");
-
- let hook = deja::LookupTableHook::from_source(
- deja::LocalFileLookupSource::new(path),
- deja::InMemoryObservedSink::new(),
- )
- .expect("hook");
- deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook)))
- .expect("install replay hook");
-
- // The fail-stop's panic backtrace is expected; silence the default hook.
- let prev = std::panic::take_hook();
- std::panic::set_hook(Box::new(|_| {}));
- let result = std::panic::catch_unwind(|| {
- decode_jwt_verified::<Claims>("a-token-this-recording-has-never-seen", b"test-secret")
- });
- std::panic::set_hook(prev);
-
- let payload = result.expect_err(
- "a token absent from the recording must FAIL-STOP — not fall through to a real decode",
- );
- let message = payload
- .downcast_ref::<String>()
- .map(String::as_str)
- .or_else(|| payload.downcast_ref::<&str>().copied())
- .unwrap_or("<non-string panic payload>");
- assert!(
- message.contains("deja replay fail-stop") && message.contains("decode_jwt"),
- "the fail-stop must name the boundary that missed; got: {message:?}"
- );
-}
diff --git a/crates/router/tests/deja_jwt_tape_excludes_token.rs b/crates/router/tests/deja_jwt_tape_excludes_token.rs
index d8bc338d91..e48d04cc91 100644
--- a/crates/router/tests/deja_jwt_tape_excludes_token.rs
+++ b/crates/router/tests/deja_jwt_tape_excludes_token.rs
@@ -12,7 +12,7 @@
//!
//! Own test binary: `set_global_runtime_hook` is a one-shot `OnceLock`, so the
//! recording install here cannot share a process with the replay install in
-//! `deja_jwt_novel_token_fail_stops.rs`.
+//! `deja_jwt_novel_token_drops_only_the_clock.rs`.
#![cfg(feature = "deja")]
use router::services::authentication::{decode_jwt_verified, JwtDecodeOutcome};
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 148c782bc3..b420345f86 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 = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false }
-deja-core = { git = "https://github.com/juspay/deja", rev = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", optional = true, default-features = false }
+deja-core = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", 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.rs
index 40faf2c11d..d5e93164dd 100644
--- a/crates/router_env/src/request_id.rs
+++ b/crates/router_env/src/request_id.rs
@@ -148,10 +148,7 @@ pub(crate) mod boundary {
return None;
}
let recorded = hook.try_replay_with_context(deja::ReplayLookup {
- // `FailStop`: with no `on_miss` the caller mints a fresh uuid —
- // a value the recording never held, and one the rest of the
- // correlation is then keyed on.
- miss_policy: deja::MissPolicy::FailStop,
+ // No miss value: on a miss the caller mints a fresh, unrecorded uuid.
boundary: "id_generation",
trait_name: "router_env::request_id",
method_name,
@@ -1304,7 +1301,9 @@ mod tests {
Ok(deja::LookupTable {
recording_id: "empty".to_string(),
policy_version: 1,
+ event_schema_version: Some(deja::CURRENT_EVENT_SCHEMA_VERSION),
entries: Vec::new(),
+ identity_entries: Vec::new(),
})
}
}
diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml
index f3f0113377..40b61c8705 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 = "ade8fd16c1d8a4d23ca8fa3397bf70fe94e80510", optional = true, default-features = false }
+deja = { git = "https://github.com/juspay/deja", rev = "9230641b943a469ef4b506c05e3e9201363f3d10", 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.rs
index 8dc4a889cf..bb785cd66d 100644
--- a/crates/storage_impl/src/business_profile.rs
+++ b/crates/storage_impl/src/business_profile.rs
@@ -352,10 +352,10 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<domain::Profile>, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
merchant_key_store,
diesel::Profile::list_profile_by_merchant_id(&conn, merchant_id),
- )
+ ))
.await
}
}
diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs
index 16aa95430f..8778f94618 100644
--- a/crates/storage_impl/src/customers.rs
+++ b/crates/storage_impl/src/customers.rs
@@ -213,12 +213,12 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
let conn = pg_connection_write(self)
.await
.change_context(DatabaseError::DatabaseConnectionError)?;
- diesel_models::Customer::update_by_customer_id_merchant_id(
+ Box::pin(diesel_models::Customer::update_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
customer_update.foreign_into(),
- )
+ ))
.await
}
};
@@ -872,14 +872,14 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
let conn = pg_connection_read(self).await?;
let customer_list_constraints =
diesel_models::query::customers::CustomerListConstraints::from(constraints);
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
diesel_models::Customer::list_customers_by_merchant_id_and_constraints(
&conn,
merchant_id,
customer_list_constraints,
),
- )
+ ))
.await
}
@@ -899,16 +899,15 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
customer_id: customer_list_constraints.customer_id.clone(),
time_range: customer_list_constraints.time_range,
};
- let customers = self
- .find_resources_new(
- key_store,
- diesel_models::Customer::list_customers_by_merchant_id_and_constraints(
- &conn,
- merchant_id,
- customers_constraints,
- ),
- )
- .await?;
+ let customers = Box::pin(self.find_resources_new(
+ key_store,
+ diesel_models::Customer::list_customers_by_merchant_id_and_constraints(
+ &conn,
+ merchant_id,
+ customers_constraints,
+ ),
+ ))
+ .await?;
let total_count =
diesel_models::Customer::get_customer_count_by_merchant_id_and_constraints(
&conn,
diff --git a/crates/storage_impl/src/invoice.rs b/crates/storage_impl/src/invoice.rs
index 36e5fe9256..c7a715c41e 100644
--- a/crates/storage_impl/src/invoice.rs
+++ b/crates/storage_impl/src/invoice.rs
@@ -57,10 +57,10 @@ impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> {
.await
.change_context(StorageError::DecryptionError)?;
let conn = connection::pg_connection_write(self).await?;
- self.call_database(
+ Box::pin(self.call_database(
key_store,
Invoice::update_invoice_entry(&conn, invoice_id, inv_new),
- )
+ ))
.await
}
@@ -71,18 +71,17 @@ impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> {
subscription_id: String,
) -> CustomResult<DomainInvoice, StorageError> {
let conn = connection::pg_connection_write(self).await?;
- let invoices: Vec<DomainInvoice> = self
- .find_resources(
- key_store,
- Invoice::list_invoices_by_subscription_id(
- &conn,
- subscription_id.clone(),
- Some(1),
- None,
- false,
- ),
- )
- .await?;
+ let invoices: Vec<DomainInvoice> = Box::pin(self.find_resources(
+ key_store,
+ Invoice::list_invoices_by_subscription_id(
+ &conn,
+ subscription_id.clone(),
+ Some(1),
+ None,
+ false,
+ ),
+ ))
+ .await?;
invoices
.last()
diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs
index a62cb31487..8bb920e4f1 100644
--- a/crates/storage_impl/src/payment_method.rs
+++ b/crates/storage_impl/src/payment_method.rs
@@ -537,10 +537,10 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.call_database_new(
+ Box::pin(self.call_database_new(
key_store,
PaymentMethod::find_by_id(&conn, payment_method_id),
- )
+ ))
.await
}
@@ -569,7 +569,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_merchant_id_payment_method_ids(
&conn,
@@ -577,7 +577,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
payment_method_ids,
Some(200),
),
- )
+ ))
.await
}
@@ -710,10 +710,10 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit),
- )
+ ))
.await
}
@@ -727,10 +727,10 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_global_customer_id(&conn, id, limit),
- )
+ ))
.await
}
@@ -746,7 +746,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_customer_id_merchant_id_status(
&conn,
@@ -755,7 +755,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
status,
limit,
),
- )
+ ))
.await
}
@@ -772,7 +772,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, Self::Error> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_customer_id_merchant_id_status_pm_type(
&conn,
@@ -782,7 +782,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
payment_method_type,
limit,
),
- )
+ ))
.await
}
@@ -798,7 +798,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_global_customer_id_merchant_id_status(
&conn,
@@ -807,7 +807,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
status,
limit,
),
- )
+ ))
.await
}
@@ -823,7 +823,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
- self.find_resources_new(
+ Box::pin(self.find_resources_new(
key_store,
PaymentMethod::find_by_global_customer_id_merchant_id_statuses(
&conn,
@@ -832,7 +832,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
statuses,
limit,
),
- )
+ ))
.await
}
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 93c830bc75..10363209bd 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -722,6 +722,9 @@ impl Cache {
// 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.
+ //
+ // `on_miss = None`: an unrecorded read reports "not in cache", which is true of
+ // the cold replay cache, so the caller falls back instead of fail-stopping.
#[cfg_attr(
feature = "deja",
deja::boundary(
@@ -732,6 +735,7 @@ impl Cache {
effect = Imc,
codec = SerdeCodec,
args = deja_in_memory_args(self.name, &key),
+ on_miss = None,
)
)]
pub async fn get_val<T>(&self, key: CacheKey) -> Option<T>
@@ -753,6 +757,8 @@ impl Cache {
}
/// Check if a key exists in cache
+ //
+ // Deja: `on_miss = false` is the same "not in cache" answer as `get_val`.
#[cfg_attr(
feature = "deja",
deja::boundary(
@@ -763,6 +769,7 @@ impl Cache {
effect = Imc,
codec = SerdeCodec,
args = deja_in_memory_args(self.name, &key),
+ on_miss = false,
)
)]
pub async fn exists(&self, key: CacheKey) -> bool {
diff --git a/crates/storage_impl/src/subscription.rs b/crates/storage_impl/src/subscription.rs
index 4bdc3bf58c..fabaef5d6a 100644
--- a/crates/storage_impl/src/subscription.rs
+++ b/crates/storage_impl/src/subscription.rs
@@ -61,10 +61,10 @@ impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> {
.await
.change_context(StorageError::DecryptionError)?;
let conn = connection::pg_connection_write(self).await?;
- self.call_database(
+ Box::pin(self.call_database(
key_store,
Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, sub_new),
- )
+ ))
.await
}
@@ -78,7 +78,7 @@ impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> {
offset: Option<i64>,
) -> CustomResult<Vec<DomainSubscription>, StorageError> {
let conn = connection::pg_connection_write(self).await?;
- self.find_resources(
+ Box::pin(self.find_resources(
key_store,
Subscription::list_by_merchant_id_profile_id(
&conn,
@@ -87,7 +87,7 @@ impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> {
limit,
offset,
),
- )
+ ))
.await
}
}