mecha10-core 0.6.5

Mecha10 core runtime and foundational types
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
pub use crate::context::{
    Context, InfrastructureConfig, MinioConfig, MlflowConfig, PostgresConfig, Receiver, RedisConfig,
};

#[cfg(feature = "messaging")]
pub use crate::stream::ReceiverExt;

#[cfg(feature = "messaging")]
pub use crate::publish::ContextPublishExt;

#[cfg(feature = "messaging")]
pub use crate::rpc::{Request, Response, RpcExt};

#[cfg(feature = "messaging")]
pub use crate::rpc_streaming::{
    StreamError, StreamMessage, StreamPayload, StreamReceiver, StreamSender, StreamingRpcExt,
};

#[cfg(feature = "messaging")]
pub use crate::discovery::DiscoveryExt;
pub use crate::discovery::{NodeMetadata, NodeStatus};

pub use crate::schema::{
    CompatibilityCheck, CompatibilityMode, MessageSchema, MessageVersionInfo, SchemaEvolution, SchemaField,
    SchemaRegistryExt, SchemaVersioningExt,
};

pub use crate::auth::{AuthExt, Permission, Policy, Rule};

pub use crate::secrets::{
    EnvironmentBackend, RedisBackend, SecretBackend, SecretsConfig, SecretsManager, VaultBackend,
};

#[cfg(feature = "messaging")]
pub use crate::health::{
    HealthMonitor, HealthReport, HealthReporter, HealthReportingExt, NodeHealthInfo, SystemHealth,
};

#[cfg(feature = "messaging")]
pub use crate::behavior_interrupt::{
    BehaviorControl, BehaviorInterruptConfig, BehaviorInterruptTrigger, InterruptMode,
};

pub use crate::metrics::{Counter, Gauge, Histogram, MetricsRegistry, NodeMetrics};

pub use crate::rate_limit::{MultiKeyRateLimiter, RateLimit, RateLimiter, RateLimiterManager};

pub use crate::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig, CircuitState};

#[cfg(feature = "messaging")]
pub use crate::dead_letter::{DeadLetterConfig, DeadLetterQueue, FailedMessage};

#[cfg(feature = "schema-validation")]
pub use crate::schema_validation::{
    export_project_schema, get_node_config_schema, get_project_schema, load_and_validate_project, validate_config_file,
    validate_node_config_file, validate_node_config_json, validate_project_config, validate_project_json,
};

pub use crate::dependency::{create_graph, DependencyGraph, ShutdownPlan, StartupPlan};

#[cfg(feature = "messaging")]
pub use crate::lifecycle::{
    get_timestamp_ms, topic_node_lifecycle, topic_node_status, topic_node_trigger, ModeChanged, ModeError, ModeRequest,
    NodeLifecycleAction, NodeLifecycleEvent, NodeLifecycleStatus, NodeStatusEvent, NodeTriggerEvent,
    TOPIC_MODE_CHANGED, TOPIC_MODE_ERROR, TOPIC_MODE_REQUEST,
};

pub use crate::topic_registry::{TopicInfo, TopicRegistry, TopologyStats};

pub use crate::topic_utils::{extract_category, format_elapsed_time, TopicMetadata, Topics};

pub use crate::state::{
    FilesystemStateManager, MemoryStateManager, StateManager, StateOptions, StateSnapshot, VersionedState,
};

pub use crate::recovery::{
    BackoffStrategy, DegradationMode, RecoveryAction, RecoveryAttempt, RecoveryHistory, RecoveryManager,
    RecoveryPolicy, RecoveryPolicyBuilder, RecoveryStats,
};

#[cfg(feature = "messaging")]
pub use crate::tracing_otel::{
    JaegerExporter, SpanBuilder, SpanData, TraceContext, TraceExporter, TracedMessage, TracingConfig, TracingExt,
    TracingHandle, ZipkinExporter,
};

pub use crate::profiling::{
    measure_latency, ExecutionStats, LatencyStats, MemoryStats, PerformanceMetrics, PerformanceReport, ProfilingExt,
    ThroughputStats, TimerGuard,
};

pub use crate::service::Service;
#[cfg(feature = "messaging")]
pub use crate::service_manager::ServiceManager;

pub use crate::node::{
    fmt_node_with_controller, run_node, HealthPriority, HealthReportingConfig, HealthStatusExt, Node, NodeImpl,
    NodeTag, NodeType, RateConfig,
};

pub use crate::config::{
    env_or_default, load_and_validate, load_config, load_config_from_env, substitute_env_vars, Validate,
};

pub use crate::model::{load_labels, load_model_config, CustomLabelsConfig, ModelConfig, PreprocessingConfig};

pub use crate::builder_setter;
pub use crate::enum_str_method;
pub use crate::run_node_simple;
pub use crate::run_node_with_instance;

pub use crate::messages::Message;

pub use crate::messages::Timestamped;

pub use crate::types::*;

/// Result type with Mecha10 error
pub use crate::error::{Mecha10Error, Result};

/// async_trait macro for async trait methods
pub use async_trait::async_trait;

/// Tokio re-exports
pub use tokio::{
    self, select,
    time::{interval, sleep, timeout, Duration, Instant},
};

/// JoinHandle for background tasks
pub use tokio::task::JoinHandle;

/// Serde re-exports
pub use serde::{Deserialize, Serialize};
pub use serde_json::{self, json, Value as JsonValue};

/// `schemars` re-export (LAB-1772) -- node config structs derive `JsonSchema`
/// alongside `Serialize`/`Deserialize` so `mecha10-schema-registry` can generate
/// their JSON Schema for `mecha10 config validate`/`mecha10 lint`. See
/// `docs/validate-configs.md`.
pub use schemars::JsonSchema;

/// Tracing macros for structured logging
pub use tracing::{debug, error, info, instrument, trace, warn, Level};

/// Derive macro for Node trait
///
/// # Example
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[derive(Node)]
/// #[subscribe("/input")]
/// #[publish("/output")]
/// struct MyNode {
///     config: MyConfig,
/// }
/// ```
#[cfg(feature = "macros")]
pub use mecha10_macros::Node;

/// Derive macro for Message trait
///
/// Automatically implements: Debug, Clone, Serialize, Deserialize, Message
///
/// # Example
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[derive(Message)]
/// struct CustomMessage {
///     pub value: f32,
///     pub timestamp: u64,
/// }
/// ```
/// Derive macro for Config with validation
///
/// # Example
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[derive(Config)]
/// struct MyConfig {
///     #[validate(range = "0.0..=10.0")]
///     max_speed: f32,
/// }
/// ```
#[cfg(feature = "macros")]
pub use mecha10_macros::Config;

/// Derive macro for ConfigDefaults
///
/// Automatically generates default_* functions for config fields
///
/// # Example
/// ```rust
/// use mecha10_core::prelude::*;
///
/// #[derive(ConfigDefaults)]
/// struct MyConfig {
///     #[config(default = 10.0)]
///     max_speed: f32,
/// }
/// ```
#[cfg(feature = "macros")]
pub use mecha10_macros::ConfigDefaults;

/// Shared implementation behind `now_micros`/`now_secs`/`now_millis`, which differ only in
/// which `Duration` unit they read off the epoch offset.
fn since_epoch() -> std::time::Duration {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("Time went backwards")
}

/// Get current time in microseconds since UNIX epoch
pub fn now_micros() -> u64 {
    since_epoch().as_micros() as u64
}

/// Get current time in whole seconds since UNIX epoch
pub fn now_secs() -> u64 {
    since_epoch().as_secs()
}

/// Create a periodic interval from a frequency in Hz
///
/// This is a convenience helper that converts frequency (Hz) to a tokio interval.
/// Commonly used for periodic publishing in drivers and nodes.
///
/// # Arguments
///
/// * `hz` - Frequency in Hertz (cycles per second)
///
/// # Returns
///
/// A tokio::time::Interval that ticks at the specified frequency
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// # async fn example() {
/// // Instead of:
/// // let interval_duration = Duration::from_secs_f32(1.0 / 30.0);
/// // let mut interval = tokio::time::interval(interval_duration);
///
/// // Simply use:
/// let mut interval = interval_at_hz(30.0);
///
/// loop {
///     interval.tick().await;
///     // Publish at 30 Hz
/// }
/// # }
/// ```
pub fn interval_at_hz(hz: f32) -> tokio::time::Interval {
    let duration = std::time::Duration::from_secs_f32(1.0 / hz);
    tokio::time::interval(duration)
}

/// Initialize logging with sensible defaults
///
/// This function is safe to call multiple times - it will silently succeed if
/// a tracing subscriber is already set (e.g., when running bundled in the CLI).
///
/// The logging system will automatically include node context (node_id) in all
/// log messages when using the Context's logging methods or the `in_node_context!` macro.
///
/// Under the `messaging` feature, this also attaches
/// [`crate::log_publisher::RedisLogLayer`], the layer that ships captured
/// log events to Redis on `/system/log` once `crate::log_publisher::attach`
/// has been called with a live `Context` (done by `run_node`). It's
/// attached here - unconditionally, before any node-specific state exists -
/// rather than deferred, because `init_logging()` is what every node
/// binary's `main.rs` calls *first* (before `run_node` ever runs): `tracing`
/// only lets the first `try_init()` call in a process actually install a
/// subscriber, so the redis layer has to ride along with whichever call
/// wins that race, not assume it'll be `run_node`'s.
pub fn init_logging() {
    use tracing_subscriber::EnvFilter;

    let base = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
    let curated = format!("{base},ort=warn,rtc_dtls=error,rtc_ice=error,rtc::peer_connection::handler=error");
    let env_filter = EnvFilter::try_new(&curated).unwrap_or_else(|_| {
        EnvFilter::new("info,ort=warn,rtc_dtls=error,rtc_ice=error,rtc::peer_connection::handler=error")
    });

    #[cfg(feature = "messaging")]
    {
        use tracing_subscriber::prelude::*;

        let _ = tracing_subscriber::registry()
            .with(env_filter)
            .with(tracing_subscriber::fmt::layer())
            .with(crate::log_publisher::RedisLogLayer::new())
            .try_init();
    }

    #[cfg(not(feature = "messaging"))]
    {
        let _ = tracing_subscriber::fmt().with_env_filter(env_filter).try_init();
    }
}

/// Macro to execute code within a node's logging context
///
/// This macro creates a tracing span with the node_id field, ensuring all logs
/// within the scope are automatically tagged with the node identifier.
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// # async fn example(ctx: &Context) -> Result<()> {
/// in_node_context!(ctx, {
///     info!("Starting processing");  // Will show: node_id=my-node Starting processing
///     debug!("Details here");         // Will show: node_id=my-node Details here
/// });
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! in_node_context {
    ($ctx:expr, $body:block) => {{
        let _span = tracing::info_span!("node", node_id = $ctx.node_id()).entered();
        $body
    }};
}

/// Re-export the in_node_context macro
pub use in_node_context;

/// Generate a standalone binary `main()` for a node crate.
///
/// Every node binary's `main.rs` follows the same shape: initialize logging,
/// then delegate to the node crate's `run()` and map its error into
/// `anyhow::Result`. This macro captures that boilerplate so individual
/// `main.rs` files don't have to duplicate it.
///
/// Named `node_binary_main!` (rather than `node_main!`) to avoid colliding
/// with [`crate::node_main`], the unrelated macro that generates a node
/// crate's internal `run()` function from a `NodeImpl` type.
///
/// # Example
///
/// ```rust,ignore
/// use mecha10_core::prelude::*;
///
/// node_binary_main!(mecha10_nodes_listener);
/// ```
///
/// expands to:
///
/// ```rust,ignore
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
///     init_logging();
///
///     mecha10_nodes_listener::run().await.map_err(|e| anyhow::anyhow!(e))
/// }
/// ```
#[macro_export]
macro_rules! node_binary_main {
    ($node_crate:ident) => {
        #[tokio::main]
        async fn main() -> anyhow::Result<()> {
            $crate::prelude::init_logging();

            $node_crate::run().await.map_err(|e| anyhow::anyhow!(e))
        }
    };
}

/// Re-export the node_binary_main macro
pub use node_binary_main;

/// Get the current time in milliseconds since UNIX epoch
///
/// This is useful when microsecond precision is excessive (logs, metrics, etc.).
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let timestamp_ms = now_millis();
/// println!("Current time: {} ms", timestamp_ms);
/// ```
pub fn now_millis() -> u64 {
    since_epoch().as_millis() as u64
}

/// Calculate time elapsed in microseconds since a given timestamp
///
/// # Arguments
///
/// * `timestamp_micros` - A timestamp in microseconds (from `now_micros()`)
///
/// # Returns
///
/// Elapsed time in microseconds
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let start = now_micros();
/// // ... do work ...
/// let elapsed = elapsed_micros(start);
/// println!("Operation took {} μs", elapsed);
/// ```
pub fn elapsed_micros(timestamp_micros: u64) -> u64 {
    now_micros().saturating_sub(timestamp_micros)
}

/// Convert a microsecond timestamp to seconds (as f64)
///
/// Useful for displaying timestamps in human-readable format.
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let timestamp = now_micros();
/// let seconds = timestamp_as_secs(timestamp);
/// println!("Time: {:.6} seconds", seconds);
/// ```
pub fn timestamp_as_secs(timestamp_micros: u64) -> f64 {
    timestamp_micros as f64 / 1_000_000.0
}

/// Create a Duration from a frequency in Hz
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let duration = duration_from_hz(30.0);  // 33.33ms for 30Hz
/// ```
pub fn duration_from_hz(hz: f32) -> Duration {
    Duration::from_secs_f32(1.0 / hz)
}

/// Normalize an angle in radians to the range [-π, π]
///
/// This is essential for angle calculations to avoid unwanted wraparound effects.
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let angle = normalize_angle(7.0);  // Returns ~0.717 (7.0 - 2π)
/// let angle2 = normalize_angle(-4.0); // Returns ~2.283 (-4.0 + 2π)
/// ```
pub fn normalize_angle(angle: f32) -> f32 {
    use std::f32::consts::PI;
    let mut normalized = angle;
    while normalized > PI {
        normalized -= 2.0 * PI;
    }
    while normalized < -PI {
        normalized += 2.0 * PI;
    }
    normalized
}

/// Normalize an angle in degrees to the range [-180, 180]
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let angle = normalize_angle_degrees(270.0);  // Returns -90.0
/// ```
pub fn normalize_angle_degrees(angle: f32) -> f32 {
    let mut normalized = angle;
    while normalized > 180.0 {
        normalized -= 360.0;
    }
    while normalized < -180.0 {
        normalized += 360.0;
    }
    normalized
}

/// Calculate the shortest angular difference between two angles in radians
///
/// Returns the angular distance in the range [-π, π].
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let diff = angle_difference(0.1, 6.2);  // Shortest path wrapping around
/// ```
pub fn angle_difference(from: f32, to: f32) -> f32 {
    normalize_angle(to - from)
}

/// Convert degrees to radians
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let radians = degrees_to_radians(180.0);  // Returns π
/// ```
pub fn degrees_to_radians(degrees: f32) -> f32 {
    degrees * std::f32::consts::PI / 180.0
}

/// Convert radians to degrees
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let degrees = radians_to_degrees(std::f32::consts::PI);  // Returns 180.0
/// ```
pub fn radians_to_degrees(radians: f32) -> f32 {
    radians * 180.0 / std::f32::consts::PI
}

/// Safely divide two numbers, returning a default value if divisor is zero
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let result = safe_divide(10.0, 2.0, 0.0);   // Returns 5.0
/// let result = safe_divide(10.0, 0.0, 99.0);  // Returns 99.0 (default)
/// ```
pub fn safe_divide(numerator: f32, denominator: f32, default: f32) -> f32 {
    if denominator.abs() < f32::EPSILON {
        default
    } else {
        numerator / denominator
    }
}

/// Clamp a value between a minimum and maximum
///
/// This is available in std but this wrapper makes it more discoverable.
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let value = clamp(15.0, 0.0, 10.0);  // Returns 10.0
/// ```
pub fn clamp<T: PartialOrd>(value: T, min: T, max: T) -> T {
    if value < min {
        min
    } else if value > max {
        max
    } else {
        value
    }
}

/// Linear interpolation between two values
///
/// # Arguments
///
/// * `a` - Start value
/// * `b` - End value
/// * `t` - Interpolation factor [0.0, 1.0]
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
///
/// let mid = lerp(0.0, 10.0, 0.5);  // Returns 5.0
/// ```
pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
    a + (b - a) * t
}

/// HashMap and HashSet from std
pub use std::collections::{HashMap, HashSet};

/// Sync primitives
pub use std::sync::{Arc, Mutex};

/// Path types
pub use std::path::{Path, PathBuf};

/// Shared pointer to a value
pub type Shared<T> = Arc<T>;

/// Shared mutable state
pub type SharedMut<T> = Arc<Mutex<T>>;