sea_core/primitives/
instance.rs

1use crate::ConceptId;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::HashMap;
5
6const DEFAULT_NAMESPACE: &str = "default";
7
8/// Represents a concrete instance of an Entity with specific field values.
9///
10/// Instances allow defining specific data objects in the DSL that can be
11/// referenced in policies and flows.
12///
13/// # Examples
14///
15/// ```
16/// use sea_core::primitives::Instance;
17/// use serde_json::json;
18///
19/// let mut vendor = Instance::new_with_namespace("vendor_123", "Vendor", "default");
20/// vendor.set_field("name", json!("Acme Corp"));
21/// vendor.set_field("credit_limit", json!(50000));
22///
23/// assert_eq!(vendor.entity_type(), "Vendor");
24/// assert_eq!(vendor.get_field("name"), Some(&json!("Acme Corp")));
25/// ```
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27pub struct Instance {
28    id: ConceptId,
29    name: String,
30    entity_type: String,
31    namespace: String,
32    fields: HashMap<String, Value>,
33}
34
35impl Instance {
36    /// Creates a new Instance (default namespace).
37    pub fn new(name: impl Into<String>, entity_type: impl Into<String>) -> Self {
38        Self::new_with_namespace(name, entity_type, DEFAULT_NAMESPACE)
39    }
40
41    pub fn new_with_namespace(
42        name: impl Into<String>,
43        entity_type: impl Into<String>,
44        namespace: impl Into<String>,
45    ) -> Self {
46        let namespace = namespace.into();
47        let name = name.into();
48        let entity_type = entity_type.into();
49        let id = ConceptId::from_concept(&namespace, &format!("{}:{}", entity_type, name));
50
51        Self {
52            id,
53            name,
54            entity_type,
55            namespace,
56            fields: HashMap::new(),
57        }
58    }
59
60    pub fn id(&self) -> &ConceptId {
61        &self.id
62    }
63
64    pub fn name(&self) -> &str {
65        &self.name
66    }
67
68    pub fn entity_type(&self) -> &str {
69        &self.entity_type
70    }
71
72    pub fn namespace(&self) -> &str {
73        &self.namespace
74    }
75
76    pub fn set_field(&mut self, key: impl Into<String>, value: Value) {
77        self.fields.insert(key.into(), value);
78    }
79
80    pub fn get_field(&self, key: &str) -> Option<&Value> {
81        self.fields.get(key)
82    }
83
84    /// Returns all fields as a reference.
85    pub fn fields(&self) -> &HashMap<String, Value> {
86        &self.fields
87    }
88
89    /// Returns a mutable reference to fields for bulk updates.
90    pub fn fields_mut(&mut self) -> &mut HashMap<String, Value> {
91        &mut self.fields
92    }
93}