digdigdig3 0.1.26

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! # ConnectorPool - Thread-Safe Connection Pool
//!
//! Lock-free connection pool using DashMap for optimal concurrent performance.
//!
//! ## Architecture
//!
//! ```text
//! ConnectorPool
//!   ├── DashMap<ExchangeId, Arc<AnyConnector>>  [Lock-free reads]
//!   └── Methods: insert, get, remove, iter, etc.
//! ```
//!
//! ## Performance
//!
//! DashMap provides:
//! - Lock-free reads (5-33x faster than RwLock)
//! - Fine-grained locking (only shard-level locks on writes)
//! - Zero contention for read-heavy workloads
//!
//! ## Usage
//!
//! ```ignore
//! use connectors_v5::connector_manager::{ConnectorPool, AnyConnector};
//! use connectors_v5::core::types::ExchangeId;
//! use std::sync::Arc;
//!
//! // Create pool
//! let pool = ConnectorPool::new();
//!
//! // Insert connectors
//! pool.insert(ExchangeId::Binance, Arc::new(AnyConnector::Binance(binance)));
//! pool.insert(ExchangeId::KuCoin, Arc::new(AnyConnector::KuCoin(kucoin)));
//!
//! // Get connector (lock-free read, cheap Arc clone)
//! if let Some(connector) = pool.get(&ExchangeId::Binance) {
//!     let price = connector.get_price(symbol, account_type).await?;
//! }
//!
//! // Iterate over all connectors
//! for entry in pool.iter() {
//!     println!("{:?} is connected", entry.key());
//! }
//! ```

use dashmap::DashMap;
use std::sync::Arc;

use crate::connector_manager::AnyConnector;
use crate::core::traits::MarketData;
use crate::core::types::{
    AccountCapabilities, AccountType, ExchangeId, MarketDataCapabilities, TradingCapabilities,
};

// ═══════════════════════════════════════════════════════════════════════════════
// ConnectorPool - Thread-Safe Pool with DashMap
// ═══════════════════════════════════════════════════════════════════════════════

/// Thread-safe connection pool with lock-free reads.
///
/// Uses `DashMap` for optimal concurrent performance. All read operations
/// (get, contains, len, etc.) are lock-free and scale linearly with CPU cores.
///
/// Write operations (insert, remove, clear) use fine-grained shard-level locking,
/// ensuring minimal contention even under high concurrency.
///
/// # Examples
///
/// ```ignore
/// let pool = ConnectorPool::new();
/// pool.insert(ExchangeId::Binance, Arc::new(connector));
///
/// if let Some(connector) = pool.get(&ExchangeId::Binance) {
///     // Use connector...
/// }
/// ```
#[derive(Clone)]
pub struct ConnectorPool {
    /// Active connector instances (lock-free reads)
    connectors: Arc<DashMap<ExchangeId, Arc<AnyConnector>>>,
}

impl ConnectorPool {
    /// Create a new empty pool.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let pool = ConnectorPool::new();
    /// assert!(pool.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            connectors: Arc::new(DashMap::new()),
        }
    }

    /// Insert a connector into the pool.
    ///
    /// If a connector with the same `ExchangeId` already exists, it will be
    /// replaced and the old connector will be returned.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique exchange identifier
    /// * `connector` - Connector instance wrapped in Arc
    ///
    /// # Returns
    ///
    /// `Some(old_connector)` if a connector was replaced, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let pool = ConnectorPool::new();
    /// let old = pool.insert(ExchangeId::Binance, Arc::new(connector));
    /// assert!(old.is_none()); // First insert
    /// ```
    pub fn insert(&self, id: ExchangeId, connector: Arc<AnyConnector>) -> Option<Arc<AnyConnector>> {
        self.connectors.insert(id, connector)
    }

    /// Get a connector by exchange ID (lock-free read).
    ///
    /// Returns a cheap Arc clone of the connector if found. The clone operation
    /// is O(1) and only increments a reference counter.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier to look up
    ///
    /// # Returns
    ///
    /// `Some(Arc<AnyConnector>)` if found, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// if let Some(connector) = pool.get(&ExchangeId::Binance) {
    ///     let price = connector.get_price(symbol, account_type).await?;
    /// }
    /// ```
    pub fn get(&self, id: &ExchangeId) -> Option<Arc<AnyConnector>> {
        self.connectors.get(id).map(|entry| entry.value().clone())
    }

    /// Remove a connector from the pool.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier to remove
    ///
    /// # Returns
    ///
    /// `Some(Arc<AnyConnector>)` if the connector was found and removed, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// if let Some(connector) = pool.remove(&ExchangeId::Binance) {
    ///     println!("Removed Binance connector");
    /// }
    /// ```
    pub fn remove(&self, id: &ExchangeId) -> Option<Arc<AnyConnector>> {
        self.connectors.remove(id).map(|(_, connector)| connector)
    }

    /// Check if a connector exists in the pool (lock-free).
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier to check
    ///
    /// # Returns
    ///
    /// `true` if the connector exists, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// if pool.contains(&ExchangeId::Binance) {
    ///     println!("Binance is connected");
    /// }
    /// ```
    pub fn contains(&self, id: &ExchangeId) -> bool {
        self.connectors.contains_key(id)
    }

    /// Count the number of active connectors (lock-free).
    ///
    /// # Returns
    ///
    /// The number of connectors currently in the pool.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let count = pool.len();
    /// println!("Active connections: {}", count);
    /// ```
    pub fn len(&self) -> usize {
        self.connectors.len()
    }

    /// Check if the pool is empty (lock-free).
    ///
    /// # Returns
    ///
    /// `true` if the pool contains no connectors, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// if pool.is_empty() {
    ///     println!("No connectors available");
    /// }
    /// ```
    pub fn is_empty(&self) -> bool {
        self.connectors.is_empty()
    }

    /// Remove all connectors from the pool.
    ///
    /// This operation is atomic - either all connectors are removed or none.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// pool.clear();
    /// assert!(pool.is_empty());
    /// ```
    pub fn clear(&self) {
        self.connectors.clear();
    }

    /// Iterate over all connectors in the pool.
    ///
    /// Returns an iterator that yields references to (ExchangeId, Arc<AnyConnector>) pairs.
    /// The iterator holds read locks on individual shards, so it's efficient for iteration
    /// while allowing concurrent reads from other threads.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// for entry in pool.iter() {
    ///     println!("{:?} is active", entry.key());
    /// }
    /// ```
    pub fn iter(&self) -> dashmap::iter::Iter<'_, ExchangeId, Arc<AnyConnector>> {
        self.connectors.iter()
    }

    /// Get a list of all exchange IDs in the pool.
    ///
    /// # Returns
    ///
    /// Vector of all ExchangeIds currently in the pool.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let ids = pool.ids();
    /// println!("Connected exchanges: {:?}", ids);
    /// ```
    pub fn ids(&self) -> Vec<ExchangeId> {
        self.connectors.iter().map(|entry| *entry.key()).collect()
    }

    /// Get market data capabilities for a connector.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier to look up
    /// * `account_type` - Account type to query capabilities for
    ///
    /// # Returns
    ///
    /// `Some(MarketDataCapabilities)` if the connector exists, `None` otherwise.
    pub fn market_data_capabilities(
        &self,
        id: &ExchangeId,
        account_type: AccountType,
    ) -> Option<MarketDataCapabilities> {
        self.connectors
            .get(id)
            .map(|c| c.market_data_capabilities(account_type))
    }

    /// Get trading capabilities for a connector.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier to look up
    /// * `account_type` - Account type to query capabilities for
    ///
    /// # Returns
    ///
    /// `Some(TradingCapabilities)` if the connector exists, `None` otherwise.
    pub fn trading_capabilities(
        &self,
        id: &ExchangeId,
        account_type: AccountType,
    ) -> Option<TradingCapabilities> {
        self.connectors
            .get(id)
            .map(|c| c.trading_capabilities(account_type))
    }

    /// Get account capabilities for a connector.
    ///
    /// # Arguments
    ///
    /// * `id` - Exchange identifier to look up
    /// * `account_type` - Account type to query capabilities for
    ///
    /// # Returns
    ///
    /// `Some(AccountCapabilities)` if the connector exists, `None` otherwise.
    pub fn account_capabilities(
        &self,
        id: &ExchangeId,
        account_type: AccountType,
    ) -> Option<AccountCapabilities> {
        self.connectors
            .get(id)
            .map(|c| c.account_capabilities(account_type))
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// ConnectorPoolBuilder - Fluent API for Pool Construction
// ═══════════════════════════════════════════════════════════════════════════════

/// Builder for constructing ConnectorPool with fluent API.
///
/// Provides a convenient way to create a pool with multiple connectors
/// in a single expression chain.
///
/// # Examples
///
/// ```ignore
/// let pool = ConnectorPoolBuilder::new()
///     .with_connector(ExchangeId::Binance, Arc::new(binance_connector))
///     .with_connector(ExchangeId::KuCoin, Arc::new(kucoin_connector))
///     .build();
///
/// assert_eq!(pool.len(), 2);
/// ```
pub struct ConnectorPoolBuilder {
    pool: ConnectorPool,
}

impl ConnectorPoolBuilder {
    /// Create a new builder with an empty pool.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let builder = ConnectorPoolBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            pool: ConnectorPool::new(),
        }
    }

    /// Add a connector to the pool.
    ///
    /// This method consumes self and returns a new builder, allowing for
    /// method chaining.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique exchange identifier
    /// * `connector` - Connector instance wrapped in Arc
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let builder = ConnectorPoolBuilder::new()
    ///     .with_connector(ExchangeId::Binance, Arc::new(connector));
    /// ```
    pub fn with_connector(self, id: ExchangeId, connector: Arc<AnyConnector>) -> Self {
        self.pool.insert(id, connector);
        self
    }

    /// Build the final ConnectorPool.
    ///
    /// Consumes the builder and returns the configured pool.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let pool = ConnectorPoolBuilder::new()
    ///     .with_connector(ExchangeId::Binance, Arc::new(connector))
    ///     .build();
    /// ```
    pub fn build(self) -> ConnectorPool {
        self.pool
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Unit Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::l3::open::crypto::cex::okx::OkxConnector;
    use std::thread;

    /// Helper function to create a mock OKX connector for testing.
    /// Uses OKX's public API to avoid credentials.
    fn create_mock_okx() -> Arc<AnyConnector> {
        // Use tokio runtime to call async constructor
        let rt = tokio::runtime::Runtime::new().unwrap();
        let connector = rt.block_on(async {
            OkxConnector::public(true).await.unwrap()
        });
        Arc::new(AnyConnector::OKX(Arc::new(connector)))
    }

    /// Helper function to create a second mock connector (using same OKX).
    /// In real usage, this would be a different exchange.
    fn create_mock_okx_2() -> Arc<AnyConnector> {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let connector = rt.block_on(async {
            OkxConnector::public(false).await.unwrap()
        });
        Arc::new(AnyConnector::OKX(Arc::new(connector)))
    }

    #[test]
    fn test_new_pool_is_empty() {
        let pool = ConnectorPool::new();
        assert!(pool.is_empty());
        assert_eq!(pool.len(), 0);
    }

    #[test]
    fn test_insert_and_get() {
        let pool = ConnectorPool::new();
        let connector = create_mock_okx();

        // Insert connector
        let old = pool.insert(ExchangeId::Binance, connector.clone());
        assert!(old.is_none());

        // Verify it exists
        assert!(!pool.is_empty());
        assert_eq!(pool.len(), 1);

        // Get connector
        let retrieved = pool.get(&ExchangeId::Binance);
        assert!(retrieved.is_some());
    }

    #[test]
    fn test_insert_replace() {
        let pool = ConnectorPool::new();
        let connector1 = create_mock_okx();
        let connector2 = create_mock_okx();

        // First insert
        pool.insert(ExchangeId::Binance, connector1);

        // Second insert should replace
        let old = pool.insert(ExchangeId::Binance, connector2);
        assert!(old.is_some());
        assert_eq!(pool.len(), 1); // Still only one connector
    }

    #[test]
    fn test_get_nonexistent() {
        let pool = ConnectorPool::new();
        let result = pool.get(&ExchangeId::Binance);
        assert!(result.is_none());
    }

    #[test]
    fn test_contains() {
        let pool = ConnectorPool::new();
        let connector = create_mock_okx();

        assert!(!pool.contains(&ExchangeId::Binance));

        pool.insert(ExchangeId::Binance, connector);

        assert!(pool.contains(&ExchangeId::Binance));
        assert!(!pool.contains(&ExchangeId::KuCoin));
    }

    #[test]
    fn test_remove() {
        let pool = ConnectorPool::new();
        let connector = create_mock_okx();

        pool.insert(ExchangeId::Binance, connector);
        assert_eq!(pool.len(), 1);

        // Remove connector
        let removed = pool.remove(&ExchangeId::Binance);
        assert!(removed.is_some());
        assert_eq!(pool.len(), 0);
        assert!(pool.is_empty());

        // Remove again should return None
        let removed_again = pool.remove(&ExchangeId::Binance);
        assert!(removed_again.is_none());
    }

    #[test]
    fn test_clear() {
        let pool = ConnectorPool::new();

        pool.insert(ExchangeId::Binance, create_mock_okx());
        pool.insert(ExchangeId::KuCoin, create_mock_okx_2());

        assert_eq!(pool.len(), 2);

        pool.clear();

        assert!(pool.is_empty());
        assert_eq!(pool.len(), 0);
    }

    #[test]
    fn test_iter() {
        let pool = ConnectorPool::new();

        pool.insert(ExchangeId::Binance, create_mock_okx());
        pool.insert(ExchangeId::KuCoin, create_mock_okx_2());

        let mut count = 0;
        for entry in pool.iter() {
            count += 1;
            assert!(
                *entry.key() == ExchangeId::Binance || *entry.key() == ExchangeId::KuCoin
            );
        }

        assert_eq!(count, 2);
    }

    #[test]
    fn test_ids() {
        let pool = ConnectorPool::new();

        pool.insert(ExchangeId::Binance, create_mock_okx());
        pool.insert(ExchangeId::KuCoin, create_mock_okx_2());

        let ids = pool.ids();
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&ExchangeId::Binance));
        assert!(ids.contains(&ExchangeId::KuCoin));
    }

    #[test]
    fn test_multiple_inserts() {
        let pool = ConnectorPool::new();

        for i in 0..10 {
            let id = if i % 2 == 0 {
                ExchangeId::Binance
            } else {
                ExchangeId::KuCoin
            };
            pool.insert(id, create_mock_okx());
        }

        // Should only have 2 unique connectors
        assert_eq!(pool.len(), 2);
    }

    #[test]
    fn test_builder_empty() {
        let pool = ConnectorPoolBuilder::new().build();
        assert!(pool.is_empty());
    }

    #[test]
    fn test_builder_single_connector() {
        let pool = ConnectorPoolBuilder::new()
            .with_connector(ExchangeId::Binance, create_mock_okx())
            .build();

        assert_eq!(pool.len(), 1);
        assert!(pool.contains(&ExchangeId::Binance));
    }

    #[test]
    fn test_builder_multiple_connectors() {
        let pool = ConnectorPoolBuilder::new()
            .with_connector(ExchangeId::Binance, create_mock_okx())
            .with_connector(ExchangeId::KuCoin, create_mock_okx_2())
            .build();

        assert_eq!(pool.len(), 2);
        assert!(pool.contains(&ExchangeId::Binance));
        assert!(pool.contains(&ExchangeId::KuCoin));
    }

    #[test]
    fn test_builder_with_duplicates() {
        let pool = ConnectorPoolBuilder::new()
            .with_connector(ExchangeId::Binance, create_mock_okx())
            .with_connector(ExchangeId::Binance, create_mock_okx()) // Duplicate
            .build();

        // Should only have 1 connector (duplicates are replaced)
        assert_eq!(pool.len(), 1);
    }

    #[test]
    fn test_concurrent_inserts() {
        let pool = Arc::new(ConnectorPool::new());
        let mut handles = vec![];

        // Spawn 10 threads that insert connectors concurrently
        for i in 0..10 {
            let pool_clone = Arc::clone(&pool);
            let handle = thread::spawn(move || {
                let id = if i % 2 == 0 {
                    ExchangeId::Binance
                } else {
                    ExchangeId::KuCoin
                };
                pool_clone.insert(id, create_mock_okx());
            });
            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // Should only have 2 unique connectors despite concurrent inserts
        assert_eq!(pool.len(), 2);
    }

    #[test]
    fn test_concurrent_reads() {
        let pool = Arc::new(ConnectorPool::new());
        pool.insert(ExchangeId::Binance, create_mock_okx());

        let mut handles = vec![];

        // Spawn 100 threads that read concurrently
        for _ in 0..100 {
            let pool_clone = Arc::clone(&pool);
            let handle = thread::spawn(move || {
                let connector = pool_clone.get(&ExchangeId::Binance);
                assert!(connector.is_some());
            });
            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_concurrent_mixed_operations() {
        let pool = Arc::new(ConnectorPool::new());
        pool.insert(ExchangeId::Binance, create_mock_okx());

        let mut handles = vec![];

        // Spawn threads with mixed operations
        for i in 0..50 {
            let pool_clone = Arc::clone(&pool);
            let handle = thread::spawn(move || {
                match i % 3 {
                    0 => {
                        // Read operation
                        let _ = pool_clone.get(&ExchangeId::Binance);
                    }
                    1 => {
                        // Insert operation
                        pool_clone.insert(ExchangeId::KuCoin, create_mock_okx_2());
                    }
                    2 => {
                        // Contains check
                        let _ = pool_clone.contains(&ExchangeId::Binance);
                    }
                    _ => unreachable!(),
                }
            });
            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // Verify pool is still in a valid state
        assert!(pool.len() > 0);
    }

    #[test]
    fn test_pool_clone() {
        let pool1 = ConnectorPool::new();
        pool1.insert(ExchangeId::Binance, create_mock_okx());

        // Clone the pool
        let pool2 = pool1.clone();

        // Both pools should share the same underlying DashMap
        assert_eq!(pool1.len(), 1);
        assert_eq!(pool2.len(), 1);

        // Insert via pool2
        pool2.insert(ExchangeId::KuCoin, create_mock_okx_2());

        // pool1 should also see the change
        assert_eq!(pool1.len(), 2);
        assert_eq!(pool2.len(), 2);
    }

    #[test]
    fn test_default_pool() {
        let pool: ConnectorPool = Default::default();
        assert!(pool.is_empty());
    }

    #[test]
    fn test_default_builder() {
        let pool = ConnectorPoolBuilder::default().build();
        assert!(pool.is_empty());
    }
}