Skip to content

Commit

Permalink
docs: add lots of doc comments and enable deny(missing_docs)
Browse files Browse the repository at this point in the history
  • Loading branch information
rklaehn committed Feb 6, 2023
1 parent 5994474 commit 8255467
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/blobs.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! Types for blobs and collections of blobs
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::util::Hash;

/// A collection of blobs
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Collection {
///
Expand All @@ -15,20 +17,24 @@ pub struct Collection {
}

impl Collection {
/// Deserialize a collection from a byte slice
pub fn from_bytes(data: &[u8]) -> Result<Self> {
let c: Collection =
postcard::from_bytes(data).context("failed to serialize Collection data")?;
Ok(c)
}

/// Total size of the raw data referred to by all blobs in this collection
pub fn total_blobs_size(&self) -> u64 {
self.total_blobs_size
}

/// The name of this collection
pub fn name(&self) -> &str {
&self.name
}

/// The number of blobs in this collection
pub fn total_entries(&self) -> u64 {
self.blobs.len() as u64
}
Expand Down
8 changes: 8 additions & 0 deletions src/get.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! The client side api
use std::fmt::Debug;
use std::io;
use std::net::SocketAddr;
Expand All @@ -24,9 +25,12 @@ pub use crate::util::Hash;

const MAX_DATA_SIZE: u64 = 1024 * 1024 * 1024;

/// Options for the client
#[derive(Clone, Debug)]
pub struct Options {
/// The address to connect to
pub addr: SocketAddr,
/// The peer id to expect
pub peer_id: Option<PeerId>,
}

Expand Down Expand Up @@ -63,8 +67,11 @@ async fn setup(opts: Options) -> Result<(Client, Connection)> {
/// Stats about the transfer.
#[derive(Debug, Clone, PartialEq)]
pub struct Stats {
/// The number of bytes transferred
pub data_len: u64,
/// The time it took to transfer the data
pub elapsed: Duration,
/// Transfer rate in megabits per second
pub mbits: f64,
}

Expand Down Expand Up @@ -99,6 +106,7 @@ impl AsyncRead for DataStream {
}
}

/// Get a collection and all its blobs from a provider
pub async fn run<A, B, C, FutA, FutB, FutC>(
hash: Hash,
token: AuthToken,
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! Send data over the internet.
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
pub mod blobs;
pub mod get;
pub mod protocol;
Expand Down
4 changes: 4 additions & 0 deletions src/protocol.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Protocol for communication between provider and client.
use std::fmt::Display;
use std::str::FromStr;

Expand All @@ -16,6 +17,7 @@ use crate::{
/// Maximum message size is limited to 100MiB for now.
const MAX_MESSAGE_SIZE: usize = 1024 * 1024 * 100;

/// Protocol version
pub const VERSION: u64 = 1;

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone, MaxSize)]
Expand Down Expand Up @@ -184,8 +186,10 @@ impl Display for AuthToken {
/// Error for parsing [`AuthToken`] using [`FromStr`].
#[derive(thiserror::Error, Debug)]
pub enum AuthTokenParseError {
/// Invalid base64 encoding.
#[error("invalid encoding: {0}")]
Base64(#[from] base64::DecodeError),
/// Invalid length.
#[error("invalid length: {0}")]
Length(usize),
}
Expand Down
26 changes: 25 additions & 1 deletion src/provider.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Provider api
use std::fmt::{self, Display};
use std::io::{BufReader, Read};
use std::net::SocketAddr;
Expand Down Expand Up @@ -25,6 +26,7 @@ use crate::util::{self, Hash};
const MAX_CONNECTIONS: u64 = 1024;
const MAX_STREAMS: u64 = 10;

/// Database containing content-addressed data (blobs or collections).
#[derive(Debug, Clone)]
pub struct Database(Arc<HashMap<Hash, BlobOrCollection>>);

Expand Down Expand Up @@ -175,20 +177,32 @@ pub struct Provider {
/// Events emitted by the [`Provider`] informing about the current status.
#[derive(Debug, Clone)]
pub enum Event {
/// A new client connected to the provider.
ClientConnected {
/// The quic connection id.
connection_id: u64,
},
/// A request was received from a client.
RequestReceived {
/// The quic connection id.
connection_id: u64,
/// The request id.
request_id: u64,
/// The hash for which the client wants to receive data.
hash: Hash,
},
/// A request was completed and the data was sent to the client.
TransferCompleted {
/// The quic connection id.
connection_id: u64,
/// The request id.
request_id: u64,
},
/// A request was aborted because the client disconnected.
TransferAborted {
/// The quic connection id.
connection_id: u64,
/// The request id.
request_id: u64,
},
}
Expand Down Expand Up @@ -424,20 +438,28 @@ pub(crate) struct Data {
size: u64,
}

/// A data source
#[derive(Debug)]
pub enum DataSource {
/// A blob of data originating from the filesystem. The name of the blob is derived from
/// the filename.
File(PathBuf),
/// NamedFile is treated the same as [`DataSource::File`], except you can pass in a custom
/// name. Passing in the empty string will explicitly _not_ persist the filename.
NamedFile { path: PathBuf, name: String },
NamedFile {
/// Path to the file
path: PathBuf,
/// Custom name
name: String,
},
}

impl DataSource {
/// Create a new [`DataSource`] from a [`PathBuf`].
pub fn new(path: PathBuf) -> Self {
DataSource::File(path)
}
/// Create a new [`DataSource`] from a [`PathBuf`] and a custom name.
pub fn with_name(path: PathBuf, name: String) -> Self {
DataSource::NamedFile { path, name }
}
Expand Down Expand Up @@ -607,11 +629,13 @@ pub struct Ticket {
}

impl Ticket {
/// Deserializes from bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let slf = postcard::from_bytes(bytes)?;
Ok(slf)
}

/// Serializes to bytes.
pub fn to_bytes(&self) -> Vec<u8> {
postcard::to_stdvec(self).expect("postcard::to_stdvec is infallible")
}
Expand Down
9 changes: 9 additions & 0 deletions src/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::util;
// TODO: change?
const P2P_ALPN: [u8; 6] = *b"libp2p";

/// A keypair.
#[derive(Debug)]
pub struct Keypair(ed25519_dalek::Keypair);

Expand All @@ -34,25 +35,30 @@ impl Deref for Keypair {
}

impl Keypair {
/// The public key of this keypair.
pub fn public(&self) -> PublicKey {
self.0.public
}

/// The secret key of this keypair.
pub fn secret(&self) -> &SecretKey {
&self.0.secret
}

/// Generate a new keypair.
pub fn generate() -> Self {
let mut rng = rand::rngs::OsRng;
let key = ed25519_dalek::Keypair::generate(&mut rng);
Self(key)
}

/// Serialise the keypair to OpenSSH format.
pub fn to_openssh(&self) -> ssh_key::Result<zeroize::Zeroizing<String>> {
let ckey = ssh_key::private::Ed25519Keypair::from(&self.0);
ssh_key::private::PrivateKey::from(ckey).to_openssh(LineEnding::default())
}

/// Deserialise the keypair from OpenSSH format.
pub fn try_from_openssh<T: AsRef<[u8]>>(data: T) -> anyhow::Result<Self> {
let ser_key = ssh_key::private::PrivateKey::from_openssh(data)?;
match ser_key.key_data() {
Expand Down Expand Up @@ -111,10 +117,13 @@ impl Display for PeerId {
}
}

/// Error when deserialising a [`PeerId`].
#[derive(thiserror::Error, Debug)]
pub enum PeerIdError {
/// Error when decoding the base64.
#[error("encoding: {0}")]
Base64(#[from] base64::DecodeError),
/// Error when decoding the public key.
#[error("key: {0}")]
Key(#[from] ed25519_dalek::SignatureError),
}
Expand Down

0 comments on commit 8255467

Please sign in to comment.