Files
akmon/push-receiver-service/README.md
2026-01-20 08:04:15 +08:00

406 lines
8.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 基于 Supabase 的推送消息接收服务
专门用于接收和存储各种推送消息到 Supabase 数据库的独立服务。
## 🌟 特性
-**基于 Supabase**: 使用 Supabase PostgreSQL 数据库
-**推送消息接收**: 支持多种类型的推送消息SOS、健康、位置、告警等
-**批量处理**: 支持单个和批量消息处理
-**重复检测**: 自动检测和处理重复消息
-**实时监控**: 提供详细的统计和监控功能
-**安全保护**: API 密钥验证和请求频率限制
-**完整日志**: 详细的操作日志记录
-**优雅关闭**: 支持服务的优雅启动和关闭
## 🚀 快速开始
### 1. 安装依赖
```bash
cd push-receiver-service
npm install
```
### 2. 配置 Supabase
1. **创建 Supabase 项目**:
- 访问 [https://supabase.com/dashboard](https://supabase.com/dashboard)
- 点击 "New project" 创建新项目
- 记录项目的 URL 和 API Keys
2. **⚠️ 重要:数据库适配说明**:
- 本服务已适配现有的 `ak_users``ak_devices`
- 推送消息相关表使用 `ps_` 前缀(`ps_push_messages``ps_push_types` 等)
- 请确保现有的基础表已存在于您的 Supabase 项目中
- 详细适配信息请查看 [`SUPABASE_ADAPTATION.md`](./SUPABASE_ADAPTATION.md)
3. **执行数据库初始化脚本**:
- 在 Supabase Dashboard 中打开 "SQL Editor"
- 复制 `database/supabase-init.sql` 文件内容
- 粘贴到 SQL Editor 中并执行
4. **配置环境变量**:
```bash
cp .env.supabase .env
```
然后编辑 `.env` 文件:
```env
SUPABASE_URL=https://your-project-ref.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
API_KEY=your-custom-api-key
```
### 3. 初始化数据库
```bash
node setup-supabase.js
```
### 4. 启动服务
```bash
node supabase-server.js
```
服务将在 `http://localhost:3001` 启动。
## 📋 API 端点
### 基础信息
- **服务信息**: `GET /`
- **健康检查**: `GET /api/health`
### 推送消息接收
- **单个消息**: `POST /api/push/message`
- **批量消息**: `POST /api/push/batch`
### 数据查询
- **统计信息**: `GET /api/stats`
- **消息列表**: `GET /api/messages`
- **清理数据**: `POST /api/cleanup`
## 🔧 API 使用示例
### 发送单个推送消息
```bash
curl -X POST http://localhost:3001/api/push/message \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"pushType": "HEALTH",
"userId": "123e4567-e89b-12d3-a456-426614174000",
"deviceId": "987fcdeb-51a2-43d7-8f9e-123456789abc",
"H": 75,
"O": 98,
"T": 36.5
}'
```
> **注意**: `userId` 和 `deviceId` 必须使用 UUID 格式,且必须是现有 `ak_users` 和 `ak_devices` 表中的有效记录。
### 发送批量推送消息
```bash
curl -X POST http://localhost:3001/api/push/batch \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"messages": [
{
"pushType": "SOS",
"userId": "123e4567-e89b-12d3-a456-426614174000",
"emergencyLevel": "HIGH",
"lat": 39.9042,
"lng": 116.4074
},
{
"pushType": "HEALTH",
"userId": "456e7890-e89b-12d3-a456-426614174001",
"H": 80,
"O": 95
}
]
}'
```
### JavaScript 调用示例
```javascript
// 发送单个推送消息
const response = await fetch('http://localhost:3001/api/push/message', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key'
},
body: JSON.stringify({
pushType: 'HEALTH',
userId: '123e4567-e89b-12d3-a456-426614174000',
deviceId: '987fcdeb-51a2-43d7-8f9e-123456789abc',
H: 105,
O: 88
})
});
const result = await response.json();
console.log('推送结果:', result);
```
### Python 调用示例
```python
import requests
# 发送单个推送消息
response = requests.post('http://localhost:3001/api/push/message',
headers={
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key'
},
json={
'pushType': 'HEALTH',
'userId': 'user_12345',
'H': 105,
'O': 88
}
)
result = response.json()
print('推送结果:', result)
```
## 📊 支持的推送类型
| 类型 | 说明 | 优先级 | 必需字段 |
|------|------|--------|----------|
| `SOS` | 紧急求救 | 1 (最高) | `userId` |
| `ALERT` | 告警信息 | 2 | `userId`, `alertType` |
| `HEALTH` | 健康数据 | 3 | `userId` |
| `LOCATION` | 位置信息 | 4 | `userId` |
| `DEVICE_STATUS` | 设备状态 | 4 | `deviceId` |
| `ACTIVITY` | 活动数据 | 5 | `userId` |
## 🗄️ 数据库结构
### 主要数据表
1. **push_messages**: 推送消息主表
2. **push_types**: 推送类型配置表
3. **message_processing_logs**: 消息处理日志表
4. **devices**: 设备信息表
5. **users**: 用户信息表
6. **system_stats**: 系统统计表
### 消息数据结构
```json
{
"id": "uuid",
"push_type": "HEALTH",
"user_id": "user_12345",
"device_id": "device_001",
"raw_data": { "完整的原始数据" },
"parsed_data": { "解析后的结构化数据" },
"received_at": "2025-06-25T10:30:00Z",
"processing_status": "processed",
"priority": 3,
"is_duplicate": false,
"source_ip": "192.168.1.100",
"user_agent": "Device Client/1.0"
}
```
## 🔒 安全配置
### API 密钥验证
在环境变量中设置 `API_KEY`
```env
API_KEY=your-secure-api-key
```
所有 API 请求(除健康检查外)都需要在请求头中包含:
```
X-API-Key: your-secure-api-key
```
### 请求频率限制
- 默认:每分钟最多 1000 个请求
- 可通过环境变量配置:`RATE_LIMIT_MAX_REQUESTS`
### CORS 配置
可通过 `ALLOWED_ORIGINS` 环境变量配置允许的来源。
## 📈 监控和日志
### 日志文件
- `logs/supabase-push-service.log`: 一般日志
- `logs/supabase-push-service-error.log`: 错误日志
- `logs/database.log`: 数据库操作日志
### 统计信息
访问 `/api/stats` 获取详细的统计信息:
```json
{
"success": true,
"data": {
"service": {
"uptime": 3600,
"requestCount": 150,
"messageCount": 120,
"errorCount": 2
},
"messages": [
{
"push_type": "HEALTH",
"total_count": 80,
"processed_count": 78,
"failed_count": 2,
"pending_count": 0
}
]
}
}
```
## 🔧 环境配置
### 完整的环境变量配置
```env
# 服务器配置
PORT=3001
HOST=0.0.0.0
NODE_ENV=production
# Supabase 配置
SUPABASE_URL=https://your-project-ref.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
# 安全配置
API_KEY=your-secure-api-key
ALLOWED_ORIGINS=*
RATE_LIMIT_MAX_REQUESTS=1000
# 日志配置
LOG_LEVEL=info
LOG_DIR=./logs
# 消息处理配置
MAX_MESSAGE_SIZE=1048576
BATCH_SIZE_LIMIT=1000
ENABLE_DUPLICATE_CHECK=true
# 数据清理配置
AUTO_CLEANUP_ENABLED=true
AUTO_CLEANUP_DAYS=30
```
## 🚀 部署
### Docker 部署
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3001
CMD ["node", "supabase-server.js"]
```
### PM2 部署
```bash
npm install -g pm2
pm2 start supabase-server.js --name "supabase-push-receiver"
pm2 startup
pm2 save
```
### 云服务部署
支持部署到:
- Vercel
- Netlify
- Railway
- Heroku
- AWS Lambda
- 腾讯云函数
## 🛠️ 开发
### 项目结构
```
push-receiver-service/
├── lib/
│ └── supabase-database.js # Supabase 数据库操作类
├── database/
│ └── supabase-init.sql # 数据库初始化脚本
├── logs/ # 日志目录
├── supabase-server.js # 主服务器文件
├── setup-supabase.js # 数据库设置脚本
├── package.json
├── .env.supabase # Supabase 环境配置模板
└── README.md
```
### 运行测试
```bash
# 测试 Supabase 连接
node setup-supabase.js
# 启动开发服务器
npm run dev
```
## 🤝 业务集成
### 与现有系统集成
1. **配置推送地址**: 将设备或系统的推送地址指向此服务
2. **设置API密钥**: 确保所有推送请求都包含正确的API密钥
3. **监控日志**: 定期检查服务日志确保正常运行
4. **数据分析**: 使用 Supabase Dashboard 或 API 进行数据分析
### 数据流处理
```
设备/系统 → 推送消息 → 接收服务 → Supabase → 业务处理
实时通知/告警
```
## 📞 支持
如果您在使用过程中遇到问题:
1. 检查日志文件获取详细错误信息
2. 确认 Supabase 配置正确
3. 验证 API 密钥和网络连接
4. 查看 Supabase Dashboard 的数据库状态
---
**注意**: 这是一个专门的消息接收服务,只负责接收和存储推送消息。业务逻辑处理需要另外实现。