aprender-simulate 0.30.0

Unified Simulation Engine for the Sovereign AI Stack
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
//! Web visualization for simular.
//!
//! WebSocket streaming server using axum.
//!
//! This module is only available with the `web` feature.

use std::sync::Arc;

use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::{Html, IntoResponse},
    routing::get,
    Router,
};
use tokio::sync::{broadcast, RwLock};

use super::SimMetrics;
use crate::engine::{SimState, SimTime};
use crate::error::SimResult;

/// Shared state for the web server.
#[derive(Clone)]
pub struct WebState {
    /// Broadcast channel for simulation updates.
    tx: broadcast::Sender<String>,
    /// Connected client count.
    client_count: Arc<RwLock<usize>>,
}

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

impl WebState {
    /// Create new web state.
    #[must_use]
    pub fn new() -> Self {
        let (tx, _) = broadcast::channel(100);
        Self {
            tx,
            client_count: Arc::new(RwLock::new(0)),
        }
    }

    /// Get a broadcast receiver for simulation updates.
    #[must_use]
    pub fn subscribe(&self) -> broadcast::Receiver<String> {
        self.tx.subscribe()
    }

    /// Get the number of connected clients.
    pub async fn client_count(&self) -> usize {
        *self.client_count.read().await
    }
}

/// Web visualization server.
pub struct WebVisualization {
    /// Server state.
    state: WebState,
    /// Server port.
    port: u16,
}

impl WebVisualization {
    /// Create new web visualization server.
    #[must_use]
    pub fn new(port: u16) -> Self {
        Self {
            state: WebState::new(),
            port,
        }
    }

    /// Get the router for the web server.
    pub fn router(&self) -> Router {
        let state = self.state.clone();
        Router::new()
            .route(
                "/ws",
                get(move |ws: WebSocketUpgrade| {
                    let state = state.clone();
                    async move { ws.on_upgrade(move |socket| handle_socket(socket, state)) }
                }),
            )
            .route("/", get(index_handler))
            .route("/health", get(health_handler))
    }

    /// Broadcast simulation state to all connected clients.
    ///
    /// # Errors
    ///
    /// Returns error if serialization fails.
    pub fn broadcast(
        &self,
        state: &SimState,
        time: SimTime,
        metrics: &SimMetrics,
    ) -> SimResult<()> {
        let payload = WebPayload {
            time: time.as_secs_f64(),
            body_count: state.num_bodies(),
            kinetic_energy: state.kinetic_energy(),
            potential_energy: state.potential_energy(),
            total_energy: state.total_energy(),
            metrics: metrics.clone(),
        };

        let json = serde_json::to_string(&payload).map_err(|e| {
            crate::error::SimError::serialization(format!("JSON serialization failed: {e}"))
        })?;

        // Ignore send errors (no subscribers is fine)
        let _ = self.state.tx.send(json);
        Ok(())
    }

    /// Get the number of connected clients.
    pub async fn client_count(&self) -> usize {
        self.state.client_count().await
    }

    /// Get the server port.
    #[must_use]
    pub const fn port(&self) -> u16 {
        self.port
    }

    /// Get a broadcast receiver for simulation updates.
    #[must_use]
    pub fn subscribe(&self) -> broadcast::Receiver<String> {
        self.state.subscribe()
    }
}

/// Handle individual WebSocket connection.
async fn handle_socket(mut socket: WebSocket, state: WebState) {
    // Increment client count
    {
        let mut count = state.client_count.write().await;
        *count += 1;
    }

    // Subscribe to broadcast channel
    let mut rx = state.tx.subscribe();

    // Send updates to client
    loop {
        tokio::select! {
            // Forward broadcast messages to client
            result = rx.recv() => {
                match result {
                    Ok(msg) => {
                        if socket.send(Message::Text(msg)).await.is_err() {
                            break;
                        }
                    }
                    Err(broadcast::error::RecvError::Lagged(_)) => {
                        // Lagged receiver — dropped messages are expected for live viz
                    }
                    Err(broadcast::error::RecvError::Closed) => {
                        break;
                    }
                }
            }
            // Handle incoming messages from client
            result = socket.recv() => {
                match result {
                    Some(Ok(Message::Close(_)) | Err(_)) | None => break,
                    Some(Ok(Message::Ping(data))) => {
                        if socket.send(Message::Pong(data)).await.is_err() {
                            break;
                        }
                    }
                    Some(Ok(_)) => {}
                }
            }
        }
    }

    // Decrement client count
    {
        let mut count = state.client_count.write().await;
        *count = count.saturating_sub(1);
    }
}

/// Index handler (simple HTML page).
async fn index_handler() -> Html<&'static str> {
    Html(INDEX_HTML)
}

/// Health check handler.
async fn health_handler() -> impl IntoResponse {
    "{\"status\":\"ok\"}"
}

/// Payload sent to WebSocket clients.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct WebPayload {
    /// Simulation time in seconds.
    pub time: f64,
    /// Number of bodies.
    pub body_count: usize,
    /// Kinetic energy.
    pub kinetic_energy: f64,
    /// Potential energy.
    pub potential_energy: f64,
    /// Total energy.
    pub total_energy: f64,
    /// Full metrics.
    pub metrics: SimMetrics,
}

/// Simple HTML page for visualization.
const INDEX_HTML: &str = r#"<!DOCTYPE html>
<html>
<head>
    <title>Simular Visualization</title>
    <style>
        body { font-family: monospace; background: #1a1a2e; color: #eee; padding: 20px; }
        .metric { margin: 10px 0; }
        .value { color: #00ff88; }
        #status { color: #ff6b6b; }
        #status.connected { color: #00ff88; }
    </style>
</head>
<body>
    <h1>Simular Visualization</h1>
    <div id="status">Disconnected</div>
    <div class="metric">Time: <span id="time" class="value">0.0</span>s</div>
    <div class="metric">Bodies: <span id="bodies" class="value">0</span></div>
    <div class="metric">Total Energy: <span id="energy" class="value">0.0</span></div>
    <div class="metric">Kinetic: <span id="ke" class="value">0.0</span></div>
    <div class="metric">Potential: <span id="pe" class="value">0.0</span></div>
    <script>
        const ws = new WebSocket(`ws://${location.host}/ws`);
        ws.onopen = () => {
            document.getElementById('status').textContent = 'Connected';
            document.getElementById('status').className = 'connected';
        };
        ws.onclose = () => {
            document.getElementById('status').textContent = 'Disconnected';
            document.getElementById('status').className = '';
        };
        ws.onmessage = (e) => {
            const data = JSON.parse(e.data);
            document.getElementById('time').textContent = data.time.toFixed(4);
            document.getElementById('bodies').textContent = data.body_count;
            document.getElementById('energy').textContent = data.total_energy.toFixed(6);
            document.getElementById('ke').textContent = data.kinetic_energy.toFixed(6);
            document.getElementById('pe').textContent = data.potential_energy.toFixed(6);
        };
    </script>
</body>
</html>"#;

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::engine::{SimState, SimTime};

    #[test]
    fn test_web_state_new() {
        let state = WebState::new();
        assert!(state.tx.receiver_count() == 0);
    }

    #[test]
    fn test_web_state_default() {
        let state = WebState::default();
        assert!(state.tx.receiver_count() == 0);
    }

    #[test]
    fn test_web_state_subscribe() {
        let state = WebState::new();
        let _rx1 = state.subscribe();
        assert_eq!(state.tx.receiver_count(), 1);

        let _rx2 = state.subscribe();
        assert_eq!(state.tx.receiver_count(), 2);
    }

    #[test]
    fn test_web_state_clone() {
        let state = WebState::new();
        let cloned = state.clone();
        // Both share the same broadcast channel
        let _rx = state.subscribe();
        assert_eq!(cloned.tx.receiver_count(), 1);
    }

    #[tokio::test]
    async fn test_web_state_client_count_initial() {
        let state = WebState::new();
        assert_eq!(state.client_count().await, 0);
    }

    #[test]
    fn test_web_visualization_new() {
        let viz = WebVisualization::new(8080);
        assert_eq!(viz.port(), 8080);
    }

    #[test]
    fn test_web_visualization_port_zero() {
        let viz = WebVisualization::new(0);
        assert_eq!(viz.port(), 0);
    }

    #[test]
    fn test_web_visualization_router() {
        let viz = WebVisualization::new(8080);
        let _router = viz.router();
        // Router was created successfully
    }

    #[test]
    fn test_web_visualization_subscribe() {
        let viz = WebVisualization::new(8080);
        let _rx = viz.subscribe();
        // Subscribed successfully
    }

    #[tokio::test]
    async fn test_web_visualization_client_count() {
        let viz = WebVisualization::new(8080);
        assert_eq!(viz.client_count().await, 0);
    }

    #[test]
    fn test_web_visualization_broadcast() {
        let viz = WebVisualization::new(8080);
        let mut rx = viz.subscribe();

        let state = SimState::default();
        let time = SimTime::from_secs(1.0);
        let metrics = SimMetrics::new();

        let result = viz.broadcast(&state, time, &metrics);
        assert!(result.is_ok());

        // Should be able to receive the broadcast
        let msg = rx.try_recv();
        assert!(msg.is_ok());
        let json = msg.unwrap();
        assert!(json.contains("\"time\":1.0"));
    }

    #[test]
    fn test_web_visualization_broadcast_no_subscribers() {
        let viz = WebVisualization::new(8080);
        // No subscribers - should still succeed (just drops message)

        let state = SimState::default();
        let time = SimTime::from_secs(1.0);
        let metrics = SimMetrics::new();

        let result = viz.broadcast(&state, time, &metrics);
        assert!(result.is_ok());
    }

    #[test]
    fn test_web_payload_serialize() {
        let payload = WebPayload {
            time: 1.0,
            body_count: 2,
            kinetic_energy: 10.0,
            potential_energy: -5.0,
            total_energy: 5.0,
            metrics: SimMetrics::new(),
        };

        let json = serde_json::to_string(&payload).ok();
        assert!(json.is_some());
        assert!(json.as_ref().map_or(false, |j| j.contains("\"time\":1.0")));
    }

    #[test]
    fn test_web_payload_deserialize() {
        let json = r#"{"time":1.0,"body_count":2,"kinetic_energy":10.0,"potential_energy":-5.0,"total_energy":5.0,"metrics":{"time":0.0,"step":0,"steps_per_second":0.0,"total_energy":null,"kinetic_energy":null,"potential_energy":null,"energy_drift":null,"body_count":0,"jidoka_warnings":0,"jidoka_errors":0,"memory_bytes":0,"custom":{}}}"#;

        let payload: WebPayload = serde_json::from_str(json).unwrap();
        assert!((payload.time - 1.0).abs() < f64::EPSILON);
        assert_eq!(payload.body_count, 2);
    }

    #[test]
    fn test_web_payload_clone() {
        let payload = WebPayload {
            time: 1.0,
            body_count: 2,
            kinetic_energy: 10.0,
            potential_energy: -5.0,
            total_energy: 5.0,
            metrics: SimMetrics::new(),
        };

        let cloned = payload.clone();
        assert!((cloned.time - 1.0).abs() < f64::EPSILON);
        assert_eq!(cloned.body_count, 2);
    }

    #[test]
    fn test_web_payload_debug() {
        let payload = WebPayload {
            time: 1.0,
            body_count: 2,
            kinetic_energy: 10.0,
            potential_energy: -5.0,
            total_energy: 5.0,
            metrics: SimMetrics::new(),
        };

        let debug_str = format!("{:?}", payload);
        assert!(debug_str.contains("WebPayload"));
        assert!(debug_str.contains("time: 1.0"));
    }

    #[tokio::test]
    async fn test_health_handler() {
        let response = health_handler().await;
        let body = response.into_response();
        // Handler returns a response
        let _ = body;
    }

    #[tokio::test]
    async fn test_index_handler() {
        let response = index_handler().await;
        let html = response.0;
        assert!(html.contains("Simular Visualization"));
        assert!(html.contains("WebSocket"));
    }

    #[test]
    fn test_index_html_content() {
        assert!(INDEX_HTML.contains("<!DOCTYPE html>"));
        assert!(INDEX_HTML.contains("Simular Visualization"));
        assert!(INDEX_HTML.contains("ws://"));
        assert!(INDEX_HTML.contains("Total Energy"));
    }

    #[test]
    fn test_broadcast_channel_capacity() {
        let state = WebState::new();
        // Channel has capacity of 100
        for i in 0..100 {
            let _ = state.tx.send(format!("msg{i}"));
        }
        // Should not panic
    }

    #[test]
    fn test_web_visualization_broadcast_multiple() {
        let viz = WebVisualization::new(8080);
        let mut rx = viz.subscribe();

        let state = SimState::default();
        let metrics = SimMetrics::new();

        // Multiple broadcasts
        for i in 0..5 {
            let time = SimTime::from_secs(i as f64);
            let result = viz.broadcast(&state, time, &metrics);
            assert!(result.is_ok());
        }

        // Should receive all broadcasts
        for i in 0..5 {
            let msg = rx.try_recv();
            assert!(msg.is_ok(), "Should receive broadcast {i}");
        }
    }

    #[test]
    fn test_web_payload_default_metrics() {
        let payload = WebPayload {
            time: 0.0,
            body_count: 0,
            kinetic_energy: 0.0,
            potential_energy: 0.0,
            total_energy: 0.0,
            metrics: SimMetrics::new(),
        };

        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"time\":0.0"));
        assert!(json.contains("\"body_count\":0"));
    }

    #[test]
    fn test_web_state_multiple_subscribers() {
        let state = WebState::new();
        let mut rx1 = state.subscribe();
        let mut rx2 = state.subscribe();
        let mut rx3 = state.subscribe();

        // Send a message
        let _ = state.tx.send("test".to_string());

        // All subscribers should receive
        assert!(rx1.try_recv().is_ok());
        assert!(rx2.try_recv().is_ok());
        assert!(rx3.try_recv().is_ok());
    }

    #[tokio::test]
    async fn test_client_count_thread_safe() {
        let state = WebState::new();
        let state_clone = state.clone();

        // Concurrent reads should work
        let (count1, count2) = tokio::join!(state.client_count(), state_clone.client_count());

        assert_eq!(count1, 0);
        assert_eq!(count2, 0);
    }

    #[test]
    fn test_web_payload_with_bodies() {
        let mut sim_state = SimState::default();
        sim_state.add_body(
            1.0,
            crate::engine::state::Vec3::new(1.0, 0.0, 0.0),
            crate::engine::state::Vec3::new(0.0, 1.0, 0.0),
        );
        sim_state.add_body(
            2.0,
            crate::engine::state::Vec3::new(-1.0, 0.0, 0.0),
            crate::engine::state::Vec3::new(0.0, -0.5, 0.0),
        );

        let viz = WebVisualization::new(8080);
        let mut rx = viz.subscribe();

        let result = viz.broadcast(&sim_state, SimTime::from_secs(1.0), &SimMetrics::new());
        assert!(result.is_ok());

        let msg = rx.try_recv().unwrap();
        assert!(msg.contains("\"body_count\":2"));
    }

    #[test]
    fn test_router_routes_exist() {
        let viz = WebVisualization::new(8080);
        let router = viz.router();

        // Router should have routes configured
        // We can't easily test route matching without a full request,
        // but we verify the router was constructed
        let _ = router;
    }

    #[test]
    fn test_web_payload_energy_values() {
        let payload = WebPayload {
            time: 10.5,
            body_count: 3,
            kinetic_energy: 100.5,
            potential_energy: -50.25,
            total_energy: 50.25,
            metrics: SimMetrics::new(),
        };

        assert!((payload.kinetic_energy - 100.5).abs() < f64::EPSILON);
        assert!((payload.potential_energy - (-50.25)).abs() < f64::EPSILON);
        assert!((payload.total_energy - 50.25).abs() < f64::EPSILON);
    }
}