Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: document missing items #3

Merged
merged 2 commits into from
Dec 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed
- Automatically assigned group IDs start now at 0 ([#2](https://github.com/soehrl/camure/pull/2))
- Document missing items ([#3](https://github.com/soehrl/camure/pull/3))
21 changes: 21 additions & 0 deletions src/barrier.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//! Barrier groups a used to synchronize all members of a group.
//!
//! The coordinator will create a barrier group using
//! [`Coordinator::create_barrier_group`](crate::session::Coordinator::create_barrier_group) and
//! members are able to join the group using
//! [`Member::join_barrier_group`](crate::session::Member::join_barrier_group).

use std::net::SocketAddr;

use ahash::HashSet;
Expand Down Expand Up @@ -132,6 +139,7 @@ impl GroupCoordinatorTypeImpl for BarrierGroupCoordinatorState {
fn process_join_request(&mut self, _addr: &SockAddr, _group: &GroupCoordinatorState) {}
}

/// Manages a barrier group.
pub struct BarrierGroupCoordinator {
pub(crate) group: GroupCoordinator<BarrierGroupCoordinatorState>,
// pub(crate) state: BarrierGroupCoordinatorState,
Expand All @@ -154,15 +162,23 @@ impl BarrierGroupCoordinator {
self.group.state.members.len() == self.group.inner.arrived.len()
}

/// Returns true if the group has members and false otherwise.
pub fn has_members(&self) -> bool {
!self.group.state.members.is_empty()
}

/// Accepts a new member into the group.
///
/// This function will block until a new member has joined the group.
#[tracing::instrument(skip(self))]
pub fn accept(&mut self) -> std::io::Result<SocketAddr> {
self.group.accept().and_then(sock_addr_to_socket_addr)
}

/// Tries to accept a new member into the group.
///
/// This function will return `Ok(None)` if no new member has joined the
/// group. This function does not block.
#[tracing::instrument(skip(self))]
pub fn try_accept(&mut self) -> std::io::Result<Option<SocketAddr>> {
let addr = self.group.try_accept()?;
Expand Down Expand Up @@ -223,6 +239,7 @@ impl BarrierGroupCoordinator {
unreachable!();
}

/// Waits until all members have arrived at the barrier.
#[tracing::instrument(skip(self))]
pub fn wait(&mut self) -> std::io::Result<()> {
if self.group.state.members.is_empty() {
Expand Down Expand Up @@ -367,6 +384,9 @@ impl GroupMemberTypeImpl for BarrierGroupMemberState {
}
}

/// Represents a member of a barrier group.
///
/// Dropping this object will leave the barrier group.
pub struct BarrierGroupMember {
pub(crate) group: GroupMember<BarrierGroupMemberState>,
}
Expand Down Expand Up @@ -398,6 +418,7 @@ impl BarrierGroupMember {
unreachable!();
}

/// Waits until all members have arrived at the barrier.
#[tracing::instrument(skip(self))]
pub fn wait(&mut self) -> std::io::Result<()> {
let reached = self.send_reached()?;
Expand Down
42 changes: 42 additions & 0 deletions src/broadcast.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//! Broadcast groups allow reliable 1-to-many communication.
//!
//! Broadcast groups allow the coordinator to reliably send messages to all
//! members. The coordinator can create broadcast groups using
//! [`Coordinator::create_broadcast_group`](crate::session::Coordinator::create_broadcast_group) and members can join broadcast groups using
//! [`Member::join_broadcast_group`](crate::session::Member::join_broadcast_group).

use std::{
collections::VecDeque,
io::{Read, Write},
Expand Down Expand Up @@ -142,6 +149,7 @@ impl GroupCoordinatorTypeImpl for BroadcastGroupSenderState {
}
}

/// A sender for broadcast messages.
pub struct BroadcastGroupSender {
pub(crate) group: GroupCoordinator<BroadcastGroupSenderState>,
pub(crate) initial_retransmit_delay: std::time::Duration,
Expand Down Expand Up @@ -225,10 +233,12 @@ impl BroadcastGroupSender {
Ok(())
}

/// Returns the group id.
pub fn id(&self) -> GroupId {
self.group.id().into()
}

/// Returns true if the group has members.
pub fn has_members(&self) -> bool {
!self.group.state.members.is_empty()
}
Expand All @@ -255,12 +265,20 @@ impl BroadcastGroupSender {
self.process_unacknlowedged_chunks()
}

/// Accepts a new connection.
///
/// This method blocks until a new connection is established or an error
/// occurs.
#[tracing::instrument(skip(self))]
pub fn accept(&mut self) -> std::io::Result<SocketAddr> {
self.process()?;
self.group.accept().and_then(sock_addr_to_socket_addr)
}

/// Tries to accept a new connection.
///
/// This method does not block and returns `Ok(None)` if no new connection
/// is available.
#[tracing::instrument(skip(self))]
pub fn try_accept(&mut self) -> std::io::Result<Option<SocketAddr>> {
self.process_unacknlowedged_chunks()?;
Expand Down Expand Up @@ -337,6 +355,7 @@ impl BroadcastGroupSender {
Ok(())
}

/// Start writing a new message to be broadcasted.
pub fn write_message(&mut self) -> MessageWriter {
MessageWriter {
buffer: ManuallyDrop::new(self.group.buffer_allocator().allocate()),
Expand All @@ -346,6 +365,7 @@ impl BroadcastGroupSender {
}
}

/// Waits until all messages have been received by all members.
pub fn wait(&mut self) -> Result<(), std::io::Error> {
while self.group.inner.packets_in_flight > 0 {
self.process()?;
Expand All @@ -354,6 +374,12 @@ impl BroadcastGroupSender {
}
}

/// A writer for a broadcast message.
///
/// This struct implements the [`Write`](std::io::Write) trait and can be used
/// to write a message. The final chunk of the message is sent when the writer
/// is dropped. If the message is split across multiple chunks, intermediate
/// chunks are sent as soon as they are complete.
pub struct MessageWriter<'a> {
sender: &'a mut BroadcastGroupSender,
buffer: ManuallyDrop<ChunkBuffer>,
Expand Down Expand Up @@ -405,11 +431,19 @@ impl Write for MessageWriter<'_> {
}
}

/// Represents a received message.
///
/// Use the [`read`](Message::read) method to read the message.
pub struct Message {
chunks: Vec<ReceivedChunk>,
}

impl Message {
/// Reads the message.
///
/// This method returns a [`MessageReader`](MessageReader) that implements
/// the [`Read`](std::io::Read) trait and can be used to read the
/// message.
pub fn read(&self) -> MessageReader {
MessageReader {
chunks: &self.chunks,
Expand All @@ -418,6 +452,10 @@ impl Message {
}
}

/// A reader for a received message.
///
/// This struct implements the [`Read`](std::io::Read) trait and can be used to
/// read the message.
pub struct MessageReader<'a> {
chunks: &'a [ReceivedChunk],
cursor: usize,
Expand Down Expand Up @@ -548,11 +586,15 @@ impl GroupMemberTypeImpl for BroadcastGroupReceiverState {
}
}

/// A receiver for broadcast messages.
pub struct BroadcastGroupReceiver {
pub(crate) group: GroupMember<BroadcastGroupReceiverState>,
}

impl BroadcastGroupReceiver {
/// Receives a message from the sender.
///
/// This method blocks until a message is received.
pub fn recv(&mut self) -> std::io::Result<Message> {
loop {
let chunks = &mut self.group.inner_mut()?.chunks;
Expand Down
25 changes: 7 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,14 @@
//! each other. Groups are always created by the coordinator and must be
//! explicitly joined by members. There are currently two different types of
//! groups.
//! - [Barrier](barrier): Synchronizes all members of a group.
//! - [Broadcast](broadcast): Broadcasts a message to all members of a group.
//!
//! ## Barrier
//!
//! ## Broadcast
//!
//! # Debugging
//! If you encounter a lot of timeouts, hangs, or other issues, you can enable
//! logging to get more information about what is happening. This crate uses the
//! [log](https://crates.io/crates/log) crate for logging. So, choose a
//! logging implementation according to their
//! [documentation](https://docs.rs/log/latest/log/) and make sure to set the
//! log level to `trace` for this crate. In order to avoid any overhead caused
//! by logging ensure that the compile time filter is set to debug or higher
//! (see [Compile Time Filters](https://docs.rs/log/latest/log/#compile-time-filters) for more
//! information).
//!
//! # Future Work
//! - **Improve Member Management**: Currrently, the chunk allocation strategy
//! is suboptimal and can be improved to increase performance.
//! # Important Notes
//! <div class="warning">
//! This library currently does not support <a href="https://en.wikipedia.org/wiki/Loopback_address">loopback interfaces</a> such as 127.0.0.1, please use the
//! actual network interface instead.
//! </div>

pub(crate) mod chunk;
pub(crate) mod chunk_socket;
Expand Down
51 changes: 46 additions & 5 deletions src/session.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Session management

use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
num::NonZeroUsize,
Expand Down Expand Up @@ -197,6 +199,11 @@ impl Coordinator {
///
/// See [`Self::start_session_with_config`] for additional configuration
/// options.
///
/// <div class="warning">
/// This library currently does not support <a href="https://en.wikipedia.org/wiki/Loopback_address">loopback interfaces</a> such as 127.0.0.1, please use the
/// actual network interface instead.
/// </div>
pub fn start_session(
bind_address: SocketAddr,
multicast_address: SocketAddr,
Expand All @@ -214,6 +221,11 @@ impl Coordinator {
/// See [`MulticastServerConfig`] for the available configuration options
/// and [`Self::start_session`] for more information regarding the address
/// parameters.
///
/// <div class="warning">
/// This library currently does not support <a href="https://en.wikipedia.org/wiki/Loopback_address">loopback interfaces</a> such as 127.0.0.1, please use the
/// actual network interface instead.
/// </div>
pub fn start_session_with_config(
bind_address: SocketAddr,
multicast_address: SocketAddr,
Expand Down Expand Up @@ -332,24 +344,38 @@ impl Coordinator {
})
}

/// Creates a new barrier group.
///
/// The `desired_group_id` parameter can be used to request a specific group
/// ID. If the ID is already in use, an error is returned. If `None` is
/// passed, the coordinator will assign an ID.
///
/// See [barrier](crate::barrier) for more information.
pub fn create_barrier_group(
&self,
desired_channel_id: Option<GroupId>,
desired_group_id: Option<GroupId>,
) -> Result<BarrierGroupCoordinator, GroupCreateError> {
let group = self.create_group(
desired_channel_id,
desired_group_id,
Some(1024.try_into().unwrap()),
BarrierGroupCoordinatorState::default(),
)?;
Ok(BarrierGroupCoordinator { group })
}

/// Creates a new broadcast group.
///
/// The `desired_group_id` parameter can be used to request a specific group
/// ID. If the ID is already in use, an error is returned. If `None` is
/// passed, the coordinator will assign an ID.
///
/// See [broadcast](crate::broadcast) for more information.
pub fn create_broadcast_group(
&self,
desired_channel_id: Option<GroupId>,
desired_group_id: Option<GroupId>,
) -> Result<BroadcastGroupSender, GroupCreateError> {
let group = self.create_group(
desired_channel_id,
desired_group_id,
Some(1024.try_into().unwrap()),
BroadcastGroupSenderState::default(),
)?;
Expand Down Expand Up @@ -447,6 +473,11 @@ impl Member {
///
/// The `addr` parameter corresponds to the `bind_addr` parameter of
/// [`Coordinator::start_session`].
///
/// <div class="warning">
/// This library currently does not support <a href="https://en.wikipedia.org/wiki/Loopback_address">loopback interfaces</a> such as 127.0.0.1, please use the
/// actual network interface instead.
/// </div>
pub fn join_session(addr: SocketAddr) -> Result<Self, JoinSessionError> {
let join_session_span = tracing::trace_span!("join_session", addr = %addr);
let _join_session_span_guard = join_session_span.enter();
Expand Down Expand Up @@ -516,7 +547,9 @@ impl Member {
move |socket, reason| match reason {
CallbackReason::Timeout => {
// We ran into a timeout, which is set to the heartbeat interval
if let Err(err) = socket.send_chunk_to(&SessionHeartbeat, &coordinator_address_copy) {
if let Err(err) =
socket.send_chunk_to(&SessionHeartbeat, &coordinator_address_copy)
{
tracing::error!(%err, "failed to send heartbeat");
todo!("handle error");
} else {
Expand Down Expand Up @@ -560,6 +593,10 @@ impl Member {
.map_err(JoinGroupError::IoError)
}

/// Joins a barrier group.
///
/// The barrier group with the specified if must have been previously
/// created by the coordinator.
pub fn join_barrier_group(
&self,
channel_id: GroupId,
Expand All @@ -568,6 +605,10 @@ impl Member {
Ok(BarrierGroupMember { group })
}

/// Joins a broadcast group.
///
/// The broadcast group with the specified if must have been previously
/// created by the coordinator.
pub fn join_broadcast_group(
&self,
channel_id: GroupId,
Expand Down