Improve Tunnel error handling (#2479)

p2p: create and use TunnelError enum
This commit is contained in:
Julian Braha 2024-05-13 03:35:54 +01:00 committed by GitHub
parent dcbe888d03
commit ed193a3ba5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 19 additions and 7 deletions

1
Cargo.lock generated
View file

@ -9455,6 +9455,7 @@ name = "sd-p2p-tunnel"
version = "0.1.0"
dependencies = [
"sd-p2p",
"thiserror",
"tokio",
]

View file

@ -11,3 +11,4 @@ repository.workspace = true
sd-p2p = { path = "../p2p" }
tokio = { workspace = true, features = ["io-util"] }
thiserror = { workspace = true }

View file

@ -6,34 +6,44 @@ use std::{
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf};
use thiserror::Error;
use sd_p2p::UnicastStream;
#[derive(Debug, Error)]
pub enum TunnelError {
#[error("Error writing discriminator.")]
DiscriminatorWriteError,
#[error("Error reading discriminator. Is this stream actually a tunnel?")]
DiscriminatorReadError,
#[error("Invalid discriminator. Is this stream actually a tunnel?")]
InvalidDiscriminator,
}
#[derive(Debug)]
pub struct Tunnel {
stream: UnicastStream,
}
impl Tunnel {
// TODO: Proper errors
pub async fn initiator(mut stream: UnicastStream) -> Result<Self, &'static str> {
pub async fn initiator(mut stream: UnicastStream) -> Result<Self, TunnelError> {
stream
.write_all(&[b'T'])
.await
.map_err(|_| "Error writing discriminator")?;
.map_err(|_| TunnelError::DiscriminatorWriteError)?;
// TODO: Do pairing + authentication
Ok(Self { stream })
}
// TODO: Proper errors
pub async fn responder(mut stream: UnicastStream) -> Result<Self, &'static str> {
pub async fn responder(mut stream: UnicastStream) -> Result<Self, TunnelError> {
let discriminator = stream
.read_u8()
.await
.map_err(|_| "Error reading discriminator. Is this stream actually a tunnel?")?;
.map_err(|_| TunnelError::DiscriminatorReadError)?;
if discriminator != b'T' {
return Err("Invalid discriminator. Is this stream actually a tunnel?");
return Err(TunnelError::InvalidDiscriminator);
}
// TODO: Do pairing + authentication