sage_broker/
session.rs

1use crate::{Cache, Peer, Subs};
2use log::info;
3use nanoid::nanoid;
4use std::sync::{Arc, RwLock, Weak};
5
6/// Represents a client and holds all of its data, may it be active or not.
7/// If the client is connected, `peer` is used to retrieve its information and
8/// send him packets.
9#[derive(Debug)]
10pub struct Session {
11    id: String,
12    client_id: String,
13    peer: RwLock<Weak<Peer>>,
14    subs: RwLock<Subs>,
15}
16
17impl Session {
18    /// Creates a new session, giving a peer and an id
19    pub fn new(client_id: &str, peer: Arc<Peer>, cache: Arc<Cache>) -> Self {
20        let id = format!("session_{}", nanoid!(10));
21        info!("New session: Unique ID:{:?}, Client ID:{:?}", id, client_id);
22
23        Session {
24            id,
25            client_id: client_id.into(),
26            peer: RwLock::new(Arc::downgrade(&peer)),
27            subs: RwLock::new(Subs::new(cache)),
28        }
29    }
30
31    /// A unique ID that cannot be changed neither can collide with
32    /// other instances of `Session`
33    /// This ID is not part of MQTT specification but is used to ensure a new
34    /// session can be created with a same client_id
35    pub fn id(&self) -> &str {
36        &self.id
37    }
38
39    /// Returns the client_id of the session
40    pub fn client_id(&self) -> &str {
41        &self.client_id
42    }
43
44    /// Assign the session to another peer
45    pub fn bind(&self, peer: Arc<Peer>) {
46        *(self.peer.write().unwrap()) = Arc::downgrade(&peer);
47    }
48
49    /// Gets the currently bound peer as as owning pointer
50    pub fn peer(&self) -> Option<Arc<Peer>> {
51        self.peer.read().unwrap().upgrade()
52    }
53
54    /// Gets the subscriptions this session has
55    pub fn subs(&self) -> &RwLock<Subs> {
56        &self.subs
57    }
58}