reinhardt-graphql 0.3.1

GraphQL API support for Reinhardt (facade crate)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! GraphQL context for request-scoped data
//!
//! Provides context management for GraphQL query execution, including
//! request information, user authentication, data loaders, and custom data.

use async_trait::async_trait;
use serde_json::Value;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::warn;

/// Error types for context operations
#[derive(Debug, thiserror::Error)]
pub enum ContextError {
	/// Required data was not found in context
	#[error("Required context data not found for key: {0}")]
	DataNotFound(String),
	/// Required data loader was not found in context
	#[error("Required data loader not found: {0}")]
	LoaderNotFound(String),
}

/// Error types for data loader operations
#[derive(Debug, thiserror::Error)]
pub enum LoaderError {
	/// An error occurred during data loading.
	#[error("Loader error: {0}")]
	Load(String),
	/// The requested item was not found.
	#[error("Not found: {0}")]
	NotFound(String),
	/// The loaded data was invalid or could not be parsed.
	#[error("Invalid data: {0}")]
	InvalidData(String),
}

/// Trait for implementing data loaders
///
/// Data loaders provide batching and caching for database queries,
/// helping to solve the N+1 query problem in GraphQL.
///
/// # Examples
///
/// ```
/// use reinhardt_graphql::context::{DataLoader, LoaderError};
/// use async_trait::async_trait;
///
/// struct UserLoader;
///
/// #[async_trait]
/// impl DataLoader for UserLoader {
///     type Key = String;
///     type Value = String;
///
///     async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
///         Ok(format!("User: {}", key))
///     }
///
///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
///         Ok(keys.into_iter().map(|k| format!("User: {}", k)).collect())
///     }
/// }
/// ```
#[async_trait]
pub trait DataLoader: Send + Sync + 'static {
	/// The key type used to look up values.
	type Key: Send;
	/// The value type returned by the loader.
	type Value: Send;

	/// Load a single value by key
	async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError>;

	/// Load multiple values by keys (batch loading)
	async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError>;
}

/// GraphQL context for managing request-scoped data
///
/// Provides access to request information, user authentication state,
/// data loaders for efficient batch loading, and custom data storage.
///
/// # Examples
///
/// ```
/// use reinhardt_graphql::context::GraphQLContext;
/// use serde_json::json;
///
/// let context = GraphQLContext::new();
///
/// // Set custom data
/// context.set_data("api_version".to_string(), json!("v1"));
///
/// // Get custom data
/// let version = context.get_data("api_version");
/// assert_eq!(version, Some(json!("v1")));
/// ```
pub struct GraphQLContext {
	/// Custom data storage
	custom_data: Arc<RwLock<HashMap<String, Value>>>,
	/// Type-erased data loaders
	data_loaders: Arc<RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>>,
}

impl GraphQLContext {
	/// Create a new GraphQL context
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::GraphQLContext;
	///
	/// let context = GraphQLContext::new();
	/// assert!(context.get_data("nonexistent").is_none());
	/// ```
	pub fn new() -> Self {
		Self {
			custom_data: Arc::new(RwLock::new(HashMap::new())),
			data_loaders: Arc::new(RwLock::new(HashMap::new())),
		}
	}

	/// Acquires a read lock on custom_data with poison recovery.
	fn custom_data_read(&self) -> RwLockReadGuard<'_, HashMap<String, Value>> {
		self.custom_data.read().unwrap_or_else(|e| {
			warn!("custom_data RwLock was poisoned, recovering read lock");
			e.into_inner()
		})
	}

	/// Acquires a write lock on custom_data with poison recovery.
	fn custom_data_write(&self) -> RwLockWriteGuard<'_, HashMap<String, Value>> {
		self.custom_data.write().unwrap_or_else(|e| {
			warn!("custom_data RwLock was poisoned, recovering write lock");
			e.into_inner()
		})
	}

	/// Acquires a read lock on data_loaders with poison recovery.
	fn loaders_read(&self) -> RwLockReadGuard<'_, HashMap<TypeId, Box<dyn Any + Send + Sync>>> {
		self.data_loaders.read().unwrap_or_else(|e| {
			warn!("data_loaders RwLock was poisoned, recovering read lock");
			e.into_inner()
		})
	}

	/// Acquires a write lock on data_loaders with poison recovery.
	fn loaders_write(&self) -> RwLockWriteGuard<'_, HashMap<TypeId, Box<dyn Any + Send + Sync>>> {
		self.data_loaders.write().unwrap_or_else(|e| {
			warn!("data_loaders RwLock was poisoned, recovering write lock");
			e.into_inner()
		})
	}

	/// Set custom data in the context
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::GraphQLContext;
	/// use serde_json::json;
	///
	/// let context = GraphQLContext::new();
	/// context.set_data("user_id".to_string(), json!("123"));
	///
	/// assert_eq!(context.get_data("user_id"), Some(json!("123")));
	/// ```
	pub fn set_data(&self, key: String, value: Value) {
		let mut data = self.custom_data_write();
		data.insert(key, value);
	}

	/// Get custom data from the context
	///
	/// Returns `None` if the key does not exist. For GraphQL resolvers that
	/// require the data to be present, use [`require_data`](Self::require_data)
	/// instead to get a proper GraphQL error.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::GraphQLContext;
	/// use serde_json::json;
	///
	/// let context = GraphQLContext::new();
	/// context.set_data("count".to_string(), json!(42));
	///
	/// assert_eq!(context.get_data("count"), Some(json!(42)));
	/// assert_eq!(context.get_data("nonexistent"), None);
	/// ```
	pub fn get_data(&self, key: &str) -> Option<Value> {
		let data = self.custom_data_read();
		data.get(key).cloned()
	}

	/// Get required custom data from the context, returning a GraphQL error if missing
	///
	/// This method should be used in GraphQL resolvers where the data is expected
	/// to be present. Instead of panicking on a missing key, it returns a
	/// descriptive [`async_graphql::Error`] that will be surfaced as a GraphQL error
	/// in the response.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::GraphQLContext;
	/// use serde_json::json;
	///
	/// let context = GraphQLContext::new();
	/// context.set_data("api_version".to_string(), json!("v1"));
	///
	/// // Successful lookup
	/// let version = context.require_data("api_version");
	/// assert!(version.is_ok());
	/// assert_eq!(version.unwrap(), json!("v1"));
	///
	/// // Missing key returns an error
	/// let missing = context.require_data("nonexistent");
	/// assert!(missing.is_err());
	/// ```
	pub fn require_data(&self, key: &str) -> async_graphql::Result<Value> {
		self.get_data(key)
			.ok_or_else(|| ContextError::DataNotFound(key.to_string()).into())
	}

	/// Remove custom data from the context
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::GraphQLContext;
	/// use serde_json::json;
	///
	/// let context = GraphQLContext::new();
	/// context.set_data("temp".to_string(), json!("value"));
	///
	/// let removed = context.remove_data("temp");
	/// assert_eq!(removed, Some(json!("value")));
	/// assert_eq!(context.get_data("temp"), None);
	/// ```
	pub fn remove_data(&self, key: &str) -> Option<Value> {
		let mut data = self.custom_data_write();
		data.remove(key)
	}

	/// Clear all custom data
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::GraphQLContext;
	/// use serde_json::json;
	///
	/// let context = GraphQLContext::new();
	/// context.set_data("key1".to_string(), json!("value1"));
	/// context.set_data("key2".to_string(), json!("value2"));
	///
	/// context.clear_data();
	///
	/// assert_eq!(context.get_data("key1"), None);
	/// assert_eq!(context.get_data("key2"), None);
	/// ```
	pub fn clear_data(&self) {
		let mut data = self.custom_data_write();
		data.clear();
	}

	/// Add a data loader to the context
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
	/// use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// struct SimpleLoader;
	///
	/// #[async_trait]
	/// impl DataLoader for SimpleLoader {
	///     type Key = i32;
	///     type Value = String;
	///
	///     async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
	///         Ok(format!("Value {}", key))
	///     }
	///
	///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
	///         Ok(keys.iter().map(|k| format!("Value {}", k)).collect())
	///     }
	/// }
	///
	/// let context = GraphQLContext::new();
	/// let loader = Arc::new(SimpleLoader);
	/// context.add_data_loader(loader.clone());
	///
	/// let retrieved = context.get_data_loader::<SimpleLoader>();
	/// assert!(retrieved.is_some());
	/// ```
	pub fn add_data_loader<T: DataLoader>(&self, loader: Arc<T>) {
		let mut loaders = self.loaders_write();
		loaders.insert(TypeId::of::<T>(), Box::new(loader));
	}

	/// Get a data loader from the context
	///
	/// Returns `None` if the loader has not been registered. For GraphQL
	/// resolvers that require the loader, use
	/// [`require_data_loader`](Self::require_data_loader) instead to get a
	/// proper GraphQL error.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
	/// use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// struct TestLoader;
	///
	/// #[async_trait]
	/// impl DataLoader for TestLoader {
	///     type Key = String;
	///     type Value = i32;
	///
	///     async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
	///         Ok(42)
	///     }
	///
	///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
	///         Ok(vec![42; keys.len()])
	///     }
	/// }
	///
	/// let context = GraphQLContext::new();
	/// let loader = Arc::new(TestLoader);
	/// context.add_data_loader(loader);
	///
	/// let retrieved = context.get_data_loader::<TestLoader>();
	/// assert!(retrieved.is_some());
	/// ```
	pub fn get_data_loader<T: DataLoader>(&self) -> Option<Arc<T>> {
		let loaders = self.loaders_read();
		loaders
			.get(&TypeId::of::<T>())
			.and_then(|loader| loader.downcast_ref::<Arc<T>>().cloned())
	}

	/// Get a required data loader from the context, returning a GraphQL error if missing
	///
	/// This method should be used in GraphQL resolvers where the data loader is
	/// expected to be registered. Instead of panicking on a missing loader, it
	/// returns a descriptive [`async_graphql::Error`] that will be surfaced as a
	/// GraphQL error in the response.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
	/// use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// struct MyLoader;
	///
	/// #[async_trait]
	/// impl DataLoader for MyLoader {
	///     type Key = String;
	///     type Value = i32;
	///
	///     async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
	///         Ok(42)
	///     }
	///
	///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
	///         Ok(vec![42; keys.len()])
	///     }
	/// }
	///
	/// let context = GraphQLContext::new();
	///
	/// // Missing loader returns an error
	/// let result = context.require_data_loader::<MyLoader>();
	/// assert!(result.is_err());
	///
	/// // After adding the loader, it succeeds
	/// context.add_data_loader(Arc::new(MyLoader));
	/// let result = context.require_data_loader::<MyLoader>();
	/// assert!(result.is_ok());
	/// ```
	pub fn require_data_loader<T: DataLoader>(&self) -> async_graphql::Result<Arc<T>> {
		self.get_data_loader::<T>().ok_or_else(|| {
			ContextError::LoaderNotFound(std::any::type_name::<T>().to_string()).into()
		})
	}

	/// Remove a data loader from the context
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
	/// use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// struct RemovableLoader;
	///
	/// #[async_trait]
	/// impl DataLoader for RemovableLoader {
	///     type Key = u64;
	///     type Value = String;
	///
	///     async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
	///         Ok(key.to_string())
	///     }
	///
	///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
	///         Ok(keys.iter().map(|k| k.to_string()).collect())
	///     }
	/// }
	///
	/// let context = GraphQLContext::new();
	/// let loader = Arc::new(RemovableLoader);
	/// context.add_data_loader(loader);
	///
	/// context.remove_data_loader::<RemovableLoader>();
	/// assert!(context.get_data_loader::<RemovableLoader>().is_none());
	/// ```
	pub fn remove_data_loader<T: DataLoader>(&self) {
		let mut loaders = self.loaders_write();
		loaders.remove(&TypeId::of::<T>());
	}

	/// Clear all data loaders
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
	/// use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// struct Loader1;
	/// struct Loader2;
	///
	/// #[async_trait]
	/// impl DataLoader for Loader1 {
	///     type Key = i32;
	///     type Value = String;
	///     async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
	///         Ok(key.to_string())
	///     }
	///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
	///         Ok(keys.iter().map(|k| k.to_string()).collect())
	///     }
	/// }
	///
	/// #[async_trait]
	/// impl DataLoader for Loader2 {
	///     type Key = String;
	///     type Value = i32;
	///     async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
	///         Ok(0)
	///     }
	///     async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
	///         Ok(vec![0; keys.len()])
	///     }
	/// }
	///
	/// let context = GraphQLContext::new();
	/// context.add_data_loader(Arc::new(Loader1));
	/// context.add_data_loader(Arc::new(Loader2));
	///
	/// context.clear_loaders();
	///
	/// assert!(context.get_data_loader::<Loader1>().is_none());
	/// assert!(context.get_data_loader::<Loader2>().is_none());
	/// ```
	pub fn clear_loaders(&self) {
		let mut loaders = self.loaders_write();
		loaders.clear();
	}
}

impl Default for GraphQLContext {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	#[derive(Debug)]
	struct TestLoader;

	#[async_trait]
	impl DataLoader for TestLoader {
		type Key = String;
		type Value = i32;

		async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
			key.parse::<i32>()
				.map_err(|e| LoaderError::InvalidData(e.to_string()))
		}

		async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
			keys.into_iter()
				.map(|k| {
					k.parse::<i32>()
						.map_err(|e| LoaderError::InvalidData(e.to_string()))
				})
				.collect()
		}
	}

	#[rstest]
	fn test_context_new() {
		// Arrange & Act
		let context = GraphQLContext::new();

		// Assert
		assert!(context.get_data("any_key").is_none());
	}

	#[rstest]
	fn test_set_and_get_data() {
		// Arrange
		let context = GraphQLContext::new();
		let value = serde_json::json!({"name": "test", "value": 42});

		// Act
		context.set_data("test_key".to_string(), value.clone());

		// Assert
		let retrieved = context.get_data("test_key");
		assert_eq!(retrieved, Some(value));
	}

	#[rstest]
	fn test_get_nonexistent_data() {
		// Arrange
		let context = GraphQLContext::new();

		// Act
		let result = context.get_data("nonexistent");

		// Assert
		assert_eq!(result, None);
	}

	#[rstest]
	fn test_remove_data() {
		// Arrange
		let context = GraphQLContext::new();
		let value = serde_json::json!("test_value");
		context.set_data("key".to_string(), value.clone());

		// Act
		let removed = context.remove_data("key");

		// Assert
		assert_eq!(removed, Some(value));
		assert_eq!(context.get_data("key"), None);
	}

	#[rstest]
	fn test_clear_data() {
		// Arrange
		let context = GraphQLContext::new();
		context.set_data("key1".to_string(), serde_json::json!(1));
		context.set_data("key2".to_string(), serde_json::json!(2));
		context.set_data("key3".to_string(), serde_json::json!(3));

		// Act
		context.clear_data();

		// Assert
		assert_eq!(context.get_data("key1"), None);
		assert_eq!(context.get_data("key2"), None);
		assert_eq!(context.get_data("key3"), None);
	}

	#[rstest]
	fn test_add_and_get_data_loader() {
		// Arrange
		let context = GraphQLContext::new();
		let loader = Arc::new(TestLoader);

		// Act
		context.add_data_loader(loader);

		// Assert
		let retrieved = context.get_data_loader::<TestLoader>();
		assert!(retrieved.is_some());
	}

	#[rstest]
	fn test_get_nonexistent_loader() {
		// Arrange
		let context = GraphQLContext::new();

		// Act
		let result = context.get_data_loader::<TestLoader>();

		// Assert
		assert!(result.is_none());
	}

	#[rstest]
	fn test_remove_data_loader() {
		// Arrange
		let context = GraphQLContext::new();
		let loader = Arc::new(TestLoader);
		context.add_data_loader(loader);

		// Act
		context.remove_data_loader::<TestLoader>();

		// Assert
		let result = context.get_data_loader::<TestLoader>();
		assert!(result.is_none());
	}

	#[rstest]
	fn test_clear_loaders() {
		struct Loader1;
		struct Loader2;

		#[async_trait]
		impl DataLoader for Loader1 {
			type Key = i32;
			type Value = String;
			async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
				Ok(key.to_string())
			}
			async fn load_many(
				&self,
				keys: Vec<Self::Key>,
			) -> Result<Vec<Self::Value>, LoaderError> {
				Ok(keys.iter().map(|k| k.to_string()).collect())
			}
		}

		#[async_trait]
		impl DataLoader for Loader2 {
			type Key = String;
			type Value = i32;
			async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
				Ok(0)
			}
			async fn load_many(
				&self,
				keys: Vec<Self::Key>,
			) -> Result<Vec<Self::Value>, LoaderError> {
				Ok(vec![0; keys.len()])
			}
		}

		// Arrange
		let context = GraphQLContext::new();
		context.add_data_loader(Arc::new(Loader1));
		context.add_data_loader(Arc::new(Loader2));

		// Act
		context.clear_loaders();

		// Assert
		assert!(context.get_data_loader::<Loader1>().is_none());
		assert!(context.get_data_loader::<Loader2>().is_none());
	}

	#[rstest]
	fn test_multiple_data_values() {
		// Arrange
		let context = GraphQLContext::new();

		// Act
		context.set_data("int".to_string(), serde_json::json!(123));
		context.set_data("string".to_string(), serde_json::json!("hello"));
		context.set_data("array".to_string(), serde_json::json!([1, 2, 3]));
		context.set_data("object".to_string(), serde_json::json!({"key": "value"}));

		// Assert
		assert_eq!(context.get_data("int"), Some(serde_json::json!(123)));
		assert_eq!(context.get_data("string"), Some(serde_json::json!("hello")));
		assert_eq!(
			context.get_data("array"),
			Some(serde_json::json!([1, 2, 3]))
		);
		assert_eq!(
			context.get_data("object"),
			Some(serde_json::json!({"key": "value"}))
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_data_loader_load() {
		// Arrange
		let loader = TestLoader;

		// Act
		let result = loader.load("42".to_string()).await;

		// Assert
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), 42);
	}

	#[rstest]
	#[tokio::test]
	async fn test_data_loader_load_many() {
		// Arrange
		let loader = TestLoader;
		let keys = vec!["1".to_string(), "2".to_string(), "3".to_string()];

		// Act
		let result = loader.load_many(keys).await;

		// Assert
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), vec![1, 2, 3]);
	}

	#[rstest]
	#[tokio::test]
	async fn test_data_loader_error() {
		// Arrange
		let loader = TestLoader;

		// Act
		let result = loader.load("invalid".to_string()).await;

		// Assert
		assert!(result.is_err());
		match result {
			Err(LoaderError::InvalidData(_)) => {}
			_ => panic!("Expected InvalidData error"),
		}
	}

	#[rstest]
	fn test_context_default() {
		// Arrange & Act
		let context = GraphQLContext::default();

		// Assert
		assert!(context.get_data("any_key").is_none());
	}

	#[rstest]
	fn test_overwrite_data() {
		// Arrange
		let context = GraphQLContext::new();
		context.set_data("key".to_string(), serde_json::json!(1));

		// Act
		context.set_data("key".to_string(), serde_json::json!(2));

		// Assert
		assert_eq!(context.get_data("key"), Some(serde_json::json!(2)));
	}

	#[rstest]
	fn test_require_data_returns_value_when_present() {
		// Arrange
		let context = GraphQLContext::new();
		context.set_data("user_id".to_string(), serde_json::json!("user-42"));

		// Act
		let result = context.require_data("user_id");

		// Assert
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), serde_json::json!("user-42"));
	}

	#[rstest]
	fn test_require_data_returns_error_when_missing() {
		// Arrange
		let context = GraphQLContext::new();

		// Act
		let result = context.require_data("nonexistent_key");

		// Assert
		assert!(result.is_err());
		let err = result.unwrap_err();
		assert!(
			err.message.contains("nonexistent_key"),
			"Error should mention the missing key, got: {}",
			err.message
		);
		assert!(
			err.message.contains("Required context data not found"),
			"Error should describe the issue, got: {}",
			err.message
		);
	}

	#[rstest]
	fn test_require_data_does_not_panic_on_missing_key() {
		// Arrange
		let context = GraphQLContext::new();

		// Act -- this must NOT panic, unlike unwrap() on get_data()
		let result = context.require_data("missing");

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	fn test_require_data_loader_returns_loader_when_present() {
		// Arrange
		let context = GraphQLContext::new();
		context.add_data_loader(Arc::new(TestLoader));

		// Act
		let result = context.require_data_loader::<TestLoader>();

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	fn test_require_data_loader_returns_error_when_missing() {
		// Arrange
		let context = GraphQLContext::new();

		// Act
		let result = context.require_data_loader::<TestLoader>();

		// Assert
		assert!(result.is_err());
		let err = result.unwrap_err();
		assert!(
			err.message.contains("Required data loader not found"),
			"Error should describe the issue, got: {}",
			err.message
		);
	}

	#[rstest]
	fn test_require_data_loader_does_not_panic_on_missing_loader() {
		// Arrange
		let context = GraphQLContext::new();

		// Act -- this must NOT panic, unlike unwrap() on get_data_loader()
		let result = context.require_data_loader::<TestLoader>();

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	fn test_require_data_loader_after_removal_returns_error() {
		// Arrange
		let context = GraphQLContext::new();
		context.add_data_loader(Arc::new(TestLoader));
		context.remove_data_loader::<TestLoader>();

		// Act
		let result = context.require_data_loader::<TestLoader>();

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	fn test_context_error_data_not_found_display() {
		// Arrange
		let err = ContextError::DataNotFound("my_key".to_string());

		// Act
		let message = err.to_string();

		// Assert
		assert_eq!(message, "Required context data not found for key: my_key");
	}

	#[rstest]
	fn test_context_error_loader_not_found_display() {
		// Arrange
		let err = ContextError::LoaderNotFound("MyLoader".to_string());

		// Act
		let message = err.to_string();

		// Assert
		assert_eq!(message, "Required data loader not found: MyLoader");
	}

	#[rstest]
	fn test_context_error_converts_to_graphql_error() {
		// Arrange
		let err = ContextError::DataNotFound("test_key".to_string());

		// Act
		let gql_err: async_graphql::Error = err.into();

		// Assert
		assert!(gql_err.message.contains("test_key"));
		assert!(gql_err.message.contains("Required context data not found"));
	}
}