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::sync::Arc;
40
41use arc_swap::Guard;
42use vortex_error::VortexExpect;
43use vortex_error::vortex_panic;
44use vortex_utils::aliases::hash_map::HashMap;
45
46use crate::ArcSwapMap;
47use crate::IdHasher;
48use crate::SessionExt;
49use crate::SessionVar;
50use crate::UnknownPluginPolicy;
51
52pub trait VortexSessionVar: SessionVar {}
58
59impl<V: SessionVar> VortexSessionVar for V {}
60
61type IdHashBuilder = BuildHasherDefault<IdHasher>;
63
64type SessionVars = HashMap<TypeId, Arc<dyn VortexSessionVar>, IdHashBuilder>;
66
67type SharedSessionVars = ArcSwapMap<TypeId, Arc<dyn VortexSessionVar>, IdHashBuilder>;
69
70pub struct SessionGuard<'a, V> {
79 snapshot: Guard<Arc<SessionVars>>,
80 _session: PhantomData<&'a VortexSession>,
81 _marker: PhantomData<fn() -> V>,
82}
83
84impl<V: VortexSessionVar> Deref for SessionGuard<'_, V> {
85 type Target = V;
86
87 fn deref(&self) -> &V {
88 self.snapshot
90 .get(&TypeId::of::<V>())
91 .vortex_expect("SessionGuard invariant: variable present in snapshot")
92 .as_any()
93 .downcast_ref::<V>()
94 .vortex_expect("Type mismatch - this is a bug")
95 }
96}
97
98impl<V: VortexSessionVar> Debug for SessionGuard<'_, V> {
99 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
100 Debug::fmt(&**self, f)
101 }
102}
103
104#[derive(Clone)]
113pub struct VortexSession(SharedSessionVars);
114
115impl Debug for VortexSession {
116 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117 self.0
118 .read(|vars| f.debug_tuple("VortexSession").field(vars).finish())
119 }
120}
121
122impl VortexSession {
123 pub fn empty() -> Self {
125 Self(SharedSessionVars::default())
126 }
127
128 pub fn register<V: VortexSessionVar>(&self, var: V) {
139 self.0.insert(TypeId::of::<V>(), Arc::new(var));
140 }
141
142 pub fn with<V: VortexSessionVar + Default>(self) -> Self {
152 self.with_some(V::default())
153 }
154
155 pub fn with_some<V: VortexSessionVar>(self, var: V) -> Self {
165 if !self.0.insert_if_absent(TypeId::of::<V>(), Arc::new(var)) {
166 vortex_panic!(
167 "Session variable of type {} already exists",
168 type_name::<V>()
169 );
170 }
171 self
172 }
173
174 pub fn allows_unknown(&self) -> bool {
176 self.get_opt::<UnknownPluginPolicy>()
177 .is_some_and(|p| p.allow_unknown)
178 }
179
180 pub fn allow_unknown(&self) {
184 self.register(UnknownPluginPolicy {
185 allow_unknown: true,
186 });
187 }
188}
189
190impl SessionExt for VortexSession {
191 fn session(&self) -> VortexSession {
192 self.clone()
193 }
194
195 fn get<V: VortexSessionVar + Default>(&self) -> SessionGuard<'_, V> {
196 self.get_or_insert_with(V::default)
197 }
198
199 fn get_or_insert_with<V: VortexSessionVar>(
200 &self,
201 init: impl FnOnce() -> V,
202 ) -> SessionGuard<'_, V> {
203 if let Some(var) = self.get_opt::<V>() {
204 return var;
205 }
206
207 let var: Arc<dyn VortexSessionVar> = Arc::new(init());
210 self.0.insert_if_absent(TypeId::of::<V>(), var);
211
212 self.get_opt::<V>()
213 .vortex_expect("a variable of type `V` is present after `insert_if_absent`")
214 }
215
216 fn get_opt<V: VortexSessionVar>(&self) -> Option<SessionGuard<'_, V>> {
217 let snapshot = self.0.load();
218 snapshot
219 .contains_key(&TypeId::of::<V>())
220 .then(|| SessionGuard {
221 snapshot,
222 _session: PhantomData,
223 _marker: PhantomData,
224 })
225 }
226}
227
228#[cfg(test)]
229mod tests {
230 use std::any::Any;
231 use std::panic::AssertUnwindSafe;
232 use std::panic::catch_unwind;
233 use std::sync::Barrier;
234 use std::thread;
235
236 use super::VortexSession;
237 use crate::SessionExt;
238 use crate::SessionVar;
239
240 #[derive(Clone, Debug, Default, PartialEq, Eq)]
241 struct Counter {
242 count: u32,
243 }
244
245 impl SessionVar for Counter {
246 fn as_any(&self) -> &dyn Any {
247 self
248 }
249
250 fn as_any_mut(&mut self) -> &mut dyn Any {
251 self
252 }
253 }
254
255 #[derive(Debug, Default)]
256 struct NonClone {
257 count: u32,
258 }
259
260 impl SessionVar for NonClone {
261 fn as_any(&self) -> &dyn Any {
262 self
263 }
264
265 fn as_any_mut(&mut self) -> &mut dyn Any {
266 self
267 }
268 }
269
270 #[derive(Clone, Debug, Default)]
271 struct Other;
272
273 impl SessionVar for Other {
274 fn as_any(&self) -> &dyn Any {
275 self
276 }
277
278 fn as_any_mut(&mut self) -> &mut dyn Any {
279 self
280 }
281 }
282
283 thread_local! {
284 static REENTRANT_SESSION: std::cell::RefCell<Option<VortexSession>> =
286 const { std::cell::RefCell::new(None) };
287 }
288
289 #[derive(Clone, Debug)]
290 struct Reentrant {
291 inner: u32,
292 }
293
294 impl Default for Reentrant {
295 fn default() -> Self {
296 REENTRANT_SESSION.with(|s| {
301 if let Some(session) = s.borrow().as_ref() {
302 drop(session.get::<Counter>());
303 }
304 });
305 Reentrant { inner: 7 }
306 }
307 }
308
309 impl SessionVar for Reentrant {
310 fn as_any(&self) -> &dyn Any {
311 self
312 }
313
314 fn as_any_mut(&mut self) -> &mut dyn Any {
315 self
316 }
317 }
318
319 #[test]
320 fn with_some_round_trip() {
321 let session = VortexSession::empty().with_some(Counter { count: 1 });
322
323 assert_eq!(*session.get::<Counter>(), Counter { count: 1 });
324 assert!(session.get_opt::<Other>().is_none());
325 }
326
327 #[test]
328 fn test_non_clone_session_var_can_be_registered_and_read() {
329 let session = VortexSession::empty().with_some(NonClone { count: 3 });
330
331 assert_eq!(session.get::<NonClone>().count, 3);
332 }
333
334 #[test]
335 fn get_inserts_default() {
336 let session = VortexSession::empty();
337 assert!(session.get_opt::<Counter>().is_none());
338
339 assert_eq!(session.get::<Counter>().count, 0);
340 assert!(session.get_opt::<Counter>().is_some());
342 }
343
344 #[test]
345 fn get_or_insert_with_inserts_only_when_absent() {
346 let session = VortexSession::empty();
347
348 assert_eq!(session.get_or_insert_with(|| Counter { count: 3 }).count, 3);
349 assert_eq!(
350 session
351 .get_or_insert_with::<Counter>(|| panic!("the variable is already present"))
352 .count,
353 3
354 );
355 }
356
357 #[test]
358 fn register_is_visible_through_clones() {
359 let session = VortexSession::empty();
360 let clone = session.clone();
361
362 session.register(Counter { count: 7 });
363
364 assert_eq!(clone.get::<Counter>().count, 7);
366 }
367
368 #[test]
369 fn with_some_mutates_shared_store() {
370 let session = VortexSession::empty();
371 let clone = session.clone();
372
373 let configured = session.with_some(Counter { count: 5 });
374 assert_eq!(configured.get::<Counter>().count, 5);
375
376 assert_eq!(clone.get::<Counter>().count, 5);
378 }
379
380 #[test]
381 fn allow_unknown_mutates_shared_store() {
382 let session = VortexSession::empty();
383 let clone = session.clone();
384 assert!(!clone.allows_unknown());
385
386 session.allow_unknown();
387
388 assert!(clone.allows_unknown());
390 }
391
392 #[test]
393 fn empty_sessions_are_independent() {
394 let session = VortexSession::empty().with_some(Counter { count: 1 });
397 let other = VortexSession::empty().with_some(Counter { count: 2 });
398
399 session.register(Counter { count: 9 });
400 assert_eq!(session.get::<Counter>().count, 9);
401 assert_eq!(other.get::<Counter>().count, 2);
402 }
403
404 #[test]
405 #[should_panic(expected = "already exists")]
406 fn with_some_duplicate_panics() {
407 VortexSession::empty()
408 .with::<Counter>()
409 .with_some(Counter { count: 1 });
410 }
411
412 #[test]
413 fn get_opt_does_not_insert_a_default() {
414 let session = VortexSession::empty();
415
416 assert!(session.get_opt::<Counter>().is_none());
418 assert!(session.get_opt::<Counter>().is_none());
419 }
420
421 #[test]
422 fn inserting_a_default_while_holding_a_guard_succeeds() {
423 let session = VortexSession::empty().with_some(Counter { count: 5 });
424
425 let counter = session.get::<Counter>();
427
428 let other = session.get::<Other>();
432
433 assert_eq!(counter.count, 5);
436 let _: &Other = &other;
437
438 assert!(session.get_opt::<Other>().is_some());
440 }
441
442 #[test]
443 fn a_held_guard_keeps_observing_its_own_snapshot_after_a_write() {
444 let session = VortexSession::empty().with_some(Counter { count: 1 });
445
446 let held = session.get::<Counter>();
447 session.register(Counter { count: 2 });
448
449 assert_eq!(held.count, 1);
452 assert_eq!(session.get::<Counter>().count, 2);
453 }
454
455 #[test]
456 fn default_insertion_may_reenter_the_session_without_deadlocking() {
457 let session = VortexSession::empty();
458 REENTRANT_SESSION.with(|s| *s.borrow_mut() = Some(session.clone()));
459
460 assert_eq!(session.get::<Reentrant>().inner, 7);
464 assert!(session.get_opt::<Reentrant>().is_some());
465 assert!(session.get_opt::<Counter>().is_some());
466
467 REENTRANT_SESSION.with(|s| *s.borrow_mut() = None);
468 }
469
470 #[test]
471 fn concurrent_with_some_same_type_allows_only_one_winner() {
472 for _ in 0..200 {
473 let session = VortexSession::empty();
474 let clone_a = session.clone();
475 let clone_b = session.clone();
476 let barrier = Barrier::new(2);
477
478 let (res_a, res_b) = thread::scope(|s| {
479 let h_a = s.spawn(|| {
480 barrier.wait();
481 catch_unwind(AssertUnwindSafe(|| clone_a.with_some(Counter { count: 1 })))
482 });
483 let h_b = s.spawn(|| {
484 barrier.wait();
485 catch_unwind(AssertUnwindSafe(|| clone_b.with_some(Counter { count: 2 })))
486 });
487 (h_a.join().unwrap(), h_b.join().unwrap())
488 });
489
490 let (winner, loser, expected) = match (res_a, res_b) {
491 (Ok(winner), Err(panic)) => (winner, panic, 1),
492 (Err(panic), Ok(winner)) => (winner, panic, 2),
493 (Ok(_), Ok(_)) => {
494 panic!("both concurrent with_some calls succeeded for same type")
495 }
496 (Err(_), Err(_)) => {
497 panic!("both concurrent with_some calls panicked for same type")
498 }
499 };
500 let msg = loser
501 .downcast_ref::<String>()
502 .map(String::as_str)
503 .or_else(|| loser.downcast_ref::<&str>().copied())
504 .unwrap_or("");
505 assert!(msg.contains("already exists"), "unexpected panic: {msg}");
506 assert_eq!(winner.get::<Counter>().count, expected);
507 assert_eq!(session.get::<Counter>().count, expected);
508 }
509 }
510}