Skip to content
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
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
127 changes: 127 additions & 0 deletions src/extractor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
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
/// never slice beyond the available buffer.
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]
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);
/// ```
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);
/// ```
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;
91 changes: 91 additions & 0 deletions src/middleware.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
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;
Comment on lines +30 to +31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Invalid associated items inside impl Next

Move type Wrapped and async fn transform to a trait, such as Transform, or remove them from the impl Next block. Only new and call should be defined in Next.

/// let service = MyService::default();
/// let next = Next::new(&service);
type Wrapped: Service;
async fn transform(&self, service: S) -> Self::Wrapped;
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());
/// ```
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
Loading