phago-distributed 1.0.0

Distributed colony implementation for horizontal scaling
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! tarpc client utilities.
//!
//! This module provides client utilities for connecting to remote shards
//! and the coordinator. It includes connection functions, retry logic,
//! and a connection pool for efficient client reuse.

use crate::rpc::protocol::{CoordinatorServiceClient, ShardServiceClient};
use crate::types::ShardId;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tarpc::client::Config;
use tokio::sync::RwLock;
use tokio_serde::formats::Bincode;
use tracing::{debug, error, info, warn};

/// Default connection timeout in milliseconds.
const DEFAULT_CONNECT_TIMEOUT_MS: u64 = 5000;

/// Default number of retry attempts for failed connections.
const DEFAULT_RETRY_ATTEMPTS: u32 = 3;

/// Default delay between retry attempts in milliseconds.
const DEFAULT_RETRY_DELAY_MS: u64 = 500;

/// Configuration for client connections.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Connection timeout.
    pub connect_timeout: Duration,
    /// Number of retry attempts.
    pub retry_attempts: u32,
    /// Delay between retries.
    pub retry_delay: Duration,
    /// Maximum pending requests per client.
    pub max_pending_requests: usize,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            connect_timeout: Duration::from_millis(DEFAULT_CONNECT_TIMEOUT_MS),
            retry_attempts: DEFAULT_RETRY_ATTEMPTS,
            retry_delay: Duration::from_millis(DEFAULT_RETRY_DELAY_MS),
            max_pending_requests: 100,
        }
    }
}

/// Create a client connection to a shard.
///
/// Establishes a TCP connection to the shard at the given address and
/// returns a tarpc client for making RPC calls.
///
/// # Arguments
///
/// * `addr` - The socket address of the shard server
///
/// # Errors
///
/// Returns an error if the connection cannot be established.
///
/// # Example
///
/// ```rust,ignore
/// use phago_distributed::rpc::client::connect_to_shard;
///
/// let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
/// let client = connect_to_shard(addr).await?;
///
/// let health = client.health_check(tarpc::context::current()).await?;
/// ```
pub async fn connect_to_shard(addr: SocketAddr) -> Result<ShardServiceClient, std::io::Error> {
    debug!("Connecting to shard at {}", addr);
    let transport = tarpc::serde_transport::tcp::connect(addr, Bincode::default).await?;
    let client = ShardServiceClient::new(Config::default(), transport).spawn();
    info!("Connected to shard at {}", addr);
    Ok(client)
}

/// Create a client connection to a shard with custom configuration.
///
/// # Arguments
///
/// * `addr` - The socket address of the shard server
/// * `config` - Client configuration
///
/// # Errors
///
/// Returns an error if the connection cannot be established.
pub async fn connect_to_shard_with_config(
    addr: SocketAddr,
    config: &ClientConfig,
) -> Result<ShardServiceClient, std::io::Error> {
    debug!("Connecting to shard at {} with custom config", addr);

    let transport = tokio::time::timeout(
        config.connect_timeout,
        tarpc::serde_transport::tcp::connect(addr, Bincode::default),
    )
    .await
    .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "connection timeout"))??;

    let mut tarpc_config = Config::default();
    tarpc_config.max_in_flight_requests = config.max_pending_requests;

    let client = ShardServiceClient::new(tarpc_config, transport).spawn();
    info!("Connected to shard at {}", addr);
    Ok(client)
}

/// Create a client connection to the coordinator.
///
/// Establishes a TCP connection to the coordinator at the given address and
/// returns a tarpc client for making RPC calls.
///
/// # Arguments
///
/// * `addr` - The socket address of the coordinator server
///
/// # Errors
///
/// Returns an error if the connection cannot be established.
///
/// # Example
///
/// ```rust,ignore
/// use phago_distributed::rpc::client::connect_to_coordinator;
///
/// let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
/// let client = connect_to_coordinator(addr).await?;
///
/// let shards = client.list_shards(tarpc::context::current()).await?;
/// ```
pub async fn connect_to_coordinator(
    addr: SocketAddr,
) -> Result<CoordinatorServiceClient, std::io::Error> {
    debug!("Connecting to coordinator at {}", addr);
    let transport = tarpc::serde_transport::tcp::connect(addr, Bincode::default).await?;
    let client = CoordinatorServiceClient::new(Config::default(), transport).spawn();
    info!("Connected to coordinator at {}", addr);
    Ok(client)
}

/// Create a client connection to the coordinator with custom configuration.
///
/// # Arguments
///
/// * `addr` - The socket address of the coordinator server
/// * `config` - Client configuration
///
/// # Errors
///
/// Returns an error if the connection cannot be established.
pub async fn connect_to_coordinator_with_config(
    addr: SocketAddr,
    config: &ClientConfig,
) -> Result<CoordinatorServiceClient, std::io::Error> {
    debug!("Connecting to coordinator at {} with custom config", addr);

    let transport = tokio::time::timeout(
        config.connect_timeout,
        tarpc::serde_transport::tcp::connect(addr, Bincode::default),
    )
    .await
    .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "connection timeout"))??;

    let mut tarpc_config = Config::default();
    tarpc_config.max_in_flight_requests = config.max_pending_requests;

    let client = CoordinatorServiceClient::new(tarpc_config, transport).spawn();
    info!("Connected to coordinator at {}", addr);
    Ok(client)
}

/// Connect to a shard with automatic retry on failure.
///
/// Attempts to connect to the shard, retrying on failure according to
/// the configuration.
///
/// # Arguments
///
/// * `addr` - The socket address of the shard server
/// * `config` - Client configuration including retry settings
///
/// # Errors
///
/// Returns an error if all retry attempts fail.
pub async fn connect_to_shard_with_retry(
    addr: SocketAddr,
    config: &ClientConfig,
) -> Result<ShardServiceClient, std::io::Error> {
    let mut last_error = None;

    for attempt in 0..config.retry_attempts {
        if attempt > 0 {
            warn!(
                "Retry attempt {} connecting to shard at {}",
                attempt + 1,
                addr
            );
            tokio::time::sleep(config.retry_delay).await;
        }

        match connect_to_shard_with_config(addr, config).await {
            Ok(client) => {
                if attempt > 0 {
                    info!(
                        "Successfully connected to shard at {} after {} attempts",
                        addr,
                        attempt + 1
                    );
                }
                return Ok(client);
            }
            Err(e) => {
                warn!("Failed to connect to shard at {}: {}", addr, e);
                last_error = Some(e);
            }
        }
    }

    error!(
        "Failed to connect to shard at {} after {} attempts",
        addr, config.retry_attempts
    );
    Err(last_error.unwrap_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotConnected, "connection failed")
    }))
}

/// Connect to the coordinator with automatic retry on failure.
///
/// # Arguments
///
/// * `addr` - The socket address of the coordinator server
/// * `config` - Client configuration including retry settings
///
/// # Errors
///
/// Returns an error if all retry attempts fail.
pub async fn connect_to_coordinator_with_retry(
    addr: SocketAddr,
    config: &ClientConfig,
) -> Result<CoordinatorServiceClient, std::io::Error> {
    let mut last_error = None;

    for attempt in 0..config.retry_attempts {
        if attempt > 0 {
            warn!(
                "Retry attempt {} connecting to coordinator at {}",
                attempt + 1,
                addr
            );
            tokio::time::sleep(config.retry_delay).await;
        }

        match connect_to_coordinator_with_config(addr, config).await {
            Ok(client) => {
                if attempt > 0 {
                    info!(
                        "Successfully connected to coordinator at {} after {} attempts",
                        addr,
                        attempt + 1
                    );
                }
                return Ok(client);
            }
            Err(e) => {
                warn!("Failed to connect to coordinator at {}: {}", addr, e);
                last_error = Some(e);
            }
        }
    }

    error!(
        "Failed to connect to coordinator at {} after {} attempts",
        addr, config.retry_attempts
    );
    Err(last_error.unwrap_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotConnected, "connection failed")
    }))
}

/// A pool of shard client connections.
///
/// The connection pool maintains a cached set of connections to shards,
/// creating new connections on demand and reusing existing ones.
///
/// # Thread Safety
///
/// The pool is thread-safe and can be shared across multiple tasks.
///
/// # Example
///
/// ```rust,ignore
/// use phago_distributed::rpc::client::ShardClientPool;
///
/// let pool = ShardClientPool::new();
/// pool.register_shard(ShardId::new(0), "127.0.0.1:8080".parse().unwrap());
///
/// let client = pool.get_client(ShardId::new(0)).await?;
/// let health = client.health_check(tarpc::context::current()).await?;
/// ```
pub struct ShardClientPool {
    /// Mapping from shard ID to address.
    addresses: Arc<RwLock<HashMap<ShardId, SocketAddr>>>,
    /// Cached client connections.
    clients: Arc<RwLock<HashMap<ShardId, ShardServiceClient>>>,
    /// Client configuration.
    config: ClientConfig,
}

impl ShardClientPool {
    /// Create a new empty connection pool.
    pub fn new() -> Self {
        Self {
            addresses: Arc::new(RwLock::new(HashMap::new())),
            clients: Arc::new(RwLock::new(HashMap::new())),
            config: ClientConfig::default(),
        }
    }

    /// Create a new connection pool with custom configuration.
    pub fn with_config(config: ClientConfig) -> Self {
        Self {
            addresses: Arc::new(RwLock::new(HashMap::new())),
            clients: Arc::new(RwLock::new(HashMap::new())),
            config,
        }
    }

    /// Register a shard's address.
    ///
    /// This does not establish a connection immediately; connections
    /// are created lazily when `get_client` is called.
    pub async fn register_shard(&self, shard_id: ShardId, addr: SocketAddr) {
        let mut addresses = self.addresses.write().await;
        addresses.insert(shard_id, addr);
        debug!("Registered shard {:?} at {}", shard_id, addr);
    }

    /// Unregister a shard and close any cached connection.
    pub async fn unregister_shard(&self, shard_id: ShardId) {
        let mut addresses = self.addresses.write().await;
        addresses.remove(&shard_id);

        let mut clients = self.clients.write().await;
        clients.remove(&shard_id);
        debug!("Unregistered shard {:?}", shard_id);
    }

    /// Get a client for the specified shard.
    ///
    /// Returns a cached client if available, otherwise creates a new connection.
    ///
    /// # Errors
    ///
    /// Returns an error if the shard is not registered or if the connection fails.
    pub async fn get_client(
        &self,
        shard_id: ShardId,
    ) -> Result<ShardServiceClient, std::io::Error> {
        // Check for cached client
        {
            let clients = self.clients.read().await;
            if let Some(client) = clients.get(&shard_id) {
                return Ok(client.clone());
            }
        }

        // Get address
        let addr = {
            let addresses = self.addresses.read().await;
            addresses.get(&shard_id).copied()
        };

        let addr = addr.ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("shard {:?} not registered", shard_id),
            )
        })?;

        // Create new connection
        let client = connect_to_shard_with_retry(addr, &self.config).await?;

        // Cache the client
        {
            let mut clients = self.clients.write().await;
            clients.insert(shard_id, client.clone());
        }

        Ok(client)
    }

    /// Get clients for all registered shards.
    ///
    /// Attempts to connect to all shards, returning successfully connected clients.
    /// Failed connections are logged but do not cause the entire operation to fail.
    pub async fn get_all_clients(&self) -> Vec<(ShardId, ShardServiceClient)> {
        let addresses: Vec<_> = {
            let addresses = self.addresses.read().await;
            addresses.iter().map(|(&id, &addr)| (id, addr)).collect()
        };

        let mut results = Vec::with_capacity(addresses.len());
        for (shard_id, _) in addresses {
            match self.get_client(shard_id).await {
                Ok(client) => results.push((shard_id, client)),
                Err(e) => warn!("Failed to get client for shard {:?}: {}", shard_id, e),
            }
        }

        results
    }

    /// Check if a shard is registered.
    pub async fn has_shard(&self, shard_id: ShardId) -> bool {
        let addresses = self.addresses.read().await;
        addresses.contains_key(&shard_id)
    }

    /// Get the number of registered shards.
    pub async fn shard_count(&self) -> usize {
        let addresses = self.addresses.read().await;
        addresses.len()
    }

    /// Get the number of cached connections.
    pub async fn cached_connection_count(&self) -> usize {
        let clients = self.clients.read().await;
        clients.len()
    }

    /// Clear all cached connections.
    ///
    /// This forces new connections to be created on the next `get_client` call.
    pub async fn clear_cache(&self) {
        let mut clients = self.clients.write().await;
        clients.clear();
        debug!("Cleared connection cache");
    }

    /// Remove a cached connection for a specific shard.
    ///
    /// Useful for forcing a reconnection after a failure.
    pub async fn invalidate_client(&self, shard_id: ShardId) {
        let mut clients = self.clients.write().await;
        clients.remove(&shard_id);
        debug!("Invalidated cached client for shard {:?}", shard_id);
    }
}

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

impl Clone for ShardClientPool {
    fn clone(&self) -> Self {
        Self {
            addresses: Arc::clone(&self.addresses),
            clients: Arc::clone(&self.clients),
            config: self.config.clone(),
        }
    }
}

/// A coordinator client wrapper with automatic reconnection.
///
/// This wrapper maintains a connection to the coordinator and
/// automatically attempts to reconnect if the connection is lost.
pub struct CoordinatorClient {
    /// The coordinator's address.
    addr: SocketAddr,
    /// The cached client connection.
    client: Arc<RwLock<Option<CoordinatorServiceClient>>>,
    /// Client configuration.
    config: ClientConfig,
}

impl CoordinatorClient {
    /// Create a new coordinator client.
    ///
    /// This does not establish a connection immediately; the connection
    /// is created lazily on the first call to `get`.
    pub fn new(addr: SocketAddr) -> Self {
        Self {
            addr,
            client: Arc::new(RwLock::new(None)),
            config: ClientConfig::default(),
        }
    }

    /// Create a new coordinator client with custom configuration.
    pub fn with_config(addr: SocketAddr, config: ClientConfig) -> Self {
        Self {
            addr,
            client: Arc::new(RwLock::new(None)),
            config,
        }
    }

    /// Get the coordinator client, creating a connection if needed.
    pub async fn get(&self) -> Result<CoordinatorServiceClient, std::io::Error> {
        // Check for cached client
        {
            let client = self.client.read().await;
            if let Some(ref c) = *client {
                return Ok(c.clone());
            }
        }

        // Create new connection
        let new_client = connect_to_coordinator_with_retry(self.addr, &self.config).await?;

        // Cache the client
        {
            let mut client = self.client.write().await;
            *client = Some(new_client.clone());
        }

        Ok(new_client)
    }

    /// Force a reconnection.
    ///
    /// Useful after detecting a connection failure.
    pub async fn reconnect(&self) -> Result<CoordinatorServiceClient, std::io::Error> {
        // Clear the cached client
        {
            let mut client = self.client.write().await;
            *client = None;
        }

        // Get a new connection
        self.get().await
    }

    /// Invalidate the cached connection without reconnecting.
    pub async fn invalidate(&self) {
        let mut client = self.client.write().await;
        *client = None;
        debug!("Invalidated coordinator client");
    }

    /// Get the coordinator's address.
    pub fn addr(&self) -> SocketAddr {
        self.addr
    }
}

impl Clone for CoordinatorClient {
    fn clone(&self) -> Self {
        Self {
            addr: self.addr,
            client: Arc::clone(&self.client),
            config: self.config.clone(),
        }
    }
}

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

    #[test]
    fn test_client_config_default() {
        let config = ClientConfig::default();
        assert_eq!(
            config.connect_timeout.as_millis(),
            DEFAULT_CONNECT_TIMEOUT_MS as u128
        );
        assert_eq!(config.retry_attempts, DEFAULT_RETRY_ATTEMPTS);
        assert_eq!(
            config.retry_delay.as_millis(),
            DEFAULT_RETRY_DELAY_MS as u128
        );
    }

    #[tokio::test]
    async fn test_shard_client_pool_register() {
        let pool = ShardClientPool::new();

        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        pool.register_shard(ShardId::new(0), addr).await;

        assert!(pool.has_shard(ShardId::new(0)).await);
        assert!(!pool.has_shard(ShardId::new(1)).await);
        assert_eq!(pool.shard_count().await, 1);
    }

    #[tokio::test]
    async fn test_shard_client_pool_unregister() {
        let pool = ShardClientPool::new();

        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        pool.register_shard(ShardId::new(0), addr).await;
        pool.unregister_shard(ShardId::new(0)).await;

        assert!(!pool.has_shard(ShardId::new(0)).await);
        assert_eq!(pool.shard_count().await, 0);
    }

    #[tokio::test]
    async fn test_shard_client_pool_get_client_not_registered() {
        let pool = ShardClientPool::new();

        let result = pool.get_client(ShardId::new(0)).await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::NotFound);
    }

    #[tokio::test]
    async fn test_shard_client_pool_clear_cache() {
        let pool = ShardClientPool::new();

        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        pool.register_shard(ShardId::new(0), addr).await;

        // The cache should be empty initially
        assert_eq!(pool.cached_connection_count().await, 0);

        // Clear should work even when empty
        pool.clear_cache().await;
        assert_eq!(pool.cached_connection_count().await, 0);
    }

    #[tokio::test]
    async fn test_shard_client_pool_invalidate_client() {
        let pool = ShardClientPool::new();

        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        pool.register_shard(ShardId::new(0), addr).await;

        // Invalidate should work even without a cached client
        pool.invalidate_client(ShardId::new(0)).await;
        assert_eq!(pool.cached_connection_count().await, 0);
    }

    #[tokio::test]
    async fn test_shard_client_pool_clone() {
        let pool = ShardClientPool::new();

        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        pool.register_shard(ShardId::new(0), addr).await;

        let pool_clone = pool.clone();
        assert!(pool_clone.has_shard(ShardId::new(0)).await);

        // Changes should be visible in both
        pool_clone
            .register_shard(ShardId::new(1), "127.0.0.1:8081".parse().unwrap())
            .await;
        assert!(pool.has_shard(ShardId::new(1)).await);
    }

    #[test]
    fn test_coordinator_client_new() {
        let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
        let client = CoordinatorClient::new(addr);

        assert_eq!(client.addr(), addr);
    }

    #[tokio::test]
    async fn test_coordinator_client_invalidate() {
        let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
        let client = CoordinatorClient::new(addr);

        // Invalidate should work even without a cached connection
        client.invalidate().await;
    }

    #[tokio::test]
    async fn test_coordinator_client_clone() {
        let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
        let client = CoordinatorClient::new(addr);
        let client_clone = client.clone();

        assert_eq!(client_clone.addr(), addr);
    }

    #[tokio::test]
    async fn test_shard_client_pool_with_config() {
        let config = ClientConfig {
            connect_timeout: Duration::from_secs(10),
            retry_attempts: 5,
            retry_delay: Duration::from_millis(200),
            max_pending_requests: 50,
        };

        let pool = ShardClientPool::with_config(config);
        assert_eq!(pool.shard_count().await, 0);
    }

    #[test]
    fn test_coordinator_client_with_config() {
        let addr: SocketAddr = "127.0.0.1:8000".parse().unwrap();
        let config = ClientConfig {
            connect_timeout: Duration::from_secs(10),
            retry_attempts: 5,
            retry_delay: Duration::from_millis(200),
            max_pending_requests: 50,
        };

        let client = CoordinatorClient::with_config(addr, config);
        assert_eq!(client.addr(), addr);
    }
}