scatter_net/legacy/packet/methods/
process.rs

1use std::sync::Arc;
2
3use bytes::Bytes;
4use ps_hash::Hash;
5
6use crate::{Packet, Peer};
7
8impl Packet {
9    pub async fn process(self, peer: Peer) -> Result<Option<Self>, PacketProcessError> {
10        use PacketProcessError::ReceivedErrorPacket;
11
12        match self {
13            Self::Empty | Self::Pong => Ok(None),
14            Self::Error(str) => Err(ReceivedErrorPacket(str)),
15            Self::Ping => Ok(Some(Self::Pong)),
16            Self::FetchRequest(request) => Ok(Some(
17                match peer
18                    .net()
19                    .fetch_encrypted_chunk(Arc::new(Hash::try_from(request.hash.as_bytes())?))
20                    .await
21                {
22                    Ok(chunk) => {
23                        Self::FetchResponse(crate::FetchResponse::Success(Bytes::from_owner(chunk)))
24                    }
25                    Err(crate::ScatterNetFetchEncryptedChunkError::NotFound) => {
26                        Self::FetchResponse(crate::FetchResponse::NotFound)
27                    }
28                    Err(err) => Self::FetchResponse(crate::FetchResponse::Error(err.to_string())),
29                },
30            )),
31            Self::FetchResponse(response) => response.process(peer).await,
32            Self::PutRequest(request) => {
33                Ok(Some((peer.net().put_blob(request.data).await).map_or_else(
34                    |_| Self::PutResponse(crate::PutResponse::Failure),
35                    |hkey| Self::PutResponse(crate::PutResponse::Success(hkey.to_string())),
36                )))
37            }
38            Self::PutResponse(response) => {
39                eprintln!("Received unsolicited PutResponse({response:?}) from {peer}");
40                Ok(Some(Self::Error("Unsolicited PutResponse.".to_string())))
41            }
42        }
43    }
44}
45
46#[derive(thiserror::Error, Debug)]
47pub enum PacketProcessError {
48    #[error(transparent)]
49    HashValidation(#[from] ps_hash::HashValidationError),
50    #[error(transparent)]
51    Put(#[from] crate::ScatterNetAsyncStoreError),
52    #[error("The Peer sent an Error packet.")]
53    ReceivedErrorPacket(String),
54    #[error(transparent)]
55    Unknown(#[from] anyhow::Error),
56}