relay_system

Trait Interface

source
pub trait Interface: Send + 'static { }
Expand description

A message interface for services.

Most commonly, this interface is an enumeration of messages, but it can also be implemented on a single message. For each individual message, this type needs to implement the FromMessage trait.

§Implementating Interfaces

There are three main ways to implement interfaces, which depends on the number of messages and their return values. The simplest way is an interface consisting of a single message with no return value. For this case, use the message directly as interface and choose NoResponse as response:

use relay_system::{FromMessage, Interface, NoResponse};

#[derive(Debug)]
pub struct MyMessage;

impl Interface for MyMessage {}

impl FromMessage<Self> for MyMessage {
    type Response = NoResponse;

    fn from_message(message: Self, _: ()) -> Self {
        message
    }
}

If there is a single message with a return value, implement the interface as a wrapper for the message and the return Sender:

use relay_system::{AsyncResponse, FromMessage, Interface, Sender};

#[derive(Debug)]
pub struct MyMessage;

#[derive(Debug)]
pub struct MyInterface(MyMessage, Sender<bool>);

impl Interface for MyInterface {}

impl FromMessage<MyMessage> for MyInterface {
    type Response = AsyncResponse<bool>;

    fn from_message(message: MyMessage, sender: Sender<bool>) -> Self {
        Self(message, sender)
    }
}

Finally, interfaces with multiple messages of any kind can most commonly be implemented through an enumeration for every message. The variants of messages with return values need a Sender again:

use relay_system::{AsyncResponse, FromMessage, Interface, NoResponse, Sender};

#[derive(Debug)]
pub struct GetFlag;

#[derive(Debug)]
pub struct SetFlag(pub bool);

#[derive(Debug)]
pub enum MyInterface {
    Get(GetFlag, Sender<bool>),
    Set(SetFlag),
}

impl Interface for MyInterface {}

impl FromMessage<GetFlag> for MyInterface {
    type Response = AsyncResponse<bool>;

    fn from_message(message: GetFlag, sender: Sender<bool>) -> Self {
        Self::Get(message, sender)
    }
}

impl FromMessage<SetFlag> for MyInterface {
    type Response = NoResponse;

    fn from_message(message: SetFlag, _: ()) -> Self {
        Self::Set(message)
    }
}

§Requirements

Interfaces are meant to be sent to services via channels. As such, they need to be both Send and 'static. It is highly encouraged to implement Debug on all interfaces and their messages.

Implementations on Foreign Types§

source§

impl Interface for ()

Services without messages can use () as their interface.

Implementors§