# System Design Architecture

This document provides a comprehensive overview of the design architecture of the SmartBulls application.

---

## 1. High-Level Architecture Overview

The system utilizes a hybrid containerized model, delegating legacy requests and routing newly migrated logic to a high-performance Node.js cluster.

```mermaid
graph TD
    Client[Mobile App Client]
    
    subgraph Proxy & Web Server
        Caddy[Caddy Reverse Proxy: Port 80/443]
        Delegator[PHP Delegator/Proxy: Port 9000]
    end
    
    subgraph Backend APIs
        NodeApp[Node.js API Cluster: Port 4000]
        NodeSockets[Websocket Server: Port 3003/4004/5005]
        GrpcEngine[gRPC Engine Service: Port 50051]
    end
    
    subgraph Databases & Cache
        MySQL[(MySQL 8.0 Database)]
        Redis[(Redis 7 Cache / Memory Lock)]
    end
    
    subgraph External Feeds
        Kite[Zerodha Kite Ticker API]
        Binance[Binance WebSockets API]
    end

    Client -->|HTTPS / WSS| Caddy
    Caddy -->|Proxy HTTP /api/*| Delegator
    Delegator -->|Proxy Migrated OTs| NodeApp
    NodeApp -->|gRPC Calls| GrpcEngine
    Caddy -->|Proxy WebSockets| NodeSockets
    
    NodeApp --> MySQL
    NodeApp --> Redis
    GrpcEngine --> MySQL
    GrpcEngine --> Redis
    
    NodeSockets --> Redis
    Kite -->|Live Quotes| NodeSockets
    Binance -->|Crypto Quotes| NodeSockets
```

---

## 2. Component Directory

### Caddy Reverse Proxy
* **Configuration:** [Caddyfile](file:///var/www/html_docker/docker/caddy/Caddyfile)
* **Responsibility:** Handles HTTPS termination, SSL certificates via Let's Encrypt, and reverse proxies requests to PHP FPM, Node.js app server, and WebSocket gateways.

### PHP Request Delegator
* **Entry point:** [public/api/index.php](file:///var/www/html_docker/public/api/index.php)
* **Responsibility:** Acts as a gateway. Operates an array of migrated operation types (`$migrated_ots`). If the requested transaction falls in this list, it proxies the request directly to the Node.js API (port 4000). Otherwise, it delegates to PHP legacy controllers.

### Node.js API (Cluster Mode)
* **Entry point:** [node_api/app.js](file:///var/www/html_docker/node_api/app.js)
* **Responsibility:** High-performance processing of user profile logic, stock list management, wallet top-ups, plan registrations, and orders.
* **Process Management:** Managed by PM2 inside the Docker container using [ecosystem.config.js](file:///var/www/html_docker/docker/node/ecosystem.config.js).

### gRPC Engine (Microservice)
* **Entry point:** [grpc_engine/server.js](file:///var/www/html_docker/grpc_engine/server.js)
* **Responsibility:** Decoupled core trading tasks (order placing, margin validation, locks, cancellation, margin calculations). Relies on persistent binary Protocol Buffers connections for low-latency.
* **Process Management:** Managed in its own PM2 configuration and Docker containers.

### Cache & Storage Layer
* **MySQL 8.0:** Stores core relational data (users, KYC, positions, orders, watchlists).
* **Redis 7:** Stores fast-lookup cache arrays, distributed locks (OTP request rate limits, login attempts lockout), and terminal statistics.

---

## 3. Directory Structure

```
/var/www/html_docker
├── Database/               # Schema files and setup sql scripts
├── docker/                 # Service Dockerfiles and ecosystem configs
│   ├── grpc/               # Docker configuration for gRPC Engine
│   └── node/               # Docker configuration for Node API
├── Document/               # Project Architecture & design flow docs (This folder)
├── grpc_engine/            # Decoupled gRPC trading services
│   ├── proto/              # Protocol Buffer (.proto) declarations
│   ├── src/                # Core logic & connections (DB, Redis)
│   └── server.js           # Server entry point
├── node_api/               # Main Node.js API source code
│   ├── src/
│   │   ├── config/         # Connection scripts (DB, Redis, etc.)
│   │   ├── controllers/    # API Route controllers
│   │   ├── grpc/           # gRPC Client connection pools
│   │   ├── middleware/     # Auth and rate-limiting middleware
│   │   ├── models/         # Database models and queries
│   │   ├── routes/         # Express endpoint definitions
│   │   ├── services/       # Core business logic helpers
│   │   └── workers/        # Background queue listeners and preloaders
│   └── app.js              # Express app initializer
├── public/                 # Public asset uploads & legacy PHP api gateway
├── Smartbulls_app/         # Flutter Mobile application codebase
└── docker-compose.yml      # Service orchestration config
```
