vortex_session/
session.rs1use std::any::TypeId;
33use std::any::type_name;
34use std::fmt::Debug;
35use std::fmt::Formatter;
36use std::hash::BuildHasherDefault;
37use std::marker::PhantomData;
38use std::ops::Deref;
39use std::ops::DerefMut;
40use std::sync::Arc;
41
42use arc_swap::Guard;
43use vortex_error::VortexExpect;
44use vortex_error::vortex_panic;
45use vortex_utils::aliases::hash_map::HashMap;
46
47use crate::ArcSwapMap;
48use crate::IdHasher;
49use crate::SessionExt;
50use crate::SessionVar;
51use crate::UnknownPluginPolicy;
52
53pub trait VortexSessionVar: SessionVar {}
63
64impl<V: SessionVar + Clone> VortexSessionVar for V {}
65
66type IdHashBuilder = BuildHasherDefault<IdHasher>;
68
69type SessionVars = HashMap<TypeId, Arc<dyn VortexSessionVar>, IdHashBuilder>;
71
72type SharedSessionVars = ArcSwapMap<TypeId, Arc<dyn VortexSessionVar>, IdHashBuilder>;
74
75pub struct SessionGuard<'a, V> {
84 snapshot: Guard<Arc<SessionVars>>,
85 _session: PhantomData<&'a VortexSession>,
86 _marker: PhantomData<fn() -> V>,
87}
88
89impl<V: VortexSessionVar> Deref for SessionGuard<'_, V> {
90 type Target = V;
91
92 fn deref(&self) -> &V {
93 self.snapshot
95 .get(&TypeId::of::<V>())
96 .vortex_expect("SessionGuard invariant: variable present in snapshot")
97 .as_any()
98 .downcast_ref::<V>()
99 .vortex_expect("Type mismatch - this is a bug")
100 }
101}
102
103impl<V: VortexSessionVar> Debug for SessionGuard<'_, V> {
104 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
105 Debug::fmt(&**self, f)
106 }
107}
108
109pub struct SessionMut<'a, V: VortexSessionVar> {
118 session: &'a VortexSession,
119 value: Option<V>,
121}
122
123impl<V: VortexSessionVar> Deref for SessionMut<'_, V> {
124 type Target = V;
125
126 fn deref(&self) -> &V {
127 self.value
128 .as_ref()
129 .vortex_expect("SessionMut invariant: value present until drop")
130 }
131}
132
133impl<V: VortexSessionVar> DerefMut for SessionMut<'_, V> {
134 fn deref_mut(&mut self) -> &mut V {
135 self.value
136 .as_mut()
137 .vortex_expect("SessionMut invariant: value present until drop")
138 }
139}
140
141impl<V: VortexSessionVar> Drop for SessionMut<'_, V> {
142 fn drop(&mut self) {
143 if let Some(value) = self.value.take() {
144 self.session.register(value);
145 }
146 }
147}
148
149impl<V: VortexSessionVar> Debug for SessionMut<'_, V> {
150 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
151 Debug::fmt(&**self, f)
152 }
153}
154
155#[derive(Clone)]
164pub struct VortexSession(SharedSessionVars);
165
166impl Debug for VortexSession {
167 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
168 self.0
169 .read(|vars| f.debug_tuple("VortexSession").field(vars).finish())
170 }
171}
172
173impl VortexSession {
174 pub fn empty() -> Self {
176 Self(SharedSessionVars::default())
177 }
178
179 pub fn register<V: VortexSessionVar>(&self, var: V) {
188 self.0.insert(TypeId::of::<V>(), Arc::new(var));
189 }
190
191 pub fn with<V: VortexSessionVar + Default>(self) -> Self {
201 self.with_some(V::default())
202 }
203
204 pub fn with_some<V: VortexSessionVar>(self, var: V) -> Self {
214 if !self.0.insert_if_absent(TypeId::of::<V>(), Arc::new(var)) {
215 vortex_panic!(
216 "Session variable of type {} already exists",
217 type_name::<V>()
218 );
219 }
220 self
221 }
222
223 pub fn allows_unknown(&self) -> bool {
225 self.get_opt::<UnknownPluginPolicy>()
226 .is_some_and(|p| p.allow_unknown)
227 }
228
229 pub fn allow_unknown(&self) {
233 self.get_mut::<UnknownPluginPolicy>().allow_unknown = true;
234 }
235}
236
237impl SessionExt for VortexSession {
238 fn session(&self) -> VortexSession {
239 self.clone()
240 }
241
242 fn get<V: VortexSessionVar + Default>(&self) -> SessionGuard<'_, V> {
243 self.get_or_insert_with(V::default)
244 }
245
246 fn get_or_insert_with<V: VortexSessionVar>(
247 &self,
248 init: impl FnOnce() -> V,
249 ) -> SessionGuard<'_, V> {
250 if let Some(var) = self.get_opt::<V>() {
251 return var;
252 }
253
254 let var: Arc<dyn VortexSessionVar> = Arc::new(init());
257 self.0.insert_if_absent(TypeId::of::<V>(), var);
258
259 self.get_opt::<V>()
260 .vortex_expect("a variable of type `V` is present after `insert_if_absent`")
261 }
262
263 fn get_opt<V: VortexSessionVar>(&self) -> Option<SessionGuard<'_, V>> {
264 let snapshot = self.0.load();
265 snapshot
266 .contains_key(&TypeId::of::<V>())
267 .then(|| SessionGuard {
268 snapshot,
269 _session: PhantomData,
270 _marker: PhantomData,
271 })
272 }
273
274 fn get_mut<V: VortexSessionVar + Default + Clone>(&self) -> SessionMut<'_, V> {
275 let value = (*self.get::<V>()).clone();
276 SessionMut {
277 session: self,
278 value: Some(value),
279 }
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use std::any::Any;
286 use std::panic::AssertUnwindSafe;
287 use std::panic::catch_unwind;
288 use std::sync::Barrier;
289 use std::thread;
290
291 use super::VortexSession;
292 use crate::SessionExt;
293 use crate::SessionVar;
294
295 #[derive(Clone, Debug, Default, PartialEq, Eq)]
296 struct Counter {
297 count: u32,
298 }
299
300 impl SessionVar for Counter {
301 fn as_any(&self) -> &dyn Any {
302 self
303 }
304
305 fn as_any_mut(&mut self) -> &mut dyn Any {
306 self
307 }
308 }
309
310 #[derive(Clone, Debug, Default)]
311 struct Other;
312
313 impl SessionVar for Other {
314 fn as_any(&self) -> &dyn Any {
315 self
316 }
317
318 fn as_any_mut(&mut self) -> &mut dyn Any {
319 self
320 }
321 }
322
323 thread_local! {
324 static REENTRANT_SESSION: std::cell::RefCell<Option<VortexSession>> =
326 const { std::cell::RefCell::new(None) };
327 }
328
329 #[derive(Clone, Debug)]
330 struct Reentrant {
331 inner: u32,
332 }
333
334 impl Default for Reentrant {
335 fn default() -> Self {
336 REENTRANT_SESSION.with(|s| {
341 if let Some(session) = s.borrow().as_ref() {
342 drop(session.get::<Counter>());
343 }
344 });
345 Reentrant { inner: 7 }
346 }
347 }
348
349 impl SessionVar for Reentrant {
350 fn as_any(&self) -> &dyn Any {
351 self
352 }
353
354 fn as_any_mut(&mut self) -> &mut dyn Any {
355 self
356 }
357 }
358
359 #[test]
360 fn with_some_round_trip() {
361 let session = VortexSession::empty().with_some(Counter { count: 1 });
362
363 assert_eq!(*session.get::<Counter>(), Counter { count: 1 });
364 assert!(session.get_opt::<Other>().is_none());
365 }
366
367 #[test]
368 fn get_inserts_default() {
369 let session = VortexSession::empty();
370 assert!(session.get_opt::<Counter>().is_none());
371
372 assert_eq!(session.get::<Counter>().count, 0);
373 assert!(session.get_opt::<Counter>().is_some());
375 }
376
377 #[test]
378 fn get_or_insert_with_inserts_only_when_absent() {
379 let session = VortexSession::empty();
380
381 assert_eq!(session.get_or_insert_with(|| Counter { count: 3 }).count, 3);
382 assert_eq!(
383 session
384 .get_or_insert_with::<Counter>(|| panic!("the variable is already present"))
385 .count,
386 3
387 );
388 }
389
390 #[test]
391 fn register_is_visible_through_clones() {
392 let session = VortexSession::empty();
393 let clone = session.clone();
394
395 session.register(Counter { count: 7 });
396
397 assert_eq!(clone.get::<Counter>().count, 7);
399 }
400
401 #[test]
402 fn with_some_mutates_shared_store() {
403 let session = VortexSession::empty();
404 let clone = session.clone();
405
406 let configured = session.with_some(Counter { count: 5 });
407 assert_eq!(configured.get::<Counter>().count, 5);
408
409 assert_eq!(clone.get::<Counter>().count, 5);
411 }
412
413 #[test]
414 fn allow_unknown_mutates_shared_store() {
415 let session = VortexSession::empty();
416 let clone = session.clone();
417 assert!(!clone.allows_unknown());
418
419 session.allow_unknown();
420
421 assert!(clone.allows_unknown());
423 }
424
425 #[test]
426 fn empty_sessions_are_independent() {
427 let session = VortexSession::empty().with_some(Counter { count: 1 });
430 let other = VortexSession::empty().with_some(Counter { count: 2 });
431
432 session.register(Counter { count: 9 });
433 assert_eq!(session.get::<Counter>().count, 9);
434 assert_eq!(other.get::<Counter>().count, 2);
435 }
436
437 #[test]
438 #[should_panic(expected = "already exists")]
439 fn with_some_duplicate_panics() {
440 VortexSession::empty()
441 .with::<Counter>()
442 .with_some(Counter { count: 1 });
443 }
444
445 #[test]
446 fn get_opt_does_not_insert_a_default() {
447 let session = VortexSession::empty();
448
449 assert!(session.get_opt::<Counter>().is_none());
451 assert!(session.get_opt::<Counter>().is_none());
452 }
453
454 #[test]
455 fn inserting_a_default_while_holding_a_guard_succeeds() {
456 let session = VortexSession::empty().with_some(Counter { count: 5 });
457
458 let counter = session.get::<Counter>();
460
461 let other = session.get::<Other>();
465
466 assert_eq!(counter.count, 5);
469 let _: &Other = &other;
470
471 assert!(session.get_opt::<Other>().is_some());
473 }
474
475 #[test]
476 fn a_held_guard_keeps_observing_its_own_snapshot_after_a_write() {
477 let session = VortexSession::empty().with_some(Counter { count: 1 });
478
479 let held = session.get::<Counter>();
480 session.register(Counter { count: 2 });
481
482 assert_eq!(held.count, 1);
485 assert_eq!(session.get::<Counter>().count, 2);
486 }
487
488 #[test]
489 fn default_insertion_may_reenter_the_session_without_deadlocking() {
490 let session = VortexSession::empty();
491 REENTRANT_SESSION.with(|s| *s.borrow_mut() = Some(session.clone()));
492
493 assert_eq!(session.get::<Reentrant>().inner, 7);
497 assert!(session.get_opt::<Reentrant>().is_some());
498 assert!(session.get_opt::<Counter>().is_some());
499
500 REENTRANT_SESSION.with(|s| *s.borrow_mut() = None);
501 }
502
503 #[test]
504 fn get_mut_inserts_default_then_mutates() {
505 let session = VortexSession::empty();
506 assert!(session.get_opt::<Counter>().is_none());
507
508 session.get_mut::<Counter>().count += 5;
509
510 assert_eq!(session.get::<Counter>().count, 5);
511 }
512
513 #[test]
514 fn get_mut_mutation_is_visible_through_clones() {
515 let session = VortexSession::empty().with_some(Counter { count: 1 });
516 let clone = session.clone();
517
518 session.get_mut::<Counter>().count = 9;
519
520 assert_eq!(clone.get::<Counter>().count, 9);
522 }
523
524 #[test]
525 fn concurrent_with_some_same_type_allows_only_one_winner() {
526 for _ in 0..200 {
527 let session = VortexSession::empty();
528 let clone_a = session.clone();
529 let clone_b = session.clone();
530 let barrier = Barrier::new(2);
531
532 let (res_a, res_b) = thread::scope(|s| {
533 let h_a = s.spawn(|| {
534 barrier.wait();
535 catch_unwind(AssertUnwindSafe(|| clone_a.with_some(Counter { count: 1 })))
536 });
537 let h_b = s.spawn(|| {
538 barrier.wait();
539 catch_unwind(AssertUnwindSafe(|| clone_b.with_some(Counter { count: 2 })))
540 });
541 (h_a.join().unwrap(), h_b.join().unwrap())
542 });
543
544 let (winner, loser, expected) = match (res_a, res_b) {
545 (Ok(winner), Err(panic)) => (winner, panic, 1),
546 (Err(panic), Ok(winner)) => (winner, panic, 2),
547 (Ok(_), Ok(_)) => {
548 panic!("both concurrent with_some calls succeeded for same type")
549 }
550 (Err(_), Err(_)) => {
551 panic!("both concurrent with_some calls panicked for same type")
552 }
553 };
554 let msg = loser
555 .downcast_ref::<String>()
556 .map(String::as_str)
557 .or_else(|| loser.downcast_ref::<&str>().copied())
558 .unwrap_or("");
559 assert!(msg.contains("already exists"), "unexpected panic: {msg}");
560 assert_eq!(winner.get::<Counter>().count, expected);
561 assert_eq!(session.get::<Counter>().count, expected);
562 }
563 }
564}