Metadata-Version: 2.4
Name: pulse-mq
Version: 0.2.0
Summary: 基于 ZeroMQ 的消息队列系统，专为金融市场数据分发设计
Author: haifeng
License-Expression: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.13
Description-Content-Type: text/markdown
Requires-Dist: pyzmq>=26.0
Requires-Dist: aiosqlite>=0.20
Requires-Dist: bcrypt>=4.2
Requires-Dist: msgpack>=1.1
Requires-Dist: pyarrow>=18.0
Requires-Dist: pandas>=2.2
Requires-Dist: pyyaml>=6.0
Requires-Dist: zstandard>=0.23
Requires-Dist: lz4>=4.3
Requires-Dist: aiohttp>=3.9
Requires-Dist: PyJWT>=2.9
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: pytest-aiohttp>=1.1; extra == "dev"

# PulseMQ

基于 ZeroMQ 的高性能消息队列系统，专为金融市场数据分发设计。

## 特性

- **高性能**：基于 ZMQ ROUTER/XPUB 架构，P50 延迟 < 1ms
- **多格式**：支持 BYTES、STRING、DataFrame（MessagePack/Apache Arrow）
- **权限控制**：namespace 级角色鉴权（sub/pub/admin），全量内存缓存
- **管理后台**：JWT 认证，实时监控仪表盘，完整的 CRUD API
- **客户端 SDK**：Python 异步客户端，自动重连、心跳、订阅恢复
- **零配置**：无需配置文件即可启动，YAML/CLI 可选覆盖

## 快速开始

### 安装

```bash
# 创建虚拟环境（Python >= 3.13）
uv venv

# 激活虚拟环境
source .venv/Scripts/activate  # Windows
source .venv/bin/activate      # Linux/Mac

# 安装依赖
uv pip install -e ".[dev]"
```

### 启动 Broker

```bash
# 零配置启动
pulsemq

# 指定配置文件
pulsemq --config config.yaml

# 覆盖个别参数
pulsemq --pub-port 6000 --sub-port 6001 --log-level debug
```

启动后自动创建管理员账号，凭证保存在 `.pulsemq_admin` 文件中。

### 访问管理后台

打开浏览器访问 `http://localhost:8080`，使用 `.pulsemq_admin` 中的账号密码登录。

### 使用客户端 SDK

```python
import asyncio
from app.client import Client

async def main():
    client = Client("localhost:5555", token="your-token")
    await client.connect()

    # 发布消息
    await client.publish("market_data:sz000651.kline.1m", b'{"price":10.5}', format="bytes")

    # 订阅消息
    async for msg in client.subscribe("market_data:sz000651.>"):
        print(f"收到: {msg.topic} = {msg.data}")

    await client.close()

asyncio.run(main())
```

## 架构

```
Publisher → ROUTER (port 5555) → [Broker] → XPUB (port 5556) → Subscriber
                                    │
                                    ├── AUTH 认证
                                    ├── PUB 消息转发
                                    ├── SUB 订阅管理
                                    └── QUERY 查询响应
```

### 消息格式

每条消息由 6 个 ZMQ frame 组成：

| Frame | 名称 | 说明 |
|-------|------|------|
| 0 | Header | 20 字节二进制（版本/类型/格式/标志/长度/计数/时间戳） |
| 1 | Namespace | UTF-8 字符串，默认 "default" |
| 2 | Topic | UTF-8 字符串，最多 3 级（如 `sz000651.kline.1m`） |
| 3 | Username | UTF-8 字符串 |
| 4 | Payload | 二进制载荷 |
| 5 | Reserved | 预留扩展 |

### 数据格式

| 格式 | 值 | 说明 | 大小限制 |
|------|---|------|---------|
| BYTES | 0x00 | 原始字节流 | 10 MB |
| STRING | 0x01 | UTF-8 文本 | 8 KB |
| DF_MSGPACK | 0x02 | DataFrame → MessagePack | 1 MB |
| DF_PYARROW | 0x03 | DataFrame → Apache Arrow IPC | 64 MB |

### 权限模型

权限控制在 namespace 级别，采用 3 级角色体系：

- `sub`：订阅权
- `pub`：发布权（包含 sub）
- `admin`：管理权（包含 pub）

用户类型：
- `super_admin`：后台管理 + 全部 MQ 权限
- `mq_super`：全部 MQ 权限（无后台管理）
- `mq_normal`：需通过 namespace_permissions 鉴权
- `admin_only`：仅后台管理

## 配置

### 零配置启动

不指定任何参数时使用默认值：

```yaml
server:
  host: "0.0.0.0"
  pub_port: 5555
  sub_port: 5556
  admin_port: 8080

storage:
  db_path: "./pulsemq.db"

auth:
  token_hash: "sha256"
  ping_interval: 30
  ping_timeout: 3

limits:
  max_connections_per_user: 10
  max_subscriptions_per_conn: 500
  cache_refresh_sec: 300

broker:
  hwm: 10000

logging:
  dir: "./logs"
  max_days: 7
  level: "info"
```

### YAML 配置文件

创建 `config.yaml`，只覆盖需要修改的项：

```yaml
server:
  pub_port: 6000
  admin_port: 9090

storage:
  db_path: "/data/pulsemq.db"
```

启动时指定配置文件：

```bash
pulsemq --config config.yaml
```

### CLI 参数

命令行参数优先级最高：`CLI > YAML > 默认值`

```bash
pulsemq --host 127.0.0.1 --pub-port 7000 --log-level debug
```

## API

### 健康检查

```bash
curl http://localhost:8080/health
# {"status":"ok","version":"4.3.0","uptime_seconds":1234,"connections":5}
```

### 管理 API

| 端点 | 方法 | 说明 |
|------|------|------|
| `/login` | POST | 登录获取 JWT |
| `/api/namespaces` | GET/POST | 命名空间列表/创建 |
| `/api/namespaces/{id}` | GET/PUT/DELETE | 命名空间详情/更新/删除 |
| `/api/namespaces/{id}/permissions` | POST | 授权 |
| `/api/topics` | GET | 主题列表（按 namespace 过滤） |
| `/api/topics/{id}` | GET/DELETE | 主题详情/删除 |
| `/api/users` | GET/POST | 用户列表/创建 |
| `/api/users/{id}` | PUT/DELETE | 用户更新/删除 |
| `/api/users/{id}/reset-token` | POST | 重置 token |
| `/api/connections` | GET | 活跃连接列表 |
| `/api/connections/disconnect-user` | POST | 断开用户连接 |
| `/api/stats/system` | GET | 系统统计 |
| `/api/stats/topics` | GET | 主题统计 |
| `/api/audit-logs` | GET | 审计日志 |

所有 API 需要在请求头中携带 JWT：

```bash
curl -H "Authorization: Bearer <token>" http://localhost:8080/api/namespaces
```

## 目录结构

```
pulse-mq/
├── app/
│   ├── __init__.py          # 版本号
│   ├── errors.py            # 自定义异常
│   ├── config.py            # 配置系统
│   ├── protocol.py          # 协议编解码
│   ├── auth.py              # 认证（token/password）
│   ├── permission.py        # 权限缓存与鉴权
│   ├── stats.py             # 统计采集
│   ├── proxy.py             # ZMQ 消息代理
│   ├── broker.py            # Broker 主进程
│   ├── client.py            # 客户端 SDK
│   ├── cli.py               # CLI 入口
│   ├── admin/
│   │   ├── app.py           # HTTP API
│   │   └── static/
│   │       └── index.html   # 管理后台前端
│   └── db/
│       ├── base.py          # 数据库抽象基类
│       ├── sqlite.py        # SQLite 适配器
│       ├── schema.py        # DDL 定义
│       └── queries.py       # CRUD 操作
├── tests/                   # 测试文件
├── docs/                    # 设计文档
├── pyproject.toml           # 项目配置
└── README.md
```

## 测试

```bash
# 运行全部测试
python -m pytest tests/ -v

# 运行特定模块测试
python -m pytest tests/test_broker.py -v
```

## 依赖

### 核心依赖

- `pyzmq` - ZeroMQ Python 绑定
- `aiosqlite` - 异步 SQLite
- `bcrypt` - 密码哈希
- `msgpack` - MessagePack 序列化
- `pyarrow` - Apache Arrow
- `pandas` - DataFrame 支持
- `pyyaml` - YAML 配置解析
- `zstandard` / `lz4` - 压缩算法
- `aiohttp` - HTTP 服务
- `PyJWT` - JWT 认证

### 开发依赖

- `pytest` - 测试框架
- `pytest-asyncio` - 异步测试支持
- `pytest-aiohttp` - aiohttp 测试支持

## 设计文档

| 文档 | 内容 |
|------|------|
| `docs/PulseMQ协议模型-v4.0.md` | 消息帧结构、数据格式、消息类型、Topic 规则、通配符 |
| `docs/消息队列权限模型.md` | 权限模型、认证机制、缓存策略、审计 |
| `docs/PulseMQ后台管理系统设计.md` | 管理后台功能、监控指标、仪表盘、SQLite 表结构 |
| `docs/PulseMQ Broker 运行设计.md` | 配置、启动流程、流控、健康检查、关闭、日志、客户端 SDK |

## 许可证

MIT
