# RDMC Exchange Hub 架构流程图

## 1. Exchange Hub 模块架构总览

```mermaid
graph TB
    subgraph "RDMC平台 (内网)"
        subgraph "rmdc-exchange-hub 模块"
            MQTTSvc["MQTTService<br/>消息服务层<br/>(Paho MQTT Client)"]
            MsgRouter["MessageRouter<br/>消息路由器"]
            
            subgraph "消息处理器 Handlers"
                RegHandler["RegisterHandler<br/>注册处理"]
                AuthHandler["AuthHandler<br/>授权处理"]
                ExecHandler["ExecHandler<br/>执行处理"]
                LogHandler["LogHandler<br/>日志处理"]
                MonitorHandler["MonitorHandler<br/>监控处理"]
                AlertHandler["AlertHandler<br/>告警处理"]
            end
            
            subgraph "状态管理"
                ConnMgr["ConnectionManager<br/>连接管理"]
                StateMgr["StateManager<br/>状态机管理"]
                CmdTracker["CommandTracker<br/>指令追踪"]
            end
            
            subgraph "同步指令支持"
                SyncMgr["SyncCommandManager<br/>同步指令管理"]
                ResultCache["ResultCache<br/>结果缓存"]
            end
        end
        
        subgraph "业务模块集成"
            ProjectMgmt["project-management<br/>项目管理"]
            WDCenter["watchdog-center<br/>一级授权中心"]
            LogCenter["日志中心"]
            MonitorCenter["监控中心"]
            Operator["执行中心"]
            Notice["通知中心"]
            Audit["审计模块"]
        end
        
        DB[(PostgreSQL<br/>数据持久化)]
    end
    
    MQTT[(MQTT Broker<br/>消息中间件)]
    
    subgraph "外部项目环境"
        Watchdog["rmdc-watchdog<br/>边缘代理"]
        WDNode["watchdog-node<br/>主机守护"]
        WDAgent["watchdog-agent<br/>业务代理"]
    end
    
    %% MQTT 连接
    MQTTSvc <=="订阅/发布"==> MQTT
    MQTT <=="跨公网"==> Watchdog
    
    %% 内部路由
    MQTTSvc --> MsgRouter
    MsgRouter --> RegHandler
    MsgRouter --> AuthHandler
    MsgRouter --> ExecHandler
    MsgRouter --> LogHandler
    MsgRouter --> MonitorHandler
    MsgRouter --> AlertHandler
    
    %% 注册与授权流程
    RegHandler --> ProjectMgmt
    AuthHandler --> WDCenter
    ProjectMgmt -.项目信息.-> RegHandler
    WDCenter -.授权信息.-> AuthHandler
    
    %% 处理器到业务模块
    ExecHandler --> Operator
    LogHandler --> LogCenter
    MonitorHandler --> MonitorCenter
    AlertHandler --> Notice
    
    %% 状态管理
    RegHandler --> ConnMgr
    MsgRouter --> StateMgr
    ExecHandler --> CmdTracker
    
    %% 同步指令支持
    ExecHandler --> SyncMgr
    LogHandler --> SyncMgr
    SyncMgr --> ResultCache
    
    %% 数据持久化
    ConnMgr --> DB
    StateMgr --> DB
    CmdTracker --> DB
    Audit --> DB
    
    %% Watchdog 内部
    Watchdog <--> WDNode
    Watchdog <--> WDAgent
    
    style MQTTSvc fill:#ff6b6b,stroke:#c92a2a,stroke-width:3px
    style MQTT fill:#ffd43b,stroke:#f08c00,stroke-width:2px
    style Watchdog fill:#4ecdc4,stroke:#087f5b,stroke-width:2px
    style SyncMgr fill:#a9e34b,stroke:#5c940d,stroke-width:2px
```

---

## 2. 消息分类与 Topic 设计

```mermaid
graph LR
    subgraph "上行通道 (Watchdog → Exchange Hub)"
        direction TB
        WD1[Watchdog Client]
        
        CmdUp["📤 wdd/RDMC/command/up<br/>指令上行"]
        MsgUp["📤 wdd/RDMC/message/up<br/>数据上行"]
        
        WD1 -->|Publish| CmdUp
        WD1 -->|Publish| MsgUp
        
        subgraph "上行指令类型"
            UCR[register - 项目注册]
            UCA[auth_request - 授权请求]
        end
        
        subgraph "上行数据类型"
            UDM[monitor - 监控数据]
            UDL[log_result - 日志结果]
            UDE[exec_result - 执行结果]
            UDA[alert - 告警信息]
            UDH[heartbeat - 心跳数据]
            UDC[register_complete - 注册完成]
        end
        
        CmdUp -.- UCR
        CmdUp -.- UCA
        MsgUp -.- UDM
        MsgUp -.- UDL
        MsgUp -.- UDE
        MsgUp -.- UDA
        MsgUp -.- UDH
        MsgUp -.- UDC
    end
    
    subgraph "下行通道 (Exchange Hub → Watchdog)"
        direction TB
        EH1[Exchange Hub]
        
        CmdDown["📥 wdd/RDMC/command/down/{project_id}<br/>指令下行"]
        MsgDown["📥 wdd/RDMC/message/down/{project_id}<br/>数据下行"]
        
        EH1 -->|Publish| CmdDown
        EH1 -->|Publish| MsgDown
        
        subgraph "下行指令类型"
            DCA[auth_response - 授权响应]
            DCL[log_query - 日志查询]
            DCE[host_exec - 主机执行]
            DCK[k8s_exec - K8s执行]
            DCU[update - 业务更新]
            DCR[auth_revoke - 授权撤销]
        end
        
        subgraph "下行数据类型"
            DDR[register_ack - 注册确认]
            DDA[auth_info - 授权信息]
        end
        
        CmdDown -.- DCA
        CmdDown -.- DCL
        CmdDown -.- DCE
        CmdDown -.- DCK
        CmdDown -.- DCU
        CmdDown -.- DCR
        MsgDown -.- DDR
        MsgDown -.- DDA
    end
    
    style CmdUp fill:#ffd43b,stroke:#f08c00
    style MsgUp fill:#74c0fc,stroke:#1c7ed6
    style CmdDown fill:#ff8787,stroke:#c92a2a
    style MsgDown fill:#a9e34b,stroke:#5c940d
```

---

## 3. 消息结构设计

### 3.1 基础消息结构

```mermaid
classDiagram
    class BaseMessage {
        +string MessageID
        +string Type
        +string ProjectID
        +int64 Timestamp
        +string Version
    }
    
    class CommandMessage {
        +CommandType CommandType
        +any Payload
        +string Signature
    }
    
    class DataMessage {
        +DataType DataType
        +any Payload
        +bool Encrypted
    }
    
    BaseMessage <|-- CommandMessage
    BaseMessage <|-- DataMessage
```

### 3.2 执行模块消息结构

```mermaid
classDiagram
    class K8sExecCommand {
        +string CommandID
        +string Namespace
        +string Resource
        +string Name
        +string Action
        +string Container
        +[]string Command
        +int Timeout
        +int TailLines
        +bool FollowLogs
    }
    
    class HostExecCommand {
        +string CommandID
        +string HostID
        +string Action
        +string Script
        +[]string Args
        +int Timeout
    }
    
    class ExecResult {
        +string CommandID
        +string Status
        +int ExitCode
        +string Output
        +string Error
        +int64 StartTime
        +int64 EndTime
        +int64 Duration
    }
    
    class CommandMessage {
        +CommandType CommandType
        +any Payload
    }
    
    CommandMessage --> K8sExecCommand : Payload (k8s_exec)
    CommandMessage --> HostExecCommand : Payload (host_exec)
    
    class DataMessage {
        +DataType DataType
        +any Payload
    }
    
    DataMessage --> ExecResult : Payload (exec_result)
```

---

## 4. 指令生命周期状态机

```mermaid
stateDiagram-v2
    [*] --> Pending: 创建指令
    
    Pending --> Sent: 发送到MQTT
    Sent --> Delivered: Watchdog确认接收
    Delivered --> Running: 开始执行
    
    Running --> Success: 执行成功
    Running --> Failed: 执行失败
    Running --> Timeout: 执行超时
    
    Sent --> Timeout: 未送达超时
    Delivered --> Timeout: 未执行超时
    
    Success --> [*]
    Failed --> [*]
    Timeout --> [*]
    
    note right of Pending: 状态持久化到数据库<br/>记录指令下发时间戳
    note right of Running: 可查询实时输出<br/>支持同步等待
    note right of Timeout: 触发告警通知<br/>记录超时原因
```

---

## 5. 项目连接状态管理

```mermaid
stateDiagram-v2
    [*] --> Offline: 初始状态
    
    Offline --> Connecting: 收到注册请求
    Connecting --> Verifying: 发送挑战随机数
    Verifying --> Online: 完成挑战-应答验证
    
    Online --> Online: 心跳刷新
    Online --> Offline: 心跳超时<br/>(默认30秒)
    
    Online --> Disconnecting: 主动下线
    Disconnecting --> Offline: 确认下线
    
    note right of Connecting: 解析项目信息<br/>验证TOTP
    note right of Verifying: 挑战-应答机制<br/>32位随机数验证
    note right of Online: 定期心跳(5秒)<br/>监控数据上报
    note right of Offline: 触发离线告警<br/>通知相关用户
```

---

## 6. MQTT Client 架构对比

### 6.1 Exchange Hub (Server 端)

```mermaid
graph TB
    subgraph "Exchange Hub MQTT 架构"
        Config[MQTTConfig<br/>连接配置]
        Client[MQTT Client<br/>Paho v3]
        
        subgraph "订阅 (Subscribe)"
            SubCmd[wdd/RDMC/command/up]
            SubMsg[wdd/RDMC/message/up]
        end
        
        subgraph "发布 (Publish)"
            PubCmd["wdd/RDMC/command/down/{project_id}"]
            PubMsg["wdd/RDMC/message/down/{project_id}"]
        end
        
        Router[消息路由器<br/>MessageRouter]
        HandlerPool[Handler Pool<br/>处理器池]
        
        Config --> Client
        Client --> SubCmd
        Client --> SubMsg
        SubCmd --> Router
        SubMsg --> Router
        Router --> HandlerPool
        
        HandlerPool --> Client
        Client --> PubCmd
        Client --> PubMsg
    end
    
    style Client fill:#ff6b6b,stroke:#c92a2a,stroke-width:2px
```

### 6.2 Watchdog (Client 端)

```mermaid
graph TB
    subgraph "Watchdog MQTT 架构"
        Config[MQTTConfig<br/>连接配置]
        Client[MQTT Client<br/>Paho v3]
        ProjectID[ProjectID]
        
        subgraph "订阅 (Subscribe)"
            SubCmd["wdd/RDMC/command/down/{project_id}"]
            SubMsg["wdd/RDMC/message/down/{project_id}"]
        end
        
        subgraph "发布 (Publish)"
            PubCmd[wdd/RDMC/command/up]
            PubMsg[wdd/RDMC/message/up]
        end
        
        CmdExecutor[CommandExecutor<br/>指令执行器]
        DataCollector[DataCollector<br/>数据采集器]
        
        Config --> Client
        ProjectID --> Client
        Client --> SubCmd
        Client --> SubMsg
        SubCmd --> CmdExecutor
        SubMsg --> CmdExecutor
        
        DataCollector --> Client
        Client --> PubCmd
        Client --> PubMsg
    end
    
    style Client fill:#4ecdc4,stroke:#087f5b,stroke-width:2px
```

---

## 7. 安全设计

```mermaid
graph LR
    subgraph "安全机制"
        TLS["TLS/SSL加密<br/>传输层安全"]
        Auth["MQTT认证<br/>用户名/密码"]
        Sign["消息签名<br/>HMAC-SHA256"]
        Encrypt["敏感数据加密<br/>AES-256-GCM"]
        TOTP["TOTP验证<br/>时间戳校验"]
    end
    
    subgraph "应用场景"
        Conn[连接建立] --> TLS
        Conn --> Auth
        
        Cmd[指令传输] --> Sign
        Cmd --> Encrypt
        
        Reg[项目注册] --> TOTP
        Reg --> Sign
    end
    
    style TLS fill:#a5d8ff,stroke:#1c7ed6
    style Auth fill:#a5d8ff,stroke:#1c7ed6
    style Sign fill:#ffd8a8,stroke:#f08c00
    style Encrypt fill:#ffd8a8,stroke:#f08c00
    style TOTP fill:#d3f9d8,stroke:#087f5b
```

---

## 8. 与业务模块集成架构

```mermaid
graph TB
    subgraph "业务模块层"
        PM["project-management<br/>项目管理"]
        WC["watchdog-center<br/>一级授权中心"]
        LC["log-center<br/>日志中心"]
        MC["monitor-center<br/>监控中心"]
        OP["octopus-operator<br/>执行中心"]
        NC["notice-center<br/>通知中心"]
    end
    
    subgraph "Exchange-Hub 接口层"
        RegAPI["RegisterAPI<br/>注册接口"]
        AuthAPI["AuthAPI<br/>授权接口"]
        CmdAPI["CommandAPI<br/>指令接口"]
        QueryAPI["QueryAPI<br/>查询接口"]
    end
    
    subgraph "Exchange-Hub 核心"
        MQTTSvc["MQTTService"]
        Handlers["Handlers"]
        StateDB["StateDB"]
    end
    
    PM --> RegAPI
    WC --> AuthAPI
    LC --> CmdAPI
    MC --> CmdAPI
    OP --> CmdAPI
    NC <-- QueryAPI
    
    RegAPI --> MQTTSvc
    AuthAPI --> MQTTSvc
    CmdAPI --> MQTTSvc
    QueryAPI --> StateDB
    
    MQTTSvc --> Handlers
    Handlers --> StateDB
    
    style MQTTSvc fill:#ff6b6b,stroke:#c92a2a
```
