memlink-runtime 0.2.0

Dynamic module loading framework with circuit breaker, caching, pooling, health checks, versioning, and auto-discovery
Documentation
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Module dependency tracking and composition.
//!
//! Manages dependencies between modules, load order, and nested calls.

use std::collections::{HashMap, HashSet, VecDeque};

use dashmap::DashMap;

use crate::error::{Error, Result};

/// Dependency information for a module.
#[derive(Debug, Clone)]
pub struct ModuleDependency {
    /// Name of the required module.
    pub name: String,
    /// Minimum version required (optional).
    pub min_version: Option<String>,
    /// Whether this dependency is optional.
    pub optional: bool,
}

/// Dependency graph node.
#[derive(Debug, Clone)]
pub struct DependencyNode {
    /// Module name.
    pub name: String,
    /// Dependencies this module requires.
    pub dependencies: Vec<ModuleDependency>,
    /// Modules that depend on this one (reverse deps).
    pub dependents: HashSet<String>,
    /// Whether the module is loaded.
    pub loaded: bool,
}

/// Module dependency graph.
#[derive(Debug)]
pub struct DependencyGraph {
    /// All nodes in the graph.
    nodes: DashMap<String, DependencyNode>,
}

impl DependencyGraph {
    /// Creates a new empty dependency graph.
    pub fn new() -> Self {
        Self {
            nodes: DashMap::new(),
        }
    }

    /// Adds a module to the graph.
    pub fn add_module(&self, name: &str, dependencies: Vec<ModuleDependency>) {
        let node = DependencyNode {
            name: name.to_string(),
            dependencies,
            dependents: HashSet::new(),
            loaded: false,
        };
        self.nodes.insert(name.to_string(), node);
    }

    /// Marks a module as loaded.
    pub fn mark_loaded(&self, name: &str) {
        if let Some(mut node) = self.nodes.get_mut(name) {
            node.loaded = true;
        }
    }

    /// Marks a module as unloaded.
    pub fn mark_unloaded(&self, name: &str) {
        if let Some(mut node) = self.nodes.get_mut(name) {
            node.loaded = false;
        }
    }

    /// Checks if all dependencies of a module are satisfied.
    pub fn dependencies_satisfied(&self, name: &str) -> bool {
        let node = match self.nodes.get(name) {
            Some(n) => n,
            None => return false,
        };

        for dep in &node.dependencies {
            if dep.optional {
                continue;
            }

            let dep_node = match self.nodes.get(&dep.name) {
                Some(n) => n,
                None => return false, // Dependency not registered
            };

            if !dep_node.loaded {
                return false; // Dependency not loaded
            }
        }

        true
    }

    /// Returns the load order for all modules (topological sort).
    ///
    /// Returns modules in order they should be loaded (dependencies first).
    pub fn load_order(&self) -> Result<Vec<String>> {
        // Kahn's algorithm for topological sort
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        let mut queue: VecDeque<String> = VecDeque::new();
        let mut result: Vec<String> = Vec::new();

        // Calculate in-degrees
        for entry in self.nodes.iter() {
            let name = entry.key().clone();
            let node = entry.value();
            let required_deps = node.dependencies.iter().filter(|d| !d.optional).count();
            in_degree.insert(name.clone(), required_deps);

            if required_deps == 0 {
                queue.push_back(name.clone());
            }
        }

        // Process queue
        while let Some(name) = queue.pop_front() {
            result.push(name.clone());

            // Reduce in-degree for dependents
            for entry in self.nodes.iter() {
                let node = entry.value();
                if node.dependencies.iter().any(|d| d.name == name && !d.optional) {
                    let in_deg = in_degree.get_mut(entry.key()).unwrap();
                    *in_deg -= 1;
                    if *in_deg == 0 {
                        queue.push_back(entry.key().clone());
                    }
                }
            }
        }

        // Check for cycles
        if result.len() != self.nodes.len() {
            return Err(Error::ModuleCallFailed(-1)); // Would be CircularDependency error
        }

        Ok(result)
    }

    /// Returns the unload order (reverse of load order).
    pub fn unload_order(&self) -> Result<Vec<String>> {
        let mut order = self.load_order()?;
        order.reverse();
        Ok(order)
    }

    /// Detects circular dependencies.
    pub fn has_cycle(&self) -> bool {
        self.load_order().is_err()
    }

    /// Returns all dependencies (transitive) for a module.
    pub fn all_dependencies(&self, name: &str) -> HashSet<String> {
        let mut result = HashSet::new();
        let mut queue: VecDeque<String> = VecDeque::new();

        if let Some(node) = self.nodes.get(name) {
            for dep in &node.dependencies {
                queue.push_back(dep.name.clone());
            }
        }

        while let Some(dep_name) = queue.pop_front() {
            if result.contains(&dep_name) {
                continue;
            }
            result.insert(dep_name.clone());

            if let Some(dep_node) = self.nodes.get(&dep_name) {
                for sub_dep in &dep_node.dependencies {
                    queue.push_back(sub_dep.name.clone());
                }
            }
        }

        result
    }

    /// Returns all modules that depend on the given module (transitive).
    pub fn all_dependents(&self, name: &str) -> HashSet<String> {
        let mut result = HashSet::new();
        let mut queue: VecDeque<String> = VecDeque::new();

        // Find direct dependents
        for entry in self.nodes.iter() {
            let node = entry.value();
            if node.dependencies.iter().any(|d| d.name == name) {
                queue.push_back(entry.key().clone());
            }
        }

        while let Some(dep_name) = queue.pop_front() {
            if result.contains(&dep_name) {
                continue;
            }
            result.insert(dep_name.clone());

            // Find dependents of this dependent
            for entry in self.nodes.iter() {
                let node = entry.value();
                if node.dependencies.iter().any(|d| d.name == dep_name) {
                    queue.push_back(entry.key().clone());
                }
            }
        }

        result
    }

    /// Checks if a module can be safely unloaded (no loaded dependents).
    pub fn can_unload(&self, name: &str) -> bool {
        let dependents = self.all_dependents(name);

        for dep_name in &dependents {
            if let Some(node) = self.nodes.get(dep_name) {
                if node.loaded {
                    return false; // Has loaded dependent
                }
            }
        }

        true
    }

    /// Returns the number of registered modules.
    pub fn module_count(&self) -> usize {
        self.nodes.len()
    }

    /// Returns all module names.
    pub fn all_modules(&self) -> Vec<String> {
        self.nodes.iter().map(|e| e.key().clone()).collect()
    }

    /// Returns information about a specific module.
    pub fn get_module(&self, name: &str) -> Option<DependencyNode> {
        self.nodes.get(name).map(|e| e.value().clone())
    }
}

impl Default for DependencyGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Context for nested module calls.
#[derive(Debug, Clone)]
pub struct CallContext {
    /// The calling module (if any).
    pub caller: Option<String>,
    /// The target module.
    pub target: String,
    /// Current call depth.
    pub depth: usize,
    /// Maximum allowed depth.
    pub max_depth: usize,
    /// Trace ID for distributed tracing.
    pub trace_id: Option<u128>,
}

impl CallContext {
    /// Creates a new root call context.
    pub fn new(target: String) -> Self {
        Self {
            caller: None,
            target,
            depth: 0,
            max_depth: 10,
            trace_id: None,
        }
    }

    /// Creates a child context for a nested call.
    pub fn child(&self, target: String) -> Option<Self> {
        if self.depth >= self.max_depth {
            return None; // Max depth exceeded
        }

        Some(Self {
            caller: Some(self.target.clone()),
            target,
            depth: self.depth + 1,
            max_depth: self.max_depth,
            trace_id: self.trace_id,
        })
    }

    /// Returns whether this is a root call (not nested).
    pub fn is_root(&self) -> bool {
        self.caller.is_none()
    }

    /// Returns whether this is a nested call.
    pub fn is_nested(&self) -> bool {
        self.caller.is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dependency_graph_basic() {
        let graph = DependencyGraph::new();

        graph.add_module("A", vec![]);
        graph.add_module("B", vec![
            ModuleDependency { name: "A".to_string(), min_version: None, optional: false }
        ]);
        graph.add_module("C", vec![
            ModuleDependency { name: "B".to_string(), min_version: None, optional: false }
        ]);

        // Load order should be A, B, C
        let order = graph.load_order().unwrap();
        assert_eq!(order, vec!["A", "B", "C"]);

        // Unload order should be C, B, A
        let order = graph.unload_order().unwrap();
        assert_eq!(order, vec!["C", "B", "A"]);
    }

    #[test]
    fn test_dependency_graph_optional() {
        let graph = DependencyGraph::new();

        graph.add_module("A", vec![]);
        graph.add_module("B", vec![
            ModuleDependency { name: "A".to_string(), min_version: None, optional: true }
        ]);

        // B can load even if A is not loaded (optional dependency)
        graph.mark_loaded("B");
        assert!(graph.dependencies_satisfied("B"));
    }

    #[test]
    fn test_dependency_graph_cycle_detection() {
        let graph = DependencyGraph::new();

        graph.add_module("A", vec![
            ModuleDependency { name: "B".to_string(), min_version: None, optional: false }
        ]);
        graph.add_module("B", vec![
            ModuleDependency { name: "A".to_string(), min_version: None, optional: false }
        ]);

        // Should detect cycle
        assert!(graph.has_cycle());
        assert!(graph.load_order().is_err());
    }

    #[test]
    fn test_call_context_depth() {
        let root = CallContext::new("A".to_string());
        assert_eq!(root.depth, 0);
        assert!(root.is_root());

        let child1 = root.child("B".to_string()).unwrap();
        assert_eq!(child1.depth, 1);
        assert!(child1.is_nested());

        let child2 = child1.child("C".to_string()).unwrap();
        assert_eq!(child2.depth, 2);

        // Test max depth
        let mut ctx = root;
        for i in 0..10 {
            if let Some(next) = ctx.child(format!("M{}", i)) {
                ctx = next;
            }
        }
        // 11th level should fail
        assert!(ctx.child("M10".to_string()).is_none());
    }

    #[test]
    fn test_transitive_dependencies() {
        let graph = DependencyGraph::new();

        graph.add_module("A", vec![]);
        graph.add_module("B", vec![
            ModuleDependency { name: "A".to_string(), min_version: None, optional: false }
        ]);
        graph.add_module("C", vec![
            ModuleDependency { name: "B".to_string(), min_version: None, optional: false }
        ]);

        // C's transitive dependencies should include A and B
        let deps = graph.all_dependencies("C");
        assert!(deps.contains("A"));
        assert!(deps.contains("B"));
        assert_eq!(deps.len(), 2);
    }

    #[test]
    fn test_can_unload() {
        let graph = DependencyGraph::new();

        graph.add_module("A", vec![]);
        graph.add_module("B", vec![
            ModuleDependency { name: "A".to_string(), min_version: None, optional: false }
        ]);

        graph.mark_loaded("A");
        graph.mark_loaded("B");

        // Can't unload A because B depends on it and is loaded
        assert!(!graph.can_unload("A"));

        // Can unload B
        assert!(graph.can_unload("B"));

        // After unloading B, can unload A
        graph.mark_unloaded("B");
        assert!(graph.can_unload("A"));
    }
}