Skip to content
Open
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
19 changes: 19 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ bincode = "2"
tokio = { version = "1", default-features = false, features = ["net", "signal", "rt-multi-thread", "macros", "sync", "time"] }
futures = "0.3"
num_cpus = "^1"
async-trait = "0.1"
bytes = "1"

[lints.clippy]
pedantic = "warn"
2 changes: 1 addition & 1 deletion docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ after formatting. Line numbers below refer to that file.
`WireframeApp` instance from a factory closure. A Ctrl+C signal triggers
graceful shutdown, notifying all workers to stop accepting new
connections.
- [ ] Standardise supporting trait definitions.
- [x] Standardize supporting trait definitions.
Provide naming conventions and generic bounds for the
`FrameProcessor` trait, state extractors and middleware via
`async_trait` and associated types.
Expand Down
7 changes: 4 additions & 3 deletions docs/rust-binary-router-library-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -769,13 +769,14 @@ within handlers.

````rustrust
use wireframe::dev::{MessageRequest, Payload}; // Hypothetical types
use std::future::Future;

pub trait FromMessageRequest: Sized {
type Error: Into<wireframe::Error>; // Error type if extraction fails
type Future: Future<Output = Result<Self, Self::Error>>;

fn from_message_request(req: &MessageRequest, payload: &mut Payload) -> Self::Future;
fn from_message_request(
req: &MessageRequest,
payload: &mut Payload,
) -> Result<Self, Self::Error>;
}

```rust
Expand Down
167 changes: 167 additions & 0 deletions src/extractor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
use std::net::SocketAddr;
use std::sync::Arc;

/// Request context passed to extractors.
///
/// This type contains metadata about the current connection and provides
/// access to application state registered with [`WireframeApp`].
#[derive(Default)]
pub struct MessageRequest {
/// Address of the peer that sent the current message.
pub peer_addr: Option<SocketAddr>,
}

/// Raw payload buffer handed to extractors.
#[derive(Default)]
pub struct Payload<'a> {
/// Incoming bytes not yet processed.
pub data: &'a [u8],
}

impl Payload<'_> {
/// Advances the payload by `count` bytes.
///
/// Consumes up to `count` bytes from the front of the slice, ensuring we
/// Consumes up to `count` bytes from the front of the payload, never exceeding the available buffer.
///
/// Advances the internal byte slice by removing up to `count` bytes from the start. If `count` exceeds the remaining length, the payload is emptied.
///
/// # Examples
///
/// ```
/// let mut payload = Payload { data: b"hello world" };
/// payload.advance(6);
/// assert_eq!(payload.data, b"world");
/// payload.advance(10);
/// assert_eq!(payload.data, b"");
/// ```
pub fn advance(&mut self, count: usize) {
let n = count.min(self.data.len());
self.data = &self.data[n..];
}

/// Returns the number of bytes remaining.
#[must_use]
/// Returns the number of bytes remaining in the payload.
///
/// # Examples
///
/// ```
/// let data = [1, 2, 3, 4];
/// let payload = Payload { data: &data };
/// assert_eq!(payload.remaining(), 4);
/// ```
pub fn remaining(&self) -> usize {
self.data.len()
}
}

/// Trait for extracting data from a [`MessageRequest`].
pub trait FromMessageRequest: Sized {
/// Error type returned when extraction fails.
type Error: std::error::Error + Send + Sync + 'static;

/// Perform extraction from the request and payload.
///
/// # Errors
///
/// Returns an error if extraction fails.
fn from_message_request(
req: &MessageRequest,
payload: &mut Payload<'_>,
) -> Result<Self, Self::Error>;
}

/// Shared application state accessible to handlers.
#[derive(Clone)]
pub struct SharedState<T: Send + Sync>(Arc<T>);

impl<T: Send + Sync> SharedState<T> {
/// Construct a new [`SharedState`].
///
/// # Examples
///
/// ```ignore
/// use std::sync::Arc;
/// use wireframe::extractor::SharedState;
///
/// let data = Arc::new(5u32);
/// let state = SharedState::new(Arc::clone(&data));
/// assert_eq!(*state, 5);
/// ```
#[must_use]

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn advance_consumes_bytes() {
let mut payload = Payload { data: b"hello" };
payload.advance(2);
assert_eq!(payload.data, b"llo");
payload.advance(10);
assert!(payload.data.is_empty());
}

#[test]
fn remaining_reports_length() {
let mut payload = Payload { data: b"abc" };
assert_eq!(payload.remaining(), 3);
payload.advance(1);
assert_eq!(payload.remaining(), 2);
}
}
/// Creates a new `SharedState` instance wrapping the provided `Arc<T>`.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// let state = Arc::new(42);
/// let shared = SharedState::new(state.clone());
/// assert_eq!(*shared, 42);
/// Creates a new `SharedState` instance wrapping the provided `Arc`.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// let state = Arc::new(42);
/// let shared = SharedState::new(state.clone());
/// assert_eq!(*shared, 42);
/// ```
pub fn new(inner: Arc<T>) -> Self {
Self(inner)
}
}

impl<T: Send + Sync> std::ops::Deref for SharedState<T> {
type Target = T;

/// Returns a reference to the inner shared state value.
///
/// This allows transparent access to the underlying state managed by `SharedState`.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// let state = Arc::new(42);
/// let shared = SharedState::new(state.clone());
/// assert_eq!(*shared, 42);
/// Returns a reference to the inner state.
///
/// Allows transparent access to the wrapped value by dereferencing `SharedState`.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// let state = SharedState::new(Arc::new(42));
/// assert_eq!(*state, 42);
/// ```
fn deref(&self) -> &Self::Target {
&self.0
}
}
23 changes: 23 additions & 0 deletions src/frame.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use async_trait::async_trait;
use bytes::BytesMut;

/// Trait defining how raw bytes are decoded into frames and how frames are
/// encoded back into bytes for transmission.
///
/// The `Frame` associated type represents a logical unit extracted from or
/// written to the wire. Errors are represented by the `Error` associated type,
/// which must implement [`std::error::Error`].
#[async_trait]
pub trait FrameProcessor: Send + Sync {
/// Logical frame type extracted from the stream.
type Frame;

/// Error type returned by `decode` and `encode`.
type Error: std::error::Error + Send + Sync + 'static;

/// Attempt to decode the next frame from `src`.
async fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Frame>, Self::Error>;

/// Encode `frame` and append the bytes to `dst`.
async fn encode(&mut self, frame: &Self::Frame, dst: &mut BytesMut) -> Result<(), Self::Error>;
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
pub mod app;
pub mod extractor;
pub mod frame;
pub mod message;
pub mod middleware;
pub mod server;
113 changes: 113 additions & 0 deletions src/middleware.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use async_trait::async_trait;

/// Incoming request wrapper passed through middleware.
#[derive(Debug)]
pub struct ServiceRequest;

/// Response produced by a handler or middleware.
#[derive(Debug, Default)]
pub struct ServiceResponse;

/// Continuation used by middleware to call the next service in the chain.
pub struct Next<'a, S>
where
S: Service + ?Sized,
{
service: &'a S,
}

impl<'a, S> Next<'a, S>
where
S: Service + ?Sized,
{
/// Creates a new `Next` instance wrapping a reference to the given service.
///
///
/// ```ignore
/// use wireframe::middleware::{ServiceRequest, ServiceResponse, Next, Service};
/// ```
/// Service produced by the middleware.
type Wrapped: Service;
async fn transform(&self, service: S) -> Self::Wrapped;
/// let service = MyService::default();
/// let next = Next::new(&service);
/// Creates a new `Next` instance wrapping a reference to the given service.
///
/// # Examples
///
/// ```
/// let service = MyService::default();
/// let next = Next::new(&service);
/// ```
pub const fn new(service: &'a S) -> Self {
Self { service }
}

/// Call the next service with the given request.
///
/// # Errors
///
/// Asynchronously invokes the next service in the middleware chain with the given request.
///
/// Returns the response from the wrapped service, or propagates any error produced.
///
/// # Examples
///
/// ```
/// # use your_crate::{ServiceRequest, ServiceResponse, Next, Service};
/// # struct DummyService;
/// # #[async_trait::async_trait]
/// # impl Service for DummyService {
/// # type Error = std::convert::Infallible;
/// # async fn call(&self, _req: ServiceRequest) -> Result<ServiceResponse, Self::Error> {
/// # Ok(ServiceResponse::default())
/// # }
/// # }
/// # let service = DummyService;
/// let next = Next::new(&service);
/// let req = ServiceRequest {};
/// let res = tokio_test::block_on(next.call(req));
/// assert!(res.is_ok());
/// Asynchronously invokes the next service in the middleware chain with the given request.
///
/// Calls the wrapped service's `call` method, forwarding the provided `ServiceRequest` and returning its response or error.
///
/// # Examples
///
/// ```
/// # use your_crate::{Next, ServiceRequest, Service, ServiceResponse};
/// # async fn example<S: Service>(next: Next<'_, S>, req: ServiceRequest) {
/// let result = next.call(req).await;
/// match result {
/// Ok(response) => { /* handle response */ }
/// Err(e) => { /* handle error */ }
/// }
/// # }
/// ```
pub async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, S::Error> {
self.service.call(req).await
}
}

/// Trait representing an asynchronous service.
#[async_trait]
pub trait Service: Send + Sync {
/// Error type returned by the service.
type Error: std::error::Error + Send + Sync + 'static;

/// Handle the incoming request and produce a response.
async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Self::Error>;
}

/// Factory for wrapping services with middleware.
#[async_trait]
pub trait Transform<S>: Send + Sync
where
S: Service,
{
/// Wrapped service produced by the middleware.
type Output: Service;

/// Create a new middleware service wrapping `service`.
async fn transform(&self, service: S) -> Self::Output;
}
Loading