perspective_server/
server.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::collections::HashMap;
14use std::error::Error;
15use std::sync::Arc;
16
17use async_lock::RwLock;
18use futures::Future;
19use futures::future::BoxFuture;
20
21use crate::ffi;
22use crate::local_client::LocalClient;
23use crate::local_session::LocalSession;
24
25pub type ServerError = Box<dyn Error + Send + Sync>;
26
27pub type ServerResult<T> = Result<T, ServerError>;
28
29type SessionCallback =
30    Arc<dyn for<'a> Fn(&'a [u8]) -> BoxFuture<'a, Result<(), ServerError>> + Send + Sync>;
31
32type OnPollRequestCallback =
33    Arc<dyn Fn(&Server) -> BoxFuture<'static, Result<(), ServerError>> + Send + Sync>;
34
35/// Use [`SessionHandler`] to implement a callback for messages emitted from
36/// a [`Session`], to be passed to the [`Server::new_session`] constructor.
37///
38/// Alternatively, a [`Session`] can be created from a closure instead via
39/// [`Server::new_session_with_callback`].
40pub trait SessionHandler: Send + Sync {
41    /// Dispatch a message from a [`Server`] for a the [`Session`] that took
42    /// this `SessionHandler` instance as a constructor argument.
43    fn send_response<'a>(
44        &'a mut self,
45        msg: &'a [u8],
46    ) -> impl Future<Output = Result<(), ServerError>> + Send + 'a;
47}
48
49/// An instance of a Perspective server. Each [`Server`] instance is separate,
50/// and does not share [`perspective_client::Table`] (or other) data with other
51/// [`Server`]s.
52#[derive(Clone)]
53pub struct Server {
54    pub(crate) server: Arc<ffi::Server>,
55    pub(crate) callbacks: Arc<RwLock<HashMap<u32, SessionCallback>>>,
56
57    pub(crate) on_poll_request: Option<OnPollRequestCallback>,
58}
59
60impl std::fmt::Debug for Server {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        let addr = std::ptr::addr_of!(self);
63        write!(f, "Server {addr:?}")?;
64        Ok(())
65    }
66}
67
68impl Server {
69    pub fn new(on_poll_request: Option<OnPollRequestCallback>) -> Self {
70        let server = Arc::new(ffi::Server::new(on_poll_request.is_some()));
71        let callbacks = Arc::default();
72        Self {
73            server,
74            callbacks,
75            on_poll_request,
76        }
77    }
78
79    /// An alternative method for creating a new [`Session`] for this
80    /// [`Server`], from a callback closure instead of a via a trait.
81    /// See [`Server::new_session`] for details.
82    ///
83    /// # Arguments
84    ///
85    /// - `send_response` -  A function invoked by the [`Server`] when a
86    ///   response message needs to be sent to the
87    ///   [`perspective_client::Client`].
88    pub async fn new_session_with_callback<F>(&self, send_response: F) -> LocalSession
89    where
90        F: for<'a> Fn(&'a [u8]) -> BoxFuture<'a, Result<(), ServerError>> + 'static + Sync + Send,
91    {
92        let id = self.server.new_session();
93        let server = self.clone();
94        self.callbacks
95            .write()
96            .await
97            .insert(id, Arc::new(send_response));
98
99        LocalSession {
100            id,
101            server,
102            closed: false,
103        }
104    }
105
106    /// Create a [`Session`] for this [`Server`], suitable for exactly one
107    /// [`perspective_client::Client`] (not necessarily in this process). A
108    /// [`Session`] represents the server-side state of a single
109    /// client-to-server connection.
110    ///
111    /// # Arguments
112    ///
113    /// - `session_handler` - An implementor of [`SessionHandler`] which will be
114    ///   invoked by the [`Server`] when a response message needs to be sent to
115    ///   the [`Client`]. The response itself should be passed to
116    ///   [`Client::handle_response`] eventually, though it may-or-may-not be in
117    ///   the same process.
118    pub async fn new_session<F>(&self, session_handler: F) -> LocalSession
119    where
120        F: SessionHandler + 'static + Sync + Send + Clone,
121    {
122        self.new_session_with_callback(move |msg| {
123            let mut session_handler = session_handler.clone();
124            Box::pin(async move { session_handler.send_response(msg).await })
125        })
126        .await
127    }
128
129    pub fn new_local_client(&self) -> LocalClient {
130        LocalClient::new(self)
131    }
132
133    /// Flush any pending messages which may have resulted from previous
134    /// [`Session::handle_request`] calls.
135    ///
136    /// Calling [`Session::poll`] may result in the `send_response` parameter
137    /// which was used to construct this (or other) [`Session`] to fire.
138    /// Whenever a [`Session::handle_request`] method is invoked for a
139    /// `perspective_server::Server`, at least one [`Session::poll`] should be
140    /// scheduled to clear other clients message queues.
141    ///
142    /// `poll()` _must_ be called after [`Table::update`] or [`Table::remove`]
143    /// and `on_poll_request` set, or these changes will not be applied.
144    pub async fn poll(&self) -> Result<(), ServerError> {
145        let responses = self.server.poll();
146        let mut results = Vec::with_capacity(responses.size());
147        for response in responses.iter_responses() {
148            let cb = self
149                .callbacks
150                .read()
151                .await
152                .get(&response.client_id())
153                .cloned();
154
155            if let Some(f) = cb {
156                results.push(f(response.msg()).await);
157            }
158        }
159
160        results.into_iter().collect()
161    }
162}