teo_runtime/namespace/
namespace.rs

1use std::collections::BTreeMap;
2use std::ops::Deref;
3use std::sync::{Arc, Mutex};
4use crate::{interface, middleware, model, model::Model, r#enum};
5use crate::config::client::Client;
6use crate::config::connector::Connector;
7use crate::config::debug::Debug;
8use crate::config::entity::Entity;
9use crate::config::server::Server;
10use crate::connection::connection::Connection;
11use crate::handler;
12use crate::interface::Interface;
13use crate::model::relation::Relation;
14use crate::r#enum::Enum;
15use crate::r#struct::Struct;
16use crate::database::database::Database;
17use crate::pipeline;
18use educe::Educe;
19use serde::Serialize;
20use crate::app::data::AppData;
21use crate::config::admin::Admin;
22use crate::handler::Handler;
23use crate::middleware::Middleware;
24use crate::traits::named::Named;
25
26#[derive(Debug, Clone)]
27pub struct Namespace {
28    pub(super) inner: Arc<Inner>,
29}
30
31#[derive(Educe, Serialize)]
32#[educe(Debug)]
33pub(super) struct Inner {
34    pub(super) path: Vec<String>,
35    pub(super) namespaces: BTreeMap<String, Namespace>,
36    pub(super) structs: BTreeMap<String, Struct>,
37    pub(super) models: BTreeMap<String, Model>,
38    pub(super) enums: BTreeMap<String, Enum>,
39    pub(super) interfaces: BTreeMap<String, Interface>,
40    pub(super) model_decorators: BTreeMap<String, model::Decorator>,
41    pub(super) model_field_decorators: BTreeMap<String, model::field::Decorator>,
42    pub(super) model_relation_decorators: BTreeMap<String, model::relation::Decorator>,
43    pub(super) model_property_decorators: BTreeMap<String, model::property::Decorator>,
44    pub(super) enum_decorators: BTreeMap<String, r#enum::Decorator>,
45    pub(super) enum_member_decorators: BTreeMap<String, r#enum::member::Decorator>,
46    pub(super) interface_decorators: BTreeMap<String, interface::Decorator>,
47    pub(super) interface_field_decorators: BTreeMap<String, interface::field::Decorator>,
48    pub(super) handler_decorators: BTreeMap<String, handler::Decorator>,
49    pub(super) pipeline_items: BTreeMap<String, pipeline::Item>,
50    pub(super) handler_middlewares: BTreeMap<String, middleware::Definition>,
51    pub(super) request_middlewares: BTreeMap<String, middleware::Definition>,
52    pub(super) handlers: BTreeMap<String, Handler>,
53    pub(super) handler_templates: BTreeMap<String, Handler>,
54    pub(super) model_handler_groups: BTreeMap<String, handler::Group>,
55    pub(super) handler_groups: BTreeMap<String, handler::Group>,
56    pub(super) server: Option<Server>,
57    pub(super) connector: Option<Connector>,
58    pub(super) clients: BTreeMap<String, Client>,
59    pub(super) entities: BTreeMap<String, Entity>,
60    pub(super) debug: Option<Debug>,
61    pub(super) admin: Option<Admin>,
62    pub(super) handler_middlewares_block: Option<middleware::Block>,
63    pub(super) request_middlewares_block: Option<middleware::Block>,
64    pub(super) database: Option<Database>,
65    pub(super) connector_reference: Option<Vec<String>>,
66    #[serde(skip)]
67    pub(super) connection: Arc<Mutex<Option<Arc<dyn Connection>>>>,
68    #[educe(Debug(ignore))] #[serde(skip)]
69    pub(super) handler_middleware_stack: Middleware,
70    #[educe(Debug(ignore))] #[serde(skip)]
71    pub(super) request_middleware_stack: Middleware,
72    #[educe(Debug(ignore))] #[serde(skip)]
73    pub(super) handler_map: handler::Map,
74    pub(super) model_opposite_relations_map: BTreeMap<Vec<String>, Vec<(Vec<String>, String)>>,
75    #[serde(skip)]
76    pub(super) app_data: AppData,
77}
78
79impl Serialize for Namespace {
80    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
81        self.inner.serialize(serializer)
82    }
83}
84
85impl Namespace {
86
87    pub fn is_main(&self) -> bool {
88        self.inner.path.is_empty()
89    }
90
91    pub fn is_std(&self) -> bool {
92        self.path().len() == 1 && self.path().first().unwrap().as_str() == "std"
93    }
94
95    pub fn path(&self) -> &Vec<String> {
96        &self.inner.path
97    }
98
99    pub fn namespaces(&self) -> &BTreeMap<String, Namespace> {
100        &self.inner.namespaces
101    }
102
103    pub fn structs(&self) -> &BTreeMap<String, Struct> {
104        &self.inner.structs
105    }
106
107    pub fn models(&self) -> &BTreeMap<String, Model> {
108        &self.inner.models
109    }
110
111    pub fn enums(&self) -> &BTreeMap<String, Enum> {
112        &self.inner.enums
113    }
114
115    pub fn interfaces(&self) -> &BTreeMap<String, Interface> {
116        &self.inner.interfaces
117    }
118
119    pub fn model_decorators(&self) -> &BTreeMap<String, model::Decorator> {
120        &self.inner.model_decorators
121    }
122
123    pub fn model_field_decorators(&self) -> &BTreeMap<String, model::field::Decorator> {
124        &self.inner.model_field_decorators
125    }
126
127    pub fn model_relation_decorators(&self) -> &BTreeMap<String, model::relation::Decorator> {
128        &self.inner.model_relation_decorators
129    }
130
131    pub fn model_property_decorators(&self) -> &BTreeMap<String, model::property::Decorator> {
132        &self.inner.model_property_decorators
133    }
134
135    pub fn enum_decorators(&self) -> &BTreeMap<String, r#enum::Decorator> {
136        &self.inner.enum_decorators
137    }
138
139    pub fn enum_member_decorators(&self) -> &BTreeMap<String, r#enum::member::Decorator> {
140        &self.inner.enum_member_decorators
141    }
142
143    pub fn interface_decorators(&self) -> &BTreeMap<String, interface::Decorator> {
144        &self.inner.interface_decorators
145    }
146
147    pub fn interface_field_decorators(&self) -> &BTreeMap<String, interface::field::Decorator> {
148        &self.inner.interface_field_decorators
149    }
150
151    pub fn handler_decorators(&self) -> &BTreeMap<String, handler::Decorator> {
152        &self.inner.handler_decorators
153    }
154
155    pub fn pipeline_items(&self) -> &BTreeMap<String, pipeline::Item> {
156        &self.inner.pipeline_items
157    }
158
159    pub fn handler_middlewares(&self) -> &BTreeMap<String, middleware::Definition> {
160        &self.inner.handler_middlewares
161    }
162
163    pub fn request_middlewares(&self) -> &BTreeMap<String, middleware::Definition> {
164        &self.inner.request_middlewares
165    }
166
167    pub fn handlers(&self) -> &BTreeMap<String, Handler> {
168        &self.inner.handlers
169    }
170
171    pub fn handler_groups(&self) -> &BTreeMap<String, handler::Group> {
172        &self.inner.handler_groups
173    }
174
175    pub fn handler_templates(&self) -> &BTreeMap<String, Handler> {
176        &self.inner.handler_templates
177    }
178
179    pub fn model_handler_groups(&self) -> &BTreeMap<String, handler::Group> {
180        &self.inner.model_handler_groups
181    }
182
183    pub fn server(&self) -> Option<&Server> {
184        self.inner.server.as_ref()
185    }
186
187    pub fn connector(&self) -> Option<&Connector> {
188        self.inner.connector.as_ref()
189    }
190
191    pub fn connection(&self) -> Option<Arc<dyn Connection>> {
192        self.inner.connection.lock().unwrap().as_ref().cloned()
193    }
194
195    pub fn set_connection(&self, connection: Option<Arc<dyn Connection>>) {
196        *self.inner.connection.lock().unwrap() = connection;
197    }
198
199    pub fn admin(&self) -> Option<&Admin> {
200        self.inner.admin.as_ref()
201    }
202
203    pub fn debug(&self) -> Option<&Debug> {
204        self.inner.debug.as_ref()
205    }
206
207    pub fn handler_middlewares_block(&self) -> Option<&middleware::Block> {
208        self.inner.handler_middlewares_block.as_ref()
209    }
210
211    pub fn request_middlewares_block(&self) -> Option<&middleware::Block> {
212        self.inner.request_middlewares_block.as_ref()
213    }
214
215    pub fn entities(&self) -> &BTreeMap<String, Entity> {
216        &self.inner.entities
217    }
218
219    pub fn clients(&self) -> &BTreeMap<String, Client> {
220        &self.inner.clients
221    }
222
223    pub fn database(&self) -> Option<&Database> {
224        self.inner.database.as_ref()
225    }
226
227    pub fn handler_middleware_stack(&self) -> Middleware {
228        self.inner.handler_middleware_stack.clone()
229    }
230
231    pub fn request_middleware_stack(&self) -> Middleware {
232        self.inner.request_middleware_stack.clone()
233    }
234
235    pub fn handler_map(&self) -> &handler::Map {
236        &self.inner.handler_map
237    }
238
239    pub fn namespace(&self, name: &str) -> Option<&Namespace> {
240        self.inner.namespaces.get(name)
241    }
242
243    pub fn namespace_at_path(&self, path: &Vec<String>) -> Option<&Namespace> {
244        let mut current = Some(self);
245        for item in path {
246            if current.is_none() {
247                return None;
248            }
249            current = current.unwrap().namespace(item);
250        }
251        current
252    }
253
254    pub fn model_decorator_at_path(&self, path: &Vec<String>) -> Option<&model::Decorator> {
255        let decorator_name = path.last().unwrap();
256        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
257        if let Some(ns) = self.namespace_at_path(&namespace_path) {
258            ns.inner.model_decorators.get(decorator_name)
259        } else {
260            None
261        }
262    }
263
264    pub fn model_field_decorator_at_path(&self, path: &Vec<String>) -> Option<&model::field::Decorator> {
265        let decorator_name = path.last().unwrap();
266        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
267        if let Some(ns) = self.namespace_at_path(&namespace_path) {
268            ns.inner.model_field_decorators.get(decorator_name)
269        } else {
270            None
271        }
272    }
273
274    pub fn model_relation_decorator_at_path(&self, path: &Vec<String>) -> Option<&model::relation::Decorator> {
275        let decorator_name = path.last().unwrap();
276        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
277        if let Some(ns) = self.namespace_at_path(&namespace_path) {
278            ns.inner.model_relation_decorators.get(decorator_name)
279        } else {
280            None
281        }
282    }
283
284    pub fn model_property_decorator_at_path(&self, path: &Vec<String>) -> Option<&model::property::Decorator> {
285        let decorator_name = path.last().unwrap();
286        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
287        if let Some(ns) = self.namespace_at_path(&namespace_path) {
288            ns.inner.model_property_decorators.get(decorator_name)
289        } else {
290            None
291        }
292    }
293
294    pub fn enum_decorator_at_path(&self, path: &Vec<String>) -> Option<&r#enum::Decorator> {
295        let decorator_name = path.last().unwrap();
296        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
297        if let Some(ns) = self.namespace_at_path(&namespace_path) {
298            ns.inner.enum_decorators.get(decorator_name)
299        } else {
300            None
301        }
302    }
303
304    pub fn enum_member_decorator_at_path(&self, path: &Vec<String>) -> Option<&r#enum::member::Decorator> {
305        let decorator_name = path.last().unwrap();
306        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
307        if let Some(ns) = self.namespace_at_path(&namespace_path) {
308            ns.inner.enum_member_decorators.get(decorator_name)
309        } else {
310            None
311        }
312    }
313
314    pub fn interface_decorator_at_path(&self, path: &Vec<String>) -> Option<&interface::Decorator> {
315        let decorator_name = path.last().unwrap();
316        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
317        if let Some(ns) = self.namespace_at_path(&namespace_path) {
318            ns.inner.interface_decorators.get(decorator_name)
319        } else {
320            None
321        }
322    }
323
324    pub fn interface_field_decorator_at_path(&self, path: &Vec<String>) -> Option<&interface::field::Decorator> {
325        let decorator_name = path.last().unwrap();
326        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
327        if let Some(ns) = self.namespace_at_path(&namespace_path) {
328            ns.inner.interface_field_decorators.get(decorator_name)
329        } else {
330            None
331        }
332    }
333
334    pub fn handler_decorator_at_path(&self, path: &Vec<String>) -> Option<&handler::Decorator> {
335        let decorator_name = path.last().unwrap();
336        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
337        if let Some(ns) = self.namespace_at_path(&namespace_path) {
338            ns.inner.handler_decorators.get(decorator_name)
339        } else {
340            None
341        }
342    }
343
344    pub fn pipeline_item_at_path(&self, path: &Vec<String>) -> Option<&pipeline::Item> {
345        let pipeline_item_name = path.last().unwrap();
346        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
347        if let Some(ns) = self.namespace_at_path(&namespace_path) {
348            ns.inner.pipeline_items.get(pipeline_item_name)
349        } else {
350            None
351        }
352    }
353
354    pub fn struct_at_path(&self, path: &Vec<String>) -> Option<&Struct> {
355        let struct_name = path.last().unwrap();
356        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
357        if let Some(ns) = self.namespace_at_path(&namespace_path) {
358            ns.inner.structs.get(struct_name)
359        } else {
360            None
361        }
362    }
363
364    pub fn enum_at_path(&self, path: &Vec<String>) -> Option<&Enum> {
365        let enum_name = path.last().unwrap();
366        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
367        if let Some(ns) = self.namespace_at_path(&namespace_path) {
368            ns.inner.enums.get(enum_name)
369        } else {
370            None
371        }
372    }
373
374    pub fn model_at_path(&self, path: &Vec<String>) -> Option<&Model> {
375        let model_name = path.last().unwrap();
376        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
377        if let Some(ns) = self.namespace_at_path(&namespace_path) {
378            ns.inner.models.get(model_name)
379        } else {
380            None
381        }
382    }
383
384    pub fn interface_at_path(&self, path: &Vec<String>) -> Option<&Interface> {
385        let interface_name = path.last().unwrap();
386        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
387        if let Some(ns) = self.namespace_at_path(&namespace_path) {
388            ns.inner.interfaces.get(interface_name)
389        } else {
390            None
391        }
392    }
393
394    pub fn handler_middleware_at_path(&self, path: &Vec<String>) -> Option<&middleware::Definition> {
395        let middleware_name = path.last().unwrap();
396        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
397        if let Some(ns) = self.namespace_at_path(&namespace_path) {
398            ns.inner.handler_middlewares.get(middleware_name)
399        } else {
400            None
401        }
402    }
403
404    pub fn request_middleware_at_path(&self, path: &Vec<String>) -> Option<&middleware::Definition> {
405        let middleware_name = path.last().unwrap();
406        let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
407        if let Some(ns) = self.namespace_at_path(&namespace_path) {
408            ns.inner.request_middlewares.get(middleware_name)
409        } else {
410            None
411        }
412    }
413
414    pub fn handler_template_at_path(&self, path: &Vec<String>) -> Option<&Handler> {
415        let handler_name = path.last().unwrap();
416        if path.len() == 1 {
417            self.inner.handler_templates.get(handler_name)
418        } else {
419            // try find a namespace first
420            let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.to_string()).collect();
421            if let Some(dest_namespace) = self.namespace_at_path(&namespace_path) {
422                dest_namespace.inner.handler_templates.get(handler_name)
423            } else {
424                None
425            }
426        }
427    }
428
429    pub fn handler_at_path(&self, path: &Vec<String>) -> Option<&Handler> {
430        let handler_name = path.last().unwrap();
431        if path.len() == 1 {
432            self.inner.handlers.get(handler_name)
433        } else {
434            // try finding a namespace first
435            let namespace_path: Vec<String> = path.into_iter().rev().skip(1).rev().map(|i| i.clone()).collect();
436            if let Some(dest_namespace) = self.namespace_at_path(&namespace_path) {
437                dest_namespace.inner.handlers.get(handler_name)
438            } else {
439                // try finding in group
440                let handler_name = path.last().unwrap();
441                let group_name = path.get(path.len() - 2).unwrap().deref();
442                let namespace_path: Vec<String> = path.into_iter().rev().skip(2).rev().map(|i| i.clone()).collect();
443                if let Some(dest_namespace) = self.namespace_at_path(&namespace_path) {
444                    if let Some(group) = dest_namespace.inner.handler_groups.get(group_name) {
445                        group.handler(handler_name)
446                    } else if let Some(group) = dest_namespace.inner.model_handler_groups.get(group_name) {
447                        group.handler(handler_name)
448                    } else {
449                        None
450                    }
451                } else {
452                    None
453                }
454            }
455        }
456    }
457
458    pub fn connector_reference(&self) -> Option<&Vec<String>> {
459        self.inner.connector_reference.as_ref()
460    }
461
462    /// Returns the opposite relation of the argument relation.
463    ///
464    /// # Arguments
465    ///
466    /// * `relation` - The relation must be of a model of this graph.
467    ///
468    /// # Return Value
469    ///
470    /// A tuple of opposite relation's model and opposite relation.
471    ///
472    pub fn opposite_relation(&self, relation: &Relation) -> (&Model, Option<&Relation>) {
473        let opposite_model = self.model_at_path(&relation.model_path()).unwrap();
474        let opposite_relation = opposite_model.relations().values().find(|r| r.fields() == relation.references() && r.references() == relation.fields());
475        (opposite_model, opposite_relation)
476    }
477
478    /// Returns the through relation of the argument relation.
479    ///
480    /// # Arguments
481    ///
482    /// * `relation` - The relation must be of a model of this graph. This relation must be a
483    /// through relation.
484    ///
485    /// # Return Value
486    ///
487    /// A tuple of through relation's model and through model's local relation.
488    ///
489    pub fn through_relation(&self, relation: &Relation) -> (&Model, &Relation) {
490        let through_model = self.model_at_path(&relation.through_path().unwrap()).unwrap();
491        let through_local_relation = through_model.relation(relation.local().unwrap()).unwrap();
492        (through_model, through_local_relation)
493    }
494
495    /// Returns the through opposite relation of the argument relation.
496    ///
497    /// # Arguments
498    ///
499    /// * `relation` - The relation must be of a model of this graph. This relation must be a
500    /// through relation.
501    ///
502    /// # Return Value
503    ///
504    /// A tuple of through relation's model and through model's foreign relation.
505    ///
506    pub fn through_opposite_relation(&self, relation: &Relation) -> (&Model, &Relation) {
507        let through_model = self.model_at_path(&relation.through_path().unwrap()).unwrap();
508        let through_foreign_relation = through_model.relation(relation.foreign().unwrap()).unwrap();
509        (through_model, through_foreign_relation)
510    }
511
512    pub fn models_under_connector(&self) -> Vec<&Model> {
513        let mut result = vec![];
514        for model in self.inner.models.values() {
515            result.push(model);
516        }
517        for n in self.inner.namespaces.values() {
518            if !n.inner.connector.is_some() {
519                result.extend(n.models_under_connector());
520            }
521        }
522        result
523    }
524
525    /// Get relations of model defined by related model
526    pub fn model_opposite_relations(&self, model: &Model) -> Vec<(&Model, &Relation)> {
527        let result = self.inner.model_opposite_relations_map.get(model.path()).unwrap();
528        result.iter().map(|result| {
529            let model = self.model_at_path(&result.0).unwrap();
530            let relation = model.relation(result.1.as_str()).unwrap();
531            (model, relation)
532        }).collect()
533    }
534
535    pub fn collect_models<F>(&self, f: F) -> Vec<&Model> where F: Fn(&Model) -> bool {
536        let filter = &f;
537        self._collect_models(filter)
538    }
539
540    pub fn _collect_models<F>(&self, f: &F) -> Vec<&Model> where F: Fn(&Model) -> bool {
541        let mut result = vec![];
542        result.extend(self.inner.models.values().filter(|m| f(*m)));
543        for n in self.inner.namespaces.values() {
544            result.extend(n._collect_models(f));
545        }
546        result
547    }
548
549    pub fn collect_enums<F>(&self, f: F) -> Vec<&Enum> where F: Fn(&Enum) -> bool {
550        let filter = &f;
551        self._collect_enums(filter)
552    }
553
554    pub fn _collect_enums<F>(&self, f: &F) -> Vec<&Enum> where F: Fn(&Enum) -> bool {
555        let mut result = vec![];
556        result.extend(self.inner.enums.values().filter(|m| f(*m)));
557        for n in self.inner.namespaces.values() {
558            result.extend(n._collect_enums(f));
559        }
560        result
561    }
562
563    pub fn app_data(&self) -> &AppData {
564        &self.inner.app_data
565    }
566}
567
568impl Named for Namespace {
569
570    fn name(&self) -> &str {
571        if self.path().is_empty() {
572            "main"
573        } else {
574            self.path().last().unwrap()
575        }
576    }
577}
578
579unsafe impl Send for Namespace { }
580unsafe impl Sync for Namespace { }