bevy_fairy 0.2.2

An agentic debugger for Bevy games: a Bevy plugin that exposes the game's state over BRP, and an MCP server that lets a coding agent read and drive it
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
/*
 * Production-Grade Connection Pool for BRP Connections
 * Copyright (C) 2025 ladvien
 *
 * Licensed under either of MIT (LICENSE-MIT) or Apache-2.0 (LICENSE-APACHE), at your option.
 *
 * Relicensed from GPL-3.0 when this crate was adopted into Ladvien/foundation_vs_slop: a GPL
 * crate in the Bevy ecosystem cannot be adopted, and being adoptable is why it is published.
 */

//! Connection pooling over the BRP HTTP transport.
//!
//! HTTP is stateless (reqwest pools TCP connections internally), so this pool
//! manages *logical endpoint leases*: acquisition is rate-limited by a
//! semaphore, and health is probed with an `rpc.discover` JSON-RPC call.

use crate::server::config::{Config, ConnectionPoolConfig};
use crate::server::error::{Error, Result};
use serde_json::Value;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, Semaphore};
use tokio::time::timeout;
use tracing::{debug, info, warn};
use uuid::Uuid;

use crate::server::brp::{builtin_methods, BrpRequest, BrpResponse};

/// Connection metadata for pool management
#[derive(Debug, Clone)]
pub struct ConnectionInfo {
    pub id: Uuid,
    pub created_at: Instant,
    pub last_used: Instant,
    pub use_count: u64,
    pub is_healthy: bool,
    pub game_endpoint: String,
}

impl ConnectionInfo {
    pub fn new(game_endpoint: String) -> Self {
        let now = Instant::now();
        Self {
            id: Uuid::new_v4(),
            created_at: now,
            last_used: now,
            use_count: 0,
            is_healthy: true,
            game_endpoint,
        }
    }

    /// Check if connection has exceeded maximum lifetime
    pub fn is_expired(&self, max_lifetime: Duration) -> bool {
        self.created_at.elapsed() > max_lifetime
    }

    /// Check if connection has been idle too long
    pub fn is_idle(&self, idle_timeout: Duration) -> bool {
        self.last_used.elapsed() > idle_timeout
    }

    /// Mark connection as used
    pub fn mark_used(&mut self) {
        self.last_used = Instant::now();
        self.use_count += 1;
    }
}

/// Pooled connection: a logical lease over one logical BRP endpoint.
///
/// Each lease owns its own `reqwest::Client` (with its own TCP pool), so
/// concurrent leases execute fully in parallel.
#[derive(Debug, Clone)]
pub struct PooledConnection {
    pub info: ConnectionInfo,
    pub client: reqwest::Client,
}

impl PooledConnection {
    pub fn new(game_endpoint: String) -> Self {
        Self {
            info: ConnectionInfo::new(game_endpoint),
            client: reqwest::Client::new(),
        }
    }

    /// Send a BRP JSON-RPC request through this lease.
    pub async fn send_request(&self, request: &BrpRequest) -> Result<BrpResponse> {
        let response = self
            .client
            .post(&self.info.game_endpoint)
            .json(request)
            .send()
            .await
            .map_err(Error::from)?;

        if !response.status().is_success() {
            return Err(Error::Connection(format!(
                "BRP server returned HTTP {}",
                response.status()
            )));
        }

        response.json::<BrpResponse>().await.map_err(Error::from)
    }

    /// Test connection health with an `rpc.discover` probe
    pub async fn health_check(&mut self) -> bool {
        let probe = BrpRequest {
            method: builtin_methods::RPC_DISCOVER_METHOD.to_string(),
            id: Some(Value::from(self.info.id.to_string())),
            params: None,
        };

        match self
            .client
            .post(&self.info.game_endpoint)
            .json(&probe)
            .send()
            .await
        {
            Ok(response) if response.status().is_success() => {
                debug!("Health check passed for connection {}", self.info.id);
                self.info.is_healthy = true;
                true
            }
            Ok(response) => {
                warn!(
                    "Health check failed for connection {}: HTTP {}",
                    self.info.id,
                    response.status()
                );
                self.info.is_healthy = false;
                false
            }
            Err(e) => {
                warn!("Health check failed for connection {}: {}", self.info.id, e);
                self.info.is_healthy = false;
                false
            }
        }
    }
}

/// Production-grade connection pool for BRP HTTP endpoints
pub struct ConnectionPool {
    config: Config,
    pool_config: ConnectionPoolConfig,
    available_connections: Arc<Mutex<VecDeque<PooledConnection>>>,
    connection_semaphore: Arc<Semaphore>,
    cleanup_handle: Option<tokio::task::JoinHandle<()>>,
    health_check_handle: Option<tokio::task::JoinHandle<()>>,
    metrics: Arc<Mutex<ConnectionPoolMetrics>>,
}

/// Connection pool metrics for monitoring
#[derive(Debug, Clone, Default)]
pub struct ConnectionPoolMetrics {
    pub active_connections: u32,
    pub available_connections: u32,
    pub total_connections_created: u64,
    pub total_connections_closed: u64,
    pub connection_timeouts: u64,
    pub health_check_failures: u64,
    pub pool_exhausted_events: u64,
}

impl ConnectionPoolMetrics {
    pub fn connection_utilization_rate(&self) -> f64 {
        if self.active_connections + self.available_connections == 0 {
            0.0
        } else {
            self.active_connections as f64
                / (self.active_connections + self.available_connections) as f64
        }
    }
}

static PROBE_SEQ: AtomicU64 = AtomicU64::new(1);

impl ConnectionPool {
    pub fn new(config: Config) -> Self {
        let pool_config = config.resilience.connection_pool.clone();
        let semaphore = Arc::new(Semaphore::new(pool_config.max_connections as usize));

        Self {
            config,
            pool_config,
            available_connections: Arc::new(Mutex::new(VecDeque::new())),
            connection_semaphore: semaphore,
            cleanup_handle: None,
            health_check_handle: None,
            metrics: Arc::new(Mutex::new(ConnectionPoolMetrics::default())),
        }
    }

    /// Start background tasks for connection pool maintenance
    pub async fn start(&mut self) -> Result<()> {
        info!("Starting connection pool with {} max connections", self.pool_config.max_connections);

        // Pre-populate pool with minimum connections
        for _ in 0..self.pool_config.min_connections {
            let connection = self.create_connection();
            let mut pool = self.available_connections.lock().await;
            pool.push_back(connection);
        }

        // Start cleanup task
        self.start_cleanup_task().await;

        // Start health check task
        self.start_health_check_task().await;

        Ok(())
    }

    /// Get a connection lease from the pool
    pub async fn get_connection(&self) -> Result<PooledConnection> {
        // Try to acquire semaphore permit
        let _permit = timeout(
            self.pool_config.connection_timeout,
            self.connection_semaphore.acquire()
        )
        .await
        .map_err(|_| {
            {
                let mut metrics = self.metrics.try_lock().unwrap();
                metrics.connection_timeouts += 1;
                metrics.pool_exhausted_events += 1;
            }
            Error::Connection("Connection pool exhausted - timeout acquiring permit".to_string())
        })?
        .map_err(|_| Error::Connection("Semaphore closed".to_string()))?;

        // Try to get existing connection from pool
        {
            let mut pool = self.available_connections.lock().await;
            if let Some(mut connection) = pool.pop_front() {
                connection.info.mark_used();

                let mut metrics = self.metrics.lock().await;
                metrics.available_connections = pool.len() as u32;
                metrics.active_connections += 1;

                debug!("Reused pooled connection {}", connection.info.id);
                return Ok(connection);
            }
        }

        // Create new connection if pool is empty
        let connection = self.create_connection();

        let mut metrics = self.metrics.lock().await;
        metrics.active_connections += 1;

        info!("Created new pooled connection {}", connection.info.id);
        Ok(connection)
    }

    /// Return a connection lease to the pool
    pub async fn return_connection(&self, connection: PooledConnection) {
        // Check if connection should be discarded
        if connection.info.is_expired(self.pool_config.max_connection_lifetime)
            || !connection.info.is_healthy
        {
            debug!("Discarding connection {} (expired or unhealthy)", connection.info.id);
            let mut metrics = self.metrics.lock().await;
            metrics.active_connections = metrics.active_connections.saturating_sub(1);
            metrics.total_connections_closed += 1;
            return;
        }

        {
            let mut pool = self.available_connections.lock().await;
            pool.push_back(connection);

            let mut metrics = self.metrics.lock().await;
            metrics.available_connections = pool.len() as u32;
            metrics.active_connections = metrics.active_connections.saturating_sub(1);
        }

        debug!("Returned connection to pool");
    }

    /// Get current pool metrics
    pub async fn get_metrics(&self) -> ConnectionPoolMetrics {
        self.metrics.lock().await.clone()
    }

    /// Shutdown the connection pool
    pub async fn shutdown(&mut self) {
        info!("Shutting down connection pool");

        if let Some(handle) = self.cleanup_handle.take() {
            handle.abort();
        }
        if let Some(handle) = self.health_check_handle.take() {
            handle.abort();
        }

        let mut pool = self.available_connections.lock().await;
        pool.clear();

        info!("Connection pool shutdown complete");
    }

    /// Create a new lease to the BRP endpoint
    fn create_connection(&self) -> PooledConnection {
        let url_str = format!(
            "http://{}:{}",
            self.config.bevy_brp_host, self.config.bevy_brp_port
        );

        let connection = PooledConnection::new(url_str);
        PROBE_SEQ.fetch_add(1, Ordering::Relaxed);
        connection
    }

    /// Start cleanup task to remove expired/idle connections
    async fn start_cleanup_task(&mut self) {
        let pool = self.available_connections.clone();
        let config = self.pool_config.clone();
        let metrics = self.metrics.clone();

        let handle = tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(30));

            loop {
                interval.tick().await;

                let mut closed_count = 0u32;
                let mut remaining_connections = VecDeque::new();

                {
                    let mut pool_guard = pool.lock().await;

                    while let Some(connection) = pool_guard.pop_front() {
                        if connection.info.is_expired(config.max_connection_lifetime)
                            || connection.info.is_idle(config.idle_timeout)
                        {
                            closed_count += 1;
                        } else {
                            remaining_connections.push_back(connection);
                        }
                    }

                    *pool_guard = remaining_connections;
                }

                if closed_count > 0 {
                    debug!("Cleaned up {} expired/idle connections", closed_count);
                    let mut metrics_guard = metrics.lock().await;
                    metrics_guard.total_connections_closed += closed_count as u64;
                    metrics_guard.available_connections = metrics_guard.available_connections.saturating_sub(closed_count);
                }
            }
        });

        self.cleanup_handle = Some(handle);
    }

    /// Start health check task for proactive connection monitoring
    async fn start_health_check_task(&mut self) {
        let pool = self.available_connections.clone();
        let metrics = self.metrics.clone();

        let handle = tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(120)); // Check every 2 minutes

            loop {
                interval.tick().await;

                let mut healthy_connections = VecDeque::new();
                let mut unhealthy_count = 0u32;

                {
                    let mut pool_guard = pool.lock().await;

                    while let Some(mut connection) = pool_guard.pop_front() {
                        if connection.health_check().await {
                            healthy_connections.push_back(connection);
                        } else {
                            unhealthy_count += 1;
                        }
                    }

                    *pool_guard = healthy_connections;
                }

                if unhealthy_count > 0 {
                    warn!("Removed {} unhealthy connections during health check", unhealthy_count);
                    let mut metrics_guard = metrics.lock().await;
                    metrics_guard.total_connections_closed += unhealthy_count as u64;
                    metrics_guard.health_check_failures += unhealthy_count as u64;
                    metrics_guard.available_connections = metrics_guard.available_connections.saturating_sub(unhealthy_count);
                }
            }
        });

        self.health_check_handle = Some(handle);
    }
}

impl Drop for ConnectionPool {
    fn drop(&mut self) {
        if let Some(handle) = self.cleanup_handle.take() {
            handle.abort();
        }
        if let Some(handle) = self.health_check_handle.take() {
            handle.abort();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_connection_info_expiry() {
        let mut info = ConnectionInfo::new("http://localhost:15702".to_string());

        // Should not be expired immediately
        assert!(!info.is_expired(Duration::from_secs(60)));

        // Should not be idle immediately
        assert!(!info.is_idle(Duration::from_secs(60)));

        // Mark as used and check use count
        info.mark_used();
        assert_eq!(info.use_count, 1);
    }

    #[test]
    fn test_metrics_utilization_rate() {
        let mut metrics = ConnectionPoolMetrics::default();
        metrics.active_connections = 3;
        metrics.available_connections = 7;

        assert_eq!(metrics.connection_utilization_rate(), 0.3);

        // Edge case: no connections
        metrics.active_connections = 0;
        metrics.available_connections = 0;
        assert_eq!(metrics.connection_utilization_rate(), 0.0);
    }
}