atomic_http 0.11.1

High level HTTP server library
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
use dashmap::DashMap;
use memmap2::Mmap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime};
use crate::dev_print;

use crate::SendableError;

#[derive(Debug)]
pub struct ZeroCopyFile {
    mmap: Mmap,
    _file: File,
    last_accessed: SystemTime,
    file_size: usize,
}

impl ZeroCopyFile {
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, SendableError> {
        let file = File::open(path.as_ref())?;
        let metadata = file.metadata()?;
        let file_size = metadata.len() as usize;
        
        // 빈 파일 처리
        if file_size == 0 {
            return Err("Cannot memory map empty file".into());
        }

        // SAFETY: 파일이 외부에서 수정되지 않는다고 가정
        let mmap = unsafe { Mmap::map(&file)? };

        Ok(Self {
            mmap,
            _file: file,
            last_accessed: SystemTime::now(),
            file_size,
        })
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.mmap
    }

    pub fn as_str(&self) -> Result<&str, SendableError> {
        Ok(std::str::from_utf8(&self.mmap)?)
    }

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

    pub fn is_empty(&self) -> bool {
        self.file_size == 0
    }

    pub fn update_access_time(&mut self) {
        self.last_accessed = SystemTime::now();
    }

    pub fn last_accessed(&self) -> SystemTime {
        self.last_accessed
    }

    /// JSON 파싱 지원 (제로카피)
    pub fn parse_json<T>(&self) -> Result<T, SendableError>
    where
        T: for<'de> serde::de::Deserialize<'de>,
    {
        let json_str = self.as_str()?;
        Ok(serde_json::from_str(json_str)?)
    }

    /// 특정 범위의 바이트 슬라이스 (제로카피)
    pub fn slice(&self, start: usize, end: usize) -> Result<&[u8], SendableError> {
        if end > self.mmap.len() || start > end {
            return Err(format!(
                "Index out of bounds: start={}, end={}, len={}",
                start, end, self.mmap.len()
            ).into());
        }
        Ok(&self.mmap[start..end])
    }

    /// 라인별 순회 이터레이터 (제로카피)
    pub fn lines(&self) -> LineIterator<'_> {
        LineIterator {
            data: &self.mmap,
            pos: 0,
        }
    }

    /// 특정 패턴 찾기
    pub fn find(&self, pattern: &[u8]) -> Option<usize> {
        self.mmap
            .windows(pattern.len())
            .position(|window| window == pattern)
    }
}

pub struct LineIterator<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Iterator for LineIterator<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.data.len() {
            return None;
        }

        let start = self.pos;

        // \n 또는 \r\n 찾기
        while self.pos < self.data.len() {
            if self.data[self.pos] == b'\n' {
                let end = self.pos;
                self.pos += 1;

                // \r\n 처리
                let line_end = if end > start && self.data[end - 1] == b'\r' {
                    end - 1
                } else {
                    end
                };

                return Some(&self.data[start..line_end]);
            }
            self.pos += 1;
        }

        // 마지막 줄 (개행 문자 없음)
        if start < self.data.len() {
            Some(&self.data[start..])
        } else {
            None
        }
    }
}

/// 캐시된 파일 데이터 (메모리에 복사본 저장)
#[derive(Debug)]
pub struct CachedFileData {
    data: Vec<u8>,
    last_accessed: SystemTime,
    modified_time: SystemTime,
    file_path: PathBuf,
    original_size: usize,
}

impl CachedFileData {
    pub fn new(data: Vec<u8>, file_path: PathBuf, modified_time: SystemTime) -> Self {
        let original_size = data.len();
        Self {
            data,
            last_accessed: SystemTime::now(),
            modified_time,
            file_path,
            original_size,
        }
    }

    pub fn get_info(&self) -> (PathBuf, usize) {
        (self.file_path.clone(), self.original_size)
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }

    pub fn as_str(&self) -> Result<&str, SendableError> {
        Ok(std::str::from_utf8(&self.data)?)
    }

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

    pub fn update_access_time(&mut self) {
        self.last_accessed = SystemTime::now();
    }

    pub fn last_accessed(&self) -> SystemTime {
        self.last_accessed
    }

    /// JSON 파싱 (캐시된 데이터에서)
    pub fn parse_json<T>(&self) -> Result<T, SendableError>
    where
        T: for<'de> serde::de::Deserialize<'de>,
    {
        let json_str = self.as_str()?;
        Ok(serde_json::from_str(json_str)?)
    }
}

/// 캐시 설정 구조체
#[derive(Debug, Clone)]
pub struct CacheConfig {
    pub max_cache_files: usize,
    pub max_cache_file_size: usize,
    pub cache_duration: Duration,
    pub total_cache_size_limit: usize,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_cache_files: 50,                    // 최대 50개 파일
            max_cache_file_size: 1024 * 1024,      // 1MB 이하 파일만 메모리 캐시
            total_cache_size_limit: 50 * 1024 * 1024, // 총 50MB 캐시 제한
            cache_duration: Duration::from_secs(300),  // 5분 캐시 유지
        }
    }
}

/// 하이브리드 파일 캐시 관리자
/// - 작은 파일: 메모리에 완전히 로드하여 캐시
/// - 큰 파일: 필요할 때마다 memmap2 사용 (캐시 안함)
pub struct ZeroCopyCache {
    // 작은 파일들의 메모리 캐시
    memory_cache: Arc<DashMap<PathBuf, CachedFileData>>,
    max_cache_files: usize,
    max_cache_file_size: usize,  // 이 크기 이하만 메모리 캐시
    cache_duration: Duration,
    total_cache_size_limit: usize,
}

// 전역 캐시 인스턴스
static GLOBAL_CACHE: OnceLock<ZeroCopyCache> = OnceLock::new();

impl ZeroCopyCache {
    pub fn new(
        max_cache_files: usize,
        max_cache_file_size: usize,
        total_cache_size_limit: usize,
        cache_duration: Duration
    ) -> Self {
        Self {
            memory_cache: Arc::new(DashMap::new()),
            max_cache_files,
            max_cache_file_size,
            total_cache_size_limit,
            cache_duration,
        }
    }

    /// 설정으로부터 캐시 생성
    pub fn from_config(config: CacheConfig) -> Self {
        Self::new(
            config.max_cache_files,
            config.max_cache_file_size,
            config.total_cache_size_limit,
            config.cache_duration,
        )
    }

    /// 기본 설정으로 캐시 생성
    pub fn default() -> Self {
        Self::from_config(CacheConfig::default())
    }

    /// 전역 캐시 초기화 (한 번만 호출)
    pub fn init_global(config: Option<CacheConfig>) -> Result<(), &'static str> {
        let cache_config = config.unwrap_or_default();
        let cache = Self::from_config(cache_config);

        GLOBAL_CACHE.set(cache)
            .map_err(|_| "Global cache already initialized")
    }

    /// 전역 캐시 인스턴스 반환
    pub fn global() -> &'static ZeroCopyCache {
        GLOBAL_CACHE.get_or_init(|| Self::default())
    }

    /// 파일을 로드 (캐시 사용 또는 직접 로드)
    pub fn load_file<P: AsRef<Path>>(&self, path: P) -> Result<FileLoadResult, SendableError> {

        let path_buf = path.as_ref().to_path_buf();
        
        // 파일 크기 확인
        let metadata = std::fs::metadata(&path_buf)?;
        let file_size = metadata.len() as usize;
        
        // 작은 파일: 메모리 캐시 사용
        if file_size <= self.max_cache_file_size {
            let modified_time = metadata.modified().unwrap_or_else(|_| SystemTime::now());
            return self.load_from_memory_cache(path_buf, file_size, modified_time);
        }
        
        // 큰 파일: 직접 memmap2 사용 (캐시 안함)
        dev_print!("Large file detected ({}MB), using direct memmap", file_size / (1024 * 1024));
        let zero_copy_file = ZeroCopyFile::new(&path_buf)?;
        Ok(FileLoadResult::DirectMemoryMap(zero_copy_file))
    }

    /// 메모리 캐시에서 파일 로드
    fn load_from_memory_cache(&self, path_buf: PathBuf, file_size: usize, modified_time: SystemTime) -> Result<FileLoadResult, SendableError> {
        // 캐시에서 먼저 찾기
        {
            if let Some(mut cached_data) = self.memory_cache.get_mut(&path_buf) {
                // 파일 수정 시간 비교: 변경되지 않았으면 캐시 사용
                if cached_data.modified_time == modified_time {
                    cached_data.update_access_time();
                    dev_print!("File loaded from memory cache: {:?} ({}KB)", path_buf, file_size / 1024);
                    return Ok(FileLoadResult::MemoryCache(cached_data.data.clone()));
                }
                // 파일이 변경됨 → guard drop 후 재로드
                dev_print!("File modified, reloading cache: {:?}", path_buf);
                drop(cached_data);
            }
        }

        // 캐시에 없거나 파일이 변경된 경우 → 파일을 읽어서 메모리에 저장
        dev_print!("Loading file to memory cache: {:?} ({}KB)", path_buf, file_size / 1024);
        let file_data = std::fs::read(&path_buf)?;
        let cached_data = CachedFileData::new(file_data.clone(), path_buf.clone(), modified_time);

        // 캐시에 추가 (또는 갱신)
        {
            // 캐시 용량 관리
            self.ensure_cache_capacity(self.memory_cache.clone(), file_size);

            self.memory_cache.insert(path_buf, cached_data);
        }

        Ok(FileLoadResult::MemoryCache(file_data))
    }

    /// 캐시 용량 확보
    fn ensure_cache_capacity(&self, cache:  Arc<DashMap<PathBuf, CachedFileData>>, new_file_size: usize) {
        // 파일 개수 제한 확인
        while cache.len() >= self.max_cache_files {
            self.evict_oldest_from_cache(&cache);
        }

        // 총 크기 제한 확인
        let current_total_size: usize = cache.iter().map(|f| f.original_size).sum();
        let mut remaining_size = current_total_size + new_file_size;

        while remaining_size > self.total_cache_size_limit && !cache.is_empty() {
            if let Some(evicted_size) = self.evict_oldest_from_cache(&cache) {
                remaining_size -= evicted_size;
            } else {
                break;
            }
        }
    }

    /// 가장 오래된 항목 제거
    fn evict_oldest_from_cache(&self, cache: &Arc<DashMap<PathBuf, CachedFileData>>) -> Option<usize> {
        if cache.is_empty() {
            return None;
        }

        let oldest_entry = cache
            .iter()
            .min_by_key(|file| file.last_accessed())
            .map(|file| (file.key().clone(), file.len()));

        if let Some((oldest_path, size)) = oldest_entry {
            cache.remove(&oldest_path);
            dev_print!("Evicted file from memory cache: {:?} ({}KB)", oldest_path, size / 1024);
            return Some(size);
        }

        None
    }

    /// 만료된 캐시 항목 정리
    pub fn cleanup_expired(&self) {
        let now = SystemTime::now();
        
        let expired_keys: Vec<PathBuf> = self.memory_cache
            .iter()
            .filter_map( |file| {
                if now.duration_since(file.last_accessed()).unwrap_or_default() > self.cache_duration {
                    Some(file.key().clone())
                } else {
                    None
                }
            })
            .collect();

        for key in expired_keys {
            if let Some((_path, removed)) = self.memory_cache.remove(&key) {
                dev_print!("Removed expired file from cache: {:?} ({}KB)", key, removed.original_size / 1024);
            }
        }
    }

    /// 캐시 통계
    pub fn stats(&self) -> CacheStats {
        let total_size: usize = self.memory_cache.iter().map(|f| f.original_size).sum();
        
        CacheStats {
            file_count: self.memory_cache.len(),
            total_size,
            max_cache_size: self.max_cache_files,
            max_file_size: self.max_cache_file_size,
            total_cache_size_limit: self.total_cache_size_limit,
        }
    }

    /// 캐시 강제 정리
    pub fn clear_cache(&self) {
        let count = self.memory_cache.len();
        let total_size: usize = self.memory_cache.iter().map(|f| f.original_size).sum();
        self.memory_cache.clear();
        dev_print!("Cleared memory cache: {} files, {}MB", count, total_size / (1024 * 1024));
    }
}

/// 파일 로드 결과
pub enum FileLoadResult {
    /// 메모리 캐시에서 로드된 데이터 (소유권 있는 복사본)
    MemoryCache(Vec<u8>),
    /// 직접 메모리 매핑된 파일 (큰 파일용)
    DirectMemoryMap(ZeroCopyFile),
}

impl FileLoadResult {
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            FileLoadResult::MemoryCache(data) => data,
            FileLoadResult::DirectMemoryMap(mmap_file) => mmap_file.as_bytes(),
        }
    }

    pub fn as_str(&self) -> Result<&str, SendableError> {
        match self {
            FileLoadResult::MemoryCache(data) => Ok(std::str::from_utf8(data)?),
            FileLoadResult::DirectMemoryMap(mmap_file) => mmap_file.as_str(),
        }
    }

    pub fn len(&self) -> usize {
        match self {
            FileLoadResult::MemoryCache(data) => data.len(),
            FileLoadResult::DirectMemoryMap(mmap_file) => mmap_file.len(),
        }
    }

    pub fn parse_json<T>(&self) -> Result<T, SendableError>
    where
        T: for<'de> serde::de::Deserialize<'de>,
    {
        match self {
            FileLoadResult::MemoryCache(data) => {
                let json_str = std::str::from_utf8(data)?;
                Ok(serde_json::from_str(json_str)?)
            }
            FileLoadResult::DirectMemoryMap(mmap_file) => mmap_file.parse_json(),
        }
    }

    pub fn is_memory_cached(&self) -> bool {
        matches!(self, FileLoadResult::MemoryCache(_))
    }

    pub fn is_memory_mapped(&self) -> bool {
        matches!(self, FileLoadResult::DirectMemoryMap(_))
    }
}

#[derive(Debug, Clone)]
pub struct CacheStats {
    pub file_count: usize,
    pub total_size: usize,
    pub max_cache_size: usize,
    pub max_file_size: usize,
    pub total_cache_size_limit: usize,
}

impl std::fmt::Display for CacheStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, 
            "Memory Cache Stats: {} files, {:.2}/{:.2} MB used, max {} files, max {:.2} MB per file",
            self.file_count,
            self.total_size as f64 / 1_048_576.0,
            self.total_cache_size_limit as f64 / 1_048_576.0,
            self.max_cache_size,
            self.max_file_size as f64 / 1_048_576.0
        )
    }
}

/// JSON 파일을 제로카피로 파싱하는 헬퍼 함수
pub fn parse_json_file<T, P>(path: P) -> Result<T, SendableError>
where
    T: for<'de> serde::de::Deserialize<'de>,
    P: AsRef<Path>,
{
    // 파일 크기에 따라 적절한 방법 선택
    let metadata = std::fs::metadata(&path)?;
    let file_size = metadata.len() as usize;
    
    if file_size <= 1024 * 1024 { // 1MB 이하는 일반 읽기
        dev_print!("Small JSON file, using standard read: {}KB", file_size / 1024);
        let data = std::fs::read(&path)?;
        let json_str = std::str::from_utf8(&data)?;
        Ok(serde_json::from_str(json_str)?)
    } else { // 큰 파일은 memmap2 사용
        dev_print!("Large JSON file, using zero-copy mmap: {}MB", file_size / (1024 * 1024));
        let zero_copy_file = ZeroCopyFile::new(path)?;
        zero_copy_file.parse_json()
    }
}

/// 캐시를 사용한 JSON 파일 파싱
pub fn parse_json_file_cached<T, P>(path: P, cache: &mut ZeroCopyCache) -> Result<T, SendableError>
where
    T: for<'de> serde::de::Deserialize<'de>,
    P: AsRef<Path>,
{
    let file_result = cache.load_file(path)?;
    file_result.parse_json()
}

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

    fn create_test_cache() -> ZeroCopyCache {
        ZeroCopyCache::from_config(CacheConfig {
            max_cache_files: 10,
            max_cache_file_size: 1024 * 1024,
            total_cache_size_limit: 10 * 1024 * 1024,
            cache_duration: Duration::from_secs(300),
        })
    }

    #[test]
    fn test_cache_returns_fresh_data() {
        let cache = create_test_cache();
        let dir = std::env::temp_dir().join("atomic_http_test_fresh");
        std::fs::create_dir_all(&dir).unwrap();
        let file_path = dir.join("test_fresh.txt");

        std::fs::write(&file_path, b"hello").unwrap();

        let result1 = cache.load_file(&file_path).unwrap();
        assert_eq!(result1.as_bytes(), b"hello");

        // 동일 파일 재요청 → 캐시 히트 (동일 내용)
        let result2 = cache.load_file(&file_path).unwrap();
        assert_eq!(result2.as_bytes(), b"hello");
        assert!(result2.is_memory_cached());

        std::fs::remove_file(&file_path).ok();
        std::fs::remove_dir(&dir).ok();
    }

    #[test]
    fn test_cache_invalidates_on_file_modification() {
        let cache = create_test_cache();
        let dir = std::env::temp_dir().join("atomic_http_test_mtime");
        std::fs::create_dir_all(&dir).unwrap();
        let file_path = dir.join("test_mtime.txt");

        // 초기 파일 작성 및 캐시
        std::fs::write(&file_path, b"version1").unwrap();
        let result1 = cache.load_file(&file_path).unwrap();
        assert_eq!(result1.as_bytes(), b"version1");

        // mtime 변경을 보장하기 위해 1초 대기 후 파일 수정
        std::thread::sleep(Duration::from_secs(1));

        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&file_path)
            .unwrap();
        file.write_all(b"version2").unwrap();
        file.flush().unwrap();
        drop(file);

        // 수정 후 요청 → 변경된 내용 반환
        let result2 = cache.load_file(&file_path).unwrap();
        assert_eq!(result2.as_bytes(), b"version2");

        std::fs::remove_file(&file_path).ok();
        std::fs::remove_dir(&dir).ok();
    }

    #[test]
    fn test_cache_stats_after_reload() {
        let cache = create_test_cache();
        let dir = std::env::temp_dir().join("atomic_http_test_stats");
        std::fs::create_dir_all(&dir).unwrap();
        let file_path = dir.join("test_stats.txt");

        std::fs::write(&file_path, b"data").unwrap();
        cache.load_file(&file_path).unwrap();
        assert_eq!(cache.stats().file_count, 1);

        // 파일 수정 후 재로드 → 캐시 엔트리 갱신 (개수 유지)
        std::thread::sleep(Duration::from_secs(1));
        std::fs::write(&file_path, b"updated_data").unwrap();
        cache.load_file(&file_path).unwrap();
        assert_eq!(cache.stats().file_count, 1);

        std::fs::remove_file(&file_path).ok();
        std::fs::remove_dir(&dir).ok();
    }
}