1use bevy_app::{App, AppExit, Last, Plugin, PreUpdate};
3use bevy_ecs::prelude::*;
4use std::{
5 marker::PhantomData,
6 sync::{Arc, Mutex},
7};
8use synctick::{CommandSender, SessionControl, SessionHandle, SessionResult, SessionStatus};
9
10#[derive(Resource)]
12pub struct SessionCommands<C: Send + Sync + 'static>(pub CommandSender<C>);
13#[derive(Resource, Clone)]
15pub struct SessionState(pub Arc<SessionStatus>);
16#[derive(Resource, Clone)]
18pub struct SessionCancellation(pub SessionControl);
19
20struct SessionSlot<C> {
21 handle: Option<SessionHandle<C>>,
22 result: Arc<SessionResult>,
23 generation: u64,
24}
25impl<C> SessionSlot<C> {
26 fn shutdown(&mut self) -> Arc<SessionResult> {
27 if let Some(handle) = &mut self.handle {
28 self.result = handle.shutdown();
29 }
30 self.result.clone()
31 }
32}
33struct OwnedSession<C> {
34 slot: Mutex<SessionSlot<C>>,
35}
36impl<C> Drop for OwnedSession<C> {
37 fn drop(&mut self) {
38 self.slot
39 .get_mut()
40 .unwrap_or_else(std::sync::PoisonError::into_inner)
41 .shutdown();
42 }
43}
44
45#[derive(Resource)]
50pub struct SessionController<C: Send + Sync + 'static> {
51 worker: Arc<OwnedSession<C>>,
52}
53impl<C: Send + Sync + 'static> SessionController<C> {
54 pub fn attach(&self, handle: SessionHandle<C>) -> SessionResult {
59 let mut slot = self
60 .worker
61 .slot
62 .lock()
63 .unwrap_or_else(std::sync::PoisonError::into_inner);
64 if slot.handle.is_some() {
65 return Err(synctick::SessionError::Configuration(
66 "session slot is occupied; detach it first".into(),
67 ));
68 }
69 slot.handle = Some(handle);
70 slot.result = Arc::new(Ok(()));
71 slot.generation = slot.generation.wrapping_add(1);
72 drop(slot);
73 Ok(())
74 }
75
76 pub fn detach(&self) -> Arc<SessionResult> {
79 let mut slot = self
80 .worker
81 .slot
82 .lock()
83 .unwrap_or_else(std::sync::PoisonError::into_inner);
84 let result = slot.shutdown();
85 if slot.handle.take().is_some() {
86 slot.generation = slot.generation.wrapping_add(1);
87 }
88 result
89 }
90}
91
92pub struct SessionGuard<C> {
95 worker: Arc<OwnedSession<C>>,
96}
97impl<C> SessionGuard<C> {
98 pub fn shutdown(&self) -> Arc<SessionResult> {
101 self.worker
102 .slot
103 .lock()
104 .unwrap_or_else(std::sync::PoisonError::into_inner)
105 .shutdown()
106 }
107}
108impl<C> Drop for SessionGuard<C> {
109 fn drop(&mut self) {
110 self.shutdown();
111 }
112}
113
114pub struct SessionPlugin<C: Send + Sync + 'static> {
119 worker: Arc<OwnedSession<C>>,
120 marker: PhantomData<fn(C)>,
121}
122impl<C: Send + Sync + 'static> SessionPlugin<C> {
123 #[must_use]
125 pub fn new(handle: SessionHandle<C>) -> (Self, SessionGuard<C>) {
126 Self::from_handle(Some(handle))
127 }
128
129 #[must_use]
133 pub fn idle() -> (Self, SessionGuard<C>) {
134 Self::from_handle(None)
135 }
136
137 fn from_handle(handle: Option<SessionHandle<C>>) -> (Self, SessionGuard<C>) {
138 let worker = Arc::new(OwnedSession {
139 slot: Mutex::new(SessionSlot {
140 handle,
141 result: Arc::new(Ok(())),
142 generation: 0,
143 }),
144 });
145 (
146 Self {
147 worker: worker.clone(),
148 marker: PhantomData,
149 },
150 SessionGuard { worker },
151 )
152 }
153}
154impl<C: Send + Sync + 'static> Plugin for SessionPlugin<C> {
155 fn build(&self, app: &mut App) {
156 let slot = self
157 .worker
158 .slot
159 .lock()
160 .unwrap_or_else(std::sync::PoisonError::into_inner);
161 let status = slot.handle.as_ref().map_or_else(
162 || Arc::new(SessionStatus::Stopped),
163 |handle| {
164 app.insert_resource(SessionCommands(handle.commands()));
165 app.insert_resource(SessionCancellation(handle.control()));
166 handle.status()
167 },
168 );
169 app.insert_resource(SessionState(status));
170 drop(slot);
171 app.insert_resource(SessionController {
172 worker: self.worker.clone(),
173 });
174 app.add_systems(PreUpdate, observe::<C>);
175 app.add_systems(Last, cancel_on_exit);
176 }
177}
178fn observe<C: Send + Sync + 'static>(
179 controller: Res<SessionController<C>>,
180 mut state: ResMut<SessionState>,
181 mut commands: Commands,
182 mut generation: Local<Option<u64>>,
183) {
184 let mut slot = controller
185 .worker
186 .slot
187 .lock()
188 .unwrap_or_else(std::sync::PoisonError::into_inner);
189 if let Some(handle) = &mut slot.handle {
190 handle.poll();
191 state.0 = handle.status();
192 } else {
193 state.0 = Arc::new(match &*slot.result {
194 Ok(()) => SessionStatus::Stopped,
195 Err(error) => SessionStatus::Failed(error.to_string()),
196 });
197 }
198 if *generation != Some(slot.generation) {
199 if let Some(handle) = &slot.handle {
200 commands.insert_resource(SessionCommands(handle.commands()));
201 commands.insert_resource(SessionCancellation(handle.control()));
202 } else {
203 commands.remove_resource::<SessionCommands<C>>();
204 commands.remove_resource::<SessionCancellation>();
205 }
206 *generation = Some(slot.generation);
207 }
208}
209fn cancel_on_exit(mut exit: MessageReader<AppExit>, control: Option<Res<SessionCancellation>>) {
210 if exit.read().next().is_some()
211 && let Some(control) = control
212 {
213 control.0.cancel();
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use crate::{BevyGame, BevySimulation, GameAdapter, test_game::Example};
221 use std::{
222 sync::atomic::Ordering,
223 thread,
224 time::{Duration, Instant},
225 };
226 use synctick::{Game, ServerConfig, SessionStatus};
227 #[test]
228 fn guard_joins_even_when_the_app_and_plugin_still_own_the_worker() {
229 let game = Example::default();
230 let observed = game.published.clone();
231 let mut cfg = ServerConfig::new(());
232 cfg.port = 0;
233 let handle = synctick::host(GameAdapter(game), cfg).unwrap();
234 let control = handle.control();
235 let (plugin, guard) = SessionPlugin::new(handle);
236 let mut app = App::new();
237 app.add_plugins(plugin);
238 let deadline = Instant::now() + Duration::from_secs(5);
239 while observed.load(Ordering::Acquire) == 0 {
240 assert!(Instant::now() < deadline);
241 app.update();
242 thread::sleep(Duration::from_millis(1));
243 }
244 drop(guard);
245 assert_eq!(*control.status(), SessionStatus::Stopped);
246 app.update();
247 assert_eq!(
248 *app.world().resource::<SessionState>().0,
249 SessionStatus::Stopped
250 );
251 assert!(matches!(
252 app.world().resource::<SessionCommands<()>>().0.submit(&()),
253 Err(synctick::SubmitError::Stopped)
254 ));
255 }
256 #[test]
257 fn guard_exposes_typed_worker_failure_after_plugin_takes_handle() {
258 struct Fails;
259 impl Game for Fails {
260 type Command = ();
261 type Initialization = ();
262 type Simulation = BevySimulation<Example>;
263 const ID: [u8; 16] = Example::ID;
264 const VERSION: u32 = 1;
265 fn create(&self, (): (), _: Duration) -> SessionResult<Self::Simulation> {
266 Err(synctick::SessionError::Simulation(
267 "initialization failed".into(),
268 ))
269 }
270 }
271 let mut cfg = ServerConfig::new(());
272 cfg.port = 0;
273 let (plugin, guard) = SessionPlugin::new(synctick::host(Fails, cfg).unwrap());
274 let mut app = App::new();
275 app.add_plugins(plugin);
276 assert!(
277 matches!(&*guard.shutdown(), Err(synctick::SessionError::Simulation(message)) if message == "initialization failed")
278 );
279 let result = app.world().resource::<SessionController<()>>().detach();
280 assert!(Arc::ptr_eq(&result, &guard.shutdown()));
281 app.update();
282 assert!(
283 matches!(&*app.world().resource::<SessionState>().0, SessionStatus::Failed(message) if message.contains("initialization failed"))
284 );
285 }
286 #[test]
287 fn idle_slot_attaches_rejects_replacement_and_can_be_reused() {
288 let (plugin, guard) = SessionPlugin::<()>::idle();
289 let mut app = App::new();
290 app.add_plugins(plugin);
291 app.update();
292 assert!(!app.world().contains_resource::<SessionCommands<()>>());
293 let make = || {
294 let mut config = ServerConfig::new(());
295 config.port = 0;
296 synctick::host(GameAdapter(Example::default()), config).unwrap()
297 };
298 let first = make();
299 let control = first.control();
300 app.world()
301 .resource::<SessionController<()>>()
302 .attach(first)
303 .unwrap();
304 app.update();
305 assert!(app.world().contains_resource::<SessionCommands<()>>());
306 let second = make();
307 let rejected = second.control();
308 assert!(
309 app.world()
310 .resource::<SessionController<()>>()
311 .attach(second)
312 .is_err()
313 );
314 assert!(rejected.is_cancelled());
315 assert!(!control.is_cancelled());
316 let result = app.world().resource::<SessionController<()>>().detach();
317 assert!(result.is_ok());
318 assert!(control.is_cancelled());
319 assert!(Arc::ptr_eq(
320 &result,
321 &app.world().resource::<SessionController<()>>().detach()
322 ));
323 app.update();
324 assert!(!app.world().contains_resource::<SessionCommands<()>>());
325 assert!(!app.world().contains_resource::<SessionCancellation>());
326 let next = make();
327 let next_control = next.control();
328 app.world()
329 .resource::<SessionController<()>>()
330 .attach(next)
331 .unwrap();
332 app.update();
333 drop(guard);
334 assert!(next_control.is_cancelled());
335 }
336}