hyperstack_server/view/
registry.rs1use crate::sorted_cache::{SortOrder, SortedViewCache};
2use crate::view::ViewSpec;
3use std::collections::HashMap;
4use std::sync::Arc;
5use tokio::sync::RwLock;
6
7#[derive(Clone)]
8pub struct ViewIndex {
9 by_export: HashMap<String, Vec<ViewSpec>>,
10 by_id: HashMap<String, ViewSpec>,
11 sorted_caches: Arc<RwLock<HashMap<String, SortedViewCache>>>,
12 derived_by_source: HashMap<String, Vec<String>>,
14}
15
16impl ViewIndex {
17 pub fn new() -> Self {
18 Self {
19 by_export: HashMap::new(),
20 by_id: HashMap::new(),
21 sorted_caches: Arc::new(RwLock::new(HashMap::new())),
22 derived_by_source: HashMap::new(),
23 }
24 }
25
26 pub fn add_spec(&mut self, spec: ViewSpec) {
27 if let Some(ref source) = spec.source_view {
28 self.derived_by_source
29 .entry(source.clone())
30 .or_default()
31 .push(spec.id.clone());
32 }
33
34 if let Some(ref pipeline) = spec.pipeline {
35 if let Some(ref sort_config) = pipeline.sort {
36 self.init_sorted_cache_sync(
37 &spec.id,
38 sort_config.field_path.clone(),
39 sort_config.order.into(),
40 );
41 }
42 }
43
44 self.by_export
45 .entry(spec.export.clone())
46 .or_default()
47 .push(spec.clone());
48 self.by_id.insert(spec.id.clone(), spec);
49 }
50
51 pub fn by_export(&self, entity: &str) -> &[ViewSpec] {
52 self.by_export
53 .get(entity)
54 .map(|v| v.as_slice())
55 .unwrap_or(&[])
56 }
57
58 pub fn get_view(&self, id: &str) -> Option<&ViewSpec> {
59 self.by_id.get(id)
60 }
61
62 pub fn get_derived_views(&self) -> Vec<&ViewSpec> {
63 self.by_id.values().filter(|s| s.is_derived()).collect()
64 }
65
66 pub fn get_derived_views_for_source(&self, source_view_id: &str) -> Vec<&ViewSpec> {
67 self.derived_by_source
68 .get(source_view_id)
69 .map(|ids| ids.iter().filter_map(|id| self.by_id.get(id)).collect())
70 .unwrap_or_default()
71 }
72
73 pub fn sorted_caches(&self) -> Arc<RwLock<HashMap<String, SortedViewCache>>> {
74 self.sorted_caches.clone()
75 }
76
77 pub async fn init_sorted_cache(
78 &self,
79 view_id: &str,
80 sort_field: Vec<String>,
81 order: SortOrder,
82 ) {
83 let mut caches = self.sorted_caches.write().await;
84 if !caches.contains_key(view_id) {
85 caches.insert(
86 view_id.to_string(),
87 SortedViewCache::new(view_id.to_string(), sort_field, order),
88 );
89 }
90 }
91
92 fn init_sorted_cache_sync(&mut self, view_id: &str, sort_field: Vec<String>, order: SortOrder) {
93 let cache = SortedViewCache::new(view_id.to_string(), sort_field, order);
94 let caches = Arc::get_mut(&mut self.sorted_caches)
95 .expect("Cannot initialize sorted cache: Arc is shared");
96 let caches = caches.get_mut();
97 if !caches.contains_key(view_id) {
98 caches.insert(view_id.to_string(), cache);
99 }
100 }
101}
102
103impl Default for ViewIndex {
104 fn default() -> Self {
105 Self::new()
106 }
107}