Skip to main content

unbanished_net/
memory.rs

1//! A relay and its connections in one process, for tests: the same rooms as the relay program
2//! ([`crate::rooms`]), and connections that send and poll like a WebSocket `Connection`.
3//! Every message is encoded and decoded on the way, as on a socket.
4
5use std::cell::RefCell;
6use std::collections::{BTreeMap, VecDeque};
7use std::rc::Rc;
8
9use crate::protocol::{decode, encode, FromRelay, ToRelay};
10use crate::rooms::{Client, Relay};
11use crate::State;
12
13struct Inner {
14    relay: Relay,
15    inboxes: BTreeMap<Client, VecDeque<Vec<u8>>>,
16    closed: BTreeMap<Client, String>,
17    next: Client,
18}
19
20/// A relay in this process.
21#[derive(Clone)]
22pub struct MemoryRelay(Rc<RefCell<Inner>>);
23
24impl MemoryRelay {
25    /// An empty relay; `seed` starts its room codes.
26    pub fn new(seed: u64) -> MemoryRelay {
27        MemoryRelay(Rc::new(RefCell::new(Inner {
28            relay: Relay::new(seed),
29            inboxes: BTreeMap::new(),
30            closed: BTreeMap::new(),
31            next: 0,
32        })))
33    }
34
35    /// An empty relay that keeps rooms' towns in `store`.
36    pub fn with_store(seed: u64, store: Box<dyn crate::store::Store>) -> MemoryRelay {
37        let relay = MemoryRelay::new(seed);
38        {
39            let mut inner = relay.0.borrow_mut();
40            let r = std::mem::replace(&mut inner.relay, Relay::new(seed));
41            inner.relay = r.with_store(store);
42        }
43        relay
44    }
45
46    /// A new game's connection to it.
47    pub fn connect(&self) -> MemoryConnection {
48        let mut inner = self.0.borrow_mut();
49        let client = inner.next;
50        inner.next += 1;
51        inner.relay.connect(client);
52        inner.inboxes.insert(client, VecDeque::new());
53        MemoryConnection {
54            relay: self.0.clone(),
55            client,
56            state: State::Open,
57        }
58    }
59}
60
61/// A game's connection to a [`MemoryRelay`].
62pub struct MemoryConnection {
63    relay: Rc<RefCell<Inner>>,
64    client: Client,
65    state: State,
66}
67
68impl MemoryConnection {
69    /// Sends a request to the relay.
70    pub fn send(&mut self, request: ToRelay) {
71        if self.state != State::Open {
72            return;
73        }
74        let request: ToRelay = decode(&encode(&request)).expect("a request round-trips");
75        let mut inner = self.relay.borrow_mut();
76        let reply = inner.relay.handle(self.client, request);
77        for (to, message) in reply.out {
78            if let Some(inbox) = inner.inboxes.get_mut(&to) {
79                inbox.push_back(encode(&message));
80            }
81        }
82        if reply.close {
83            let out = inner.relay.disconnect(self.client);
84            for (to, message) in out {
85                if let Some(inbox) = inner.inboxes.get_mut(&to) {
86                    inbox.push_back(encode(&message));
87                }
88            }
89            inner
90                .closed
91                .insert(self.client, "the relay closed the connection".into());
92        }
93    }
94
95    /// The messages that arrived since the last call.
96    pub fn poll(&mut self) -> Vec<FromRelay> {
97        let mut inner = self.relay.borrow_mut();
98        let out = inner
99            .inboxes
100            .get_mut(&self.client)
101            .map(|inbox| inbox.drain(..).collect::<Vec<_>>())
102            .unwrap_or_default();
103        if let Some(reason) = inner.closed.get(&self.client) {
104            self.state = State::Closed(reason.clone());
105        }
106        out.iter()
107            .map(|bytes| decode(bytes).expect("a message round-trips"))
108            .collect()
109    }
110
111    /// The connection's state.
112    pub fn state(&self) -> &State {
113        &self.state
114    }
115}
116
117impl Drop for MemoryConnection {
118    fn drop(&mut self) {
119        let mut inner = self.relay.borrow_mut();
120        let out = inner.relay.disconnect(self.client);
121        for (to, message) in out {
122            if let Some(inbox) = inner.inboxes.get_mut(&to) {
123                inbox.push_back(encode(&message));
124            }
125        }
126        inner.inboxes.remove(&self.client);
127    }
128}