Module router

Module router 

Source
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 IDs
  • Service: Handles individual service connections

§Service Routing Flow

  1. Client connects and sends a u8 service identifier
  2. ServiceRouter::parse_service_id converts the u8 to a typed service ID
  3. ServiceRouter::create_service creates the appropriate service instance
  4. The service’s Service::run method 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
ServiceRouter
Routes incoming connections to appropriate services