dx-dcp 0.1.0

Development Context Protocol - binary-first replacement for MCP
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
//! TCP transport implementation for DCP server.
//!
//! Provides TCP server with configurable bind address, connection limits,
//! TLS support, and protocol negotiation.

use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufReader};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{broadcast, RwLock, Semaphore};
use tokio_rustls::rustls;
use tokio_rustls::TlsAcceptor;

/// TLS version configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TlsVersion {
    /// TLS 1.2
    #[default]
    Tls12,
    /// TLS 1.3
    Tls13,
}

/// TLS configuration
#[derive(Debug, Clone)]
pub struct TlsConfig {
    /// Path to certificate file (PEM format)
    pub cert_path: PathBuf,
    /// Path to private key file (PEM format)
    pub key_path: PathBuf,
    /// Minimum TLS version (default: 1.2)
    pub min_version: TlsVersion,
}

impl TlsConfig {
    /// Create a new TLS configuration
    pub fn new(cert_path: impl Into<PathBuf>, key_path: impl Into<PathBuf>) -> Self {
        Self {
            cert_path: cert_path.into(),
            key_path: key_path.into(),
            min_version: TlsVersion::default(),
        }
    }

    /// Set minimum TLS version
    pub fn with_min_version(mut self, version: TlsVersion) -> Self {
        self.min_version = version;
        self
    }

    /// Build a TLS acceptor from this configuration
    pub fn build_acceptor(&self) -> io::Result<TlsAcceptor> {
        // Load certificates
        let cert_file = File::open(&self.cert_path).map_err(|e| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "Failed to open certificate file {:?}: {}",
                    self.cert_path, e
                ),
            )
        })?;
        let mut cert_reader = BufReader::new(cert_file);
        let certs: Vec<_> = rustls_pemfile::certs(&mut cert_reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Failed to parse certificates: {}", e),
                )
            })?;

        if certs.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "No certificates found in certificate file",
            ));
        }

        // Load private key
        let key_file = File::open(&self.key_path).map_err(|e| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!("Failed to open key file {:?}: {}", self.key_path, e),
            )
        })?;
        let mut key_reader = BufReader::new(key_file);

        let key = rustls_pemfile::private_key(&mut key_reader)
            .map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Failed to parse private key: {}", e),
                )
            })?
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    "No private key found in key file",
                )
            })?;

        // Build server config
        let config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(certs, key)
            .map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Failed to build TLS config: {}", e),
                )
            })?;

        Ok(TlsAcceptor::from(Arc::new(config)))
    }
}

/// TCP listener configuration
#[derive(Debug, Clone)]
pub struct TcpConfig {
    /// Bind address (e.g., "0.0.0.0:9000")
    pub bind_addr: SocketAddr,
    /// Maximum concurrent connections
    pub max_connections: usize,
    /// Connection timeout in seconds
    pub connection_timeout_secs: u64,
    /// Read buffer size
    pub read_buffer_size: usize,
    /// Enable TCP_NODELAY
    pub nodelay: bool,
    /// TLS configuration (optional)
    pub tls: Option<TlsConfig>,
}

impl Default for TcpConfig {
    fn default() -> Self {
        Self {
            bind_addr: "127.0.0.1:9000".parse().unwrap(),
            max_connections: 1000,
            connection_timeout_secs: 30,
            read_buffer_size: 8192,
            nodelay: true,
            tls: None,
        }
    }
}

/// Protocol mode after negotiation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProtocolMode {
    /// MCP JSON-RPC over newline-delimited JSON
    #[default]
    McpJson,
    /// DCP binary protocol
    DcpBinary,
}

/// Connection state
#[derive(Debug)]
pub struct Connection {
    /// Unique connection ID
    pub id: u64,
    /// Peer address
    pub peer_addr: SocketAddr,
    /// Detected protocol mode
    pub protocol: ProtocolMode,
    /// Connection creation time
    pub created_at: Instant,
    /// Bytes read counter
    pub bytes_read: AtomicU64,
    /// Bytes written counter
    pub bytes_written: AtomicU64,
}

impl Connection {
    /// Create a new connection
    pub fn new(id: u64, peer_addr: SocketAddr) -> Self {
        Self {
            id,
            peer_addr,
            protocol: ProtocolMode::McpJson,
            created_at: Instant::now(),
            bytes_read: AtomicU64::new(0),
            bytes_written: AtomicU64::new(0),
        }
    }

    /// Record bytes read
    pub fn record_read(&self, bytes: u64) {
        self.bytes_read.fetch_add(bytes, Ordering::Relaxed);
    }

    /// Record bytes written
    pub fn record_write(&self, bytes: u64) {
        self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
    }

    /// Get total bytes read
    pub fn total_bytes_read(&self) -> u64 {
        self.bytes_read.load(Ordering::Relaxed)
    }

    /// Get total bytes written
    pub fn total_bytes_written(&self) -> u64 {
        self.bytes_written.load(Ordering::Relaxed)
    }

    /// Get connection age
    pub fn age(&self) -> Duration {
        self.created_at.elapsed()
    }
}

/// DCP magic bytes for binary protocol detection
pub const DCP_MAGIC: [u8; 4] = [0x44, 0x43, 0x50, 0x01]; // "DCP\x01"

/// TCP server implementation
pub struct TcpServer {
    /// Server configuration
    config: TcpConfig,
    /// Active connections
    connections: Arc<RwLock<HashMap<u64, Arc<Connection>>>>,
    /// Connection ID counter
    connection_counter: AtomicU64,
    /// Connection limit semaphore
    connection_semaphore: Arc<Semaphore>,
    /// Shutdown signal sender
    shutdown_tx: broadcast::Sender<()>,
    /// Whether server is running
    running: Arc<std::sync::atomic::AtomicBool>,
}

impl TcpServer {
    /// Create a new TCP server with the given configuration
    pub fn new(config: TcpConfig) -> Self {
        let (shutdown_tx, _) = broadcast::channel(1);
        Self {
            connection_semaphore: Arc::new(Semaphore::new(config.max_connections)),
            config,
            connections: Arc::new(RwLock::new(HashMap::new())),
            connection_counter: AtomicU64::new(1),
            shutdown_tx,
            running: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    /// Get the server configuration
    pub fn config(&self) -> &TcpConfig {
        &self.config
    }

    /// Get current connection count
    pub async fn connection_count(&self) -> usize {
        self.connections.read().await.len()
    }

    /// Get a connection by ID
    pub async fn get_connection(&self, id: u64) -> Option<Arc<Connection>> {
        self.connections.read().await.get(&id).cloned()
    }

    /// Check if server is running
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::SeqCst)
    }

    /// Try to acquire a connection slot
    /// Returns None if connection limit is reached
    pub fn try_acquire_connection(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
        self.connection_semaphore.clone().try_acquire_owned().ok()
    }

    /// Register a new connection
    pub async fn register_connection(&self, peer_addr: SocketAddr) -> Arc<Connection> {
        let id = self.connection_counter.fetch_add(1, Ordering::SeqCst);
        let conn = Arc::new(Connection::new(id, peer_addr));
        self.connections.write().await.insert(id, Arc::clone(&conn));
        conn
    }

    /// Remove a connection
    pub async fn remove_connection(&self, id: u64) -> Option<Arc<Connection>> {
        self.connections.write().await.remove(&id)
    }

    /// Detect protocol from first bytes
    /// Returns (protocol_mode, bytes_to_process)
    pub fn detect_protocol(first_bytes: &[u8]) -> ProtocolMode {
        if first_bytes.is_empty() {
            return ProtocolMode::McpJson;
        }

        // Check for DCP magic bytes
        if first_bytes.len() >= 4 && first_bytes[..4] == DCP_MAGIC {
            return ProtocolMode::DcpBinary;
        }

        // Check for JSON (starts with '{' or '[')
        let first_non_ws = first_bytes.iter().find(|&&b| !b.is_ascii_whitespace());
        if let Some(&b) = first_non_ws {
            if b == b'{' || b == b'[' {
                return ProtocolMode::McpJson;
            }
        }

        // Default to binary if unclear
        ProtocolMode::DcpBinary
    }

    /// Start accepting connections
    pub async fn run<H>(&self, handler: H) -> io::Result<()>
    where
        H: ConnectionHandler + Clone + Send + Sync + 'static,
    {
        if self.config.tls.is_some() {
            self.running.store(false, Ordering::SeqCst);
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "TLS configuration is present, but TCP TLS accept handling is not wired; refusing plaintext",
            ));
        }

        let listener = TcpListener::bind(self.config.bind_addr).await?;
        self.running.store(true, Ordering::SeqCst);

        let mut shutdown_rx = self.shutdown_tx.subscribe();

        loop {
            tokio::select! {
                result = listener.accept() => {
                    match result {
                        Ok((stream, peer_addr)) => {
                            // Try to acquire connection slot
                            let permit = match self.try_acquire_connection() {
                                Some(p) => p,
                                None => {
                                    // Connection limit reached, reject
                                    drop(stream);
                                    continue;
                                }
                            };

                            // Set TCP options
                            if self.config.nodelay {
                                let _ = stream.set_nodelay(true);
                            }

                            // Register connection
                            let conn = self.register_connection(peer_addr).await;
                            let handler = handler.clone();
                            let connections = Arc::clone(&self.connections);
                            let timeout = Duration::from_secs(self.config.connection_timeout_secs);
                            let buffer_size = self.config.read_buffer_size;

                            // Spawn connection handler
                            tokio::spawn(async move {
                                let _permit = permit; // Hold permit until connection closes
                                let conn_id = conn.id;

                                let result = Self::handle_connection(
                                    stream,
                                    conn,
                                    handler,
                                    timeout,
                                    buffer_size,
                                ).await;

                                // Clean up connection
                                connections.write().await.remove(&conn_id);

                                if let Err(e) = result {
                                    // Log error but don't crash
                                    eprintln!("Connection {} error: {}", conn_id, e);
                                }
                            });
                        }
                        Err(e) => {
                            eprintln!("Accept error: {}", e);
                        }
                    }
                }
                _ = shutdown_rx.recv() => {
                    break;
                }
            }
        }

        self.running.store(false, Ordering::SeqCst);
        Ok(())
    }

    /// Handle a single connection
    async fn handle_connection<H>(
        mut stream: TcpStream,
        conn: Arc<Connection>,
        handler: H,
        timeout: Duration,
        buffer_size: usize,
    ) -> io::Result<()>
    where
        H: ConnectionHandler,
    {
        let mut buffer = vec![0u8; buffer_size];

        // Read first bytes for protocol detection
        let first_read = tokio::time::timeout(timeout, stream.read(&mut buffer)).await;

        let n = match first_read {
            Ok(Ok(0)) => return Ok(()), // EOF
            Ok(Ok(n)) => n,
            Ok(Err(e)) => return Err(e),
            Err(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "connection timeout",
                ))
            }
        };

        // Detect protocol
        let protocol = Self::detect_protocol(&buffer[..n]);

        // Update connection protocol
        // Note: Connection.protocol is not mutable after creation,
        // but we pass the detected protocol to the handler

        // Call handler with detected protocol and initial data
        handler
            .handle(&mut stream, &conn, protocol, &buffer[..n])
            .await
    }

    /// Graceful shutdown - stop accepting, drain existing connections
    pub async fn shutdown(&self, timeout: Duration) -> io::Result<()> {
        // Signal shutdown
        let _ = self.shutdown_tx.send(());

        // Wait for connections to drain
        let deadline = Instant::now() + timeout;
        while self.connection_count().await > 0 {
            if Instant::now() > deadline {
                // Force close remaining connections
                self.connections.write().await.clear();
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        Ok(())
    }

    /// Get shutdown signal receiver
    pub fn shutdown_receiver(&self) -> broadcast::Receiver<()> {
        self.shutdown_tx.subscribe()
    }
}

/// Connection handler trait
pub trait ConnectionHandler: Send + Sync + Clone + 'static {
    /// Handle a connection with detected protocol and initial data
    fn handle(
        &self,
        stream: &mut TcpStream,
        conn: &Connection,
        protocol: ProtocolMode,
        initial_data: &[u8],
    ) -> impl std::future::Future<Output = io::Result<()>> + Send;
}

/// Simple echo handler for testing
#[derive(Clone)]
pub struct EchoHandler;

impl ConnectionHandler for EchoHandler {
    async fn handle(
        &self,
        stream: &mut TcpStream,
        conn: &Connection,
        _protocol: ProtocolMode,
        initial_data: &[u8],
    ) -> io::Result<()> {
        // Echo back initial data
        if !initial_data.is_empty() {
            stream.write_all(initial_data).await?;
            conn.record_read(initial_data.len() as u64);
            conn.record_write(initial_data.len() as u64);
        }

        // Continue echoing
        let mut buffer = vec![0u8; 4096];
        loop {
            let n = stream.read(&mut buffer).await?;
            if n == 0 {
                break;
            }
            conn.record_read(n as u64);
            stream.write_all(&buffer[..n]).await?;
            conn.record_write(n as u64);
        }

        Ok(())
    }
}

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

    #[test]
    fn test_tcp_config_default() {
        let config = TcpConfig::default();
        assert_eq!(config.max_connections, 1000);
        assert_eq!(config.connection_timeout_secs, 30);
        assert!(config.nodelay);
        assert!(config.tls.is_none());
    }

    #[test]
    fn test_connection_new() {
        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        let conn = Connection::new(1, addr);
        assert_eq!(conn.id, 1);
        assert_eq!(conn.peer_addr, addr);
        assert_eq!(conn.protocol, ProtocolMode::McpJson);
    }

    #[test]
    fn test_connection_bytes_tracking() {
        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        let conn = Connection::new(1, addr);

        conn.record_read(100);
        conn.record_read(50);
        conn.record_write(200);

        assert_eq!(conn.total_bytes_read(), 150);
        assert_eq!(conn.total_bytes_written(), 200);
    }

    #[test]
    fn test_detect_protocol_json() {
        assert_eq!(
            TcpServer::detect_protocol(b"{\"jsonrpc\":\"2.0\"}"),
            ProtocolMode::McpJson
        );
        assert_eq!(
            TcpServer::detect_protocol(b"  {\"test\":1}"),
            ProtocolMode::McpJson
        );
        assert_eq!(
            TcpServer::detect_protocol(b"[1,2,3]"),
            ProtocolMode::McpJson
        );
    }

    #[test]
    fn test_detect_protocol_binary() {
        assert_eq!(
            TcpServer::detect_protocol(&DCP_MAGIC),
            ProtocolMode::DcpBinary
        );
        assert_eq!(
            TcpServer::detect_protocol(&[0x44, 0x43, 0x50, 0x01, 0x00, 0x00]),
            ProtocolMode::DcpBinary
        );
    }

    #[test]
    fn test_detect_protocol_empty() {
        assert_eq!(TcpServer::detect_protocol(&[]), ProtocolMode::McpJson);
    }

    #[tokio::test]
    async fn test_tcp_server_connection_limit() {
        let config = TcpConfig {
            max_connections: 2,
            ..Default::default()
        };
        let server = TcpServer::new(config);

        // Acquire two permits
        let permit1 = server.try_acquire_connection();
        let permit2 = server.try_acquire_connection();

        assert!(permit1.is_some());
        assert!(permit2.is_some());

        // Third should fail
        let permit3 = server.try_acquire_connection();
        assert!(permit3.is_none());

        // Drop one permit
        drop(permit1);

        // Now should succeed
        let permit4 = server.try_acquire_connection();
        assert!(permit4.is_some());
    }

    #[tokio::test]
    async fn test_tcp_server_register_connection() {
        let config = TcpConfig::default();
        let server = TcpServer::new(config);

        let addr: SocketAddr = "192.168.1.1:12345".parse().unwrap();
        let conn = server.register_connection(addr).await;

        assert_eq!(conn.id, 1);
        assert_eq!(conn.peer_addr, addr);
        assert_eq!(server.connection_count().await, 1);

        // Register another
        let addr2: SocketAddr = "192.168.1.2:12346".parse().unwrap();
        let conn2 = server.register_connection(addr2).await;
        assert_eq!(conn2.id, 2);
        assert_eq!(server.connection_count().await, 2);
    }

    #[tokio::test]
    async fn test_tcp_server_remove_connection() {
        let config = TcpConfig::default();
        let server = TcpServer::new(config);

        let addr: SocketAddr = "192.168.1.1:12345".parse().unwrap();
        let conn = server.register_connection(addr).await;
        let id = conn.id;

        assert_eq!(server.connection_count().await, 1);

        let removed = server.remove_connection(id).await;
        assert!(removed.is_some());
        assert_eq!(server.connection_count().await, 0);

        // Remove again should return None
        let removed_again = server.remove_connection(id).await;
        assert!(removed_again.is_none());
    }
}