zlink_core/server/service.rs
1//! Serice-related API.
2
3use core::{fmt::Debug, future::Future};
4
5use futures_util::Stream;
6use serde::{Deserialize, Serialize};
7
8use crate::{Call, Reply};
9
10/// Service trait for handling method calls.
11pub trait Service {
12 /// The type of method call that this service handles.
13 ///
14 /// This should be a type that can deserialize itself from a complete method call message: i-e
15 /// an object containing `method` and `parameter` fields. This can be easily achieved using the
16 /// `serde::Deserialize` derive (See the code snippet in
17 /// [`crate::connection::WriteConnection::send_call`] documentation for an example).
18 type MethodCall<'de>: Deserialize<'de> + Debug;
19 /// The type of the successful reply.
20 ///
21 /// This should be a type that can serialize itself as the `parameters` field of the reply.
22 type ReplyParams<'ser>: Serialize + Debug
23 where
24 Self: 'ser;
25 /// The type of the item that [`Service::ReplyStream`] will be expected to yield.
26 ///
27 /// This should be a type that can serialize itself as the `parameters` field of the reply.
28 type ReplyStreamParams: Serialize + Debug;
29 /// The type of the multi-reply stream.
30 ///
31 /// If the client asks for multiple replies, this stream will be used to send them.
32 type ReplyStream: Stream<Item = Reply<Self::ReplyStreamParams>> + Unpin;
33 /// The type of the error reply.
34 ///
35 /// This should be a type that can serialize itself to the whole reply object, containing
36 /// `error` and `parameter` fields. This can be easily achieved using the `serde::Serialize`
37 /// derive (See the code snippet in [`crate::connection::ReadConnection::receive_reply`]
38 /// documentation for an example).
39 type ReplyError<'ser>: Serialize + Debug
40 where
41 Self: 'ser;
42
43 /// Handle a method call.
44 fn handle<'ser>(
45 &'ser mut self,
46 method: Call<Self::MethodCall<'_>>,
47 ) -> impl Future<
48 Output = MethodReply<Self::ReplyParams<'ser>, Self::ReplyStream, Self::ReplyError<'ser>>,
49 >;
50}
51
52/// A service method call reply.
53#[derive(Debug)]
54pub enum MethodReply<Params, ReplyStream, ReplyError> {
55 /// A single reply.
56 Single(Option<Params>),
57 /// An error reply.
58 Error(ReplyError),
59 /// A multi-reply stream.
60 Multi(ReplyStream),
61}