Expand description
Service Router Abstractions
This module provides the core abstractions for routing incoming connections to different services based on a service identifier sent by the client.
§Core Traits
ServiceRouter: Routes connections to services based on service IDsService: Handles individual service connections
§Service Routing Flow
- Client connects and sends a
u8service identifier ServiceRouter::parse_service_idconverts theu8to a typed service IDServiceRouter::create_servicecreates the appropriate service instance- The service’s
Service::runmethod handles the connection
§Example
use zoe_relay::{ServiceRouter, Service, ConnectionInfo};
use zoe_wire_protocol::StreamPair;
use async_trait::async_trait;
#[derive(Debug, Clone, PartialEq)]
enum ServiceType {
MessageService,
BlobService,
}
impl TryFrom<u8> for ServiceType {
type Error = MyError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(ServiceType::MessageService),
2 => Ok(ServiceType::BlobService),
_ => Err(MyError::UnknownService(value)),
}
}
}
impl std::fmt::Display for ServiceType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ServiceType::MessageService => write!(f, "MessageService"),
ServiceType::BlobService => write!(f, "BlobService"),
}
}
}
#[derive(Debug, thiserror::Error)]
enum MyError {
#[error("Unknown service ID: {0}")]
UnknownService(u8),
}
struct MyRouter;
struct MyService { /* service fields */ }
#[async_trait]
impl Service for MyService {
type Error = MyError;
async fn run(self) -> Result<(), Self::Error> {
// Service implementation
Ok(())
}
}
#[async_trait]
impl ServiceRouter for MyRouter {
type Error = MyError;
type ServiceId = ServiceType;
type Service = MyService;
async fn parse_service_id(&self, service_id: u8) -> Result<Self::ServiceId, Self::Error> {
ServiceType::try_from(service_id)
}
async fn create_service(
&self,
service_id: &Self::ServiceId,
connection_info: &ConnectionInfo,
streams: StreamPair,
) -> Result<Self::Service, Self::Error> {
Ok(MyService { /* initialize service */ })
}
}Traits§
- Service
- A service that handles a specific type of connection
- Service
Router - Routes incoming connections to appropriate services