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
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
use async_trait::async_trait;
use http::Response;
use tokio::io::AsyncWriteExt;

#[cfg(feature = "arena")]
use crate::ArenaWriter;
use crate::{SendableError, Writer};
#[cfg(feature = "response_file")]
use std::path::Path;

use crate::helpers::traits::zero_copy::ZeroCopyCache;

impl Writer {
    pub async fn write_bytes(&mut self) -> Result<(), SendableError> {
        self.stream.send_bytes(self.bytes.as_slice()).await?;
        Ok(())
    }

    #[cfg(feature = "response_file")]
    pub fn response_file<P>(&mut self, path: P) -> Result<(), SendableError>
    where
        P: AsRef<Path>,
    {
        let root_path = &self.options.root_path;
        let file_path = root_path.join(path);

        // 제로카피 기능이 활성화된 경우 memmap2 사용 시도
        // 파일 크기 확인
        if let Ok(metadata) = std::fs::metadata(&file_path) {
            let file_size = metadata.len() as usize;

            // 작은 파일들은 제로카피 캐시 사용
            if file_size <= 10 * 1024 * 1024 {
                // 10MB 이하
                crate::dev_print!(
                    "Using zero-copy for file: {:?} ({}KB)",
                    file_path,
                    file_size / 1024
                );
                self.body = format!("__ZERO_COPY_FILE__:{}", file_path.to_str().unwrap());
                self.use_file = true;
                return Ok(());
            }
        }

        // 기존 방식 (대용량 파일 또는 zero_copy 기능 비활성화)
        self.body = file_path.to_str().unwrap().to_string();
        self.use_file = true;
        Ok(())
    }
}

#[async_trait]
pub trait ResponseUtil {
    async fn responser(&mut self) -> Result<(), SendableError>;

    async fn send_zero_copy_file(&mut self, mut send_string: String) -> Result<(), SendableError>;
}

#[async_trait]
impl ResponseUtil for Response<Writer> {
    async fn responser(&mut self) -> Result<(), SendableError> {
        let mut send_string = String::new();
        if cfg!(feature = "response_file") && self.body().use_file {
            use http::StatusCode;
            *self.status_mut() = StatusCode::from_u16(200)?;
        }
        let status_line = format!("{:?} {}\r\n", self.version(), self.status());
        send_string.push_str(&status_line);

        #[cfg(feature = "connection_pool")]
        {
            use http::header::CONNECTION;
            let options = &self.body().options;
            let connection_config = &options.connection_option;

            // Keep-alive 설정이 활성화된 경우에만 헤더 추가
            if connection_config.enable_keep_alive && !self.headers().contains_key(CONNECTION) {
                send_string.push_str("Connection: keep-alive\r\n");
                send_string.push_str(&format!(
                    "Keep-Alive: timeout={}, max={}\r\n",
                    connection_config.max_idle_time.as_secs(),
                    connection_config.max_connections_per_host
                ));
            } else if !connection_config.enable_keep_alive && !self.headers().contains_key(CONNECTION) {
                send_string.push_str("Connection: close\r\n");
            }
        }

        if cfg!(feature = "response_file") && self.body().use_file {
            use tokio::{
                fs,
                io::{self, AsyncReadExt},
            };

            #[cfg(feature = "response_file")]
            {
                use http::header::CONTENT_TYPE;
                self.headers_mut().remove(CONTENT_TYPE);

                // 제로카피 파일 처리 확인
                if self.body().body.starts_with("__ZERO_COPY_FILE__:") {
                    return self.send_zero_copy_file(send_string).await;
                }

                // 기존 파일 처리 방식
                match self.body().body.split('.').last().unwrap() {
                    "zip" => {
                        send_string.push_str("Content-Type: application/zip\r\n");
                        send_string.push_str(&format!(
                            "content-disposition: attachment; filename={}\r\n",
                            self.body().body
                        ));
                    }
                    _ => {
                        send_string.push_str(&format!(
                            "Content-Type: {}\r\n",
                            get_content_type(&self.body().body)
                        ));
                    }
                }
            }

            for (key, value) in self.headers().iter() {
                send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
            }

            let file = fs::File::open(&self.body().body).await?;
            let content_length = file.metadata().await?.len();
            send_string.push_str(format!("content-length: {}\r\n", content_length).as_str());

            send_string.push_str("\r\n");

            // 여기서 mutable borrow 문제 해결: body_mut()을 한 번만 호출
            let body = self.body_mut();
            body.stream.send_bytes(send_string.as_bytes()).await?;

            let mut reader = io::BufReader::new(file);
            let mut buffer = match content_length < 1048576 * 5 {
                true => vec![0; content_length as usize],
                false => vec![0; 1048576 * 5],
            };
            while let Ok(len) = reader.read(&mut buffer).await {
                if len == 0 {
                    break;
                }
                body.stream.send_bytes(&buffer[0..len]).await?;
            }
        } else if !self.body().bytes.is_empty() {
            for (key, value) in self.headers().iter() {
                send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
            }
            send_string.push_str("\r\n");
            let mut send_bytes = send_string.as_bytes().to_vec();
            send_bytes.extend(self.body().bytes.clone());

            // mutable borrow 문제 해결
            let body = self.body_mut();
            body.bytes = send_bytes;
            body.write_bytes().await?;
        } else {
            let (body_str, content_string) = get_body(self.body().body.as_str()).await;
            send_string.push_str(&content_string);

            for (key, value) in self.headers().iter() {
                send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
            }
            crate::dev_print!("headers: {}", &send_string);
            send_string.push_str("\r\n");

            send_string.push_str(&body_str);

            // mutable borrow 문제 해결
            self.body_mut()
                .stream
                .send_bytes(send_string.as_bytes())
                .await?;
        }

        // flush는 별도로 처리
        self.body_mut().stream.flush().await?;
        Ok(())
    }

    async fn send_zero_copy_file(&mut self, mut send_string: String) -> Result<(), SendableError> {
        use http::header::CONTENT_TYPE;
        let file_path = &self.body().body[19..]; // "__ZERO_COPY_FILE__:" 이후의 경로

        // 캐시를 사용한 파일 로드
        let cache = ZeroCopyCache::global();
        let file_result = cache.load_file(file_path)?;
        let file_data = file_result.as_bytes();
        let content_length = file_data.len();

        let load_method = if file_result.is_memory_cached() {
            "memory_cache"
        } else {
            "mmap"
        };
        crate::dev_print!(
            "Zero-copy file serving: {} ({} bytes, method: {})",
            file_path,
            content_length,
            load_method
        );

        // Content-Type 설정
        match file_path.split('.').last().unwrap() {
            "zip" => {
                send_string.push_str("Content-Type: application/zip\r\n");
                send_string.push_str(&format!(
                    "content-disposition: attachment; filename={}\r\n",
                    file_path.split('/').last().unwrap_or(file_path)
                ));
            }
            "json" => {
                send_string.push_str("Content-Type: application/json\r\n");
            }
            _ => {
                send_string.push_str(&format!(
                    "Content-Type: {}\r\n",
                    get_content_type(file_path)
                ));
            }
        }

        self.headers_mut().remove(CONTENT_TYPE);

        // 추가 헤더들
        for (key, value) in self.headers().iter() {
            send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
        }

        // Content-Length와 헤더 끝
        send_string.push_str(&format!("content-length: {}\r\n", content_length));
        send_string.push_str("\r\n");

        let body = self.body_mut();

        #[cfg(feature = "vectored_io")]
        {
            // Vectored I/O로 헤더와 파일 데이터를 한 번에 전송
            use std::io::IoSlice;
            let header_slice = IoSlice::new(send_string.as_bytes());
            let file_slice = IoSlice::new(file_data);
            let bufs = [header_slice, file_slice];

            body.stream.send_vectored(&bufs).await?;
            crate::dev_print!(
                "Vectored I/O: sent header+file in single syscall ({} + {} bytes)",
                send_string.len(),
                content_length
            );
        }

        #[cfg(not(feature = "vectored_io"))]
        {
            // 기존 방식: 별도 전송
            body.stream.send_bytes(send_string.as_bytes()).await?;
            body.stream.send_bytes(file_data).await?;
        }

        crate::dev_print!(
            "Zero-copy file sent successfully: {} bytes ({})",
            content_length,
            load_method
        );
        Ok(())
    }
}

#[cfg(feature = "arena")]
#[async_trait]
pub trait ResponseUtilArena {
    async fn responser_arena(&mut self) -> Result<(), SendableError>;

    #[cfg(feature = "arena")]
    async fn send_arena_zero_copy_file(
        &mut self,
        file_path: &str,
        mut send_string: String,
    ) -> Result<(), SendableError>;
}

#[cfg(feature = "arena")]
#[async_trait]
impl ResponseUtilArena for Response<ArenaWriter> {
    async fn responser_arena(&mut self) -> Result<(), SendableError> {
        let mut send_string = String::new();

        if cfg!(feature = "response_file") && self.body().use_file {
            use http::StatusCode;
            *self.status_mut() = StatusCode::from_u16(200)?;
        }

        let status_line = format!("{:?} {}\r\n", self.version(), self.status());
        send_string.push_str(&status_line);

        #[cfg(feature = "connection_pool")]
        {
            use http::header::CONNECTION;
            let options = &self.body().options;
            let connection_config = &options.connection_option;

            // Keep-alive 설정이 활성화된 경우에만 헤더 추가
            if connection_config.enable_keep_alive && !self.headers().contains_key(CONNECTION) {
                send_string.push_str("Connection: keep-alive\r\n");
                send_string.push_str(&format!(
                    "Keep-Alive: timeout={}, max={}\r\n",
                    connection_config.max_idle_time.as_secs(),
                    connection_config.max_connections_per_host
                ));
            } else if !connection_config.enable_keep_alive && !self.headers().contains_key(CONNECTION) {
                send_string.push_str("Connection: close\r\n");
            }
        }

        if cfg!(feature = "response_file") && self.body().use_file {
            #[cfg(feature = "response_file")]
            {
                use http::header::CONTENT_TYPE;
                use tokio::{
                    fs,
                    io::{self, AsyncReadExt},
                };
                self.headers_mut().remove(CONTENT_TYPE);

                if self.body().response_data_len > 0 {
                    let file_path = unsafe {
                        let data = std::slice::from_raw_parts(
                            self.body().response_data_ptr,
                            self.body().response_data_len,
                        );
                        std::str::from_utf8(data)?
                    };

                    // Arena + 제로카피 조합 처리
                    if file_path.starts_with("__ZERO_COPY_FILE__:") {
                        let actual_path = &file_path[19..];
                        return self
                            .send_arena_zero_copy_file(actual_path, send_string)
                            .await;
                    }

                    match file_path.split('.').last().unwrap() {
                        "zip" => {
                            send_string.push_str("Content-Type: application/zip\r\n");
                            send_string.push_str(&format!(
                                "content-disposition: attachment; filename={}\r\n",
                                file_path
                            ));
                        }
                        _ => {
                            send_string.push_str(&format!(
                                "Content-Type: {}\r\n",
                                get_content_type(file_path)
                            ));
                        }
                    }

                    for (key, value) in self.headers().iter() {
                        send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
                    }

                    let file = fs::File::open(file_path).await?;
                    let content_length = file.metadata().await?.len();
                    send_string
                        .push_str(format!("content-length: {}\r\n", content_length).as_str());

                    send_string.push_str("\r\n");

                    // mutable borrow 문제 해결
                    let body = self.body_mut();
                    body.stream.send_bytes(send_string.as_bytes()).await?;

                    let mut reader = io::BufReader::new(file);
                    let mut buffer = match content_length < 1048576 * 5 {
                        true => vec![0; content_length as usize],
                        false => vec![0; 1048576 * 5],
                    };
                    while let Ok(len) = reader.read(&mut buffer).await {
                        if len == 0 {
                            break;
                        }
                        body.stream.send_bytes(&buffer[0..len]).await?;
                    }
                }
            }
        } else {
            if self.body().response_data_len > 0 {
                // Arena 메모리로 할당된 응답 데이터 사용
                for (key, value) in self.headers().iter() {
                    send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
                }

                let content_length =
                    format!("content-length: {}\r\n", self.body().response_data_len);
                send_string.push_str(&content_length);
                send_string.push_str("\r\n");

                // mutable borrow 문제 해결: body_mut()을 한 번만 호출
                let body = self.body_mut();

                // Arena 데이터 직접 전송 (제로카피)
                let response_data = unsafe {
                    std::slice::from_raw_parts(body.response_data_ptr, body.response_data_len)
                };

                #[cfg(feature = "vectored_io")]
                {
                    // Vectored I/O로 헤더와 응답 데이터를 한 번에 전송
                    use std::io::IoSlice;
                    let header_slice = IoSlice::new(send_string.as_bytes());
                    let data_slice = IoSlice::new(response_data);
                    let bufs = [header_slice, data_slice];

                    body.stream.send_vectored(&bufs).await?;
                    crate::dev_print!(
                        "Arena Vectored I/O: sent header+data in single syscall ({} + {} bytes)",
                        send_string.len(),
                        response_data.len()
                    );
                }

                #[cfg(not(feature = "vectored_io"))]
                {
                    // 기존 방식: 별도 전송
                    body.stream.send_bytes(send_string.as_bytes()).await?;
                    body.stream.send_bytes(response_data).await?;
                }
            } else {
                // 빈 응답
                for (key, value) in self.headers().iter() {
                    send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
                }
                send_string.push_str("content-length: 0\r\n");
                send_string.push_str("\r\n");

                self.body_mut()
                    .stream
                    .send_bytes(send_string.as_bytes())
                    .await?;
            }
        }

        // flush는 별도로 처리
        self.body_mut().stream.flush().await?;
        Ok(())
    }

    #[cfg(feature = "arena")]
    async fn send_arena_zero_copy_file(
        &mut self,
        file_path: &str,
        mut send_string: String,
    ) -> Result<(), SendableError> {
        use http::header::CONTENT_TYPE;

        // 캐시를 사용한 파일 로드
        let file_result = ZeroCopyCache::global().load_file(file_path)?;
        let file_data = file_result.as_bytes();
        let content_length = file_data.len();

        let load_method = if file_result.is_memory_cached() {
            "arena+memory_cache"
        } else {
            "arena+mmap"
        };
        crate::dev_print!(
            "Arena + Zero-copy file serving: {} ({} bytes, method: {})",
            file_path,
            content_length,
            load_method
        );

        self.headers_mut().remove(CONTENT_TYPE);

        // Content-Type 설정
        match file_path.split('.').last().unwrap() {
            "zip" => {
                send_string.push_str("Content-Type: application/zip\r\n");
                send_string.push_str(&format!(
                    "content-disposition: attachment; filename={}\r\n",
                    file_path.split('/').last().unwrap_or(file_path)
                ));
            }
            "json" => {
                send_string.push_str("Content-Type: application/json\r\n");
            }
            _ => {
                send_string.push_str(&format!(
                    "Content-Type: {}\r\n",
                    get_content_type(file_path)
                ));
            }
        }

        // 추가 헤더들
        for (key, value) in self.headers().iter() {
            send_string.push_str(&format!("{}: {}\r\n", key.as_str(), value.to_str()?));
        }

        // Content-Length와 헤더 끝
        send_string.push_str(&format!("content-length: {}\r\n", content_length));
        send_string.push_str("\r\n");

        // mutable borrow 문제 해결: body_mut()을 한 번만 호출
        let body = self.body_mut();

        #[cfg(feature = "vectored_io")]
        {
            // Vectored I/O로 헤더와 파일 데이터를 한 번에 전송
            use std::io::IoSlice;
            let header_slice = IoSlice::new(send_string.as_bytes());
            let file_slice = IoSlice::new(file_data);
            let bufs = [header_slice, file_slice];

            body.stream.send_vectored(&bufs).await?;
            crate::dev_print!(
                "Arena Vectored I/O: sent header+file in single syscall ({} + {} bytes)",
                send_string.len(),
                content_length
            );
        }

        #[cfg(not(feature = "vectored_io"))]
        {
            // 기존 방식: 별도 전송
            body.stream.send_bytes(send_string.as_bytes()).await?;
            body.stream.send_bytes(file_data).await?;
        }

        crate::dev_print!(
            "Arena + Zero-copy file sent: {} bytes ({})",
            content_length,
            load_method
        );
        Ok(())
    }
}

#[async_trait]
pub trait SendBytes {
    async fn send_bytes(&mut self, bytes: &[u8]) -> Result<(), SendableError>;

    #[cfg(feature = "vectored_io")]
    async fn send_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> Result<(), SendableError>;
}

#[async_trait]
impl SendBytes for tokio::net::TcpStream {
    async fn send_bytes(&mut self, bytes: &[u8]) -> Result<(), SendableError> {
        use tokio::io::AsyncWriteExt;

        #[cfg(feature = "vectored_io")]
        {
            // vectored_io 기능이 켜져 있을 때도 부분 쓰기 처리
            let mut written = 0;
            while written < bytes.len() {
                let n = self.write_vectored(&[std::io::IoSlice::new(&bytes[written..])]).await?;
                if n == 0 {
                    return Err("Connection closed during write".into());
                }
                written += n;
            }
        }

        #[cfg(not(feature = "vectored_io"))]
        {
            // write_all은 이미 부분 쓰기를 처리함
            self.write_all(bytes).await?;
        }
        Ok(())
    }

    #[cfg(feature = "vectored_io")]
    async fn send_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> Result<(), SendableError> {
        use tokio::io::AsyncWriteExt;

        // 전체 데이터 크기 계산
        let total_size: usize = bufs.iter().map(|b| b.len()).sum();
        let mut written = 0;

        // 부분 쓰기를 처리하기 위한 루프
        while written < total_size {
            // 현재 쓸 버퍼들의 오프셋 계산
            let mut current_written = written;
            let mut buf_idx = 0;

            // written 바이트만큼 건너뛰기
            while buf_idx < bufs.len() && current_written >= bufs[buf_idx].len() {
                current_written -= bufs[buf_idx].len();
                buf_idx += 1;
            }

            if buf_idx >= bufs.len() {
                break; // 모두 전송됨
            }

            // 남은 버퍼들을 IoSlice로 재구성
            let mut remaining_bufs: Vec<std::io::IoSlice> = Vec::with_capacity(bufs.len() - buf_idx);

            // 첫 번째 버퍼는 오프셋을 적용
            if current_written > 0 {
                remaining_bufs.push(std::io::IoSlice::new(&bufs[buf_idx][current_written..]));
                buf_idx += 1;
            }

            // 나머지 버퍼들 추가
            for buf in &bufs[buf_idx..] {
                remaining_bufs.push(std::io::IoSlice::new(buf));
            }

            // 쓰기 수행
            let n = self.write_vectored(&remaining_bufs).await?;
            if n == 0 {
                return Err("Connection closed during vectored write".into());
            }
            written += n;
        }

        Ok(())
    }
}

pub fn get_content_type(file_name: &str) -> String {
    let guess = mime_guess::from_path(file_name);

    if let Some(mime) = guess.first() {
        mime.to_string()
    } else {
        use std::str::FromStr;

        String::from_str("text/plain").unwrap_or_default()
    }
}

async fn get_body(body: &str) -> (String, String) {
    let length = body.len();

    let content_length = format!("content-length: {}\r\n", length);
    crate::dev_print!("content-length: {}\n", &content_length);
    (body.into(), content_length)
}