# Gateway 迁移到 Protocol 包指南

## 概述
Gateway 必须完全迁移到使用 `@jrsoft/subway-protocol` 包，Protocol 是唯一的协议标准。

## 迁移原则
1. **不修改 Protocol**：Protocol 保持现有的严格定义
2. **Gateway 必须适配**：Gateway 需要适配 Protocol 的所有要求
3. **不考虑向后兼容**：这是未上线项目，可以进行破坏性更改

## 主要改动点

### 1. 类型定义迁移
- 删除 `src/types/common.types.ts` 中的消息类型定义
- 导入并使用 `@jrsoft/subway-protocol` 的类型

### 2. 必需字段适配
Gateway 需要确保所有消息都包含 Protocol 要求的必需字段：
- **timestamp**: 所有消息都需要时间戳
- **version**: 所有消息都需要协议版本
- **callback**: CommandMessage 必须提供回调 URL

### 3. 枚举类型迁移
- 使用 Protocol 的枚举类型（ClientType, Priority, CommandStatus 等）
- 移除字符串字面量，改用枚举

### 4. 需要修改的核心文件

#### 消息处理相关
- `src/ws/message.handler.ts` - 使用 Protocol 的消息类型
- `src/ws/websocket.handler.ts` - 使用 Protocol 的类型守卫
- `src/dispatcher/command.dispatcher.ts` - 使用 Protocol 的 Command 类型

#### API 控制器
- `src/api/device.controller.ts` - 确保 callback 必填
- `src/api/gateway.controller.ts` - 确保 callback 必填
- `src/api/enhanced-device.controller.ts` - 使用 Protocol 类型

#### 工具和回调
- `src/callback/callback.handler.ts` - 使用 Protocol 的响应类型
- `src/callback/enhanced-callback.handler.ts` - 使用 Protocol 的消息类型
- `src/utils/message.factory.ts` - 删除，使用 Protocol 的 MessageFactory

## 具体迁移步骤

### Step 1: 安装 Protocol 包
```bash
cd jrsoft-subway-gateway
npm install @jrsoft/subway-protocol@latest
```

### Step 2: 更新导入
将所有本地类型导入改为从 Protocol 包导入：
```typescript
// Before
import { CommandMessage, BaseMessage } from '../types/common.types';

// After
import { CommandMessage, BaseMessage, MessageType, ClientType } from '@jrsoft/subway-protocol';
```

### Step 3: 适配必需字段
确保所有创建的消息都包含必需字段：
```typescript
// 创建命令时必须提供 callback
const commandMessage = MessageFactory.createCommandMessage(
  requestRef,
  targetClientId,
  command,
  callbackUrl, // 必需，不能为空
  { priority, timeout }
);
```

### Step 4: 使用 Protocol 的工厂方法
```typescript
import { MessageFactory } from '@jrsoft/subway-protocol';

// 使用 Protocol 的工厂方法创建消息
const registerMessage = MessageFactory.createRegisterMessage(
  clientId,
  ClientType.DEVICE,
  clientInfo
);
```

### Step 5: 使用 Protocol 的验证器
```typescript
import { MessageValidator } from '@jrsoft/subway-protocol';

// 验证接收到的消息
const validation = MessageValidator.validateMessage(message);
if (!validation.isValid) {
  throw new Error(validation.errors.join(', '));
}
```

## 注意事项

### 1. Callback URL 处理
- Gateway API 必须要求调用方提供 callback URL
- 如果调用方确实不需要回调，可以提供一个占位符 URL（如 'http://noop'）
- 在回调处理时检查 URL 是否为占位符，避免不必要的网络请求

### 2. 内部接口保留
以下接口是 Gateway 内部使用，不需要迁移到 Protocol：
- `PendingCommand`
- `LongRunningCommand`
- `DeviceConnection`
- `IDeviceManager`
- `ICommandDispatcher`

### 3. 常量迁移
使用 Protocol 提供的常量：
```typescript
import { PROTOCOL_VERSION, DEFAULT_TIMEOUT, Priority } from '@jrsoft/subway-protocol';
```

## 测试策略
1. 更新所有单元测试，使用 Protocol 类型
2. 更新集成测试，确保消息格式符合 Protocol 标准
3. 使用 MessageValidator 验证所有发送和接收的消息

## 完成标准
- [ ] 所有消息类型使用 Protocol 定义
- [ ] 所有消息创建使用 MessageFactory
- [ ] 所有消息验证使用 MessageValidator  
- [ ] 删除本地的重复类型定义
- [ ] 所有测试通过
- [ ] callback 字段在所有命令中都是必需的