adk_plugin/context.rs
1//! Type-safe shared state container for plugins.
2//!
3//! [`PluginContext`] uses the TypeMap pattern where each type serves as its own key,
4//! providing a type-safe, concurrent key-value store for plugin shared state.
5//!
6//! # Overview
7//!
8//! Plugins often need to share state across hook invocations within a single agent run.
9//! For example, a rate-limiting plugin tracks request counts, a caching plugin stores
10//! cached responses, and a metrics plugin accumulates statistics.
11//!
12//! `PluginContext` enables this by allowing plugins to insert and retrieve values
13//! keyed by their Rust type. Each unique type can have exactly one value stored.
14//!
15//! [`EnhancedPluginManager`](crate::EnhancedPluginManager) hands each invocation its own
16//! context, so state one user's run writes is never read by another's. State meant for every
17//! invocation of the agent goes in [`PluginContext::shared`].
18//!
19//! # Examples
20//!
21//! ```rust
22//! use adk_plugin::PluginContext;
23//!
24//! #[derive(Clone, Debug, PartialEq)]
25//! struct RequestCount(u32);
26//!
27//! #[derive(Clone, Debug, PartialEq)]
28//! struct CacheHits(u64);
29//!
30//! # #[tokio::main]
31//! # async fn main() {
32//! let ctx = PluginContext::new();
33//!
34//! // Insert typed state
35//! ctx.insert(RequestCount(0)).await;
36//! ctx.insert(CacheHits(42)).await;
37//!
38//! // Retrieve typed state
39//! let count = ctx.get::<RequestCount>().await;
40//! assert_eq!(count, Some(RequestCount(0)));
41//!
42//! // Update state (last write wins)
43//! ctx.insert(RequestCount(5)).await;
44//! let count = ctx.get::<RequestCount>().await;
45//! assert_eq!(count, Some(RequestCount(5)));
46//!
47//! // Remove state
48//! let removed = ctx.remove::<CacheHits>().await;
49//! assert_eq!(removed, Some(CacheHits(42)));
50//! assert_eq!(ctx.get::<CacheHits>().await, None);
51//! # }
52//! ```
53
54use std::any::{Any, TypeId};
55use std::collections::HashMap;
56use std::sync::Arc;
57
58use tokio::sync::RwLock;
59
60/// A type-safe, concurrent key-value store for plugin shared state.
61///
62/// Uses the TypeMap pattern where each type serves as its own key.
63/// Thread-safe via [`tokio::sync::RwLock`] for concurrent async access.
64///
65/// # Concurrency
66///
67/// - Multiple readers can access state concurrently via [`get`](Self::get) and
68/// [`contains`](Self::contains).
69/// - Writers acquire exclusive access via [`insert`](Self::insert) and
70/// [`remove`](Self::remove).
71/// - No locks are held across await points — each method acquires and releases
72/// the lock within a single operation.
73///
74/// # Examples
75///
76/// ```rust
77/// use adk_plugin::PluginContext;
78///
79/// #[derive(Clone, Debug)]
80/// struct RateLimitState {
81/// requests_this_minute: u32,
82/// }
83///
84/// # #[tokio::main]
85/// # async fn main() {
86/// let ctx = PluginContext::new();
87///
88/// // A rate-limiting plugin writes state
89/// ctx.insert(RateLimitState { requests_this_minute: 1 }).await;
90///
91/// // A metrics plugin reads it
92/// if let Some(state) = ctx.get::<RateLimitState>().await {
93/// println!("Requests: {}", state.requests_this_minute);
94/// }
95/// # }
96/// ```
97pub struct PluginContext {
98 state: RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>,
99 /// The per-agent context this invocation's context reaches through `shared()`.
100 shared: Option<Arc<PluginContext>>,
101}
102
103impl PluginContext {
104 /// Creates a new empty `PluginContext`.
105 ///
106 /// # Examples
107 ///
108 /// ```rust
109 /// use adk_plugin::PluginContext;
110 ///
111 /// let ctx = PluginContext::new();
112 /// ```
113 pub fn new() -> Self {
114 Self { state: RwLock::new(HashMap::new()), shared: None }
115 }
116
117 /// Creates an empty context for one invocation whose [`shared`](Self::shared) context is
118 /// `shared`.
119 ///
120 /// [`EnhancedPluginManager`](crate::EnhancedPluginManager) creates one per invocation
121 /// over its per-agent context; build one directly to test a plugin outside a manager.
122 /// Implements spec 3.1 §12 phase 0 (`PluginContext` per invocation).
123 ///
124 /// # Examples
125 ///
126 /// ```rust
127 /// use std::sync::Arc;
128 ///
129 /// use adk_plugin::PluginContext;
130 ///
131 /// #[derive(Clone, Debug, PartialEq)]
132 /// struct Calls(u32);
133 ///
134 /// # #[tokio::main]
135 /// # async fn main() {
136 /// let agent_wide = Arc::new(PluginContext::new());
137 /// let invocation = PluginContext::with_shared(Arc::clone(&agent_wide));
138 ///
139 /// invocation.insert(Calls(1)).await;
140 /// invocation.shared().insert(Calls(7)).await;
141 /// assert_eq!(invocation.get::<Calls>().await, Some(Calls(1)));
142 /// assert_eq!(agent_wide.get::<Calls>().await, Some(Calls(7)));
143 /// # }
144 /// ```
145 pub fn with_shared(shared: Arc<PluginContext>) -> Self {
146 Self { state: RwLock::new(HashMap::new()), shared: Some(shared) }
147 }
148
149 /// Returns the context every invocation of the agent shares.
150 ///
151 /// Hooks receive their invocation's context; state that must outlive the invocation or
152 /// be seen by other users' invocations, such as an agent-wide rate limit, goes here. A
153 /// context created with [`new`](Self::new) has no separate shared context and returns
154 /// itself. Implements spec 3.1 §12 phase 0 (`PluginContext` per invocation).
155 ///
156 /// # Examples
157 ///
158 /// ```rust
159 /// use adk_plugin::PluginContext;
160 ///
161 /// #[derive(Clone, Debug, PartialEq)]
162 /// struct Limit(u32);
163 ///
164 /// # #[tokio::main]
165 /// # async fn main() {
166 /// let ctx = PluginContext::new();
167 /// ctx.shared().insert(Limit(10)).await;
168 /// assert_eq!(ctx.get::<Limit>().await, Some(Limit(10)));
169 /// # }
170 /// ```
171 pub fn shared(&self) -> &PluginContext {
172 self.shared.as_deref().unwrap_or(self)
173 }
174
175 /// Inserts a value into the context. The type itself is the key.
176 ///
177 /// If a value of the same type already exists, it is replaced.
178 /// The previous value is discarded.
179 ///
180 /// # Examples
181 ///
182 /// ```rust
183 /// use adk_plugin::PluginContext;
184 ///
185 /// #[derive(Clone, Debug, PartialEq)]
186 /// struct Counter(u32);
187 ///
188 /// # #[tokio::main]
189 /// # async fn main() {
190 /// let ctx = PluginContext::new();
191 /// ctx.insert(Counter(1)).await;
192 /// ctx.insert(Counter(2)).await; // Replaces the previous value
193 ///
194 /// assert_eq!(ctx.get::<Counter>().await, Some(Counter(2)));
195 /// # }
196 /// ```
197 pub async fn insert<T: Send + Sync + 'static>(&self, value: T) {
198 self.state.write().await.insert(TypeId::of::<T>(), Box::new(value));
199 }
200
201 /// Gets a clone of the stored value for type `T`.
202 ///
203 /// Returns `None` if no value of type `T` has been inserted.
204 ///
205 /// # Examples
206 ///
207 /// ```rust
208 /// use adk_plugin::PluginContext;
209 ///
210 /// #[derive(Clone, Debug, PartialEq)]
211 /// struct Name(String);
212 ///
213 /// # #[tokio::main]
214 /// # async fn main() {
215 /// let ctx = PluginContext::new();
216 ///
217 /// assert_eq!(ctx.get::<Name>().await, None);
218 ///
219 /// ctx.insert(Name("alice".to_string())).await;
220 /// assert_eq!(ctx.get::<Name>().await, Some(Name("alice".to_string())));
221 /// # }
222 /// ```
223 pub async fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
224 self.state.read().await.get(&TypeId::of::<T>()).and_then(|v| v.downcast_ref::<T>()).cloned()
225 }
226
227 /// Checks if a value of type `T` exists in the context.
228 ///
229 /// # Examples
230 ///
231 /// ```rust
232 /// use adk_plugin::PluginContext;
233 ///
234 /// #[derive(Clone, Debug)]
235 /// struct Marker;
236 ///
237 /// # #[tokio::main]
238 /// # async fn main() {
239 /// let ctx = PluginContext::new();
240 ///
241 /// assert!(!ctx.contains::<Marker>().await);
242 /// ctx.insert(Marker).await;
243 /// assert!(ctx.contains::<Marker>().await);
244 /// # }
245 /// ```
246 pub async fn contains<T: Send + Sync + 'static>(&self) -> bool {
247 self.state.read().await.contains_key(&TypeId::of::<T>())
248 }
249
250 /// Removes a value of type `T`, returning it if present.
251 ///
252 /// After removal, [`get`](Self::get) and [`contains`](Self::contains) for
253 /// type `T` will return `None` and `false` respectively.
254 ///
255 /// # Examples
256 ///
257 /// ```rust
258 /// use adk_plugin::PluginContext;
259 ///
260 /// #[derive(Clone, Debug, PartialEq)]
261 /// struct Token(String);
262 ///
263 /// # #[tokio::main]
264 /// # async fn main() {
265 /// let ctx = PluginContext::new();
266 /// ctx.insert(Token("abc".to_string())).await;
267 ///
268 /// let removed = ctx.remove::<Token>().await;
269 /// assert_eq!(removed, Some(Token("abc".to_string())));
270 /// assert_eq!(ctx.get::<Token>().await, None);
271 /// # }
272 /// ```
273 pub async fn remove<T: Send + Sync + 'static>(&self) -> Option<T> {
274 self.state
275 .write()
276 .await
277 .remove(&TypeId::of::<T>())
278 .and_then(|v| v.downcast::<T>().ok())
279 .map(|b| *b)
280 }
281}
282
283impl Default for PluginContext {
284 fn default() -> Self {
285 Self::new()
286 }
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[derive(Clone, Debug, PartialEq)]
294 struct Counter(u32);
295
296 #[derive(Clone, Debug, PartialEq)]
297 struct Name(String);
298
299 #[tokio::test]
300 async fn test_new_context_is_empty() {
301 let ctx = PluginContext::new();
302 assert!(!ctx.contains::<Counter>().await);
303 assert_eq!(ctx.get::<Counter>().await, None);
304 }
305
306 #[tokio::test]
307 async fn test_insert_and_get() {
308 let ctx = PluginContext::new();
309 ctx.insert(Counter(42)).await;
310
311 let value = ctx.get::<Counter>().await;
312 assert_eq!(value, Some(Counter(42)));
313 }
314
315 #[tokio::test]
316 async fn test_insert_overwrites_previous() {
317 let ctx = PluginContext::new();
318 ctx.insert(Counter(1)).await;
319 ctx.insert(Counter(99)).await;
320
321 assert_eq!(ctx.get::<Counter>().await, Some(Counter(99)));
322 }
323
324 #[tokio::test]
325 async fn test_multiple_types() {
326 let ctx = PluginContext::new();
327 ctx.insert(Counter(10)).await;
328 ctx.insert(Name("hello".to_string())).await;
329
330 assert_eq!(ctx.get::<Counter>().await, Some(Counter(10)));
331 assert_eq!(ctx.get::<Name>().await, Some(Name("hello".to_string())));
332 }
333
334 #[tokio::test]
335 async fn test_contains() {
336 let ctx = PluginContext::new();
337 assert!(!ctx.contains::<Counter>().await);
338
339 ctx.insert(Counter(0)).await;
340 assert!(ctx.contains::<Counter>().await);
341 }
342
343 #[tokio::test]
344 async fn test_remove_returns_value() {
345 let ctx = PluginContext::new();
346 ctx.insert(Counter(7)).await;
347
348 let removed = ctx.remove::<Counter>().await;
349 assert_eq!(removed, Some(Counter(7)));
350 }
351
352 #[tokio::test]
353 async fn test_remove_makes_get_return_none() {
354 let ctx = PluginContext::new();
355 ctx.insert(Counter(7)).await;
356 ctx.remove::<Counter>().await;
357
358 assert_eq!(ctx.get::<Counter>().await, None);
359 assert!(!ctx.contains::<Counter>().await);
360 }
361
362 #[tokio::test]
363 async fn test_remove_nonexistent_returns_none() {
364 let ctx = PluginContext::new();
365 let removed = ctx.remove::<Counter>().await;
366 assert_eq!(removed, None);
367 }
368
369 #[tokio::test]
370 async fn test_default_creates_empty_context() {
371 let ctx = PluginContext::default();
372 assert!(!ctx.contains::<Counter>().await);
373 }
374
375 #[tokio::test]
376 async fn an_invocation_context_keeps_its_state_apart_from_the_shared_one() {
377 let shared = Arc::new(PluginContext::new());
378 let first = PluginContext::with_shared(Arc::clone(&shared));
379 let second = PluginContext::with_shared(Arc::clone(&shared));
380
381 first.insert(Counter(1)).await;
382 assert_eq!(second.get::<Counter>().await, None);
383
384 first.shared().insert(Name("agent-wide".to_string())).await;
385 assert_eq!(second.shared().get::<Name>().await, Some(Name("agent-wide".to_string())));
386 assert_eq!(second.get::<Name>().await, None);
387 }
388
389 #[tokio::test]
390 async fn test_concurrent_access() {
391 use std::sync::Arc;
392
393 let ctx = Arc::new(PluginContext::new());
394 ctx.insert(Counter(0)).await;
395
396 let ctx_clone = Arc::clone(&ctx);
397 let writer = tokio::spawn(async move {
398 for i in 1..=100 {
399 ctx_clone.insert(Counter(i)).await;
400 }
401 });
402
403 let ctx_clone2 = Arc::clone(&ctx);
404 let reader = tokio::spawn(async move {
405 for _ in 0..100 {
406 // Should never panic — reads are always valid
407 let _ = ctx_clone2.get::<Counter>().await;
408 }
409 });
410
411 writer.await.unwrap();
412 reader.await.unwrap();
413
414 // Final value should be 100 (last write)
415 assert_eq!(ctx.get::<Counter>().await, Some(Counter(100)));
416 }
417}