From 653f7c4234d8e20b3f4b2012a3f3db39fb8b852b Mon Sep 17 00:00:00 2001 From: Almaz Shagiev Date: Mon, 25 May 2026 08:12:34 +0300 Subject: [PATCH] docs: add OpenAPI spec and architecture diagram - OpenAPI 3.0 spec for all API endpoints - Detailed architecture diagram in README showing service flow --- README.md | 214 +++++++++++++++++++++------------ docs/openapi.yaml | 297 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 433 insertions(+), 78 deletions(-) create mode 100644 docs/openapi.yaml diff --git a/README.md b/README.md index 18685ff..86393fb 100644 --- a/README.md +++ b/README.md @@ -1,109 +1,167 @@ -# fintech-project -Payment orchestrator +# Payment Orchestrator -## Start +A payment orchestrator service that routes payouts through multiple providers (Stripe, mock providers) with automatic fallback support. -Development is handled in docker containers +## Architecture -1. Copy .env.example contents into your local .env file -2. Run migrations -3. make local-up +``` + ┌─────────────────────────────────────────────────────────────┐ + │ CLIENT │ + │ (Merchant System) │ + └─────────────────────────────┬───────────────────────────────┘ + │ + │ HTTP POST /v1/payouts + ▼ + ┌─────────────────────────────────────────────────────────────┐ + │ API (:8080) │ + │ │ + │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ + │ │ Rate Limiter│ │ HTTP Router │ │ Prometheus Metrics │ │ + │ │ (Redis) │ │ (Chi) │ │ (/metrics) │ │ + │ └─────────────┘ └──────┬──────┘ └─────────────────────┘ │ + └──────────────────────────┼──────────────────────────────────┘ + │ + │ gRPC (CreatePayout, GetPayout, CancelPayout) + ▼ + ┌─────────────────────────────────────────────────────────────┐ + │ ORCHESTRATOR (:50051) │ + │ │ + │ ┌──────────────────────────────────────────────────────┐ │ + │ │ Routing Layer │ │ + │ │ ┌──────────┐ ┌──────────┐ ┌─────────────────────┐ │ │ + │ │ │ Priority │ │ Weighted │ │ SuccessBased │ │ │ + │ │ │ │ │ │ │ (track success %) │ │ │ + │ │ └──────────┘ └──────────┘ └─────────────────────┘ │ │ + │ └──────────────────────────┬───────────────────────────┘ │ + │ │ │ + │ ┌──────────────────────────▼───────────────────────────┐ │ + │ │ Fallback Engine │ │ + │ │ Provider A ──► (fail) ──► Provider B ──► (fail) │ │ + │ │ │ │ + │ │ Terminal errors (decline, fraud) stop immediately │ │ + │ └──────────────────────────────────────────────────────┘ │ + └──────────────────────────┬──────────────────────────────────┘ + │ + ┌──────────────────────────┼──────────────────────────────────┐ + │ ▼ │ + │ ┌─────────────────────────────────────────────────────┐ │ + │ │ PROVIDERS │ │ + │ │ │ │ + │ │ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │ │ + │ │ │ Stripe │ │Mock Card│ │ Crypto Sim │ │ │ + │ │ │ (card) │ │ (card) │ │ (crypto) │ │ │ + │ │ └─────────┘ └─────────┘ └─────────────┘ │ │ + │ │ │ │ │ │ │ + │ │ └──────────────┴───────────────┘ │ │ + │ │ │ │ │ + │ │ ▼ │ │ + │ │ External Payment Rails │ │ + │ └─────────────────────────────────────────────────────┘ │ + └──────────────────────────────────────────────────────────────┘ + + ┌─────────────────────────────────────────────────────────────┐ + │ INFRASTRUCTURE │ + │ │ + │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ + │ │ PostgreSQL │ │ Redis │ │ Grafana │ │ + │ │ (payouts) │ │(rate limit) │ │ :3000 │ │ + │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ + │ │ + │ ┌─────────────┐ │ + │ │ Prometheus │◄──── scrapes /metrics from all services │ + │ │ :9090 │ │ + │ └─────────────┘ │ + └─────────────────────────────────────────────────────────────┘ +``` -## API environment +## Features -The API reads `API_*` variables from the process environment. For local development it also loads the root `.env` file automatically via `godotenv`. +- **Multi-provider routing** - Route payouts through Stripe, mock providers, or crypto simulator +- **Automatic fallback** - On retryable errors, automatically try the next provider +- **Routing algorithms** - Priority, Weighted, and Success-based routing +- **Idempotent API** - Safe request retries with idempotency keys +- **Rate limiting** - Redis-backed token bucket rate limiter +- **Observability** - Prometheus metrics + Grafana dashboards -Example `.env` values: +## Quick Start -```env -API_ENV=development -API_HTTP_ADDR=:8080 -API_LOG_LEVEL=info -API_READ_TIMEOUT=5s -API_READ_HEADER_TIMEOUT=2s -API_WRITE_TIMEOUT=10s -API_IDLE_TIMEOUT=30s -API_SHUTDOWN_TIMEOUT=10s -``` +```bash +# Start infrastructure (Postgres, Redis) +make up -Common local flows: +# Run migrations +make migrate-up -```bash -make build-api && make run-api -make api-up +# Build services +make build + +# Run orchestrator and API +./bin/orchestrator start --config deploy/configs/orchestrator-local.yaml & +./bin/api & ``` -- `make run-api` runs the API binary locally and loads `.env` via the app. -- `make api-up` starts the API in Docker Compose with the same `API_*` values coming from `.env`. +## API Endpoints -## Observability +| Method | Endpoint | Description | +|--------|----------|-------------| +| `POST` | `/v1/payouts` | Create a new payout | +| `GET` | `/v1/payouts/{id}` | Get payout status | +| `POST` | `/v1/payouts/{id}/cancel` | Cancel a pending payout | +| `GET` | `/health` | Health check | +| `GET` | `/metrics` | Prometheus metrics | -The project includes a full observability stack with Prometheus and Grafana. +Full API documentation: [docs/openapi.yaml](docs/openapi.yaml) -### Architecture +## Example Request +```bash +curl -X POST http://localhost:8080/v1/payouts \ + -H "Content-Type: application/json" \ + -H "Idempotency-Key: $(uuidgen)" \ + -d '{"amount": 1000, "currency": "USD", "rail": "card"}' ``` -┌─────────────────────────────────────────────────────────────────┐ -│ SERVICES │ -│ │ -│ API (:8080) Orchestrator (:8081/50051) Webhook (:8082)│ -│ └─ /metrics └─ /metrics └─ /metrics │ -└──────────────────────────────┬──────────────────────────────────┘ - │ scrape /metrics - ▼ - ┌─────────────────────┐ - │ Prometheus │ - │ :9090 │ - └──────────┬──────────┘ - │ - ▼ - ┌─────────────────────┐ - │ Grafana │ - │ :3000 │ - └─────────────────────┘ + +Response: +```json +{"payout_id": "550e8400-e29b-41d4-a716-446655440000"} ``` -### Quick Start +## Configuration -```bash -# Start infrastructure (Postgres, Redis) -make up +Copy `.env.example` to `.env` and configure: -# Start observability stack -make observability-up +```env +API_ENV=development +API_HTTP_ADDR=:8080 +API_RATE_LIMIT_ENABLED=true +``` -# Build and run services -make build -./bin/orchestrator start --config deploy/configs/orchestrator-local.yaml & -./bin/webhook start --config deploy/configs/webhook-local.yaml & -API_REDIS_PASSWORD="change_me_redis_password" ./bin/api & +## Observability + +```bash +# Start Prometheus + Grafana +make observability-up # Open Grafana make grafana-open -# or visit http://localhost:3000 (admin/admin) ``` -### Available Metrics - -| Service | Metrics | -|---------|---------| -| **API** | HTTP latency (p50/p95/p99), request counts, in-flight requests, rate limiter stats | -| **Orchestrator** | gRPC latency per method, response codes, handling time histograms | -| **Webhook** | HTTP latency, request counts, event processing stats | +Pre-built dashboards: +- **API Overview** - HTTP latency, request rate, rate limiter stats +- **Orchestrator Overview** - gRPC latency, provider distribution -### Grafana Dashboards +## Load Testing -Pre-provisioned dashboards in the **Fintech** folder: - -- **API Overview** - HTTP latency, request rate by endpoint, error rate, rate limiter stats -- **Orchestrator Overview** - gRPC latency, response code distribution, success rate -- **Webhook Overview** - Event processing latency, request counts +```bash +# Run k6 load tests +make loadtest-create # Create payout load test +make loadtest-rate-limit # Rate limiter stress test +``` -### Makefile Targets +## Development ```bash -make observability-up # Start Prometheus + Grafana -make observability-down # Stop observability stack -make grafana-open # Open Grafana in browser -make prometheus-open # Open Prometheus in browser -``` \ No newline at end of file +make build # Build all services +make test # Run tests +make lint # Run linter +``` diff --git a/docs/openapi.yaml b/docs/openapi.yaml new file mode 100644 index 0000000..2e94c45 --- /dev/null +++ b/docs/openapi.yaml @@ -0,0 +1,297 @@ +openapi: 3.0.3 +info: + title: Payment Orchestrator API + description: | + A payment orchestrator service that routes payouts through multiple providers + with automatic fallback support. + + ## Features + - Multi-provider routing (Stripe, mock providers) + - Automatic fallback on provider failure + - Idempotent payout creation + - Rate limiting (Redis token bucket) + + ## Rails + - `card` - Card payments via Stripe or mock providers + - `crypto` - Crypto payments via simulated provider + version: 1.0.0 + contact: + name: API Support + +servers: + - url: http://localhost:8080 + description: Local development server + +tags: + - name: Payouts + description: Payout operations + +paths: + /v1/payouts: + post: + tags: + - Payouts + summary: Create a payout + description: | + Creates a new payout and routes it through the configured providers. + The request is idempotent - sending the same request with the same + Idempotency-Key will return the existing payout. + + ## Routing + The orchestrator selects providers based on the configured algorithm: + - **Priority**: Providers ordered by config + - **Weighted**: Random selection by weight + - **SuccessBased**: Highest success rate first + + ## Fallback + If the primary provider fails with a retryable error, the orchestrator + automatically tries the next available provider. + operationId: createPayout + parameters: + - name: Idempotency-Key + in: header + required: true + description: | + Unique key for idempotent requests. Use UUID v6 for best results + (lexicographically sortable). + schema: + type: string + format: uuid + example: "1e5f3b2a-9c4d-4e8a-8b7c-6d5e4f3a2b1c" + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreatePayoutRequest' + examples: + card_payment: + summary: Card payout + value: + amount: 1000 + currency: USD + rail: card + crypto_payment: + summary: Crypto payout + value: + amount: 5000 + currency: EUR + rail: crypto + responses: + '202': + description: Payout accepted and processing + content: + application/json: + schema: + $ref: '#/components/schemas/CreatePayoutResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: "invalid request: amount must be positive" + '409': + description: Idempotency key conflict + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: "idempotency key already used with different request" + '429': + description: Rate limit exceeded + headers: + Retry-After: + schema: + type: integer + description: Seconds to wait before retry + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: "rate limit exceeded" + retry_after: 1 + + /v1/payouts/{id}: + get: + tags: + - Payouts + summary: Get payout by ID + description: Retrieves the current state of a payout including provider details. + operationId: getPayout + parameters: + - name: id + in: path + required: true + description: Payout ID (UUID) + schema: + type: string + format: uuid + responses: + '200': + description: Payout details + content: + application/json: + schema: + $ref: '#/components/schemas/Payout' + '404': + description: Payout not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: "payout not found" + + /v1/payouts/{id}/cancel: + post: + tags: + - Payouts + summary: Cancel a payout + description: | + Cancels a pending payout. Only payouts in `pending` state can be cancelled. + Once sent to the provider, cancellation is no longer possible. + operationId: cancelPayout + parameters: + - name: id + in: path + required: true + description: Payout ID (UUID) + schema: + type: string + format: uuid + responses: + '200': + description: Payout cancelled + content: + application/json: + schema: + $ref: '#/components/schemas/Payout' + '400': + description: Cannot cancel payout + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: "cannot cancel payout in state 'sent'" + '404': + description: Payout not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + + /health: + get: + tags: + - Health + summary: Health check + description: Returns the health status of the API service. + operationId: healthCheck + responses: + '200': + description: Service is healthy + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: "ok" + +components: + schemas: + CreatePayoutRequest: + type: object + required: + - amount + - currency + - rail + properties: + amount: + type: integer + description: Amount in cents (smallest currency unit) + minimum: 1 + example: 1000 + currency: + type: string + description: ISO 4217 currency code + enum: [USD, EUR, GBP] + example: USD + rail: + type: string + description: Payment rail/method + enum: [card, crypto] + example: card + + CreatePayoutResponse: + type: object + properties: + payout_id: + type: string + format: uuid + description: Unique identifier for the created payout + example: "550e8400-e29b-41d4-a716-446655440000" + + Payout: + type: object + properties: + payout_id: + type: string + format: uuid + description: Unique identifier for the payout + example: "550e8400-e29b-41d4-a716-446655440000" + state: + type: string + description: Current state of the payout + enum: [pending, sent, succeeded, failed, cancelled] + example: pending + amount: + type: integer + description: Amount in cents + example: 1000 + currency: + type: string + description: ISO 4217 currency code + example: USD + rail: + type: string + description: Payment rail/method + example: card + provider: + type: string + nullable: true + description: Provider that handled the payout + example: stripe + external_id: + type: string + nullable: true + description: Provider's reference ID (e.g., Stripe PaymentIntent ID) + example: pi_3abc123xyz + created_at: + type: string + format: date-time + description: When the payout was created + example: "2024-01-15T10:30:00Z" + updated_at: + type: string + format: date-time + description: When the payout was last updated + example: "2024-01-15T10:30:05Z" + + ErrorResponse: + type: object + properties: + error: + type: string + description: Error message + example: "invalid request" + retry_after: + type: integer + description: Seconds to wait before retry (only for rate limiting) + example: 1