repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/backoff_retry.rs | pingora-proxy/examples/backoff_retry.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::time::Duration;
use async_trait::async_trait;
use log::info;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_core::{prelude::Opt, Error};
use pingora_proxy::{ProxyHttp, Session};
/// This example shows how to setup retry-able errors with a backoff policy
#[derive(Default)]
struct RetryCtx {
pub retries: u32,
}
struct BackoffRetryProxy;
#[async_trait]
impl ProxyHttp for BackoffRetryProxy {
type CTX = RetryCtx;
fn new_ctx(&self) -> Self::CTX {
Self::CTX::default()
}
fn fail_to_connect(
&self,
_session: &mut Session,
_peer: &HttpPeer,
ctx: &mut Self::CTX,
e: Box<Error>,
) -> Box<Error> {
ctx.retries += 1;
let mut retry_e = e;
retry_e.set_retry(true);
retry_e
}
async fn upstream_peer(
&self,
_session: &mut Session,
ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
const MAX_SLEEP: Duration = Duration::from_secs(10);
if ctx.retries > 0 {
// simple example of exponential backoff with a max of 10s
let sleep_ms =
std::cmp::min(Duration::from_millis(u64::pow(10, ctx.retries)), MAX_SLEEP);
info!("sleeping for ms: {sleep_ms:?}");
tokio::time::sleep(sleep_ms).await;
}
let mut peer = HttpPeer::new(("10.0.0.1", 80), false, "".into());
peer.options.connection_timeout = Some(Duration::from_millis(100));
Ok(Box::new(peer))
}
}
// RUST_LOG=INFO cargo run --example backoff_retry -- --conf examples/conf.yaml
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy =
pingora_proxy::http_proxy_service(&my_server.configuration, BackoffRetryProxy);
my_proxy.add_tcp("0.0.0.0:6195");
my_server.add_service(my_proxy);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/grpc_web_module.rs | pingora-proxy/examples/grpc_web_module.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_core::{
modules::http::{
grpc_web::{GrpcWeb, GrpcWebBridge},
HttpModules,
},
prelude::Opt,
};
use pingora_proxy::{ProxyHttp, Session};
// This example shows how to use the gRPC-web bridge module
pub struct GrpcWebBridgeProxy;
#[async_trait]
impl ProxyHttp for GrpcWebBridgeProxy {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
fn init_downstream_modules(&self, modules: &mut HttpModules) {
// Add the gRPC web module
modules.add_module(Box::new(GrpcWeb))
}
async fn early_request_filter(
&self,
session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<()> {
let grpc = session
.downstream_modules_ctx
.get_mut::<GrpcWebBridge>()
.expect("GrpcWebBridge module added");
// initialize gRPC module for this request
grpc.init();
Ok(())
}
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
// this needs to be your gRPC server
let grpc_peer = Box::new(HttpPeer::new(
("1.1.1.1", 443),
true,
"one.one.one.one".to_string(),
));
Ok(grpc_peer)
}
}
// RUST_LOG=INFO cargo run --example grpc_web_module
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy =
pingora_proxy::http_proxy_service(&my_server.configuration, GrpcWebBridgeProxy);
my_proxy.add_tcp("0.0.0.0:6194");
my_server.add_service(my_proxy);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/connection_filter.rs | pingora-proxy/examples/connection_filter.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use clap::Parser;
use log::info;
use pingora_core::listeners::ConnectionFilter;
use pingora_core::prelude::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_proxy::{ProxyHttp, Session};
use std::sync::Arc;
/// This example demonstrates how to implement a connection filter
pub struct MyProxy;
#[async_trait]
impl ProxyHttp for MyProxy {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
// Forward to httpbin.org for testing
let peer = HttpPeer::new(("httpbin.org", 80), false, "httpbin.org".into());
Ok(Box::new(peer))
}
}
/// Connection filter that blocks ALL connections (for testing)
#[derive(Debug, Clone)]
struct BlockAllFilter;
#[async_trait]
impl ConnectionFilter for BlockAllFilter {
async fn should_accept(&self, addr: &std::net::SocketAddr) -> bool {
info!("BLOCKING connection from {} (BlockAllFilter active)", addr);
false
}
}
// RUST_LOG=INFO cargo run --example connection_filter
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy = pingora_proxy::http_proxy_service(&my_server.configuration, MyProxy);
// Create a filter that blocks ALL connections
let filter = Arc::new(BlockAllFilter);
info!("Setting BlockAllFilter on proxy service");
my_proxy.set_connection_filter(filter.clone());
info!("Adding TCP endpoints AFTER setting filter");
my_proxy.add_tcp("0.0.0.0:6195");
my_proxy.add_tcp("0.0.0.0:6196");
info!("====================================");
info!("Server starting with BlockAllFilter");
info!("This filter blocks ALL connections!");
info!("====================================");
info!("");
info!("Test with:");
info!(" curl http://localhost:6195/get");
info!(" curl http://localhost:6196/get");
info!("");
info!("ALL requests should be blocked!");
info!("You should see 'BLOCKING connection' in the logs");
info!("and curl should fail with 'Connection refused' or hang");
info!("");
my_server.add_service(my_proxy);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/rate_limiter.rs | pingora-proxy/examples/rate_limiter.rs | use async_trait::async_trait;
use once_cell::sync::Lazy;
use pingora_core::prelude::*;
use pingora_http::{RequestHeader, ResponseHeader};
use pingora_limits::rate::Rate;
use pingora_load_balancing::prelude::{RoundRobin, TcpHealthCheck};
use pingora_load_balancing::LoadBalancer;
use pingora_proxy::{http_proxy_service, ProxyHttp, Session};
use std::sync::Arc;
use std::time::Duration;
fn main() {
let mut server = Server::new(Some(Opt::default())).unwrap();
server.bootstrap();
let mut upstreams = LoadBalancer::try_from_iter(["1.1.1.1:443", "1.0.0.1:443"]).unwrap();
// Set health check
let hc = TcpHealthCheck::new();
upstreams.set_health_check(hc);
upstreams.health_check_frequency = Some(Duration::from_secs(1));
// Set background service
let background = background_service("health check", upstreams);
let upstreams = background.task();
// Set load balancer
let mut lb = http_proxy_service(&server.configuration, LB(upstreams));
lb.add_tcp("0.0.0.0:6188");
// let rate = Rate
server.add_service(background);
server.add_service(lb);
server.run_forever();
}
pub struct LB(Arc<LoadBalancer<RoundRobin>>);
impl LB {
pub fn get_request_appid(&self, session: &mut Session) -> Option<String> {
match session
.req_header()
.headers
.get("appid")
.map(|v| v.to_str())
{
None => None,
Some(v) => match v {
Ok(v) => Some(v.to_string()),
Err(_) => None,
},
}
}
}
// Rate limiter
static RATE_LIMITER: Lazy<Rate> = Lazy::new(|| Rate::new(Duration::from_secs(1)));
// max request per second per client
static MAX_REQ_PER_SEC: isize = 1;
#[async_trait]
impl ProxyHttp for LB {
type CTX = ();
fn new_ctx(&self) {}
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
let upstream = self.0.select(b"", 256).unwrap();
// Set SNI
let peer = Box::new(HttpPeer::new(upstream, true, "one.one.one.one".to_string()));
Ok(peer)
}
async fn upstream_request_filter(
&self,
_session: &mut Session,
upstream_request: &mut RequestHeader,
_ctx: &mut Self::CTX,
) -> Result<()>
where
Self::CTX: Send + Sync,
{
upstream_request
.insert_header("Host", "one.one.one.one")
.unwrap();
Ok(())
}
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool>
where
Self::CTX: Send + Sync,
{
let appid = match self.get_request_appid(session) {
None => return Ok(false), // no client appid found, skip rate limiting
Some(addr) => addr,
};
// retrieve the current window requests
let curr_window_requests = RATE_LIMITER.observe(&appid, 1);
if curr_window_requests > MAX_REQ_PER_SEC {
// rate limited, return 429
let mut header = ResponseHeader::build(429, None).unwrap();
header
.insert_header("X-Rate-Limit-Limit", MAX_REQ_PER_SEC.to_string())
.unwrap();
header.insert_header("X-Rate-Limit-Remaining", "0").unwrap();
header.insert_header("X-Rate-Limit-Reset", "1").unwrap();
session.set_keepalive(None);
session
.write_response_header(Box::new(header), true)
.await?;
return Ok(true);
}
Ok(false)
}
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/virtual_l4.rs | pingora-proxy/examples/virtual_l4.rs | //! This example demonstrates to how to implement a custom L4 connector
//! together with a virtual socket.
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use async_trait::async_trait;
use pingora_core::connectors::L4Connect;
use pingora_core::prelude::HttpPeer;
use pingora_core::protocols::l4::socket::SocketAddr as L4SocketAddr;
use pingora_core::protocols::l4::stream::Stream;
use pingora_core::protocols::l4::virt::{VirtualSocket, VirtualSocketStream};
use pingora_core::server::RunArgs;
use pingora_core::server::{configuration::ServerConf, Server};
use pingora_core::services::listening::Service;
use pingora_core::upstreams::peer::PeerOptions;
use pingora_error::Result;
use pingora_proxy::{http_proxy_service_with_name, prelude::*, HttpProxy, ProxyHttp};
use tokio::io::{AsyncRead, AsyncWrite};
/// Static virtual socket that serves a single HTTP request with a static response.
///
/// In real world use cases you would implement [`VirtualSocket`] for streams
/// that implement `AsyncRead + AsyncWrite`.
#[derive(Debug)]
struct StaticVirtualSocket {
content: Vec<u8>,
read_pos: usize,
}
impl StaticVirtualSocket {
fn new() -> Self {
let response = b"HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, world!";
Self {
content: response.to_vec(),
read_pos: 0,
}
}
}
impl AsyncRead for StaticVirtualSocket {
fn poll_read(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
debug_assert!(self.read_pos <= self.content.len());
let remaining = self.content.len() - self.read_pos;
if remaining == 0 {
return std::task::Poll::Ready(Ok(()));
}
let to_read = std::cmp::min(remaining, buf.remaining());
buf.put_slice(&self.content[self.read_pos..self.read_pos + to_read]);
self.read_pos += to_read;
std::task::Poll::Ready(Ok(()))
}
}
impl AsyncWrite for StaticVirtualSocket {
fn poll_write(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
// Discard all writes
std::task::Poll::Ready(Ok(buf.len()))
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
}
impl VirtualSocket for StaticVirtualSocket {
fn set_socket_option(
&self,
_opt: pingora_core::protocols::l4::virt::VirtualSockOpt,
) -> std::io::Result<()> {
Ok(())
}
}
#[derive(Debug)]
struct VirtualConnector;
#[async_trait]
impl L4Connect for VirtualConnector {
async fn connect(&self, _addr: &L4SocketAddr) -> pingora_error::Result<Stream> {
Ok(Stream::from(VirtualSocketStream::new(Box::new(
StaticVirtualSocket::new(),
))))
}
}
struct VirtualProxy {
connector: Arc<dyn L4Connect + Send + Sync>,
}
impl VirtualProxy {
fn new() -> Self {
Self {
connector: Arc::new(VirtualConnector),
}
}
}
#[async_trait::async_trait]
impl ProxyHttp for VirtualProxy {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
// Route everything to example.org unless the Host header is "virtual.test",
// in which case target the special virtual address 203.0.113.1:18080.
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<pingora_core::upstreams::peer::HttpPeer>> {
let mut options = PeerOptions::new();
options.custom_l4 = Some(self.connector.clone());
Ok(Box::new(HttpPeer {
_address: L4SocketAddr::Inet(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
80,
)),
scheme: pingora_core::upstreams::peer::Scheme::HTTP,
sni: "example.org".to_string(),
proxy: None,
client_cert_key: None,
group_key: 0,
options,
}))
}
}
fn main() {
// Minimal server config
let conf = Arc::new(ServerConf::default());
// Build the service and set the default L4 connector
let mut svc: Service<HttpProxy<VirtualProxy>> =
http_proxy_service_with_name(&conf, VirtualProxy::new(), "virtual-proxy");
// Listen
let addr = "127.0.0.1:6196";
svc.add_tcp(addr);
let mut server = Server::new(None).unwrap();
server.add_service(svc);
let run = RunArgs::default();
eprintln!("Listening on {addr}, try: curl http://{addr}/");
server.run(run);
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/multi_lb.rs | pingora-proxy/examples/multi_lb.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use std::sync::Arc;
use pingora_core::{prelude::*, services::background::GenBackgroundService};
use pingora_load_balancing::{
health_check::TcpHealthCheck,
selection::{BackendIter, BackendSelection, RoundRobin},
LoadBalancer,
};
use pingora_proxy::{http_proxy_service, ProxyHttp, Session};
struct Router {
cluster_one: Arc<LoadBalancer<RoundRobin>>,
cluster_two: Arc<LoadBalancer<RoundRobin>>,
}
#[async_trait]
impl ProxyHttp for Router {
type CTX = ();
fn new_ctx(&self) {}
async fn upstream_peer(&self, session: &mut Session, _ctx: &mut ()) -> Result<Box<HttpPeer>> {
// determine LB cluster based on request uri
let cluster = if session.req_header().uri.path().starts_with("/one/") {
&self.cluster_one
} else {
&self.cluster_two
};
let upstream = cluster
.select(b"", 256) // hash doesn't matter for round robin
.unwrap();
println!("upstream peer is: {upstream:?}");
// Set SNI to one.one.one.one
let peer = Box::new(HttpPeer::new(upstream, true, "one.one.one.one".to_string()));
Ok(peer)
}
}
fn build_cluster_service<S>(upstreams: &[&str]) -> GenBackgroundService<LoadBalancer<S>>
where
S: BackendSelection + 'static,
S::Iter: BackendIter,
{
let mut cluster = LoadBalancer::try_from_iter(upstreams).unwrap();
cluster.set_health_check(TcpHealthCheck::new());
cluster.health_check_frequency = Some(std::time::Duration::from_secs(1));
background_service("cluster health check", cluster)
}
// RUST_LOG=INFO cargo run --example multi_lb
// curl 127.0.0.1:6188/one/
// curl 127.0.0.1:6188/two/
fn main() {
let mut my_server = Server::new(None).unwrap();
my_server.bootstrap();
// build multiple clusters
let cluster_one = build_cluster_service::<RoundRobin>(&["1.1.1.1:443", "127.0.0.1:343"]);
let cluster_two = build_cluster_service::<RoundRobin>(&["1.0.0.1:443", "127.0.0.2:343"]);
let router = Router {
cluster_one: cluster_one.task(),
cluster_two: cluster_two.task(),
};
let mut router_service = http_proxy_service(&my_server.configuration, router);
router_service.add_tcp("0.0.0.0:6188");
my_server.add_service(router_service);
my_server.add_service(cluster_one);
my_server.add_service(cluster_two);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/modify_response.rs | pingora-proxy/examples/modify_response.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::net::ToSocketAddrs;
use pingora_core::server::configuration::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_http::ResponseHeader;
use pingora_proxy::{ProxyHttp, Session};
const HOST: &str = "ip.jsontest.com";
#[derive(Serialize, Deserialize)]
pub struct Resp {
ip: String,
}
pub struct Json2Yaml {
addr: std::net::SocketAddr,
}
pub struct MyCtx {
buffer: Vec<u8>,
}
#[async_trait]
impl ProxyHttp for Json2Yaml {
type CTX = MyCtx;
fn new_ctx(&self) -> Self::CTX {
MyCtx { buffer: vec![] }
}
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
let peer = Box::new(HttpPeer::new(self.addr, false, HOST.to_owned()));
Ok(peer)
}
async fn upstream_request_filter(
&self,
_session: &mut Session,
upstream_request: &mut pingora_http::RequestHeader,
_ctx: &mut Self::CTX,
) -> Result<()> {
upstream_request
.insert_header("Host", HOST.to_owned())
.unwrap();
Ok(())
}
async fn response_filter(
&self,
_session: &mut Session,
upstream_response: &mut ResponseHeader,
_ctx: &mut Self::CTX,
) -> Result<()>
where
Self::CTX: Send + Sync,
{
// Remove content-length because the size of the new body is unknown
upstream_response.remove_header("Content-Length");
upstream_response
.insert_header("Transfer-Encoding", "Chunked")
.unwrap();
Ok(())
}
fn response_body_filter(
&self,
_session: &mut Session,
body: &mut Option<Bytes>,
end_of_stream: bool,
ctx: &mut Self::CTX,
) -> Result<Option<std::time::Duration>>
where
Self::CTX: Send + Sync,
{
// buffer the data
if let Some(b) = body {
ctx.buffer.extend(&b[..]);
// drop the body
b.clear();
}
if end_of_stream {
// This is the last chunk, we can process the data now
let json_body: Resp = serde_json::de::from_slice(&ctx.buffer).unwrap();
let yaml_body = serde_yaml::to_string(&json_body).unwrap();
*body = Some(Bytes::copy_from_slice(yaml_body.as_bytes()));
}
Ok(None)
}
}
// RUST_LOG=INFO cargo run --example modify_response
// curl 127.0.0.1:6191
fn main() {
env_logger::init();
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy = pingora_proxy::http_proxy_service(
&my_server.configuration,
Json2Yaml {
// hardcode the IP of ip.jsontest.com for now
addr: ("142.251.2.121", 80)
.to_socket_addrs()
.unwrap()
.next()
.unwrap(),
},
);
my_proxy.add_tcp("127.0.0.1:6191");
my_server.add_service(my_proxy);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/gateway.rs | pingora-proxy/examples/gateway.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use bytes::Bytes;
use log::info;
use prometheus::register_int_counter;
use pingora_core::server::configuration::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_http::ResponseHeader;
use pingora_proxy::{ProxyHttp, Session};
fn check_login(req: &pingora_http::RequestHeader) -> bool {
// implement you logic check logic here
req.headers.get("Authorization").map(|v| v.as_bytes()) == Some(b"password")
}
pub struct MyGateway {
req_metric: prometheus::IntCounter,
}
#[async_trait]
impl ProxyHttp for MyGateway {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
if session.req_header().uri.path().starts_with("/login")
&& !check_login(session.req_header())
{
let _ = session
.respond_error_with_body(403, Bytes::from_static(b"no way!"))
.await;
// true: early return as the response is already written
return Ok(true);
}
Ok(false)
}
async fn upstream_peer(
&self,
session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
let addr = if session.req_header().uri.path().starts_with("/family") {
("1.0.0.1", 443)
} else {
("1.1.1.1", 443)
};
info!("connecting to {addr:?}");
let peer = Box::new(HttpPeer::new(addr, true, "one.one.one.one".to_string()));
Ok(peer)
}
async fn response_filter(
&self,
_session: &mut Session,
upstream_response: &mut ResponseHeader,
_ctx: &mut Self::CTX,
) -> Result<()>
where
Self::CTX: Send + Sync,
{
// replace existing header if any
upstream_response
.insert_header("Server", "MyGateway")
.unwrap();
// because we don't support h3
upstream_response.remove_header("alt-svc");
Ok(())
}
async fn logging(
&self,
session: &mut Session,
_e: Option<&pingora_core::Error>,
ctx: &mut Self::CTX,
) {
let response_code = session
.response_written()
.map_or(0, |resp| resp.status.as_u16());
info!(
"{} response code: {response_code}",
self.request_summary(session, ctx)
);
self.req_metric.inc();
}
}
// RUST_LOG=INFO cargo run --example gateway
// curl 127.0.0.1:6191 -H "Host: one.one.one.one"
// curl 127.0.0.1:6190/family/ -H "Host: one.one.one.one"
// curl 127.0.0.1:6191/login/ -H "Host: one.one.one.one" -I -H "Authorization: password"
// curl 127.0.0.1:6191/login/ -H "Host: one.one.one.one" -I -H "Authorization: bad"
// For metrics
// curl 127.0.0.1:6192/
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy = pingora_proxy::http_proxy_service(
&my_server.configuration,
MyGateway {
req_metric: register_int_counter!("req_counter", "Number of requests").unwrap(),
},
);
my_proxy.add_tcp("0.0.0.0:6191");
my_server.add_service(my_proxy);
let mut prometheus_service_http =
pingora_core::services::listening::Service::prometheus_http_service();
prometheus_service_http.add_tcp("127.0.0.1:6192");
my_server.add_service(prometheus_service_http);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/ctx.rs | pingora-proxy/examples/ctx.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use log::info;
use std::sync::Mutex;
use pingora_core::server::configuration::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_proxy::{ProxyHttp, Session};
// global counter
static REQ_COUNTER: Mutex<usize> = Mutex::new(0);
pub struct MyProxy {
// counter for the service
beta_counter: Mutex<usize>, // AtomicUsize works too
}
pub struct MyCtx {
beta_user: bool,
}
fn check_beta_user(req: &pingora_http::RequestHeader) -> bool {
// some simple logic to check if user is beta
req.headers.get("beta-flag").is_some()
}
#[async_trait]
impl ProxyHttp for MyProxy {
type CTX = MyCtx;
fn new_ctx(&self) -> Self::CTX {
MyCtx { beta_user: false }
}
async fn request_filter(&self, session: &mut Session, ctx: &mut Self::CTX) -> Result<bool> {
ctx.beta_user = check_beta_user(session.req_header());
Ok(false)
}
async fn upstream_peer(
&self,
_session: &mut Session,
ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
let mut req_counter = REQ_COUNTER.lock().unwrap();
*req_counter += 1;
let addr = if ctx.beta_user {
let mut beta_count = self.beta_counter.lock().unwrap();
*beta_count += 1;
info!("I'm a beta user #{beta_count}");
("1.0.0.1", 443)
} else {
info!("I'm an user #{req_counter}");
("1.1.1.1", 443)
};
let peer = Box::new(HttpPeer::new(addr, true, "one.one.one.one".to_string()));
Ok(peer)
}
}
// RUST_LOG=INFO cargo run --example ctx
// curl 127.0.0.1:6190 -H "Host: one.one.one.one"
// curl 127.0.0.1:6190 -H "Host: one.one.one.one" -H "beta-flag: 1"
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy = pingora_proxy::http_proxy_service(
&my_server.configuration,
MyProxy {
beta_counter: Mutex::new(0),
},
);
my_proxy.add_tcp("0.0.0.0:6190");
my_server.add_service(my_proxy);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/use_module.rs | pingora-proxy/examples/use_module.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use pingora_core::modules::http::HttpModules;
use pingora_core::server::configuration::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_http::RequestHeader;
use pingora_proxy::{ProxyHttp, Session};
// This example shows how to build and import 3rd party modules
/// A simple ACL to check "Authorization: basic $credential" header
mod my_acl {
use super::*;
use pingora_core::modules::http::{HttpModule, HttpModuleBuilder, Module};
use pingora_error::{Error, ErrorType::HTTPStatus};
use std::any::Any;
// This is the struct for per request module context
struct MyAclCtx {
credential_header: String,
}
// Implement how the module would consume and/or modify request and/or response
#[async_trait]
impl HttpModule for MyAclCtx {
async fn request_header_filter(&mut self, req: &mut RequestHeader) -> Result<()> {
let Some(auth) = req.headers.get(http::header::AUTHORIZATION) else {
return Error::e_explain(HTTPStatus(403), "Auth failed, no auth header");
};
if auth.as_bytes() != self.credential_header.as_bytes() {
Error::e_explain(HTTPStatus(403), "Auth failed, credential mismatch")
} else {
Ok(())
}
}
// boilerplate code for all modules
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
// This is the singleton object which will be attached to the server
pub struct MyAcl {
pub credential: String,
}
impl HttpModuleBuilder for MyAcl {
// This function defines how to create each Ctx. This function is called when a new request
// arrives
fn init(&self) -> Module {
Box::new(MyAclCtx {
// Make it easier to compare header
// We could also store this value in MyAcl and use Arc to share it with every Ctx.
credential_header: format!("basic {}", self.credential),
})
}
}
}
pub struct MyProxy;
#[async_trait]
impl ProxyHttp for MyProxy {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
// This function is only called once when the server starts
fn init_downstream_modules(&self, modules: &mut HttpModules) {
// Add the module to MyProxy
modules.add_module(Box::new(my_acl::MyAcl {
credential: "testcode".into(),
}))
}
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
let peer = Box::new(HttpPeer::new(
("1.1.1.1", 443),
true,
"one.one.one.one".to_string(),
));
Ok(peer)
}
}
// RUST_LOG=INFO cargo run --example use_module
// curl 127.0.0.1:6193 -H "Host: one.one.one.one" -v
// curl 127.0.0.1:6193 -H "Host: one.one.one.one" -H "Authorization: basic testcode"
// curl 127.0.0.1:6193 -H "Host: one.one.one.one" -H "Authorization: basic wrong" -v
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy = pingora_proxy::http_proxy_service(&my_server.configuration, MyProxy);
my_proxy.add_tcp("0.0.0.0:6193");
my_server.add_service(my_proxy);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-proxy/examples/load_balancer.rs | pingora-proxy/examples/load_balancer.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use log::info;
use pingora_core::services::background::background_service;
use std::{sync::Arc, time::Duration};
use pingora_core::server::configuration::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_load_balancing::{health_check, selection::RoundRobin, LoadBalancer};
use pingora_proxy::{ProxyHttp, Session};
pub struct LB(Arc<LoadBalancer<RoundRobin>>);
#[async_trait]
impl ProxyHttp for LB {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
async fn upstream_peer(&self, _session: &mut Session, _ctx: &mut ()) -> Result<Box<HttpPeer>> {
let upstream = self
.0
.select(b"", 256) // hash doesn't matter
.unwrap();
info!("upstream peer is: {:?}", upstream);
let peer = Box::new(HttpPeer::new(upstream, true, "one.one.one.one".to_string()));
Ok(peer)
}
async fn upstream_request_filter(
&self,
_session: &mut Session,
upstream_request: &mut pingora_http::RequestHeader,
_ctx: &mut Self::CTX,
) -> Result<()> {
upstream_request
.insert_header("Host", "one.one.one.one")
.unwrap();
Ok(())
}
}
// RUST_LOG=INFO cargo run --example load_balancer
fn main() {
env_logger::init();
// read command line arguments
let opt = Opt::parse_args();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
// 127.0.0.1:343" is just a bad server
let mut upstreams =
LoadBalancer::try_from_iter(["1.1.1.1:443", "1.0.0.1:443", "127.0.0.1:343"]).unwrap();
// We add health check in the background so that the bad server is never selected.
let hc = health_check::TcpHealthCheck::new();
upstreams.set_health_check(hc);
upstreams.health_check_frequency = Some(Duration::from_secs(1));
let background = background_service("health check", upstreams);
let upstreams = background.task();
let mut lb = pingora_proxy::http_proxy_service(&my_server.configuration, LB(upstreams));
lb.add_tcp("0.0.0.0:6188");
let cert_path = format!("{}/tests/keys/server.crt", env!("CARGO_MANIFEST_DIR"));
let key_path = format!("{}/tests/keys/key.pem", env!("CARGO_MANIFEST_DIR"));
let mut tls_settings =
pingora_core::listeners::tls::TlsSettings::intermediate(&cert_path, &key_path).unwrap();
tls_settings.enable_h2();
lb.add_tls_with_settings("0.0.0.0:6189", None, tls_settings);
my_server.add_service(lb);
my_server.add_service(background);
my_server.run_forever();
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-openssl/src/lib.rs | pingora-openssl/src/lib.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The OpenSSL API compatibility layer.
//!
//! This crate aims at making [openssl] APIs interchangeable with [boring](https://docs.rs/boring/latest/boring/).
//! In other words, this crate and [`pingora-boringssl`](https://docs.rs/pingora-boringssl) expose identical rust APIs.
#![warn(clippy::all)]
use openssl as ssl_lib;
pub use openssl_sys as ssl_sys;
pub use tokio_openssl as tokio_ssl;
pub mod ext;
// export commonly used libs
pub use ssl_lib::dh;
pub use ssl_lib::error;
pub use ssl_lib::hash;
pub use ssl_lib::nid;
pub use ssl_lib::pkey;
pub use ssl_lib::ssl;
pub use ssl_lib::x509;
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-openssl/src/ext.rs | pingora-openssl/src/ext.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use foreign_types::ForeignTypeRef;
use libc::*;
use openssl::error::ErrorStack;
use openssl::pkey::{HasPrivate, PKeyRef};
use openssl::ssl::{Ssl, SslAcceptor, SslRef};
use openssl::x509::store::X509StoreRef;
use openssl::x509::verify::X509VerifyParamRef;
use openssl::x509::X509Ref;
use openssl_sys::{
SSL_ctrl, EVP_PKEY, SSL, SSL_CTRL_SET_GROUPS_LIST, SSL_CTRL_SET_VERIFY_CERT_STORE, X509,
X509_VERIFY_PARAM,
};
use std::ffi::CString;
use std::os::raw;
fn cvt(r: c_long) -> Result<c_long, ErrorStack> {
if r != 1 {
Err(ErrorStack::get())
} else {
Ok(r)
}
}
extern "C" {
pub fn X509_VERIFY_PARAM_add1_host(
param: *mut X509_VERIFY_PARAM,
name: *const c_char,
namelen: size_t,
) -> c_int;
pub fn SSL_use_certificate(ssl: *mut SSL, cert: *mut X509) -> c_int;
pub fn SSL_use_PrivateKey(ssl: *mut SSL, key: *mut EVP_PKEY) -> c_int;
pub fn SSL_set_cert_cb(
ssl: *mut SSL,
cb: ::std::option::Option<
unsafe extern "C" fn(ssl: *mut SSL, arg: *mut raw::c_void) -> raw::c_int,
>,
arg: *mut raw::c_void,
);
}
/// Add name as an additional reference identifier that can match the peer's certificate
///
/// See [X509_VERIFY_PARAM_set1_host](https://www.openssl.org/docs/man3.1/man3/X509_VERIFY_PARAM_set1_host.html).
pub fn add_host(verify_param: &mut X509VerifyParamRef, host: &str) -> Result<(), ErrorStack> {
if host.is_empty() {
return Ok(());
}
unsafe {
cvt(X509_VERIFY_PARAM_add1_host(
verify_param.as_ptr(),
host.as_ptr() as *const c_char,
host.len(),
) as c_long)
.map(|_| ())
}
}
/// Set the verify cert store of `ssl`
///
/// See [SSL_set1_verify_cert_store](https://www.openssl.org/docs/man1.1.1/man3/SSL_set1_verify_cert_store.html).
pub fn ssl_set_verify_cert_store(
ssl: &mut SslRef,
cert_store: &X509StoreRef,
) -> Result<(), ErrorStack> {
unsafe {
cvt(SSL_ctrl(
ssl.as_ptr(),
SSL_CTRL_SET_VERIFY_CERT_STORE,
1, // increase the ref count of X509Store so that ssl_ctx can outlive X509StoreRef
cert_store.as_ptr() as *mut c_void,
))?;
}
Ok(())
}
/// Load the certificate into `ssl`
///
/// See [SSL_use_certificate](https://www.openssl.org/docs/man1.1.1/man3/SSL_use_certificate.html).
pub fn ssl_use_certificate(ssl: &mut SslRef, cert: &X509Ref) -> Result<(), ErrorStack> {
unsafe {
cvt(SSL_use_certificate(ssl.as_ptr(), cert.as_ptr()) as c_long)?;
}
Ok(())
}
/// Load the private key into `ssl`
///
/// See [SSL_use_certificate](https://www.openssl.org/docs/man1.1.1/man3/SSL_use_PrivateKey.html).
pub fn ssl_use_private_key<T>(ssl: &mut SslRef, key: &PKeyRef<T>) -> Result<(), ErrorStack>
where
T: HasPrivate,
{
unsafe {
cvt(SSL_use_PrivateKey(ssl.as_ptr(), key.as_ptr()) as c_long)?;
}
Ok(())
}
/// Add the certificate into the cert chain of `ssl`
///
/// See [SSL_add1_chain_cert](https://www.openssl.org/docs/man1.1.1/man3/SSL_add1_chain_cert.html)
pub fn ssl_add_chain_cert(ssl: &mut SslRef, cert: &X509Ref) -> Result<(), ErrorStack> {
const SSL_CTRL_CHAIN_CERT: i32 = 89;
unsafe {
cvt(SSL_ctrl(
ssl.as_ptr(),
SSL_CTRL_CHAIN_CERT,
1, // increase the ref count of X509 so that ssl can outlive X509StoreRef
cert.as_ptr() as *mut c_void,
))?;
}
Ok(())
}
/// Set renegotiation
///
/// This function is specific to BoringSSL. This function is noop for OpenSSL.
pub fn ssl_set_renegotiate_mode_freely(_ssl: &mut SslRef) {}
/// Set the curves/groups of `ssl`
///
/// See [set_groups_list](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_curves.html).
pub fn ssl_set_groups_list(ssl: &mut SslRef, groups: &str) -> Result<(), ErrorStack> {
if groups.contains('\0') {
return Err(ErrorStack::get());
}
let groups = CString::new(groups).map_err(|_| ErrorStack::get())?;
unsafe {
cvt(SSL_ctrl(
ssl.as_ptr(),
SSL_CTRL_SET_GROUPS_LIST,
0,
groups.as_ptr() as *mut c_void,
))?;
}
Ok(())
}
/// Set's whether a second keyshare to be sent in client hello when PQ is used.
///
/// This function is specific to BoringSSL. This function is noop for OpenSSL.
pub fn ssl_use_second_key_share(_ssl: &mut SslRef, _enabled: bool) {}
/// Clear the error stack
///
/// SSL calls should check and clear the OpenSSL error stack. But some calls fail to do so.
/// This causes the next unrelated SSL call to fail due to the leftover errors. This function allows
/// caller to clear the error stack before performing SSL calls to avoid this issue.
pub fn clear_error_stack() {
let _ = ErrorStack::get();
}
/// Create a new [Ssl] from &[SslAcceptor]
///
/// this function is to unify the interface between this crate and [`pingora-boringssl`](https://docs.rs/pingora-boringssl)
pub fn ssl_from_acceptor(acceptor: &SslAcceptor) -> Result<Ssl, ErrorStack> {
Ssl::new(acceptor.context())
}
/// Suspend the TLS handshake when a certificate is needed.
///
/// This function will cause tls handshake to pause and return the error: SSL_ERROR_WANT_X509_LOOKUP.
/// The caller should set the certificate and then call [unblock_ssl_cert()] before continue the
/// handshake on the tls connection.
pub fn suspend_when_need_ssl_cert(ssl: &mut SslRef) {
unsafe {
SSL_set_cert_cb(ssl.as_ptr(), Some(raw_cert_block), std::ptr::null_mut());
}
}
/// Unblock a TLS handshake after the certificate is set.
///
/// The user should continue to call tls handshake after this function is called.
pub fn unblock_ssl_cert(ssl: &mut SslRef) {
unsafe {
SSL_set_cert_cb(ssl.as_ptr(), None, std::ptr::null_mut());
}
}
// Just block the handshake
extern "C" fn raw_cert_block(_ssl: *mut openssl_sys::SSL, _arg: *mut c_void) -> c_int {
-1
}
/// Whether the TLS error is SSL_ERROR_WANT_X509_LOOKUP
pub fn is_suspended_for_cert(error: &openssl::ssl::Error) -> bool {
error.code().as_raw() == openssl_sys::SSL_ERROR_WANT_X509_LOOKUP
}
#[allow(clippy::mut_from_ref)]
/// Get a mutable SslRef ouf of SslRef, which is a missing functionality even when holding &mut SslStream
/// # Safety
/// the caller needs to make sure that they hold a &mut SslStream (or other types of mutable ref to the Ssl)
pub unsafe fn ssl_mut(ssl: &SslRef) -> &mut SslRef {
SslRef::from_ptr_mut(ssl.as_ptr())
}
#[cfg(test)]
mod tests {
use super::*;
use openssl::ssl::{SslContextBuilder, SslMethod};
#[test]
fn test_ssl_set_groups_list() {
let ctx_builder = SslContextBuilder::new(SslMethod::tls()).unwrap();
let ssl = Ssl::new(&ctx_builder.build()).unwrap();
let ssl_ref = unsafe { ssl_mut(&ssl) };
// Valid input
assert!(ssl_set_groups_list(ssl_ref, "P-256:P-384").is_ok());
// Invalid input (contains null byte)
assert!(ssl_set_groups_list(ssl_ref, "P-256\0P-384").is_err());
}
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-lru/src/lib.rs | pingora-lru/src/lib.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! An implementation of an LRU that focuses on memory efficiency, concurrency and persistence
//!
//! Features
//! - keys can have different sizes
//! - LRUs are sharded to avoid global locks.
//! - Memory layout and usage are optimized: small and no memory fragmentation
pub mod linked_list;
use linked_list::{LinkedList, LinkedListIter};
use hashbrown::HashMap;
use parking_lot::RwLock;
use std::sync::atomic::{AtomicUsize, Ordering};
/// The LRU with `N` shards
pub struct Lru<T, const N: usize> {
units: [RwLock<LruUnit<T>>; N],
weight: AtomicUsize,
weight_limit: usize,
len_watermark: Option<usize>,
len: AtomicUsize,
evicted_weight: AtomicUsize,
evicted_len: AtomicUsize,
}
impl<T, const N: usize> Lru<T, N> {
/// Create an [Lru] with the given weight limit and predicted capacity.
///
/// The capacity is per shard (for simplicity). So the total capacity = capacity * N
pub fn with_capacity(weight_limit: usize, capacity: usize) -> Self {
Self::with_capacity_and_watermark(weight_limit, capacity, None)
}
/// Create an [Lru] with the given weight limit, predicted capacity and optional watermark
///
/// The capacity is per shard (for simplicity). So the total capacity = capacity * N
///
/// The watermark indicates at what count we should begin evicting and acts as a limit
/// on the total number of allowed items.
pub fn with_capacity_and_watermark(
weight_limit: usize,
capacity: usize,
len_watermark: Option<usize>,
) -> Self {
// use the unsafe code from ArrayVec just to init the array
let mut units = arrayvec::ArrayVec::<_, N>::new();
for _ in 0..N {
units.push(RwLock::new(LruUnit::with_capacity(capacity)));
}
Lru {
units: units.into_inner().map_err(|_| "").unwrap(),
weight: AtomicUsize::new(0),
weight_limit,
len_watermark,
len: AtomicUsize::new(0),
evicted_weight: AtomicUsize::new(0),
evicted_len: AtomicUsize::new(0),
}
}
/// Admit the key value to the [Lru]
///
/// Return the shard index which the asset is added to
pub fn admit(&self, key: u64, data: T, weight: usize) -> usize {
let shard = get_shard(key, N);
let unit = &mut self.units[shard].write();
// Make sure weight is positive otherwise eviction won't work
// TODO: Probably should use NonZeroUsize instead
let weight = weight.max(1);
let old_weight = unit.admit(key, data, weight);
if old_weight != weight {
self.weight.fetch_add(weight, Ordering::Relaxed);
if old_weight > 0 {
self.weight.fetch_sub(old_weight, Ordering::Relaxed);
} else {
// Assume old_weight == 0 means a new item is admitted
self.len.fetch_add(1, Ordering::Relaxed);
}
}
shard
}
/// Increment the weight associated with a given key, up to an optional max weight.
/// If a `max_weight` is provided, the weight cannot exceed this max weight. If the current
/// weight is higher than the max, it will be capped to the max.
///
/// Return the total new weight. 0 indicates the key did not exist.
pub fn increment_weight(&self, key: u64, delta: usize, max_weight: Option<usize>) -> usize {
let shard = get_shard(key, N);
let unit = &mut self.units[shard].write();
if let Some((old_weight, new_weight)) = unit.increment_weight(key, delta, max_weight) {
if new_weight >= old_weight {
self.weight
.fetch_add(new_weight - old_weight, Ordering::Relaxed);
} else {
self.weight
.fetch_sub(old_weight - new_weight, Ordering::Relaxed);
}
new_weight
} else {
0
}
}
/// Promote the key to the head of the LRU
///
/// Return `true` if the key exists.
pub fn promote(&self, key: u64) -> bool {
self.units[get_shard(key, N)].write().access(key)
}
/// Promote to the top n of the LRU
///
/// This function is a bit more efficient in terms of reducing lock contention because it
/// will acquire a write lock only if the key is outside top n but only acquires a read lock
/// when the key is already in the top n.
///
/// Return false if the item doesn't exist
pub fn promote_top_n(&self, key: u64, top: usize) -> bool {
let unit = &self.units[get_shard(key, N)];
if !unit.read().need_promote(key, top) {
return true;
}
unit.write().access(key)
}
/// Evict at most one item from the given shard
///
/// Return the evicted asset and its size if there is anything to evict
pub fn evict_shard(&self, shard: u64) -> Option<(T, usize)> {
let evicted = self.units[get_shard(shard, N)].write().evict();
if let Some((_, weight)) = evicted.as_ref() {
self.weight.fetch_sub(*weight, Ordering::Relaxed);
self.len.fetch_sub(1, Ordering::Relaxed);
self.evicted_weight.fetch_add(*weight, Ordering::Relaxed);
self.evicted_len.fetch_add(1, Ordering::Relaxed);
}
evicted
}
/// Evict the [Lru] until the overall weight is below the limit (or the configured watermark).
///
/// Return a list of evicted items.
///
/// The evicted items are randomly selected from all the shards.
pub fn evict_to_limit(&self) -> Vec<(T, usize)> {
let mut evicted = vec![];
let mut initial_weight = self.weight();
let mut initial_len = self.len();
let mut shard_seed = rand::random(); // start from a random shard
let mut empty_shard = 0;
// Entries can be admitted or removed from the LRU by others during the loop below
// Track initial size not to over evict due to entries admitted after the loop starts
// self.weight() / self.len() is also used not to over evict
// due to entries already removed by others
while ((initial_weight > self.weight_limit && self.weight() > self.weight_limit)
|| self
.len_watermark
.is_some_and(|w| initial_len > w && self.len() > w))
&& empty_shard < N
{
if let Some(i) = self.evict_shard(shard_seed) {
initial_weight -= i.1;
initial_len = initial_len.saturating_sub(1);
evicted.push(i)
} else {
empty_shard += 1;
}
// move on to the next shard
shard_seed += 1;
}
evicted
}
/// Remove the given asset.
pub fn remove(&self, key: u64) -> Option<(T, usize)> {
let removed = self.units[get_shard(key, N)].write().remove(key);
if let Some((_, weight)) = removed.as_ref() {
self.weight.fetch_sub(*weight, Ordering::Relaxed);
self.len.fetch_sub(1, Ordering::Relaxed);
}
removed
}
/// Insert the item to the tail of this LRU.
///
/// Useful to recreate an LRU in most-to-least order
pub fn insert_tail(&self, key: u64, data: T, weight: usize) -> bool {
if self.units[get_shard(key, N)]
.write()
.insert_tail(key, data, weight)
{
self.weight.fetch_add(weight, Ordering::Relaxed);
self.len.fetch_add(1, Ordering::Relaxed);
true
} else {
false
}
}
/// Check existence of a key without changing the order in LRU.
pub fn peek(&self, key: u64) -> bool {
self.units[get_shard(key, N)].read().peek(key).is_some()
}
/// Check the weight of a key without changing the order in LRU.
pub fn peek_weight(&self, key: u64) -> Option<usize> {
self.units[get_shard(key, N)].read().peek_weight(key)
}
/// Return the current total weight.
pub fn weight(&self) -> usize {
self.weight.load(Ordering::Relaxed)
}
/// Return the total weight of items evicted from this [Lru].
pub fn evicted_weight(&self) -> usize {
self.evicted_weight.load(Ordering::Relaxed)
}
/// Return the total count of items evicted from this [Lru].
pub fn evicted_len(&self) -> usize {
self.evicted_len.load(Ordering::Relaxed)
}
/// The number of items inside this [Lru].
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.len.load(Ordering::Relaxed)
}
/// Scan a shard with the given function F
pub fn iter_for_each<F>(&self, shard: usize, f: F)
where
F: FnMut((&T, usize)),
{
assert!(shard < N);
self.units[shard].read().iter().for_each(f);
}
/// Get the total number of shards
pub const fn shards(&self) -> usize {
N
}
/// Get the number of items inside a shard
pub fn shard_len(&self, shard: usize) -> usize {
self.units[shard].read().len()
}
/// Get the weight (total size) inside a shard
pub fn shard_weight(&self, shard: usize) -> usize {
self.units[shard].read().used_weight
}
}
#[inline]
fn get_shard(key: u64, n_shards: usize) -> usize {
(key % n_shards as u64) as usize
}
struct LruNode<T> {
data: T,
list_index: usize,
weight: usize,
}
struct LruUnit<T> {
lookup_table: HashMap<u64, Box<LruNode<T>>>,
order: LinkedList,
used_weight: usize,
}
impl<T> LruUnit<T> {
fn with_capacity(capacity: usize) -> Self {
LruUnit {
lookup_table: HashMap::with_capacity(capacity),
order: LinkedList::with_capacity(capacity),
used_weight: 0,
}
}
/// Peek data associated with key, if it exists.
pub fn peek(&self, key: u64) -> Option<&T> {
self.lookup_table.get(&key).map(|n| &n.data)
}
/// Peek weight associated with key, if it exists.
pub fn peek_weight(&self, key: u64) -> Option<usize> {
self.lookup_table.get(&key).map(|n| n.weight)
}
/// Admit into LRU, return old weight if there was any.
pub fn admit(&mut self, key: u64, data: T, weight: usize) -> usize {
if let Some(node) = self.lookup_table.get_mut(&key) {
let old_weight = Self::adjust_weight(node, &mut self.used_weight, weight);
node.data = data;
self.order.promote(node.list_index);
return old_weight;
}
self.used_weight += weight;
let list_index = self.order.push_head(key);
let node = Box::new(LruNode {
data,
list_index,
weight,
});
self.lookup_table.insert(key, node);
0
}
/// Increase the weight of an existing key. Returns the new weight or 0 if the key did not
/// exist, along with the new weight (or 0).
///
/// If a `max_weight` is provided, the weight cannot exceed this max weight. If the current
/// weight is higher than the max, it will be capped to the max.
pub fn increment_weight(
&mut self,
key: u64,
delta: usize,
max_weight: Option<usize>,
) -> Option<(usize, usize)> {
if let Some(node) = self.lookup_table.get_mut(&key) {
let new_weight =
max_weight.map_or(node.weight + delta, |m| (node.weight + delta).min(m));
let old_weight = Self::adjust_weight(node, &mut self.used_weight, new_weight);
self.order.promote(node.list_index);
return Some((old_weight, new_weight));
}
None
}
pub fn access(&mut self, key: u64) -> bool {
if let Some(node) = self.lookup_table.get(&key) {
self.order.promote(node.list_index);
true
} else {
false
}
}
// Check if a key is already in the top n most recently used nodes.
// this is a heuristic to reduce write, which requires exclusive locks, for promotion,
// especially on very populate nodes
// NOTE: O(n) search here so limit needs to be small
pub fn need_promote(&self, key: u64, limit: usize) -> bool {
!self.order.exist_near_head(key, limit)
}
// try to evict 1 node
pub fn evict(&mut self) -> Option<(T, usize)> {
self.order.pop_tail().map(|key| {
// unwrap is safe because we always insert in both the hashtable and the list
let node = self.lookup_table.remove(&key).unwrap();
self.used_weight -= node.weight;
(node.data, node.weight)
})
}
// TODO: scan the tail up to K elements to decide which ones to evict
pub fn remove(&mut self, key: u64) -> Option<(T, usize)> {
self.lookup_table.remove(&key).map(|node| {
let list_key = self.order.remove(node.list_index);
assert_eq!(key, list_key);
self.used_weight -= node.weight;
(node.data, node.weight)
})
}
pub fn insert_tail(&mut self, key: u64, data: T, weight: usize) -> bool {
if self.lookup_table.contains_key(&key) {
return false;
}
let list_index = self.order.push_tail(key);
let node = Box::new(LruNode {
data,
list_index,
weight,
});
self.lookup_table.insert(key, node);
self.used_weight += weight;
true
}
pub fn len(&self) -> usize {
assert_eq!(self.lookup_table.len(), self.order.len());
self.lookup_table.len()
}
#[cfg(test)]
pub fn used_weight(&self) -> usize {
self.used_weight
}
pub fn iter(&self) -> LruUnitIter<'_, T> {
LruUnitIter {
unit: self,
iter: self.order.iter(),
}
}
// Adjusts node weight to the new given weight.
// Returns old weight.
#[inline]
fn adjust_weight(node: &mut LruNode<T>, used_weight: &mut usize, weight: usize) -> usize {
let old_weight = node.weight;
if weight != old_weight {
*used_weight += weight;
*used_weight -= old_weight;
node.weight = weight;
}
old_weight
}
}
struct LruUnitIter<'a, T> {
unit: &'a LruUnit<T>,
iter: LinkedListIter<'a>,
}
impl<'a, T> Iterator for LruUnitIter<'a, T> {
type Item = (&'a T, usize);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|key| {
// safe because we always items in table and list are always 1:1
let node = self.unit.lookup_table.get(key).unwrap();
(&node.data, node.weight)
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator for LruUnitIter<'_, T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|key| {
// safe because we always items in table and list are always 1:1
let node = self.unit.lookup_table.get(key).unwrap();
(&node.data, node.weight)
})
}
}
#[cfg(test)]
mod test_lru {
use super::*;
fn assert_lru<T: Copy + PartialEq + std::fmt::Debug, const N: usize>(
lru: &Lru<T, N>,
values: &[T],
shard: usize,
) {
let mut list_values = vec![];
lru.iter_for_each(shard, |(v, _)| list_values.push(*v));
assert_eq!(values, &list_values)
}
#[test]
fn test_admit() {
let lru = Lru::<_, 2>::with_capacity(30, 10);
assert_eq!(lru.len(), 0);
lru.admit(2, 2, 3);
assert_eq!(lru.len(), 1);
assert_eq!(lru.weight(), 3);
lru.admit(2, 2, 1);
assert_eq!(lru.len(), 1);
assert_eq!(lru.weight(), 1);
lru.admit(2, 2, 2); // admit again with different weight
assert_eq!(lru.len(), 1);
assert_eq!(lru.weight(), 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
assert_eq!(lru.weight(), 2 + 3 + 4);
assert_eq!(lru.len(), 3);
}
#[test]
fn test_promote() {
let lru = Lru::<_, 2>::with_capacity(30, 10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
lru.admit(5, 5, 5);
lru.admit(6, 6, 6);
assert_lru(&lru, &[6, 4, 2], 0);
assert_lru(&lru, &[5, 3], 1);
assert!(lru.promote(3));
assert_lru(&lru, &[3, 5], 1);
assert!(lru.promote(3));
assert_lru(&lru, &[3, 5], 1);
assert!(lru.promote(2));
assert_lru(&lru, &[2, 6, 4], 0);
assert!(!lru.promote(7)); // 7 doesn't exist
assert_lru(&lru, &[2, 6, 4], 0);
assert_lru(&lru, &[3, 5], 1);
// promote 2 to top 1, already there
assert!(lru.promote_top_n(2, 1));
assert_lru(&lru, &[2, 6, 4], 0);
// promote 4 to top 3, already there
assert!(lru.promote_top_n(4, 3));
assert_lru(&lru, &[2, 6, 4], 0);
// promote 4 to top 2
assert!(lru.promote_top_n(4, 2));
assert_lru(&lru, &[4, 2, 6], 0);
// promote 2 to top 1
assert!(lru.promote_top_n(2, 1));
assert_lru(&lru, &[2, 4, 6], 0);
assert!(!lru.promote_top_n(7, 1)); // 7 doesn't exist
}
#[test]
fn test_evict() {
let lru = Lru::<_, 2>::with_capacity(14, 10);
// same weight to make the random eviction less random
lru.admit(2, 2, 2);
lru.admit(3, 3, 2);
lru.admit(4, 4, 4);
lru.admit(5, 5, 4);
lru.admit(6, 6, 2);
lru.admit(7, 7, 2);
assert_lru(&lru, &[6, 4, 2], 0);
assert_lru(&lru, &[7, 5, 3], 1);
assert_eq!(lru.weight(), 16);
assert_eq!(lru.len(), 6);
let evicted = lru.evict_to_limit();
assert_eq!(lru.weight(), 14);
assert_eq!(lru.len(), 5);
assert_eq!(lru.evicted_weight(), 2);
assert_eq!(lru.evicted_len(), 1);
assert_eq!(evicted.len(), 1);
assert_eq!(evicted[0].1, 2); //weight
assert!(evicted[0].0 == 2 || evicted[0].0 == 3); //either 2 or 3 are evicted
let lru = Lru::<_, 2>::with_capacity(6, 10);
// same weight random eviction less random
lru.admit(2, 2, 2);
lru.admit(3, 3, 2);
lru.admit(4, 4, 2);
lru.admit(5, 5, 2);
lru.admit(6, 6, 2);
lru.admit(7, 7, 2);
assert_eq!(lru.weight(), 12);
assert_eq!(lru.len(), 6);
let evicted = lru.evict_to_limit();
// NOTE: there is a low chance this test would fail see the TODO in evict_to_limit
assert_eq!(lru.weight(), 6);
assert_eq!(lru.len(), 3);
assert_eq!(lru.evicted_weight(), 6);
assert_eq!(lru.evicted_len(), 3);
assert_eq!(evicted.len(), 3);
}
#[test]
fn test_increment_weight() {
let lru = Lru::<_, 2>::with_capacity(6, 10);
lru.admit(1, 1, 1);
lru.increment_weight(1, 1, None);
assert_eq!(lru.weight(), 1 + 1);
lru.increment_weight(0, 1000, None);
assert_eq!(lru.weight(), 1 + 1);
lru.admit(2, 2, 2);
lru.increment_weight(2, 2, None);
assert_eq!(lru.weight(), 1 + 1 + 2 + 2);
lru.increment_weight(2, 2, Some(3));
assert_eq!(lru.weight(), 1 + 1 + 3);
}
#[test]
fn test_remove() {
let lru = Lru::<_, 2>::with_capacity(30, 10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
lru.admit(5, 5, 5);
lru.admit(6, 6, 6);
assert_eq!(lru.weight(), 2 + 3 + 4 + 5 + 6);
assert_eq!(lru.len(), 5);
assert_lru(&lru, &[6, 4, 2], 0);
assert_lru(&lru, &[5, 3], 1);
let node = lru.remove(6).unwrap();
assert_eq!(node.0, 6); // data
assert_eq!(node.1, 6); // weight
assert_eq!(lru.weight(), 2 + 3 + 4 + 5);
assert_eq!(lru.len(), 4);
assert_lru(&lru, &[4, 2], 0);
let node = lru.remove(3).unwrap();
assert_eq!(node.0, 3); // data
assert_eq!(node.1, 3); // weight
assert_eq!(lru.weight(), 2 + 4 + 5);
assert_eq!(lru.len(), 3);
assert_lru(&lru, &[5], 1);
assert!(lru.remove(7).is_none());
}
#[test]
fn test_peek() {
let lru = Lru::<_, 2>::with_capacity(30, 10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
assert!(lru.peek(4));
assert!(lru.peek(3));
assert!(lru.peek(2));
assert_lru(&lru, &[4, 2], 0);
assert_lru(&lru, &[3], 1);
}
#[test]
fn test_insert_tail() {
let lru = Lru::<_, 2>::with_capacity(30, 10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
lru.admit(5, 5, 5);
lru.admit(6, 6, 6);
assert_eq!(lru.weight(), 2 + 3 + 4 + 5 + 6);
assert_eq!(lru.len(), 5);
assert_lru(&lru, &[6, 4, 2], 0);
assert_lru(&lru, &[5, 3], 1);
assert!(lru.insert_tail(7, 7, 7));
assert_eq!(lru.weight(), 2 + 3 + 4 + 5 + 6 + 7);
assert_eq!(lru.len(), 6);
assert_lru(&lru, &[5, 3, 7], 1);
// ignore existing ones
assert!(!lru.insert_tail(6, 6, 7));
}
#[test]
fn test_watermark_eviction() {
const WEIGHT_LIMIT: usize = usize::MAX / 2;
let lru = Lru::<u64, 2>::with_capacity_and_watermark(WEIGHT_LIMIT, 10, Some(4));
// admit 6 items, each weight 1
for k in [2u64, 3, 4, 5, 6, 7] {
lru.admit(k, k, 1);
}
assert!(lru.weight() < WEIGHT_LIMIT);
assert_eq!(lru.len(), 6);
let evicted = lru.evict_to_limit();
assert_eq!(lru.len(), 4);
assert_eq!(evicted.len(), 2);
assert_eq!(lru.evicted_len(), 2);
}
}
#[cfg(test)]
mod test_lru_unit {
use super::*;
fn assert_lru<T: Copy + PartialEq + std::fmt::Debug>(lru: &LruUnit<T>, values: &[T]) {
let list_values: Vec<_> = lru.iter().map(|(v, _)| *v).collect();
assert_eq!(values, &list_values)
}
#[test]
fn test_admit() {
let mut lru = LruUnit::with_capacity(10);
assert_eq!(lru.len(), 0);
assert!(lru.peek(0).is_none());
lru.admit(2, 2, 1);
assert_eq!(lru.len(), 1);
assert_eq!(lru.peek(2).unwrap(), &2);
assert_eq!(lru.used_weight(), 1);
lru.admit(2, 2, 2); // admit again with different weight
assert_eq!(lru.used_weight(), 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
assert_eq!(lru.used_weight(), 2 + 3 + 4);
assert_lru(&lru, &[4, 3, 2]);
}
#[test]
fn test_access() {
let mut lru = LruUnit::with_capacity(10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
assert_lru(&lru, &[4, 3, 2]);
assert!(lru.access(3));
assert_lru(&lru, &[3, 4, 2]);
assert!(lru.access(3));
assert_lru(&lru, &[3, 4, 2]);
assert!(lru.access(2));
assert_lru(&lru, &[2, 3, 4]);
assert!(!lru.access(5)); // 5 doesn't exist
assert_lru(&lru, &[2, 3, 4]);
assert!(!lru.need_promote(2, 1));
assert!(lru.need_promote(3, 1));
assert!(!lru.need_promote(4, 9999));
}
#[test]
fn test_evict() {
let mut lru = LruUnit::with_capacity(10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
assert_lru(&lru, &[4, 3, 2]);
assert!(lru.access(3));
assert!(lru.access(3));
assert!(lru.access(2));
assert_lru(&lru, &[2, 3, 4]);
assert_eq!(lru.used_weight(), 2 + 3 + 4);
assert_eq!(lru.evict(), Some((4, 4)));
assert_eq!(lru.used_weight(), 2 + 3);
assert_lru(&lru, &[2, 3]);
assert_eq!(lru.evict(), Some((3, 3)));
assert_eq!(lru.used_weight(), 2);
assert_lru(&lru, &[2]);
assert_eq!(lru.evict(), Some((2, 2)));
assert_eq!(lru.used_weight(), 0);
assert_lru(&lru, &[]);
assert_eq!(lru.evict(), None);
assert_eq!(lru.used_weight(), 0);
assert_lru(&lru, &[]);
}
#[test]
fn test_increment_weight() {
let mut lru = LruUnit::with_capacity(10);
lru.admit(1, 1, 1);
lru.increment_weight(1, 1, None);
assert_eq!(lru.used_weight(), 1 + 1);
lru.increment_weight(0, 1000, None);
assert_eq!(lru.used_weight(), 1 + 1);
lru.admit(2, 2, 2);
lru.increment_weight(2, 2, None);
assert_eq!(lru.used_weight(), 1 + 1 + 2 + 2);
lru.admit(3, 3, 3);
lru.increment_weight(3, 3, Some(5));
assert_eq!(lru.used_weight(), 1 + 1 + 2 + 2 + 3 + 2);
lru.increment_weight(3, 3, Some(3));
assert_eq!(lru.used_weight(), 1 + 1 + 2 + 2 + 3);
}
#[test]
fn test_remove() {
let mut lru = LruUnit::with_capacity(10);
lru.admit(2, 2, 2);
lru.admit(3, 3, 3);
lru.admit(4, 4, 4);
lru.admit(5, 5, 5);
assert_lru(&lru, &[5, 4, 3, 2]);
assert!(lru.access(4));
assert!(lru.access(3));
assert!(lru.access(3));
assert!(lru.access(2));
assert_lru(&lru, &[2, 3, 4, 5]);
assert_eq!(lru.used_weight(), 2 + 3 + 4 + 5);
assert_eq!(lru.remove(2), Some((2, 2)));
assert_eq!(lru.used_weight(), 3 + 4 + 5);
assert_lru(&lru, &[3, 4, 5]);
assert_eq!(lru.remove(4), Some((4, 4)));
assert_eq!(lru.used_weight(), 3 + 5);
assert_lru(&lru, &[3, 5]);
assert_eq!(lru.remove(5), Some((5, 5)));
assert_eq!(lru.used_weight(), 3);
assert_lru(&lru, &[3]);
assert_eq!(lru.remove(1), None);
assert_eq!(lru.used_weight(), 3);
assert_lru(&lru, &[3]);
assert_eq!(lru.remove(3), Some((3, 3)));
assert_eq!(lru.used_weight(), 0);
assert_lru(&lru, &[]);
}
#[test]
fn test_insert_tail() {
let mut lru = LruUnit::with_capacity(10);
assert_eq!(lru.len(), 0);
assert!(lru.peek(0).is_none());
assert!(lru.insert_tail(2, 2, 1));
assert_eq!(lru.len(), 1);
assert_eq!(lru.peek(2).unwrap(), &2);
assert_eq!(lru.used_weight(), 1);
assert!(!lru.insert_tail(2, 2, 2));
assert!(lru.insert_tail(3, 3, 3));
assert_eq!(lru.used_weight(), 1 + 3);
assert_lru(&lru, &[2, 3]);
assert!(lru.insert_tail(4, 4, 4));
assert!(lru.insert_tail(5, 5, 5));
assert_eq!(lru.used_weight(), 1 + 3 + 4 + 5);
assert_lru(&lru, &[2, 3, 4, 5]);
}
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-lru/src/linked_list.rs | pingora-lru/src/linked_list.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Can't tell people you know Rust until you write a (doubly) linked list
//! Doubly linked list
//!
//! Features
//! - Preallocate consecutive memory, no memory fragmentation.
//! - No shrink function: for Lru cache that grows to a certain size but never shrinks.
//! - Relatively fast and efficient.
// inspired by clru::FixedSizeList (Élie!)
use std::mem::replace;
type Index = usize;
const NULL: Index = usize::MAX;
const HEAD: Index = 0;
const TAIL: Index = 1;
const OFFSET: usize = 2;
#[derive(Debug)]
struct Node {
pub(crate) prev: Index,
pub(crate) next: Index,
pub(crate) data: u64,
}
// Functionally the same as vec![head, tail, data_nodes...] where head & tail are fixed and
// the rest data nodes can expand. Both head and tail can be accessed faster than using index
struct Nodes {
// we use these sentinel nodes to guard the head and tail of the list so that list
// manipulation is simpler (fewer if-else)
head: Node,
tail: Node,
data_nodes: Vec<Node>,
}
impl Nodes {
fn with_capacity(capacity: usize) -> Self {
Nodes {
head: Node {
prev: NULL,
next: TAIL,
data: 0,
},
tail: Node {
prev: HEAD,
next: NULL,
data: 0,
},
data_nodes: Vec::with_capacity(capacity),
}
}
fn new_node(&mut self, data: u64) -> Index {
const VEC_EXP_GROWTH_CAP: usize = 65536;
let node = Node {
prev: NULL,
next: NULL,
data,
};
// Constrain the growth of vec: vec always double its capacity when it needs to grow.
// It could waste too much memory when it is already very large.
// Here we limit the memory waste to 10% once it grows beyond the cap.
// The amortized growth cost is O(n) beyond the max of the initially reserved capacity and
// the cap. But this list is for limited sized LRU and we recycle released node, so
// hopefully insertions are rare beyond certain sizes
if self.data_nodes.capacity() > VEC_EXP_GROWTH_CAP
&& self.data_nodes.capacity() - self.data_nodes.len() < 2
{
self.data_nodes
.reserve_exact(self.data_nodes.capacity() / 10)
}
self.data_nodes.push(node);
self.data_nodes.len() - 1 + OFFSET
}
fn len(&self) -> usize {
self.data_nodes.len()
}
fn head(&self) -> &Node {
&self.head
}
fn tail(&self) -> &Node {
&self.tail
}
}
impl std::ops::Index<usize> for Nodes {
type Output = Node;
fn index(&self, index: usize) -> &Self::Output {
match index {
HEAD => &self.head,
TAIL => &self.tail,
_ => &self.data_nodes[index - OFFSET],
}
}
}
impl std::ops::IndexMut<usize> for Nodes {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
match index {
HEAD => &mut self.head,
TAIL => &mut self.tail,
_ => &mut self.data_nodes[index - OFFSET],
}
}
}
/// Doubly linked list
pub struct LinkedList {
nodes: Nodes,
free: Vec<Index>, // to keep track of freed node to be used again
}
// Panic when index used as parameters are invalid
// Index returned by push_* is always valid.
impl LinkedList {
/// Create a [LinkedList] with the given predicted capacity.
pub fn with_capacity(capacity: usize) -> Self {
LinkedList {
nodes: Nodes::with_capacity(capacity),
free: vec![],
}
}
// Allocate a new node and return its index
// NOTE: this node is leaked if not used by caller
fn new_node(&mut self, data: u64) -> Index {
if let Some(index) = self.free.pop() {
// have a free node, update its payload and return its index
self.nodes[index].data = data;
index
} else {
// create a new node
self.nodes.new_node(data)
}
}
/// How many nodes in the list
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
// exclude the 2 sentinels
self.nodes.len() - self.free.len()
}
fn valid_index(&self, index: Index) -> bool {
index != HEAD && index != TAIL && index < self.nodes.len() + OFFSET
// TODO: check node prev/next not NULL
// TODO: debug_check index not in self.free
}
fn node(&self, index: Index) -> Option<&Node> {
if self.valid_index(index) {
Some(&self.nodes[index])
} else {
None
}
}
/// Peek into the list
pub fn peek(&self, index: Index) -> Option<u64> {
self.node(index).map(|n| n.data)
}
// safe because the index still needs to be in the range of the vec
fn peek_unchecked(&self, index: Index) -> &u64 {
&self.nodes[index].data
}
/// Whether the value exists closed (up to search_limit nodes) to the head of the list
// It can be done via iter().take().find() but this is cheaper
pub fn exist_near_head(&self, value: u64, search_limit: usize) -> bool {
let mut current_node = HEAD;
for _ in 0..search_limit {
current_node = self.nodes[current_node].next;
if current_node == TAIL {
return false;
}
if self.nodes[current_node].data == value {
return true;
}
}
false
}
// put a node right after the node at `at`
fn insert_after(&mut self, node_index: Index, at: Index) {
assert!(at != TAIL && at != node_index); // can't insert after tail or to itself
let next = replace(&mut self.nodes[at].next, node_index);
let node = &mut self.nodes[node_index];
node.next = next;
node.prev = at;
self.nodes[next].prev = node_index;
}
/// Put the data at the head of the list.
pub fn push_head(&mut self, data: u64) -> Index {
let new_node_index = self.new_node(data);
self.insert_after(new_node_index, HEAD);
new_node_index
}
/// Put the data at the tail of the list.
pub fn push_tail(&mut self, data: u64) -> Index {
let new_node_index = self.new_node(data);
self.insert_after(new_node_index, self.nodes.tail().prev);
new_node_index
}
// lift the node out of the linked list, to either delete it or insert to another place
// NOTE: the node is leaked if not used by the caller
fn lift(&mut self, index: Index) -> u64 {
// can't touch the sentinels
assert!(index != HEAD && index != TAIL);
let node = &mut self.nodes[index];
// zero out the pointers, useful in case we try to access a freed node
let prev = replace(&mut node.prev, NULL);
let next = replace(&mut node.next, NULL);
let data = node.data;
// make sure we are accessing a node in the list, not freed already
assert!(prev != NULL && next != NULL);
self.nodes[prev].next = next;
self.nodes[next].prev = prev;
data
}
/// Remove the node at the index, and return the value
pub fn remove(&mut self, index: Index) -> u64 {
self.free.push(index);
self.lift(index)
}
/// Remove the tail of the list
pub fn pop_tail(&mut self) -> Option<u64> {
let data_tail = self.nodes.tail().prev;
if data_tail == HEAD {
None // empty list
} else {
Some(self.remove(data_tail))
}
}
/// Put the node at the index to the head
pub fn promote(&mut self, index: Index) {
if self.nodes.head().next == index {
return; // already head
}
self.lift(index);
self.insert_after(index, HEAD);
}
fn next(&self, index: Index) -> Index {
self.nodes[index].next
}
fn prev(&self, index: Index) -> Index {
self.nodes[index].prev
}
/// Get the head of the list
pub fn head(&self) -> Option<Index> {
let data_head = self.nodes.head().next;
if data_head == TAIL {
None
} else {
Some(data_head)
}
}
/// Get the tail of the list
pub fn tail(&self) -> Option<Index> {
let data_tail = self.nodes.tail().prev;
if data_tail == HEAD {
None
} else {
Some(data_tail)
}
}
/// Iterate over the list
pub fn iter(&self) -> LinkedListIter<'_> {
LinkedListIter {
list: self,
head: HEAD,
tail: TAIL,
len: self.len(),
}
}
}
/// The iter over the list
pub struct LinkedListIter<'a> {
list: &'a LinkedList,
head: Index,
tail: Index,
len: usize,
}
impl<'a> Iterator for LinkedListIter<'a> {
type Item = &'a u64;
fn next(&mut self) -> Option<Self::Item> {
let next_index = self.list.next(self.head);
if next_index == TAIL || next_index == NULL {
None
} else {
self.head = next_index;
self.len -= 1;
Some(self.list.peek_unchecked(next_index))
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl DoubleEndedIterator for LinkedListIter<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
let prev_index = self.list.prev(self.tail);
if prev_index == HEAD || prev_index == NULL {
None
} else {
self.tail = prev_index;
self.len -= 1;
Some(self.list.peek_unchecked(prev_index))
}
}
}
#[cfg(test)]
mod test {
use super::*;
// assert the list is the same as `values`
fn assert_list(list: &LinkedList, values: &[u64]) {
let list_values: Vec<_> = list.iter().copied().collect();
assert_eq!(values, &list_values)
}
fn assert_list_reverse(list: &LinkedList, values: &[u64]) {
let list_values: Vec<_> = list.iter().rev().copied().collect();
assert_eq!(values, &list_values)
}
#[test]
fn test_insert() {
let mut list = LinkedList::with_capacity(10);
assert_eq!(list.len(), 0);
assert!(list.node(2).is_none());
assert_eq!(list.head(), None);
assert_eq!(list.tail(), None);
let index1 = list.push_head(2);
assert_eq!(list.len(), 1);
assert_eq!(list.peek(index1).unwrap(), 2);
let index2 = list.push_head(3);
assert_eq!(list.head(), Some(index2));
assert_eq!(list.tail(), Some(index1));
let index3 = list.push_tail(4);
assert_eq!(list.head(), Some(index2));
assert_eq!(list.tail(), Some(index3));
assert_list(&list, &[3, 2, 4]);
assert_list_reverse(&list, &[4, 2, 3]);
}
#[test]
fn test_pop() {
let mut list = LinkedList::with_capacity(10);
list.push_head(2);
list.push_head(3);
list.push_tail(4);
assert_list(&list, &[3, 2, 4]);
assert_eq!(list.pop_tail(), Some(4));
assert_eq!(list.pop_tail(), Some(2));
assert_eq!(list.pop_tail(), Some(3));
assert_eq!(list.pop_tail(), None);
}
#[test]
fn test_promote() {
let mut list = LinkedList::with_capacity(10);
let index2 = list.push_head(2);
let index3 = list.push_head(3);
let index4 = list.push_tail(4);
assert_list(&list, &[3, 2, 4]);
list.promote(index3);
assert_list(&list, &[3, 2, 4]);
list.promote(index2);
assert_list(&list, &[2, 3, 4]);
list.promote(index4);
assert_list(&list, &[4, 2, 3]);
}
#[test]
fn test_exist_near_head() {
let mut list = LinkedList::with_capacity(10);
list.push_head(2);
list.push_head(3);
list.push_tail(4);
assert_list(&list, &[3, 2, 4]);
assert!(!list.exist_near_head(4, 1));
assert!(!list.exist_near_head(4, 2));
assert!(list.exist_near_head(4, 3));
assert!(list.exist_near_head(4, 4));
assert!(list.exist_near_head(4, 99999));
}
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-lru/benches/bench_lru.rs | pingora-lru/benches/bench_lru.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use rand::distributions::WeightedIndex;
use rand::prelude::*;
use std::sync::Arc;
use std::thread;
use std::time::Instant;
// Non-uniform distributions, 100 items, 10 of them are 100x more likely to appear
const WEIGHTS: &[usize] = &[
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100,
];
const ITERATIONS: usize = 5_000_000;
const THREADS: usize = 8;
fn main() {
let lru = parking_lot::Mutex::new(lru::LruCache::<u64, ()>::unbounded());
let plru = pingora_lru::Lru::<(), 10>::with_capacity(1000, 100);
// populate first, then we bench access/promotion
for i in 0..WEIGHTS.len() {
lru.lock().put(i as u64, ());
}
for i in 0..WEIGHTS.len() {
plru.admit(i as u64, (), 1);
}
// single thread
let mut rng = thread_rng();
let dist = WeightedIndex::new(WEIGHTS).unwrap();
let before = Instant::now();
for _ in 0..ITERATIONS {
lru.lock().get(&(dist.sample(&mut rng) as u64));
}
let elapsed = before.elapsed();
println!(
"lru promote total {elapsed:?}, {:?} avg per operation",
elapsed / ITERATIONS as u32
);
let before = Instant::now();
for _ in 0..ITERATIONS {
plru.promote(dist.sample(&mut rng) as u64);
}
let elapsed = before.elapsed();
println!(
"pingora lru promote total {elapsed:?}, {:?} avg per operation",
elapsed / ITERATIONS as u32
);
let before = Instant::now();
for _ in 0..ITERATIONS {
plru.promote_top_n(dist.sample(&mut rng) as u64, 10);
}
let elapsed = before.elapsed();
println!(
"pingora lru promote_top_10 total {elapsed:?}, {:?} avg per operation",
elapsed / ITERATIONS as u32
);
// concurrent
let lru = Arc::new(lru);
let mut handlers = vec![];
for i in 0..THREADS {
let lru = lru.clone();
let handler = thread::spawn(move || {
let mut rng = thread_rng();
let dist = WeightedIndex::new(WEIGHTS).unwrap();
let before = Instant::now();
for _ in 0..ITERATIONS {
lru.lock().get(&(dist.sample(&mut rng) as u64));
}
let elapsed = before.elapsed();
println!(
"lru promote total {elapsed:?}, {:?} avg per operation thread {i}",
elapsed / ITERATIONS as u32
);
});
handlers.push(handler);
}
for thread in handlers {
thread.join().unwrap();
}
let plru = Arc::new(plru);
let mut handlers = vec![];
for i in 0..THREADS {
let plru = plru.clone();
let handler = thread::spawn(move || {
let mut rng = thread_rng();
let dist = WeightedIndex::new(WEIGHTS).unwrap();
let before = Instant::now();
for _ in 0..ITERATIONS {
plru.promote(dist.sample(&mut rng) as u64);
}
let elapsed = before.elapsed();
println!(
"pingora lru promote total {elapsed:?}, {:?} avg per operation thread {i}",
elapsed / ITERATIONS as u32
);
});
handlers.push(handler);
}
for thread in handlers {
thread.join().unwrap();
}
let mut handlers = vec![];
for i in 0..THREADS {
let plru = plru.clone();
let handler = thread::spawn(move || {
let mut rng = thread_rng();
let dist = WeightedIndex::new(WEIGHTS).unwrap();
let before = Instant::now();
for _ in 0..ITERATIONS {
plru.promote_top_n(dist.sample(&mut rng) as u64, 10);
}
let elapsed = before.elapsed();
println!(
"pingora lru promote_top_10 total {elapsed:?}, {:?} avg per operation thread {i}",
elapsed / ITERATIONS as u32
);
});
handlers.push(handler);
}
for thread in handlers {
thread.join().unwrap();
}
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
cloudflare/pingora | https://github.com/cloudflare/pingora/blob/5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094/pingora-lru/benches/bench_linked_list.rs | pingora-lru/benches/bench_linked_list.rs | // Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::time::Instant;
fn main() {
const ITEMS: usize = 5_000_000;
// push bench
let mut std_list = std::collections::LinkedList::<u64>::new();
let before = Instant::now();
for _ in 0..ITEMS {
std_list.push_front(0);
}
let elapsed = before.elapsed();
println!(
"std linked list push_front total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
let mut list = pingora_lru::linked_list::LinkedList::with_capacity(ITEMS);
let before = Instant::now();
for _ in 0..ITEMS {
list.push_head(0);
}
let elapsed = before.elapsed();
println!(
"pingora linked list push_head total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
// iter bench
let mut count = 0;
let before = Instant::now();
for _ in std_list.iter() {
count += 1;
}
let elapsed = before.elapsed();
println!(
"std linked list iter total {count} {elapsed:?}, {:?} avg per operation",
elapsed / count as u32
);
let mut count = 0;
let before = Instant::now();
for _ in list.iter() {
count += 1;
}
let elapsed = before.elapsed();
println!(
"pingora linked list iter total {count} {elapsed:?}, {:?} avg per operation",
elapsed / count as u32
);
// search bench
let before = Instant::now();
for _ in 0..ITEMS {
assert!(!std_list.iter().take(10).any(|v| *v == 1));
}
let elapsed = before.elapsed();
println!(
"std linked search first 10 items total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
let before = Instant::now();
for _ in 0..ITEMS {
assert!(!list.iter().take(10).any(|v| *v == 1));
}
let elapsed = before.elapsed();
println!(
"pingora linked search first 10 items total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
let before = Instant::now();
for _ in 0..ITEMS {
assert!(!list.exist_near_head(1, 10));
}
let elapsed = before.elapsed();
println!(
"pingora linked optimized search first 10 items total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
// move node bench
let before = Instant::now();
for _ in 0..ITEMS {
let value = std_list.pop_back().unwrap();
std_list.push_front(value);
}
let elapsed = before.elapsed();
println!(
"std linked list move back to front total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
let before = Instant::now();
for _ in 0..ITEMS {
let index = list.tail().unwrap();
list.promote(index);
}
let elapsed = before.elapsed();
println!(
"pingora linked list move tail to head total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
// pop bench
let before = Instant::now();
for _ in 0..ITEMS {
std_list.pop_back();
}
let elapsed = before.elapsed();
println!(
"std linked list pop_back {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
let before = Instant::now();
for _ in 0..ITEMS {
list.pop_tail();
}
let elapsed = before.elapsed();
println!(
"pingora linked list pop_tail total {elapsed:?}, {:?} avg per operation",
elapsed / ITEMS as u32
);
}
| rust | Apache-2.0 | 5c4bd0bc546b2d9caaff4a438a4cf3d69e5a5094 | 2026-01-04T15:36:50.761692Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/connector-template/test.rs | connector-template/test.rs | use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::{
types::{self, api, storage::enums,
}};
use crate::utils::{self, ConnectorActions};
use test_utils::connector_auth;
#[derive(Clone, Copy)]
struct {{project-name | downcase | pascal_case}}Test;
impl ConnectorActions for {{project-name | downcase | pascal_case}}Test {}
impl utils::Connector for {{project-name | downcase | pascal_case}}Test {
fn get_data(&self) -> api::ConnectorData {
use router::connector::{{project-name | downcase | pascal_case}};
utils::construct_connector_data_old(
Box::new({{project-name | downcase | pascal_case}}::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.{{project-name | downcase}}
.expect("Missing connector authentication configuration").into(),
)
}
fn get_name(&self) -> String {
"{{project-name | downcase}}".to_string()
}
}
static CONNECTOR: {{project-name | downcase | pascal_case}}Test = {{project-name | downcase | pascal_case}}Test {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/connector-template/mod.rs | connector-template/mod.rs | pub mod transformers;
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, Mask};
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
request::{Method, Request, RequestBuilder, RequestContent},
};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData,
PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation, ConnectorSpecifications},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use std::sync::LazyLock;
use common_enums::enums;
use hyperswitch_interfaces::api::ConnectorSpecifications;
use hyperswitch_domain_models::router_response_types::{ConnectorInfo, SupportedPaymentMethods};
use crate::{
constants::headers,
types::ResponseRouterData,
utils,
};
use hyperswitch_domain_models::payment_method_data::PaymentMethodData;
use transformers as {{project-name | downcase}};
#[derive(Clone)]
pub struct {{project-name | downcase | pascal_case}} {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync)
}
impl {{project-name | downcase | pascal_case}} {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector
}
}
}
impl api::Payment for {{project-name | downcase | pascal_case}} {}
impl api::PaymentSession for {{project-name | downcase | pascal_case}} {}
impl api::ConnectorAccessToken for {{project-name | downcase | pascal_case}} {}
impl api::MandateSetup for {{project-name | downcase | pascal_case}} {}
impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {}
impl api::PaymentSync for {{project-name | downcase | pascal_case}} {}
impl api::PaymentCapture for {{project-name | downcase | pascal_case}} {}
impl api::PaymentVoid for {{project-name | downcase | pascal_case}} {}
impl api::Refund for {{project-name | downcase | pascal_case}} {}
impl api::RefundExecute for {{project-name | downcase | pascal_case}} {}
impl api::RefundSync for {{project-name | downcase | pascal_case}} {}
impl api::PaymentToken for {{project-name | downcase | pascal_case}} {}
impl
ConnectorIntegration<
PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for {{project-name | downcase | pascal_case}}
where
Self: ConnectorIntegration<Flow, Request, Response>,{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for {{project-name | downcase | pascal_case}} {
fn id(&self) -> &'static str {
"{{project-name | downcase}}"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
todo!()
// TODO! Check connector documentation, on which unit they are processing the currency.
// If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
// if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.{{project-name}}.base_url.as_ref()
}
fn get_auth_header(&self, auth_type:&ConnectorAuthType)-> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> {
let auth = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}AuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked())])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}ErrorResponse = res
.response
.parse_struct("{{project-name | downcase | pascal_case}}ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for {{project-name | downcase | pascal_case}}
{
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl
ConnectorIntegration<
Session,
PaymentsSessionData,
PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for {{project-name | downcase | pascal_case}}
{
}
impl
ConnectorIntegration<
SetupMandate,
SetupMandateRequestData,
PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
}
impl
ConnectorIntegration<
Authorize,
PaymentsAuthorizeData,
PaymentsResponseData,
> for {{project-name | downcase | pascal_case}} {
fn get_headers(&self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors,) -> CustomResult<Vec<(String, masking::Maskable<String>)>,errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(&self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data =
{{project-name | downcase}}::{{project-name | downcase | pascal_case}}RouterData::from((
amount,
req,
));
let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData,errors::ConnectorError> {
let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("{{project-name | downcase | pascal_case}} PaymentsAuthorizeResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>
for {{project-name | downcase | pascal_case}}
{
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: {{project-name | downcase}}:: {{project-name | downcase | pascal_case}}PaymentsResponse = res
.response
.parse_struct("{{project-name | downcase}} PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
Capture,
PaymentsCaptureData,
PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: {{project-name | downcase }}::{{project-name | downcase | pascal_case}}PaymentsResponse = res
.response
.parse_struct("{{project-name | downcase | pascal_case}} PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
Void,
PaymentsCancelData,
PaymentsResponseData,
> for {{project-name | downcase | pascal_case}}
{}
impl
ConnectorIntegration<
Execute,
RefundsData,
RefundsResponseData,
> for {{project-name | downcase | pascal_case}} {
fn get_headers(&self, req: &RefundsRouterData<Execute>, connectors: &Connectors,) -> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(&self, req: &RefundsRouterData<Execute>, _connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
{{project-name | downcase}}::{{project-name | downcase | pascal_case}}RouterData::from((
refund_amount,
req,
));
let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(&self, req: &RefundsRouterData<Execute>, connectors: &Connectors,) -> CustomResult<Option<Request>,errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(types::RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>,errors::ConnectorError> {
let response: {{project-name| downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for {{project-name | downcase | pascal_case}} {
fn get_headers(&self, req: &RefundSyncRouterData,connectors: &Connectors,) -> CustomResult<Vec<(String, masking::Maskable<String>)>,errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,_connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData,errors::ConnectorError,> {
let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for {{project-name | downcase | pascal_case}} {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static {{project-name | upcase}}_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(SupportedPaymentMethods::new);
static {{project-name | upcase}}_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "{{project-name | downcase | pascal_case}}",
description: "{{project-name | downcase | pascal_case}} connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static {{project-name | upcase}}_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for {{project-name | downcase | pascal_case}} {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&{{project-name | upcase}}_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*{{project-name | upcase}}_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&{{project-name | upcase}}_SUPPORTED_WEBHOOK_FLOWS)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/connector-template/transformers.rs | connector-template/transformers.rs | use common_enums::enums;
use serde::{Deserialize, Serialize};
use masking::Secret;
use common_utils::types::{StringMinorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use crate::types::{RefundsResponseRouterData, ResponseRouterData};
//TODO: Fill the struct with respective fields
pub struct {{project-name | downcase | pascal_case}}RouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T>
From<(
StringMinorUnit,
T,
)> for {{project-name | downcase | pascal_case}}RouterData<T>
{
fn from(
(amount, item): (
StringMinorUnit,
T,
),
) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct {{project-name | downcase | pascal_case}}PaymentsRequest {
amount: StringMinorUnit,
card: {{project-name | downcase | pascal_case}}Card
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct {{project-name | downcase | pascal_case}}Card {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&PaymentsAuthorizeRouterData>> for {{project-name | downcase | pascal_case}}PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&PaymentsAuthorizeRouterData>) -> Result<Self,Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
Err(errors::ConnectorError::NotImplemented("Card payment method not implemented".to_string()).into())
},
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct {{project-name | downcase | pascal_case}}AuthType {
pub(super) api_key: Secret<String>
}
impl TryFrom<&ConnectorAuthType> for {{project-name | downcase | pascal_case}}AuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum {{project-name | downcase | pascal_case}}PaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for common_enums::AttemptStatus {
fn from(item: {{project-name | downcase | pascal_case}}PaymentStatus) -> Self {
match item {
{{project-name | downcase | pascal_case}}PaymentStatus::Succeeded => Self::Charged,
{{project-name | downcase | pascal_case}}PaymentStatus::Failed => Self::Failure,
{{project-name | downcase | pascal_case}}PaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct {{project-name | downcase | pascal_case}}PaymentsResponse {
status: {{project-name | downcase | pascal_case}}PaymentStatus,
id: String,
}
impl<F,T> TryFrom<ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, PaymentsResponseData>) -> Result<Self,Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct {{project-name | downcase | pascal_case}}RefundRequest {
pub amount: StringMinorUnit
}
impl<F> TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&RefundsRouterData<F>>> for {{project-name | downcase | pascal_case}}RefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&RefundsRouterData<F>>) -> Result<Self,Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: RefundsResponseRouterData<RSync, RefundResponse>) -> Result<Self,Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct {{project-name | downcase | pascal_case}}ErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/serde.rs | crates/masking/src/serde.rs | //! Serde-related.
pub use erased_serde::Serialize as ErasedSerialize;
pub use serde::{de, Deserialize, Serialize, Serializer};
use serde_json::{value::Serializer as JsonValueSerializer, Value};
use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret};
/// Marker trait for secret types which can be [`Serialize`]-d by [`serde`].
///
/// When the `serde` feature of this crate is enabled and types are marked with
/// this trait, they receive a [`Serialize` impl] for `Secret<T>`.
/// (NOTE: all types which impl `DeserializeOwned` receive a [`Deserialize`]
/// impl)
///
/// This is done deliberately to prevent accidental exfiltration of secrets
/// via `serde` serialization.
#[cfg_attr(docsrs, cfg(feature = "serde"))]
pub trait SerializableSecret: Serialize {}
// #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
// pub trait NonSerializableSecret: Serialize {}
impl SerializableSecret for Value {}
impl SerializableSecret for u8 {}
impl SerializableSecret for u16 {}
impl SerializableSecret for i8 {}
impl SerializableSecret for i32 {}
impl SerializableSecret for i64 {}
impl SerializableSecret for url::Url {}
#[cfg(feature = "time")]
impl SerializableSecret for time::Date {}
impl<T: SerializableSecret> SerializableSecret for &T {}
impl<'de, T, I> Deserialize<'de> for Secret<T, I>
where
T: Clone + de::DeserializeOwned + Sized,
I: Strategy<T>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
T::deserialize(deserializer).map(Self::new)
}
}
impl<T, I> Serialize for Secret<T, I>
where
T: SerializableSecret + Serialize + Sized,
I: Strategy<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
pii_serializer::pii_serialize(self, serializer)
}
}
impl<'de, T, I> Deserialize<'de> for StrongSecret<T, I>
where
T: Clone + de::DeserializeOwned + Sized + ZeroizableSecret,
I: Strategy<T>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(Self::new)
}
}
impl<T, I> Serialize for StrongSecret<T, I>
where
T: SerializableSecret + Serialize + ZeroizableSecret + Sized,
I: Strategy<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
pii_serializer::pii_serialize(self, serializer)
}
}
/// Masked serialization.
///
/// the default behaviour for secrets is to serialize in exposed format since the common use cases
/// for storing the secret to database or sending it over the network requires the secret to be exposed
/// This method allows to serialize the secret in masked format if needed for logs or other insecure exposures
pub fn masked_serialize<T: Serialize>(value: &T) -> Result<Value, serde_json::Error> {
value.serialize(PIISerializer {
inner: JsonValueSerializer,
})
}
/// Masked serialization.
///
/// Trait object for supporting serialization to Value while accounting for masking
/// The usual Serde Serialize trait cannot be used as trait objects
/// like &dyn Serialize or boxed trait objects like Box<dyn Serialize> because of Rust's "object safety" rules.
/// In particular, the trait contains generic methods which cannot be made into a trait object.
/// In this case we remove the generic for assuming the serialization to be of 2 types only raw json or masked json
pub trait ErasedMaskSerialize: ErasedSerialize {
/// Masked serialization.
fn masked_serialize(&self) -> Result<Value, serde_json::Error>;
}
impl<T: Serialize + ErasedSerialize> ErasedMaskSerialize for T {
fn masked_serialize(&self) -> Result<Value, serde_json::Error> {
masked_serialize(self)
}
}
impl Serialize for dyn ErasedMaskSerialize + '_ {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
erased_serde::serialize(self, serializer)
}
}
impl Serialize for dyn ErasedMaskSerialize + '_ + Send {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
erased_serde::serialize(self, serializer)
}
}
use pii_serializer::PIISerializer;
mod pii_serializer {
use std::fmt::Display;
pub(super) fn pii_serialize<
V: Serialize,
T: std::fmt::Debug + PeekInterface<V>,
S: Serializer,
>(
value: &T,
serializer: S,
) -> Result<S::Ok, S::Error> {
// Mask the value if the serializer is of type PIISerializer
// or send empty map if the serializer is of type FlatMapSerializer over PiiSerializer
if std::any::type_name::<S>() == std::any::type_name::<PIISerializer>() {
format!("{value:?}").serialize(serializer)
} else if std::any::type_name::<S>()
== std::any::type_name::<
serde::__private::ser::FlatMapSerializer<'_, SerializeMap<PIISerializer>>,
>()
{
std::collections::HashMap::<String, String>::from([]).serialize(serializer)
} else {
value.peek().serialize(serializer)
}
}
use serde::{Serialize, Serializer};
use serde_json::{value::Serializer as JsonValueSerializer, Map, Value};
use crate::PeekInterface;
pub(super) struct PIISerializer {
pub inner: JsonValueSerializer,
}
impl Clone for PIISerializer {
fn clone(&self) -> Self {
Self {
inner: JsonValueSerializer,
}
}
}
impl Serializer for PIISerializer {
type Ok = Value;
type Error = serde_json::Error;
type SerializeSeq = SerializeVec<Self>;
type SerializeTuple = SerializeVec<Self>;
type SerializeTupleStruct = SerializeVec<Self>;
type SerializeTupleVariant = SerializeTupleVariant<Self>;
type SerializeMap = SerializeMap<Self>;
type SerializeStruct = SerializeMap<Self>;
type SerializeStructVariant = SerializeStructVariant<Self>;
#[inline]
fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_bool(value)
}
#[inline]
fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(value.into())
}
#[inline]
fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(value.into())
}
#[inline]
fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(value.into())
}
fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_i64(value)
}
fn serialize_i128(self, value: i128) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_i128(value)
}
#[inline]
fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(value.into())
}
#[inline]
fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(value.into())
}
#[inline]
fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(value.into())
}
#[inline]
fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
Ok(Value::Number(value.into()))
}
fn serialize_u128(self, value: u128) -> Result<Self::Ok, Self::Error> {
self.inner.serialize_u128(value)
}
#[inline]
fn serialize_f32(self, float: f32) -> Result<Self::Ok, Self::Error> {
Ok(Value::from(float))
}
#[inline]
fn serialize_f64(self, float: f64) -> Result<Self::Ok, Self::Error> {
Ok(Value::from(float))
}
#[inline]
fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> {
let mut s = String::new();
s.push(value);
Ok(Value::String(s))
}
#[inline]
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
Ok(Value::String(value.to_owned()))
}
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
let vec = value.iter().map(|&b| Value::Number(b.into())).collect();
Ok(Value::Array(vec))
}
#[inline]
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::Null)
}
#[inline]
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
#[inline]
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
self.serialize_str(variant)
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
let mut values = Map::new();
values.insert(String::from(variant), value.serialize(self)?);
Ok(Value::Object(values))
}
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Ok(SerializeVec {
vec: Vec::with_capacity(len.unwrap_or(0)),
ser: self,
})
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Ok(SerializeTupleVariant {
name: String::from(variant),
vec: Vec::with_capacity(len),
ser: self,
})
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Ok(SerializeMap {
inner: self.clone().inner.serialize_map(len)?,
ser: self,
})
}
fn serialize_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
self.serialize_map(Some(len))
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Ok(SerializeStructVariant {
name: String::from(variant),
map: Map::new(),
ser: self,
})
}
fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Display,
{
self.inner.collect_str(value)
}
}
pub(super) struct SerializeVec<T: Serializer> {
vec: Vec<Value>,
ser: T,
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeSeq for SerializeVec<T> {
type Ok = Value;
type Error = T::Error;
fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.vec.push(value.serialize(self.ser.clone())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::Array(self.vec))
}
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTuple for SerializeVec<T> {
type Ok = Value;
type Error = T::Error;
fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
serde::ser::SerializeSeq::end(self)
}
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleStruct for SerializeVec<T> {
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
serde::ser::SerializeSeq::end(self)
}
}
pub(super) struct SerializeStructVariant<T: Serializer> {
name: String,
map: Map<String, Value>,
ser: T,
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeStructVariant
for SerializeStructVariant<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.map
.insert(String::from(key), value.serialize(self.ser.clone())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
let mut object = Map::new();
object.insert(self.name, Value::Object(self.map));
Ok(Value::Object(object))
}
}
pub(super) struct SerializeTupleVariant<T: Serializer> {
name: String,
vec: Vec<Value>,
ser: T,
}
impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleVariant
for SerializeTupleVariant<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.vec.push(value.serialize(self.ser.clone())?);
Ok(())
}
fn end(self) -> Result<Value, Self::Error> {
let mut object = Map::new();
object.insert(self.name, Value::Array(self.vec));
Ok(Value::Object(object))
}
}
pub(super) struct SerializeMap<T: Serializer> {
inner: <serde_json::value::Serializer as Serializer>::SerializeMap,
ser: T,
}
impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeMap
for SerializeMap<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_key<V>(&mut self, key: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
self.inner.serialize_key(key)?;
Ok(())
}
fn serialize_value<V>(&mut self, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
let value = value.serialize(self.ser.clone())?;
self.inner.serialize_value(&value)?;
Ok(())
}
fn end(self) -> Result<Value, Self::Error> {
self.inner.end()
}
}
impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeStruct
for SerializeMap<T>
{
type Ok = Value;
type Error = T::Error;
fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error>
where
V: ?Sized + Serialize,
{
serde::ser::SerializeMap::serialize_entry(self, key, value)
}
fn end(self) -> Result<Value, Self::Error> {
serde::ser::SerializeMap::end(self)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/bytes.rs | crates/masking/src/bytes.rs | //! Optional `Secret` wrapper type for the `bytes::BytesMut` crate.
use core::fmt;
use bytes::BytesMut;
#[cfg(all(feature = "bytes", feature = "serde"))]
use serde::de::{self, Deserialize};
use super::{PeekInterface, ZeroizableSecret};
/// Instance of [`BytesMut`] protected by a type that impls the [`ExposeInterface`]
/// trait like `Secret<T>`.
///
/// Because of the nature of how the `BytesMut` type works, it needs some special
/// care in order to have a proper zeroizing drop handler.
#[derive(Clone)]
#[cfg_attr(docsrs, cfg(feature = "bytes"))]
pub struct SecretBytesMut(BytesMut);
impl SecretBytesMut {
/// Wrap bytes in `SecretBytesMut`
pub fn new(bytes: impl Into<BytesMut>) -> Self {
Self(bytes.into())
}
}
impl PeekInterface<BytesMut> for SecretBytesMut {
fn peek(&self) -> &BytesMut {
&self.0
}
fn peek_mut(&mut self) -> &mut BytesMut {
&mut self.0
}
}
impl fmt::Debug for SecretBytesMut {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SecretBytesMut([REDACTED])")
}
}
impl From<BytesMut> for SecretBytesMut {
fn from(bytes: BytesMut) -> Self {
Self::new(bytes)
}
}
impl Drop for SecretBytesMut {
fn drop(&mut self) {
self.0.resize(self.0.capacity(), 0);
self.0.as_mut().zeroize();
debug_assert!(self.0.as_ref().iter().all(|b| *b == 0));
}
}
#[cfg(all(feature = "bytes", feature = "serde"))]
impl<'de> Deserialize<'de> for SecretBytesMut {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct SecretBytesVisitor;
impl<'de> de::Visitor<'de> for SecretBytesVisitor {
type Value = SecretBytesMut;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("byte array")
}
#[inline]
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
let mut bytes = BytesMut::with_capacity(v.len());
bytes.extend_from_slice(v);
Ok(SecretBytesMut(bytes))
}
#[inline]
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: de::SeqAccess<'de>,
{
// 4096 is cargo culted from upstream
let len = core::cmp::min(seq.size_hint().unwrap_or(0), 4096);
let mut bytes = BytesMut::with_capacity(len);
use bytes::BufMut;
while let Some(value) = seq.next_element()? {
bytes.put_u8(value);
}
Ok(SecretBytesMut(bytes))
}
}
deserializer.deserialize_bytes(SecretBytesVisitor)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/vec.rs | crates/masking/src/vec.rs | //! Secret `Vec` types
//!
//! There is not alias type by design.
#[cfg(feature = "serde")]
use super::{SerializableSecret, Serialize};
#[cfg(feature = "serde")]
impl<S: Serialize> SerializableSecret for Vec<S> {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/lib.rs | crates/masking/src/lib.rs | #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
#![warn(missing_docs)]
//! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped.
//! Secret-keeping library inspired by secrecy.
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
pub use zeroize::{self, DefaultIsZeroes, Zeroize as ZeroizableSecret};
mod strategy;
pub use strategy::{Strategy, WithType, WithoutType};
mod abs;
pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrategy};
mod secret;
mod strong_secret;
#[cfg(feature = "serde")]
pub use secret::JsonMaskStrategy;
pub use secret::Secret;
pub use strong_secret::StrongSecret;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
mod boxed;
#[cfg(feature = "bytes")]
mod bytes;
#[cfg(feature = "bytes")]
pub use self::bytes::SecretBytesMut;
#[cfg(feature = "alloc")]
mod string;
#[cfg(feature = "alloc")]
mod vec;
#[cfg(feature = "serde")]
mod serde;
#[cfg(feature = "serde")]
pub use crate::serde::{
masked_serialize, Deserialize, ErasedMaskSerialize, SerializableSecret, Serialize,
};
/// This module should be included with asterisk.
///
/// `use masking::prelude::*;`
pub mod prelude {
pub use super::{ExposeInterface, ExposeOptionInterface, PeekInterface};
}
#[cfg(feature = "diesel")]
mod diesel;
#[cfg(feature = "cassandra")]
mod cassandra;
pub mod maskable;
pub use maskable::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/abs.rs | crates/masking/src/abs.rs | //! Abstract data types.
use crate::Secret;
/// Interface to expose a reference to an inner secret
pub trait PeekInterface<S> {
/// Only method providing access to the secret value.
fn peek(&self) -> &S;
/// Provide a mutable reference to the inner value.
fn peek_mut(&mut self) -> &mut S;
}
/// Interface that consumes a option secret and returns the value.
pub trait ExposeOptionInterface<S> {
/// Expose option.
fn expose_option(self) -> S;
}
/// Interface that consumes a secret and returns the inner value.
pub trait ExposeInterface<S> {
/// Consume the secret and return the inner value
fn expose(self) -> S;
}
impl<S, I> ExposeOptionInterface<Option<S>> for Option<Secret<S, I>>
where
S: Clone,
I: crate::Strategy<S>,
{
fn expose_option(self) -> Option<S> {
self.map(ExposeInterface::expose)
}
}
impl<S, I> ExposeInterface<S> for Secret<S, I>
where
I: crate::Strategy<S>,
{
fn expose(self) -> S {
self.inner_secret
}
}
/// Interface that consumes a secret and converts it to a secret with a different masking strategy.
pub trait SwitchStrategy<FromStrategy, ToStrategy> {
/// The type returned by `switch_strategy()`.
type Output;
/// Consumes the secret and converts it to a secret with a different masking strategy.
fn switch_strategy(self) -> Self::Output;
}
impl<S, FromStrategy, ToStrategy> SwitchStrategy<FromStrategy, ToStrategy>
for Secret<S, FromStrategy>
where
FromStrategy: crate::Strategy<S>,
ToStrategy: crate::Strategy<S>,
{
type Output = Secret<S, ToStrategy>;
fn switch_strategy(self) -> Self::Output {
Secret::new(self.inner_secret)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/string.rs | crates/masking/src/string.rs | //! Secret strings
//!
//! There is not alias type by design.
use alloc::{
str::FromStr,
string::{String, ToString},
};
#[cfg(feature = "serde")]
use super::SerializableSecret;
use super::{Secret, Strategy};
use crate::StrongSecret;
#[cfg(feature = "serde")]
impl SerializableSecret for String {}
impl<I> FromStr for Secret<String, I>
where
I: Strategy<String>,
{
type Err = core::convert::Infallible;
fn from_str(src: &str) -> Result<Self, Self::Err> {
Ok(Self::new(src.to_string()))
}
}
impl<I> FromStr for StrongSecret<String, I>
where
I: Strategy<String>,
{
type Err = core::convert::Infallible;
fn from_str(src: &str) -> Result<Self, Self::Err> {
Ok(Self::new(src.to_string()))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/cassandra.rs | crates/masking/src/cassandra.rs | use scylla::{
deserialize::DeserializeValue,
frame::response::result::ColumnType,
serialize::{
value::SerializeValue,
writers::{CellWriter, WrittenCellProof},
SerializationError,
},
};
use crate::{abs::PeekInterface, StrongSecret};
impl<T> SerializeValue for StrongSecret<T>
where
T: SerializeValue + zeroize::Zeroize + Clone,
{
fn serialize<'b>(
&self,
column_type: &ColumnType<'_>,
writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
self.peek().serialize(column_type, writer)
}
}
impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for StrongSecret<T>
where
T: DeserializeValue<'frame, 'metadata> + zeroize::Zeroize + Clone,
{
fn type_check(column_type: &ColumnType<'_>) -> Result<(), scylla::deserialize::TypeCheckError> {
T::type_check(column_type)
}
fn deserialize(
column_type: &'metadata ColumnType<'metadata>,
v: Option<scylla::deserialize::FrameSlice<'frame>>,
) -> Result<Self, scylla::deserialize::DeserializationError> {
Ok(Self::new(T::deserialize(column_type, v)?))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/maskable.rs | crates/masking/src/maskable.rs | //! This module contains Masking objects and traits
use crate::{ExposeInterface, Secret};
/// An Enum that allows us to optionally mask data, based on which enum variant that data is stored
/// in.
#[derive(Clone, Eq, PartialEq)]
pub enum Maskable<T: Eq + PartialEq + Clone> {
/// Variant which masks the data by wrapping in a Secret
Masked(Secret<T>),
/// Varant which doesn't mask the data
Normal(T),
}
impl<T: std::fmt::Debug + Clone + Eq + PartialEq> std::fmt::Debug for Maskable<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Masked(secret_value) => std::fmt::Debug::fmt(secret_value, f),
Self::Normal(value) => std::fmt::Debug::fmt(value, f),
}
}
}
impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Self::Masked(value) => crate::PeekInterface::peek(value).hash(state),
Self::Normal(value) => value.hash(state),
}
}
}
impl<T: Eq + PartialEq + Clone> Maskable<T> {
/// Get the inner data while consuming self
pub fn into_inner(self) -> T {
match self {
Self::Masked(inner_secret) => inner_secret.expose(),
Self::Normal(inner) => inner,
}
}
/// Create a new Masked data
pub fn new_masked(item: Secret<T>) -> Self {
Self::Masked(item)
}
/// Create a new non-masked data
pub fn new_normal(item: T) -> Self {
Self::Normal(item)
}
/// Checks whether the data is masked.
/// Returns `true` if the data is wrapped in the `Masked` variant,
/// returns `false` otherwise.
pub fn is_masked(&self) -> bool {
matches!(self, Self::Masked(_))
}
/// Checks whether the data is normal (not masked).
/// Returns `true` if the data is wrapped in the `Normal` variant,
/// returns `false` otherwise.
pub fn is_normal(&self) -> bool {
matches!(self, Self::Normal(_))
}
}
/// Trait for providing a method on custom types for constructing `Maskable`
pub trait Mask {
/// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone`
type Output: Eq + Clone + PartialEq;
/// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self`
fn into_masked(self) -> Maskable<Self::Output>;
}
impl Mask for String {
type Output = Self;
fn into_masked(self) -> Maskable<Self::Output> {
Maskable::new_masked(self.into())
}
}
impl Mask for Secret<String> {
type Output = String;
fn into_masked(self) -> Maskable<Self::Output> {
Maskable::new_masked(self)
}
}
impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> {
fn from(value: T) -> Self {
Self::new_normal(value)
}
}
impl From<&str> for Maskable<String> {
fn from(value: &str) -> Self {
Self::new_normal(value.to_string())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/secret.rs | crates/masking/src/secret.rs | //! Structure describing secret.
use std::{fmt, marker::PhantomData};
use crate::{strategy::Strategy, PeekInterface, StrongSecret};
/// Secret thing.
///
/// To get access to value use method `expose()` of trait [`crate::ExposeInterface`].
///
/// ## Masking
/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a zero-variant
/// enum and pass this enum as a second generic parameter to [`Secret`] while defining it.
/// [`Secret`] will take care of applying the masking strategy on the inner secret when being
/// displayed.
///
/// ## Masking Example
///
/// ```
/// use masking::Strategy;
/// use masking::Secret;
/// use std::fmt;
///
/// enum MyStrategy {}
///
/// impl<T> Strategy<T> for MyStrategy
/// where
/// T: fmt::Display
/// {
/// fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "{}", val.to_string().to_ascii_lowercase())
/// }
/// }
///
/// let my_secret: Secret<String, MyStrategy> = Secret::new("HELLO".to_string());
///
/// assert_eq!("hello", &format!("{:?}", my_secret));
/// ```
pub struct Secret<Secret, MaskingStrategy = crate::WithType>
where
MaskingStrategy: Strategy<Secret>,
{
pub(crate) inner_secret: Secret,
pub(crate) masking_strategy: PhantomData<MaskingStrategy>,
}
impl<SecretValue, MaskingStrategy> Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
/// Take ownership of a secret value
pub fn new(secret: SecretValue) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
/// Zip 2 secrets with the same masking strategy into one
pub fn zip<OtherSecretValue>(
self,
other: Secret<OtherSecretValue, MaskingStrategy>,
) -> Secret<(SecretValue, OtherSecretValue), MaskingStrategy>
where
MaskingStrategy: Strategy<OtherSecretValue> + Strategy<(SecretValue, OtherSecretValue)>,
{
(self.inner_secret, other.inner_secret).into()
}
/// consume self and modify the inner value
pub fn map<OtherSecretValue>(
self,
f: impl FnOnce(SecretValue) -> OtherSecretValue,
) -> Secret<OtherSecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<OtherSecretValue>,
{
f(self.inner_secret).into()
}
/// Convert to [`StrongSecret`]
pub fn into_strong(self) -> StrongSecret<SecretValue, MaskingStrategy>
where
SecretValue: zeroize::DefaultIsZeroes,
{
StrongSecret::new(self.inner_secret)
}
/// Convert to [`Secret`] with a reference to the inner secret
pub fn as_ref(&self) -> Secret<&SecretValue, MaskingStrategy>
where
MaskingStrategy: for<'a> Strategy<&'a SecretValue>,
{
Secret::new(self.peek())
}
}
impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue>
for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn peek(&self) -> &SecretValue {
&self.inner_secret
}
fn peek_mut(&mut self) -> &mut SecretValue {
&mut self.inner_secret
}
}
impl<SecretValue, MaskingStrategy> From<SecretValue> for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn from(secret: SecretValue) -> Self {
Self::new(secret)
}
}
impl<SecretValue, MaskingStrategy> Clone for Secret<SecretValue, MaskingStrategy>
where
SecretValue: Clone,
MaskingStrategy: Strategy<SecretValue>,
{
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
}
impl<SecretValue, MaskingStrategy> PartialEq for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: PartialEq,
MaskingStrategy: Strategy<SecretValue>,
{
fn eq(&self, other: &Self) -> bool {
self.peek().eq(other.peek())
}
}
impl<SecretValue, MaskingStrategy> Eq for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: Eq,
MaskingStrategy: Strategy<SecretValue>,
{
}
impl<SecretValue, MaskingStrategy> std::hash::Hash for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: std::hash::Hash,
MaskingStrategy: Strategy<SecretValue>,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.peek().hash(state);
}
}
impl<SecretValue, MaskingStrategy> fmt::Debug for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<SecretValue, MaskingStrategy> Default for Secret<SecretValue, MaskingStrategy>
where
SecretValue: Default,
MaskingStrategy: Strategy<SecretValue>,
{
fn default() -> Self {
SecretValue::default().into()
}
}
// Required by base64-serde to serialize Secret of Vec<u8> which contains the base64 decoded value
impl AsRef<[u8]> for Secret<Vec<u8>> {
fn as_ref(&self) -> &[u8] {
self.peek().as_slice()
}
}
/// Strategy for masking JSON values
#[cfg(feature = "serde")]
pub enum JsonMaskStrategy {}
#[cfg(feature = "serde")]
impl Strategy<serde_json::Value> for JsonMaskStrategy {
fn fmt(value: &serde_json::Value, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match value {
serde_json::Value::Object(map) => {
write!(f, "{{")?;
let mut first = true;
for (key, val) in map {
if !first {
write!(f, ", ")?;
}
first = false;
write!(f, "\"{key}\":")?;
Self::fmt(val, f)?;
}
write!(f, "}}")
}
serde_json::Value::Array(arr) => {
write!(f, "[")?;
let mut first = true;
for val in arr {
if !first {
write!(f, ", ")?;
}
first = false;
Self::fmt(val, f)?;
}
write!(f, "]")
}
serde_json::Value::String(s) => {
// For strings, we show a masked version that gives a hint about the content
// String::chars().count() is an approximation and could be greater than
// the actual "character" count, since it does not consider graphemes (what we
// usually consider as a "character"). To be more accurate at the cost of some
// performance we can use "graphemes()" from the unicode-segmentation crate
let char_count = s.chars().count();
let masked = if char_count <= 2 {
"**".to_string()
} else if char_count <= 6 {
let first = s.chars().next().unwrap_or('*');
format!("{first}**")
} else {
// For longer strings, show first and last character with length in between
let first = s.chars().next().unwrap_or('*');
let last = s.chars().last().unwrap_or('*');
format!("{first}**{count}**{last}", count = char_count - 2)
};
write!(f, "\"{masked}\"")
}
serde_json::Value::Number(n) => {
// For numbers, we can show the order of magnitude
if n.is_i64() || n.is_u64() {
let num_str = n.to_string();
let masked_num = "*".repeat(num_str.len());
write!(f, "{masked_num}")
} else if n.is_f64() {
// For floats, just use a generic mask
write!(f, "**.**")
} else {
write!(f, "0")
}
}
serde_json::Value::Bool(b) => {
// For booleans, we can show a hint about which one it is
write!(f, "{}", if *b { "**true" } else { "**false" })
}
serde_json::Value::Null => write!(f, "null"),
}
}
}
#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for Secret<T, crate::WithType>
where
T: prost::Message + Default + Clone,
{
fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
self.peek().encode_raw(buf);
}
fn merge_field(
&mut self,
tag: u32,
wire_type: prost::encoding::WireType,
buf: &mut impl bytes::Buf,
ctx: prost::encoding::DecodeContext,
) -> Result<(), prost::DecodeError> {
if tag == 1 {
self.peek_mut().merge_field(tag, wire_type, buf, ctx)
} else {
prost::encoding::skip_field(wire_type, tag, buf, ctx)
}
}
fn encoded_len(&self) -> usize {
self.peek().encoded_len()
}
fn clear(&mut self) {
self.peek_mut().clear();
}
}
#[cfg(test)]
mod hash_tests {
use std::hash::{DefaultHasher, Hash, Hasher};
use super::*;
#[test]
fn test_secret_hash_implementation() {
let secret1: Secret<String> = Secret::new("test_string".to_string());
let secret2: Secret<String> = Secret::new("test_string".to_string());
let secret3: Secret<String> = Secret::new("different_string".to_string());
// Test that equal secrets hash to the same value
let mut hasher1 = DefaultHasher::new();
let mut hasher2 = DefaultHasher::new();
secret1.hash(&mut hasher1);
secret2.hash(&mut hasher2);
assert_eq!(hasher1.finish(), hasher2.finish());
// Test that different secrets hash to different values (usually)
let mut hasher3 = DefaultHasher::new();
secret3.hash(&mut hasher3);
assert_ne!(hasher1.finish(), hasher3.finish());
}
}
#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn test_json_mask_strategy() {
// Create a sample JSON with different types for testing
let original = json!({ "user": { "name": "John Doe", "email": "john@example.com", "age": 35, "verified": true }, "card": { "number": "4242424242424242", "cvv": 123, "amount": 99.99 }, "tags": ["personal", "premium"], "null_value": null, "short": "hi" });
// Apply the JsonMaskStrategy
let secret = Secret::<_, JsonMaskStrategy>::new(original.clone());
let masked_str = format!("{secret:?}");
// Get specific values from original
let original_obj = original.as_object().expect("Original should be an object");
let user_obj = original_obj["user"]
.as_object()
.expect("User should be an object");
let name = user_obj["name"].as_str().expect("Name should be a string");
let email = user_obj["email"]
.as_str()
.expect("Email should be a string");
let age = user_obj["age"].as_i64().expect("Age should be a number");
let verified = user_obj["verified"]
.as_bool()
.expect("Verified should be a boolean");
let card_obj = original_obj["card"]
.as_object()
.expect("Card should be an object");
let card_number = card_obj["number"]
.as_str()
.expect("Card number should be a string");
let cvv = card_obj["cvv"].as_i64().expect("CVV should be a number");
let tags = original_obj["tags"]
.as_array()
.expect("Tags should be an array");
let tag1 = tags
.first()
.and_then(|v| v.as_str())
.expect("First tag should be a string");
// Now explicitly verify the masking patterns for each value type
// 1. String masking - pattern: first char + ** + length - 2 + ** + last char
let expected_name_mask = format!(
"\"{}**{}**{}\"",
name.chars().next().unwrap(),
name.chars().count() - 2,
name.chars().last().unwrap()
);
let expected_email_mask = format!(
"\"{}**{}**{}\"",
email.chars().next().unwrap(),
email.chars().count() - 2,
email.chars().last().unwrap()
);
let expected_card_mask = format!(
"\"{}**{}**{}\"",
card_number.chars().next().unwrap(),
card_number.chars().count() - 2,
card_number.chars().last().unwrap()
);
let expected_tag1_mask = if tag1.chars().count() <= 2 {
"\"**\"".to_string()
} else if tag1.chars().count() <= 6 {
format!("\"{}**\"", &tag1.chars().next().unwrap())
} else {
format!(
"\"{}**{}**{}\"",
tag1.chars().next().unwrap(),
tag1.chars().count() - 2,
tag1.chars().last().unwrap()
)
};
let expected_short_mask = "\"**\"".to_string(); // For "hi"
// 2. Number masking
let expected_age_mask = "*".repeat(age.to_string().len()); // Repeat * for the number of digits
let expected_cvv_mask = "*".repeat(cvv.to_string().len());
// 3. Boolean masking
let expected_verified_mask = if verified { "**true" } else { "**false" };
// Check that the masked output includes the expected masked patterns
assert!(
masked_str.contains(&expected_name_mask),
"Name not masked correctly. Expected: {expected_name_mask}"
);
assert!(
masked_str.contains(&expected_email_mask),
"Email not masked correctly. Expected: {expected_email_mask}",
);
assert!(
masked_str.contains(&expected_card_mask),
"Card number not masked correctly. Expected: {expected_card_mask}",
);
assert!(
masked_str.contains(&expected_tag1_mask),
"Tag not masked correctly. Expected: {expected_tag1_mask}",
);
assert!(
masked_str.contains(&expected_short_mask),
"Short string not masked correctly. Expected: {expected_short_mask}",
);
assert!(
masked_str.contains(&expected_age_mask),
"Age not masked correctly. Expected: {expected_age_mask}",
);
assert!(
masked_str.contains(&expected_cvv_mask),
"CVV not masked correctly. Expected: {expected_cvv_mask}",
);
assert!(
masked_str.contains(expected_verified_mask),
"Boolean not masked correctly. Expected: {expected_verified_mask}",
);
// Check structure preservation
assert!(
masked_str.contains("\"user\""),
"Structure not preserved - missing user object"
);
assert!(
masked_str.contains("\"card\""),
"Structure not preserved - missing card object"
);
assert!(
masked_str.contains("\"tags\""),
"Structure not preserved - missing tags array"
);
assert!(
masked_str.contains("\"null_value\":null"),
"Null value not preserved correctly"
);
// Additional security checks to ensure no original values are exposed
assert!(
!masked_str.contains(name),
"Original name value exposed in masked output"
);
assert!(
!masked_str.contains(email),
"Original email value exposed in masked output"
);
assert!(
!masked_str.contains(card_number),
"Original card number exposed in masked output"
);
assert!(
!masked_str.contains(&age.to_string()),
"Original age value exposed in masked output"
);
assert!(
!masked_str.contains(&cvv.to_string()),
"Original CVV value exposed in masked output"
);
assert!(
!masked_str.contains(tag1),
"Original tag value exposed in masked output"
);
assert!(
!masked_str.contains("hi"),
"Original short string value exposed in masked output"
);
}
#[test]
fn test_unicode_masking_safety() {
// This test ensures that masking does not panic on multi-byte unicode characters,
// and that the output is as expected.
let unicode_test_cases = vec![
("ü", r#""**""#), // 1 char <= 2
("😀", r#""**""#), // 1 char <= 2
("überspringen", r#""ü**10**n""#), // 12 chars > 6
("end with ü", r#""e**8**ü""#), // 10 chars > 6
("😀-a-long-string-with-emoji-😀", r#""😀**26**😀""#), // 28 chars > 6
("a", r#""**""#), // 1 char <= 2
("ab", r#""**""#), // 2 chars <= 2
("abc", r#""a**""#), // 3 chars <= 6
("abcdef", r#""a**""#), // 6 chars <= 6
("abcdefg", r#""a**5**g""#), // 7 chars > 6
("Homyel’ Voblasc’", r#""H**14**’""#),
("кпукпукп", r#""к**6**п""#),
];
for (input, expected_mask) in unicode_test_cases {
let json = json!({ "key": input });
let secret = Secret::<_, JsonMaskStrategy>::new(json);
let masked_str = format!("{secret:?}");
let expected_output = format!(r#"{{"key":{}}}"#, expected_mask);
assert_eq!(masked_str, expected_output, "Failed for input: '{}'", input);
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/strategy.rs | crates/masking/src/strategy.rs | use core::fmt;
/// Debugging trait which is specialized for handling secret values
pub trait Strategy<T> {
/// Format information about the secret's type.
fn fmt(value: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
}
/// Debug with type
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WithType {}
impl<T> Strategy<T> for WithType {
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ")?;
fmt.write_str(std::any::type_name::<T>())?;
fmt.write_str(" ***")
}
}
/// Debug without type
pub enum WithoutType {}
impl<T> Strategy<T> for WithoutType {
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ***")
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/boxed.rs | crates/masking/src/boxed.rs | //! `Box` types containing secrets
//!
//! There is not alias type by design.
#[cfg(feature = "serde")]
use super::{SerializableSecret, Serialize};
#[cfg(feature = "serde")]
impl<S: Serialize> SerializableSecret for Box<S> {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/diesel.rs | crates/masking/src/diesel.rs | //! Diesel-related.
use diesel::{
backend::Backend,
deserialize::{self, FromSql, Queryable},
expression::AsExpression,
internal::derives::as_expression::Bound,
serialize::{self, Output, ToSql},
sql_types,
};
use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret};
impl<S, I, T> AsExpression<T> for &Secret<S, I>
where
T: sql_types::SingleValue,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, T> AsExpression<T> for &&Secret<S, I>
where
T: sql_types::SingleValue,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, T, DB> ToSql<T, DB> for Secret<S, I>
where
DB: Backend,
S: ToSql<T, DB>,
I: Strategy<S>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
ToSql::<T, DB>::to_sql(&self.inner_secret, out)
}
}
impl<DB, S, T, I> FromSql<T, DB> for Secret<S, I>
where
DB: Backend,
S: FromSql<T, DB>,
I: Strategy<S>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
S::from_sql(bytes).map(|raw| raw.into())
}
}
impl<S, I, T> AsExpression<T> for Secret<S, I>
where
T: sql_types::SingleValue,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<ST, DB, S, I> Queryable<ST, DB> for Secret<S, I>
where
DB: Backend,
I: Strategy<S>,
ST: sql_types::SingleValue,
Self: FromSql<ST, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<S, I, T> AsExpression<T> for &StrongSecret<S, I>
where
T: sql_types::SingleValue,
S: ZeroizableSecret,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, T> AsExpression<T> for &&StrongSecret<S, I>
where
T: sql_types::SingleValue,
S: ZeroizableSecret,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<S, I, DB, T> ToSql<T, DB> for StrongSecret<S, I>
where
DB: Backend,
S: ToSql<T, DB> + ZeroizableSecret,
I: Strategy<S>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
ToSql::<T, DB>::to_sql(&self.inner_secret, out)
}
}
impl<DB, S, I, T> FromSql<T, DB> for StrongSecret<S, I>
where
DB: Backend,
S: FromSql<T, DB> + ZeroizableSecret,
I: Strategy<S>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
S::from_sql(bytes).map(|raw| raw.into())
}
}
impl<S, I, T> AsExpression<T> for StrongSecret<S, I>
where
T: sql_types::SingleValue,
S: ZeroizableSecret,
I: Strategy<S>,
{
type Expression = Bound<T, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
impl<ST, DB, S, I> Queryable<ST, DB> for StrongSecret<S, I>
where
I: Strategy<S>,
DB: Backend,
S: ZeroizableSecret,
ST: sql_types::SingleValue,
Self: FromSql<ST, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/src/strong_secret.rs | crates/masking/src/strong_secret.rs | //! Structure describing secret.
use std::{fmt, marker::PhantomData};
use subtle::ConstantTimeEq;
use zeroize::{self, Zeroize as ZeroizableSecret};
use crate::{strategy::Strategy, PeekInterface};
/// Secret thing.
///
/// To get access to value use method `expose()` of trait [`crate::ExposeInterface`].
pub struct StrongSecret<Secret: ZeroizableSecret, MaskingStrategy = crate::WithType> {
/// Inner secret value
pub(crate) inner_secret: Secret,
pub(crate) masking_strategy: PhantomData<MaskingStrategy>,
}
impl<Secret: ZeroizableSecret, MaskingStrategy> StrongSecret<Secret, MaskingStrategy> {
/// Take ownership of a secret value
pub fn new(secret: Secret) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> PeekInterface<Secret>
for StrongSecret<Secret, MaskingStrategy>
{
fn peek(&self) -> &Secret {
&self.inner_secret
}
fn peek_mut(&mut self) -> &mut Secret {
&mut self.inner_secret
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> From<Secret>
for StrongSecret<Secret, MaskingStrategy>
{
fn from(secret: Secret) -> Self {
Self::new(secret)
}
}
impl<Secret: Clone + ZeroizableSecret, MaskingStrategy> Clone
for StrongSecret<Secret, MaskingStrategy>
{
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
}
impl<Secret, MaskingStrategy> PartialEq for StrongSecret<Secret, MaskingStrategy>
where
Self: PeekInterface<Secret>,
Secret: ZeroizableSecret + StrongEq,
{
fn eq(&self, other: &Self) -> bool {
StrongEq::strong_eq(self.peek(), other.peek())
}
}
impl<Secret, MaskingStrategy> Eq for StrongSecret<Secret, MaskingStrategy>
where
Self: PeekInterface<Secret>,
Secret: ZeroizableSecret + StrongEq,
{
}
impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Debug
for StrongSecret<Secret, MaskingStrategy>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Display
for StrongSecret<Secret, MaskingStrategy>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> Default for StrongSecret<Secret, MaskingStrategy>
where
Secret: ZeroizableSecret + Default,
{
fn default() -> Self {
Secret::default().into()
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> Drop for StrongSecret<Secret, MaskingStrategy> {
fn drop(&mut self) {
self.inner_secret.zeroize();
}
}
trait StrongEq {
fn strong_eq(&self, other: &Self) -> bool;
}
impl StrongEq for String {
fn strong_eq(&self, other: &Self) -> bool {
let lhs = self.as_bytes();
let rhs = other.as_bytes();
bool::from(lhs.ct_eq(rhs))
}
}
impl StrongEq for Vec<u8> {
fn strong_eq(&self, other: &Self) -> bool {
let lhs = &self;
let rhs = &other;
bool::from(lhs.ct_eq(rhs))
}
}
#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for StrongSecret<T, crate::WithType>
where
T: prost::Message + Default + Clone + ZeroizableSecret,
{
fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
self.peek().encode_raw(buf);
}
fn merge_field(
&mut self,
tag: u32,
wire_type: prost::encoding::WireType,
buf: &mut impl bytes::Buf,
ctx: prost::encoding::DecodeContext,
) -> Result<(), prost::DecodeError> {
if tag == 1 {
self.peek_mut().merge_field(tag, wire_type, buf, ctx)
} else {
prost::encoding::skip_field(wire_type, tag, buf, ctx)
}
}
fn encoded_len(&self) -> usize {
self.peek().encoded_len()
}
fn clear(&mut self) {
self.peek_mut().clear();
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/masking/tests/basic.rs | crates/masking/tests/basic.rs | #![allow(dead_code, clippy::panic_in_result_fn)]
use masking::Secret;
#[cfg(feature = "serde")]
use masking::SerializableSecret;
#[cfg(feature = "alloc")]
use masking::ZeroizableSecret;
#[cfg(feature = "serde")]
use serde::Serialize;
#[test]
fn basic() {
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountNumber(String);
#[cfg(feature = "alloc")]
impl ZeroizableSecret for AccountNumber {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
#[cfg(feature = "serde")]
impl SerializableSecret for AccountNumber {}
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composite {
secret_number: Secret<AccountNumber>,
not_secret: String,
}
// construct
let secret_number = Secret::<AccountNumber>::new(AccountNumber("abc".to_string()));
let not_secret = "not secret".to_string();
let composite = Composite {
secret_number,
not_secret,
};
// clone
#[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal
let composite2 = composite.clone();
assert_eq!(composite, composite2);
// format
let got = format!("{composite:?}");
let exp = r#"Composite { secret_number: *** basic::basic::AccountNumber ***, not_secret: "not secret" }"#;
assert_eq!(got, exp);
// serialize
#[cfg(feature = "serde")]
{
let got = serde_json::to_string(&composite).unwrap();
let exp = r#"{"secret_number":"abc","not_secret":"not secret"}"#;
assert_eq!(got, exp);
}
// end
}
#[test]
fn without_serialize() {
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountNumber(String);
#[cfg(feature = "alloc")]
impl ZeroizableSecret for AccountNumber {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composite {
#[cfg_attr(feature = "serde", serde(skip))]
secret_number: Secret<AccountNumber>,
not_secret: String,
}
// construct
let secret_number = Secret::<AccountNumber>::new(AccountNumber("abc".to_string()));
let not_secret = "not secret".to_string();
let composite = Composite {
secret_number,
not_secret,
};
// format
let got = format!("{composite:?}");
let exp = r#"Composite { secret_number: *** basic::without_serialize::AccountNumber ***, not_secret: "not secret" }"#;
assert_eq!(got, exp);
// serialize
#[cfg(feature = "serde")]
{
let got = serde_json::to_string(&composite).unwrap();
let exp = r#"{"not_secret":"not secret"}"#;
assert_eq!(got, exp);
}
// end
}
#[test]
fn for_string() {
#[cfg_attr(all(feature = "alloc", feature = "serde"), derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composite {
secret_number: Secret<String>,
not_secret: String,
}
// construct
let secret_number = Secret::<String>::new("abc".to_string());
let not_secret = "not secret".to_string();
let composite = Composite {
secret_number,
not_secret,
};
// clone
#[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal
let composite2 = composite.clone();
assert_eq!(composite, composite2);
// format
let got = format!("{composite:?}");
let exp =
r#"Composite { secret_number: *** alloc::string::String ***, not_secret: "not secret" }"#;
assert_eq!(got, exp);
// serialize
#[cfg(all(feature = "alloc", feature = "serde"))]
{
let got = serde_json::to_string(&composite).unwrap();
let exp = r#"{"secret_number":"abc","not_secret":"not secret"}"#;
assert_eq!(got, exp);
}
// end
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/connector_configs/src/lib.rs | crates/connector_configs/src/lib.rs | pub mod common_config;
pub mod connector;
pub mod response_modifier;
pub mod transformer;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/connector_configs/src/connector.rs | crates/connector_configs/src/connector.rs | use std::collections::HashMap;
#[cfg(feature = "payouts")]
use api_models::enums::PayoutConnectors;
use api_models::{
enums::{
AuthenticationConnectors, BillingConnectors, Connector, PmAuthConnectors, TaxConnectors,
},
payments,
};
use serde::{Deserialize, Serialize};
use crate::common_config::{CardProvider, InputData, Provider, ZenApplePay};
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PayloadCurrencyAuthKeyType {
pub api_key: String,
pub processing_account_id: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Classic {
pub password_classic: String,
pub username_classic: String,
pub merchant_id_classic: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Evoucher {
pub password_evoucher: String,
pub username_evoucher: String,
pub merchant_id_evoucher: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct CashtoCodeCurrencyAuthKeyType {
pub classic: Classic,
pub evoucher: Evoucher,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CurrencyAuthValue {
CashtoCode(CashtoCodeCurrencyAuthKeyType),
Payload(PayloadCurrencyAuthKeyType),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub enum ConnectorAuthType {
HeaderKey {
api_key: String,
},
BodyKey {
api_key: String,
key1: String,
},
SignatureKey {
api_key: String,
key1: String,
api_secret: String,
},
MultiAuthKey {
api_key: String,
key1: String,
api_secret: String,
key2: String,
},
CurrencyAuthKey {
auth_key_map: HashMap<String, CurrencyAuthValue>,
},
CertificateAuth {
certificate: String,
private_key: String,
},
#[default]
NoKey,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum ApplePayTomlConfig {
Standard(Box<payments::ApplePayMetadata>),
Zen(ZenApplePay),
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum KlarnaEndpoint {
Europe,
NorthAmerica,
Oceania,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConfigMerchantAdditionalDetails {
pub open_banking_recipient_data: Option<InputData>,
pub account_data: Option<InputData>,
pub iban: Option<Vec<InputData>>,
pub bacs: Option<Vec<InputData>>,
pub connector_recipient_id: Option<InputData>,
pub wallet_id: Option<InputData>,
pub faster_payments: Option<Vec<InputData>>,
pub sepa: Option<Vec<InputData>>,
pub sepa_instant: Option<Vec<InputData>>,
pub elixir: Option<Vec<InputData>>,
pub bankgiro: Option<Vec<InputData>>,
pub plusgiro: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIdConfigForCard {
pub three_ds: Option<Vec<InputData>>,
pub no_three_ds: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIdConfigForRedirect {
pub three_ds: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIdConfigForApplePay {
pub encrypt: Option<Vec<InputData>>,
pub decrypt: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AccountIDSupportedMethods {
apple_pay: HashMap<String, AccountIdConfigForApplePay>,
card: HashMap<String, AccountIdConfigForCard>,
interac: HashMap<String, AccountIdConfigForRedirect>,
pay_safe_card: HashMap<String, AccountIdConfigForRedirect>,
skrill: HashMap<String, AccountIdConfigForRedirect>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConfigMetadata {
pub merchant_config_currency: Option<InputData>,
pub merchant_account_id: Option<InputData>,
pub account_name: Option<InputData>,
pub account_type: Option<InputData>,
pub terminal_id: Option<InputData>,
pub google_pay: Option<Vec<InputData>>,
pub apple_pay: Option<Vec<InputData>>,
pub merchant_id: Option<InputData>,
pub endpoint_prefix: Option<InputData>,
pub mcc: Option<InputData>,
pub merchant_country_code: Option<InputData>,
pub merchant_name: Option<InputData>,
pub acquirer_bin: Option<InputData>,
pub acquirer_merchant_id: Option<InputData>,
pub acquirer_country_code: Option<InputData>,
pub three_ds_requestor_name: Option<InputData>,
pub three_ds_requestor_id: Option<InputData>,
pub pull_mechanism_for_external_3ds_enabled: Option<InputData>,
pub klarna_region: Option<InputData>,
pub pricing_type: Option<InputData>,
pub source_balance_account: Option<InputData>,
pub brand_id: Option<InputData>,
pub destination_account_number: Option<InputData>,
pub dpa_id: Option<InputData>,
pub dpa_name: Option<InputData>,
pub locale: Option<InputData>,
pub card_brands: Option<InputData>,
pub merchant_category_code: Option<InputData>,
pub merchant_configuration_id: Option<InputData>,
pub currency_id: Option<InputData>,
pub platform_id: Option<InputData>,
pub ledger_account_id: Option<InputData>,
pub tenant_id: Option<InputData>,
pub platform_url: Option<InputData>,
pub report_group: Option<InputData>,
pub proxy_url: Option<InputData>,
pub shop_name: Option<InputData>,
pub merchant_funding_source: Option<InputData>,
pub account_id: Option<AccountIDSupportedMethods>,
pub name: Option<InputData>,
pub client_merchant_reference_id: Option<InputData>,
pub merchant_payment_method_route_id: Option<InputData>,
pub site: Option<InputData>,
pub purpose_of_payment: Option<InputData>,
pub organizational_unit_id: Option<InputData>,
pub issuer_id: Option<InputData>,
pub jwt_mac_key: Option<InputData>,
pub company_name: Option<InputData>,
pub product_name: Option<InputData>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConnectorWalletDetailsConfig {
pub samsung_pay: Option<Vec<InputData>>,
pub paze: Option<Vec<InputData>>,
pub google_pay: Option<Vec<InputData>>,
pub amazon_pay: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConnectorTomlConfig {
pub connector_auth: Option<ConnectorAuthType>,
pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>,
pub metadata: Option<Box<ConfigMetadata>>,
pub connector_wallets_details: Option<Box<ConnectorWalletDetailsConfig>>,
pub additional_merchant_data: Option<Box<ConfigMerchantAdditionalDetails>>,
pub credit: Option<Vec<CardProvider>>,
pub debit: Option<Vec<CardProvider>>,
pub bank_transfer: Option<Vec<Provider>>,
pub bank_redirect: Option<Vec<Provider>>,
pub bank_debit: Option<Vec<Provider>>,
pub open_banking: Option<Vec<Provider>>,
pub pay_later: Option<Vec<Provider>>,
pub wallet: Option<Vec<Provider>>,
pub crypto: Option<Vec<Provider>>,
pub reward: Option<Vec<Provider>>,
pub upi: Option<Vec<Provider>>,
pub voucher: Option<Vec<Provider>>,
pub gift_card: Option<Vec<Provider>>,
pub card_redirect: Option<Vec<Provider>>,
pub is_verifiable: Option<bool>,
pub real_time_payment: Option<Vec<Provider>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ConnectorConfig {
pub authipay: Option<ConnectorTomlConfig>,
pub juspaythreedsserver: Option<ConnectorTomlConfig>,
pub katapult: Option<ConnectorTomlConfig>,
pub aci: Option<ConnectorTomlConfig>,
pub adyen: Option<ConnectorTomlConfig>,
pub affirm: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub adyen_payout: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub adyenplatform_payout: Option<ConnectorTomlConfig>,
pub airwallex: Option<ConnectorTomlConfig>,
pub amazonpay: Option<ConnectorTomlConfig>,
pub archipel: Option<ConnectorTomlConfig>,
pub authorizedotnet: Option<ConnectorTomlConfig>,
pub bamboraapac: Option<ConnectorTomlConfig>,
pub bankofamerica: Option<ConnectorTomlConfig>,
pub barclaycard: Option<ConnectorTomlConfig>,
pub billwerk: Option<ConnectorTomlConfig>,
pub bitpay: Option<ConnectorTomlConfig>,
pub blackhawknetwork: Option<ConnectorTomlConfig>,
pub calida: Option<ConnectorTomlConfig>,
pub bluesnap: Option<ConnectorTomlConfig>,
pub boku: Option<ConnectorTomlConfig>,
pub braintree: Option<ConnectorTomlConfig>,
pub breadpay: Option<ConnectorTomlConfig>,
pub cardinal: Option<ConnectorTomlConfig>,
pub cashtocode: Option<ConnectorTomlConfig>,
pub celero: Option<ConnectorTomlConfig>,
pub chargebee: Option<ConnectorTomlConfig>,
pub custombilling: Option<ConnectorTomlConfig>,
pub checkbook: Option<ConnectorTomlConfig>,
pub checkout: Option<ConnectorTomlConfig>,
pub coinbase: Option<ConnectorTomlConfig>,
pub coingate: Option<ConnectorTomlConfig>,
pub cryptopay: Option<ConnectorTomlConfig>,
pub ctp_visa: Option<ConnectorTomlConfig>,
pub cybersource: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub cybersource_payout: Option<ConnectorTomlConfig>,
pub iatapay: Option<ConnectorTomlConfig>,
pub itaubank: Option<ConnectorTomlConfig>,
pub opennode: Option<ConnectorTomlConfig>,
pub bambora: Option<ConnectorTomlConfig>,
pub datatrans: Option<ConnectorTomlConfig>,
pub deutschebank: Option<ConnectorTomlConfig>,
pub digitalvirgo: Option<ConnectorTomlConfig>,
pub dlocal: Option<ConnectorTomlConfig>,
pub dwolla: Option<ConnectorTomlConfig>,
pub ebanx_payout: Option<ConnectorTomlConfig>,
pub elavon: Option<ConnectorTomlConfig>,
pub envoy: Option<ConnectorTomlConfig>,
pub facilitapay: Option<ConnectorTomlConfig>,
pub finix: Option<ConnectorTomlConfig>,
pub fiserv: Option<ConnectorTomlConfig>,
pub fiservemea: Option<ConnectorTomlConfig>,
pub fiuu: Option<ConnectorTomlConfig>,
pub flexiti: Option<ConnectorTomlConfig>,
pub forte: Option<ConnectorTomlConfig>,
pub getnet: Option<ConnectorTomlConfig>,
pub gigadat: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub gigadat_payout: Option<ConnectorTomlConfig>,
pub globalpay: Option<ConnectorTomlConfig>,
pub globepay: Option<ConnectorTomlConfig>,
pub gocardless: Option<ConnectorTomlConfig>,
pub gpayments: Option<ConnectorTomlConfig>,
pub hipay: Option<ConnectorTomlConfig>,
pub helcim: Option<ConnectorTomlConfig>,
pub hyperswitch_vault: Option<ConnectorTomlConfig>,
pub hyperwallet: Option<ConnectorTomlConfig>,
pub inespay: Option<ConnectorTomlConfig>,
pub jpmorgan: Option<ConnectorTomlConfig>,
pub klarna: Option<ConnectorTomlConfig>,
pub loonio: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub loonio_payout: Option<ConnectorTomlConfig>,
pub mifinity: Option<ConnectorTomlConfig>,
pub mollie: Option<ConnectorTomlConfig>,
pub moneris: Option<ConnectorTomlConfig>,
pub mpgs: Option<ConnectorTomlConfig>,
pub multisafepay: Option<ConnectorTomlConfig>,
pub nexinets: Option<ConnectorTomlConfig>,
pub nexixpay: Option<ConnectorTomlConfig>,
pub nmi: Option<ConnectorTomlConfig>,
pub nomupay_payout: Option<ConnectorTomlConfig>,
pub noon: Option<ConnectorTomlConfig>,
pub nordea: Option<ConnectorTomlConfig>,
pub novalnet: Option<ConnectorTomlConfig>,
pub nuvei_payout: Option<ConnectorTomlConfig>,
pub nuvei: Option<ConnectorTomlConfig>,
pub paybox: Option<ConnectorTomlConfig>,
pub payload: Option<ConnectorTomlConfig>,
pub payme: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub payone_payout: Option<ConnectorTomlConfig>,
pub paypal: Option<ConnectorTomlConfig>,
pub paysafe: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub paypal_payout: Option<ConnectorTomlConfig>,
pub paystack: Option<ConnectorTomlConfig>,
pub paytm: Option<ConnectorTomlConfig>,
pub payu: Option<ConnectorTomlConfig>,
pub peachpayments: Option<ConnectorTomlConfig>,
pub payjustnow: Option<ConnectorTomlConfig>,
pub payjustnowinstore: Option<ConnectorTomlConfig>,
pub phonepe: Option<ConnectorTomlConfig>,
pub placetopay: Option<ConnectorTomlConfig>,
pub plaid: Option<ConnectorTomlConfig>,
pub powertranz: Option<ConnectorTomlConfig>,
pub prophetpay: Option<ConnectorTomlConfig>,
pub razorpay: Option<ConnectorTomlConfig>,
pub recurly: Option<ConnectorTomlConfig>,
pub riskified: Option<ConnectorTomlConfig>,
pub rapyd: Option<ConnectorTomlConfig>,
pub redsys: Option<ConnectorTomlConfig>,
pub santander: Option<ConnectorTomlConfig>,
pub shift4: Option<ConnectorTomlConfig>,
pub sift: Option<ConnectorTomlConfig>,
pub silverflow: Option<ConnectorTomlConfig>,
pub stripe: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub stripe_payout: Option<ConnectorTomlConfig>,
pub stripebilling: Option<ConnectorTomlConfig>,
pub signifyd: Option<ConnectorTomlConfig>,
pub tersouro: Option<ConnectorTomlConfig>,
pub tokenex: Option<ConnectorTomlConfig>,
pub tokenio: Option<ConnectorTomlConfig>,
pub trustpay: Option<ConnectorTomlConfig>,
pub trustpayments: Option<ConnectorTomlConfig>,
pub threedsecureio: Option<ConnectorTomlConfig>,
pub netcetera: Option<ConnectorTomlConfig>,
pub tsys: Option<ConnectorTomlConfig>,
pub vgs: Option<ConnectorTomlConfig>,
pub volt: Option<ConnectorTomlConfig>,
pub wellsfargo: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub wise_payout: Option<ConnectorTomlConfig>,
pub worldline: Option<ConnectorTomlConfig>,
pub worldpay: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub worldpay_payout: Option<ConnectorTomlConfig>,
pub worldpayvantiv: Option<ConnectorTomlConfig>,
pub worldpayxml: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub worldpayxml_payout: Option<ConnectorTomlConfig>,
pub xendit: Option<ConnectorTomlConfig>,
pub zift: Option<ConnectorTomlConfig>,
pub square: Option<ConnectorTomlConfig>,
pub stax: Option<ConnectorTomlConfig>,
pub dummy_connector: Option<ConnectorTomlConfig>,
pub stripe_test: Option<ConnectorTomlConfig>,
pub paypal_test: Option<ConnectorTomlConfig>,
pub zen: Option<ConnectorTomlConfig>,
pub zsl: Option<ConnectorTomlConfig>,
pub taxjar: Option<ConnectorTomlConfig>,
pub tesouro: Option<ConnectorTomlConfig>,
pub ctp_mastercard: Option<ConnectorTomlConfig>,
pub unified_authentication_service: Option<ConnectorTomlConfig>,
}
impl ConnectorConfig {
fn new() -> Result<Self, String> {
let config_str = if cfg!(feature = "production") {
include_str!("../toml/production.toml")
} else if cfg!(feature = "sandbox") {
include_str!("../toml/sandbox.toml")
} else {
include_str!("../toml/development.toml")
};
let config = toml::from_str::<Self>(config_str);
match config {
Ok(data) => Ok(data),
Err(err) => Err(err.to_string()),
}
}
#[cfg(feature = "payouts")]
pub fn get_payout_connector_config(
connector: PayoutConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
PayoutConnectors::Adyen => Ok(connector_data.adyen_payout),
PayoutConnectors::Adyenplatform => Ok(connector_data.adyenplatform_payout),
PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout),
PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout),
PayoutConnectors::Gigadat => Ok(connector_data.gigadat_payout),
PayoutConnectors::Loonio => Ok(connector_data.loonio_payout),
PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout),
PayoutConnectors::Nuvei => Ok(connector_data.nuvei_payout),
PayoutConnectors::Payone => Ok(connector_data.payone_payout),
PayoutConnectors::Paypal => Ok(connector_data.paypal_payout),
PayoutConnectors::Stripe => Ok(connector_data.stripe_payout),
PayoutConnectors::Wise => Ok(connector_data.wise_payout),
PayoutConnectors::Worldpay => Ok(connector_data.worldpay_payout),
PayoutConnectors::Worldpayxml => Ok(connector_data.worldpayxml_payout),
}
}
pub fn get_billing_connector_config(
connector: BillingConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
BillingConnectors::Chargebee => Ok(connector_data.chargebee),
BillingConnectors::Stripebilling => Ok(connector_data.stripebilling),
BillingConnectors::Recurly => Ok(connector_data.recurly),
BillingConnectors::Custombilling => Ok(connector_data.custombilling),
#[cfg(feature = "dummy_connector")]
BillingConnectors::DummyBillingConnector => Ok(connector_data.dummy_connector),
}
}
pub fn get_authentication_connector_config(
connector: AuthenticationConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
AuthenticationConnectors::Threedsecureio => Ok(connector_data.threedsecureio),
AuthenticationConnectors::Netcetera => Ok(connector_data.netcetera),
AuthenticationConnectors::Gpayments => Ok(connector_data.gpayments),
AuthenticationConnectors::CtpMastercard => Ok(connector_data.ctp_mastercard),
AuthenticationConnectors::CtpVisa => Ok(connector_data.ctp_visa),
AuthenticationConnectors::UnifiedAuthenticationService => {
Ok(connector_data.unified_authentication_service)
}
AuthenticationConnectors::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver),
AuthenticationConnectors::Cardinal => Ok(connector_data.cardinal),
}
}
pub fn get_tax_processor_config(
connector: TaxConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
TaxConnectors::Taxjar => Ok(connector_data.taxjar),
}
}
pub fn get_pm_authentication_processor_config(
connector: PmAuthConnectors,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
PmAuthConnectors::Plaid => Ok(connector_data.plaid),
}
}
pub fn get_connector_config(
connector: Connector,
) -> Result<Option<ConnectorTomlConfig>, String> {
let connector_data = Self::new()?;
match connector {
Connector::Aci => Ok(connector_data.aci),
Connector::Authipay => Ok(connector_data.authipay),
Connector::Adyen => Ok(connector_data.adyen),
Connector::Affirm => Ok(connector_data.affirm),
Connector::Adyenplatform => Err("Use get_payout_connector_config".to_string()),
Connector::Airwallex => Ok(connector_data.airwallex),
Connector::Amazonpay => Ok(connector_data.amazonpay),
Connector::Archipel => Ok(connector_data.archipel),
Connector::Authorizedotnet => Ok(connector_data.authorizedotnet),
Connector::Bamboraapac => Ok(connector_data.bamboraapac),
Connector::Bankofamerica => Ok(connector_data.bankofamerica),
Connector::Barclaycard => Ok(connector_data.barclaycard),
Connector::Billwerk => Ok(connector_data.billwerk),
Connector::Bitpay => Ok(connector_data.bitpay),
Connector::Bluesnap => Ok(connector_data.bluesnap),
Connector::Calida => Ok(connector_data.calida),
Connector::Blackhawknetwork => Ok(connector_data.blackhawknetwork),
Connector::Boku => Ok(connector_data.boku),
Connector::Braintree => Ok(connector_data.braintree),
Connector::Breadpay => Ok(connector_data.breadpay),
Connector::Cashtocode => Ok(connector_data.cashtocode),
Connector::Cardinal => Ok(connector_data.cardinal),
Connector::Celero => Ok(connector_data.celero),
Connector::Chargebee => Ok(connector_data.chargebee),
Connector::Checkbook => Ok(connector_data.checkbook),
Connector::Checkout => Ok(connector_data.checkout),
Connector::Coinbase => Ok(connector_data.coinbase),
Connector::Coingate => Ok(connector_data.coingate),
Connector::Cryptopay => Ok(connector_data.cryptopay),
Connector::CtpVisa => Ok(connector_data.ctp_visa),
Connector::Custombilling => Ok(connector_data.custombilling),
Connector::Cybersource => Ok(connector_data.cybersource),
#[cfg(feature = "dummy_connector")]
Connector::DummyBillingConnector => Ok(connector_data.dummy_connector),
Connector::Iatapay => Ok(connector_data.iatapay),
Connector::Itaubank => Ok(connector_data.itaubank),
Connector::Opennode => Ok(connector_data.opennode),
Connector::Bambora => Ok(connector_data.bambora),
Connector::Datatrans => Ok(connector_data.datatrans),
Connector::Deutschebank => Ok(connector_data.deutschebank),
Connector::Digitalvirgo => Ok(connector_data.digitalvirgo),
Connector::Dlocal => Ok(connector_data.dlocal),
Connector::Dwolla => Ok(connector_data.dwolla),
Connector::Ebanx => Ok(connector_data.ebanx_payout),
Connector::Elavon => Ok(connector_data.elavon),
Connector::Facilitapay => Ok(connector_data.facilitapay),
Connector::Finix => Ok(connector_data.finix),
Connector::Fiserv => Ok(connector_data.fiserv),
Connector::Fiservemea => Ok(connector_data.fiservemea),
Connector::Fiuu => Ok(connector_data.fiuu),
Connector::Flexiti => Ok(connector_data.flexiti),
Connector::Forte => Ok(connector_data.forte),
Connector::Getnet => Ok(connector_data.getnet),
Connector::Gigadat => Ok(connector_data.gigadat),
Connector::Globalpay => Ok(connector_data.globalpay),
Connector::Globepay => Ok(connector_data.globepay),
Connector::Gocardless => Ok(connector_data.gocardless),
Connector::Gpayments => Ok(connector_data.gpayments),
Connector::Hipay => Ok(connector_data.hipay),
Connector::HyperswitchVault => Ok(connector_data.hyperswitch_vault),
Connector::Helcim => Ok(connector_data.helcim),
Connector::Inespay => Ok(connector_data.inespay),
Connector::Jpmorgan => Ok(connector_data.jpmorgan),
Connector::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver),
Connector::Klarna => Ok(connector_data.klarna),
Connector::Loonio => Ok(connector_data.loonio),
Connector::Mifinity => Ok(connector_data.mifinity),
Connector::Mollie => Ok(connector_data.mollie),
Connector::Moneris => Ok(connector_data.moneris),
Connector::Multisafepay => Ok(connector_data.multisafepay),
Connector::Nexinets => Ok(connector_data.nexinets),
Connector::Nexixpay => Ok(connector_data.nexixpay),
Connector::Prophetpay => Ok(connector_data.prophetpay),
Connector::Nmi => Ok(connector_data.nmi),
Connector::Nordea => Ok(connector_data.nordea),
Connector::Nomupay => Err("Use get_payout_connector_config".to_string()),
Connector::Novalnet => Ok(connector_data.novalnet),
Connector::Noon => Ok(connector_data.noon),
Connector::Nuvei => Ok(connector_data.nuvei),
Connector::Paybox => Ok(connector_data.paybox),
Connector::Payload => Ok(connector_data.payload),
Connector::Payme => Ok(connector_data.payme),
Connector::Payone => Err("Use get_payout_connector_config".to_string()),
Connector::Paypal => Ok(connector_data.paypal),
Connector::Paysafe => Ok(connector_data.paysafe),
Connector::Paystack => Ok(connector_data.paystack),
Connector::Payu => Ok(connector_data.payu),
Connector::Peachpayments => Ok(connector_data.peachpayments),
Connector::Placetopay => Ok(connector_data.placetopay),
Connector::Plaid => Ok(connector_data.plaid),
Connector::Powertranz => Ok(connector_data.powertranz),
Connector::Razorpay => Ok(connector_data.razorpay),
Connector::Rapyd => Ok(connector_data.rapyd),
Connector::Recurly => Ok(connector_data.recurly),
Connector::Redsys => Ok(connector_data.redsys),
Connector::Riskified => Ok(connector_data.riskified),
Connector::Santander => Ok(connector_data.santander),
Connector::Shift4 => Ok(connector_data.shift4),
Connector::Signifyd => Ok(connector_data.signifyd),
Connector::Silverflow => Ok(connector_data.silverflow),
Connector::Square => Ok(connector_data.square),
Connector::Stax => Ok(connector_data.stax),
Connector::Stripe => Ok(connector_data.stripe),
Connector::Stripebilling => Ok(connector_data.stripebilling),
Connector::Tesouro => Ok(connector_data.tesouro),
Connector::Tokenex => Ok(connector_data.tokenex),
Connector::Tokenio => Ok(connector_data.tokenio),
Connector::Trustpay => Ok(connector_data.trustpay),
Connector::Trustpayments => Ok(connector_data.trustpayments),
Connector::Threedsecureio => Ok(connector_data.threedsecureio),
Connector::Taxjar => Ok(connector_data.taxjar),
Connector::Tsys => Ok(connector_data.tsys),
Connector::Vgs => Ok(connector_data.vgs),
Connector::Volt => Ok(connector_data.volt),
Connector::Wellsfargo => Ok(connector_data.wellsfargo),
Connector::Wise => Err("Use get_payout_connector_config".to_string()),
Connector::Worldline => Ok(connector_data.worldline),
Connector::Worldpay => Ok(connector_data.worldpay),
Connector::Worldpayvantiv => Ok(connector_data.worldpayvantiv),
Connector::Worldpayxml => Ok(connector_data.worldpayxml),
Connector::Zen => Ok(connector_data.zen),
Connector::Zsl => Ok(connector_data.zsl),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector1 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector2 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector3 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector4 => Ok(connector_data.stripe_test),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector5 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector6 => Ok(connector_data.dummy_connector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector7 => Ok(connector_data.paypal_test),
Connector::Netcetera => Ok(connector_data.netcetera),
Connector::CtpMastercard => Ok(connector_data.ctp_mastercard),
Connector::Xendit => Ok(connector_data.xendit),
Connector::Paytm => Ok(connector_data.paytm),
Connector::Zift => Ok(connector_data.zift),
Connector::Phonepe => Ok(connector_data.phonepe),
Connector::Payjustnow => Ok(connector_data.payjustnow),
Connector::Payjustnowinstore => Ok(connector_data.payjustnowinstore),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/connector_configs/src/common_config.rs | crates/connector_configs/src/common_config.rs | use api_models::{payment_methods, payments};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub struct ZenApplePay {
pub terminal_uuid: Option<String>,
pub pay_wall_secret: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(untagged)]
pub enum ApplePayData {
ApplePay(payments::ApplePayMetadata),
ApplePayCombined(payments::ApplePayCombinedMetadata),
Zen(ZenApplePay),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpayDashboardPayLoad {
#[serde(skip_serializing_if = "Option::is_none")]
pub gateway_merchant_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")]
pub stripe_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename(
serialize = "stripe_publishable_key",
deserialize = "stripe:publishable_key"
))]
#[serde(alias = "stripe:publishable_key")]
#[serde(alias = "stripe_publishable_key")]
pub stripe_publishable_key: Option<String>,
pub merchant_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_id: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub struct ZenGooglePay {
pub terminal_uuid: Option<String>,
pub pay_wall_secret: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(untagged)]
pub enum GooglePayData {
Standard(GpayDashboardPayLoad),
Zen(ZenGooglePay),
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkData {
pub client_id: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(untagged)]
pub enum GoogleApiModelData {
Standard(payments::GpayMetaData),
Zen(ZenGooglePay),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct PaymentMethodsEnabled {
pub payment_method: api_models::enums::PaymentMethod,
pub payment_method_types: Option<Vec<payment_methods::RequestPaymentMethodTypes>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct ApiModelMetaData {
pub merchant_config_currency: Option<api_models::enums::Currency>,
pub merchant_account_id: Option<String>,
pub account_name: Option<String>,
pub terminal_id: Option<String>,
pub merchant_id: Option<String>,
pub google_pay: Option<GoogleApiModelData>,
pub paypal_sdk: Option<PaypalSdkData>,
pub apple_pay: Option<ApplePayData>,
pub apple_pay_combined: Option<ApplePayData>,
pub endpoint_prefix: Option<String>,
pub mcc: Option<String>,
pub merchant_country_code: Option<String>,
pub merchant_name: Option<String>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
pub klarna_region: Option<KlarnaEndpoint>,
pub source_balance_account: Option<String>,
pub brand_id: Option<String>,
pub destination_account_number: Option<String>,
pub dpa_id: Option<String>,
pub dpa_name: Option<String>,
pub locale: Option<String>,
pub card_brands: Option<Vec<String>>,
pub merchant_category_code: Option<String>,
pub merchant_configuration_id: Option<String>,
pub tenant_id: Option<String>,
pub platform_url: Option<String>,
pub account_id: Option<serde_json::Value>,
pub site: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub enum KlarnaEndpoint {
Europe,
NorthAmerica,
Oceania,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CardProvider {
pub payment_method_type: api_models::enums::CardNetwork,
/// List of currencies accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "specific_accepted",
"list": ["USD", "INR"]
}
), value_type = Option<AcceptedCurrencies>)]
pub accepted_currencies: Option<api_models::admin::AcceptedCurrencies>,
#[schema(example = json!(
{
"type": "specific_accepted",
"list": ["UK", "AU"]
}
), value_type = Option<AcceptedCountries>)]
pub accepted_countries: Option<api_models::admin::AcceptedCountries>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Provider {
pub payment_method_type: api_models::enums::PaymentMethodType,
/// List of currencies accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "specific_accepted",
"list": ["USD", "INR"]
}
), value_type = Option<AcceptedCurrencies>)]
pub accepted_currencies: Option<api_models::admin::AcceptedCurrencies>,
#[schema(example = json!(
{
"type": "specific_accepted",
"list": ["UK", "AU"]
}
), value_type = Option<AcceptedCountries>)]
pub accepted_countries: Option<api_models::admin::AcceptedCountries>,
pub payment_experience: Option<api_models::enums::PaymentExperience>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct ConnectorApiIntegrationPayload {
pub connector_type: String,
pub profile_id: common_utils::id_type::ProfileId,
pub connector_name: api_models::enums::Connector,
#[serde(skip_deserializing)]
#[schema(example = "stripe_US_travel")]
pub connector_label: Option<String>,
pub merchant_connector_id: Option<String>,
pub disabled: bool,
pub test_mode: bool,
pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>,
pub metadata: Option<ApiModelMetaData>,
pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct DashboardPaymentMethodPayload {
pub payment_method: api_models::enums::PaymentMethod,
pub payment_method_type: String,
pub provider: Option<Vec<Provider>>,
pub card_provider: Option<Vec<CardProvider>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct DashboardRequestPayload {
pub connector: api_models::enums::Connector,
pub payment_methods_enabled: Option<Vec<DashboardPaymentMethodPayload>>,
pub metadata: Option<ApiModelMetaData>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(tag = "type", content = "options")]
pub enum InputType {
Text,
Number,
Toggle,
Radio(Vec<String>),
Select(Vec<String>),
MultiSelect(Vec<String>),
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub struct InputData {
pub name: String,
pub label: String,
pub placeholder: String,
pub required: bool,
#[serde(flatten)]
pub input_type: InputType,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/connector_configs/src/response_modifier.rs | crates/connector_configs/src/response_modifier.rs | use crate::common_config::{
CardProvider, ConnectorApiIntegrationPayload, DashboardPaymentMethodPayload,
DashboardRequestPayload, Provider,
};
impl ConnectorApiIntegrationPayload {
pub fn get_transformed_response_payload(response: Self) -> DashboardRequestPayload {
let mut wallet_details: Vec<Provider> = Vec::new();
let mut bank_redirect_details: Vec<Provider> = Vec::new();
let mut pay_later_details: Vec<Provider> = Vec::new();
let mut debit_details: Vec<CardProvider> = Vec::new();
let mut credit_details: Vec<CardProvider> = Vec::new();
let mut bank_transfer_details: Vec<Provider> = Vec::new();
let mut crypto_details: Vec<Provider> = Vec::new();
let mut bank_debit_details: Vec<Provider> = Vec::new();
let mut reward_details: Vec<Provider> = Vec::new();
let mut real_time_payment_details: Vec<Provider> = Vec::new();
let mut upi_details: Vec<Provider> = Vec::new();
let mut voucher_details: Vec<Provider> = Vec::new();
let mut gift_card_details: Vec<Provider> = Vec::new();
let mut card_redirect_details: Vec<Provider> = Vec::new();
let mut open_banking_details: Vec<Provider> = Vec::new();
let mut mobile_payment_details: Vec<Provider> = Vec::new();
let mut network_token_details: Vec<Provider> = Vec::new();
if let Some(payment_methods_enabled) = response.payment_methods_enabled.clone() {
for methods in payment_methods_enabled {
match methods.payment_method {
api_models::enums::PaymentMethod::Card => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
match method_type.payment_method_type {
api_models::enums::PaymentMethodType::Credit => {
if let Some(card_networks) = method_type.card_networks {
for card in card_networks {
credit_details.push(CardProvider {
payment_method_type: card,
accepted_currencies: method_type
.accepted_currencies
.clone(),
accepted_countries: method_type
.accepted_countries
.clone(),
})
}
}
}
api_models::enums::PaymentMethodType::Debit => {
if let Some(card_networks) = method_type.card_networks {
for card in card_networks {
// debit_details.push(card)
debit_details.push(CardProvider {
payment_method_type: card,
accepted_currencies: method_type
.accepted_currencies
.clone(),
accepted_countries: method_type
.accepted_countries
.clone(),
})
}
}
}
_ => (),
}
}
}
}
api_models::enums::PaymentMethod::Wallet => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
// wallet_details.push(method_type.payment_method_type)
wallet_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::BankRedirect => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
bank_redirect_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::PayLater => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
pay_later_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::BankTransfer => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
bank_transfer_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Crypto => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
crypto_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::BankDebit => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
bank_debit_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Reward => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
reward_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::RealTimePayment => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
real_time_payment_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::OpenBanking => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
open_banking_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Upi => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
upi_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::Voucher => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
voucher_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::GiftCard => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
gift_card_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::CardRedirect => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
card_redirect_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::MobilePayment => {
if let Some(payment_method_types) = methods.payment_method_types {
for method_type in payment_method_types {
mobile_payment_details.push(Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
})
}
}
}
api_models::enums::PaymentMethod::NetworkToken => {
if let Some(payment_method_types) = methods.payment_method_types {
network_token_details.extend(payment_method_types.into_iter().map(
|method_type| Provider {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
payment_experience: method_type.payment_experience,
},
));
}
}
}
}
}
let open_banking = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::OpenBanking,
payment_method_type: api_models::enums::PaymentMethod::OpenBanking.to_string(),
provider: Some(open_banking_details),
card_provider: None,
};
let upi = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Upi,
payment_method_type: api_models::enums::PaymentMethod::Upi.to_string(),
provider: Some(upi_details),
card_provider: None,
};
let voucher: DashboardPaymentMethodPayload = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Voucher,
payment_method_type: api_models::enums::PaymentMethod::Voucher.to_string(),
provider: Some(voucher_details),
card_provider: None,
};
let gift_card: DashboardPaymentMethodPayload = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::GiftCard,
payment_method_type: api_models::enums::PaymentMethod::GiftCard.to_string(),
provider: Some(gift_card_details),
card_provider: None,
};
let reward = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Reward,
payment_method_type: api_models::enums::PaymentMethod::Reward.to_string(),
provider: Some(reward_details),
card_provider: None,
};
let real_time_payment = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::RealTimePayment,
payment_method_type: api_models::enums::PaymentMethod::RealTimePayment.to_string(),
provider: Some(real_time_payment_details),
card_provider: None,
};
let wallet = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Wallet,
payment_method_type: api_models::enums::PaymentMethod::Wallet.to_string(),
provider: Some(wallet_details),
card_provider: None,
};
let bank_redirect = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::BankRedirect,
payment_method_type: api_models::enums::PaymentMethod::BankRedirect.to_string(),
provider: Some(bank_redirect_details),
card_provider: None,
};
let bank_debit = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::BankDebit,
payment_method_type: api_models::enums::PaymentMethod::BankDebit.to_string(),
provider: Some(bank_debit_details),
card_provider: None,
};
let bank_transfer = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::BankTransfer,
payment_method_type: api_models::enums::PaymentMethod::BankTransfer.to_string(),
provider: Some(bank_transfer_details),
card_provider: None,
};
let crypto = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Crypto,
payment_method_type: api_models::enums::PaymentMethod::Crypto.to_string(),
provider: Some(crypto_details),
card_provider: None,
};
let card_redirect = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::CardRedirect,
payment_method_type: api_models::enums::PaymentMethod::CardRedirect.to_string(),
provider: Some(card_redirect_details),
card_provider: None,
};
let pay_later = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::PayLater,
payment_method_type: api_models::enums::PaymentMethod::PayLater.to_string(),
provider: Some(pay_later_details),
card_provider: None,
};
let debit_details = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Card,
payment_method_type: api_models::enums::PaymentMethodType::Debit.to_string(),
provider: None,
card_provider: Some(debit_details),
};
let credit_details = DashboardPaymentMethodPayload {
payment_method: api_models::enums::PaymentMethod::Card,
payment_method_type: api_models::enums::PaymentMethodType::Credit.to_string(),
provider: None,
card_provider: Some(credit_details),
};
DashboardRequestPayload {
connector: response.connector_name,
payment_methods_enabled: Some(vec![
open_banking,
upi,
voucher,
reward,
real_time_payment,
wallet,
bank_redirect,
bank_debit,
bank_transfer,
crypto,
card_redirect,
pay_later,
debit_details,
credit_details,
gift_card,
]),
metadata: response.metadata,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/connector_configs/src/transformer.rs | crates/connector_configs/src/transformer.rs | use std::str::FromStr;
use api_models::{
enums::{
Connector, PaymentMethod,
PaymentMethodType::{self, AliPay, ApplePay, GooglePay, Klarna, Paypal, WeChatPay},
},
payment_methods,
refunds::MinorUnit,
};
use crate::common_config::{
ConnectorApiIntegrationPayload, DashboardRequestPayload, PaymentMethodsEnabled, Provider,
};
impl DashboardRequestPayload {
pub fn transform_card(
payment_method_type: PaymentMethodType,
card_provider: Vec<api_models::enums::CardNetwork>,
) -> payment_methods::RequestPaymentMethodTypes {
payment_methods::RequestPaymentMethodTypes {
payment_method_type,
card_networks: Some(card_provider),
minimum_amount: Some(MinorUnit::zero()),
maximum_amount: Some(MinorUnit::new(68607706)),
recurring_enabled: Some(true),
installment_payment_enabled: Some(false),
accepted_currencies: None,
accepted_countries: None,
payment_experience: None,
}
}
pub fn get_payment_experience(
connector: Connector,
payment_method_type: PaymentMethodType,
payment_method: PaymentMethod,
payment_experience: Option<api_models::enums::PaymentExperience>,
) -> Option<api_models::enums::PaymentExperience> {
match payment_method {
PaymentMethod::BankRedirect => None,
_ => match (connector, payment_method_type) {
#[cfg(feature = "dummy_connector")]
(Connector::DummyConnector4, _) | (Connector::DummyConnector7, _) => {
Some(api_models::enums::PaymentExperience::RedirectToUrl)
}
(Connector::Paypal, Paypal) => payment_experience,
(Connector::Klarna, Klarna) => payment_experience,
(Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => {
Some(api_models::enums::PaymentExperience::RedirectToUrl)
}
(Connector::Braintree, Paypal) => {
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
}
(Connector::Globepay, AliPay)
| (Connector::Globepay, WeChatPay)
| (Connector::Stripe, WeChatPay) => {
Some(api_models::enums::PaymentExperience::DisplayQrCode)
}
(_, GooglePay)
| (_, ApplePay)
| (_, PaymentMethodType::SamsungPay)
| (_, PaymentMethodType::Paze)
| (_, PaymentMethodType::AmazonPay) => {
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
}
(_, PaymentMethodType::DirectCarrierBilling) => {
Some(api_models::enums::PaymentExperience::CollectOtp)
}
(_, PaymentMethodType::Cashapp) | (_, PaymentMethodType::Swish) => {
Some(api_models::enums::PaymentExperience::DisplayQrCode)
}
_ => Some(api_models::enums::PaymentExperience::RedirectToUrl),
},
}
}
pub fn transform_payment_method(
connector: Connector,
provider: Vec<Provider>,
payment_method: PaymentMethod,
) -> Vec<payment_methods::RequestPaymentMethodTypes> {
let mut payment_method_types = Vec::new();
for method_type in provider {
let data = payment_methods::RequestPaymentMethodTypes {
payment_method_type: method_type.payment_method_type,
card_networks: None,
minimum_amount: Some(MinorUnit::zero()),
maximum_amount: Some(MinorUnit::new(68607706)),
recurring_enabled: Some(true),
installment_payment_enabled: Some(false),
accepted_currencies: method_type.accepted_currencies,
accepted_countries: method_type.accepted_countries,
payment_experience: Self::get_payment_experience(
connector,
method_type.payment_method_type,
payment_method,
method_type.payment_experience,
),
};
payment_method_types.push(data)
}
payment_method_types
}
pub fn create_connector_request(
request: Self,
api_response: ConnectorApiIntegrationPayload,
) -> ConnectorApiIntegrationPayload {
let mut card_payment_method_types = Vec::new();
let mut payment_method_enabled = Vec::new();
if let Some(payment_methods_enabled) = request.payment_methods_enabled.clone() {
for payload in payment_methods_enabled {
match payload.payment_method {
PaymentMethod::Card => {
if let Some(card_provider) = payload.card_provider {
let payment_type =
PaymentMethodType::from_str(&payload.payment_method_type)
.map_err(|_| "Invalid key received".to_string());
if let Ok(payment_type) = payment_type {
for method in card_provider {
let data = payment_methods::RequestPaymentMethodTypes {
payment_method_type: payment_type,
card_networks: Some(vec![method.payment_method_type]),
minimum_amount: Some(MinorUnit::zero()),
maximum_amount: Some(MinorUnit::new(68607706)),
recurring_enabled: Some(true),
installment_payment_enabled: Some(false),
accepted_currencies: method.accepted_currencies,
accepted_countries: method.accepted_countries,
payment_experience: None,
};
card_payment_method_types.push(data)
}
}
}
}
PaymentMethod::BankRedirect
| PaymentMethod::Wallet
| PaymentMethod::PayLater
| PaymentMethod::BankTransfer
| PaymentMethod::Crypto
| PaymentMethod::BankDebit
| PaymentMethod::Reward
| PaymentMethod::RealTimePayment
| PaymentMethod::Upi
| PaymentMethod::Voucher
| PaymentMethod::GiftCard
| PaymentMethod::OpenBanking
| PaymentMethod::CardRedirect
| PaymentMethod::MobilePayment
| PaymentMethod::NetworkToken => {
if let Some(provider) = payload.provider {
let val = Self::transform_payment_method(
request.connector,
provider,
payload.payment_method,
);
if !val.is_empty() {
let methods = PaymentMethodsEnabled {
payment_method: payload.payment_method,
payment_method_types: Some(val),
};
payment_method_enabled.push(methods);
}
}
}
};
}
if !card_payment_method_types.is_empty() {
let card = PaymentMethodsEnabled {
payment_method: PaymentMethod::Card,
payment_method_types: Some(card_payment_method_types),
};
payment_method_enabled.push(card);
}
}
ConnectorApiIntegrationPayload {
connector_type: api_response.connector_type,
profile_id: api_response.profile_id,
connector_name: api_response.connector_name,
connector_label: api_response.connector_label,
merchant_connector_id: api_response.merchant_connector_id,
disabled: api_response.disabled,
test_mode: api_response.test_mode,
payment_methods_enabled: Some(payment_method_enabled),
connector_webhook_details: api_response.connector_webhook_details,
metadata: request.metadata,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/lib.rs | crates/common_enums/src/lib.rs | pub mod connector_enums;
pub mod enums;
pub mod transformers;
pub use enums::*;
pub use transformers::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/enums.rs | crates/common_enums/src/enums.rs | mod accounts;
mod payments;
mod ui;
use std::{
collections::HashSet,
fmt,
num::{ParseFloatError, TryFromIntError},
str::FromStr,
};
pub use accounts::{
MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType,
};
use diesel::{
backend::Backend,
deserialize::FromSql,
expression::AsExpression,
serialize::{Output, ToSql},
sql_types::Text,
};
pub use payments::ProductType;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use smithy::SmithyModel;
pub use ui::*;
use utoipa::ToSchema;
pub use super::connector_enums::InvoiceStatus;
#[doc(hidden)]
pub mod diesel_exports {
pub use super::{
DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus,
DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind,
DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus,
DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage,
DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus,
DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus,
DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode,
DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus,
DbRefundStatus as RefundStatus,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRoutingApproach as RoutingApproach, DbScaExemptionType as ScaExemptionType,
DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState,
DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub type ApplicationResult<T> = Result<T, ApplicationError>;
#[derive(Debug, thiserror::Error)]
pub enum ApplicationError {
#[error("Application configuration error")]
ConfigurationError,
#[error("Invalid configuration value provided: {0}")]
InvalidConfigurationValueError(String),
#[error("Metrics error")]
MetricsError,
#[error("I/O: {0}")]
IoError(std::io::Error),
#[error("Error while constructing api client: {0}")]
ApiClientError(ApiClientError),
}
#[derive(Debug, thiserror::Error, PartialEq, Clone)]
pub enum ApiClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
#[error("Invalid proxy configuration")]
InvalidProxyConfiguration,
#[error("Client construction failed")]
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
#[error("Request body serialization failed")]
BodySerializationFailed,
#[error("Unexpected state reached/Invariants conflicted")]
UnexpectedState,
#[error("Failed to parse URL")]
UrlParsingFailed,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
#[error("Failed to send request to connector {0}")]
RequestNotSent(String),
#[error("Failed to decode response")]
ResponseDecodingFailed,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("connection closed before a message could complete")]
ConnectionClosedIncompleteMessage,
#[error("Server responded with Internal Server Error")]
InternalServerErrorReceived,
#[error("Server responded with Bad Gateway")]
BadGatewayReceived,
#[error("Server responded with Service Unavailable")]
ServiceUnavailableReceived,
#[error("Server responded with Gateway Timeout")]
GatewayTimeoutReceived,
#[error("Server responded with unexpected response")]
UnexpectedServerResponse,
}
impl ApiClientError {
pub fn is_upstream_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
pub fn is_connection_closed_before_message_could_complete(&self) -> bool {
self == &Self::ConnectionClosedIncompleteMessage
}
}
impl From<std::io::Error> for ApplicationError {
fn from(err: std::io::Error) -> Self {
Self::IoError(err)
}
}
/// The status of the attempt
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum AttemptStatus {
Started,
AuthenticationFailed,
RouterDeclined,
AuthenticationPending,
AuthenticationSuccessful,
Authorized,
AuthorizationFailed,
Charged,
Authorizing,
CodInitiated,
Voided,
VoidedPostCharge,
VoidInitiated,
CaptureInitiated,
CaptureFailed,
VoidFailed,
AutoRefunded,
PartialCharged,
PartiallyAuthorized,
PartialChargedAndChargeable,
Unresolved,
#[default]
Pending,
Failure,
PaymentMethodAwaited,
ConfirmationAwaited,
DeviceDataCollectionPending,
IntegrityFailure,
Expired,
}
impl AttemptStatus {
pub fn is_terminal_status(self) -> bool {
match self {
Self::RouterDeclined
| Self::Charged
| Self::AutoRefunded
| Self::Voided
| Self::VoidedPostCharge
| Self::VoidFailed
| Self::CaptureFailed
| Self::Failure
| Self::PartialCharged
| Self::Expired => true,
Self::Started
| Self::AuthenticationFailed
| Self::AuthenticationPending
| Self::AuthenticationSuccessful
| Self::Authorized
| Self::PartiallyAuthorized
| Self::AuthorizationFailed
| Self::Authorizing
| Self::CodInitiated
| Self::VoidInitiated
| Self::CaptureInitiated
| Self::PartialChargedAndChargeable
| Self::Unresolved
| Self::Pending
| Self::PaymentMethodAwaited
| Self::ConfirmationAwaited
| Self::DeviceDataCollectionPending
| Self::IntegrityFailure => false,
}
}
pub fn is_payment_terminal_failure(self) -> bool {
match self {
Self::RouterDeclined
| Self::Failure
| Self::Expired
| Self::VoidFailed
| Self::CaptureFailed
| Self::AuthenticationFailed
| Self::AuthorizationFailed => true,
Self::Started
| Self::AuthenticationPending
| Self::AuthenticationSuccessful
| Self::Authorized
| Self::Charged
| Self::Authorizing
| Self::CodInitiated
| Self::Voided
| Self::VoidedPostCharge
| Self::VoidInitiated
| Self::CaptureInitiated
| Self::AutoRefunded
| Self::PartialCharged
| Self::PartiallyAuthorized
| Self::PartialChargedAndChargeable
| Self::Unresolved
| Self::Pending
| Self::PaymentMethodAwaited
| Self::ConfirmationAwaited
| Self::DeviceDataCollectionPending
| Self::IntegrityFailure => false,
}
}
pub fn is_success(self) -> bool {
matches!(self, Self::Charged | Self::PartialCharged)
}
}
#[derive(
Clone,
Copy,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ApplePayPaymentMethodType {
Debit,
Credit,
Prepaid,
Store,
}
/// Indicates the method by which a card is discovered during a payment
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum CardDiscovery {
#[default]
Manual,
SavedCard,
ClickToPay,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RevenueRecoveryAlgorithmType {
#[default]
Monitoring,
Smart,
Cascading,
}
#[derive(
Default,
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GsmDecision {
Retry,
#[default]
DoDefault,
}
#[derive(
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum RecommendedAction {
DoNotRetry,
RetryAfter10Days,
RetryAfter1Hour,
RetryAfter24Hours,
RetryAfter2Days,
RetryAfter4Days,
RetryAfter6Days,
RetryAfter8Days,
RetryAfterInstrumentUpdate,
RetryLater,
RetryWithDifferentPaymentMethodData,
StopRecurring,
}
#[derive(
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum GsmFeature {
Retry,
}
#[derive(
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum StandardisedCode {
AccountClosedOrInvalid,
AuthenticationFailed,
AuthenticationRequired,
AuthorizationMissingOrRevoked,
CardLostOrStolen,
CardNotSupportedRestricted,
CfgPmNotEnabledOrMisconfigured,
ComplianceOrSanctionsRestriction,
ConfigurationIssue,
CreditLimitExceeded,
CurrencyOrCorridorNotEnabled,
DoNotHonor,
DownstreamTechnicalIssue,
DuplicateRequest,
GenericUnknownError,
IncorrectAuthenticationCode,
InsufficientFunds,
IntegCryptographicIssue,
IntegrationIssue,
InvalidCardNumber,
InvalidCredentials,
InvalidCvv,
InvalidExpiryDate,
InvalidState,
IssuerUnavailable,
MerchantInactive,
MissingOrInvalidParam,
OperationNotAllowed,
PaymentCancelledByUser,
PaymentMethodIssue,
PaymentSessionTimeout,
PmAddressMismatch,
PspAcquirerError,
PspFraudEngineDecline,
RateLimit,
StoredCredentialOrMitNotEnabled,
SubscriptionPlanInactive,
SuspectedFraud,
ThreeDsAuthenticationServiceIssue,
ThreeDsConfigurationIssue,
ThreeDsDataOrProtocolInvalid,
TransactionNotPermitted,
TransactionTimedOut,
VelocityLimitExceeded,
WalletOrTokenConfigIssue,
}
/// Specifies the type of cardholder authentication to be applied for a payment.
///
/// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer.
/// - `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified.
///
/// Note: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum AuthenticationType {
/// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer
ThreeDs,
/// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant.
#[default]
NoThreeDs,
}
impl AuthenticationType {
pub fn is_three_ds(&self) -> bool {
matches!(self, Self::ThreeDs)
}
}
/// The status of the capture
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
pub enum FraudCheckStatus {
Fraud,
ManualReview,
#[default]
Pending,
Legit,
TransactionFailure,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum CaptureStatus {
// Capture request initiated
#[default]
Started,
// Capture request was successful
Charged,
// Capture is pending at connector side
Pending,
// Capture request failed
Failed,
}
#[derive(
Default,
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum AuthorizationStatus {
Success,
Failure,
// Processing state is before calling connector
#[default]
Processing,
// Requires merchant action
Unresolved,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentResourceUpdateStatus {
Success,
Failure,
}
impl PaymentResourceUpdateStatus {
pub fn is_success(&self) -> bool {
matches!(self, Self::Success)
}
}
#[derive(
Clone,
Debug,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BlocklistDataKind {
PaymentMethod,
CardBin,
ExtendedCardBin,
}
/// Specifies how the payment is captured.
/// - `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted.
/// - `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum CaptureMethod {
/// Post the payment authorization, the capture will be executed on the full amount immediately.
#[default]
Automatic,
/// The capture will happen only if the merchant triggers a Capture API request. Allows for a single capture of the authorized amount.
Manual,
/// The capture will happen only if the merchant triggers a Capture API request. Allows for multiple partial captures up to the authorized amount.
ManualMultiple,
/// The capture can be scheduled to automatically get triggered at a specific date & time.
Scheduled,
/// Handles separate auth and capture sequentially; effectively the same as `Automatic` for most connectors.
SequentialAutomatic,
}
/// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking.
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
strum::Display,
strum::EnumString,
serde::Deserialize,
serde::Serialize,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ConnectorType {
/// PayFacs, Acquirers, Gateways, BNPL etc
PaymentProcessor,
/// Fraud, Currency Conversion, Crypto etc
PaymentVas,
/// Accounting, Billing, Invoicing, Tax etc
FinOperations,
/// Inventory, ERP, CRM, KYC etc
FizOperations,
/// Payment Networks like Visa, MasterCard etc
Networks,
/// All types of banks including corporate / commercial / personal / neo banks
BankingEntities,
/// All types of non-banking financial institutions including Insurance, Credit / Lending etc
NonBankingFinance,
/// Acquirers, Gateways etc
PayoutProcessor,
/// PaymentMethods Auth Services
PaymentMethodAuth,
/// 3DS Authentication Service Providers
AuthenticationProcessor,
/// Tax Calculation Processor
TaxProcessor,
/// Represents billing processors that handle subscription management, invoicing,
/// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing.
BillingProcessor,
/// Represents vaulting processors that handle the storage and management of payment method data
VaultProcessor,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentAction {
PSync,
CompleteAuthorize,
PaymentAuthenticateCompleteAuthorize,
}
#[derive(Clone, PartialEq)]
pub enum CallConnectorAction {
Trigger,
Avoid,
StatusUpdate {
status: AttemptStatus,
error_code: Option<String>,
error_message: Option<String>,
},
HandleResponse(Vec<u8>),
UCSConsumeResponse(Vec<u8>),
UCSHandleResponse(Vec<u8>),
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
SmithyModel,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "UPPERCASE")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum DocumentKind {
Cnpj,
Cpf,
}
/// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment.
#[allow(clippy::upper_case_acronyms)]
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
SmithyModel,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum Currency {
AED,
AFN,
ALL,
AMD,
ANG,
AOA,
ARS,
AUD,
AWG,
AZN,
BAM,
BBD,
BDT,
BGN,
BHD,
BIF,
BMD,
BND,
BOB,
BRL,
BSD,
BTN,
BWP,
BYN,
BZD,
CAD,
CDF,
CHF,
CLF,
CLP,
CNY,
COP,
CRC,
CUC,
CUP,
CVE,
CZK,
DJF,
DKK,
DOP,
DZD,
EGP,
ERN,
ETB,
EUR,
FJD,
FKP,
GBP,
GEL,
GHS,
GIP,
GMD,
GNF,
GTQ,
GYD,
HKD,
HNL,
HRK,
HTG,
HUF,
IDR,
ILS,
INR,
IQD,
IRR,
ISK,
JMD,
JOD,
JPY,
KES,
KGS,
KHR,
KMF,
KPW,
KRW,
KWD,
KYD,
KZT,
LAK,
LBP,
LKR,
LRD,
LSL,
LYD,
MAD,
MDL,
MGA,
MKD,
MMK,
MNT,
MOP,
MRU,
MUR,
MVR,
MWK,
MXN,
MYR,
MZN,
NAD,
NGN,
NIO,
NOK,
NPR,
NZD,
OMR,
PAB,
PEN,
PGK,
PHP,
PKR,
PLN,
PYG,
QAR,
RON,
RSD,
RUB,
RWF,
SAR,
SBD,
SCR,
SDG,
SEK,
SGD,
SHP,
SLE,
SLL,
SOS,
SRD,
SSP,
STD,
STN,
SVC,
SYP,
SZL,
THB,
TJS,
TMT,
TND,
TOP,
TRY,
TTD,
TWD,
TZS,
UAH,
UGX,
#[default]
USD,
UYU,
UZS,
VES,
VND,
VUV,
WST,
XAF,
XCD,
XOF,
XPF,
YER,
ZAR,
ZMW,
ZWL,
}
impl Currency {
/// Convert the amount to its base denomination based on Currency and return String
pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
Ok(format!("{amount_f64:.2}"))
}
/// Convert the amount to its base denomination based on Currency and return f64
pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> {
let amount_f64: f64 = u32::try_from(amount)?.into();
let amount = if self.is_zero_decimal_currency() {
amount_f64
} else if self.is_three_decimal_currency() {
amount_f64 / 1000.00
} else {
amount_f64 / 100.00
};
Ok(amount)
}
///Convert the higher decimal amount to its base absolute units
pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> {
let amount_f64 = amount.parse::<f64>()?;
let amount_string = if self.is_zero_decimal_currency() {
amount_f64
} else if self.is_three_decimal_currency() {
amount_f64 * 1000.00
} else {
amount_f64 * 100.00
};
Ok(amount_string.to_string())
}
/// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
pub fn to_currency_base_unit_with_zero_decimal_check(
self,
amount: i64,
) -> Result<String, TryFromIntError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
if self.is_zero_decimal_currency() {
Ok(amount_f64.to_string())
} else {
Ok(format!("{amount_f64:.2}"))
}
}
pub fn iso_4217(self) -> &'static str {
match self {
Self::AED => "784",
Self::AFN => "971",
Self::ALL => "008",
Self::AMD => "051",
Self::ANG => "532",
Self::AOA => "973",
Self::ARS => "032",
Self::AUD => "036",
Self::AWG => "533",
Self::AZN => "944",
Self::BAM => "977",
Self::BBD => "052",
Self::BDT => "050",
Self::BGN => "975",
Self::BHD => "048",
Self::BIF => "108",
Self::BMD => "060",
Self::BND => "096",
Self::BOB => "068",
Self::BRL => "986",
Self::BSD => "044",
Self::BTN => "064",
Self::BWP => "072",
Self::BYN => "933",
Self::BZD => "084",
Self::CAD => "124",
Self::CDF => "976",
Self::CHF => "756",
Self::CLF => "990",
Self::CLP => "152",
Self::COP => "170",
Self::CRC => "188",
Self::CUC => "931",
Self::CUP => "192",
Self::CVE => "132",
Self::CZK => "203",
Self::DJF => "262",
Self::DKK => "208",
Self::DOP => "214",
Self::DZD => "012",
Self::EGP => "818",
Self::ERN => "232",
Self::ETB => "230",
Self::EUR => "978",
Self::FJD => "242",
Self::FKP => "238",
Self::GBP => "826",
Self::GEL => "981",
Self::GHS => "936",
Self::GIP => "292",
Self::GMD => "270",
Self::GNF => "324",
Self::GTQ => "320",
Self::GYD => "328",
Self::HKD => "344",
Self::HNL => "340",
Self::HTG => "332",
Self::HUF => "348",
Self::HRK => "191",
Self::IDR => "360",
Self::ILS => "376",
Self::INR => "356",
Self::IQD => "368",
Self::IRR => "364",
Self::ISK => "352",
Self::JMD => "388",
Self::JOD => "400",
Self::JPY => "392",
Self::KES => "404",
Self::KGS => "417",
Self::KHR => "116",
Self::KMF => "174",
Self::KPW => "408",
Self::KRW => "410",
Self::KWD => "414",
Self::KYD => "136",
Self::KZT => "398",
Self::LAK => "418",
Self::LBP => "422",
Self::LKR => "144",
Self::LRD => "430",
Self::LSL => "426",
Self::LYD => "434",
Self::MAD => "504",
Self::MDL => "498",
Self::MGA => "969",
Self::MKD => "807",
Self::MMK => "104",
Self::MNT => "496",
Self::MOP => "446",
Self::MRU => "929",
Self::MUR => "480",
Self::MVR => "462",
Self::MWK => "454",
Self::MXN => "484",
Self::MYR => "458",
Self::MZN => "943",
Self::NAD => "516",
Self::NGN => "566",
Self::NIO => "558",
Self::NOK => "578",
Self::NPR => "524",
Self::NZD => "554",
Self::OMR => "512",
Self::PAB => "590",
Self::PEN => "604",
Self::PGK => "598",
Self::PHP => "608",
Self::PKR => "586",
Self::PLN => "985",
Self::PYG => "600",
Self::QAR => "634",
Self::RON => "946",
Self::CNY => "156",
Self::RSD => "941",
Self::RUB => "643",
Self::RWF => "646",
Self::SAR => "682",
Self::SBD => "090",
Self::SCR => "690",
Self::SDG => "938",
Self::SEK => "752",
Self::SGD => "702",
Self::SHP => "654",
Self::SLE => "925",
Self::SLL => "694",
Self::SOS => "706",
Self::SRD => "968",
Self::SSP => "728",
Self::STD => "678",
Self::STN => "930",
Self::SVC => "222",
Self::SYP => "760",
Self::SZL => "748",
Self::THB => "764",
Self::TJS => "972",
Self::TMT => "934",
Self::TND => "788",
Self::TOP => "776",
Self::TRY => "949",
Self::TTD => "780",
Self::TWD => "901",
Self::TZS => "834",
Self::UAH => "980",
Self::UGX => "800",
Self::USD => "840",
Self::UYU => "858",
Self::UZS => "860",
Self::VES => "928",
Self::VND => "704",
Self::VUV => "548",
Self::WST => "882",
Self::XAF => "950",
Self::XCD => "951",
Self::XOF => "952",
Self::XPF => "953",
Self::YER => "886",
Self::ZAR => "710",
Self::ZMW => "967",
Self::ZWL => "932",
}
}
pub fn is_zero_decimal_currency(self) -> bool {
match self {
Self::BIF
| Self::CLP
| Self::DJF
| Self::GNF
| Self::IRR
| Self::JPY
| Self::KMF
| Self::KRW
| Self::MGA
| Self::PYG
| Self::RWF
| Self::UGX
| Self::VND
| Self::VUV
| Self::XAF
| Self::XOF
| Self::XPF => true,
Self::AED
| Self::AFN
| Self::ALL
| Self::AMD
| Self::ANG
| Self::AOA
| Self::ARS
| Self::AUD
| Self::AWG
| Self::AZN
| Self::BAM
| Self::BBD
| Self::BDT
| Self::BGN
| Self::BHD
| Self::BMD
| Self::BND
| Self::BOB
| Self::BRL
| Self::BSD
| Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
| Self::CDF
| Self::CHF
| Self::CLF
| Self::CNY
| Self::COP
| Self::CRC
| Self::CUC
| Self::CUP
| Self::CVE
| Self::CZK
| Self::DKK
| Self::DOP
| Self::DZD
| Self::EGP
| Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
| Self::FKP
| Self::GBP
| Self::GEL
| Self::GHS
| Self::GIP
| Self::GMD
| Self::GTQ
| Self::GYD
| Self::HKD
| Self::HNL
| Self::HRK
| Self::HTG
| Self::HUF
| Self::IDR
| Self::ILS
| Self::INR
| Self::IQD
| Self::ISK
| Self::JMD
| Self::JOD
| Self::KES
| Self::KGS
| Self::KHR
| Self::KPW
| Self::KWD
| Self::KYD
| Self::KZT
| Self::LAK
| Self::LBP
| Self::LKR
| Self::LRD
| Self::LSL
| Self::LYD
| Self::MAD
| Self::MDL
| Self::MKD
| Self::MMK
| Self::MNT
| Self::MOP
| Self::MRU
| Self::MUR
| Self::MVR
| Self::MWK
| Self::MXN
| Self::MYR
| Self::MZN
| Self::NAD
| Self::NGN
| Self::NIO
| Self::NOK
| Self::NPR
| Self::NZD
| Self::OMR
| Self::PAB
| Self::PEN
| Self::PGK
| Self::PHP
| Self::PKR
| Self::PLN
| Self::QAR
| Self::RON
| Self::RSD
| Self::RUB
| Self::SAR
| Self::SBD
| Self::SCR
| Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
| Self::SLE
| Self::SLL
| Self::SOS
| Self::SRD
| Self::SSP
| Self::STD
| Self::STN
| Self::SVC
| Self::SYP
| Self::SZL
| Self::THB
| Self::TJS
| Self::TMT
| Self::TND
| Self::TOP
| Self::TRY
| Self::TTD
| Self::TWD
| Self::TZS
| Self::UAH
| Self::USD
| Self::UYU
| Self::UZS
| Self::VES
| Self::WST
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/transformers.rs | crates/common_enums/src/transformers.rs | use std::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::enums::PayoutStatus;
use crate::enums::{
AttemptStatus, Country, CountryAlpha2, CountryAlpha3, DisputeStatus, EventType, IntentStatus,
MandateStatus, PaymentMethod, PaymentMethodType, RefundStatus, SubscriptionStatus,
};
impl Display for NumericCountryCodeParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Invalid Country Code")
}
}
impl CountryAlpha2 {
pub const fn from_alpha2_to_alpha3(code: Self) -> CountryAlpha3 {
match code {
Self::AF => CountryAlpha3::AFG,
Self::AX => CountryAlpha3::ALA,
Self::AL => CountryAlpha3::ALB,
Self::DZ => CountryAlpha3::DZA,
Self::AS => CountryAlpha3::ASM,
Self::AD => CountryAlpha3::AND,
Self::AO => CountryAlpha3::AGO,
Self::AI => CountryAlpha3::AIA,
Self::AQ => CountryAlpha3::ATA,
Self::AG => CountryAlpha3::ATG,
Self::AR => CountryAlpha3::ARG,
Self::AM => CountryAlpha3::ARM,
Self::AW => CountryAlpha3::ABW,
Self::AU => CountryAlpha3::AUS,
Self::AT => CountryAlpha3::AUT,
Self::AZ => CountryAlpha3::AZE,
Self::BS => CountryAlpha3::BHS,
Self::BH => CountryAlpha3::BHR,
Self::BD => CountryAlpha3::BGD,
Self::BB => CountryAlpha3::BRB,
Self::BY => CountryAlpha3::BLR,
Self::BE => CountryAlpha3::BEL,
Self::BZ => CountryAlpha3::BLZ,
Self::BJ => CountryAlpha3::BEN,
Self::BM => CountryAlpha3::BMU,
Self::BT => CountryAlpha3::BTN,
Self::BO => CountryAlpha3::BOL,
Self::BQ => CountryAlpha3::BES,
Self::BA => CountryAlpha3::BIH,
Self::BW => CountryAlpha3::BWA,
Self::BV => CountryAlpha3::BVT,
Self::BR => CountryAlpha3::BRA,
Self::IO => CountryAlpha3::IOT,
Self::BN => CountryAlpha3::BRN,
Self::BG => CountryAlpha3::BGR,
Self::BF => CountryAlpha3::BFA,
Self::BI => CountryAlpha3::BDI,
Self::CV => CountryAlpha3::CPV,
Self::KH => CountryAlpha3::KHM,
Self::CM => CountryAlpha3::CMR,
Self::CA => CountryAlpha3::CAN,
Self::KY => CountryAlpha3::CYM,
Self::CF => CountryAlpha3::CAF,
Self::TD => CountryAlpha3::TCD,
Self::CL => CountryAlpha3::CHL,
Self::CN => CountryAlpha3::CHN,
Self::CX => CountryAlpha3::CXR,
Self::CC => CountryAlpha3::CCK,
Self::CO => CountryAlpha3::COL,
Self::KM => CountryAlpha3::COM,
Self::CG => CountryAlpha3::COG,
Self::CD => CountryAlpha3::COD,
Self::CK => CountryAlpha3::COK,
Self::CR => CountryAlpha3::CRI,
Self::CI => CountryAlpha3::CIV,
Self::HR => CountryAlpha3::HRV,
Self::CU => CountryAlpha3::CUB,
Self::CW => CountryAlpha3::CUW,
Self::CY => CountryAlpha3::CYP,
Self::CZ => CountryAlpha3::CZE,
Self::DK => CountryAlpha3::DNK,
Self::DJ => CountryAlpha3::DJI,
Self::DM => CountryAlpha3::DMA,
Self::DO => CountryAlpha3::DOM,
Self::EC => CountryAlpha3::ECU,
Self::EG => CountryAlpha3::EGY,
Self::SV => CountryAlpha3::SLV,
Self::GQ => CountryAlpha3::GNQ,
Self::ER => CountryAlpha3::ERI,
Self::EE => CountryAlpha3::EST,
Self::ET => CountryAlpha3::ETH,
Self::FK => CountryAlpha3::FLK,
Self::FO => CountryAlpha3::FRO,
Self::FJ => CountryAlpha3::FJI,
Self::FI => CountryAlpha3::FIN,
Self::FR => CountryAlpha3::FRA,
Self::GF => CountryAlpha3::GUF,
Self::PF => CountryAlpha3::PYF,
Self::TF => CountryAlpha3::ATF,
Self::GA => CountryAlpha3::GAB,
Self::GM => CountryAlpha3::GMB,
Self::GE => CountryAlpha3::GEO,
Self::DE => CountryAlpha3::DEU,
Self::GH => CountryAlpha3::GHA,
Self::GI => CountryAlpha3::GIB,
Self::GR => CountryAlpha3::GRC,
Self::GL => CountryAlpha3::GRL,
Self::GD => CountryAlpha3::GRD,
Self::GP => CountryAlpha3::GLP,
Self::GU => CountryAlpha3::GUM,
Self::GT => CountryAlpha3::GTM,
Self::GG => CountryAlpha3::GGY,
Self::GN => CountryAlpha3::GIN,
Self::GW => CountryAlpha3::GNB,
Self::GY => CountryAlpha3::GUY,
Self::HT => CountryAlpha3::HTI,
Self::HM => CountryAlpha3::HMD,
Self::VA => CountryAlpha3::VAT,
Self::HN => CountryAlpha3::HND,
Self::HK => CountryAlpha3::HKG,
Self::HU => CountryAlpha3::HUN,
Self::IS => CountryAlpha3::ISL,
Self::IN => CountryAlpha3::IND,
Self::ID => CountryAlpha3::IDN,
Self::IR => CountryAlpha3::IRN,
Self::IQ => CountryAlpha3::IRQ,
Self::IE => CountryAlpha3::IRL,
Self::IM => CountryAlpha3::IMN,
Self::IL => CountryAlpha3::ISR,
Self::IT => CountryAlpha3::ITA,
Self::JM => CountryAlpha3::JAM,
Self::JP => CountryAlpha3::JPN,
Self::JE => CountryAlpha3::JEY,
Self::JO => CountryAlpha3::JOR,
Self::KZ => CountryAlpha3::KAZ,
Self::KE => CountryAlpha3::KEN,
Self::KI => CountryAlpha3::KIR,
Self::KP => CountryAlpha3::PRK,
Self::KR => CountryAlpha3::KOR,
Self::KW => CountryAlpha3::KWT,
Self::KG => CountryAlpha3::KGZ,
Self::LA => CountryAlpha3::LAO,
Self::LV => CountryAlpha3::LVA,
Self::LB => CountryAlpha3::LBN,
Self::LS => CountryAlpha3::LSO,
Self::LR => CountryAlpha3::LBR,
Self::LY => CountryAlpha3::LBY,
Self::LI => CountryAlpha3::LIE,
Self::LT => CountryAlpha3::LTU,
Self::LU => CountryAlpha3::LUX,
Self::MO => CountryAlpha3::MAC,
Self::MK => CountryAlpha3::MKD,
Self::MG => CountryAlpha3::MDG,
Self::MW => CountryAlpha3::MWI,
Self::MY => CountryAlpha3::MYS,
Self::MV => CountryAlpha3::MDV,
Self::ML => CountryAlpha3::MLI,
Self::MT => CountryAlpha3::MLT,
Self::MH => CountryAlpha3::MHL,
Self::MQ => CountryAlpha3::MTQ,
Self::MR => CountryAlpha3::MRT,
Self::MU => CountryAlpha3::MUS,
Self::YT => CountryAlpha3::MYT,
Self::MX => CountryAlpha3::MEX,
Self::FM => CountryAlpha3::FSM,
Self::MD => CountryAlpha3::MDA,
Self::MC => CountryAlpha3::MCO,
Self::MN => CountryAlpha3::MNG,
Self::ME => CountryAlpha3::MNE,
Self::MS => CountryAlpha3::MSR,
Self::MA => CountryAlpha3::MAR,
Self::MZ => CountryAlpha3::MOZ,
Self::MM => CountryAlpha3::MMR,
Self::NA => CountryAlpha3::NAM,
Self::NR => CountryAlpha3::NRU,
Self::NP => CountryAlpha3::NPL,
Self::NL => CountryAlpha3::NLD,
Self::NC => CountryAlpha3::NCL,
Self::NZ => CountryAlpha3::NZL,
Self::NI => CountryAlpha3::NIC,
Self::NE => CountryAlpha3::NER,
Self::NG => CountryAlpha3::NGA,
Self::NU => CountryAlpha3::NIU,
Self::NF => CountryAlpha3::NFK,
Self::MP => CountryAlpha3::MNP,
Self::NO => CountryAlpha3::NOR,
Self::OM => CountryAlpha3::OMN,
Self::PK => CountryAlpha3::PAK,
Self::PW => CountryAlpha3::PLW,
Self::PS => CountryAlpha3::PSE,
Self::PA => CountryAlpha3::PAN,
Self::PG => CountryAlpha3::PNG,
Self::PY => CountryAlpha3::PRY,
Self::PE => CountryAlpha3::PER,
Self::PH => CountryAlpha3::PHL,
Self::PN => CountryAlpha3::PCN,
Self::PL => CountryAlpha3::POL,
Self::PT => CountryAlpha3::PRT,
Self::PR => CountryAlpha3::PRI,
Self::QA => CountryAlpha3::QAT,
Self::RE => CountryAlpha3::REU,
Self::RO => CountryAlpha3::ROU,
Self::RU => CountryAlpha3::RUS,
Self::RW => CountryAlpha3::RWA,
Self::BL => CountryAlpha3::BLM,
Self::SH => CountryAlpha3::SHN,
Self::KN => CountryAlpha3::KNA,
Self::LC => CountryAlpha3::LCA,
Self::MF => CountryAlpha3::MAF,
Self::PM => CountryAlpha3::SPM,
Self::VC => CountryAlpha3::VCT,
Self::WS => CountryAlpha3::WSM,
Self::SM => CountryAlpha3::SMR,
Self::ST => CountryAlpha3::STP,
Self::SA => CountryAlpha3::SAU,
Self::SN => CountryAlpha3::SEN,
Self::RS => CountryAlpha3::SRB,
Self::SC => CountryAlpha3::SYC,
Self::SL => CountryAlpha3::SLE,
Self::SG => CountryAlpha3::SGP,
Self::SX => CountryAlpha3::SXM,
Self::SK => CountryAlpha3::SVK,
Self::SI => CountryAlpha3::SVN,
Self::SB => CountryAlpha3::SLB,
Self::SO => CountryAlpha3::SOM,
Self::ZA => CountryAlpha3::ZAF,
Self::GS => CountryAlpha3::SGS,
Self::SS => CountryAlpha3::SSD,
Self::ES => CountryAlpha3::ESP,
Self::LK => CountryAlpha3::LKA,
Self::SD => CountryAlpha3::SDN,
Self::SR => CountryAlpha3::SUR,
Self::SJ => CountryAlpha3::SJM,
Self::SZ => CountryAlpha3::SWZ,
Self::SE => CountryAlpha3::SWE,
Self::CH => CountryAlpha3::CHE,
Self::SY => CountryAlpha3::SYR,
Self::TW => CountryAlpha3::TWN,
Self::TJ => CountryAlpha3::TJK,
Self::TZ => CountryAlpha3::TZA,
Self::TH => CountryAlpha3::THA,
Self::TL => CountryAlpha3::TLS,
Self::TG => CountryAlpha3::TGO,
Self::TK => CountryAlpha3::TKL,
Self::TO => CountryAlpha3::TON,
Self::TT => CountryAlpha3::TTO,
Self::TN => CountryAlpha3::TUN,
Self::TR => CountryAlpha3::TUR,
Self::TM => CountryAlpha3::TKM,
Self::TC => CountryAlpha3::TCA,
Self::TV => CountryAlpha3::TUV,
Self::UG => CountryAlpha3::UGA,
Self::UA => CountryAlpha3::UKR,
Self::AE => CountryAlpha3::ARE,
Self::GB => CountryAlpha3::GBR,
Self::US => CountryAlpha3::USA,
Self::UM => CountryAlpha3::UMI,
Self::UY => CountryAlpha3::URY,
Self::UZ => CountryAlpha3::UZB,
Self::VU => CountryAlpha3::VUT,
Self::VE => CountryAlpha3::VEN,
Self::VN => CountryAlpha3::VNM,
Self::VG => CountryAlpha3::VGB,
Self::VI => CountryAlpha3::VIR,
Self::WF => CountryAlpha3::WLF,
Self::EH => CountryAlpha3::ESH,
Self::YE => CountryAlpha3::YEM,
Self::ZM => CountryAlpha3::ZMB,
Self::ZW => CountryAlpha3::ZWE,
}
}
}
impl Country {
pub const fn from_alpha2(code: CountryAlpha2) -> Self {
match code {
CountryAlpha2::AF => Self::Afghanistan,
CountryAlpha2::AX => Self::AlandIslands,
CountryAlpha2::AL => Self::Albania,
CountryAlpha2::DZ => Self::Algeria,
CountryAlpha2::AS => Self::AmericanSamoa,
CountryAlpha2::AD => Self::Andorra,
CountryAlpha2::AO => Self::Angola,
CountryAlpha2::AI => Self::Anguilla,
CountryAlpha2::AQ => Self::Antarctica,
CountryAlpha2::AG => Self::AntiguaAndBarbuda,
CountryAlpha2::AR => Self::Argentina,
CountryAlpha2::AM => Self::Armenia,
CountryAlpha2::AW => Self::Aruba,
CountryAlpha2::AU => Self::Australia,
CountryAlpha2::AT => Self::Austria,
CountryAlpha2::AZ => Self::Azerbaijan,
CountryAlpha2::BS => Self::Bahamas,
CountryAlpha2::BH => Self::Bahrain,
CountryAlpha2::BD => Self::Bangladesh,
CountryAlpha2::BB => Self::Barbados,
CountryAlpha2::BY => Self::Belarus,
CountryAlpha2::BE => Self::Belgium,
CountryAlpha2::BZ => Self::Belize,
CountryAlpha2::BJ => Self::Benin,
CountryAlpha2::BM => Self::Bermuda,
CountryAlpha2::BT => Self::Bhutan,
CountryAlpha2::BO => Self::BoliviaPlurinationalState,
CountryAlpha2::BQ => Self::BonaireSintEustatiusAndSaba,
CountryAlpha2::BA => Self::BosniaAndHerzegovina,
CountryAlpha2::BW => Self::Botswana,
CountryAlpha2::BV => Self::BouvetIsland,
CountryAlpha2::BR => Self::Brazil,
CountryAlpha2::IO => Self::BritishIndianOceanTerritory,
CountryAlpha2::BN => Self::BruneiDarussalam,
CountryAlpha2::BG => Self::Bulgaria,
CountryAlpha2::BF => Self::BurkinaFaso,
CountryAlpha2::BI => Self::Burundi,
CountryAlpha2::CV => Self::CaboVerde,
CountryAlpha2::KH => Self::Cambodia,
CountryAlpha2::CM => Self::Cameroon,
CountryAlpha2::CA => Self::Canada,
CountryAlpha2::KY => Self::CaymanIslands,
CountryAlpha2::CF => Self::CentralAfricanRepublic,
CountryAlpha2::TD => Self::Chad,
CountryAlpha2::CL => Self::Chile,
CountryAlpha2::CN => Self::China,
CountryAlpha2::CX => Self::ChristmasIsland,
CountryAlpha2::CC => Self::CocosKeelingIslands,
CountryAlpha2::CO => Self::Colombia,
CountryAlpha2::KM => Self::Comoros,
CountryAlpha2::CG => Self::Congo,
CountryAlpha2::CD => Self::CongoDemocraticRepublic,
CountryAlpha2::CK => Self::CookIslands,
CountryAlpha2::CR => Self::CostaRica,
CountryAlpha2::CI => Self::CotedIvoire,
CountryAlpha2::HR => Self::Croatia,
CountryAlpha2::CU => Self::Cuba,
CountryAlpha2::CW => Self::Curacao,
CountryAlpha2::CY => Self::Cyprus,
CountryAlpha2::CZ => Self::Czechia,
CountryAlpha2::DK => Self::Denmark,
CountryAlpha2::DJ => Self::Djibouti,
CountryAlpha2::DM => Self::Dominica,
CountryAlpha2::DO => Self::DominicanRepublic,
CountryAlpha2::EC => Self::Ecuador,
CountryAlpha2::EG => Self::Egypt,
CountryAlpha2::SV => Self::ElSalvador,
CountryAlpha2::GQ => Self::EquatorialGuinea,
CountryAlpha2::ER => Self::Eritrea,
CountryAlpha2::EE => Self::Estonia,
CountryAlpha2::ET => Self::Ethiopia,
CountryAlpha2::FK => Self::FalklandIslandsMalvinas,
CountryAlpha2::FO => Self::FaroeIslands,
CountryAlpha2::FJ => Self::Fiji,
CountryAlpha2::FI => Self::Finland,
CountryAlpha2::FR => Self::France,
CountryAlpha2::GF => Self::FrenchGuiana,
CountryAlpha2::PF => Self::FrenchPolynesia,
CountryAlpha2::TF => Self::FrenchSouthernTerritories,
CountryAlpha2::GA => Self::Gabon,
CountryAlpha2::GM => Self::Gambia,
CountryAlpha2::GE => Self::Georgia,
CountryAlpha2::DE => Self::Germany,
CountryAlpha2::GH => Self::Ghana,
CountryAlpha2::GI => Self::Gibraltar,
CountryAlpha2::GR => Self::Greece,
CountryAlpha2::GL => Self::Greenland,
CountryAlpha2::GD => Self::Grenada,
CountryAlpha2::GP => Self::Guadeloupe,
CountryAlpha2::GU => Self::Guam,
CountryAlpha2::GT => Self::Guatemala,
CountryAlpha2::GG => Self::Guernsey,
CountryAlpha2::GN => Self::Guinea,
CountryAlpha2::GW => Self::GuineaBissau,
CountryAlpha2::GY => Self::Guyana,
CountryAlpha2::HT => Self::Haiti,
CountryAlpha2::HM => Self::HeardIslandAndMcDonaldIslands,
CountryAlpha2::VA => Self::HolySee,
CountryAlpha2::HN => Self::Honduras,
CountryAlpha2::HK => Self::HongKong,
CountryAlpha2::HU => Self::Hungary,
CountryAlpha2::IS => Self::Iceland,
CountryAlpha2::IN => Self::India,
CountryAlpha2::ID => Self::Indonesia,
CountryAlpha2::IR => Self::IranIslamicRepublic,
CountryAlpha2::IQ => Self::Iraq,
CountryAlpha2::IE => Self::Ireland,
CountryAlpha2::IM => Self::IsleOfMan,
CountryAlpha2::IL => Self::Israel,
CountryAlpha2::IT => Self::Italy,
CountryAlpha2::JM => Self::Jamaica,
CountryAlpha2::JP => Self::Japan,
CountryAlpha2::JE => Self::Jersey,
CountryAlpha2::JO => Self::Jordan,
CountryAlpha2::KZ => Self::Kazakhstan,
CountryAlpha2::KE => Self::Kenya,
CountryAlpha2::KI => Self::Kiribati,
CountryAlpha2::KP => Self::KoreaDemocraticPeoplesRepublic,
CountryAlpha2::KR => Self::KoreaRepublic,
CountryAlpha2::KW => Self::Kuwait,
CountryAlpha2::KG => Self::Kyrgyzstan,
CountryAlpha2::LA => Self::LaoPeoplesDemocraticRepublic,
CountryAlpha2::LV => Self::Latvia,
CountryAlpha2::LB => Self::Lebanon,
CountryAlpha2::LS => Self::Lesotho,
CountryAlpha2::LR => Self::Liberia,
CountryAlpha2::LY => Self::Libya,
CountryAlpha2::LI => Self::Liechtenstein,
CountryAlpha2::LT => Self::Lithuania,
CountryAlpha2::LU => Self::Luxembourg,
CountryAlpha2::MO => Self::Macao,
CountryAlpha2::MK => Self::MacedoniaTheFormerYugoslavRepublic,
CountryAlpha2::MG => Self::Madagascar,
CountryAlpha2::MW => Self::Malawi,
CountryAlpha2::MY => Self::Malaysia,
CountryAlpha2::MV => Self::Maldives,
CountryAlpha2::ML => Self::Mali,
CountryAlpha2::MT => Self::Malta,
CountryAlpha2::MH => Self::MarshallIslands,
CountryAlpha2::MQ => Self::Martinique,
CountryAlpha2::MR => Self::Mauritania,
CountryAlpha2::MU => Self::Mauritius,
CountryAlpha2::YT => Self::Mayotte,
CountryAlpha2::MX => Self::Mexico,
CountryAlpha2::FM => Self::MicronesiaFederatedStates,
CountryAlpha2::MD => Self::MoldovaRepublic,
CountryAlpha2::MC => Self::Monaco,
CountryAlpha2::MN => Self::Mongolia,
CountryAlpha2::ME => Self::Montenegro,
CountryAlpha2::MS => Self::Montserrat,
CountryAlpha2::MA => Self::Morocco,
CountryAlpha2::MZ => Self::Mozambique,
CountryAlpha2::MM => Self::Myanmar,
CountryAlpha2::NA => Self::Namibia,
CountryAlpha2::NR => Self::Nauru,
CountryAlpha2::NP => Self::Nepal,
CountryAlpha2::NL => Self::Netherlands,
CountryAlpha2::NC => Self::NewCaledonia,
CountryAlpha2::NZ => Self::NewZealand,
CountryAlpha2::NI => Self::Nicaragua,
CountryAlpha2::NE => Self::Niger,
CountryAlpha2::NG => Self::Nigeria,
CountryAlpha2::NU => Self::Niue,
CountryAlpha2::NF => Self::NorfolkIsland,
CountryAlpha2::MP => Self::NorthernMarianaIslands,
CountryAlpha2::NO => Self::Norway,
CountryAlpha2::OM => Self::Oman,
CountryAlpha2::PK => Self::Pakistan,
CountryAlpha2::PW => Self::Palau,
CountryAlpha2::PS => Self::PalestineState,
CountryAlpha2::PA => Self::Panama,
CountryAlpha2::PG => Self::PapuaNewGuinea,
CountryAlpha2::PY => Self::Paraguay,
CountryAlpha2::PE => Self::Peru,
CountryAlpha2::PH => Self::Philippines,
CountryAlpha2::PN => Self::Pitcairn,
CountryAlpha2::PL => Self::Poland,
CountryAlpha2::PT => Self::Portugal,
CountryAlpha2::PR => Self::PuertoRico,
CountryAlpha2::QA => Self::Qatar,
CountryAlpha2::RE => Self::Reunion,
CountryAlpha2::RO => Self::Romania,
CountryAlpha2::RU => Self::RussianFederation,
CountryAlpha2::RW => Self::Rwanda,
CountryAlpha2::BL => Self::SaintBarthelemy,
CountryAlpha2::SH => Self::SaintHelenaAscensionAndTristandaCunha,
CountryAlpha2::KN => Self::SaintKittsAndNevis,
CountryAlpha2::LC => Self::SaintLucia,
CountryAlpha2::MF => Self::SaintMartinFrenchpart,
CountryAlpha2::PM => Self::SaintPierreAndMiquelon,
CountryAlpha2::VC => Self::SaintVincentAndTheGrenadines,
CountryAlpha2::WS => Self::Samoa,
CountryAlpha2::SM => Self::SanMarino,
CountryAlpha2::ST => Self::SaoTomeAndPrincipe,
CountryAlpha2::SA => Self::SaudiArabia,
CountryAlpha2::SN => Self::Senegal,
CountryAlpha2::RS => Self::Serbia,
CountryAlpha2::SC => Self::Seychelles,
CountryAlpha2::SL => Self::SierraLeone,
CountryAlpha2::SG => Self::Singapore,
CountryAlpha2::SX => Self::SintMaartenDutchpart,
CountryAlpha2::SK => Self::Slovakia,
CountryAlpha2::SI => Self::Slovenia,
CountryAlpha2::SB => Self::SolomonIslands,
CountryAlpha2::SO => Self::Somalia,
CountryAlpha2::ZA => Self::SouthAfrica,
CountryAlpha2::GS => Self::SouthGeorgiaAndTheSouthSandwichIslands,
CountryAlpha2::SS => Self::SouthSudan,
CountryAlpha2::ES => Self::Spain,
CountryAlpha2::LK => Self::SriLanka,
CountryAlpha2::SD => Self::Sudan,
CountryAlpha2::SR => Self::Suriname,
CountryAlpha2::SJ => Self::SvalbardAndJanMayen,
CountryAlpha2::SZ => Self::Swaziland,
CountryAlpha2::SE => Self::Sweden,
CountryAlpha2::CH => Self::Switzerland,
CountryAlpha2::SY => Self::SyrianArabRepublic,
CountryAlpha2::TW => Self::TaiwanProvinceOfChina,
CountryAlpha2::TJ => Self::Tajikistan,
CountryAlpha2::TZ => Self::TanzaniaUnitedRepublic,
CountryAlpha2::TH => Self::Thailand,
CountryAlpha2::TL => Self::TimorLeste,
CountryAlpha2::TG => Self::Togo,
CountryAlpha2::TK => Self::Tokelau,
CountryAlpha2::TO => Self::Tonga,
CountryAlpha2::TT => Self::TrinidadAndTobago,
CountryAlpha2::TN => Self::Tunisia,
CountryAlpha2::TR => Self::Turkey,
CountryAlpha2::TM => Self::Turkmenistan,
CountryAlpha2::TC => Self::TurksAndCaicosIslands,
CountryAlpha2::TV => Self::Tuvalu,
CountryAlpha2::UG => Self::Uganda,
CountryAlpha2::UA => Self::Ukraine,
CountryAlpha2::AE => Self::UnitedArabEmirates,
CountryAlpha2::GB => Self::UnitedKingdomOfGreatBritainAndNorthernIreland,
CountryAlpha2::US => Self::UnitedStatesOfAmerica,
CountryAlpha2::UM => Self::UnitedStatesMinorOutlyingIslands,
CountryAlpha2::UY => Self::Uruguay,
CountryAlpha2::UZ => Self::Uzbekistan,
CountryAlpha2::VU => Self::Vanuatu,
CountryAlpha2::VE => Self::VenezuelaBolivarianRepublic,
CountryAlpha2::VN => Self::Vietnam,
CountryAlpha2::VG => Self::VirginIslandsBritish,
CountryAlpha2::VI => Self::VirginIslandsUS,
CountryAlpha2::WF => Self::WallisAndFutuna,
CountryAlpha2::EH => Self::WesternSahara,
CountryAlpha2::YE => Self::Yemen,
CountryAlpha2::ZM => Self::Zambia,
CountryAlpha2::ZW => Self::Zimbabwe,
}
}
pub const fn to_alpha2(self) -> CountryAlpha2 {
match self {
Self::Afghanistan => CountryAlpha2::AF,
Self::AlandIslands => CountryAlpha2::AX,
Self::Albania => CountryAlpha2::AL,
Self::Algeria => CountryAlpha2::DZ,
Self::AmericanSamoa => CountryAlpha2::AS,
Self::Andorra => CountryAlpha2::AD,
Self::Angola => CountryAlpha2::AO,
Self::Anguilla => CountryAlpha2::AI,
Self::Antarctica => CountryAlpha2::AQ,
Self::AntiguaAndBarbuda => CountryAlpha2::AG,
Self::Argentina => CountryAlpha2::AR,
Self::Armenia => CountryAlpha2::AM,
Self::Aruba => CountryAlpha2::AW,
Self::Australia => CountryAlpha2::AU,
Self::Austria => CountryAlpha2::AT,
Self::Azerbaijan => CountryAlpha2::AZ,
Self::Bahamas => CountryAlpha2::BS,
Self::Bahrain => CountryAlpha2::BH,
Self::Bangladesh => CountryAlpha2::BD,
Self::Barbados => CountryAlpha2::BB,
Self::Belarus => CountryAlpha2::BY,
Self::Belgium => CountryAlpha2::BE,
Self::Belize => CountryAlpha2::BZ,
Self::Benin => CountryAlpha2::BJ,
Self::Bermuda => CountryAlpha2::BM,
Self::Bhutan => CountryAlpha2::BT,
Self::BoliviaPlurinationalState => CountryAlpha2::BO,
Self::BonaireSintEustatiusAndSaba => CountryAlpha2::BQ,
Self::BosniaAndHerzegovina => CountryAlpha2::BA,
Self::Botswana => CountryAlpha2::BW,
Self::BouvetIsland => CountryAlpha2::BV,
Self::Brazil => CountryAlpha2::BR,
Self::BritishIndianOceanTerritory => CountryAlpha2::IO,
Self::BruneiDarussalam => CountryAlpha2::BN,
Self::Bulgaria => CountryAlpha2::BG,
Self::BurkinaFaso => CountryAlpha2::BF,
Self::Burundi => CountryAlpha2::BI,
Self::CaboVerde => CountryAlpha2::CV,
Self::Cambodia => CountryAlpha2::KH,
Self::Cameroon => CountryAlpha2::CM,
Self::Canada => CountryAlpha2::CA,
Self::CaymanIslands => CountryAlpha2::KY,
Self::CentralAfricanRepublic => CountryAlpha2::CF,
Self::Chad => CountryAlpha2::TD,
Self::Chile => CountryAlpha2::CL,
Self::China => CountryAlpha2::CN,
Self::ChristmasIsland => CountryAlpha2::CX,
Self::CocosKeelingIslands => CountryAlpha2::CC,
Self::Colombia => CountryAlpha2::CO,
Self::Comoros => CountryAlpha2::KM,
Self::Congo => CountryAlpha2::CG,
Self::CongoDemocraticRepublic => CountryAlpha2::CD,
Self::CookIslands => CountryAlpha2::CK,
Self::CostaRica => CountryAlpha2::CR,
Self::CotedIvoire => CountryAlpha2::CI,
Self::Croatia => CountryAlpha2::HR,
Self::Cuba => CountryAlpha2::CU,
Self::Curacao => CountryAlpha2::CW,
Self::Cyprus => CountryAlpha2::CY,
Self::Czechia => CountryAlpha2::CZ,
Self::Denmark => CountryAlpha2::DK,
Self::Djibouti => CountryAlpha2::DJ,
Self::Dominica => CountryAlpha2::DM,
Self::DominicanRepublic => CountryAlpha2::DO,
Self::Ecuador => CountryAlpha2::EC,
Self::Egypt => CountryAlpha2::EG,
Self::ElSalvador => CountryAlpha2::SV,
Self::EquatorialGuinea => CountryAlpha2::GQ,
Self::Eritrea => CountryAlpha2::ER,
Self::Estonia => CountryAlpha2::EE,
Self::Ethiopia => CountryAlpha2::ET,
Self::FalklandIslandsMalvinas => CountryAlpha2::FK,
Self::FaroeIslands => CountryAlpha2::FO,
Self::Fiji => CountryAlpha2::FJ,
Self::Finland => CountryAlpha2::FI,
Self::France => CountryAlpha2::FR,
Self::FrenchGuiana => CountryAlpha2::GF,
Self::FrenchPolynesia => CountryAlpha2::PF,
Self::FrenchSouthernTerritories => CountryAlpha2::TF,
Self::Gabon => CountryAlpha2::GA,
Self::Gambia => CountryAlpha2::GM,
Self::Georgia => CountryAlpha2::GE,
Self::Germany => CountryAlpha2::DE,
Self::Ghana => CountryAlpha2::GH,
Self::Gibraltar => CountryAlpha2::GI,
Self::Greece => CountryAlpha2::GR,
Self::Greenland => CountryAlpha2::GL,
Self::Grenada => CountryAlpha2::GD,
Self::Guadeloupe => CountryAlpha2::GP,
Self::Guam => CountryAlpha2::GU,
Self::Guatemala => CountryAlpha2::GT,
Self::Guernsey => CountryAlpha2::GG,
Self::Guinea => CountryAlpha2::GN,
Self::GuineaBissau => CountryAlpha2::GW,
Self::Guyana => CountryAlpha2::GY,
Self::Haiti => CountryAlpha2::HT,
Self::HeardIslandAndMcDonaldIslands => CountryAlpha2::HM,
Self::HolySee => CountryAlpha2::VA,
Self::Honduras => CountryAlpha2::HN,
Self::HongKong => CountryAlpha2::HK,
Self::Hungary => CountryAlpha2::HU,
Self::Iceland => CountryAlpha2::IS,
Self::India => CountryAlpha2::IN,
Self::Indonesia => CountryAlpha2::ID,
Self::IranIslamicRepublic => CountryAlpha2::IR,
Self::Iraq => CountryAlpha2::IQ,
Self::Ireland => CountryAlpha2::IE,
Self::IsleOfMan => CountryAlpha2::IM,
Self::Israel => CountryAlpha2::IL,
Self::Italy => CountryAlpha2::IT,
Self::Jamaica => CountryAlpha2::JM,
Self::Japan => CountryAlpha2::JP,
Self::Jersey => CountryAlpha2::JE,
Self::Jordan => CountryAlpha2::JO,
Self::Kazakhstan => CountryAlpha2::KZ,
Self::Kenya => CountryAlpha2::KE,
Self::Kiribati => CountryAlpha2::KI,
Self::KoreaDemocraticPeoplesRepublic => CountryAlpha2::KP,
Self::KoreaRepublic => CountryAlpha2::KR,
Self::Kuwait => CountryAlpha2::KW,
Self::Kyrgyzstan => CountryAlpha2::KG,
Self::LaoPeoplesDemocraticRepublic => CountryAlpha2::LA,
Self::Latvia => CountryAlpha2::LV,
Self::Lebanon => CountryAlpha2::LB,
Self::Lesotho => CountryAlpha2::LS,
Self::Liberia => CountryAlpha2::LR,
Self::Libya => CountryAlpha2::LY,
Self::Liechtenstein => CountryAlpha2::LI,
Self::Lithuania => CountryAlpha2::LT,
Self::Luxembourg => CountryAlpha2::LU,
Self::Macao => CountryAlpha2::MO,
Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha2::MK,
Self::Madagascar => CountryAlpha2::MG,
Self::Malawi => CountryAlpha2::MW,
Self::Malaysia => CountryAlpha2::MY,
Self::Maldives => CountryAlpha2::MV,
Self::Mali => CountryAlpha2::ML,
Self::Malta => CountryAlpha2::MT,
Self::MarshallIslands => CountryAlpha2::MH,
Self::Martinique => CountryAlpha2::MQ,
Self::Mauritania => CountryAlpha2::MR,
Self::Mauritius => CountryAlpha2::MU,
Self::Mayotte => CountryAlpha2::YT,
Self::Mexico => CountryAlpha2::MX,
Self::MicronesiaFederatedStates => CountryAlpha2::FM,
Self::MoldovaRepublic => CountryAlpha2::MD,
Self::Monaco => CountryAlpha2::MC,
Self::Mongolia => CountryAlpha2::MN,
Self::Montenegro => CountryAlpha2::ME,
Self::Montserrat => CountryAlpha2::MS,
Self::Morocco => CountryAlpha2::MA,
Self::Mozambique => CountryAlpha2::MZ,
Self::Myanmar => CountryAlpha2::MM,
Self::Namibia => CountryAlpha2::NA,
Self::Nauru => CountryAlpha2::NR,
Self::Nepal => CountryAlpha2::NP,
Self::Netherlands => CountryAlpha2::NL,
Self::NewCaledonia => CountryAlpha2::NC,
Self::NewZealand => CountryAlpha2::NZ,
Self::Nicaragua => CountryAlpha2::NI,
Self::Niger => CountryAlpha2::NE,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/connector_enums.rs | crates/common_enums/src/connector_enums.rs | use std::collections::HashSet;
use smithy::SmithyModel;
use utoipa::ToSchema;
pub use super::enums::{PaymentMethod, PayoutType};
pub use crate::PaymentMethodType;
// A connector is an integration to fulfill payments
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
ToSchema,
serde::Deserialize,
serde::Serialize,
strum::VariantNames,
strum::EnumIter,
strum::Display,
strum::EnumString,
Hash,
SmithyModel,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum Connector {
Authipay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_billing_test")]
#[strum(serialize = "stripe_billing_test")]
DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
DummyConnector1,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
DummyConnector2,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
DummyConnector3,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_test")]
#[strum(serialize = "stripe_test")]
DummyConnector4,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "adyen_test")]
#[strum(serialize = "adyen_test")]
DummyConnector5,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "checkout_test")]
#[strum(serialize = "checkout_test")]
DummyConnector6,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "paypal_test")]
#[strum(serialize = "paypal_test")]
DummyConnector7,
Aci,
Adyen,
Affirm,
Airwallex,
Amazonpay,
Archipel,
Authorizedotnet,
Bambora,
Bamboraapac,
Bankofamerica,
Barclaycard,
Billwerk,
Bitpay,
Bluesnap,
Blackhawknetwork,
#[serde(alias = "bluecode")]
Calida,
Boku,
Braintree,
Breadpay,
Cardinal,
Cashtocode,
Celero,
Chargebee,
Checkbook,
Checkout,
Coinbase,
Coingate,
Custombilling,
Cryptopay,
CtpMastercard,
CtpVisa,
Cybersource,
Datatrans,
Deutschebank,
Digitalvirgo,
Dlocal,
Dwolla,
Ebanx,
Elavon,
Facilitapay,
Finix,
Fiserv,
Fiservemea,
Fiuu,
Flexiti,
Forte,
Getnet,
Gigadat,
Globalpay,
Globepay,
Gocardless,
Gpayments,
Hipay,
Helcim,
HyperswitchVault,
// Hyperwallet, added as template code for future usage
Inespay,
Iatapay,
Itaubank,
Jpmorgan,
Juspaythreedsserver,
Klarna,
Loonio,
Mifinity,
Mollie,
Moneris,
Multisafepay,
Netcetera,
Nexinets,
Nexixpay,
Nmi,
Nomupay,
Noon,
Nordea,
Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
Paybox,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Payload,
Payme,
Payone,
Paypal,
Paysafe,
Paystack,
Paytm,
Payu,
Peachpayments,
Payjustnow,
Payjustnowinstore,
Phonepe,
Placetopay,
Powertranz,
Prophetpay,
Rapyd,
Razorpay,
Recurly,
Redsys,
Santander,
Shift4,
Silverflow,
Square,
Stax,
Stripe,
Stripebilling,
Taxjar,
Threedsecureio,
// Tokenio,
//Thunes,
Tesouro,
Tokenex,
Tokenio,
Trustpay,
Trustpayments,
Tsys,
// UnifiedAuthenticationService,
Vgs,
Volt,
Wellsfargo,
// Wellsfargopayout,
Wise,
Worldline,
Worldpay,
Worldpayvantiv,
Worldpayxml,
Signifyd,
Plaid,
Riskified,
Xendit,
Zen,
Zift,
Zsl,
}
impl Connector {
#[cfg(feature = "payouts")]
pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!(
(self, payout_method),
(Self::Paypal, Some(PayoutType::Wallet))
| (_, Some(PayoutType::Card))
| (Self::Adyenplatform, _)
| (Self::Nomupay, _)
| (Self::Loonio, _)
| (Self::Worldpay, Some(PayoutType::Wallet))
| (Self::Worldpayxml, Some(PayoutType::Wallet))
)
}
#[cfg(feature = "payouts")]
pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (_, Some(PayoutType::Bank)))
}
#[cfg(feature = "payouts")]
pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (_, Some(PayoutType::Card)))
}
#[cfg(feature = "payouts")]
pub fn is_payout_quote_call_required(self) -> bool {
matches!(self, Self::Wise | Self::Gigadat)
}
#[cfg(feature = "payouts")]
pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (Self::Paypal, _))
}
#[cfg(feature = "payouts")]
pub fn supports_access_token_for_external_vault(self) -> bool {
matches!(self, Self::Vgs)
}
#[cfg(feature = "payouts")]
pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool {
matches!(self, Self::Stripe | Self::Nomupay)
}
pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool {
matches!(
(self, payment_method),
(Self::Airwallex, _)
| (Self::Deutschebank, _)
| (Self::Globalpay, _)
| (Self::Jpmorgan, _)
| (Self::Moneris, _)
| (Self::Nordea, _)
| (Self::Paypal, _)
| (Self::Payu, _)
| (
Self::Trustpay,
PaymentMethod::BankRedirect | PaymentMethod::BankTransfer
)
| (Self::Tesouro, _)
| (Self::Iatapay, _)
| (Self::Volt, _)
| (Self::Itaubank, _)
| (Self::Facilitapay, _)
| (Self::Dwolla, _)
)
}
pub fn requires_order_creation_before_payment(self, payment_method: PaymentMethod) -> bool {
matches!(
(self, payment_method),
(Self::Razorpay, PaymentMethod::Upi) | (Self::Airwallex, _) //ordercreation required for all flows in airwallex
)
}
pub fn supports_file_storage_module(self) -> bool {
matches!(self, Self::Stripe | Self::Checkout | Self::Worldpayvantiv)
}
pub fn requires_defend_dispute(self) -> bool {
matches!(self, Self::Checkout)
}
pub fn is_separate_authentication_supported(self) -> bool {
match self {
#[cfg(feature = "dummy_connector")]
Self::DummyBillingConnector => false,
#[cfg(feature = "dummy_connector")]
Self::DummyConnector1
| Self::DummyConnector2
| Self::DummyConnector3
| Self::DummyConnector4
| Self::DummyConnector5
| Self::DummyConnector6
| Self::DummyConnector7 => false,
Self::Aci
// Add Separate authentication support for connectors
| Self::Authipay
| Self::Affirm
| Self::Adyenplatform
| Self::Airwallex
| Self::Amazonpay
| Self::Authorizedotnet
| Self::Bambora
| Self::Bamboraapac
| Self::Bankofamerica
| Self::Barclaycard
| Self::Billwerk
| Self::Bitpay
| Self::Bluesnap
| Self::Blackhawknetwork
| Self::Calida
| Self::Boku
| Self::Breadpay
| Self::Cashtocode
| Self::Celero
| Self::Chargebee
| Self::Checkbook
| Self::Coinbase
| Self::Coingate
| Self::Cryptopay
| Self::Custombilling
| Self::Deutschebank
| Self::Digitalvirgo
| Self::Dlocal
| Self::Dwolla
| Self::Ebanx
| Self::Elavon
| Self::Facilitapay
| Self::Finix
| Self::Fiserv
| Self::Fiservemea
| Self::Fiuu
| Self::Flexiti
| Self::Forte
| Self::Getnet
| Self::Gigadat
| Self::Globalpay
| Self::Globepay
| Self::Gocardless
| Self::Gpayments
| Self::Hipay
| Self::Helcim
| Self::HyperswitchVault
| Self::Iatapay
| Self::Inespay
| Self::Itaubank
| Self::Jpmorgan
| Self::Juspaythreedsserver
| Self::Klarna
| Self::Loonio
| Self::Mifinity
| Self::Mollie
| Self::Moneris
| Self::Multisafepay
| Self::Nexinets
| Self::Nexixpay
| Self::Nomupay
| Self::Nordea
| Self::Novalnet
| Self::Opennode
| Self::Paybox
| Self::Payload
| Self::Payme
| Self::Payone
| Self::Paypal
| Self::Paysafe
| Self::Paystack
| Self::Payu
| Self::Peachpayments
| Self::Placetopay
| Self::Powertranz
| Self::Prophetpay
| Self::Rapyd
| Self::Recurly
| Self::Redsys
| Self::Santander
| Self::Shift4
| Self::Silverflow
| Self::Square
| Self::Stax
| Self::Stripebilling
| Self::Taxjar
| Self::Tesouro
// | Self::Thunes
| Self::Trustpay
| Self::Trustpayments
// | Self::Tokenio
| Self::Tsys
// | Self::UnifiedAuthenticationService
| Self::Vgs
| Self::Volt
| Self::Wellsfargo
// | Self::Wellsfargopayout
| Self::Wise
| Self::Worldline
| Self::Worldpay
| Self::Worldpayvantiv
| Self::Worldpayxml
| Self::Xendit
| Self::Zen
| Self::Zsl
| Self::Signifyd
| Self::Plaid
| Self::Razorpay
| Self::Riskified
| Self::Threedsecureio
| Self::Netcetera
| Self::CtpMastercard
| Self::Cardinal
| Self::CtpVisa
| Self::Noon
| Self::Tokenex
| Self::Tokenio
| Self::Stripe
| Self::Datatrans
| Self::Paytm
| Self::Payjustnow
| Self::Payjustnowinstore
| Self::Phonepe => false,
Self::Checkout |Self::Zift| Self::Nmi |Self::Braintree|
Self::Cybersource | Self::Archipel | Self::Nuvei | Self::Adyen => true,
}
}
pub fn get_payment_methods_supporting_extended_authorization(self) -> HashSet<PaymentMethod> {
HashSet::from([PaymentMethod::Card])
}
pub fn get_payment_method_types_supporting_extended_authorization(
self,
) -> HashSet<PaymentMethodType> {
HashSet::from([PaymentMethodType::Credit, PaymentMethodType::Debit])
}
pub fn is_overcapture_supported_by_connector(self) -> bool {
matches!(self, Self::Stripe | Self::Adyen)
}
pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool {
matches!(self, Self::Adyenplatform | Self::Adyen)
}
/// Validates if dummy connector can be created
/// Dummy connectors can be created only if dummy_connector feature is enabled in the configs
#[cfg(feature = "dummy_connector")]
pub fn validate_dummy_connector_create(self, is_dummy_connector_enabled: bool) -> bool {
matches!(
self,
Self::DummyConnector1
| Self::DummyConnector2
| Self::DummyConnector3
| Self::DummyConnector4
| Self::DummyConnector5
| Self::DummyConnector6
| Self::DummyConnector7
) && !is_dummy_connector_enabled
}
}
// Enum representing different status an invoice can have.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum InvoiceStatus {
InvoiceCreated,
PaymentPending,
PaymentPendingTimeout,
PaymentSucceeded,
PaymentFailed,
PaymentCanceled,
InvoicePaid,
ManualReview,
Voided,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/enums/ui.rs | crates/common_enums/src/enums/ui.rs | use std::fmt;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use utoipa::ToSchema;
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
pub enum ElementPosition {
Left,
#[default]
#[serde(rename = "top left")]
TopLeft,
Top,
#[serde(rename = "top right")]
TopRight,
Right,
#[serde(rename = "bottom right")]
BottomRight,
Bottom,
#[serde(rename = "bottom left")]
BottomLeft,
Center,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, ToSchema)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
pub enum ElementSize {
Variants(SizeVariants),
Percentage(u32),
Pixels(u32),
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum SizeVariants {
#[default]
Cover,
Contain,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkDetailsLayout {
#[default]
Layout1,
Layout2,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkSdkLabelType {
#[default]
Above,
Floating,
Never,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkShowSdkTerms {
Always,
#[default]
Auto,
Never,
}
impl<'de> Deserialize<'de> for ElementSize {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ElementSizeVisitor;
impl Visitor<'_> for ElementSizeVisitor {
type Value = ElementSize;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string with possible values - contain, cover or values in percentage or pixels. For eg: 48px or 50%")
}
fn visit_str<E>(self, value: &str) -> Result<ElementSize, E>
where
E: serde::de::Error,
{
if let Some(percent) = value.strip_suffix('%') {
percent
.parse::<u32>()
.map(ElementSize::Percentage)
.map_err(E::custom)
} else if let Some(px) = value.strip_suffix("px") {
px.parse::<u32>()
.map(ElementSize::Pixels)
.map_err(E::custom)
} else {
match value {
"cover" => Ok(ElementSize::Variants(SizeVariants::Cover)),
"contain" => Ok(ElementSize::Variants(SizeVariants::Contain)),
_ => Err(E::custom("invalid size variant")),
}
}
}
}
deserializer.deserialize_str(ElementSizeVisitor)
}
}
impl Serialize for ElementSize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
match self {
Self::Variants(variant) => serializer.serialize_str(variant.to_string().as_str()),
Self::Pixels(pixel_count) => {
serializer.serialize_str(format!("{pixel_count}px").as_str())
}
Self::Percentage(pixel_count) => {
serializer.serialize_str(format!("{pixel_count}%").as_str())
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/enums/accounts.rs | crates/common_enums/src/enums/accounts.rs | use utoipa::ToSchema;
#[derive(
Copy,
Default,
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MerchantProductType {
#[default]
Orchestration,
Vault,
Recon,
Recovery,
CostObservability,
DynamicRouting,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum MerchantAccountType {
#[default]
Standard,
Platform,
Connected,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum OrganizationType {
#[default]
Standard,
Platform,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum MerchantAccountRequestType {
#[default]
Standard,
Connected,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_enums/src/enums/payments.rs | crates/common_enums/src/enums/payments.rs | use utoipa::ToSchema;
#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProductType {
#[default]
Physical,
Digital,
Travel,
Ride,
Event,
Accommodation,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/build.rs | crates/drainer/build.rs | fn main() {
#[cfg(feature = "vergen")]
router_env::vergen::generate_cargo_instructions();
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/errors.rs | crates/drainer/src/errors.rs | use redis_interface as redis;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DrainerError {
#[error("Error in parsing config : {0}")]
ConfigParsingError(String),
#[error("Error during redis operation : {0:?}")]
RedisError(error_stack::Report<redis::errors::RedisError>),
#[error("Application configuration error: {0}")]
ConfigurationError(config::ConfigError),
#[error("Error while configuring signals: {0}")]
SignalError(String),
#[error("Error while parsing data from the stream: {0:?}")]
ParsingError(error_stack::Report<common_utils::errors::ParsingError>),
#[error("Unexpected error occurred: {0}")]
UnexpectedError(String),
#[error("I/O: {0}")]
IoError(std::io::Error),
}
#[derive(Debug, Error, Clone, serde::Serialize)]
pub enum HealthCheckError {
#[error("Database health check is failing with error: {message}")]
DbError { message: String },
#[error("Redis health check is failing with error: {message}")]
RedisError { message: String },
}
impl From<std::io::Error> for DrainerError {
fn from(err: std::io::Error) -> Self {
Self::IoError(err)
}
}
pub type DrainerResult<T> = error_stack::Result<T, DrainerError>;
impl From<config::ConfigError> for DrainerError {
fn from(err: config::ConfigError) -> Self {
Self::ConfigurationError(err)
}
}
impl From<error_stack::Report<redis::errors::RedisError>> for DrainerError {
fn from(err: error_stack::Report<redis::errors::RedisError>) -> Self {
Self::RedisError(err)
}
}
impl actix_web::ResponseError for HealthCheckError {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::DbError { .. } | Self::RedisError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/stream.rs | crates/drainer/src/stream.rs | use std::collections::HashMap;
use redis_interface as redis;
use router_env::{logger, tracing};
use crate::{errors, metrics, Store};
pub type StreamEntries = Vec<(String, HashMap<String, String>)>;
pub type StreamReadResult = HashMap<String, StreamEntries>;
impl Store {
#[inline(always)]
pub fn drainer_stream(&self, shard_key: &str) -> String {
// Example: {shard_5}_drainer_stream
format!("{{{}}}_{}", shard_key, self.config.drainer_stream_name,)
}
#[inline(always)]
pub(crate) fn get_stream_key_flag(&self, stream_index: u8) -> String {
format!("{}_in_use", self.get_drainer_stream_name(stream_index))
}
#[inline(always)]
pub(crate) fn get_drainer_stream_name(&self, stream_index: u8) -> String {
self.drainer_stream(format!("shard_{stream_index}").as_str())
}
#[router_env::instrument(skip_all)]
pub async fn is_stream_available(&self, stream_index: u8) -> bool {
let stream_key_flag = self.get_stream_key_flag(stream_index);
match self
.redis_conn
.set_key_if_not_exists_with_expiry(&stream_key_flag.as_str().into(), true, None)
.await
{
Ok(resp) => resp == redis::types::SetnxReply::KeySet,
Err(error) => {
logger::error!(operation="lock_stream",err=?error);
false
}
}
}
pub async fn make_stream_available(&self, stream_name_flag: &str) -> errors::DrainerResult<()> {
match self.redis_conn.delete_key(&stream_name_flag.into()).await {
Ok(redis::DelReply::KeyDeleted) => Ok(()),
Ok(redis::DelReply::KeyNotDeleted) => {
logger::error!("Tried to unlock a stream which is already unlocked");
Ok(())
}
Err(error) => Err(errors::DrainerError::from(error).into()),
}
}
pub async fn read_from_stream(
&self,
stream_name: &str,
max_read_count: u64,
) -> errors::DrainerResult<StreamReadResult> {
// "0-0" id gives first entry
let stream_id = "0-0";
let (output, execution_time) = common_utils::date_time::time_it(|| async {
self.redis_conn
.stream_read_entries(stream_name, stream_id, Some(max_read_count))
.await
.map_err(errors::DrainerError::from)
})
.await;
metrics::REDIS_STREAM_READ_TIME.record(
execution_time,
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
Ok(output?)
}
pub async fn trim_from_stream(
&self,
stream_name: &str,
minimum_entry_id: &str,
) -> errors::DrainerResult<usize> {
let trim_kind = redis::StreamCapKind::MinID;
let trim_type = redis::StreamCapTrim::Exact;
let trim_id = minimum_entry_id;
let (trim_result, execution_time) =
common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {
let trim_result = self
.redis_conn
.stream_trim_entries(&stream_name.into(), (trim_kind, trim_type, trim_id))
.await
.map_err(errors::DrainerError::from)?;
// Since xtrim deletes entries below given id excluding the given id.
// Hence, deleting the minimum entry id
self.redis_conn
.stream_delete_entries(&stream_name.into(), minimum_entry_id)
.await
.map_err(errors::DrainerError::from)?;
Ok(trim_result)
})
.await;
metrics::REDIS_STREAM_TRIM_TIME.record(
execution_time,
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
// adding 1 because we are deleting the given id too
Ok(trim_result? + 1)
}
pub async fn delete_from_stream(
&self,
stream_name: &str,
entry_id: &str,
) -> errors::DrainerResult<()> {
let (_trim_result, execution_time) =
common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {
self.redis_conn
.stream_delete_entries(&stream_name.into(), entry_id)
.await
.map_err(errors::DrainerError::from)?;
Ok(())
})
.await;
metrics::REDIS_STREAM_DEL_TIME.record(
execution_time,
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/settings.rs | crates/drainer/src/settings.rs | use std::{collections::HashMap, path::PathBuf, sync::Arc};
use common_utils::{ext_traits::ConfigExt, id_type, DbConnectionParams};
use config::{Environment, File};
use external_services::managers::{
encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig,
};
use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{
RawSecret, SecretState, SecretStateContainer, SecuredSecret,
},
};
use masking::Secret;
use redis_interface as redis;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use router_env::{env, logger};
use serde::Deserialize;
use crate::{errors, secrets_transformers};
#[derive(clap::Parser, Default)]
#[cfg_attr(feature = "vergen", command(version = router_env::version!()))]
pub struct CmdLineConf {
/// Config file.
/// Application will look for "config/config.toml" if this option isn't specified.
#[arg(short = 'f', long, value_name = "FILE")]
pub config_path: Option<PathBuf>,
}
#[derive(Clone)]
pub struct AppState {
pub conf: Arc<Settings<RawSecret>>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
}
impl AppState {
/// # Panics
///
/// Panics if secret or encryption management client cannot be initiated
pub async fn new(conf: Settings<SecuredSecret>) -> Self {
#[allow(clippy::expect_used)]
let secret_management_client = conf
.secrets_management
.get_secret_management_client()
.await
.expect("Failed to create secret management client");
let raw_conf =
secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await;
#[allow(clippy::expect_used)]
let encryption_client = raw_conf
.encryption_management
.get_encryption_management_client()
.await
.expect("Failed to create encryption management client");
Self {
conf: Arc::new(raw_conf),
encryption_client,
}
}
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Settings<S: SecretState> {
pub server: Server,
pub master_database: SecretStateContainer<Database, S>,
pub redis: redis::RedisSettings,
pub log: Log,
pub drainer: DrainerSettings,
pub encryption_management: EncryptionManagementConfig,
pub secrets_management: SecretsManagementConfig,
pub multitenancy: Multitenancy,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
}
impl DbConnectionParams for Database {
fn get_username(&self) -> &str {
&self.username
}
fn get_password(&self) -> Secret<String> {
self.password.clone()
}
fn get_host(&self) -> &str {
&self.host
}
fn get_port(&self) -> u16 {
self.port
}
fn get_dbname(&self) -> &str {
&self.dbname
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct DrainerSettings {
pub stream_name: String,
pub num_partitions: u8,
pub max_read_count: u64,
pub shutdown_interval: u32, // in milliseconds
pub loop_interval: u32, // in milliseconds
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Multitenancy {
pub enabled: bool,
pub tenants: TenantConfig,
}
impl Multitenancy {
pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> {
&self.tenants.0
}
pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> {
self.tenants
.0
.values()
.map(|tenant| tenant.tenant_id.clone())
.collect()
}
pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> {
self.tenants.0.get(tenant_id)
}
}
#[derive(Debug, Clone, Default)]
pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>);
impl<'de> Deserialize<'de> for TenantConfig {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Inner {
base_url: String,
schema: String,
accounts_schema: String,
redis_key_prefix: String,
clickhouse_database: String,
}
let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?;
Ok(Self(
hashmap
.into_iter()
.map(|(key, value)| {
(
key.clone(),
Tenant {
tenant_id: key,
base_url: value.base_url,
schema: value.schema,
accounts_schema: value.accounts_schema,
redis_key_prefix: value.redis_key_prefix,
clickhouse_database: value.clickhouse_database,
},
)
})
.collect(),
))
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct Tenant {
pub tenant_id: id_type::TenantId,
pub base_url: String,
pub schema: String,
pub accounts_schema: String,
pub redis_key_prefix: String,
pub clickhouse_database: String,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Server {
pub port: u16,
pub workers: usize,
pub host: String,
}
impl Server {
pub fn validate(&self) -> Result<(), errors::DrainerError> {
common_utils::fp_utils::when(self.host.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"server host must not be empty".into(),
))
})
}
}
impl Default for Database {
fn default() -> Self {
Self {
username: String::new(),
password: String::new().into(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
}
}
}
impl Default for DrainerSettings {
fn default() -> Self {
Self {
stream_name: "DRAINER_STREAM".into(),
num_partitions: 64,
max_read_count: 100,
shutdown_interval: 1000, // in milliseconds
loop_interval: 100, // in milliseconds
}
}
}
impl Default for Server {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 8080,
workers: 1,
}
}
}
impl Database {
fn validate(&self) -> Result<(), errors::DrainerError> {
use common_utils::fp_utils::when;
when(self.host.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database host must not be empty".into(),
))
})?;
when(self.dbname.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database name must not be empty".into(),
))
})?;
when(self.username.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database user username must not be empty".into(),
))
})?;
when(self.password.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database user password must not be empty".into(),
))
})
}
}
impl DrainerSettings {
fn validate(&self) -> Result<(), errors::DrainerError> {
common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"drainer stream name must not be empty".into(),
))
})
}
}
impl Settings<SecuredSecret> {
pub fn new() -> Result<Self, errors::DrainerError> {
Self::with_config_path(None)
}
pub fn with_config_path(config_path: Option<PathBuf>) -> Result<Self, errors::DrainerError> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `DRAINER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = env::which();
let config_path = router_env::Config::config_path(&environment.to_string(), config_path);
let config = router_env::Config::builder(&environment.to_string())?
.add_source(File::from(config_path).required(false))
.add_source(
Environment::with_prefix("DRAINER")
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("redis.cluster_urls"),
)
.build()?;
// The logger may not yet be initialized when constructing the application configuration
#[allow(clippy::print_stderr)]
serde_path_to_error::deserialize(config).map_err(|error| {
logger::error!(%error, "Unable to deserialize application configuration");
eprintln!("Unable to deserialize application configuration: {error}");
errors::DrainerError::from(error.into_inner())
})
}
pub fn validate(&self) -> Result<(), errors::DrainerError> {
self.server.validate()?;
self.master_database.get_inner().validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.redis.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError("invalid Redis configuration".into())
})?;
self.drainer.validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.secrets_management.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError(
"invalid secrets management configuration".into(),
)
})?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.encryption_management.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError(
"invalid encryption management configuration".into(),
)
})?;
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/services.rs | crates/drainer/src/services.rs | use std::sync::Arc;
use actix_web::{body, HttpResponse, ResponseError};
use error_stack::Report;
use redis_interface::RedisConnectionPool;
use crate::{
connection::{diesel_make_pg_pool, PgPool},
logger,
settings::Tenant,
};
#[derive(Clone)]
pub struct Store {
pub master_pool: PgPool,
pub redis_conn: Arc<RedisConnectionPool>,
pub config: StoreConfig,
pub request_id: Option<String>,
}
#[derive(Clone)]
pub struct StoreConfig {
pub drainer_stream_name: String,
pub drainer_num_partitions: u8,
pub use_legacy_version: bool,
}
impl Store {
/// # Panics
///
/// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration.
/// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client.
pub async fn new(config: &crate::Settings, test_transaction: bool, tenant: &Tenant) -> Self {
let redis_conn = crate::connection::redis_connection(config).await;
Self {
master_pool: diesel_make_pg_pool(
config.master_database.get_inner(),
test_transaction,
&tenant.schema,
)
.await,
redis_conn: Arc::new(RedisConnectionPool::clone(
&redis_conn,
&tenant.redis_key_prefix,
)),
config: StoreConfig {
drainer_stream_name: config.drainer.stream_name.clone(),
drainer_num_partitions: config.drainer.num_partitions,
use_legacy_version: config.redis.use_legacy_version,
},
request_id: None,
}
}
pub fn use_legacy_version(&self) -> bool {
self.config.use_legacy_version
}
}
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
where
T: error_stack::Context + ResponseError + Clone,
{
logger::error!(?error);
let body = serde_json::json!({
"message": error.to_string()
})
.to_string();
HttpResponse::InternalServerError()
.content_type(mime::APPLICATION_JSON)
.body(body)
}
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/lib.rs | crates/drainer/src/lib.rs | mod connection;
pub mod errors;
mod handler;
mod health_check;
pub mod logger;
pub(crate) mod metrics;
mod query;
pub mod services;
pub mod settings;
mod stream;
mod types;
mod utils;
use std::{collections::HashMap, sync::Arc};
mod secrets_transformers;
use actix_web::dev::Server;
use common_utils::{id_type, signals::get_allowed_signals};
use diesel_models::kv;
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
use router_env::{
instrument,
tracing::{self, Instrument},
};
use tokio::sync::mpsc;
pub(crate) type Settings = settings::Settings<RawSecret>;
use crate::{
connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData,
};
pub async fn start_drainer(
stores: HashMap<id_type::TenantId, Arc<Store>>,
conf: DrainerSettings,
) -> errors::DrainerResult<()> {
let drainer_handler = handler::Handler::from_conf(conf, stores);
let (tx, rx) = mpsc::channel::<()>(1);
let signal = get_allowed_signals().change_context(errors::DrainerError::SignalError(
"Failed while getting allowed signals".to_string(),
))?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()).in_current_span());
let handler_clone = drainer_handler.clone();
tokio::task::spawn(async move { handler_clone.shutdown_listener(rx).await });
drainer_handler.spawn_error_handlers(tx)?;
drainer_handler.spawn().await?;
handle.close();
let _ = task_handle
.await
.map_err(|err| logger::error!("Failed while joining signal handler: {:?}", err));
Ok(())
}
pub async fn start_web_server(
conf: Settings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Result<Server, errors::DrainerError> {
let server = conf.server.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(health_check::Health::server(conf.clone(), stores.clone()))
})
.bind((server.host.as_str(), server.port))?
.run();
let _ = web_server.handle();
Ok(web_server)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/logger.rs | crates/drainer/src/logger.rs | #[doc(inline)]
pub use router_env::{debug, error, info, warn};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/connection.rs | crates/drainer/src/connection.rs | use bb8::PooledConnection;
use common_utils::DbConnectionParams;
use diesel::PgConnection;
use crate::{settings::Database, Settings};
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
#[allow(clippy::expect_used)]
pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis connection Pool")
}
// TODO: use stores defined in storage_impl instead
/// # Panics
///
/// Will panic if could not create a db pool
#[allow(clippy::expect_used)]
pub async fn diesel_make_pg_pool(
database: &Database,
_test_transaction: bool,
schema: &str,
) -> PgPool {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let pool = bb8::Pool::builder()
.max_size(database.pool_size)
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout));
pool.build(manager)
.await
.expect("Failed to create PostgreSQL connection pool")
}
#[allow(clippy::expect_used)]
pub async fn pg_connection(
pool: &PgPool,
) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {
pool.get()
.await
.expect("Couldn't retrieve PostgreSQL connection")
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/types.rs | crates/drainer/src/types.rs | use std::collections::HashMap;
use common_utils::errors;
use error_stack::ResultExt;
use serde::{de::value::MapDeserializer, Deserialize, Serialize};
use crate::{
kv,
utils::{deserialize_db_op, deserialize_i64},
};
#[derive(Deserialize, Serialize)]
pub struct StreamData {
pub request_id: String,
pub global_id: String,
#[serde(deserialize_with = "deserialize_db_op")]
pub typed_sql: kv::DBOperation,
#[serde(deserialize_with = "deserialize_i64")]
pub pushed_at: i64,
}
impl StreamData {
pub fn from_hashmap(
hashmap: HashMap<String, String>,
) -> errors::CustomResult<Self, errors::ParsingError> {
let iter = MapDeserializer::<
'_,
std::collections::hash_map::IntoIter<String, String>,
serde_json::error::Error,
>::new(hashmap.into_iter());
Self::deserialize(iter)
.change_context(errors::ParsingError::StructParseFailure("StreamData"))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/secrets_transformers.rs | crates/drainer/src/secrets_transformers.rs | use common_utils::errors::CustomResult;
use hyperswitch_interfaces::secrets_interface::{
secret_handler::SecretsHandler,
secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
SecretManagementInterface, SecretsManagementError,
};
use crate::settings::{Database, Settings};
#[async_trait::async_trait]
impl SecretsHandler for Database {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let secured_db_config = value.get_inner();
let raw_db_password = secret_management_client
.get_secret(secured_db_config.password.clone())
.await?;
Ok(value.transition_state(|db| Self {
password: raw_db_password,
..db
}))
}
}
/// # Panics
///
/// Will panic even if fetching raw secret fails for at least one config value
pub async fn fetch_raw_secrets(
conf: Settings<SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> Settings<RawSecret> {
#[allow(clippy::expect_used)]
let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client)
.await
.expect("Failed to decrypt database password");
Settings {
server: conf.server,
master_database: database,
redis: conf.redis,
log: conf.log,
drainer: conf.drainer,
encryption_management: conf.encryption_management,
secrets_management: conf.secrets_management,
multitenancy: conf.multitenancy,
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/health_check.rs | crates/drainer/src/health_check.rs | use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::{errors::CustomResult, id_type};
use diesel_models::{Config, ConfigNew};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
use crate::{
connection::pg_connection,
errors::HealthCheckError,
services::{self, log_and_return_error_response, Store},
Settings,
};
pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0";
pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")];
pub struct Health;
impl Health {
pub fn server(conf: Settings, stores: HashMap<id_type::TenantId, Arc<Store>>) -> Scope {
web::scope("health")
.app_data(web::Data::new(conf))
.app_data(web::Data::new(stores))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Drainer health was called");
actix_web::HttpResponse::Ok().body("Drainer health is good")
}
#[instrument(skip_all)]
pub async fn deep_health_check(
conf: web::Data<Settings>,
stores: web::Data<HashMap<String, Arc<Store>>>,
) -> impl actix_web::Responder {
let mut deep_health_res = HashMap::new();
for (tenant, store) in stores.iter() {
logger::info!("Tenant: {:?}", tenant);
let response = match deep_health_check_func(conf.clone(), store).await {
Ok(response) => serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
Err(err) => return log_and_return_error_response(err),
};
deep_health_res.insert(tenant.clone(), response);
}
services::http_response_json(
serde_json::to_string(&deep_health_res)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
conf: web::Data<Settings>,
store: &Arc<Store>,
) -> Result<DrainerHealthCheckResponse, error_stack::Report<HealthCheckError>> {
logger::info!("Deep health check was called");
logger::debug!("Database health check begin");
let db_status = store
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(HealthCheckError::DbError { message })
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = store
.health_check_redis(&conf.into_inner())
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(HealthCheckError::RedisError { message })
})?;
logger::debug!("Redis health check end");
Ok(DrainerHealthCheckResponse {
database: db_status,
redis: redis_status,
})
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DrainerHealthCheckResponse {
pub database: bool,
pub redis: bool,
}
#[async_trait::async_trait]
pub trait HealthCheckInterface {
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError>;
async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError>;
}
#[async_trait::async_trait]
impl HealthCheckInterface for Store {
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> {
let conn = pg_connection(&self.master_pool).await;
conn
.transaction_async(|conn| {
Box::pin(async move {
let query =
diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
logger::error!(read_err=?err,"Error while reading element in the database");
HealthCheckDBError::DbReadError
})?;
logger::debug!("Database read was successful");
let config = ConfigNew {
key: "test_key".to_string(),
config: "test_value".to_string(),
};
config.insert(&conn).await.map_err(|err| {
logger::error!(write_err=?err,"Error while writing to database");
HealthCheckDBError::DbWriteError
})?;
logger::debug!("Database write was successful");
Config::delete_by_key(&conn, "test_key").await.map_err(|err| {
logger::error!(delete_err=?err,"Error while deleting element in the database");
HealthCheckDBError::DbDeleteError
})?;
logger::debug!("Database delete was successful");
Ok::<_, HealthCheckDBError>(())
})
})
.await?;
Ok(())
}
async fn health_check_redis(
&self,
_conf: &Settings,
) -> CustomResult<(), HealthCheckRedisError> {
let redis_conn = self.redis_conn.clone();
redis_conn
.serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30)
.await
.change_context(HealthCheckRedisError::SetFailed)?;
logger::debug!("Redis set_key was successful");
redis_conn
.get_key::<()>(&"test_key".into())
.await
.change_context(HealthCheckRedisError::GetFailed)?;
logger::debug!("Redis get_key was successful");
redis_conn
.delete_key(&"test_key".into())
.await
.change_context(HealthCheckRedisError::DeleteFailed)?;
logger::debug!("Redis delete_key was successful");
redis_conn
.stream_append_entry(
&TEST_STREAM_NAME.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
TEST_STREAM_DATA.to_vec(),
)
.await
.change_context(HealthCheckRedisError::StreamAppendFailed)?;
logger::debug!("Stream append succeeded");
let output = redis_conn
.stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10))
.await
.change_context(HealthCheckRedisError::StreamReadFailed)?;
logger::debug!("Stream read succeeded");
let (_, id_to_trim) = output
.get(&redis_conn.add_prefix(TEST_STREAM_NAME))
.and_then(|entries| {
entries
.last()
.map(|last_entry| (entries, last_entry.0.clone()))
})
.ok_or(error_stack::report!(
HealthCheckRedisError::StreamReadFailed
))?;
logger::debug!("Stream parse succeeded");
redis_conn
.stream_trim_entries(
&TEST_STREAM_NAME.into(),
(
redis_interface::StreamCapKind::MinID,
redis_interface::StreamCapTrim::Exact,
id_to_trim,
),
)
.await
.change_context(HealthCheckRedisError::StreamTrimFailed)?;
logger::debug!("Stream trim succeeded");
Ok(())
}
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckDBError {
#[error("Error while connecting to database")]
DbError,
#[error("Error while writing to database")]
DbWriteError,
#[error("Error while reading element in the database")]
DbReadError,
#[error("Error while deleting element in the database")]
DbDeleteError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error in database transaction")]
TransactionError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DbError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckRedisError {
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
#[error("Failed to append data to the stream in Redis")]
StreamAppendFailed,
#[error("Failed to read data from the stream in Redis")]
StreamReadFailed,
#[error("Failed to trim data from the stream in Redis")]
StreamTrimFailed,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/utils.rs | crates/drainer/src/utils.rs | use std::sync::{atomic, Arc};
use error_stack::report;
use redis_interface as redis;
use serde::de::Deserialize;
use crate::{
errors, kv, metrics,
stream::{StreamEntries, StreamReadResult},
};
pub fn parse_stream_entries<'a>(
read_result: &'a StreamReadResult,
stream_name: &str,
) -> errors::DrainerResult<&'a StreamEntries> {
read_result.get(stream_name).ok_or_else(|| {
report!(errors::DrainerError::RedisError(report!(
redis::errors::RedisError::NotFound
)))
})
}
pub(crate) fn deserialize_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = serde_json::Value::deserialize(deserializer)?;
match s {
serde_json::Value::String(str_val) => str_val.parse().map_err(serde::de::Error::custom),
serde_json::Value::Number(num_val) => match num_val.as_i64() {
Some(val) => Ok(val),
None => Err(serde::de::Error::custom(format!(
"could not convert {num_val:?} to i64"
))),
},
other => Err(serde::de::Error::custom(format!(
"unexpected data format - expected string or number, got: {other:?}"
))),
}
}
pub(crate) fn deserialize_db_op<'de, D>(deserializer: D) -> Result<kv::DBOperation, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = serde_json::Value::deserialize(deserializer)?;
match s {
serde_json::Value::String(str_val) => {
serde_json::from_str(&str_val).map_err(serde::de::Error::custom)
}
other => Err(serde::de::Error::custom(format!(
"unexpected data format - expected string got: {other:?}"
))),
}
}
// Here the output is in the format (stream_index, jobs_picked),
// similar to the first argument of the function
#[inline(always)]
pub async fn increment_stream_index(
(index, jobs_picked): (u8, Arc<atomic::AtomicU8>),
total_streams: u8,
) -> u8 {
if index == total_streams - 1 {
match jobs_picked.load(atomic::Ordering::SeqCst) {
0 => metrics::CYCLES_COMPLETED_UNSUCCESSFULLY.add(1, &[]),
_ => metrics::CYCLES_COMPLETED_SUCCESSFULLY.add(1, &[]),
}
jobs_picked.store(0, atomic::Ordering::SeqCst);
0
} else {
index + 1
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/query.rs | crates/drainer/src/query.rs | use std::sync::Arc;
use common_utils::errors::CustomResult;
use diesel_models::errors::DatabaseError;
use crate::{kv, logger, metrics, pg_connection, services::Store};
#[async_trait::async_trait]
pub trait ExecuteQuery {
async fn execute_query(
self,
store: &Arc<Store>,
pushed_at: i64,
) -> CustomResult<(), DatabaseError>;
}
#[async_trait::async_trait]
impl ExecuteQuery for kv::DBOperation {
async fn execute_query(
self,
store: &Arc<Store>,
pushed_at: i64,
) -> CustomResult<(), DatabaseError> {
let conn = pg_connection(&store.master_pool).await;
let operation = self.operation();
let table = self.table();
let tags = router_env::metric_attributes!(("operation", operation), ("table", table));
let (result, execution_time) =
Box::pin(common_utils::date_time::time_it(|| self.execute(&conn))).await;
push_drainer_delay(pushed_at, operation, table, tags);
metrics::QUERY_EXECUTION_TIME.record(execution_time, tags);
match result {
Ok(result) => {
logger::info!(operation = operation, table = table, ?result);
metrics::SUCCESSFUL_QUERY_EXECUTION.add(1, tags);
Ok(())
}
Err(err) => {
logger::error!(operation = operation, table = table, ?err);
metrics::ERRORS_WHILE_QUERY_EXECUTION.add(1, tags);
Err(err)
}
}
}
}
#[inline(always)]
fn push_drainer_delay(
pushed_at: i64,
operation: &str,
table: &str,
tags: &[router_env::opentelemetry::KeyValue],
) {
let drained_at = common_utils::date_time::now_unix_timestamp();
let delay = drained_at - pushed_at;
logger::debug!(operation, table, delay = format!("{delay} secs"));
match u64::try_from(delay) {
Ok(delay) => metrics::DRAINER_DELAY_SECONDS.record(delay, tags),
Err(error) => logger::error!(
pushed_at,
drained_at,
delay,
?error,
"Invalid drainer delay"
),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/main.rs | crates/drainer/src/main.rs | use std::collections::HashMap;
use drainer::{errors::DrainerResult, logger, services, settings, start_drainer, start_web_server};
use router_env::tracing::Instrument;
#[tokio::main]
async fn main() -> DrainerResult<()> {
// Get configuration
let cmd_line = <settings::CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = settings::Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
#[allow(clippy::expect_used)]
conf.validate()
.expect("Failed to validate drainer configuration");
let state = settings::AppState::new(conf.clone()).await;
let mut stores = HashMap::new();
for (tenant_name, tenant) in conf.multitenancy.get_tenants() {
let store = std::sync::Arc::new(services::Store::new(&state.conf, false, tenant).await);
stores.insert(tenant_name.clone(), store);
}
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!("Starting drainer (Version: {})", router_env::git_tag!());
}
let _guard = router_env::setup(
&conf.log,
router_env::service_name!(),
[router_env::service_name!()],
);
#[allow(clippy::expect_used)]
let web_server = Box::pin(start_web_server(
state.conf.as_ref().clone(),
stores.clone(),
))
.await
.expect("Failed to create the server");
tokio::spawn(
async move {
let _ = web_server.await;
logger::error!("The health check probe stopped working!");
}
.in_current_span(),
);
logger::debug!(startup_config=?conf);
logger::info!("Drainer started [{:?}] [{:?}]", conf.drainer, conf.log);
start_drainer(stores.clone(), conf.drainer).await?;
Ok(())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/metrics.rs | crates/drainer/src/metrics.rs | use router_env::{counter_metric, global_meter, histogram_metric_f64, histogram_metric_u64};
global_meter!(DRAINER_METER, "DRAINER");
counter_metric!(JOBS_PICKED_PER_STREAM, DRAINER_METER);
counter_metric!(CYCLES_COMPLETED_SUCCESSFULLY, DRAINER_METER);
counter_metric!(CYCLES_COMPLETED_UNSUCCESSFULLY, DRAINER_METER);
counter_metric!(ERRORS_WHILE_QUERY_EXECUTION, DRAINER_METER);
counter_metric!(SUCCESSFUL_QUERY_EXECUTION, DRAINER_METER);
counter_metric!(SHUTDOWN_SIGNAL_RECEIVED, DRAINER_METER);
counter_metric!(SUCCESSFUL_SHUTDOWN, DRAINER_METER);
counter_metric!(STREAM_EMPTY, DRAINER_METER);
counter_metric!(STREAM_PARSE_FAIL, DRAINER_METER);
counter_metric!(DRAINER_HEALTH, DRAINER_METER);
histogram_metric_f64!(QUERY_EXECUTION_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_f64!(REDIS_STREAM_READ_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_f64!(REDIS_STREAM_TRIM_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_f64!(CLEANUP_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_u64!(DRAINER_DELAY_SECONDS, DRAINER_METER); // Time in (s) seconds
histogram_metric_f64!(REDIS_STREAM_DEL_TIME, DRAINER_METER); // Time in (ms) milliseconds
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/drainer/src/handler.rs | crates/drainer/src/handler.rs | use std::{
collections::HashMap,
sync::{atomic, Arc},
};
use common_utils::id_type;
use router_env::tracing::Instrument;
use tokio::{
sync::{mpsc, oneshot},
time::{self, Duration},
};
use crate::{
errors, instrument, logger, metrics, query::ExecuteQuery, tracing, utils, DrainerSettings,
Store, StreamData,
};
/// Handler handles the spawning and closing of drainer
/// Arc is used to enable creating a listener for graceful shutdown
#[derive(Clone)]
pub struct Handler {
inner: Arc<HandlerInner>,
}
impl std::ops::Deref for Handler {
type Target = HandlerInner;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
pub struct HandlerInner {
shutdown_interval: Duration,
loop_interval: Duration,
active_tasks: Arc<atomic::AtomicU64>,
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
running: Arc<atomic::AtomicBool>,
}
impl Handler {
pub fn from_conf(
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Self {
let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into());
let loop_interval = Duration::from_millis(conf.loop_interval.into());
let active_tasks = Arc::new(atomic::AtomicU64::new(0));
let running = Arc::new(atomic::AtomicBool::new(true));
let handler = HandlerInner {
shutdown_interval,
loop_interval,
active_tasks,
conf,
stores,
running,
};
Self {
inner: Arc::new(handler),
}
}
pub fn close(&self) {
self.running.store(false, atomic::Ordering::SeqCst);
}
pub async fn spawn(&self) -> errors::DrainerResult<()> {
let mut stream_index: u8 = 0;
let jobs_picked = Arc::new(atomic::AtomicU8::new(0));
while self.running.load(atomic::Ordering::SeqCst) {
metrics::DRAINER_HEALTH.add(1, &[]);
for store in self.stores.values() {
if store.is_stream_available(stream_index).await {
let _task_handle = tokio::spawn(
drainer_handler(
store.clone(),
stream_index,
self.conf.max_read_count,
self.active_tasks.clone(),
jobs_picked.clone(),
)
.in_current_span(),
);
}
}
stream_index = utils::increment_stream_index(
(stream_index, jobs_picked.clone()),
self.conf.num_partitions,
)
.await;
time::sleep(self.loop_interval).await;
}
Ok(())
}
pub(crate) async fn shutdown_listener(&self, mut rx: mpsc::Receiver<()>) {
while let Some(_c) = rx.recv().await {
logger::info!("Awaiting shutdown!");
metrics::SHUTDOWN_SIGNAL_RECEIVED.add(1, &[]);
let shutdown_started = time::Instant::now();
rx.close();
//Check until the active tasks are zero. This does not include the tasks in the stream.
while self.active_tasks.load(atomic::Ordering::SeqCst) != 0 {
time::sleep(self.shutdown_interval).await;
}
logger::info!("Terminating drainer");
metrics::SUCCESSFUL_SHUTDOWN.add(1, &[]);
let shutdown_ended = shutdown_started.elapsed().as_secs_f64() * 1000f64;
metrics::CLEANUP_TIME.record(shutdown_ended, &[]);
self.close();
}
logger::info!(
tasks_remaining = self.active_tasks.load(atomic::Ordering::SeqCst),
"Drainer shutdown successfully"
)
}
pub fn spawn_error_handlers(&self, tx: mpsc::Sender<()>) -> errors::DrainerResult<()> {
let (redis_error_tx, redis_error_rx) = oneshot::channel();
let redis_conn_clone = self
.stores
.values()
.next()
.map(|store| store.redis_conn.clone());
match redis_conn_clone {
None => {
logger::error!("No redis connection found");
Err(
errors::DrainerError::UnexpectedError("No redis connection found".to_string())
.into(),
)
}
Some(redis_conn_clone) => {
// Spawn a task to monitor if redis is down or not
let _task_handle = tokio::spawn(
async move { redis_conn_clone.on_error(redis_error_tx).await }
.in_current_span(),
);
//Spawns a task to send shutdown signal if redis goes down
let _task_handle =
tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span());
Ok(())
}
}
}
}
pub async fn redis_error_receiver(rx: oneshot::Receiver<()>, shutdown_channel: mpsc::Sender<()>) {
match rx.await {
Ok(_) => {
logger::error!("The redis server failed");
let _ = shutdown_channel.send(()).await.map_err(|err| {
logger::error!("Failed to send signal to the shutdown channel {err}")
});
}
Err(err) => {
logger::error!("Channel receiver error {err}");
}
}
}
#[router_env::instrument(skip_all)]
async fn drainer_handler(
store: Arc<Store>,
stream_index: u8,
max_read_count: u64,
active_tasks: Arc<atomic::AtomicU64>,
jobs_picked: Arc<atomic::AtomicU8>,
) -> errors::DrainerResult<()> {
active_tasks.fetch_add(1, atomic::Ordering::Release);
let stream_name = store.get_drainer_stream_name(stream_index);
let drainer_result = Box::pin(drainer(
store.clone(),
max_read_count,
stream_name.as_str(),
jobs_picked,
))
.await;
if let Err(error) = drainer_result {
logger::error!(?error)
}
let flag_stream_name = store.get_stream_key_flag(stream_index);
let output = store.make_stream_available(flag_stream_name.as_str()).await;
active_tasks.fetch_sub(1, atomic::Ordering::Release);
output.inspect_err(|err| logger::error!(operation = "unlock_stream", err=?err))
}
#[instrument(skip_all, fields(global_id, request_id, session_id))]
async fn drainer(
store: Arc<Store>,
max_read_count: u64,
stream_name: &str,
jobs_picked: Arc<atomic::AtomicU8>,
) -> errors::DrainerResult<()> {
let stream_read = match store.read_from_stream(stream_name, max_read_count).await {
Ok(result) => {
jobs_picked.fetch_add(1, atomic::Ordering::SeqCst);
result
}
Err(error) => {
if let errors::DrainerError::RedisError(redis_err) = error.current_context() {
if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable =
redis_err.current_context()
{
metrics::STREAM_EMPTY.add(1, &[]);
return Ok(());
} else {
return Err(error);
}
} else {
return Err(error);
}
}
};
// parse_stream_entries returns error if no entries is found, handle it
let entries = utils::parse_stream_entries(
&stream_read,
store.redis_conn.add_prefix(stream_name).as_str(),
)?;
let read_count = entries.len();
metrics::JOBS_PICKED_PER_STREAM.add(
u64::try_from(read_count).unwrap_or(u64::MIN),
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
let session_id = common_utils::generate_id_with_default_len("drainer_session");
tracing::Span::current().record("session_id", &session_id);
let mut last_processed_id = String::new();
for (entry_id, entry) in entries.clone() {
let data = match StreamData::from_hashmap(entry) {
Ok(data) => data,
Err(err) => {
logger::error!(operation = "deserialization", err=?err);
metrics::STREAM_PARSE_FAIL.add(
1,
router_env::metric_attributes!(("operation", "deserialization")),
);
// break from the loop in case of a deser error
break;
}
};
tracing::Span::current().record("request_id", data.request_id);
tracing::Span::current().record("global_id", data.global_id);
match data.typed_sql.execute_query(&store, data.pushed_at).await {
Ok(_) => {
last_processed_id = entry_id;
}
Err(err) => match err.current_context() {
// In case of Uniqueviolation we can't really do anything to fix it so just clear
// it from the stream
diesel_models::errors::DatabaseError::UniqueViolation => {
last_processed_id = entry_id;
}
// break from the loop in case of an error in query
_ => break,
},
}
if store.use_legacy_version() {
store
.delete_from_stream(stream_name, &last_processed_id)
.await?;
}
}
if !(last_processed_id.is_empty() || store.use_legacy_version()) {
let entries_trimmed = store
.trim_from_stream(stream_name, &last_processed_id)
.await?;
if read_count != entries_trimmed {
logger::error!(
read_entries = %read_count,
trimmed_entries = %entries_trimmed,
?entries,
"Assertion Failed no. of entries read from the stream doesn't match no. of entries trimmed"
);
}
} else {
logger::error!(read_entries = %read_count,?entries,"No streams were processed in this session");
}
Ok(())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/api_keys.rs | crates/api_models/src/api_keys.rs | use common_utils::custom_serde;
use masking::StrongSecret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
/// The request body for creating an API Key.
#[derive(Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CreateApiKeyRequest {
/// A unique name for the API Key to help you identify it.
#[schema(max_length = 64, example = "Sandbox integration key")]
pub name: String,
/// A description to provide more context about the API Key.
#[schema(
max_length = 256,
example = "Key used by our developers to integrate with the sandbox environment"
)]
pub description: Option<String>,
/// An expiration date for the API Key. Although we allow keys to never expire, we recommend
/// rotating your keys once every 6 months.
#[schema(example = "2022-09-10T10:11:12Z")]
pub expiration: ApiKeyExpiration,
}
/// The response body for creating an API Key.
#[derive(Debug, Serialize, ToSchema)]
pub struct CreateApiKeyResponse {
/// The identifier for the API Key.
#[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)]
pub key_id: common_utils::id_type::ApiKeyId,
/// The identifier for the Merchant Account.
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
/// The unique name for the API Key to help you identify it.
#[schema(max_length = 64, example = "Sandbox integration key")]
pub name: String,
/// The description to provide more context about the API Key.
#[schema(
max_length = 256,
example = "Key used by our developers to integrate with the sandbox environment"
)]
pub description: Option<String>,
/// The plaintext API Key used for server-side API access. Ensure you store the API Key
/// securely as you will not be able to see it again.
#[schema(value_type = String, max_length = 128)]
pub api_key: StrongSecret<String>,
/// The time at which the API Key was created.
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
/// The expiration date for the API Key.
#[schema(example = "2022-09-10T10:11:12Z")]
pub expiration: ApiKeyExpiration,
/*
/// The date and time indicating when the API Key was last used.
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_used: Option<PrimitiveDateTime>,
*/
}
/// The response body for retrieving an API Key.
#[derive(Debug, Serialize, ToSchema)]
pub struct RetrieveApiKeyResponse {
/// The identifier for the API Key.
#[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)]
pub key_id: common_utils::id_type::ApiKeyId,
/// The identifier for the Merchant Account.
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
/// The unique name for the API Key to help you identify it.
#[schema(max_length = 64, example = "Sandbox integration key")]
pub name: String,
/// The description to provide more context about the API Key.
#[schema(
max_length = 256,
example = "Key used by our developers to integrate with the sandbox environment"
)]
pub description: Option<String>,
/// The first few characters of the plaintext API Key to help you identify it.
#[schema(value_type = String, max_length = 64)]
pub prefix: StrongSecret<String>,
/// The time at which the API Key was created.
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
/// The expiration date for the API Key.
#[schema(example = "2022-09-10T10:11:12Z")]
pub expiration: ApiKeyExpiration,
/*
/// The date and time indicating when the API Key was last used.
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_used: Option<PrimitiveDateTime>,
*/
}
/// The request body for updating an API Key.
#[derive(Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateApiKeyRequest {
/// A unique name for the API Key to help you identify it.
#[schema(max_length = 64, example = "Sandbox integration key")]
pub name: Option<String>,
/// A description to provide more context about the API Key.
#[schema(
max_length = 256,
example = "Key used by our developers to integrate with the sandbox environment"
)]
pub description: Option<String>,
/// An expiration date for the API Key. Although we allow keys to never expire, we recommend
/// rotating your keys once every 6 months.
#[schema(example = "2022-09-10T10:11:12Z")]
pub expiration: Option<ApiKeyExpiration>,
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub key_id: common_utils::id_type::ApiKeyId,
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
}
/// The response body for revoking an API Key.
#[derive(Debug, Serialize, ToSchema)]
pub struct RevokeApiKeyResponse {
/// The identifier for the Merchant Account.
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
/// The identifier for the API Key.
#[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)]
pub key_id: common_utils::id_type::ApiKeyId,
/// Indicates whether the API key was revoked or not.
#[schema(example = "true")]
pub revoked: bool,
}
/// The constraints that are applicable when listing API Keys associated with a merchant account.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ListApiKeyConstraints {
/// The maximum number of API Keys to include in the response.
pub limit: Option<i64>,
/// The number of API Keys to skip when retrieving the list of API keys.
pub skip: Option<i64>,
}
/// The expiration date and time for an API Key.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ApiKeyExpiration {
/// The API Key does not expire.
#[serde(with = "never")]
Never,
/// The API Key expires at the specified date and time.
#[serde(with = "custom_serde::iso8601")]
DateTime(PrimitiveDateTime),
}
impl From<ApiKeyExpiration> for Option<PrimitiveDateTime> {
fn from(expiration: ApiKeyExpiration) -> Self {
match expiration {
ApiKeyExpiration::Never => None,
ApiKeyExpiration::DateTime(date_time) => Some(date_time),
}
}
}
impl From<Option<PrimitiveDateTime>> for ApiKeyExpiration {
fn from(date_time: Option<PrimitiveDateTime>) -> Self {
date_time.map_or(Self::Never, Self::DateTime)
}
}
// This implementation is required as otherwise, `serde` would serialize and deserialize
// `ApiKeyExpiration::Never` as `null`, which is not preferable.
// Reference: https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291
mod never {
const NEVER: &str = "never";
pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(NEVER)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error>
where
D: serde::Deserializer<'de>,
{
struct NeverVisitor;
impl serde::de::Visitor<'_> for NeverVisitor {
type Value = ();
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, r#""{NEVER}""#)
}
fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
if value == NEVER {
Ok(())
} else {
Err(E::invalid_value(serde::de::Unexpected::Str(value), &self))
}
}
}
deserializer.deserialize_str(NeverVisitor)
}
}
impl<'a> ToSchema<'a> for ApiKeyExpiration {
fn schema() -> (
&'a str,
utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
) {
use utoipa::openapi::{KnownFormat, ObjectBuilder, OneOfBuilder, SchemaFormat, SchemaType};
(
"ApiKeyExpiration",
OneOfBuilder::new()
.item(
ObjectBuilder::new()
.schema_type(SchemaType::String)
.enum_values(Some(["never"])),
)
.item(
ObjectBuilder::new()
.schema_type(SchemaType::String)
.format(Some(SchemaFormat::KnownFormat(KnownFormat::DateTime))),
)
.into(),
)
}
}
#[cfg(test)]
mod api_key_expiration_tests {
use super::*;
#[test]
fn test_serialization() {
assert_eq!(
serde_json::to_string(&ApiKeyExpiration::Never).unwrap(),
r#""never""#
);
let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap();
let time = time::Time::from_hms(11, 12, 13).unwrap();
assert_eq!(
serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new(
date, time
)))
.unwrap(),
r#""2022-09-10T11:12:13.000Z""#
);
}
#[test]
fn test_deserialization() {
assert_eq!(
serde_json::from_str::<ApiKeyExpiration>(r#""never""#).unwrap(),
ApiKeyExpiration::Never
);
let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap();
let time = time::Time::from_hms(11, 12, 13).unwrap();
assert_eq!(
serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(),
ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time))
);
}
#[test]
fn test_null() {
let result = serde_json::from_str::<ApiKeyExpiration>("null");
assert!(result.is_err());
let result = serde_json::from_str::<Option<ApiKeyExpiration>>("null").unwrap();
assert_eq!(result, None);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/errors.rs | crates/api_models/src/errors.rs | pub mod actix;
pub mod types;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/consts.rs | crates/api_models/src/consts.rs | /// Max payment intent fulfillment expiry
pub const MAX_ORDER_FULFILLMENT_EXPIRY: i64 = 1800;
/// Min payment intent fulfillment expiry
pub const MIN_ORDER_FULFILLMENT_EXPIRY: i64 = 60;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/mandates.rs | crates/api_models/src/mandates.rs | use common_types::payments as common_payments_types;
use masking::Secret;
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::enums as api_enums;
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct MandateId {
pub mandate_id: String,
}
#[derive(Default, Debug, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct MandateRevokedResponse {
/// The identifier for mandate
#[smithy(value_type = "String")]
pub mandate_id: String,
/// The status for mandates
#[schema(value_type = MandateStatus)]
#[smithy(value_type = "MandateStatus")]
pub status: api_enums::MandateStatus,
/// If there was an error while calling the connectors the code is received here
#[schema(example = "E0001")]
#[smithy(value_type = "Option<String>")]
pub error_code: Option<String>,
/// If there was an error while calling the connector the error message is received here
#[schema(example = "Failed while verifying the card")]
#[smithy(value_type = "Option<String>")]
pub error_message: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct MandateResponse {
/// The identifier for mandate
#[smithy(value_type = "String")]
pub mandate_id: String,
/// The status for mandates
#[schema(value_type = MandateStatus)]
#[smithy(value_type = "MandateStatus")]
pub status: api_enums::MandateStatus,
/// The identifier for payment method
#[smithy(value_type = "String")]
pub payment_method_id: String,
/// The payment method
#[smithy(value_type = "String")]
pub payment_method: String,
/// The payment method type
#[smithy(value_type = "Option<String>")]
pub payment_method_type: Option<String>,
/// The card details for mandate
#[smithy(value_type = "Option<MandateCardDetails>")]
pub card: Option<MandateCardDetails>,
/// Details about the customer’s acceptance
#[schema(value_type = Option<CustomerAcceptance>)]
#[smithy(value_type = "Option<CustomerAcceptance>")]
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
}
#[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct MandateCardDetails {
/// The last 4 digits of card
#[smithy(value_type = "Option<String>")]
pub last4_digits: Option<String>,
/// The expiry month of card
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub card_exp_month: Option<Secret<String>>,
/// The expiry year of card
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub card_exp_year: Option<Secret<String>>,
/// The card holder name
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub card_holder_name: Option<Secret<String>>,
/// The token from card locker
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub card_token: Option<Secret<String>>,
/// The card scheme network for the particular card
#[smithy(value_type = "Option<String>")]
pub scheme: Option<String>,
/// The country code in in which the card was issued
#[smithy(value_type = "Option<String>")]
pub issuer_country: Option<String>,
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
/// A unique identifier alias to identify a particular card
pub card_fingerprint: Option<Secret<String>>,
/// The first 6 digits of card
#[smithy(value_type = "Option<String>")]
pub card_isin: Option<String>,
/// The bank that issued the card
#[smithy(value_type = "Option<String>")]
pub card_issuer: Option<String>,
/// The network that facilitates payment card transactions
#[schema(value_type = Option<CardNetwork>)]
#[smithy(value_type = "Option<CardNetwork>")]
pub card_network: Option<api_enums::CardNetwork>,
/// The type of the payment card
#[smithy(value_type = "Option<String>")]
pub card_type: Option<String>,
/// The nick_name of the card holder
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub nick_name: Option<Secret<String>>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, SmithyModel)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types", mixin = true)]
pub struct MandateListConstraints {
/// limit on the number of objects to return
#[smithy(value_type = "Option<i64>", http_query = "limit")]
pub limit: Option<i64>,
/// offset on the number of objects to return
#[smithy(value_type = "Option<i64>", http_query = "offset")]
pub offset: Option<i64>,
/// status of the mandate
#[smithy(value_type = "Option<MandateStatus>", http_query = "mandate_status")]
pub mandate_status: Option<api_enums::MandateStatus>,
/// connector linked to mandate
#[smithy(value_type = "Option<String>", http_query = "connector")]
pub connector: Option<String>,
/// The time at which mandate is created
#[schema(example = "2022-09-10T10:11:12Z")]
#[smithy(value_type = "Option<String>", http_query = "created_time")]
pub created_time: Option<PrimitiveDateTime>,
/// Time less than the mandate created time
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(rename = "created_time.lt")]
#[smithy(value_type = "Option<String>", http_query = "created_time.lt")]
pub created_time_lt: Option<PrimitiveDateTime>,
/// Time greater than the mandate created time
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(rename = "created_time.gt")]
#[smithy(value_type = "Option<String>", http_query = "created_time.gt")]
pub created_time_gt: Option<PrimitiveDateTime>,
/// Time less than or equals to the mandate created time
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(rename = "created_time.lte")]
#[smithy(value_type = "Option<String>", http_query = "created_time.lte")]
pub created_time_lte: Option<PrimitiveDateTime>,
/// Time greater than or equals to the mandate created time
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(rename = "created_time.gte")]
#[smithy(value_type = "Option<String>", http_query = "created_time.gte")]
pub created_time_gte: Option<PrimitiveDateTime>,
}
/// Details required for recurring payment
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,
)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum RecurringDetails {
#[smithy(value_type = "String")]
MandateId(String),
#[smithy(value_type = "String")]
PaymentMethodId(String),
#[smithy(value_type = "ProcessorPaymentToken")]
ProcessorPaymentToken(ProcessorPaymentToken),
/// Network transaction ID and Card Details for MIT payments when payment_method_data
/// is not stored in the application
#[smithy(value_type = "NetworkTransactionIdAndCardDetails")]
NetworkTransactionIdAndCardDetails(Box<NetworkTransactionIdAndCardDetails>),
/// Network transaction ID and Network Token Details for MIT payments when payment_method_data
/// is not stored in the application
#[smithy(value_type = "NetworkTransactionIdAndNetworkTokenDetails")]
NetworkTransactionIdAndNetworkTokenDetails(Box<NetworkTransactionIdAndNetworkTokenDetails>),
}
/// Processor payment token for MIT payments where payment_method_data is not available
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct ProcessorPaymentToken {
#[smithy(value_type = "String")]
pub processor_payment_token: String,
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct NetworkTransactionIdAndCardDetails {
/// The card number
#[schema(value_type = String, example = "4242424242424242")]
#[smithy(value_type = "String")]
pub card_number: cards::CardNumber,
/// The card's expiry month
#[schema(value_type = String, example = "24")]
#[smithy(value_type = "String")]
pub card_exp_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String, example = "24")]
#[smithy(value_type = "String")]
pub card_exp_year: Secret<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
#[smithy(value_type = "Option<String>")]
pub card_holder_name: Option<Secret<String>>,
/// The name of the issuer of card
#[schema(example = "chase")]
#[smithy(value_type = "Option<String>")]
pub card_issuer: Option<String>,
/// The card network for the card
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
#[smithy(value_type = "Option<CardNetwork>")]
pub card_network: Option<api_enums::CardNetwork>,
#[schema(example = "CREDIT")]
#[smithy(value_type = "Option<String>")]
pub card_type: Option<String>,
#[schema(example = "INDIA")]
#[smithy(value_type = "Option<String>")]
pub card_issuing_country: Option<String>,
#[schema(example = "IN")]
#[smithy(value_type = "Option<String>")]
pub card_issuing_country_code: Option<String>,
#[schema(example = "JP_AMEX")]
#[smithy(value_type = "Option<String>")]
pub bank_code: Option<String>,
/// The card holder's nick name
#[schema(value_type = Option<String>, example = "John Test")]
#[smithy(value_type = "Option<String>")]
pub nick_name: Option<Secret<String>>,
/// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub network_transaction_id: Secret<String>,
}
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct NetworkTransactionIdAndNetworkTokenDetails {
/// The Network Token
#[schema(value_type = String, example = "4604000460040787")]
#[smithy(value_type = "String")]
pub network_token: cards::NetworkToken,
/// The token's expiry month
#[schema(value_type = String, example = "05")]
#[smithy(value_type = "String")]
pub token_exp_month: Secret<String>,
/// The token's expiry year
#[schema(value_type = String, example = "24")]
#[smithy(value_type = "String")]
pub token_exp_year: Secret<String>,
/// The card network for the card
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
#[smithy(value_type = "Option<CardNetwork>")]
pub card_network: Option<api_enums::CardNetwork>,
/// The type of the card such as Credit, Debit
#[schema(example = "CREDIT")]
#[smithy(value_type = "Option<String>")]
pub card_type: Option<String>,
/// The country in which the card was issued
#[schema(example = "INDIA")]
#[smithy(value_type = "Option<String>")]
pub card_issuing_country: Option<String>,
/// The bank code of the bank that issued the card
#[schema(example = "JP_AMEX")]
#[smithy(value_type = "Option<String>")]
pub bank_code: Option<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
#[smithy(value_type = "Option<String>")]
pub card_holder_name: Option<Secret<String>>,
/// The name of the issuer of card
#[schema(example = "chase")]
#[smithy(value_type = "Option<String>")]
pub card_issuer: Option<String>,
/// The card holder's nick name
#[schema(value_type = Option<String>, example = "John Test")]
#[smithy(value_type = "Option<String>")]
pub nick_name: Option<Secret<String>>,
/// The ECI(Electronic Commerce Indicator) value for this authentication.
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub eci: Option<String>,
/// The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub network_transaction_id: Secret<String>,
}
impl RecurringDetails {
pub fn is_network_transaction_id_and_card_details_flow(self) -> bool {
matches!(self, Self::NetworkTransactionIdAndCardDetails(_))
}
pub fn is_network_transaction_id_and_network_token_details_flow(self) -> bool {
matches!(self, Self::NetworkTransactionIdAndNetworkTokenDetails(_))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/user.rs | crates/api_models/src/user.rs | use std::fmt::Debug;
use common_enums::{EntityType, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, id_type, pii};
use masking::Secret;
use utoipa::ToSchema;
use crate::user_role::UserStatus;
pub mod dashboard_metadata;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
#[cfg(feature = "control_center_theme")]
pub mod theme;
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct SignUpWithMerchantIdRequest {
pub name: Secret<String>,
pub email: pii::Email,
pub password: Secret<String>,
pub company_name: String,
}
pub type SignUpWithMerchantIdResponse = AuthorizeResponse;
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct SignUpRequest {
pub email: pii::Email,
pub password: Secret<String>,
}
pub type SignInRequest = SignUpRequest;
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct ConnectAccountRequest {
pub email: pii::Email,
}
pub type ConnectAccountResponse = AuthorizeResponse;
#[derive(serde::Serialize, Debug, Clone)]
pub struct AuthorizeResponse {
pub is_email_sent: bool,
//this field is added for audit/debug reasons
#[serde(skip_serializing)]
pub user_id: String,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct ChangePasswordRequest {
pub new_password: Secret<String>,
pub old_password: Secret<String>,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct ForgotPasswordRequest {
pub email: pii::Email,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct ResetPasswordRequest {
pub token: Secret<String>,
pub password: Secret<String>,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct RotatePasswordRequest {
pub password: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct InviteUserRequest {
pub email: pii::Email,
pub name: Secret<String>,
pub role_id: String,
}
#[derive(Debug, serde::Serialize)]
pub struct InviteMultipleUserResponse {
pub email: pii::Email,
pub is_email_sent: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub password: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ReInviteUserRequest {
pub email: pii::Email,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct AcceptInviteFromEmailRequest {
pub token: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ValidateOnlyQueryParam {
pub status_check: Option<bool>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum InvitationAcceptanceStatus {
AlreadyAccepted,
SuccessfullyAccepted,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum AcceptInviteResponse {
Token(TokenResponse),
Status(InvitationAcceptanceStatus),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SwitchOrganizationRequest {
pub org_id: id_type::OrganizationId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SwitchMerchantRequest {
pub merchant_id: id_type::MerchantId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SwitchProfileRequest {
pub profile_id: id_type::ProfileId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CloneConnectorSource {
pub mca_id: id_type::MerchantConnectorAccountId,
pub merchant_id: id_type::MerchantId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CloneConnectorDestination {
pub connector_label: Option<String>,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CloneConnectorRequest {
pub source: CloneConnectorSource,
pub destination: CloneConnectorDestination,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CreateInternalUserRequest {
pub name: Secret<String>,
pub email: pii::Email,
pub password: Secret<String>,
pub role_id: String,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CreateTenantUserRequest {
pub name: Secret<String>,
pub email: pii::Email,
pub password: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct UserOrgMerchantCreateRequest {
pub organization_name: Secret<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub merchant_name: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PlatformAccountCreateRequest {
#[schema(max_length = 64, value_type = String, example = "organization_abc")]
pub organization_name: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PlatformAccountCreateResponse {
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_abc")]
pub org_id: id_type::OrganizationId,
#[schema(value_type = Option<String>, example = "organization_abc")]
pub org_name: Option<String>,
#[schema(value_type = OrganizationType, example = "standard")]
pub org_type: common_enums::OrganizationType,
#[schema(value_type = String, example = "merchant_abc")]
pub merchant_id: id_type::MerchantId,
#[schema(value_type = MerchantAccountType, example = "standard")]
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserMerchantCreate {
pub company_name: String,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: Option<common_enums::MerchantAccountRequestType>,
}
#[derive(serde::Serialize, Debug, Clone)]
pub struct GetUserDetailsResponse {
pub merchant_id: id_type::MerchantId,
pub name: Secret<String>,
pub email: pii::Email,
pub verification_days_left: Option<i64>,
pub role_id: String,
// This field is added for audit/debug reasons
#[serde(skip_serializing)]
pub user_id: String,
pub org_id: id_type::OrganizationId,
pub is_two_factor_auth_setup: bool,
pub recovery_codes_left: Option<usize>,
pub profile_id: id_type::ProfileId,
pub entity_type: EntityType,
pub theme_id: Option<String>,
pub version: common_enums::ApiVersion,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetUserRoleDetailsRequest {
pub email: pii::Email,
}
#[derive(Debug, serde::Serialize)]
pub struct GetUserRoleDetailsResponseV2 {
pub role_id: String,
pub org: NameIdUnit<Option<String>, id_type::OrganizationId>,
pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>,
pub profile: Option<NameIdUnit<String, id_type::ProfileId>>,
pub status: UserStatus,
pub entity_type: EntityType,
pub role_name: String,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct NameIdUnit<N: Debug + Clone, I: Debug + Clone> {
pub name: N,
pub id: I,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyEmailRequest {
pub token: Secret<String>,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SendVerifyEmailRequest {
pub email: pii::Email,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserAccountDetailsRequest {
pub name: Option<Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SkipTwoFactorAuthQueryParam {
pub skip_two_factor_auth: Option<bool>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct TokenResponse {
pub token: Secret<String>,
pub token_type: TokenPurpose,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TwoFactorAuthStatusResponse {
pub totp: bool,
pub recovery_code: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TwoFactorAuthAttempts {
pub is_completed: bool,
pub remaining_attempts: u8,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TwoFactorAuthStatusResponseWithAttempts {
pub totp: TwoFactorAuthAttempts,
pub recovery_code: TwoFactorAuthAttempts,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TwoFactorStatus {
pub status: Option<TwoFactorAuthStatusResponseWithAttempts>,
pub is_skippable: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct BeginTotpResponse {
pub secret: Option<TotpSecret>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TotpSecret {
pub secret: Secret<String>,
pub totp_url: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyTotpRequest {
pub totp: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyRecoveryCodeRequest {
pub recovery_code: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct RecoveryCodes {
pub recovery_codes: Vec<Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(tag = "auth_type")]
#[serde(rename_all = "snake_case")]
pub enum AuthConfig {
OpenIdConnect {
private_config: OpenIdConnectPrivateConfig,
public_config: OpenIdConnectPublicConfig,
},
MagicLink,
Password,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct OpenIdConnectPrivateConfig {
pub base_url: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub private_key: Option<Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct OpenIdConnectPublicConfig {
pub name: OpenIdProvider,
}
#[derive(
Debug, serde::Deserialize, serde::Serialize, Copy, Clone, strum::Display, Eq, PartialEq,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OpenIdProvider {
Okta,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct OpenIdConnect {
pub name: OpenIdProvider,
pub base_url: String,
pub client_id: String,
pub client_secret: Secret<String>,
pub private_key: Option<Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateUserAuthenticationMethodRequest {
pub owner_id: String,
pub owner_type: common_enums::Owner,
pub auth_method: AuthConfig,
pub allow_signup: bool,
pub email_domain: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateUserAuthenticationMethodResponse {
pub id: String,
pub auth_id: String,
pub owner_id: String,
pub owner_type: common_enums::Owner,
pub auth_type: common_enums::UserAuthType,
pub email_domain: Option<String>,
pub allow_signup: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateUserAuthenticationMethodRequest {
AuthMethod {
id: String,
auth_config: AuthConfig,
},
EmailDomain {
owner_id: String,
email_domain: String,
},
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetUserAuthenticationMethodsRequest {
pub auth_id: Option<String>,
pub email_domain: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserAuthenticationMethodResponse {
pub id: String,
pub auth_id: String,
pub auth_method: AuthMethodDetails,
pub allow_signup: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AuthMethodDetails {
#[serde(rename = "type")]
pub auth_type: common_enums::UserAuthType,
pub name: Option<OpenIdProvider>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetSsoAuthUrlRequest {
pub id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SsoSignInRequest {
pub state: Secret<String>,
pub code: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AuthIdAndThemeIdQueryParam {
pub auth_id: Option<String>,
pub theme_id: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AuthSelectRequest {
pub id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct UserKeyTransferRequest {
pub from: u32,
pub limit: u32,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserTransferKeyResponse {
pub total_transferred: usize,
}
#[derive(Debug, serde::Serialize)]
pub struct ListOrgsForUserResponse {
pub org_id: id_type::OrganizationId,
pub org_name: Option<String>,
pub org_type: common_enums::OrganizationType,
}
#[derive(Debug, serde::Serialize)]
pub struct UserMerchantAccountResponse {
pub merchant_id: id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
pub version: common_enums::ApiVersion,
}
#[derive(Debug, serde::Serialize)]
pub struct ListProfilesForUserInOrgAndMerchantAccountResponse {
pub profile_id: id_type::ProfileId,
pub profile_name: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/blocklist.rs | crates/api_models/src/blocklist.rs | use common_enums::enums;
use common_utils::events::ApiEventMetric;
use masking::StrongSecret;
use utoipa::ToSchema;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case", tag = "type", content = "data")]
pub enum BlocklistRequest {
CardBin(String),
Fingerprint(String),
ExtendedCardBin(String),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GenerateFingerprintRequest {
pub data: StrongSecret<String>,
pub key: StrongSecret<String>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct Card {
pub card_number: StrongSecret<String>,
}
pub type AddToBlocklistRequest = BlocklistRequest;
pub type DeleteFromBlocklistRequest = BlocklistRequest;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BlocklistResponse {
pub fingerprint_id: String,
#[schema(value_type = BlocklistDataKind)]
pub data_kind: enums::BlocklistDataKind,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct GenerateFingerprintResponsePayload {
pub fingerprint_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleBlocklistResponse {
pub blocklist_guard_status: String,
}
pub type AddToBlocklistResponse = BlocklistResponse;
pub type DeleteFromBlocklistResponse = BlocklistResponse;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ListBlocklistQuery {
#[schema(value_type = BlocklistDataKind)]
pub data_kind: enums::BlocklistDataKind,
#[serde(default = "default_list_limit")]
pub limit: u16,
#[serde(default)]
pub offset: u16,
pub client_secret: Option<String>,
}
fn default_list_limit() -> u16 {
10
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleBlocklistQuery {
#[schema(value_type = BlocklistDataKind)]
pub status: bool,
}
impl ApiEventMetric for BlocklistRequest {}
impl ApiEventMetric for BlocklistResponse {}
impl ApiEventMetric for ToggleBlocklistResponse {}
impl ApiEventMetric for ListBlocklistQuery {}
impl ApiEventMetric for GenerateFingerprintRequest {}
impl ApiEventMetric for ToggleBlocklistQuery {}
impl ApiEventMetric for GenerateFingerprintResponsePayload {}
impl ApiEventMetric for Card {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/connector_onboarding.rs | crates/api_models/src/connector_onboarding.rs | use common_utils::id_type;
use super::{admin, enums};
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct ActionUrlRequest {
pub connector: enums::Connector,
pub connector_id: id_type::MerchantConnectorAccountId,
pub return_url: String,
}
#[derive(serde::Serialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ActionUrlResponse {
PayPal(PayPalActionUrlResponse),
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct OnboardingSyncRequest {
pub profile_id: id_type::ProfileId,
pub connector_id: id_type::MerchantConnectorAccountId,
pub connector: enums::Connector,
}
#[derive(serde::Serialize, Debug, Clone)]
pub struct PayPalActionUrlResponse {
pub action_url: String,
}
#[derive(serde::Serialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum OnboardingStatus {
PayPal(PayPalOnboardingStatus),
}
#[derive(serde::Serialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum PayPalOnboardingStatus {
AccountNotFound,
PaymentsNotReceivable,
PpcpCustomDenied,
MorePermissionsNeeded,
EmailNotVerified,
Success(PayPalOnboardingDone),
ConnectorIntegrated(Box<admin::MerchantConnectorResponse>),
}
#[derive(serde::Serialize, Debug, Clone)]
pub struct PayPalOnboardingDone {
pub payer_id: id_type::MerchantId,
}
#[derive(serde::Serialize, Debug, Clone)]
pub struct PayPalIntegrationDone {
pub connector_id: String,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct ResetTrackingIdRequest {
pub connector_id: id_type::MerchantConnectorAccountId,
pub connector: enums::Connector,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/verifications.rs | crates/api_models/src/verifications.rs | use common_utils::id_type;
/// The request body for verification of merchant (everything except domain_names are prefilled)
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayMerchantVerificationConfigs {
pub domain_names: Vec<String>,
pub encrypt_to: String,
pub partner_internal_merchant_identifier: String,
pub partner_merchant_name: String,
}
/// The derivation point for domain names from request body
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ApplepayMerchantVerificationRequest {
pub domain_names: Vec<String>,
pub merchant_connector_account_id: id_type::MerchantConnectorAccountId,
}
/// Response to be sent for the verify/applepay api
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ApplepayMerchantResponse {
pub status_message: String,
}
/// QueryParams to be send by the merchant for fetching the verified domains
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ApplepayGetVerifiedDomainsParam {
pub merchant_id: id_type::MerchantId,
pub merchant_connector_account_id: id_type::MerchantConnectorAccountId,
}
/// Response to be sent for derivation of the already verified domains
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ApplepayVerifiedDomainsResponse {
pub verified_domains: Vec<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/lib.rs | crates/api_models/src/lib.rs | pub mod admin;
pub mod analytics;
pub mod api_keys;
pub mod apple_pay_certificates_migration;
pub mod authentication;
pub mod blocklist;
pub mod cards_info;
pub mod chat;
pub mod conditional_configs;
pub mod connector_enums;
pub mod connector_onboarding;
pub mod consts;
pub mod currency;
pub mod customers;
pub mod disputes;
pub mod enums;
pub mod ephemeral_key;
#[cfg(feature = "errors")]
pub mod errors;
pub mod events;
pub mod external_service_auth;
pub mod feature_matrix;
pub mod files;
pub mod gsm;
pub mod health_check;
pub mod locker_migration;
pub mod mandates;
pub mod oidc;
pub mod open_router;
pub mod organization;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod pm_auth;
pub mod poll;
pub mod process_tracker;
pub mod profile_acquirer;
#[cfg(feature = "v2")]
pub mod proxy;
#[cfg(feature = "recon")]
pub mod recon;
pub mod refunds;
pub mod relay;
#[cfg(feature = "v2")]
pub mod revenue_recovery_data_backfill;
pub mod routing;
pub mod subscription;
pub mod surcharge_decision_configs;
pub mod three_ds_decision_rule;
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
pub mod user;
pub mod user_role;
pub mod verifications;
pub mod verify_connector;
pub mod webhook_events;
pub mod webhooks;
pub trait ValidateFieldAndGet<Request> {
fn validate_field_and_get(
&self,
request: &Request,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ValidationError>
where
Self: Sized;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/revenue_recovery_data_backfill.rs | crates/api_models/src/revenue_recovery_data_backfill.rs | use std::{collections::HashMap, fs::File, io::BufReader};
use actix_multipart::form::{tempfile::TempFile, MultipartForm};
use actix_web::{HttpResponse, ResponseError};
use common_enums::{CardNetwork, PaymentMethodType};
use common_utils::{events::ApiEventMetric, id_type, pii::PhoneNumberStrategy};
use csv::Reader;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{Date, PrimitiveDateTime};
use crate::payments;
#[derive(Debug, Deserialize, Serialize)]
pub struct RevenueRecoveryBackfillRequest {
pub bin_number: Option<Secret<String>>,
pub customer_id_resp: String,
pub connector_payment_id: Option<String>,
pub token: Option<Secret<String>>,
pub exp_date: Option<Secret<String>>,
pub card_network: Option<CardNetwork>,
pub payment_method_sub_type: Option<PaymentMethodType>,
pub clean_bank_name: Option<String>,
pub country_name: Option<String>,
pub daily_retry_history: Option<String>,
pub is_active: Option<bool>,
#[serde(
default,
deserialize_with = "RevenueRecoveryBackfillRequest::deserialize_history_vec_opt"
)]
pub account_update_history: Option<Vec<AccountUpdateHistoryRecord>>,
}
impl RevenueRecoveryBackfillRequest {
pub fn deserialize_history_vec_opt<'de, D>(
deserializer: D,
) -> Result<Option<Vec<AccountUpdateHistoryRecord>>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let val = Option::<String>::deserialize(deserializer)?;
match val.as_deref().map(str::trim) {
None | Some("") => Ok(None),
Some(s) => serde_json::from_str::<Vec<AccountUpdateHistoryRecord>>(s)
.map(Some)
.map_err(serde::de::Error::custom),
}
}
}
#[derive(Debug, Serialize)]
pub struct UnlockStatusResponse {
pub unlocked: bool,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct UnlockStatusRequest {
pub connector_customer_id: String,
pub payment_intent_id: id_type::GlobalPaymentId,
}
#[derive(Debug, Serialize)]
pub struct RevenueRecoveryDataBackfillResponse {
pub processed_records: usize,
pub failed_records: usize,
}
#[derive(Debug, Serialize)]
pub struct CsvParsingResult {
pub records: Vec<RevenueRecoveryBackfillRequest>,
pub failed_records: Vec<CsvParsingError>,
}
#[derive(Debug, Serialize)]
pub struct CsvParsingError {
pub row_number: usize,
pub error: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountUpdateHistoryRecord {
pub old_token: String,
pub new_token: String,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub updated_at: PrimitiveDateTime,
pub old_token_info: Option<payments::AdditionalCardInfo>,
pub new_token_info: Option<payments::AdditionalCardInfo>,
}
/// Comprehensive card
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComprehensiveCardData {
pub card_type: Option<String>,
pub card_exp_month: Option<Secret<String>>,
pub card_exp_year: Option<Secret<String>>,
pub card_network: Option<CardNetwork>,
pub card_issuer: Option<String>,
pub card_issuing_country: Option<String>,
pub daily_retry_history: Option<HashMap<PrimitiveDateTime, i32>>,
pub is_active: Option<bool>,
pub account_update_history: Option<Vec<AccountUpdateHistoryRecord>>,
}
impl ApiEventMetric for RevenueRecoveryDataBackfillResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for UnlockStatusResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for UnlockStatusRequest {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for CsvParsingResult {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for CsvParsingError {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for RedisDataResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for UpdateTokenStatusRequest {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
impl ApiEventMetric for UpdateTokenStatusResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
#[derive(Debug, Clone, Serialize)]
pub enum BackfillError {
InvalidCardType(String),
DatabaseError(String),
RedisError(String),
CsvParsingError(String),
FileProcessingError(String),
}
#[derive(serde::Deserialize)]
pub struct BackfillQuery {
pub cutoff_time: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum RedisKeyType {
Status, // for customer:{id}:status
Tokens, // for customer:{id}:tokens
}
#[derive(Debug, Deserialize)]
pub struct GetRedisDataQuery {
pub key_type: RedisKeyType,
}
#[derive(Debug, Serialize)]
pub struct RedisDataResponse {
pub exists: bool,
pub ttl_seconds: i64,
pub data: Option<serde_json::Value>,
}
#[derive(Debug, Serialize)]
pub enum ScheduledAtUpdate {
SetToNull,
SetToDateTime(PrimitiveDateTime),
}
impl<'de> Deserialize<'de> for ScheduledAtUpdate {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
match value {
serde_json::Value::String(s) => {
if s.to_lowercase() == "null" {
Ok(Self::SetToNull)
} else {
// Parse as datetime using iso8601 deserializer
common_utils::custom_serde::iso8601::deserialize(
&mut serde_json::Deserializer::from_str(&format!("\"{}\"", s)),
)
.map(Self::SetToDateTime)
.map_err(serde::de::Error::custom)
}
}
_ => Err(serde::de::Error::custom(
"Expected null variable or datetime iso8601 ",
)),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct UpdateTokenStatusRequest {
pub connector_customer_id: String,
pub payment_processor_token: Secret<String, PhoneNumberStrategy>,
pub scheduled_at: Option<ScheduledAtUpdate>,
pub is_hard_decline: Option<bool>,
pub error_code: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct UpdateTokenStatusResponse {
pub updated: bool,
pub message: String,
}
impl std::fmt::Display for BackfillError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidCardType(msg) => write!(f, "Invalid card type: {}", msg),
Self::DatabaseError(msg) => write!(f, "Database error: {}", msg),
Self::RedisError(msg) => write!(f, "Redis error: {}", msg),
Self::CsvParsingError(msg) => write!(f, "CSV parsing error: {}", msg),
Self::FileProcessingError(msg) => write!(f, "File processing error: {}", msg),
}
}
}
impl std::error::Error for BackfillError {}
impl ResponseError for BackfillError {
fn error_response(&self) -> HttpResponse {
HttpResponse::BadRequest().json(serde_json::json!({
"error": self.to_string()
}))
}
}
#[derive(Debug, MultipartForm)]
pub struct RevenueRecoveryDataBackfillForm {
#[multipart(rename = "file")]
pub file: TempFile,
}
impl RevenueRecoveryDataBackfillForm {
pub fn validate_and_get_records_with_errors(&self) -> Result<CsvParsingResult, BackfillError> {
// Step 1: Open the file
let file = File::open(self.file.file.path())
.map_err(|error| BackfillError::FileProcessingError(error.to_string()))?;
let mut csv_reader = Reader::from_reader(BufReader::new(file));
// Step 2: Parse CSV into typed records
let mut records = Vec::new();
let mut failed_records = Vec::new();
for (row_index, record_result) in csv_reader
.deserialize::<RevenueRecoveryBackfillRequest>()
.enumerate()
{
match record_result {
Ok(record) => {
records.push(record);
}
Err(err) => {
failed_records.push(CsvParsingError {
row_number: row_index + 2, // +2 because enumerate starts at 0 and CSV has header row
error: err.to_string(),
});
}
}
}
Ok(CsvParsingResult {
records,
failed_records,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/refunds.rs | crates/api_models/src/refunds.rs | use std::collections::HashMap;
pub use common_utils::types::MinorUnit;
use common_utils::{pii, types::TimeRange};
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use super::payments::AmountFilter;
#[cfg(feature = "v1")]
use crate::admin;
use crate::{admin::MerchantConnectorInfo, enums};
#[cfg(feature = "v1")]
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize, SmithyModel)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct RefundRequest {
/// The payment id against which refund is to be initiated
#[schema(
max_length = 30,
min_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4",
value_type = String,
)]
#[smithy(value_type = "String")]
pub payment_id: common_utils::id_type::PaymentId,
/// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id.
#[schema(
max_length = 30,
min_length = 30,
example = "ref_mbabizu24mvu3mela5njyhpit4"
)]
#[smithy(value_type = "Option<String>")]
pub refund_id: Option<String>,
/// The identifier for the Merchant Account
#[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub merchant_id: Option<common_utils::id_type::MerchantId>,
/// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount
#[schema(value_type = Option<i64> , minimum = 100, example = 6540)]
#[smithy(value_type = "Option<i64>")]
pub amount: Option<MinorUnit>,
/// Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer`
#[schema(max_length = 255, example = "Customer returned the product")]
#[smithy(value_type = "Option<String>")]
pub reason: Option<String>,
/// To indicate whether to refund needs to be instant or scheduled. Default value is instant
#[schema(default = "Instant", example = "Instant")]
#[smithy(value_type = "Option<RefundType>")]
pub refund_type: Option<RefundType>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
#[smithy(value_type = "Option<Object>")]
pub metadata: Option<pii::SecretSerdeValue>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
#[smithy(value_type = "Option<MerchantConnectorDetailsWrap>")]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
/// Charge specific fields for controlling the revert of funds from either platform or connected account
#[schema(value_type = Option<SplitRefund>)]
#[smithy(value_type = "Option<SplitRefund>")]
pub split_refunds: Option<common_types::refunds::SplitRefund>,
/// If true, returns stringified connector raw response body
pub all_keys_required: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RefundsCreateRequest {
/// The payment id against which refund is initiated
#[schema(
max_length = 30,
min_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4",
value_type = String,
)]
pub payment_id: common_utils::id_type::GlobalPaymentId,
/// Unique Identifier for the Refund given by the Merchant.
#[schema(
max_length = 64,
min_length = 1,
example = "ref_mbabizu24mvu3mela5njyhpit4",
value_type = String,
)]
pub merchant_reference_id: common_utils::id_type::RefundReferenceId,
/// The identifier for the Merchant Account
#[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)]
pub merchant_id: Option<common_utils::id_type::MerchantId>,
/// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment
#[schema(value_type = Option<i64> , minimum = 100, example = 6540)]
pub amount: Option<MinorUnit>,
/// Reason for the refund. Often useful for displaying to users and your customer support executive.
#[schema(max_length = 255, example = "Customer returned the product")]
pub reason: Option<String>,
/// To indicate whether to refund needs to be instant or scheduled. Default value is instant
#[schema(default = "Instant", example = "Instant")]
pub refund_type: Option<RefundType>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorAuthDetails>)]
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
/// If true, returns stringified connector raw response body
pub return_raw_connector_response: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Default, Debug, Clone, Deserialize)]
pub struct RefundsRetrieveBody {
pub force_sync: Option<bool>,
pub all_keys_required: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Default, Debug, Clone, Deserialize)]
pub struct RefundsRetrieveBody {
pub force_sync: Option<bool>,
pub return_raw_connector_response: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Default, Debug, Clone, Deserialize)]
pub struct RefundsRetrievePayload {
/// `force_sync` with the connector to get refund details
pub force_sync: Option<bool>,
/// Merchant connector details used to make payments.
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
/// If true, returns stringified connector raw response body
pub return_raw_connector_response: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RefundsRetrieveRequest {
/// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id.
#[schema(
max_length = 30,
min_length = 30,
example = "ref_mbabizu24mvu3mela5njyhpit4"
)]
pub refund_id: String,
/// `force_sync` with the connector to get refund details
/// (defaults to false)
pub force_sync: Option<bool>,
/// Merchant connector details used to make payments.
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
/// If true, returns stringified connector raw response body
pub all_keys_required: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RefundsRetrieveRequest {
/// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id.
#[schema(
max_length = 30,
min_length = 30,
example = "ref_mbabizu24mvu3mela5njyhpit4"
)]
pub refund_id: common_utils::id_type::GlobalRefundId,
/// `force_sync` with the connector to get refund details
/// (defaults to false)
pub force_sync: Option<bool>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorAuthDetails>)]
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
/// If true, returns stringified connector raw response body
pub return_raw_connector_response: Option<bool>,
}
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize, SmithyModel)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct RefundUpdateRequest {
#[serde(skip)]
pub refund_id: String,
/// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive
#[schema(max_length = 255, example = "Customer returned the product")]
#[smithy(value_type = "Option<String>")]
pub reason: Option<String>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
#[smithy(value_type = "Option<Object>")]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v2")]
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RefundMetadataUpdateRequest {
/// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive
#[schema(max_length = 255, example = "Customer returned the product")]
pub reason: Option<String>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RefundManualUpdateRequest {
#[serde(skip)]
pub refund_id: String,
/// Merchant ID
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
/// The status for refund
pub status: Option<RefundStatus>,
/// The code for the error
pub error_code: Option<String>,
/// The error message
pub error_message: Option<String>,
}
#[cfg(feature = "v1")]
/// To indicate whether to refund needs to be instant or scheduled
#[derive(
Default,
Debug,
Clone,
Copy,
ToSchema,
Deserialize,
Serialize,
Eq,
PartialEq,
strum::Display,
SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum RefundType {
Scheduled,
#[default]
Instant,
}
#[cfg(feature = "v2")]
/// To indicate whether the refund needs to be instant or scheduled
#[derive(
Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display,
)]
#[serde(rename_all = "snake_case")]
pub enum RefundType {
Scheduled,
#[default]
Instant,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct RefundResponse {
/// Unique Identifier for the refund
#[smithy(value_type = "String")]
pub refund_id: String,
/// The payment id against which refund is initiated
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub payment_id: common_utils::id_type::PaymentId,
/// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc
#[schema(value_type = i64 , minimum = 100, example = 6540)]
#[smithy(value_type = "i64")]
pub amount: MinorUnit,
/// The three-letter ISO currency code
#[smithy(value_type = "String")]
pub currency: String,
/// The status for refund
#[smithy(value_type = "RefundStatus")]
pub status: RefundStatus,
/// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive
#[smithy(value_type = "Option<String>")]
pub reason: Option<String>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object
#[schema(value_type = Option<Object>)]
#[smithy(value_type = "Option<Object>")]
pub metadata: Option<pii::SecretSerdeValue>,
/// The error message
#[smithy(value_type = "Option<String>")]
pub error_message: Option<String>,
/// The code for the error
#[smithy(value_type = "Option<String>")]
pub error_code: Option<String>,
/// Error code unified across the connectors is received here if there was an error while calling connector
#[smithy(value_type = "Option<String>")]
pub unified_code: Option<String>,
/// Error message unified across the connectors is received here if there was an error while calling connector
#[smithy(value_type = "Option<String>")]
pub unified_message: Option<String>,
/// The timestamp at which refund is created
#[serde(with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<String>")]
pub created_at: Option<PrimitiveDateTime>,
/// The timestamp at which refund is updated
#[serde(with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<String>")]
pub updated_at: Option<PrimitiveDateTime>,
/// The connector used for the refund and the corresponding payment
#[schema(example = "stripe")]
#[smithy(value_type = "String")]
pub connector: String,
/// The id of business profile for this refund
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub profile_id: Option<common_utils::id_type::ProfileId>,
/// The merchant_connector_id of the processor through which this payment went through
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
/// Charge specific fields for controlling the revert of funds from either platform or connected account
#[schema(value_type = Option<SplitRefund>,)]
#[smithy(value_type = "Option<SplitRefund>")]
pub split_refunds: Option<common_types::refunds::SplitRefund>,
/// Error code received from the issuer in case of failed refunds
#[smithy(value_type = "Option<String>")]
pub issuer_error_code: Option<String>,
/// Error message received from the issuer in case of failed refunds
#[smithy(value_type = "Option<String>")]
pub issuer_error_message: Option<String>,
/// Contains whole connector response
#[schema(value_type = Option<String>)]
pub raw_connector_response: Option<masking::Secret<String>>,
}
#[cfg(feature = "v1")]
impl RefundResponse {
pub fn get_refund_id_as_string(&self) -> String {
self.refund_id.clone()
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct RefundResponse {
/// Global Refund Id for the refund
#[schema(value_type = String)]
pub id: common_utils::id_type::GlobalRefundId,
/// The payment id against which refund is initiated
#[schema(value_type = String)]
pub payment_id: common_utils::id_type::GlobalPaymentId,
/// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment.
#[schema(
max_length = 30,
min_length = 30,
example = "ref_mbabizu24mvu3mela5njyhpit4",
value_type = Option<String>,
)]
pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>,
/// The refund amount
#[schema(value_type = i64 , minimum = 100, example = 6540)]
pub amount: MinorUnit,
/// The three-letter ISO currency code
#[schema(value_type = Currency)]
pub currency: common_enums::Currency,
/// The status for refund
pub status: RefundStatus,
/// An arbitrary string attached to the object
pub reason: Option<String>,
/// Metadata is useful for storing additional, unstructured information on an object
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
/// The error details for the refund
pub error_details: Option<RefundErrorDetails>,
/// The timestamp at which refund is created
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The timestamp at which refund is updated
#[serde(with = "common_utils::custom_serde::iso8601")]
pub updated_at: PrimitiveDateTime,
/// The connector used for the refund and the corresponding payment
#[schema(example = "stripe", value_type = Connector)]
pub connector: enums::Connector,
/// The id of business profile for this refund
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
/// The merchant_connector_id of the processor through which this payment went through
#[schema(value_type = String)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
/// The reference id of the connector for the refund
pub connector_refund_reference_id: Option<String>,
/// Contains raw connector response
#[schema(value_type = Option<String>)]
pub raw_connector_response: Option<masking::Secret<String>>,
}
#[cfg(feature = "v2")]
impl RefundResponse {
pub fn get_refund_id_as_string(&self) -> String {
self.id.get_string_repr().to_owned()
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct RefundErrorDetails {
pub code: String,
pub message: String,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct RefundListRequest {
/// The identifier for the payment
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub payment_id: Option<common_utils::id_type::PaymentId>,
/// The identifier for the refund
#[smithy(value_type = "Option<String>")]
pub refund_id: Option<String>,
/// The identifier for business profile
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub profile_id: Option<common_utils::id_type::ProfileId>,
/// Limit on the number of objects to return
#[smithy(value_type = "Option<i64>")]
pub limit: Option<i64>,
/// The starting point within a list of objects
#[smithy(value_type = "Option<i64>")]
pub offset: Option<i64>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc)
#[serde(flatten)]
pub time_range: Option<TimeRange>,
/// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range)
#[smithy(value_type = "Option<AmountFilter>")]
pub amount_filter: Option<AmountFilter>,
/// The list of connectors to filter refunds list
#[smithy(value_type = "Option<Vec<String>>")]
pub connector: Option<Vec<String>>,
/// The list of merchant connector ids to filter the refunds list for selected label
#[schema(value_type = Option<Vec<String>>)]
#[smithy(value_type = "Option<Vec<String>>")]
pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
/// The list of currencies to filter refunds list
#[schema(value_type = Option<Vec<Currency>>)]
#[smithy(value_type = "Option<Vec<Currency>>")]
pub currency: Option<Vec<enums::Currency>>,
/// The list of refund statuses to filter refunds list
#[schema(value_type = Option<Vec<RefundStatus>>)]
#[smithy(value_type = "Option<Vec<RefundStatus>>")]
pub refund_status: Option<Vec<enums::RefundStatus>>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct RefundListRequest {
/// The identifier for the payment
#[schema(value_type = Option<String>)]
pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
/// The identifier for the refund
#[schema(value_type = String)]
pub refund_id: Option<common_utils::id_type::GlobalRefundId>,
/// Limit on the number of objects to return
pub limit: Option<i64>,
/// The starting point within a list of objects
pub offset: Option<i64>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc)
#[serde(flatten)]
pub time_range: Option<TimeRange>,
/// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range)
pub amount_filter: Option<AmountFilter>,
/// The list of connectors to filter refunds list
pub connector: Option<Vec<String>>,
/// The list of merchant connector ids to filter the refunds list for selected label
#[schema(value_type = Option<Vec<String>>)]
pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
/// The list of currencies to filter refunds list
#[schema(value_type = Option<Vec<Currency>>)]
pub currency: Option<Vec<enums::Currency>>,
/// The list of refund statuses to filter refunds list
#[schema(value_type = Option<Vec<RefundStatus>>)]
pub refund_status: Option<Vec<enums::RefundStatus>>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct RefundListResponse {
/// The number of refunds included in the list
#[smithy(value_type = "usize")]
pub count: usize,
/// The total number of refunds in the list
#[smithy(value_type = "i64")]
pub total_count: i64,
/// The List of refund response object
#[smithy(value_type = "Vec<RefundResponse>")]
pub data: Vec<RefundResponse>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)]
pub struct RefundListMetaData {
/// The list of available connector filters
pub connector: Vec<String>,
/// The list of available currency filters
#[schema(value_type = Vec<Currency>)]
pub currency: Vec<enums::Currency>,
/// The list of available refund status filters
#[schema(value_type = Vec<RefundStatus>)]
pub refund_status: Vec<enums::RefundStatus>,
}
#[derive(Clone, Debug, serde::Serialize, ToSchema)]
pub struct RefundListFilters {
/// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances
pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
/// The list of available currency filters
#[schema(value_type = Vec<Currency>)]
pub currency: Vec<enums::Currency>,
/// The list of available refund status filters
#[schema(value_type = Vec<RefundStatus>)]
pub refund_status: Vec<enums::RefundStatus>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct RefundAggregateResponse {
/// The list of refund status with their count
pub status_with_count: HashMap<enums::RefundStatus, i64>,
}
/// The status for refunds
#[derive(
Debug,
Eq,
Clone,
Copy,
PartialEq,
Default,
Deserialize,
Serialize,
ToSchema,
strum::Display,
strum::EnumIter,
SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Pending,
Review,
}
impl From<enums::RefundStatus> for RefundStatus {
fn from(status: enums::RefundStatus) -> Self {
match status {
enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed,
enums::RefundStatus::ManualReview => Self::Review,
enums::RefundStatus::Pending => Self::Pending,
enums::RefundStatus::Success => Self::Succeeded,
}
}
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(status: RefundStatus) -> Self {
match status {
RefundStatus::Failed => Self::Failure,
RefundStatus::Review => Self::ManualReview,
RefundStatus::Pending => Self::Pending,
RefundStatus::Succeeded => Self::Success,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/routing.rs | crates/api_models/src/routing.rs | use std::{fmt::Debug, ops::Deref};
use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule};
use common_utils::{
errors::{ParsingError, ValidationError},
ext_traits::ValueExt,
fp_utils, pii,
};
use euclid::frontend::ast::Program;
pub use euclid::{
dssa::types::EuclidAnalysable,
enums::RoutableConnectors,
frontend::{
ast,
dir::{DirKeyKind, EuclidDirFilter},
},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{enums::TransactionType, open_router};
// Define constants for default values
const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0;
const DEFAULT_BUCKET_SIZE: i32 = 200;
const DEFAULT_HEDGING_PERCENT: f64 = 5.0;
const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35;
const DEFAULT_PAYMENT_METHOD: &str = "CARD";
const MAX_NAME_LENGTH: usize = 64;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ConnectorSelection {
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
impl ConnectorSelection {
pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> {
match self {
Self::Priority(list) => list.clone(),
Self::VolumeSplit(splits) => {
splits.iter().map(|split| split.connector.clone()).collect()
}
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
pub name: String,
pub description: String,
pub algorithm: StaticRoutingAlgorithm,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
#[schema(value_type = Option<String>)]
pub name: Option<RoutingConfigName>,
pub description: Option<String>,
pub algorithm: Option<StaticRoutingAlgorithm>,
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(try_from = "String")]
#[schema(value_type = String)]
pub struct RoutingConfigName(String);
impl RoutingConfigName {
pub fn new(name: impl Into<String>) -> Result<Self, ValidationError> {
let name = name.into();
if name.len() > MAX_NAME_LENGTH {
return Err(ValidationError::InvalidValue {
message: format!(
"Length of name field must not exceed {} characters",
MAX_NAME_LENGTH
),
});
}
Ok(Self(name))
}
}
impl TryFrom<String> for RoutingConfigName {
type Error = ValidationError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl Deref for RoutingConfigName {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct ProfileDefaultRoutingConfig {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub connectors: Vec<RoutableConnectorChoice>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveQuery {
pub limit: Option<u16>,
pub offset: Option<u8>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingActivatePayload {
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQuery {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQueryWrapper {
pub routing_query: RoutingRetrieveQuery,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Response of the retrieved routing configs for a merchant account
pub struct RoutingRetrieveResponse {
pub algorithm: Option<MerchantRoutingAlgorithm>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
#[serde(untagged)]
pub enum LinkedRoutingConfigRetrieveResponse {
MerchantAccountBased(Box<RoutingRetrieveResponse>),
ProfileBased(Vec<RoutingDictionaryRecord>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Routing Algorithm specific to merchants
pub struct MerchantRoutingAlgorithm {
#[schema(value_type = String)]
pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
pub description: String,
pub algorithm: RoutingAlgorithmWrapper,
pub created_at: i64,
pub modified_at: i64,
pub algorithm_for: TransactionType,
}
impl EuclidDirFilter for ConnectorSelection {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardBin,
DirKeyKind::ExtendedCardBin,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::PayLaterType,
DirKeyKind::WalletType,
DirKeyKind::UpiType,
DirKeyKind::BankRedirectType,
DirKeyKind::BankDebitType,
DirKeyKind::CryptoType,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::AuthenticationType,
DirKeyKind::MandateAcceptanceType,
DirKeyKind::MandateType,
DirKeyKind::PaymentType,
DirKeyKind::SetupFutureUsage,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::IssuerCountry,
DirKeyKind::BusinessCountry,
DirKeyKind::BusinessLabel,
DirKeyKind::MetaData,
DirKeyKind::RewardType,
DirKeyKind::VoucherType,
DirKeyKind::CardRedirectType,
DirKeyKind::BankTransferType,
DirKeyKind::RealTimePaymentType,
DirKeyKind::TransactionInitiator,
DirKeyKind::NetworkTokenType,
];
}
impl EuclidAnalysable for ConnectorSelection {
fn get_dir_value_for_analysis(
&self,
rule_name: String,
) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> {
self.get_connector_list()
.into_iter()
.map(|connector_choice| {
let connector_name = connector_choice.connector.to_string();
let mca_id = connector_choice.merchant_connector_id.clone();
(
euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())),
std::collections::HashMap::from_iter([(
"CONNECTOR_SELECTION".to_string(),
serde_json::json!({
"rule_name": rule_name,
"connector_name": connector_name,
"mca_id": mca_id,
}),
)]),
)
})
.collect()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]
pub struct ConnectorVolumeSplit {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
/// Routable Connector chosen for a payment
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")]
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)]
pub enum RoutableChoiceKind {
OnlyConnector,
FullStruct,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum RoutableChoiceSerde {
OnlyConnector(Box<RoutableConnectors>),
FullStruct {
connector: RoutableConnectors,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
}
impl std::fmt::Display for RoutableConnectorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base = self.connector.to_string();
if let Some(mca_id) = &self.merchant_connector_id {
return write!(f, "{}:{}", base, mca_id.get_string_repr());
}
write!(f, "{base}")
}
}
impl From<RoutableConnectorChoice> for ast::ConnectorChoice {
fn from(value: RoutableConnectorChoice) -> Self {
Self {
connector: value.connector,
}
}
}
impl PartialEq for RoutableConnectorChoice {
fn eq(&self, other: &Self) -> bool {
self.connector.eq(&other.connector)
&& self.merchant_connector_id.eq(&other.merchant_connector_id)
}
}
impl Eq for RoutableConnectorChoice {}
impl From<RoutableChoiceSerde> for RoutableConnectorChoice {
fn from(value: RoutableChoiceSerde) -> Self {
match value {
RoutableChoiceSerde::OnlyConnector(connector) => Self {
choice_kind: RoutableChoiceKind::OnlyConnector,
connector: *connector,
merchant_connector_id: None,
},
RoutableChoiceSerde::FullStruct {
connector,
merchant_connector_id,
} => Self {
choice_kind: RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id,
},
}
}
}
impl From<RoutableConnectorChoice> for RoutableChoiceSerde {
fn from(value: RoutableConnectorChoice) -> Self {
match value.choice_kind {
RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)),
RoutableChoiceKind::FullStruct => Self::FullStruct {
connector: value.connector,
merchant_connector_id: value.merchant_connector_id,
},
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct RoutableConnectorChoiceWithStatus {
pub routable_connector_choice: RoutableConnectorChoice,
pub status: bool,
}
impl RoutableConnectorChoiceWithStatus {
pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self {
Self {
routable_connector_choice,
status,
}
}
}
#[derive(
Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingAlgorithmKind {
Single,
Priority,
VolumeSplit,
Advanced,
Dynamic,
ThreeDsDecisionRule,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingPayloadWrapper {
pub updated_config: Vec<RoutableConnectorChoice>,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum RoutingAlgorithmWrapper {
Static(StaticRoutingAlgorithm),
Dynamic(DynamicRoutingAlgorithm),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum DynamicRoutingAlgorithm {
EliminationBasedAlgorithm(EliminationRoutingConfig),
SuccessBasedAlgorithm(SuccessBasedRoutingConfig),
ContractBasedAlgorithm(ContractBasedRoutingConfig),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "RoutingAlgorithmSerde"
)]
pub enum StaticRoutingAlgorithm {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
#[schema(value_type=ProgramConnectorSelection)]
Advanced(Program<ConnectorSelection>),
#[schema(value_type=ProgramThreeDsDecisionRule)]
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ProgramThreeDsDecisionRule {
pub default_selection: ThreeDSDecisionRule,
#[schema(value_type = RuleThreeDsDecisionRule)]
pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>,
#[schema(value_type = HashMap<String, serde_json::Value>)]
pub metadata: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RuleThreeDsDecisionRule {
pub name: String,
pub connector_selection: ThreeDSDecision,
#[schema(value_type = Vec<IfStatement>)]
pub statements: Vec<ast::IfStatement>,
}
impl StaticRoutingAlgorithm {
pub fn should_validate_connectors_in_routing_config(&self) -> bool {
match self {
Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true,
Self::ThreeDsDecisionRule(_) => false,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmSerde {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
Advanced(Program<ConnectorSelection>),
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm {
type Error = error_stack::Report<ParsingError>;
fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> {
match &value {
RoutingAlgorithmSerde::Priority(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Priority Algorithm",
))?
}
RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Volume split Algorithm",
))?
}
_ => {}
};
Ok(match value {
RoutingAlgorithmSerde::Single(i) => Self::Single(i),
RoutingAlgorithmSerde::Priority(i) => Self::Priority(i),
RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i),
RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i),
RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(i),
})
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "StraightThroughAlgorithmSerde",
into = "StraightThroughAlgorithmSerde"
)]
pub enum StraightThroughAlgorithm {
#[schema(title = "Single")]
Single(Box<RoutableConnectorChoice>),
#[schema(title = "Priority")]
Priority(Vec<RoutableConnectorChoice>),
#[schema(title = "VolumeSplit")]
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum StraightThroughAlgorithmInner {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum StraightThroughAlgorithmSerde {
Direct(StraightThroughAlgorithmInner),
Nested {
algorithm: StraightThroughAlgorithmInner,
},
}
impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm {
type Error = error_stack::Report<ParsingError>;
fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> {
let inner = match value {
StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm,
StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm,
};
match &inner {
StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Priority Algorithm",
))?
}
StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Volume split Algorithm",
))?
}
_ => {}
};
Ok(match inner {
StraightThroughAlgorithmInner::Single(single) => Self::Single(single),
StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist),
StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit),
})
}
}
impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde {
fn from(value: StraightThroughAlgorithm) -> Self {
let inner = match value {
StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn),
StraightThroughAlgorithm::Priority(plist) => {
StraightThroughAlgorithmInner::Priority(plist)
}
StraightThroughAlgorithm::VolumeSplit(vsplit) => {
StraightThroughAlgorithmInner::VolumeSplit(vsplit)
}
};
Self::Nested { algorithm: inner }
}
}
impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm {
fn from(value: StraightThroughAlgorithm) -> Self {
match value {
StraightThroughAlgorithm::Single(conn) => Self::Single(conn),
StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns),
StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits),
}
}
}
impl StaticRoutingAlgorithm {
pub fn get_kind(&self) -> RoutingAlgorithmKind {
match self {
Self::Single(_) => RoutingAlgorithmKind::Single,
Self::Priority(_) => RoutingAlgorithmKind::Priority,
Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit,
Self::Advanced(_) => RoutingAlgorithmKind::Advanced,
Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingAlgorithmRef {
pub algorithm_id: Option<common_utils::id_type::RoutingId>,
pub timestamp: i64,
pub config_algo_id: Option<String>,
pub surcharge_config_algo_id: Option<String>,
}
impl RoutingAlgorithmRef {
pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) {
self.algorithm_id = Some(new_id);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn update_conditional_config_id(&mut self, ids: String) {
self.config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn update_surcharge_config_id(&mut self, ids: String) {
self.surcharge_config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn parse_routing_algorithm(
value: Option<pii::SecretSerdeValue>,
) -> Result<Option<Self>, error_stack::Report<ParsingError>> {
value
.map(|val| val.parse_value::<Self>("RoutingAlgorithmRef"))
.transpose()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionaryRecord {
#[schema(value_type = String)]
pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
pub kind: RoutingAlgorithmKind,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
pub algorithm_for: Option<TransactionType>,
pub decision_engine_routing_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionary {
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
pub active_id: Option<String>,
pub records: Vec<RoutingDictionaryRecord>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
#[serde(untagged)]
pub enum RoutingKind {
Config(RoutingDictionary),
RoutingAlgorithm(Vec<RoutingDictionaryRecord>),
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct RoutingAlgorithmId {
#[schema(value_type = String)]
pub routing_algorithm_id: common_utils::id_type::RoutingId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingLinkWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: RoutingAlgorithmId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicAlgorithmWithTimestamp<T> {
pub algorithm_id: Option<T>,
pub timestamp: i64,
}
impl<T> DynamicAlgorithmWithTimestamp<T> {
pub fn new(algorithm_id: Option<T>) -> Self {
Self {
algorithm_id,
timestamp: common_utils::date_time::now_unix_timestamp(),
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
pub dynamic_routing_volume_split: Option<u8>,
pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>,
pub contract_based_routing: Option<ContractRoutingAlgorithm>,
#[serde(default)]
pub is_merchant_created_in_decision_engine: bool,
}
pub trait DynamicRoutingAlgoAccessor {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>;
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures;
}
impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl EliminationRoutingAlgorithm {
pub fn new(
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
common_utils::id_type::RoutingId,
>,
) -> Self {
Self {
algorithm_id_with_timestamp,
enabled_feature: DynamicRoutingFeatures::None,
}
}
}
impl SuccessBasedAlgorithm {
pub fn new(
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
common_utils::id_type::RoutingId,
>,
) -> Self {
Self {
algorithm_id_with_timestamp,
enabled_feature: DynamicRoutingFeatures::None,
}
}
}
impl DynamicRoutingAlgorithmRef {
pub fn update(&mut self, new: Self) {
if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm {
self.elimination_routing_algorithm = Some(elimination_routing_algorithm)
}
if let Some(success_based_algorithm) = new.success_based_algorithm {
self.success_based_algorithm = Some(success_based_algorithm)
}
if let Some(contract_based_routing) = new.contract_based_routing {
self.contract_based_routing = Some(contract_based_routing)
}
}
pub fn update_enabled_features(
&mut self,
algo_type: DynamicRoutingType,
feature_to_enable: DynamicRoutingFeatures,
) {
match algo_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
}
}
pub fn update_volume_split(&mut self, volume: Option<u8>) {
self.dynamic_routing_volume_split = volume
}
pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) {
self.is_merchant_created_in_decision_engine = is_created;
}
pub fn is_success_rate_routing_enabled(&self) -> bool {
self.success_based_algorithm
.as_ref()
.map(|success_based_routing| {
if success_based_routing
.algorithm_id_with_timestamp
.algorithm_id
.is_none()
{
return false;
}
success_based_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
})
.unwrap_or_default()
}
pub fn is_elimination_enabled(&self) -> bool {
self.elimination_routing_algorithm
.as_ref()
.map(|elimination_routing| {
if elimination_routing
.algorithm_id_with_timestamp
.algorithm_id
.is_none()
{
return false;
}
elimination_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
})
.unwrap_or_default()
}
}
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplit {
pub routing_type: RoutingType,
pub split: u8,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplitWrapper {
pub routing_info: RoutingVolumeSplit,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum RoutingType {
#[default]
Static,
Dynamic,
}
impl RoutingType {
pub fn is_dynamic_routing(self) -> bool {
self == Self::Dynamic
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuccessBasedAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ContractRoutingAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EliminationRoutingAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
impl EliminationRoutingAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
impl SuccessBasedAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
impl DynamicRoutingAlgorithmRef {
pub fn update_algorithm_id(
&mut self,
new_id: common_utils::id_type::RoutingId,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
};
}
pub fn update_feature(
&mut self,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
};
}
pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
if let Some(success_based_algo) = &self.success_based_algorithm {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: success_based_algo.enabled_feature,
});
}
}
DynamicRoutingType::EliminationRouting => {
if let Some(elimination_based_algo) = &self.elimination_routing_algorithm {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: elimination_based_algo.enabled_feature,
});
}
}
DynamicRoutingType::ContractBasedRouting => {
if let Some(contract_based_algo) = &self.contract_based_routing {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: contract_based_algo.enabled_feature,
});
}
}
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleDynamicRoutingQuery {
pub enable: DynamicRoutingFeatures,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/webhook_events.rs | crates/api_models/src/webhook_events.rs | use std::collections::HashSet;
use common_enums::{EventClass, EventType, WebhookDeliveryAttempt};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
/// The constraints to apply when filtering events.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventListConstraints {
/// Filter events created after the specified time.
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_after: Option<PrimitiveDateTime>,
/// Filter events created before the specified time.
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_before: Option<PrimitiveDateTime>,
/// Include at most the specified number of events.
pub limit: Option<u16>,
/// Include events after the specified offset.
pub offset: Option<u16>,
/// Filter all events associated with the specified object identifier (Payment Intent ID,
/// Refund ID, etc.)
pub object_id: Option<String>,
/// Filter all events associated with the specified Event_id
pub event_id: Option<String>,
/// Filter all events associated with the specified business profile ID.
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
/// Filter events by their class.
pub event_classes: Option<HashSet<EventClass>>,
/// Filter events by their type.
pub event_types: Option<HashSet<EventType>>,
/// Filter all events by `is_overall_delivery_successful` field of the event.
pub is_delivered: Option<bool>,
}
#[derive(Debug)]
pub enum EventListConstraintsInternal {
GenericFilter {
created_after: Option<PrimitiveDateTime>,
created_before: Option<PrimitiveDateTime>,
limit: Option<i64>,
offset: Option<i64>,
event_classes: Option<HashSet<EventClass>>,
event_types: Option<HashSet<EventType>>,
is_delivered: Option<bool>,
},
ObjectIdFilter {
object_id: String,
},
EventIdFilter {
event_id: String,
},
}
/// The response body for each item when listing events.
#[derive(Debug, Serialize, ToSchema)]
pub struct EventListItemResponse {
/// The identifier for the Event.
#[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")]
pub event_id: String,
/// The identifier for the Merchant Account.
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
/// The identifier for the Business Profile.
#[schema(max_length = 64, value_type = String, example = "SqB0zwDGR5wHppWf0bx7GKr1f2")]
pub profile_id: common_utils::id_type::ProfileId,
/// The identifier for the object (Payment Intent ID, Refund ID, etc.)
#[schema(max_length = 64, example = "QHrfd5LUDdZaKtAjdJmMu0dMa1")]
pub object_id: String,
/// Specifies the type of event, which includes the object and its status.
pub event_type: EventType,
/// Specifies the class of event (the type of object: Payment, Refund, etc.)
pub event_class: EventClass,
/// Indicates whether the webhook was ultimately delivered or not.
pub is_delivery_successful: Option<bool>,
/// The identifier for the initial delivery attempt. This will be the same as `event_id` for
/// the initial delivery attempt.
#[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")]
pub initial_attempt_id: String,
/// Time at which the event was created.
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
}
/// The response body of list initial delivery attempts api call.
#[derive(Debug, Serialize, ToSchema)]
pub struct TotalEventsResponse {
/// The list of events
pub events: Vec<EventListItemResponse>,
/// Count of total events
pub total_count: i64,
}
impl TotalEventsResponse {
pub fn new(total_count: i64, events: Vec<EventListItemResponse>) -> Self {
Self {
events,
total_count,
}
}
}
impl common_utils::events::ApiEventMetric for TotalEventsResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Events {
merchant_id: self.events.first().map(|event| event.merchant_id.clone())?,
})
}
}
/// The response body for retrieving an event.
#[derive(Debug, Serialize, ToSchema)]
pub struct EventRetrieveResponse {
#[serde(flatten)]
pub event_information: EventListItemResponse,
/// The request information (headers and body) sent in the webhook.
pub request: OutgoingWebhookRequestContent,
/// The response information (headers, body and status code) received for the webhook sent.
pub response: OutgoingWebhookResponseContent,
/// Indicates the type of delivery attempt.
pub delivery_attempt: Option<WebhookDeliveryAttempt>,
}
impl common_utils::events::ApiEventMetric for EventRetrieveResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Events {
merchant_id: self.event_information.merchant_id.clone(),
})
}
}
/// The request information (headers and body) sent in the webhook.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct OutgoingWebhookRequestContent {
/// The request body sent in the webhook.
#[schema(value_type = String)]
#[serde(alias = "payload")]
pub body: Secret<String>,
/// The request headers sent in the webhook.
#[schema(
value_type = Vec<(String, String)>,
example = json!([["content-type", "application/json"], ["content-length", "1024"]]))
]
pub headers: Vec<(String, Secret<String>)>,
}
/// The response information (headers, body and status code) received for the webhook sent.
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct OutgoingWebhookResponseContent {
/// The response body received for the webhook sent.
#[schema(value_type = Option<String>)]
#[serde(alias = "payload")]
pub body: Option<Secret<String>>,
/// The response headers received for the webhook sent.
#[schema(
value_type = Option<Vec<(String, String)>>,
example = json!([["content-type", "application/json"], ["content-length", "1024"]]))
]
pub headers: Option<Vec<(String, Secret<String>)>>,
/// The HTTP status code for the webhook sent.
#[schema(example = 200)]
pub status_code: Option<u16>,
/// Error message in case any error occurred when trying to deliver the webhook.
#[schema(example = 200)]
pub error_message: Option<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct EventListRequestInternal {
pub merchant_id: common_utils::id_type::MerchantId,
pub constraints: EventListConstraints,
}
impl common_utils::events::ApiEventMetric for EventListRequestInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Events {
merchant_id: self.merchant_id.clone(),
})
}
}
#[derive(Debug, serde::Serialize)]
pub struct WebhookDeliveryAttemptListRequestInternal {
pub merchant_id: common_utils::id_type::MerchantId,
pub initial_attempt_id: String,
}
impl common_utils::events::ApiEventMetric for WebhookDeliveryAttemptListRequestInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Events {
merchant_id: self.merchant_id.clone(),
})
}
}
#[derive(Debug, serde::Serialize)]
pub struct WebhookDeliveryRetryRequestInternal {
pub merchant_id: common_utils::id_type::MerchantId,
pub event_id: String,
}
impl common_utils::events::ApiEventMetric for WebhookDeliveryRetryRequestInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Events {
merchant_id: self.merchant_id.clone(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/customers.rs | crates/api_models/src/customers.rs | use common_types::primitive_wrappers::CustomerListLimit;
use common_utils::{crypto, custom_serde, id_type, pii, types::Description};
use masking::Secret;
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use utoipa::ToSchema;
use crate::payments;
/// The customer details
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerRequest {
/// The identifier for the customer object. If not provided the customer ID will be autogenerated.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
#[smithy(value_type = "Option<String>")]
pub customer_id: Option<id_type::CustomerId>,
/// The identifier for the Merchant Account
#[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
#[serde(skip)]
pub merchant_id: id_type::MerchantId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")]
#[smithy(value_type = "Option<String>")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")]
#[smithy(value_type = "Option<String>")]
pub email: Option<pii::Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
#[smithy(value_type = "Option<String>")]
pub phone: Option<Secret<String>>,
/// An arbitrary string that you can attach to a customer object.
#[schema(max_length = 255, example = "First Customer", value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub description: Option<Description>,
/// The country code for the customer phone number
#[schema(max_length = 255, example = "+65")]
#[smithy(value_type = "Option<String>")]
pub phone_country_code: Option<String>,
/// The address for the customer
#[schema(value_type = Option<AddressDetails>)]
#[smithy(value_type = "Option<AddressDetails>")]
pub address: Option<payments::AddressDetails>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
#[smithy(value_type = "Option<Object>")]
pub metadata: Option<pii::SecretSerdeValue>,
/// Customer's tax registration ID
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: Option<Secret<String>>,
}
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types", mixin = true)]
pub struct CustomerListRequest {
/// Offset
#[schema(example = 32)]
#[smithy(value_type = "Option<u32>", http_query = "offset")]
pub offset: Option<u32>,
/// Limit
#[schema(example = 32)]
#[smithy(value_type = "Option<u16>", http_query = "limit")]
pub limit: Option<u16>,
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
pub struct CustomerListRequestWithConstraints {
/// Offset
#[schema(example = 32)]
pub offset: Option<u32>,
/// Limit
#[schema(example = 32)]
pub limit: Option<CustomerListLimit>,
/// Unique identifier for a customer
pub customer_id: Option<id_type::CustomerId>,
/// Filter with created time range
#[serde(flatten)]
pub time_range: Option<common_utils::types::TimeRange>,
}
#[cfg(feature = "v1")]
impl CustomerRequest {
pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
Some(
self.customer_id
.to_owned()
.unwrap_or_else(common_utils::generate_customer_id_of_default_length),
)
}
pub fn get_address(&self) -> Option<payments::AddressDetails> {
self.address.clone()
}
pub fn get_optional_email(&self) -> Option<pii::Email> {
self.email.clone()
}
}
/// The customer details
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CustomerRequest {
/// The merchant identifier for the customer object.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub merchant_reference_id: Option<id_type::CustomerId>,
/// The customer's name
#[schema(max_length = 255, value_type = String, example = "Jon Test")]
pub name: Secret<String>,
/// The customer's email address
#[schema(value_type = String, max_length = 255, example = "JonTest@test.com")]
pub email: pii::Email,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
pub phone: Option<Secret<String>>,
/// An arbitrary string that you can attach to a customer object.
#[schema(max_length = 255, example = "First Customer", value_type = Option<String>)]
pub description: Option<Description>,
/// The country code for the customer phone number
#[schema(max_length = 255, example = "+65")]
pub phone_country_code: Option<String>,
/// The default billing address for the customer
#[schema(value_type = Option<AddressDetails>)]
pub default_billing_address: Option<payments::AddressDetails>,
/// The default shipping address for the customer
#[schema(value_type = Option<AddressDetails>)]
pub default_shipping_address: Option<payments::AddressDetails>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
pub tax_registration_id: Option<Secret<String>>,
}
#[cfg(feature = "v2")]
impl CustomerRequest {
pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
self.merchant_reference_id.clone()
}
pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> {
self.default_billing_address.clone()
}
pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> {
self.default_shipping_address.clone()
}
pub fn get_optional_email(&self) -> Option<pii::Email> {
Some(self.email.clone())
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerResponse {
/// The identifier for the customer object
#[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
#[smithy(value_type = "String")]
pub customer_id: id_type::CustomerId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")]
#[smithy(value_type = "Option<String>")]
pub name: crypto::OptionalEncryptableName,
/// The customer's email address
#[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")]
#[smithy(value_type = "Option<String>")]
pub email: crypto::OptionalEncryptableEmail,
/// The customer's phone number
#[schema(value_type = Option<String>,max_length = 255, example = "9123456789")]
#[smithy(value_type = "Option<String>")]
pub phone: crypto::OptionalEncryptablePhone,
/// The country code for the customer phone number
#[schema(max_length = 255, example = "+65")]
#[smithy(value_type = "Option<String>")]
pub phone_country_code: Option<String>,
/// An arbitrary string that you can attach to a customer object.
#[schema(max_length = 255, example = "First Customer", value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub description: Option<Description>,
/// The address for the customer
#[schema(value_type = Option<AddressDetails>)]
#[smithy(value_type = "Option<AddressDetails>")]
pub address: Option<payments::AddressDetails>,
/// A timestamp (ISO 8601 code) that determines when the customer was created
#[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")]
#[serde(with = "custom_serde::iso8601")]
#[smithy(value_type = "Option<String>")]
pub created_at: time::PrimitiveDateTime,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
#[smithy(value_type = "Option<Object>")]
pub metadata: Option<pii::SecretSerdeValue>,
/// The identifier for the default payment method.
#[schema(max_length = 64, example = "pm_djh2837dwduh890123")]
#[smithy(value_type = "Option<String>")]
pub default_payment_method_id: Option<String>,
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
}
#[cfg(feature = "v1")]
impl CustomerResponse {
pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
Some(self.customer_id.clone())
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CustomerResponse {
/// Unique identifier for the customer
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub id: id_type::GlobalCustomerId,
/// The identifier for the customer object
#[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub merchant_reference_id: Option<id_type::CustomerId>,
/// Connector specific customer reference ids
#[schema(value_type = Option<Object>, example = json!({"mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506"}))]
pub connector_customer_ids: Option<common_types::customers::ConnectorCustomerMap>,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")]
pub name: crypto::OptionalEncryptableName,
/// The customer's email address
#[schema(value_type = Option<String> ,max_length = 255, example = "JonTest@test.com")]
pub email: crypto::OptionalEncryptableEmail,
/// The customer's phone number
#[schema(value_type = Option<String>,max_length = 255, example = "9123456789")]
pub phone: crypto::OptionalEncryptablePhone,
/// The country code for the customer phone number
#[schema(max_length = 255, example = "+65")]
pub phone_country_code: Option<String>,
/// An arbitrary string that you can attach to a customer object.
#[schema(max_length = 255, example = "First Customer", value_type = Option<String>)]
pub description: Option<Description>,
/// The default billing address for the customer
#[schema(value_type = Option<AddressDetails>)]
pub default_billing_address: Option<payments::AddressDetails>,
/// The default shipping address for the customer
#[schema(value_type = Option<AddressDetails>)]
pub default_shipping_address: Option<payments::AddressDetails>,
/// A timestamp (ISO 8601 code) that determines when the customer was created
#[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")]
#[serde(with = "custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// The identifier for the default payment method.
#[schema(value_type = Option<String>, max_length = 64, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")]
pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
}
#[cfg(feature = "v2")]
impl CustomerResponse {
pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
self.merchant_reference_id.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerDeleteResponse {
/// The identifier for the customer object
#[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
#[smithy(value_type = "String")]
pub customer_id: id_type::CustomerId,
/// Whether customer was deleted or not
#[schema(example = false)]
#[smithy(value_type = "bool")]
pub customer_deleted: bool,
/// Whether address was deleted or not
#[schema(example = false)]
#[smithy(value_type = "bool")]
pub address_deleted: bool,
/// Whether payment methods deleted or not
#[schema(example = false)]
#[smithy(value_type = "bool")]
pub payment_methods_deleted: bool,
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize, Serialize, ToSchema)]
pub struct CustomerDeleteResponse {
/// Unique identifier for the customer
#[schema(
min_length = 32,
max_length = 64,
example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
value_type = String
)]
pub id: id_type::GlobalCustomerId,
/// The identifier for the customer object
#[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub merchant_reference_id: Option<id_type::CustomerId>,
/// Whether customer was deleted or not
#[schema(example = false)]
pub customer_deleted: bool,
/// Whether address was deleted or not
#[schema(example = false)]
pub address_deleted: bool,
/// Whether payment methods deleted or not
#[schema(example = false)]
pub payment_methods_deleted: bool,
}
/// The identifier for the customer object. If not provided the customer ID will be autogenerated.
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerUpdateRequest {
/// The identifier for the Merchant Account
#[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
#[serde(skip)]
pub merchant_id: id_type::MerchantId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")]
#[smithy(value_type = "Option<String>")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")]
#[smithy(value_type = "Option<String>")]
pub email: Option<pii::Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
#[smithy(value_type = "Option<String>")]
pub phone: Option<Secret<String>>,
/// An arbitrary string that you can attach to a customer object.
#[schema(max_length = 255, example = "First Customer", value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub description: Option<Description>,
/// The country code for the customer phone number
#[schema(max_length = 255, example = "+65")]
#[smithy(value_type = "Option<String>")]
pub phone_country_code: Option<String>,
/// The address for the customer
#[schema(value_type = Option<AddressDetails>)]
#[smithy(value_type = "Option<AddressDetails>")]
pub address: Option<payments::AddressDetails>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
#[smithy(value_type = "Option<Object>")]
pub metadata: Option<pii::SecretSerdeValue>,
/// Customer's tax registration ID
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
impl CustomerUpdateRequest {
pub fn get_address(&self) -> Option<payments::AddressDetails> {
self.address.clone()
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CustomerUpdateRequest {
/// The customer's name
#[schema(max_length = 255, value_type = String, example = "Jon Test")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(value_type = String, max_length = 255, example = "JonTest@test.com")]
pub email: Option<pii::Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
pub phone: Option<Secret<String>>,
/// An arbitrary string that you can attach to a customer object.
#[schema(max_length = 255, example = "First Customer", value_type = Option<String>)]
pub description: Option<Description>,
/// The country code for the customer phone number
#[schema(max_length = 255, example = "+65")]
pub phone_country_code: Option<String>,
/// The default billing address for the customer
#[schema(value_type = Option<AddressDetails>)]
pub default_billing_address: Option<payments::AddressDetails>,
/// The default shipping address for the customer
#[schema(value_type = Option<AddressDetails>)]
pub default_shipping_address: Option<payments::AddressDetails>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// The unique identifier of the payment method
#[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")]
pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
pub tax_registration_id: Option<Secret<String>>,
}
#[cfg(feature = "v2")]
impl CustomerUpdateRequest {
pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> {
self.default_billing_address.clone()
}
pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> {
self.default_shipping_address.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
pub struct CustomerUpdateRequestInternal {
pub customer_id: id_type::CustomerId,
pub request: CustomerUpdateRequest,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
pub struct CustomerUpdateRequestInternal {
pub id: id_type::GlobalCustomerId,
pub request: CustomerUpdateRequest,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct CustomerListResponse {
/// List of customers
pub data: Vec<CustomerResponse>,
/// Total count of customers
pub total_count: usize,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/poll.rs | crates/api_models/src/poll.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use serde::Serialize;
use utoipa::ToSchema;
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct PollResponse {
/// The poll id
pub poll_id: String,
/// Status of the poll
pub status: PollStatus,
}
#[derive(Debug, strum::Display, strum::EnumString, Clone, serde::Serialize, ToSchema)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PollStatus {
Pending,
Completed,
NotFound,
}
impl ApiEventMetric for PollResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Poll {
poll_id: self.poll_id.clone(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/disputes.rs | crates/api_models/src/disputes.rs | use std::collections::HashMap;
use common_utils::types::{StringMinorUnit, TimeRange};
use masking::{Deserialize, Serialize};
use serde::de::Error;
use smithy::SmithyModel;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use super::enums::{Currency, DisputeStage, DisputeStatus};
use crate::{admin::MerchantConnectorInfo, files};
#[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)]
pub struct DisputeResponse {
/// The identifier for dispute
pub dispute_id: String,
/// The identifier for payment_intent
#[schema(value_type = String)]
pub payment_id: common_utils::id_type::PaymentId,
/// The identifier for payment_attempt
pub attempt_id: String,
/// The dispute amount
pub amount: StringMinorUnit,
/// The three-letter ISO currency code
#[schema(value_type = Currency)]
pub currency: Currency,
/// Stage of the dispute
pub dispute_stage: DisputeStage,
/// Status of the dispute
pub dispute_status: DisputeStatus,
/// connector to which dispute is associated with
pub connector: String,
/// Status of the dispute sent by connector
pub connector_status: String,
/// Dispute id sent by connector
pub connector_dispute_id: String,
/// Reason of dispute sent by connector
pub connector_reason: Option<String>,
/// Reason code of dispute sent by connector
pub connector_reason_code: Option<String>,
/// Evidence deadline of dispute sent by connector
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub challenge_required_by: Option<PrimitiveDateTime>,
/// Dispute created time sent by connector
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub connector_created_at: Option<PrimitiveDateTime>,
/// Dispute updated time sent by connector
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub connector_updated_at: Option<PrimitiveDateTime>,
/// Time at which dispute is received
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The `profile_id` associated with the dispute
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
/// The `merchant_connector_id` of the connector / processor through which the dispute was processed
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct DisputeResponsePaymentsRetrieve {
/// The identifier for dispute
#[smithy(value_type = "String")]
pub dispute_id: String,
/// Stage of the dispute
#[smithy(value_type = "DisputeStage")]
pub dispute_stage: DisputeStage,
/// Status of the dispute
#[smithy(value_type = "DisputeStatus")]
pub dispute_status: DisputeStatus,
/// Status of the dispute sent by connector
#[smithy(value_type = "String")]
pub connector_status: String,
/// Dispute id sent by connector
#[smithy(value_type = "String")]
pub connector_dispute_id: String,
/// Reason of dispute sent by connector
#[smithy(value_type = "Option<String>")]
pub connector_reason: Option<String>,
/// Reason code of dispute sent by connector
#[smithy(value_type = "Option<String>")]
pub connector_reason_code: Option<String>,
/// Evidence deadline of dispute sent by connector
#[serde(with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<String>")]
pub challenge_required_by: Option<PrimitiveDateTime>,
/// Dispute created time sent by connector
#[serde(with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<String>")]
pub connector_created_at: Option<PrimitiveDateTime>,
/// Dispute updated time sent by connector
#[serde(with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<String>")]
pub connector_updated_at: Option<PrimitiveDateTime>,
/// Time at which dispute is received
#[serde(with = "common_utils::custom_serde::iso8601")]
#[smithy(value_type = "String")]
pub created_at: PrimitiveDateTime,
}
#[derive(Debug, Serialize, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EvidenceType {
CancellationPolicy,
CustomerCommunication,
CustomerSignature,
Receipt,
RefundPolicy,
ServiceDocumentation,
ShippingDocumentation,
InvoiceShowingDistinctTransactions,
RecurringTransactionAgreement,
UncategorizedFile,
}
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct DisputeEvidenceBlock {
/// Evidence type
pub evidence_type: EvidenceType,
/// File metadata
pub file_metadata_response: files::FileMetadataResponse,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct DisputeListGetConstraints {
/// The identifier for dispute
pub dispute_id: Option<String>,
/// The payment_id against which dispute is raised
pub payment_id: Option<common_utils::id_type::PaymentId>,
/// Limit on the number of objects to return
pub limit: Option<u32>,
/// The starting point within a list of object
pub offset: Option<u32>,
/// The identifier for business profile
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
/// The comma separated list of status of the disputes
#[serde(default, deserialize_with = "parse_comma_separated")]
pub dispute_status: Option<Vec<DisputeStatus>>,
/// The comma separated list of stages of the disputes
#[serde(default, deserialize_with = "parse_comma_separated")]
pub dispute_stage: Option<Vec<DisputeStage>>,
/// Reason for the dispute
pub reason: Option<String>,
/// The comma separated list of connectors linked to disputes
#[serde(default, deserialize_with = "parse_comma_separated")]
pub connector: Option<Vec<String>>,
/// The comma separated list of currencies of the disputes
#[serde(default, deserialize_with = "parse_comma_separated")]
pub currency: Option<Vec<Currency>>,
/// The merchant connector id to filter the disputes list
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
pub time_range: Option<TimeRange>,
}
#[derive(Clone, Debug, serde::Serialize, ToSchema)]
pub struct DisputeListFilters {
/// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances
pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
/// The list of available currency filters
pub currency: Vec<Currency>,
/// The list of available dispute status filters
pub dispute_status: Vec<DisputeStatus>,
/// The list of available dispute stage filters
pub dispute_stage: Vec<DisputeStage>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct SubmitEvidenceRequest {
///Dispute Id
pub dispute_id: String,
/// Logs showing the usage of service by customer
pub access_activity_log: Option<String>,
/// Billing address of the customer
pub billing_address: Option<String>,
/// File Id of cancellation policy
pub cancellation_policy: Option<String>,
/// Details of showing cancellation policy to customer before purchase
pub cancellation_policy_disclosure: Option<String>,
/// Details telling why customer's subscription was not cancelled
pub cancellation_rebuttal: Option<String>,
/// File Id of customer communication
pub customer_communication: Option<String>,
/// Customer email address
pub customer_email_address: Option<String>,
/// Customer name
pub customer_name: Option<String>,
/// IP address of the customer
pub customer_purchase_ip: Option<String>,
/// Fild Id of customer signature
pub customer_signature: Option<String>,
/// Product Description
pub product_description: Option<String>,
/// File Id of receipt
pub receipt: Option<String>,
/// File Id of refund policy
pub refund_policy: Option<String>,
/// Details of showing refund policy to customer before purchase
pub refund_policy_disclosure: Option<String>,
/// Details why customer is not entitled to refund
pub refund_refusal_explanation: Option<String>,
/// Customer service date
pub service_date: Option<String>,
/// File Id service documentation
pub service_documentation: Option<String>,
/// Shipping address of the customer
pub shipping_address: Option<String>,
/// Delivery service that shipped the product
pub shipping_carrier: Option<String>,
/// Shipping date
pub shipping_date: Option<String>,
/// File Id shipping documentation
pub shipping_documentation: Option<String>,
/// Tracking number of shipped product
pub shipping_tracking_number: Option<String>,
/// File Id showing two distinct transactions when customer claims a payment was charged twice
pub invoice_showing_distinct_transactions: Option<String>,
/// File Id of recurring transaction agreement
pub recurring_transaction_agreement: Option<String>,
/// Any additional supporting file
pub uncategorized_file: Option<String>,
/// Any additional evidence statements
pub uncategorized_text: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct DeleteEvidenceRequest {
/// Id of the dispute
pub dispute_id: String,
/// Evidence Type to be deleted
pub evidence_type: EvidenceType,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DisputeRetrieveRequest {
/// The identifier for dispute
pub dispute_id: String,
/// Decider to enable or disable the connector call for dispute retrieve request
pub force_sync: Option<bool>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct DisputesAggregateResponse {
/// Different status of disputes with their count
pub status_with_count: HashMap<DisputeStatus, i64>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DisputeRetrieveBody {
/// Decider to enable or disable the connector call for dispute retrieve request
pub force_sync: Option<bool>,
}
fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>
where
D: serde::Deserializer<'de>,
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
let output = Option::<&str>::deserialize(v)?;
output
.map(|s| {
s.split(",")
.map(|x| x.parse::<T>().map_err(D::Error::custom))
.collect::<Result<_, _>>()
})
.transpose()
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/feature_matrix.rs | crates/api_models/src/feature_matrix.rs | use std::collections::HashSet;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)]
pub struct FeatureMatrixRequest {
// List of connectors for which the feature matrix is requested
#[schema(value_type = Option<Vec<Connector>>)]
pub connectors: Option<Vec<common_enums::connector_enums::Connector>>,
}
#[derive(Debug, Clone, ToSchema, Serialize)]
pub struct CardSpecificFeatures {
/// Indicates whether three_ds card payments are supported
#[schema(value_type = FeatureStatus)]
pub three_ds: common_enums::FeatureStatus,
/// Indicates whether non three_ds card payments are supported
#[schema(value_type = FeatureStatus)]
pub no_three_ds: common_enums::FeatureStatus,
/// List of supported card networks
#[schema(value_type = Vec<CardNetwork>)]
pub supported_card_networks: Vec<common_enums::CardNetwork>,
}
#[derive(Debug, Clone, ToSchema, Serialize)]
#[serde(untagged)]
pub enum PaymentMethodSpecificFeatures {
/// Card specific features
Card(CardSpecificFeatures),
}
#[derive(Debug, ToSchema, Serialize)]
pub struct SupportedPaymentMethod {
/// The payment method supported by the connector
#[schema(value_type = PaymentMethod)]
pub payment_method: common_enums::PaymentMethod,
/// The payment method type supported by the connector
#[schema(value_type = PaymentMethodType)]
pub payment_method_type: common_enums::PaymentMethodType,
/// The display name of the payment method type
pub payment_method_type_display_name: String,
/// Indicates whether the payment method supports mandates via the connector
#[schema(value_type = FeatureStatus)]
pub mandates: common_enums::FeatureStatus,
/// Indicates whether the payment method supports refunds via the connector
#[schema(value_type = FeatureStatus)]
pub refunds: common_enums::FeatureStatus,
/// List of supported capture methods supported by the payment method type
#[schema(value_type = Vec<CaptureMethod>)]
pub supported_capture_methods: Vec<common_enums::CaptureMethod>,
/// Information on the Payment method specific payment features
#[serde(flatten)]
pub payment_method_specific_features: Option<PaymentMethodSpecificFeatures>,
/// List of countries supported by the payment method type via the connector
#[schema(value_type = Option<HashSet<CountryAlpha3>>)]
pub supported_countries: Option<HashSet<common_enums::CountryAlpha3>>,
/// List of currencies supported by the payment method type via the connector
#[schema(value_type = Option<HashSet<Currency>>)]
pub supported_currencies: Option<HashSet<common_enums::Currency>>,
}
#[derive(Debug, ToSchema, Serialize)]
pub struct ConnectorFeatureMatrixResponse {
/// The name of the connector
pub name: String,
/// The display name of the connector
pub display_name: String,
/// The description of the connector
pub description: String,
/// The base url of the connector
pub base_url: Option<String>,
/// The category of the connector
#[schema(value_type = HyperswitchConnectorCategory, example = "payment_gateway")]
pub category: common_enums::HyperswitchConnectorCategory,
/// The integration status of the connector
#[schema(value_type = ConnectorIntegrationStatus, example = "live")]
pub integration_status: common_enums::ConnectorIntegrationStatus,
/// The list of payment methods supported by the connector
pub supported_payment_methods: Option<Vec<SupportedPaymentMethod>>,
/// The list of webhook flows supported by the connector
#[schema(value_type = Option<Vec<EventClass>>)]
pub supported_webhook_flows: Option<Vec<common_enums::EventClass>>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct FeatureMatrixListResponse {
/// The number of connectors included in the response
pub connector_count: usize,
// The list of payments response objects
pub connectors: Vec<ConnectorFeatureMatrixResponse>,
}
impl common_utils::events::ApiEventMetric for FeatureMatrixListResponse {}
impl common_utils::events::ApiEventMetric for FeatureMatrixRequest {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/profile_acquirer.rs | crates/api_models/src/profile_acquirer.rs | use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct ProfileAcquirerCreate {
/// The merchant id assigned by the acquirer
#[schema(value_type= String,example = "M123456789")]
pub acquirer_assigned_merchant_id: String,
/// merchant name
#[schema(value_type= String,example = "NewAge Retailer")]
pub merchant_name: String,
/// Network provider
#[schema(value_type= String,example = "VISA")]
pub network: common_enums::enums::CardNetwork,
/// Acquirer bin
#[schema(value_type= String,example = "456789")]
pub acquirer_bin: String,
/// Acquirer ica provided by acquirer
#[schema(value_type= Option<String>,example = "401288")]
pub acquirer_ica: Option<String>,
/// Fraud rate for the particular acquirer configuration
#[schema(value_type= f64,example = 0.01)]
pub acquirer_fraud_rate: f64,
/// Parent profile id to link the acquirer account with
#[schema(value_type= String,example = "pro_ky0yNyOXXlA5hF8JzE5q")]
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Serialize, Deserialize, ToSchema, Clone)]
pub struct ProfileAcquirerResponse {
/// The unique identifier of the profile acquirer
#[schema(value_type= String,example = "pro_acq_LCRdERuylQvNQ4qh3QE0")]
pub profile_acquirer_id: common_utils::id_type::ProfileAcquirerId,
/// The merchant id assigned by the acquirer
#[schema(value_type= String,example = "M123456789")]
pub acquirer_assigned_merchant_id: String,
/// Merchant name
#[schema(value_type= String,example = "NewAge Retailer")]
pub merchant_name: String,
/// Network provider
#[schema(value_type= String,example = "VISA")]
pub network: common_enums::enums::CardNetwork,
/// Acquirer bin
#[schema(value_type= String,example = "456789")]
pub acquirer_bin: String,
/// Acquirer ica provided by acquirer
#[schema(value_type= Option<String>,example = "401288")]
pub acquirer_ica: Option<String>,
/// Fraud rate for the particular acquirer configuration
#[schema(value_type= f64,example = 0.01)]
pub acquirer_fraud_rate: f64,
/// Parent profile id to link the acquirer account with
#[schema(value_type= String,example = "pro_ky0yNyOXXlA5hF8JzE5q")]
pub profile_id: common_utils::id_type::ProfileId,
}
impl common_utils::events::ApiEventMetric for ProfileAcquirerCreate {}
impl common_utils::events::ApiEventMetric for ProfileAcquirerResponse {}
impl
From<(
common_utils::id_type::ProfileAcquirerId,
&common_utils::id_type::ProfileId,
&common_types::domain::AcquirerConfig,
)> for ProfileAcquirerResponse
{
fn from(
(profile_acquirer_id, profile_id, acquirer_config): (
common_utils::id_type::ProfileAcquirerId,
&common_utils::id_type::ProfileId,
&common_types::domain::AcquirerConfig,
),
) -> Self {
Self {
profile_acquirer_id,
profile_id: profile_id.clone(),
acquirer_assigned_merchant_id: acquirer_config.acquirer_assigned_merchant_id.clone(),
merchant_name: acquirer_config.merchant_name.clone(),
network: acquirer_config.network.clone(),
acquirer_bin: acquirer_config.acquirer_bin.clone(),
acquirer_ica: acquirer_config.acquirer_ica.clone(),
acquirer_fraud_rate: acquirer_config.acquirer_fraud_rate,
}
}
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ProfileAcquirerUpdate {
#[schema(value_type = Option<String>, example = "M987654321")]
pub acquirer_assigned_merchant_id: Option<String>,
#[schema(value_type = Option<String>, example = "Updated Retailer Name")]
pub merchant_name: Option<String>,
#[schema(value_type = Option<String>, example = "MASTERCARD")]
pub network: Option<common_enums::enums::CardNetwork>,
#[schema(value_type = Option<String>, example = "987654")]
pub acquirer_bin: Option<String>,
#[schema(value_type = Option<String>, example = "501299")]
pub acquirer_ica: Option<String>,
#[schema(value_type = Option<f64>, example = "0.02")]
pub acquirer_fraud_rate: Option<f64>,
}
impl common_utils::events::ApiEventMetric for ProfileAcquirerUpdate {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/three_ds_decision_rule.rs | crates/api_models/src/three_ds_decision_rule.rs | use euclid::frontend::dir::enums::{
CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType,
};
use utoipa::ToSchema;
/// Represents the payment data used in the 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentData {
/// The amount of the payment in minor units (e.g., cents for USD).
#[schema(value_type = i64)]
pub amount: common_utils::types::MinorUnit,
/// The currency of the payment.
#[schema(value_type = Currency)]
pub currency: common_enums::Currency,
}
/// Represents metadata about the payment method used in the 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentMethodMetaData {
/// The card network (e.g., Visa, Mastercard) if the payment method is a card.
#[schema(value_type = CardNetwork)]
pub card_network: Option<common_enums::CardNetwork>,
}
/// Represents data about the customer's device used in the 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CustomerDeviceData {
/// The platform of the customer's device (e.g., Web, Android, iOS).
pub platform: Option<CustomerDevicePlatform>,
/// The type of the customer's device (e.g., Mobile, Tablet, Desktop).
pub device_type: Option<CustomerDeviceType>,
/// The display size of the customer's device.
pub display_size: Option<CustomerDeviceDisplaySize>,
}
/// Represents data about the issuer used in the 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct IssuerData {
/// The name of the issuer.
pub name: Option<String>,
/// The country of the issuer.
#[schema(value_type = Country)]
pub country: Option<common_enums::Country>,
}
/// Represents data about the acquirer used in the 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct AcquirerData {
/// The country of the acquirer.
#[schema(value_type = Country)]
pub country: Option<common_enums::Country>,
/// The fraud rate associated with the acquirer.
pub fraud_rate: Option<f64>,
}
/// Represents the request to execute a 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ThreeDsDecisionRuleExecuteRequest {
/// The ID of the routing algorithm to be executed.
#[schema(value_type = String)]
pub routing_id: common_utils::id_type::RoutingId,
/// Data related to the payment.
pub payment: PaymentData,
/// Optional metadata about the payment method.
pub payment_method: Option<PaymentMethodMetaData>,
/// Optional data about the customer's device.
pub customer_device: Option<CustomerDeviceData>,
/// Optional data about the issuer.
pub issuer: Option<IssuerData>,
/// Optional data about the acquirer.
pub acquirer: Option<AcquirerData>,
}
/// Represents the response from executing a 3DS decision rule.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ThreeDsDecisionRuleExecuteResponse {
/// The decision made by the 3DS decision rule engine.
#[schema(value_type = ThreeDSDecision)]
pub decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision,
}
impl common_utils::events::ApiEventMetric for ThreeDsDecisionRuleExecuteRequest {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::ThreeDsDecisionRule)
}
}
impl common_utils::events::ApiEventMetric for ThreeDsDecisionRuleExecuteResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::ThreeDsDecisionRule)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/process_tracker.rs | crates/api_models/src/process_tracker.rs | #[cfg(feature = "v2")]
pub mod revenue_recovery;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/ephemeral_key.rs | crates/api_models/src/ephemeral_key.rs | use common_utils::id_type;
#[cfg(feature = "v2")]
use masking::Secret;
use smithy::SmithyModel;
use utoipa::ToSchema;
#[cfg(feature = "v1")]
/// Information required to create an ephemeral key.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct EphemeralKeyCreateRequest {
/// Customer ID for which an ephemeral key must be created
#[schema(
min_length = 1,
max_length = 64,
value_type = String,
example = "cus_y3oqhf46pyzuxjbcn2giaqnb44"
)]
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ResourceId {
#[schema(value_type = String)]
Customer(id_type::GlobalCustomerId),
}
#[cfg(feature = "v2")]
/// Information required to create a client secret.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ClientSecretCreateRequest {
/// Resource ID for which a client secret must be created
pub resource_id: ResourceId,
}
#[cfg(feature = "v2")]
/// client_secret for the resource_id mentioned
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)]
pub struct ClientSecretResponse {
/// Client Secret id
#[schema(value_type = String, max_length = 32, min_length = 1)]
pub id: id_type::ClientSecretId,
/// resource_id to which this client secret belongs to
#[schema(value_type = ResourceId)]
pub resource_id: ResourceId,
/// time at which this client secret was created
pub created_at: time::PrimitiveDateTime,
/// time at which this client secret would expire
pub expires: time::PrimitiveDateTime,
#[schema(value_type=String)]
/// client secret
pub secret: Secret<String>,
}
#[cfg(feature = "v1")]
impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
#[cfg(feature = "v1")]
impl common_utils::events::ApiEventMetric for EphemeralKeyCreateResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for ClientSecretCreateRequest {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for ClientSecretResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
#[cfg(feature = "v1")]
/// ephemeral_key for the customer_id mentioned
#[derive(
Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct EphemeralKeyCreateResponse {
/// customer_id to which this ephemeral key belongs to
#[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
#[smithy(value_type = "String")]
pub customer_id: id_type::CustomerId,
/// time at which this ephemeral key was created
#[smithy(value_type = "i64")]
pub created_at: i64,
/// time at which this ephemeral key would expire
#[smithy(value_type = "i64")]
pub expires: i64,
/// ephemeral key
#[smithy(value_type = "String")]
pub secret: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/pm_auth.rs | crates/api_models/src/pm_auth.rs | use common_enums::{PaymentMethod, PaymentMethodType};
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
id_type, impl_api_event_type,
};
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct LinkTokenCreateRequest {
pub language: Option<String>, // optional language field to be passed
pub client_secret: Option<String>, // client secret to be passed in req body
pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch
pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector
pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LinkTokenCreateResponse {
pub link_token: String, // link_token received in response
pub connector: String, // pm_auth connector name in response
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ExchangeTokenCreateRequest {
pub public_token: String,
pub client_secret: Option<String>,
pub payment_id: id_type::PaymentId,
pub payment_method: PaymentMethod,
pub payment_method_type: PaymentMethodType,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct ExchangeTokenCreateResponse {
pub access_token: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodAuthConfig {
pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodAuthConnectorChoice {
pub payment_method: PaymentMethod,
pub payment_method_type: PaymentMethodType,
pub connector_name: String,
pub mca_id: id_type::MerchantConnectorAccountId,
}
impl_api_event_type!(
Miscellaneous,
(
LinkTokenCreateRequest,
LinkTokenCreateResponse,
ExchangeTokenCreateRequest,
ExchangeTokenCreateResponse
)
);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/organization.rs | crates/api_models/src/organization.rs | use common_enums::OrganizationType;
use common_utils::{id_type, pii};
use utoipa::ToSchema;
pub struct OrganizationNew {
pub org_id: id_type::OrganizationId,
pub org_type: OrganizationType,
pub org_name: Option<String>,
}
impl OrganizationNew {
pub fn new(org_type: OrganizationType, org_name: Option<String>) -> Self {
Self {
org_id: id_type::OrganizationId::default(),
org_type,
org_name,
}
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct OrganizationId {
pub organization_id: id_type::OrganizationId,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct OrganizationCreateRequest {
/// Name of the organization
pub organization_name: String,
/// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct OrganizationUpdateRequest {
/// Name of the organization
pub organization_name: Option<String>,
/// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Platform merchant id is unique distiguisher for special merchant in the platform org
#[schema(value_type = String)]
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct OrganizationResponse {
/// The unique identifier for the Organization
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
pub organization_id: id_type::OrganizationId,
/// Name of the Organization
pub organization_name: Option<String>,
/// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: time::PrimitiveDateTime,
pub created_at: time::PrimitiveDateTime,
/// Organization Type of the organization
#[schema(value_type = Option<OrganizationType>, example = "standard")]
pub organization_type: Option<OrganizationType>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct OrganizationResponse {
/// The unique identifier for the Organization
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
pub id: id_type::OrganizationId,
/// Name of the Organization
pub organization_name: Option<String>,
/// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: time::PrimitiveDateTime,
pub created_at: time::PrimitiveDateTime,
/// Organization Type of the organization
#[schema(value_type = Option<OrganizationType>, example = "standard")]
pub organization_type: Option<OrganizationType>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/open_router.rs | crates/api_models/src/open_router.rs | use std::{collections::HashMap, fmt::Debug};
use common_utils::{errors, id_type, types::MinorUnit};
pub use euclid::{
dssa::types::EuclidAnalysable,
frontend::{
ast,
dir::{DirKeyKind, EuclidDirFilter},
},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
enums::{Currency, PaymentMethod},
payment_methods,
};
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct OpenRouterDecideGatewayRequest {
pub payment_info: PaymentInfo,
#[schema(value_type = String)]
pub merchant_id: id_type::ProfileId,
pub eligible_gateway_list: Option<Vec<String>>,
pub ranking_algorithm: Option<RankingAlgorithm>,
pub elimination_enabled: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct DecideGatewayResponse {
pub decided_gateway: Option<String>,
pub gateway_priority_map: Option<serde_json::Value>,
pub filter_wise_gateways: Option<serde_json::Value>,
pub priority_logic_tag: Option<String>,
pub routing_approach: Option<String>,
pub gateway_before_evaluation: Option<String>,
pub priority_logic_output: Option<PriorityLogicOutput>,
pub reset_approach: Option<String>,
pub routing_dimension: Option<String>,
pub routing_dimension_level: Option<String>,
pub is_scheduled_outage: Option<bool>,
pub is_dynamic_mga_enabled: Option<bool>,
pub gateway_mga_id_map: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct PriorityLogicOutput {
pub is_enforcement: Option<bool>,
pub gws: Option<Vec<String>>,
pub priority_logic_tag: Option<String>,
pub gateway_reference_ids: Option<HashMap<String, String>>,
pub primary_logic: Option<PriorityLogicData>,
pub fallback_logic: Option<PriorityLogicData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct PriorityLogicData {
pub name: Option<String>,
pub status: Option<String>,
pub failure_reason: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RankingAlgorithm {
SrBasedRouting,
PlBasedRouting,
NtwBasedRouting,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInfo {
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
pub amount: MinorUnit,
pub currency: Currency,
// customerId: Option<ETCu::CustomerId>,
// preferredGateway: Option<ETG::Gateway>,
pub payment_type: String,
pub metadata: Option<String>,
// internalMetadata: Option<String>,
// isEmi: Option<bool>,
// emiBank: Option<String>,
// emiTenure: Option<i32>,
pub payment_method_type: String,
pub payment_method: PaymentMethod,
// paymentSource: Option<String>,
// authType: Option<ETCa::txn_card_info::AuthType>,
// cardIssuerBankName: Option<String>,
pub card_isin: Option<String>,
// cardType: Option<ETCa::card_type::CardType>,
// cardSwitchProvider: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct DecidedGateway {
pub gateway_priority_map: Option<HashMap<String, f64>>,
pub debit_routing_output: Option<DebitRoutingOutput>,
pub routing_approach: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct DebitRoutingOutput {
pub co_badged_card_networks_info: CoBadgedCardNetworks,
pub issuer_country: common_enums::CountryAlpha2,
pub is_regulated: bool,
pub regulated_name: Option<common_enums::RegulatedName>,
pub card_type: common_enums::CardType,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct CoBadgedCardNetworksInfo {
pub network: common_enums::CardNetwork,
pub saving_percentage: Option<f64>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct CoBadgedCardNetworks(pub Vec<CoBadgedCardNetworksInfo>);
impl CoBadgedCardNetworks {
pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> {
self.0.iter().map(|info| info.network.clone()).collect()
}
pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> {
self.0
.iter()
.find(|info| info.network.is_signature_network())
.map(|info| info.network.clone())
}
}
impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData {
fn from(output: &DebitRoutingOutput) -> Self {
Self {
co_badged_card_networks_info: output.co_badged_card_networks_info.clone(),
issuer_country_code: output.issuer_country,
is_regulated: output.is_regulated,
regulated_name: output.regulated_name.clone(),
}
}
}
impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(
(output, card_type): (payment_methods::CoBadgedCardData, String),
) -> Result<Self, Self::Error> {
let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| {
error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType"))
})?;
Ok(Self {
co_badged_card_networks_info: output.co_badged_card_networks_info.get_card_networks(),
issuer_country: output.issuer_country_code,
is_regulated: output.is_regulated,
regulated_name: output.regulated_name,
card_type: parsed_card_type,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoBadgedCardRequest {
pub merchant_category_code: common_enums::DecisionEngineMerchantCategoryCode,
pub acquirer_country: common_enums::CountryAlpha2,
pub co_badged_card_data: Option<DebitRoutingRequestData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DebitRoutingRequestData {
pub co_badged_card_networks_info: Vec<common_enums::CardNetwork>,
pub issuer_country: common_enums::CountryAlpha2,
pub is_regulated: bool,
pub regulated_name: Option<common_enums::RegulatedName>,
pub card_type: common_enums::CardType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ErrorResponse {
pub status: String,
pub error_code: String,
pub error_message: String,
pub priority_logic_tag: Option<String>,
pub filter_wise_gateways: Option<serde_json::Value>,
pub error_info: UnifiedError,
pub is_dynamic_mga_enabled: bool,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UnifiedError {
pub code: String,
pub user_message: String,
pub developer_message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdateScorePayload {
#[schema(value_type = String)]
pub merchant_id: id_type::ProfileId,
pub gateway: String,
pub status: TxnStatus,
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
}
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
pub struct UpdateScoreResponse {
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TxnStatus {
Started,
AuthenticationFailed,
JuspayDeclined,
PendingVbv,
VBVSuccessful,
Authorized,
AuthorizationFailed,
Charged,
Authorizing,
CODInitiated,
Voided,
VoidedPostCharge,
VoidInitiated,
Nop,
CaptureInitiated,
CaptureFailed,
VoidFailed,
AutoRefunded,
PartialCharged,
ToBeCharged,
Pending,
Failure,
Declined,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DecisionEngineConfigSetupRequest {
pub merchant_id: String,
pub config: DecisionEngineConfigVariant,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GetDecisionEngineConfigRequest {
pub merchant_id: String,
pub algorithm: DecisionEngineDynamicAlgorithmType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum DecisionEngineDynamicAlgorithmType {
SuccessRate,
Elimination,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type", content = "data")]
#[serde(rename_all = "camelCase")]
pub enum DecisionEngineConfigVariant {
SuccessRate(DecisionEngineSuccessRateData),
Elimination(DecisionEngineEliminationData),
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DecisionEngineSuccessRateData {
pub default_latency_threshold: Option<f64>,
pub default_bucket_size: Option<i32>,
pub default_hedging_percent: Option<f64>,
pub default_lower_reset_factor: Option<f64>,
pub default_upper_reset_factor: Option<f64>,
pub default_gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>,
pub sub_level_input_config: Option<Vec<DecisionEngineSRSubLevelInputConfig>>,
}
impl DecisionEngineSuccessRateData {
pub fn update(&mut self, new_config: Self) {
if let Some(threshold) = new_config.default_latency_threshold {
self.default_latency_threshold = Some(threshold);
}
if let Some(bucket_size) = new_config.default_bucket_size {
self.default_bucket_size = Some(bucket_size);
}
if let Some(hedging_percent) = new_config.default_hedging_percent {
self.default_hedging_percent = Some(hedging_percent);
}
if let Some(lower_reset_factor) = new_config.default_lower_reset_factor {
self.default_lower_reset_factor = Some(lower_reset_factor);
}
if let Some(upper_reset_factor) = new_config.default_upper_reset_factor {
self.default_upper_reset_factor = Some(upper_reset_factor);
}
if let Some(gateway_extra_score) = new_config.default_gateway_extra_score {
self.default_gateway_extra_score
.as_mut()
.map(|score| score.extend(gateway_extra_score));
}
if let Some(sub_level_input_config) = new_config.sub_level_input_config {
self.sub_level_input_config.as_mut().map(|config| {
config.extend(sub_level_input_config);
});
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DecisionEngineSRSubLevelInputConfig {
pub payment_method_type: Option<String>,
pub payment_method: Option<String>,
pub latency_threshold: Option<f64>,
pub bucket_size: Option<i32>,
pub hedging_percent: Option<f64>,
pub lower_reset_factor: Option<f64>,
pub upper_reset_factor: Option<f64>,
pub gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>,
}
impl DecisionEngineSRSubLevelInputConfig {
pub fn update(&mut self, new_config: Self) {
if let Some(payment_method_type) = new_config.payment_method_type {
self.payment_method_type = Some(payment_method_type);
}
if let Some(payment_method) = new_config.payment_method {
self.payment_method = Some(payment_method);
}
if let Some(latency_threshold) = new_config.latency_threshold {
self.latency_threshold = Some(latency_threshold);
}
if let Some(bucket_size) = new_config.bucket_size {
self.bucket_size = Some(bucket_size);
}
if let Some(hedging_percent) = new_config.hedging_percent {
self.hedging_percent = Some(hedging_percent);
}
if let Some(lower_reset_factor) = new_config.lower_reset_factor {
self.lower_reset_factor = Some(lower_reset_factor);
}
if let Some(upper_reset_factor) = new_config.upper_reset_factor {
self.upper_reset_factor = Some(upper_reset_factor);
}
if let Some(gateway_extra_score) = new_config.gateway_extra_score {
self.gateway_extra_score
.as_mut()
.map(|score| score.extend(gateway_extra_score));
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DecisionEngineGatewayWiseExtraScore {
pub gateway_name: String,
pub gateway_sigma_factor: f64,
}
impl DecisionEngineGatewayWiseExtraScore {
pub fn update(&mut self, new_config: Self) {
self.gateway_name = new_config.gateway_name;
self.gateway_sigma_factor = new_config.gateway_sigma_factor;
}
}
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DecisionEngineEliminationData {
pub threshold: f64,
}
impl DecisionEngineEliminationData {
pub fn update(&mut self, new_config: Self) {
self.threshold = new_config.threshold;
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MerchantAccount {
pub merchant_id: String,
pub gateway_success_rate_based_decider_input: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FetchRoutingConfig {
pub merchant_id: String,
pub algorithm: AlgorithmType,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "camelCase")]
pub enum AlgorithmType {
SuccessRate,
Elimination,
DebitRouting,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/cards_info.rs | crates/api_models/src/cards_info.rs | use std::fmt::Debug;
use common_utils::events::ApiEventMetric;
use utoipa::ToSchema;
use crate::enums;
#[derive(serde::Deserialize, ToSchema)]
pub struct CardsInfoRequestParams {
#[schema(example = "pay_OSERgeV9qAy7tlK7aKpc_secret_TuDUoh11Msxh12sXn3Yp")]
pub client_secret: Option<String>,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CardsInfoRequest {
pub client_secret: Option<String>,
pub card_iin: String,
}
#[derive(serde::Serialize, Debug, ToSchema)]
pub struct CardInfoResponse {
#[schema(example = "374431")]
pub card_iin: String,
#[schema(example = "AMEX")]
pub card_issuer: Option<String>,
#[schema(example = "AMEX")]
pub card_network: Option<String>,
#[schema(example = "CREDIT")]
pub card_type: Option<String>,
#[schema(example = "CLASSIC")]
pub card_sub_type: Option<String>,
#[schema(example = "INDIA")]
pub card_issuing_country: Option<String>,
}
#[derive(serde::Serialize, Debug, ToSchema)]
pub struct CardInfoMigrateResponseRecord {
pub card_iin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<String>,
pub card_type: Option<String>,
pub card_sub_type: Option<String>,
pub card_issuing_country: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct CardInfoCreateRequest {
pub card_iin: String,
pub card_issuer: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_type: Option<String>,
pub card_subtype: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code_id: Option<String>,
pub bank_code: Option<String>,
pub country_code: Option<String>,
pub last_updated_provider: Option<String>,
}
impl ApiEventMetric for CardInfoCreateRequest {}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct CardInfoUpdateRequest {
pub card_iin: String,
pub card_issuer: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_type: Option<String>,
pub card_subtype: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code_id: Option<String>,
pub bank_code: Option<String>,
pub country_code: Option<String>,
pub last_updated_provider: Option<String>,
pub line_number: Option<i64>,
}
impl ApiEventMetric for CardInfoUpdateRequest {}
#[derive(Debug, Default, serde::Serialize)]
pub enum CardInfoMigrationStatus {
Success,
#[default]
Failed,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct CardInfoMigrationResponse {
pub line_number: Option<i64>,
pub card_iin: String,
pub card_issuer: Option<String>,
pub card_network: Option<String>,
pub card_type: Option<String>,
pub card_sub_type: Option<String>,
pub card_issuing_country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub migration_error: Option<String>,
pub migration_status: CardInfoMigrationStatus,
}
impl ApiEventMetric for CardInfoMigrationResponse {}
type CardInfoMigrationResponseType = (
Result<CardInfoMigrateResponseRecord, String>,
CardInfoUpdateRequest,
);
impl From<CardInfoMigrationResponseType> for CardInfoMigrationResponse {
fn from((response, record): CardInfoMigrationResponseType) -> Self {
match response {
Ok(res) => Self {
card_iin: record.card_iin,
line_number: record.line_number,
card_issuer: res.card_issuer,
card_network: res.card_network,
card_type: res.card_type,
card_sub_type: res.card_sub_type,
card_issuing_country: res.card_issuing_country,
migration_status: CardInfoMigrationStatus::Success,
migration_error: None,
},
Err(e) => Self {
card_iin: record.card_iin,
migration_status: CardInfoMigrationStatus::Failed,
migration_error: Some(e),
line_number: record.line_number,
..Self::default()
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/enums.rs | crates/api_models/src/enums.rs | use std::str::FromStr;
pub use common_enums::*;
pub use euclid::enums::RoutableConnectors;
use smithy::SmithyModel;
use utoipa::ToSchema;
pub use super::connector_enums::Connector;
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingAlgorithm {
RoundRobin,
MaxConversion,
MinCost,
Custom,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutConnectors {
Adyen,
Adyenplatform,
Cybersource,
Ebanx,
Gigadat,
Loonio,
Nomupay,
Nuvei,
Payone,
Paypal,
Stripe,
Wise,
Worldpay,
Worldpayxml,
}
#[cfg(feature = "v2")]
/// Whether active attempt is to be set/unset
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub enum UpdateActiveAttempt {
/// Request to set the active attempt id
#[schema(value_type = Option<String>)]
Set(common_utils::id_type::GlobalAttemptId),
/// To unset the active attempt id
Unset,
}
#[cfg(feature = "payouts")]
impl From<PayoutConnectors> for RoutableConnectors {
fn from(value: PayoutConnectors) -> Self {
match value {
PayoutConnectors::Adyen => Self::Adyen,
PayoutConnectors::Adyenplatform => Self::Adyenplatform,
PayoutConnectors::Cybersource => Self::Cybersource,
PayoutConnectors::Ebanx => Self::Ebanx,
PayoutConnectors::Gigadat => Self::Gigadat,
PayoutConnectors::Loonio => Self::Loonio,
PayoutConnectors::Nomupay => Self::Nomupay,
PayoutConnectors::Nuvei => Self::Nuvei,
PayoutConnectors::Payone => Self::Payone,
PayoutConnectors::Paypal => Self::Paypal,
PayoutConnectors::Stripe => Self::Stripe,
PayoutConnectors::Wise => Self::Wise,
PayoutConnectors::Worldpay => Self::Worldpay,
PayoutConnectors::Worldpayxml => Self::Worldpayxml,
}
}
}
#[cfg(feature = "payouts")]
impl From<PayoutConnectors> for Connector {
fn from(value: PayoutConnectors) -> Self {
match value {
PayoutConnectors::Adyen => Self::Adyen,
PayoutConnectors::Adyenplatform => Self::Adyenplatform,
PayoutConnectors::Cybersource => Self::Cybersource,
PayoutConnectors::Ebanx => Self::Ebanx,
PayoutConnectors::Gigadat => Self::Gigadat,
PayoutConnectors::Loonio => Self::Loonio,
PayoutConnectors::Nomupay => Self::Nomupay,
PayoutConnectors::Nuvei => Self::Nuvei,
PayoutConnectors::Payone => Self::Payone,
PayoutConnectors::Paypal => Self::Paypal,
PayoutConnectors::Stripe => Self::Stripe,
PayoutConnectors::Wise => Self::Wise,
PayoutConnectors::Worldpay => Self::Worldpay,
PayoutConnectors::Worldpayxml => Self::Worldpayxml,
}
}
}
#[cfg(feature = "payouts")]
impl TryFrom<Connector> for PayoutConnectors {
type Error = String;
fn try_from(value: Connector) -> Result<Self, Self::Error> {
match value {
Connector::Adyen => Ok(Self::Adyen),
Connector::Adyenplatform => Ok(Self::Adyenplatform),
Connector::Cybersource => Ok(Self::Cybersource),
Connector::Ebanx => Ok(Self::Ebanx),
Connector::Gigadat => Ok(Self::Gigadat),
Connector::Loonio => Ok(Self::Loonio),
Connector::Nuvei => Ok(Self::Nuvei),
Connector::Nomupay => Ok(Self::Nomupay),
Connector::Payone => Ok(Self::Payone),
Connector::Paypal => Ok(Self::Paypal),
Connector::Stripe => Ok(Self::Stripe),
Connector::Wise => Ok(Self::Wise),
Connector::Worldpay => Ok(Self::Worldpay),
Connector::Worldpayxml => Ok(Self::Worldpayxml),
_ => Err(format!("Invalid payout connector {value}")),
}
}
}
#[cfg(feature = "frm")]
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FrmConnectors {
/// Signifyd Risk Manager. Official docs: https://docs.signifyd.com/
Signifyd,
Riskified,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TaxConnectors {
Taxjar,
}
#[derive(Clone, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BillingConnectors {
Chargebee,
Recurly,
Stripebilling,
Custombilling,
#[cfg(feature = "dummy_connector")]
DummyBillingConnector,
}
#[derive(Clone, Copy, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum VaultConnectors {
Vgs,
HyperswitchVault,
Tokenex,
}
impl From<VaultConnectors> for Connector {
fn from(value: VaultConnectors) -> Self {
match value {
VaultConnectors::Vgs => Self::Vgs,
VaultConnectors::HyperswitchVault => Self::HyperswitchVault,
VaultConnectors::Tokenex => Self::Tokenex,
}
}
}
#[derive(
Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum FrmAction {
CancelTxn,
AutoRefund,
ManualReview,
}
#[derive(
Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum FrmPreferredFlowTypes {
Pre,
Post,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct UnresolvedResponseReason {
pub code: String,
/// A message to merchant to give hint on next action he/she should do to resolve
pub message: String,
}
/// Possible field type of required fields in payment_method_data
#[derive(
Clone,
Debug,
Eq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FieldType {
UserCardNumber,
UserGiftCardNumber,
UserCardExpiryMonth,
UserCardExpiryYear,
UserCardCvc,
UserGiftCardPin,
UserCardNetwork,
UserFullName,
UserEmailAddress,
UserPhoneNumber,
UserPhoneNumberCountryCode, //phone number's country code
UserCountry { options: Vec<String> }, //for country inside payment method data ex- bank redirect
UserCurrency { options: Vec<String> },
UserCryptoCurrencyNetwork, //for crypto network associated with the cryptopcurrency
UserBillingName,
UserAddressLine1,
UserAddressLine2,
UserAddressCity,
UserAddressPincode,
UserAddressState,
UserAddressCountry { options: Vec<String> },
UserShippingName,
UserShippingAddressLine1,
UserShippingAddressLine2,
UserShippingAddressCity,
UserShippingAddressPincode,
UserShippingAddressState,
UserShippingAddressCountry { options: Vec<String> },
UserSocialSecurityNumber,
UserBlikCode,
UserBank,
UserBankOptions { options: Vec<String> },
UserBankAccountNumber,
UserSourceBankAccountId,
UserDestinationBankAccountId,
Text,
DropDown { options: Vec<String> },
UserDateOfBirth,
UserVpaId,
LanguagePreference { options: Vec<String> },
UserPixKey,
UserCpf,
UserCnpj,
UserIban,
UserBsbNumber,
UserBankSortCode,
UserBankRoutingNumber,
UserBankType { options: Vec<String> },
UserBankAccountHolderName,
UserMsisdn,
UserClientIdentifier,
OrderDetailsProductName,
}
impl FieldType {
pub fn get_billing_variants() -> Vec<Self> {
vec![
Self::UserBillingName,
Self::UserAddressLine1,
Self::UserAddressLine2,
Self::UserAddressCity,
Self::UserAddressPincode,
Self::UserAddressState,
Self::UserAddressCountry { options: vec![] },
]
}
pub fn get_shipping_variants() -> Vec<Self> {
vec![
Self::UserShippingName,
Self::UserShippingAddressLine1,
Self::UserShippingAddressLine2,
Self::UserShippingAddressCity,
Self::UserShippingAddressPincode,
Self::UserShippingAddressState,
Self::UserShippingAddressCountry { options: vec![] },
]
}
}
/// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing
impl PartialEq for FieldType {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::UserCardNumber, Self::UserCardNumber) => true,
(Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true,
(Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true,
(Self::UserCardCvc, Self::UserCardCvc) => true,
(Self::UserFullName, Self::UserFullName) => true,
(Self::UserEmailAddress, Self::UserEmailAddress) => true,
(Self::UserPhoneNumber, Self::UserPhoneNumber) => true,
(Self::UserPhoneNumberCountryCode, Self::UserPhoneNumberCountryCode) => true,
(
Self::UserCountry {
options: options_self,
},
Self::UserCountry {
options: options_other,
},
) => options_self.eq(options_other),
(
Self::UserCurrency {
options: options_self,
},
Self::UserCurrency {
options: options_other,
},
) => options_self.eq(options_other),
(Self::UserCryptoCurrencyNetwork, Self::UserCryptoCurrencyNetwork) => true,
(Self::UserBillingName, Self::UserBillingName) => true,
(Self::UserAddressLine1, Self::UserAddressLine1) => true,
(Self::UserAddressLine2, Self::UserAddressLine2) => true,
(Self::UserAddressCity, Self::UserAddressCity) => true,
(Self::UserAddressPincode, Self::UserAddressPincode) => true,
(Self::UserAddressState, Self::UserAddressState) => true,
(Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true,
(Self::UserShippingName, Self::UserShippingName) => true,
(Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true,
(Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true,
(Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true,
(Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true,
(Self::UserShippingAddressState, Self::UserShippingAddressState) => true,
(Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => {
true
}
(Self::UserBlikCode, Self::UserBlikCode) => true,
(Self::UserBank, Self::UserBank) => true,
(Self::Text, Self::Text) => true,
(
Self::DropDown {
options: options_self,
},
Self::DropDown {
options: options_other,
},
) => options_self.eq(options_other),
(Self::UserDateOfBirth, Self::UserDateOfBirth) => true,
(Self::UserVpaId, Self::UserVpaId) => true,
(Self::UserPixKey, Self::UserPixKey) => true,
(Self::UserCpf, Self::UserCpf) => true,
(Self::UserCnpj, Self::UserCnpj) => true,
(Self::LanguagePreference { .. }, Self::LanguagePreference { .. }) => true,
(Self::UserMsisdn, Self::UserMsisdn) => true,
(Self::UserClientIdentifier, Self::UserClientIdentifier) => true,
(Self::OrderDetailsProductName, Self::OrderDetailsProductName) => true,
_unused => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_partialeq_for_field_type() {
let user_address_country_is_us = FieldType::UserAddressCountry {
options: vec!["US".to_string()],
};
let user_address_country_is_all = FieldType::UserAddressCountry {
options: vec!["ALL".to_string()],
};
assert!(user_address_country_is_us.eq(&user_address_country_is_all))
}
}
/// Denotes the retry action
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
Clone,
PartialEq,
Eq,
ToSchema,
SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum RetryAction {
/// Manual retry through request is being deprecated, now it is available through profile
ManualRetry,
/// Denotes that the payment is requeued
Requeue,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PmAuthConnectors {
Plaid,
}
pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> {
PmAuthConnectors::from_str(connector_name).ok()
}
pub fn convert_authentication_connector(connector_name: &str) -> Option<AuthenticationConnectors> {
AuthenticationConnectors::from_str(connector_name).ok()
}
pub fn convert_tax_connector(connector_name: &str) -> Option<TaxConnectors> {
TaxConnectors::from_str(connector_name).ok()
}
pub fn convert_billing_connector(connector_name: &str) -> Option<BillingConnectors> {
BillingConnectors::from_str(connector_name).ok()
}
#[cfg(feature = "frm")]
pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> {
FrmConnectors::from_str(connector_name).ok()
}
pub fn convert_vault_connector(connector_name: &str) -> Option<VaultConnectors> {
VaultConnectors::from_str(connector_name).ok()
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)]
pub enum ReconPermissionScope {
#[serde(rename = "R")]
Read = 0,
#[serde(rename = "RW")]
Write = 1,
}
impl From<PermissionScope> for ReconPermissionScope {
fn from(scope: PermissionScope) -> Self {
match scope {
PermissionScope::Read => Self::Read,
PermissionScope::Write => Self::Write,
}
}
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
ToSchema,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum TokenStatus {
/// Indicates that the token is active and can be used for payments
Active,
/// Indicates that the token is inactive and can't be used for payments
Inactive,
/// Indicates that the token is suspended from network's end for some reason and can't be used for payments until it is re-activated
Suspended,
/// Indicates that the token is expired and can't be used for payments
Expired,
/// Indicates that the token is deleted and further can't be used for payments
Deleted,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/conditional_configs.rs | crates/api_models/src/conditional_configs.rs | use common_utils::events;
use euclid::frontend::ast::Program;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecisionManagerRecord {
pub name: String,
pub program: Program<common_types::payments::ConditionalConfigs>,
pub created_at: i64,
pub modified_at: i64,
}
impl events::ApiEventMetric for DecisionManagerRecord {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConditionalConfigReq {
pub name: Option<String>,
pub algorithm: Option<Program<common_types::payments::ConditionalConfigs>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecisionManagerRequest {
pub name: Option<String>,
pub program: Option<Program<common_types::payments::ConditionalConfigs>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum DecisionManager {
DecisionManagerv0(ConditionalConfigReq),
DecisionManagerv1(DecisionManagerRequest),
}
impl events::ApiEventMetric for DecisionManager {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
pub type DecisionManagerResponse = DecisionManagerRecord;
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecisionManagerRequest {
pub name: String,
pub program: Program<common_types::payments::ConditionalConfigs>,
}
#[cfg(feature = "v2")]
impl events::ApiEventMetric for DecisionManagerRequest {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/apple_pay_certificates_migration.rs | crates/api_models/src/apple_pay_certificates_migration.rs | #[derive(Debug, Clone, serde::Serialize)]
pub struct ApplePayCertificatesMigrationResponse {
pub migration_successful: Vec<common_utils::id_type::MerchantId>,
pub migration_failed: Vec<common_utils::id_type::MerchantId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct ApplePayCertificatesMigrationRequest {
pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
}
impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/subscription.rs | crates/api_models/src/subscription.rs | use common_enums::{InvoiceStatus, SubscriptionStatus};
use common_types::payments::CustomerAcceptance;
use common_utils::{
errors::ValidationError,
events::ApiEventMetric,
fp_utils,
id_type::{
CustomerId, InvoiceId, MerchantConnectorAccountId, MerchantId, PaymentId, ProfileId,
SubscriptionId,
},
types::{MinorUnit, Url},
};
use masking::Secret;
use utoipa::ToSchema;
use crate::{
enums::{
AuthenticationType, CaptureMethod, Currency, FutureUsage, IntentStatus, PaymentExperience,
PaymentMethod, PaymentMethodType, PaymentType,
},
mandates::RecurringDetails,
payments::{Address, NextActionData, PaymentMethodDataRequest},
};
/// Request payload for creating a subscription.
///
/// This struct captures details required to create a subscription,
/// including plan, profile, merchant connector, and optional customer info.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateSubscriptionRequest {
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
/// Identifier for the subscription plan.
pub plan_id: Option<String>,
/// Optional coupon code applied to the subscription.
pub coupon_code: Option<String>,
/// customer ID associated with this subscription.
pub customer_id: CustomerId,
/// payment details for the subscription.
pub payment_details: CreateSubscriptionPaymentDetails,
/// billing address for the subscription.
pub billing: Option<Address>,
/// shipping address for the subscription.
pub shipping: Option<Address>,
}
/// Response payload returned after successfully creating a subscription.
///
/// Includes details such as subscription ID, status, plan, merchant, and customer info.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct SubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Identifier for the associated subscription plan.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
#[schema(value_type = Option<String>)]
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: Option<Secret<String>>,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Optional coupon code applied to this subscription.
pub coupon_code: Option<String>,
/// Optional customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Payment details for the invoice.
pub payment: Option<PaymentResponseData>,
/// Invoice Details for the subscription.
pub invoice: Option<Invoice>,
}
impl SubscriptionResponse {
/// Creates a new [`CreateSubscriptionResponse`] with the given identifiers.
///
/// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`.
#[allow(clippy::too_many_arguments)]
pub fn new(
id: SubscriptionId,
merchant_reference_id: Option<String>,
status: SubscriptionStatus,
plan_id: Option<String>,
item_price_id: Option<String>,
profile_id: ProfileId,
merchant_id: MerchantId,
client_secret: Option<Secret<String>>,
customer_id: CustomerId,
payment: Option<PaymentResponseData>,
invoice: Option<Invoice>,
) -> Self {
Self {
id,
merchant_reference_id,
status,
plan_id,
item_price_id,
profile_id,
client_secret,
merchant_id,
coupon_code: None,
customer_id,
payment,
invoice,
}
}
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct GetSubscriptionItemsResponse {
pub item_id: String,
pub name: String,
pub description: Option<String>,
pub price_id: Vec<SubscriptionItemPrices>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct SubscriptionItemPrices {
pub price_id: String,
// This can be plan_id or addon_id
pub item_id: Option<String>,
pub amount: MinorUnit,
pub currency: Currency,
pub interval: PeriodUnit,
pub interval_count: i64,
pub trial_period: Option<i64>,
pub trial_period_unit: Option<PeriodUnit>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub enum PeriodUnit {
Day,
Week,
Month,
Year,
}
/// For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ClientSecret(String);
impl ClientSecret {
pub fn new(secret: String) -> Self {
Self(secret)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn as_string(&self) -> &String {
&self.0
}
}
#[derive(serde::Deserialize, serde::Serialize, Debug, ToSchema)]
pub struct GetSubscriptionItemsQuery {
#[schema(value_type = Option<String>)]
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: Option<ClientSecret>,
pub limit: Option<u32>,
pub offset: Option<u32>,
pub item_type: SubscriptionItemType,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum SubscriptionItemType {
/// This is a subscription plan
Plan,
/// This is a subscription addon
Addon,
}
impl ApiEventMetric for SubscriptionResponse {}
impl ApiEventMetric for CreateSubscriptionRequest {}
impl ApiEventMetric for GetSubscriptionItemsQuery {}
impl ApiEventMetric for GetSubscriptionItemsResponse {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ConfirmSubscriptionPaymentDetails {
pub shipping: Option<Address>,
pub billing: Option<Address>,
pub payment_method: PaymentMethod,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub customer_acceptance: Option<CustomerAcceptance>,
pub payment_type: Option<PaymentType>,
#[schema(value_type = Option<String>, example = "token_sxJdmpUnpNsJk5VWzcjl")]
pub payment_token: Option<Secret<String>>,
}
impl ConfirmSubscriptionPaymentDetails {
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
fp_utils::when(
self.payment_method_data.is_none() && self.payment_token.is_none(),
|| {
Err(ValidationError::MissingRequiredField {
field_name: String::from(
"Either payment_method_data or payment_token must be present",
),
}
.into())
},
)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateSubscriptionPaymentDetails {
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = String)]
pub return_url: Url,
pub setup_future_usage: Option<FutureUsage>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
pub payment_type: Option<PaymentType>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentDetails {
pub payment_method: Option<PaymentMethod>,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub setup_future_usage: Option<FutureUsage>,
pub customer_acceptance: Option<CustomerAcceptance>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
pub payment_type: Option<PaymentType>,
#[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: Option<Secret<String>>,
}
impl PaymentDetails {
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
fp_utils::when(
self.payment_method_data.is_none() && self.payment_method_id.is_none(),
|| {
Err(ValidationError::MissingRequiredField {
field_name: String::from(
"Either payment_method_data or payment_method_id must be present",
),
}
.into())
},
)
}
}
// Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization
// Eg: Amount will be serialized as { amount: {Value: 100 }}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CreatePaymentsRequestData {
pub amount: MinorUnit,
pub currency: Currency,
pub customer_id: Option<CustomerId>,
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub profile_id: Option<ProfileId>,
pub setup_future_usage: Option<FutureUsage>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct ConfirmPaymentsRequestData {
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub profile_id: Option<ProfileId>,
pub payment_method: PaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<PaymentMethodType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub customer_acceptance: Option<CustomerAcceptance>,
pub payment_type: Option<PaymentType>,
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>, example = "token_sxJdmpUnpNsJk5VWzcjl")]
pub payment_token: Option<Secret<String>>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CreateAndConfirmPaymentsRequestData {
pub amount: MinorUnit,
pub currency: Currency,
pub customer_id: Option<CustomerId>,
pub confirm: bool,
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub profile_id: Option<ProfileId>,
pub setup_future_usage: Option<FutureUsage>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub capture_method: Option<CaptureMethod>,
pub authentication_type: Option<AuthenticationType>,
pub payment_method: Option<PaymentMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<PaymentMethodType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<PaymentMethodDataRequest>,
pub customer_acceptance: Option<CustomerAcceptance>,
pub payment_type: Option<PaymentType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recurring_details: Option<RecurringDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
pub off_session: Option<bool>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentResponseData {
pub payment_id: PaymentId,
pub status: IntentStatus,
pub amount: MinorUnit,
pub currency: Currency,
pub profile_id: Option<ProfileId>,
pub connector: Option<String>,
/// Identifier for Payment Method
#[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: Option<Secret<String>>,
/// The url to which user must be redirected to after completion of the purchase
#[schema(value_type = Option<String>)]
pub return_url: Option<Url>,
pub next_action: Option<NextActionData>,
pub payment_experience: Option<PaymentExperience>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub payment_method_type: Option<PaymentMethodType>,
#[schema(value_type = Option<String>)]
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: Option<Secret<String>>,
pub billing: Option<Address>,
pub shipping: Option<Address>,
pub payment_type: Option<PaymentType>,
#[schema(value_type = Option<String>, example = "token_sxJdmpUnpNsJk5VWzcjl")]
pub payment_token: Option<Secret<String>>,
}
impl PaymentResponseData {
pub fn get_billing_address(&self) -> Option<Address> {
self.billing.clone()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateMitPaymentRequestData {
pub amount: MinorUnit,
pub currency: Currency,
pub confirm: bool,
pub customer_id: Option<CustomerId>,
pub recurring_details: Option<RecurringDetails>,
pub off_session: Option<bool>,
pub profile_id: Option<ProfileId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ConfirmSubscriptionRequest {
#[schema(value_type = Option<String>)]
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: Option<ClientSecret>,
/// Payment details for the invoice.
pub payment_details: ConfirmSubscriptionPaymentDetails,
}
impl ConfirmSubscriptionRequest {
pub fn get_billing_address(&self) -> Option<Address> {
self.payment_details
.payment_method_data
.as_ref()
.and_then(|data| data.billing.clone())
.or(self.payment_details.billing.clone())
}
// Perform validation on ConfirmSubscriptionRequest fields
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
self.payment_details.validate()
}
}
impl ApiEventMetric for ConfirmSubscriptionRequest {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateAndConfirmSubscriptionRequest {
/// Identifier for the associated plan_id.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
/// Identifier for the coupon code for the subscription.
pub coupon_code: Option<String>,
/// Identifier for customer.
pub customer_id: CustomerId,
/// Billing address for the subscription.
pub billing: Option<Address>,
/// Shipping address for the subscription.
pub shipping: Option<Address>,
/// Payment details for the invoice.
pub payment_details: PaymentDetails,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
}
impl CreateAndConfirmSubscriptionRequest {
pub fn get_billing_address(&self) -> Option<Address> {
self.payment_details
.payment_method_data
.as_ref()
.and_then(|data| data.billing.clone())
.or(self.billing.clone())
}
pub fn validate(&self) -> Result<(), error_stack::Report<ValidationError>> {
self.payment_details.validate()
}
}
impl ApiEventMetric for CreateAndConfirmSubscriptionRequest {}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct ConfirmSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Identifier for the associated subscription plan.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: Option<String>,
/// Optional coupon code applied to this subscription.
pub coupon: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Payment details for the invoice.
pub payment: Option<PaymentResponseData>,
/// Customer ID associated with this subscription.
pub customer_id: Option<CustomerId>,
/// Invoice Details for the subscription.
pub invoice: Option<Invoice>,
/// Billing Processor subscription ID.
pub billing_processor_subscription_id: Option<String>,
}
impl ConfirmSubscriptionResponse {
pub fn get_optional_invoice_id(&self) -> Option<InvoiceId> {
self.invoice.as_ref().map(|invoice| invoice.id.to_owned())
}
pub fn get_optional_payment_id(&self) -> Option<PaymentId> {
self.payment
.as_ref()
.map(|payment| payment.payment_id.to_owned())
}
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct Invoice {
/// Unique identifier for the invoice.
pub id: InvoiceId,
/// Unique identifier for the subscription.
pub subscription_id: SubscriptionId,
/// Identifier for the merchant.
pub merchant_id: MerchantId,
/// Identifier for the profile.
pub profile_id: ProfileId,
/// Identifier for the merchant connector account.
pub merchant_connector_id: MerchantConnectorAccountId,
/// Identifier for the Payment.
pub payment_intent_id: Option<PaymentId>,
/// Identifier for Payment Method
#[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")]
pub payment_method_id: Option<String>,
/// Identifier for the Customer.
pub customer_id: CustomerId,
/// Invoice amount.
pub amount: MinorUnit,
/// Currency for the invoice payment.
pub currency: Currency,
/// Status of the invoice.
pub status: InvoiceStatus,
/// billing processor invoice id
pub billing_processor_invoice_id: Option<String>,
}
impl ApiEventMetric for ConfirmSubscriptionResponse {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct UpdateSubscriptionRequest {
/// Identifier for the associated plan_id.
pub plan_id: String,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
}
impl ApiEventMetric for UpdateSubscriptionRequest {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct EstimateSubscriptionQuery {
/// Identifier for the associated subscription plan.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: String,
/// Identifier for the coupon code for the subscription.
pub coupon_code: Option<String>,
}
impl ApiEventMetric for EstimateSubscriptionQuery {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ListSubscriptionQuery {
/// Number of records to return.
pub limit: Option<i64>,
/// Offset for pagination.
pub offset: Option<i64>,
}
impl ApiEventMetric for ListSubscriptionQuery {}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct EstimateSubscriptionResponse {
/// Estimated amount to be charged for the invoice.
pub amount: MinorUnit,
/// Currency for the amount.
pub currency: Currency,
/// Identifier for the associated plan_id.
pub plan_id: Option<String>,
/// Identifier for the associated item_price_id for the subscription.
pub item_price_id: Option<String>,
/// Identifier for the coupon code for the subscription.
pub coupon_code: Option<String>,
/// Identifier for customer.
pub customer_id: Option<CustomerId>,
pub line_items: Vec<SubscriptionLineItem>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct SubscriptionLineItem {
/// Unique identifier for the line item.
pub item_id: String,
/// Type of the line item.
pub item_type: String,
/// Description of the line item.
pub description: String,
/// Amount for the line item.
pub amount: MinorUnit,
/// Currency for the line item
pub currency: Currency,
/// Quantity of the line item.
pub quantity: i64,
}
impl ApiEventMetric for EstimateSubscriptionResponse {}
/// Request payload for pausing a subscription.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PauseSubscriptionRequest {
/// List of options to pause the subscription.
pub pause_option: Option<PauseOption>,
/// Optional date when the subscription should be paused (if not provided, pauses immediately)
#[schema(value_type = Option<String>)]
pub pause_at: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PauseOption {
/// Pause immediately
Immediately,
/// Pause at the end of current term
EndOfTerm,
/// Pause on a specific date,
SpecificDate,
}
/// Response payload returned after successfully pausing a subscription.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct PauseSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Date when the subscription was paused
#[schema(value_type = Option<String>)]
pub paused_at: Option<time::PrimitiveDateTime>,
}
/// Request payload for resuming a subscription.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ResumeSubscriptionRequest {
/// Options to resume the subscription.
pub resume_option: Option<ResumeOption>,
/// Optional date when the subscription should be resumed (if not provided, resumes immediately)
#[schema(value_type = Option<String>)]
pub resume_date: Option<time::PrimitiveDateTime>,
/// Applicable when charges get added during this operation and resume_option is set as 'immediately'. Allows to raise invoice immediately or add them to unbilled charges.
pub charges_handling: Option<ChargesHandling>,
/// Applicable when the subscription has past due invoices and resume_option is set as 'immediately'. Allows to collect past due invoices or retain them as unpaid. If 'schedule_payment_collection' option is chosen in this field, remaining refundable credits and excess payments are applied
pub unpaid_invoices_handling: Option<UnpaidInvoicesHandling>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ResumeOption {
/// Resume immediately
Immediately,
/// Resume on a specific date,
SpecificDate,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ChargesHandling {
InvoiceImmediately,
AddToUnbilledCharges,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum UnpaidInvoicesHandling {
NoAction,
SchedulePaymentCollection,
}
/// Response payload returned after successfully resuming a subscription.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct ResumeSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Date when the subscription was resumed
#[schema(value_type = Option<String>)]
pub next_billing_at: Option<time::PrimitiveDateTime>,
}
/// Request payload for cancelling a subscription.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CancelSubscriptionRequest {
/// Optional reason for cancelling the subscription
pub cancel_option: Option<CancelOption>,
/// Optional date when the subscription should be cancelled (if not provided, cancels immediately)
#[schema(value_type = Option<String>)]
pub cancel_at: Option<time::PrimitiveDateTime>,
/// Specifies how to handle unbilled charges when canceling immediately
pub unbilled_charges_option: Option<UnbilledChargesOption>,
/// Specifies how to handle credits for current term charges when canceling immediately
pub credit_option_for_current_term_charges: Option<CreditOption>,
/// Specifies how to handle past due invoices when canceling immediately
pub account_receivables_handling: Option<AccountReceivablesHandling>,
/// Specifies how to handle refundable credits when canceling immediately
pub refundable_credits_handling: Option<RefundableCreditsHandling>,
/// Reason code for canceling the subscription
pub cancel_reason_code: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CancelOption {
Immediately,
EndOfTerm,
SpecificDate,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum RefundableCreditsHandling {
NoAction,
ScheduleRefund,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum AccountReceivablesHandling {
NoAction,
SchedulePaymentCollection,
WriteOff,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CreditOption {
None,
Prorate,
Full,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum UnbilledChargesOption {
Invoice,
Delete,
}
/// Response payload returned after successfully cancelling a subscription.
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CancelSubscriptionResponse {
/// Unique identifier for the subscription.
pub id: SubscriptionId,
/// Current status of the subscription.
pub status: SubscriptionStatus,
/// Merchant specific Unique identifier.
pub merchant_reference_id: Option<String>,
/// Associated profile ID.
pub profile_id: ProfileId,
/// Merchant identifier owning this subscription.
pub merchant_id: MerchantId,
/// Customer ID associated with this subscription.
pub customer_id: CustomerId,
/// Date when the subscription was cancelled
#[schema(value_type = Option<String>)]
pub cancelled_at: Option<time::PrimitiveDateTime>,
}
impl ApiEventMetric for PauseSubscriptionRequest {}
impl ApiEventMetric for PauseSubscriptionResponse {}
impl ApiEventMetric for ResumeSubscriptionRequest {}
impl ApiEventMetric for ResumeSubscriptionResponse {}
impl ApiEventMetric for CancelSubscriptionRequest {}
impl ApiEventMetric for CancelSubscriptionResponse {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/webhooks.rs | crates/api_models/src/webhooks.rs | use common_utils::custom_serde;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
#[cfg(feature = "payouts")]
use crate::payouts;
use crate::{disputes, enums as api_enums, mandates, payments, refunds, subscription};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)]
#[serde(rename_all = "snake_case")]
pub enum IncomingWebhookEvent {
/// Authorization + Capture failure
PaymentIntentFailure,
/// Authorization + Capture success
PaymentIntentSuccess,
PaymentIntentProcessing,
PaymentIntentPartiallyFunded,
PaymentIntentCancelled,
PaymentIntentCancelFailure,
PaymentIntentAuthorizationSuccess,
PaymentIntentAuthorizationFailure,
PaymentIntentExtendAuthorizationSuccess,
PaymentIntentExtendAuthorizationFailure,
PaymentIntentCaptureSuccess,
PaymentIntentCaptureFailure,
PaymentIntentExpired,
PaymentActionRequired,
EventNotSupported,
SourceChargeable,
SourceTransactionCreated,
RefundFailure,
RefundSuccess,
DisputeOpened,
DisputeExpired,
DisputeAccepted,
DisputeCancelled,
DisputeChallenged,
// dispute has been successfully challenged by the merchant
DisputeWon,
// dispute has been unsuccessfully challenged
DisputeLost,
MandateActive,
MandateRevoked,
EndpointVerification,
ExternalAuthenticationARes,
FrmApproved,
FrmRejected,
#[cfg(feature = "payouts")]
PayoutSuccess,
#[cfg(feature = "payouts")]
PayoutFailure,
#[cfg(feature = "payouts")]
PayoutProcessing,
#[cfg(feature = "payouts")]
PayoutCancelled,
#[cfg(feature = "payouts")]
PayoutCreated,
#[cfg(feature = "payouts")]
PayoutExpired,
#[cfg(feature = "payouts")]
PayoutReversed,
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
RecoveryPaymentFailure,
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
RecoveryPaymentSuccess,
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
RecoveryPaymentPending,
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
RecoveryInvoiceCancel,
SetupWebhook,
InvoiceGenerated,
}
impl IncomingWebhookEvent {
/// Convert UCS event type integer to IncomingWebhookEvent
/// Maps from proto WebhookEventType enum values to IncomingWebhookEvent variants
pub fn from_ucs_event_type(event_type: i32) -> Self {
match event_type {
0 => Self::EventNotSupported,
// Payment intent events
1 => Self::PaymentIntentFailure,
2 => Self::PaymentIntentSuccess,
3 => Self::PaymentIntentProcessing,
4 => Self::PaymentIntentPartiallyFunded,
5 => Self::PaymentIntentCancelled,
6 => Self::PaymentIntentCancelFailure,
7 => Self::PaymentIntentAuthorizationSuccess,
8 => Self::PaymentIntentAuthorizationFailure,
9 => Self::PaymentIntentCaptureSuccess,
10 => Self::PaymentIntentCaptureFailure,
11 => Self::PaymentIntentExpired,
12 => Self::PaymentActionRequired,
// Source events
13 => Self::SourceChargeable,
14 => Self::SourceTransactionCreated,
// Refund events
15 => Self::RefundFailure,
16 => Self::RefundSuccess,
// Dispute events
17 => Self::DisputeOpened,
18 => Self::DisputeExpired,
19 => Self::DisputeAccepted,
20 => Self::DisputeCancelled,
21 => Self::DisputeChallenged,
22 => Self::DisputeWon,
23 => Self::DisputeLost,
// Mandate events
24 => Self::MandateActive,
25 => Self::MandateRevoked,
// Miscellaneous events
26 => Self::EndpointVerification,
27 => Self::ExternalAuthenticationARes,
28 => Self::FrmApproved,
29 => Self::FrmRejected,
// Payout events
#[cfg(feature = "payouts")]
30 => Self::PayoutSuccess,
#[cfg(feature = "payouts")]
31 => Self::PayoutFailure,
#[cfg(feature = "payouts")]
32 => Self::PayoutProcessing,
#[cfg(feature = "payouts")]
33 => Self::PayoutCancelled,
#[cfg(feature = "payouts")]
34 => Self::PayoutCreated,
#[cfg(feature = "payouts")]
35 => Self::PayoutExpired,
#[cfg(feature = "payouts")]
36 => Self::PayoutReversed,
_ => Self::EventNotSupported,
}
}
}
pub enum WebhookFlow {
Payment,
#[cfg(feature = "payouts")]
Payout,
Refund,
Dispute,
Subscription,
ReturnResponse,
BankTransfer,
Mandate,
ExternalAuthentication,
FraudCheck,
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
Recovery,
Setup,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// This enum tells about the affect a webhook had on an object
pub enum WebhookResponseTracker {
#[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
status: common_enums::IntentStatus,
},
#[cfg(feature = "v2")]
Payment {
payment_id: common_utils::id_type::GlobalPaymentId,
status: common_enums::IntentStatus,
},
#[cfg(feature = "payouts")]
Payout {
payout_id: common_utils::id_type::PayoutId,
status: common_enums::PayoutStatus,
},
#[cfg(feature = "v1")]
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
status: common_enums::RefundStatus,
},
#[cfg(feature = "v2")]
Refund {
payment_id: common_utils::id_type::GlobalPaymentId,
refund_id: common_utils::id_type::GlobalRefundId,
status: common_enums::RefundStatus,
},
#[cfg(feature = "v1")]
Dispute {
dispute_id: String,
payment_id: common_utils::id_type::PaymentId,
status: common_enums::DisputeStatus,
},
#[cfg(feature = "v2")]
Dispute {
dispute_id: String,
payment_id: common_utils::id_type::GlobalPaymentId,
status: common_enums::DisputeStatus,
},
Mandate {
mandate_id: String,
status: common_enums::MandateStatus,
},
#[cfg(feature = "v1")]
PaymentMethod {
payment_method_id: String,
status: common_enums::PaymentMethodStatus,
},
NoEffect,
Relay {
relay_id: common_utils::id_type::RelayId,
status: common_enums::RelayStatus,
},
}
impl WebhookResponseTracker {
#[cfg(feature = "v1")]
pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> {
match self {
Self::Payment { payment_id, .. }
| Self::Refund { payment_id, .. }
| Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()),
Self::NoEffect | Self::Mandate { .. } | Self::PaymentMethod { .. } => None,
#[cfg(feature = "payouts")]
Self::Payout { .. } => None,
Self::Relay { .. } => None,
}
}
#[cfg(feature = "v1")]
pub fn get_refund_id(&self) -> Option<String> {
match self {
Self::Refund { refund_id, .. } => Some(refund_id.to_owned()),
_ => None,
}
}
#[cfg(feature = "v1")]
pub fn get_payment_method_id(&self) -> Option<String> {
match self {
Self::PaymentMethod {
payment_method_id, ..
} => Some(payment_method_id.to_owned()),
Self::Payment { .. }
| Self::Refund { .. }
| Self::Dispute { .. }
| Self::NoEffect
| Self::Mandate { .. }
| Self::Relay { .. } => None,
#[cfg(feature = "payouts")]
Self::Payout { .. } => None,
}
}
#[cfg(feature = "v2")]
pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> {
match self {
Self::Payment { payment_id, .. }
| Self::Refund { payment_id, .. }
| Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()),
Self::NoEffect | Self::Mandate { .. } => None,
#[cfg(feature = "payouts")]
Self::Payout { .. } => None,
Self::Relay { .. } => None,
}
}
#[cfg(feature = "v2")]
pub fn get_refund_id(&self) -> Option<common_utils::id_type::GlobalRefundId> {
match self {
Self::Refund { refund_id, .. } => Some(refund_id.to_owned()),
_ => None,
}
}
}
impl From<IncomingWebhookEvent> for WebhookFlow {
fn from(evt: IncomingWebhookEvent) -> Self {
match evt {
IncomingWebhookEvent::PaymentIntentFailure
| IncomingWebhookEvent::PaymentIntentSuccess
| IncomingWebhookEvent::PaymentIntentProcessing
| IncomingWebhookEvent::PaymentActionRequired
| IncomingWebhookEvent::PaymentIntentPartiallyFunded
| IncomingWebhookEvent::PaymentIntentCancelled
| IncomingWebhookEvent::PaymentIntentCancelFailure
| IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
| IncomingWebhookEvent::PaymentIntentAuthorizationFailure
| IncomingWebhookEvent::PaymentIntentCaptureSuccess
| IncomingWebhookEvent::PaymentIntentCaptureFailure
| IncomingWebhookEvent::PaymentIntentExpired
| IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess
| IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure => Self::Payment,
IncomingWebhookEvent::EventNotSupported => Self::ReturnResponse,
IncomingWebhookEvent::RefundSuccess | IncomingWebhookEvent::RefundFailure => {
Self::Refund
}
IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => {
Self::Mandate
}
IncomingWebhookEvent::DisputeOpened
| IncomingWebhookEvent::DisputeAccepted
| IncomingWebhookEvent::DisputeExpired
| IncomingWebhookEvent::DisputeCancelled
| IncomingWebhookEvent::DisputeChallenged
| IncomingWebhookEvent::DisputeWon
| IncomingWebhookEvent::DisputeLost => Self::Dispute,
IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse,
IncomingWebhookEvent::SourceChargeable
| IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer,
IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication,
IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => {
Self::FraudCheck
}
#[cfg(feature = "payouts")]
IncomingWebhookEvent::PayoutSuccess
| IncomingWebhookEvent::PayoutFailure
| IncomingWebhookEvent::PayoutProcessing
| IncomingWebhookEvent::PayoutCancelled
| IncomingWebhookEvent::PayoutCreated
| IncomingWebhookEvent::PayoutExpired
| IncomingWebhookEvent::PayoutReversed => Self::Payout,
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
IncomingWebhookEvent::RecoveryInvoiceCancel
| IncomingWebhookEvent::RecoveryPaymentFailure
| IncomingWebhookEvent::RecoveryPaymentPending
| IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery,
IncomingWebhookEvent::SetupWebhook => Self::Setup,
IncomingWebhookEvent::InvoiceGenerated => Self::Subscription,
}
}
}
pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>;
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum RefundIdType {
RefundId(String),
ConnectorRefundId(String),
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum MandateIdType {
MandateId(String),
ConnectorMandateId(String),
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum AuthenticationIdType {
AuthenticationId(common_utils::id_type::AuthenticationId),
ConnectorAuthenticationId(String),
}
#[cfg(feature = "payouts")]
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum PayoutIdType {
PayoutAttemptId(String),
ConnectorPayoutId(String),
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum ObjectReferenceId {
PaymentId(payments::PaymentIdType),
RefundId(RefundIdType),
MandateId(MandateIdType),
ExternalAuthenticationID(AuthenticationIdType),
#[cfg(feature = "payouts")]
PayoutId(PayoutIdType),
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
InvoiceId(InvoiceIdType),
SubscriptionId(common_utils::id_type::SubscriptionId),
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum InvoiceIdType {
ConnectorInvoiceId(String),
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl ObjectReferenceId {
pub fn get_connector_transaction_id_as_string(
self,
) -> Result<String, common_utils::errors::ValidationError> {
match self {
Self::PaymentId(
payments::PaymentIdType::ConnectorTransactionId(id)
) => Ok(id),
Self::PaymentId(_)=>Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "ConnectorTransactionId variant of PaymentId is required but received otherr variant",
},
),
Self::RefundId(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "PaymentId is required but received RefundId",
},
),
Self::MandateId(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "PaymentId is required but received MandateId",
},
),
Self::ExternalAuthenticationID(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "PaymentId is required but received ExternalAuthenticationID",
},
),
#[cfg(feature = "payouts")]
Self::PayoutId(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "PaymentId is required but received PayoutId",
},
),
Self::InvoiceId(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "PaymentId is required but received InvoiceId",
},
),
Self::SubscriptionId(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "PaymentId is required but received SubscriptionId",
},
),
}
}
}
pub struct IncomingWebhookDetails {
pub object_reference_id: ObjectReferenceId,
pub resource_object: Vec<u8>,
}
#[cfg(feature = "payouts")]
pub struct PayoutWebhookUpdate {
pub error_message: Option<String>,
pub error_code: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct OutgoingWebhook {
/// The merchant id of the merchant
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
/// The unique event id for each webhook
pub event_id: String,
/// The type of event this webhook corresponds to.
#[schema(value_type = EventType)]
pub event_type: api_enums::EventType,
/// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow
pub content: OutgoingWebhookContent,
/// The time at which webhook was sent
#[serde(default, with = "custom_serde::iso8601")]
pub timestamp: PrimitiveDateTime,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
#[cfg(feature = "v1")]
pub enum OutgoingWebhookContent {
#[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
PaymentDetails(Box<payments::PaymentsResponse>),
#[schema(value_type = RefundResponse, title = "RefundResponse")]
RefundDetails(Box<refunds::RefundResponse>),
#[schema(value_type = DisputeResponse, title = "DisputeResponse")]
DisputeDetails(Box<disputes::DisputeResponse>),
#[schema(value_type = MandateResponse, title = "MandateResponse")]
MandateDetails(Box<mandates::MandateResponse>),
#[cfg(feature = "payouts")]
#[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
PayoutDetails(Box<payouts::PayoutCreateResponse>),
#[schema(value_type = ConfirmSubscriptionResponse, title = "ConfirmSubscriptionResponse")]
SubscriptionDetails(Box<subscription::ConfirmSubscriptionResponse>),
}
#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
#[cfg(feature = "v2")]
pub enum OutgoingWebhookContent {
#[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
PaymentDetails(Box<payments::PaymentsResponse>),
#[schema(value_type = RefundResponse, title = "RefundResponse")]
RefundDetails(Box<refunds::RefundResponse>),
#[schema(value_type = DisputeResponse, title = "DisputeResponse")]
DisputeDetails(Box<disputes::DisputeResponse>),
#[schema(value_type = MandateResponse, title = "MandateResponse")]
MandateDetails(Box<mandates::MandateResponse>),
#[cfg(feature = "payouts")]
#[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
PayoutDetails(Box<payouts::PayoutCreateResponse>),
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorWebhookSecrets {
pub secret: Vec<u8>,
pub additional_secret: Option<masking::Secret<String>>,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl IncomingWebhookEvent {
pub fn is_recovery_transaction_event(&self) -> bool {
matches!(
self,
Self::RecoveryPaymentFailure
| Self::RecoveryPaymentSuccess
| Self::RecoveryPaymentPending
)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/user_role.rs | crates/api_models/src/user_role.rs | use common_enums::{ParentGroup, PermissionGroup};
use common_utils::pii;
use masking::Secret;
pub mod role;
#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum AuthorizationInfo {
Group(GroupInfo),
GroupWithTag(ParentInfo),
}
// TODO: To be deprecated
#[derive(Debug, serde::Serialize)]
pub struct GroupInfo {
pub group: PermissionGroup,
pub description: &'static str,
}
#[derive(Debug, serde::Serialize, Clone)]
pub struct ParentInfo {
pub name: ParentGroup,
pub description: &'static str,
pub groups: Vec<PermissionGroup>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserRoleRequest {
pub email: pii::Email,
pub role_id: String,
}
#[derive(Debug, serde::Serialize)]
pub enum UserStatus {
Active,
InvitationSent,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
}
#[derive(Debug, serde::Serialize)]
pub struct ListUsersInEntityResponse {
pub email: pii::Email,
pub roles: Vec<role::MinimalRoleInfo>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListInvitationForUserResponse {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
pub entity_name: Option<Secret<String>>,
pub role_id: String,
}
pub type AcceptInvitationsV2Request = Vec<Entity>;
pub type AcceptInvitationsPreAuthRequest = Vec<Entity>;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Entity {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListUsersInEntityRequest {
pub entity_type: Option<common_enums::EntityType>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/relay.rs | crates/api_models/src/relay.rs | use common_utils::types::MinorUnit;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::enums as api_enums;
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RelayRequest {
/// The identifier that is associated to a resource at the connector reference to which the relay request is being made
#[schema(example = "7256228702616471803954")]
pub connector_resource_id: String,
/// Identifier of the connector ( merchant connector account ) which was chosen to make the payment
#[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
/// The type of relay request
#[serde(rename = "type")]
#[schema(value_type = RelayType)]
pub relay_type: api_enums::RelayType,
/// The data that is associated with the relay request
pub data: Option<RelayData>,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RelayData {
/// The data that is associated with a refund relay request
Refund(RelayRefundRequestData),
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RelayRefundRequestData {
/// The amount that is being refunded
#[schema(value_type = i64 , example = 6540)]
pub amount: MinorUnit,
/// The currency in which the amount is being refunded
#[schema(value_type = Currency)]
pub currency: api_enums::Currency,
/// The reason for the refund
#[schema(max_length = 255, example = "Customer returned the product")]
pub reason: Option<String>,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RelayResponse {
/// The unique identifier for the Relay
#[schema(example = "relay_mbabizu24mvu3mela5njyhpit4", value_type = String)]
pub id: common_utils::id_type::RelayId,
/// The status of the relay request
#[schema(value_type = RelayStatus)]
pub status: api_enums::RelayStatus,
/// The identifier that is associated to a resource at the connector reference to which the relay request is being made
#[schema(example = "pi_3MKEivSFNglxLpam0ZaL98q9")]
pub connector_resource_id: String,
/// The error details if the relay request failed
pub error: Option<RelayError>,
/// The identifier that is associated to a resource at the connector to which the relay request is being made
#[schema(example = "re_3QY4TnEOqOywnAIx1Mm1p7GQ")]
pub connector_reference_id: Option<String>,
/// Identifier of the connector ( merchant connector account ) which was chosen to make the payment
#[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
/// The business profile that is associated with this relay request.
#[schema(example = "pro_abcdefghijklmnopqrstuvwxyz", value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
/// The type of relay request
#[serde(rename = "type")]
#[schema(value_type = RelayType)]
pub relay_type: api_enums::RelayType,
/// The data that is associated with the relay request
pub data: Option<RelayData>,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RelayError {
/// The error code
pub code: String,
/// The error message
pub message: String,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RelayRetrieveRequest {
/// The unique identifier for the Relay
#[serde(default)]
pub force_sync: bool,
/// The unique identifier for the Relay
pub id: common_utils::id_type::RelayId,
}
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RelayRetrieveBody {
/// The unique identifier for the Relay
#[serde(default)]
pub force_sync: bool,
}
impl common_utils::events::ApiEventMetric for RelayRequest {}
impl common_utils::events::ApiEventMetric for RelayResponse {}
impl common_utils::events::ApiEventMetric for RelayRetrieveRequest {}
impl common_utils::events::ApiEventMetric for RelayRetrieveBody {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/admin.rs | crates/api_models/src/admin.rs | use std::collections::{HashMap, HashSet};
use common_types::primitive_wrappers;
use common_utils::{
consts,
crypto::Encryptable,
errors::{self, CustomResult},
ext_traits::Encode,
id_type, link_utils, pii,
};
#[cfg(feature = "v1")]
use common_utils::{crypto::OptionalEncryptableName, ext_traits::ValueExt};
#[cfg(feature = "v2")]
use masking::ExposeInterface;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use utoipa::ToSchema;
use super::payments::AddressDetails;
use crate::{
consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY},
enums as api_enums, payment_methods,
};
#[cfg(feature = "v1")]
use crate::{profile_acquirer::ProfileAcquirerResponse, routing};
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
pub struct MerchantAccountListRequest {
pub organization_id: id_type::OrganizationId,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantAccountCreate {
/// The identifier for the Merchant Account
#[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
pub merchant_id: id_type::MerchantId,
/// Name of the Merchant Account
#[schema(value_type= Option<String>,example = "NewAge Retailer")]
pub merchant_name: Option<Secret<String>>,
/// Details about the merchant, can contain phone and emails of primary and secondary contact person
pub merchant_details: Option<MerchantDetails>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<url::Url>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// The routing algorithm to be used for routing payments to desired connectors
#[serde(skip)]
#[schema(deprecated)]
pub routing_algorithm: Option<serde_json::Value>,
/// The routing algorithm to be used for routing payouts to desired connectors
#[cfg(feature = "payouts")]
#[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.
#[schema(default = false, example = false)]
pub sub_merchants_enabled: Option<bool>,
/// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant
#[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)]
pub parent_merchant_id: Option<id_type::MerchantId>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = false, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled.
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Metadata is useful for storing additional, unstructured information on an object
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<MerchantAccountMetadata>,
/// API key that will be used for client side API access. A publishable key has to be always paired with a `client_secret`.
/// A `client_secret` can be obtained by creating a payment with `confirm` set to false
#[schema(example = "AH3423bkjbkjdsfbkj")]
pub publishable_key: Option<String>,
/// An identifier for the vault used to store payment method information.
#[schema(example = "locker_abc123")]
pub locker_id: Option<String>,
/// Details about the primary business unit of the merchant account
#[schema(value_type = Option<PrimaryBusinessDetails>)]
pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>,
/// The frm routing algorithm to be used for routing payments to desired FRM's
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
/// The id of the organization to which the merchant belongs to, if not passed an organization is created
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
pub organization_id: Option<id_type::OrganizationId>,
/// Default payment method collect link config
#[schema(value_type = Option<BusinessCollectLinkConfig>)]
pub pm_collect_link_config: Option<BusinessCollectLinkConfig>,
/// Product Type of this merchant account
#[schema(value_type = Option<MerchantProductType>, example = "Orchestration")]
pub product_type: Option<api_enums::MerchantProductType>,
/// Merchant Account Type of this merchant account
#[schema(value_type = Option<MerchantAccountRequestType>, example = "standard")]
pub merchant_account_type: Option<api_enums::MerchantAccountRequestType>,
}
#[cfg(feature = "v1")]
impl MerchantAccountCreate {
pub fn get_merchant_reference_id(&self) -> id_type::MerchantId {
self.merchant_id.clone()
}
pub fn get_payment_response_hash_key(&self) -> Option<String> {
self.payment_response_hash_key.clone().or(Some(
common_utils::crypto::generate_cryptographically_secure_random_string(64),
))
}
pub fn get_primary_details_as_value(
&self,
) -> CustomResult<serde_json::Value, errors::ParsingError> {
self.primary_business_details
.clone()
.unwrap_or_default()
.encode_to_value()
}
pub fn get_pm_link_config_as_value(
&self,
) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> {
self.pm_collect_link_config
.as_ref()
.map(|pm_collect_link_config| pm_collect_link_config.encode_to_value())
.transpose()
}
pub fn get_merchant_details_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.merchant_details
.as_ref()
.map(|merchant_details| merchant_details.encode_to_value().map(Secret::new))
.transpose()
}
pub fn get_metadata_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.metadata
.as_ref()
.map(|metadata| metadata.encode_to_value().map(Secret::new))
.transpose()
}
pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> {
match self.routing_algorithm {
Some(ref routing_algorithm) => {
let _: routing::StaticRoutingAlgorithm = routing_algorithm
.clone()
.parse_value("StaticRoutingAlgorithm")?;
Ok(())
}
None => Ok(()),
}
}
// Get the enable payment response hash as a boolean, where the default value is true
pub fn get_enable_payment_response_hash(&self) -> bool {
self.enable_payment_response_hash.unwrap_or(true)
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
#[schema(as = MerchantAccountCreate)]
pub struct MerchantAccountCreateWithoutOrgId {
/// Name of the Merchant Account, This will be used as a prefix to generate the id
#[schema(value_type= String, max_length = 64, example = "NewAge Retailer")]
pub merchant_name: Secret<common_utils::new_type::MerchantName>,
/// Details about the merchant, contains phone and emails of primary and secondary contact person.
pub merchant_details: Option<MerchantDetails>,
/// Metadata is useful for storing additional, unstructured information about the merchant account.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
#[schema(value_type = Option<MerchantProductType>)]
pub product_type: Option<api_enums::MerchantProductType>,
}
// In v2 the struct used in the API is MerchantAccountCreateWithoutOrgId
// The following struct is only used internally, so we can reuse the common
// part of `create_merchant_account` without duplicating its code for v2
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct MerchantAccountCreate {
pub merchant_name: Secret<common_utils::new_type::MerchantName>,
pub merchant_details: Option<MerchantDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub organization_id: id_type::OrganizationId,
/// Product Type of this merchant account
#[schema(value_type = Option<MerchantProductType>)]
pub product_type: Option<api_enums::MerchantProductType>,
}
#[cfg(feature = "v2")]
impl MerchantAccountCreate {
pub fn get_merchant_reference_id(&self) -> id_type::MerchantId {
id_type::MerchantId::from_merchant_name(self.merchant_name.clone().expose())
}
pub fn get_merchant_details_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.merchant_details
.as_ref()
.map(|merchant_details| merchant_details.encode_to_value().map(Secret::new))
.transpose()
}
pub fn get_metadata_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.metadata
.as_ref()
.map(|metadata| metadata.encode_to_value().map(Secret::new))
.transpose()
}
pub fn get_primary_details_as_value(
&self,
) -> CustomResult<serde_json::Value, errors::ParsingError> {
Vec::<PrimaryBusinessDetails>::new().encode_to_value()
}
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct CardTestingGuardConfig {
/// Determines if Card IP Blocking is enabled for profile
pub card_ip_blocking_status: CardTestingGuardStatus,
/// Determines the unsuccessful payment threshold for Card IP Blocking for profile
pub card_ip_blocking_threshold: i32,
/// Determines if Guest User Card Blocking is enabled for profile
pub guest_user_card_blocking_status: CardTestingGuardStatus,
/// Determines the unsuccessful payment threshold for Guest User Card Blocking for profile
pub guest_user_card_blocking_threshold: i32,
/// Determines if Customer Id Blocking is enabled for profile
pub customer_id_blocking_status: CardTestingGuardStatus,
/// Determines the unsuccessful payment threshold for Customer Id Blocking for profile
pub customer_id_blocking_threshold: i32,
/// Determines Redis Expiry for Card Testing Guard for profile
pub card_testing_guard_expiry: i32,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CardTestingGuardStatus {
Enabled,
Disabled,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct AuthenticationConnectorDetails {
/// List of authentication connectors
#[schema(value_type = Vec<AuthenticationConnectors>)]
pub authentication_connectors: Vec<common_enums::AuthenticationConnectors>,
/// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process.
pub three_ds_requestor_url: String,
/// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred.
pub three_ds_requestor_app_url: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct ExternalVaultConnectorDetails {
/// Merchant Connector id to be stored for vault connector
#[schema(value_type = Option<String>)]
pub vault_connector_id: id_type::MerchantConnectorAccountId,
/// External vault to be used for storing payment method information
#[schema(value_type = Option<VaultSdk>)]
pub vault_sdk: Option<common_enums::VaultSdk>,
/// Fields to tokenization in vault
pub vault_token_selector: Option<Vec<VaultTokenField>>,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct VaultTokenField {
/// Type of field to be tokenized in
#[schema(value_type = Option<VaultTokenType>)]
pub token_type: common_enums::VaultTokenType,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct MerchantAccountMetadata {
pub compatible_connector: Option<api_enums::Connector>,
#[serde(flatten)]
pub data: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantAccountUpdate {
/// The identifier for the Merchant Account
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: id_type::MerchantId,
/// Name of the Merchant Account
#[schema(example = "NewAge Retailer")]
pub merchant_name: Option<String>,
/// Details about the merchant
pub merchant_details: Option<MerchantDetails>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<url::Url>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// The routing algorithm to be used for routing payments to desired connectors
#[serde(skip)]
#[schema(deprecated)]
pub routing_algorithm: Option<serde_json::Value>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[cfg(feature = "payouts")]
#[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.
#[schema(default = false, example = false)]
pub sub_merchants_enabled: Option<bool>,
/// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant
#[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)]
pub parent_merchant_id: Option<id_type::MerchantId>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = false, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// API key that will be used for server side API access
#[schema(example = "AH3423bkjbkjdsfbkj")]
pub publishable_key: Option<String>,
/// An identifier for the vault used to store payment method information.
#[schema(example = "locker_abc123")]
pub locker_id: Option<String>,
/// Details about the primary business unit of the merchant account
pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>,
/// The frm routing algorithm to be used for routing payments to desired FRM's
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
/// The default profile that must be used for creating merchant accounts and payments
#[schema(max_length = 64, value_type = Option<String>)]
pub default_profile: Option<id_type::ProfileId>,
/// Default payment method collect link config
#[schema(value_type = Option<BusinessCollectLinkConfig>)]
pub pm_collect_link_config: Option<BusinessCollectLinkConfig>,
}
#[cfg(feature = "v1")]
impl MerchantAccountUpdate {
pub fn get_primary_details_as_value(
&self,
) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> {
self.primary_business_details
.as_ref()
.map(|primary_business_details| primary_business_details.encode_to_value())
.transpose()
}
pub fn get_pm_link_config_as_value(
&self,
) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> {
self.pm_collect_link_config
.as_ref()
.map(|pm_collect_link_config| pm_collect_link_config.encode_to_value())
.transpose()
}
pub fn get_merchant_details_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.merchant_details
.as_ref()
.map(|merchant_details| merchant_details.encode_to_value().map(Secret::new))
.transpose()
}
pub fn get_metadata_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.metadata
.as_ref()
.map(|metadata| metadata.encode_to_value().map(Secret::new))
.transpose()
}
pub fn get_webhook_details_as_value(
&self,
) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> {
self.webhook_details
.as_ref()
.map(|webhook_details| webhook_details.encode_to_value())
.transpose()
}
pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> {
match self.routing_algorithm {
Some(ref routing_algorithm) => {
let _: routing::StaticRoutingAlgorithm = routing_algorithm
.clone()
.parse_value("StaticRoutingAlgorithm")?;
Ok(())
}
None => Ok(()),
}
}
// Get the enable payment response hash as a boolean, where the default value is true
pub fn get_enable_payment_response_hash(&self) -> bool {
self.enable_payment_response_hash.unwrap_or(true)
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantAccountUpdate {
/// Name of the Merchant Account
#[schema(example = "NewAge Retailer")]
pub merchant_name: Option<String>,
/// Details about the merchant
pub merchant_details: Option<MerchantDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v2")]
impl MerchantAccountUpdate {
pub fn get_merchant_details_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.merchant_details
.as_ref()
.map(|merchant_details| merchant_details.encode_to_value().map(Secret::new))
.transpose()
}
pub fn get_metadata_as_secret(
&self,
) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
self.metadata
.as_ref()
.map(|metadata| metadata.encode_to_value().map(Secret::new))
.transpose()
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, ToSchema, Serialize)]
pub struct MerchantAccountResponse {
/// The identifier for the Merchant Account
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: id_type::MerchantId,
/// Name of the Merchant Account
#[schema(value_type = Option<String>,example = "NewAge Retailer")]
pub merchant_name: OptionalEncryptableName,
/// The URL to redirect after completion of the payment
#[schema(max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<String>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = false, example = true)]
pub enable_payment_response_hash: bool,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
#[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")]
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: bool,
/// Details about the merchant
#[schema(value_type = Option<MerchantDetails>)]
pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[serde(skip)]
#[schema(deprecated)]
pub routing_algorithm: Option<serde_json::Value>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[cfg(feature = "payouts")]
#[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false.
#[schema(default = false, example = false)]
pub sub_merchants_enabled: Option<bool>,
/// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant
#[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)]
pub parent_merchant_id: Option<id_type::MerchantId>,
/// API key that will be used for server side API access
#[schema(example = "AH3423bkjbkjdsfbkj")]
pub publishable_key: Option<String>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// An identifier for the vault used to store payment method information.
#[schema(example = "locker_abc123")]
pub locker_id: Option<String>,
/// Details about the primary business unit of the merchant account
#[schema(value_type = Vec<PrimaryBusinessDetails>)]
pub primary_business_details: Vec<PrimaryBusinessDetails>,
/// The frm routing algorithm to be used to process the incoming request from merchant to outgoing payment FRM.
#[schema(value_type = Option<StaticRoutingAlgorithm>, max_length = 255, example = r#"{"type": "single", "data": "stripe" }"#)]
pub frm_routing_algorithm: Option<serde_json::Value>,
/// The organization id merchant is associated with
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
pub organization_id: id_type::OrganizationId,
/// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false
pub is_recon_enabled: bool,
/// The default profile that must be used for creating merchant accounts and payments
#[schema(max_length = 64, value_type = Option<String>)]
pub default_profile: Option<id_type::ProfileId>,
/// Used to indicate the status of the recon module for a merchant account
#[schema(value_type = ReconStatus, example = "not_requested")]
pub recon_status: api_enums::ReconStatus,
/// Default payment method collect link config
#[schema(value_type = Option<BusinessCollectLinkConfig>)]
pub pm_collect_link_config: Option<BusinessCollectLinkConfig>,
/// Product Type of this merchant account
#[schema(value_type = Option<MerchantProductType>, example = "Orchestration")]
pub product_type: Option<api_enums::MerchantProductType>,
/// Merchant Account Type of this merchant account
#[schema(value_type = MerchantAccountType, example = "standard")]
pub merchant_account_type: api_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, ToSchema, Serialize)]
pub struct MerchantAccountResponse {
/// The identifier for the Merchant Account
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub id: id_type::MerchantId,
/// Name of the Merchant Account
#[schema(value_type = String,example = "NewAge Retailer")]
pub merchant_name: Secret<String>,
/// Details about the merchant
#[schema(value_type = Option<MerchantDetails>)]
pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>,
/// API key that will be used for server side API access
#[schema(example = "AH3423bkjbkjdsfbkj")]
pub publishable_key: String,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// The id of the organization which the merchant is associated with
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
pub organization_id: id_type::OrganizationId,
/// Used to indicate the status of the recon module for a merchant account
#[schema(value_type = ReconStatus, example = "not_requested")]
pub recon_status: api_enums::ReconStatus,
/// Product Type of this merchant account
#[schema(value_type = Option<MerchantProductType>, example = "Orchestration")]
pub product_type: Option<api_enums::MerchantProductType>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantDetails {
/// The merchant's primary contact name
#[schema(value_type = Option<String>, max_length = 255, example = "John Doe")]
pub primary_contact_person: Option<Secret<String>>,
/// The merchant's primary phone number
#[schema(value_type = Option<String>, max_length = 255, example = "999999999")]
pub primary_phone: Option<Secret<String>>,
/// The merchant's primary email address
#[schema(value_type = Option<String>, max_length = 255, example = "johndoe@test.com")]
pub primary_email: Option<pii::Email>,
/// The merchant's secondary contact name
#[schema(value_type = Option<String>, max_length= 255, example = "John Doe2")]
pub secondary_contact_person: Option<Secret<String>>,
/// The merchant's secondary phone number
#[schema(value_type = Option<String>, max_length = 255, example = "999999988")]
pub secondary_phone: Option<Secret<String>>,
/// The merchant's secondary email address
#[schema(value_type = Option<String>, max_length = 255, example = "johndoe2@test.com")]
pub secondary_email: Option<pii::Email>,
/// The business website of the merchant
#[schema(max_length = 255, example = "www.example.com")]
pub website: Option<String>,
/// A brief description about merchant's business
#[schema(
max_length = 255,
example = "Online Retail with a wide selection of organic products for North America"
)]
pub about_business: Option<String>,
/// The merchant's address details
pub address: Option<AddressDetails>,
#[schema(value_type = Option<String>, example = "123456789")]
pub merchant_tax_registration_id: Option<Secret<String>>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct PrimaryBusinessDetails {
#[schema(value_type = CountryAlpha2)]
pub country: api_enums::CountryAlpha2,
#[schema(example = "food")]
pub business: String,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct WebhookDetails {
///The version for Webhook
#[schema(max_length = 255, max_length = 255, example = "1.0.2")]
pub webhook_version: Option<String>,
///The user name for Webhook login
#[schema(max_length = 255, max_length = 255, example = "ekart_retail")]
pub webhook_username: Option<String>,
///The password for Webhook login
#[schema(value_type = Option<String>, max_length = 255, example = "ekart@123")]
pub webhook_password: Option<Secret<String>>,
///The url for the webhook endpoint
#[schema(value_type = Option<String>, example = "www.ekart.com/webhooks")]
pub webhook_url: Option<Secret<String>>,
/// If this property is true, a webhook message is posted whenever a new payment is created
#[schema(example = true)]
pub payment_created_enabled: Option<bool>,
/// If this property is true, a webhook message is posted whenever a payment is successful
#[schema(example = true)]
pub payment_succeeded_enabled: Option<bool>,
/// If this property is true, a webhook message is posted whenever a payment fails
#[schema(example = true)]
pub payment_failed_enabled: Option<bool>,
/// List of payment statuses that triggers a webhook for payment intents
#[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))]
pub payment_statuses_enabled: Option<Vec<api_enums::IntentStatus>>,
/// List of refund statuses that triggers a webhook for refunds
#[schema(value_type = Vec<IntentStatus>, example = json!(["success", "failure"]))]
pub refund_statuses_enabled: Option<Vec<api_enums::RefundStatus>>,
/// List of payout statuses that triggers a webhook for payouts
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))]
pub payout_statuses_enabled: Option<Vec<api_enums::PayoutStatus>>,
}
impl WebhookDetails {
pub fn merge(self, other: Self) -> Self {
Self {
webhook_version: other.webhook_version.or(self.webhook_version),
webhook_username: other.webhook_username.or(self.webhook_username),
webhook_password: other.webhook_password.or(self.webhook_password),
webhook_url: other.webhook_url.or(self.webhook_url),
payment_created_enabled: other
.payment_created_enabled
.or(self.payment_created_enabled),
payment_succeeded_enabled: other
.payment_succeeded_enabled
.or(self.payment_succeeded_enabled),
payment_failed_enabled: other.payment_failed_enabled.or(self.payment_failed_enabled),
payment_statuses_enabled: other
.payment_statuses_enabled
.or(self.payment_statuses_enabled),
refund_statuses_enabled: other
.refund_statuses_enabled
.or(self.refund_statuses_enabled),
#[cfg(feature = "payouts")]
payout_statuses_enabled: other
.payout_statuses_enabled
.or(self.payout_statuses_enabled),
}
}
fn validate_statuses<T>(statuses: &[T], status_type_name: &str) -> Result<(), String>
where
T: strum::IntoEnumIterator + Copy + PartialEq + std::fmt::Debug,
T: Into<Option<api_enums::EventType>>,
{
let valid_statuses: Vec<T> = T::iter().filter(|s| (*s).into().is_some()).collect();
for status in statuses {
if !valid_statuses.contains(status) {
return Err(format!(
"Invalid {status_type_name} webhook status provided: {status:?}"
));
}
}
Ok(())
}
pub fn validate(&self) -> Result<(), String> {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/health_check.rs | crates/api_models/src/health_check.rs | use std::collections::hash_map::HashMap;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RouterHealthCheckResponse {
pub database: bool,
pub redis: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub vault: Option<bool>,
#[cfg(feature = "olap")]
pub analytics: bool,
#[cfg(feature = "olap")]
pub opensearch: bool,
pub outgoing_request: bool,
#[cfg(feature = "dynamic_routing")]
pub grpc_health_check: HealthCheckMap,
#[cfg(feature = "dynamic_routing")]
pub decision_engine: bool,
pub unified_connector_service: Option<bool>,
}
impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {}
/// gRPC based services eligible for Health check
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HealthCheckServices {
/// Dynamic routing service
DynamicRoutingService,
}
pub type HealthCheckMap = HashMap<HealthCheckServices, bool>;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SchedulerHealthCheckResponse {
pub database: bool,
pub redis: bool,
pub outgoing_request: bool,
}
pub enum HealthState {
Running,
Error,
NotApplicable,
}
impl From<HealthState> for bool {
fn from(value: HealthState) -> Self {
match value {
HealthState::Running => true,
HealthState::Error | HealthState::NotApplicable => false,
}
}
}
impl From<HealthState> for Option<bool> {
fn from(value: HealthState) -> Self {
match value {
HealthState::Running => Some(true),
HealthState::Error => Some(false),
HealthState::NotApplicable => None,
}
}
}
impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/payouts.rs | crates/api_models/src/payouts.rs | use std::collections::HashMap;
use cards::CardNumber;
use common_enums::CardNetwork;
#[cfg(feature = "v2")]
use common_utils::types::BrowserInformation;
use common_utils::{
consts::default_payouts_list_limit,
crypto, id_type, link_utils, payout_method_utils,
pii::{self, Email},
transformers::ForeignFrom,
types::{UnifiedCode, UnifiedMessage},
};
use masking::Secret;
#[cfg(feature = "v1")]
use payments::BrowserInformation;
use router_derive::FlatStruct;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{admin, enums as api_enums, payment_methods::RequiredFieldInfo, payments};
#[derive(Debug, Serialize, Clone, ToSchema)]
pub enum PayoutRequest {
PayoutActionRequest(PayoutActionRequest),
PayoutCreateRequest(Box<PayoutCreateRequest>),
PayoutRetrieveRequest(PayoutRetrieveRequest),
}
#[derive(
Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema,
)]
#[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)]
#[serde(deny_unknown_fields)]
pub struct PayoutCreateRequest {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.**
#[schema(
value_type = Option<String>,
min_length = 30,
max_length = 30,
example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
#[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)]
pub payout_id: Option<id_type::PayoutId>,
/// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.**
#[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")]
#[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)]
pub merchant_id: Option<id_type::MerchantId>,
/// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported.
#[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")]
pub merchant_order_reference_id: Option<String>,
/// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = Option<u64>, example = 1000)]
#[mandatory_in(PayoutsCreateRequest = u64)]
#[remove_in(PayoutsConfirmRequest)]
#[serde(default, deserialize_with = "payments::amount::deserialize_option")]
pub amount: Option<payments::Amount>,
/// The currency of the payout request can be specified here
#[schema(value_type = Option<Currency>, example = "USD")]
#[mandatory_in(PayoutsCreateRequest = Currency)]
#[remove_in(PayoutsConfirmRequest)]
pub currency: Option<api_enums::Currency>,
/// Specifies routing algorithm for selecting a connector
#[schema(value_type = Option<StaticRoutingAlgorithm>, example = json!({
"type": "single",
"data": "adyen"
}))]
pub routing: Option<serde_json::Value>,
/// This field allows the merchant to manually select a connector with which the payout can go through.
#[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))]
pub connector: Option<Vec<api_enums::PayoutConnectors>>,
/// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it.
#[schema(value_type = Option<bool>, example = true, default = false)]
#[remove_in(PayoutConfirmRequest)]
pub confirm: Option<bool>,
/// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed.
#[schema(value_type = Option<PayoutType>, example = "card")]
pub payout_type: Option<api_enums::PayoutType>,
/// The payout method information required for carrying out a payout
#[schema(value_type = Option<PayoutMethodData>)]
pub payout_method_data: Option<PayoutMethodData>,
/// The billing address for the payout
#[schema(value_type = Option<Address>, example = json!(r#"{
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Francisco",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+1" }
}"#))]
pub billing: Option<payments::Address>,
/// Set to true to confirm the payout without review, no further action required
#[schema(value_type = Option<bool>, example = true, default = false)]
pub auto_fulfill: Option<bool>,
/// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._
#[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
/// Passing this object creates a new customer or attaches an existing customer to the payout
#[schema(value_type = Option<CustomerDetails>)]
pub customer: Option<payments::CustomerDetails>,
/// It's a token used for client side verification.
#[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
#[remove_in(PayoutsCreateRequest)]
#[mandatory_in(PayoutConfirmRequest = String)]
pub client_secret: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
pub return_url: Option<String>,
/// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._
#[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)]
pub business_country: Option<api_enums::CountryAlpha2>,
/// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._
#[schema(deprecated, example = "food", value_type = Option<String>)]
pub business_label: Option<String>,
/// A description of the payout
#[schema(example = "It's my first payout request", value_type = Option<String>)]
pub description: Option<String>,
/// Type of entity to whom the payout is being carried out to, select from the given list of options
#[schema(value_type = Option<PayoutEntityType>, example = "Individual")]
pub entity_type: Option<api_enums::PayoutEntityType>,
/// Specifies whether or not the payout request is recurring
#[schema(value_type = Option<bool>, default = false)]
pub recurring: Option<bool>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Provide a reference to a stored payout method, used to process the payout.
#[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)]
pub payout_token: Option<String>,
/// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used.
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// The send method which will be required for processing payouts, check options for better understanding.
#[schema(value_type = Option<PayoutSendPriority>, example = "instant")]
pub priority: Option<api_enums::PayoutSendPriority>,
/// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_.
#[schema(default = false, example = true, value_type = Option<bool>)]
pub payout_link: Option<bool>,
/// Custom payout link config for the particular payout, if payout link is to be generated.
#[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)]
pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>,
/// Will be used to expire client secret after certain amount of time to be supplied in seconds
/// (900) for 15 mins
#[schema(value_type = Option<u32>, example = 900)]
pub session_expiry: Option<u32>,
/// Customer's email. _Deprecated: Use customer object instead._
#[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
pub email: Option<Email>,
/// Customer's name. _Deprecated: Use customer object instead._
#[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")]
pub name: Option<Secret<String>>,
/// Customer's phone. _Deprecated: Use customer object instead._
#[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")]
pub phone: Option<Secret<String>>,
/// Customer's phone country code. _Deprecated: Use customer object instead._
#[schema(deprecated, max_length = 255, example = "+1")]
pub phone_country_code: Option<String>,
/// Identifier for payout method
pub payout_method_id: Option<String>,
/// Additional details required by 3DS 2.0
#[schema(value_type = Option<BrowserInformation>)]
pub browser_info: Option<BrowserInformation>,
}
impl PayoutCreateRequest {
pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> {
self.customer_id
.as_ref()
.or(self.customer.as_ref().map(|customer| &customer.id))
}
}
/// Custom payout link config for the particular payout, if payout link is to be generated.
#[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)]
pub struct PayoutCreatePayoutLinkConfig {
/// The unique identifier for the collect link.
#[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")]
pub payout_link_id: Option<String>,
#[serde(flatten)]
#[schema(value_type = Option<GenericLinkUiConfig>)]
pub ui_config: Option<link_utils::GenericLinkUiConfig>,
/// List of payout methods shown on collect UI
#[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)]
pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>,
/// Form layout of the payout link
#[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")]
pub form_layout: Option<api_enums::UIWidgetFormLayout>,
/// `test_mode` allows for opening payout links without any restrictions. This removes
/// - domain name validations
/// - check for making sure link is accessed within an iframe
#[schema(value_type = Option<bool>, example = false)]
pub test_mode: Option<bool>,
}
/// The payout method information required for carrying out a payout
#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PayoutMethodData {
Card(CardPayout),
Bank(Bank),
Wallet(Wallet),
BankRedirect(BankRedirect),
Passthrough(Passthrough),
}
impl Default for PayoutMethodData {
fn default() -> Self {
Self::Card(CardPayout::default())
}
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct CardPayout {
/// The card number
#[schema(value_type = String, example = "4242424242424242")]
pub card_number: CardNumber,
/// The card's expiry month
#[schema(value_type = String)]
pub expiry_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String)]
pub expiry_year: Secret<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Doe")]
pub card_holder_name: Option<Secret<String>>,
/// The card's network
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
pub card_network: Option<CardNetwork>,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(untagged)]
pub enum Bank {
Ach(AchBankTransfer),
Bacs(BacsBankTransfer),
Sepa(SepaBankTransfer),
Pix(PixBankTransfer),
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct AchBankTransfer {
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<api_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
/// Bank account number is an unique identifier assigned by a bank to a customer.
#[schema(value_type = String, example = "000123456")]
pub bank_account_number: Secret<String>,
/// [9 digits] Routing number - used in USA for identifying a specific bank.
#[schema(value_type = String, example = "110000000")]
pub bank_routing_number: Secret<String>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct BacsBankTransfer {
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<api_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
/// Bank account number is an unique identifier assigned by a bank to a customer.
#[schema(value_type = String, example = "000123456")]
pub bank_account_number: Secret<String>,
/// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches.
#[schema(value_type = String, example = "98-76-54")]
pub bank_sort_code: Secret<String>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
// The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone.
pub struct SepaBankTransfer {
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<api_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
/// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer.
#[schema(value_type = String, example = "DE89370400440532013000")]
pub iban: Secret<String>,
/// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches
#[schema(value_type = String, example = "HSBCGB2LXXX")]
pub bic: Option<Secret<String>>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct PixBankTransfer {
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank branch
#[schema(value_type = Option<String>, example = "3707")]
pub bank_branch: Option<String>,
/// Bank account number is an unique identifier assigned by a bank to a customer.
#[schema(value_type = String, example = "000123456")]
pub bank_account_number: Secret<String>,
/// Unique key for pix customer
#[schema(value_type = String, example = "000123456")]
pub pix_key: Secret<String>,
/// Individual taxpayer identification number
#[schema(value_type = Option<String>, example = "000123456")]
pub tax_id: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum Wallet {
ApplePayDecrypt(ApplePayDecrypt),
Paypal(Paypal),
Venmo(Venmo),
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BankRedirect {
Interac(Interac),
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct Interac {
/// Customer email linked with interac account
#[schema(value_type = String, example = "john.doe@example.com")]
pub email: Email,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct Passthrough {
/// PSP token generated for the payout method
#[schema(value_type = String, example = "token_12345")]
pub psp_token: Secret<String>,
/// Payout method type of the token
#[schema(value_type = PaymentMethodType, example = "paypal")]
pub token_type: api_enums::PaymentMethodType,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct Paypal {
/// Email linked with paypal account
#[schema(value_type = String, example = "john.doe@example.com")]
pub email: Option<Email>,
/// mobile number linked to paypal account
#[schema(value_type = String, example = "16608213349")]
pub telephone_number: Option<Secret<String>>,
/// id of the paypal account
#[schema(value_type = String, example = "G83KXTJ5EHCQ2")]
pub paypal_id: Option<Secret<String>>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct Venmo {
/// mobile number linked to venmo account
#[schema(value_type = String, example = "16608213349")]
pub telephone_number: Option<Secret<String>>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
pub struct ApplePayDecrypt {
/// The dpan number associated with card number
#[schema(value_type = String, example = "4242424242424242")]
pub dpan: CardNumber,
/// The card's expiry month
#[schema(value_type = String)]
pub expiry_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String)]
pub expiry_year: Secret<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Doe")]
pub card_holder_name: Option<Secret<String>>,
/// The card's network
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
pub card_network: Option<CardNetwork>,
}
#[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)]
#[serde(deny_unknown_fields)]
pub struct PayoutCreateResponse {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
#[schema(
value_type = String,
min_length = 30,
max_length = 30,
example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
pub payout_id: id_type::PayoutId,
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
#[schema(max_length = 255, value_type = String, example = "merchant_1668273825")]
pub merchant_id: id_type::MerchantId,
/// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported.
#[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")]
pub merchant_order_reference_id: Option<String>,
/// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// Recipient's currency for the payout request
#[schema(value_type = Currency, example = "USD")]
pub currency: api_enums::Currency,
/// The connector used for the payout
#[schema(example = "wise")]
pub connector: Option<String>,
/// The payout method that is to be used
#[schema(value_type = Option<PayoutType>, example = "bank")]
pub payout_type: Option<api_enums::PayoutType>,
/// The payout method details for the payout
#[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{
"card": {
"last4": "2503",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "08",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
}
}"#))]
pub payout_method_data: Option<PayoutMethodDataResponse>,
/// The billing address for the payout
#[schema(value_type = Option<Address>, example = json!(r#"{
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Francisco",
"state": "CA",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+1" }
}"#))]
pub billing: Option<payments::Address>,
/// Set to true to confirm the payout without review, no further action required
#[schema(value_type = bool, example = true, default = false)]
pub auto_fulfill: bool,
/// The identifier for the customer object. If not provided the customer ID will be autogenerated.
#[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
/// Passing this object creates a new customer or attaches an existing customer to the payout
#[schema(value_type = Option<CustomerDetailsResponse>)]
pub customer: Option<payments::CustomerDetailsResponse>,
/// It's a token used for client side verification.
#[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
pub client_secret: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = String, example = "https://hyperswitch.io")]
pub return_url: Option<String>,
/// Business country of the merchant for this payout
#[schema(example = "US", value_type = CountryAlpha2)]
pub business_country: Option<api_enums::CountryAlpha2>,
/// Business label of the merchant for this payout
#[schema(example = "food", value_type = Option<String>)]
pub business_label: Option<String>,
/// A description of the payout
#[schema(example = "It's my first payout request", value_type = Option<String>)]
pub description: Option<String>,
/// Type of entity to whom the payout is being carried out to
#[schema(value_type = PayoutEntityType, example = "Individual")]
pub entity_type: api_enums::PayoutEntityType,
/// Specifies whether or not the payout request is recurring
#[schema(value_type = bool, default = false)]
pub recurring: bool,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Unique identifier of the merchant connector account
#[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")]
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Current status of the Payout
#[schema(value_type = PayoutStatus, example = RequiresConfirmation)]
pub status: api_enums::PayoutStatus,
/// If there was an error while calling the connector the error message is received here
#[schema(value_type = Option<String>, example = "Failed while verifying the card")]
pub error_message: Option<String>,
/// If there was an error while calling the connectors the code is received here
#[schema(value_type = Option<String>, example = "E0001")]
pub error_code: Option<String>,
/// The business profile that is associated with this payout
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// Time when the payout was created
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created: Option<PrimitiveDateTime>,
/// Underlying processor's payout resource ID
#[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")]
pub connector_transaction_id: Option<String>,
/// Payout's send priority (if applicable)
#[schema(value_type = Option<PayoutSendPriority>, example = "instant")]
pub priority: Option<api_enums::PayoutSendPriority>,
/// List of attempts
#[schema(value_type = Option<Vec<PayoutAttemptResponse>>)]
#[serde(skip_serializing_if = "Option::is_none")]
pub attempts: Option<Vec<PayoutAttemptResponse>>,
/// If payout link was requested, this contains the link's ID and the URL to render the payout widget
#[schema(value_type = Option<PayoutLinkResponse>)]
pub payout_link: Option<PayoutLinkResponse>,
/// Customer's email. _Deprecated: Use customer object instead._
#[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
pub email: crypto::OptionalEncryptableEmail,
/// Customer's name. _Deprecated: Use customer object instead._
#[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")]
pub name: crypto::OptionalEncryptableName,
/// Customer's phone. _Deprecated: Use customer object instead._
#[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")]
pub phone: crypto::OptionalEncryptablePhone,
/// Customer's phone country code. _Deprecated: Use customer object instead._
#[schema(deprecated, max_length = 255, example = "+1")]
pub phone_country_code: Option<String>,
/// (This field is not live yet)
/// Error code unified across the connectors is received here in case of errors while calling the underlying connector
#[remove_in(PayoutCreateResponse)]
#[schema(value_type = Option<String>, max_length = 255, example = "UE_000")]
pub unified_code: Option<UnifiedCode>,
/// (This field is not live yet)
/// Error message unified across the connectors is received here in case of errors while calling the underlying connector
#[remove_in(PayoutCreateResponse)]
#[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")]
pub unified_message: Option<UnifiedMessage>,
/// Identifier for payout method
pub payout_method_id: Option<String>,
}
/// The payout method information for response
#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PayoutMethodDataResponse {
#[schema(value_type = CardAdditionalData)]
Card(Box<payout_method_utils::CardAdditionalData>),
#[schema(value_type = BankAdditionalData)]
Bank(Box<payout_method_utils::BankAdditionalData>),
#[schema(value_type = WalletAdditionalData)]
Wallet(Box<payout_method_utils::WalletAdditionalData>),
#[schema(value_type = BankRedirectAdditionalData)]
BankRedirect(Box<payout_method_utils::BankRedirectAdditionalData>),
#[schema(value_type = PassthroughAddtionalData)]
Passthrough(Box<payout_method_utils::PassthroughAddtionalData>),
}
#[derive(
Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema,
)]
pub struct PayoutAttemptResponse {
/// Unique identifier for the attempt
pub attempt_id: String,
/// The status of the attempt
#[schema(value_type = PayoutStatus, example = "failed")]
pub status: api_enums::PayoutStatus,
/// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 6583)]
pub amount: common_utils::types::MinorUnit,
/// The currency of the amount of the payout attempt
#[schema(value_type = Option<Currency>, example = "USD")]
pub currency: Option<api_enums::Currency>,
/// The connector used for the payout
pub connector: Option<String>,
/// Connector's error code in case of failures
pub error_code: Option<String>,
/// Connector's error message in case of failures
pub error_message: Option<String>,
/// The payout method that was used
#[schema(value_type = Option<PayoutType>, example = "bank")]
pub payment_method: Option<api_enums::PayoutType>,
/// Payment Method Type
#[schema(value_type = Option<PaymentMethodType>, example = "bacs")]
pub payout_method_type: Option<api_enums::PaymentMethodType>,
/// A unique identifier for a payout provided by the connector
pub connector_transaction_id: Option<String>,
/// If the payout was cancelled the reason provided here
pub cancellation_reason: Option<String>,
/// (This field is not live yet)
/// Error code unified across the connectors is received here in case of errors while calling the underlying connector
#[remove_in(PayoutAttemptResponse)]
#[schema(value_type = Option<String>, max_length = 255, example = "UE_000")]
pub unified_code: Option<UnifiedCode>,
/// (This field is not live yet)
/// Error message unified across the connectors is received here in case of errors while calling the underlying connector
#[remove_in(PayoutAttemptResponse)]
#[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")]
pub unified_message: Option<UnifiedMessage>,
}
#[derive(Default, Debug, Clone, Deserialize, ToSchema)]
pub struct PayoutRetrieveBody {
pub force_sync: Option<bool>,
#[schema(value_type = Option<String>)]
pub merchant_id: Option<id_type::MerchantId>,
}
#[derive(Debug, Serialize, ToSchema, Clone, Deserialize)]
pub struct PayoutRetrieveRequest {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
#[schema(
value_type = String,
min_length = 30,
max_length = 30,
example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
pub payout_id: id_type::PayoutId,
/// `force_sync` with the connector to get payout details
/// (defaults to false)
#[schema(value_type = Option<bool>, default = false, example = true)]
pub force_sync: Option<bool>,
/// The identifier for the Merchant Account.
#[schema(value_type = Option<String>)]
pub merchant_id: Option<id_type::MerchantId>,
}
#[derive(Debug, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema)]
#[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)]
pub struct PayoutActionRequest {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
#[schema(
value_type = String,
min_length = 30,
max_length = 30,
example = "187282ab-40ef-47a9-9206-5099ba31e432"
)]
pub payout_id: id_type::PayoutId,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/oidc.rs | crates/api_models/src/oidc.rs | use std::str::FromStr;
use common_utils::events::ApiEventMetric;
use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
const RESPONSE_TYPES_SUPPORTED: &[ResponseType] = &[ResponseType::Code];
const RESPONSE_MODES_SUPPORTED: &[ResponseMode] = &[ResponseMode::Query];
const SUBJECT_TYPES_SUPPORTED: &[SubjectType] = &[SubjectType::Public];
const ID_TOKEN_SIGNING_ALGS_SUPPORTED: &[SigningAlgorithm] = &[SigningAlgorithm::Rs256];
const GRANT_TYPES_SUPPORTED: &[GrantType] = &[GrantType::AuthorizationCode];
const SCOPES_SUPPORTED: &[Scope] = &[Scope::Openid, Scope::Email];
const TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED: &[TokenAuthMethod] =
&[TokenAuthMethod::ClientSecretBasic];
const CLAIMS_SUPPORTED: &[Claim] = &[
Claim::Aud,
Claim::Email,
Claim::EmailVerified,
Claim::Exp,
Claim::Iat,
Claim::Iss,
Claim::Sub,
];
/// OIDC Response Type
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseType {
Code,
}
/// OIDC Response Mode
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseMode {
Query,
}
/// OIDC Subject Type
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubjectType {
Public,
}
/// OIDC Signing Algorithm
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum SigningAlgorithm {
#[serde(rename = "RS256")]
Rs256,
}
/// JWK Key Type
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum KeyType {
#[serde(rename = "RSA")]
Rsa,
}
/// JWK Key Use
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KeyUse {
Sig,
}
/// OIDC Grant Type
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
AuthorizationCode,
}
/// OIDC Scope
#[derive(
Copy, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Scope {
Openid,
Email,
}
/// OIDC Token Endpoint Authentication Method
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenAuthMethod {
ClientSecretBasic,
}
/// OIDC Claim
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Claim {
Aud,
Email,
EmailVerified,
Exp,
Iat,
Iss,
Sub,
}
/// OIDC Authorization Error as per RFC 6749
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OidcAuthorizationError {
InvalidRequest,
UnauthorizedClient,
AccessDenied,
UnsupportedResponseType,
InvalidScope,
ServerError,
TemporarilyUnavailable,
}
/// OIDC Token Error as per RFC 6749
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OidcTokenError {
InvalidRequest,
InvalidClient,
InvalidGrant,
UnauthorizedClient,
UnsupportedGrantType,
InvalidScope,
}
/// OpenID Connect Discovery Response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct OidcDiscoveryResponse {
/// The issuer identifier for the OpenID Provider
#[schema(example = "https://sandbox.hyperswitch.io")]
pub issuer: String,
/// URL of the authorization endpoint
#[schema(example = "https://app.hyperswitch.io/oauth2/authorize")]
pub authorization_endpoint: String,
/// URL of the token endpoint
#[schema(example = "https://sandbox.hyperswitch.io/oauth2/token")]
pub token_endpoint: String,
/// URL of the JSON Web Key Set document
#[schema(example = "https://sandbox.hyperswitch.io/oauth2/jwks")]
pub jwks_uri: String,
/// List of OAuth 2.0 response_type values supported
pub response_types_supported: Vec<ResponseType>,
/// List of OAuth 2.0 response_mode values supported
pub response_modes_supported: Vec<ResponseMode>,
/// List of Subject Identifier types supported
pub subject_types_supported: Vec<SubjectType>,
/// List of JWS signing algorithms supported for ID Tokens
pub id_token_signing_alg_values_supported: Vec<SigningAlgorithm>,
/// List of OAuth 2.0 grant type values supported
pub grant_types_supported: Vec<GrantType>,
/// List of OAuth 2.0 scope values supported
pub scopes_supported: Vec<Scope>,
/// List of Client Authentication methods supported by the token endpoint
pub token_endpoint_auth_methods_supported: Vec<TokenAuthMethod>,
/// List of Claim Names supported
pub claims_supported: Vec<Claim>,
/// Whether the claims parameter is supported
#[serde(default)]
#[schema(example = false)]
pub claims_parameter_supported: bool,
/// Whether the request parameter is supported
#[serde(default)]
#[schema(example = false)]
pub request_parameter_supported: bool,
/// Whether the request_uri parameter is supported
#[serde(default)]
#[schema(example = false)]
pub request_uri_parameter_supported: bool,
}
impl OidcDiscoveryResponse {
pub fn new(issuer: String, control_center_url: String) -> Self {
let authorization_endpoint = format!("{}/oauth2/authorize", control_center_url);
let token_endpoint = format!("{}/oauth2/token", issuer);
let jwks_uri = format!("{}/oauth2/jwks", issuer);
Self {
issuer,
authorization_endpoint,
token_endpoint,
jwks_uri,
response_types_supported: RESPONSE_TYPES_SUPPORTED.to_vec(),
response_modes_supported: RESPONSE_MODES_SUPPORTED.to_vec(),
subject_types_supported: SUBJECT_TYPES_SUPPORTED.to_vec(),
id_token_signing_alg_values_supported: ID_TOKEN_SIGNING_ALGS_SUPPORTED.to_vec(),
grant_types_supported: GRANT_TYPES_SUPPORTED.to_vec(),
scopes_supported: SCOPES_SUPPORTED.to_vec(),
token_endpoint_auth_methods_supported: TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED.to_vec(),
claims_supported: CLAIMS_SUPPORTED.to_vec(),
claims_parameter_supported: false,
request_parameter_supported: false,
request_uri_parameter_supported: false,
}
}
}
/// JWKS (JSON Web Key Set) response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct JwksResponse {
/// Array of JSON Web Keys
pub keys: Vec<Jwk>,
}
/// JSON Web Key (JWK) for RSA public key
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Jwk {
/// Key type
pub kty: KeyType,
/// Key ID
#[schema(example = "key-1")]
pub kid: String,
/// Public key use
#[serde(rename = "use")]
pub key_use: KeyUse,
/// Algorithm
pub alg: SigningAlgorithm,
/// RSA public key modulus
pub n: String,
/// RSA public key exponent
#[schema(example = "AQAB")]
pub e: String,
}
/// Custom deserializer for space-separated scope strings
fn deserialize_scope_vec<'de, D>(deserializer: D) -> Result<Vec<Scope>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let s = String::deserialize(deserializer)?;
s.split_whitespace()
.map(|scope_str| {
Scope::from_str(scope_str)
.map_err(|_| D::Error::custom(format!("Invalid scope: '{}'", scope_str)))
})
.collect()
}
/// OIDC Authorization Request
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct OidcAuthorizeQuery {
/// OAuth 2.0 Response Type value
pub response_type: ResponseType,
/// OAuth 2.0 Client Identifier
#[schema(example = "client_abc123")]
pub client_id: String,
/// Redirection URI to which the response will be sent
#[schema(example = "https://example.com/callback")]
pub redirect_uri: String,
/// OpenID Connect scope values
#[serde(deserialize_with = "deserialize_scope_vec")]
pub scope: Vec<Scope>,
/// Opaque value used to maintain state between request and callback
#[schema(example = "state_xyz789")]
pub state: String,
/// String value used to associate a Client session with an ID Token
#[schema(example = "nonce_abc123")]
pub nonce: Option<String>,
}
/// OIDC Token Request
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct OidcTokenRequest {
/// OAuth 2.0 Grant Type value
pub grant_type: GrantType,
/// Authorization code received from the authorization server
#[schema(example = "auth_code_xyz789")]
pub code: String,
/// Redirection URI that was used in the authorization request
#[schema(example = "https://example.com/callback")]
pub redirect_uri: String,
/// OAuth 2.0 Client Identifier
#[schema(example = "client_abc123")]
pub client_id: String,
}
/// OIDC Token Response
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct OidcTokenResponse {
/// ID Token value associated with the authenticated session
#[schema(value_type = String)]
pub id_token: Secret<String>,
/// OAuth 2.0 Token Type value
#[schema(example = "Bearer")]
pub token_type: String,
/// Expiration time of the ID Token in seconds since the response was generated
#[schema(example = 3600)]
pub expires_in: u64,
}
impl ApiEventMetric for OidcDiscoveryResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Oidc)
}
}
impl ApiEventMetric for JwksResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Oidc)
}
}
impl ApiEventMetric for OidcAuthorizeQuery {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Oidc)
}
}
impl ApiEventMetric for OidcTokenRequest {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Oidc)
}
}
impl ApiEventMetric for OidcTokenResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Oidc)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/verify_connector.rs | crates/api_models/src/verify_connector.rs | use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::{admin, enums};
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyConnectorRequest {
pub connector_name: enums::Connector,
pub connector_account_details: admin::ConnectorAuthType,
}
common_utils::impl_api_event_type!(Miscellaneous, (VerifyConnectorRequest));
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/api_models/src/chat.rs | crates/api_models/src/chat.rs | use common_utils::id_type;
use masking::Secret;
use time::PrimitiveDateTime;
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ChatRequest {
pub message: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ChatResponse {
pub response: Secret<serde_json::Value>,
pub merchant_id: id_type::MerchantId,
pub status: String,
#[serde(skip_serializing)]
pub query_executed: Option<Secret<String>>,
#[serde(skip_serializing)]
pub row_count: Option<i32>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ChatListRequest {
pub merchant_id: Option<id_type::MerchantId>,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ChatConversation {
pub id: String,
pub session_id: Option<String>,
pub user_id: Option<String>,
pub merchant_id: Option<String>,
pub profile_id: Option<String>,
pub org_id: Option<String>,
pub role_id: Option<String>,
pub user_query: Secret<String>,
pub response: Secret<serde_json::Value>,
pub database_query: Option<String>,
pub interaction_status: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ChatListResponse {
pub conversations: Vec<ChatConversation>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.