mpc_manager/state/
group.rs1use super::{
6 parameters::Parameters,
7 session::{Session, SessionId},
8 ClientId,
9};
10use serde::{Deserialize, Serialize};
11use std::collections::{HashMap, HashSet};
12use thiserror::Error;
13use uuid::Uuid;
14
15#[cfg(feature = "server")]
16use super::session::{SessionKind, SessionValue};
17
18pub type GroupId = Uuid;
20
21#[derive(Debug, Error)]
23pub enum GroupError {
24 #[error("group is full")]
26 GroupFull,
27}
28
29#[derive(Debug, Deserialize, Serialize)]
31pub struct Group {
32 pub id: GroupId,
34 pub params: Parameters,
36 #[serde(skip)]
38 pub(crate) sessions: HashMap<SessionId, Session>,
39 #[serde(skip)]
41 pub(crate) clients: HashSet<ClientId>,
42}
43
44impl Group {
45 pub fn new(id: GroupId, params: Parameters) -> Self {
47 Self {
48 id,
49 params,
50 sessions: HashMap::new(),
51 clients: HashSet::new(),
52 }
53 }
54
55 #[cfg(feature = "server")]
57 pub fn add_client(&mut self, client_id: ClientId) -> anyhow::Result<()> {
58 let clients = self.clients.len();
59 if clients >= self.params.n().into() {
60 return Err(GroupError::GroupFull.into());
61 }
62 self.clients.insert(client_id);
63 Ok(())
64 }
65
66 #[cfg(feature = "server")]
68 pub fn drop_client(&mut self, client_id: ClientId) {
69 self.clients.remove(&client_id);
70 }
72
73 #[cfg(feature = "server")]
75 pub fn add_session(&mut self, kind: SessionKind, value: SessionValue) -> Session {
76 let session_id = Uuid::new_v4();
77 let session = Session::new(session_id, kind, value);
78 let session_c = session.clone();
79 self.sessions.insert(session_id, session);
80 session_c
81 }
82
83 #[cfg(feature = "server")]
85 pub fn get_session(&self, session_id: &SessionId) -> Option<&Session> {
86 self.sessions.get(session_id)
87 }
88
89 #[cfg(feature = "server")]
91 pub fn get_session_mut(&mut self, session_id: &SessionId) -> Option<&mut Session> {
92 self.sessions.get_mut(session_id)
93 }
94
95 #[cfg(feature = "server")]
97 pub fn is_empty(&self) -> bool {
98 self.clients.len() == 0
99 }
100
101 #[cfg(feature = "server")]
103 pub fn is_full(&self) -> bool {
104 self.clients.len() == self.params.n() as usize
105 }
106
107 #[cfg(feature = "server")]
109 pub fn id(&self) -> GroupId {
110 self.id
111 }
112
113 #[cfg(feature = "server")]
115 pub fn clients(&self) -> &HashSet<ClientId> {
116 &self.clients
117 }
118}
119
120impl Clone for Group {
121 fn clone(&self) -> Self {
125 Self {
126 id: self.id,
127 params: self.params.clone(),
128 sessions: HashMap::new(),
129 clients: HashSet::new(),
130 }
131 }
132}