Skip to main content

mecha10_core/
prelude.rs

1pub use crate::context::{
2    Context, InfrastructureConfig, MinioConfig, MlflowConfig, PostgresConfig, Receiver, RedisConfig,
3};
4
5pub use crate::blackboard::Blackboard;
6
7#[cfg(feature = "messaging")]
8pub use crate::stream::ReceiverExt;
9
10#[cfg(feature = "messaging")]
11pub use crate::publish::ContextPublishExt;
12
13#[cfg(feature = "messaging")]
14pub use crate::rpc::{Request, Response, RpcExt};
15
16#[cfg(feature = "messaging")]
17pub use crate::rpc_streaming::{
18    StreamError, StreamMessage, StreamPayload, StreamReceiver, StreamSender, StreamingRpcExt,
19};
20
21#[cfg(feature = "messaging")]
22pub use crate::discovery::DiscoveryExt;
23pub use crate::discovery::{NodeMetadata, NodeStatus};
24
25pub use crate::schema::{
26    CompatibilityCheck, CompatibilityMode, MessageSchema, MessageVersionInfo, SchemaEvolution, SchemaField,
27    SchemaRegistryExt, SchemaVersioningExt,
28};
29
30pub use crate::auth::{AuthExt, Permission, Policy, Rule};
31
32pub use crate::secrets::{
33    EnvironmentBackend, RedisBackend, SecretBackend, SecretsConfig, SecretsManager, VaultBackend,
34};
35
36#[cfg(feature = "messaging")]
37pub use crate::health::{
38    HealthMonitor, HealthReport, HealthReporter, HealthReportingExt, NodeHealthInfo, SystemHealth,
39};
40
41#[cfg(feature = "messaging")]
42pub use crate::behavior_interrupt::{
43    BehaviorControl, BehaviorInterruptConfig, BehaviorInterruptTrigger, InterruptMode,
44};
45
46#[cfg(feature = "messaging")]
47pub use crate::on_demand::subscribe_on_demand;
48pub use crate::on_demand::OnDemandRequest;
49
50#[cfg(feature = "messaging")]
51pub use crate::echo::echo_topic;
52pub use crate::echo::forward_echo;
53
54pub use crate::metrics::{Counter, Gauge, Histogram, MetricsRegistry, NodeMetrics};
55
56pub use crate::rate_limit::{MultiKeyRateLimiter, RateLimit, RateLimiter, RateLimiterManager};
57
58pub use crate::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig, CircuitState};
59
60#[cfg(feature = "messaging")]
61pub use crate::dead_letter::{DeadLetterConfig, DeadLetterQueue, FailedMessage};
62
63#[cfg(feature = "schema-validation")]
64pub use crate::schema_validation::{
65    export_project_schema, get_project_schema, load_and_validate_project, validate_config_file,
66    validate_node_config_file, validate_node_config_json, validate_project_config, validate_project_json,
67};
68
69pub use crate::dependency::{create_graph, DependencyGraph, ShutdownPlan, StartupPlan};
70
71#[cfg(feature = "messaging")]
72pub use crate::lifecycle::{
73    get_timestamp_ms, topic_node_lifecycle, topic_node_status, topic_node_trigger, ModeChanged, ModeError, ModeRequest,
74    NodeLifecycleAction, NodeLifecycleEvent, NodeLifecycleStatus, NodeStatusEvent, NodeTriggerEvent,
75    TOPIC_MODE_CHANGED, TOPIC_MODE_ERROR, TOPIC_MODE_REQUEST,
76};
77
78pub use crate::topic_registry::{TopicInfo, TopicRegistry, TopologyStats};
79
80pub use crate::topic_utils::{extract_category, format_elapsed_time, TopicMetadata, Topics};
81
82pub use crate::state::{
83    FilesystemStateManager, MemoryStateManager, StateManager, StateOptions, StateSnapshot, VersionedState,
84};
85
86pub use crate::recovery::{
87    BackoffStrategy, DegradationMode, RecoveryAction, RecoveryAttempt, RecoveryHistory, RecoveryManager,
88    RecoveryPolicy, RecoveryPolicyBuilder, RecoveryStats,
89};
90
91#[cfg(feature = "messaging")]
92pub use crate::tracing_otel::{
93    JaegerExporter, SpanBuilder, SpanData, TraceContext, TraceExporter, TracedMessage, TracingConfig, TracingExt,
94    TracingHandle, ZipkinExporter,
95};
96
97pub use crate::profiling::{
98    measure_latency, ExecutionStats, LatencyStats, MemoryStats, PerformanceMetrics, PerformanceReport, ProfilingExt,
99    ThroughputStats, TimerGuard,
100};
101
102pub use crate::service::Service;
103#[cfg(feature = "messaging")]
104pub use crate::service_manager::ServiceManager;
105
106pub use crate::node::{
107    fmt_node_with_controller, run_node, HealthPriority, HealthReportingConfig, HealthStatusExt, Node, NodeImpl,
108    NodeTag, NodeType, RateConfig,
109};
110
111pub use crate::config::{
112    env_or_default, load_and_validate, load_config, load_config_from_env, substitute_env_vars, Validate,
113};
114
115pub use crate::model::{load_labels, load_model_config, CustomLabelsConfig, ModelConfig, PreprocessingConfig};
116
117pub use crate::builder_setter;
118pub use crate::enum_str_method;
119
120pub use crate::messages::Message;
121
122pub use crate::messages::Timestamped;
123
124pub use crate::types::*;
125
126pub use crate::error::{Mecha10Error, Result};
127
128pub use async_trait::async_trait;
129
130pub use tokio::{
131    self, select,
132    time::{interval, sleep, timeout, Duration, Instant},
133};
134
135pub use tokio::task::JoinHandle;
136
137pub use serde::{Deserialize, Serialize};
138pub use serde_json::{self, json, Value as JsonValue};
139
140pub use schemars::JsonSchema;
141
142pub use tracing::{debug, error, info, instrument, trace, warn, Level};
143
144#[cfg(feature = "macros")]
145pub use mecha10_macros::Node;
146
147#[cfg(feature = "macros")]
148pub use mecha10_macros::Config;
149
150#[cfg(feature = "macros")]
151pub use mecha10_macros::ConfigDefaults;
152
153/// Shared implementation behind `now_micros`/`now_secs`/`now_millis`, which differ only in
154/// which `Duration` unit they read off the epoch offset.
155fn since_epoch() -> std::time::Duration {
156    std::time::SystemTime::now()
157        .duration_since(std::time::UNIX_EPOCH)
158        .expect("Time went backwards")
159}
160
161/// Get current time in microseconds since UNIX epoch
162pub fn now_micros() -> u64 {
163    since_epoch().as_micros() as u64
164}
165
166/// Get current time in whole seconds since UNIX epoch
167pub fn now_secs() -> u64 {
168    since_epoch().as_secs()
169}
170
171/// Create a periodic interval from a frequency in Hz
172///
173/// This is a convenience helper that converts frequency (Hz) to a tokio interval.
174/// Commonly used for periodic publishing in drivers and nodes.
175///
176/// # Arguments
177///
178/// * `hz` - Frequency in Hertz (cycles per second)
179///
180/// # Returns
181///
182/// A tokio::time::Interval that ticks at the specified frequency
183///
184/// # Example
185///
186/// Marked `no_run`: the `loop` below never breaks, so running it to completion
187/// would hang the doctest forever.
188/// ```rust,no_run
189/// use mecha10_core::prelude::*;
190///
191/// # async fn example() {
192/// // Instead of:
193/// // let interval_duration = Duration::from_secs_f32(1.0 / 30.0);
194/// // let mut interval = tokio::time::interval(interval_duration);
195///
196/// // Simply use:
197/// let mut interval = interval_at_hz(30.0);
198///
199/// loop {
200///     interval.tick().await;
201///     // Publish at 30 Hz
202/// }
203/// # }
204/// ```
205pub fn interval_at_hz(hz: f32) -> tokio::time::Interval {
206    let duration = std::time::Duration::from_secs_f32(1.0 / hz);
207    tokio::time::interval(duration)
208}
209
210/// Initialize logging with sensible defaults
211///
212/// This function is safe to call multiple times - it will silently succeed if
213/// a tracing subscriber is already set (e.g., when running bundled in the CLI).
214///
215/// The logging system will automatically include node context (node_id) in all
216/// log messages when using the Context's logging methods or the `in_node_context!` macro.
217///
218/// Under the `messaging` feature, this also attaches
219/// [`crate::log_publisher::RedisLogLayer`], the layer that ships captured
220/// log events to Redis on `/system/log` once `crate::log_publisher::attach`
221/// has been called with a live `Context` (done by `run_node`). It's
222/// attached here - unconditionally, before any node-specific state exists -
223/// rather than deferred, because `init_logging()` is what every node
224/// binary's `main.rs` calls *first* (before `run_node` ever runs): `tracing`
225/// only lets the first `try_init()` call in a process actually install a
226/// subscriber, so the redis layer has to ride along with whichever call
227/// wins that race, not assume it'll be `run_node`'s.
228pub fn init_logging() {
229    use tracing_subscriber::EnvFilter;
230
231    static SENTRY_GUARD: std::sync::OnceLock<sentry::ClientInitGuard> = std::sync::OnceLock::new();
232    if SENTRY_GUARD.get().is_none() && sentry::Hub::current().client().is_none() {
233        let sentry_dsn = std::env::var("SENTRY_DSN_NODES").unwrap_or_else(|_| {
234            "https://7ea967345cb382353a93ce31365e4790@o4506107376631808.ingest.us.sentry.io/4512334108229632"
235                .to_string()
236        });
237        let mut sentry_opts = sentry::ClientOptions::default();
238        sentry_opts.dsn = sentry_dsn.parse().ok();
239        sentry_opts.release = sentry::release_name!();
240        let _ = SENTRY_GUARD.set(sentry::init(sentry_opts));
241    }
242
243    let base = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
244    let curated = format!("{base},ort=warn,rtc_dtls=error,rtc_ice=error,rtc::peer_connection::handler=error");
245    let env_filter = EnvFilter::try_new(&curated).unwrap_or_else(|_| {
246        EnvFilter::new("info,ort=warn,rtc_dtls=error,rtc_ice=error,rtc::peer_connection::handler=error")
247    });
248
249    #[cfg(feature = "messaging")]
250    {
251        use tracing_subscriber::prelude::*;
252
253        let _ = tracing_subscriber::registry()
254            .with(env_filter)
255            .with(tracing_subscriber::fmt::layer())
256            .with(crate::log_publisher::RedisLogLayer::new())
257            .try_init();
258    }
259
260    #[cfg(not(feature = "messaging"))]
261    {
262        let _ = tracing_subscriber::fmt().with_env_filter(env_filter).try_init();
263    }
264}
265
266#[macro_export]
267macro_rules! in_node_context {
268    ($ctx:expr, $body:block) => {{
269        let _span = tracing::info_span!("node", node_id = $ctx.node_id()).entered();
270        $body
271    }};
272}
273
274pub use in_node_context;
275
276#[macro_export]
277macro_rules! node_binary_main {
278    ($node_crate:ident) => {
279        #[tokio::main]
280        async fn main() -> anyhow::Result<()> {
281            $crate::prelude::init_logging();
282
283            $node_crate::run().await.map_err(|e| anyhow::anyhow!(e))
284        }
285    };
286}
287
288pub use node_binary_main;
289
290/// Get the current time in milliseconds since UNIX epoch
291///
292/// This is useful when microsecond precision is excessive (logs, metrics, etc.).
293///
294/// # Example
295///
296/// ```rust
297/// use mecha10_core::prelude::*;
298///
299/// let timestamp_ms = now_millis();
300/// println!("Current time: {} ms", timestamp_ms);
301/// ```
302pub fn now_millis() -> u64 {
303    since_epoch().as_millis() as u64
304}
305
306/// Calculate time elapsed in microseconds since a given timestamp
307///
308/// # Arguments
309///
310/// * `timestamp_micros` - A timestamp in microseconds (from `now_micros()`)
311///
312/// # Returns
313///
314/// Elapsed time in microseconds
315///
316/// # Example
317///
318/// ```rust
319/// use mecha10_core::prelude::*;
320///
321/// let start = now_micros();
322/// // ... do work ...
323/// let elapsed = elapsed_micros(start);
324/// println!("Operation took {} μs", elapsed);
325/// ```
326pub fn elapsed_micros(timestamp_micros: u64) -> u64 {
327    now_micros().saturating_sub(timestamp_micros)
328}
329
330/// Convert a microsecond timestamp to seconds (as f64)
331///
332/// Useful for displaying timestamps in human-readable format.
333///
334/// # Example
335///
336/// ```rust
337/// use mecha10_core::prelude::*;
338///
339/// let timestamp = now_micros();
340/// let seconds = timestamp_as_secs(timestamp);
341/// println!("Time: {:.6} seconds", seconds);
342/// ```
343pub fn timestamp_as_secs(timestamp_micros: u64) -> f64 {
344    timestamp_micros as f64 / 1_000_000.0
345}
346
347/// Create a Duration from a frequency in Hz
348///
349/// # Example
350///
351/// ```rust
352/// use mecha10_core::prelude::*;
353///
354/// let duration = duration_from_hz(30.0);  // 33.33ms for 30Hz
355/// ```
356pub fn duration_from_hz(hz: f32) -> Duration {
357    Duration::from_secs_f32(1.0 / hz)
358}
359
360/// Normalize an angle in radians to the range [-π, π]
361///
362/// This is essential for angle calculations to avoid unwanted wraparound effects.
363///
364/// # Example
365///
366/// ```rust
367/// use mecha10_core::prelude::*;
368///
369/// let angle = normalize_angle(7.0);  // Returns ~0.717 (7.0 - 2π)
370/// let angle2 = normalize_angle(-4.0); // Returns ~2.283 (-4.0 + 2π)
371/// ```
372pub fn normalize_angle(angle: f32) -> f32 {
373    use std::f32::consts::PI;
374    let mut normalized = angle;
375    while normalized > PI {
376        normalized -= 2.0 * PI;
377    }
378    while normalized < -PI {
379        normalized += 2.0 * PI;
380    }
381    normalized
382}
383
384/// Normalize an angle in degrees to the range [-180, 180]
385///
386/// # Example
387///
388/// ```rust
389/// use mecha10_core::prelude::*;
390///
391/// let angle = normalize_angle_degrees(270.0);  // Returns -90.0
392/// ```
393pub fn normalize_angle_degrees(angle: f32) -> f32 {
394    let mut normalized = angle;
395    while normalized > 180.0 {
396        normalized -= 360.0;
397    }
398    while normalized < -180.0 {
399        normalized += 360.0;
400    }
401    normalized
402}
403
404/// Calculate the shortest angular difference between two angles in radians
405///
406/// Returns the angular distance in the range [-π, π].
407///
408/// # Example
409///
410/// ```rust
411/// use mecha10_core::prelude::*;
412///
413/// let diff = angle_difference(0.1, 6.2);  // Shortest path wrapping around
414/// ```
415pub fn angle_difference(from: f32, to: f32) -> f32 {
416    normalize_angle(to - from)
417}
418
419/// Convert degrees to radians
420///
421/// # Example
422///
423/// ```rust
424/// use mecha10_core::prelude::*;
425///
426/// let radians = degrees_to_radians(180.0);  // Returns π
427/// ```
428pub fn degrees_to_radians(degrees: f32) -> f32 {
429    degrees * std::f32::consts::PI / 180.0
430}
431
432/// Convert radians to degrees
433///
434/// # Example
435///
436/// ```rust
437/// use mecha10_core::prelude::*;
438///
439/// let degrees = radians_to_degrees(std::f32::consts::PI);  // Returns 180.0
440/// ```
441pub fn radians_to_degrees(radians: f32) -> f32 {
442    radians * 180.0 / std::f32::consts::PI
443}
444
445/// Safely divide two numbers, returning a default value if divisor is zero
446///
447/// # Example
448///
449/// ```rust
450/// use mecha10_core::prelude::*;
451///
452/// let result = safe_divide(10.0, 2.0, 0.0);   // Returns 5.0
453/// let result = safe_divide(10.0, 0.0, 99.0);  // Returns 99.0 (default)
454/// ```
455pub fn safe_divide(numerator: f32, denominator: f32, default: f32) -> f32 {
456    if denominator.abs() < f32::EPSILON {
457        default
458    } else {
459        numerator / denominator
460    }
461}
462
463/// Clamp a value between a minimum and maximum
464///
465/// This is available in std but this wrapper makes it more discoverable.
466///
467/// # Example
468///
469/// ```rust
470/// use mecha10_core::prelude::*;
471///
472/// let value = clamp(15.0, 0.0, 10.0);  // Returns 10.0
473/// ```
474pub fn clamp<T: PartialOrd>(value: T, min: T, max: T) -> T {
475    if value < min {
476        min
477    } else if value > max {
478        max
479    } else {
480        value
481    }
482}
483
484/// Linear interpolation between two values
485///
486/// # Arguments
487///
488/// * `a` - Start value
489/// * `b` - End value
490/// * `t` - Interpolation factor [0.0, 1.0]
491///
492/// # Example
493///
494/// ```rust
495/// use mecha10_core::prelude::*;
496///
497/// let mid = lerp(0.0, 10.0, 0.5);  // Returns 5.0
498/// ```
499pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
500    a + (b - a) * t
501}
502
503pub use std::collections::{HashMap, HashSet};
504
505pub use std::sync::{Arc, Mutex};
506
507pub use std::path::{Path, PathBuf};
508
509pub type Shared<T> = Arc<T>;
510pub type SharedMut<T> = Arc<Mutex<T>>;
511
512#[cfg(test)]
513mod sentry_options_tests {
514    // Regression test for the E0639 compile error: `sentry::ClientOptions` is
515    // `#[non_exhaustive]`, so it cannot be built with a struct-literal +
516    // `..Default::default()`. Construction must go through
517    // `ClientOptions::default()` followed by field assignment, as done in
518    // `init_logging`. If a future edit reverts to the struct-literal form,
519    // this module (and `init_logging` itself) will fail to compile.
520    #[test]
521    fn client_options_builds_via_default_and_field_assignment() {
522        let dsn = "https://public@sentry.example.com/1";
523
524        let mut opts = sentry::ClientOptions::default();
525        opts.dsn = dsn.parse().ok();
526        opts.release = sentry::release_name!();
527
528        assert!(opts.dsn.is_some());
529    }
530
531    #[test]
532    fn invalid_dsn_parses_to_none_without_panicking() {
533        let mut opts = sentry::ClientOptions::default();
534        opts.dsn = "not-a-valid-dsn".parse().ok();
535
536        assert!(opts.dsn.is_none());
537    }
538}