actr_runtime/lib.rs
1//! # Actor-RTC Runtime Layer
2//!
3//! Runtime infrastructure for the Actor-RTC framework, providing complete Actor lifecycle management
4//! and message transport capabilities.
5//!
6//! ## Overview
7//!
8//! `actr-runtime` is the core runtime library that powers Actor nodes. It provides:
9//!
10//! - **Actor Lifecycle**: System initialization, node startup/shutdown
11//! - **Message Transport**: Multi-layer architecture (Wire → Transport → Gate → Dispatch)
12//! - **Communication Modes**: Intra-process (zero-copy) and cross-process (WebRTC/WebSocket)
13//! - **Message Persistence**: SQLite-backed mailbox with ACID guarantees
14//!
15//! ## Architecture Layers
16//!
17//! ```text
18//! ┌─────────────────────────────────────────────────────┐
19//! │ Lifecycle Management (ActrSystem → ActrNode → ActrRef)
20//! ├─────────────────────────────────────────────────────┤
21//! │ Layer 3: Inbound Dispatch │ DataStreamRegistry
22//! │ (Fast Path Routing) │ MediaFrameRegistry
23//! ├─────────────────────────────────────────────────────┤
24//! │ Layer 2: Outbound Gate │ InprocOutGate
25//! │ (Message Sending) │ OutprocOutGate
26//! ├─────────────────────────────────────────────────────┤
27//! │ Layer 1: Transport │ Lane (core abstraction)
28//! │ (Channel Management) │ InprocTransportManager
29//! │ │ OutprocTransportManager
30//! ├─────────────────────────────────────────────────────┤
31//! │ Layer 0: Wire │ WebRtcGate
32//! │ (Physical Connections) │ WebRtcCoordinator
33//! │ │ SignalingClient
34//! └─────────────────────────────────────────────────────┘
35//! ```
36//!
37//! ## Core Types
38//!
39//! ### Lifecycle Management
40//!
41//! The runtime follows a three-phase lifecycle:
42//!
43//! ```rust,ignore
44//! use actr_runtime::prelude::*;
45//!
46//! #[tokio::main]
47//! async fn main() -> ActorResult<()> {
48//! // Phase 1: Create generic-free infrastructure
49//! let config = actr_config::Config::default();
50//! let system = ActrSystem::new(config).await?;
51//!
52//! // Phase 2: Attach business logic (Workload)
53//! let node = system.attach(MyWorkload::default());
54//!
55//! // Phase 3: Start and get running node
56//! let running = node.start().await?;
57//!
58//! // Option 1: Convenience method (wait for Ctrl+C and shutdown)
59//! running.wait_for_ctrl_c_and_shutdown().await?;
60//!
61//! // Option 2: Manual control (for custom shutdown logic)
62//! // tokio::signal::ctrl_c().await?;
63//! // running.shutdown().await?;
64//!
65//! Ok(())
66//! }
67//! ```
68//!
69//! ### Transport Abstraction
70//!
71//! **Lane** is the core transport abstraction, representing a unidirectional message channel:
72//!
73//! ```rust,ignore
74//! use actr_runtime::transport::Lane;
75//! use actr_protocol::PayloadType;
76//!
77//! // Lane supports 4 variants:
78//! // - WebRtcDataChannel: Reliable/Signal/LatencyFirst
79//! // - WebRtcMediaTrack: Real-time media
80//! // - Mpsc: Intra-process (zero-copy)
81//! // - WebSocket: Fallback transport
82//!
83//! // Send message through lane
84//! lane.send(data).await?;
85//!
86//! // Receive from lane
87//! let data = lane.recv().await?;
88//! ```
89//!
90//! ### Communication Modes
91//!
92//! #### Intra-process (Shell ↔ Workload)
93//!
94//! ```rust,ignore
95//! use actr_runtime::transport::InprocTransportManager;
96//!
97//! let mgr = InprocTransportManager::new();
98//!
99//! // Zero-serialization, direct RpcEnvelope passing
100//! let response = mgr.send_request(
101//! PayloadType::RpcReliable,
102//! None, // identifier
103//! envelope
104//! ).await?;
105//! ```
106//!
107//! #### Cross-process (WebRTC/WebSocket)
108//!
109//! ```rust,ignore
110//! use actr_runtime::transport::OutprocTransportManager;
111//!
112//! let mgr = OutprocTransportManager::new(config);
113//!
114//! // Protobuf serialization, automatic protocol negotiation
115//! mgr.send(&dest, PayloadType::RpcReliable, &data).await?;
116//! ```
117//!
118//! ### Message Persistence
119//!
120//! All incoming messages go through the Mailbox (State Path):
121//!
122//! ```rust,ignore
123//! use actr_mailbox::{Mailbox, MessagePriority};
124//!
125//! // Enqueue message (persisted to SQLite)
126//! let msg_id = mailbox.enqueue(from, payload, MessagePriority::Normal).await?;
127//!
128//! // Dequeue batch (ordered by priority)
129//! let messages = mailbox.dequeue().await?;
130//!
131//! // Process and acknowledge
132//! for msg in messages {
133//! process_message(&msg).await?;
134//! mailbox.ack(msg.id).await?;
135//! }
136//! ```
137//!
138//! ## Feature Status
139//!
140//! ### ✅ Implemented
141//!
142//! - Actor lifecycle management (ActrSystem/ActrNode/ActrRef)
143//! - 4-Lane transport architecture (WebRTC DataChannel + MediaTrack)
144//! - WebSocket signaling client
145//! - Intra-process zero-copy channels
146//! - SQLite-backed mailbox with priorities
147//! - Context factory for message handling
148//! - Basic service discovery helpers (RouteCandidates)
149//! - Distributed tracing integration (feature `opentelemetry`, Jaeger/OTLP)
150//!
151//! ### ⏳ Pending
152//!
153//! - Health checks and metrics collection
154//! - Prometheus metrics export
155//!
156//! ## Usage Note
157//!
158//! This is a low-level runtime library. For application development, use the high-level
159//! framework APIs provided by `actr-framework` which builds on top of this runtime.
160
161// Lifecycle management layer (not architectural layering)
162pub mod lifecycle;
163
164// ActrRef - Lightweight Actor reference
165pub mod actr_ref;
166
167// Layer 3: Inbound dispatch layer
168pub mod inbound;
169
170// Layer 2: Outbound gate abstraction layer
171pub mod outbound;
172
173// Layer 1: Transport layer
174pub mod transport;
175
176// Layer 0: Wire layer
177pub mod wire;
178
179pub mod context;
180pub mod context_factory;
181pub mod error;
182pub mod monitoring;
183pub mod observability;
184pub mod resource;
185
186// TODO: Implement health check and metrics collection modules
187// pub mod health;
188// pub mod metrics;
189
190pub use observability::{ObservabilityGuard, init_observability};
191
192// Re-export core types
193pub use actr_protocol::{ActorResult, ActrId, ActrType, ProtocolError};
194
195// Runtime core structures
196pub use actr_ref::ActrRef;
197pub use lifecycle::{ActrNode, ActrSystem, NetworkEventHandle};
198
199// Layer 3: Inbound dispatch layer
200pub use inbound::{DataStreamCallback, DataStreamRegistry, MediaFrameRegistry, MediaTrackCallback};
201
202// Re-export MediaSample and MediaType from framework (dependency inversion)
203pub use actr_framework::{MediaSample, MediaType};
204
205// Layer 2: Outbound gate abstraction layer
206pub use outbound::{InprocOutGate, OutGate, OutprocOutGate};
207
208// Layer 1: Transport layer
209pub use transport::{
210 DataLane,
211 DefaultWireBuilder,
212 DefaultWireBuilderConfig,
213 Dest,
214 DestTransport,
215 ExponentialBackoff,
216 InprocTransportManager, // Intra-process transport manager
217 NetworkError,
218 NetworkResult,
219 OutprocTransportManager,
220 WireBuilder,
221 WireHandle,
222};
223
224// Backward compatible alias (deprecated)
225#[allow(deprecated)]
226pub use transport::TransportManager;
227
228// Layer 0: Wire Layer
229pub use wire::{
230 AuthConfig, AuthType, IceServer, ReconnectConfig, SignalingClient, SignalingConfig,
231 SignalingStats, WebRtcConfig, WebRtcCoordinator, WebRtcGate, WebRtcNegotiator,
232 WebSocketConnection, WebSocketSignalingClient,
233};
234
235// Mailbox
236pub use actr_mailbox::{Mailbox, MailboxStats, MessagePriority, MessageRecord, MessageStatus};
237
238// System interfaces
239pub use context_factory::ContextFactory;
240
241// Utility modules
242pub use error::{RuntimeError, RuntimeResult};
243pub use monitoring::{Alert, AlertConfig, AlertSeverity, Monitor, MonitoringConfig};
244pub use resource::{ResourceConfig, ResourceManager, ResourceQuota, ResourceUsage};
245
246// Optional feature re-exports (pending implementation)
247// pub use health::{HealthChecker, HealthStatus, HealthReport};
248// pub use metrics::{RuntimeMetrics, MetricsRegistry, MetricsConfig};
249
250pub mod prelude {
251 //! Convenience prelude module
252 //!
253 //! Re-exports commonly used types and traits for quick imports:
254 //!
255 //! ```rust
256 //! use actr_runtime::prelude::*;
257 //! ```
258
259 // Core structures
260 pub use crate::actr_ref::ActrRef;
261 pub use crate::lifecycle::{
262 ActrNode, ActrSystem, CompatLockFile, CompatLockManager, CompatibilityCheck,
263 DiscoveryResult,
264 };
265
266 // Layer 3: Inbound dispatch layer
267 pub use crate::inbound::{
268 DataStreamCallback, DataStreamRegistry, MediaFrameRegistry, MediaTrackCallback,
269 };
270
271 // Re-export MediaSample and MediaType from framework (dependency inversion)
272 pub use actr_framework::{MediaSample, MediaType};
273
274 // Layer 2: Outbound gate abstraction layer
275 pub use crate::outbound::{InprocOutGate, OutGate, OutprocOutGate};
276
277 // System interfaces
278 pub use crate::context_factory::ContextFactory;
279
280 // WebRTC subsystem
281 pub use crate::wire::webrtc::{
282 AuthConfig, AuthType, IceServer, ReconnectConfig, SignalingClient, SignalingConfig,
283 WebRtcConfig, WebRtcCoordinator, WebRtcGate, WebRtcNegotiator, WebSocketSignalingClient,
284 };
285
286 // Mailbox subsystem
287 pub use actr_mailbox::{Mailbox, MailboxStats, MessagePriority, MessageRecord, MessageStatus};
288
289 // Transport layer (transport management)
290 pub use crate::transport::{
291 DataLane,
292 DefaultWireBuilder,
293 DefaultWireBuilderConfig,
294 Dest,
295 DestTransport,
296 InprocTransportManager, // Intra-process transport manager
297 NetworkError,
298 NetworkResult,
299 OutprocTransportManager, // Cross-process transport manager
300 WireBuilder,
301 WireHandle,
302 };
303
304 // Backward compatible alias (deprecated)
305 #[allow(deprecated)]
306 pub use crate::transport::TransportManager;
307
308 // Utility modules
309 pub use crate::error::{RuntimeError, RuntimeResult};
310 pub use crate::monitoring::{Alert, AlertSeverity, Monitor};
311 pub use crate::resource::{ResourceManager, ResourceQuota, ResourceUsage};
312
313 // Base types
314 pub use actr_protocol::{ActorResult, ActrId, ActrType, ProtocolError};
315
316 // Framework traits (for implementing Workload)
317 pub use actr_framework::{Context, Workload};
318
319 // Async trait support
320 pub use async_trait::async_trait;
321
322 // Common utilities
323 pub use anyhow::{Context as AnyhowContext, Result as AnyhowResult};
324 pub use chrono::{DateTime, Utc};
325 pub use uuid::Uuid;
326
327 // Tokio runtime primitives
328 pub use tokio::sync::{Mutex, RwLock, broadcast, mpsc, oneshot};
329 pub use tokio::time::{Duration, Instant, sleep, timeout};
330
331 // Logging
332 pub use tracing::{debug, error, info, trace, warn};
333}
334
335pub const INITIAL_CONNECTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);