wasma-sys 1.3.0-beta-stable

WASMA Windows Assignment System Monitoring Architecture — client and protocol layer
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_client_unix_posix_raw_app.rs
// Raw POSIX Application Data Access Client
// UClient varsayılan implementasyonu - read() tabanlı, trait miras alır
// Ocak 2026

use std::os::unix::io::{AsRawFd, RawFd};
use std::sync::Arc;
use std::time::Duration;

// Mevcut WASMA modüllerinden import
use crate::parser::WasmaConfig;
use crate::uclient::SectionMemory;

// ============================================================================
// POSIX ALT MODÜLÜ - Tüm unsafe POSIX çağrıları burada izole edilir
// ============================================================================

pub mod posix {
    use std::io;
    use std::os::unix::io::RawFd;

    /// POSIX open() - dosya veya cihaz fd'si açar
    /// flags: libc::O_RDONLY, libc::O_RDWR, libc::O_NONBLOCK vb.
    pub fn posix_open(path: &str, flags: i32) -> io::Result<RawFd> {
        use std::ffi::CString;
        let c_path =
            CString::new(path).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
        let fd = unsafe { libc::open(c_path.as_ptr(), flags) };
        if fd < 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(fd)
        }
    }

    /// POSIX read() - fd üzerinden ham veri okur
    /// Güvenli wrapper: buffer sınırı aşılamaz
    pub fn posix_read(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
        let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
        match n {
            -1 => Err(io::Error::last_os_error()),
            0 => Ok(0), // EOF
            n => Ok(n as usize),
        }
    }

    /// POSIX read_exact() - tam olarak n byte okur, EOF veya hata olana dek
    pub fn posix_read_exact(fd: RawFd, buf: &mut [u8]) -> io::Result<()> {
        let mut total = 0;
        while total < buf.len() {
            match posix_read(fd, &mut buf[total..]) {
                Ok(0) => {
                    return Err(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "Beklenmedik EOF: POSIX read_exact",
                    ))
                }
                Ok(n) => total += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    /// POSIX close() - fd'yi serbest bırakır
    pub fn posix_close(fd: RawFd) -> io::Result<()> {
        let ret = unsafe { libc::close(fd) };
        if ret == 0 {
            Ok(())
        } else {
            Err(io::Error::last_os_error())
        }
    }

    /// POSIX fcntl() - fd özelliklerini sorgular/ayarlar
    pub fn posix_set_nonblocking(fd: RawFd, nonblocking: bool) -> io::Result<()> {
        let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
        if flags < 0 {
            return Err(io::Error::last_os_error());
        }
        let new_flags = if nonblocking {
            flags | libc::O_NONBLOCK
        } else {
            flags & !libc::O_NONBLOCK
        };
        let ret = unsafe { libc::fcntl(fd, libc::F_SETFL, new_flags) };
        if ret < 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }

    /// POSIX poll() - fd'nin okumaya hazır olup olmadığını kontrol eder
    /// timeout_ms: -1 → sonsuz bekleme, 0 → anında dön
    pub fn posix_poll_readable(fd: RawFd, timeout_ms: i32) -> io::Result<bool> {
        let mut pfd = libc::pollfd {
            fd,
            events: libc::POLLIN,
            revents: 0,
        };
        let ret = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
        match ret {
            -1 => Err(io::Error::last_os_error()),
            0 => Ok(false), // timeout
            _ => Ok(pfd.revents & libc::POLLIN != 0),
        }
    }
}

// ============================================================================
// UCLİENT ENGINE TRAIT - Tüm UClient implementasyonlarının sözleşmesi
// ============================================================================

/// UClientEngine - WASMA istemci motorunun temel sözleşmesi
/// raw_app, wgclient ve diğer istemciler bu trait'i implement eder
pub trait UClientEngine {
    /// Motoru başlatır ve veri akışını işlemeye başlar
    fn start_engine(&mut self) -> Result<(), Box<dyn std::error::Error>>;

    /// Tek bir veri bloğunu renderer'a gönderir
    fn dispatch_data(&self, data: &[u8]);

    /// Bellek kullanımını döndürür: (toplam_byte, hücre_sayısı, hücre_boyutu)
    fn memory_usage(&self) -> (usize, usize, usize);

    /// Motorun config referansını döndürür
    fn get_config(&self) -> &WasmaConfig;

    /// Motoru durdurur ve kaynakları serbest bırakır
    fn shutdown(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        println!("🛑 UClientEngine: Motor stopping...");
        Ok(())
    }

    /// Motorun aktif olup olmadığını döndürür
    fn is_active(&self) -> bool {
        true
    }
}

// ============================================================================
// RAW APP DESCRIPTOR - Uygulama kimliği ve POSIX fd yönetimi
// ============================================================================

/// Uygulama kaynağının türü
#[derive(Debug, Clone, PartialEq)]
pub enum RawAppSource {
    /// Unix domain socket (varsayılan)
    UnixSocket(String),
    /// Karakter cihazı (örn: /dev/wasma0)
    CharDevice(String),
    /// Named pipe / FIFO
    NamedPipe(String),
    /// TCP soket fd (mevcut bağlantıdan devir alınan)
    TcpSocket { ip: String, port: u16 },
    /// Stdin (test amaçlı)
    Stdin,
}

impl RawAppSource {
    /// Kaynağın path veya adresini döndürür
    pub fn display_name(&self) -> String {
        match self {
            Self::UnixSocket(p) => format!("unix:{}", p),
            Self::CharDevice(p) => format!("chardev:{}", p),
            Self::NamedPipe(p) => format!("fifo:{}", p),
            Self::TcpSocket { ip, port } => format!("tcp:{}:{}", ip, port),
            Self::Stdin => "stdin".to_string(),
        }
    }
}

/// Raw uygulama kaynağını tanımlayan yapı
pub struct RawAppDescriptor {
    /// Uygulama adı / kimliği
    pub app_id: String,
    /// Veri kaynağı türü
    pub source: RawAppSource,
    /// Açık olan POSIX fd (None ise henüz açılmamış)
    fd: Option<RawFd>,
    /// Bloke olmayan mod
    nonblocking: bool,
}

impl RawAppDescriptor {
    pub fn new(app_id: impl Into<String>, source: RawAppSource) -> Self {
        Self {
            app_id: app_id.into(),
            source,
            fd: None,
            nonblocking: false,
        }
    }

    /// Kaynağı açar ve fd'yi alır
    pub fn open(&mut self) -> Result<RawFd, std::io::Error> {
        if let Some(fd) = self.fd {
            return Ok(fd); // Zaten açık
        }

        let fd = match &self.source {
            RawAppSource::UnixSocket(path) => self.connect_unix_socket(path)?,
            RawAppSource::CharDevice(path) => posix::posix_open(path, libc::O_RDONLY)?,
            RawAppSource::NamedPipe(path) => {
                posix::posix_open(path, libc::O_RDONLY | libc::O_NONBLOCK)?
            }
            RawAppSource::TcpSocket { ip, port } => self.connect_tcp(ip, *port)?,
            RawAppSource::Stdin => {
                0 // stdin fd = 0
            }
        };

        self.fd = Some(fd);
        println!(
            "📂 RawAppDescriptor: '{}' opened (fd={})",
            self.source.display_name(),
            fd
        );
        Ok(fd)
    }

    /// Unix domain socket bağlantısı
    fn connect_unix_socket(&self, path: &str) -> Result<RawFd, std::io::Error> {
        use std::os::unix::net::UnixStream;
        let stream = UnixStream::connect(path)?;
        let fd = stream.as_raw_fd();
        // stream drop edilmeden önce fd'yi çıkarmalıyız
        // ManuallyDrop ile ownership'i biz alıyoruz
        let _ = std::mem::ManuallyDrop::new(stream);
        Ok(fd)
    }

    /// TCP soket bağlantısı
    fn connect_tcp(&self, ip: &str, port: u16) -> Result<RawFd, std::io::Error> {
        use std::net::TcpStream;
        let addr = format!("{}:{}", ip, port);
        let stream = TcpStream::connect(&addr)?;
        let fd = stream.as_raw_fd();
        let _ = std::mem::ManuallyDrop::new(stream);
        Ok(fd)
    }

    /// Non-blocking modu ayarlar
    pub fn set_nonblocking(&mut self, nb: bool) -> Result<(), std::io::Error> {
        if let Some(fd) = self.fd {
            posix::posix_set_nonblocking(fd, nb)?;
        }
        self.nonblocking = nb;
        Ok(())
    }

    /// fd'yi döndürür
    pub fn fd(&self) -> Option<RawFd> {
        self.fd
    }

    /// fd'nin okumaya hazır olup olmadığını kontrol eder
    pub fn poll_readable(&self, timeout_ms: i32) -> Result<bool, std::io::Error> {
        match self.fd {
            Some(fd) => posix::posix_poll_readable(fd, timeout_ms),
            None => Err(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "Descriptor henüz açılmadı",
            )),
        }
    }
}

impl Drop for RawAppDescriptor {
    fn drop(&mut self) {
        if let Some(fd) = self.fd.take() {
            // stdin'i kapatma
            if fd != 0 {
                let _ = posix::posix_close(fd);
                println!(
                    "📁 RawAppDescriptor: '{}' closed (fd={})",
                    self.source.display_name(),
                    fd
                );
            }
        }
    }
}

// ============================================================================
// RAW APP BUFFER - Sıfır ekstra kopya buffer yönetimi
// ============================================================================

/// read() tabanlı çift buffer yapısı
/// A ve B tampon arasında ping-pong yapar → işlem sırasında okuma devam eder
pub struct RawAppBuffer {
    buf_a: Vec<u8>,
    buf_b: Vec<u8>,
    active: bool, // true = A aktif, false = B aktif
    buf_size: usize,
}

impl RawAppBuffer {
    pub fn new(buf_size: usize) -> Self {
        Self {
            buf_a: vec![0u8; buf_size],
            buf_b: vec![0u8; buf_size],
            active: true,
            buf_size,
        }
    }

    /// Aktif okuma tamponunu döndürür (mutable)
    pub fn write_buf(&mut self) -> &mut [u8] {
        if self.active {
            &mut self.buf_a
        } else {
            &mut self.buf_b
        }
    }

    /// İşlem tamponunu döndürür (immutable) - okuma tamponunun karşısı
    pub fn read_buf(&self) -> &[u8] {
        if self.active {
            &self.buf_b
        } else {
            &self.buf_a
        }
    }

    /// Tamponları değiştirir (swap)
    pub fn swap(&mut self) {
        self.active = !self.active;
    }

    pub fn buf_size(&self) -> usize {
        self.buf_size
    }
}

// ============================================================================
// RAW APP CLIENT - Ana istemci yapısı, UClientEngine trait'ini implement eder
// ============================================================================

/// RawAppClient - UClientEngine trait'inden türeyen raw POSIX uygulama istemcisi
///
/// uclient.rs'deki UClient'ın raw POSIX fd tabanlı versiyonu.
/// Aynı SectionMemory mantığını korur, ancak:
///   - TCP TcpStream yerine ham POSIX fd kullanır
///   - read() çağrıları posix modülünde izole edilir
///   - Çift tampon (ping-pong) ile kesintisiz veri akışı sağlar
///   - UClientEngine trait'i aracılığıyla WGClient ile değiştirilebilir
pub struct RawAppClient {
    config: Arc<WasmaConfig>,
    descriptor: RawAppDescriptor,
    memory: SectionMemory,
    buffer: RawAppBuffer,
    active: bool,
}

impl RawAppClient {
    /// Config ve varsayılan UnixSocket kaynağıyla oluşturur
    pub fn new(config: WasmaConfig) -> Self {
        let level = config.resource_limits.scope_level;

        // Varsayılan kaynak: WASMA unix socket
        let source = RawAppSource::UnixSocket("/run/wasma/app.sock".to_string());

        Self {
            descriptor: RawAppDescriptor::new("wasma.raw.app", source),
            memory: SectionMemory::new(level),
            buffer: RawAppBuffer::new(Self::buf_size_for_level(level)),
            config: Arc::new(config),
            active: false,
        }
    }

    /// Arc<WasmaConfig> ile oluşturur (WindowHandler entegrasyonu için)
    pub fn from_config(config: Arc<WasmaConfig>) -> Self {
        let level = config.resource_limits.scope_level;
        let source = RawAppSource::UnixSocket("/run/wasma/app.sock".to_string());
        Self {
            descriptor: RawAppDescriptor::new("wasma.raw.app", source),
            memory: SectionMemory::new(level),
            buffer: RawAppBuffer::new(Self::buf_size_for_level(level)),
            config,
            active: false,
        }
    }

    /// Kaynak türünü özelleştirir (builder pattern)
    pub fn with_source(mut self, source: RawAppSource) -> Self {
        self.descriptor = RawAppDescriptor::new(self.descriptor.app_id.clone(), source);
        self
    }

    /// scope_level'e göre uygun tampon boyutunu hesaplar
    fn buf_size_for_level(level: u32) -> usize {
        match level {
            0 => 4096,            // NULL_EXCEPTION: 4KB raw akış
            1..=10 => 8 * 1024,   // Düşük seviye: 8KB
            11..=50 => 64 * 1024, // Orta seviye: 64KB
            _ => 256 * 1024,      // Yüksek seviye: 256KB
        }
    }

    /// NULL_EXCEPTION modunda raw akış işler (scope_level == 0)
    fn process_raw_stream(&self, data: &[u8]) {
        // scope_level = 0: bölümleme yok, direkt dispatcher'a gönder
        self.dispatch_data(data);
    }

    /// Bölümlenmiş modda hücre doldur ve işle (scope_level > 0)
    fn process_partitioned(&mut self, fd: RawFd) -> Result<(), Box<dyn std::error::Error>> {
        for i in 0..self.memory.cell_count {
            let cell = self.memory.get_cell_mut(i);
            posix::posix_read_exact(fd, cell)?;
            // Hücre dolduktan sonra dispatcher'a gönder
            let cell_data = self.memory.get_cell(i).to_vec();
            self.dispatch_data(&cell_data);
        }
        Ok(())
    }
}

// ============================================================================
// UCLİENT ENGINE TRAIT İMPLEMENTASYONU
// ============================================================================

impl UClientEngine for RawAppClient {
    fn start_engine(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let level = self.config.resource_limits.scope_level;

        println!(
            "🔌 RawAppClient: Source opened → {}",
            self.descriptor.source.display_name()
        );

        let fd = self.descriptor.open()?;
        self.active = true;

        println!("🟢 WASMA RawAppClient: Motor Başladı");
        println!(
            "📡 Mod: {}",
            if level == 0 {
                "NULL_EXCEPTION (Bypass/Raw)"
            } else {
                "Bölümlenmiş (Partitioned)"
            }
        );
        println!("🎨 Renderer: {}", self.config.resource_limits.renderer);
        println!("📦 Tampon boyutu: {} byte", self.buffer.buf_size());

        if level == 0 {
            // NULL_EXCEPTION: 4KB pencereler halinde ham akış
            loop {
                // Okumaya hazır mı? (100ms timeout)
                match self.descriptor.poll_readable(100) {
                    Ok(false) => continue, // timeout, tekrar dene
                    Ok(true) => {}
                    Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(e) => return Err(Box::new(e)),
                }

                let write_buf = self.buffer.write_buf();
                match posix::posix_read(fd, write_buf) {
                    Ok(0) => {
                        println!("📭 EOF getting, motor stopping.");
                        break;
                    }
                    Ok(n) => {
                        // Swap: işlenmiş tampon okuma tamponuna geçiyor
                        self.buffer.swap();
                        let data = self.buffer.read_buf()[..n].to_vec();
                        self.process_raw_stream(&data);
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        // Non-blocking: veri yok, bekle
                        std::thread::sleep(Duration::from_millis(1));
                        continue;
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(e) => return Err(Box::new(e)),
                }
            }
        } else {
            // Bölümlenmiş mod: SectionMemory hücreleri doldur
            loop {
                match self.process_partitioned(fd) {
                    Ok(_) => {}
                    Err(e) if e.to_string().contains("Beklenmedik EOF") => {
                        println!("📭 Data flowing completed..");
                        break;
                    }
                    Err(e) => return Err(e),
                }
            }
        }

        self.active = false;
        Ok(())
    }

    fn dispatch_data(&self, data: &[u8]) {
        // Mevcut uclient.rs dispatch_to_hardware() mantığıyla uyumlu
        match self.config.resource_limits.renderer.as_str() {
            "glx_renderer" => {
                #[cfg(feature = "glx")]
                {
                    // GLX: direkt VRAM texture güncelleme
                    // uclient.rs run_glx() ile aynı mantık
                    println!("🎨 GLX dispatch: {} byte", data.len());
                }
                #[cfg(not(feature = "glx"))]
                {
                    self.dispatch_cpu_fallback(data);
                }
            }
            "renderer_opencl" | "opencl" => {
                #[cfg(feature = "opencl-gpu")]
                {
                    println!("🎮 OpenCL dispatch: {} byte", data.len());
                }
                #[cfg(not(feature = "opencl-gpu"))]
                {
                    self.dispatch_cpu_fallback(data);
                }
            }
            "renderer_iuhd" | "intel_uhd" => {
                #[cfg(feature = "intel-uhd")]
                {
                    println!("💻 Intel UHD dispatch: {} byte", data.len());
                }
                #[cfg(not(feature = "intel-uhd"))]
                {
                    self.dispatch_cpu_fallback(data);
                }
            }
            "cpu_renderer" | "cpu" | _ => {
                self.dispatch_cpu_fallback(data);
            }
        }
    }

    fn memory_usage(&self) -> (usize, usize, usize) {
        (
            self.memory.raw_storage.len(),
            self.memory.cell_count,
            self.memory.cell_size,
        )
    }

    fn get_config(&self) -> &WasmaConfig {
        &self.config
    }

    fn shutdown(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.active = false;
        println!(
            "🛑 RawAppClient closed: {}",
            self.descriptor.source.display_name()
        );
        // descriptor Drop trait'i ile fd'yi otomatik kapatır
        Ok(())
    }

    fn is_active(&self) -> bool {
        self.active
    }
}

// ============================================================================
// ÖZEL YARDIMCI METODLAR (Trait dışı)
// ============================================================================

impl RawAppClient {
    /// CPU fallback renderer - feature flag olmadan her zaman kullanılabilir
    fn dispatch_cpu_fallback(&self, data: &[u8]) {
        // uclient.rs run_cpu() ile aynı mantık
        for chunk in data.chunks(1024) {
            let _sum: u32 = chunk.iter().map(|&x| x as u32).sum();
        }
    }

    /// Descriptor'a erişim (test/debug için)
    pub fn descriptor(&self) -> &RawAppDescriptor {
        &self.descriptor
    }

    /// Descriptor'a mutable erişim (kaynak değişimi için)
    pub fn descriptor_mut(&mut self) -> &mut RawAppDescriptor {
        &mut self.descriptor
    }
}

// ============================================================================
// BUILDER - RawAppClient kolayca oluşturmak için
// ============================================================================

pub struct RawAppClientBuilder {
    config: Option<WasmaConfig>,
    source: Option<RawAppSource>,
    app_id: Option<String>,
}

impl RawAppClientBuilder {
    pub fn new() -> Self {
        Self {
            config: None,
            source: None,
            app_id: None,
        }
    }

    pub fn with_config(mut self, config: WasmaConfig) -> Self {
        self.config = Some(config);
        self
    }

    pub fn with_source(mut self, source: RawAppSource) -> Self {
        self.source = Some(source);
        self
    }

    pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
        self.app_id = Some(id.into());
        self
    }

    pub fn build(self) -> Result<RawAppClient, String> {
        let config = self.config.ok_or("Config required")?;
        let mut client = RawAppClient::new(config);

        if let Some(source) = self.source {
            let app_id = self.app_id.unwrap_or_else(|| "wasma.raw.app".to_string());
            client.descriptor = RawAppDescriptor::new(app_id, source);
        }

        Ok(client)
    }
}

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

// ============================================================================
// TESTLER
// ============================================================================

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

    fn make_config() -> WasmaConfig {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        parser.parse(&content).unwrap()
    }

    #[test]
    fn test_raw_app_client_creation() {
        let config = make_config();
        let client = RawAppClient::new(config);

        let (total, cells, cell_size) = client.memory_usage();
        assert!(total > 0);
        assert!(cells > 0);
        assert_eq!(cell_size, 1024 * 1024);
        assert!(!client.is_active());

        println!(
            "✅ RawAppClient building...: cells={}, cell_size={}KB",
            cells,
            cell_size / 1024
        );
    }

    #[test]
    fn test_builder_pattern() {
        let config = make_config();
        let client = RawAppClientBuilder::new()
            .with_config(config)
            .with_source(RawAppSource::Stdin)
            .with_app_id("test.app")
            .build()
            .unwrap();

        assert_eq!(client.descriptor().app_id, "test.app");
        assert_eq!(client.descriptor().source, RawAppSource::Stdin);
        println!("✅ Builder pattern running");
    }

    #[test]
    fn test_section_memory_compatibility() {
        // uclient.rs SectionMemory ile uyumluluk testi
        let mem = SectionMemory::new(10);
        assert_eq!(mem.cell_count, 10);
        assert_eq!(mem.cell_size, 1024 * 1024);
        println!("✅ SectionMemory compability verifying");
    }

    #[test]
    fn test_raw_app_buffer_pingpong() {
        let mut buf = RawAppBuffer::new(4096);

        // A tamponuna yaz
        buf.write_buf()[0] = 0xAB;
        buf.swap();

        // Swap sonrası read_buf A'yı göstermeli
        assert_eq!(buf.read_buf()[0], 0xAB);

        // B tamponuna yaz
        buf.write_buf()[0] = 0xCD;
        buf.swap();

        // Swap sonrası read_buf B'yi göstermeli
        assert_eq!(buf.read_buf()[0], 0xCD);

        println!("✅ Ping-pong buffer running");
    }

    #[test]
    fn test_dispatch_cpu_fallback() {
        let config = make_config();
        let client = RawAppClient::new(config);
        let data = vec![1u8; 2048];
        // Panik olmadan çalışmalı
        client.dispatch_data(&data);
        println!("✅ CPU fallback dispatch running");
    }

    #[test]
    fn test_buf_size_for_level() {
        assert_eq!(RawAppClient::buf_size_for_level(0), 4096);
        assert_eq!(RawAppClient::buf_size_for_level(5), 8 * 1024);
        assert_eq!(RawAppClient::buf_size_for_level(25), 64 * 1024);
        assert_eq!(RawAppClient::buf_size_for_level(100), 256 * 1024);
        println!("✅ Buffer sizing verifying");
    }

    #[test]
    fn test_source_display_names() {
        assert_eq!(
            RawAppSource::UnixSocket("/run/wasma/app.sock".into()).display_name(),
            "unix:/run/wasma/app.sock"
        );
        assert_eq!(RawAppSource::Stdin.display_name(), "stdin");
        assert_eq!(
            RawAppSource::TcpSocket {
                ip: "127.0.0.1".into(),
                port: 8080
            }
            .display_name(),
            "tcp:127.0.0.1:8080"
        );
        println!("✅ RawAppSource display_name running...");
    }

    #[test]
    fn test_uclient_engine_trait_object() {
        // Trait object olarak kullanılabildiğini doğrula
        let config = make_config();
        let client: Box<dyn UClientEngine> = Box::new(RawAppClient::new(config));
        assert!(!client.is_active());
        println!("✅ UClientEngine trait object running...");
    }
}