ng_net/actors/client/
blocks_put.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::*;
18
19use crate::broker::BROKER;
20use crate::connection::NoiseFSM;
21use crate::types::*;
22use crate::{actor::*, types::ProtocolMessage};
23
24impl BlocksPut {
25    pub fn get_actor(&self, id: i64) -> Box<dyn EActor> {
26        Actor::<BlocksPut, ()>::new_responder(id)
27    }
28}
29
30impl TryFrom<ProtocolMessage> for BlocksPut {
31    type Error = ProtocolError;
32    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
33        let req: ClientRequestContentV0 = msg.try_into()?;
34        if let ClientRequestContentV0::BlocksPut(a) = req {
35            Ok(a)
36        } else {
37            log_debug!("INVALID {:?}", req);
38            Err(ProtocolError::InvalidValue)
39        }
40    }
41}
42
43impl From<BlocksPut> for ProtocolMessage {
44    fn from(msg: BlocksPut) -> ProtocolMessage {
45        let overlay = *msg.overlay();
46        ProtocolMessage::from_client_request_v0(ClientRequestContentV0::BlocksPut(msg), overlay)
47    }
48}
49
50impl Actor<'_, BlocksPut, ()> {}
51
52#[async_trait::async_trait]
53impl EActor for Actor<'_, BlocksPut, ()> {
54    async fn respond(
55        &mut self,
56        msg: ProtocolMessage,
57        fsm: Arc<Mutex<NoiseFSM>>,
58    ) -> Result<(), ProtocolError> {
59        let req = BlocksPut::try_from(msg)?;
60        let sb = { BROKER.read().await.get_server_broker()? };
61        let mut res: Result<(), ServerError> = Ok(());
62        let overlay = req.overlay().clone();
63        match req {
64            BlocksPut::V0(v0) => {
65                for block in v0.blocks {
66                    let r = sb.read().await.put_block(&overlay, block);
67                    if r.is_err() {
68                        res = r;
69                        break;
70                    }
71                }
72            }
73        }
74
75        fsm.lock()
76            .await
77            .send_in_reply_to(res.into(), self.id())
78            .await?;
79        Ok(())
80    }
81}