forked from rojo-rbx/rojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve_session.rs
427 lines (344 loc) · 13.5 KB
/
serve_session.rs
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::{
collections::HashSet,
path::Path,
sync::{Arc, Mutex, MutexGuard},
time::Instant,
};
use crossbeam_channel::Sender;
use memofs::Vfs;
use rbx_dom_weak::RbxInstanceProperties;
use crate::{
change_processor::ChangeProcessor,
message_queue::MessageQueue,
project::Project,
session_id::SessionId,
snapshot::{
apply_patch_set, compute_patch_set, AppliedPatchSet, InstanceContext,
InstancePropertiesWithMeta, PatchSet, PathIgnoreRule, RojoTree,
},
snapshot_middleware::snapshot_from_vfs,
};
/// Contains all of the state for a Rojo serve session.
///
/// Nothing here is specific to any Rojo interface. Though the primary way to
/// interact with a serve session is Rojo's HTTP right now, there's no reason
/// why Rojo couldn't expose an IPC or channels-based API for embedding in the
/// future. `ServeSession` would be roughly the right interface to expose for
/// those cases.
pub struct ServeSession {
/// The object responsible for listening to changes from the in-memory
/// filesystem, applying them, updating the Roblox instance tree, and
/// routing messages through the session's message queue to any connected
/// clients.
///
/// SHOULD BE DROPPED FIRST! ServeSession and ChangeProcessor communicate
/// with eachother via channels. If ServeSession hangs up those channels
/// before dropping the ChangeProcessor, its thread will panic with a
/// RecvError, causing the main thread to panic on drop.
///
/// Allowed to be unused because it has side effects when dropped.
#[allow(unused)]
change_processor: ChangeProcessor,
/// When the serve session was started. Used only for user-facing
/// diagnostics.
start_time: Instant,
/// The root project for the serve session, if there was one defined.
///
/// This will be defined if a folder with a `default.project.json` file was
/// used for starting the serve session, or if the user specified a full
/// path to a `.project.json` file.
///
/// If `root_project` is None, values from the project should be treated as
/// their defaults.
root_project: Option<Project>,
/// A randomly generated ID for this serve session. It's used to ensure that
/// a client doesn't begin connecting to a different server part way through
/// an operation that needs to be atomic.
session_id: SessionId,
/// The tree of Roblox instances associated with this session that will be
/// updated in real-time. This is derived from the session's VFS and will
/// eventually be mutable to connected clients.
tree: Arc<Mutex<RojoTree>>,
/// An in-memory filesystem containing all of the files relevant for this
/// live session.
///
/// The main use for accessing it from the session is for debugging issues
/// with Rojo's live-sync protocol.
vfs: Arc<Vfs>,
/// A queue of changes that have been applied to `tree` that affect clients.
///
/// Clients to the serve session will subscribe to this queue either
/// directly or through the HTTP API to be notified of mutations that need
/// to be applied.
message_queue: Arc<MessageQueue<AppliedPatchSet>>,
/// A channel to send mutation requests on. These will be handled by the
/// ChangeProcessor and trigger changes in the tree.
tree_mutation_sender: Sender<PatchSet>,
}
/// Methods that need thread-safety bounds on VfsFetcher are limited to this
/// block to prevent needing to spread Send + Sync + 'static into everything
/// that handles ServeSession.
impl ServeSession {
/// Start a new serve session from the given in-memory filesystem and start
/// path.
///
/// The project file is expected to be loaded out-of-band since it's
/// currently loaded from the filesystem directly instead of through the
/// in-memory filesystem layer.
pub fn new<P: AsRef<Path>>(vfs: Vfs, start_path: P) -> Self {
let start_path = start_path.as_ref();
let start_time = Instant::now();
log::trace!("Starting new ServeSession at path {}", start_path.display());
log::trace!("Loading project file from {}", start_path.display());
let root_project = Project::load_fuzzy(start_path).expect("TODO: Project load failed");
let mut tree = RojoTree::new(InstancePropertiesWithMeta {
properties: RbxInstanceProperties {
name: "ROOT".to_owned(),
class_name: "Folder".to_owned(),
properties: Default::default(),
},
metadata: Default::default(),
});
let root_id = tree.get_root_id();
let mut instance_context = InstanceContext::default();
if let Some(project) = &root_project {
let rules = project.glob_ignore_paths.iter().map(|glob| PathIgnoreRule {
glob: glob.clone(),
base_path: project.folder_location().to_path_buf(),
});
instance_context.add_path_ignore_rules(rules);
}
log::trace!("Generating snapshot of instances from VFS");
let snapshot = snapshot_from_vfs(&instance_context, &vfs, &start_path)
.expect("snapshot failed")
.expect("snapshot did not return an instance");
log::trace!("Computing initial patch set");
let patch_set = compute_patch_set(&snapshot, &tree, root_id);
log::trace!("Applying initial patch set");
apply_patch_set(&mut tree, patch_set);
let session_id = SessionId::new();
let message_queue = MessageQueue::new();
let tree = Arc::new(Mutex::new(tree));
let message_queue = Arc::new(message_queue);
let vfs = Arc::new(vfs);
let (tree_mutation_sender, tree_mutation_receiver) = crossbeam_channel::unbounded();
log::trace!("Starting ChangeProcessor");
let change_processor = ChangeProcessor::start(
Arc::clone(&tree),
Arc::clone(&vfs),
Arc::clone(&message_queue),
tree_mutation_receiver,
);
Self {
change_processor,
start_time,
session_id,
root_project,
tree,
message_queue,
tree_mutation_sender,
vfs,
}
}
}
impl ServeSession {
pub fn tree_handle(&self) -> Arc<Mutex<RojoTree>> {
Arc::clone(&self.tree)
}
pub fn tree(&self) -> MutexGuard<'_, RojoTree> {
self.tree.lock().unwrap()
}
pub fn tree_mutation_sender(&self) -> Sender<PatchSet> {
self.tree_mutation_sender.clone()
}
#[allow(unused)]
pub fn vfs(&self) -> &Vfs {
&self.vfs
}
pub fn message_queue(&self) -> &MessageQueue<AppliedPatchSet> {
&self.message_queue
}
pub fn session_id(&self) -> SessionId {
self.session_id
}
pub fn project_name(&self) -> Option<&str> {
self.root_project
.as_ref()
.map(|project| project.name.as_str())
}
pub fn project_port(&self) -> Option<u16> {
self.root_project
.as_ref()
.and_then(|project| project.serve_port)
}
pub fn start_time(&self) -> Instant {
self.start_time
}
pub fn serve_place_ids(&self) -> Option<&HashSet<u64>> {
self.root_project
.as_ref()
.and_then(|project| project.serve_place_ids.as_ref())
}
}
/// This module is named to trick Insta into naming the resulting snapshots
/// correctly.
///
/// See https://github.com/mitsuhiko/insta/issues/78
#[cfg(test)]
mod serve_session {
use super::*;
use std::{path::PathBuf, time::Duration};
use maplit::hashmap;
use memofs::{InMemoryFs, VfsEvent, VfsSnapshot};
use rojo_insta_ext::RedactionMap;
use tokio::{runtime::Runtime, timer::Timeout};
use crate::tree_view::view_tree;
#[test]
fn just_folder() {
let mut imfs = InMemoryFs::new();
imfs.load_snapshot("/foo", VfsSnapshot::empty_dir())
.unwrap();
let vfs = Vfs::new(imfs);
let session = ServeSession::new(vfs, "/foo");
let mut rm = RedactionMap::new();
insta::assert_yaml_snapshot!(view_tree(&session.tree(), &mut rm));
}
#[test]
fn project_with_folder() {
let mut imfs = InMemoryFs::new();
imfs.load_snapshot(
"/foo",
VfsSnapshot::dir(hashmap! {
"default.project.json" => VfsSnapshot::file(r#"
{
"name": "HelloWorld",
"tree": {
"$path": "src"
}
}
"#),
"src" => VfsSnapshot::dir(hashmap! {
"hello.txt" => VfsSnapshot::file("Hello, world!"),
}),
}),
)
.unwrap();
let vfs = Vfs::new(imfs);
let session = ServeSession::new(vfs, "/foo");
let mut rm = RedactionMap::new();
insta::assert_yaml_snapshot!(view_tree(&session.tree(), &mut rm));
}
#[test]
fn script_with_meta() {
let mut imfs = InMemoryFs::new();
imfs.load_snapshot(
"/root",
VfsSnapshot::dir(hashmap! {
"test.lua" => VfsSnapshot::file("This is a test."),
"test.meta.json" => VfsSnapshot::file(r#"{ "ignoreUnknownInstances": true }"#),
}),
)
.unwrap();
let vfs = Vfs::new(imfs);
let session = ServeSession::new(vfs, "/root");
let mut rm = RedactionMap::new();
insta::assert_yaml_snapshot!(view_tree(&session.tree(), &mut rm));
}
#[test]
fn change_txt_file() {
let mut imfs = InMemoryFs::new();
imfs.load_snapshot("/foo.txt", VfsSnapshot::file("Hello!"))
.unwrap();
let vfs = Vfs::new(imfs.clone());
let session = ServeSession::new(vfs, "/foo.txt");
let mut rm = RedactionMap::new();
insta::assert_yaml_snapshot!(
"change_txt_file_before",
view_tree(&session.tree(), &mut rm)
);
imfs.load_snapshot("/foo.txt", VfsSnapshot::file("World!"))
.unwrap();
let receiver = session.message_queue().subscribe_any();
imfs.raise_event(VfsEvent::Write(PathBuf::from("/foo.txt")));
let receiver = Timeout::new(receiver, Duration::from_millis(200));
let mut rt = Runtime::new().unwrap();
let result = rt.block_on(receiver).unwrap();
insta::assert_yaml_snapshot!("change_txt_file_patch", rm.redacted_yaml(result));
insta::assert_yaml_snapshot!("change_txt_file_after", view_tree(&session.tree(), &mut rm));
}
#[test]
fn change_script_meta() {
let mut imfs = InMemoryFs::new();
imfs.load_snapshot(
"/root",
VfsSnapshot::dir(hashmap! {
"test.lua" => VfsSnapshot::file("This is a test."),
"test.meta.json" => VfsSnapshot::file(r#"{ "ignoreUnknownInstances": true }"#),
}),
)
.unwrap();
let vfs = Vfs::new(imfs.clone());
let session = ServeSession::new(vfs, "/root");
let mut rm = RedactionMap::new();
insta::assert_yaml_snapshot!(
"change_script_meta_before",
view_tree(&session.tree(), &mut rm)
);
imfs.load_snapshot(
"/root/test.meta.json",
VfsSnapshot::file(r#"{ "ignoreUnknownInstances": false }"#),
)
.unwrap();
let receiver = session.message_queue().subscribe_any();
imfs.raise_event(VfsEvent::Write(PathBuf::from("/root/test.meta.json")));
let receiver = Timeout::new(receiver, Duration::from_millis(200));
let mut rt = Runtime::new().unwrap();
let result = rt.block_on(receiver).unwrap();
insta::assert_yaml_snapshot!("change_script_meta_patch", rm.redacted_yaml(result));
insta::assert_yaml_snapshot!(
"change_script_meta_after",
view_tree(&session.tree(), &mut rm)
);
}
#[test]
fn change_file_in_project() {
let mut imfs = InMemoryFs::new();
imfs.load_snapshot(
"/foo",
VfsSnapshot::dir(hashmap! {
"default.project.json" => VfsSnapshot::file(r#"
{
"name": "change_file_in_project",
"tree": {
"$className": "Folder",
"Child": {
"$path": "file.txt"
}
}
}
"#),
"file.txt" => VfsSnapshot::file("initial content"),
}),
)
.unwrap();
let vfs = Vfs::new(imfs.clone());
let session = ServeSession::new(vfs, "/foo");
let mut rm = RedactionMap::new();
insta::assert_yaml_snapshot!(
"change_file_in_project_before",
view_tree(&session.tree(), &mut rm)
);
imfs.load_snapshot("/foo/file.txt", VfsSnapshot::file("Changed!"))
.unwrap();
let receiver = session.message_queue().subscribe_any();
imfs.raise_event(VfsEvent::Write(PathBuf::from("/foo/file.txt")));
let receiver = Timeout::new(receiver, Duration::from_millis(200));
let mut rt = Runtime::new().unwrap();
let result = rt.block_on(receiver).unwrap();
insta::assert_yaml_snapshot!("change_file_in_project_patch", rm.redacted_yaml(result));
insta::assert_yaml_snapshot!(
"change_file_in_project_after",
view_tree(&session.tree(), &mut rm)
);
}
}