Skip to main content

p2panda_sync/
traits.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Interfaces for implementing sync protocols and managers.
4use std::error::Error as StdError;
5use std::fmt::Debug;
6use std::pin::Pin;
7
8use futures_util::Sink;
9use futures_util::Stream;
10use serde::{Deserialize, Serialize};
11
12use crate::{FromSync, SessionConfig, ToSync};
13
14/// Generic protocol interface which runs over a sink and stream pair.
15pub trait Protocol {
16    type Output;
17    type Error: StdError + Send + Sync + 'static;
18    type Message: Serialize + for<'a> Deserialize<'a>;
19
20    fn run(
21        self,
22        sink: &mut (impl Sink<Self::Message, Error = impl Debug> + Unpin),
23        stream: &mut (impl Stream<Item = Result<Self::Message, impl Debug>> + Unpin),
24    ) -> impl Future<Output = Result<Self::Output, Self::Error>>;
25}
26
27/// Interface for managing sync sessions and consuming events they emit.
28#[allow(clippy::type_complexity)]
29pub trait Manager<T> {
30    type Protocol: Protocol + Send + 'static;
31    type Args: Clone + Send + 'static;
32    type Message: Clone + Send + 'static;
33    type Event: Clone + Debug + Send + 'static;
34    type Error: StdError + Send + Sync + 'static;
35
36    fn from_args(args: Self::Args) -> Self;
37
38    /// Instantiate a new sync session.
39    fn session(
40        &mut self,
41        session_id: u64,
42        config: &SessionConfig<T>,
43    ) -> impl Future<Output = Self::Protocol>;
44
45    /// Retrieve a send handle to an already existing sync session.
46    fn session_handle(
47        &self,
48        session_id: u64,
49    ) -> impl Future<Output = Option<Pin<Box<dyn Sink<ToSync<Self::Message>, Error = Self::Error>>>>>;
50
51    /// Subscribe to the manager event stream.
52    fn subscribe(&mut self) -> impl Stream<Item = FromSync<Self::Event>> + Send + Unpin + 'static;
53}