ng_net/actors/client/
topic_sync_req.rs

1/*
2 * Copyright (c) 2022-2025 Niko Bonnieure, Par le Peuple, NextGraph.org developers
3 * All rights reserved.
4 * Licensed under the Apache License, Version 2.0
5 * <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
6 * or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
7 * at your option. All files in the project carrying such
8 * notice may not be copied, modified, or distributed except
9 * according to those terms.
10*/
11
12use std::sync::Arc;
13
14use async_std::sync::Mutex;
15
16use ng_repo::errors::*;
17use ng_repo::log::*;
18use ng_repo::repo::Repo;
19use ng_repo::types::*;
20
21use crate::broker::BROKER;
22use crate::connection::NoiseFSM;
23use crate::types::*;
24use crate::{actor::*, types::ProtocolMessage};
25
26impl TopicSyncReq {
27    pub fn get_actor(&self, id: i64) -> Box<dyn EActor> {
28        Actor::<TopicSyncReq, TopicSyncRes>::new_responder(id)
29    }
30
31    pub fn new_empty(topic: TopicId, overlay: &OverlayId) -> Self {
32        TopicSyncReq::V0(TopicSyncReqV0 {
33            topic,
34            known_heads: vec![],
35            target_heads: vec![],
36            overlay: Some(*overlay),
37            known_commits: None,
38        })
39    }
40
41    pub fn new(
42        repo: &Repo,
43        topic_id: &TopicId,
44        known_heads: Vec<ObjectId>,
45        target_heads: Vec<ObjectId>,
46        known_commits: Option<BloomFilter>,
47    ) -> TopicSyncReq {
48        TopicSyncReq::V0(TopicSyncReqV0 {
49            topic: *topic_id,
50            known_heads,
51            target_heads,
52            overlay: Some(repo.store.get_store_repo().overlay_id_for_read_purpose()),
53            known_commits,
54        })
55    }
56}
57
58impl TryFrom<ProtocolMessage> for TopicSyncReq {
59    type Error = ProtocolError;
60    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
61        let req: ClientRequestContentV0 = msg.try_into()?;
62        if let ClientRequestContentV0::TopicSyncReq(a) = req {
63            Ok(a)
64        } else {
65            log_debug!("INVALID {:?}", req);
66            Err(ProtocolError::InvalidValue)
67        }
68    }
69}
70
71impl From<TopicSyncReq> for ProtocolMessage {
72    fn from(msg: TopicSyncReq) -> ProtocolMessage {
73        let overlay = *msg.overlay();
74        ProtocolMessage::from_client_request_v0(ClientRequestContentV0::TopicSyncReq(msg), overlay)
75    }
76}
77
78impl TryFrom<ProtocolMessage> for TopicSyncRes {
79    type Error = ProtocolError;
80    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
81        let res: ClientResponseContentV0 = msg.try_into()?;
82        if let ClientResponseContentV0::TopicSyncRes(a) = res {
83            Ok(a)
84        } else {
85            log_debug!("INVALID {:?}", res);
86            Err(ProtocolError::InvalidValue)
87        }
88    }
89}
90
91impl From<TopicSyncRes> for ProtocolMessage {
92    fn from(b: TopicSyncRes) -> ProtocolMessage {
93        let mut cr: ClientResponse = ClientResponseContentV0::TopicSyncRes(b).into();
94        cr.set_result(ServerError::PartialContent.into());
95        cr.into()
96    }
97}
98
99impl Actor<'_, TopicSyncReq, TopicSyncRes> {}
100
101#[async_trait::async_trait]
102impl EActor for Actor<'_, TopicSyncReq, TopicSyncRes> {
103    async fn respond(
104        &mut self,
105        msg: ProtocolMessage,
106        fsm: Arc<Mutex<NoiseFSM>>,
107    ) -> Result<(), ProtocolError> {
108        let req = TopicSyncReq::try_from(msg)?;
109
110        let sb = { BROKER.read().await.get_server_broker()? };
111
112        let res = {
113            sb.read().await.topic_sync_req(
114                req.overlay(),
115                req.topic(),
116                req.known_heads(),
117                req.target_heads(),
118                req.known_commits(),
119            )
120        };
121
122        // IF NEEDED, the topic_sync_req could be changed to return a stream, and then the send_in_reply_to would be also totally async
123        match res {
124            Ok(blocks) => {
125                if blocks.is_empty() {
126                    let re: Result<(), ServerError> = Err(ServerError::EmptyStream);
127                    fsm.lock()
128                        .await
129                        .send_in_reply_to(re.into(), self.id())
130                        .await?;
131                    return Ok(());
132                }
133                let mut lock = fsm.lock().await;
134
135                for block in blocks {
136                    lock.send_in_reply_to(block.into(), self.id()).await?;
137                }
138                let re: Result<(), ServerError> = Err(ServerError::EndOfStream);
139                lock.send_in_reply_to(re.into(), self.id()).await?;
140            }
141            Err(e) => {
142                let re: Result<(), ServerError> = Err(e);
143                fsm.lock()
144                    .await
145                    .send_in_reply_to(re.into(), self.id())
146                    .await?;
147            }
148        }
149        Ok(())
150    }
151}