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
|
use std::convert::TryInto;
use crate::{
deserialize::Deserialize,
primitive::{Variant, VariantList},
serialize::Serialize,
};
use num_derive::{FromPrimitive, ToPrimitive};
mod heartbeat;
mod initdata;
mod initrequest;
pub mod objects;
mod rpccall;
mod syncmessage;
mod translation;
pub use translation::*;
pub use heartbeat::*;
pub use initdata::*;
pub use initrequest::*;
pub use rpccall::*;
pub use syncmessage::*;
use once_cell::sync::OnceCell;
pub static SYNC_PROXY: OnceCell<SyncProxy> = OnceCell::new();
#[derive(Debug, Clone)]
pub struct SyncProxy {
sync_channel: crossbeam_channel::Sender<SyncMessage>,
rpc_channel: crossbeam_channel::Sender<RpcCall>,
}
/// SyncProxy sends sync and rpc messages
impl SyncProxy {
/// Initialize the global SYNC_PROXY object and return receiver ends for the SyncMessage and RpcCall channels
pub fn init(cap: usize) -> (crossbeam_channel::Receiver<SyncMessage>, crossbeam_channel::Receiver<RpcCall>) {
let (sync_tx, sync_rx) = crossbeam_channel::bounded(cap);
let (rpc_tx, rpc_rx) = crossbeam_channel::bounded(cap);
SYNC_PROXY.set(SyncProxy { sync_channel: sync_tx, rpc_channel: rpc_tx }).unwrap();
(sync_rx, rpc_rx)
}
/// Send a SyncMessage
fn sync(
&self,
class_name: &str,
object_name: Option<&str>,
function: &str,
params: VariantList,
) {
let msg = SyncMessage {
class_name: class_name.to_string(),
object_name: object_name.unwrap_or("").to_string(),
slot_name: function.to_string(),
params,
};
debug!("submitting {:#?}", msg);
self.sync_channel.send(msg).unwrap();
}
/// Send an RpcCall
fn rpc(&self, function: &str, params: VariantList) {}
}
/// A base Syncable Object
///
/// Provides default implementations for sending SyncMessages and
/// RpcCalls so you usually only have to set the CLASS const
pub trait Syncable {
/// The Class of the object as transmitted in the SyncMessage
const CLASS: &'static str;
/// Send a SyncMessage.
fn send_sync(&self, object_name: Option<&str>, function: &str, params: VariantList) {
crate::message::signalproxy::SYNC_PROXY.get().unwrap().sync(
Self::CLASS,
object_name,
function,
params,
);
}
/// Send a RpcCall
fn send_rpc(&self, function: &str, params: VariantList) {
crate::message::signalproxy::SYNC_PROXY
.get()
.unwrap()
.rpc(function, params);
}
}
/// Methods for a Stateful Syncable object on the client side.
pub trait StatefulSyncableServer: Syncable + translation::NetworkMap
where
Variant: From<<Self as translation::NetworkMap>::Item>,
{
fn sync(&mut self, mut msg: crate::message::SyncMessage)
where
Self: Sized,
{
match msg.slot_name.as_str() {
"requestUpdate" => StatefulSyncableServer::request_update(
self,
msg.params.pop().unwrap().try_into().unwrap(),
),
_ => StatefulSyncableServer::sync_custom(self, msg),
}
}
fn sync_custom(&mut self, mut msg: crate::message::SyncMessage)
where
Self: Sized,
{
match msg.slot_name.as_str() {
_ => (),
}
}
/// Client -> Server: Update the whole object with received data
fn update(&mut self)
where
Self: Sized,
{
self.send_sync(None, "update", vec![self.to_network_map().into()]);
}
/// Server -> Client: Update the whole object with received data
fn request_update(&mut self, mut param: <Self as translation::NetworkMap>::Item)
where
Self: Sized,
{
*self = Self::from_network_map(&mut param);
}
}
/// Methods for a Stateful Syncable object on the server side.
pub trait StatefulSyncableClient: Syncable + translation::NetworkMap {
fn sync(&mut self, mut msg: crate::message::SyncMessage)
where
Self: Sized,
{
match msg.slot_name.as_str() {
"update" => {
StatefulSyncableClient::update(self, msg.params.pop().unwrap().try_into().unwrap())
}
_ => StatefulSyncableClient::sync_custom(self, msg),
}
}
fn sync_custom(&mut self, msg: crate::message::SyncMessage)
where
Self: Sized,
{
match msg.slot_name.as_str() {
_ => (),
}
}
/// Client -> Server: Update the whole object with received data
fn update(&mut self, mut param: <Self as translation::NetworkMap>::Item)
where
Self: Sized,
{
*self = Self::from_network_map(&mut param);
}
/// Server -> Client: Update the whole object with received data
fn request_update(&mut self)
where
Self: Sized,
{
self.send_sync(None, "requestUpdate", vec![self.to_network_map().into()]);
}
}
#[derive(Clone, Debug, std::cmp::PartialEq)]
pub enum Message {
/// Bidirectional
SyncMessage(SyncMessage),
/// Bidirectional
RpcCall(RpcCall),
InitRequest(InitRequest),
InitData(InitData),
/// Bidirectional
HeartBeat(HeartBeat),
/// Bidirectional
HeartBeatReply(HeartBeatReply),
}
// impl Message {
// fn act(&self) {
// match &self {
// Message::SyncMessage(value) => value.serialize(),
// Message::RpcCall(value) => value.serialize(),
// Message::InitRequest(value) => value.serialize(),
// Message::InitData(value) => value.serialize(),
// Message::HeartBeat(value) => value.serialize(),
// Message::HeartBeatReply(value) => value.serialize(),
// }
// }
// }
impl Serialize for Message {
fn serialize(&self) -> Result<Vec<std::primitive::u8>, failure::Error> {
match &self {
Message::SyncMessage(value) => value.serialize(),
Message::RpcCall(value) => value.serialize(),
Message::InitRequest(value) => value.serialize(),
Message::InitData(value) => value.serialize(),
Message::HeartBeat(value) => value.serialize(),
Message::HeartBeatReply(value) => value.serialize(),
}
}
}
impl Deserialize for Message {
fn parse(b: &[std::primitive::u8]) -> Result<(std::primitive::usize, Self), failure::Error> {
let (_, message_type) = i32::parse(&b[9..13])?;
match MessageType::from(message_type) {
MessageType::SyncMessage => {
let (size, res) = SyncMessage::parse(&b)?;
Ok((size, Message::SyncMessage(res)))
}
MessageType::RpcCall => {
let (size, res) = RpcCall::parse(&b)?;
Ok((size, Message::RpcCall(res)))
}
MessageType::InitRequest => {
let (size, res) = InitRequest::parse(&b)?;
Ok((size, Message::InitRequest(res)))
}
MessageType::InitData => {
let (size, res) = InitData::parse(&b)?;
Ok((size, Message::InitData(res)))
}
MessageType::HeartBeat => {
let (size, res) = HeartBeat::parse(&b)?;
Ok((size, Message::HeartBeat(res)))
}
MessageType::HeartBeatReply => {
let (size, res) = HeartBeatReply::parse(&b)?;
Ok((size, Message::HeartBeatReply(res)))
}
}
}
}
/// Type of an SignalProxy Message
/// The first element in the VariantList that is received
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum MessageType {
/// Bidirectional
SyncMessage = 0x00000001,
/// Bidirectional
RpcCall = 0x00000002,
InitRequest = 0x00000003,
InitData = 0x00000004,
/// Bidirectional
HeartBeat = 0x00000005,
/// Bidirectional
HeartBeatReply = 0x00000006,
}
impl From<i32> for MessageType {
fn from(val: i32) -> Self {
match val {
0x00000001 => MessageType::SyncMessage,
0x00000002 => MessageType::RpcCall,
0x00000003 => MessageType::InitRequest,
0x00000004 => MessageType::InitData,
0x00000005 => MessageType::HeartBeat,
0x00000006 => MessageType::HeartBeatReply,
_ => unimplemented!(),
}
}
}
|