flare-core 0.1.2

A high-performance, reliable long-connection communication toolkit for Rust, supporting WebSocket and QUIC protocols with features like authentication, device management, serialization negotiation, and protocol racing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! 快速构建命令和 Frame 消息的辅助模块
//! 提供便捷方法创建各种类型的命令,自动生成消息 ID 和时间戳

use super::flare::core::{
    commands::{
        Command, CustomCommand, MessageCommand, NotificationCommand, SystemCommand,
    },
    Reliability, Frame,
};
use super::flare::core::commands::{
    command::Type as CommandType,
    message_command::Type as MessageType,
    notification_command::Type as NotificationType,
    system_command::{SerializationFormat, Type as SystemType},
};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

static COUNTER: AtomicU64 = AtomicU64::new(0);

/// 生成唯一的消息 ID(基于时间戳和递增计数器)
pub fn generate_message_id() -> String {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis();
    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("{}-{:016x}", timestamp, counter)
}

/// 获取当前时间戳(毫秒)
pub fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64
}

/// Frame 构建器
pub struct FrameBuilder {
    command: Option<Command>,
    message_id: Option<String>,
    reliability: Reliability,
    timestamp: Option<u64>,
    metadata: HashMap<String, Vec<u8>>,
}

impl FrameBuilder {
    /// 创建新的 Frame 构建器
    pub fn new() -> Self {
        Self {
            command: None,
            message_id: None,
            reliability: Reliability::BestEffort,
            timestamp: None,
            metadata: HashMap::new(),
        }
    }

    /// 设置命令
    pub fn with_command(mut self, command: Command) -> Self {
        self.command = Some(command);
        self
    }

    /// 设置消息 ID(不设置则自动生成)
    pub fn with_message_id(mut self, message_id: String) -> Self {
        self.message_id = Some(message_id);
        self
    }

    /// 设置可靠性等级
    pub fn with_reliability(mut self, reliability: Reliability) -> Self {
        self.reliability = reliability;
        self
    }

    /// 设置时间戳(不设置则使用当前时间)
    pub fn with_timestamp(mut self, timestamp: u64) -> Self {
        self.timestamp = Some(timestamp);
        self
    }

    /// 添加元数据
    pub fn with_metadata(mut self, key: String, value: Vec<u8>) -> Self {
        self.metadata.insert(key, value);
        self
    }

    /// 添加字符串元数据
    pub fn with_metadata_str(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value.into_bytes());
        self
    }

    /// 构建 Frame
    pub fn build(self) -> Frame {
        Frame {
            command: self.command,
            message_id: self.message_id.unwrap_or_else(generate_message_id),
            reliability: self.reliability as i32,
            timestamp: self.timestamp.unwrap_or_else(current_timestamp),
            metadata: self.metadata,
        }
    }
}

impl Default for FrameBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================
// 系统命令构建方法
// ============================================================

/// 创建 PING 命令(最简单,只需类型)
pub fn ping() -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Ping as i32,
        format: SerializationFormat::Protobuf as i32,
        message: String::new(),
        metadata: HashMap::new(),
        data: Vec::new(),
    }
}

/// 创建 PONG 命令
pub fn pong() -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Pong as i32,
        format: SerializationFormat::Protobuf as i32,
        message: String::new(),
        metadata: HashMap::new(),
        data: Vec::new(),
    }
}

/// 创建 CONNECT 命令
pub fn connect(format: SerializationFormat, metadata: HashMap<String, Vec<u8>>) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Connect as i32,
        format: format as i32,
        message: String::new(),
        metadata,
        data: Vec::new(),
    }
}

/// 创建 CONNECT_ACK 命令
pub fn connect_ack(
    format: SerializationFormat,
    metadata: HashMap<String, Vec<u8>>,
) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::ConnectAck as i32,
        format: format as i32,
        message: String::new(),
        metadata,
        data: Vec::new(),
    }
}

/// 创建 CLOSE 命令
pub fn close(message: Option<String>, metadata: Option<HashMap<String, Vec<u8>>>) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Close as i32,
        format: SerializationFormat::Protobuf as i32,
        message: message.unwrap_or_default(),
        metadata: metadata.unwrap_or_default(),
        data: Vec::new(),
    }
}

/// 创建 ERROR 命令
pub fn error(
    message: String,
    metadata: Option<HashMap<String, Vec<u8>>>,
) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Error as i32,
        format: SerializationFormat::Protobuf as i32,
        message,
        metadata: metadata.unwrap_or_default(),
        data: Vec::new(),
    }
}

/// 创建 EVENT 命令
pub fn event(
    message: String,
    metadata: Option<HashMap<String, Vec<u8>>>,
    data: Option<Vec<u8>>,
) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Event as i32,
        format: SerializationFormat::Protobuf as i32,
        message,
        metadata: metadata.unwrap_or_default(),
        data: data.unwrap_or_default(),
    }
}

/// 创建 AUTH 命令
pub fn auth(
    metadata: HashMap<String, Vec<u8>>,
    data: Option<Vec<u8>>,
) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Auth as i32,
        format: SerializationFormat::Protobuf as i32,
        message: String::new(),
        metadata,
        data: data.unwrap_or_default(),
    }
}

/// 创建 AUTH_ACK 命令
pub fn auth_ack(
    message: Option<String>,
    metadata: Option<HashMap<String, Vec<u8>>>,
) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::AuthAck as i32,
        format: SerializationFormat::Protobuf as i32,
        message: message.unwrap_or_default(),
        metadata: metadata.unwrap_or_default(),
        data: Vec::new(),
    }
}

/// 创建 KICKED 命令(被踢下线)
/// 
/// # 参数
/// - `reason`: 被踢的原因(必需)
/// - `metadata`: 可选的元数据(如设备信息、冲突连接ID等)
/// 
/// # 示例
/// ```rust
/// use flare_core::common::protocol::builder::kicked;
/// use flare_core::common::protocol::frame_with_system_command;
/// use std::collections::HashMap;
/// 
/// let mut metadata = HashMap::new();
/// metadata.insert("conflict_device".to_string(), "device-123".as_bytes().to_vec());
/// 
/// let kick_cmd = kicked("设备冲突:同一平台已有其他设备在线", Some(metadata));
/// let frame = frame_with_system_command(kick_cmd, Reliability::AtLeastOnce);
/// ```
pub fn kicked(
    reason: impl Into<String>,
    metadata: Option<HashMap<String, Vec<u8>>>,
) -> SystemCommand {
    SystemCommand {
        r#type: SystemType::Kicked as i32,
        format: SerializationFormat::Protobuf as i32,
        message: reason.into(),
        metadata: metadata.unwrap_or_default(),
        data: Vec::new(),
    }
}

// ============================================================
// 消息命令构建方法
// ============================================================

/// 创建 SEND 消息命令
pub fn send_message(
    message_id: String,
    payload: Vec<u8>,
    metadata: Option<HashMap<String, Vec<u8>>>,
    seq: Option<u64>,
) -> MessageCommand {
    MessageCommand {
        r#type: MessageType::Send as i32,
        message_id,
        payload,
        metadata: metadata.unwrap_or_default(),
        seq: seq.unwrap_or(0),
    }
}

/// 创建 ACK 消息命令
pub fn ack_message(
    message_id: String,
    metadata: Option<HashMap<String, Vec<u8>>>,
) -> MessageCommand {
    MessageCommand {
        r#type: MessageType::Ack as i32,
        message_id,
        payload: Vec::new(),
        metadata: metadata.unwrap_or_default(),
        seq: 0,
    }
}

/// 创建 DATA 消息命令(无需 ACK)
pub fn data_message(
    message_id: String,
    payload: Vec<u8>,
    metadata: Option<HashMap<String, Vec<u8>>>,
    seq: Option<u64>,
) -> MessageCommand {
    MessageCommand {
        r#type: MessageType::Data as i32,
        message_id,
        payload,
        metadata: metadata.unwrap_or_default(),
        seq: seq.unwrap_or(0),
    }
}

// ============================================================
// 通知命令构建方法
// ============================================================

/// 创建通知命令
pub fn notification(
    notification_type: NotificationType,
    title: String,
    content: Vec<u8>,
    metadata: Option<HashMap<String, Vec<u8>>>,
) -> NotificationCommand {
    NotificationCommand {
        r#type: notification_type as i32,
        title,
        content,
        metadata: metadata.unwrap_or_default(),
    }
}

// ============================================================
// 自定义命令构建方法
// ============================================================

/// 创建自定义命令
pub fn custom_command(
    name: String,
    data: Vec<u8>,
    metadata: Option<HashMap<String, Vec<u8>>>,
) -> CustomCommand {
    CustomCommand {
        name,
        data,
        metadata: metadata.unwrap_or_default(),
    }
}

// ============================================================
// Frame 快速构建方法
// ============================================================

/// 创建包含系统命令的 Frame
pub fn frame_with_system_command(
    system_command: SystemCommand,
    reliability: Reliability,
) -> Frame {
    FrameBuilder::new()
        .with_command(Command {
            r#type: Some(CommandType::System(system_command)),
        })
        .with_reliability(reliability)
        .build()
}

/// 创建包含消息命令的 Frame
pub fn frame_with_message_command(
    message_command: MessageCommand,
    reliability: Reliability,
) -> Frame {
    FrameBuilder::new()
        .with_command(Command {
            r#type: Some(CommandType::Message(message_command)),
        })
        .with_reliability(reliability)
        .build()
}

/// 创建包含通知命令的 Frame
pub fn frame_with_notification_command(
    notification_command: NotificationCommand,
    reliability: Reliability,
) -> Frame {
    FrameBuilder::new()
        .with_command(Command {
            r#type: Some(CommandType::Notification(notification_command)),
        })
        .with_reliability(reliability)
        .build()
}

/// 创建包含自定义命令的 Frame
pub fn frame_with_custom_command(
    custom_command: CustomCommand,
    reliability: Reliability,
) -> Frame {
    FrameBuilder::new()
        .with_command(Command {
            r#type: Some(CommandType::Custom(custom_command)),
        })
        .with_reliability(reliability)
        .build()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ping_pong() {
        let ping_cmd = ping();
        assert_eq!(ping_cmd.r#type, SystemType::Ping as i32);
        
        let pong_cmd = pong();
        assert_eq!(pong_cmd.r#type, SystemType::Pong as i32);
    }

    #[test]
    fn test_generate_message_id() {
        let id1 = generate_message_id();
        let id2 = generate_message_id();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_frame_builder() {
        let frame = FrameBuilder::new()
            .with_command(Command {
                r#type: Some(CommandType::System(ping())),
            })
            .with_reliability(Reliability::AtLeastOnce)
            .build();
        
        assert!(!frame.message_id.is_empty());
        assert!(frame.timestamp > 0);
    }
}