Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Implement interactive rule statistics, paginated domain/IP tables, and PWA install functionality.

luolei52b36103e823
diff --git a/.gitignore b/.gitignore
index 3afc1e3..8c67043 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,8 @@ out/
# Database
*.db
*.db-journal
+*.db-wal
+*.db-shm
*.sqlite
*.sqlite3
@@ -58,3 +60,4 @@ next-env.d.ts
# AI dev logs
.specstory/
+.claude/
diff --git a/README.en.md b/README.en.md
index 544d1ff..285fddd 100644
--- a/README.en.md
+++ b/README.en.md
@@ -23,17 +23,12 @@
</p>
![Clash Master Overview](./assets/clash-master-overview.png)
-
-## 🤔 Preface
-
-From concept to this complete version, this project took only **4 hours**. The core MVP was completed in just **1 hour** ([Tweet](https://x.com/luoleiorg/status/2019418455276204185)).
-
-Thanks to [@Kai](https://x.com/real_kai42) for providing [Kimi Code](https://www.kimi.com/code/console) Allegretto subscription support.
-
-Throughout the entire development process, I didn't write a single line of code myself (didn't even open an IDE) — all handed over to [Kimi K2.5](https://www.kimi.com/code/console). As a veteran of Vibe Coding, this experience with Kimi still surprised me: **no usage limits, no Token anxiety**. Made-in-China AI, the future is promising.
+![Clash Master Rules](./assets/clash-master-rules.png)
+![Clash Master Regions](./assets/clash-master-regions.png)
## 📋 Table of Contents
+- [✨ Features](#-features)
- [🚀 Quick Start](#-quick-start)
- [📖 First Use](#-first-use)
- [🔧 Port Conflict Resolution](#-port-conflict-resolution)
@@ -52,31 +47,14 @@ Throughout the entire development process, I didn't write a single line of code
| 🌐 **Domain Analysis** | View traffic, associated IPs, and connection count per domain |
| 🗺️ **IP Analysis** | ASN, geo-location, and associated domain display |
| 🚀 **Proxy Statistics** | Traffic distribution and connection count per proxy node |
+| 📱 **PWA Support** | Install as desktop app for native experience |
| 🌙 **Dark Mode** | Light / Dark / System theme support |
| 🌍 **i18n Support** | English / Chinese seamless switching |
| 🔄 **Multi-Backend** | Monitor multiple OpenClash backend instances simultaneously |
## 🚀 Quick Start
-### Option 1: One-Click Setup Script (Recommended)
-
-The easiest way - automatically detects port conflicts and configures:
-
-```bash
-# Download and run
-curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
-
-# Or use wget
-wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
-```
-
-The script will automatically:
-- ✅ Check if default ports (3000/3001/3002) are in use
-- ✅ Suggest available alternative ports
-- ✅ Create configuration file
-- ✅ Start the service
-
-### Option 2: Docker Compose (Manual)
+### Option 1: Docker Compose (Recommended)
Create a `docker-compose.yml` file:
@@ -87,15 +65,15 @@ services:
container_name: clash-master
restart: unless-stopped
ports:
- - "3000:3000" # Web UI
- - "3001:3001" # API
- - "3002:3002" # WebSocket
+ - "3000:3000" # Web UI
+ - "3001:3001" # API
+ - "3002:3002" # WebSocket
volumes:
- ./data:/app/data
environment:
- NODE_ENV=production
- API_PORT=3001
- - WS_PORT=3002
+ - COLLECTOR_WS_PORT=3002
- DB_PATH=/app/data/stats.db
```
@@ -105,7 +83,7 @@ Then run:
docker compose up -d
```
-Open `http://localhost:3000` to get started.
+Open <http://localhost:3000> to get started.
### Option 2: Docker Run
@@ -120,9 +98,28 @@ docker run -d \
foru17/clash-master:latest
```
-Open `http://localhost:3000` to get started.
+Open <http://localhost:3000> to get started.
+
+### Option 3: One-Click Script
-### Option 3: Source Code
+Automatically detects port conflicts and configures everything:
+
+```bash
+# Using curl
+curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+
+# Or using wget
+wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+```
+
+The script will automatically:
+
+- ✅ Download `docker-compose.yml`
+- ✅ Check if default ports (3000/3001/3002) are in use
+- ✅ Suggest available alternative ports
+- ✅ Create configuration file and start the service
+
+### Option 4: Source Code
```bash
# 1. Clone the repository
@@ -132,12 +129,12 @@ cd clash-master
# 2. Install dependencies
pnpm install
-# 3. Start services
-./start.sh
-
-# 4. Open http://localhost:3000 to configure
+# 3. Start development services
+pnpm dev
```
+Open <http://localhost:3000> to configure.
+
## 📖 First Use
![First Use](./assets/clash-master-setup.png)
@@ -158,23 +155,9 @@ pnpm install
If you see "port already in use" error, here are the solutions:
-### Solution 1: Use One-Click Script (Easiest)
+### Solution 1: Use .env File
-```bash
-./setup.sh
-```
-
-The script will automatically detect and suggest available ports.
-
-### Solution 2: Use .env File
-
-Create a `.env` file:
-
-```bash
-cp .env.example .env
-```
-
-Modify ports to your preferred values:
+Create a `.env` file in the same directory as `docker-compose.yml`:
```env
WEB_EXTERNAL_PORT=8080 # Change Web UI port
@@ -189,19 +172,27 @@ docker compose down
docker compose up -d
```
-Now access http://localhost:8080
+Now access <http://localhost:8080>
-### Solution 3: Directly modify docker-compose.yml
+### Solution 2: Directly Modify docker-compose.yml
```yaml
ports:
- - "8080:3000" # External 8080 → Internal 3000
- - "8081:3001" # External 8081 → Internal 3001
- - "8082:3002" # External 8082 → Internal 3002
+ - "8080:3000" # External 8080 → Internal 3000
+ - "8081:3001" # External 8081 → Internal 3001
+ - "8082:3002" # External 8082 → Internal 3002
environment:
- - NEXT_PUBLIC_WS_PORT=8082 # Tell frontend to use 8082
+ - NEXT_PUBLIC_WS_PORT=8082 # Tell frontend to use 8082
```
+### Solution 3: Use One-Click Script
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+```
+
+The script will automatically detect and suggest available ports.
+
## 🐳 Docker Configuration
### Ports
@@ -212,6 +203,10 @@ environment:
| 3001 | API | ✅ | REST API port |
| 3002 | WebSocket | ✅ | Real-time data transmission |
+### Multi-Architecture Support
+
+Docker images support both `linux/amd64` and `linux/arm64`.
+
### Data Persistence
Data is stored in `/app/data` inside the container. Mount it to host to prevent data loss:
@@ -229,39 +224,16 @@ docker compose pull
docker compose up -d
```
-> 💡 New images are automatically built and pushed to [Docker Hub](https://hub.docker.com/r/foru17/clash-master) on every push to `main` or new tag.
-
-## 📁 Project Structure
-
-```
-clash-master/
-├── docker-compose.yml # Docker Compose config
-├── Dockerfile # Docker image build
-├── docker-start.sh # Docker startup script
-├── start.sh # Source startup script
-├── assets/ # Screenshots and icons
-├── apps/
-│ ├── collector/ # Data collection service (Node.js + WebSocket)
-│ └── web/ # Next.js frontend app
-└── packages/
- └── shared/ # Shared types and utilities
-```
-
## ❓ FAQ
### Q: "Port already in use" error?
-**A:** Use the one-click setup script, it will automatically detect and suggest available ports:
-
-```bash
-./setup.sh
-```
-
-Or manually modify ports in `.env` file.
+**A:** See [Port Conflict Resolution](#-port-conflict-resolution) above. The simplest approach is to create a `.env` file with custom ports.
### Q: Cannot access after changing ports?
**A:** Make sure three things:
+
1. Ports are modified in `.env` file
2. Service is restarted: `docker compose restart`
3. You're using the new port (e.g., `http://localhost:8080`)
@@ -269,6 +241,7 @@ Or manually modify ports in `.env` file.
### Q: Failed to connect to OpenClash?
**A:** Check the following:
+
1. Is "External Control" enabled in OpenClash?
2. Is the OpenClash address correct? (Format: `IP:Port`)
3. If Secret is configured, is the Token correct?
@@ -277,6 +250,7 @@ Or manually modify ports in `.env` file.
### Q: How to view service logs?
**A:**
+
```bash
# View all logs
docker logs -f clash-master
@@ -296,17 +270,31 @@ cp -r ./data ./data-backup-$(date +%Y%m%d)
### Q: How to clean up historical data?
**A:**
-1. Click "Backend Config" at the bottom of the left sidebar
+
+1. Click "Settings" at the bottom of the left sidebar
2. Switch to the "Database" tab
3. Select cleanup range: 1 day / 7 days / 30 days / All
-### Q: Support ARM architecture?
+## 📁 Project Structure
-**A:** Docker images support `linux/amd64` and `linux/arm64`.
+```
+clash-master/
+├── docker-compose.yml # Docker Compose config
+├── Dockerfile # Docker image build
+├── setup.sh # One-click setup script
+├── docker-start.sh # Docker container startup script
+├── start.sh # Source code dev startup script
+├── assets/ # Screenshots and icons
+├── apps/
+│ ├── collector/ # Data collection service (Node.js + WebSocket)
+│ └── web/ # Next.js frontend app
+└── packages/
+ └── shared/ # Shared types and utilities
+```
## 🛠️ Tech Stack
-- **Frontend**: [Next.js 15](https://nextjs.org/) + [React 19](https://react.dev/) + [TypeScript](https://www.typescriptlang.org/)
+- **Frontend**: [Next.js 16](https://nextjs.org/) + [React 19](https://react.dev/) + [TypeScript](https://www.typescriptlang.org/)
- **Styling**: [Tailwind CSS](https://tailwindcss.com/) + [shadcn/ui](https://ui.shadcn.com/)
- **Charts**: [Recharts](https://recharts.org/)
- **i18n**: [next-intl](https://next-intl-docs.vercel.app/)
diff --git a/README.md b/README.md
index c17f8af..04822b5 100644
--- a/README.md
+++ b/README.md
@@ -23,6 +23,8 @@
</p>
![Clash Master Overview](./assets/clash-master-overview.png)
+![Clash Master Rules](./assets/clash-master-rules.png)
+![Clash Master Regions](./assets/clash-master-regions.png)
## 📋 目录
@@ -37,26 +39,7 @@
## 🚀 快速开始
-### 方式一:一键脚本(推荐)
-
-最简单的方式,自动检测端口冲突并配置:
-
-```bash
-# 下载脚本
-curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
-
-# 或使用 wget
-wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
-```
-
-脚本会自动:
-
-- ✅ 检测默认端口(3000/3001/3002)是否被占用
-- ✅ 提供可用的替代端口
-- ✅ 创建配置文件
-- ✅ 启动服务
-
-### 方式二:Docker Compose(手动)
+### 方式一:Docker Compose(推荐)
创建 `docker-compose.yml`:
@@ -87,24 +70,7 @@ docker compose up -d
访问 <http://localhost:3000>
-### 方式三:使用 .env 配置文件
-
-适合需要自定义端口的场景:
-
-```bash
-# 1. 下载配置文件
-curl -O https://raw.githubusercontent.com/foru17/clash-master/main/.env.example
-curl -O https://raw.githubusercontent.com/foru17/clash-master/main/docker-compose.yml
-
-# 2. 重命名为 .env 并编辑
-mv .env.example .env
-# 修改 .env 中的端口
-
-# 3. 启动
-docker compose up -d
-```
-
-### 方式四:Docker 直接运行
+### 方式二:Docker 直接运行
```bash
docker run -d \
@@ -117,6 +83,43 @@ docker run -d \
foru17/clash-master:latest
```
+访问 <http://localhost:3000>
+
+### 方式三:一键脚本
+
+自动检测端口冲突并配置,适合不熟悉 Docker 的用户:
+
+```bash
+# 使用 curl
+curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+
+# 或使用 wget
+wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+```
+
+脚本会自动:
+
+- ✅ 下载 `docker-compose.yml`
+- ✅ 检测默认端口(3000/3001/3002)是否被占用
+- ✅ 提供可用的替代端口
+- ✅ 创建配置文件并启动服务
+
+### 方式四:源码运行
+
+```bash
+# 1. 克隆仓库
+git clone https://github.com/foru17/clash-master.git
+cd clash-master
+
+# 2. 安装依赖
+pnpm install
+
+# 3. 启动开发服务
+pnpm dev
+```
+
+访问 <http://localhost:3000>
+
## 📖 首次使用
![首次使用](./assets/clash-master-setup.png)
@@ -137,23 +140,9 @@ docker run -d \
如果看到错误提示端口已被占用,有以下几种解决方案:
-### 方案 1:使用一键脚本(最简单)
+### 方案 1:使用 .env 文件
-```bash
-./setup.sh
-```
-
-脚本会自动检测并提供可用的端口。
-
-### 方案 2:使用 .env 文件
-
-创建 `.env` 文件:
-
-```bash
-cp .env.example .env
-```
-
-修改端口为你想要的值:
+创建 `.env` 文件(与 `docker-compose.yml` 同目录):
```env
WEB_EXTERNAL_PORT=8080 # 修改 Web UI 端口
@@ -170,7 +159,7 @@ docker compose up -d
现在访问 <http://localhost:8080>
-### 方案 3:直接修改 docker-compose.yml
+### 方案 2:直接修改 docker-compose.yml
```yaml
ports:
@@ -181,6 +170,14 @@ environment:
- NEXT_PUBLIC_WS_PORT=8082 # 告诉前端使用 8082
```
+### 方案 3:使用一键脚本
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+```
+
+脚本会自动检测并提供可用的端口。
+
## 🐳 Docker 配置
### 端口说明
@@ -191,6 +188,10 @@ environment:
| 3001 | API 接口 | ✅ | REST API 端口 |
| 3002 | WebSocket | ✅ | 实时数据传输 |
+### 多架构支持
+
+Docker 镜像同时支持 `linux/amd64` 和 `linux/arm64`。
+
### 数据持久化
数据默认存储在容器内的 `/app/data` 目录,建议映射到宿主机:
@@ -212,13 +213,7 @@ docker compose up -d
### Q: 提示 "端口已被占用" 怎么办?
-**A:** 使用一键配置脚本,它会自动检测并提供可用端口:
-
-```bash
-./setup.sh
-```
-
-或者手动修改 `.env` 文件中的端口。
+**A:** 参考上方[端口冲突解决](#-端口冲突解决)部分。最简单的方式是创建 `.env` 文件修改端口。
### Q: 修改端口后无法访问?
@@ -261,24 +256,19 @@ cp -r ./data ./data-backup-$(date +%Y%m%d)
**A:**
-1. 点击左侧边栏底部的「后端配置」
+1. 点击左侧边栏底部的「设置」
2. 切换到「数据库」标签页
3. 选择清理范围:1天前 / 7天前 / 30天前 / 全部
-### Q: 支持 ARM 架构吗?
-
-**A:** 目前 Docker 镜像支持 `linux/amd64` 和 `linux/arm64`。
-
## 📁 项目结构
```
clash-master/
├── docker-compose.yml # Docker Compose 配置
├── Dockerfile # Docker 镜像构建
-├── setup.sh # 一键配置脚本 ⭐
-├── docker-start.sh # Docker 启动脚本
-├── start.sh # 源码启动脚本
-├── .env.example # 环境变量示例
+├── setup.sh # 一键配置脚本
+├── docker-start.sh # Docker 容器启动脚本
+├── start.sh # 源码开发启动脚本
├── assets/ # 预览图和图标
├── apps/
│ ├── collector/ # 数据收集服务(Node.js + WebSocket)
@@ -290,8 +280,10 @@ clash-master/
## 🛠️ 技术栈
- **前端**: Next.js 16 + React 19 + TypeScript + Tailwind CSS
-- **数据收集**: Node.js + WebSocket + SQLite
+- **UI 组件**: shadcn/ui
+- **数据收集**: Node.js + Fastify + WebSocket + SQLite
- **可视化**: Recharts + D3.js
+- **国际化**: next-intl(中/英)
- **部署**: Docker + Docker Compose
## 📄 许可证
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index 05da53f..8967158 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -50,8 +50,8 @@ export class APIServer {
}
const summary = this.db.getSummary(backendId);
- const topDomains = this.db.getTopDomains(backendId, 1000);
- const topIPs = this.db.getTopIPs(backendId, 1000);
+ const topDomains = this.db.getTopDomains(backendId, 10);
+ const topIPs = this.db.getTopIPs(backendId, 10);
const proxyStats = this.db.getProxyStats(backendId);
const ruleStats = this.db.getRuleStats(backendId);
const hourlyStats = this.db.getHourlyStats(backendId, 24);
@@ -86,28 +86,52 @@ export class APIServer {
return this.db.getGlobalSummary();
});
- // Get domain statistics for a specific backend
+ // Get domain statistics for a specific backend (paginated)
app.get('/api/stats/domains', async (request, reply) => {
const backendId = getBackendId(request);
-
+
if (backendId === null) {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- const { limit = 50 } = request.query as { limit?: string };
- return this.db.getDomainStats(backendId, parseInt(limit as string) || 50);
+ const { offset, limit, sortBy, sortOrder, search } = request.query as {
+ offset?: string;
+ limit?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+ };
+ return this.db.getDomainStatsPaginated(backendId, {
+ offset: offset ? parseInt(offset) || 0 : 0,
+ limit: limit ? parseInt(limit) || 50 : 50,
+ sortBy,
+ sortOrder,
+ search,
+ });
});
- // Get IP statistics for a specific backend
+ // Get IP statistics for a specific backend (paginated)
app.get('/api/stats/ips', async (request, reply) => {
const backendId = getBackendId(request);
-
+
if (backendId === null) {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- const { limit = 50 } = request.query as { limit?: string };
- return this.db.getIPStats(backendId, parseInt(limit as string) || 50);
+ const { offset, limit, sortBy, sortOrder, search } = request.query as {
+ offset?: string;
+ limit?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+ };
+ return this.db.getIPStatsPaginated(backendId, {
+ offset: offset ? parseInt(offset) || 0 : 0,
+ limit: limit ? parseInt(limit) || 50 : 50,
+ sortBy,
+ sortOrder,
+ search,
+ });
});
// Get per-proxy traffic breakdown for a specific domain
@@ -219,6 +243,65 @@ export class APIServer {
return this.db.getRuleStats(backendId);
});
+ // Get domains for a specific rule
+ app.get('/api/stats/rules/domains', async (request, reply) => {
+ const backendId = getBackendId(request);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule } = request.query as { rule?: string };
+ if (!rule) {
+ return reply.status(400).send({ error: 'Rule parameter is required' });
+ }
+
+ return this.db.getRuleDomains(backendId, rule);
+ });
+
+ // Get IPs for a specific rule
+ app.get('/api/stats/rules/ips', async (request, reply) => {
+ const backendId = getBackendId(request);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule } = request.query as { rule?: string };
+ if (!rule) {
+ return reply.status(400).send({ error: 'Rule parameter is required' });
+ }
+
+ return this.db.getRuleIPs(backendId, rule);
+ });
+
+ // Get rule chain flow for a specific rule
+ app.get('/api/stats/rules/chain-flow', async (request, reply) => {
+ const backendId = getBackendId(request);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule } = request.query as { rule?: string };
+ if (!rule) {
+ return reply.status(400).send({ error: 'Rule parameter is required' });
+ }
+
+ return this.db.getRuleChainFlow(backendId, rule);
+ });
+
+ // Get all rule chain flows merged into unified DAG
+ app.get('/api/stats/rules/chain-flow-all', async (request, reply) => {
+ const backendId = getBackendId(request);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ return this.db.getAllRuleChainFlows(backendId);
+ });
+
// Get rule to proxy mapping for a specific backend
app.get('/api/stats/rule-proxy-map', async (request, reply) => {
const backendId = getBackendId(request);
diff --git a/apps/collector/src/batch-writer.ts b/apps/collector/src/batch-writer.ts
deleted file mode 100644
index d0bbce6..0000000
--- a/apps/collector/src/batch-writer.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { StatsDatabase } from './db.js';
-import { GeoIPService } from './geo-service.js';
-
-export interface TrafficUpdate {
- domain: string;
- ip: string;
- chain: string;
- chains: string[];
- upload: number;
- download: number;
-}
-
-interface GeoIPResult {
- ip: string;
- geo: {
- country: string;
- country_name: string;
- continent: string;
- } | null;
- upload: number;
- download: number;
-}
-
-interface BatchConfig {
- // Flush interval in milliseconds
- flushIntervalMs: number;
-
- // Max buffer size before forced flush
- maxBufferSize: number;
-
- // Whether to write connection_logs (can be disabled for minimal retention)
- writeConnectionLogs: boolean;
-}
-
-const DEFAULT_CONFIG: BatchConfig = {
- flushIntervalMs: 1000, // Flush every 1 second
- maxBufferSize: 1000, // Force flush at 1000 entries
- writeConnectionLogs: true, // Enable by default
-};
-
-/**
- * Optimized batch writer for traffic data
- *
- * Key optimizations:
- * 1. In-memory buffering to reduce SQLite transactions
- * 2. Aggregation of same-key updates within batch window
- * 3. Single transaction for all stats tables
- * 4. Optional connection_logs for storage efficiency
- */
-export class BatchWriter {
- private db: StatsDatabase;
- private geoService?: GeoIPService;
- private config: BatchConfig;
-
- // Buffer storage
- private buffer: Map<string, TrafficUpdate & { count: number; firstSeen: number }> = new Map();
- private geoQueue: GeoIPResult[] = [];
- private connectionLogBuffer: TrafficUpdate[] = [];
-
- // Flush management
- private flushTimer: NodeJS.Timeout | null = null;
- private lastFlushTime = 0;
- private isFlushing = false;
-
- // Metrics
- private totalBuffered = 0;
- private totalFlushed = 0;
-
- constructor(
- db: StatsDatabase,
- geoService?: GeoIPService,
- config: Partial<BatchConfig> = {}
- ) {
- this.db = db;
- this.geoService = geoService;
- this.config = { ...DEFAULT_CONFIG, ...config };
- this.startFlushTimer();
- }
-
- /**
- * Add a traffic update to the buffer
- * Returns immediately, data is written on next flush
- */
- add(backendId: number, update: TrafficUpdate): void {
- // Create aggregation key (domain + ip + chain for granular tracking)
- const key = `${backendId}:${update.domain}:${update.ip}:${update.chain}`;
- const now = Date.now();
-
- const existing = this.buffer.get(key);
- if (existing) {
- // Aggregate with existing entry
- existing.upload += update.upload;
- existing.download += update.download;
- existing.count += 1;
- } else {
- // New entry
- this.buffer.set(key, {
- ...update,
- count: 1,
- firstSeen: now,
- });
- }
-
- // Also buffer for connection_logs if enabled
- if (this.config.writeConnectionLogs) {
- this.connectionLogBuffer.push(update);
- }
-
- this.totalBuffered++;
-
- // Check if we need to force flush
- if (this.buffer.size >= this.config.maxBufferSize) {
- this.flush(backendId);
- }
- }
-
- /**
- * Queue GeoIP result for batch country stats update
- */
- queueGeoIP(ip: string, geo: GeoIPResult['geo'], upload: number, download: number): void {
- this.geoQueue.push({ ip, geo, upload, download });
- }
-
- /**
- * Force flush all buffered data to database
- */
- async flush(backendId: number): Promise<void> {
- if (this.isFlushing || this.buffer.size === 0) {
- return;
- }
-
- this.isFlushing = true;
- const startTime = Date.now();
-
- try {
- // Copy buffers and clear immediately to allow new data during write
- const updates = Array.from(this.buffer.values());
- const geoResults = [...this.geoQueue];
- const connectionLogs = this.config.writeConnectionLogs
- ? [...this.connectionLogBuffer]
- : [];
-
- this.buffer.clear();
- this.geoQueue = [];
- if (this.config.writeConnectionLogs) {
- this.connectionLogBuffer = [];
- }
-
- // Perform batch write in single transaction
- this.db.batchUpdateTrafficStats(backendId, updates.map(u => ({
- domain: u.domain,
- ip: u.ip,
- chain: u.chain,
- chains: u.chains,
- upload: u.upload,
- download: u.download,
- })));
-
- // Process GeoIP results
- for (const result of geoResults) {
- if (result.geo) {
- this.db.updateCountryStats(
- backendId,
- result.geo.country,
- result.geo.country_name,
- result.geo.continent,
- result.upload,
- result.download
- );
- }
- }
-
- // Write connection logs (may be skipped if disabled)
- if (connectionLogs.length > 0) {
- this.db.batchInsertConnectionLogs(backendId, connectionLogs);
- }
-
- this.totalFlushed += updates.length;
-
- const duration = Date.now() - startTime;
- if (duration > 100) {
- console.log(`[BatchWriter] Flushed ${updates.length} updates in ${duration}ms`);
- }
- } catch (err) {
- console.error('[BatchWriter] Flush failed:', err);
- // TODO: Implement retry or error recovery
- } finally {
- this.isFlushing = false;
- this.lastFlushTime = Date.now();
- }
- }
-
- /**
- * Get current buffer statistics
- */
- getStats(): { buffered: number; flushed: number; pendingFlush: number } {
- return {
- buffered: this.totalBuffered,
- flushed: this.totalFlushed,
- pendingFlush: this.buffer.size,
- };
- }
-
- /**
- * Stop the flush timer and cleanup
- */
- stop(): void {
- if (this.flushTimer) {
- clearInterval(this.flushTimer);
- this.flushTimer = null;
- }
- }
-
- /**
- * Start the automatic flush timer
- */
- private startFlushTimer(): void {
- this.flushTimer = setInterval(() => {
- // Timer check is done at backend level
- }, this.config.flushIntervalMs);
- }
-}
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index 5834d08..700f62b 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -1,5 +1,3 @@
-"use client";
-
import WebSocket from 'ws';
import type { ConnectionsData } from '@clashmaster/shared';
import { StatsDatabase } from './db.js';
@@ -18,6 +16,8 @@ interface TrafficUpdate {
ip: string;
chain: string;
chains: string[];
+ rule: string;
+ rulePayload: string;
upload: number;
download: number;
}
@@ -169,19 +169,17 @@ class BatchBuffer {
try {
db.batchUpdateTrafficStats(backendId, updates);
- // Process geo results
- for (const result of geoResults) {
- if (result.geo) {
- db.updateCountryStats(
- backendId,
- result.geo.country,
- result.geo.country_name,
- result.geo.continent,
- result.upload,
- result.download
- );
- }
- }
+ // Process geo results in batch
+ const countryUpdates = geoResults
+ .filter((r): r is GeoIPResult & { geo: NonNullable<GeoIPResult['geo']> } => r.geo !== null)
+ .map(r => ({
+ country: r.geo.country,
+ countryName: r.geo.country_name,
+ continent: r.geo.continent,
+ upload: r.upload,
+ download: r.download,
+ }));
+ db.batchUpdateCountryStats(backendId, countryUpdates);
} catch (err) {
console.error(`[Collector:${backendId}] Batch write failed:`, err);
}
@@ -209,6 +207,8 @@ interface TrackedConnection {
domain: string;
ip: string;
chains: string[];
+ rule: string;
+ rulePayload: string;
lastUpload: number;
lastDownload: number;
totalUpload: number;
@@ -229,15 +229,16 @@ export function createCollector(
let lastBroadcastTime = 0;
const broadcastThrottleMs = 500;
let flushInterval: NodeJS.Timeout | null = null;
-
- // Start batch flush interval (every 1000ms)
+ const FLUSH_INTERVAL_MS = parseInt(process.env.FLUSH_INTERVAL_MS || '2000');
+
+ // Start batch flush interval
flushInterval = setInterval(() => {
const stats = batchBuffer.flush(db, geoService, id);
-
+
if (batchBuffer.shouldLog() && (stats.domains > 0 || stats.rules > 0)) {
console.log(`[Collector:${id}] Active: ${activeConnections.size}, Domains: ${stats.domains}, Rules: ${stats.rules}`);
}
- }, 1000);
+ }, FLUSH_INTERVAL_MS);
const collector = new OpenClashCollector(id, {
url,
@@ -281,6 +282,8 @@ export function createCollector(
const domain = metadata.host || metadata.sniffHost || '';
const ip = metadata.destinationIP || '';
const chains = Array.isArray(conn.chains) ? conn.chains : ['DIRECT'];
+ const rule = conn.rule || 'Match';
+ const rulePayload = conn.rulePayload || '';
const existing = activeConnections.get(conn.id);
@@ -291,6 +294,8 @@ export function createCollector(
domain,
ip,
chains,
+ rule,
+ rulePayload,
lastUpload: conn.upload,
lastDownload: conn.download,
totalUpload: conn.upload,
@@ -304,6 +309,8 @@ export function createCollector(
ip,
chain: chains[0] || 'DIRECT',
chains,
+ rule,
+ rulePayload,
upload: conn.upload,
download: conn.download,
});
@@ -342,6 +349,8 @@ export function createCollector(
ip: existing.ip,
chain: existing.chains[0] || 'DIRECT',
chains: existing.chains,
+ rule: existing.rule || 'Match',
+ rulePayload: existing.rulePayload || '',
upload: uploadDelta,
download: downloadDelta,
});
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index 8bbc3f8..b4a9f40 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -14,6 +14,8 @@ export interface TrafficUpdate {
ip: string;
chain: string;
chains: string[];
+ rule: string;
+ rulePayload: string;
upload: number;
download: number;
}
@@ -41,6 +43,14 @@ export class StatsDatabase {
}
private init() {
+ // Enable WAL mode and performance PRAGMAs for reduced disk IO
+ this.db.pragma('journal_mode = WAL');
+ this.db.pragma('synchronous = NORMAL');
+ this.db.pragma('wal_autocheckpoint = 1000');
+ this.db.pragma('temp_store = MEMORY');
+ this.db.pragma('cache_size = -16000'); // 16MB page cache
+ this.db.pragma('busy_timeout = 5000');
+
// Domain statistics - aggregated by domain per backend
this.db.exec(`
CREATE TABLE IF NOT EXISTS domain_stats (
@@ -71,6 +81,7 @@ export class StatsDatabase {
asn TEXT,
geoip TEXT,
chains TEXT,
+ rules TEXT,
PRIMARY KEY (backend_id, ip),
FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
);
@@ -186,6 +197,52 @@ export class StatsDatabase {
);
`);
+ // Rule-specific cross-reference tables for accurate per-rule traffic
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS rule_chain_traffic (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ chain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule, chain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_chain_traffic ON rule_chain_traffic(backend_id, rule);`);
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS rule_domain_traffic (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule, domain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_domain_traffic ON rule_domain_traffic(backend_id, rule);`);
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS rule_ip_traffic (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ ip TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule, ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_rule_ip_traffic ON rule_ip_traffic(backend_id, rule);`);
+
// Create indexes
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_domain_stats_backend ON domain_stats(backend_id);`);
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_domain_stats_traffic ON domain_stats(total_download + total_upload);`);
@@ -339,6 +396,7 @@ export class StatsDatabase {
asn TEXT,
geoip TEXT,
chains TEXT,
+ rules TEXT,
PRIMARY KEY (backend_id, ip),
FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
);
@@ -499,8 +557,9 @@ export class StatsDatabase {
// Only process if there's actual traffic
if (update.upload === 0 && update.download === 0) return;
- // Get the initial rule (last element in chains array) and final proxy (first element)
- const initialRule = update.chains.length > 0 ? update.chains[update.chains.length - 1] : 'DIRECT';
+ // Get rule name from chains (friendly name) or fallback to rule + rulePayload
+ const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
+ update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
const transaction = this.db.transaction(() => {
@@ -538,15 +597,15 @@ export class StatsDatabase {
upload: update.upload,
download: update.download,
timestamp,
- rule: initialRule,
+ rule: ruleName,
chain: update.chain
});
}
// Update IP stats with backend_id
const ipStmt = this.db.prepare(`
- INSERT INTO ip_stats (backend_id, ip, domains, total_upload, total_download, total_connections, last_seen, chains)
- VALUES (@backendId, @ip, @domain, @upload, @download, 1, @timestamp, @chain)
+ INSERT INTO ip_stats (backend_id, ip, domains, total_upload, total_download, total_connections, last_seen, chains, rules)
+ VALUES (@backendId, @ip, @domain, @upload, @download, 1, @timestamp, @chain, @rule)
ON CONFLICT(backend_id, ip) DO UPDATE SET
domains = CASE
WHEN ip_stats.domains IS NULL THEN @domain
@@ -561,8 +620,15 @@ export class StatsDatabase {
WHEN ip_stats.chains IS NULL THEN @chain
WHEN INSTR(ip_stats.chains, @chain) > 0 THEN ip_stats.chains
ELSE ip_stats.chains || ',' || @chain
+ END,
+ rules = CASE
+ WHEN ip_stats.rules IS NULL THEN @rule
+ WHEN INSTR(ip_stats.rules, @rule) > 0 THEN ip_stats.rules
+ ELSE ip_stats.rules || ',' || @rule
END
`);
+ // Store full chain path (joined with > for clarity)
+ const fullChain = update.chains.join(' > ');
ipStmt.run({
backendId,
ip: update.ip,
@@ -570,7 +636,8 @@ export class StatsDatabase {
upload: update.upload,
download: update.download,
timestamp,
- chain: update.chain
+ chain: fullChain,
+ rule: ruleName
});
// Update proxy stats with backend_id
@@ -604,13 +671,72 @@ export class StatsDatabase {
`);
ruleStmt.run({
backendId,
- rule: initialRule,
+ rule: ruleName,
finalProxy,
upload: update.upload,
download: update.download,
timestamp
});
+ // Update rule_chain_traffic (all connections have a chain)
+ const ruleChainStmt = this.db.prepare(`
+ INSERT INTO rule_chain_traffic (backend_id, rule, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @chain, @upload, @download, 1, @timestamp)
+ ON CONFLICT(backend_id, rule, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + 1,
+ last_seen = @timestamp
+ `);
+ ruleChainStmt.run({
+ backendId,
+ rule: ruleName,
+ chain: fullChain,
+ upload: update.upload,
+ download: update.download,
+ timestamp
+ });
+
+ // Update rule_domain_traffic (only when domain is known)
+ if (domainName !== 'unknown') {
+ const ruleDomainStmt = this.db.prepare(`
+ INSERT INTO rule_domain_traffic (backend_id, rule, domain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @domain, @upload, @download, 1, @timestamp)
+ ON CONFLICT(backend_id, rule, domain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + 1,
+ last_seen = @timestamp
+ `);
+ ruleDomainStmt.run({
+ backendId,
+ rule: ruleName,
+ domain: domainName,
+ upload: update.upload,
+ download: update.download,
+ timestamp
+ });
+ }
+
+ // Update rule_ip_traffic (all connections have an IP)
+ const ruleIPStmt = this.db.prepare(`
+ INSERT INTO rule_ip_traffic (backend_id, rule, ip, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @ip, @upload, @download, 1, @timestamp)
+ ON CONFLICT(backend_id, rule, ip) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + 1,
+ last_seen = @timestamp
+ `);
+ ruleIPStmt.run({
+ backendId,
+ rule: ruleName,
+ ip: update.ip,
+ upload: update.upload,
+ download: update.download,
+ timestamp
+ });
+
// Update rule-proxy mapping with backend_id
if (update.chains.length > 1) {
const rule = update.chains[update.chains.length - 1];
@@ -663,13 +789,19 @@ export class StatsDatabase {
const domainMap = new Map<string, TrafficUpdate & { count: number }>();
const ipMap = new Map<string, TrafficUpdate & { count: number }>();
const chainMap = new Map<string, { chains: string[]; upload: number; download: number; count: number }>();
- const ruleProxyMap = new Map<string, { rule: string; proxy: string; count: number }>();
+ const ruleProxyMap = new Map<string, { rule: string; proxy: string; upload: number; download: number; count: number }>();
const hourlyMap = new Map<string, { upload: number; download: number; connections: number }>();
+ const ruleChainMap = new Map<string, { rule: string; chain: string; upload: number; download: number; count: number }>();
+ const ruleDomainMap = new Map<string, { rule: string; domain: string; upload: number; download: number; count: number }>();
+ const ruleIPMap = new Map<string, { rule: string; ip: string; upload: number; download: number; count: number }>();
for (const update of updates) {
if (update.upload === 0 && update.download === 0) continue;
- const initialRule = update.chains.length > 0 ? update.chains[update.chains.length - 1] : 'DIRECT';
+ // Use the last element of chains as the rule name (friendly name from Clash config)
+ // e.g., "漏网之鱼", "微软服务", "TikTok"
+ const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
+ update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
// Aggregate domain stats
@@ -693,7 +825,7 @@ export class StatsDatabase {
existingIp.download += update.download;
existingIp.count++;
} else {
- ipMap.set(ipKey, { ...update, count: 1 });
+ ipMap.set(ipKey, { ...update, rule: ruleName, count: 1 });
}
// Aggregate chain stats
@@ -713,12 +845,14 @@ export class StatsDatabase {
}
// Aggregate rule stats
- const ruleKey = `${initialRule}:${finalProxy}`;
+ const ruleKey = `${ruleName}:${finalProxy}`;
const existingRule = ruleProxyMap.get(ruleKey);
if (existingRule) {
+ existingRule.upload += update.upload;
+ existingRule.download += update.download;
existingRule.count++;
} else {
- ruleProxyMap.set(ruleKey, { rule: initialRule, proxy: finalProxy, count: 1 });
+ ruleProxyMap.set(ruleKey, { rule: ruleName, proxy: finalProxy, upload: update.upload, download: update.download, count: 1 });
}
// Aggregate hourly stats
@@ -729,12 +863,48 @@ export class StatsDatabase {
existingHour.download += update.download;
existingHour.connections++;
} else {
- hourlyMap.set(hourKey, {
- upload: update.upload,
- download: update.download,
- connections: 1
+ hourlyMap.set(hourKey, {
+ upload: update.upload,
+ download: update.download,
+ connections: 1
});
}
+
+ // Aggregate rule_chain_traffic
+ const fullChainForRule = update.chains.join(' > ');
+ const ruleChainKey = `${ruleName}:${fullChainForRule}`;
+ const existingRuleChain = ruleChainMap.get(ruleChainKey);
+ if (existingRuleChain) {
+ existingRuleChain.upload += update.upload;
+ existingRuleChain.download += update.download;
+ existingRuleChain.count++;
+ } else {
+ ruleChainMap.set(ruleChainKey, { rule: ruleName, chain: fullChainForRule, upload: update.upload, download: update.download, count: 1 });
+ }
+
+ // Aggregate rule_domain_traffic (only when domain exists)
+ if (update.domain) {
+ const ruleDomainKey = `${ruleName}:${update.domain}`;
+ const existingRuleDomain = ruleDomainMap.get(ruleDomainKey);
+ if (existingRuleDomain) {
+ existingRuleDomain.upload += update.upload;
+ existingRuleDomain.download += update.download;
+ existingRuleDomain.count++;
+ } else {
+ ruleDomainMap.set(ruleDomainKey, { rule: ruleName, domain: update.domain, upload: update.upload, download: update.download, count: 1 });
+ }
+ }
+
+ // Aggregate rule_ip_traffic
+ const ruleIPKey = `${ruleName}:${update.ip}`;
+ const existingRuleIP = ruleIPMap.get(ruleIPKey);
+ if (existingRuleIP) {
+ existingRuleIP.upload += update.upload;
+ existingRuleIP.download += update.download;
+ existingRuleIP.count++;
+ } else {
+ ruleIPMap.set(ruleIPKey, { rule: ruleName, ip: update.ip, upload: update.upload, download: update.download, count: 1 });
+ }
}
// Execute batch upserts in a single transaction
@@ -766,7 +936,10 @@ export class StatsDatabase {
`);
for (const [key, data] of domainMap) {
- const initialRule = data.chains.length > 0 ? data.chains[data.chains.length - 1] : 'DIRECT';
+ const ruleName = data.chains.length > 1 ? data.chains[data.chains.length - 1] :
+ data.rulePayload ? `${data.rule}(${data.rulePayload})` : data.rule;
+ // Store full chain path (joined with > for clarity)
+ const fullChain = data.chains.join(' > ');
domainStmt.run({
backendId,
domain: data.domain,
@@ -775,15 +948,15 @@ export class StatsDatabase {
download: data.download,
count: data.count,
timestamp,
- rule: initialRule,
- chain: data.chain
+ rule: ruleName,
+ chain: fullChain
});
}
// IP stats
const ipStmt = this.db.prepare(`
- INSERT INTO ip_stats (backend_id, ip, domains, total_upload, total_download, total_connections, last_seen, chains)
- VALUES (@backendId, @ip, @domain, @upload, @download, @count, @timestamp, @chain)
+ INSERT INTO ip_stats (backend_id, ip, domains, total_upload, total_download, total_connections, last_seen, chains, rules)
+ VALUES (@backendId, @ip, @domain, @upload, @download, @count, @timestamp, @chain, @rule)
ON CONFLICT(backend_id, ip) DO UPDATE SET
domains = CASE
WHEN ip_stats.domains IS NULL THEN @domain
@@ -798,10 +971,17 @@ export class StatsDatabase {
WHEN ip_stats.chains IS NULL THEN @chain
WHEN INSTR(ip_stats.chains, @chain) > 0 THEN ip_stats.chains
ELSE ip_stats.chains || ',' || @chain
+ END,
+ rules = CASE
+ WHEN ip_stats.rules IS NULL THEN @rule
+ WHEN INSTR(ip_stats.rules, @rule) > 0 THEN ip_stats.rules
+ ELSE ip_stats.rules || ',' || @rule
END
`);
for (const [key, data] of ipMap) {
+ // Store full chain path (joined with > for clarity)
+ const fullChain = data.chains.join(' > ');
ipStmt.run({
backendId,
ip: data.ip,
@@ -810,7 +990,8 @@ export class StatsDatabase {
download: data.download,
count: data.count,
timestamp,
- chain: data.chain
+ chain: fullChain,
+ rule: data.rule
});
}
@@ -839,9 +1020,11 @@ export class StatsDatabase {
// Rule stats
const ruleStmt = this.db.prepare(`
INSERT INTO rule_stats (backend_id, rule, final_proxy, total_upload, total_download, total_connections, last_seen)
- VALUES (@backendId, @rule, @proxy, 0, 0, @count, @timestamp)
+ VALUES (@backendId, @rule, @proxy, @upload, @download, @count, @timestamp)
ON CONFLICT(backend_id, rule) DO UPDATE SET
final_proxy = @proxy,
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
total_connections = total_connections + @count,
last_seen = @timestamp
`);
@@ -851,6 +1034,8 @@ export class StatsDatabase {
backendId,
rule: data.rule,
proxy: data.proxy,
+ upload: data.upload,
+ download: data.download,
count: data.count,
timestamp
});
@@ -890,6 +1075,75 @@ export class StatsDatabase {
});
}
+ // Rule chain traffic
+ const ruleChainStmt = this.db.prepare(`
+ INSERT INTO rule_chain_traffic (backend_id, rule, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @chain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, rule, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of ruleChainMap) {
+ ruleChainStmt.run({
+ backendId,
+ rule: data.rule,
+ chain: data.chain,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
+
+ // Rule domain traffic
+ const ruleDomainStmt = this.db.prepare(`
+ INSERT INTO rule_domain_traffic (backend_id, rule, domain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @domain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, rule, domain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of ruleDomainMap) {
+ ruleDomainStmt.run({
+ backendId,
+ rule: data.rule,
+ domain: data.domain,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
+
+ // Rule IP traffic
+ const ruleIPStmt = this.db.prepare(`
+ INSERT INTO rule_ip_traffic (backend_id, rule, ip, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @ip, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, rule, ip) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of ruleIPMap) {
+ ruleIPStmt.run({
+ backendId,
+ rule: data.rule,
+ ip: data.ip,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
+
// Batch insert into connection_logs for detailed analytics
// All records are preserved for accuracy
const logStmt = this.db.prepare(`
@@ -1192,6 +1446,31 @@ export class StatsDatabase {
stmt.run(backendId, country, countryName, continent, upload, download, upload, download);
}
+ // Batch update country stats - wraps all upserts in a single transaction
+ batchUpdateCountryStats(backendId: number, results: Array<{
+ country: string; countryName: string; continent: string;
+ upload: number; download: number;
+ }>): void {
+ if (results.length === 0) return;
+
+ const stmt = this.db.prepare(`
+ INSERT INTO country_stats (backend_id, country, country_name, continent, total_upload, total_download, total_connections, last_seen)
+ VALUES (?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)
+ ON CONFLICT(backend_id, country) DO UPDATE SET
+ total_upload = total_upload + ?,
+ total_download = total_download + ?,
+ total_connections = total_connections + 1,
+ last_seen = CURRENT_TIMESTAMP
+ `);
+
+ const tx = this.db.transaction(() => {
+ for (const r of results) {
+ stmt.run(backendId, r.country, r.countryName, r.continent, r.upload, r.download, r.upload, r.download);
+ }
+ });
+ tx();
+ }
+
// Get top domains for a specific backend
getTopDomains(backendId: number, limit = 10): DomainStats[] {
return this.getDomainStats(backendId, limit);
@@ -1202,6 +1481,155 @@ export class StatsDatabase {
return this.getIPStats(backendId, limit);
}
+ // Get domain stats with server-side pagination, sorting and search
+ getDomainStatsPaginated(backendId: number, opts: {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+ } = {}): { data: DomainStats[]; total: number } {
+ const offset = opts.offset ?? 0;
+ const limit = Math.min(opts.limit ?? 50, 200);
+ const sortOrder = opts.sortOrder === 'asc' ? 'ASC' : 'DESC';
+ const search = opts.search?.trim() || '';
+
+ const sortColumnMap: Record<string, string> = {
+ domain: 'domain',
+ totalDownload: 'total_download',
+ totalUpload: 'total_upload',
+ totalConnections: 'total_connections',
+ lastSeen: 'last_seen',
+ };
+ const sortColumn = sortColumnMap[opts.sortBy || 'totalDownload'] || 'total_download';
+
+ const whereClause = search
+ ? 'WHERE backend_id = ? AND domain LIKE ?'
+ : 'WHERE backend_id = ?';
+ const params: any[] = search
+ ? [backendId, `%${search}%`]
+ : [backendId];
+
+ const countStmt = this.db.prepare(
+ `SELECT COUNT(*) as total FROM domain_stats ${whereClause}`
+ );
+ const { total } = countStmt.get(...params) as { total: number };
+
+ const dataStmt = this.db.prepare(`
+ SELECT domain, total_upload as totalUpload, total_download as totalDownload,
+ total_connections as totalConnections, last_seen as lastSeen, ips, rules, chains
+ FROM domain_stats
+ ${whereClause}
+ ORDER BY ${sortColumn} ${sortOrder}
+ LIMIT ? OFFSET ?
+ `);
+ const rows = dataStmt.all(...params, limit, offset) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ const data = rows.map(row => ({
+ ...row,
+ ips: row.ips ? row.ips.split(',') : [],
+ rules: row.rules ? row.rules.split(',') : [],
+ chains: row.chains ? row.chains.split(',') : [],
+ })) as DomainStats[];
+
+ return { data, total };
+ }
+
+ // Get IP stats with server-side pagination, sorting and search
+ getIPStatsPaginated(backendId: number, opts: {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+ } = {}): { data: IPStats[]; total: number } {
+ const offset = opts.offset ?? 0;
+ const limit = Math.min(opts.limit ?? 50, 200);
+ const sortOrder = opts.sortOrder === 'asc' ? 'ASC' : 'DESC';
+ const search = opts.search?.trim() || '';
+
+ const sortColumnMap: Record<string, string> = {
+ ip: 'i.ip',
+ totalDownload: 'i.total_download',
+ totalUpload: 'i.total_upload',
+ totalConnections: 'i.total_connections',
+ lastSeen: 'i.last_seen',
+ };
+ const sortColumn = sortColumnMap[opts.sortBy || 'totalDownload'] || 'i.total_download';
+
+ const whereClause = search
+ ? 'WHERE i.backend_id = ? AND (i.ip LIKE ? OR i.domains LIKE ?)'
+ : 'WHERE i.backend_id = ?';
+ const params: any[] = search
+ ? [backendId, `%${search}%`, `%${search}%`]
+ : [backendId];
+
+ const countStmt = this.db.prepare(
+ `SELECT COUNT(*) as total FROM ip_stats i ${whereClause}`
+ );
+ const { total } = countStmt.get(...params) as { total: number };
+
+ const dataStmt = this.db.prepare(`
+ SELECT
+ i.ip,
+ i.domains,
+ i.total_upload as totalUpload,
+ i.total_download as totalDownload,
+ i.total_connections as totalConnections,
+ i.last_seen as lastSeen,
+ COALESCE(i.asn, g.asn) as asn,
+ CASE
+ WHEN g.country IS NOT NULL THEN
+ json_array(
+ g.country,
+ COALESCE(g.country_name, g.country),
+ COALESCE(g.city, ''),
+ COALESCE(g.as_name, '')
+ )
+ WHEN i.geoip IS NOT NULL THEN
+ json(i.geoip)
+ ELSE
+ NULL
+ END as geoIP,
+ i.chains
+ FROM ip_stats i
+ LEFT JOIN geoip_cache g ON i.ip = g.ip
+ ${whereClause}
+ ORDER BY ${sortColumn} ${sortOrder}
+ LIMIT ? OFFSET ?
+ `);
+ const rows = dataStmt.all(...params, limit, offset) as Array<{
+ ip: string;
+ domains: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ }>;
+
+ const data = rows.map(row => ({
+ ...row,
+ domains: row.domains ? row.domains.split(',') : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: row.chains ? row.chains.split(',') : [],
+ })) as IPStats[];
+
+ return { data, total };
+ }
+
// Get proxy stats for a specific backend
getProxyStats(backendId: number): ProxyStats[] {
const stmt = this.db.prepare(`
@@ -1496,6 +1924,309 @@ export class StatsDatabase {
})) as IPStats[];
}
+ // Get domains for a specific rule (by matching rule name in domain_stats.rules)
+ getRuleDomains(backendId: number, rule: string, limit = 50): DomainStats[] {
+ // Query rule_domain_traffic for accurate per-rule domain traffic, join domain_stats for ips/chains
+ const stmt = this.db.prepare(`
+ SELECT
+ rdt.domain,
+ rdt.total_upload as totalUpload,
+ rdt.total_download as totalDownload,
+ rdt.total_connections as totalConnections,
+ rdt.last_seen as lastSeen,
+ ds.ips,
+ ds.chains
+ FROM rule_domain_traffic rdt
+ LEFT JOIN domain_stats ds ON rdt.backend_id = ds.backend_id AND rdt.domain = ds.domain
+ WHERE rdt.backend_id = ? AND rdt.rule = ?
+ ORDER BY (rdt.total_upload + rdt.total_download) DESC
+ LIMIT ?
+ `);
+
+ const rows = stmt.all(backendId, rule, limit) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => ({
+ domain: row.domain,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
+ rules: [rule],
+ })) as DomainStats[];
+ }
+
+ // Get IPs for a specific rule (by matching rule name in ip_stats.rules)
+ getRuleIPs(backendId: number, rule: string, limit = 50): IPStats[] {
+ // Query rule_ip_traffic for accurate per-rule IP traffic, join ip_stats and geoip_cache for metadata
+ const stmt = this.db.prepare(`
+ SELECT
+ rit.ip,
+ rit.total_upload as totalUpload,
+ rit.total_download as totalDownload,
+ rit.total_connections as totalConnections,
+ rit.last_seen as lastSeen,
+ i.domains,
+ i.chains,
+ COALESCE(i.asn, g.asn) as asn,
+ CASE
+ WHEN g.country IS NOT NULL THEN
+ json_array(
+ g.country,
+ COALESCE(g.country_name, g.country),
+ COALESCE(g.city, ''),
+ COALESCE(g.as_name, '')
+ )
+ ELSE
+ NULL
+ END as geoIPData
+ FROM rule_ip_traffic rit
+ LEFT JOIN ip_stats i ON rit.backend_id = i.backend_id AND rit.ip = i.ip
+ LEFT JOIN geoip_cache g ON rit.ip = g.ip
+ WHERE rit.backend_id = ? AND rit.rule = ?
+ ORDER BY (rit.total_upload + rit.total_download) DESC
+ LIMIT ?
+ `);
+
+ const rows = stmt.all(backendId, rule, limit) as Array<{
+ ip: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ domains: string | null;
+ chains: string | null;
+ asn: string | null;
+ geoIPData: string | null;
+ }>;
+
+ return rows.map(row => ({
+ ip: row.ip,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
+ asn: row.asn || undefined,
+ geoIP: row.geoIPData ? JSON.parse(row.geoIPData).filter(Boolean) : undefined,
+ })) as IPStats[];
+ }
+
+ // Get rule chain flow for visualization
+ getRuleChainFlow(backendId: number, rule: string): { nodes: Array<{ name: string; totalUpload: number; totalDownload: number; totalConnections: number }>; links: Array<{ source: number; target: number }> } {
+ // Query rule_chain_traffic for accurate per-rule chain flow data
+ const stmt = this.db.prepare(`
+ SELECT chain, total_upload as totalUpload, total_download as totalDownload, total_connections as totalConnections
+ FROM rule_chain_traffic
+ WHERE backend_id = ? AND rule = ?
+ `);
+
+ const rows = stmt.all(backendId, rule) as Array<{
+ chain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ }>;
+
+ const nodeMap = new Map<string, { name: string; totalUpload: number; totalDownload: number; totalConnections: number }>();
+ const linkSet = new Set<string>();
+
+ for (const row of rows) {
+ // chain is stored as "proxy > group > rule" - parse and reverse to "rule > group > proxy"
+ const chainParts = row.chain.split(' > ').map(p => p.trim()).filter(Boolean);
+ if (chainParts.length === 0) continue;
+
+ // Find the rule in the chain and reverse the flow
+ const ruleIndex = chainParts.findIndex(part => part === rule);
+ if (ruleIndex === -1) continue;
+
+ const flowPath = chainParts.slice(0, ruleIndex + 1).reverse();
+
+ for (let i = 0; i < flowPath.length; i++) {
+ const nodeName = flowPath[i];
+ if (!nodeMap.has(nodeName)) {
+ nodeMap.set(nodeName, { name: nodeName, totalUpload: 0, totalDownload: 0, totalConnections: 0 });
+ }
+ const node = nodeMap.get(nodeName)!;
+ node.totalUpload += row.totalUpload;
+ node.totalDownload += row.totalDownload;
+ node.totalConnections += row.totalConnections;
+ }
+
+ for (let i = 0; i < flowPath.length - 1; i++) {
+ linkSet.add(`${flowPath[i]}|${flowPath[i + 1]}`);
+ }
+ }
+
+ const nodes = Array.from(nodeMap.values());
+ const nodeIndexMap = new Map(nodes.map((n, i) => [n.name, i]));
+
+ const links = Array.from(linkSet).map(linkStr => {
+ const [sourceName, targetName] = linkStr.split('|');
+ return { source: nodeIndexMap.get(sourceName)!, target: nodeIndexMap.get(targetName)! };
+ });
+
+ return { nodes, links };
+ }
+
+ // Get all rule chain flows merged into a unified DAG
+ getAllRuleChainFlows(backendId: number): {
+ nodes: Array<{ name: string; layer: number; nodeType: 'rule' | 'group' | 'proxy'; totalUpload: number; totalDownload: number; totalConnections: number; rules: string[] }>;
+ links: Array<{ source: number; target: number; rules: string[] }>;
+ rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }>;
+ maxLayer: number;
+ } {
+ // Query rule_chain_traffic for accurate per-rule data
+ const stmt = this.db.prepare(`
+ SELECT rule, chain, total_upload as totalUpload, total_download as totalDownload, total_connections as totalConnections
+ FROM rule_chain_traffic
+ WHERE backend_id = ?
+ `);
+
+ const rows = stmt.all(backendId) as Array<{
+ rule: string;
+ chain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ }>;
+
+ // nodeMap: name -> { stats + rules set + max layer }
+ const nodeMap = new Map<string, {
+ totalUpload: number; totalDownload: number; totalConnections: number;
+ rules: Set<string>; layer: number;
+ }>();
+ // linkMap: "source|target" -> rules set
+ const linkMap = new Map<string, Set<string>>();
+ // rulePaths: rule -> Set of node names, Set of link keys
+ const rulePathNodes = new Map<string, Set<string>>();
+ const rulePathLinks = new Map<string, Set<string>>();
+
+ for (const row of rows) {
+ const rule = row.rule;
+ if (!rulePathNodes.has(rule)) {
+ rulePathNodes.set(rule, new Set());
+ rulePathLinks.set(rule, new Set());
+ }
+
+ const chainParts = row.chain.split(' > ').map(p => p.trim()).filter(Boolean);
+ if (chainParts.length === 0) continue;
+
+ const ruleIndex = chainParts.findIndex(part => part === rule);
+ if (ruleIndex === -1) continue;
+
+ // Chain stored as: proxy > ... > rule, reverse to: rule > ... > proxy
+ const flowPath = chainParts.slice(0, ruleIndex + 1).reverse();
+ if (flowPath.length < 2) continue;
+
+ for (let i = 0; i < flowPath.length; i++) {
+ const nodeName = flowPath[i];
+ if (!nodeMap.has(nodeName)) {
+ nodeMap.set(nodeName, {
+ totalUpload: 0, totalDownload: 0, totalConnections: 0,
+ rules: new Set(), layer: i,
+ });
+ }
+ const node = nodeMap.get(nodeName)!;
+ node.totalUpload += row.totalUpload;
+ node.totalDownload += row.totalDownload;
+ node.totalConnections += row.totalConnections;
+ node.rules.add(rule);
+ node.layer = Math.max(node.layer, i);
+
+ rulePathNodes.get(rule)!.add(nodeName);
+ }
+
+ for (let i = 0; i < flowPath.length - 1; i++) {
+ const linkKey = `${flowPath[i]}|${flowPath[i + 1]}`;
+ if (!linkMap.has(linkKey)) {
+ linkMap.set(linkKey, new Set());
+ }
+ linkMap.get(linkKey)!.add(rule);
+ rulePathLinks.get(rule)!.add(linkKey);
+ }
+ }
+
+ // Determine node types and fix layer assignments
+ const nodeEntries = Array.from(nodeMap.entries());
+ const nodeTypeMap = new Map<string, 'rule' | 'group' | 'proxy'>();
+ let computedMaxLayer = 0;
+
+ for (const [name, data] of nodeEntries) {
+ const hasOutgoing = Array.from(linkMap.keys()).some(k => k.startsWith(name + '|'));
+ const hasIncoming = Array.from(linkMap.keys()).some(k => k.endsWith('|' + name));
+
+ if (!hasIncoming) {
+ nodeTypeMap.set(name, 'rule');
+ data.layer = 0;
+ } else if (!hasOutgoing) {
+ nodeTypeMap.set(name, 'proxy');
+ } else {
+ nodeTypeMap.set(name, 'group');
+ }
+ computedMaxLayer = Math.max(computedMaxLayer, data.layer);
+ }
+
+ // Force all proxy nodes to the rightmost column
+ for (const [name, data] of nodeEntries) {
+ if (nodeTypeMap.get(name) === 'proxy') {
+ data.layer = computedMaxLayer;
+ }
+ }
+
+ // Convert to arrays
+ const nodes = nodeEntries.map(([name, data]) => ({
+ name,
+ layer: data.layer,
+ nodeType: nodeTypeMap.get(name)!,
+ totalUpload: data.totalUpload,
+ totalDownload: data.totalDownload,
+ totalConnections: data.totalConnections,
+ rules: Array.from(data.rules),
+ }));
+
+ const nodeIndexMap = new Map(nodes.map((n, i) => [n.name, i]));
+
+ const links = Array.from(linkMap.entries()).map(([key, rules]) => {
+ const [sourceName, targetName] = key.split('|');
+ return {
+ source: nodeIndexMap.get(sourceName)!,
+ target: nodeIndexMap.get(targetName)!,
+ rules: Array.from(rules),
+ };
+ });
+
+ // Build rulePaths with index references
+ const rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }> = {};
+ for (const [rule, nodeNames] of rulePathNodes) {
+ const nodeIndices = Array.from(nodeNames).map(n => nodeIndexMap.get(n)!).filter(i => i !== undefined);
+ const linkIndices: number[] = [];
+ const linkKeys = rulePathLinks.get(rule)!;
+ links.forEach((link, idx) => {
+ const sourceName = nodes[link.source].name;
+ const targetName = nodes[link.target].name;
+ if (linkKeys.has(`${sourceName}|${targetName}`)) {
+ linkIndices.push(idx);
+ }
+ });
+ rulePaths[rule] = { nodeIndices, linkIndices };
+ }
+
+ const maxLayer = nodes.reduce((max, n) => Math.max(max, n.layer), 0);
+
+ return { nodes, links, rulePaths, maxLayer };
+ }
+
// Get recent connections for a specific backend
getRecentConnections(backendId: number, limit = 100): Connection[] {
const stmt = this.db.prepare(`
@@ -1539,6 +2270,11 @@ export class StatsDatabase {
const rulesStmt = this.db.prepare(`DELETE FROM rule_stats WHERE backend_id = ?`);
deletedRules = rulesStmt.run(backendId).changes;
+
+ // Clear rule cross-reference tables
+ this.db.prepare(`DELETE FROM rule_chain_traffic WHERE backend_id = ?`).run(backendId);
+ this.db.prepare(`DELETE FROM rule_domain_traffic WHERE backend_id = ?`).run(backendId);
+ this.db.prepare(`DELETE FROM rule_ip_traffic WHERE backend_id = ?`).run(backendId);
} else {
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
const connectionsStmt = this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ? AND timestamp < ?`);
@@ -1568,6 +2304,11 @@ export class StatsDatabase {
const rulesStmt = this.db.prepare(`DELETE FROM rule_stats`);
deletedRules = rulesStmt.run().changes;
+
+ // Clear rule cross-reference tables
+ this.db.prepare(`DELETE FROM rule_chain_traffic`).run();
+ this.db.prepare(`DELETE FROM rule_domain_traffic`).run();
+ this.db.prepare(`DELETE FROM rule_ip_traffic`).run();
} else {
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
const connectionsStmt = this.db.prepare(`DELETE FROM connection_logs WHERE timestamp < ?`);
@@ -1810,6 +2551,9 @@ export class StatsDatabase {
this.db.prepare(`DELETE FROM proxy_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM rule_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM rule_proxy_map WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_chain_traffic WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_domain_traffic WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_ip_traffic WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM country_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM hourly_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ?`).run(id);
diff --git a/apps/collector/src/geo-service.ts b/apps/collector/src/geo-service.ts
index 7648f1c..b2621ee 100644
--- a/apps/collector/src/geo-service.ts
+++ b/apps/collector/src/geo-service.ts
@@ -21,10 +21,10 @@ export class GeoIPService {
resolve: (value: GeoLocation | null) => void;
}[] = [];
private isProcessing: boolean = false;
+ private processorTimer: NodeJS.Timeout | null = null;
constructor(db: StatsDatabase) {
this.db = db;
- this.startQueueProcessor();
}
// Get geolocation for an IP (with caching)
@@ -80,43 +80,42 @@ export class GeoIPService {
private async queryWithQueue(ip: string): Promise<GeoLocation | null> {
return new Promise((resolve) => {
this.queue.push({ ip, resolve });
+ this.scheduleProcessing();
});
}
- // Process queue with rate limiting
- private startQueueProcessor() {
- const processQueue = async () => {
- if (this.isProcessing || this.queue.length === 0) {
- setTimeout(processQueue, 100);
- return;
- }
+ // Schedule queue processing (on-demand, no idle spinning)
+ private scheduleProcessing() {
+ if (this.processorTimer || this.isProcessing) return;
- this.isProcessing = true;
- const item = this.queue.shift();
-
- if (item) {
- try {
- // Respect rate limit
- const now = Date.now();
- const timeSinceLastRequest = now - this.lastRequestTime;
- if (timeSinceLastRequest < this.minRequestInterval) {
- await this.sleep(this.minRequestInterval - timeSinceLastRequest);
- }
-
- const result = await this.queryAPI(item.ip);
- this.lastRequestTime = Date.now();
- item.resolve(result);
- } catch (err) {
- console.error(`[GeoIP] Error querying ${item.ip}:`, err);
- item.resolve(null);
- }
- }
+ const delay = Math.max(0, this.minRequestInterval - (Date.now() - this.lastRequestTime));
+ this.processorTimer = setTimeout(() => {
+ this.processorTimer = null;
+ this.processNext();
+ }, delay);
+ }
- this.isProcessing = false;
- setTimeout(processQueue, 100);
- };
+ // Process the next item in the queue
+ private async processNext() {
+ if (this.isProcessing || this.queue.length === 0) return;
+
+ this.isProcessing = true;
+ const item = this.queue.shift()!;
- processQueue();
+ try {
+ const result = await this.queryAPI(item.ip);
+ this.lastRequestTime = Date.now();
+ item.resolve(result);
+ } catch (err) {
+ console.error(`[GeoIP] Error querying ${item.ip}:`, err);
+ item.resolve(null);
+ } finally {
+ this.isProcessing = false;
+ // Continue processing if more items in queue
+ if (this.queue.length > 0) {
+ this.scheduleProcessing();
+ }
+ }
}
// Query the API
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index 95c0a87..e997390 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -52,6 +52,30 @@ async function main() {
// Check for backend config changes every 5 seconds
setInterval(manageBackends, 5000);
+ // Auto-cleanup: enforce data retention policy
+ function runAutoCleanup() {
+ try {
+ const config = db.getRetentionConfig();
+ if (!config.autoCleanup) return;
+
+ const connCutoff = new Date(Date.now() - config.connectionLogsDays * 86400000).toISOString();
+ const hourlyCutoff = new Date(Date.now() - config.hourlyStatsDays * 86400000).toISOString();
+
+ const deletedLogs = db.deleteOldConnectionLogs(connCutoff);
+ const deletedHourly = db.deleteOldHourlyStats(hourlyCutoff);
+
+ if (deletedLogs > 0 || deletedHourly > 0) {
+ console.log(`[Cleanup] Deleted ${deletedLogs} connection logs, ${deletedHourly} hourly stats`);
+ }
+ } catch (err) {
+ console.error('[Cleanup] Auto-cleanup failed:', err);
+ }
+ }
+
+ // First cleanup 30 seconds after startup, then every 6 hours
+ setTimeout(runAutoCleanup, 30000);
+ setInterval(runAutoCleanup, 6 * 60 * 60 * 1000);
+
// Handle graceful shutdown
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index 51c8c4e..14ad7a2 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -151,32 +151,39 @@ export class StatsWebSocketServer {
// Broadcast stats to all connected clients
async broadcastStats(force = false) {
const now = Date.now();
-
+
// Throttle broadcasts to prevent overwhelming clients
if (!force && now - this.lastBroadcastTime < this.broadcastThrottleMs) {
return;
}
-
+
this.lastBroadcastTime = now;
if (this.clients.size === 0) return;
try {
let sentCount = 0;
-
+ // Cache stats per backendId to avoid redundant DB queries
+ const statsCache = new Map<number | null, StatsSummary | null>();
+
// Send stats to each client based on their subscribed backend
for (const [ws, clientInfo] of this.clients) {
- if (ws.readyState === WebSocket.OPEN) {
- const stats = this.getStatsForBackend(clientInfo.backendId);
- if (stats) {
- const message: WebSocketMessage = {
- type: 'stats',
- data: stats,
- timestamp: new Date().toISOString()
- };
- ws.send(JSON.stringify(message));
- sentCount++;
- }
+ if (ws.readyState !== WebSocket.OPEN) continue;
+
+ const cacheKey = clientInfo.backendId;
+ if (!statsCache.has(cacheKey)) {
+ statsCache.set(cacheKey, this.getStatsForBackend(cacheKey));
+ }
+ const stats = statsCache.get(cacheKey)!;
+
+ if (stats) {
+ const message: WebSocketMessage = {
+ type: 'stats',
+ data: stats,
+ timestamp: new Date().toISOString()
+ };
+ ws.send(JSON.stringify(message));
+ sentCount++;
}
}
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index f4bf9a3..dad2704 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -28,6 +28,7 @@ import { OverviewTab } from "@/components/overview";
import { TopDomainsChart } from "@/components/top-domains-chart";
import { ProxyStatsChart } from "@/components/proxy-stats-chart";
import { InteractiveProxyStats } from "@/components/interactive-proxy-stats";
+import { InteractiveRuleStats } from "@/components/interactive-rule-stats";
import { RuleChainChart } from "@/components/rule-chain-chart";
import { WorldTrafficMap } from "@/components/world-traffic-map";
import { CountryTrafficList } from "@/components/country-traffic-list";
@@ -110,8 +111,10 @@ const OverviewContent = memo(function OverviewContent({
const DomainsContent = memo(function DomainsContent({
data,
+ activeBackendId,
}: {
data: StatsSummary | null;
+ activeBackendId?: number;
}) {
const t = useTranslations("domains");
return (
@@ -123,10 +126,10 @@ const DomainsContent = memo(function DomainsContent({
<TabsTrigger value="ips">{t("ipList")}</TabsTrigger>
</TabsList>
<TabsContent value="domains" className="overflow-hidden">
- <DomainsTable data={data?.topDomains || []} />
+ <DomainsTable activeBackendId={activeBackendId} />
</TabsContent>
<TabsContent value="ips" className="overflow-hidden">
- <IPsTable data={data?.topIPs || []} />
+ <IPsTable activeBackendId={activeBackendId} />
</TabsContent>
</Tabs>
</div>
@@ -175,12 +178,17 @@ const ProxiesContent = memo(function ProxiesContent({
const RulesContent = memo(function RulesContent({
data,
+ activeBackendId,
}: {
data: StatsSummary | null;
+ activeBackendId?: number;
}) {
return (
<div className="space-y-6">
- <RuleChainChart data={data?.ruleStats || []} />
+ <InteractiveRuleStats
+ data={data?.ruleStats || []}
+ activeBackendId={activeBackendId}
+ />
</div>
);
});
@@ -332,7 +340,7 @@ export default function DashboardPage() {
/>
);
case "domains":
- return <DomainsContent data={data} />;
+ return <DomainsContent data={data} activeBackendId={activeBackend?.id} />;
case "countries":
return <CountriesContent countryData={countryData} />;
case "proxies":
@@ -340,7 +348,7 @@ export default function DashboardPage() {
<ProxiesContent data={data} activeBackendId={activeBackend?.id} />
);
case "rules":
- return <RulesContent data={data} />;
+ return <RulesContent data={data} activeBackendId={activeBackend?.id} />;
case "network":
return <NetworkContent />;
default:
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index 9e77e1e..c7154a7 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -1,4 +1,5 @@
@import "tailwindcss";
+@import "@xyflow/react/dist/style.css";
@custom-variant dark (&:is(.dark *));
@@ -302,3 +303,9 @@
transform: translateY(-2px);
box-shadow: 0 12px 24px -8px rgba(0, 0, 0, 0.2);
}
+
+/* Chain flow graph - smooth node position animation on rule switch */
+.chain-flow-graph .react-flow__node {
+ transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
+}
+
diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsx
index 8b2b31a..51582d9 100644
--- a/apps/web/components/domains-table.tsx
+++ b/apps/web/components/domains-table.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useMemo, useCallback } from "react";
+import { useState, useCallback, useEffect, useRef } from "react";
import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Globe, Server, Waypoints, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
@@ -18,7 +18,7 @@ import {
} from "@/components/ui/dropdown-menu";
interface DomainsTableProps {
- data: DomainStats[];
+ activeBackendId?: number;
}
type SortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections" | "lastSeen";
@@ -56,9 +56,13 @@ function getCountryFlag(country: string): string {
return COUNTRY_FLAGS[country] || COUNTRY_FLAGS[country.toUpperCase()] || "🌐";
}
-export function DomainsTable({ data }: DomainsTableProps) {
+export function DomainsTable({ activeBackendId }: DomainsTableProps) {
const t = useTranslations("domains");
+ const [data, setData] = useState<DomainStats[]>([]);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(false);
const [search, setSearch] = useState("");
+ const [debouncedSearch, setDebouncedSearch] = useState("");
const [sortKey, setSortKey] = useState<SortKey>("totalDownload");
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
const [currentPage, setCurrentPage] = useState(1);
@@ -68,10 +72,51 @@ export function DomainsTable({ data }: DomainsTableProps) {
const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);
const [ipDetails, setIPDetails] = useState<Record<string, IPStats[]>>({});
const [ipDetailsLoading, setIPDetailsLoading] = useState<string | null>(null);
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ // Debounce search input
+ useEffect(() => {
+ debounceRef.current = setTimeout(() => {
+ setDebouncedSearch(search);
+ setCurrentPage(1);
+ }, 300);
+ return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
+ }, [search]);
+
+ // Fetch data from server
+ useEffect(() => {
+ let cancelled = false;
+ const fetchData = async () => {
+ setLoading(true);
+ try {
+ const result = await api.getDomains(activeBackendId, {
+ offset: (currentPage - 1) * pageSize,
+ limit: pageSize,
+ sortBy: sortKey,
+ sortOrder,
+ search: debouncedSearch || undefined,
+ });
+ if (!cancelled) {
+ setData(result.data);
+ setTotal(result.total);
+ }
+ } catch (err) {
+ console.error("Failed to fetch domains:", err);
+ if (!cancelled) {
+ setData([]);
+ setTotal(0);
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ };
+ fetchData();
+ return () => { cancelled = true; };
+ }, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch]);
// Fetch proxy stats when a domain is expanded
const fetchProxyStats = useCallback(async (domain: string) => {
- if (proxyStats[domain]) return; // Already cached
+ if (proxyStats[domain]) return;
setProxyStatsLoading(domain);
try {
const stats = await api.getDomainProxyStats(domain);
@@ -86,7 +131,7 @@ export function DomainsTable({ data }: DomainsTableProps) {
// Fetch IP details when a domain is expanded
const fetchIPDetails = useCallback(async (domain: string) => {
- if (ipDetails[domain]) return; // Already cached
+ if (ipDetails[domain]) return;
setIPDetailsLoading(domain);
try {
const details = await api.getDomainIPDetails(domain);
@@ -109,33 +154,10 @@ export function DomainsTable({ data }: DomainsTableProps) {
setCurrentPage(1);
};
- const filteredData = useMemo(() => {
- return (data || [])
- .filter((domain) =>
- domain.domain.toLowerCase().includes(search.toLowerCase())
- )
- .sort((a, b) => {
- const aValue = a[sortKey];
- const bValue = b[sortKey];
- const modifier = sortOrder === "asc" ? 1 : -1;
-
- if (typeof aValue === "string" && typeof bValue === "string") {
- return aValue.localeCompare(bValue) * modifier;
- }
- return ((aValue as number) - (bValue as number)) * modifier;
- });
- }, [data, search, sortKey, sortOrder]);
-
- // Pagination
- const totalPages = Math.ceil(filteredData.length / pageSize);
- const paginatedData = useMemo(() => {
- const start = (currentPage - 1) * pageSize;
- return filteredData.slice(start, start + pageSize);
- }, [filteredData, currentPage, pageSize]);
+ const totalPages = Math.ceil(total / pageSize);
const handleSearchChange = (value: string) => {
setSearch(value);
- setCurrentPage(1);
};
const handlePageSizeChange = (size: PageSize) => {
@@ -165,7 +187,7 @@ export function DomainsTable({ data }: DomainsTableProps) {
const getPageNumbers = () => {
const pages: (number | string)[] = [];
const maxVisible = 5;
-
+
if (totalPages <= maxVisible) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
@@ -196,7 +218,7 @@ export function DomainsTable({ data }: DomainsTableProps) {
<div>
<h3 className="text-lg font-semibold">{t("title")}</h3>
<p className="text-sm text-muted-foreground">
- {filteredData.length} {t("domainsCount")}
+ {total} {t("domainsCount")}
</p>
</div>
<div className="relative">
@@ -213,7 +235,7 @@ export function DomainsTable({ data }: DomainsTableProps) {
{/* Desktop Table Header - Hidden on mobile */}
<div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
+ <div
className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("domain")}
>
@@ -223,21 +245,21 @@ export function DomainsTable({ data }: DomainsTableProps) {
<div className="col-span-2 flex items-center">
{t("proxy")}
</div>
- <div
+ <div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalDownload")}
>
{t("download")}
<SortIcon column="totalDownload" />
</div>
- <div
+ <div
className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalUpload")}
>
{t("upload")}
<SortIcon column="totalUpload" />
</div>
- <div
+ <div
className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalConnections")}
>
@@ -280,14 +302,18 @@ export function DomainsTable({ data }: DomainsTableProps) {
{/* Table Body */}
<div className="divide-y divide-border/30 min-h-[300px]">
- {paginatedData.length === 0 ? (
+ {loading && data.length === 0 ? (
+ <div className="px-5 py-12 text-center text-muted-foreground">
+ <Loader2 className="h-6 w-6 animate-spin mx-auto mb-2" />
+ </div>
+ ) : data.length === 0 ? (
<div className="px-5 py-12 text-center text-muted-foreground">
{t("noResults")}
</div>
) : (
- paginatedData.map((domain, index) => {
+ data.map((domain, index) => {
const isExpanded = expandedDomain === domain.domain;
-
+
return (
<div key={domain.domain} className="group">
{/* Desktop Row */}
@@ -362,8 +388,8 @@ export function DomainsTable({ data }: DomainsTableProps) {
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium transition-all",
- isExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
+ isExpanded
+ ? "bg-primary/10 text-primary hover:bg-primary/20"
: "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
)}
onClick={(e) => {
@@ -403,8 +429,8 @@ export function DomainsTable({ data }: DomainsTableProps) {
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isExpanded
- ? "bg-primary/10 text-primary"
+ isExpanded
+ ? "bg-primary/10 text-primary"
: "bg-secondary/50 text-muted-foreground"
)}
onClick={(e) => {
@@ -537,11 +563,11 @@ export function DomainsTable({ data }: DomainsTableProps) {
{(() => {
const totalIPTraffic = ipDetails[domain.domain].reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0);
return ipDetails[domain.domain].map((ipStat) => {
- const flag = ipStat.geoIP && ipStat.geoIP.length > 0
- ? getCountryFlag(ipStat.geoIP[0])
+ const flag = ipStat.geoIP && ipStat.geoIP.length > 0
+ ? getCountryFlag(ipStat.geoIP[0])
: "🌐";
- const location = ipStat.geoIP && ipStat.geoIP.length > 1
- ? ipStat.geoIP[1]
+ const location = ipStat.geoIP && ipStat.geoIP.length > 1
+ ? ipStat.geoIP[1]
: ipStat.geoIP?.[0] || null;
const ipTraffic = ipStat.totalDownload + ipStat.totalUpload;
const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;
@@ -642,19 +668,19 @@ export function DomainsTable({ data }: DomainsTableProps) {
</DropdownMenuContent>
</DropdownMenu>
<span className="text-sm text-muted-foreground">
- {t("total")} {filteredData.length}
+ {t("total")} {total}
</span>
</div>
-
+
{/* Pagination info and controls */}
<div className="flex items-center gap-2 sm:gap-3">
<p className="text-xs sm:text-sm text-muted-foreground hidden sm:block">
- {t("showing")} {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, filteredData.length)} {t("of")} {filteredData.length}
+ {t("showing")} {Math.min((currentPage - 1) * pageSize + 1, total)} - {Math.min(currentPage * pageSize, total)} {t("of")} {total}
</p>
<p className="text-xs text-muted-foreground sm:hidden">
- {(currentPage - 1) * pageSize + 1}-{Math.min(currentPage * pageSize, filteredData.length)} / {filteredData.length}
+ {Math.min((currentPage - 1) * pageSize + 1, total)}-{Math.min(currentPage * pageSize, total)} / {total}
</p>
-
+
<div className="flex items-center gap-1">
<Button
variant="ghost"
@@ -665,7 +691,7 @@ export function DomainsTable({ data }: DomainsTableProps) {
>
<ChevronLeft className="h-4 w-4" />
</Button>
-
+
{getPageNumbers().map((page, idx) => (
page === '...' ? (
<span key={`ellipsis-${idx}`} className="px-1 sm:px-2 text-muted-foreground text-xs">...</span>
@@ -681,7 +707,7 @@ export function DomainsTable({ data }: DomainsTableProps) {
</Button>
)
))}
-
+
<Button
variant="ghost"
size="icon"
diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/interactive-rule-stats.tsx
new file mode 100644
index 0000000..1300660
--- /dev/null
+++ b/apps/web/components/interactive-rule-stats.tsx
@@ -0,0 +1,1349 @@
+"use client";
+
+import { useState, useCallback, useMemo, useEffect } from "react";
+import { Server, ChevronLeft, ChevronRight, Loader2, BarChart3, Link2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, Waypoints, ChevronDown, ChevronUp } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from "recharts";
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Cell as BarCell, LabelList } from "recharts";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { formatBytes, formatNumber } from "@/lib/utils";
+import { cn } from "@/lib/utils";
+import { api } from "@/lib/api";
+import { Favicon } from "@/components/favicon";
+import { UnifiedRuleChainFlow } from "@/components/rule-chain-flow";
+import type { RuleStats, DomainStats, IPStats } from "@clashmaster/shared";
+
+interface InteractiveRuleStatsProps {
+ data: RuleStats[];
+ activeBackendId?: number;
+}
+
+const COLORS = [
+ "#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B",
+ "#EF4444", "#EC4899", "#6366F1", "#14B8A6", "#F97316",
+];
+
+const CHART_COLORS = [
+ "#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B",
+ "#EF4444", "#EC4899", "#6366F1", "#14B8A6", "#F97316",
+];
+
+const PAGE_SIZE_OPTIONS = [10, 20, 50] as const;
+type PageSize = typeof PAGE_SIZE_OPTIONS[number];
+
+// Generate gradient based on IP - same as DomainsTable
+const getIPGradient = (ip: string) => {
+ const colors = [
+ "from-emerald-500 to-teal-400",
+ "from-blue-500 to-cyan-400",
+ "from-violet-500 to-purple-400",
+ "from-orange-500 to-amber-400",
+ "from-rose-500 to-pink-400",
+ ];
+ let hash = 0;
+ for (let i = 0; i < ip.length; i++) {
+ hash = ip.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ return colors[Math.abs(hash) % colors.length];
+};
+
+// Domain sort keys
+type DomainSortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections";
+type SortOrder = "asc" | "desc";
+
+// IP sort keys
+type IPSortKey = "ip" | "totalDownload" | "totalUpload" | "totalConnections";
+
+// Color palette for icons
+const ICON_COLORS = [
+ { bg: "bg-blue-500", text: "text-white" },
+ { bg: "bg-violet-500", text: "text-white" },
+ { bg: "bg-emerald-500", text: "text-white" },
+ { bg: "bg-amber-500", text: "text-white" },
+ { bg: "bg-rose-500", text: "text-white" },
+ { bg: "bg-cyan-500", text: "text-white" },
+ { bg: "bg-indigo-500", text: "text-white" },
+ { bg: "bg-teal-500", text: "text-white" },
+];
+
+const getDomainColor = (domain: string) => {
+ let hash = 0;
+ for (let i = 0; i < domain.length; i++) {
+ hash = domain.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ return ICON_COLORS[Math.abs(hash) % ICON_COLORS.length];
+};
+
+const getIPColor = (ip: string) => {
+ let hash = 0;
+ for (let i = 0; i < ip.length; i++) {
+ hash = ip.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ return ICON_COLORS[Math.abs(hash) % ICON_COLORS.length];
+};
+
+// Get country flag emoji from country code
+function getCountryFlag(countryCode: string): string {
+ if (!countryCode || countryCode === 'unknown') return '🌐';
+ const code = countryCode.toUpperCase();
+ if (code === 'ZZ') return '🌐';
+ // Convert country code to regional indicator symbols
+ const base = 127397;
+ try {
+ return String.fromCodePoint(
+ ...code.split('').map(char => base + char.charCodeAt(0))
+ );
+ } catch {
+ return '🌐';
+ }
+}
+
+// Custom label renderer for bar chart
+function renderCustomBarLabel(props: any) {
+ const { x, y, width, value, height } = props;
+ return (
+ <text
+ x={x + width + 6}
+ y={y + height / 2}
+ fill="currentColor"
+ fontSize={11}
+ dominantBaseline="central"
+ textAnchor="start"
+ style={{ fontVariantNumeric: "tabular-nums" }}
+ >
+ {formatBytes(value, 0)}
+ </text>
+ );
+}
+
+export function InteractiveRuleStats({ data, activeBackendId }: InteractiveRuleStatsProps) {
+ const t = useTranslations("rules");
+ const domainsT = useTranslations("domains");
+ const ipsT = useTranslations("ips");
+
+ const [selectedRule, setSelectedRule] = useState<string | null>(null);
+ const [ruleDomains, setRuleDomains] = useState<DomainStats[]>([]);
+ const [ruleIPs, setRuleIPs] = useState<IPStats[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [activeTab, setActiveTab] = useState("domains");
+
+ // Pagination states
+ const [domainPage, setDomainPage] = useState(1);
+ const [domainPageSize, setDomainPageSize] = useState<PageSize>(10);
+ const [domainSearch, setDomainSearch] = useState("");
+ const [ipPage, setIpPage] = useState(1);
+ const [ipPageSize, setIpPageSize] = useState<PageSize>(10);
+ const [ipSearch, setIpSearch] = useState("");
+ const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
+
+ // Sort states
+ const [domainSortKey, setDomainSortKey] = useState<DomainSortKey>("totalDownload");
+ const [domainSortOrder, setDomainSortOrder] = useState<SortOrder>("desc");
+ const [ipSortKey, setIpSortKey] = useState<IPSortKey>("totalDownload");
+ const [ipSortOrder, setIpSortOrder] = useState<SortOrder>("desc");
+
+ // Expanded states
+ const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
+ const [expandedIP, setExpandedIP] = useState<string | null>(null);
+
+ useEffect(() => {
+ const media = window.matchMedia("(min-width: 640px)");
+ const update = () => setShowDomainBarLabels(media.matches);
+ update();
+ media.addEventListener("change", update);
+ return () => media.removeEventListener("change", update);
+ }, []);
+
+ const chartData = useMemo(() => {
+ if (!data) return [];
+ return data.map((rule, index) => ({
+ name: rule.rule,
+ rawName: rule.rule,
+ value: rule.totalDownload + rule.totalUpload,
+ download: rule.totalDownload,
+ upload: rule.totalUpload,
+ connections: rule.totalConnections,
+ finalProxy: rule.finalProxy,
+ color: COLORS[index % COLORS.length],
+ rank: index,
+ }));
+ }, [data]);
+
+ const totalTraffic = useMemo(() => {
+ return chartData.reduce((sum, item) => sum + item.value, 0);
+ }, [chartData]);
+
+ const maxTotal = useMemo(() => {
+ if (!chartData.length) return 1;
+ return Math.max(...chartData.map(r => r.value));
+ }, [chartData]);
+
+ // Domain sort handler
+ const handleDomainSort = (key: DomainSortKey) => {
+ if (domainSortKey === key) {
+ setDomainSortOrder(domainSortOrder === "asc" ? "desc" : "asc");
+ } else {
+ setDomainSortKey(key);
+ setDomainSortOrder("desc");
+ }
+ setDomainPage(1);
+ };
+
+ // IP sort handler
+ const handleIPSort = (key: IPSortKey) => {
+ if (ipSortKey === key) {
+ setIpSortOrder(ipSortOrder === "asc" ? "desc" : "asc");
+ } else {
+ setIpSortKey(key);
+ setIpSortOrder("desc");
+ }
+ setIpPage(1);
+ };
+
+ // Toggle expand handlers
+ const toggleExpandDomain = (domain: string) => {
+ setExpandedDomain(expandedDomain === domain ? null : domain);
+ };
+
+ const toggleExpandIP = (ip: string) => {
+ setExpandedIP(expandedIP === ip ? null : ip);
+ };
+
+ // Sort icon component
+ const DomainSortIcon = ({ column }: { column: DomainSortKey }) => {
+ if (domainSortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
+ return domainSortOrder === "asc" ? (
+ <ArrowUp className="ml-1 h-3 w-3 text-primary" />
+ ) : (
+ <ArrowDown className="ml-1 h-3 w-3 text-primary" />
+ );
+ };
+
+ const IPSortIcon = ({ column }: { column: IPSortKey }) => {
+ if (ipSortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
+ return ipSortOrder === "asc" ? (
+ <ArrowUp className="ml-1 h-3 w-3 text-primary" />
+ ) : (
+ <ArrowDown className="ml-1 h-3 w-3 text-primary" />
+ );
+ };
+
+ // Load rule details
+ const loadRuleDetails = useCallback(async (rule: string) => {
+ setLoading(true);
+ try {
+ const [domains, ips] = await Promise.all([
+ api.getRuleDomains(rule, activeBackendId),
+ api.getRuleIPs(rule, activeBackendId),
+ ]);
+ setRuleDomains(domains);
+ setRuleIPs(ips);
+ // Reset pagination
+ setDomainPage(1);
+ setIpPage(1);
+ setDomainSearch("");
+ setIpSearch("");
+ } catch (err) {
+ console.error(`Failed to load details for ${rule}:`, err);
+ setRuleDomains([]);
+ setRuleIPs([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [activeBackendId]);
+
+ // Default select first rule when data loads
+ useEffect(() => {
+ if (chartData.length > 0 && !selectedRule) {
+ const firstRule = chartData[0].rawName;
+ setSelectedRule(firstRule);
+ loadRuleDetails(firstRule);
+ }
+ }, [chartData, selectedRule, loadRuleDetails]);
+
+ const handleRuleClick = useCallback((rule: string) => {
+ if (selectedRule !== rule) {
+ setSelectedRule(rule);
+ loadRuleDetails(rule);
+ }
+ }, [selectedRule, loadRuleDetails]);
+
+ const selectedRuleData = useMemo(() => {
+ return chartData.find(r => r.rawName === selectedRule);
+ }, [chartData, selectedRule]);
+
+ // Filter, sort and paginate domains
+ const filteredDomains = useMemo(() => {
+ let result = ruleDomains;
+ if (domainSearch) {
+ result = ruleDomains.filter(d =>
+ d.domain.toLowerCase().includes(domainSearch.toLowerCase())
+ );
+ }
+ // Sort
+ return [...result].sort((a, b) => {
+ const aValue = a[domainSortKey];
+ const bValue = b[domainSortKey];
+ const modifier = domainSortOrder === "asc" ? 1 : -1;
+ if (typeof aValue === "string" && typeof bValue === "string") {
+ return aValue.localeCompare(bValue) * modifier;
+ }
+ return ((aValue as number) - (bValue as number)) * modifier;
+ });
+ }, [ruleDomains, domainSearch, domainSortKey, domainSortOrder]);
+
+ const paginatedDomains = useMemo(() => {
+ const start = (domainPage - 1) * domainPageSize;
+ return filteredDomains.slice(start, start + domainPageSize);
+ }, [filteredDomains, domainPage, domainPageSize]);
+
+ const domainTotalPages = Math.ceil(filteredDomains.length / domainPageSize);
+
+ // Filter, sort and paginate IPs
+ const filteredIPs = useMemo(() => {
+ let result = ruleIPs;
+ if (ipSearch) {
+ result = ruleIPs.filter(ip =>
+ ip.ip.toLowerCase().includes(ipSearch.toLowerCase()) ||
+ ip.domains.some(d => d.toLowerCase().includes(ipSearch.toLowerCase()))
+ );
+ }
+ // Sort
+ return [...result].sort((a, b) => {
+ const aValue = a[ipSortKey];
+ const bValue = b[ipSortKey];
+ const modifier = ipSortOrder === "asc" ? 1 : -1;
+ if (typeof aValue === "string" && typeof bValue === "string") {
+ return aValue.localeCompare(bValue) * modifier;
+ }
+ return ((aValue as number) - (bValue as number)) * modifier;
+ });
+ }, [ruleIPs, ipSearch, ipSortKey, ipSortOrder]);
+
+ const paginatedIPs = useMemo(() => {
+ const start = (ipPage - 1) * ipPageSize;
+ return filteredIPs.slice(start, start + ipPageSize);
+ }, [filteredIPs, ipPage, ipPageSize]);
+
+ const ipTotalPages = Math.ceil(filteredIPs.length / ipPageSize);
+
+ // Chart data
+ const domainChartData = useMemo(() => {
+ if (!ruleDomains?.length) return [];
+ return ruleDomains
+ .slice(0, 10)
+ .map((domain, index) => ({
+ name: domain.domain.length > 15 ? domain.domain.slice(0, 15) + "..." : domain.domain,
+ fullDomain: domain.domain,
+ total: domain.totalDownload + domain.totalUpload,
+ download: domain.totalDownload,
+ upload: domain.totalUpload,
+ connections: domain.totalConnections,
+ color: CHART_COLORS[index % CHART_COLORS.length],
+ }));
+ }, [ruleDomains]);
+
+ const getPageNumbers = (currentPage: number, totalPages: number) => {
+ const pages: (number | string)[] = [];
+ const maxVisible = 5;
+
+ if (totalPages <= maxVisible) {
+ for (let i = 1; i <= totalPages; i++) pages.push(i);
+ } else {
+ if (currentPage <= 3) {
+ for (let i = 1; i <= 4; i++) pages.push(i);
+ pages.push('...');
+ pages.push(totalPages);
+ } else if (currentPage >= totalPages - 2) {
+ pages.push(1);
+ pages.push('...');
+ for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
+ } else {
+ pages.push(1);
+ pages.push('...');
+ for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
+ pages.push('...');
+ pages.push(totalPages);
+ }
+ }
+ return pages;
+ };
+
+ if (chartData.length === 0) {
+ return (
+ <Card>
+ <CardContent className="p-12 text-center text-muted-foreground">
+ {t("noData")}
+ </CardContent>
+ </Card>
+ );
+ }
+
+ return (
+ <div className="space-y-6 overflow-x-hidden">
+ {/* Top Section: Three Column Layout */}
+ <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
+ {/* Left: Pie Chart (3 columns) */}
+ <Card className="lg:col-span-3">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
+ {t("distribution")}
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="h-[200px] w-full">
+ <ResponsiveContainer width="100%" height="100%">
+ <PieChart>
+ <Pie
+ data={chartData}
+ cx="50%"
+ cy="50%"
+ innerRadius={50}
+ outerRadius={80}
+ paddingAngle={2}
+ dataKey="value">
+ {chartData.map((entry, index) => (
+ <Cell key={`cell-${index}`} fill={entry.color} />
+ ))}
+ </Pie>
+ <RechartsTooltip
+ content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (
+ <div className="bg-background border border-border p-3 rounded-lg shadow-lg">
+ <p className="font-medium text-sm mb-1">{item.name}</p>
+ <p className="text-xs text-muted-foreground">{formatBytes(item.value)}</p>
+ </div>
+ );
+ }
+ return null;
+ }}
+ />
+ </PieChart>
+ </ResponsiveContainer>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* Middle: Rule List (4 columns) */}
+ <Card className="lg:col-span-4">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
+ {t("ruleList")}
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="p-3">
+ <ScrollArea className="h-[280px] pr-3">
+ <div className="space-y-2">
+ {chartData.map((item) => {
+ const percentage = totalTraffic > 0 ? (item.value / totalTraffic) * 100 : 0;
+ const barPercent = (item.value / maxTotal) * 100;
+ const isSelected = selectedRule === item.rawName;
+
+ // Badge color based on rank
+ const badgeColor = item.rank === 0
+ ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400"
+ : item.rank === 1
+ ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"
+ : item.rank === 2
+ ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400"
+ : "bg-muted text-muted-foreground";
+
+ return (
+ <button
+ key={item.rawName}
+ onClick={() => handleRuleClick(item.rawName)}
+ className={cn(
+ "w-full p-2.5 rounded-xl border text-left transition-all duration-200",
+ isSelected
+ ? "border-primary bg-primary/5 ring-1 ring-primary/20"
+ : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30"
+ )}>
+ {/* Row 1: Rank + Name + Total */}
+ <div className="flex items-center gap-2 mb-1.5">
+ <span className={cn(
+ "w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0",
+ badgeColor
+ )}>
+ {item.rank + 1}
+ </span>
+
+ <span className="flex-1 text-sm font-medium truncate" title={item.name}>
+ {item.name}
+ </span>
+
+ <span className="text-sm font-bold tabular-nums shrink-0">
+ {formatBytes(item.value)}
+ </span>
+ </div>
+
+ {/* Row 2: Progress bar + Stats */}
+ <div className="pl-7 space-y-1">
+ {/* Progress bar - dual color */}
+ <div className="h-1.5 rounded-full bg-muted overflow-hidden flex">
+ <div
+ className="h-full bg-blue-500 dark:bg-blue-400"
+ style={{ width: `${(item.download / item.value) * barPercent}%` }}
+ />
+ <div
+ className="h-full bg-purple-500 dark:bg-purple-400"
+ style={{ width: `${(item.upload / item.value) * barPercent}%` }}
+ />
+ </div>
+ {/* Stats */}
+ <div className="flex flex-wrap items-center justify-between gap-1 text-xs text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
+ <span className="text-blue-500 dark:text-blue-400">↓ {formatBytes(item.download)}</span>
+ <span className="text-purple-500 dark:text-purple-400">↑ {formatBytes(item.upload)}</span>
+ <span className="flex items-center gap-1 tabular-nums">
+ <Link2 className="w-3 h-3" />
+ {formatNumber(item.connections)}
+ </span>
+ </div>
+ <span className="tabular-nums">{percentage.toFixed(1)}%</span>
+ </div>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </ScrollArea>
+ </CardContent>
+ </Card>
+
+ {/* Right: Top Domains Chart (5 columns) */}
+ <Card className="lg:col-span-5">
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
+ <BarChart3 className="h-4 w-4" />
+ {t("topDomains")}
+ </CardTitle>
+ {selectedRuleData && (
+ <span className="text-xs text-muted-foreground">
+ {selectedRuleData.name}
+ </span>
+ )}
+ </div>
+ </CardHeader>
+ <CardContent>
+ {loading ? (
+ <div className="flex items-center justify-center py-8 h-[280px]">
+ <div className="h-5 w-5 border-2 border-primary/30 border-t-primary rounded-full animate-spin" />
+ </div>
+ ) : domainChartData.length === 0 ? (
+ <div className="text-center py-8 text-muted-foreground h-[280px] flex items-center justify-center">
+ {domainsT("noResults")}
+ </div>
+ ) : (
+ <div className="h-[280px] w-full min-w-0 overflow-hidden sm:overflow-visible">
+ <ResponsiveContainer width="100%" height="100%">
+ <BarChart
+ data={domainChartData}
+ layout="vertical"
+ margin={{ top: 5, right: showDomainBarLabels ? 50 : 10, left: 5, bottom: 5 }}
+ >
+ <CartesianGrid
+ strokeDasharray="3 3"
+ stroke="#888888"
+ opacity={0.2}
+ horizontal={false}
+ />
+ <XAxis
+ type="number"
+ tickFormatter={(value) => formatBytes(value, 0)}
+ tick={{ fill: "#888888", fontSize: 10 }}
+ tickLine={false}
+ axisLine={false}
+ />
+ <YAxis
+ type="category"
+ dataKey="name"
+ width={90}
+ tick={{ fontSize: 10, fill: "currentColor" }}
+ tickLine={false}
+ axisLine={false}
+ />
+ <RechartsTooltip
+ content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (
+ <div className="bg-background border border-border p-3 rounded-lg shadow-lg min-w-[200px] max-w-[90vw] sm:min-w-[280px]">
+ <div className="flex items-center gap-2 mb-3">
+ <Favicon domain={item.fullDomain} size="sm" />
+ <span className="font-medium text-sm text-foreground truncate max-w-[200px]">
+ {item.fullDomain}
+ </span>
+ </div>
+ <div className="space-y-2 text-xs">
+ <div className="flex justify-between items-center">
+ <span className="text-muted-foreground">Total Traffic</span>
+ <span className="font-semibold text-foreground">{formatBytes(item.total)}</span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-blue-500">Download</span>
+ <span className="text-foreground">{formatBytes(item.download)}</span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-purple-500">Upload</span>
+ <span className="text-foreground">{formatBytes(item.upload)}</span>
+ </div>
+ <div className="flex justify-between items-center pt-1 border-t border-border/50">
+ <span className="text-emerald-500">Connections</span>
+ <span className="text-foreground">{formatNumber(item.connections)}</span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ return null;
+ }}
+ cursor={{ fill: "rgba(128, 128, 128, 0.1)" }}
+ />
+ <Bar
+ dataKey="total"
+ radius={[0, 4, 4, 0]}
+ maxBarSize={24}
+ >
+ {domainChartData.map((entry, index) => (
+ <BarCell key={`cell-${index}`} fill={entry.color} />
+ ))}
+ {showDomainBarLabels && (
+ <LabelList
+ dataKey="total"
+ position="right"
+ content={renderCustomBarLabel}
+ />
+ )}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+
+ {/* Unified Chain Flow Visualization - shows all rules, highlights selected */}
+ <UnifiedRuleChainFlow
+ selectedRule={selectedRule}
+ activeBackendId={activeBackendId}
+ />
+
+ {/* Bottom Section: Domain List & IP Addresses with pagination */}
+ {selectedRule && (
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
+ {/* Simplified Tabs - no icons, no counts, like Domains page */}
+ <TabsList className="glass">
+ <TabsTrigger value="domains">
+ {domainsT("domainList")}
+ </TabsTrigger>
+ <TabsTrigger value="ips">
+ {ipsT("ipList")}
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="domains" className="mt-4">
+ <Card>
+ {/* Header with search */}
+ <div className="p-4 border-b border-border/50">
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div>
+ <h3 className="text-base font-semibold">{domainsT("associatedDomains")}</h3>
+ <p className="text-sm text-muted-foreground">
+ {filteredDomains.length} {domainsT("domainsCount")}
+ </p>
+ </div>
+ <div className="relative">
+ <Input
+ placeholder={domainsT("search")}
+ value={domainSearch}
+ onChange={(e) => {
+ setDomainSearch(e.target.value);
+ setDomainPage(1);
+ }}
+ className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
+ />
+ </div>
+ </div>
+ </div>
+
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : filteredDomains.length === 0 ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {domainSearch ? domainsT("noResults") : "No domains found"}
+ </div>
+ ) : (
+ <>
+ {/* Desktop Table Header */}
+ <div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
+ <div
+ className="col-span-4 flex items-center cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleDomainSort("domain")}
+ >
+ {domainsT("domain")}
+ <DomainSortIcon column="domain" />
+ </div>
+ <div
+ className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleDomainSort("totalDownload")}
+ >
+ {domainsT("download")}
+ <DomainSortIcon column="totalDownload" />
+ </div>
+ <div
+ className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleDomainSort("totalUpload")}
+ >
+ {domainsT("upload")}
+ <DomainSortIcon column="totalUpload" />
+ </div>
+ <div
+ className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleDomainSort("totalConnections")}
+ >
+ {domainsT("conn")}
+ <DomainSortIcon column="totalConnections" />
+ </div>
+ <div className="col-span-2 flex items-center justify-end">
+ {domainsT("ipCount")}
+ </div>
+ </div>
+
+ {/* Mobile Sort Bar */}
+ <div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
+ {([
+ { key: "domain" as DomainSortKey, label: domainsT("domain") },
+ { key: "totalDownload" as DomainSortKey, label: domainsT("download") },
+ { key: "totalUpload" as DomainSortKey, label: domainsT("upload") },
+ { key: "totalConnections" as DomainSortKey, label: domainsT("conn") },
+ ]).map(({ key, label }) => (
+ <button
+ key={key}
+ className={cn(
+ "flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
+ domainSortKey === key
+ ? "bg-primary/10 text-primary"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => handleDomainSort(key)}
+ >
+ {label}
+ {domainSortKey === key && (
+ domainSortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
+ )}
+ </button>
+ ))}
+ </div>
+
+ {/* Domain List */}
+ <div className="divide-y divide-border/30">
+ {(() => {
+ const totalDomainTraffic = filteredDomains.reduce(
+ (sum, d) => sum + d.totalDownload + d.totalUpload, 0
+ );
+ return paginatedDomains.map((domain, index) => {
+ const domainTraffic = domain.totalDownload + domain.totalUpload;
+ const percent = totalDomainTraffic > 0 ? (domainTraffic / totalDomainTraffic) * 100 : 0;
+ const isExpanded = expandedDomain === domain.domain;
+
+ return (
+ <div key={domain.domain} className="group">
+ {/* Desktop Row */}
+ <div
+ className={cn(
+ "hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",
+ isExpanded && "bg-secondary/10"
+ )}
+ style={{ animationDelay: `${index * 50}ms` }}
+ onClick={() => toggleExpandDomain(domain.domain)}
+ >
+ {/* Domain with Favicon */}
+ <div className="col-span-4 flex items-center gap-3 min-w-0">
+ <Favicon domain={domain.domain} size="sm" className="shrink-0" />
+ <span className="font-medium text-sm truncate" title={domain.domain}>
+ {domain.domain}
+ </span>
+ </div>
+
+ {/* Download */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
+ </div>
+
+ {/* Upload */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
+ </div>
+
+ {/* Connections */}
+ <div className="col-span-2 flex items-center justify-end">
+ <span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
+ {formatNumber(domain.totalConnections)}
+ </span>
+ </div>
+
+ {/* IP Count - Clickable */}
+ <div className="col-span-2 flex items-center justify-end">
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-2 gap-1 text-xs font-medium transition-all",
+ isExpanded
+ ? "bg-primary/10 text-primary hover:bg-primary/20"
+ : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpandDomain(domain.domain);
+ }}
+ >
+ <Server className="h-3 w-3" />
+ {domain.ips.length}
+ {isExpanded ? (
+ <ChevronUp className="h-3 w-3 ml-0.5" />
+ ) : (
+ <ChevronDown className="h-3 w-3 ml-0.5" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ {/* Mobile Row - Card-style layout */}
+ <div
+ className={cn(
+ "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
+ isExpanded && "bg-secondary/10"
+ )}
+ onClick={() => toggleExpandDomain(domain.domain)}
+ >
+ {/* Top: Favicon + Domain + Expand */}
+ <div className="flex items-center gap-2.5 mb-2">
+ <Favicon domain={domain.domain} size="sm" className="shrink-0" />
+ <span className="font-medium text-sm truncate flex-1" title={domain.domain}>
+ {domain.domain}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-2 gap-1 text-xs font-medium shrink-0",
+ isExpanded
+ ? "bg-primary/10 text-primary"
+ : "bg-secondary/50 text-muted-foreground"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpandDomain(domain.domain);
+ }}
+ >
+ <Server className="h-3 w-3" />
+ {domain.ips.length}
+ {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
+ </Button>
+ </div>
+
+ {/* Bottom: Stats row */}
+ <div className="flex items-center justify-between text-xs pl-[30px]">
+ <span className="text-blue-500 tabular-nums">↓ {formatBytes(domain.totalDownload)}</span>
+ <span className="text-purple-500 tabular-nums">↑ {formatBytes(domain.totalUpload)}</span>
+ <span className="px-2 py-0.5 rounded-full bg-secondary text-muted-foreground font-medium">
+ {formatNumber(domain.totalConnections)} {domainsT("conn")}
+ </span>
+ </div>
+ </div>
+
+ {/* Expanded Details: Associated IPs */}
+ {isExpanded && (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className="pt-3">
+ {/* Associated IPs */}
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {domainsT("associatedIPs")}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {domain.ips.map((ip) => {
+ const gradient = getIPGradient(ip);
+ return (
+ <div
+ key={ip}
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}>
+ <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
+ </div>
+ <code className="text-xs font-mono break-all">{ip}</code>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ });
+ })()}
+ </div>
+
+ {/* Pagination */}
+ {filteredDomains.length > 0 && (
+ <div className="p-3 border-t border-border/50 bg-secondary/20">
+ <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
+ <Rows3 className="h-4 w-4" />
+ <span>{domainPageSize} / {domainsT("page")}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {PAGE_SIZE_OPTIONS.map((size) => (
+ <DropdownMenuItem
+ key={size}
+ onClick={() => {
+ setDomainPageSize(size);
+ setDomainPage(1);
+ }}
+ className={domainPageSize === size ? "bg-primary/10" : ""}
+ >
+ {size} / {domainsT("page")}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <span className="text-sm text-muted-foreground">
+ {domainsT("total")} {filteredDomains.length}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <p className="text-xs text-muted-foreground">
+ {(domainPage - 1) * domainPageSize + 1}-{Math.min(domainPage * domainPageSize, filteredDomains.length)} / {filteredDomains.length}
+ </p>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => setDomainPage(p => Math.max(1, p - 1))}
+ disabled={domainPage === 1}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ {getPageNumbers(domainPage, domainTotalPages).map((page, idx) => (
+ page === '...' ? (
+ <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
+ ) : (
+ <Button
+ key={page}
+ variant={domainPage === page ? "default" : "ghost"}
+ size="sm"
+ className="h-8 w-8 px-0 text-xs"
+ onClick={() => setDomainPage(page as number)}
+ >
+ {page}
+ </Button>
+ )
+ ))}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => setDomainPage(p => Math.min(domainTotalPages, p + 1))}
+ disabled={domainPage === domainTotalPages}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </TabsContent>
+
+ <TabsContent value="ips" className="mt-4">
+ <Card>
+ {/* Header with search */}
+ <div className="p-4 border-b border-border/50">
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div>
+ <h3 className="text-base font-semibold">{ipsT("associatedIPs")}</h3>
+ <p className="text-sm text-muted-foreground">
+ {filteredIPs.length} IPs
+ </p>
+ </div>
+ <div className="relative">
+ <Input
+ placeholder={ipsT("search")}
+ value={ipSearch}
+ onChange={(e) => {
+ setIpSearch(e.target.value);
+ setIpPage(1);
+ }}
+ className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
+ />
+ </div>
+ </div>
+ </div>
+
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : filteredIPs.length === 0 ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {ipSearch ? ipsT("noResults") : "No IPs found"}
+ </div>
+ ) : (
+ <>
+ {/* Desktop Table Header */}
+ <div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
+ <div
+ className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleIPSort("ip")}
+ >
+ {ipsT("ipAddress")}
+ <IPSortIcon column="ip" />
+ </div>
+ <div className="col-span-2 flex items-center">
+ {ipsT("location")}
+ </div>
+ <div
+ className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleIPSort("totalDownload")}
+ >
+ {ipsT("download")}
+ <IPSortIcon column="totalDownload" />
+ </div>
+ <div
+ className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleIPSort("totalUpload")}
+ >
+ {ipsT("upload")}
+ <IPSortIcon column="totalUpload" />
+ </div>
+ <div
+ className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleIPSort("totalConnections")}
+ >
+ {ipsT("conn")}
+ <IPSortIcon column="totalConnections" />
+ </div>
+ <div className="col-span-2 flex items-center justify-end">
+ {ipsT("domainCount")}
+ </div>
+ </div>
+
+ {/* Mobile Sort Bar */}
+ <div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
+ {([
+ { key: "ip" as IPSortKey, label: ipsT("ipAddress") },
+ { key: "totalDownload" as IPSortKey, label: ipsT("download") },
+ { key: "totalUpload" as IPSortKey, label: ipsT("upload") },
+ { key: "totalConnections" as IPSortKey, label: ipsT("conn") },
+ ]).map(({ key, label }) => (
+ <button
+ key={key}
+ className={cn(
+ "flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
+ ipSortKey === key
+ ? "bg-primary/10 text-primary"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => handleIPSort(key)}
+ >
+ {label}
+ {ipSortKey === key && (
+ ipSortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
+ )}
+ </button>
+ ))}
+ </div>
+
+ {/* IP List */}
+ <div className="divide-y divide-border/30">
+ {(() => {
+ const totalIPTraffic = filteredIPs.reduce(
+ (sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0
+ );
+ return paginatedIPs.map((ip, index) => {
+ const ipTraffic = ip.totalDownload + ip.totalUpload;
+ const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;
+ const isExpanded = expandedIP === ip.ip;
+ const ipColor = getIPColor(ip.ip);
+
+ return (
+ <div key={ip.ip} className="group">
+ {/* Desktop Row */}
+ <div
+ className={cn(
+ "hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",
+ isExpanded && "bg-secondary/10"
+ )}
+ style={{ animationDelay: `${index * 50}ms` }}
+ onClick={() => toggleExpandIP(ip.ip)}
+ >
+ {/* IP with Icon */}
+ <div className="col-span-3 flex items-center gap-3 min-w-0">
+ <div className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
+ <Server className="w-3 h-3" />
+ </div>
+ <code className="text-sm font-mono truncate">{ip.ip}</code>
+ </div>
+
+ {/* Location */}
+ <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ {ip.geoIP && ip.geoIP.length > 0 ? (
+ <>
+ <span className="text-sm shrink-0" title={ip.geoIP[1] || ip.geoIP[0]}>
+ {getCountryFlag(ip.geoIP[0])}
+ </span>
+ <span className="text-xs truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ </>
+ ) : (
+ <span className="text-xs text-muted-foreground">-</span>
+ )}
+ </div>
+
+ {/* Download */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-blue-500">{formatBytes(ip.totalDownload)}</span>
+ </div>
+
+ {/* Upload */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-purple-500">{formatBytes(ip.totalUpload)}</span>
+ </div>
+
+ {/* Connections */}
+ <div className="col-span-1 flex items-center justify-end">
+ <span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
+ {formatNumber(ip.totalConnections)}
+ </span>
+ </div>
+
+ {/* Domains Count - Clickable */}
+ <div className="col-span-2 flex items-center justify-end">
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-2 gap-1 text-xs font-medium transition-all",
+ isExpanded
+ ? "bg-primary/10 text-primary hover:bg-primary/20"
+ : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpandIP(ip.ip);
+ }}
+ >
+ <Link2 className="h-3 w-3" />
+ {ip.domains.length}
+ {isExpanded ? (
+ <ChevronUp className="h-3 w-3 ml-0.5" />
+ ) : (
+ <ChevronDown className="h-3 w-3 ml-0.5" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ {/* Mobile Row - Card-style layout */}
+ <div
+ className={cn(
+ "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
+ isExpanded && "bg-secondary/10"
+ )}
+ onClick={() => toggleExpandIP(ip.ip)}
+ >
+ {/* Top: IP Icon + IP + Location + Expand */}
+ <div className="flex items-center gap-2.5 mb-2">
+ <div className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
+ <Server className="w-3 h-3" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <code className="text-sm font-medium truncate block">{ip.ip}</code>
+ {ip.geoIP && ip.geoIP.length > 0 && (
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <span className="text-sm">{getCountryFlag(ip.geoIP[0])}</span>
+ <span className="truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ </div>
+ )}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-2 gap-1 text-xs font-medium shrink-0",
+ isExpanded
+ ? "bg-primary/10 text-primary"
+ : "bg-secondary/50 text-muted-foreground"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpandIP(ip.ip);
+ }}
+ >
+ <Link2 className="h-3 w-3" />
+ {ip.domains.length}
+ {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
+ </Button>
+ </div>
+
+ {/* Bottom: Stats row */}
+ <div className="flex items-center justify-between text-xs pl-[30px]">
+ <span className="text-blue-500 tabular-nums">↓ {formatBytes(ip.totalDownload)}</span>
+ <span className="text-purple-500 tabular-nums">↑ {formatBytes(ip.totalUpload)}</span>
+ <span className="px-2 py-0.5 rounded-full bg-secondary text-muted-foreground font-medium">
+ {formatNumber(ip.totalConnections)} {ipsT("conn")}
+ </span>
+ </div>
+ </div>
+
+ {/* Expanded Details: Associated Domains */}
+ {isExpanded && (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className="pt-3">
+ {/* Associated Domains */}
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Link2 className="h-3 w-3" />
+ {ipsT("associatedDomains")}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {ip.domains.map((domain) => {
+ const domainColor = getDomainColor(domain);
+ return (
+ <div
+ key={domain}
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}>
+ <Globe className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
+ </div>
+ <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">{domain}</span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ });
+ })()}
+ </div>
+
+ {/* Pagination */}
+ {filteredIPs.length > 0 && (
+ <div className="p-3 border-t border-border/50 bg-secondary/20">
+ <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
+ <Rows3 className="h-4 w-4" />
+ <span>{ipPageSize} / {ipsT("page")}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {PAGE_SIZE_OPTIONS.map((size) => (
+ <DropdownMenuItem
+ key={size}
+ onClick={() => {
+ setIpPageSize(size);
+ setIpPage(1);
+ }}
+ className={ipPageSize === size ? "bg-primary/10" : ""}
+ >
+ {size} / {ipsT("page")}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <span className="text-sm text-muted-foreground">
+ {ipsT("total")} {filteredIPs.length}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <p className="text-xs text-muted-foreground">
+ {(ipPage - 1) * ipPageSize + 1}-{Math.min(ipPage * ipPageSize, filteredIPs.length)} / {filteredIPs.length}
+ </p>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => setIpPage(p => Math.max(1, p - 1))}
+ disabled={ipPage === 1}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ {getPageNumbers(ipPage, ipTotalPages).map((page, idx) => (
+ page === '...' ? (
+ <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
+ ) : (
+ <Button
+ key={page}
+ variant={ipPage === page ? "default" : "ghost"}
+ size="sm"
+ className="h-8 w-8 px-0 text-xs"
+ onClick={() => setIpPage(page as number)}
+ >
+ {page}
+ </Button>
+ )
+ ))}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => setIpPage(p => Math.min(ipTotalPages, p + 1))}
+ disabled={ipPage === ipTotalPages}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </TabsContent>
+ </Tabs>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsx
index 01a5b84..b23ed25 100644
--- a/apps/web/components/ips-table.tsx
+++ b/apps/web/components/ips-table.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useMemo, useCallback } from "react";
+import { useState, useCallback, useEffect, useRef } from "react";
import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, Globe, Server, ChevronDown, ChevronUp, Link2, Waypoints, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
@@ -17,7 +17,7 @@ import {
} from "@/components/ui/dropdown-menu";
interface IPsTableProps {
- data: IPStats[];
+ activeBackendId?: number;
}
type SortKey = "ip" | "totalDownload" | "totalUpload" | "totalConnections" | "lastSeen";
@@ -69,9 +69,13 @@ function getCountryFlag(country: string): string {
return COUNTRY_FLAGS[country] || COUNTRY_FLAGS[country.toUpperCase()] || "🌐";
}
-export function IPsTable({ data }: IPsTableProps) {
+export function IPsTable({ activeBackendId }: IPsTableProps) {
const t = useTranslations("ips");
+ const [data, setData] = useState<IPStats[]>([]);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(false);
const [search, setSearch] = useState("");
+ const [debouncedSearch, setDebouncedSearch] = useState("");
const [sortKey, setSortKey] = useState<SortKey>("totalDownload");
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
const [currentPage, setCurrentPage] = useState(1);
@@ -79,10 +83,51 @@ export function IPsTable({ data }: IPsTableProps) {
const [expandedIP, setExpandedIP] = useState<string | null>(null);
const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});
const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ // Debounce search input
+ useEffect(() => {
+ debounceRef.current = setTimeout(() => {
+ setDebouncedSearch(search);
+ setCurrentPage(1);
+ }, 300);
+ return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
+ }, [search]);
+
+ // Fetch data from server
+ useEffect(() => {
+ let cancelled = false;
+ const fetchData = async () => {
+ setLoading(true);
+ try {
+ const result = await api.getIPs(activeBackendId, {
+ offset: (currentPage - 1) * pageSize,
+ limit: pageSize,
+ sortBy: sortKey,
+ sortOrder,
+ search: debouncedSearch || undefined,
+ });
+ if (!cancelled) {
+ setData(result.data);
+ setTotal(result.total);
+ }
+ } catch (err) {
+ console.error("Failed to fetch IPs:", err);
+ if (!cancelled) {
+ setData([]);
+ setTotal(0);
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ };
+ fetchData();
+ return () => { cancelled = true; };
+ }, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch]);
// Fetch proxy stats when an IP is expanded
const fetchProxyStats = useCallback(async (ip: string) => {
- if (proxyStats[ip]) return; // Already cached
+ if (proxyStats[ip]) return;
setProxyStatsLoading(ip);
try {
const stats = await api.getIPProxyStats(ip);
@@ -105,34 +150,10 @@ export function IPsTable({ data }: IPsTableProps) {
setCurrentPage(1);
};
- const filteredData = useMemo(() => {
- return (data || [])
- .filter((ip) =>
- ip.ip.toLowerCase().includes(search.toLowerCase()) ||
- ip.domains.some((d) => d.toLowerCase().includes(search.toLowerCase()))
- )
- .sort((a, b) => {
- const aValue = a[sortKey];
- const bValue = b[sortKey];
- const modifier = sortOrder === "asc" ? 1 : -1;
-
- if (typeof aValue === "string" && typeof bValue === "string") {
- return aValue.localeCompare(bValue) * modifier;
- }
- return ((aValue as number) - (bValue as number)) * modifier;
- });
- }, [data, search, sortKey, sortOrder]);
-
- // Pagination
- const totalPages = Math.ceil(filteredData.length / pageSize);
- const paginatedData = useMemo(() => {
- const start = (currentPage - 1) * pageSize;
- return filteredData.slice(start, start + pageSize);
- }, [filteredData, currentPage, pageSize]);
+ const totalPages = Math.ceil(total / pageSize);
const handleSearchChange = (value: string) => {
setSearch(value);
- setCurrentPage(1);
};
const handlePageSizeChange = (size: PageSize) => {
@@ -161,7 +182,7 @@ export function IPsTable({ data }: IPsTableProps) {
const getPageNumbers = () => {
const pages: (number | string)[] = [];
const maxVisible = 5;
-
+
if (totalPages <= maxVisible) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
@@ -192,7 +213,7 @@ export function IPsTable({ data }: IPsTableProps) {
<div>
<h3 className="text-lg font-semibold">{t("title")}</h3>
<p className="text-sm text-muted-foreground">
- {filteredData.length} {t("ipsCount")}
+ {total} {t("ipsCount")}
</p>
</div>
<div className="relative">
@@ -209,7 +230,7 @@ export function IPsTable({ data }: IPsTableProps) {
{/* Desktop Table Header */}
<div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
+ <div
className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("ip")}
>
@@ -222,14 +243,14 @@ export function IPsTable({ data }: IPsTableProps) {
<div className="col-span-1 flex items-center">
{t("location")}
</div>
- <div
+ <div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalDownload")}
>
{t("download")}
<SortIcon column="totalDownload" />
</div>
- <div
+ <div
className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalUpload")}
>
@@ -275,15 +296,19 @@ export function IPsTable({ data }: IPsTableProps) {
{/* Table Body */}
<div className="divide-y divide-border/30 min-h-[300px]">
- {paginatedData.length === 0 ? (
+ {loading && data.length === 0 ? (
+ <div className="px-5 py-12 text-center text-muted-foreground">
+ <Loader2 className="h-6 w-6 animate-spin mx-auto mb-2" />
+ </div>
+ ) : data.length === 0 ? (
<div className="px-5 py-12 text-center text-muted-foreground">
{t("noResults")}
</div>
) : (
- paginatedData.map((ip, index) => {
+ data.map((ip, index) => {
const ipColor = getIPColor(ip.ip);
const isExpanded = expandedIP === ip.ip;
-
+
return (
<div key={ip.ip} className="group">
{/* Desktop Row */}
@@ -365,8 +390,8 @@ export function IPsTable({ data }: IPsTableProps) {
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium transition-all",
- isExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
+ isExpanded
+ ? "bg-primary/10 text-primary hover:bg-primary/20"
: "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
)}
onClick={(e) => {
@@ -406,8 +431,8 @@ export function IPsTable({ data }: IPsTableProps) {
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isExpanded
- ? "bg-primary/10 text-primary"
+ isExpanded
+ ? "bg-primary/10 text-primary"
: "bg-secondary/50 text-muted-foreground"
)}
onClick={(e) => {
@@ -589,19 +614,19 @@ export function IPsTable({ data }: IPsTableProps) {
</DropdownMenuContent>
</DropdownMenu>
<span className="text-sm text-muted-foreground">
- {t("total")} {filteredData.length}
+ {t("total")} {total}
</span>
</div>
-
+
{/* Pagination info and controls */}
<div className="flex items-center gap-2 sm:gap-3">
<p className="text-xs sm:text-sm text-muted-foreground hidden sm:block">
- {t("showing")} {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, filteredData.length)} {t("of")} {filteredData.length}
+ {t("showing")} {Math.min((currentPage - 1) * pageSize + 1, total)} - {Math.min(currentPage * pageSize, total)} {t("of")} {total}
</p>
<p className="text-xs text-muted-foreground sm:hidden">
- {(currentPage - 1) * pageSize + 1}-{Math.min(currentPage * pageSize, filteredData.length)} / {filteredData.length}
+ {Math.min((currentPage - 1) * pageSize + 1, total)}-{Math.min(currentPage * pageSize, total)} / {total}
</p>
-
+
<div className="flex items-center gap-1">
<Button
variant="ghost"
@@ -612,7 +637,7 @@ export function IPsTable({ data }: IPsTableProps) {
>
<ChevronLeft className="h-4 w-4" />
</Button>
-
+
{getPageNumbers().map((page, idx) => (
page === '...' ? (
<span key={`ellipsis-${idx}`} className="px-1 sm:px-2 text-muted-foreground text-xs">...</span>
@@ -628,7 +653,7 @@ export function IPsTable({ data }: IPsTableProps) {
</Button>
)
))}
-
+
<Button
variant="ghost"
size="icon"
diff --git a/apps/web/components/navigation.tsx b/apps/web/components/navigation.tsx
index 0f98299..bd7a491 100644
--- a/apps/web/components/navigation.tsx
+++ b/apps/web/components/navigation.tsx
@@ -24,7 +24,14 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { useVersionCheck } from "@/hooks/use-version-check";
+import { usePWAInstall } from "@/hooks/use-pwa-install";
interface NavigationProps {
activeTab: string;
@@ -37,10 +44,10 @@ const GITHUB_URL = "https://github.com/foru17/clash-master";
const NAV_ITEMS = [
{ id: "overview", icon: LayoutDashboard },
+ { id: "rules", icon: Route },
{ id: "domains", icon: Globe },
{ id: "countries", icon: MapPin },
{ id: "proxies", icon: Server },
- { id: "rules", icon: Route },
];
export function Navigation({
@@ -56,6 +63,8 @@ export function Navigation({
const aboutT = useTranslations("about");
const { latestVersion, hasUpdate, isChecking, stars, checkNow } =
useVersionCheck(APP_VERSION);
+ const { canInstall, promptInstall } = usePWAInstall();
+ const pwaT = useTranslations("pwa");
return (
<>
@@ -102,6 +111,32 @@ export function Navigation({
})}
</nav>
+ {/* PWA Install Prompt */}
+ {canInstall && (
+ <div className="px-4 pb-3">
+ <TooltipProvider delayDuration={300}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={promptInstall}
+ className="group w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all bg-gradient-to-r from-primary/8 to-primary/4 hover:from-primary/14 hover:to-primary/8 border border-primary/15 hover:border-primary/30">
+ <span className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10 group-hover:bg-primary/15 transition-colors">
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-primary">
+ <path d="M8 1.5v8m0 0L5 6.5m3 3 3-3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
+ <path d="M2.5 10.5v2a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
+ </svg>
+ </span>
+ <span className="text-primary/90">{pwaT("installApp")}</span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-[200px]">
+ <p className="text-xs">{pwaT("tooltip")}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ )}
+
{/* Bottom Actions */}
<div className="p-4 border-t border-border/40 space-y-1">
<button
diff --git a/apps/web/components/rule-chain-flow.tsx b/apps/web/components/rule-chain-flow.tsx
new file mode 100644
index 0000000..750dea1
--- /dev/null
+++ b/apps/web/components/rule-chain-flow.tsx
@@ -0,0 +1,677 @@
+"use client";
+
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
+import {
+ ReactFlow,
+ ReactFlowProvider,
+ Background,
+ Controls,
+ Handle,
+ getStraightPath,
+ useReactFlow,
+ type Node,
+ type Edge,
+ type EdgeProps,
+ Position,
+ useNodesState,
+ useEdgesState,
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import { Workflow, Loader2, Server, Layers, Eye } from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { cn, formatBytes, formatNumber } from "@/lib/utils";
+import { useTheme } from "next-themes";
+import { api } from "@/lib/api";
+import { useTranslations } from "next-intl";
+
+// ---------- Types ----------
+
+interface MergedChainNode {
+ name: string;
+ layer: number;
+ nodeType: "rule" | "group" | "proxy";
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ rules: string[];
+}
+
+interface AllChainFlowData {
+ nodes: MergedChainNode[];
+ links: Array<{ source: number; target: number; rules: string[] }>;
+ rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }>;
+ maxLayer: number;
+}
+
+interface UnifiedRuleChainFlowProps {
+ selectedRule: string | null;
+ activeBackendId?: number;
+}
+
+// ---------- Layout constants ----------
+
+const COLUMN_WIDTH = 280;
+const NODE_HEIGHT = 95;
+const OTHER_NODES_OFFSET = 130;
+
+// ---------- Custom Edge ----------
+
+function MergedAnimatedFlowEdge({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ data,
+}: EdgeProps) {
+ const edgeData = data as
+ | { isToProxy?: boolean; dimmed?: boolean; showAll?: boolean }
+ | undefined;
+ const isToProxy = edgeData?.isToProxy;
+ const dimmed = edgeData?.dimmed;
+ const showAll = edgeData?.showAll;
+ const [edgePath] = getStraightPath({ sourceX, sourceY, targetX, targetY });
+
+ const dotColor = isToProxy ? "#34d399" : "#a5b4fc";
+ const trackColor = isToProxy
+ ? "rgba(16, 185, 129, 0.12)"
+ : "rgba(129, 140, 248, 0.12)";
+ const lineColor = isToProxy
+ ? "rgba(16, 185, 129, 0.3)"
+ : "rgba(129, 140, 248, 0.3)";
+
+ // Particles only when actively highlighted (not dimmed and not showAll overview)
+ const showParticles = !dimmed && !showAll;
+
+ return (
+ <g
+ style={{ opacity: dimmed ? 0.12 : 1, transition: "opacity 0.4s ease" }}
+ >
+ <path
+ d={edgePath}
+ fill="none"
+ stroke={trackColor}
+ strokeWidth={10}
+ strokeLinecap="round"
+ />
+ <path
+ d={edgePath}
+ fill="none"
+ stroke={lineColor}
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ />
+ {showParticles && (
+ <>
+ <circle r="3.5" fill={dotColor} opacity="0.9">
+ <animateMotion
+ dur="2s"
+ repeatCount="indefinite"
+ path={edgePath}
+ begin="0s"
+ />
+ </circle>
+ <circle r="2.5" fill={dotColor} opacity="0.5">
+ <animateMotion
+ dur="2s"
+ repeatCount="indefinite"
+ path={edgePath}
+ begin="0.66s"
+ />
+ </circle>
+ <circle r="1.5" fill={dotColor} opacity="0.25">
+ <animateMotion
+ dur="2s"
+ repeatCount="indefinite"
+ path={edgePath}
+ begin="1.33s"
+ />
+ </circle>
+ </>
+ )}
+ </g>
+ );
+}
+
+// ---------- Custom Node ----------
+
+function MergedChainNodeComponent({
+ data,
+}: {
+ data: MergedChainNode & { dimmed?: boolean };
+}) {
+ const dimmed = data.dimmed;
+ const wrapStyle = {
+ opacity: dimmed ? 0.12 : 1,
+ transition: "opacity 0.4s ease",
+ };
+
+ // PROXY node - green theme with PROXY badge
+ if (data.nodeType === "proxy") {
+ return (
+ <div className="relative" style={wrapStyle}>
+ <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full bg-emerald-500 text-white text-[9px] font-semibold tracking-wider z-10 shadow-sm">
+ PROXY
+ </div>
+ <div className="relative px-5 py-3.5 rounded-xl border border-emerald-400/50 bg-gradient-to-br from-emerald-50 to-teal-50/50 dark:from-emerald-500/15 dark:to-emerald-500/5 min-w-[170px] shadow-md shadow-emerald-500/10 ring-1 ring-emerald-500/10">
+ <Handle
+ type="target"
+ position={Position.Left}
+ className="!w-2.5 !h-2.5 !bg-emerald-400 !border-emerald-500"
+ />
+ <div className="flex items-center gap-2.5 mb-2">
+ <div className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-gradient-to-br from-emerald-400 to-emerald-600 shadow-sm">
+ <Server className="h-4 w-4" />
+ </div>
+ <span className="text-xs font-semibold truncate flex-1 text-emerald-800 dark:text-emerald-200 max-w-[120px]">
+ {data.name}
+ </span>
+ </div>
+ <div className="flex items-center gap-3 text-[11px]">
+ <span className="text-emerald-600 dark:text-emerald-400">
+ ↓ {formatBytes(data.totalDownload)}
+ </span>
+ <span className="text-emerald-500/70 dark:text-emerald-400/60">
+ ↑ {formatBytes(data.totalUpload)}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ // Rule node - violet theme with connection count badge
+ if (data.nodeType === "rule") {
+ return (
+ <div className="relative" style={wrapStyle}>
+ <div className="relative px-5 py-3.5 rounded-xl border border-violet-300/50 dark:border-violet-500/30 bg-gradient-to-br from-violet-50 to-white dark:from-violet-500/15 dark:to-violet-900/20 min-w-[170px] shadow-sm">
+ <div className="flex items-center gap-2.5 mb-2">
+ <div className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-violet-500 shadow-sm">
+ <Workflow className="h-4 w-4" />
+ </div>
+ <span className="text-xs font-medium truncate flex-1 max-w-[120px]">
+ {data.name}
+ </span>
+ </div>
+ <div className="flex items-center gap-3 text-[11px] text-muted-foreground">
+ <span className="text-blue-500">
+ ↓ {formatBytes(data.totalDownload)}
+ </span>
+ <span className="text-purple-500">
+ ↑ {formatBytes(data.totalUpload)}
+ </span>
+ </div>
+ <div className="absolute -top-2.5 -right-2.5 px-1.5 py-0.5 rounded-full bg-violet-500 text-white text-[10px] font-medium shadow-sm">
+ {formatNumber(data.totalConnections)}
+ </div>
+ <Handle
+ type="source"
+ position={Position.Right}
+ className="!w-2 !h-2 !bg-indigo-300 !border-indigo-400"
+ />
+ </div>
+ </div>
+ );
+ }
+
+ // Group node - blue/indigo theme
+ return (
+ <div className="relative" style={wrapStyle}>
+ <div className="relative px-5 py-3.5 rounded-xl border border-blue-300/40 dark:border-blue-500/30 bg-gradient-to-br from-blue-50/80 to-white dark:from-blue-500/15 dark:to-blue-900/20 min-w-[170px] shadow-sm">
+ <Handle
+ type="target"
+ position={Position.Left}
+ className="!w-2 !h-2 !bg-indigo-300 !border-indigo-400"
+ />
+ <div className="flex items-center gap-2.5 mb-2">
+ <div className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-blue-500 shadow-sm">
+ <Layers className="h-4 w-4" />
+ </div>
+ <span className="text-xs font-medium truncate flex-1 max-w-[120px]">
+ {data.name}
+ </span>
+ </div>
+ <div className="flex items-center gap-3 text-[11px] text-muted-foreground">
+ <span className="text-blue-500">
+ ↓ {formatBytes(data.totalDownload)}
+ </span>
+ <span className="text-purple-500">
+ ↑ {formatBytes(data.totalUpload)}
+ </span>
+ </div>
+ <Handle
+ type="source"
+ position={Position.Right}
+ className="!w-2 !h-2 !bg-indigo-300 !border-indigo-400"
+ />
+ </div>
+ </div>
+ );
+}
+
+// ---------- Registered types (defined outside component to avoid re-creation) ----------
+
+const nodeTypes = { mergedChainNode: MergedChainNodeComponent };
+const edgeTypes = { mergedAnimatedFlow: MergedAnimatedFlowEdge };
+
+// ---------- Compute a structure fingerprint for detecting structural vs data-only changes ----------
+
+function computeStructureKey(data: AllChainFlowData): string {
+ const nodeNames = data.nodes.map((n) => n.name).join("|");
+ const linkKeys = data.links.map((l) => `${l.source}-${l.target}`).join("|");
+ return `${nodeNames}::${linkKeys}`;
+}
+
+// ---------- Inner renderer (needs ReactFlowProvider context) ----------
+
+function FlowRenderer({
+ data,
+ selectedRule,
+ showAll,
+}: {
+ data: AllChainFlowData;
+ selectedRule: string | null;
+ showAll: boolean;
+}) {
+ const { fitView } = useReactFlow();
+ const { resolvedTheme } = useTheme();
+ const isDark = resolvedTheme === "dark";
+ const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
+ const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
+ const isFirstRender = useRef(true);
+ const reactFlowReady = useRef(false);
+ const pendingFitViewRef = useRef<(() => void) | null>(null);
+ const prevStructureKeyRef = useRef<string>("");
+ const prevSelectedRuleRef = useRef<string | null>(null);
+ const prevShowAllRef = useRef<boolean>(false);
+
+ // Active chain indices
+ const activeIndices = useMemo(() => {
+ if (!selectedRule || !data.rulePaths[selectedRule]) return null;
+ return data.rulePaths[selectedRule];
+ }, [selectedRule, data]);
+
+ // Structure key to detect structural vs data-only changes
+ const structureKey = useMemo(() => computeStructureKey(data), [data]);
+
+ // Compute layout & trigger viewport animation
+ useEffect(() => {
+ if (data.nodes.length === 0) {
+ setNodes([]);
+ setEdges([]);
+ return;
+ }
+
+ // Detect if this is a data-only update (same structure, same selection, same showAll)
+ const isDataOnlyUpdate =
+ structureKey === prevStructureKeyRef.current &&
+ selectedRule === prevSelectedRuleRef.current &&
+ showAll === prevShowAllRef.current &&
+ !isFirstRender.current;
+
+ prevStructureKeyRef.current = structureKey;
+ prevSelectedRuleRef.current = selectedRule;
+ prevShowAllRef.current = showAll;
+
+ // For data-only updates: update node data in-place without re-layout or fitView
+ if (isDataOnlyUpdate) {
+ setNodes((prev) =>
+ prev.map((node) => {
+ const idx = Number(node.id);
+ const freshNode = data.nodes[idx];
+ if (!freshNode) return node;
+ const activeNodeSet = activeIndices
+ ? new Set(activeIndices.nodeIndices)
+ : null;
+ return {
+ ...node,
+ data: {
+ ...freshNode,
+ dimmed: activeNodeSet ? !activeNodeSet.has(idx) : false,
+ },
+ };
+ })
+ );
+ return;
+ }
+
+ const activeNodeSet = activeIndices
+ ? new Set(activeIndices.nodeIndices)
+ : null;
+
+ // Group nodes by layer, sort by traffic within each layer
+ const layerGroups = new Map<number, number[]>();
+ data.nodes.forEach((node, idx) => {
+ if (!layerGroups.has(node.layer))
+ layerGroups.set(node.layer, []);
+ layerGroups.get(node.layer)!.push(idx);
+ });
+ for (const [, indices] of layerGroups) {
+ indices.sort((a, b) => {
+ const at =
+ data.nodes[a].totalUpload + data.nodes[a].totalDownload;
+ const bt =
+ data.nodes[b].totalUpload + data.nodes[b].totalDownload;
+ return bt - at;
+ });
+ }
+
+ // ----- Position computation -----
+ const positions = new Map<number, { x: number; y: number }>();
+
+ if (activeNodeSet && !showAll) {
+ // FOCUSED MODE: selected chain nodes centered, fanned out per layer
+ // Group active nodes by layer (handles multiple proxies in same layer)
+ const activeByLayer = new Map<number, number[]>();
+ for (const nodeIdx of activeIndices!.nodeIndices) {
+ const layer = data.nodes[nodeIdx].layer;
+ if (!activeByLayer.has(layer))
+ activeByLayer.set(layer, []);
+ activeByLayer.get(layer)!.push(nodeIdx);
+ }
+
+ // Position active nodes: single → y=0, multiple → fanned vertically around y=0
+ for (const [layer, indices] of activeByLayer) {
+ indices.sort((a, b) => {
+ const at =
+ data.nodes[a].totalUpload + data.nodes[a].totalDownload;
+ const bt =
+ data.nodes[b].totalUpload + data.nodes[b].totalDownload;
+ return bt - at;
+ });
+ const count = indices.length;
+ const totalHeight = count * NODE_HEIGHT;
+ indices.forEach((nodeIdx, posInLayer) => {
+ positions.set(nodeIdx, {
+ x: layer * COLUMN_WIDTH,
+ y:
+ posInLayer * NODE_HEIGHT -
+ totalHeight / 2 +
+ NODE_HEIGHT / 2,
+ });
+ });
+ }
+
+ // Non-active nodes below: offset from the lowest active node
+ let maxActiveY = 0;
+ for (const pos of positions.values()) {
+ maxActiveY = Math.max(maxActiveY, pos.y);
+ }
+ for (const [layer, indices] of layerGroups) {
+ const others = indices.filter((i) => !activeNodeSet.has(i));
+ others.forEach((nodeIdx, posInLayer) => {
+ positions.set(nodeIdx, {
+ x: layer * COLUMN_WIDTH,
+ y:
+ maxActiveY +
+ OTHER_NODES_OFFSET +
+ posInLayer * NODE_HEIGHT,
+ });
+ });
+ }
+ } else {
+ // SHOW-ALL / no selection: natural column layout, vertically centered
+ for (const [layer, indices] of layerGroups) {
+ const layerHeight = indices.length * NODE_HEIGHT;
+ indices.forEach((nodeIdx, posInLayer) => {
+ positions.set(nodeIdx, {
+ x: layer * COLUMN_WIDTH,
+ y: posInLayer * NODE_HEIGHT - layerHeight / 2,
+ });
+ });
+ }
+ }
+
+ // ----- Build flow nodes -----
+ const flowNodes: Node[] = data.nodes.map((node, idx) => ({
+ id: String(idx),
+ type: "mergedChainNode",
+ position: positions.get(idx) || { x: 0, y: 0 },
+ data: {
+ ...node,
+ dimmed: activeNodeSet ? !activeNodeSet.has(idx) : false,
+ },
+ sourcePosition: Position.Right,
+ targetPosition: Position.Left,
+ }));
+
+ // ----- Build flow edges -----
+ const activeLinkSet = activeIndices
+ ? new Set(activeIndices.linkIndices)
+ : null;
+ const flowEdges: Edge[] = data.links.map((link, idx) => {
+ const targetNode = data.nodes[link.target];
+ const isToProxy = targetNode?.nodeType === "proxy";
+ const isDimmed = activeLinkSet ? !activeLinkSet.has(idx) : false;
+ return {
+ id: `e-${link.source}-${link.target}`,
+ source: String(link.source),
+ target: String(link.target),
+ type: "mergedAnimatedFlow",
+ data: { isToProxy, dimmed: isDimmed, showAll },
+ };
+ });
+
+ setNodes(flowNodes);
+ setEdges(flowEdges);
+
+ // ----- Animate viewport -----
+ const duration = isFirstRender.current ? 0 : 400;
+ isFirstRender.current = false;
+
+ const doFitView = () => {
+ if (showAll || !activeIndices) {
+ fitView({ duration, padding: 0.15 });
+ } else {
+ fitView({
+ nodes: activeIndices.nodeIndices.map((i) => ({
+ id: String(i),
+ })),
+ duration,
+ padding: 0.15,
+ });
+ }
+ };
+
+ // If ReactFlow hasn't initialized yet, defer fitView to onInit callback
+ if (!reactFlowReady.current) {
+ pendingFitViewRef.current = doFitView;
+ return;
+ }
+
+ // Use double rAF to ensure container resize + React commit + ReactFlow
+ // internal ResizeObserver have all completed before computing the viewport.
+ let cancelled = false;
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ if (cancelled) return;
+ doFitView();
+ });
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [data, activeIndices, showAll, structureKey, setNodes, setEdges, fitView]);
+
+ // Called when ReactFlow instance is ready — execute any pending fitView
+ const handleInit = useCallback(() => {
+ reactFlowReady.current = true;
+ if (pendingFitViewRef.current) {
+ const pending = pendingFitViewRef.current;
+ pendingFitViewRef.current = null;
+ // Still use rAF to let the first paint with nodes complete
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ pending();
+ });
+ });
+ }
+ }, []);
+
+ return (
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ nodeTypes={nodeTypes}
+ edgeTypes={edgeTypes}
+ onInit={handleInit}
+ colorMode={isDark ? "dark" : "light"}
+ attributionPosition="bottom-right"
+ nodesDraggable={false}
+ nodesConnectable={false}
+ edgesFocusable={false}
+ zoomOnScroll={false}
+ panOnScroll={false}
+ zoomOnDoubleClick={false}
+ className="chain-flow-graph"
+ >
+ <Background color={isDark ? "#374151" : "#e5e7eb"} gap={20} size={1} />
+ <Controls showInteractive={false} />
+ </ReactFlow>
+ );
+}
+
+// ---------- Main component ----------
+
+export function UnifiedRuleChainFlow({
+ selectedRule,
+ activeBackendId,
+}: UnifiedRuleChainFlowProps) {
+ const t = useTranslations("rules");
+ const [data, setData] = useState<AllChainFlowData | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [showAll, setShowAll] = useState(false);
+ const prevRuleRef = useRef(selectedRule);
+
+ // Initial fetch + background polling every 5 seconds
+ useEffect(() => {
+ let cancelled = false;
+ let interval: ReturnType<typeof setInterval> | null = null;
+
+ async function initialLoad() {
+ setLoading(true);
+ setError(null);
+ try {
+ const result = await api.getAllRuleChainFlows(activeBackendId);
+ if (cancelled) return;
+ setData(result);
+ setLoading(false);
+ // Start polling after successful initial load
+ interval = setInterval(async () => {
+ try {
+ const fresh = await api.getAllRuleChainFlows(activeBackendId);
+ if (!cancelled) setData(fresh);
+ } catch {
+ // Silent failure for background polls
+ }
+ }, 5000);
+ } catch (err) {
+ if (cancelled) return;
+ console.error("Failed to load chain flows:", err);
+ setError("Failed to load chain flows");
+ setLoading(false);
+ }
+ }
+
+ initialLoad();
+
+ return () => {
+ cancelled = true;
+ if (interval) clearInterval(interval);
+ };
+ }, [activeBackendId]);
+
+ // When user selects a different rule, auto-disable showAll
+ useEffect(() => {
+ if (selectedRule && selectedRule !== prevRuleRef.current) {
+ prevRuleRef.current = selectedRule;
+ setShowAll(false);
+ }
+ }, [selectedRule]);
+
+ // Container height: compact for focused mode, taller for show-all
+ const containerHeight = useMemo(() => {
+ if (!data || data.nodes.length === 0) return 280;
+
+ if (!showAll && selectedRule && data.rulePaths[selectedRule]) {
+ // Focused mode: just enough for the active chain
+ const activeNodes = data.rulePaths[selectedRule].nodeIndices;
+ const layerCounts = new Map<number, number>();
+ for (const idx of activeNodes) {
+ const layer = data.nodes[idx].layer;
+ layerCounts.set(layer, (layerCounts.get(layer) || 0) + 1);
+ }
+ const maxActiveInLayer =
+ layerCounts.size > 0 ? Math.max(...layerCounts.values()) : 1;
+ return Math.max(200, maxActiveInLayer * NODE_HEIGHT + 100);
+ }
+
+ // Show-all mode: full height based on densest layer
+ const layerCounts = new Map<number, number>();
+ data.nodes.forEach((node) => {
+ layerCounts.set(node.layer, (layerCounts.get(node.layer) || 0) + 1);
+ });
+ const maxNodesInLayer = Math.max(...layerCounts.values());
+ return Math.min(600, Math.max(300, maxNodesInLayer * 90 + 60));
+ }, [data, showAll, selectedRule]);
+
+ if (loading) {
+ return (
+ <Card className="mb-4">
+ <CardContent className="py-8">
+ <div className="flex items-center justify-center gap-2 text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span className="text-sm">{t("loadingChainFlow")}</span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ if (error || !data || data.nodes.length <= 1) {
+ return null;
+ }
+
+ return (
+ <Card className="mb-4 overflow-hidden">
+ <CardHeader className="pb-3">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-sm font-semibold flex items-center gap-2">
+ <Workflow className="h-4 w-4 text-primary" />
+ {t("chainFlow")}
+ </CardTitle>
+ <Button
+ variant={showAll ? "default" : "outline"}
+ size="sm"
+ className={cn(
+ "h-7 px-3 text-xs gap-1.5 rounded-full",
+ showAll && "bg-primary/90 hover:bg-primary"
+ )}
+ onClick={() => setShowAll(!showAll)}
+ >
+ <Eye className="h-3.5 w-3.5" />
+ {t("showAll")}
+ </Button>
+ </div>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <div style={{ height: containerHeight }} className="w-full">
+ <ReactFlowProvider>
+ <FlowRenderer
+ data={data}
+ selectedRule={showAll ? null : selectedRule}
+ showAll={showAll}
+ />
+ </ReactFlowProvider>
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+// Backward-compatible alias
+export { UnifiedRuleChainFlow as RuleChainFlow };
diff --git a/apps/web/components/stats-cards.tsx b/apps/web/components/stats-cards.tsx
index 3bb40ab..2e07010 100644
--- a/apps/web/components/stats-cards.tsx
+++ b/apps/web/components/stats-cards.tsx
@@ -1,7 +1,14 @@
"use client";
+import { useRef, useEffect } from "react";
import { Download, Upload, Globe, Activity, Server, Route } from "lucide-react";
import { useTranslations } from "next-intl";
+import {
+ motion,
+ useSpring,
+ useTransform,
+ useMotionValue,
+} from "framer-motion";
import { formatBytes } from "@/lib/utils";
import type { StatsSummary } from "@clashmaster/shared";
@@ -10,6 +17,45 @@ interface StatsCardsProps {
error?: string | null;
}
+// ---------- Animated number display ----------
+
+const springConfig = { stiffness: 80, damping: 20, mass: 0.5 };
+
+function AnimatedValue({
+ value,
+ formatter,
+ className,
+ title,
+}: {
+ value: number;
+ formatter: (n: number) => string;
+ className?: string;
+ title?: string;
+}) {
+ const motionValue = useMotionValue(0);
+ const spring = useSpring(motionValue, springConfig);
+ const display = useTransform(spring, (v) => formatter(Math.round(v)));
+ const isFirstRender = useRef(true);
+
+ useEffect(() => {
+ if (isFirstRender.current) {
+ // Jump to initial value instantly (no animation on mount)
+ motionValue.jump(value);
+ isFirstRender.current = false;
+ } else {
+ motionValue.set(value);
+ }
+ }, [value, motionValue]);
+
+ return (
+ <motion.span className={className} title={title}>
+ {display}
+ </motion.span>
+ );
+}
+
+// ---------- Stat Card ----------
+
function StatCard({
value,
label,
@@ -48,6 +94,53 @@ function StatCard({
);
}
+// ---------- Animated Stat Card (for numeric values) ----------
+
+function AnimatedStatCard({
+ value,
+ formatter,
+ label,
+ subvalue,
+ icon: Icon,
+ color,
+}: {
+ value: number;
+ formatter: (n: number) => string;
+ label: string;
+ subvalue?: string;
+ icon: React.ElementType;
+ color: string;
+}) {
+ return (
+ <div className="rounded-xl p-4 border bg-card flex flex-col">
+ <div
+ className="w-10 h-10 rounded-lg flex items-center justify-center mb-3"
+ style={{ backgroundColor: `${color}15` }}
+ >
+ <Icon className="w-5 h-5" style={{ color }} />
+ </div>
+ <div className="flex-1">
+ <p className="text-muted-foreground text-xs uppercase tracking-wider font-medium truncate">
+ {label}
+ </p>
+ <AnimatedValue
+ value={value}
+ formatter={formatter}
+ className="text-xl font-bold mt-1 tabular-nums truncate block"
+ title={formatter(value)}
+ />
+ {subvalue && (
+ <p className="text-xs text-muted-foreground mt-0.5 truncate">
+ {subvalue}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ---------- Circular Progress Card ----------
+
function CircularProgressCard({
value,
max,
@@ -64,10 +157,25 @@ function CircularProgressCard({
const radius = 28;
const strokeWidth = 4;
const circumference = radius * 2 * Math.PI;
- const percentage = Math.min(100, Math.max(0, (value / max) * 100));
- const offset = circumference - (percentage / 100) * circumference;
const size = 64;
+ // Animated progress ring
+ const percentage = Math.min(100, Math.max(0, (value / max) * 100));
+ const targetOffset = circumference - (percentage / 100) * circumference;
+
+ const motionOffset = useMotionValue(circumference);
+ const springOffset = useSpring(motionOffset, springConfig);
+ const isFirstRender = useRef(true);
+
+ useEffect(() => {
+ if (isFirstRender.current) {
+ motionOffset.jump(targetOffset);
+ isFirstRender.current = false;
+ } else {
+ motionOffset.set(targetOffset);
+ }
+ }, [targetOffset, motionOffset]);
+
return (
<div className="rounded-xl p-4 border bg-card flex flex-col">
<div className="mb-3">
@@ -82,7 +190,7 @@ function CircularProgressCard({
fill="transparent"
className="text-muted/15"
/>
- <circle
+ <motion.circle
cx={size / 2}
cy={size / 2}
r={radius}
@@ -90,7 +198,7 @@ function CircularProgressCard({
strokeWidth={strokeWidth}
fill="transparent"
strokeDasharray={circumference}
- strokeDashoffset={offset}
+ strokeDashoffset={springOffset}
strokeLinecap="round"
/>
</svg>
@@ -103,14 +211,19 @@ function CircularProgressCard({
<p className="text-muted-foreground text-xs uppercase tracking-wider font-medium truncate">
{label}
</p>
- <p className="text-xl font-bold mt-1 tabular-nums truncate" title={formatBytes(value)}>
- {formatBytes(value)}
- </p>
+ <AnimatedValue
+ value={value}
+ formatter={formatBytes}
+ className="text-xl font-bold mt-1 tabular-nums truncate block"
+ title={formatBytes(value)}
+ />
</div>
</div>
);
}
+// ---------- Today Card ----------
+
function TodayCard({
download,
upload,
@@ -139,15 +252,19 @@ function TodayCard({
<div className="mt-2 space-y-1.5">
<div className="flex items-center justify-between gap-2">
<span className="text-xs text-muted-foreground truncate">{downloadLabel}</span>
- <span className="text-sm font-semibold tabular-nums truncate">
- {formatBytes(download)}
- </span>
+ <AnimatedValue
+ value={download}
+ formatter={formatBytes}
+ className="text-sm font-semibold tabular-nums truncate"
+ />
</div>
<div className="flex items-center justify-between gap-2">
<span className="text-xs text-muted-foreground truncate">{uploadLabel}</span>
- <span className="text-sm font-semibold tabular-nums truncate">
- {formatBytes(upload)}
- </span>
+ <AnimatedValue
+ value={upload}
+ formatter={formatBytes}
+ className="text-sm font-semibold tabular-nums truncate"
+ />
</div>
</div>
</div>
@@ -155,6 +272,8 @@ function TodayCard({
);
}
+// ---------- Main ----------
+
export function StatsCards({ data }: StatsCardsProps) {
const t = useTranslations("stats");
const maxTraffic = Math.max(
@@ -186,21 +305,24 @@ export function StatsCards({ data }: StatsCardsProps) {
downloadLabel={t("download")}
uploadLabel={t("upload")}
/>
- <StatCard
- value={(data?.totalDomains || 0).toLocaleString()}
+ <AnimatedStatCard
+ value={data?.totalDomains || 0}
+ formatter={(n) => n.toLocaleString()}
label={t("domains")}
icon={Globe}
color="#06B6D4"
/>
- <StatCard
- value={(data?.totalRules || 0).toLocaleString()}
+ <AnimatedStatCard
+ value={data?.totalRules || 0}
+ formatter={(n) => n.toLocaleString()}
label={t("rules")}
subvalue={t("tracked")}
icon={Route}
color="#F59E0B"
/>
- <StatCard
- value={formatBytes((data?.totalDownload || 0) + (data?.totalUpload || 0))}
+ <AnimatedStatCard
+ value={(data?.totalDownload || 0) + (data?.totalUpload || 0)}
+ formatter={formatBytes}
label={t("total")}
subvalue={`${(data?.totalDomains || 0)} ${t("tracked")}`}
icon={Server}
diff --git a/apps/web/components/ui/tooltip.tsx b/apps/web/components/ui/tooltip.tsx
new file mode 100644
index 0000000..d80a144
--- /dev/null
+++ b/apps/web/components/ui/tooltip.tsx
@@ -0,0 +1,57 @@
+"use client"
+
+import * as React from "react"
+import { Tooltip as TooltipPrimitive } from "radix-ui"
+
+import { cn } from "@/lib/utils"
+
+function TooltipProvider({
+ delayDuration = 0,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
+ return (
+ <TooltipPrimitive.Provider
+ data-slot="tooltip-provider"
+ delayDuration={delayDuration}
+ {...props}
+ />
+ )
+}
+
+function Tooltip({
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
+ return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
+}
+
+function TooltipTrigger({
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
+ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
+}
+
+function TooltipContent({
+ className,
+ sideOffset = 0,
+ children,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
+ return (
+ <TooltipPrimitive.Portal>
+ <TooltipPrimitive.Content
+ data-slot="tooltip-content"
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
+ </TooltipPrimitive.Content>
+ </TooltipPrimitive.Portal>
+ )
+}
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/apps/web/hooks/use-pwa-install.ts b/apps/web/hooks/use-pwa-install.ts
new file mode 100644
index 0000000..0fe01d0
--- /dev/null
+++ b/apps/web/hooks/use-pwa-install.ts
@@ -0,0 +1,73 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+
+interface BeforeInstallPromptEvent extends Event {
+ prompt(): Promise<void>;
+ userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
+}
+
+export function usePWAInstall() {
+ const [deferredPrompt, setDeferredPrompt] =
+ useState<BeforeInstallPromptEvent | null>(null);
+ const [isInstalled, setIsInstalled] = useState(false);
+
+ useEffect(() => {
+ // Check if already installed (standalone mode)
+ const isStandalone =
+ window.matchMedia("(display-mode: standalone)").matches ||
+ (window.navigator as unknown as { standalone?: boolean }).standalone ===
+ true;
+
+ if (isStandalone) {
+ setIsInstalled(true);
+ return;
+ }
+
+ const handler = (e: Event) => {
+ e.preventDefault();
+ setDeferredPrompt(e as BeforeInstallPromptEvent);
+ };
+
+ const installedHandler = () => {
+ setIsInstalled(true);
+ setDeferredPrompt(null);
+ };
+
+ window.addEventListener("beforeinstallprompt", handler);
+ window.addEventListener("appinstalled", installedHandler);
+
+ // Listen for display-mode changes (e.g. user installs from browser UI)
+ const mq = window.matchMedia("(display-mode: standalone)");
+ const mqHandler = (e: MediaQueryListEvent) => {
+ if (e.matches) {
+ setIsInstalled(true);
+ setDeferredPrompt(null);
+ }
+ };
+ mq.addEventListener("change", mqHandler);
+
+ return () => {
+ window.removeEventListener("beforeinstallprompt", handler);
+ window.removeEventListener("appinstalled", installedHandler);
+ mq.removeEventListener("change", mqHandler);
+ };
+ }, []);
+
+ const promptInstall = useCallback(async () => {
+ if (!deferredPrompt) return false;
+ deferredPrompt.prompt();
+ const { outcome } = await deferredPrompt.userChoice;
+ if (outcome === "accepted") {
+ setIsInstalled(true);
+ }
+ setDeferredPrompt(null);
+ return outcome === "accepted";
+ }, [deferredPrompt]);
+
+ return {
+ canInstall: !!deferredPrompt && !isInstalled,
+ isInstalled,
+ promptInstall,
+ };
+}
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 514edea..fc243bb 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -87,21 +87,21 @@ export const api = {
backendCount: number;
}>(`${API_BASE}/stats/global`),
- getDomains: (backendId?: number, limit = 50, range?: TimeRange) =>
- fetchJson<DomainStats[]>(buildUrl(`${API_BASE}/stats/domains`, {
- backendId,
- limit,
- start: range?.start,
- end: range?.end,
- })),
-
- getIPs: (backendId?: number, limit = 50, range?: TimeRange) =>
- fetchJson<IPStats[]>(buildUrl(`${API_BASE}/stats/ips`, {
- backendId,
- limit,
- start: range?.start,
- end: range?.end,
- })),
+ getDomains: (backendId?: number, opts?: {
+ offset?: number; limit?: number;
+ sortBy?: string; sortOrder?: string; search?: string;
+ }) =>
+ fetchJson<{ data: DomainStats[]; total: number }>(
+ buildUrl(`${API_BASE}/stats/domains`, { backendId, ...opts })
+ ),
+
+ getIPs: (backendId?: number, opts?: {
+ offset?: number; limit?: number;
+ sortBy?: string; sortOrder?: string; search?: string;
+ }) =>
+ fetchJson<{ data: IPStats[]; total: number }>(
+ buildUrl(`${API_BASE}/stats/ips`, { backendId, ...opts })
+ ),
getProxies: (backendId?: number, limit = 50, range?: TimeRange) =>
fetchJson<ProxyStats[]>(buildUrl(`${API_BASE}/stats/proxies`, {
@@ -188,6 +188,31 @@ export const api = {
buildUrl(`${API_BASE}/stats/proxies/ips`, { chain, backendId })
),
+ getRuleDomains: (rule: string, backendId?: number) =>
+ fetchJson<DomainStats[]>(
+ buildUrl(`${API_BASE}/stats/rules/domains`, { rule, backendId })
+ ),
+
+ getRuleIPs: (rule: string, backendId?: number) =>
+ fetchJson<IPStats[]>(
+ buildUrl(`${API_BASE}/stats/rules/ips`, { rule, backendId })
+ ),
+
+ getRuleChainFlow: (rule: string, backendId?: number) =>
+ fetchJson<{ nodes: Array<{ name: string; totalUpload: number; totalDownload: number; totalConnections: number }>; links: Array<{ source: number; target: number }> }>(
+ buildUrl(`${API_BASE}/stats/rules/chain-flow`, { rule, backendId })
+ ),
+
+ getAllRuleChainFlows: (backendId?: number) =>
+ fetchJson<{
+ nodes: Array<{ name: string; layer: number; nodeType: 'rule' | 'group' | 'proxy'; totalUpload: number; totalDownload: number; totalConnections: number; rules: string[] }>;
+ links: Array<{ source: number; target: number; rules: string[] }>;
+ rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }>;
+ maxLayer: number;
+ }>(
+ buildUrl(`${API_BASE}/stats/rules/chain-flow-all`, { backendId })
+ ),
+
search: (q: string) =>
fetchJson<DomainStats[]>(
`${API_BASE}/search?q=${encodeURIComponent(q)}`
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index 2e35709..70fd443 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -168,9 +168,18 @@
},
"rules": {
"title": "Rules",
- "distribution": "Rule Chain Distribution",
+ "distribution": "Rule Traffic Distribution",
+ "ruleList": "Rule List",
+ "topDomains": "Top Domains",
"description": "Traffic distribution by matching rules and their final proxy nodes",
- "connections": "conn"
+ "connections": "conn",
+ "noData": "No data",
+ "total": "Total",
+ "download": "Download",
+ "upload": "Upload",
+ "chainFlow": "Rule Chain Flow",
+ "loadingChainFlow": "Loading chain flow...",
+ "showAll": "Show All"
},
"network": {
"title": "Network",
@@ -187,6 +196,10 @@
"low": "Low",
"high": "High"
},
+ "pwa": {
+ "installApp": "INSTALL",
+ "tooltip": "Install as a desktop app for faster access and a native experience"
+ },
"about": {
"title": "About",
"version": "Version",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 13a5681..7e80697 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -167,9 +167,18 @@
},
"rules": {
"title": "规则",
- "distribution": "规则链路分布",
+ "distribution": "规则流量分布",
+ "ruleList": "规则列表",
+ "topDomains": "热门域名",
"description": "按匹配规则和最终代理节点的流量分布",
- "connections": "连接"
+ "connections": "连接",
+ "noData": "暂无数据",
+ "total": "总计",
+ "download": "下载",
+ "upload": "上传",
+ "chainFlow": "规则链路流向",
+ "loadingChainFlow": "加载链路流向...",
+ "showAll": "显示全部"
},
"network": {
"title": "网络",
@@ -186,6 +195,10 @@
"low": "低",
"high": "高"
},
+ "pwa": {
+ "installApp": "安装应用",
+ "tooltip": "安装为桌面应用,享受更快的访问速度和原生体验"
+ },
"about": {
"title": "关于",
"version": "版本",
diff --git a/apps/web/package.json b/apps/web/package.json
index 7b5722f..519f7e3 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -15,6 +15,7 @@
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
+ "@xyflow/react": "^12.10.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"d3-scale": "^4.0.2",
diff --git a/assets/clash-master-overview.png b/assets/clash-master-overview.png
index 1208c8f..becf706 100644
Binary files a/assets/clash-master-overview.png and b/assets/clash-master-overview.png differ
diff --git a/assets/clash-master-regions.png b/assets/clash-master-regions.png
new file mode 100644
index 0000000..f6ffa89
Binary files /dev/null and b/assets/clash-master-regions.png differ
diff --git a/assets/clash-master-rules.png b/assets/clash-master-rules.png
new file mode 100644
index 0000000..3c9f06c
Binary files /dev/null and b/assets/clash-master-rules.png differ
diff --git a/assets/clash-master-setup.png b/assets/clash-master-setup.png
index 2aee182..3d2ea98 100644
Binary files a/assets/clash-master-setup.png and b/assets/clash-master-setup.png differ
diff --git a/docker-compose.yml b/docker-compose.yml
index 204dc7a..faa3a5d 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -19,7 +19,7 @@ services:
# 告诉前端浏览器应该连接哪个 WebSocket 端口
- NEXT_PUBLIC_WS_PORT=${WS_EXTERNAL_PORT:-3002}
- DB_PATH=/app/data/stats.db
- networks:Open Source Project
+ networks:
- clash-master-network
# 健康检查
healthcheck:
diff --git a/package.json b/package.json
index b299a2d..f76b79a 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "clash-master",
- "version": "1.0.5",
+ "version": "1.0.6",
"private": true,
"workspaces": [
"apps/*",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 79e1a2a..01ac5ea 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -69,6 +69,9 @@ importers:
'@radix-ui/react-scroll-area':
specifier: ^1.2.10
+ '@xyflow/react':
+ specifier: ^12.10.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -2219,6 +2222,9 @@ packages:
resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==}
+
resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==}
@@ -2231,6 +2237,9 @@ packages:
resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==}
+
resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==}
@@ -2240,6 +2249,12 @@ packages:
resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==}
+
resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==}
@@ -2483,6 +2498,15 @@ packages:
resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==}
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-eOtz3whDMWrB4KWVatIBrKuxECHqip6PfA8fTpaS2RUGVpiEAe+nqDKsLqkViVWxDGreq0lWX71Xth/SPAzXiw==}
+ peerDependencies:
+ react: '>=17'
+ react-dom: '>=17'
+
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-7v7B/PkiVrkdZzSbL+inGAo6tkR/WQHHG0/jhSvLQToCsfa8YubOGmBYd1s08tpKpihdHDZFwzQZeR69QSBb4Q==}
+
resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}
@@ -2697,6 +2721,9 @@ packages:
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
+ resolution: {integrity: sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==}
+
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
@@ -2762,6 +2789,10 @@ packages:
resolution: {integrity: sha512-g9y9WbMnF5uqB9qKqwIIa/921RYWzlUDv9Jl1/yONQwxbOfszAWTCm8u7HOTgJgRDXiRZN56cHT9pd24dmXs8w==}
+ resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-68/n9JWarxXkOWMshcT5IcjbB+agblQUaIsbnXmrzejn2O82n3p2A9R2zEB9HIEFWKFwPAEDDN8gR0VdSAyyAQ==}
@@ -2794,6 +2825,10 @@ packages:
resolution: {integrity: sha512-XoGGqhLUN/W14NmaqcO/bb1nqjDAw5WtSYb2X8wiuQWvSZUsUVYsOSkOybUrNvcBjaywBdYPy03eXHMXjk9nZA==}
+ resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
engines: {node: '>=12'}
@@ -2821,6 +2856,10 @@ packages:
resolution: {integrity: sha512-fFg7aoaEm9/jf+qfstak0IYpnesZLiMX6GZvXtUSdv8RH2o4E2qeelgdU09eKS6wGuiGMfcnMI0nTIqWzRHGpw==}
+ resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}
@@ -4769,6 +4808,21 @@ packages:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
+ resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
+ engines: {node: '>=12.7.0'}
+ peerDependencies:
+ '@types/react': '>=16.8'
+ immer: '>=9.0.6'
+ react: '>=16.8'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+
snapshots:
'@alloc/[email protected]': {}
@@ -6871,6 +6925,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-selection': 3.0.11
+
'@types/[email protected]': {}
@@ -6883,6 +6941,8 @@ snapshots:
dependencies:
'@types/d3-time': 3.0.4
+ '@types/[email protected]': {}
+
dependencies:
'@types/d3-path': 3.1.1
@@ -6891,6 +6951,15 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-selection': 3.0.11
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-selection': 3.0.11
+
dependencies:
'@types/eslint': 9.6.1
@@ -7159,6 +7228,29 @@ snapshots:
'@xtuc/[email protected]': {}
+ dependencies:
+ '@xyflow/system': 0.0.74
+ classcat: 5.0.5
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ zustand: 4.5.7(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - immer
+
+ '@xyflow/[email protected]':
+ dependencies:
+ '@types/d3-drag': 3.0.7
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-selection': 3.0.11
+ '@types/d3-transition': 3.0.9
+ '@types/d3-zoom': 3.0.8
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-zoom: 3.0.0
+
@@ -7407,6 +7499,8 @@ snapshots:
dependencies:
clsx: 2.1.1
+
@@ -7460,6 +7554,11 @@ snapshots:
d3-dispatch: 2.0.0
d3-selection: 2.0.0
+ dependencies:
+ d3-dispatch: 2.0.0
+ d3-selection: 3.0.0
+
@@ -7490,6 +7589,8 @@ snapshots:
+
dependencies:
d3-path: 3.1.0
@@ -7515,6 +7616,15 @@ snapshots:
d3-selection: 2.0.0
d3-timer: 2.0.0
+ dependencies:
+ d3-color: 2.0.0
+ d3-dispatch: 2.0.0
+ d3-ease: 2.0.0
+ d3-interpolate: 2.0.1
+ d3-selection: 3.0.0
+ d3-timer: 2.0.0
+
dependencies:
d3-dispatch: 2.0.0
@@ -7523,6 +7633,14 @@ snapshots:
d3-selection: 2.0.0
d3-transition: 2.0.0([email protected])
+ dependencies:
+ d3-dispatch: 2.0.0
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-transition: 2.0.0([email protected])
+
@@ -9917,3 +10035,10 @@ snapshots:
zod: 4.3.6
+
+ dependencies:
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.11
+ react: 19.2.4
diff --git a/setup.sh b/setup.sh
index a68a898..c1b8b51 100755
--- a/setup.sh
+++ b/setup.sh
@@ -264,10 +264,26 @@ ask_start() {
fi
}
+# Download docker-compose.yml if not present
+download_compose_file() {
+ if [ ! -f "docker-compose.yml" ]; then
+ print_info "Downloading docker-compose.yml..."
+ if command -v curl &> /dev/null; then
+ curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/foru17/clash-master/main/docker-compose.yml
+ elif command -v wget &> /dev/null; then
+ wget -qO docker-compose.yml https://raw.githubusercontent.com/foru17/clash-master/main/docker-compose.yml
+ else
+ print_error "Neither curl nor wget is available"
+ exit 1
+ fi
+ print_success "docker-compose.yml downloaded"
+ fi
+}
+
# Main function
main() {
show_welcome
-
+
# Check if Docker is installed
if ! command -v docker &> /dev/null; then
print_error "Docker is not installed"
@@ -277,14 +293,14 @@ main() {
echo ""
exit 1
fi
-
+
# Check docker-compose
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
print_error "Docker Compose is not installed"
echo ""
exit 1
fi
-
+
# Check if .env already exists
if [ -f ".env" ]; then
print_warning "Existing .env file detected"
@@ -296,17 +312,18 @@ main() {
exit 0
fi
fi
-
+
# Check ports
check_ports
-
+
# Create configuration
create_env_file
create_data_dir
-
+ download_compose_file
+
# Show summary
show_summary
-
+
# Ask to start
ask_start
}