Skip to main content

signer_remote/remote/
crdt_crypted_event_vo.rs

1use serde::{Deserialize, Serialize};
2use signer_core::{SignerCrypted, SignerKeys, SignerUser};
3use signer_crdt::{view::CrdtEventVO, errors::ViewError};
4
5use crate::{
6    error::{RemoteError, RemoteResult},
7    remote::{HttpClient, HttpClientConfig},
8};
9
10/// CRDT 加密事件视图对象
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct CrdtCryptedEventVO {
13    pub clock: i32,
14    pub peer: String,
15    pub data: SignerCrypted<CrdtEventVO>,
16}
17
18/// POST CRDT 事件请求
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct PostCrdtEventsRequest {
21    /// 数据
22    pub data: Vec<CrdtCryptedEventVO>,
23}
24
25/// 获取 CRDT 事件响应
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct GetCrdtEventsResponse {
28    /// 数据
29    pub data: Vec<CrdtCryptedEventVO>,
30}
31
32impl CrdtCryptedEventVO {
33    /// 从 signer-crdt 的 CrdtEventVO 创建加密事件
34    pub fn encrypt(
35        keys: &SignerKeys,
36        data: &CrdtEventVO,
37    ) -> Result<Self, ViewError> {
38        // 移除 crdt_event 中的 revert 字段内容
39        let data = CrdtEventVO {
40            revert: None,
41            ..data.clone()
42        };
43
44        Ok(Self {
45            clock: data.clock,
46            peer: data.peer.clone(),
47            data: SignerCrypted::create(keys, &keys.pub_key, data)?,
48        })
49    }
50
51    /// 解密事件为 signer-crdt 的 CrdtEventVO
52    pub fn decrypt(
53        &self,
54        keys: &SignerKeys,
55    ) -> Result<CrdtEventVO, ViewError> {
56        let data = self.data.decrypt(keys)?;
57        Ok(CrdtEventVO {
58            revert: None,
59            ..data
60        })
61    }
62
63    /// 推送 CRDT 事件到服务器
64    pub async fn push(
65        events: Vec<CrdtCryptedEventVO>,
66        addr: &str,
67        keys: &SignerKeys,
68        user: &SignerUser,
69    ) -> RemoteResult<()> {
70        if events.is_empty() {
71            return Ok(());
72        }
73
74        let req = PostCrdtEventsRequest { data: events };
75
76        let config = HttpClientConfig::new(keys.clone(), user.clone(), addr.to_string());
77        let client = HttpClient::new(config);
78
79        let _: serde_json::Value = client
80            .post("/api/crdt-events", &req)
81            .await
82            .map_err(|e| RemoteError::Internal(format!("推送 CRDT 事件失败: {}", e)))?;
83
84        Ok(())
85    }
86
87    /// 从服务器拉取 CRDT 事件
88    pub async fn pull(
89        addr: &str,
90        keys: &SignerKeys,
91        user: &SignerUser,
92        frontiers: &str, // JSON 字符串形式的前沿信息
93    ) -> RemoteResult<Vec<CrdtCryptedEventVO>> {
94        let config = HttpClientConfig::new(keys.clone(), user.clone(), addr.to_string());
95        let client = HttpClient::new(config);
96
97        #[derive(serde::Serialize)]
98        struct QueryParams {
99            frontiers: Option<String>,
100        }
101
102        let query = QueryParams {
103            frontiers: Some(frontiers.to_string()),
104        };
105
106        let r: GetCrdtEventsResponse = client
107            .get_with_query("/api/crdt-events", &query)
108            .await
109            .map_err(|e| RemoteError::Internal(format!("拉取 CRDT 事件失败: {}", e)))?;
110
111        Ok(r.data)
112    }
113}