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
//! 信封相关结构体和方法
use serde::{Deserialize, Serialize};
use signer_core::{SignerCrypted, SignerSigned, SignerKeys, SignerUser};
use signer_crdt::{SignerMeta, view::{MessageVO, ChatVO, UserVO}};
use crate::{
error::{RemoteError, RemoteResult},
remote::{HttpClient, HttpClientConfig, SignerRemote},
};
/// 信封
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Envelope {
pub data: SignerSigned<SignerCrypted<EnvelopeInner>>,
}
/// 信封内部结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvelopeInner {
pub destinations: Vec<String>,
pub message: MessageVO,
}
impl EnvelopeInner {
/// 消费信封内容,自动处理 Chat 创建和用户信息拉取
pub async fn consume(&self, meta: &SignerMeta) -> RemoteResult<()> {
tracing::info!("开始消费信封,消息ID: {}", self.message.id);
// 获取聊天键
let chat_key = self.message.chat.chat_key(meta).await
.map_err(|e| RemoteError::Internal(format!("获取聊天键失败: {}", e)))?;
// 检查 Chat 是否存在
let chat_variant = self.message.chat.chat_variant();
let existing_chat = ChatVO::get(meta, &chat_key, &chat_variant).await
.map_err(|e| RemoteError::Internal(format!("检查聊天是否存在失败: {}", e)))?;
if existing_chat.is_none() {
tracing::info!("聊天 {} 不存在,尝试创建", chat_key);
// 如果是私聊类型,需要先确保用户信息存在
let ChatVO::Private(_) = &self.message.chat;
let existing_user = UserVO::get(meta, &chat_key).await
.map_err(|e| RemoteError::Internal(format!("检查用户是否存在失败: {}", e)))?;
if existing_user.is_none() {
tracing::info!("用户 {} 不存在,尝试从目标服务器拉取", chat_key);
if self.destinations.is_empty() {
return Err(RemoteError::Internal(
format!("无法拉取用户 {} 信息:destinations 为空", chat_key)
));
}
let mut last_error = None;
let mut success = false;
// 遍历所有目标服务器,尝试拉取用户信息
for destination in &self.destinations {
tracing::info!("尝试从服务器 {} 拉取用户 {} 信息", destination, chat_key);
let remote = SignerRemote::new(destination);
match remote.pull_user(meta, &chat_key).await {
Ok(_) => {
tracing::info!("成功从服务器 {} 拉取用户 {} 信息", destination, chat_key);
success = true;
break;
}
Err(e) => {
tracing::warn!("从服务器 {} 拉取用户 {} 信息失败: {}", destination, chat_key, e);
last_error = Some(e);
}
}
}
if !success {
let error_msg = if let Some(e) = last_error {
format!("从所有目标服务器拉取用户 {} 信息均失败,最后一个错误: {}", chat_key, e)
} else {
format!("从所有目标服务器拉取用户 {} 信息均失败", chat_key)
};
tracing::error!("{}", error_msg);
return Err(RemoteError::Internal(error_msg));
}
// 重新检查用户是否已成功拉取
let existing_user_after_pull = UserVO::get(meta, &chat_key).await
.map_err(|e| RemoteError::Internal(format!("重新检查用户是否存在失败: {}", e)))?;
if existing_user_after_pull.is_none() {
return Err(RemoteError::Internal(
format!("用户 {} 拉取失败:拉取后仍不存在于本地数据库", chat_key)
));
}
tracing::info!("成功拉取并保存用户 {} 信息到本地数据库", chat_key);
}
// 创建 Chat
self.message.chat.put(meta).await
.map_err(|e| RemoteError::Internal(format!("创建聊天失败: {}", e)))?;
tracing::info!("成功创建聊天 {}", chat_key);
}
// 保存消息
self.message.put(meta).await
.map_err(|e| RemoteError::Internal(format!("保存消息失败: {}", e)))?;
tracing::info!("成功消费信封,消息ID: {}", self.message.id);
Ok(())
}
}
/// 信封盒子
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvelopeBox {
pub id: i32,
pub envelope: Box<Envelope>,
}
/// POST 信封请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostEnvelopesRequest {
pub data: Vec<Envelope>,
}
/// 获取信封响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetEnvelopesResponse {
pub data: Vec<EnvelopeBox>,
}
impl Envelope {
/// 创建信封
pub async fn create(
keys: &SignerKeys,
message: &MessageVO,
destinations: Vec<String>,
chat_key: &str,
) -> RemoteResult<Self> {
let inner = EnvelopeInner {
destinations,
message: message.clone(),
};
let inner = SignerCrypted::create(keys, chat_key, inner.clone())
.map_err(|e| RemoteError::Internal(format!("创建加密信封失败: {}", e)))?;
let inner = SignerSigned::from_value(keys, &inner)
.map_err(|e| RemoteError::Internal(format!("创建签名信封失败: {}", e)))?;
Ok(Self { data: inner })
}
/// 打开信封
pub fn open(&self, keys: &SignerKeys) -> RemoteResult<EnvelopeInner> {
let inner = self.data.verify_to_value()
.map_err(|e| RemoteError::Internal(format!("验证信封签名失败: {}", e)))?;
let inner = inner.decrypt(keys)
.map_err(|e| RemoteError::Internal(format!("解密信封失败: {}", e)))?;
Ok(inner)
}
/// 推送信封到服务器
pub async fn push(envelopes: Vec<Envelope>, addr: &str, keys: &SignerKeys, user: &SignerUser) -> RemoteResult<()> {
if envelopes.is_empty() {
return Ok(());
}
let req = PostEnvelopesRequest {
data: envelopes,
};
let config = HttpClientConfig::new(keys.clone(), user.clone(), addr.to_string());
let client = HttpClient::new(config);
let _: serde_json::Value = client.post("/api/envelopes", &req).await
.map_err(|e| RemoteError::Internal(format!("推送信封失败: {}", e)))?;
Ok(())
}
/// 从服务器拉取信封(消息队列模式)
/// 返回 (信封列表, 信封ID列表) 用于后续 ACK 确认
pub async fn pull(addr: &str, keys: &SignerKeys, user: &SignerUser) -> RemoteResult<(Vec<Envelope>, Vec<i32>)> {
let config = HttpClientConfig::new(keys.clone(), user.clone(), addr.to_string());
let client = HttpClient::new(config);
let r: GetEnvelopesResponse = client.get("/api/envelopes").await
.map_err(|e| RemoteError::Internal(format!("拉取信封失败: {}", e)))?;
let mut envelopes = Vec::new();
let mut envelope_ids = Vec::new();
for envelope_box in r.data {
envelopes.push(*envelope_box.envelope);
envelope_ids.push(envelope_box.id);
}
tracing::info!("成功拉取 {} 个锁定信封", envelopes.len());
Ok((envelopes, envelope_ids))
}
/// 确认信封处理完成(ACK)
pub async fn ack(addr: &str, keys: &SignerKeys, user: &SignerUser, envelope_ids: Vec<i32>) -> RemoteResult<()> {
if envelope_ids.is_empty() {
return Ok(());
}
let config = HttpClientConfig::new(keys.clone(), user.clone(), addr.to_string());
let client = HttpClient::new(config);
// 构建逗号分隔的 ID 字符串
let ids_param = envelope_ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",");
let url = format!("/api/envelopes?ids={}", ids_param);
let _: serde_json::Value = client.delete(&url).await
.map_err(|e| RemoteError::Internal(format!("确认信封失败: {}", e)))?;
tracing::info!("成功确认 {} 个信封", envelope_ids.len());
Ok(())
}
/// 拉取并处理信封(完整流程)
pub async fn pull_and_process(addr: &str, keys: &SignerKeys, user: &SignerUser, meta: &SignerMeta) -> RemoteResult<()> {
// 1. 拉取锁定的信封
let (envelopes, envelope_ids) = Self::pull(addr, keys, user).await?;
if envelopes.is_empty() {
tracing::debug!("没有可处理的信封");
return Ok(());
}
let mut processed_ids = Vec::new();
let mut failed_count = 0;
let mut messages_to_save = Vec::new(); // Collect messages for batch saving
let mut chats_to_create = Vec::new(); // Collect chats for batch creation
let mut users_to_pull = std::collections::HashMap::new(); // Collect users to pull (chat_key -> destinations)
// 2. 打开每个信封并收集消息、聊天和用户信息
for (envelope, envelope_id) in envelopes.into_iter().zip(envelope_ids.iter()) {
match envelope.open(keys) {
Ok(inner) => {
tracing::debug!("成功打开信封 ID: {}", envelope_id);
// 收集消息
messages_to_save.push(inner.message.clone());
// 检查 Chat 是否存在
let chat_key = match inner.message.chat.chat_key(meta).await {
Ok(key) => key,
Err(e) => {
failed_count += 1;
tracing::error!("获取聊天键失败 for 信封 ID {}: {}", envelope_id, e);
continue;
}
};
let chat_variant = inner.message.chat.chat_variant();
match ChatVO::get(meta, &chat_key, &chat_variant).await {
Ok(Some(_)) => {
// Chat already exists, no need to create
tracing::debug!("聊天 {} 已存在", chat_key);
}
Ok(None) => {
// Chat does not exist, need to create
tracing::debug!("聊天 {} 不存在,准备创建", chat_key);
chats_to_create.push(inner.message.chat.clone());
// 如果是私聊类型,需要先确保用户信息存在
let ChatVO::Private(_) = &inner.message.chat;
// Check if user already exists
match UserVO::get(meta, &chat_key).await {
Ok(Some(_)) => {
// User already exists
tracing::debug!("用户 {} 已存在", chat_key);
}
Ok(None) => {
// User does not exist, need to pull
tracing::debug!("用户 {} 不存在,准备从服务器拉取", chat_key);
// Store destinations for this user
users_to_pull.insert(chat_key.clone(), inner.destinations.clone());
}
Err(e) => {
failed_count += 1;
tracing::error!("检查用户 {} 是否存在失败: {}", chat_key, e);
continue;
}
}
}
Err(e) => {
failed_count += 1;
tracing::error!("检查聊天 {} 是否存在失败: {}", chat_key, e);
continue;
}
}
processed_ids.push(*envelope_id);
}
Err(e) => {
failed_count += 1;
tracing::error!("打开信封 ID {} 失败: {}", envelope_id, e);
// 打开失败的信封不加入 ACK 列表
}
}
}
// 3. 批量拉取用户信息
if !users_to_pull.is_empty() {
tracing::info!("开始批量拉取 {} 个用户信息", users_to_pull.len());
for (chat_key, destinations) in users_to_pull {
if destinations.is_empty() {
tracing::warn!("无法拉取用户 {} 信息:destinations 为空", chat_key);
failed_count += 1;
// Remove this user from the list of users to process successfully
processed_ids.retain(|&_id| {
// This is a simplification. Ideally, we'd track which envelope ID corresponds to which chat_key.
// For now, we'll assume if a user pull fails, we don't ack any envelopes.
// A more robust solution would require tracking envelope_id -> chat_key mapping.
// Let's just log and continue, but mark the whole operation as partially failed.
true
});
continue;
}
let mut last_error = None;
let mut success = false;
// 遍历所有目标服务器,尝试拉取用户信息
for destination in &destinations {
tracing::info!("尝试从服务器 {} 拉取用户 {} 信息", destination, chat_key);
let remote = SignerRemote::new(destination);
match remote.pull_user(meta, &chat_key).await {
Ok(_) => {
tracing::info!("成功从服务器 {} 拉取用户 {} 信息", destination, chat_key);
success = true;
break;
}
Err(e) => {
tracing::warn!("从服务器 {} 拉取用户 {} 信息失败: {}", destination, chat_key, e);
last_error = Some(e);
}
}
}
if !success {
let error_msg = if let Some(e) = last_error {
format!("从所有目标服务器拉取用户 {} 信息均失败,最后一个错误: {}", chat_key, e)
} else {
format!("从所有目标服务器拉取用户 {} 信息均失败", chat_key)
};
tracing::error!("{}", error_msg);
failed_count += 1;
// If user pull fails, we should not ack the envelopes that depend on this user.
// This is a complex scenario. For simplicity, we'll log and continue.
// A more robust solution would require tracking which envelopes depend on which users.
}
}
}
// 4. 批量创建 Chat
if !chats_to_create.is_empty() {
tracing::info!("开始批量创建 {} 个聊天", chats_to_create.len());
for chat in chats_to_create {
match chat.put(meta).await {
Ok(_) => {
tracing::debug!("成功创建聊天");
}
Err(e) => {
failed_count += 1;
tracing::error!("创建聊天失败: {}", e);
// If chat creation fails, it might affect messages that depend on it.
// This is a complex scenario. For simplicity, we'll log and continue.
}
}
}
}
// 5. 批量保存消息
if !messages_to_save.is_empty() {
tracing::info!("开始批量保存 {} 个消息", messages_to_save.len());
match MessageVO::put_many(messages_to_save.clone(), meta).await {
Ok(_) => {
tracing::info!("成功批量保存 {} 个消息", processed_ids.len());
}
Err(e) => {
failed_count += messages_to_save.len() as u32; // Consider all messages as failed
tracing::error!("批量保存消息失败: {}", e);
}
}
}
// 6. 确认成功处理的信封
// Note: In this optimized version, we're acking all envelopes that were successfully opened,
// even if subsequent steps (user pull, chat create, message save) failed for some.
// This might lead to data inconsistency. A better approach would be to track success at a more granular level.
// For now, we'll keep it simple and ack all successfully opened envelopes.
if !processed_ids.is_empty() {
if let Err(e) = Self::ack(addr, keys, user, processed_ids.clone()).await {
tracing::error!("确认信封失败: {}", e);
// ACK 失败不影响处理结果,但会记录错误
}
}
tracing::info!(
"信封处理完成:成功处理 {} 个信封 (其中可能包含部分失败的操作),失败 {} 个信封",
processed_ids.len(),
failed_count
);
Ok(())
}
}