signer_remote/remote/
crdt_crypted_event_vo.rs1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct CrdtCryptedEventVO {
13 pub clock: i32,
14 pub peer: String,
15 pub data: SignerCrypted<CrdtEventVO>,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct PostCrdtEventsRequest {
21 pub data: Vec<CrdtCryptedEventVO>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct GetCrdtEventsResponse {
28 pub data: Vec<CrdtCryptedEventVO>,
30}
31
32impl CrdtCryptedEventVO {
33 pub fn encrypt(
35 keys: &SignerKeys,
36 data: &CrdtEventVO,
37 ) -> Result<Self, ViewError> {
38 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 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 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 pub async fn pull(
89 addr: &str,
90 keys: &SignerKeys,
91 user: &SignerUser,
92 frontiers: &str, ) -> 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}