zlink_core/server/service.rs
1//! Service-related API.
2
3use core::{fmt::Debug, future::Future};
4
5use futures_util::Stream;
6use serde::{Deserialize, Serialize};
7
8use crate::{connection::Socket, Call, Connection, 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, Sock: Socket>(
45 &'ser mut self,
46 method: &'ser Call<Self::MethodCall<'_>>,
47 conn: &mut Connection<Sock>,
48 ) -> impl Future<
49 Output = MethodReply<Self::ReplyParams<'ser>, Self::ReplyStream, Self::ReplyError<'ser>>,
50 >;
51}
52
53/// A service method call reply.
54#[derive(Debug)]
55pub enum MethodReply<Params, ReplyStream, ReplyError> {
56 /// A single reply.
57 Single(Option<Params>),
58 /// An error reply.
59 Error(ReplyError),
60 /// A multi-reply stream.
61 Multi(ReplyStream),
62}