Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(deja): route every clock and entropy read in the router through one seam (#14091)
Uzair Khan32b14ad1cfed
diff --git a/.clippy.toml b/.clippy.tomlindex 88530b7fb7..773ad0565d 100644--- a/.clippy.toml+++ b/.clippy.toml@@ -4,6 +4,24 @@ allow-panic-in-tests = trueallow-print-in-tests = trueallow-unwrap-in-tests = true+# Every read of the clock or of entropy goes through an instrumented function in+# `common_utils`, so that a replay can reproduce it. The only code allowed to read+# a raw source is a seam body itself, and each of those says so in an `#[allow]`+# with a reason. "It is only telemetry" and "it is only a test" are not exceptions:+# a raw read in either place is the one the next person copies onto a request path.disallowed-methods = [{ path = "diesel::query_dsl::QueryDsl::into_boxed", reason = "dynamic list queries must be built via diesel_models::list::boxed_list_query! or diesel_models::list::into_boxed_list" },+ { path = "time::OffsetDateTime::now_utc", reason = "a clock read outside a seam cannot be reproduced on replay; use common_utils::date_time (now, now_unix_timestamp, now_unix_timestamp_millis, now_rfc7231_http_date, date_as_yyyymmddthhmmssmmmz)" },+ { path = "chrono::Utc::now", reason = "a clock read outside a seam cannot be reproduced on replay; use common_utils::date_time" },+ { path = "std::time::SystemTime::now", reason = "a clock read outside a seam cannot be reproduced on replay; use common_utils::date_time" },+ { path = "uuid::Uuid::new_v4", reason = "a v4 UUID is drawn from entropy and cannot be reproduced on replay; use common_utils::generate_uuid_v4" },+ { path = "uuid::Uuid::now_v7", reason = "a v7 UUID is a timestamp plus 74 random bits, so neither the raw-clock nor the new_v4 entry catches it; use common_utils::generate_uuid_v7" },+ { path = "rand::thread_rng", reason = "a random draw outside a seam cannot be reproduced on replay; use common_utils (generate_random_alphanumeric_string, generate_random_numeric_string, generate_random_bytes, generate_random_number_in_range, generate_random_index, generate_random_permutation, generate_random_f64_unit), or common_utils::crypto for key material" },+ { path = "std::process::id", reason = "a process id differs between the recording process and the replay process; use common_utils::process_id" },+ { path = "gethostname::gethostname", reason = "a hostname differs between the recording host and the replay host; use common_utils::hostname, which reads HOSTNAME from the environment (the pod name under Kubernetes)" },+ { path = "rand::random", reason = "a random draw outside a seam cannot be reproduced on replay; use common_utils" },+]++disallowed-macros = [+ { path = "nanoid::nanoid", reason = "a nanoid is drawn from entropy and cannot be reproduced on replay; use common_utils::generate_nanoid_with_default_alphabet, or generate_id / generate_id_with_len for the consts::ALPHABETS variants" },]diff --git a/Cargo.lock b/Cargo.lockindex 5d92f081a8..0cea7caa26 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2871,7 +2871,7 @@ checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"[[package]]name = "deja"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"+source = "git+https://github.com/juspay/deja?rev=de0a42a42248fc22722bc5a385d9fa6a39449e91#de0a42a42248fc22722bc5a385d9fa6a39449e91"dependencies = ["deja-context","deja-core",@@ -2888,7 +2888,7 @@ dependencies = [[[package]]name = "deja-context"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"+source = "git+https://github.com/juspay/deja?rev=de0a42a42248fc22722bc5a385d9fa6a39449e91#de0a42a42248fc22722bc5a385d9fa6a39449e91"dependencies = ["pin-project-lite",]@@ -2896,7 +2896,7 @@ dependencies = [[[package]]name = "deja-core"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"+source = "git+https://github.com/juspay/deja?rev=de0a42a42248fc22722bc5a385d9fa6a39449e91#de0a42a42248fc22722bc5a385d9fa6a39449e91"dependencies = ["serde","serde_json",@@ -2906,7 +2906,7 @@ dependencies = [[[package]]name = "deja-derive"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"+source = "git+https://github.com/juspay/deja?rev=de0a42a42248fc22722bc5a385d9fa6a39449e91#de0a42a42248fc22722bc5a385d9fa6a39449e91"dependencies = ["proc-macro2","quote",@@ -2916,7 +2916,7 @@ dependencies = [[[package]]name = "deja-diesel"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"+source = "git+https://github.com/juspay/deja?rev=de0a42a42248fc22722bc5a385d9fa6a39449e91#de0a42a42248fc22722bc5a385d9fa6a39449e91"dependencies = ["async-bb8-diesel","deja-runtime",@@ -2926,7 +2926,7 @@ dependencies = [[[package]]name = "deja-runtime"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"+source = "git+https://github.com/juspay/deja?rev=de0a42a42248fc22722bc5a385d9fa6a39449e91#de0a42a42248fc22722bc5a385d9fa6a39449e91"dependencies = ["async-trait","deja-context",@@ -10397,6 +10397,7 @@ dependencies = ["base64 0.22.1","clap 4.5.38","common_enums",+ "common_utils","hyperswitch_masking","rand 0.8.5","regex",diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.tomlindex 2495b4cd0a..3f1d8f14e0 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 = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false }error-stack = "0.4.1"futures = { version = "0.3.31", optional = true }globset = "0.4.16"@@ -65,7 +65,7 @@ tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread"], optionalurl = { version = "2.5.4", features = ["serde"] }urlencoding = "2.1.3"utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order"] }-uuid = { version = "1.17.0", features = ["v7"] }+uuid = { version = "1.17.0", features = ["serde", "v4", "v7"] }ammonia = "3.3"# First party cratesdiff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rsindex 57ef863be2..93f84fe2fa 100644--- a/crates/common_utils/src/crypto.rs+++ b/crates/common_utils/src/crypto.rs@@ -908,21 +908,85 @@ pub fn extract_rsa_public_key_components(Ok((n_b64, e_b64))}+/// Random bytes for a cryptographic operation whose output has to be reproducible+/// on replay.+///+/// deja: seams the entropy a crypto primitive consumes internally. Substituting the+/// input leaves the candidate running the real algorithm over its own plaintext, so+/// a changed algorithm or message still diverges. Same shape as `GcmAes256::nonce`.+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils::crypto",+ operation = "secure_random_bytes",+ codec = SerdeCodec,+ )+)]+fn secure_random_bytes(length: usize) -> Vec<u8> {+ use rand::RngCore;++ let mut bytes = vec![0_u8; length];+ rand::rngs::OsRng.fill_bytes(&mut bytes);+ bytes+}++/// An `OsRng` that draws through [`secure_random_bytes`].+///+/// `rand_core`'s traits are not sealed, so an RNG can be handed to the `rsa`+/// crate. (`ring`'s `SecureRandom` *is* sealed, which is why `RsaPssSha256`+/// below cannot get the same treatment.)+#[derive(Debug, Clone, Copy)]+struct SeamedOsRng;++impl rand::RngCore for SeamedOsRng {+ fn next_u32(&mut self) -> u32 {+ let bytes: [u8; 4] = secure_random_bytes(4).try_into().unwrap_or([0; 4]);+ u32::from_le_bytes(bytes)+ }++ fn next_u64(&mut self) -> u64 {+ let bytes: [u8; 8] = secure_random_bytes(8).try_into().unwrap_or([0; 8]);+ u64::from_le_bytes(bytes)+ }++ fn fill_bytes(&mut self, dest: &mut [u8]) {+ let bytes = secure_random_bytes(dest.len());+ if bytes.len() == dest.len() {+ dest.copy_from_slice(&bytes);+ }+ }++ fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {+ self.fill_bytes(dest);+ Ok(())+ }+}++// Safety: every byte comes from `OsRng`; the seam only changes when they are+// drawn, never how.+impl rand::CryptoRng for SeamedOsRng {}+/// Encrypt plaintext using RSA-OAEP with SHA-256./// `public_key_der` must be a DER-encoded SubjectPublicKeyInfo (PKCS#8) public key./// Returns the raw ciphertext bytes.+//+// deja: OAEP padding is randomised, so the ciphertext differs on every run and+// fiservcommercehub's outbound request (`connector_relay/fiservcommercehub.rs:343`)+// never matched its recording. The RNG is an argument here, so the fix is to+// substitute the padding bytes rather than the ciphertext -- no key material and+// no plaintext enters the tape, and a candidate that changed the encryption still+// diverges.pub fn encrypt_rsa_oaep_sha256(public_key_der: &[u8],plaintext: &[u8],) -> CustomResult<Vec<u8>, errors::CryptoError> {- use rand::rngs::OsRng;-let public_key = rsa::RsaPublicKey::from_public_key_der(public_key_der).change_context(errors::CryptoError::EncodingFailed).attach_printable("Failed to parse DER public key for RSA-OAEP")?;let padding = Oaep::new::<rsa::sha2::Sha256>();- let mut rng = OsRng;+ let mut rng = SeamedOsRng;public_key.encrypt(&mut rng, padding, plaintext)@@ -931,6 +995,15 @@ pub fn encrypt_rsa_oaep_sha256(}/// Represents the RSA-PSS-SHA256 signing algorithm+//+// deja: NOT seamed — the one nondeterminism source left open here. PSS randomises+// its salt, so amazonpay's signature (`connectors/amazonpay.rs:175`) differs every+// run. Seaming the salt RNG is impossible: `ring::rand::SecureRandom` is sealed+// (`rand.rs:31`, `pub(crate) sealed`, in both 0.16.20 and 0.17), so nothing can be+// injected into `RsaKeyPair::sign`. Seaming `sign_message` instead is refused — its+// first argument is the PEM private key and tapes are widely read. The fix is to+// move this impl onto `rsa`, whose `pss::SigningKey::sign_with_rng` takes the RNG;+// that replaces a live signing implementation, so it needs its own change.#[derive(Debug)]pub struct RsaPssSha256;diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rsindex 287d418ba6..349a958520 100644--- a/crates/common_utils/src/keymanager.rs+++ b/crates/common_utils/src/keymanager.rs@@ -11,7 +11,6 @@ use once_cell::sync::OnceCell;use router_env::{global_meter, histogram_metric_f64, instrument, logger, metric_attributes, tracing,};-use time::OffsetDateTime;#[cfg(feature = "ext_services_latency")]use crate::consts::EXTERNAL_CALL_TAG;@@ -141,7 +140,7 @@ where))?;let latency_ms = elapsed.as_millis();- let created_at_timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos();+ let created_at_timestamp = crate::date_time::now().assume_utc().unix_timestamp_nanos();#[cfg(feature = "ext_services_latency")]{let downstream_request_id = responsediff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rsindex 997889da91..157bb40c6a 100644--- a/crates/common_utils/src/lib.rs+++ b/crates/common_utils/src/lib.rs@@ -79,6 +79,7 @@ pub mod date_time {deja::time(component = "common_utils", operation = "date_time::now", codec = SerdeCodec,))]pub fn now() -> PrimitiveDateTime {+ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]let utc_date_time = OffsetDateTime::now_utc();PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())}@@ -99,12 +100,41 @@ pub mod date_time {))]pub fn now_unix_timestamp() -> i64 {+ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]OffsetDateTime::now_utc().unix_timestamp()}/// Return the UNIX timestamp in nanoseconds of the current date and time in UTC+ ///+ /// Reads through `now()`, which is already a seam, so this needs no seam and+ /// no gate exception of its own and costs no extra event. `now()` keeps the+ /// full nanosecond, so the value is unchanged. `track_caller` so a caller's+ /// own location is what `now()` records.+ #[cfg_attr(feature = "deja", track_caller)]pub fn now_unix_timestamp_nanos() -> i128 {- OffsetDateTime::now_utc().unix_timestamp_nanos()+ now().assume_utc().unix_timestamp_nanos()+ }++ /// Return the UNIX timestamp in milliseconds of the current date and time in UTC.+ ///+ /// The seam for the millisecond timestamp several connectors sign into an+ /// outbound request, previously open-coded as `now_utc()…nanos() / 1_000_000`.+ #[cfg_attr(feature = "deja", track_caller)]+ #[cfg_attr(+ feature = "deja",+ deja::time(+ component = "common_utils",+ operation = "date_time::now_unix_timestamp_millis",+ codec = SerdeCodec,+ )+ )]+ pub fn now_unix_timestamp_millis() -> i128 {+ #[allow(+ clippy::disallowed_methods,+ reason = "this IS the seam for a millisecond timestamp"+ )]+ let now = OffsetDateTime::now_utc();+ now.unix_timestamp_nanos() / 1_000_000}/// Calculate execution time for a async block in milliseconds@@ -143,6 +173,7 @@ pub mod date_time {.encode();// Read the clock directly rather than via `now()`: both are instrumented seams, and// nesting them would record a redundant inner event for every outer call.+ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]convert_to_pdt(OffsetDateTime::now_utc()).assume_utc().format(&Iso8601::<ISO_CONFIG>)@@ -158,6 +189,7 @@ pub mod date_time {))]pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> {+ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]let now_utc = OffsetDateTime::now_utc();// Desired format: ddd, DD MMM YYYY HH:mm:ss GMT// Example: Fri, 23 May 2025 06:19:35 GMT@@ -262,6 +294,280 @@ pub mod date_time {}}+/// Generate a version 4 (random) UUID.+///+/// Nothing in the request determines a v4 UUID, so an unseamed read cannot be+/// replayed. Connectors put it in idempotency keys, request references, and — for+/// deutschebank, payeezy, authipay and the fiserv family — inside the signed+/// string, so a raw read moves the outbound bytes. Returns the `Uuid` rather than+/// a string so callers keep their own rendering.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "common_utils", operation = "generate_uuid_v4", codec = SerdeCodec,)+)]+#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+pub fn generate_uuid_v4() -> uuid::Uuid {+ uuid::Uuid::new_v4()+}++/// Generate a random alphanumeric string of the given length.+///+/// This is the seam for the nonce-and-salt shape that connectors open-coded as+/// `Alphanumeric.sample_string(&mut rand::thread_rng(), n)`.+///+/// Keeps the thread-local RNG deliberately: several of these are signed into+/// outbound requests, and swapping the generator would be a security change riding+/// on a determinism refactor. Use the `crypto` variant where unpredictability+/// matters.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_alphanumeric_string",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_alphanumeric_string(length: usize) -> String {+ use rand::distributions::DistString;++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ rand::distributions::Alphanumeric.sample_string(&mut rng, length)+}++/// Generate a random string of decimal digits of the given length.+///+/// The digit counterpart of [`generate_random_alphanumeric_string`]; santander+/// puts both on the wire. Draws once for the whole string rather than once per+/// character, so a call costs one recorded event and not `length` of them.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_numeric_string",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_numeric_string(length: usize) -> String {+ use rand::Rng;++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ (0..length)+ .map(|_| char::from(rng.gen_range(b'0'..=b'9')))+ .collect()+}++/// Generate a version 7 (time-ordered) UUID.+///+/// A v7 UUID is a millisecond timestamp followed by 74 random bits, so it is a+/// clock read and an entropy read at once — neither the raw-clock nor the+/// `Uuid::new_v4` gate entry catches it, which is why it has its own seam and its+/// own entry. razorpay and trustpay put one on the wire; vault ids, publishable+/// keys and relay ids are stored under one.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "common_utils", operation = "generate_uuid_v7", codec = SerdeCodec,)+)]+#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+pub fn generate_uuid_v7() -> uuid::Uuid {+ uuid::Uuid::now_v7()+}++/// Generate a nanoid of the given length using nanoid's own default alphabet.+///+/// Deliberately distinct from [`generate_id_with_len`], which uses+/// `consts::ALPHABETS` — 62 characters, no `-` or `_`. nanoid's default alphabet+/// has 64 and includes both. Five connectors put a default-alphabet nanoid on the+/// wire as a payment reference, so routing them through `generate_id_with_len`+/// would change the bytes they send; this seam keeps them byte-identical.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_nanoid_with_default_alphabet",+ codec = SerdeCodec,+ )+)]+#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]+pub fn generate_nanoid_with_default_alphabet(length: usize) -> String {+ nanoid::nanoid!(length)+}++/// Draw a uniform `f64` in `[0, 1)`.+///+/// This is the seam for a sampling decision: a value drawn here is compared+/// against a rollout percentage or a firing probability, so it decides which+/// branch the request takes. Unseamed, a replay takes a different branch from+/// the recording and the divergence is nobody's bug.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_f64_unit",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_f64_unit() -> f64 {+ use rand::Rng;++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ rng.gen_range(0.0..1.0)+}++/// Draw a uniform integer in `min..=max`, both ends inclusive.+///+/// Panics on an empty range, exactly as `rand`'s `gen_range` does for the+/// open-coded form this replaces.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_number_in_range",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_number_in_range(min: i64, max: i64) -> i64 {+ use rand::Rng;++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ rng.gen_range(min..=max)+}++/// Pick a uniform index into a collection of `length` items, or `None` if empty.+///+/// The seam for "choose one of these at random" where the choice decides what+/// goes on the wire — which OIDC key signs a token, for instance.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_index",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_index(length: usize) -> Option<usize> {+ use rand::Rng;++ if length == 0 {+ return None;+ }++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ Some(rng.gen_range(0..length))+}++/// The current process id.+///+/// Ambient state, not an input: a recording pod and a replay pod are different+/// processes, so anything derived from this on a request path would diverge.+/// There is no such caller today — this seam exists so that the gate on+/// `std::process::id` has somewhere to send the first one.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "common_utils", operation = "process_id", codec = SerdeCodec,)+)]+#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+pub fn process_id() -> u32 {+ std::process::id()+}++/// The host's name, read from the `HOSTNAME` environment variable.+///+/// Ambient state, like [`process_id`]: it differs between a recording host and a+/// replay host, so anything derived from it on a request path would diverge.+/// There is no such caller today; the seam exists so the gate on `gethostname`+/// has somewhere to send the first one.+///+/// Reads the environment rather than calling `gethostname(2)` on purpose. Under+/// Kubernetes `HOSTNAME` is the pod name, which is the identity that actually+/// matters here and is the same convention deja already uses to resolve its own+/// instance id (`identity.pod_name_env`). It also keeps `common_utils` free of a+/// dependency that would not build for wasm32, which this crate is compiled for.+/// Returns `None` when the variable is unset — a shell may set it without+/// exporting it, so a caller must handle its absence.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "common_utils", operation = "hostname", codec = SerdeCodec,)+)]+pub fn hostname() -> Option<String> {+ std::env::var("HOSTNAME")+ .ok()+ .filter(|name| !name.is_empty())+}++/// Produce a random permutation of `0..length`.+///+/// The seam for "shuffle these", which has no single-value shape: recording the+/// permutation costs one event where drawing it position by position would cost+/// `length` of them.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_permutation",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_permutation(length: usize) -> Vec<usize> {+ use rand::seq::SliceRandom;++ let mut indices: Vec<usize> = (0..length).collect();++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ indices.shuffle(&mut rng);+ indices+}++/// Generate `length` random bytes.+///+/// Not cryptographically secure — it keeps the thread-local RNG the open-coded+/// callers used. For key material use+/// [`crypto::generate_cryptographically_secure_random_bytes`] instead.+#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_random_bytes",+ codec = SerdeCodec,+ )+)]+pub fn generate_random_bytes(length: usize) -> Vec<u8> {+ use rand::Rng;++ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]+ let mut rng = rand::thread_rng();+ (0..length).map(|_| rng.gen()).collect()+}+/// Generate a nanoid with the given prefix and length#[inline]#[cfg_attr(feature = "deja", track_caller)]@@ -269,6 +575,7 @@ pub mod date_time {feature = "deja",deja::id(component = "common_utils", operation = "generate_id", codec = SerdeCodec,))]+#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]pub fn generate_id(length: usize, prefix: &str) -> String {format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS))}@@ -340,6 +647,7 @@ pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcquicodec = SerdeCodec,))]+#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]pub fn generate_id_with_default_len(prefix: &str) -> String {let len: usize = consts::ID_LENGTH;format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS))@@ -356,6 +664,7 @@ pub fn generate_id_with_default_len(prefix: &str) -> String {codec = SerdeCodec,))]+#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]pub fn generate_time_ordered_id(prefix: &str) -> String {format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple())}@@ -371,6 +680,7 @@ pub fn generate_time_ordered_id(prefix: &str) -> String {codec = SerdeCodec,))]+#[allow(clippy::disallowed_methods, reason = "this function IS the seam")]pub fn generate_time_ordered_id_without_prefix() -> String {uuid::Uuid::now_v7().as_simple().to_string()}@@ -382,6 +692,7 @@ pub fn generate_time_ordered_id_without_prefix() -> String {feature = "deja",deja::id(component = "common_utils", operation = "generate_id_with_len", codec = SerdeCodec,))]+#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]pub fn generate_id_with_len(length: usize) -> String {nanoid::nanoid!(length, &consts::ALPHABETS)}diff --git a/crates/common_utils/src/tokenization.rs b/crates/common_utils/src/tokenization.rsindex 8d19d68668..915c86a3ef 100644--- a/crates/common_utils/src/tokenization.rs+++ b/crates/common_utils/src/tokenization.rs@@ -11,6 +11,5 @@ use crate::consts::TOKEN_LENGTH;/// # Returns/// A randomly generated token string of length `TOKEN_LENGTH`pub fn generate_token() -> String {- use nanoid::nanoid;- nanoid!(TOKEN_LENGTH)+ crate::generate_nanoid_with_default_alphabet(TOKEN_LENGTH)}diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rsindex f9808262f3..a87d8186a9 100644--- a/crates/common_utils/src/types.rs+++ b/crates/common_utils/src/types.rs@@ -1539,7 +1539,8 @@ pub struct PublishableKey(LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_Limpl PublishableKey {/// Create a new PublishableKey Domain type without any length check from a static strpub fn generate(env_prefix: &'static str) -> Self {- let publishable_key_string = format!("pk_{env_prefix}_{}", uuid::Uuid::now_v7().simple());+ let publishable_key_string =+ format!("pk_{env_prefix}_{}", crate::generate_uuid_v7().simple());Self(LengthString::new_unchecked(publishable_key_string))}diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.tomlindex 607eda0d04..e3fc00a781 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 = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false, features = ["error-stack"] }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false, features = ["error-stack"] }[lints]workspace = truediff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rsindex ca74226e4f..a87f424dce 100644--- a/crates/diesel_models/src/query/generics.rs+++ b/crates/diesel_models/src/query/generics.rs@@ -86,7 +86,9 @@ pub mod db_metrics {status_code: if success { 200 } else { 500 },success,latency_ms: time_elapsed.as_millis(),- created_at_timestamp: common_utils::date_time::now_unix_timestamp_nanos(),+ created_at_timestamp: common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos(),});}}diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex 07522f9f2d..c7c58553ee 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -64,7 +64,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 = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false }error-stack = "0.4.1"hex = "0.4.3"hyper = "0.14.32"diff --git a/crates/external_services/src/grpc_client/deja_transport.rs b/crates/external_services/src/grpc_client/deja_transport.rsindex 4d80ed8a14..da7ca964f4 100644--- a/crates/external_services/src/grpc_client/deja_transport.rs+++ b/crates/external_services/src/grpc_client/deja_transport.rs@@ -58,7 +58,8 @@ impl<S> DejaGrpcTransport<S> {////// Valid ONLY under replay, where every call is served from the recording:/// readiness is answered directly, and a call the recording cannot answer- /// fail-stops via [`fail_stop_absent_transport`] rather than connecting.+ /// fail-stops via `deja::__private::fail_stop_absent_executor` rather than+ /// connecting.pub fn substituted() -> Self {Self { inner: None }}@@ -81,43 +82,6 @@ where}}-/// Replay fail-stop for a boundary that deliberately has no transport.-///-/// Distinct from `deja::__private::fail_stop_substitute_miss`, whose message-/// offers `replay_strategy = Execute` as the remedy: with nothing beneath the-/// boundary there is nothing to run, and the miss says nothing about the-/// candidate either way.-///-/// Names the rpc path and authority because `BOUNDARY` and `COMPONENT` are-/// module constants shared by every transport this wrapper is installed on.-// Panicking IS deja's fail-stop mechanism, not an accident: `catch_fail_stop_async`-// classifies the payload by `FAIL_STOP_SENTINEL` and renders the divergence. Returning-// an error instead would erase the stop from the diff artifact.-#[allow(clippy::panic)]-#[cold]-#[inline(never)]-fn fail_stop_absent_transport(- boundary: &str,- component: &str,- rpc: &str,- authority: Option<&str>,-) -> ! {- let target = match authority {- Some(authority) => format!("`{rpc}` at `{authority}`"),- None => format!("`{rpc}`"),- };- panic!(- "{} Substitute boundary `{boundary}` in `{component}` has no transport for \- {target}. It was constructed for substitution only: the host builds this \- transport eagerly, that connect did not succeed, and replay never issues \- this call live. The recording has no entry for these args, so there is \- nothing to substitute and nothing this boundary could have executed. This \- says nothing about the candidate — the call could not have been served \- here whatever the candidate did.",- deja::FAIL_STOP_SENTINEL- );-}-/// A boundary with no transport asked to issue a call live. Unreachable in/// practice — [`DejaGrpcTransport::substituted`] exists only under replay, where/// the `run` thunk is never invoked — but named so a broken invariant is legible.@@ -346,7 +310,19 @@ wheremove || async { Err(BoxError::from(AbsentTransportError)) },reconstruct_from_recorded,extract_envelope,- move || fail_stop_absent_transport(BOUNDARY, COMPONENT, &rpc, authority.as_deref()),+ // 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)+ },).await}diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rsindex 08fc8e975c..25196b226c 100644--- a/crates/external_services/src/http_client.rs+++ b/crates/external_services/src/http_client.rs@@ -84,7 +84,8 @@ pub fn serialize_to_xml_bytes<T: serde::Serialize>(args = hyperswitch_masking::ExposeInterface::expose(boundary::request_args(&request, option_timeout_secs)),// Rebuild the recorded reqwest::Response (status+headers+body) so the// outgoing call (e.g. Stripe) is served from the lookup table with no- // network. A recorded error reconstructs to None -> falls through to live.+ // 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,))]diff --git a/crates/external_services/src/http_client/boundary.rs b/crates/external_services/src/http_client/boundary.rsindex 15cd154e07..bb39db9526 100644--- a/crates/external_services/src/http_client/boundary.rs+++ b/crates/external_services/src/http_client/boundary.rs@@ -112,17 +112,24 @@ fn captured_body_json(response: &reqwest::Response) -> Secret<serde_json::Value>})}+/// Captures response headers, keeping every value under a repeated name.+///+/// This used to `insert` one value per name, so a response carrying three+/// `set-cookie` headers recorded one. The loss only bites on replay, and not at+/// this boundary: record builds the key-manager payload from the live response+/// and replay builds it from the reconstructed one, so the two payloads differ+/// in entry count and diverge downstream at `km` — twelve of the fifty-seven+/// value divergences on the 42-tape sweep.+///+/// Order across distinct names is deliberately not recorded. The comparison+/// sorts arrays before comparing (`bag_canon`), so a permutation of the same+/// values is already absorbed; only a change in what was recorded can diverge.fn response_headers_json(response: &reqwest::Response) -> Secret<serde_json::Value> {- let mut map = serde_json::Map::new();- for (key, value) in response.headers() {- if let Ok(value) = value.to_str() {- map.insert(- key.as_str().to_string(),- serde_json::Value::String(value.to_string()),- );- }- }- Secret::new(serde_json::Value::Object(map))+ // A non-UTF-8 header value has no JSON representation; drop the one entry+ // rather than failing the whole capture.+ Secret::new(deja::http::headers(response.headers().iter().filter_map(+ |(name, value)| value.to_str().ok().map(|value| (name.as_str(), value)),+ )))}pub(super) fn response_result(@@ -174,12 +181,15 @@ impl deja::codec::ReplayCodec for HttpResponseCodec {/// and body bytes, and all three come from the tape, so that call touches no/// network.///-/// A recorded ERROR carries no `status` field and reconstructs to `None`, which-/// the boundary treats as a lookup miss and answers by executing LIVE. Replaying-/// a request whose connector call failed therefore issues a real outbound request-/// to the real endpoint. This is the current Ok-only replay policy: replay is-/// egress-free only for as long as every recorded call succeeded, so it must not-/// be relied on as an egress guarantee.+/// Returning `None` does not fall through to a live call. deja maps it to+/// `Reconstructed::Failed`, which fail-stops the request with a named reason —+/// so a recorded value this build cannot read halts the replay rather than+/// quietly reaching the real endpoint.+///+/// Headers are read as an array of values per name and no other shape is+/// accepted. A recording written before that capture stored a single string per+/// name and had already lost every repeat; reading one would replay a tape that+/// still carries the defect this fixes, so it fail-stops instead.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()?;@@ -193,8 +203,13 @@ pub(super) fn replay_response(recorded: &serde_json::Value) -> Option<reqwest::Rlet mut builder = http::Response::builder().status(status);if let Some(headers) = recorded.get("response_headers").and_then(|h| h.as_object()) {- for (name, value) in headers {- if let Some(value) = value.as_str() {+ for (name, values) in headers {+ // `?` rather than a skip: a name whose values are not an array is a+ // pre-fix recording, and replaying it with its headers dropped would+ // be worse than refusing it.+ for value in values.as_array()?.iter().filter_map(|value| value.as_str()) {+ // `Builder::header` is `try_append`, so a repeated name keeps+ // every value rather than replacing the previous one.builder = builder.header(name.as_str(), value);}}@@ -238,3 +253,66 @@ fn request_body(body: &RequestContent) -> serde_json::Value {}}}++#[cfg(test)]+mod tests {+ use super::*;++ /// Three `set-cookie` headers must survive capture and reconstruct as three.+ ///+ /// Fails on the `insert`-per-name capture this replaced, which kept one value+ /// per name and so recorded a single cookie.+ #[test]+ fn repeated_headers_survive_capture_and_reconstruct() {+ let mut builder = http::Response::builder().status(200);+ for (name, value) in [+ ("x-request-id", "req-1"),+ ("set-cookie", "a=1"),+ ("set-cookie", "b=2"),+ ("set-cookie", "c=3"),+ ] {+ builder = builder.header(name, value);+ }+ let source = reqwest::Response::from(+ builder+ .body(bytes::Bytes::from_static(b"{}"))+ .expect("failed to build the test response"),+ );++ let result: CustomResult<reqwest::Response, HttpClientError> = Ok(source);+ let (captured, _) = response_result(&result);+ let captured = captured.expose();++ let reconstructed =+ replay_response(&captured).expect("a captured response must reconstruct");+ let cookies: Vec<&str> = reconstructed+ .headers()+ .get_all("set-cookie")+ .iter()+ .filter_map(|value| value.to_str().ok())+ .collect();+ assert_eq!(+ cookies,+ ["a=1", "b=2", "c=3"],+ "every set-cookie value must survive the round trip"+ );+ }++ /// A recording written before the capture kept repeats stored one string per+ /// name, having already lost every repeated value. Reconstructing it would+ /// replay a tape that still carries the defect this fixes, so it refuses —+ /// and deja turns that refusal into a fail-stop with a named reason rather+ /// than a live call.+ #[test]+ fn a_recording_with_one_value_per_name_is_refused() {+ let recorded = serde_json::json!({+ "status": 200,+ "response_headers": { "content-type": "application/json" },+ "response_body": { "raw_bytes": [] },+ });+ assert!(+ replay_response(&recorded).is_none(),+ "a pre-fix recording must refuse rather than replay with its headers dropped"+ );+ }+}diff --git a/crates/hyperswitch_connectors/src/connector_relay/fiservcommercehub.rs b/crates/hyperswitch_connectors/src/connector_relay/fiservcommercehub.rsindex 88f2bfb988..095bf0f5af 100644--- a/crates/hyperswitch_connectors/src/connector_relay/fiservcommercehub.rs+++ b/crates/hyperswitch_connectors/src/connector_relay/fiservcommercehub.rs@@ -16,8 +16,6 @@ use hyperswitch_interfaces::{use hyperswitch_masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};use ring::hmac;use serde::{Deserialize, Serialize};-use time::OffsetDateTime;-use uuid::Uuid;pub struct Fiservcommercehub;@@ -282,9 +280,9 @@ impl Fiservcommercehub {auth: &FiservcommercehubAuthType,body_str: &str,) -> Vec<(String, Maskable<String>)> {- let timestamp_ms = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;+ let timestamp_ms = common_utils::date_time::now_unix_timestamp_millis();let timestamp_str = timestamp_ms.to_string();- let client_request_id = Uuid::new_v4().to_string();+ let client_request_id = common_utils::generate_uuid_v4().to_string();let signature = auth.generate_hmac_signature(&client_request_id, ×tamp_str, body_str);vec![diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rsindex 72663ef09c..10a4349bf9 100644--- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs@@ -68,7 +68,7 @@ use hyperswitch_interfaces::{};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use serde::{Deserialize, Serialize};-use time::{Duration, OffsetDateTime, PrimitiveDateTime};+use time::{Duration, PrimitiveDateTime};use url::Url;#[cfg(feature = "payouts")]@@ -3640,7 +3640,11 @@ impl} => {// Validate expiry_date doesn't exceed 5 days from nowif let Some(expiry) = expiry_date {- let now = OffsetDateTime::now_utc();+ // The value never reaches the request, but it decides+ // whether the request is made at all: a recording whose+ // expiry_date was valid would fail this check when replayed+ // six days later. Substituting the clock is what stops that.+ let now = common_utils::date_time::now().assume_utc();let max_expiry = now + Duration::days(5);let max_expiry_primitive =PrimitiveDateTime::new(max_expiry.date(), max_expiry.time());@@ -5037,7 +5041,9 @@ pub fn get_wait_screen_metadata() -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {match next_action.action.payment_method_type {PaymentType::Blik => {- let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();+ let current_time = common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos();Ok(Some(serde_json::json!(WaitScreenData {display_from_timestamp: current_time,display_to_timestamp: Some(current_time + Duration::minutes(1).whole_nanoseconds()),@@ -5045,7 +5051,9 @@ pub fn get_wait_screen_metadata(})))}PaymentType::Mbway => {- let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();+ let current_time = common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos();Ok(Some(serde_json::json!(WaitScreenData {display_from_timestamp: current_time,display_to_timestamp: None,diff --git a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rsindex 921a063ab4..d67a3c2f96 100644--- a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs@@ -32,7 +32,6 @@ use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;use url::Url;-use uuid::Uuid;use crate::{types::{CreateOrderResponseRouterData, RefundsResponseRouterData, ResponseRouterData},@@ -131,7 +130,7 @@ impl TryFrom<&AirwallexRouterData<&types::CreateOrderRouterData>> for AirwallexI};Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),amount,currency,merchant_order_id: item.router_data.connector_request_reference_id.clone(),@@ -664,7 +663,7 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>};Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),payment_method,payment_method_options,return_url,@@ -1015,7 +1014,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for AirwallexCompleteRtype Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),three_ds: AirwallexThreeDsData {acs_response: item.request@@ -1047,7 +1046,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for AirwallexPaymentsCaptureRequtype Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),amount: Some(utils::to_currency_base_unit(item.request.amount_to_capture,item.request.currency,@@ -1067,7 +1066,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AirwallexPaymentsCancelRequestype Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),cancellation_reason: item.request.cancellation_reason.clone(),})}@@ -1640,7 +1639,7 @@ impl<F> TryFrom<&AirwallexRouterData<&types::RefundsRouterData<F>>> for Airwalleitem: &AirwallexRouterData<&types::RefundsRouterData<F>>,) -> Result<Self, Self::Error> {Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),amount: Some(item.amount.to_owned()),reason: item.router_data.request.reason.clone(),payment_intent_id: item.router_data.request.connector_transaction_id.clone(),@@ -2068,7 +2067,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {Ok(Self {- request_id: Uuid::new_v4().to_string(),+ request_id: common_utils::generate_uuid_v4().to_string(),email: item.request.email.to_owned(),phone_number: item.request.phone.to_owned(),first_name: item.request.name.to_owned(),diff --git a/crates/hyperswitch_connectors/src/connectors/amazonpay.rs b/crates/hyperswitch_connectors/src/connectors/amazonpay.rsindex 399e394369..8bd6f6bb78 100644--- a/crates/hyperswitch_connectors/src/connectors/amazonpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/amazonpay.rs@@ -3,7 +3,6 @@ pub mod transformers;use std::sync::LazyLock;use base64::{engine::general_purpose::STANDARD, Engine};-use chrono::Utc;use common_enums::enums;use common_utils::{crypto::{RsaPssSha256, SignMessage},@@ -229,9 +228,11 @@ where),(HEADER_DATE.to_string(),- Utc::now()- .format("%Y-%m-%dT%H:%M:%SZ")- .to_string()+ common_utils::date_time::now()+ .format(&time::macros::format_description!(+ "[year]-[month]-[day]T[hour]:[minute]:[second]Z"+ ))+ .change_context(errors::ConnectorError::RequestEncodingFailed)?.into_masked(),),(diff --git a/crates/hyperswitch_connectors/src/connectors/authipay.rs b/crates/hyperswitch_connectors/src/connectors/authipay.rsindex a42e48c5d4..bc1a3a1bd5 100644--- a/crates/hyperswitch_connectors/src/connectors/authipay.rs+++ b/crates/hyperswitch_connectors/src/connectors/authipay.rs@@ -109,14 +109,14 @@ whereconnectors: &Connectors,) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>{- let timestamp = time::OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;+ let timestamp = common_utils::date_time::now_unix_timestamp_millis();let auth: authipay::AuthipayAuthType =authipay::AuthipayAuthType::try_from(&req.connector_auth_type)?;let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;let authipay_req = self.get_request_body(req, connectors)?;- let client_request_id = uuid::Uuid::new_v4().to_string();+ let client_request_id = common_utils::generate_uuid_v4().to_string();let hmac = self.generate_authorization_signature(auth,diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rsindex 648f086f63..3fb1dea835 100644--- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs@@ -32,7 +32,6 @@ use hyperswitch_domain_models::{};use hyperswitch_interfaces::errors;use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};-use rand::distributions::{Alphanumeric, DistString};use regex::Regex;use serde::{Deserialize, Serialize};use serde_json::Value;@@ -49,7 +48,7 @@ const MAX_ID_LENGTH: usize = 20;const ADDRESS_MAX_LENGTH: usize = 60;fn get_random_string() -> String {- Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ID_LENGTH)+ common_utils::generate_random_alphanumeric_string(MAX_ID_LENGTH)}#[derive(Debug, Serialize)]diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rsindex 49679dcefd..2c1e7d2200 100644--- a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs+++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs@@ -152,7 +152,7 @@ wherereq: &RouterData<Flow, Request, Response>,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- let date = OffsetDateTime::now_utc();+ let date = common_utils::date_time::now().assume_utc();let boa_req = self.get_request_body(req, connectors)?;let http_method = self.get_http_method();let auth = bankofamerica::BankOfAmericaAuthType::try_from(&req.connector_auth_type)?;diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rsindex 5afaf738da..d394b29b18 100644--- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs+++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs@@ -165,7 +165,7 @@ wherereq: &RouterData<Flow, Request, Response>,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- let date = OffsetDateTime::now_utc();+ let date = common_utils::date_time::now().assume_utc();let barclaycard_req = self.get_request_body(req, connectors)?;let http_method = self.get_http_method();let auth = barclaycard::BarclaycardAuthType::try_from(&req.connector_auth_type)?;diff --git a/crates/hyperswitch_connectors/src/connectors/boku.rs b/crates/hyperswitch_connectors/src/connectors/boku.rsindex cb99663f74..61423bf1fd 100644--- a/crates/hyperswitch_connectors/src/connectors/boku.rs+++ b/crates/hyperswitch_connectors/src/connectors/boku.rs@@ -46,7 +46,6 @@ use hyperswitch_interfaces::{use hyperswitch_masking::{ExposeInterface, Mask, PeekInterface, Secret, WithType};use ring::hmac;use router_env::logger;-use time::OffsetDateTime;use transformers as boku;use crate::{@@ -106,7 +105,7 @@ wherelet connector_method = Self::get_http_method(self);- let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;+ let timestamp = common_utils::date_time::now_unix_timestamp_millis();let secret_key = boku::BokuAuthType::try_from(&req.connector_auth_type)?.key_iddiff --git a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rsindex 1f17e27516..a77e846613 100644--- a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs@@ -14,7 +14,6 @@ use hyperswitch_interfaces::errors;use hyperswitch_masking::Secret;use serde::{Deserialize, Serialize};use url::Url;-use uuid::Uuid;use crate::{types::{RefundsResponseRouterData, ResponseRouterData},@@ -163,7 +162,7 @@ implcountry,merchant_id: auth_type.merchant_id,merchant_transaction_id: Secret::new(item.payment_id.to_string()),- merchant_request_id: Uuid::new_v4().to_string(),+ merchant_request_id: common_utils::generate_uuid_v4().to_string(),merchant_item_description,notification_url: item.request.webhook_url.clone(),payment_method,@@ -403,7 +402,7 @@ impl<F> TryFrom<&BokuRouterData<&RefundsRouterData<F>>> for BokuRefundRequest {refund_amount: item.amount,merchant_id: auth_type.merchant_id,merchant_refund_id: Secret::new(item.router_data.request.refund_id.to_string()),- merchant_request_id: Uuid::new_v4().to_string(),+ merchant_request_id: common_utils::generate_uuid_v4().to_string(),charge_id: item.router_data.requestdiff --git a/crates/hyperswitch_connectors/src/connectors/checkout.rs b/crates/hyperswitch_connectors/src/connectors/checkout.rsindex d84b68a16e..0e1a23f426 100644--- a/crates/hyperswitch_connectors/src/connectors/checkout.rs+++ b/crates/hyperswitch_connectors/src/connectors/checkout.rs@@ -1710,7 +1710,7 @@ impl ConnectorSpecifications for Checkout {let attempt_id = payment_attempt.attempt_id.clone();if is_amex & (attempt_id.clone().len() > AMEX_PAYMENT_REFERENCE_LENGTH) {- nanoid::nanoid!(AMEX_PAYMENT_REFERENCE_LENGTH)+ common_utils::generate_nanoid_with_default_alphabet(AMEX_PAYMENT_REFERENCE_LENGTH)} else {payment_attempt.attempt_id.clone()}diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rsindex 6a1817a361..e73c48a5ab 100644--- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs+++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs@@ -334,7 +334,7 @@ wherereq: &RouterData<Flow, Request, Response>,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- let date = OffsetDateTime::now_utc();+ let date = common_utils::date_time::now().assume_utc();let cybersource_req = self.get_request_body(req, connectors)?;let auth = cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?;let merchant_account = auth.merchant_account.clone();diff --git a/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs b/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rsindex c0e078bb42..318d187de8 100644--- a/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs+++ b/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs@@ -163,7 +163,7 @@ wherereq: &RouterData<Flow, Request, Response>,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {- let date = OffsetDateTime::now_utc();+ let date = common_utils::date_time::now().assume_utc();let cybersource_req = self.get_request_body(req, connectors)?;let auth = cybersourcedecisionmanager::CybersourcedecisionmanagerAuthType::try_from(&req.connector_auth_type,diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rsindex e92bc25120..9c06bdf83f 100644--- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs@@ -1,8 +1,7 @@pub mod transformers;-use std::{sync::LazyLock, time::SystemTime};+use std::sync::LazyLock;-use actix_web::http::header::Date;use base64::Engine;use common_enums::enums;use common_utils::{@@ -49,7 +48,6 @@ use hyperswitch_interfaces::{webhooks,};use hyperswitch_masking::{ExposeInterface, Mask, Secret};-use rand::distributions::{Alphanumeric, DistString};use ring::hmac;use transformers as deutschebank;@@ -215,8 +213,9 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>) -> CustomResult<Option<Request>, errors::ConnectorError> {let auth = deutschebank::DeutschebankAuthType::try_from(&req.connector_auth_type)?;let client_id = auth.client_id.expose();- let date = Date(SystemTime::now().into()).to_string();- let random_string = Alphanumeric.sample_string(&mut rand::thread_rng(), 50);+ let date = common_utils::date_time::now_rfc7231_http_date()+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ let random_string = common_utils::generate_random_alphanumeric_string(50);let string_to_sign = client_id.clone() + &date + &random_string;let key = hmac::Key::new(hmac::HMAC_SHA256, auth.client_key.expose().as_bytes());diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rsindex f50250f74b..036196e3de 100644--- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs@@ -580,7 +580,7 @@ impl) -> Result<Self, Self::Error> {let signed_on = match item.response.approval_date.clone() {Some(date) => date.chars().take(10).collect(),- None => time::OffsetDateTime::now_utc().date().to_string(),+ None => common_utils::date_time::now().date().to_string(),};let response_code = item.response.rc.clone();let is_response_success = is_response_success(&response_code);diff --git a/crates/hyperswitch_connectors/src/connectors/dwolla.rs b/crates/hyperswitch_connectors/src/connectors/dwolla.rsindex b6f467f094..139ecb8f0b 100644--- a/crates/hyperswitch_connectors/src/connectors/dwolla.rs+++ b/crates/hyperswitch_connectors/src/connectors/dwolla.rs@@ -113,7 +113,7 @@ where),(headers::IDEMPOTENCY_KEY.to_string(),- uuid::Uuid::new_v4().to_string().into(),+ common_utils::generate_uuid_v4().to_string().into(),),];Ok(header)diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rsindex 98389bd6fa..d72b3c55b7 100644--- a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs@@ -132,7 +132,7 @@ impl TryFrom<&FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>>} => {// Set expiry time to 15 minutes from nowlet dynamic_pix_expires_at = {- let now = time::OffsetDateTime::now_utc();+ let now = common_utils::date_time::now().assume_utc();let expires_at = now + time::Duration::minutes(15);PrimitiveDateTime::new(expires_at.date(), expires_at.time())@@ -499,13 +499,13 @@ fn get_qr_code_data(datetime.unix_timestamp() * 1000} else {// If dynamic_pix_due_date isn't present, use current time + 15 minutes- let now = time::OffsetDateTime::now_utc();+ let now = common_utils::date_time::now().assume_utc();let expires_at = now + time::Duration::minutes(15);expires_at.unix_timestamp() * 1000}} else {// If meta is null, use current time + 15 minutes- let now = time::OffsetDateTime::now_utc();+ let now = common_utils::date_time::now().assume_utc();let expires_at = now + time::Duration::minutes(15);expires_at.unix_timestamp() * 1000};diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv.rs b/crates/hyperswitch_connectors/src/connectors/fiserv.rsindex 1731da216c..a471282bc6 100644--- a/crates/hyperswitch_connectors/src/connectors/fiserv.rs+++ b/crates/hyperswitch_connectors/src/connectors/fiserv.rs@@ -45,9 +45,7 @@ use hyperswitch_interfaces::{};use hyperswitch_masking::{ExposeInterface, Mask, PeekInterface};use ring::hmac;-use time::OffsetDateTime;use transformers as fiserv;-use uuid::Uuid;use crate::{constants::headers, types::ResponseRouterData, utils as connector_utils, utils::convert_amount,@@ -95,14 +93,14 @@ whereconnectors: &Connectors,) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>{- let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;+ let timestamp = common_utils::date_time::now_unix_timestamp_millis();let auth: fiserv::FiservAuthType =fiserv::FiservAuthType::try_from(&req.connector_auth_type)?;let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;let fiserv_req = self.get_request_body(req, connectors)?;- let client_request_id = Uuid::new_v4().to_string();+ let client_request_id = common_utils::generate_uuid_v4().to_string();let hmac = self.generate_authorization_signature(auth,diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rsindex 29af8b199e..cf36e9021c 100644--- a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs@@ -45,9 +45,7 @@ use hyperswitch_interfaces::{};use hyperswitch_masking::{ExposeInterface, Mask, PeekInterface};use ring::hmac;-use time::OffsetDateTime;use transformers as fiservemea;-use uuid::Uuid;use crate::{constants::headers,@@ -134,11 +132,11 @@ whereconnectors: &Connectors,) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>{- let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;+ let timestamp = common_utils::date_time::now_unix_timestamp_millis();let auth: fiservemea::FiservemeaAuthType =fiservemea::FiservemeaAuthType::try_from(&req.connector_auth_type)?;- let client_request_id = Uuid::new_v4().to_string();+ let client_request_id = common_utils::generate_uuid_v4().to_string();let http_method = self.get_http_method();let hmac = match http_method {Method::Get => selfdiff --git a/crates/hyperswitch_connectors/src/connectors/flexiti.rs b/crates/hyperswitch_connectors/src/connectors/flexiti.rsindex 574deea1ab..c9cd60846d 100644--- a/crates/hyperswitch_connectors/src/connectors/flexiti.rs+++ b/crates/hyperswitch_connectors/src/connectors/flexiti.rs@@ -44,7 +44,6 @@ use hyperswitch_interfaces::{};use hyperswitch_masking::PeekInterface;use transformers as flexiti;-use uuid::Uuid;use crate::{capture_method_not_supported,@@ -89,7 +88,7 @@ impl Flexiti {fn get_default_header() -> (String, hyperswitch_masking::Maskable<String>) {("x-reference-id".to_string(),- Uuid::new_v4().to_string().into(),+ common_utils::generate_uuid_v4().to_string().into(),)}}diff --git a/crates/hyperswitch_connectors/src/connectors/gigadat.rs b/crates/hyperswitch_connectors/src/connectors/gigadat.rsindex 1659ecb2ed..4858557ee8 100644--- a/crates/hyperswitch_connectors/src/connectors/gigadat.rs+++ b/crates/hyperswitch_connectors/src/connectors/gigadat.rs@@ -59,7 +59,6 @@ use lazy_static::lazy_static;#[cfg(feature = "payouts")]use router_env::{instrument, tracing};use transformers as gigadat;-use uuid::Uuid;#[cfg(feature = "payouts")]use crate::utils::{to_payout_connector_meta, RouterData as RouterDataTrait};@@ -500,7 +499,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat),(headers::IDEMPOTENCY_KEY.to_string(),- Uuid::new_v4().to_string().into_masked(),+ common_utils::generate_uuid_v4().to_string().into_masked(),),])}diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rsindex 4453064f94..f6f9dcee22 100644--- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs@@ -25,7 +25,6 @@ use hyperswitch_interfaces::{errors,};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};-use rand::distributions::DistString;use serde::{Deserialize, Serialize};use url::Url;@@ -306,7 +305,7 @@ impl TryFrom<&RefreshTokenRouterData> for GlobalpayRefreshTokenRequest {.change_context(errors::ConnectorError::FailedToObtainAuthType).attach_printable("Could not convert connector_auth to globalpay_auth")?;- let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let nonce = common_utils::generate_random_alphanumeric_string(12);let nonce_with_api_key = format!("{}{}", nonce, globalpay_auth.key.peek());let secret_vec = crypto::Sha512.generate_digest(nonce_with_api_key.as_bytes())diff --git a/crates/hyperswitch_connectors/src/connectors/globepay.rs b/crates/hyperswitch_connectors/src/connectors/globepay.rsindex a6a4e0802c..844705c457 100644--- a/crates/hyperswitch_connectors/src/connectors/globepay.rs+++ b/crates/hyperswitch_connectors/src/connectors/globepay.rs@@ -44,8 +44,6 @@ use hyperswitch_interfaces::{webhooks,};use hyperswitch_masking::ExposeInterface;-use rand::distributions::DistString;-use time::OffsetDateTime;use transformers as globepay;use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};@@ -104,8 +102,8 @@ fn get_globlepay_query_params(connector_auth_type: &ConnectorAuthType,) -> CustomResult<String, errors::ConnectorError> {let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;- let time = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000).to_string();- let nonce_str = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let time = common_utils::date_time::now_unix_timestamp_millis().to_string();+ let nonce_str = common_utils::generate_random_alphanumeric_string(12);let valid_string = format!("{}&{time}&{nonce_str}&{}",auth_type.partner_code.expose(),diff --git a/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs b/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rsindex 80f7d9649f..f45c2b40f4 100644--- a/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs+++ b/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs@@ -574,6 +574,6 @@ impl ConnectorSpecifications for GotymeSanlam {&self,_payout_attempt: &hyperswitch_domain_models::payouts::payout_attempt::PayoutAttempt,) -> String {- uuid::Uuid::new_v4().to_string()+ common_utils::generate_uuid_v4().to_string()}}diff --git a/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rsindex fad405e113..adce78b8d9 100644--- a/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs@@ -156,7 +156,7 @@ impl TryFrom<&GpaymentsRouterData<&PreAuthNRouterData>>merchant_id: metadata.merchant_id,skip_auto_browser_info_collect: Some(true),// should auto generate this id.- three_ds_requestor_trans_id: uuid::Uuid::new_v4().hyphenated().to_string(),+ three_ds_requestor_trans_id: common_utils::generate_uuid_v4().hyphenated().to_string(),})}}diff --git a/crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs b/crates/hyperswitch_connectors/src/connectors/moneris/transformers.rsindex a02692d952..49006e531e 100644--- a/crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs@@ -117,7 +117,7 @@ impl TryFrom<&MonerisRouterData<&PaymentsAuthorizeRouterData>> for MonerisPaymenconnector: "Moneris",})?};- let idempotency_key = uuid::Uuid::new_v4().to_string();+ let idempotency_key = common_utils::generate_uuid_v4().to_string();let amount = Amount {currency: item.router_data.request.currency,amount: item.amount,@@ -162,7 +162,7 @@ impl TryFrom<&MonerisRouterData<&PaymentsAuthorizeRouterData>> for MonerisPaymen})}PaymentMethodData::MandatePayment => {- let idempotency_key = uuid::Uuid::new_v4().to_string();+ let idempotency_key = common_utils::generate_uuid_v4().to_string();let amount = Amount {currency: item.router_data.request.currency,amount: item.amount,@@ -352,7 +352,7 @@ impl TryFrom<&MonerisRouterData<&PaymentsCaptureRouterData>> for MonerisPaymentscurrency: item.router_data.request.currency,amount: item.amount,};- let idempotency_key = uuid::Uuid::new_v4().to_string();+ let idempotency_key = common_utils::generate_uuid_v4().to_string();Ok(Self {amount,idempotency_key,@@ -370,7 +370,7 @@ pub struct MonerisCancelRequest {impl TryFrom<&PaymentsCancelRouterData> for MonerisCancelRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {- let idempotency_key = uuid::Uuid::new_v4().to_string();+ let idempotency_key = common_utils::generate_uuid_v4().to_string();let reason = item.request.cancellation_reason.clone();Ok(Self {idempotency_key,@@ -395,7 +395,7 @@ impl<F> TryFrom<&MonerisRouterData<&RefundsRouterData<F>>> for MonerisRefundRequcurrency: item.router_data.request.currency,amount: item.amount,};- let idempotency_key = uuid::Uuid::new_v4().to_string();+ let idempotency_key = common_utils::generate_uuid_v4().to_string();let reason = item.router_data.request.reason.clone();let payment_id = item.router_data.request.connector_transaction_id.clone();Ok(Self {diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets.rs b/crates/hyperswitch_connectors/src/connectors/nexinets.rsindex a9d78ea613..eddf1de926 100644--- a/crates/hyperswitch_connectors/src/connectors/nexinets.rs+++ b/crates/hyperswitch_connectors/src/connectors/nexinets.rs@@ -891,7 +891,7 @@ impl ConnectorSpecifications for Nexinets {.unwrap_or_else(|| {let max_payment_reference_id_length =nexinets::nexinets_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH;- nanoid::nanoid!(max_payment_reference_id_length)+ common_utils::generate_nanoid_with_default_alphabet(max_payment_reference_id_length)})}}diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rsindex 903718e19e..a0513e74b0 100644--- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs@@ -52,7 +52,6 @@ use hyperswitch_masking::{ExposeInterface, Mask};use lazy_static::lazy_static;use serde_json::Value;use transformers as nexixpay;-use uuid::Uuid;use crate::{constants::headers,@@ -159,7 +158,7 @@ impl ConnectorCommon for Nexixpay {),(headers::CORRELATION_ID.to_string(),- Uuid::new_v4().to_string().into_masked(),+ common_utils::generate_uuid_v4().to_string().into_masked(),),])}@@ -911,7 +910,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo{let mut header = vec![(headers::IDEMPOTENCY_KEY.to_string(),- Uuid::new_v4().to_string().into_masked(),+ common_utils::generate_uuid_v4().to_string().into_masked(),)];let mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);@@ -1011,7 +1010,7 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ne{let mut header = vec![(headers::IDEMPOTENCY_KEY.to_string(),- Uuid::new_v4().to_string().into_masked(),+ common_utils::generate_uuid_v4().to_string().into_masked(),)];let mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);@@ -1118,7 +1117,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nexixpa{let mut header = vec![(headers::IDEMPOTENCY_KEY.to_string(),- Uuid::new_v4().to_string().into_masked(),+ common_utils::generate_uuid_v4().to_string().into_masked(),)];let mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);diff --git a/crates/hyperswitch_connectors/src/connectors/nomupay.rs b/crates/hyperswitch_connectors/src/connectors/nomupay.rsindex b5fba9a427..b920acc5f4 100644--- a/crates/hyperswitch_connectors/src/connectors/nomupay.rs+++ b/crates/hyperswitch_connectors/src/connectors/nomupay.rs@@ -1,7 +1,5 @@pub mod transformers;-use std::time::{Duration, SystemTime, UNIX_EPOCH};-use common_utils::{errors::CustomResult,ext_traits::BytesExt,@@ -117,11 +115,8 @@ fn get_signature() -> CustomResult<String, errors::ConnectorError> {match body {RequestContent::Json(masked_json) => {- let expiration_time = SystemTime::now() + Duration::from_secs(4 * 60);- let expires_in = match expiration_time.duration_since(UNIX_EPOCH) {- Ok(duration) => duration.as_secs(),- Err(_e) => 0,- };+ let expires_in =+ u64::try_from(common_utils::date_time::now_unix_timestamp() + 4 * 60).unwrap_or(0);let mut option_map = Map::new();option_map.insert("alg".to_string(), json!("ES256"));diff --git a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rsindex 23f73ad6ea..20b920afa7 100644--- a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs@@ -15,7 +15,6 @@ use hyperswitch_domain_models::{};use hyperswitch_interfaces::errors;use hyperswitch_masking::Secret;-use rand::distributions::DistString;use serde::{Deserialize, Deserializer, Serialize};use crate::{@@ -115,7 +114,7 @@ impl TryFrom<&AccessTokenAuthenticationRouterData> for NordeaOAuthRequest {AccessScope::PaymentsMultiple,].to_vec();- let state = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 15);+ let state = common_utils::generate_random_alphanumeric_string(15);Ok(Self {country,diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rsindex 7557b31a2e..c26b9ad69c 100644--- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs+++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs@@ -1843,7 +1843,7 @@ impl ConnectorSpecifications for Nuvei {payment_attempt.payment_id.get_string_repr().to_owned()} else {let max_payment_reference_id_length = nuvei::MAX_CLIENT_UNIQUE_ID_LENGTH;- nanoid::nanoid!(max_payment_reference_id_length)+ common_utils::generate_nanoid_with_default_alphabet(max_payment_reference_id_length)}}}diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rsindex b621abe845..ea87eb1c50 100644--- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs@@ -1326,8 +1326,9 @@ wherelet additional_params = match item.request.is_customer_initiated_mandate_payment() {true => Some(V2AdditionalParams {rebill_expiry: Some(- time::OffsetDateTime::now_utc()- .replace_year(time::OffsetDateTime::now_utc().year() + 5)+ date_time::now()+ .assume_utc()+ .replace_year(date_time::now().assume_utc().year() + 5).map_err(|_| errors::ConnectorError::DateFormattingFailed)?.date().format(&time::macros::format_description!("[year][month][day]"))diff --git a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rsindex 6adef0f392..7b23d4d67c 100644--- a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs@@ -498,12 +498,7 @@ fn get_transaction_type(}}fn get_paybox_request_number() -> Result<String, Error> {- let time_stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .ok()- .ok_or(errors::ConnectorError::RequestEncodingFailed)?- .as_millis()- .to_string();+ let time_stamp = common_utils::date_time::now_unix_timestamp_millis().to_string();// unix time (in milliseconds) has 13 digits.if we consider 8 digits(the number digits to make day deterministic) there is no collision in the paybox_request_number as it will reset the paybox_request_number for each day and paybox accepting maximum length is 10 so we gonna take 9 (13-9)let request_number = time_stamp.get(4..)diff --git a/crates/hyperswitch_connectors/src/connectors/payeezy.rs b/crates/hyperswitch_connectors/src/connectors/payeezy.rsindex 7cedf71ee6..9d1c10eda6 100644--- a/crates/hyperswitch_connectors/src/connectors/payeezy.rs+++ b/crates/hyperswitch_connectors/src/connectors/payeezy.rs@@ -45,7 +45,6 @@ use hyperswitch_interfaces::{webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},};use hyperswitch_masking::{ExposeInterface, Mask};-use rand::distributions::DistString;use ring::hmac;use transformers as payeezy;@@ -69,13 +68,8 @@ where.get_request_body(req, connectors)?.get_inner_value().expose();- let timestamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .ok()- .ok_or(errors::ConnectorError::RequestEncodingFailed)?- .as_millis()- .to_string();- let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 19);+ let timestamp = common_utils::date_time::now_unix_timestamp_millis().to_string();+ let nonce = common_utils::generate_random_alphanumeric_string(19);let signature_string = auth.api_key.clone().zip(auth.merchant_token.clone()).map(|(api_key, merchant_token)| {format!("{api_key}{nonce}{timestamp}{merchant_token}{request_payload}")diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rsindex 852c40e4fb..d1d359baca 100644--- a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs@@ -25,7 +25,6 @@ use hyperswitch_interfaces::{};use hyperswitch_masking::Secret;use serde::{Deserialize, Serialize};-use time::OffsetDateTime;use crate::{types::ResponseRouterData,@@ -906,7 +905,8 @@ fn get_transaction_operations(}fn get_send_date_time() -> Result<String, errors::ConnectorError> {- OffsetDateTime::now_utc()+ common_utils::date_time::now()+ .assume_utc().format(&time::format_description::well_known::Iso8601::DEFAULT).map_err(|_| errors::ConnectorError::RequestEncodingFailed)}diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rsindex 574a21e33f..7a90d2bbcd 100644--- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs@@ -11,7 +11,6 @@ use hyperswitch_domain_models::{use hyperswitch_interfaces::{consts, errors};use hyperswitch_masking::{ExposeInterface, Secret};use serde::{Deserialize, Serialize};-use uuid::Uuid;use crate::{types::{RefundsResponseRouterData, ResponseRouterData},@@ -163,7 +162,7 @@ impl TryFrom<&PowertranzRouterData<&PaymentsAuthorizeRouterData>> for PowertranzAuthenticationType::NoThreeDs => (false, None),};Ok(Self {- transaction_identifier: Uuid::new_v4().to_string(),+ transaction_identifier: common_utils::generate_uuid_v4().to_string(),total_amount: item.amount,currency_code: item.router_data.request.currency.iso_4217().to_string(),three_d_secure,diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd.rs b/crates/hyperswitch_connectors/src/connectors/rapyd.rsindex df06688269..7d1a6a4e10 100644--- a/crates/hyperswitch_connectors/src/connectors/rapyd.rs+++ b/crates/hyperswitch_connectors/src/connectors/rapyd.rs@@ -49,7 +49,6 @@ use hyperswitch_interfaces::{webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},};use hyperswitch_masking::{ExposeInterface, Mask, PeekInterface, Secret};-use rand::distributions::{Alphanumeric, DistString};use ring::hmac;use router_env::logger;use transformers as rapyd;@@ -226,7 +225,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseDataconnectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {let timestamp = date_time::now_unix_timestamp();- let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let salt = common_utils::generate_random_alphanumeric_string(12);let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;let body = types::PaymentsAuthorizeType::get_request_body(self, req, connectors)?;@@ -340,7 +339,7 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Raconnectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {let timestamp = date_time::now_unix_timestamp();- let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let salt = common_utils::generate_random_alphanumeric_string(12);let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;let url_path = format!("/v1/payments/{}", req.request.connector_transaction_id);@@ -432,7 +431,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Rapconnectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {let timestamp = date_time::now_unix_timestamp();- let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let salt = common_utils::generate_random_alphanumeric_string(12);let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;let response_id = req.request.connector_transaction_id.clone();@@ -530,7 +529,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> foconnectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {let timestamp = date_time::now_unix_timestamp();- let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let salt = common_utils::generate_random_alphanumeric_string(12);let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;let url_path = format!(@@ -664,7 +663,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Rapyd {connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {let timestamp = date_time::now_unix_timestamp();- let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);+ let salt = common_utils::generate_random_alphanumeric_string(12);let body = types::RefundExecuteType::get_request_body(self, req, connectors)?;let req_body = body.get_inner_value().expose();diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay.rs b/crates/hyperswitch_connectors/src/connectors/razorpay.rsindex e2b3e45a7a..ab3550f14e 100644--- a/crates/hyperswitch_connectors/src/connectors/razorpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/razorpay.rs@@ -849,6 +849,6 @@ impl ConnectorSpecifications for Razorpay {.merchant_reference_id.as_ref().map(|id| id.get_string_repr().to_owned())- .unwrap_or_else(|| uuid::Uuid::now_v7().to_string())+ .unwrap_or_else(|| common_utils::generate_uuid_v7().to_string())}}diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rsindex 8d95aec9ff..90cb82ba89 100644--- a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs@@ -18,7 +18,7 @@ use hyperswitch_domain_models::{use hyperswitch_interfaces::errors;use hyperswitch_masking::Secret;use serde::{Deserialize, Serialize};-use time::{Duration, OffsetDateTime};+use time::Duration;use crate::{types::{@@ -273,7 +273,9 @@ pub struct WaitScreenData {pub fn get_wait_screen_metadata() -> CustomResult<Option<serde_json::Value>, errors::ConnectorError>{- let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();+ let current_time = common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos();Ok(Some(serde_json::json!(WaitScreenData {display_from_timestamp: current_time,display_to_timestamp: Some(current_time + Duration::minutes(5).whole_nanoseconds()),diff --git a/crates/hyperswitch_connectors/src/connectors/santander.rs b/crates/hyperswitch_connectors/src/connectors/santander.rsindex 14af13406b..ade7ca867c 100644--- a/crates/hyperswitch_connectors/src/connectors/santander.rs+++ b/crates/hyperswitch_connectors/src/connectors/santander.rs@@ -1427,7 +1427,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for San.ok_or(errors::ConnectorError::MissingRequiredField {field_name: "issue_date/due_date".into(),})?;- let payment_date_final = time::OffsetDateTime::now_utc()+ let payment_date_final = common_utils::date_time::now().date().format(&time::macros::format_description!("[year]-[month]-[day]")).change_context(errors::ConnectorError::DateFormattingFailed)?;diff --git a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rsindex c9d0d4cd8d..09c47b767b 100644--- a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs@@ -709,7 +709,7 @@ implenvironment: Some(Environment::Producao),nsu_code,nsu_date: Some(- time::OffsetDateTime::now_utc()+ common_utils::date_time::now().date().format(&time::macros::format_description!("[year]-[month]-[day]")).change_context(errors::ConnectorError::DateFormattingFailed)?,@@ -719,7 +719,7 @@ implclient_number: order_id.clone(),due_date: Some(format_as_date_only(due_date)?),issue_date: Some(- time::OffsetDateTime::now_utc()+ common_utils::date_time::now().date().format(&time::macros::format_description!("[year]-[month]-[day]")).change_context(errors::ConnectorError::DateFormattingFailed)?,@@ -1117,7 +1117,8 @@ impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>>// Use mandate_execution_date from MIT data if provided, otherwise default to current date + 1 daylet due_date = match mit_data.mandate_execution_date {Some(exec_date) => format_as_date_only(Some(exec_date))?,- None => time::OffsetDateTime::now_utc()+ None => common_utils::date_time::now()+ .assume_utc().checked_add(time::Duration::days(1)).ok_or(errors::ConnectorError::DateFormattingFailed)?.date()@@ -2609,7 +2610,7 @@ impl.as_ref().and_then(|token| token.parse::<i64>().ok());- let current_date = time::OffsetDateTime::now_utc().date();+ let current_date = common_utils::date_time::now().date();let data_inicial = match mandate_details.as_ref().and_then(|md| md.start_date) {Some(start_date) => {@@ -2808,7 +2809,8 @@ impl TryFrom<&PaymentsPushNotificationRouterData> for SantanderPixAutomaticSolic.attach_printable("Failed to get pix_automatico_push expiry time")?;let expiry_seconds = i64::from(expiry_time_seconds);- let offset_datetime = time::OffsetDateTime::now_utc()+ let offset_datetime = common_utils::date_time::now()+ .assume_utc().checked_add(time::Duration::seconds(expiry_seconds)).ok_or(errors::ConnectorError::ParsingFailed)?;@@ -2904,7 +2906,9 @@ impl TryFrom<&PaymentsPushNotificationRouterData> for SantanderPixAutomaticSolicfn get_wait_screen_metadata(expiry_in_secs: u64,) -> CustomResult<Option<Value>, errors::ConnectorError> {- let current_time = time::OffsetDateTime::now_utc().unix_timestamp_nanos();+ let current_time = common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos();let expiry_duration_nanos = i128::from(expiry_in_secs) * 1_000_000_000;// confirm this value from sdk teamlet delay_in_secs: u16 = 5;@@ -3245,7 +3249,7 @@ implidentifier: item.data.request.scope.clone(),connector_webhook_id: Some(santander_composite_webhook_id(item.data.payment_method_type,- &uuid::Uuid::new_v4().to_string(),+ &common_utils::generate_uuid_v4().to_string(),)),status: common_enums::WebhookRegistrationStatus::Success,error_code: None,diff --git a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rsindex c738e97ce7..fe3faeb894 100644--- a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs+++ b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs@@ -984,7 +984,7 @@ impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequestcurrency,};Ok(Self {- return_id: uuid::Uuid::new_v4().to_string(),+ return_id: common_utils::generate_uuid_v4().to_string(),refund_transaction_id: item.request.refund_transaction_id.clone(),refund,order_id: item.attempt_id.clone(),diff --git a/crates/hyperswitch_connectors/src/connectors/tesouro.rs b/crates/hyperswitch_connectors/src/connectors/tesouro.rsindex 053c0baddd..8d346e40e5 100644--- a/crates/hyperswitch_connectors/src/connectors/tesouro.rs+++ b/crates/hyperswitch_connectors/src/connectors/tesouro.rs@@ -1021,7 +1021,7 @@ impl ConnectorSpecifications for Tesouro {} else {let max_payment_reference_id_length =tesouro::tesouro_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH;- nanoid::nanoid!(max_payment_reference_id_length)+ common_utils::generate_nanoid_with_default_alphabet(max_payment_reference_id_length)}}}diff --git a/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rsindex 5ce83bd904..9d7ba213dd 100644--- a/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs@@ -818,8 +818,11 @@ impl TryFrom<&TesouroRouterData<&PaymentsAuthorizeRouterData>> for TesouroAuthor})?;Some(tesouro_metadata.activity_date)} else {- let now = chrono::Utc::now();- Some(now.format("%Y-%m-%d").to_string())+ Some(+ common_utils::date_time::now()+ .format(&time::macros::format_description!("[year]-[month]-[day]"))+ .change_context(errors::ConnectorError::RequestEncodingFailed)?,+ )}};diff --git a/crates/hyperswitch_connectors/src/connectors/tokenio.rs b/crates/hyperswitch_connectors/src/connectors/tokenio.rsindex bbc3d58648..74fc697054 100644--- a/crates/hyperswitch_connectors/src/connectors/tokenio.rs+++ b/crates/hyperswitch_connectors/src/connectors/tokenio.rs@@ -1,8 +1,5 @@pub mod transformers;-use std::{- sync::LazyLock,- time::{SystemTime, UNIX_EPOCH},-};+use std::sync::LazyLock;use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};use common_enums::{enums, FeatureStatus, PaymentMethodType};@@ -72,11 +69,7 @@ impl Tokenio {connectors: &Connectors,) -> CustomResult<String, errors::ConnectorError> {// Create JWT header- let exp_time = SystemTime::now()- .duration_since(UNIX_EPOCH)- .change_context(errors::ConnectorError::RequestEncodingFailed)?- .as_millis()- + 600_000; // 10 minutes+ let exp_time = common_utils::date_time::now_unix_timestamp_millis() + 600_000; // 10 minuteslet header = serde_json::json!({"alg": match auth.key_algorithm {diff --git a/crates/hyperswitch_connectors/src/connectors/truelayer.rs b/crates/hyperswitch_connectors/src/connectors/truelayer.rsindex b66faa9e2e..4cc056b682 100644--- a/crates/hyperswitch_connectors/src/connectors/truelayer.rs+++ b/crates/hyperswitch_connectors/src/connectors/truelayer.rs@@ -101,7 +101,7 @@ whereconnectors: &Connectors,) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>{- let idempotency_key = uuid::Uuid::new_v4().to_string();+ let idempotency_key = common_utils::generate_uuid_v4().to_string();let truelayer_req = self.get_request_body(req, connectors).map(|req| req.get_inner_value().expose().clone())?;@@ -1095,7 +1095,7 @@ impl ConnectorSpecifications for Truelayer {#[cfg(feature = "v1")]_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,) -> api::ConnectorCustomerAction {- let connector_customer_id = uuid::Uuid::new_v4().to_string();+ let connector_customer_id = common_utils::generate_uuid_v4().to_string();api::ConnectorCustomerAction::GeneratedCustomerId(connector_customer_id)}}diff --git a/crates/hyperswitch_connectors/src/connectors/trustly.rs b/crates/hyperswitch_connectors/src/connectors/trustly.rsindex 77ff8dcd0a..67c155ee70 100644--- a/crates/hyperswitch_connectors/src/connectors/trustly.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustly.rs@@ -938,7 +938,7 @@ impl ConnectorSpecifications for Trustly {#[cfg(feature = "v1")]_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,) -> api::ConnectorCustomerAction {- let connector_customer_id = uuid::Uuid::new_v4().to_string();+ let connector_customer_id = common_utils::generate_uuid_v4().to_string();api::ConnectorCustomerAction::GeneratedCustomerId(connector_customer_id)}}diff --git a/crates/hyperswitch_connectors/src/connectors/trustly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustly/transformers.rsindex 3293c82dfa..da3815acad 100644--- a/crates/hyperswitch_connectors/src/connectors/trustly/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustly/transformers.rs@@ -526,7 +526,7 @@ impl<F> TryFrom<&TrustlyRouterData<&PayoutsRouterData<F>>> for RegisterAccountReNone};- let uuid = uuid::Uuid::new_v4().to_string();+ let uuid = common_utils::generate_uuid_v4().to_string();let auth_details =TrustlyAuthType::try_from(&item.router_data.connector_auth_type)?;let private_key = auth_details.private_key.clone();@@ -711,7 +711,7 @@ impl<F> TryFrom<&TrustlyRouterData<&PayoutsRouterData<F>>> for AccountPayoutRequTrustlyAuthType::try_from(&item.router_data.connector_auth_type)?;let private_key = auth_details.private_key.clone();- let uuid = uuid::Uuid::new_v4().to_string();+ let uuid = common_utils::generate_uuid_v4().to_string();let account_payout_data = AccountPayoutData {account_i_d: account_id.account_id,amount: item.amount.clone(),@@ -880,7 +880,7 @@ impl<F> TryFrom<&PayoutsRouterData<F>> for TrustlyPayoutSyncRequest {};let private_key = auth_details.private_key.clone();- let uuid = uuid::Uuid::new_v4().to_string();+ let uuid = common_utils::generate_uuid_v4().to_string();let signature = generate_trustly_signature(TrustlyMethod::GetWithdrawals.as_str(),uuid.as_str(),diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rsindex 0c429d4b66..e2e09208e0 100644--- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs@@ -1591,6 +1591,6 @@ impl ConnectorSpecifications for Trustpay {_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,) -> String {// The length of receipt for Trustpay order request should not exceed 35 characters.- uuid::Uuid::now_v7().simple().to_string()+ common_utils::generate_uuid_v7().simple().to_string()}}diff --git a/crates/hyperswitch_connectors/src/connectors/volt.rs b/crates/hyperswitch_connectors/src/connectors/volt.rsindex 7c5ec8edfc..85543b1d86 100644--- a/crates/hyperswitch_connectors/src/connectors/volt.rs+++ b/crates/hyperswitch_connectors/src/connectors/volt.rs@@ -121,7 +121,7 @@ where),(headers::IDEMPOTENCY_KEY.to_string(),- uuid::Uuid::new_v4().to_string().into(),+ common_utils::generate_uuid_v4().to_string().into(),),(X_VOLT_API_VERSION.to_string(), VOLT_VERSION.into()),(diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rsindex 66eef29be6..d5beac9282 100644--- a/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs+++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs@@ -299,7 +299,7 @@ wherereq: &RouterData<Flow, Request, Response>,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- let date = OffsetDateTime::now_utc();+ let date = common_utils::date_time::now().assume_utc();let wellsfargo_req = self.get_request_body(req, connectors)?;let auth = wellsfargo::WellsfargoAuthType::try_from(&req.connector_auth_type)?;let merchant_account = auth.merchant_account.clone();diff --git a/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wise/transformers.rsindex f7d5809ba3..d1a04ce7ac 100644--- a/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs@@ -540,7 +540,7 @@ impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutCreateRequest {Ok(Self {target_account,quote_uuid,- customer_transaction_id: uuid::Uuid::new_v4().to_string(),+ customer_transaction_id: common_utils::generate_uuid_v4().to_string(),details: wise_transfer_details,})}diff --git a/crates/hyperswitch_connectors/src/connectors/worldline.rs b/crates/hyperswitch_connectors/src/connectors/worldline.rsindex 79ef8b9161..7699a6d665 100644--- a/crates/hyperswitch_connectors/src/connectors/worldline.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldline.rs@@ -49,7 +49,6 @@ use hyperswitch_interfaces::{use hyperswitch_masking::{ExposeInterface, Mask, PeekInterface};use ring::hmac;use router_env::logger;-use time::{format_description, OffsetDateTime};use transformers as worldline;use crate::{@@ -89,12 +88,7 @@ impl Worldline {}pub fn get_current_date_time() -> CustomResult<String, errors::ConnectorError> {- let format = format_description::parse(- "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT",- )- .change_context(errors::ConnectorError::InvalidDateFormat)?;- OffsetDateTime::now_utc()- .format(&format)+ common_utils::date_time::now_rfc7231_http_date().change_context(errors::ConnectorError::InvalidDateFormat)}}diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rsindex 33cf347a7b..b3eb167f59 100644--- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs@@ -1815,7 +1815,7 @@ impl ConnectorSpecifications for Worldpayvantiv {} else {let max_payment_reference_id_length =worldpayvantiv::worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH;- nanoid::nanoid!(max_payment_reference_id_length)+ common_utils::generate_nanoid_with_default_alphabet(max_payment_reference_id_length)}}#[cfg(feature = "v2")]diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rsindex 008a6b4a0a..5be991e78e 100644--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs@@ -2479,8 +2479,7 @@ wherefn generate_jwt_for_ddc(metadata_for_jwt: WorldpayxmlConnectorMetadataObject,) -> Result<String, errors::ConnectorError> {- let iat: u64 = chrono::Utc::now()- .timestamp()+ let iat: u64 = common_utils::date_time::now_unix_timestamp().try_into().map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?;@@ -2503,7 +2502,7 @@ fn generate_jwt_for_ddc()?;let payload_json = DeviceDataCollectionJwt {- jti: uuid::Uuid::new_v4().to_string(),+ jti: common_utils::generate_uuid_v4().to_string(),iat,iss: Secret::new(iss),org_unit_id: Secret::new(org_unit_id),@@ -2532,8 +2531,7 @@ fn generate_challenge_jwt(return_url: String,metadata_for_jwt: WorldpayxmlConnectorMetadataObject,) -> Result<String, errors::ConnectorError> {- let iat: u64 = chrono::Utc::now()- .timestamp()+ let iat: u64 = common_utils::date_time::now_unix_timestamp().try_into().map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?;@@ -2556,7 +2554,7 @@ fn generate_challenge_jwt()?;let payload_json = ChallengeJwt {- jti: uuid::Uuid::new_v4().to_string(),+ jti: common_utils::generate_uuid_v4().to_string(),iat,iss: Secret::new(iss),org_unit_id: Secret::new(org_unit_id),diff --git a/crates/hyperswitch_connectors/src/connectors/zen.rs b/crates/hyperswitch_connectors/src/connectors/zen.rsindex 0f2f6c11ef..d64e037650 100644--- a/crates/hyperswitch_connectors/src/connectors/zen.rs+++ b/crates/hyperswitch_connectors/src/connectors/zen.rs@@ -49,7 +49,6 @@ use hyperswitch_interfaces::{};use hyperswitch_masking::{Mask, PeekInterface, Secret};use transformers::{self as zen, ZenPaymentStatus, ZenWebhookTxnType};-use uuid::Uuid;use crate::{constants::headers, types::ResponseRouterData};@@ -71,7 +70,10 @@ impl api::RefundSync for Zen {}impl Zen {fn get_default_header() -> (String, hyperswitch_masking::Maskable<String>) {- ("request-id".to_string(), Uuid::new_v4().to_string().into())+ (+ "request-id".to_string(),+ common_utils::generate_uuid_v4().to_string().into(),+ )}}diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rsindex 7f15281612..f206470f4e 100644--- a/crates/hyperswitch_connectors/src/utils.rs+++ b/crates/hyperswitch_connectors/src/utils.rs@@ -80,7 +80,6 @@ use quick_xml::{events::{BytesDecl, BytesText, Event},Writer,};-use rand::Rng;use regex::Regex;use router_env::logger;use serde::{Deserialize, Serialize};@@ -362,8 +361,7 @@ pub(crate) fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) ->pub(crate) fn generate_random_bytes(length: usize) -> Vec<u8> {// returns random bytes of length n- let mut rng = rand::thread_rng();- (0..length).map(|_| Rng::gen(&mut rng)).collect()+ common_utils::generate_random_bytes(length)}pub(crate) fn missing_field_err(@@ -3658,7 +3656,8 @@ macro_rules! capture_method_not_supported {macro_rules! get_formatted_date_time {($date_format:tt) => {{let format = time::macros::format_description!($date_format);- time::OffsetDateTime::now_utc()+ common_utils::date_time::now()+ .assume_utc().format(&format).change_context(ConnectorError::InvalidDateFormat)}};@@ -7933,27 +7932,24 @@ pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>(}pub fn generate_12_digit_number() -> u64 {- let mut rng = rand::thread_rng();- rng.gen_range(100_000_000_000..=999_999_999_999)+ const MIN: i64 = 100_000_000_000;+ const MAX: i64 = 999_999_999_999;+ u64::try_from(common_utils::generate_random_number_in_range(MIN, MAX))+ .unwrap_or(100_000_000_000)}pub fn generate_random_string_containing_digits(min_len: usize, max_len: usize) -> String {- let mut rng = rand::thread_rng();- let len = rng.gen_range(min_len..=max_len);+ common_utils::generate_random_numeric_string(random_length(min_len, max_len))+}- (0..len)- .map(|_| char::from(rng.gen_range(b'0'..=b'9')))- .collect()+/// Pick a length in `min_len..=max_len` through the seamed index draw.+fn random_length(min_len: usize, max_len: usize) -> usize {+ let span = max_len.saturating_sub(min_len).saturating_add(1);+ min_len.saturating_add(common_utils::generate_random_index(span).unwrap_or(0))}pub fn generate_alphanumeric_code(min_len: usize, max_len: usize) -> String {- let mut rng = rand::thread_rng();- let len = rng.gen_range(min_len..=max_len);-- rng.sample_iter(&rand::distributions::Alphanumeric)- .take(len)- .map(char::from)- .collect()+ common_utils::generate_random_alphanumeric_string(random_length(min_len, max_len))}/// Normalizes a string by converting to lowercase, performing NFKD normalization(https://unicode.org/reports/tr15/#Description_Norm),and removing special characters and spaces.diff --git a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rsindex 6bd961bb45..fc87951b5e 100644--- a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs+++ b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs@@ -4,7 +4,6 @@ use common_utils::request::Method;use router_env::RequestId;use serde::Serialize;use serde_json::json;-use time::OffsetDateTime;/// struct ConnectorEvent#[derive(Debug, Serialize)]@@ -69,7 +68,7 @@ impl ConnectorEvent {url,method: method.to_string(),merchant_id,- created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,+ created_at: common_utils::date_time::now_unix_timestamp_millis(),request_id: request_id.map(|i| i.to_string()).unwrap_or("NO_REQUEST_ID".to_string()),diff --git a/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs b/crates/hyperswitch_interfaces/src/events/routing_api_logs.rsindex d8ed519f03..1b091ffd98 100644--- a/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs+++ b/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs@@ -7,7 +7,6 @@ use common_utils::request::Method;use router_env::RequestId;use serde::Serialize;use serde_json::json;-use time::OffsetDateTime;/// RoutingEngine enum#[derive(Debug, Clone, Copy, Serialize)]@@ -88,7 +87,9 @@ impl RoutingEvent {payment_id,profile_id,merchant_id,- created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),+ created_at: common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos(),status_code: None,request_id: request_id.map(|i| i.to_string())diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.tomlindex 39cf60c7c9..a47023248b 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 cratescommon_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }-deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false, features = ["error-stack"] }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false, features = ["error-stack"] }router_env = { version = "0.1.0", path = "../router_env", optional = true }[dev-dependencies]diff --git a/crates/redis_interface/src/metrics.rs b/crates/redis_interface/src/metrics.rsindex 44ed3a0530..42c93c4a46 100644--- a/crates/redis_interface/src/metrics.rs+++ b/crates/redis_interface/src/metrics.rs@@ -144,7 +144,9 @@ wherestatus_code: if success { 200 } else { 500 },success,latency_ms: time_elapsed.as_millis(),- created_at_timestamp: common_utils::date_time::now_unix_timestamp_nanos(),+ created_at_timestamp: common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos(),});}diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rsindex 7a342317be..417e881351 100644--- a/crates/redis_interface/src/test.rs+++ b/crates/redis_interface/src/test.rs@@ -37,11 +37,8 @@ fn unique_test_id() -> String {use std::sync::atomic::{AtomicU64, Ordering};static COUNTER: AtomicU64 = AtomicU64::new(0);let counter = COUNTER.fetch_add(1, Ordering::SeqCst);- let pid = std::process::id();- let millis = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis())- .unwrap_or(0);+ let pid = common_utils::process_id();+ let millis = common_utils::date_time::now_unix_timestamp_millis();format!("{pid}_{millis}_{counter}")}@@ -915,14 +912,7 @@ async fn test_set_expire_at_and_get_ttl() {let _ = pool.set_key(&key, "value".to_string()).await;- let future_ts = i64::try_from(- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_secs(),- )- .unwrap()- + 120;+ let future_ts = common_utils::date_time::now_unix_timestamp() + 120;let set_result = pool.set_expire_at(&key, future_ts).await;let ttl_result = pool.get_ttl(&key).await;diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 6ac4499715..9c65693421 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -300,8 +300,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 = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }-deja-core = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", 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/configs/settings.rs b/crates/router/src/configs/settings.rsindex 6331fb9dfa..902553f140 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -43,7 +43,6 @@ pub use payment_methods::configs::{},AuthenticationServiceConfig, MicroServicesConfig,};-use rand::seq::IteratorRandom;use redis_interface::RedisSettings;pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};use rust_decimal::Decimal;@@ -1065,9 +1064,23 @@ impl OidcSettings {self.client.values().find(|c| c.client_id == client_id)}+ // deja: split out of get_signing_key so the sort's property — candidate+ // order follows the key set's content, not which `HashMap` instance holds+ // it — is testable without pinning the draw. See the tests below.+ fn sorted_key_ids(&self) -> Vec<&String> {+ // `HashMap` iteration is seeded per process, so seaming the draw alone+ // is not enough — a recorded index would select a different key on+ // replay. Sorting gives the index a stable meaning.+ let mut key_ids: Vec<&String> = self.key.keys().collect();+ key_ids.sort_unstable();+ key_ids+ }+pub fn get_signing_key(&self) -> Option<&OidcKey> {- let mut rng = rand::thread_rng();- self.key.values().choose_stable(&mut rng)+ let key_ids = self.sorted_key_ids();++ let index = common_utils::generate_random_index(key_ids.len())?;+ self.key.get(key_ids.get(index).copied()?)}pub fn get_all_keys(&self) -> Vec<&OidcKey> {@@ -1075,6 +1088,59 @@ impl OidcSettings {}}+#[cfg(test)]+mod oidc_signing_key_tests {+ use std::collections::HashMap;++ use hyperswitch_masking::Secret;++ use super::{OidcClient, OidcKey, OidcSettings};++ fn oidc_key(kid: &str) -> OidcKey {+ OidcKey {+ kid: kid.to_string(),+ private_key: Secret::new(String::new()),+ }+ }++ fn oidc_settings_with_keys(kids: &[&str]) -> OidcSettings {+ OidcSettings {+ key: kids+ .iter()+ .map(|kid| (kid.to_string(), oidc_key(kid)))+ .collect::<HashMap<String, OidcKey>>(),+ client: HashMap::<String, OidcClient>::new(),+ }+ }++ // deja: a replay reproduces `self.key`'s content from config, not its+ // iteration order -- `HashMap`'s hasher is seeded per instance, so two+ // `OidcSettings` built from the same config data can iterate their keys+ // in a different order. `get_signing_key` sorts before drawing so the+ // recorded index still names the same key; that is the property this+ // test asserts, and it is not visible from either single call's result+ // shape alone. If the sort in `sorted_key_ids` is ever dropped, two+ // independently-constructed instances holding the same key set resolve+ // their candidate order from raw hasher-seeded iteration, which very+ // reliably differs across instances for a set this size -- so this+ // assertion fails on that regression rather than passing by accident.+ #[test]+ fn signing_key_order_is_independent_of_which_hashmap_instance_holds_it() {+ let kids = ["a", "m", "z", "b", "y", "c", "x", "d", "w", "e"];++ let first = oidc_settings_with_keys(&kids);+ let second = oidc_settings_with_keys(&kids);++ assert_eq!(+ first.sorted_key_ids(),+ second.sorted_key_ids(),+ "the same signing-key set, built as two separate HashMap instances, \+ produced a different candidate order -- a recorded index would no \+ longer name the same key on replay"+ );+ }+}+#[derive(Debug, Deserialize, Clone)]#[serde(default)]pub struct Locker {diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex fc096428dd..7cf9d74c95 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -21,7 +21,6 @@ use hyperswitch_domain_models::merchant_connector_account::{};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use pm_auth::types as pm_auth_types;-use uuid::Uuid;#[cfg(feature = "olap")]use {base64::Engine,@@ -80,7 +79,7 @@ pub fn create_merchant_publishable_key() -> String {format!("pk_{}_{}",router_env::env::prefix_for_env(),- Uuid::new_v4().simple()+ common_utils::generate_uuid_v4().simple())}diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex ef03c8d500..a931b70aab 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -1099,9 +1099,7 @@ pub async fn schedule_dispute_sync_task()?;if core_utils::should_add_dispute_sync_task_to_pt(state, connector) {- let offset_date_time = time::OffsetDateTime::now_utc();- let created_from =- time::PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time());+ let created_from = common_utils::date_time::now();let dispute_polling_interval = *business_profile.dispute_polling_interval.unwrap_or_default()diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rsindex 28fed68152..1644aa9e61 100644--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs@@ -154,7 +154,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudCpayment_method_token: None,connector_customer: None,preprocessing_id: None,- connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ connector_request_reference_id: common_utils::generate_uuid_v4().to_string(),test_mode: None,recurring_mandate_payment_data: None,#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rsindex a49389615c..2d9a42d4e6 100644--- a/crates/router/src/core/fraud_check/flows/record_return.rs+++ b/crates/router/src/core/fraud_check/flows/record_return.rs@@ -109,7 +109,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudChconnector_customer: None,preprocessing_id: None,payment_method_status: None,- connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ connector_request_reference_id: common_utils::generate_uuid_v4().to_string(),test_mode: None,recurring_mandate_payment_data: None,#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rsindex 6affa3d750..6c555c996c 100644--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs@@ -161,7 +161,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckRespconnector_customer: None,preprocessing_id: None,payment_method_status: None,- connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ connector_request_reference_id: common_utils::generate_uuid_v4().to_string(),test_mode: None,recurring_mandate_payment_data: None,#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rsindex 5c4c5236ad..382913468c 100644--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs@@ -127,7 +127,7 @@ implpayment_method_token: None,connector_customer: None,preprocessing_id: None,- connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ connector_request_reference_id: common_utils::generate_uuid_v4().to_string(),test_mode: None,recurring_mandate_payment_data: None,#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rsindex 7ecda8437f..a878c375fc 100644--- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs+++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs@@ -3,7 +3,6 @@ use common_enums::FrmSuggestion;use common_utils::ext_traits::Encode;use diesel_models::enums::FraudCheckLastStep;use router_env::{instrument, tracing};-use uuid::Uuid;use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};use crate::{@@ -108,7 +107,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {Some(Some(fraud_check)) => Ok(fraud_check),_ => {db.insert_fraud_check_response(FraudCheckNew {- frm_id: Uuid::new_v4().simple().to_string(),+ frm_id: common_utils::generate_uuid_v4().simple().to_string(),payment_id: payment_data.payment_intent.get_id().to_owned(),merchant_id: payment_data.merchant_account.get_id().clone(),processor_merchant_id: Some(diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 223b3aa539..4f335e9def 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -1057,7 +1057,7 @@ impl PaymentMethodsController for PmCards<'_> {key_store.merchant_id.clone(),customer_id.to_owned(),),- vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),+ vault_id: domain::VaultId::generate(common_utils::generate_uuid_v7().to_string()),data: pmd,ttl: self.state.conf.locker.ttl_for_storage_in_secs,}@@ -2128,8 +2128,9 @@ pub fn encode_add_vault_request(// New fingerprint migration path uses merchant-scoped vault entity ids.pm_types::AddVaultRequestNew {entity_id: merchant_id,- vault_id: vault_id- .unwrap_or_else(|| domain::VaultId::generate(uuid::Uuid::now_v7().to_string())),+ vault_id: vault_id.unwrap_or_else(|| {+ domain::VaultId::generate(common_utils::generate_uuid_v7().to_string())+ }),data: pmd,ttl,}@@ -2154,7 +2155,7 @@ pub fn encode_add_vault_request(merchant_id,customer_id.to_owned(),),- vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),+ vault_id: domain::VaultId::generate(common_utils::generate_uuid_v7().to_string()),data: pmd,ttl,}@@ -2213,8 +2214,8 @@ pub fn encode_add_vault_request(ttl: i64,vault_id: Option<domain::VaultId>,) -> errors::CustomResult<Vec<u8>, errors::VaultError> {- let vault_id =- vault_id.unwrap_or_else(|| domain::VaultId::generate(uuid::Uuid::now_v7().to_string()));+ let vault_id = vault_id+ .unwrap_or_else(|| domain::VaultId::generate(common_utils::generate_uuid_v7().to_string()));if should_trigger_fingerprint_migration {pm_types::AddVaultRequestNew {@@ -3841,9 +3842,9 @@ pub async fn mock_call_to_locker_hs() -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> {let mut locker_mock_up = storage::LockerMockUpNew {card_id: card_id.to_string(),- external_id: uuid::Uuid::new_v4().to_string(),- card_fingerprint: uuid::Uuid::new_v4().to_string(),- card_global_fingerprint: uuid::Uuid::new_v4().to_string(),+ external_id: common_utils::generate_uuid_v4().to_string(),+ card_fingerprint: common_utils::generate_uuid_v4().to_string(),+ card_global_fingerprint: common_utils::generate_uuid_v4().to_string(),merchant_id: id_type::MerchantId::default(),card_number: "4111111111111111".to_string(),card_exp_year: "2099".to_string(),diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rsindex e4ed3060b3..19f971e844 100644--- a/crates/router/src/core/payment_methods/network_tokenization.rs+++ b/crates/router/src/core/payment_methods/network_tokenization.rs@@ -141,7 +141,7 @@ pub async fn mk_tokenization_req(.attach_printable("Error on jwe encrypt")?;let order_data = pm_types::OrderData {- consent_id: uuid::Uuid::new_v4().to_string(),+ consent_id: common_utils::generate_uuid_v4().to_string(),customer_id,};@@ -313,7 +313,7 @@ pub async fn generate_network_token(.attach_printable("Error on jwe encrypt")?;let order_data = pm_types::OrderData {- consent_id: uuid::Uuid::new_v4().to_string(),+ consent_id: common_utils::generate_uuid_v4().to_string(),customer_id,};diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 81cd35d6fa..105440ede5 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -64,14 +64,12 @@ use openssl::{pkey::PKey,symm::{decrypt_aead, Cipher},};-use rand::Rng;#[cfg(feature = "v2")]use redis_interface::errors::RedisError;use router_env::{instrument, logger, tracing};use rust_decimal::Decimal;use serde::{de::DeserializeOwned, Deserialize, Serialize};use serde_with::{serde_as, VecSkipError};-use uuid::Uuid;use x509_parser::parse_x509_certificate;use super::{@@ -903,7 +901,7 @@ pub async fn get_token_for_recurring_mandate(.await.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;- let token = Uuid::new_v4().to_string();+ let token = common_utils::generate_uuid_v4().to_string();let payment_method_type = payment_method.get_payment_method_subtype();let mandate_connector_details = payments::MandateConnectorDetails {connector: mandate.connector,@@ -2657,7 +2655,7 @@ impl From<RolloutConfig> for RolloutExecutionResult {Self::default()}true => {- let sampled_value: f64 = rand::thread_rng().gen_range(0.0..1.0);+ let sampled_value: f64 = common_utils::generate_random_f64_unit();let should_execute = sampled_value < config.rollout_percent;logger::debug!(@@ -4399,7 +4397,7 @@ pub async fn make_ephemeral_key() -> errors::RouterResponse<ephemeral_key::EphemeralKey> {let store = &state.store;let id = utils::generate_id(consts::ID_LENGTH, "eki");- let secret = format!("epk_{}", Uuid::new_v4().simple());+ let secret = format!("epk_{}", common_utils::generate_uuid_v4().simple());let ek = ephemeral_key::EphemeralKeyNew {id,customer_id,@@ -5601,9 +5599,7 @@ fn validate_manual_retry_cutoff(intent_fulfillment_time: Option<i64>,is_token_based_retry: bool,) -> bool {- let utc_current_time = time::OffsetDateTime::now_utc();- let primitive_utc_current_time =- time::PrimitiveDateTime::new(utc_current_time.date(), utc_current_time.time());+ let primitive_utc_current_time = common_utils::date_time::now();let time_difference_from_creation = primitive_utc_current_time - created_at;// Token based retries (S2S) use the fulfillment window;@@ -7487,7 +7483,7 @@ fn check_expiration_date_is_valid(let expiration_time =time::OffsetDateTime::from_unix_timestamp_nanos(expiration_ms * 1_000_000).change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;- let now = time::OffsetDateTime::now_utc();+ let now = common_utils::date_time::now().assume_utc();Ok(expiration_time > now)}diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex c8fe147208..2aeaed824b 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -2443,11 +2443,13 @@ pub fn perform_dynamic_routing_volume_split(rng_seed: Option<&str>,) -> RoutingResult<api_models::routing::RoutingVolumeSplit> {let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();- let weighted_index = distributions::WeightedIndex::new(weights)- .change_context(errors::RoutingError::VolumeSplitFailed)- .attach_printable("Error creating weighted distribution for volume split")?;let idx = if let Some(seed) = rng_seed {+ // Already reproducible: the index is a pure function of the seed.+ let weighted_index = distributions::WeightedIndex::new(&weights)+ .change_context(errors::RoutingError::VolumeSplitFailed)+ .attach_printable("Error creating weighted distribution for volume split")?;+let mut hasher = hash_map::DefaultHasher::new();seed.hash(&mut hasher);let hash = hasher.finish();@@ -2455,8 +2457,7 @@ pub fn perform_dynamic_routing_volume_split(let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash);weighted_index.sample(&mut rng)} else {- let mut rng = rand::thread_rng();- weighted_index.sample(&mut rng)+ sample_volume_split_index(&weights)?};let routing_choice = *splits@@ -2467,16 +2468,36 @@ pub fn perform_dynamic_routing_volume_split(Ok(routing_choice)}-pub fn perform_volume_split(- mut splits: Vec<routing_types::ConnectorVolumeSplit>,-) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {- let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();+/// Draw the volume-split index for `weights`.+///+/// deja: this draw decides which connector a payment is routed to, so it changes+/// the outbound request. It is seamed at the index rather than at the chosen+/// connector because a `usize` records losslessly and the weights key the call —+/// a candidate that changed the split therefore still diverges on the args.+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::routing",+ operation = "volume_split_index",+ codec = ResultOkCodec,+ )+)]+fn sample_volume_split_index(weights: &[u8]) -> RoutingResult<usize> {let weighted_index = distributions::WeightedIndex::new(weights).change_context(errors::RoutingError::VolumeSplitFailed).attach_printable("Error creating weighted distribution for volume split")?;+ #[allow(clippy::disallowed_methods, reason = "this function IS the seam")]let mut rng = rand::thread_rng();- let idx = weighted_index.sample(&mut rng);+ Ok(weighted_index.sample(&mut rng))+}++pub fn perform_volume_split(+ mut splits: Vec<routing_types::ConnectorVolumeSplit>,+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {+ let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();+ let idx = sample_volume_split_index(&weights)?;splits.get(idx)diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rsindex 852cf01954..0618696934 100644--- a/crates/router/src/core/payments/types.rs+++ b/crates/router/src/core/payments/types.rs@@ -461,10 +461,7 @@ impl ForeignTryFrom<&api_models::payments::ExternalThreeDsData> for Authenticatithreeds_server_transaction_id: Some(external_auth_data.ds_trans_id.clone()),message_version: Some(external_auth_data.version.clone()),ds_trans_id: Some(external_auth_data.ds_trans_id.clone()),- created_at: time::PrimitiveDateTime::new(- time::OffsetDateTime::now_utc().date(),- time::OffsetDateTime::now_utc().time(),- ),+ created_at: common_utils::date_time::now(),challenge_code: None,challenge_cancel: None,challenge_code_reason: None,diff --git a/crates/router/src/core/relay.rs b/crates/router/src/core/relay.rsindex 58135de35d..6a1aa5c566 100644--- a/crates/router/src/core/relay.rs+++ b/crates/router/src/core/relay.rs@@ -1217,7 +1217,7 @@ pub async fn relay_unreferenced_refund(let connector_resource_id = request.connector_resource_id.clone()- .unwrap_or_else(|| format!("internal_{}", uuid::Uuid::now_v7()));+ .unwrap_or_else(|| format!("internal_{}", common_utils::generate_uuid_v7()));let (updated_relay, connector_name, raw_connector_response) =process_relay_unreferenced_refund(diff --git a/crates/router/src/core/revenue_recovery/retry_stats/record.rs b/crates/router/src/core/revenue_recovery/retry_stats/record.rsindex 4f6d7059eb..f04c2e13d7 100644--- a/crates/router/src/core/revenue_recovery/retry_stats/record.rs+++ b/crates/router/src/core/revenue_recovery/retry_stats/record.rs@@ -231,7 +231,7 @@ async fn with_retry_stats_lock<T>(redis_lock_expiry_seconds: u32,work: impl core::future::Future<Output = CustomResult<T, StorageError>>,) -> CustomResult<Option<T>, StorageError> {- let lock_token = uuid::Uuid::new_v4().to_string();+ let lock_token = common_utils::generate_uuid_v4().to_string();let wait_duration =std::time::Duration::from_millis(u64::from(delay_between_retries_in_milliseconds));let mut acquired = false;diff --git a/crates/router/src/core/tokenization.rs b/crates/router/src/core/tokenization.rsindex cf2a569162..ef7f683467 100644--- a/crates/router/src/core/tokenization.rs+++ b/crates/router/src/core/tokenization.rs@@ -37,7 +37,7 @@ pub async fn create_vault_token_core(req: api_models::tokenization::GenericTokenizationRequest,) -> RouterResponse<api_models::tokenization::GenericTokenizationResponse> {// Generate a unique vault ID- let vault_id = domain::VaultId::generate(uuid::Uuid::now_v7().to_string());+ let vault_id = domain::VaultId::generate(common_utils::generate_uuid_v7().to_string());let db = state.store.as_ref();let customer_id = req.customer_id.clone();// Create vault requestdiff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 9f04db1025..81639eccad 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -47,7 +47,7 @@ pub use hyperswitch_interfaces::{};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use router_env::tracing;-use time::{Duration, OffsetDateTime};+use time::Duration;use unified_connector_service_cards::{CardNumber, NetworkToken};use unified_connector_service_client::payments::{self as payments_grpc, client_authentication_token_data,@@ -239,7 +239,9 @@ fn build_ucs_l2_l3_data(l2_l3_data: Option<&L2L3Data>) -> Option<payments_grpc::pub fn build_upi_wait_screen_data() -> Result<serde_json::Value, error_stack::Report<UnifiedConnectorServiceError>> {- let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();+ let current_time = common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos();let wait_screen_data = api_models::payments::WaitScreenInstructions {display_from_timestamp: current_time,diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex 1377a54449..d067d20089 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -2755,7 +2755,7 @@ pub async fn create_user_authentication_method(.change_context(UserErrors::InternalServerError).attach_printable("Failed to decode DEK")?;- let id = uuid::Uuid::new_v4().to_string();+ let id = common_utils::generate_uuid_v4().to_string();let (private_config, public_config) = utils::user::construct_public_and_private_db_configs(&state,@@ -2792,7 +2792,12 @@ pub async fn create_user_authentication_method(.ok_or(UserErrors::InvalidAuthMethodOperationWithMessage("Email domain not found".to_string(),))?;- (uuid::Uuid::new_v4().to_string(), email_domain)+ // deja: the second generate_uuid_v4 in this function, and it must stay+ // second. The function has no #[instrument], so the two calls are told+ // apart by occurrence within an inherited span path. Swap them and the+ // unconditional call's index starts depending on whether auth_methods+ // is empty — a fork-numbering collision. Keep it after.+ (common_utils::generate_uuid_v4().to_string(), email_domain)};for db_auth_method in auth_methods {@@ -3017,7 +3022,8 @@ pub async fn get_sso_auth_url(.change_context(UserErrors::InternalServerError).attach_printable("Unable to parse OpenIdConnectPublicConfig")?;- let oidc_state = Secret::new(nanoid::nanoid!());+ // nanoid's own default length, kept explicit now the call goes through the seam.+ let oidc_state = Secret::new(common_utils::generate_nanoid_with_default_alphabet(21));utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?;let redirect_url =diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rsindex 8ed455b26a..02c2bf8e56 100644--- a/crates/router/src/core/user/theme.rs+++ b/crates/router/src/core/user/theme.rs@@ -9,7 +9,6 @@ use error_stack::ResultExt;use hyperswitch_domain_models::api::ApplicationResponse;use hyperswitch_masking::ExposeInterface;use rdkafka::message::ToBytes;-use uuid::Uuid;use crate::{consts::user::REDIS_THEME_CONFIG_VERSION_TTL_IN_SECS as redis_theme_config_ttl,@@ -127,7 +126,7 @@ pub async fn create_theme(};let new_theme = ThemeNew::new(- Uuid::new_v4().to_string(),+ common_utils::generate_uuid_v4().to_string(),request.theme_name,request.lineage,email_config,@@ -265,7 +264,7 @@ pub async fn create_user_theme().await?;let new_theme = ThemeNew::new(- Uuid::new_v4().to_string(),+ common_utils::generate_uuid_v4().to_string(),request.theme_name,lineage,email_config,diff --git a/crates/router/src/core/webhooks/gateway.rs b/crates/router/src/core/webhooks/gateway.rsindex aa36e187b4..3735b76324 100644--- a/crates/router/src/core/webhooks/gateway.rs+++ b/crates/router/src/core/webhooks/gateway.rs@@ -12,7 +12,6 @@ use hyperswitch_interfaces::webhooks::{};use hyperswitch_masking::{ErasedMaskSerialize, Secret};use router_env::{logger, tracing::Instrument};-use time::OffsetDateTime;use unified_connector_service_client::payments as payments_grpc;#[cfg(feature = "v1")]@@ -900,7 +899,7 @@ fn build_merchant_event_id(ctx: &WebhookGatewayContext) -> String {.get_id().get_string_repr(),ctx.connector_name,- OffsetDateTime::now_utc().unix_timestamp()+ common_utils::date_time::now_unix_timestamp())}diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rsindex 2aec9d27c2..2c1d2393e7 100644--- a/crates/router/src/core/webhooks/utils.rs+++ b/crates/router/src/core/webhooks/utils.rs@@ -471,7 +471,7 @@ pub(super) async fn perform_redis_lock<A>(whereA: SessionStateInfo,{- let lock_value: String = uuid::Uuid::new_v4().to_string();+ let lock_value: String = common_utils::generate_uuid_v4().to_string();let redis_conn = state.store().get_redis_conn()diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rsindex 5a6d28dd3c..d0aaace9a2 100644--- a/crates/router/src/db/user_authentication_method.rs+++ b/crates/router/src/db/user_authentication_method.rs@@ -137,9 +137,10 @@ impl UserAuthenticationMethodInterface for MockDb {.find(|uam| uam.owner_id == user_authentication_method.owner_id).map(|uam| uam.auth_id.clone());- let auth_id = existing_auth_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+ let auth_id =+ existing_auth_id.unwrap_or_else(|| common_utils::generate_uuid_v4().to_string());let user_authentication_method = storage::UserAuthenticationMethod {- id: uuid::Uuid::new_v4().to_string(),+ id: common_utils::generate_uuid_v4().to_string(),auth_id,owner_id: user_authentication_method.auth_id,owner_type: user_authentication_method.owner_type,diff --git a/crates/router/src/deja_boot.rs b/crates/router/src/deja_boot.rsindex ae0adbbe99..9d2aa71f92 100644--- a/crates/router/src/deja_boot.rs+++ b/crates/router/src/deja_boot.rs@@ -30,6 +30,10 @@ fn non_empty(value: Option<&str>) -> Option<&str> {/// Without a known revision it falls back to the bare-timestamp form (with a/// warning) rather than claiming a provenance it does not have.fn fallback_run_id(settings: &DejaSettings) -> String {+ #[allow(+ clippy::disallowed_methods,+ reason = "names the recording itself, once at boot before any request; seaming it would be circular"+ )]let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or(std::time::Duration::ZERO);@@ -130,11 +134,20 @@ fn env_value_named(name: &str) -> Option<String> {}fn fallback_instance_id() -> String {+ #[allow(+ clippy::disallowed_methods,+ reason = "distinguishes one running instance from another, once at boot before any request; seaming it would be circular"+ )]let now_ns = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or(std::time::Duration::ZERO).as_nanos();- format!("pi-{}-{now_ns}", std::process::id())+ #[allow(+ clippy::disallowed_methods,+ reason = "distinguishes one running instance from another, once at boot before any request; seaming it would be circular"+ )]+ let pid = std::process::id();+ format!("pi-{pid}-{now_ns}")}fn resolved_instance_id(settings: &DejaSettings) -> String {diff --git a/crates/router/src/events/account_updater.rs b/crates/router/src/events/account_updater.rsindex 7e80fccd1f..2bce9ea148 100644--- a/crates/router/src/events/account_updater.rs+++ b/crates/router/src/events/account_updater.rs@@ -47,7 +47,9 @@ impl<'a> KafkaAccountUpdaterEvent<'a> {updater_outcome,error_category,latency_ms,- created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),+ created_at: common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos(),}}}diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rsindex c49a013924..f18685e46c 100644--- a/crates/router/src/events/api_logs.rs+++ b/crates/router/src/events/api_logs.rs@@ -3,7 +3,6 @@ pub use common_utils::events::{ApiEventMetric, ApiEventsType};use common_utils::impl_api_event_type;use router_env::{types::FlowMetric, RequestId};use serde::Serialize;-use time::OffsetDateTime;use super::EventType;#[cfg(feature = "dummy_connector")]@@ -73,7 +72,7 @@ impl ApiEvent {tenant_id,merchant_id,api_flow: api_flow.to_string(),- created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,+ created_at_timestamp: common_utils::date_time::now_unix_timestamp_millis(),request_id: request_id.to_string(),latency,status_code,diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rsindex 95250a53b5..4c1024c022 100644--- a/crates/router/src/events/outgoing_webhook_logs.rs+++ b/crates/router/src/events/outgoing_webhook_logs.rs@@ -2,7 +2,6 @@ use api_models::{enums::EventType as OutgoingWebhookEventType, webhooks::Outgoinuse common_enums::WebhookDeliveryAttempt;use serde::Serialize;use serde_json::Value;-use time::OffsetDateTime;use super::EventType;use crate::services::kafka::KafkaMessage;@@ -197,7 +196,7 @@ impl OutgoingWebhookEvent {content,is_error: error.is_some(),error,- created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,+ created_at_timestamp: common_utils::date_time::now_unix_timestamp_millis(),initial_attempt_id,status_code,delivery_attempt,diff --git a/crates/router/src/routes/dummy_connector/utils.rs b/crates/router/src/routes/dummy_connector/utils.rsindex f1c53280ca..905a3765a5 100644--- a/crates/router/src/routes/dummy_connector/utils.rs+++ b/crates/router/src/routes/dummy_connector/utils.rs@@ -4,7 +4,6 @@ use common_utils::ext_traits::AsyncExt;use error_stack::{report, ResultExt};use hyperswitch_masking::PeekInterface;use maud::html;-use rand::{distributions::Uniform, prelude::Distribution};use tokio::time as tokio;use super::{@@ -17,13 +16,14 @@ use crate::{};pub async fn tokio_mock_sleep(delay: u64, tolerance: u64) {- let mut rng = rand::thread_rng();- // TODO: change this to `Uniform::try_from`- // this would require changing the fn signature- // to return a Result- let effective_delay = Uniform::from((delay - tolerance)..(delay + tolerance));+ // Half-open `(delay - tolerance)..(delay + tolerance)` as it was, expressed+ // as the inclusive range the seam takes.+ let low = i64::try_from(delay.saturating_sub(tolerance)).unwrap_or(0);+ let high = i64::try_from(delay.saturating_add(tolerance)).unwrap_or(i64::MAX);+ let effective_delay = common_utils::generate_random_number_in_range(low, high.max(low + 1) - 1);+tokio::sleep(tokio::Duration::from_millis(- effective_delay.sample(&mut rng),+ u64::try_from(effective_delay).unwrap_or(delay),)).await}diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rsindex 8210e44efe..f80b56e4f9 100644--- a/crates/router/src/services/authentication/cookies.rs+++ b/crates/router/src/services/authentication/cookies.rs@@ -78,7 +78,9 @@ fn create_cookie<'c>(#[cfg(feature = "olap")]fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) {let max_age = Duration::seconds(seconds);- let expiry = OffsetDateTime::now_utc().saturating_add(max_age);+ let expiry = common_utils::date_time::now()+ .assume_utc()+ .saturating_add(max_age);(expiry, max_age)}diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rsindex 41f0eba3de..99ecb9a87f 100644--- a/crates/router/src/services/jwt.rs+++ b/crates/router/src/services/jwt.rs@@ -13,6 +13,10 @@ use crate::{configs::Settings, core::errors::UserErrors};feature = "deja",deja::id(component = "router::jwt", operation = "generate_exp", codec = ResultOkCodec,))]+#[allow(+ clippy::disallowed_methods,+ reason = "this function IS the seam: the deja::id attribute above records and replays the absolute expiry"+)]pub fn generate_exp(exp_duration: std::time::Duration,) -> CustomResult<std::time::Duration, UserErrors> {diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rsindex cfd7afc1e6..383680f6a6 100644--- a/crates/router/src/services/kafka.rs+++ b/crates/router/src/services/kafka.rs@@ -33,7 +33,7 @@ pub mod revenue_recovery;use diesel_models::refund::Refund;use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};use serde::Serialize;-use time::{OffsetDateTime, PrimitiveDateTime};+use time::PrimitiveDateTime;#[cfg(feature = "payouts")]use self::payout::KafkaPayout;@@ -394,12 +394,12 @@ impl KafkaProducer {.key(&event.key()).payload(&event.value()?).timestamp(event.creation_timestamp().unwrap_or_else(|| {- (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000)+ common_utils::date_time::now_unix_timestamp_millis().try_into().unwrap_or_else(|_| {// kafka producer accepts milliseconds// try converting nanos to millis if that fails convert seconds to millis- OffsetDateTime::now_utc().unix_timestamp() * 1_000+ common_utils::date_time::now_unix_timestamp() * 1_000})})),)diff --git a/crates/router/src/services/oidc_provider.rs b/crates/router/src/services/oidc_provider.rsindex 6b14832a38..0b66b24482 100644--- a/crates/router/src/services/oidc_provider.rs+++ b/crates/router/src/services/oidc_provider.rs@@ -1,4 +1,4 @@-use std::time::{Duration, SystemTime, UNIX_EPOCH};+use std::time::Duration;use api_models::oidc::{Jwk, JwksResponse, KeyType, KeyUse, OidcAuthorizeQuery, OidcDiscoveryResponse,@@ -192,10 +192,8 @@ async fn generate_id_token(state: &SessionState,auth_code_data: &AuthCodeData,) -> OidcResult<String> {- let now = SystemTime::now()- .duration_since(UNIX_EPOCH)- .change_context(OidcErrors::ServerError)?- .as_secs();+ let now = u64::try_from(common_utils::date_time::now_unix_timestamp())+ .change_context(OidcErrors::ServerError)?;let exp_duration = Duration::from_secs(ID_TOKEN_TTL_IN_SECS);let exp = jwt::generate_exp(exp_duration).change_context(OidcErrors::ServerError)?@@ -226,10 +224,8 @@ async fn generate_access_token(state: &SessionState,auth_code_data: &AuthCodeData,) -> OidcResult<String> {- let now = SystemTime::now()- .duration_since(UNIX_EPOCH)- .change_context(OidcErrors::ServerError)?- .as_secs();+ let now = u64::try_from(common_utils::date_time::now_unix_timestamp())+ .change_context(OidcErrors::ServerError)?;let exp_duration = Duration::from_secs(ACCESS_TOKEN_TTL_IN_SECS);let exp = jwt::generate_exp(exp_duration).change_context(OidcErrors::ServerError)?diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rsindex f32f2d60c8..2458dd9b0b 100644--- a/crates/router/src/types/domain/user.rs+++ b/crates/router/src/types/domain/user.rs@@ -26,7 +26,6 @@ use diesel_models::{use error_stack::{report, ResultExt};use hyperswitch_domain_models::api::ApplicationResponse;use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};-use rand::distributions::{Alphanumeric, DistString};use time::PrimitiveDateTime;use unicode_segmentation::UnicodeSegmentation;@@ -1001,7 +1000,7 @@ impl NewUser {deja::id(component = "router::user", operation = "generate_user_id", codec = SerdeCodec,))]fn generate_user_id() -> String {- uuid::Uuid::new_v4().to_string()+ common_utils::generate_uuid_v4().to_string()}impl TryFrom<NewUser> for storage_user::UserNew {@@ -1384,19 +1383,41 @@ pub struct RecoveryCodes(pub Vec<Secret<String>>);impl RecoveryCodes {pub fn generate_new() -> Self {- let mut rand = rand::thread_rng();- let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT)- .map(|_| {- let code_part_1 =- Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);- let code_part_2 =- Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);+ Self(+ Self::generate_new_inner()+ .into_iter()+ .map(Secret::new)+ .collect(),+ )+ }- Secret::new(format!("{code_part_1}-{code_part_2}"))+ // deja: the codes are drawn from the RNG, so a replay cannot reproduce the+ // stored row or the response unless the draw is recorded. Returns plain+ // `String`s on purpose: masking::Secret serializes lossily to "***", which+ // would record a useless masked value -- same reason as+ // `generate_password_hash_inner`. The caller re-wraps immediately.+ #[cfg_attr(feature = "deja", track_caller)]+ #[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::user",+ operation = "generate_recovery_codes",+ codec = SerdeCodec,+ )+ )]+ fn generate_new_inner() -> Vec<String> {+ (0..consts::user::RECOVERY_CODES_COUNT)+ .map(|_| {+ let code_part_1 = common_utils::generate_random_alphanumeric_string(+ consts::user::RECOVERY_CODE_LENGTH / 2,+ );+ let code_part_2 = common_utils::generate_random_alphanumeric_string(+ consts::user::RECOVERY_CODE_LENGTH / 2,+ );++ format!("{code_part_1}-{code_part_2}")})- .collect::<Vec<_>>();-- Self(recovery_codes)+ .collect()}pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> {@@ -1568,3 +1589,32 @@ where.change_context(UserErrors::InternalServerError)}}++#[cfg(test)]+mod recovery_codes_tests {+ use std::collections::HashSet;++ use super::RecoveryCodes;+ use crate::consts;++ // deja: `generate_new_inner` draws `RECOVERY_CODES_COUNT` codes from the+ // RNG. "eight strings of the right length and charset" is the property a+ // replay's shape assertions would naturally catch; pairwise distinctness+ // is not visible from either code's shape alone. If a replay ever served+ // the same recorded draw to two of the eight slots -- the same shape a+ // fork-numbering collision takes -- two of a user's recovery codes would+ // authenticate identically, and a test asserting only format or length+ // would not notice.+ #[test]+ fn recovery_codes_are_pairwise_distinct() {+ let codes = RecoveryCodes::generate_new_inner();+ assert_eq!(codes.len(), consts::user::RECOVERY_CODES_COUNT);++ let unique: HashSet<&String> = codes.iter().collect();+ assert_eq!(+ unique.len(),+ codes.len(),+ "two of the generated recovery codes are identical: {codes:?}"+ );+ }+}diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rsindex ef16ac34b6..46a923ba12 100644--- a/crates/router/src/types/storage/payment_attempt.rs+++ b/crates/router/src/types/storage/payment_attempt.rs@@ -126,7 +126,6 @@ impl AttemptStatusExt for enums::AttemptStatus {mod tests {use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;use tokio::sync::oneshot;- use uuid::Uuid;use crate::{configs::settings::Settings,@@ -286,7 +285,7 @@ mod tests {let current_time = common_utils::date_time::now();let payment_id =common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();- let attempt_id = Uuid::new_v4().to_string();+ let attempt_id = common_utils::generate_uuid_v4().to_string();let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp();let connector = types::Connector::DummyConnector1.to_string();@@ -421,7 +420,7 @@ mod tests {/// Kind of test: state-based testingasync fn test_payment_attempt_mandate_field() {let state = create_single_connection_test_transaction_pool().await;- let uuid = Uuid::new_v4().to_string();+ let uuid = common_utils::generate_uuid_v4().to_string();let merchant_id =common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1")).unwrap();diff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rsindex 974becc0b5..d41c4a1337 100644--- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs+++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs@@ -338,7 +338,7 @@ impl RedisTokenManager {pub fn find_nearest_date_from_current(retry_history: &HashMap<PrimitiveDateTime, i32>,) -> Option<(PrimitiveDateTime, i32)> {- let now_utc = OffsetDateTime::now_utc();+ let now_utc = date_time::now().assume_utc();let reference_time = PrimitiveDateTime::new(now_utc.date(),Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),@@ -428,7 +428,7 @@ impl RedisTokenManager {state: &SessionState,payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {- let today = OffsetDateTime::now_utc().date();+ let today = date_time::now().date();let card_config = &state.conf.revenue_recovery.card_config;let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =@@ -511,7 +511,7 @@ impl RedisTokenManager {let card_config = &state.conf.revenue_recovery.card_config;let card_network_config = card_config.get_network_config(network_type);- let now_utc = OffsetDateTime::now_utc();+ let now_utc = date_time::now().assume_utc();let reference_time = PrimitiveDateTime::new(now_utc.date(),Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),@@ -599,7 +599,7 @@ impl RedisTokenManager {let last_external_attempt_at = token_data.modified_at;- let now_utc = OffsetDateTime::now_utc();+ let now_utc = date_time::now().assume_utc();let reference_time = PrimitiveDateTime::new(now_utc.date(),Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),@@ -672,7 +672,7 @@ impl RedisTokenManager {is_hard_decline: &Option<bool>,payment_processor_token_id: Option<&str>,) -> CustomResult<bool, errors::StorageError> {- let now_utc = OffsetDateTime::now_utc();+ let now_utc = date_time::now().assume_utc();let reference_time = PrimitiveDateTime::new(now_utc.date(),Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),@@ -697,10 +697,7 @@ impl RedisTokenManager {daily_retry_history: status.daily_retry_history.clone(),scheduled_at: None,is_hard_decline: *is_hard_decline,- modified_at: Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- )),+ modified_at: Some(date_time::now()),is_active: status.is_active,account_update_history: status.account_update_history.clone(),decision_threshold: status.decision_threshold,@@ -778,10 +775,7 @@ impl RedisTokenManager {daily_retry_history: status.daily_retry_history.clone(),scheduled_at: None,is_hard_decline: status.is_hard_decline,- modified_at: Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- )),+ modified_at: Some(date_time::now()),is_active: status.is_active,account_update_history: status.account_update_history.clone(),decision_threshold: status.decision_threshold,@@ -830,10 +824,7 @@ impl RedisTokenManager {daily_retry_history: status.daily_retry_history.clone(),scheduled_at: schedule_time,is_hard_decline: status.is_hard_decline,- modified_at: Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- )),+ modified_at: Some(date_time::now()),is_active: status.is_active,account_update_history: status.account_update_history.clone(),decision_threshold: decision_threshold.or(status.decision_threshold),@@ -1178,10 +1169,7 @@ impl RedisTokenManager {.unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value});- existing_token.modified_at = Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- ));+ existing_token.modified_at = Some(date_time::now());// Update account_update_history if providedif let Some(history) = &card_data.account_update_history {@@ -1345,10 +1333,7 @@ impl AccountUpdaterAction {let mut updated_token = scheduled_token.clone();updated_token.is_active = Some(false);- updated_token.modified_at = Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- ));+ updated_token.modified_at = Some(date_time::now());RedisTokenManager::upsert_payment_processor_token(state,@@ -1375,10 +1360,7 @@ impl AccountUpdaterAction {daily_retry_history: HashMap::new(),scheduled_at: None,is_hard_decline: Some(false),- modified_at: Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- )),+ modified_at: Some(date_time::now()),is_active: Some(true),account_update_history: Some(vec![AccountUpdateHistoryRecord {old_token: scheduled_token@@ -1386,10 +1368,7 @@ impl AccountUpdaterAction {.payment_processor_token.clone(),new_token: new_token.to_owned(),- updated_at: PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- ),+ updated_at: date_time::now(),old_token_info: Some(api_models::payments::AdditionalCardInfo::from(&scheduled_token.payment_processor_token_details,)),@@ -1417,10 +1396,7 @@ impl AccountUpdaterAction {updated_mandate_details.card_network.clone();updated_token.payment_processor_token_details.card_isin =updated_mandate_details.card_isin.clone();- updated_token.modified_at = Some(PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- ));+ updated_token.modified_at = Some(date_time::now());updated_token.account_update_history.get_or_insert_with(Vec::new)@@ -1433,10 +1409,7 @@ impl AccountUpdaterAction {.payment_processor_token_details.payment_processor_token.clone(),- updated_at: PrimitiveDateTime::new(- OffsetDateTime::now_utc().date(),- OffsetDateTime::now_utc().time(),- ),+ updated_at: date_time::now(),old_token_info: Some(api_models::payments::AdditionalCardInfo::from(&scheduled_token.payment_processor_token_details,)),diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 796969425d..36f5e0ec65 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -124,6 +124,7 @@ pub mod error_parser {feature = "deja",deja::id(component = "router::utils", operation = "generate_id", codec = SerdeCodec,))]+#[allow(clippy::disallowed_macros, reason = "this function IS the seam")]pub fn generate_id(length: usize, prefix: &str) -> String {format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS))}diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rsindex 9912b395c5..289a638c8c 100644--- a/crates/router/src/utils/user/password.rs+++ b/crates/router/src/utils/user/password.rs@@ -75,18 +75,40 @@ pub fn get_index_for_correct_recovery_code(}pub fn get_temp_password() -> Secret<String> {- let uuid_pass = uuid::Uuid::new_v4().to_string();+ Secret::new(get_temp_password_inner())+}++// deja: the temporary password is emailed to the user, so it reaches an outbound+// request and must be reproducible on replay. Returns a plain `String` because+// masking::Secret serializes lossily to "***" -- see+// `generate_password_hash_inner`. The caller re-wraps immediately.+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::user::password",+ operation = "get_temp_password",+ codec = SerdeCodec,+ )+)]+fn get_temp_password_inner() -> String {+ let uuid_pass = common_utils::generate_uuid_v4().to_string();++ #[allow(+ clippy::disallowed_methods,+ reason = "this function IS the seam: the whole password is recorded as one value"+ )]let mut rng = rand::thread_rng();let special_chars: Vec<char> = "!@#$%^&*()-_=+[]{}|;:,.<>?".chars().collect();let special_char = special_chars.choose(&mut rng).unwrap_or(&'@');- Secret::new(format!(+ format!("{}{}{}{}{}",uuid_pass,rng.gen_range('A'..='Z'),special_char,rng.gen_range('a'..='z'),rng.gen_range('0'..='9'),- ))+ )}diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rsindex 4dfd8c0fa1..480e17e3e7 100644--- a/crates/router/src/utils/user/sample_data.rs+++ b/crates/router/src/utils/user/sample_data.rs@@ -11,7 +11,6 @@ use diesel_models::user::sample_data::PaymentAttemptBatchNew;use diesel_models::{enums as storage_enums, DisputeNew, RefundNew};use error_stack::ResultExt;use hyperswitch_domain_models::payments::PaymentIntent;-use rand::{prelude::SliceRandom, thread_rng, Rng};use time::OffsetDateTime;use crate::{@@ -136,11 +135,12 @@ pub async fn generate_sample_data(let mut disputes_count = 0;- let mut random_array: Vec<usize> = (1..=sample_data_size).collect();-- // Shuffle the array- let mut rng = thread_rng();- random_array.shuffle(&mut rng);+ // A shuffle of `1..=n` is a permutation of `0..n` with one added, so it goes+ // through the permutation seam rather than shuffling in place.+ let random_array: Vec<usize> = common_utils::generate_random_permutation(sample_data_size)+ .into_iter()+ .map(|index| index + 1)+ .collect();let mut res: Vec<(PaymentIntent,@@ -199,16 +199,16 @@ pub async fn generate_sample_data(let payment_id = id_type::PaymentId::generate_test_payment_id_for_sample_data();let attempt_id = payment_id.get_attempt_id(1);let client_secret = payment_id.generate_client_secret();- let amount = thread_rng().gen_range(min_amount..=max_amount);-- let created_at @ modified_at @ last_synced =- OffsetDateTime::from_unix_timestamp(thread_rng().gen_range(start_time..=end_time))- .map(common_utils::date_time::convert_to_pdt)- .unwrap_or(- req.start_time.unwrap_or_else(|| {- common_utils::date_time::now() - time::Duration::days(7)- }),- );+ let amount = common_utils::generate_random_number_in_range(min_amount, max_amount);++ let created_at @ modified_at @ last_synced = OffsetDateTime::from_unix_timestamp(+ common_utils::generate_random_number_in_range(start_time, end_time),+ )+ .map(common_utils::date_time::convert_to_pdt)+ .unwrap_or(+ req.start_time+ .unwrap_or_else(|| common_utils::date_time::now() - time::Duration::days(7)),+ );let session_expiry =created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));@@ -326,7 +326,9 @@ pub async fn generate_sample_data(.to_string(),),payment_method: Some(common_enums::PaymentMethod::Card),- payment_method_type: Some(get_payment_method_type(thread_rng().gen_range(1..=2))),+ payment_method_type: Some(get_payment_method_type(+ u8::try_from(common_utils::generate_random_number_in_range(1, 2)).unwrap_or(1),+ )),authentication_type: Some(*auth_type.get((num - 1) % auth_type_len)diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex 1b4d8e202d..26ee9ceb02 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -37,8 +37,6 @@ use hyperswitch_domain_models::{};#[cfg(feature = "v2")]use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};-#[cfg(feature = "v2")]-use rand::Rng;use router_env::{logger,tracing::{self, instrument},@@ -478,7 +476,7 @@ async fn should_force_schedule_due_to_missed_slots(.max_retry_count_for_thirty_day;// Calculate time difference since last retry and compare with threshold- (time::OffsetDateTime::now_utc() - most_recent_date.assume_utc()).whole_hours()+ (common_utils::date_time::now().assume_utc() - most_recent_date.assume_utc()).whole_hours()> threshold_hours.into()})// Default to false if no valid retry history found (either none exists or all have retry_count = 0)@@ -597,7 +595,7 @@ struct TokenProcessResult {#[cfg(feature = "v2")]pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 {- let now_utc = time::OffsetDateTime::now_utc();+ let now_utc = common_utils::date_time::now().assume_utc();let scheduled_offset_dt = scheduled_time.assume_utc();let difference = scheduled_offset_dt - now_utc;@@ -1008,7 +1006,8 @@ async fn get_token_availability_for_schedule_time(if payment_token.token_status.is_hard_decline.unwrap_or(false) {PaymentProcessorTokenResponse::HardDecline} else if payment_token.retry_wait_time_hours > 0 {- let utc_schedule_time: time::OffsetDateTime = time::OffsetDateTime::now_utc()+ let utc_schedule_time: time::OffsetDateTime = common_utils::date_time::now()+ .assume_utc()+ time::Duration::hours(payment_token.retry_wait_time_hours);let next_available_time = time::PrimitiveDateTime::new(utc_schedule_time.date(),@@ -1139,7 +1138,7 @@ pub async fn calculate_smart_retry_time(token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,) -> Result<(Option<RetryDecision>, bool), errors::ProcessTrackerError> {let wait_hours = token_with_retry_info.retry_wait_time_hours;- let current_time = time::OffsetDateTime::now_utc();+ let current_time = common_utils::date_time::now().assume_utc();let future_time = current_time + time::Duration::hours(wait_hours);// Timestamp after which retry can be done without penalty@@ -1174,7 +1173,7 @@ pub async fn calculate_smart_retry_time(.recovery_timestamp.unretried_invoice_schedule_time_offset_seconds;let scheduled_time =- time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);+ common_utils::date_time::now().assume_utc() + time::Duration::seconds(schedule_offset);logger::info!("Skipping Decider call, forcing a schedule for the token:- '{:?}' to time:- {}",masked_token,@@ -1264,7 +1263,8 @@ pub async fn call_decider_for_payment_processor_tokens_select_closest_time(.token_status.payment_processor_token_details;- let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);+ let utc_schedule_time =+ common_utils::date_time::now().assume_utc() + time::Duration::minutes(1);let schedule_time =time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());@@ -1433,13 +1433,12 @@ pub fn add_random_delay_to_schedule_time(state: &SessionState,schedule_time: time::PrimitiveDateTime,) -> time::PrimitiveDateTime {- let mut rng = rand::thread_rng();let delay_limit = state.conf.revenue_recovery.recovery_timestamp.max_random_schedule_delay_in_seconds;- let random_secs = rng.gen_range(1..=delay_limit);+ let random_secs = common_utils::generate_random_number_in_range(1, delay_limit);logger::info!("Adding random delay of {random_secs} seconds to schedule time");schedule_time + time::Duration::seconds(random_secs)}@@ -1661,7 +1660,7 @@ fn pick_index<T: Copy + std::fmt::Debug>((f64::from(budget) * w / s).min(1.0)};// Draw the (unseeded) random value into a variable so the per-step decision is fully logged.- let draw = rand::random::<f64>();+ let draw = common_utils::generate_random_f64_unit();let fired = draw < p;logger::debug!(context = context,@@ -1821,7 +1820,7 @@ pub fn compute_mathmodel_retry_time();return None;}- let now = time::OffsetDateTime::now_utc();+ let now = common_utils::date_time::now().assume_utc();let dow_scores = slot_scores(&stats.dow);let dom_scores = slot_scores(&stats.dom);@@ -2074,7 +2073,7 @@ mod mathmodel_retry_time_tests {let grace: u32 = 14;for stats in [sample(), StatsDocument::default()] {for _ in 0..200 {- let before = time::OffsetDateTime::now_utc();+ let before = common_utils::date_time::now().assume_utc();let dt = compute_mathmodel_retry_time(&stats, 3, grace, DEFAULT_RETRY_HOUR).expect("grace > 1 => Some");let last = (before + time::Duration::days(i64::from(grace) + 1)).date();@@ -2092,7 +2091,7 @@ mod mathmodel_retry_time_tests {fn window_starts_next_day() {// Failure day is excluded: the earliest candidate is tomorrow. grace COUNTS today, so grace 2// = today + 1 future day (tomorrow) — assert the pick is that next day, not the failure day.- let before = time::OffsetDateTime::now_utc();+ let before = common_utils::date_time::now().assume_utc();let dt = compute_mathmodel_retry_time(&sample(), 3, 2, DEFAULT_RETRY_HOUR).expect("grace 2 => Some");assert!(@@ -2158,7 +2157,7 @@ mod mathmodel_retry_time_tests {// Every slot corrupt (k > n) on all three axes -> all dropped -> uniform -> still a valid// in-window datetime, never a panic or a skipped retry.let corrupt = doc_with(&[(0, 1, 100), (3, 2, 50)], &[(5, 1, 80)], &[(9, 1, 30)]);- let before = time::OffsetDateTime::now_utc();+ let before = common_utils::date_time::now().assume_utc();for _ in 0..50 {let dt = compute_mathmodel_retry_time(&corrupt, 3, 14, DEFAULT_RETRY_HOUR).expect("grace > 1 => Some");@@ -2176,7 +2175,7 @@ mod mathmodel_retry_time_tests {#[test]fn grace_is_capped_at_max() {- let before = time::OffsetDateTime::now_utc();+ let before = common_utils::date_time::now().assume_utc();let dt = compute_mathmodel_retry_time(&sample(), 3, 365, DEFAULT_RETRY_HOUR).expect("grace > 1 => Some");let last = (before + time::Duration::days(i64::from(MAX_GRACE_DAYS) + 1)).date();diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rsindex d603220e9c..e83f041001 100644--- a/crates/router/tests/connectors/utils.rs+++ b/crates/router/tests/connectors/utils.rs@@ -394,7 +394,7 @@ pub trait ConnectorActions: Connector {payment_amount: 1000,minor_payment_amount: MinorUnit::new(1000),currency: enums::Currency::USD,- refund_id: uuid::Uuid::new_v4().to_string(),+ refund_id: common_utils::generate_uuid_v4().to_string(),connector_transaction_id: "".to_string(),webhook_url: None,refund_amount: 100,@@ -508,8 +508,8 @@ pub trait ConnectorActions: Connector {connector: self.get_name(),tenant_id: common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),- payment_id: uuid::Uuid::new_v4().to_string(),- attempt_id: uuid::Uuid::new_v4().to_string(),+ payment_id: common_utils::generate_uuid_v4().to_string(),+ attempt_id: common_utils::generate_uuid_v4().to_string(),status: enums::AttemptStatus::default(),auth_type: info.clone()@@ -545,7 +545,7 @@ pub trait ConnectorActions: Connector {recurring_mandate_payment_data: None,preprocessing_id: None,- connector_request_reference_id: uuid::Uuid::new_v4().to_string(),+ connector_request_reference_id: common_utils::generate_uuid_v4().to_string(),#[cfg(feature = "payouts")]payout_method_data: info.and_then(|p| p.payout_method_data),#[cfg(feature = "payouts")]@@ -1124,7 +1124,7 @@ impl Default for PaymentRefundType {payment_amount: 100,minor_payment_amount: MinorUnit::new(100),currency: enums::Currency::USD,- refund_id: uuid::Uuid::new_v4().to_string(),+ refund_id: common_utils::generate_uuid_v4().to_string(),connector_transaction_id: String::new(),refund_amount: 100,minor_refund_amount: MinorUnit::new(100),diff --git a/crates/router/tests/customers.rs b/crates/router/tests/customers.rsindex 3e1194c923..66dae4672c 100644--- a/crates/router/tests/customers.rs+++ b/crates/router/tests/customers.rs@@ -10,7 +10,7 @@ mod utils;async fn customer_success() {Box::pin(utils::setup()).await;- let customer_id = format!("customer_{}", uuid::Uuid::new_v4());+ let customer_id = format!("customer_{}", common_utils::generate_uuid_v4());let api_key = ("API-KEY", "MySecretApiKey");let name = "Doe";let new_name = "new Doe";@@ -79,7 +79,7 @@ async fn customer_success() {async fn customer_failure() {Box::pin(utils::setup()).await;- let customer_id = format!("customer_{}", uuid::Uuid::new_v4());+ let customer_id = format!("customer_{}", common_utils::generate_uuid_v4());let api_key = ("api-key", "MySecretApiKey");let mut request = serde_json::json!({diff --git a/crates/router/tests/deja_jwt_tape_excludes_token.rs b/crates/router/tests/deja_jwt_tape_excludes_token.rsindex a7ad2c5688..d8bc338d91 100644--- a/crates/router/tests/deja_jwt_tape_excludes_token.rs+++ b/crates/router/tests/deja_jwt_tape_excludes_token.rs@@ -30,6 +30,10 @@ struct Claims {sub: String,}+#[allow(+ clippy::expect_used,+ reason = "test helper: a free fn, so allow-expect-in-tests does not cover it; a failure to read the artifact dir should fail the test loudly"+)]fn artifact_bytes(dir: &std::path::Path) -> Vec<u8> {let mut out = Vec::new();let mut stack = vec![dir.to_path_buf()];diff --git a/crates/router/tests/feature_off_config_purity.rs b/crates/router/tests/feature_off_config_purity.rsindex 08bec3684e..7b89468545 100644--- a/crates/router/tests/feature_off_config_purity.rs+++ b/crates/router/tests/feature_off_config_purity.rs@@ -8,7 +8,6 @@ use std::{io::ErrorKind,path::{Path, PathBuf},sync::atomic::{AtomicU64, Ordering},- time::{SystemTime, UNIX_EPOCH},};use router::configs::settings::Settings;@@ -182,16 +181,15 @@ struct CleanupDir {impl CleanupDir {fn new() -> Self {- let unique_nanos = SystemTime::now()- .duration_since(UNIX_EPOCH)- .expect("system clock before unix epoch")- .as_nanos();+ let unique_nanos = common_utils::date_time::now()+ .assume_utc()+ .unix_timestamp_nanos();for _ in 0..100 {let unique = NEXT_TEMP_ID.fetch_add(1, Ordering::Relaxed);+ let pid = common_utils::process_id();let path = std::env::temp_dir().join(format!(- "feature_off_config_purity-{}-{unique_nanos}-{unique}",- std::process::id()+ "feature_off_config_purity-{pid}-{unique_nanos}-{unique}"));match fs::create_dir(&path) {Ok(()) => return Self { path },diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rsindex e342913bc1..56cc57e00c 100644--- a/crates/router/tests/payments.rs+++ b/crates/router/tests/payments.rs@@ -17,7 +17,6 @@ use router::{};use time::macros::datetime;use tokio::sync::oneshot;-use uuid::Uuid;// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid// do we'll test refund and payment in same tests and later implement thread_local variables.@@ -29,7 +28,7 @@ use uuid::Uuid;async fn payments_create_stripe() {Box::pin(utils::setup()).await;- let payment_id = format!("test_{}", Uuid::new_v4());+ let payment_id = format!("test_{}", common_utils::generate_uuid_v4());let api_key = ("API-KEY", "MySecretApiKey");let request = serde_json::json!({@@ -98,7 +97,7 @@ async fn payments_create_stripe() {async fn payments_create_adyen() {Box::pin(utils::setup()).await;- let payment_id = format!("test_{}", Uuid::new_v4());+ let payment_id = format!("test_{}", common_utils::generate_uuid_v4());let api_key = ("API-KEY", "321");let request = serde_json::json!({@@ -167,7 +166,7 @@ async fn payments_create_adyen() {async fn payments_create_fail() {Box::pin(utils::setup()).await;- let payment_id = format!("test_{}", Uuid::new_v4());+ let payment_id = format!("test_{}", common_utils::generate_uuid_v4());let api_key = ("API-KEY", "MySecretApiKey");let invalid_request = serde_json::json!({@@ -538,7 +537,7 @@ async fn payments_create_core() {// redis_conn: connection::redis_connection(&conf).await,// };-// let customer_id = format!("cust_{}", Uuid::new_v4());+// let customer_id = format!("cust_{}", common_utils::generate_uuid_v4());// let merchant_id = "jarnura".to_string();// let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();// let customer_data = api::CreateCustomerRequest {@@ -615,7 +614,7 @@ async fn payments_create_core_adyen_no_redirect() {let payment_id =id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();- let customer_id = format!("cust_{}", Uuid::new_v4());+ let customer_id = format!("cust_{}", common_utils::generate_uuid_v4());let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();let key_store = state.storediff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rsindex 437986d208..d741d69aa4 100644--- a/crates/router/tests/payments2.rs+++ b/crates/router/tests/payments2.rs@@ -13,7 +13,6 @@ use router::{};use time::macros::datetime;use tokio::sync::oneshot;-use uuid::Uuid;#[test]fn connector_list() {@@ -301,7 +300,7 @@ async fn payments_create_core() {// redis_conn: connection::redis_connection(&conf).await,// };//-// let customer_id = format!("cust_{}", Uuid::new_v4());+// let customer_id = format!("cust_{}", common_utils::generate_uuid_v4());// let merchant_id = "jarnura".to_string();// let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();// let customer_data = api::CreateCustomerRequest {@@ -380,7 +379,7 @@ async fn payments_create_core_adyen_no_redirect() {).unwrap();- let customer_id = format!("cust_{}", Uuid::new_v4());+ let customer_id = format!("cust_{}", common_utils::generate_uuid_v4());let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();let payment_id =id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rsindex b05d5ef50b..01f4f55e08 100644--- a/crates/router/tests/utils.rs+++ b/crates/router/tests/utils.rs@@ -192,7 +192,7 @@ impl<T> AppClient<T> {}fn mk_merchant_account(merchant_id: Option<String>) -> Value {- let merchant_id = merchant_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+ let merchant_id = merchant_id.unwrap_or_else(|| common_utils::generate_uuid_v4().to_string());json!({"merchant_id": merchant_id,diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.tomlindex 860b1a97ca..4cb4288476 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 = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }-deja-core = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", 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/logger/formatter.rs b/crates/router_env/src/logger/formatter.rsindex 8e64f744fb..605c762572 100644--- a/crates/router_env/src/logger/formatter.rs+++ b/crates/router_env/src/logger/formatter.rs@@ -165,7 +165,15 @@ wheredefault_fields: HashMap<String, Value>,formatter: F,) -> error_stack::Result<Self, ConfigError> {+ #[allow(+ clippy::disallowed_methods,+ reason = "router_env cannot use the common_utils seams: common_utils depends on router_env (common_utils/Cargo.toml:74), so the reverse edge would be a dependency cycle. Moving the seam primitives below router_env is the fix, and it is a different change"+ )]let pid = std::process::id();+ #[allow(+ clippy::disallowed_methods,+ reason = "router_env cannot use the common_utils seams -- common_utils depends on router_env, so the reverse edge would be a cycle -- and a log line wants the real syscall hostname, where common_utils::hostname reads HOSTNAME from the environment"+ )]let hostname = gethostname::gethostname().to_string_lossy().into_owned();let service = service.to_string();#[cfg(feature = "vergen")]@@ -227,7 +235,12 @@ wheremap_serializer.serialize_entry(FN, name)?;map_serializer.serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?;- if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) {+ #[allow(+ clippy::disallowed_methods,+ reason = "router_env cannot use the common_utils seams: common_utils depends on router_env (common_utils/Cargo.toml:74), so the reverse edge would be a dependency cycle. Moving the seam primitives below router_env is the fix, and it is a different change"+ )]+ let formatted_time = time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT);+ if let Ok(time) = &formatted_time {map_serializer.serialize_entry(TIME, time)?;}diff --git a/crates/router_env/src/request_id.rs b/crates/router_env/src/request_id.rsindex a486826709..1cf3309ab1 100644--- a/crates/router_env/src/request_id.rs+++ b/crates/router_env/src/request_id.rs@@ -407,6 +407,10 @@ pub(crate) mod boundary {self.caller,args,)+ // Self-describe the correlation root so replay tooling+ // reads a role rather than having to know this+ // boundary's name.+ .with_role(deja::ROLE_INGRESS).with_semantics(deja::BoundarySemantics {replay_strategy: deja::ReplayStrategy::Substitute,kind: None,@@ -564,6 +568,10 @@ fn generate_uuid_v7() -> String {}// RECORD (or replay miss): generate live and record the value.+ #[allow(+ clippy::disallowed_methods,+ reason = "this IS the seam: the record/replay boundary is written out by hand just above, because router_env cannot depend on common_utils -- common_utils depends on router_env, so the reverse edge would be a cycle"+ )]let generated_value = Uuid::now_v7().to_string();boundary::record_id_generation("generate_uuid_v7",@@ -577,11 +585,19 @@ fn generate_uuid_v7() -> String {}// Bootstrap / uncorrelated: generate live; identity folds into http_incoming.+ #[allow(+ clippy::disallowed_methods,+ reason = "uncorrelated bootstrap id: there is no correlation yet, so there is no recording to serve it from; it folds into http_incoming's identity. router_env cannot reach the common_utils seams anyway -- that edge would be a cycle"+ )]Uuid::now_v7().to_string()}#[cfg(not(feature = "deja"))]{+ #[allow(+ clippy::disallowed_methods,+ reason = "deja is off in this build, so there is no boundary to route through; and router_env cannot reach the common_utils seams either, that edge would be a cycle"+ )]Uuid::now_v7().to_string()}}diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rsindex 9da2102bf8..1df96dce95 100644--- a/crates/scheduler/src/consumer.rs+++ b/crates/scheduler/src/consumer.rs@@ -19,7 +19,6 @@ use router_env::{};use time::PrimitiveDateTime;use tokio::sync::mpsc;-use uuid::Uuid;use super::env::logger;pub use super::workflows::ProcessTrackerWorkflow;@@ -46,17 +45,10 @@ where{use std::time::Duration;- use rand::distributions::{Distribution, Uniform};+ let jitter_ceiling = i64::try_from(settings.loop_interval).unwrap_or(i64::MAX);+ let timeout = common_utils::generate_random_number_in_range(0, jitter_ceiling);- let mut rng = rand::thread_rng();-- // TODO: this can be removed once rand-0.9 is released- // reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942- #[allow(clippy::unnecessary_fallible_conversions)]- let timeout = Uniform::try_from(0..=settings.loop_interval)- .change_context(errors::ProcessTrackerError::ConfigurationError)?;-- tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await;+ tokio::time::sleep(Duration::from_millis(u64::try_from(timeout).unwrap_or(0))).await;let mut interval = tokio::time::interval(Duration::from_millis(settings.loop_interval));@@ -144,7 +136,7 @@ pub async fn consumer_operations<T: SchedulerSessionState + 'static>(enums::ApplicationSource::Cug => settings.cug_stream.clone(),};let group_name = settings.consumer.consumer_group.clone();- let consumer_name = format!("consumer_{}", Uuid::new_v4());+ let consumer_name = format!("consumer_{}", common_utils::generate_uuid_v4());let _group_created = &mut state.get_db()@@ -238,7 +230,7 @@ pub async fn start_workflow<T>(whereT: SchedulerSessionState,{- let workflow_id = Uuid::now_v7();+ let workflow_id = common_utils::generate_uuid_v7();tracing::Span::current().record("workflow_id", workflow_id.to_string());logger::info!(pt.name=?process.name, pt.id=%process.id);diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rsindex 9417c3c143..dc77f0830f 100644--- a/crates/scheduler/src/producer.rs+++ b/crates/scheduler/src/producer.rs@@ -33,17 +33,10 @@ where{use std::time::Duration;- use rand::distributions::{Distribution, Uniform};+ let jitter_ceiling = i64::try_from(scheduler_settings.loop_interval).unwrap_or(i64::MAX);+ let timeout = common_utils::generate_random_number_in_range(0, jitter_ceiling);- let mut rng = rand::thread_rng();-- // TODO: this can be removed once rand-0.9 is released- // reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942- #[allow(clippy::unnecessary_fallible_conversions)]- let timeout = Uniform::try_from(0..=scheduler_settings.loop_interval)- .change_context(errors::ProcessTrackerError::ConfigurationError)?;-- tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await;+ tokio::time::sleep(Duration::from_millis(u64::try_from(timeout).unwrap_or(0))).await;let mut interval =tokio::time::interval(Duration::from_millis(scheduler_settings.loop_interval));diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rsindex 46b35c31a9..a6244c48fa 100644--- a/crates/scheduler/src/utils.rs+++ b/crates/scheduler/src/utils.rs@@ -6,7 +6,6 @@ pub use diesel_models::process_tracker as storage;use error_stack::{report, ResultExt};use redis_interface::{RedisConnectionWithContext, RedisEntryId};use router_env::{instrument, tracing};-use uuid::Uuid;use super::{consumer::{self, types::process_data, workflows},@@ -167,7 +166,7 @@ pub fn divide_into_batches(conf: &SchedulerSettings,application_source: enums::ApplicationSource,) -> Vec<ProcessTrackerBatch> {- let batch_id = Uuid::new_v4().to_string();+ let batch_id = common_utils::generate_uuid_v4().to_string();let stream_name = match application_source {enums::ApplicationSource::Main => &conf.stream,diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.tomlindex 23fc2105f8..22d95cbea2 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 = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", 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/test_utils/Cargo.toml b/crates/test_utils/Cargo.tomlindex e4f388445d..3130b8a077 100644--- a/crates/test_utils/Cargo.toml+++ b/crates/test_utils/Cargo.toml@@ -32,6 +32,7 @@ toml = "0.8.22"# First party crateshyperswitch_masking = "0.0.1"common_enums = { version = "0.1.0", path = "../common_enums" }+common_utils = { version = "0.1.0", path = "../common_utils" }[lints]workspace = truediff --git a/crates/test_utils/tests/connectors/authorizedotnet_ui.rs b/crates/test_utils/tests/connectors/authorizedotnet_ui.rsindex e71e96a547..f1f61cd00d 100644--- a/crates/test_utils/tests/connectors/authorizedotnet_ui.rs+++ b/crates/test_utils/tests/connectors/authorizedotnet_ui.rs@@ -1,4 +1,3 @@-use rand::Rng;use serial_test::serial;use thirtyfour::{prelude::*, WebDriver};@@ -14,7 +13,7 @@ impl SeleniumTest for AuthorizedotnetSeleniumTest {async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {let conn = AuthorizedotnetSeleniumTest {};- let amount = rand::thread_rng().gen_range(1..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing+ let amount = common_utils::generate_random_number_in_range(1, 999); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testinglet pub_key = conn.get_configs().automation_configsdiff --git a/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs b/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rsindex 856ebc53c7..746babc0eb 100644--- a/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs+++ b/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs@@ -1,4 +1,3 @@-use rand::Rng;use thirtyfour::{prelude::*, WebDriver};use crate::{selenium::*, tester};@@ -13,7 +12,7 @@ impl SeleniumTest for AuthorizedotnetSeleniumTest {async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {let conn = AuthorizedotnetSeleniumTest {};- let amount = rand::thread_rng().gen_range(50..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing(+ let amount = common_utils::generate_random_number_in_range(50, 999); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing(conn.make_webhook_test(web_driver,&format!("{CHECKOUT_BASE_URL}/saved/227?amount={amount}"),