1use std::collections::HashMap;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13use a2a_protocol_types::error::A2aResult;
14use a2a_protocol_types::params::ListTasksParams;
15use a2a_protocol_types::responses::TaskListResponse;
16use a2a_protocol_types::task::{Task, TaskId};
17use tokio::sync::RwLock;
18
19use super::super::task_store::{InMemoryTaskStore, RecordedEvent, TaskStore, TaskStoreConfig};
20use super::context::TenantContext;
21
22#[derive(Debug, Clone)]
30#[non_exhaustive]
31pub struct TenantStoreConfig {
32 pub per_tenant: TaskStoreConfig,
35
36 pub max_tenants: usize,
61
62 pub max_total_tasks: Option<usize>,
75}
76
77impl Default for TenantStoreConfig {
78 fn default() -> Self {
79 Self {
80 per_tenant: TaskStoreConfig::default(),
81 max_tenants: 1000,
82 max_total_tasks: None,
83 }
84 }
85}
86
87impl TenantStoreConfig {
88 #[must_use]
90 pub const fn with_per_tenant(mut self, config: TaskStoreConfig) -> Self {
91 self.per_tenant = config;
92 self
93 }
94
95 #[must_use]
98 pub const fn with_max_tenants(mut self, max: usize) -> Self {
99 self.max_tenants = max;
100 self
101 }
102
103 #[must_use]
106 pub const fn with_max_total_tasks(mut self, max: usize) -> Self {
107 self.max_total_tasks = Some(max);
108 self
109 }
110}
111
112#[derive(Debug)]
142pub struct TenantAwareInMemoryTaskStore {
143 stores: RwLock<HashMap<String, Arc<InMemoryTaskStore>>>,
144 config: TenantStoreConfig,
145 overrides: HashMap<String, TaskStoreConfig>,
154 metrics: crate::metrics::MetricsHandle,
160 budget: Option<Arc<crate::store::task_store::TaskBudget>>,
163 holds: std::sync::Mutex<HashMap<String, crate::store::EventHolds>>,
169}
170
171impl Default for TenantAwareInMemoryTaskStore {
172 fn default() -> Self {
173 Self::new()
174 }
175}
176
177impl TenantAwareInMemoryTaskStore {
178 #[must_use]
180 pub fn new() -> Self {
181 Self::with_config(TenantStoreConfig::default())
182 }
183
184 #[must_use]
186 pub fn with_config(config: TenantStoreConfig) -> Self {
187 Self {
188 stores: RwLock::new(HashMap::new()),
189 budget: config
190 .max_total_tasks
191 .map(|max| Arc::new(crate::store::task_store::TaskBudget::new(max))),
192 config,
193 overrides: HashMap::new(),
194 metrics: crate::metrics::MetricsHandle::default(),
195 holds: std::sync::Mutex::default(),
196 }
197 }
198
199 #[must_use]
203 pub fn total_tasks(&self) -> Option<usize> {
204 self.budget.as_ref().map(|b| b.held())
205 }
206
207 #[must_use]
217 pub fn with_metrics(mut self, metrics: crate::metrics::MetricsHandle) -> Self {
218 self.metrics = metrics;
219 self
220 }
221
222 #[must_use]
248 pub fn with_tenant_override(
249 mut self,
250 tenant: impl Into<String>,
251 config: TaskStoreConfig,
252 ) -> Self {
253 self.overrides.insert(tenant.into(), config);
254 self
255 }
256
257 async fn get_store(&self) -> A2aResult<Arc<InMemoryTaskStore>> {
264 let tenant = TenantContext::partition();
265 let config_tenant = TenantContext::current();
266
267 {
269 let stores = self.stores.read().await;
270 if let Some(store) = stores.get(&tenant) {
271 return Ok(Arc::clone(store));
272 }
273 }
274
275 let mut stores = self.stores.write().await;
277 if let Some(store) = stores.get(&tenant) {
279 return Ok(Arc::clone(store));
280 }
281
282 if stores.len() >= self.config.max_tenants {
283 return Err(a2a_protocol_types::error::A2aError::internal(format!(
284 "tenant limit exceeded: max {} tenants",
285 self.config.max_tenants
286 )));
287 }
288
289 let store = Arc::new(
290 InMemoryTaskStore::partition(
291 self.overrides
292 .get(&config_tenant)
293 .unwrap_or(&self.config.per_tenant)
294 .clone(),
295 self.budget.clone(),
296 )
297 .with_metrics(self.metrics.clone()),
298 );
299 self.partition_holds()
300 .insert(tenant.clone(), store.holds.clone());
301 stores.insert(tenant, Arc::clone(&store));
302 drop(stores);
303 Ok(store)
304 }
305
306 async fn get_existing_store(&self) -> Option<Arc<InMemoryTaskStore>> {
312 let tenant = TenantContext::partition();
313 let stores = self.stores.read().await;
314 stores.get(&tenant).map(Arc::clone)
315 }
316
317 pub async fn tenant_count(&self) -> usize {
319 self.stores.read().await.len()
320 }
321
322 pub async fn run_eviction_all(&self) {
326 let stores: Vec<_> = self.stores.read().await.values().cloned().collect();
332 for store in stores {
333 store.run_eviction().await;
334 }
335 }
336
337 pub async fn erase_caller(&self, caller: &str) -> crate::store::caller_keys::CallerErasure {
341 let mut stores = self.stores.write().await;
342 let theirs: Vec<String> = stores
343 .keys()
344 .filter(|p| crate::store::caller_keys::is_callers_partition(p, caller))
345 .cloned()
346 .collect();
347 let mut done = crate::store::caller_keys::CallerErasure::default();
348 for partition in theirs {
349 if let Some(store) = stores.remove(&partition) {
350 self.partition_holds().remove(&partition);
351 done.rows += store.erase_all().await;
352 done.partitions += 1;
353 }
354 }
355 done
356 }
357
358 pub async fn prune_empty_tenants(&self) {
383 let mut stores = self.stores.write().await;
390 let mut empty_tenants = Vec::new();
391 for (tenant, store) in stores.iter() {
392 if store.is_prunable().await {
395 empty_tenants.push(tenant.clone());
396 }
397 }
398 for tenant in empty_tenants {
399 self.partition_holds().remove(&tenant);
400 stores.remove(&tenant);
401 }
402 }
403
404 fn partition_holds(
407 &self,
408 ) -> std::sync::MutexGuard<'_, HashMap<String, crate::store::EventHolds>> {
409 self.holds
410 .lock()
411 .unwrap_or_else(std::sync::PoisonError::into_inner)
412 }
413}
414
415#[allow(clippy::manual_async_fn)]
416impl TaskStore for TenantAwareInMemoryTaskStore {
417 fn is_process_local(&self) -> bool {
418 true
419 }
420
421 fn isolates_tenants(&self) -> bool {
422 true
423 }
424
425 fn supports_idempotency(&self) -> bool {
429 true
430 }
431
432 fn claim_idempotency_key<'a>(
433 &'a self,
434 key: &'a str,
435 message_id: &'a a2a_protocol_types::message::MessageId,
436 task_id: &'a TaskId,
437 ) -> Pin<
438 Box<dyn Future<Output = A2aResult<super::super::task_store::IdempotencyClaim>> + Send + 'a>,
439 > {
440 Box::pin(async move {
441 let store = self.get_store().await?;
442 store.claim_idempotency_key(key, message_id, task_id).await
443 })
444 }
445
446 fn idempotency_holder<'a>(
447 &'a self,
448 key: &'a str,
449 ) -> Pin<
450 Box<
451 dyn Future<Output = A2aResult<Option<super::super::task_store::IdempotencyHolder>>>
452 + Send
453 + 'a,
454 >,
455 > {
456 Box::pin(async move {
457 match self.get_existing_store().await {
461 Some(store) => store.idempotency_holder(key).await,
462 None => Ok(None),
463 }
464 })
465 }
466
467 fn release_idempotency_key<'a>(
468 &'a self,
469 key: &'a str,
470 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
471 Box::pin(async move {
472 match self.get_existing_store().await {
478 Some(store) => store.release_idempotency_key(key).await,
479 None => Ok(()),
480 }
481 })
482 }
483
484 fn save<'a>(
485 &'a self,
486 task: &'a Task,
487 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
488 Box::pin(async move {
489 let store = self.get_store().await?;
490 store.save(task).await
491 })
492 }
493
494 fn save_artifact_delta<'a>(
499 &'a self,
500 task: &'a Task,
501 delta: crate::store::ArtifactDelta,
502 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
503 Box::pin(async move {
504 let store = self.get_store().await?;
505 store.save_artifact_delta(task, delta).await
506 })
507 }
508
509 fn try_save_artifact_delta<'a>(
510 &'a self,
511 task: &'a Task,
512 delta: crate::store::ArtifactDelta,
513 ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
514 Box::pin(async move {
515 let store = self.get_store().await?;
516 store.try_save_artifact_delta(task, delta).await
517 })
518 }
519
520 fn save_status_delta<'a>(
521 &'a self,
522 task: &'a Task,
523 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
524 Box::pin(async move {
525 let store = self.get_store().await?;
526 store.save_status_delta(task).await
527 })
528 }
529
530 fn try_save_status_delta<'a>(
531 &'a self,
532 task: &'a Task,
533 ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
534 Box::pin(async move {
535 let store = self.get_store().await?;
536 store.try_save_status_delta(task).await
537 })
538 }
539
540 fn get<'a>(
541 &'a self,
542 id: &'a TaskId,
543 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<Task>>> + Send + 'a>> {
544 Box::pin(async move {
545 match self.get_existing_store().await {
546 Some(store) => store.get(id).await,
547 None => Ok(None),
548 }
549 })
550 }
551
552 fn get_with_position<'a>(
553 &'a self,
554 id: &'a TaskId,
555 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<(Task, Option<u64>)>>> + Send + 'a>> {
556 Box::pin(async move {
557 match self.get_existing_store().await {
558 Some(store) => store.get_with_position(id).await,
559 None => Ok(None),
560 }
561 })
562 }
563
564 fn list<'a>(
565 &'a self,
566 params: &'a ListTasksParams,
567 ) -> Pin<Box<dyn Future<Output = A2aResult<TaskListResponse>> + Send + 'a>> {
568 Box::pin(async move {
569 match self.get_existing_store().await {
570 Some(store) => store.list(params).await,
571 None => Ok(TaskListResponse::new(Vec::new())),
572 }
573 })
574 }
575
576 fn insert_if_absent<'a>(
577 &'a self,
578 task: &'a Task,
579 ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
580 Box::pin(async move {
581 let store = self.get_store().await?;
582 store.insert_if_absent(task).await
583 })
584 }
585
586 fn delete<'a>(
587 &'a self,
588 id: &'a TaskId,
589 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
590 Box::pin(async move {
591 match self.get_existing_store().await {
592 Some(store) => store.delete(id).await,
593 None => Ok(()),
594 }
595 })
596 }
597
598 fn supports_event_log(&self) -> bool {
603 true
604 }
605
606 fn append_event<'a>(
607 &'a self,
608 task_id: &'a TaskId,
609 seq: u64,
610 event: &'a a2a_protocol_types::events::StreamResponse,
611 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
612 Box::pin(async move {
613 let store = self.get_store().await?;
614 store.append_event(task_id, seq, event).await
615 })
616 }
617
618 fn last_event_seq<'a>(
619 &'a self,
620 task_id: &'a TaskId,
621 ) -> Pin<Box<dyn Future<Output = A2aResult<u64>> + Send + 'a>> {
622 Box::pin(async move {
623 match self.get_existing_store().await {
627 Some(store) => store.last_event_seq(task_id).await,
628 None => Ok(0),
629 }
630 })
631 }
632
633 fn hold_events(&self, task_id: &TaskId, after: u64) -> Option<crate::store::EventHold> {
637 let partition = TenantContext::partition();
638 let holds = self.partition_holds().get(&partition).cloned();
639 holds.map(|holds| holds.hold(task_id, after))
640 }
641
642 fn earliest_event_seq<'a>(
643 &'a self,
644 task_id: &'a TaskId,
645 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<u64>>> + Send + 'a>> {
646 Box::pin(async move {
647 match self.get_existing_store().await {
654 Some(store) => store.earliest_event_seq(task_id).await,
655 None => Ok(None),
656 }
657 })
658 }
659
660 fn trim_event_log<'a>(
661 &'a self,
662 task_id: &'a TaskId,
663 below: u64,
664 ) -> Pin<Box<dyn Future<Output = A2aResult<u64>> + Send + 'a>> {
665 Box::pin(async move {
666 match self.get_existing_store().await {
668 Some(store) => store.trim_event_log(task_id, below).await,
669 None => Ok(0),
670 }
671 })
672 }
673
674 fn read_events<'a>(
675 &'a self,
676 task_id: &'a TaskId,
677 after_seq: u64,
678 limit: usize,
679 ) -> Pin<Box<dyn Future<Output = A2aResult<Vec<RecordedEvent>>> + Send + 'a>> {
680 Box::pin(async move {
681 match self.get_existing_store().await {
682 Some(store) => store.read_events(task_id, after_seq, limit).await,
683 None => Ok(Vec::new()),
684 }
685 })
686 }
687
688 fn count<'a>(&'a self) -> Pin<Box<dyn Future<Output = A2aResult<u64>> + Send + 'a>> {
689 Box::pin(async move {
690 match self.get_existing_store().await {
691 Some(store) => store.count().await,
692 None => Ok(0),
693 }
694 })
695 }
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701 use a2a_protocol_types::task::{ContextId, TaskState, TaskStatus};
702
703 fn make_task(id: &str, state: TaskState) -> Task {
705 Task::new(
706 TaskId::new(id),
707 ContextId::new("ctx-default"),
708 TaskStatus::new(state),
709 )
710 }
711
712 #[tokio::test]
724 async fn with_metrics_reaches_the_per_tenant_stores() {
725 use a2a_protocol_types::events::StreamResponse;
726 use a2a_protocol_types::events::TaskStatusUpdateEvent;
727
728 #[derive(Default)]
729 struct Recorder(std::sync::Mutex<Vec<(String, String)>>);
730
731 impl crate::metrics::Metrics for Recorder {
732 fn on_persistence_error(&self, operation: &str, error_kind: &str) {
733 self.0
734 .lock()
735 .expect("not poisoned")
736 .push((operation.to_owned(), error_kind.to_owned()));
737 }
738 }
739
740 let recorder = Arc::new(Recorder::default());
741 let store = TenantAwareInMemoryTaskStore::new()
742 .with_metrics(crate::metrics::MetricsHandle::from_arc(recorder.clone()));
743
744 store
748 .append_event(
749 &TaskId::new("gone"),
750 1,
751 &StreamResponse::StatusUpdate(TaskStatusUpdateEvent::new(
752 TaskId::new("gone"),
753 ContextId::new("ctx-default"),
754 TaskStatus::new(TaskState::Working),
755 )),
756 )
757 .await
758 .expect("a missing task must not fail the agent");
759
760 assert_eq!(
761 *recorder.0.lock().expect("not poisoned"),
762 vec![(
763 crate::metrics::persistence_operation::EVENT_APPEND.to_owned(),
764 crate::metrics::event_append_error::TASK_ABSENT.to_owned(),
765 )],
766 "the partition must report to the handle the store was given"
767 );
768 }
769
770 #[tokio::test]
782 async fn per_tenant_page_size_cap_reaches_the_delegate() {
783 let store = TenantAwareInMemoryTaskStore::with_config(TenantStoreConfig {
784 per_tenant: TaskStoreConfig {
785 max_page_size: 2,
786 ..TaskStoreConfig::default()
787 },
788 max_tenants: 10,
789 max_total_tasks: None,
790 });
791
792 TenantContext::scope("capped", async {
793 for i in 0..5 {
794 store
795 .save(&make_task(&format!("t{i}"), TaskState::Submitted))
796 .await
797 .expect("save");
798 }
799
800 let listed = store
801 .list(&ListTasksParams::new().with_page_size(100))
802 .await
803 .expect("list");
804
805 assert_eq!(
806 listed.tasks.len(),
807 2,
808 "the caller asked for 100; per_tenant.max_page_size is 2. \
809 A delegate built with the default config would return 5"
810 );
811 })
812 .await;
813 }
814
815 #[tokio::test]
822 async fn an_override_gives_that_tenant_its_own_store_config() {
823 async fn saved_then_listed(
824 store: &TenantAwareInMemoryTaskStore,
825 tenant: &'static str,
826 ) -> usize {
827 TenantContext::scope(tenant, async {
828 for i in 0..5 {
829 store
830 .save(&make_task(&format!("{tenant}-{i}"), TaskState::Submitted))
831 .await
832 .expect("save");
833 }
834 store
835 .list(&ListTasksParams::new().with_page_size(100))
836 .await
837 .expect("list")
838 .tasks
839 .len()
840 })
841 .await
842 }
843
844 let store = TenantAwareInMemoryTaskStore::with_config(TenantStoreConfig {
845 per_tenant: TaskStoreConfig {
846 max_page_size: 50,
847 ..TaskStoreConfig::default()
848 },
849 max_tenants: 10,
850 max_total_tasks: None,
851 })
852 .with_tenant_override(
853 "small",
854 TaskStoreConfig {
855 max_page_size: 1,
856 ..TaskStoreConfig::default()
857 },
858 );
859
860 assert_eq!(
861 saved_then_listed(&store, "small").await,
862 1,
863 "the override caps this tenant's page size at 1"
864 );
865 assert_eq!(
866 saved_then_listed(&store, "ordinary").await,
867 5,
868 "a tenant with no override keeps per_tenant's cap of 50"
869 );
870 }
871
872 #[tokio::test]
875 async fn tenant_context_default_is_empty_string() {
876 let tenant = TenantContext::current();
878 assert_eq!(tenant, "", "default tenant should be empty string");
879 }
880
881 #[tokio::test]
882 async fn tenant_context_scope_sets_and_restores() {
883 let before = TenantContext::current();
884 assert_eq!(before, "");
885
886 let inside = TenantContext::scope("acme", async { TenantContext::current() }).await;
887 assert_eq!(inside, "acme", "scope should set the tenant");
888
889 let after = TenantContext::current();
890 assert_eq!(after, "", "tenant should revert after scope exits");
891 }
892
893 #[tokio::test]
894 async fn tenant_context_nested_scopes() {
895 TenantContext::scope("outer", async {
896 assert_eq!(TenantContext::current(), "outer");
897 TenantContext::scope("inner", async {
898 assert_eq!(TenantContext::current(), "inner");
899 })
900 .await;
901 assert_eq!(
902 TenantContext::current(),
903 "outer",
904 "should restore outer tenant after inner scope"
905 );
906 })
907 .await;
908 }
909
910 #[tokio::test]
913 async fn tenant_isolation_save_and_get() {
914 let store = TenantAwareInMemoryTaskStore::new();
915
916 TenantContext::scope("tenant-a", async {
918 store
919 .save(&make_task("t1", TaskState::Submitted))
920 .await
921 .unwrap();
922 })
923 .await;
924
925 let found = TenantContext::scope("tenant-a", async {
927 store.get(&TaskId::new("t1")).await.unwrap()
928 })
929 .await;
930 assert!(found.is_some(), "tenant-a should see its own task");
931
932 let not_found = TenantContext::scope("tenant-b", async {
934 store.get(&TaskId::new("t1")).await.unwrap()
935 })
936 .await;
937 assert!(
938 not_found.is_none(),
939 "tenant-b should not see tenant-a's task"
940 );
941 }
942
943 #[tokio::test]
944 async fn tenant_isolation_list() {
945 let store = TenantAwareInMemoryTaskStore::new();
946
947 TenantContext::scope("alpha", async {
948 store
949 .save(&make_task("a1", TaskState::Submitted))
950 .await
951 .unwrap();
952 store
953 .save(&make_task("a2", TaskState::Working))
954 .await
955 .unwrap();
956 })
957 .await;
958
959 TenantContext::scope("beta", async {
960 store
961 .save(&make_task("b1", TaskState::Submitted))
962 .await
963 .unwrap();
964 })
965 .await;
966
967 let alpha_list = TenantContext::scope("alpha", async {
968 let params = ListTasksParams::default();
969 store.list(¶ms).await.unwrap()
970 })
971 .await;
972 assert_eq!(
973 alpha_list.tasks.len(),
974 2,
975 "alpha should see only its 2 tasks"
976 );
977
978 let beta_list = TenantContext::scope("beta", async {
979 let params = ListTasksParams::default();
980 store.list(¶ms).await.unwrap()
981 })
982 .await;
983 assert_eq!(beta_list.tasks.len(), 1, "beta should see only its 1 task");
984 }
985
986 #[tokio::test]
987 async fn tenant_isolation_delete() {
988 let store = TenantAwareInMemoryTaskStore::new();
989
990 TenantContext::scope("tenant-a", async {
991 store
992 .save(&make_task("t1", TaskState::Submitted))
993 .await
994 .unwrap();
995 })
996 .await;
997
998 TenantContext::scope("tenant-b", async {
1000 store.delete(&TaskId::new("t1")).await.unwrap();
1001 })
1002 .await;
1003
1004 let still_exists = TenantContext::scope("tenant-a", async {
1005 store.get(&TaskId::new("t1")).await.unwrap()
1006 })
1007 .await;
1008 assert!(
1009 still_exists.is_some(),
1010 "tenant-a's task should survive tenant-b's delete"
1011 );
1012 }
1013
1014 #[tokio::test]
1015 async fn tenant_isolation_insert_if_absent() {
1016 let store = TenantAwareInMemoryTaskStore::new();
1017
1018 let inserted_a = TenantContext::scope("tenant-a", async {
1020 store
1021 .insert_if_absent(&make_task("shared-id", TaskState::Submitted))
1022 .await
1023 .unwrap()
1024 })
1025 .await;
1026 assert!(inserted_a, "tenant-a insert should succeed");
1027
1028 let inserted_b = TenantContext::scope("tenant-b", async {
1029 store
1030 .insert_if_absent(&make_task("shared-id", TaskState::Working))
1031 .await
1032 .unwrap()
1033 })
1034 .await;
1035 assert!(
1036 inserted_b,
1037 "tenant-b insert of same ID should also succeed (different partition)"
1038 );
1039 }
1040
1041 #[tokio::test]
1042 async fn tenant_isolation_count() {
1043 let store = TenantAwareInMemoryTaskStore::new();
1044
1045 TenantContext::scope("x", async {
1046 store
1047 .save(&make_task("t1", TaskState::Submitted))
1048 .await
1049 .unwrap();
1050 store
1051 .save(&make_task("t2", TaskState::Submitted))
1052 .await
1053 .unwrap();
1054 })
1055 .await;
1056
1057 TenantContext::scope("y", async {
1058 store
1059 .save(&make_task("t3", TaskState::Submitted))
1060 .await
1061 .unwrap();
1062 })
1063 .await;
1064
1065 let count_x = TenantContext::scope("x", async { store.count().await.unwrap() }).await;
1066 assert_eq!(count_x, 2, "tenant x should have 2 tasks");
1067
1068 let count_y = TenantContext::scope("y", async { store.count().await.unwrap() }).await;
1069 assert_eq!(count_y, 1, "tenant y should have 1 task");
1070 }
1071
1072 #[tokio::test]
1084 async fn a_full_tenant_table_refuses_new_tenants_and_pruning_does_not_help() {
1085 let store = TenantAwareInMemoryTaskStore::with_config(TenantStoreConfig {
1086 per_tenant: TaskStoreConfig::default(),
1087 max_tenants: 2,
1088 max_total_tasks: None,
1089 });
1090
1091 for junk in ["junk-1", "junk-2"] {
1092 TenantContext::scope(junk, async {
1093 store
1094 .save(&make_task("t", TaskState::Working))
1095 .await
1096 .expect("a fresh tenant partition is created on demand");
1097 })
1098 .await;
1099 }
1100 assert_eq!(store.tenant_count().await, 2, "the table is full");
1101
1102 let refused = TenantContext::scope("legitimate", async {
1103 store.save(&make_task("t", TaskState::Working)).await
1104 })
1105 .await;
1106 assert!(
1107 refused.is_err(),
1108 "a new tenant must be refused once the cap is reached"
1109 );
1110
1111 store.prune_empty_tenants().await;
1113 assert_eq!(
1114 store.tenant_count().await,
1115 2,
1116 "pruning reclaims nothing while the junk partitions hold live tasks"
1117 );
1118
1119 let still_refused = TenantContext::scope("legitimate", async {
1120 store.save(&make_task("t", TaskState::Working)).await
1121 })
1122 .await;
1123 assert!(
1124 still_refused.is_err(),
1125 "so the lockout outlives the pruning that is supposed to end it"
1126 );
1127
1128 for junk in ["junk-1", "junk-2"] {
1130 TenantContext::scope(junk, async {
1131 store.delete(&TaskId::new("t")).await.expect("delete");
1132 })
1133 .await;
1134 }
1135 store.prune_empty_tenants().await;
1136 assert_eq!(store.tenant_count().await, 0, "now the slots come back");
1137
1138 let admitted = TenantContext::scope("legitimate", async {
1139 store.save(&make_task("t", TaskState::Working)).await
1140 })
1141 .await;
1142 assert!(admitted.is_ok(), "and the legitimate tenant gets in");
1143 }
1144
1145 #[tokio::test]
1146 async fn tenant_count_reflects_active_tenants() {
1147 let store = TenantAwareInMemoryTaskStore::new();
1148 assert_eq!(store.tenant_count().await, 0);
1149
1150 TenantContext::scope("a", async {
1151 store
1152 .save(&make_task("t1", TaskState::Submitted))
1153 .await
1154 .unwrap();
1155 })
1156 .await;
1157 assert_eq!(store.tenant_count().await, 1);
1158
1159 TenantContext::scope("b", async {
1160 store
1161 .save(&make_task("t2", TaskState::Submitted))
1162 .await
1163 .unwrap();
1164 })
1165 .await;
1166 assert_eq!(store.tenant_count().await, 2);
1167 }
1168
1169 #[tokio::test]
1170 async fn max_tenants_limit_enforced() {
1171 let config = TenantStoreConfig {
1172 per_tenant: TaskStoreConfig::default(),
1173 max_tenants: 2,
1174 max_total_tasks: None,
1175 };
1176 let store = TenantAwareInMemoryTaskStore::with_config(config);
1177
1178 TenantContext::scope("t1", async {
1180 store
1181 .save(&make_task("task-a", TaskState::Submitted))
1182 .await
1183 .unwrap();
1184 })
1185 .await;
1186 TenantContext::scope("t2", async {
1187 store
1188 .save(&make_task("task-b", TaskState::Submitted))
1189 .await
1190 .unwrap();
1191 })
1192 .await;
1193
1194 let result = TenantContext::scope("t3", async {
1196 store.save(&make_task("task-c", TaskState::Submitted)).await
1197 })
1198 .await;
1199 assert!(
1200 result.is_err(),
1201 "exceeding max_tenants should return an error"
1202 );
1203 }
1204
1205 #[tokio::test]
1206 async fn existing_tenant_does_not_count_against_limit() {
1207 let config = TenantStoreConfig {
1208 per_tenant: TaskStoreConfig::default(),
1209 max_tenants: 1,
1210 max_total_tasks: None,
1211 };
1212 let store = TenantAwareInMemoryTaskStore::with_config(config);
1213
1214 TenantContext::scope("only", async {
1215 store
1216 .save(&make_task("t1", TaskState::Submitted))
1217 .await
1218 .unwrap();
1219 store
1221 .save(&make_task("t2", TaskState::Working))
1222 .await
1223 .unwrap();
1224 })
1225 .await;
1226
1227 let count = TenantContext::scope("only", async { store.count().await.unwrap() }).await;
1228 assert_eq!(count, 2, "existing tenant can add more tasks");
1229 }
1230
1231 #[tokio::test]
1234 async fn no_tenant_context_uses_default_partition() {
1235 let store = TenantAwareInMemoryTaskStore::new();
1236
1237 store
1239 .save(&make_task("default-task", TaskState::Submitted))
1240 .await
1241 .unwrap();
1242
1243 let fetched = store.get(&TaskId::new("default-task")).await.unwrap();
1244 assert!(
1245 fetched.is_some(),
1246 "task saved without tenant context should be retrievable without context"
1247 );
1248
1249 let not_found = TenantContext::scope("other", async {
1251 store.get(&TaskId::new("default-task")).await.unwrap()
1252 })
1253 .await;
1254 assert!(
1255 not_found.is_none(),
1256 "default partition task should not leak to named tenants"
1257 );
1258 }
1259
1260 #[tokio::test]
1263 async fn prune_empty_tenants_removes_empty_partitions() {
1264 let store = TenantAwareInMemoryTaskStore::new();
1265
1266 TenantContext::scope("keep", async {
1267 store
1268 .save(&make_task("t1", TaskState::Submitted))
1269 .await
1270 .unwrap();
1271 })
1272 .await;
1273 TenantContext::scope("remove", async {
1274 store
1275 .save(&make_task("t2", TaskState::Submitted))
1276 .await
1277 .unwrap();
1278 })
1279 .await;
1280 assert_eq!(store.tenant_count().await, 2);
1281
1282 TenantContext::scope("remove", async {
1284 store.delete(&TaskId::new("t2")).await.unwrap();
1285 })
1286 .await;
1287
1288 store.prune_empty_tenants().await;
1289 assert_eq!(
1290 store.tenant_count().await,
1291 1,
1292 "empty tenant partition should be pruned"
1293 );
1294 }
1295
1296 #[tokio::test]
1302 async fn a_key_is_read_in_its_own_tenant_and_reading_makes_no_partition() {
1303 use crate::store::task_store::IdempotencyHolder;
1304 use a2a_protocol_types::message::MessageId;
1305
1306 const KEY: &str = "8f14e45fceea167a5a36dedd4bea2543";
1307 let store = TenantAwareInMemoryTaskStore::new();
1308 TenantContext::scope("acme", async {
1309 store
1310 .claim_idempotency_key(KEY, &MessageId::new("m1"), &TaskId::new("t1"))
1311 .await
1312 .unwrap();
1313 })
1314 .await;
1315
1316 let in_acme = TenantContext::scope("acme", async {
1317 store.idempotency_holder(KEY).await.unwrap()
1318 })
1319 .await;
1320 assert_eq!(
1321 in_acme,
1322 Some(IdempotencyHolder::new(
1323 MessageId::new("m1"),
1324 TaskId::new("t1")
1325 ))
1326 );
1327 let in_globex = TenantContext::scope("globex", async {
1328 store.idempotency_holder(KEY).await.unwrap()
1329 })
1330 .await;
1331 assert_eq!(in_globex, None, "another tenant's key is not visible");
1332 assert_eq!(
1333 store.tenant_count().await,
1334 1,
1335 "reading under a tenant with no partition made none"
1336 );
1337 }
1338
1339 #[tokio::test]
1346 async fn a_partition_still_holding_idempotency_keys_is_not_pruned() {
1347 let store = TenantAwareInMemoryTaskStore::new();
1348
1349 TenantContext::scope("keyed", async {
1350 store
1351 .save(&make_task("t1", TaskState::Submitted))
1352 .await
1353 .unwrap();
1354 store
1355 .claim_idempotency_key(
1356 "8f14e45fceea167a5a36dedd4bea2543",
1357 &a2a_protocol_types::message::MessageId::new("msg-1"),
1358 &TaskId::new("t1"),
1359 )
1360 .await
1361 .unwrap();
1362 store.delete(&TaskId::new("t1")).await.unwrap();
1365 assert_eq!(
1366 store.count().await.unwrap(),
1367 0,
1368 "the partition holds no task, which is what used to decide this"
1369 );
1370 })
1371 .await;
1372 assert_eq!(store.tenant_count().await, 1);
1373
1374 store.prune_empty_tenants().await;
1375 assert_eq!(
1376 store.tenant_count().await,
1377 1,
1378 "a partition holding a live idempotency key must survive the prune"
1379 );
1380
1381 let claim = TenantContext::scope("keyed", async {
1383 store
1384 .claim_idempotency_key(
1385 "8f14e45fceea167a5a36dedd4bea2543",
1386 &a2a_protocol_types::message::MessageId::new("msg-1"),
1387 &TaskId::new("t2"),
1388 )
1389 .await
1390 .unwrap()
1391 })
1392 .await;
1393 assert!(
1394 matches!(
1395 claim,
1396 crate::store::task_store::IdempotencyClaim::Replay(ref id) if id.0 == "t1"
1397 ),
1398 "the surviving key must still name the first task, got {claim:?}"
1399 );
1400 }
1401
1402 #[tokio::test]
1405 async fn a_partition_holding_neither_tasks_nor_keys_is_still_pruned() {
1406 let store = TenantAwareInMemoryTaskStore::new();
1407
1408 TenantContext::scope("transient", async {
1409 store
1410 .save(&make_task("t1", TaskState::Submitted))
1411 .await
1412 .unwrap();
1413 store.delete(&TaskId::new("t1")).await.unwrap();
1414 })
1415 .await;
1416 assert_eq!(store.tenant_count().await, 1);
1417
1418 store.prune_empty_tenants().await;
1419 assert_eq!(
1420 store.tenant_count().await,
1421 0,
1422 "a genuinely empty partition must still give its slot back"
1423 );
1424 }
1425
1426 #[test]
1430 fn default_creates_new_tenant_store() {
1431 let store = TenantAwareInMemoryTaskStore::default();
1432 let rt = tokio::runtime::Builder::new_current_thread()
1433 .enable_all()
1434 .build()
1435 .unwrap();
1436 let count = rt.block_on(store.tenant_count());
1437 assert_eq!(count, 0, "default store should have no tenants");
1438 }
1439
1440 #[tokio::test]
1442 async fn run_eviction_all_runs_without_error() {
1443 let store = TenantAwareInMemoryTaskStore::new();
1444
1445 TenantContext::scope("t1", async {
1447 store
1448 .save(&make_task("task-a", TaskState::Completed))
1449 .await
1450 .unwrap();
1451 })
1452 .await;
1453 TenantContext::scope("t2", async {
1454 store
1455 .save(&make_task("task-b", TaskState::Working))
1456 .await
1457 .unwrap();
1458 })
1459 .await;
1460
1461 store.run_eviction_all().await;
1463 }
1464
1465 #[tokio::test]
1469 async fn get_store_double_check_path() {
1470 let store = TenantAwareInMemoryTaskStore::new();
1471
1472 TenantContext::scope("racer", async {
1474 store
1475 .save(&make_task("t1", TaskState::Submitted))
1476 .await
1477 .unwrap();
1478 store
1480 .save(&make_task("t2", TaskState::Working))
1481 .await
1482 .unwrap();
1483
1484 let count = store.count().await.unwrap();
1485 assert_eq!(count, 2, "both tasks should be in same tenant store");
1486 })
1487 .await;
1488
1489 assert_eq!(
1490 store.tenant_count().await,
1491 1,
1492 "should have exactly 1 tenant"
1493 );
1494 }
1495
1496 #[test]
1497 fn default_tenant_store_config() {
1498 let cfg = TenantStoreConfig::default();
1499 assert_eq!(cfg.max_tenants, 1000);
1500 }
1501
1502 #[tokio::test]
1514 async fn run_eviction_all_evicts_in_every_tenant() {
1515 let store = TenantAwareInMemoryTaskStore::with_config(TenantStoreConfig {
1516 per_tenant: TaskStoreConfig {
1517 task_ttl: Some(std::time::Duration::from_millis(1)),
1518 ..TaskStoreConfig::default()
1519 },
1520 ..TenantStoreConfig::default()
1521 });
1522
1523 for tenant in ["tenant-a", "tenant-b"] {
1524 TenantContext::scope(tenant, async {
1525 store
1526 .save(&make_task("t1", TaskState::Completed))
1527 .await
1528 .expect("save");
1529 })
1530 .await;
1531 }
1532
1533 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1535 store.run_eviction_all().await;
1536
1537 for tenant in ["tenant-a", "tenant-b"] {
1538 let still_there = TenantContext::scope(tenant, async {
1539 store.get(&TaskId::new("t1")).await.expect("get")
1540 })
1541 .await;
1542 assert!(
1543 still_there.is_none(),
1544 "a terminal task past its TTL must be evicted in {tenant}; \
1545 surviving means run_eviction_all did not reach this partition"
1546 );
1547 }
1548 }
1549
1550 #[test]
1556 fn in_memory_tenant_store_advertises_idempotency_support() {
1557 let store = TenantAwareInMemoryTaskStore::new();
1558 assert!(
1559 store.supports_idempotency(),
1560 "the tenant-aware in-memory store partitions by tenant, which is \
1561 exactly the scope a key needs; it must advertise support"
1562 );
1563 }
1564
1565 #[test]
1566 fn every_tenant_store_config_setter_sets_its_field() {
1567 let d = TenantStoreConfig::default();
1568 let per_tenant =
1569 TaskStoreConfig::default().with_max_page_size(d.per_tenant.max_page_size + 1);
1570 let cfg = TenantStoreConfig::default()
1571 .with_per_tenant(per_tenant)
1572 .with_max_tenants(d.max_tenants + 1);
1573 assert_eq!(cfg.per_tenant.max_page_size, d.per_tenant.max_page_size + 1);
1574 assert_eq!(cfg.max_tenants, d.max_tenants + 1);
1575 }
1576}
1577
1578#[cfg(test)]
1579mod idempotency_isolation_tests {
1580 use super::*;
1581 use crate::store::task_store::IdempotencyClaim;
1582 use a2a_protocol_types::message::MessageId;
1583
1584 const KEY: &str = "8f14e45fceea167a5a36dedd4bea2543";
1585
1586 #[tokio::test]
1587 async fn one_tenants_key_never_names_another_tenants_task() {
1588 let store = TenantAwareInMemoryTaskStore::new();
1592
1593 let a = TenantContext::scope("tenant-a", async {
1594 store
1595 .claim_idempotency_key(KEY, &MessageId::new("m1"), &TaskId::new("task-a"))
1596 .await
1597 .unwrap()
1598 })
1599 .await;
1600 assert_eq!(a, IdempotencyClaim::Claimed);
1601
1602 let b = TenantContext::scope("tenant-b", async {
1603 store
1604 .claim_idempotency_key(KEY, &MessageId::new("m1"), &TaskId::new("task-b"))
1605 .await
1606 .unwrap()
1607 })
1608 .await;
1609 assert_eq!(
1610 b,
1611 IdempotencyClaim::Claimed,
1612 "tenant-b must claim its own key, not replay tenant-a's task"
1613 );
1614 }
1615
1616 #[tokio::test]
1617 async fn a_retry_within_one_tenant_still_replays() {
1618 let store = TenantAwareInMemoryTaskStore::new();
1619 TenantContext::scope("tenant-a", async {
1620 let first = store
1621 .claim_idempotency_key(KEY, &MessageId::new("m1"), &TaskId::new("task-a"))
1622 .await
1623 .unwrap();
1624 assert_eq!(first, IdempotencyClaim::Claimed);
1625
1626 let retry = store
1627 .claim_idempotency_key(KEY, &MessageId::new("m1"), &TaskId::new("task-other"))
1628 .await
1629 .unwrap();
1630 assert_eq!(retry, IdempotencyClaim::Replay(TaskId::new("task-a")));
1631 })
1632 .await;
1633 }
1634
1635 #[tokio::test]
1640 async fn release_frees_the_key_in_its_own_tenant_only() {
1641 let store = TenantAwareInMemoryTaskStore::new();
1642 for tenant in ["tenant-a", "tenant-b"] {
1643 TenantContext::scope(tenant, async {
1644 let claim = store
1645 .claim_idempotency_key(KEY, &MessageId::new("m1"), &TaskId::new("t1"))
1646 .await
1647 .unwrap();
1648 assert_eq!(claim, IdempotencyClaim::Claimed);
1649 })
1650 .await;
1651 }
1652
1653 TenantContext::scope("tenant-a", async {
1654 store.release_idempotency_key(KEY).await.unwrap();
1655 let reclaim = store
1656 .claim_idempotency_key(KEY, &MessageId::new("m2"), &TaskId::new("t2"))
1657 .await
1658 .unwrap();
1659 assert_eq!(reclaim, IdempotencyClaim::Claimed, "released, so free");
1660 })
1661 .await;
1662
1663 TenantContext::scope("tenant-b", async {
1664 let held = store
1665 .claim_idempotency_key(KEY, &MessageId::new("m2"), &TaskId::new("t2"))
1666 .await
1667 .unwrap();
1668 assert_ne!(
1669 held,
1670 IdempotencyClaim::Claimed,
1671 "tenant-a's release must not free tenant-b's key"
1672 );
1673 })
1674 .await;
1675 }
1676
1677 #[tokio::test]
1678 async fn releasing_under_an_unknown_tenant_creates_no_partition() {
1679 let store = TenantAwareInMemoryTaskStore::new();
1682 TenantContext::scope("never-seen", async {
1683 store.release_idempotency_key(KEY).await.unwrap();
1684 })
1685 .await;
1686 assert_eq!(store.tenant_count().await, 0);
1687 }
1688}
1689
1690#[cfg(test)]
1691#[path = "event_log_tests.rs"]
1692mod event_log_tests;
1693
1694#[cfg(test)]
1695#[path = "total_cap_tests.rs"]
1696mod total_cap_tests;