Skip to main content

privchat_protocol/
protocol.rs

1// Copyright 2025 Shanghai Boyu Information Technology Co., Ltd.
2// https://privchat.dev
3//
4// Author: zoujiaqing <zoujiaqing@gmail.com>
5//
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10//     http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use serde::{Deserialize, Serialize};
19use std::collections::HashMap;
20use std::fmt::Debug;
21
22/// 消息基础trait
23pub trait Message: Debug + Send + Sync {
24    /// 获取消息类型
25    fn message_type(&self) -> MessageType;
26}
27
28/// 消息类型枚举
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30pub enum MessageType {
31    /// 连接请求 - 客户端发起连接
32    AuthorizationRequest = 1,
33    /// 连接响应 - 服务端连接确认
34    AuthorizationResponse = 2,
35    /// 断开连接请求 - 客户端主动断开
36    DisconnectRequest = 3,
37    /// 断开连接响应 - 服务端断开确认
38    DisconnectResponse = 4,
39    /// 发送消息请求 - 客户端发送消息
40    SendMessageRequest = 5,
41    /// 发送消息响应 - 服务端发送确认
42    SendMessageResponse = 6,
43    /// 推送消息请求 - 服务端推送消息
44    PushMessageRequest = 7,
45    /// 推送消息响应 - 客户端接收确认
46    PushMessageResponse = 8,
47    /// 批量接收消息请求 - 服务端批量推送消息
48    PushBatchRequest = 9,
49    /// 批量接收消息响应 - 客户端批量接收确认
50    PushBatchResponse = 10,
51    /// 心跳请求 - 客户端发送心跳
52    PingRequest = 11,
53    /// 心跳响应 - 服务端心跳回复
54    PongResponse = 12,
55    /// 订阅请求 - 客户端订阅频道
56    SubscribeRequest = 13,
57    /// 订阅响应 - 服务端订阅确认
58    SubscribeResponse = 14,
59    /// 推送消息请求 - 服务端推送频道消息
60    PublishRequest = 15,
61    /// 推送消息响应 - 客户端推送确认
62    PublishResponse = 16,
63    /// RPC消息请求 - 客户端发送RPC消息
64    RpcRequest = 17,
65    /// RPC消息响应 - 服务端发送RPC消息
66    RpcResponse = 18,
67}
68
69impl From<u8> for MessageType {
70    fn from(value: u8) -> Self {
71        match value {
72            1 => MessageType::AuthorizationRequest,
73            2 => MessageType::AuthorizationResponse,
74            3 => MessageType::DisconnectRequest,
75            4 => MessageType::DisconnectResponse,
76            5 => MessageType::SendMessageRequest,
77            6 => MessageType::SendMessageResponse,
78            7 => MessageType::PushMessageRequest,
79            8 => MessageType::PushMessageResponse,
80            9 => MessageType::PushBatchRequest,
81            10 => MessageType::PushBatchResponse,
82            11 => MessageType::PingRequest,
83            12 => MessageType::PongResponse,
84            13 => MessageType::SubscribeRequest,
85            14 => MessageType::SubscribeResponse,
86            15 => MessageType::PublishRequest,
87            16 => MessageType::PublishResponse,
88            17 => MessageType::RpcRequest,
89            18 => MessageType::RpcResponse,
90            _ => MessageType::AuthorizationRequest, // 默认值
91        }
92    }
93}
94
95impl From<MessageType> for u8 {
96    fn from(msg_type: MessageType) -> Self {
97        msg_type as u8
98    }
99}
100
101/// 消息设置
102#[derive(Debug, Clone, Default, Serialize, Deserialize)]
103pub struct MessageSetting {
104    pub need_receipt: bool,
105    pub signal: u8,
106}
107
108impl MessageSetting {
109    pub fn new() -> Self {
110        Self::default()
111    }
112}
113
114/// 数据包结构
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct Packet<T: Message> {
117    pub message_type: MessageType,
118    pub body: T,
119}
120
121impl<T: Message> Packet<T> {
122    pub fn new(message_type: MessageType, body: T) -> Self {
123        Self { message_type, body }
124    }
125}
126
127/// 连接请求
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct AuthorizationRequest {
130    /// 认证类型
131    pub auth_type: AuthType,
132    /// 认证令牌
133    pub auth_token: String,
134    /// 客户端信息
135    pub client_info: ClientInfo,
136    /// 设备信息
137    pub device_info: DeviceInfo,
138    /// 协议版本
139    pub protocol_version: String,
140    /// 扩展属性
141    pub properties: HashMap<String, String>,
142}
143
144impl AuthorizationRequest {
145    pub fn new() -> Self {
146        Self {
147            auth_type: AuthType::JWT,
148            auth_token: String::new(),
149            client_info: ClientInfo {
150                client_type: String::new(),
151                version: String::new(),
152                os: String::new(),
153                os_version: String::new(),
154                device_model: None,
155                app_package: None,
156            },
157            device_info: DeviceInfo {
158                device_id: String::new(),
159                device_type: DeviceType::Unknown,
160                app_id: String::new(),
161                push_token: None,
162                push_channel: None,
163                device_name: String::new(),
164                device_model: None,
165                os_version: None,
166                app_version: None,
167                manufacturer: None,
168                device_fingerprint: None,
169            },
170            protocol_version: crate::version::VERSION.to_string(),
171            properties: HashMap::new(),
172        }
173    }
174
175    pub fn create_packet(self) -> Packet<Self> {
176        Packet::new(MessageType::AuthorizationRequest, self)
177    }
178}
179
180/// 连接响应
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct AuthorizationResponse {
183    /// 连接是否成功
184    pub success: bool,
185    /// 错误码
186    pub error_code: Option<String>,
187    /// 错误信息
188    pub error_message: Option<String>,
189    /// 会话ID
190    pub session_id: Option<String>,
191    /// 用户ID
192    pub user_id: Option<u64>,
193    /// 服务器分配的连接ID
194    pub connection_id: Option<String>,
195    /// 服务器信息
196    pub server_info: Option<ServerInfo>,
197    /// 心跳间隔(秒)
198    pub heartbeat_interval: Option<u64>,
199}
200
201/// 认证类型
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub enum AuthType {
204    /// JWT令牌认证
205    JWT,
206    /// 用户名密码认证
207    UserPassword,
208    /// 第三方OAuth认证
209    OAuth,
210    /// 匿名认证
211    Anonymous,
212}
213
214/// 客户端信息
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct ClientInfo {
217    /// 客户端类型
218    pub client_type: String,
219    /// 客户端版本
220    pub version: String,
221    /// 操作系统
222    pub os: String,
223    /// 操作系统版本
224    pub os_version: String,
225    /// 设备型号
226    pub device_model: Option<String>,
227    /// 应用包名
228    pub app_package: Option<String>,
229}
230
231/// 设备信息
232#[derive(Debug, Clone, Serialize, Deserialize)]
233pub struct DeviceInfo {
234    pub device_id: String,
235    pub device_type: DeviceType,
236    pub app_id: String,
237    pub push_token: Option<String>,
238    pub push_channel: Option<String>,
239    pub device_name: String,
240    pub device_model: Option<String>,
241    pub os_version: Option<String>,
242    pub app_version: Option<String>,
243    pub manufacturer: Option<String>,
244    pub device_fingerprint: Option<String>,
245}
246
247/// 设备类型
248#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
249#[serde(rename_all = "lowercase")]
250#[allow(non_camel_case_types)]
251pub enum DeviceType {
252    #[serde(rename = "ios")]
253    iOS,
254    #[serde(rename = "android")]
255    Android,
256    #[serde(rename = "web")]
257    Web,
258    #[serde(rename = "macos")]
259    MacOS,
260    #[serde(rename = "windows")]
261    Windows,
262    #[serde(rename = "linux")]
263    Linux,
264    #[serde(rename = "iot")]
265    IoT,
266    #[serde(rename = "unknown")]
267    Unknown,
268}
269
270impl DeviceType {
271    pub fn as_str(&self) -> &str {
272        match self {
273            DeviceType::iOS => "ios",
274            DeviceType::Android => "android",
275            DeviceType::Web => "web",
276            DeviceType::MacOS => "macos",
277            DeviceType::Windows => "windows",
278            DeviceType::Linux => "linux",
279            DeviceType::IoT => "iot",
280            DeviceType::Unknown => "unknown",
281        }
282    }
283
284    pub fn from_str(s: &str) -> Self {
285        match s.to_lowercase().as_str() {
286            "ios" => DeviceType::iOS,
287            "android" => DeviceType::Android,
288            "web" => DeviceType::Web,
289            "macos" => DeviceType::MacOS,
290            "windows" => DeviceType::Windows,
291            "linux" | "freebsd" | "unix" => DeviceType::Linux,
292            "iot" => DeviceType::IoT,
293            _ => DeviceType::Unknown,
294        }
295    }
296}
297
298/// 服务器信息
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct ServerInfo {
301    pub version: String,
302    pub name: String,
303    pub features: Vec<String>,
304    pub max_message_size: u64,
305    pub connection_timeout: u64,
306}
307
308/// 断开连接请求
309#[derive(Debug, Clone, Serialize, Deserialize)]
310pub struct DisconnectRequest {
311    pub reason: DisconnectReason,
312    pub message: Option<String>,
313}
314
315/// 断开连接响应
316#[derive(Debug, Clone, Serialize, Deserialize)]
317pub struct DisconnectResponse {
318    pub acknowledged: bool,
319}
320
321/// 断开连接原因
322#[derive(Debug, Clone, Serialize, Deserialize)]
323pub enum DisconnectReason {
324    UserInitiated,
325    ServerShutdown,
326    AuthenticationFailed,
327    ProtocolError,
328    Timeout,
329    DuplicateConnection,
330    ServerMaintenance,
331}
332
333/// 通用消息包装器
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct MessagePacket {
336    pub message_type: String,
337    pub server_message_id: Option<u64>,
338    pub timestamp: u64,
339    pub payload: serde_json::Value,
340    pub headers: HashMap<String, String>,
341}
342
343/// 错误响应
344#[derive(Debug, Clone, Serialize, Deserialize)]
345pub struct ErrorResponse {
346    pub error_code: String,
347    pub error_message: String,
348    pub error_details: Option<HashMap<String, String>>,
349    pub timestamp: u64,
350}
351
352/// 发送消息请求
353#[derive(Debug, Clone, Default, Serialize, Deserialize)]
354pub struct SendMessageRequest {
355    pub setting: MessageSetting,
356    pub client_seq: u32,
357    pub local_message_id: u64,
358    pub stream_no: String,
359    pub channel_id: u64,
360    pub message_type: u32,
361    pub expire: u32,
362    pub from_uid: u64,
363    pub topic: String,
364    pub payload: Vec<u8>,
365}
366
367impl SendMessageRequest {
368    pub fn new() -> Self {
369        Self::default()
370    }
371
372    pub fn create_packet(self) -> Packet<Self> {
373        Packet::new(MessageType::SendMessageRequest, self)
374    }
375
376    pub fn verify_string(&self) -> String {
377        format!(
378            "{}:{}:{}",
379            self.local_message_id, self.channel_id, self.from_uid
380        )
381    }
382}
383
384/// 发送消息响应
385#[derive(Debug, Clone, Default, Serialize, Deserialize)]
386pub struct SendMessageResponse {
387    pub client_seq: u32,
388    pub server_message_id: u64,
389    pub message_seq: u32,
390    pub reason_code: u32,
391}
392
393impl SendMessageResponse {
394    pub fn new() -> Self {
395        Self::default()
396    }
397
398    pub fn create_packet(self) -> Packet<Self> {
399        Packet::new(MessageType::SendMessageResponse, self)
400    }
401}
402
403/// 推送消息请求(服务端推送给客户端)
404#[derive(Debug, Clone, Default, Serialize, Deserialize)]
405pub struct PushMessageRequest {
406    pub setting: MessageSetting,
407    pub msg_key: String,
408    pub server_message_id: u64,
409    pub message_seq: u32,
410    pub local_message_id: u64,
411    pub stream_no: String,
412    pub stream_seq: u32,
413    pub stream_flag: u8,
414    pub timestamp: u32,
415    pub channel_id: u64,
416    pub channel_type: u8,
417    pub message_type: u32,
418    pub expire: u32,
419    pub topic: String,
420    pub from_uid: u64,
421    pub payload: Vec<u8>,
422}
423
424impl PushMessageRequest {
425    pub fn new() -> Self {
426        Self::default()
427    }
428
429    pub fn create_packet(self) -> Packet<Self> {
430        Packet::new(MessageType::PushMessageRequest, self)
431    }
432
433    pub fn verify_string(&self) -> String {
434        format!(
435            "{}:{}:{}",
436            self.server_message_id, self.channel_id, self.from_uid
437        )
438    }
439}
440
441/// 推送消息响应(客户端确认接收)
442#[derive(Debug, Clone, Default, Serialize, Deserialize)]
443pub struct PushMessageResponse {
444    pub succeed: bool,
445    pub message: Option<String>,
446}
447
448impl PushMessageResponse {
449    pub fn new() -> Self {
450        Self::default()
451    }
452
453    pub fn create_packet(self) -> Packet<Self> {
454        Packet::new(MessageType::PushMessageResponse, self)
455    }
456}
457
458/// 心跳消息
459#[derive(Debug, Clone, Default, Serialize, Deserialize)]
460pub struct PingRequest {
461    pub timestamp: i64,
462}
463
464impl PingRequest {
465    pub fn new() -> Self {
466        Self::default()
467    }
468
469    pub fn create_packet(self) -> Packet<Self> {
470        Packet::new(MessageType::PingRequest, self)
471    }
472}
473
474/// 心跳回复消息
475#[derive(Debug, Clone, Default, Serialize, Deserialize)]
476pub struct PongResponse {
477    pub timestamp: i64,
478}
479
480impl PongResponse {
481    pub fn new() -> Self {
482        Self::default()
483    }
484
485    pub fn create_packet(self) -> Packet<Self> {
486        Packet::new(MessageType::PongResponse, self)
487    }
488}
489
490/// 订阅消息
491#[derive(Debug, Clone, Default, Serialize, Deserialize)]
492pub struct SubscribeRequest {
493    pub setting: u8,
494    pub local_message_id: u64,
495    pub channel_id: u64,
496    pub channel_type: u8,
497    pub action: u8,
498    pub param: String,
499}
500
501impl SubscribeRequest {
502    pub fn new() -> Self {
503        Self::default()
504    }
505
506    pub fn create_packet(self) -> Packet<Self> {
507        Packet::new(MessageType::SubscribeRequest, self)
508    }
509}
510
511/// 订阅确认消息
512#[derive(Debug, Clone, Default, Serialize, Deserialize)]
513pub struct SubscribeResponse {
514    pub local_message_id: u64,
515    pub channel_id: u64,
516    pub channel_type: u8,
517    pub action: u8,
518    pub reason_code: u8,
519}
520
521impl SubscribeResponse {
522    pub fn new() -> Self {
523        Self::default()
524    }
525
526    pub fn create_packet(self) -> Packet<Self> {
527        Packet::new(MessageType::SubscribeResponse, self)
528    }
529}
530
531/// 批量接收消息
532#[derive(Debug, Clone, Default, Serialize, Deserialize)]
533pub struct PushBatchRequest {
534    pub messages: Vec<PushMessageRequest>,
535}
536
537impl PushBatchRequest {
538    pub fn new() -> Self {
539        Self::default()
540    }
541
542    pub fn create_packet(self) -> Packet<Self> {
543        Packet::new(MessageType::PushBatchRequest, self)
544    }
545
546    pub fn single_batch(messages: Vec<PushMessageRequest>) -> Self {
547        Self { messages }
548    }
549
550    pub fn multi_batch(messages: Vec<PushMessageRequest>) -> Self {
551        Self { messages }
552    }
553
554    pub fn message_count(&self) -> usize {
555        self.messages.len()
556    }
557
558    pub fn is_empty(&self) -> bool {
559        self.messages.is_empty()
560    }
561}
562
563/// 批量接收确认消息
564#[derive(Debug, Clone, Default, Serialize, Deserialize)]
565pub struct PushBatchResponse {
566    pub succeed: bool,
567    pub message: Option<String>,
568}
569
570impl PushBatchResponse {
571    pub fn new() -> Self {
572        Self::default()
573    }
574
575    pub fn create_packet(self) -> Packet<Self> {
576        Packet::new(MessageType::PushBatchResponse, self)
577    }
578
579    pub fn success() -> Self {
580        Self {
581            succeed: true,
582            message: Some("批量消息接收成功".to_string()),
583        }
584    }
585
586    pub fn failure(error_msg: &str) -> Self {
587        Self {
588            succeed: false,
589            message: Some(error_msg.to_string()),
590        }
591    }
592}
593
594/// 频道推送消息
595#[derive(Debug, Clone, Default, Serialize, Deserialize)]
596pub struct PublishRequest {
597    pub channel_id: u64,
598    pub topic: Option<String>,
599    pub timestamp: u64,
600    pub payload: Vec<u8>,
601    pub publisher: Option<String>,
602    pub server_message_id: Option<u64>,
603}
604
605impl PublishRequest {
606    pub fn new() -> Self {
607        Self::default()
608    }
609
610    pub fn create_packet(self) -> Packet<Self> {
611        Packet::new(MessageType::PublishRequest, self)
612    }
613
614    pub fn system_push(channel_id: u64, payload: Vec<u8>) -> Self {
615        use std::time::{SystemTime, UNIX_EPOCH};
616        let timestamp = SystemTime::now()
617            .duration_since(UNIX_EPOCH)
618            .unwrap()
619            .as_secs();
620        let server_message_id = timestamp;
621        Self {
622            channel_id,
623            topic: None,
624            timestamp,
625            payload,
626            publisher: Some("system".to_string()),
627            server_message_id: Some(server_message_id),
628        }
629    }
630
631    pub fn topic_push(channel_id: u64, topic: &str, payload: Vec<u8>) -> Self {
632        use std::time::{SystemTime, UNIX_EPOCH};
633        let timestamp = SystemTime::now()
634            .duration_since(UNIX_EPOCH)
635            .unwrap()
636            .as_secs();
637        let server_message_id = timestamp;
638        Self {
639            channel_id,
640            topic: Some(topic.to_string()),
641            timestamp,
642            payload,
643            publisher: None,
644            server_message_id: Some(server_message_id),
645        }
646    }
647}
648
649/// 推送确认消息
650#[derive(Debug, Clone, Default, Serialize, Deserialize)]
651pub struct PublishResponse {
652    pub succeed: bool,
653    pub message: Option<String>,
654}
655
656impl PublishResponse {
657    pub fn new() -> Self {
658        Self::default()
659    }
660
661    pub fn create_packet(self) -> Packet<Self> {
662        Packet::new(MessageType::PublishResponse, self)
663    }
664
665    pub fn success() -> Self {
666        Self {
667            succeed: true,
668            message: Some("推送消息接收成功".to_string()),
669        }
670    }
671
672    pub fn failure(error_msg: &str) -> Self {
673        Self {
674            succeed: false,
675            message: Some(error_msg.to_string()),
676        }
677    }
678}
679
680/// RPC 请求消息
681#[derive(Debug, Clone, Serialize, Deserialize)]
682pub struct RpcRequest {
683    pub route: String,
684    pub body: serde_json::Value,
685}
686
687impl RpcRequest {
688    pub fn new() -> Self {
689        Self {
690            route: String::new(),
691            body: serde_json::Value::Null,
692        }
693    }
694
695    pub fn create_packet(self) -> Packet<Self> {
696        Packet::new(MessageType::RpcRequest, self)
697    }
698}
699
700/// RPC 响应消息
701#[derive(Debug, Clone, Serialize, Deserialize)]
702pub struct RpcResponse {
703    pub code: i32,
704    pub message: String,
705    pub data: Option<serde_json::Value>,
706}
707
708impl RpcResponse {
709    pub fn new() -> Self {
710        Self {
711            code: 0,
712            message: "OK".to_string(),
713            data: None,
714        }
715    }
716
717    pub fn create_packet(self) -> Packet<Self> {
718        Packet::new(MessageType::RpcResponse, self)
719    }
720
721    pub fn success(data: serde_json::Value) -> Self {
722        Self {
723            code: 0,
724            message: "OK".to_string(),
725            data: Some(data),
726        }
727    }
728
729    pub fn success_empty() -> Self {
730        Self {
731            code: 0,
732            message: "OK".to_string(),
733            data: None,
734        }
735    }
736
737    pub fn error(code: i32, message: String) -> Self {
738        Self {
739            code,
740            message,
741            data: None,
742        }
743    }
744
745    #[inline]
746    pub fn is_ok(&self) -> bool {
747        self.code == 0
748    }
749
750    #[inline]
751    pub fn is_err(&self) -> bool {
752        self.code != 0
753    }
754}
755
756impl Message for AuthorizationRequest {
757    fn message_type(&self) -> MessageType {
758        MessageType::AuthorizationRequest
759    }
760}
761
762impl Message for AuthorizationResponse {
763    fn message_type(&self) -> MessageType {
764        MessageType::AuthorizationResponse
765    }
766}
767
768impl Message for SendMessageRequest {
769    fn message_type(&self) -> MessageType {
770        MessageType::SendMessageRequest
771    }
772}
773
774impl Message for SendMessageResponse {
775    fn message_type(&self) -> MessageType {
776        MessageType::SendMessageResponse
777    }
778}
779
780impl Message for PushMessageRequest {
781    fn message_type(&self) -> MessageType {
782        MessageType::PushMessageRequest
783    }
784}
785
786impl Message for PushMessageResponse {
787    fn message_type(&self) -> MessageType {
788        MessageType::PushMessageResponse
789    }
790}
791
792impl Message for PingRequest {
793    fn message_type(&self) -> MessageType {
794        MessageType::PingRequest
795    }
796}
797
798impl Message for PongResponse {
799    fn message_type(&self) -> MessageType {
800        MessageType::PongResponse
801    }
802}
803
804impl Message for DisconnectRequest {
805    fn message_type(&self) -> MessageType {
806        MessageType::DisconnectRequest
807    }
808}
809
810impl Message for SubscribeRequest {
811    fn message_type(&self) -> MessageType {
812        MessageType::SubscribeRequest
813    }
814}
815
816impl Message for SubscribeResponse {
817    fn message_type(&self) -> MessageType {
818        MessageType::SubscribeResponse
819    }
820}
821
822impl Message for PushBatchRequest {
823    fn message_type(&self) -> MessageType {
824        MessageType::PushBatchRequest
825    }
826}
827
828impl Message for PushBatchResponse {
829    fn message_type(&self) -> MessageType {
830        MessageType::PushBatchResponse
831    }
832}
833
834impl DisconnectResponse {
835    pub fn new() -> Self {
836        Self {
837            acknowledged: false,
838        }
839    }
840
841    pub fn create_packet(self) -> Packet<Self> {
842        Packet::new(MessageType::DisconnectResponse, self)
843    }
844}
845
846impl Message for DisconnectResponse {
847    fn message_type(&self) -> MessageType {
848        MessageType::DisconnectResponse
849    }
850}
851
852impl Message for PublishRequest {
853    fn message_type(&self) -> MessageType {
854        MessageType::PublishRequest
855    }
856}
857
858impl Message for PublishResponse {
859    fn message_type(&self) -> MessageType {
860        MessageType::PublishResponse
861    }
862}
863
864impl Message for RpcRequest {
865    fn message_type(&self) -> MessageType {
866        MessageType::RpcRequest
867    }
868}
869
870impl Message for RpcResponse {
871    fn message_type(&self) -> MessageType {
872        MessageType::RpcResponse
873    }
874}
875
876#[cfg(test)]
877mod tests {
878    use super::*;
879
880    #[test]
881    fn test_message_creation() {
882        let connect_msg = AuthorizationRequest::new();
883        let packet = connect_msg.create_packet();
884        assert_eq!(packet.message_type, MessageType::AuthorizationRequest);
885
886        let send_msg = SendMessageRequest::new();
887        let packet = send_msg.create_packet();
888        assert_eq!(packet.message_type, MessageType::SendMessageRequest);
889    }
890
891    #[test]
892    fn test_message_types() {
893        assert_eq!(MessageType::AuthorizationRequest as u8, 1);
894        assert_eq!(MessageType::SendMessageRequest as u8, 5);
895        assert_eq!(MessageType::PushMessageRequest as u8, 7);
896    }
897
898    #[test]
899    fn test_message_type_conversion() {
900        assert_eq!(MessageType::from(1u8), MessageType::AuthorizationRequest);
901        assert_eq!(u8::from(MessageType::AuthorizationRequest), 1);
902    }
903
904    #[test]
905    fn test_message_setting() {
906        let setting = MessageSetting::new();
907        assert_eq!(setting.need_receipt, false);
908    }
909
910    #[test]
911    fn test_batch_message() {
912        let mut messages = Vec::new();
913        for i in 1..=3 {
914            let mut recv_msg = PushMessageRequest::new();
915            recv_msg.server_message_id = i as u64;
916            recv_msg.from_uid = i as u64;
917            recv_msg.channel_id = 1;
918            recv_msg.payload = format!("Message {}", i).into_bytes();
919            messages.push(recv_msg);
920        }
921        let batch_msg = PushBatchRequest::single_batch(messages);
922        assert_eq!(batch_msg.message_count(), 3);
923    }
924
925    #[test]
926    fn test_publish_message() {
927        let system_msg = PublishRequest::system_push(12345, "系统通知内容".as_bytes().to_vec());
928        assert_eq!(system_msg.channel_id, 12345);
929    }
930
931    #[test]
932    fn test_disconnect_ack_message() {
933        let disconnect_ack = DisconnectResponse { acknowledged: true };
934        assert_eq!(disconnect_ack.acknowledged, true);
935    }
936
937    #[test]
938    fn test_recv_batch_ack_message() {
939        let batch_ack = PushBatchResponse::success();
940        assert_eq!(batch_ack.succeed, true);
941    }
942}