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//!
150//! ### ⏳ Pending
151//!
152//! - Health checks and metrics collection
153//! - Prometheus metrics export
154//! - Distributed tracing integration
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 resource;
184
185// TODO: Implement health check and metrics collection modules
186// pub mod health;
187// pub mod metrics;
188
189// Re-export core types
190pub use actr_protocol::{ActorResult, ActrId, ActrType, ProtocolError};
191
192// Runtime core structures
193pub use actr_ref::ActrRef;
194pub use lifecycle::{ActrNode, ActrSystem};
195
196// Layer 3: Inbound dispatch layer
197pub use inbound::{DataStreamCallback, DataStreamRegistry, MediaFrameRegistry, MediaTrackCallback};
198
199// Re-export MediaSample and MediaType from framework (dependency inversion)
200pub use actr_framework::{MediaSample, MediaType};
201
202// Layer 2: Outbound gate abstraction layer
203pub use outbound::{InprocOutGate, OutGate, OutprocOutGate};
204
205// Layer 1: Transport layer
206pub use transport::{
207    DataLane,
208    DefaultWireBuilder,
209    DefaultWireBuilderConfig,
210    Dest,
211    DestTransport,
212    ExponentialBackoff,
213    InprocTransportManager, // Intra-process transport manager
214    NetworkError,
215    NetworkResult,
216    OutprocTransportManager,
217    WireBuilder,
218    WireHandle,
219};
220
221// Backward compatible alias (deprecated)
222#[allow(deprecated)]
223pub use transport::TransportManager;
224
225// Layer 0: Wire Layer
226pub use wire::{
227    AuthConfig, AuthType, IceServer, ReconnectConfig, SignalingClient, SignalingConfig,
228    SignalingStats, WebRtcConfig, WebRtcCoordinator, WebRtcGate, WebRtcNegotiator,
229    WebSocketConnection, WebSocketSignalingClient,
230};
231
232// Mailbox
233pub use actr_mailbox::{Mailbox, MailboxStats, MessagePriority, MessageRecord, MessageStatus};
234
235// System interfaces
236pub use context_factory::ContextFactory;
237
238// Utility modules
239pub use error::{RuntimeError, RuntimeResult};
240pub use monitoring::{Alert, AlertConfig, AlertSeverity, Monitor, MonitoringConfig};
241pub use resource::{ResourceConfig, ResourceManager, ResourceQuota, ResourceUsage};
242
243// Optional feature re-exports (pending implementation)
244// pub use health::{HealthChecker, HealthStatus, HealthReport};
245// pub use metrics::{RuntimeMetrics, MetricsRegistry, MetricsConfig};
246
247pub mod prelude {
248    //! Convenience prelude module
249    //!
250    //! Re-exports commonly used types and traits for quick imports:
251    //!
252    //! ```rust
253    //! use actr_runtime::prelude::*;
254    //! ```
255
256    // Core structures
257    pub use crate::actr_ref::ActrRef;
258    pub use crate::lifecycle::{ActrNode, ActrSystem};
259
260    // Layer 3: Inbound dispatch layer
261    pub use crate::inbound::{
262        DataStreamCallback, DataStreamRegistry, MediaFrameRegistry, MediaTrackCallback,
263    };
264
265    // Re-export MediaSample and MediaType from framework (dependency inversion)
266    pub use actr_framework::{MediaSample, MediaType};
267
268    // Layer 2: Outbound gate abstraction layer
269    pub use crate::outbound::{InprocOutGate, OutGate, OutprocOutGate};
270
271    // System interfaces
272    pub use crate::context_factory::ContextFactory;
273
274    // WebRTC subsystem
275    pub use crate::wire::webrtc::{
276        AuthConfig, AuthType, IceServer, ReconnectConfig, SignalingClient, SignalingConfig,
277        WebRtcConfig, WebRtcCoordinator, WebRtcGate, WebRtcNegotiator, WebSocketSignalingClient,
278    };
279
280    // Mailbox subsystem
281    pub use actr_mailbox::{Mailbox, MailboxStats, MessagePriority, MessageRecord, MessageStatus};
282
283    // Transport layer (transport management)
284    pub use crate::transport::{
285        DataLane,
286        DefaultWireBuilder,
287        DefaultWireBuilderConfig,
288        Dest,
289        DestTransport,
290        InprocTransportManager, // Intra-process transport manager
291        NetworkError,
292        NetworkResult,
293        OutprocTransportManager, // Cross-process transport manager
294        WireBuilder,
295        WireHandle,
296    };
297
298    // Backward compatible alias (deprecated)
299    #[allow(deprecated)]
300    pub use crate::transport::TransportManager;
301
302    // Utility modules
303    pub use crate::error::{RuntimeError, RuntimeResult};
304    pub use crate::monitoring::{Alert, AlertSeverity, Monitor};
305    pub use crate::resource::{ResourceManager, ResourceQuota, ResourceUsage};
306
307    // Base types
308    pub use actr_protocol::{ActorResult, ActrId, ActrType, ProtocolError};
309
310    // Framework traits (for implementing Workload)
311    pub use actr_framework::{Context, Workload};
312
313    // Async trait support
314    pub use async_trait::async_trait;
315
316    // Common utilities
317    pub use anyhow::{Context as AnyhowContext, Result as AnyhowResult};
318    pub use chrono::{DateTime, Utc};
319    pub use uuid::Uuid;
320
321    // Tokio runtime primitives
322    pub use tokio::sync::{Mutex, RwLock, broadcast, mpsc, oneshot};
323    pub use tokio::time::{Duration, Instant, sleep, timeout};
324
325    // Logging
326    pub use tracing::{debug, error, info, trace, warn};
327}