1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use std::collections::HashMap;
use std::net::SocketAddr;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use async_lock::{Mutex, MutexGuard};
use bonsaidb_core::api;
use bonsaidb_core::api::ApiName;
use bonsaidb_core::arc_bytes::serde::Bytes;
use bonsaidb_core::connection::{Session, SessionId};
use bonsaidb_core::networking::MessageReceived;
use bonsaidb_core::pubsub::{Receiver, Subscriber as _};
use bonsaidb_local::Subscriber;
use bonsaidb_utils::fast_async_lock;
use derive_where::derive_where;
use flume::Sender;
use parking_lot::RwLock;

use crate::{Backend, CustomServer, Error, NoBackend};

/// The ways a client can be connected to the server.
#[derive(Debug, PartialEq, Eq)]
pub enum Transport {
    /// A connection over BonsaiDb's QUIC-based protocol.
    Bonsai,
    /// A connection over WebSockets.
    #[cfg(feature = "websockets")]
    WebSocket,
}

/// A connected database client.
#[derive(Debug)]
#[derive_where(Clone)]
pub struct ConnectedClient<B: Backend = NoBackend> {
    data: Arc<ConnectedClientData<B>>,
}

#[derive(Debug)]
struct ConnectedClientData<B: Backend = NoBackend> {
    id: u32,
    sessions: RwLock<HashMap<Option<SessionId>, ClientSession>>,
    address: SocketAddr,
    transport: Transport,
    response_sender: Sender<(Option<SessionId>, ApiName, Bytes)>,
    client_data: Mutex<Option<B::ClientData>>,
    connected: AtomicBool,
}

#[derive(Debug)]
struct ClientSession {
    session: Session,
    subscribers: HashMap<u64, Subscriber>,
}

impl<B: Backend> ConnectedClient<B> {
    /// Returns the address of the connected client.
    #[must_use]
    pub fn address(&self) -> &SocketAddr {
        &self.data.address
    }

    /// Returns the transport method the client is connected via.
    #[must_use]
    pub fn transport(&self) -> &Transport {
        &self.data.transport
    }

    /// Returns true if the server still believes the client is connected.
    #[must_use]
    pub fn connected(&self) -> bool {
        self.data.connected.load(Ordering::Relaxed)
    }

    pub(crate) fn set_disconnected(&self) {
        self.data.connected.store(false, Ordering::Relaxed);
    }

    pub(crate) fn logged_in_as(&self, session: Session) {
        let mut sessions = self.data.sessions.write();
        sessions.insert(
            session.id,
            ClientSession {
                session,
                subscribers: HashMap::default(),
            },
        );
    }

    pub(crate) fn log_out(&self, session: SessionId) -> Option<Session> {
        let mut sessions = self.data.sessions.write();
        sessions.remove(&Some(session)).map(|cs| cs.session)
    }

    /// Sends a custom API response to the client.
    pub fn send<Api: api::Api>(
        &self,
        session: Option<&Session>,
        response: &Api::Response,
    ) -> Result<(), Error> {
        let encoded = pot::to_vec(&Result::<&Api::Response, Api::Error>::Ok(response))?;
        self.data.response_sender.send((
            session.and_then(|session| session.id),
            Api::name(),
            Bytes::from(encoded),
        ))?;
        Ok(())
    }

    /// Returns a locked reference to the stored client data.
    pub async fn client_data(&self) -> LockedClientDataGuard<'_, B::ClientData> {
        LockedClientDataGuard(fast_async_lock!(self.data.client_data))
    }

    /// Looks up an active authentication session by its unique id. `None`
    /// represents the unauthenticated session, and the result can be used to
    /// check what permissions are allowed by default.
    #[must_use]
    pub fn session(&self, session_id: Option<SessionId>) -> Option<Session> {
        let sessions = self.data.sessions.read();
        sessions.get(&session_id).map(|data| data.session.clone())
    }

    /// Returns a collection of all active [`Session`]s for this client.
    #[must_use]
    pub fn all_sessions<C: FromIterator<Session>>(&self) -> C {
        let sessions = self.data.sessions.read();
        sessions.values().map(|s| s.session.clone()).collect()
    }

    pub(crate) fn register_subscriber(
        &self,
        subscriber: Subscriber,
        session_id: Option<SessionId>,
    ) {
        let subscriber_id = subscriber.id();
        let receiver = subscriber.receiver().clone();
        {
            let mut sessions = self.data.sessions.write();
            if let Some(client_session) = sessions.get_mut(&session_id) {
                client_session
                    .subscribers
                    .insert(subscriber.id(), subscriber);
            } else {
                // TODO return error for session not found.
                return;
            }
        }
        let task_self = self.clone();
        tokio::task::spawn(async move {
            task_self
                .forward_notifications_for(session_id, subscriber_id, receiver)
                .await;
        });
    }

    /// Sets the associated data for this client.
    pub async fn set_client_data(&self, data: B::ClientData) {
        let mut client_data = fast_async_lock!(self.data.client_data);
        *client_data = Some(data);
    }

    async fn forward_notifications_for(
        &self,
        session_id: Option<SessionId>,
        subscriber_id: u64,
        receiver: Receiver,
    ) {
        let session = self.session(session_id);
        while let Ok(message) = receiver.receive_async().await {
            if self
                .send::<MessageReceived>(
                    session.as_ref(),
                    &MessageReceived {
                        subscriber_id,
                        topic: Bytes::from(message.topic.0.into_vec()),
                        payload: Bytes::from(&message.payload[..]),
                    },
                )
                .is_err()
            {
                break;
            }
        }
    }

    pub(crate) fn subscribe_by_id(
        &self,
        subscriber_id: u64,
        topic: Bytes,
        check_session_id: Option<SessionId>,
    ) -> Result<(), crate::Error> {
        let mut sessions = self.data.sessions.write();
        if let Some(client_session) = sessions.get_mut(&check_session_id) {
            if let Some(subscriber) = client_session.subscribers.get(&subscriber_id) {
                subscriber.subscribe_to_bytes(topic.0)?;
                Ok(())
            } else {
                Err(Error::other(
                    "bonsaidb-server pubsub",
                    "invalid subscriber id",
                ))
            }
        } else {
            Err(Error::other("bonsaidb-server auth", "invalid session id"))
        }
    }

    pub(crate) fn unsubscribe_by_id(
        &self,
        subscriber_id: u64,
        topic: &[u8],
        check_session_id: Option<SessionId>,
    ) -> Result<(), crate::Error> {
        let mut sessions = self.data.sessions.write();
        if let Some(client_session) = sessions.get_mut(&check_session_id) {
            if let Some(subscriber) = client_session.subscribers.get(&subscriber_id) {
                subscriber.unsubscribe_from_bytes(topic)?;
                Ok(())
            } else {
                Err(Error::other(
                    "bonsaidb-server pubsub",
                    "invalid subscriber id",
                ))
            }
        } else {
            Err(Error::other("bonsaidb-server auth", "invalid session id"))
        }
    }

    pub(crate) fn unregister_subscriber_by_id(
        &self,
        subscriber_id: u64,
        check_session_id: Option<SessionId>,
    ) -> Result<(), crate::Error> {
        let mut sessions = self.data.sessions.write();
        if let Some(client_session) = sessions.get_mut(&check_session_id) {
            if client_session.subscribers.remove(&subscriber_id).is_some() {
                Ok(())
            } else {
                Err(Error::other(
                    "bonsaidb-server pubsub",
                    "invalid subscriber id",
                ))
            }
        } else {
            Err(Error::other("bonsaidb-server auth", "invalid session id"))
        }
    }
}

/// A locked reference to associated client data.
pub struct LockedClientDataGuard<'client, ClientData>(MutexGuard<'client, Option<ClientData>>);

impl<'client, ClientData> Deref for LockedClientDataGuard<'client, ClientData> {
    type Target = Option<ClientData>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'client, ClientData> DerefMut for LockedClientDataGuard<'client, ClientData> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug)]
pub struct OwnedClient<B: Backend> {
    client: ConnectedClient<B>,
    runtime: Arc<tokio::runtime::Handle>,
    server: Option<CustomServer<B>>,
}

impl<B: Backend> OwnedClient<B> {
    pub(crate) fn new(
        id: u32,
        address: SocketAddr,
        transport: Transport,
        response_sender: Sender<(Option<SessionId>, ApiName, Bytes)>,
        server: CustomServer<B>,
        default_session: Session,
    ) -> Self {
        let mut session = HashMap::new();
        session.insert(
            None,
            ClientSession {
                session: default_session,
                subscribers: HashMap::default(),
            },
        );
        Self {
            client: ConnectedClient {
                data: Arc::new(ConnectedClientData {
                    id,
                    address,
                    transport,
                    response_sender,
                    sessions: RwLock::new(session),
                    client_data: Mutex::default(),
                    connected: AtomicBool::new(true),
                }),
            },
            runtime: Arc::new(tokio::runtime::Handle::current()),
            server: Some(server),
        }
    }

    pub fn clone(&self) -> ConnectedClient<B> {
        self.client.clone()
    }
}

impl<B: Backend> Drop for OwnedClient<B> {
    fn drop(&mut self) {
        let id = self.client.data.id;
        let server = self.server.take().unwrap();
        self.runtime
            .spawn(async move { server.disconnect_client(id).await });
    }
}

impl<B: Backend> Deref for OwnedClient<B> {
    type Target = ConnectedClient<B>;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}