1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! Node registry for dynamic behavior instantiation
//!
//! This module provides the `NodeRegistry` for registering and creating behavior nodes
//! from string identifiers and JSON configuration.
use crate::BoxedBehavior;
use anyhow::{anyhow, Context as AnyhowContext, Result};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
pub type NodeFactory = Arc<dyn Fn(Value) -> Result<BoxedBehavior> + Send + Sync>;
#[derive(Clone)]
pub struct NodeRegistry {
factories: Arc<RwLock<HashMap<String, NodeFactory>>>,
}
impl NodeRegistry {
/// Create a new empty node registry.
pub fn new() -> Self {
Self {
factories: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Register a node type with a factory function.
///
/// The factory function will be called each time a node of this type is created.
/// It receives the JSON configuration and should return a boxed behavior node.
///
/// # Arguments
///
/// * `node_type` - String identifier for this node type (e.g., "move_to_goal")
/// * `factory` - Function that creates instances of this node type
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
/// use serde_json::json;
///
/// # #[derive(Debug)]
/// # struct MoveBehavior { speed: f64 }
/// # #[async_trait::async_trait]
/// # impl mecha10_behavior_runtime::BehaviorNode for MoveBehavior {
/// # async fn tick(&mut self, _ctx: &mecha10_behavior_runtime::Context) -> anyhow::Result<mecha10_behavior_runtime::NodeStatus> {
/// # Ok(mecha10_behavior_runtime::NodeStatus::Success)
/// # }
/// # }
///
/// let mut registry = NodeRegistry::new();
///
/// registry.register("move", |config| {
/// let speed = config.get("speed")
/// .and_then(|v| v.as_f64())
/// .unwrap_or(1.0);
/// Ok(Box::new(MoveBehavior { speed }))
/// });
/// ```
pub fn register<F>(&mut self, node_type: impl Into<String>, factory: F)
where
F: Fn(Value) -> Result<BoxedBehavior> + Send + Sync + 'static,
{
let mut factories = self.factories.write().unwrap();
factories.insert(node_type.into(), Arc::new(factory));
}
/// Create a node instance from a registered type.
///
/// This looks up the factory function for the given node type and calls it
/// with the provided configuration to create a new instance.
///
/// # Arguments
///
/// * `node_type` - The type identifier that was used during registration
/// * `config` - JSON configuration to pass to the factory function
///
/// # Returns
///
/// A boxed behavior node instance, or an error if:
/// - The node type is not registered
/// - The factory function returns an error
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
/// use serde_json::json;
///
/// # let mut registry = NodeRegistry::new();
/// # registry.register("move", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
///
/// let config = json!({ "speed": 2.0 });
/// let node = registry.create("move", config).unwrap();
/// ```
pub fn create(&self, node_type: &str, config: Value) -> Result<BoxedBehavior> {
let factories = self.factories.read().unwrap();
let factory = factories
.get(node_type)
.ok_or_else(|| anyhow!("Node type '{}' not registered", node_type))?;
factory(config).with_context(|| format!("Failed to create node of type '{}'", node_type))
}
/// Check if a node type is registered.
///
/// # Arguments
///
/// * `node_type` - The type identifier to check
///
/// # Returns
///
/// `true` if the node type is registered, `false` otherwise
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
///
/// let mut registry = NodeRegistry::new();
/// registry.register("move", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
///
/// assert!(registry.has_node("move"));
/// assert!(!registry.has_node("unknown"));
/// ```
pub fn has_node(&self, node_type: &str) -> bool {
self.contains(node_type)
}
/// Check if a node type is registered.
///
/// Same check as [`has_node`](Self::has_node) - both names are kept since callers use
/// either spelling, but the lookup itself lives here to avoid duplicating the `RwLock` read.
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
///
/// let mut registry = NodeRegistry::new();
/// registry.register("move", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
///
/// assert!(registry.contains("move"));
/// assert!(!registry.contains("unknown"));
/// ```
pub fn contains(&self, node_type: &str) -> bool {
let factories = self.factories.read().unwrap();
factories.contains_key(node_type)
}
/// Get a list of all registered node types.
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
///
/// let mut registry = NodeRegistry::new();
/// registry.register("move", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
/// registry.register("rotate", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
///
/// let types = registry.registered_types();
/// assert!(types.contains(&"move".to_string()));
/// assert!(types.contains(&"rotate".to_string()));
/// ```
pub fn registered_types(&self) -> Vec<String> {
let factories = self.factories.read().unwrap();
factories.keys().cloned().collect()
}
/// Get the number of registered node types.
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
///
/// let mut registry = NodeRegistry::new();
/// assert_eq!(registry.len(), 0);
///
/// registry.register("move", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
/// assert_eq!(registry.len(), 1);
/// ```
pub fn len(&self) -> usize {
let factories = self.factories.read().unwrap();
factories.len()
}
/// Check if the registry is empty.
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::NodeRegistry;
///
/// let registry = NodeRegistry::new();
/// assert!(registry.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Default for NodeRegistry {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for NodeRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let factories = self.factories.read().unwrap();
f.debug_struct("NodeRegistry")
.field("registered_types", &factories.keys().collect::<Vec<_>>())
.finish()
}
}