kftray-http-logs 0.33.0

HTTP logging library for KFtray
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
use std::sync::Arc;

use tracing::debug;
use tracing::trace;
pub const DEFAULT_MIN_VALID_HEADERS_SIZE: usize = 16;
// Match the transport detector's bounded handshake buffer; frame bytes are
// excluded.
const MAX_WEBSOCKET_HEADERS_SIZE: usize = 65_536;
// One less than the longest end marker, `\r\n0\r\n\r\n`, so a marker split
// across reads is still found.
const CHUNKED_END_MARKER_OVERLAP: usize = 6;

#[derive(Debug, Clone)]
pub struct ResponseAnalyzerConfig {
    pub min_headers_size: usize,
}

impl Default for ResponseAnalyzerConfig {
    fn default() -> Self {
        Self {
            min_headers_size: DEFAULT_MIN_VALID_HEADERS_SIZE,
        }
    }
}

#[derive(Debug, Clone)]
pub struct HttpResponseAnalyzer {
    config: Arc<ResponseAnalyzerConfig>,
}

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

impl HttpResponseAnalyzer {
    pub fn new(config: ResponseAnalyzerConfig) -> Self {
        Self {
            config: Arc::new(config),
        }
    }

    pub fn config(&self) -> &ResponseAnalyzerConfig {
        &self.config
    }

    pub fn detect_chunked_encoding(response_data: &[u8]) -> bool {
        if let Some(headers_end) = find_headers_end(response_data) {
            let header_section = &response_data[..headers_end];
            return std::str::from_utf8(header_section)
                .map(|h| h.to_lowercase().contains("transfer-encoding: chunked"))
                .unwrap_or(false);
        }
        false
    }

    pub fn check_content_length_match(response_data: &[u8]) -> bool {
        if let Some(headers_end) = find_headers_end(response_data) {
            let headers = &response_data[..headers_end];
            if let Some(content_length) = parse_content_length(headers) {
                let body_size = response_data.len() - (headers_end + 4);
                return body_size >= content_length;
            }
        }
        false
    }

    pub fn has_bodyless_status(response_data: &[u8]) -> bool {
        find_headers_end(response_data)
            .and_then(|_| response_data.windows(2).position(|w| w == b"\r\n"))
            .and_then(|line_end| std::str::from_utf8(&response_data[..line_end]).ok())
            .and_then(Self::extract_status_code)
            .is_some_and(|status| status == 204 || status == 304)
    }

    pub fn has_chunked_end_marker(chunk_data: &[u8]) -> bool {
        Self::has_chunked_end_marker_after(chunk_data, 0)
    }

    fn has_chunked_end_marker_after(response_data: &[u8], scanned_len: usize) -> bool {
        let body_start = if response_data.starts_with(b"HTTP/") {
            match find_headers_end(response_data) {
                Some(headers_end) => headers_end + 4,
                None => return false,
            }
        } else {
            0
        };
        let scan_start = body_start
            .max(scanned_len.saturating_sub(CHUNKED_END_MARKER_OVERLAP))
            .min(response_data.len());
        let chunk_data = &response_data[scan_start..];

        let standard_markers = chunk_data.windows(5).any(|w| w == b"0\r\n\r\n");

        let leading_crlf_markers = chunk_data.windows(7).any(|w| w == b"\r\n0\r\n\r\n");

        let with_trailers = if let Some(pos) = chunk_data.windows(3).position(|w| w == b"0\r\n") {
            let end_pos = pos + 3;
            if end_pos < chunk_data.len() {
                chunk_data[end_pos..].windows(4).any(|w| w == b"\r\n\r\n")
            } else {
                false
            }
        } else {
            false
        };

        standard_markers || leading_crlf_markers || with_trailers
    }

    pub fn is_websocket_upgrade(response_data: &[u8]) -> bool {
        let bounded_data = &response_data[..response_data.len().min(MAX_WEBSOCKET_HEADERS_SIZE)];
        let Some(headers_end) = find_headers_end(bounded_data) else {
            return false;
        };
        let header_bytes = &bounded_data[..headers_end + 4];
        let mut headers = [httparse::EMPTY_HEADER; 64];
        match Self::parse_websocket_upgrade(header_bytes, &mut headers) {
            Err(httparse::Error::TooManyHeaders) => {
                // Count only the complete bounded header block, never coalesced
                // frames.
                let header_count = header_bytes
                    .windows(2)
                    .filter(|pair| *pair == b"\r\n")
                    .count()
                    - 2;
                let mut headers = vec![httparse::EMPTY_HEADER; header_count];
                Self::parse_websocket_upgrade(header_bytes, &mut headers).unwrap_or(false)
            }
            result => result.unwrap_or(false),
        }
    }

    fn parse_websocket_upgrade<'a>(
        response_data: &'a [u8], headers: &mut [httparse::Header<'a>],
    ) -> Result<bool, httparse::Error> {
        let mut response = httparse::Response::new(headers);
        if !response.parse(response_data)?.is_complete() || response.code != Some(101) {
            return Ok(false);
        }
        let has_token = |name: &str, token: &str| {
            response.headers.iter().any(|header| {
                header.name.eq_ignore_ascii_case(name)
                    && std::str::from_utf8(header.value).is_ok_and(|value| {
                        value
                            .split(',')
                            .any(|part| part.trim().eq_ignore_ascii_case(token))
                    })
            })
        };
        Ok(has_token("upgrade", "websocket")
            && has_token("connection", "upgrade")
            && response.headers.iter().any(|header| {
                header.name.eq_ignore_ascii_case("sec-websocket-accept") && !header.value.is_empty()
            }))
    }

    pub fn appears_complete(
        &self, response_data: &[u8], is_chunked: bool, found_end_marker: bool,
    ) -> bool {
        if Self::is_websocket_upgrade(response_data) {
            trace!("Detected WebSocket upgrade response - considering complete for logging");
            return true;
        }

        if is_chunked {
            return found_end_marker;
        }

        Self::check_content_length_match(response_data)
    }

    pub fn is_ready_for_logging(
        response_data: &[u8], is_chunked: bool, found_end_marker: bool,
    ) -> bool {
        HttpResponseAnalyzer::default().is_ready_for_logging_with_config(
            response_data,
            is_chunked,
            found_end_marker,
        )
    }

    pub fn is_ready_for_logging_with_config(
        &self, response_data: &[u8], is_chunked: bool, found_end_marker: bool,
    ) -> bool {
        if let Some(headers_end) = find_headers_end(response_data) {
            if Self::is_websocket_upgrade(response_data) {
                trace!(
                    "WebSocket upgrade response fully confirmed with all necessary headers - complete"
                );
                return true;
            }

            if is_chunked {
                if found_end_marker {
                    trace!("Chunked response with end marker detected - complete");
                    return true;
                }

                if response_data.len() > 100_000_000 {
                    debug!(
                        "Very large chunked response ({}B) - forcing log despite missing end marker",
                        response_data.len()
                    );
                    return true;
                }

                return false;
            }

            let headers = &response_data[..headers_end];
            if let Some(content_length) = parse_content_length(headers) {
                let body_size = response_data.len() - (headers_end + 4);

                if body_size == content_length {
                    trace!("Response with exact Content-Length match - complete");
                    return true;
                }

                if body_size >= content_length {
                    trace!("Response with sufficient Content-Length - complete");
                    return true;
                }

                return false;
            }

            let headers_str = std::str::from_utf8(headers).unwrap_or("");
            if headers_str.to_lowercase().contains("connection: close") {
                trace!("Response with Connection: close header - complete");
                return true;
            }

            if headers_str.starts_with("HTTP/1.0")
                && !headers_str.to_lowercase().contains("content-length:")
            {
                trace!("HTTP/1.0 response without Content-Length - complete");
                return true;
            }

            if let Some(status_code) = Self::extract_status_code(headers_str)
                && ((100..200).contains(&status_code) || status_code == 204 || status_code == 304)
            {
                trace!(
                    "Response with no-body status code {} - complete",
                    status_code
                );
                return true;
            }
        }

        false
    }

    fn extract_status_code(header_str: &str) -> Option<u16> {
        let lines: Vec<&str> = header_str.split("\r\n").collect();
        if lines.is_empty() {
            return None;
        }

        let status_line = lines[0];
        let parts: Vec<&str> = status_line.split_whitespace().collect();
        if parts.len() < 2 {
            return None;
        }

        parts[1].parse::<u16>().ok()
    }

    pub fn process_chunk(
        response_data: &[u8], scanned_len: usize, is_chunked: bool, found_end_marker: &mut bool,
        total_chunks_received: &mut usize,
    ) {
        if is_chunked && !*found_end_marker {
            *total_chunks_received += 1;

            if Self::has_chunked_end_marker_after(response_data, scanned_len) {
                *found_end_marker = true;
                trace!(
                    "Found end marker for chunked response after {} chunks, {}B total",
                    total_chunks_received,
                    response_data.len()
                );
            }
        }
    }

    pub fn is_multipart_response(headers: &[u8]) -> bool {
        if let Ok(headers_str) = std::str::from_utf8(headers) {
            return headers_str
                .to_lowercase()
                .contains("content-type: multipart/");
        }
        false
    }

    pub fn is_streaming_response(headers: &[u8]) -> bool {
        if let Ok(headers_str) = std::str::from_utf8(headers) {
            let h_lower = headers_str.to_lowercase();
            return h_lower.contains("content-type: text/event-stream")
                || h_lower.contains("content-type: application/x-ndjson")
                || (h_lower.contains("content-type: application/json")
                    && h_lower.contains("transfer-encoding: chunked"));
        }
        false
    }
}

fn find_headers_end(data: &[u8]) -> Option<usize> {
    data.windows(4).position(|w| w == b"\r\n\r\n")
}

fn parse_content_length(headers: &[u8]) -> Option<usize> {
    std::str::from_utf8(headers)
        .ok()
        .and_then(|h| h.to_lowercase().find("content-length:"))
        .and_then(|pos| {
            let remaining = &headers[pos + 15..];
            let end_pos = remaining
                .iter()
                .position(|&b| b == b'\r')
                .unwrap_or(remaining.len());
            std::str::from_utf8(&remaining[..end_pos])
                .ok()
                .and_then(|s| s.trim().parse::<usize>().ok())
        })
}

pub use DEFAULT_MIN_VALID_HEADERS_SIZE as MIN_VALID_HEADERS_SIZE;

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

    #[test]
    fn test_detect_chunked_encoding() {
        let chunked_response = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\ndata";
        let non_chunked_response = b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\ndata";
        let no_headers_response = b"some invalid data";

        assert!(HttpResponseAnalyzer::detect_chunked_encoding(
            chunked_response
        ));
        assert!(!HttpResponseAnalyzer::detect_chunked_encoding(
            non_chunked_response
        ));
        assert!(!HttpResponseAnalyzer::detect_chunked_encoding(
            no_headers_response
        ));
    }

    #[test]
    fn test_check_content_length_match() {
        let complete_response = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata";
        let incomplete_response = b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\ndata";
        let no_headers_response = b"some invalid data";
        let equal_response = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nabcd";
        let exceeding_response = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nabcd";
        let missing_last_bytes = b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\ndata";
        let headers_only = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n";

        assert!(HttpResponseAnalyzer::check_content_length_match(
            complete_response
        ));
        assert!(!HttpResponseAnalyzer::check_content_length_match(
            incomplete_response
        ));
        assert!(!HttpResponseAnalyzer::check_content_length_match(
            no_headers_response
        ));
        assert!(HttpResponseAnalyzer::check_content_length_match(
            equal_response
        ));
        assert!(HttpResponseAnalyzer::check_content_length_match(
            exceeding_response
        ));
        assert!(!HttpResponseAnalyzer::check_content_length_match(
            missing_last_bytes
        ));
        assert!(!HttpResponseAnalyzer::check_content_length_match(
            headers_only
        ));
    }

    #[test]
    fn test_has_bodyless_status_with_non_utf8_header_value() {
        let not_modified = b"HTTP/1.1 304 Not Modified\r\nETag: \"v\xe9\"\r\n\r\n";
        let no_content = b"HTTP/1.1 204 No Content\r\nX-Name: caf\xe9\r\n\r\n";
        let ok = b"HTTP/1.1 200 OK\r\nETag: \"v\xe9\"\r\nContent-Length: 0\r\n\r\n";
        let headers_incomplete = b"HTTP/1.1 304 Not Modified\r\nETag: \"v\xe9\"\r\n";

        assert!(HttpResponseAnalyzer::has_bodyless_status(not_modified));
        assert!(HttpResponseAnalyzer::has_bodyless_status(no_content));
        assert!(!HttpResponseAnalyzer::has_bodyless_status(ok));
        assert!(!HttpResponseAnalyzer::has_bodyless_status(
            headers_incomplete
        ));
    }

    #[test]
    fn test_has_chunked_end_marker() {
        let with_end_marker = b"5\r\nhello\r\n0\r\n\r\n";
        let without_end_marker = b"5\r\nhello\r\n";
        let with_leading_crlf = b"5\r\nhello\r\n\r\n0\r\n\r\n";
        let with_trailers = b"5\r\nhello\r\n0\r\nX-Trailer: value\r\n\r\n";
        let partial_marker = b"5\r\nhello\r\n0\r\n";

        assert!(HttpResponseAnalyzer::has_chunked_end_marker(
            with_end_marker
        ));
        assert!(!HttpResponseAnalyzer::has_chunked_end_marker(
            without_end_marker
        ));
        assert!(HttpResponseAnalyzer::has_chunked_end_marker(
            with_leading_crlf
        ));
        assert!(HttpResponseAnalyzer::has_chunked_end_marker(with_trailers));
        assert!(!HttpResponseAnalyzer::has_chunked_end_marker(
            partial_marker
        ));
    }

    #[test]
    fn chunked_end_marker_ignores_header_values_ending_in_zero() {
        let headers = b"HTTP/1.1 200 OK\r\nCache-Control: public, max-age=3600\r\nServer: nginx/1.20.0\r\nTransfer-Encoding: chunked\r\nExpires: 0\r\n\r\n";

        assert!(!HttpResponseAnalyzer::has_chunked_end_marker(headers));

        let first_chunk = [&headers[..], b"a\r\nfirst-part\r\n"].concat();
        assert!(!HttpResponseAnalyzer::has_chunked_end_marker(&first_chunk));

        let complete = [&first_chunk[..], b"0\r\n\r\n"].concat();
        assert!(HttpResponseAnalyzer::has_chunked_end_marker(&complete));

        let empty_body = [&headers[..], b"0\r\n\r\n"].concat();
        assert!(HttpResponseAnalyzer::has_chunked_end_marker(&empty_body));
    }

    #[test]
    fn test_is_websocket_upgrade() {
        let websocket_response = b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n";
        let normal_response = b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\ndata";
        let partial_websocket = b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n";
        let no_headers_response = b"some invalid data";

        assert!(HttpResponseAnalyzer::is_websocket_upgrade(
            websocket_response
        ));
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(normal_response));
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            partial_websocket
        ));
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            no_headers_response
        ));
        let rejected_with_upgrade_headers = String::from_utf8(websocket_response.to_vec())
            .unwrap()
            .replace("101 Switching Protocols", "200 OK");
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            rejected_with_upgrade_headers.as_bytes()
        ));
        let token_list = String::from_utf8(websocket_response.to_vec())
            .unwrap()
            .replace("Connection: Upgrade", "cOnNeCtIoN: keep-alive, Upgrade");
        assert!(HttpResponseAnalyzer::is_websocket_upgrade(
            token_list.as_bytes()
        ));
        let unrelated_header = String::from_utf8(websocket_response.to_vec())
            .unwrap()
            .replace("Upgrade: websocket", "X-Upgrade: websocket");
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            unrelated_header.as_bytes()
        ));
    }

    #[test]
    fn test_websocket_logging_readiness_validates_status_and_tokens() {
        let response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: proof\r\nContent-Length: 128\r\n\r\n";
        let rejected = response.replace("101 Switching Protocols", "200 OK");
        assert!(!HttpResponseAnalyzer::is_ready_for_logging(
            rejected.as_bytes(),
            false,
            false
        ));
        let unrelated = rejected.replace("Upgrade: websocket", "X-Upgrade: websocket");
        assert!(!HttpResponseAnalyzer::is_ready_for_logging(
            unrelated.as_bytes(),
            false,
            false
        ));
        let token_list = response.replace("Connection: Upgrade", "Connection: keep-alive, Upgrade");
        assert!(HttpResponseAnalyzer::is_ready_for_logging(
            token_list.as_bytes(),
            false,
            false
        ));
    }

    #[test]
    fn test_websocket_upgrade_with_many_headers_still_validates_handshake() {
        let extra_headers = "X-Extra: value\r\n".repeat(80);
        let response = format!(
            "HTTP/1.1 101 Switching Protocols\r\n{extra_headers}Upgrade: websocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Accept: proof\r\n\r\n"
        );
        assert!(HttpResponseAnalyzer::is_websocket_upgrade(
            response.as_bytes()
        ));
        assert!(HttpResponseAnalyzer::default().appears_complete(
            response.as_bytes(),
            false,
            false
        ));
        let no_accept = response.replace("Sec-WebSocket-Accept: proof\r\n", "");
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            no_accept.as_bytes()
        ));
        let rejected = response.replace("101 Switching Protocols", "200 OK");
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            rejected.as_bytes()
        ));
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            &response.as_bytes()[..response.len() - 2]
        ));
        let with_frames = format!("{response}{}", "frame".repeat(20_000));
        assert!(HttpResponseAnalyzer::is_websocket_upgrade(
            with_frames.as_bytes()
        ));
        let oversized =
            response.replace("X-Extra: value", &format!("X-Extra: {}", "a".repeat(1000)));
        assert!(!HttpResponseAnalyzer::is_websocket_upgrade(
            oversized.as_bytes()
        ));
    }

    #[test]
    fn test_parse_content_length() {
        let headers = b"HTTP/1.1 200 OK\r\nContent-Length: 42\r\nContent-Type: text/plain\r\n";
        let no_cl_headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n";
        let invalid_cl_headers = b"HTTP/1.1 200 OK\r\nContent-Length: abc\r\n";
        let empty_headers = b"";

        assert_eq!(parse_content_length(headers), Some(42));
        assert_eq!(parse_content_length(no_cl_headers), None);
        assert_eq!(parse_content_length(invalid_cl_headers), None);
        assert_eq!(parse_content_length(empty_headers), None);
    }

    #[test]
    fn test_appears_complete() {
        let analyzer = HttpResponseAnalyzer::default();

        let websocket_response = b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n";
        assert!(
            analyzer.appears_complete(websocket_response, false, false),
            "WebSocket responses should be considered complete"
        );

        let chunked_complete =
            b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n";
        assert!(
            analyzer.appears_complete(chunked_complete, true, true),
            "Chunked responses with end marker should be complete"
        );

        let chunked_incomplete = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello";
        assert!(
            !analyzer.appears_complete(chunked_incomplete, true, false),
            "Chunked responses without end marker should not be complete"
        );

        let complete_response = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata";
        assert!(
            analyzer.appears_complete(complete_response, false, false),
            "Response with matching content-length should be complete"
        );

        let incomplete_response = b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\ndata";
        assert!(
            !analyzer.appears_complete(incomplete_response, false, false),
            "Response with insufficient content-length should not be complete"
        );
    }

    #[test]
    fn test_is_ready_for_logging() {
        let complete_response = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata";
        assert!(
            HttpResponseAnalyzer::is_ready_for_logging(complete_response, false, false),
            "Complete response should be ready for logging"
        );

        let incomplete_response = b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\ndata";
        assert!(
            !HttpResponseAnalyzer::is_ready_for_logging(incomplete_response, false, false),
            "Incomplete response should not be ready for logging"
        );
    }

    #[test]
    fn test_is_ready_for_logging_with_config() {
        let analyzer = HttpResponseAnalyzer::default();

        let websocket_response = b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n";
        assert!(
            analyzer.is_ready_for_logging_with_config(websocket_response, false, false),
            "WebSocket upgrade should be ready for logging"
        );

        let chunked_complete =
            b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n";
        assert!(
            analyzer.is_ready_for_logging_with_config(chunked_complete, true, true),
            "Chunked with end marker should be ready for logging"
        );

        let chunked_incomplete = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello";
        assert!(
            !analyzer.is_ready_for_logging_with_config(chunked_incomplete, true, false),
            "Chunked without end marker should not be ready for logging"
        );

        let http10_response =
            b"HTTP/1.0 200 OK\r\n\r\nSome data that doesn't have a content-length";
        assert!(
            analyzer.is_ready_for_logging_with_config(http10_response, false, false),
            "HTTP/1.0 response without content-length should be ready for logging"
        );

        let no_body_response = b"HTTP/1.1 204 No Content\r\n\r\n";
        assert!(
            analyzer.is_ready_for_logging_with_config(no_body_response, false, false),
            "204 response should be ready for logging"
        );

        let connection_close = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nSome data";
        assert!(
            analyzer.is_ready_for_logging_with_config(connection_close, false, false),
            "Response with Connection: close should be ready for logging"
        );
    }

    #[test]
    fn test_extract_status_code() {
        assert_eq!(
            HttpResponseAnalyzer::extract_status_code("HTTP/1.1 200 OK\r\n"),
            Some(200)
        );
        assert_eq!(
            HttpResponseAnalyzer::extract_status_code("HTTP/1.1 404 Not Found\r\n"),
            Some(404)
        );
        assert_eq!(HttpResponseAnalyzer::extract_status_code(""), None);
        assert_eq!(HttpResponseAnalyzer::extract_status_code("Invalid"), None);
        assert_eq!(
            HttpResponseAnalyzer::extract_status_code("HTTP/1.1\r\n"),
            None
        );
        assert_eq!(
            HttpResponseAnalyzer::extract_status_code("HTTP/1.1 abc\r\n"),
            None
        );
    }

    #[test]
    fn test_process_chunk() {
        let mut found_end_marker = false;
        let mut total_chunks = 0;

        let chunk_with_end = b"5\r\nhello\r\n0\r\n\r\n";
        HttpResponseAnalyzer::process_chunk(
            chunk_with_end,
            0,
            true,
            &mut found_end_marker,
            &mut total_chunks,
        );
        assert!(found_end_marker);
        assert_eq!(total_chunks, 1);

        found_end_marker = false;
        total_chunks = 0;

        let chunk_without_end = b"5\r\nhello\r\n";
        HttpResponseAnalyzer::process_chunk(
            chunk_without_end,
            0,
            true,
            &mut found_end_marker,
            &mut total_chunks,
        );
        assert!(!found_end_marker);
        assert_eq!(total_chunks, 1);

        HttpResponseAnalyzer::process_chunk(
            b"some data",
            0,
            false,
            &mut found_end_marker,
            &mut total_chunks,
        );
        assert!(!found_end_marker);
        assert_eq!(total_chunks, 1);
    }

    #[test]
    fn process_chunk_finds_end_marker_split_at_any_read_boundary() {
        let response = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nExpires: 0\r\n\r\na\r\nfirst-part\r\n0\r\n\r\n";

        for split in 1..response.len() {
            let mut found_end_marker = false;
            let mut total_chunks = 0;

            HttpResponseAnalyzer::process_chunk(
                &response[..split],
                0,
                true,
                &mut found_end_marker,
                &mut total_chunks,
            );
            assert!(!found_end_marker, "marker found early at split {split}");

            HttpResponseAnalyzer::process_chunk(
                response,
                split,
                true,
                &mut found_end_marker,
                &mut total_chunks,
            );
            assert!(found_end_marker, "marker missed at split {split}");
        }
    }

    #[test]
    fn test_is_multipart_response() {
        let multipart_headers = b"HTTP/1.1 200 OK\r\nContent-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575\r\n\r\n";
        let normal_headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n";
        let invalid_headers = b"invalid data";

        assert!(HttpResponseAnalyzer::is_multipart_response(
            multipart_headers
        ));
        assert!(!HttpResponseAnalyzer::is_multipart_response(normal_headers));
        assert!(!HttpResponseAnalyzer::is_multipart_response(
            invalid_headers
        ));
    }

    #[test]
    fn test_is_streaming_response() {
        let sse_headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n";
        let ndjson_headers = b"HTTP/1.1 200 OK\r\nContent-Type: application/x-ndjson\r\n\r\n";
        let json_chunked_headers = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n";
        let normal_headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n";
        let invalid_headers = b"invalid data";

        assert!(HttpResponseAnalyzer::is_streaming_response(sse_headers));
        assert!(HttpResponseAnalyzer::is_streaming_response(ndjson_headers));
        assert!(HttpResponseAnalyzer::is_streaming_response(
            json_chunked_headers
        ));
        assert!(!HttpResponseAnalyzer::is_streaming_response(normal_headers));
        assert!(!HttpResponseAnalyzer::is_streaming_response(
            invalid_headers
        ));
    }

    #[test]
    fn test_analyzer_configuration() {
        let default_analyzer = HttpResponseAnalyzer::default();
        assert_eq!(
            default_analyzer.config().min_headers_size,
            DEFAULT_MIN_VALID_HEADERS_SIZE
        );

        let custom_config = ResponseAnalyzerConfig {
            min_headers_size: 32,
        };
        let custom_analyzer = HttpResponseAnalyzer::new(custom_config);
        assert_eq!(custom_analyzer.config().min_headers_size, 32);
    }

    #[test]
    fn test_find_headers_end() {
        let with_headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nBody goes here";
        let without_headers = b"No headers here";
        let partial_headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n";

        let header_end_position = with_headers
            .windows(4)
            .position(|w| w == b"\r\n\r\n")
            .unwrap();

        assert_eq!(find_headers_end(with_headers), Some(header_end_position));
        assert_eq!(find_headers_end(without_headers), None);
        assert_eq!(find_headers_end(partial_headers), None);
    }
}