From 24e6a7c45b91ac2a518e0dac53337e936c45133a Mon Sep 17 00:00:00 2001 From: tinu hareesswar Date: Mon, 13 Apr 2026 23:46:59 +0530 Subject: [PATCH] docs: improve README, configuration reference, API docs, and contributing guide - README: add badges, tighten value prop, add working quick-start with curl examples, document routing strategies - configuration.md: expand from stub to full reference covering all config sections - api-reference.md: replace redirect with endpoint map and Postman/OpenAPI pointers - CONTRIBUTING.md: fix broken links, correct repo URLs, add security contact Co-Authored-By: Claude Sonnet 4.6 --- CONTRIBUTING.md | 29 ++-- README.md | 318 ++++++++++++++++++++++-------------------- docs/api-reference.md | 34 ++++- docs/configuration.md | 234 +++++++++++++++++++++++++++---- 4 files changed, 408 insertions(+), 207 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 62e2eb34..2871ec99 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,10 +1,10 @@ # Contributing to Decision Engine -Thank you for considering contributing to Decision Engine! This document provides guidelines and instructions for contributing. +Thank you for considering contributing to Decision Engine! This document describes how to report issues, propose changes, and submit pull requests. ## Code of Conduct -By participating in this project, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md). +Be respectful, constructive, and professional. We follow the spirit of the [Contributor Covenant](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). Unacceptable behaviour can be reported privately to `hyperswitch@juspay.in`. ## How Can I Contribute? @@ -38,32 +38,29 @@ We welcome feature suggestions! Feature requests should include: #### Development Environment Setup -For setting up the database, please refer to the following guides: -- **MySQL Setup**: [docs/setup-guide-mysql.md](docs/setup-guide-mysql.md) -- **PostgreSQL Setup**: [docs/setup-guide-postgres.md](docs/setup-guide-postgres.md) +The canonical local setup — CLI, Docker, Compose, and Helm — lives in [docs/local-setup.md](docs/local-setup.md). Database-specific quickstarts: +- **PostgreSQL**: [docs/setup-guide-postgres.md](docs/setup-guide-postgres.md) +- **MySQL**: [docs/setup-guide-mysql.md](docs/setup-guide-mysql.md) ```bash # Clone your fork -git clone https://github.com/your-username/decision-engine.git -cd Decision Engine +git clone https://github.com/YOUR_USERNAME/decision-engine.git +cd decision-engine -# Add the upstream repository -git remote add upstream https://github.com/project-owner/decision-engine.git +# Track upstream +git remote add upstream https://github.com/juspay/decision-engine.git # Create a branch -git checkout -b feature/your-feature-name +git checkout -b feat/your-feature-name -# Install development dependencies +# Recommended dev tooling cargo install cargo-watch cargo-insta cargo-audit -# Run tests +# Run the test suite cargo test -# Run specific tests -cargo test routing_test - -# Run with auto-reload for development +# Auto-reload loop during development cargo watch -x run ``` diff --git a/README.md b/README.md index 725a9931..82346ebc 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,19 @@
-Rust -License -Docker -Release -Slack - -

- # ⚡ Decision Engine -### **The Brain Behind Smarter Payments** - -**Open-Source • High-Performance • Success Rate Based** +**An open-source, high-performance payment routing engine — written in Rust.** -*Route payments intelligently. Maximize success rates. Zero vendor lock-in.* +*Route every transaction to the gateway most likely to succeed, in real time, with zero vendor lock-in.* ---- +[![CI](https://img.shields.io/github/actions/workflow/status/juspay/decision-engine/ci-push.yml?branch=main&label=CI&style=flat-square)](https://github.com/juspay/decision-engine/actions/workflows/ci-push.yml) +[![Release](https://img.shields.io/github/v/release/juspay/decision-engine?include_prereleases&style=flat-square&label=release&color=brightgreen)](https://github.com/juspay/decision-engine/releases) +[![License](https://img.shields.io/badge/license-AGPL--3.0-blue?style=flat-square)](LICENSE) +[![Rust](https://img.shields.io/badge/rust-1.85%2B-orange?style=flat-square&logo=rust&logoColor=white)](https://www.rust-lang.org/) +[![Docker](https://img.shields.io/badge/docker-ready-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/juspay/decision-engine/pkgs/container/decision-engine) +[![Slack](https://img.shields.io/badge/slack-join%20chat-4A154B?style=flat-square&logo=slack&logoColor=white)](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) -**[🚀 Quick Start](#-quick-start)** • -**[📚 Documentation](#-documentation)** • -**[🏗 Architecture](#-architecture)** • -**[🤝 Contributing](#-contributing)** +**[Quick Start](#-quick-start)** · **[Documentation](#-documentation)** · **[Architecture](#-architecture)** · **[Routing Strategies](#-routing-strategies)** · **[Contributing](#-contributing)**
@@ -29,224 +21,240 @@ ## 🎯 What is Decision Engine? -Decision Engine is a **high-performance payment gateway router** built in Rust that intelligently selects the optimal payment gateway for each transaction — in real-time. - -``` -┌─────────────┐ ┌──────────────────┐ ┌─────────────┐ -│ Payment │────▶│ Decision Engine │────▶│ Best │ -│ Request │ │ (Fast routing) │ │ Gateway │ -└─────────────┘ └──────────────────┘ └─────────────┘ +Decision Engine is a standalone payment routing service that, for each transaction, picks the gateway most likely to authorise successfully. It combines **rule-based routing** (merchant-authored policies) with **success-rate–based dynamic routing** (learned from live traffic), and it is designed to drop into any orchestrator — including [Hyperswitch](https://github.com/juspay/hyperswitch), commercial stacks, or a home-grown payments service. + +```text + ┌──────────────┐ ┌──────────────────┐ ┌──────────────┐ + │ Payment │──────▶│ Decision Engine │──────▶│ Chosen │ + │ Request │ │ rules + SR data │ │ Gateway │ + └──────────────┘ └──────────────────┘ └──────────────┘ + │ + ▼ + success / failure feedback + (used to update SR scores) ``` -### Why Teams Choose Decision Engine +### Why teams choose Decision Engine -| 💥 The Problem | ✅ Our Solution | -|----------------|-----------------| -| Payment failures from gateway downtime | **Real-time health monitoring** with automatic failover | -| Suboptimal routing = lost revenue | **SR-based routing** based on success rates & latency | -| Vendor lock-in limits flexibility | **Modular design** — works with any orchestrator | -| Complex rule management | **Flexible policies** — rule-based + SR-based hybrid | +| Problem you probably have | How Decision Engine solves it | +|---|---| +| Gateway outages silently tank your auth rate | **Elimination routing** deprioritises unhealthy gateways in real time | +| Static routing tables leave money on the table | **SR-based dynamic ordering** learns from live success rates | +| Business rules live in code, not config | **Priority Logic V2** — a versioned, API-driven rule engine | +| Vendor lock-in with existing orchestrators | **Drop-in HTTP service**, DB-agnostic (MySQL or PostgreSQL) | +| Compliance scope creep | **No card data ever touches the engine** — integrate behind your vault | --- ## ✨ Features - - - - - -
- -### 🧠 Intelligent Routing - -| Feature | What It Does | -|---------|--------------| -| **Eligibility Check** | Filters out ineligible gateways before routing | -| **Rule-Based Ordering** | Apply merchant-specific priority rules | -| **Dynamic Ordering** | Success rate based gateway optimization | -| **Downtime Detection** | Auto-pause failing gateways | - - - -### 🛠 Built for Production - -| Capability | Details | -|------------|---------| -| **⚡ Blazing Fast** | Fast routing decisions | -| **🔐 Memory Safe** | Built in Rust — no data races | -| **📊 Multi-DB** | MySQL & PostgreSQL support | -| **🐳 Docker Ready** | One-command deployment | -| **☸️ K8s Native** | Helm charts included | - -
+### 🧠 Intelligent routing +- **Eligibility filtering** — rule out gateways that can't process the transaction +- **Priority Logic V2** — author rules over any payment field (`amount`, `payment_method`, `card_network`, `billing_country`, …) with `AND` / `OR` / nested logic, number ranges, enum arrays, volume splits, and per-rule metadata +- **SR-based dynamic ordering** — gateways are reordered on live success-rate scores at a configurable dimension (merchant, payment method, BIN, …) +- **Elimination routing** — gateways dropping below a configurable SR threshold are temporarily removed from selection +- **Hedging / exploration** — a tunable percentage of traffic is sent off-policy to keep SR estimates honest +- **Debit network routing (US)** — pick the lowest-cost debit network on co-badged cards +- **Scheduled outage awareness** — exclude gateways during known maintenance windows + +### 🛠 Built for production +- **Rust** — memory-safe, no GC pauses, suitable for the hot path of a payments stack +- **Pluggable storage** — MySQL or PostgreSQL; Redis for ephemeral SR state +- **First-class ops** — Prometheus metrics, structured logs, health endpoint, Grafana dashboards +- **Docker & Helm** — pinned GHCR images (`v1.4`) and a shipped Helm chart +- **Versioned Compose profiles** — `postgres-ghcr`, `mysql-ghcr`, `dashboard-*`, `monitoring`, and local-build equivalents (see [local-setup.md](docs/local-setup.md)) --- -## 📊 Performance at a Glance +## 🚀 Quick Start -
- -| Metric | Value | -|--------|-------| -| Routing Decision Time | **Low latency** | -| Memory Footprint | **~50MB** | -| Concurrent Requests | **100K+** | -| Uptime SLA Support | **99.99%** | - -
- ---- - -## 🏃 Quick Start - -### 🐳 Docker (Recommended) +The fastest path is Docker Compose against the pinned GHCR image. ```bash -# Clone and run git clone https://github.com/juspay/decision-engine.git cd decision-engine -docker compose --profile postgres-ghcr up -d -# That's it! API ready at http://localhost:8080 +# PostgreSQL stack (API + Postgres + Redis + migrations) +docker compose --profile postgres-ghcr up -d ``` -### 🦀 From Source +Verify: ```bash -# Prerequisites: Rust 1.85+, MySQL/PostgreSQL, Redis - -git clone https://github.com/juspay/decision-engine.git -cd decision-engine -cargo build --release +curl http://localhost:8080/health +# → {"message":"Health is good"} +``` -# Configure -cp config.example.toml config/development.toml -# Edit config with your settings +Make your first routing decision: -# Run migrations & start -diesel migration run -./target/release/open_router +```bash +curl -s http://localhost:8080/decide-gateway \ + -H 'Content-Type: application/json' \ + -d '{ + "merchantId": "test_merchant1", + "eligibleGatewayList": ["GatewayA", "GatewayB", "GatewayC"], + "rankingAlgorithm": "SR_BASED_ROUTING", + "eliminationEnabled": true, + "paymentInfo": { + "paymentId": "PAY12359", + "amount": 100.50, + "currency": "USD", + "customerId": "CUST12345", + "paymentType": "ORDER_PAYMENT", + "paymentMethodType": "UPI", + "paymentMethod": "UPI_PAY" + } + }' ``` -### ✅ Verify +Need MySQL, a local source build, or Helm? See the [**Local Setup Guide**](docs/local-setup.md) — it is the canonical reference and covers every supported path. + +### Build from source ```bash -curl http://localhost:8080/health -# → {"message":"Health is good"} +# Prerequisites: Rust 1.85+, PostgreSQL (or MySQL), Redis + +# PostgreSQL build +cargo build --release --no-default-features --features middleware,kms-aws,postgres +just migrate-pg +RUSTFLAGS="-Awarnings" cargo run --no-default-features --features postgres + +# MySQL build +cargo build --release --features release +RUSTFLAGS="-Awarnings" cargo run --features release ``` +> A ready-to-import [Postman collection](decision-engine.postman_collection.json) is included at the repo root. + --- ## 📖 Documentation -| 📘 Resource | Description | -|-------------|-------------| -| [Local Setup Guide](docs/local-setup.md) | Canonical guide for CLI, Docker, Compose profiles, and Helm | -| [MySQL Setup Guide](docs/setup-guide-mysql.md) | MySQL-specific walkthrough | -| [PostgreSQL Setup Guide](docs/setup-guide-postgres.md) | PostgreSQL-specific walkthrough | -| [API Reference](docs/api-reference1.md) | Complete REST API documentation | -| [Configuration Guide](docs/configuration.md) | All config options explained | -| [Deep Dive Blog](https://juspay.io/blog/juspay-orchestrator-and-merchant-controlled-routing-engine) | How routing logic works | +| Resource | What it covers | +|---|---| +| [**Local Setup Guide**](docs/local-setup.md) | Canonical setup — CLI, Docker, Compose profiles, Helm, troubleshooting | +| [PostgreSQL Quickstart](docs/setup-guide-postgres.md) | Postgres-focused commands | +| [MySQL Quickstart](docs/setup-guide-mysql.md) | MySQL-focused commands | +| [**API Reference**](docs/api-reference.md) | Endpoint map + full request/response examples (`decide-gateway`, `update-gateway-score`, rule CRUD, Priority Logic V2) | +| [Configuration Guide](docs/configuration.md) | Every config section, environment overrides, and examples | +| [OpenAPI Spec](docs/openapi.json) | Machine-readable API definition (importable into Postman / Swagger) | +| [Helm Chart](helm-charts/) | Kubernetes deployment | +| [Deep-dive blog](https://juspay.io/blog/juspay-orchestrator-and-merchant-controlled-routing-engine) | Background on the routing logic | + +Run the full docs portal locally with any `dashboard-*` Compose profile — it is served at `http://localhost:8081/introduction`. --- ## 🏗 Architecture -### High-Level Flow -
- Decision Engine Architecture + Decision Engine architecture
-### Integration Pattern - -Decision Engine integrates seamlessly into your existing payment stack: +### Integration pattern
- Integration Pattern + Integration pattern
-**Integration Steps:** +| Step | Flow | Component | Action | +|:---:|:---:|---|---| +| 1 | → | Your app | Initiates a payment | +| 2 | → | Orchestrator | Calls Decision Engine with eligible gateways + context | +| 3 | → | Decision Engine | Applies rules, SR scores, and health data to pick a gateway | +| 4 | → | Vault | Detokenises card data (engine never sees PAN) | +| 5 | → | Gateway | Processes the authorisation | +| 6 | ← | Gateway | Returns success / failure | +| 7 | → | Decision Engine | Orchestrator calls `/update-gateway-score` so SR stats stay current | +| 8 | ← | Your app | Receives the final result | + +**Design properties** +- **Zero PCI scope** — all card data flows via your vault; the engine sees tokens only. +- **Stateless hot path** — routing decisions read from Redis / DB; horizontal scale is trivial. +- **Orchestrator-agnostic** — a thin HTTP contract with JSON payloads; no SDK lock-in. + +--- + +## 🧭 Routing Strategies + +Decision Engine exposes multiple ranking algorithms via the `rankingAlgorithm` field on `/decide-gateway`: -| Step | Direction | Component | Action | -|:----:|:---------:|-----------|--------| -| 1 | → | Your App | Initiates payment request | -| 2 | → | Orchestrator | Forwards to Decision Engine | -| 3 | → | Decision Engine | Selects optimal gateway | -| 4 | → | Vault | Returns card token (PCI-safe) | -| 5 | → | Gateway | Processes payment | -| 6 | ← | Gateway | Returns result | -| 7 | ← | Orchestrator | Routes response back | -| 8 | ← | Your App | Receives final result | +| Algorithm | When to use | +|---|---| +| `SR_BASED_ROUTING` | Default. Pick the gateway with the best live success-rate score at the configured dimension. | +| `NTW_BASED_ROUTING` | US debit routing — select the lowest-cost network on co-badged cards. | +| `PL_BASED_ROUTING` | Evaluate a merchant-authored [Priority Logic V2](docs/api-reference1.md#priority-logic-v2) rule. | -**Key Benefits:** -- **Zero PCI scope** — Vault handles all card data -- **Drop-in integration** — Works with any orchestrator -- **Intelligent fallback** — Auto-switches on gateway failure +Responses include a `routing_approach` field that tells you exactly *why* a gateway was chosen — `SR_SELECTION_V3_ROUTING`, `SR_V3_DOWNTIME_ROUTING`, `SR_V3_ALL_DOWNTIME_ROUTING`, `SR_V3_HEDGING`, `SR_V3_DOWNTIME_HEDGING`, or `SR_V3_ALL_DOWNTIME_HEDGING`. The semantics of each value are documented in the [API reference](docs/api-reference1.md#routing-approach). + +Feedback loop: call `/update-gateway-score` with the transaction outcome (`SUCCESS` / `FAILURE`) so the engine can update its SR estimates. This is the mechanism that makes dynamic routing learn. --- ## 🗺 Roadmap -| Status | Feature | Description | -|:------:|---------|-------------| -| ✅ | Rule-based routing | Merchant-defined priority rules | -| ✅ | Dynamic ordering | SR-based gateway selection | -| ✅ | Downtime detection | Automatic health monitoring | -| ✅ | Multi-database | MySQL & PostgreSQL support | -| 🔄 | Enhanced routing models | Better success rate prediction | -| 🔄 | Admin dashboard | Visual rule management UI | -| 📋 | Multi-tenant analytics | Per-tenant routing insights | -| 📋 | GraphQL API | Alternative query interface | +| Status | Item | +|:---:|---| +| ✅ | Rule-based routing (Priority Logic V2) | +| ✅ | SR-based dynamic ordering | +| ✅ | Elimination routing with downtime detection | +| ✅ | MySQL + PostgreSQL support | +| ✅ | Helm chart & GHCR images | +| 🔄 | Enhanced SR prediction models | +| 🔄 | Admin dashboard for rule management | +| 📋 | Per-tenant routing analytics | +| 📋 | GraphQL API surface | + +Legend: ✅ shipped · 🔄 in progress · 📋 planned. --- ## 🤝 Contributing -We ❤️ contributions! +Contributions are welcome — bug reports, documentation fixes, new features, and rule-engine extensions. ```bash -# 1. Fork & clone +# 1. Fork and clone git clone https://github.com/YOUR_USERNAME/decision-engine.git +cd decision-engine -# 2. Create branch -git checkout -b feature/your-feature +# 2. Create a branch +git checkout -b feat/your-feature -# 3. Make changes & test +# 3. Run the checks locally +cargo fmt --all +cargo clippy --all-targets -- -D warnings cargo test -# 4. Submit PR! +# 4. Open a pull request ``` -👉 See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. - -🌱 **New to open source?** Check out [good first issues](https://github.com/juspay/decision-engine/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)! +See [CONTRIBUTING.md](CONTRIBUTING.md) for the full workflow, code style, and commit message conventions. New contributors: look for [`good first issue`](https://github.com/juspay/decision-engine/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). --- -## 💬 Community +## 💬 Community & Support + +| Channel | For | +|---|---| +| [Slack](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) | Real-time questions, discussions | +| [GitHub Discussions](https://github.com/juspay/decision-engine/discussions) | Design questions, ideas, RFCs | +| [GitHub Issues](https://github.com/juspay/decision-engine/issues) | Bugs and feature requests | -| Platform | What It's For | -|----------|---------------| -| [![Slack](https://img.shields.io/badge/Slack-Join_Chat-4A154B?logo=slack)](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) | Real-time help, discussions | -| [GitHub Discussions](https://github.com/juspay/decision-engine/discussions) | Ideas, feature requests | -| [GitHub Issues](https://github.com/juspay/decision-engine/issues) | Bug reports | +For security-sensitive reports, please **do not** file a public issue — email the maintainers at `hyperswitch@juspay.in`. --- ## 📜 License -Licensed under [GNU AGPL v3.0](LICENSE). +Decision Engine is licensed under the [GNU Affero General Public License v3.0](LICENSE). Commercial and embedded-use questions: `hyperswitch@juspay.in`. ---
-### Built with ❤️ by [Juspay](https://juspay.io) - -*Reliable, open-source payments infrastructure for the world.* +Built by [Juspay](https://juspay.io) and the Hyperswitch community. -**[⬆ Back to Top](#-decision-engine)** +**[⬆ Back to top](#-decision-engine)**
diff --git a/docs/api-reference.md b/docs/api-reference.md index f249414f..bf9a87d1 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1,9 +1,33 @@ # API Reference -Decision Engine API documentation is available in: +Decision Engine exposes a small, JSON-over-HTTP API. The authoritative reference — with request / response examples for every endpoint — lives in **[api-reference1.md](api-reference1.md)**. -- [Primary API Reference](api-reference1.md) -- Mint API pages under `docs/api-reference/endpoint/*` +## Endpoint map -If you run docs locally (`dashboard-*` profiles), browse: -- `http://localhost:8081/introduction` +| Area | Method + path | Purpose | +|---|---|---| +| **Routing decision** | `POST /decide-gateway` | Pick the best gateway for a transaction | +| **Feedback loop** | `POST /update-gateway-score` | Report a transaction outcome so SR stats update | +| **Health** | `GET /health` | Liveness probe | +| **Rule CRUD** | `POST /rule/create` | Create a routing / elimination config | +| | `POST /rule/get` | Retrieve a config | +| | `POST /rule/update` | Update a config | +| | `POST /rule/delete` | Remove a config | +| **Merchant CRUD** | `POST /merchant-account/create` | Register a merchant | +| | `GET /merchant-account/{id}` | Retrieve a merchant | +| | `DELETE /merchant-account/{id}` | Delete a merchant | +| **Priority Logic V2** | `POST /routing/create` | Create a routing algorithm | +| | `POST /routing/evaluate` | Dry-run an algorithm against a payload | +| | `POST /routing/activate` | Make an algorithm the active one | +| | `POST /routing/list/{merchant_id}` | List all algorithms for a merchant | +| | `POST /routing/list/active/{merchant_id}` | List the currently active algorithms | + +## Other formats + +- **OpenAPI spec** — [`openapi.json`](openapi.json) (machine-readable, importable into Postman / Insomnia / Swagger UI). +- **Postman collection** — [`decision-engine.postman_collection.json`](../decision-engine.postman_collection.json) at the repo root. +- **Hosted docs** — start any `dashboard-*` Docker Compose profile and browse `http://localhost:8081/introduction`. + +## Full reference + +👉 **[api-reference1.md](api-reference1.md)** — complete endpoint documentation with curl examples and response schemas. diff --git a/docs/configuration.md b/docs/configuration.md index a78d1742..2477f9e5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,16 +1,31 @@ -# Configuration Guide +# Configuration Reference -This document explains how to configure Decision Engine for local and on-prem deployments. +Decision Engine is configured from a single TOML file loaded at process start. This page documents every section that the service reads. For deployment-specific setup (Docker, Helm, cargo), see the [Local Setup Guide](local-setup.md). -## Primary Config Files +## Config file locations -- `config/development.toml`: host/source runs -- `config/docker-configuration.toml`: Docker/Compose runs -- `helm-charts/config/development.toml`: Kubernetes chart template config +| Deployment target | File | +|---|---| +| Host / source run (`cargo run`) | `config/development.toml` | +| Docker & Docker Compose | `config/docker-configuration.toml` (mounted at `/local/config/development.toml`) | +| Helm chart | `helm-charts/config/development.toml` (rendered into the config map) | -## Core Sections +A full, commented reference lives at [`config.example.toml`](../config.example.toml) at the repo root — copy and edit it for custom deployments. -### Server +## Precedence + +1. Defaults compiled into the binary. +2. Values from the TOML file. +3. Environment variables (when explicitly supported — see [Environment overrides](#environment-overrides)). +4. Helm `extraEnvVars` (Kubernetes only). + +--- + +## Sections + +### `[server]` + +HTTP listener for the public API. ```toml [server] @@ -18,52 +33,209 @@ host = "0.0.0.0" port = 8080 ``` -### Metrics +### `[metrics]` + +Prometheus scrape endpoint. Exposed on a separate port so it can be firewalled off from public traffic. ```toml [metrics] host = "0.0.0.0" -port = 9090 +port = 9094 ``` -### Logging +### `[log.console]` + +Structured logging configuration. ```toml [log.console] -enabled = true -level = "DEBUG" -log_format = "default" +enabled = true +level = "DEBUG" # TRACE | DEBUG | INFO | WARN | ERROR +log_format = "default" # default | json +``` + +In production, prefer `level = "INFO"` and `log_format = "json"` so logs ship cleanly into Loki / ELK / Datadog. + +### `[limit]` + +Coarse global rate limiter. + +```toml +[limit] +request_count = 1 # requests... +duration = 60 # ...per this many seconds per key +``` + +### `[database]` — MySQL + +Used when the binary is built with the default (`release`) features. + +```toml +[database] +username = "root" +password = "root" +host = "127.0.0.1" +port = 3306 +dbname = "jdb" ``` -### Database +### `[pg_database]` — PostgreSQL + +Used when the binary is built with `--features postgres`. + +```toml +[pg_database] +pg_username = "db_user" +pg_password = "db_pass" +pg_host = "localhost" +pg_port = 5432 +pg_dbname = "decision_engine_db" +``` -Use either MySQL or PostgreSQL as required by your deployment mode. +Exactly one of `[database]` or `[pg_database]` is consumed, depending on the build. The other section is ignored. -For Docker Compose profiles, connection details are pre-wired via service names and mounted config. -For source runs, ensure your database URL in config matches your local DB. +### `[redis]` -### Redis +Redis holds ephemeral SR state, caches, and rate-limit counters. All fields below are honoured by the [`fred`](https://crates.io/crates/fred) client. ```toml [redis] -host = "127.0.0.1" -port = 6379 +host = "127.0.0.1" +port = 6379 +pool_size = 5 +reconnect_max_attempts = 5 +reconnect_delay = 5 # seconds +use_legacy_version = false +stream_read_count = 1 +auto_pipeline = true +disable_auto_backpressure = false +max_in_flight_commands = 5000 +default_command_timeout = 30 # seconds +unresponsive_timeout = 10 # seconds +max_feed_count = 200 +``` + +### `[cache]` and `[cache_config]` + +In-process cache (Moka) in front of Redis, plus TTLs for config lookups. + +```toml +[cache] +tti = 7200 # time-to-idle, seconds +max_capacity = 5000 + +[cache_config] +service_config_redis_prefix = "DE_service_config_" +service_config_ttl = 300 # seconds +``` + +### `[compression_filepath]` + +Path on disk where Redis ZSTD compression dictionaries are loaded from. + +```toml +[compression_filepath] +zstd_compression_filepath = "/tmp/extra-paths/redis-zstd-dictionaries/sbx" +``` + +### `[tenant_secrets]` + +Per-tenant isolation. Each entry maps a tenant id to its DB schema (and, in commercial builds, its secret manager binding). + +```toml +[tenant_secrets] +public = { schema = "public" } +``` + +### `[routing_config.keys]` + +The **schema of fields the rule engine can match on**. Every `lhs` you can use inside a Priority Logic V2 rule must be declared here, together with its type: + +| Declared type | Matches against | +|---|---| +| `integer` | numeric conditions with optional `min` | +| `enum` | `enum_variant` / `enum_variant_array` with a fixed value set | +| `str_value` | free-form strings with optional `min_length`, `exact_length`, `regex` | +| `udf` | opaque user-defined field (e.g., `metadata`) | + +```toml +[routing_config.keys] +amount = { type = "integer", min = 0 } +payment_method = { type = "enum", values = "card, upi, wallet, bank_transfer, …" } +card_bin = { type = "str_value", exact_length = 6, regex = "^[0-9]{6}$" } +billing_country = { type = "enum", values = "India, UnitedStatesOfAmerica, …" } +``` + +> See the top of [`config/development.toml`](../config/development.toml) for the full list of fields that ship with the default build, including `payment_method`, `payment_method_type`, `card_network`, `currency`, `issuer_country`, `authentication_type`, `capture_method`, and more. + +### `[debit_routing_config]` and subsections + +Fees used by the US debit-routing algorithm (`NTW_BASED_ROUTING`). + +```toml +[debit_routing_config] +fraud_check_fee = 1.0 + +[debit_routing_config.network_fee] +visa = { percentage = 0.1375, fixed_amount = 2.0 } +mastercard = { percentage = 0.15, fixed_amount = 4.0 } +accel = { percentage = 0.0, fixed_amount = 4.0 } +nyce = { percentage = 0.10, fixed_amount = 1.5 } +pulse = { percentage = 0.10, fixed_amount = 3.0 } + +[debit_routing_config.interchange_fee] +# Per-network interchange — see config.example.toml for the full matrix. +``` + +The engine uses these numbers to pick the cheapest eligible network on a co-badged debit card. + +### `[pm_filters.*]` + +Eligibility filters per connector. Each connector section declares which payment-method / country / currency combinations it supports, and the engine uses that to filter the `eligibleGatewayList` before ranking. + +```toml +[pm_filters.stripe] +# payment_method.payment_method_type = "country, currency, …" +card.credit = "UnitedStatesOfAmerica, France, … : USD, EUR, …" +# … ``` -### Secrets Manager +Add a new connector by adding a new `[pm_filters.]` section. The complete list of shipped connectors is in `config/development.toml`. + +### `[secrets_manager]` + +Controls how secrets (DB credentials, gateway keys) are resolved at boot. + +```toml +[secrets_manager] +secrets_management_config = "no_encryption" # no_encryption | aws_kms | hashicorp_vault +``` + +In local development, `no_encryption` is the norm. For production, see the KMS-backed and Vault-backed variants in `config.example.toml`. + +--- + +## Environment overrides -`secrets_manager` controls encryption/key-management behavior. In local environments this is commonly set to `no_encryption`. +Many scalar values can be overridden via environment variables at runtime — useful in Kubernetes, where secrets should never land in a committed config file. Common ones: -## Environment Overrides +| Variable | Overrides | +|---|---| +| `ROUTER__REDIS__HOST` | `[redis].host` | +| `ROUTER__REDIS__PORT` | `[redis].port` | +| `ROUTER__PG_DATABASE__PG_PASSWORD` | `[pg_database].pg_password` | +| `ROUTER__DATABASE__PASSWORD` | `[database].password` | +| `ROUTER__SERVER__PORT` | `[server].port` | +| `ROUTER__LOG__CONSOLE__LEVEL` | `[log.console].level` | -Use environment variables to override selected runtime values when needed (for example in Helm via `extraEnvVars`). +The pattern is `ROUTER__
__` (double underscores between levels). Nested tables like `[log.console]` become `ROUTER__LOG__CONSOLE__…`. -For deployment-specific examples, see: +For Helm, set these via `extraEnvVars` — see `helm-charts/values.yaml`. -- [Local Setup Guide](local-setup.md) -- [Helm Chart README](../helm-charts/README.md) +--- -## Related Docs +## Related documentation -- [Local Setup Guide](local-setup.md) -- [API Reference](api-reference1.md) +- [Local Setup Guide](local-setup.md) — how to run the engine with a given config +- [API Reference](api-reference1.md) — how the routing configuration is used at request time +- [Helm Chart](../helm-charts/) — Kubernetes packaging