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
use super::client::Client;
use anyhow::Result;
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use serde::{de::DeserializeOwned, Serialize, Serializer};
use stardust_xr::{
messenger::MessengerError,
schemas::flex::{deserialize, flexbuffers::DeserializationError, serialize},
};
use std::{
fmt::Debug,
future::Future,
pin::Pin,
sync::{Arc, Weak},
vec::Vec,
};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum NodeError {
#[error("client has been dropped")]
ClientDropped,
#[error("Messenger error: {e}")]
MessengerError { e: MessengerError },
#[error("Node does not exist anymore")]
DoesNotExist,
#[error("invalid path")]
InvalidPath,
#[error("Serialization failed")]
Serialization,
#[error("Deserialization failed with an error: {e}")]
Deserialization { e: DeserializationError },
#[error("Server returned an error: {e}")]
ReturnedError { e: String },
#[error("Attempted to register to a singleton twice")]
OverrideSingleton,
#[error("Map is not a valid flexbuffer map at the root")]
MapInvalid,
}
pub trait NodeType: Send + Sync + Sized + 'static {
fn node(&self) -> &Node;
fn client(&self) -> Result<Arc<Client>, NodeError> {
self.node().client()
}
fn alias(&self) -> Self;
}
pub trait HandledNodeType: NodeType {}
pub trait ClientOwned: NodeType {}
type Signal = dyn Fn(&[u8]) -> Result<()> + Send + Sync + 'static;
type Method = dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static;
pub type BoxedFuture<O> = Pin<Box<dyn Future<Output = O>>>;
pub struct NodeInternals {
pub client: Weak<Client>,
self_ref: Weak<NodeInternals>,
parent: String,
name: String,
pub(crate) local_signals: Mutex<FxHashMap<String, Arc<Signal>>>,
pub(crate) local_methods: Mutex<FxHashMap<String, Arc<Method>>>,
pub(crate) destroyable: bool,
}
impl NodeInternals {
pub(crate) fn path(&self) -> String {
self.parent.clone() + "/" + &self.name
}
}
impl Serialize for NodeInternals {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.path().serialize(serializer)
}
}
impl Drop for NodeInternals {
fn drop(&mut self) {
if let Some(client) = self.client.upgrade() {
let path = self.path();
if self.destroyable {
let _ = client.message_sender_handle.signal(&path, "destroy", &[]);
}
client.scenegraph.remove_node(&path);
}
}
}
pub enum Node {
Owned(Arc<NodeInternals>),
Aliased(Weak<NodeInternals>),
}
impl Node {
pub(crate) fn new<'a, S: Serialize>(
client: &Arc<Client>,
interface_path: &'a str,
interface_method: &'a str,
parent_path: &'a str,
destroyable: bool,
id: &str,
data: S,
) -> Result<Node, NodeError> {
let node = Node::from_path(client, parent_path, id, destroyable);
client
.message_sender_handle
.signal(
interface_path,
interface_method,
&serialize(data).map_err(|_| NodeError::Serialization)?,
)
.map_err(|e| NodeError::MessengerError { e })?;
Ok(node)
}
pub fn from_path(
client: &Arc<Client>,
parent: impl ToString,
name: impl ToString,
destroyable: bool,
) -> Node {
let node = Arc::new_cyclic(|self_ref| NodeInternals {
client: Arc::downgrade(client),
self_ref: self_ref.clone(),
parent: parent.to_string(),
name: name.to_string(),
local_signals: Mutex::new(FxHashMap::default()),
local_methods: Mutex::new(FxHashMap::default()),
destroyable,
});
client.scenegraph.add_node(&node);
Node::Owned(node)
}
pub fn add_local_signal<F>(&self, name: impl ToString, signal: F) -> Result<(), NodeError>
where
F: Fn(&[u8]) -> Result<()> + Send + Sync + 'static,
{
self.internals()?
.local_signals
.lock()
.insert(name.to_string(), Arc::new(signal));
Ok(())
}
pub fn add_local_method<F>(&self, name: impl ToString, method: F) -> Result<(), NodeError>
where
F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
{
self.internals()?
.local_methods
.lock()
.insert(name.to_string(), Arc::new(method));
Ok(())
}
pub(crate) fn internals(&self) -> Result<Arc<NodeInternals>, NodeError> {
match self {
Node::Owned(node) => Ok(node.clone()),
Node::Aliased(node) => node.upgrade().ok_or(NodeError::DoesNotExist),
}
}
pub fn client(&self) -> Result<Arc<Client>, NodeError> {
self.internals()?
.client
.upgrade()
.ok_or(NodeError::ClientDropped)
}
pub fn get_name(&self) -> Result<String, NodeError> {
Ok(self.internals()?.parent.to_string())
}
pub fn get_path(&self) -> Result<String, NodeError> {
Ok(self.internals()?.path())
}
pub fn send_remote_signal<S: Serialize>(
&self,
signal_name: &str,
data: &S,
) -> Result<(), NodeError> {
self.send_remote_signal_raw(
signal_name,
&serialize(data).map_err(|_| NodeError::Serialization)?,
)
}
pub fn send_remote_signal_raw(&self, signal_name: &str, data: &[u8]) -> Result<(), NodeError> {
self.client()?
.message_sender_handle
.signal(&self.get_path()?, signal_name, data)
.map_err(|e| NodeError::MessengerError { e })
}
pub fn execute_remote_method<S: Serialize, D: DeserializeOwned>(
&self,
method_name: &str,
send_data: &S,
) -> Result<impl Future<Output = Result<D, NodeError>>, NodeError> {
let send_data = serialize(send_data).map_err(|_| NodeError::Serialization)?;
let future = self.execute_remote_method_raw(method_name, &send_data)?;
Ok(async move {
future
.await
.and_then(|data| deserialize(&data).map_err(|e| NodeError::Deserialization { e }))
})
}
pub fn execute_remote_method_trait<S: Serialize, D: DeserializeOwned>(
&self,
method_name: &str,
send_data: &S,
) -> Result<Pin<Box<dyn Future<Output = Result<D, NodeError>>>>, NodeError> {
let send_data = serialize(send_data).map_err(|_| NodeError::Serialization)?;
let future = self.execute_remote_method_raw(method_name, &send_data)?;
Ok(Box::pin(async move {
future
.await
.and_then(|data| deserialize(&data).map_err(|e| NodeError::Deserialization { e }))
}))
}
pub fn execute_remote_method_raw(
&self,
method_name: &str,
data: &[u8],
) -> Result<impl Future<Output = Result<Vec<u8>, NodeError>>, NodeError> {
let future = self
.client()?
.message_sender_handle
.method(&self.get_path()?, method_name, data)
.map_err(|e| NodeError::MessengerError { e })?;
Ok(async move { future.await.map_err(|e| NodeError::ReturnedError { e }) })
}
fn set_enabled(&self, enabled: bool) -> Result<(), NodeError> {
self.send_remote_signal("set_enabled", &enabled)
}
}
impl NodeType for Node {
fn node(&self) -> &Node {
self
}
fn alias(&self) -> Self {
match self {
Node::Owned(internals) => Node::Aliased(Arc::downgrade(internals)),
Node::Aliased(internals) => Node::Aliased(internals.clone()),
}
}
}
impl Debug for Node {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut dbg = f.debug_struct("Node");
if let Ok(internals) = self.internals() {
dbg.field("path", &internals.path())
.field(
"local_signals",
&internals
.local_signals
.lock()
.iter()
.map(|(key, _)| key)
.collect::<Vec<_>>(),
)
.field(
"local_methods",
&internals
.local_methods
.lock()
.iter()
.map(|(key, _)| key)
.collect::<Vec<_>>(),
);
} else {
dbg.field("node", &"broken");
}
dbg.finish()
}
}