arete_server/view/
registry.rs1use crate::row_scope::{ScopeField, DEFAULT_MAX_SCOPE_PARTITIONS};
2use crate::sorted_cache::{SortOrder, SortedViewCache};
3use crate::view::ViewSpec;
4use std::collections::HashMap;
5use std::sync::Arc;
6use tokio::sync::RwLock;
7
8#[derive(Clone)]
9pub struct ViewIndex {
10 by_export: HashMap<String, Vec<ViewSpec>>,
11 by_id: HashMap<String, ViewSpec>,
12 sorted_caches: Arc<RwLock<HashMap<String, SortedViewCache>>>,
13 derived_by_source: HashMap<String, Vec<String>>,
15 entity_scopes: HashMap<String, ScopeField>,
17 max_scope_partitions: usize,
19}
20
21impl ViewIndex {
22 pub fn new() -> Self {
23 Self {
24 by_export: HashMap::new(),
25 by_id: HashMap::new(),
26 sorted_caches: Arc::new(RwLock::new(HashMap::new())),
27 derived_by_source: HashMap::new(),
28 entity_scopes: HashMap::new(),
29 max_scope_partitions: DEFAULT_MAX_SCOPE_PARTITIONS,
30 }
31 }
32
33 pub fn set_entity_scope(&mut self, export: impl Into<String>, field: ScopeField) {
40 self.entity_scopes.insert(export.into(), field);
41 self.partition_scoped_caches();
42 }
43
44 pub fn set_max_scope_partitions(&mut self, max_partitions: usize) {
48 self.max_scope_partitions = max_partitions.max(1);
49 self.partition_scoped_caches();
50 }
51
52 pub fn max_scope_partitions(&self) -> usize {
53 self.max_scope_partitions
54 }
55
56 pub fn scope_field_for_view(&self, view_id: &str) -> Option<&ScopeField> {
59 if self.entity_scopes.is_empty() {
60 return None;
61 }
62 let mut current = view_id;
63 for _ in 0..=self.by_id.len() {
66 let Some(spec) = self.by_id.get(current) else {
67 let entity = current.split('/').next().unwrap_or(current);
69 return self.entity_scopes.get(entity);
70 };
71 if let Some(field) = self.entity_scopes.get(&spec.export) {
72 return Some(field);
73 }
74 match spec.source_view.as_deref() {
75 Some(source) if source != current => current = source,
76 _ => return None,
77 }
78 }
79 None
80 }
81
82 pub(crate) fn validate_scope_projection(&self, spec: &ViewSpec) -> anyhow::Result<()> {
84 if let (Some(scope), Some(fields)) =
85 (self.scope_field_for_view(&spec.id), &spec.projection.fields)
86 {
87 if !scope
88 .path()
89 .first()
90 .is_some_and(|root| fields.contains(root))
91 {
92 anyhow::bail!(
93 "View {} projection must retain its row scope field",
94 spec.id
95 );
96 }
97 }
98 Ok(())
99 }
100
101 pub(crate) fn validate_scope_projections(&self) -> anyhow::Result<()> {
102 for spec in self.by_id.values() {
103 self.validate_scope_projection(spec)?;
104 }
105 Ok(())
106 }
107
108 pub(crate) fn entity_scope_paths(&self) -> std::collections::BTreeMap<String, String> {
111 self.entity_scopes
112 .iter()
113 .map(|(export, field)| (export.clone(), field.path().join(".")))
114 .collect()
115 }
116
117 pub fn has_scoped_entities(&self) -> bool {
119 !self.entity_scopes.is_empty()
120 }
121
122 fn partition_scoped_caches(&mut self) {
124 let scoped: Vec<(String, ScopeField)> = self
125 .by_id
126 .keys()
127 .filter_map(|id| {
128 self.scope_field_for_view(id)
129 .map(|field| (id.clone(), field.clone()))
130 })
131 .collect();
132 if scoped.is_empty() {
133 return;
134 }
135 let max_partitions = self.max_scope_partitions;
136 let caches = Arc::get_mut(&mut self.sorted_caches)
137 .expect("Cannot partition sorted caches: Arc is shared");
138 let caches = caches.get_mut();
139 for (view_id, field) in scoped {
140 if let Some(cache) = caches.get_mut(&view_id) {
141 cache.partition_by_scope(field, max_partitions);
142 }
143 }
144 }
145
146 pub fn add_spec(&mut self, spec: ViewSpec) {
147 if let Some(ref source) = spec.source_view {
148 self.derived_by_source
149 .entry(source.clone())
150 .or_default()
151 .push(spec.id.clone());
152 }
153
154 if let Some(ref pipeline) = spec.pipeline {
155 if let Some(ref sort_config) = pipeline.sort {
156 self.init_sorted_cache_sync(
157 &spec.id,
158 sort_config.field_path.clone(),
159 sort_config.order.into(),
160 );
161 }
162 }
163
164 if !spec.is_derived() {
168 self.by_export
169 .entry(spec.export.clone())
170 .or_default()
171 .push(spec.clone());
172 }
173 let partition = self.has_scoped_entities();
174 self.by_id.insert(spec.id.clone(), spec);
175 if partition {
176 self.partition_scoped_caches();
177 }
178 }
179
180 pub fn by_export(&self, entity: &str) -> &[ViewSpec] {
181 self.by_export
182 .get(entity)
183 .map(|v| v.as_slice())
184 .unwrap_or(&[])
185 }
186
187 pub fn get_view(&self, id: &str) -> Option<&ViewSpec> {
188 self.by_id.get(id)
189 }
190
191 pub(crate) fn snapshot_specs(&self) -> Vec<&ViewSpec> {
193 let mut specs = self.by_id.values().collect::<Vec<_>>();
194 specs.sort_by(|left, right| left.id.cmp(&right.id));
195 specs
196 }
197
198 pub fn get_derived_views(&self) -> Vec<&ViewSpec> {
199 self.by_id.values().filter(|s| s.is_derived()).collect()
200 }
201
202 pub fn get_derived_views_for_source(&self, source_view_id: &str) -> Vec<&ViewSpec> {
203 self.derived_by_source
204 .get(source_view_id)
205 .map(|ids| ids.iter().filter_map(|id| self.by_id.get(id)).collect())
206 .unwrap_or_default()
207 }
208
209 pub fn sorted_caches(&self) -> Arc<RwLock<HashMap<String, SortedViewCache>>> {
210 self.sorted_caches.clone()
211 }
212
213 pub async fn init_sorted_cache(
214 &self,
215 view_id: &str,
216 sort_field: Vec<String>,
217 order: SortOrder,
218 ) {
219 let mut caches = self.sorted_caches.write().await;
220 if !caches.contains_key(view_id) {
221 caches.insert(
222 view_id.to_string(),
223 SortedViewCache::new(view_id.to_string(), sort_field, order),
224 );
225 }
226 }
227
228 fn init_sorted_cache_sync(&mut self, view_id: &str, sort_field: Vec<String>, order: SortOrder) {
229 let cache = SortedViewCache::new(view_id.to_string(), sort_field, order);
230 let caches = Arc::get_mut(&mut self.sorted_caches)
231 .expect("Cannot initialize sorted cache: Arc is shared");
232 let caches = caches.get_mut();
233 if !caches.contains_key(view_id) {
234 caches.insert(view_id.to_string(), cache);
235 }
236 }
237}
238
239impl Default for ViewIndex {
240 fn default() -> Self {
241 Self::new()
242 }
243}