plexus_core/plexus/context.rs
1//! Global Plexus RPC context for sharing state with activations
2//!
3//! This module provides a thread-safe way to share the Plexus RPC server hash
4//! with all activations. The hash is set once during hub initialization
5//! and can be read by any activation when creating stream items.
6
7use std::sync::RwLock;
8
9/// Global Plexus RPC context: the hash set once at the service's start
10/// (NEST-15: and moved when that service's root changes while it serves).
11static PLEXUS_CONTEXT: RwLock<Option<String>> = RwLock::new(None);
12
13/// Shared Plexus RPC context accessible to all activations
14#[derive(Debug, Clone)]
15pub struct PlexusContext {
16 /// Hash of all activations for cache invalidation
17 pub hash: String,
18}
19
20impl PlexusContext {
21 /// Initialize the global Plexus RPC context
22 ///
23 /// This should be called once during hub initialization.
24 /// Subsequent calls will be ignored.
25 pub fn init(hash: String) {
26 let mut ctx = PLEXUS_CONTEXT.write().unwrap_or_else(|p| p.into_inner());
27 if ctx.is_none() {
28 *ctx = Some(hash);
29 }
30 }
31
32 /// NEST-15: the service whose hash was `from` now serves `to` (its
33 /// root's table changed): items carry `to` from now on. A hash another
34 /// service set is left as it is.
35 pub(crate) fn moved(from: &str, to: &str) {
36 let mut ctx = PLEXUS_CONTEXT.write().unwrap_or_else(|p| p.into_inner());
37 if ctx.as_deref() == Some(from) {
38 *ctx = Some(to.to_string());
39 }
40 }
41
42 /// Get the global Plexus RPC server hash
43 ///
44 /// Returns an empty string if the context hasn't been initialized yet.
45 pub fn hash() -> String {
46 PLEXUS_CONTEXT.read().unwrap_or_else(|p| p.into_inner()).clone().unwrap_or_default()
47 }
48}