pingora-core 0.9.1

Pingora's APIs and traits for the core network protocols.
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
// Copyright 2026 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! HTTP response (de)compression libraries
//!
//! Gzip, Brotli, Zstd, and dictionary-compressed Zstd (dcz, [RFC 9842](https://datatracker.ietf.org/doc/html/rfc9842)) are supported.

use super::HttpTask;

use bytes::Bytes;
use log::{debug, warn};
use pingora_error::{ErrorType, Result};
use pingora_http::{RequestHeader, ResponseHeader};
use std::time::Duration;

use strum::EnumCount;
use strum_macros::EnumCount as EnumCountMacro;

mod brotli;
mod gzip;
mod zstd;

/// Re-export [RFC 9842](https://datatracker.ietf.org/doc/html/rfc9842) constants for external use.
pub use zstd::{DCZ_HEADER_SIZE, DCZ_MAGIC};

/// The type of error to return when (de)compression fails
pub const COMPRESSION_ERROR: ErrorType = ErrorType::new("CompressionError");

/// The trait for both compress and decompress because the interface and syntax are the same:
/// encode some bytes to other bytes
pub trait Encode {
    /// Encode the input bytes. The `end` flag signals the end of the entire input. The `end` flag
    /// helps the encoder to flush out the remaining buffered encoded data because certain compression
    /// algorithms prefer to collect large enough data to compress all together.
    fn encode(&mut self, input: &[u8], end: bool) -> Result<Bytes>;
    /// Return the Encoder's name, the total input bytes, the total output bytes and the total
    /// duration spent on encoding the data.
    fn stat(&self) -> (&'static str, usize, usize, Duration);
}

/// The response compression object. Currently support gzip compression and brotli decompression.
///
/// To use it, the caller should create a [`ResponseCompressionCtx`] per HTTP session.
/// The caller should call the corresponding filters for the request header, response header and
/// response body. If the algorithms are supported, the output response body will be encoded.
/// The response header will be adjusted accordingly as well. If the algorithm is not supported
/// or no encoding is needed, the response is untouched.
///
/// If configured and if the request's `accept-encoding` header contains the algorithm supported and the
/// incoming response doesn't have that encoding, the filter will compress the response.
/// If configured and supported, and if the incoming response's `content-encoding` isn't one of the
/// request's `accept-encoding` supported algorithm, the ctx will decompress the response.
///
/// # Currently supported algorithms and actions
/// - Brotli decompression: if the response is br compressed, this ctx can decompress it
/// - Gzip compression: if the response is uncompressed, this ctx can compress it with gzip
pub struct ResponseCompressionCtx(CtxInner);

/// Dictionary data for [RFC 9842](https://datatracker.ietf.org/doc/html/rfc9842) shared dictionary compression.
#[derive(Clone, Debug)]
pub struct DictionaryData {
    pub bytes: Bytes,
    pub hash: [u8; 32],
}

enum CtxInner {
    HeaderPhase {
        // Store the preferred list to compare with content-encoding
        accept_encoding: Vec<Algorithm>,
        encoding_levels: [u32; Algorithm::COUNT],
        decompress_enable: [bool; Algorithm::COUNT],
        preserve_etag: [bool; Algorithm::COUNT],
        // Optional dictionary for dcz compression (RFC 9842).
        dictionary: Option<DictionaryData>,
    },
    BodyPhase(Option<Box<dyn Encode + Send + Sync>>),
}

impl ResponseCompressionCtx {
    /// Create a new [`ResponseCompressionCtx`] with the expected compression level. `0` will disable
    /// the compression. The compression level is applied across all algorithms.
    /// The `decompress_enable` flag will tell the ctx to decompress if needed.
    /// The `preserve_etag` flag indicates whether the ctx should avoid modifying the etag,
    /// which will otherwise be weakened if the flag is false and (de)compression is applied.
    pub fn new(compression_level: u32, decompress_enable: bool, preserve_etag: bool) -> Self {
        Self(CtxInner::HeaderPhase {
            accept_encoding: Vec::new(),
            encoding_levels: [compression_level; Algorithm::COUNT],
            decompress_enable: [decompress_enable; Algorithm::COUNT],
            preserve_etag: [preserve_etag; Algorithm::COUNT],
            dictionary: None,
        })
    }

    /// Whether the encoder is enabled.
    /// The enablement will change according to the request and response filter by this ctx.
    pub fn is_enabled(&self) -> bool {
        match &self.0 {
            CtxInner::HeaderPhase {
                decompress_enable,
                encoding_levels: levels,
                ..
            } => levels.iter().any(|l| *l != 0) || decompress_enable.iter().any(|d| *d),
            CtxInner::BodyPhase(c) => c.is_some(),
        }
    }

    /// Whether this ctx is in the response header phase.
    pub fn is_header_phase(&self) -> bool {
        matches!(self.0, CtxInner::HeaderPhase { .. })
    }

    /// Return the stat of this ctx:
    /// algorithm name, in bytes, out bytes, time took for the compression
    pub fn get_info(&self) -> Option<(&'static str, usize, usize, Duration)> {
        match &self.0 {
            CtxInner::HeaderPhase { .. } => None,
            CtxInner::BodyPhase(c) => c.as_ref().map(|c| c.stat()),
        }
    }

    /// Adjust the compression level for all compression algorithms.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn adjust_level(&mut self, new_level: u32) {
        match &mut self.0 {
            CtxInner::HeaderPhase {
                encoding_levels: levels,
                ..
            } => {
                *levels = [new_level; Algorithm::COUNT];
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Adjust the compression level for a specific algorithm.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn adjust_algorithm_level(&mut self, algorithm: Algorithm, new_level: u32) {
        match &mut self.0 {
            CtxInner::HeaderPhase {
                encoding_levels: levels,
                ..
            } => {
                levels[algorithm.index()] = new_level;
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Adjust the decompression flag for all compression algorithms.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn adjust_decompression(&mut self, enabled: bool) {
        match &mut self.0 {
            CtxInner::HeaderPhase {
                decompress_enable, ..
            } => {
                *decompress_enable = [enabled; Algorithm::COUNT];
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Adjust the decompression flag for a specific algorithm.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn adjust_algorithm_decompression(&mut self, algorithm: Algorithm, enabled: bool) {
        match &mut self.0 {
            CtxInner::HeaderPhase {
                decompress_enable, ..
            } => {
                decompress_enable[algorithm.index()] = enabled;
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Adjust preserve etag setting.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn adjust_preserve_etag(&mut self, enabled: bool) {
        match &mut self.0 {
            CtxInner::HeaderPhase { preserve_etag, .. } => {
                *preserve_etag = [enabled; Algorithm::COUNT];
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Adjust preserve etag setting for a specific algorithm.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn adjust_algorithm_preserve_etag(&mut self, algorithm: Algorithm, enabled: bool) {
        match &mut self.0 {
            CtxInner::HeaderPhase { preserve_etag, .. } => {
                preserve_etag[algorithm.index()] = enabled;
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Set the dictionary for [RFC 9842](https://datatracker.ietf.org/doc/html/rfc9842) dictionary compression.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn set_dictionary(&mut self, dictionary_bytes: Bytes, dictionary_hash: [u8; 32]) {
        match &mut self.0 {
            CtxInner::HeaderPhase { dictionary, .. } => {
                *dictionary = Some(DictionaryData {
                    bytes: dictionary_bytes,
                    hash: dictionary_hash,
                });
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Check if a dictionary has been set.
    pub fn has_dictionary(&self) -> bool {
        match &self.0 {
            CtxInner::HeaderPhase { dictionary, .. } => dictionary.is_some(),
            CtxInner::BodyPhase(_) => false,
        }
    }

    /// Clear any previously set dictionary.
    /// # Panic
    /// This function will panic if it has already started encoding the response body.
    pub fn clear_dictionary(&mut self) {
        match &mut self.0 {
            CtxInner::HeaderPhase { dictionary, .. } => {
                *dictionary = None;
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Feed the request header into this ctx.
    pub fn request_filter(&mut self, req: &RequestHeader) {
        if !self.is_enabled() {
            return;
        }
        match &mut self.0 {
            CtxInner::HeaderPhase {
                accept_encoding, ..
            } => parse_accept_encoding(
                req.headers.get(http::header::ACCEPT_ENCODING),
                accept_encoding,
            ),
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Whether [`Self::response_header_filter`] would decompress the body of this response.
    ///
    /// This ctx replaces the response body in place, so a filter that runs before it cannot tell
    /// from the response header alone what the body will look like by the time it reaches
    /// downstream. This predicate answers that question ahead of time. For example, a caller
    /// framing a byte range against the response body needs to know whether the body it is
    /// measuring is about to be swapped for its decompressed form, which invalidates both the
    /// offsets and the length it computed.
    ///
    /// This assumes the response has a body: unlike [`Self::response_header_filter`] it takes no
    /// `end` flag, and a response without a body is never decompressed. Informational (`1xx`)
    /// responses are not final, so they are reported as not decompressed; ask again with the
    /// final response header.
    ///
    /// Returns `false` once this ctx has left the header phase, because by then the decision has
    /// already been made. This is a read-only query, so unlike the `adjust_*` methods it never
    /// panics and is safe to call in any phase.
    pub fn will_decompress(&self, resp: &ResponseHeader) -> bool {
        if !self.is_enabled() {
            return false;
        }
        match &self.0 {
            CtxInner::HeaderPhase {
                decompress_enable,
                accept_encoding,
                ..
            } => {
                // an informational response is not the final one, the filter defers the decision
                if resp.status.is_informational() {
                    return false;
                }
                match decide_action(resp, accept_encoding) {
                    Action::Decompress(algorithm) => {
                        // mirrors `algorithm.decompressor(decompress_enable[idx]).is_some()`
                        // in the response header filter, without building the decompressor
                        decompress_enable[algorithm.index()] && algorithm.can_decompress()
                    }
                    Action::Noop | Action::Compress(_) => false,
                }
            }
            // the response header was already filtered, whatever it decided is done
            CtxInner::BodyPhase(_) => false,
        }
    }

    /// Feed the response header into this ctx
    pub fn response_header_filter(&mut self, resp: &mut ResponseHeader, end: bool) {
        if !self.is_enabled() {
            return;
        }
        match &self.0 {
            CtxInner::HeaderPhase {
                decompress_enable,
                preserve_etag,
                accept_encoding,
                encoding_levels: levels,
                dictionary,
            } => {
                if resp.status.is_informational() {
                    if resp.status == http::status::StatusCode::SWITCHING_PROTOCOLS {
                        // no transformation for websocket (TODO: cite RFC)
                        self.0 = CtxInner::BodyPhase(None);
                    }
                    // else, wait for the final response header for decision
                    return;
                }
                // do nothing if no body
                if end {
                    self.0 = CtxInner::BodyPhase(None);
                    return;
                }

                if depends_on_accept_encoding(
                    resp,
                    levels.iter().any(|level| *level != 0),
                    decompress_enable,
                ) {
                    // The response depends on the Accept-Encoding header, make sure to indicate it
                    // in the Vary response header.
                    // https://www.rfc-editor.org/rfc/rfc9110#name-vary
                    add_vary_header(resp, &http::header::ACCEPT_ENCODING);
                }

                let action = decide_action(resp, accept_encoding);
                debug!("compression action: {action:?}");
                let (encoder, preserve_etag) = match action {
                    Action::Noop => (None, false),
                    Action::Compress(algorithm) => {
                        let idx = algorithm.index();
                        let compressor = match algorithm {
                            Algorithm::Dcz => {
                                // RFC 9842: dictionary-compressed responses vary on
                                // Available-Dictionary so caches don't serve this variant
                                // to clients with a different or missing dictionary.
                                let enc = dictionary.as_ref().and_then(|d| {
                                    algorithm.maybe_compressor_with_dictionary(levels[idx], d)
                                });
                                if enc.is_some() {
                                    add_vary_header(resp, &AVAILABLE_DICTIONARY);
                                }
                                enc
                            }
                            _ => algorithm.compressor(levels[idx]),
                        };
                        (compressor, preserve_etag[idx])
                    }
                    Action::Decompress(algorithm) => {
                        let idx = algorithm.index();
                        (
                            algorithm.decompressor(decompress_enable[idx]),
                            preserve_etag[idx],
                        )
                    }
                };
                if encoder.is_some() {
                    adjust_response_header(resp, &action, preserve_etag);
                }
                self.0 = CtxInner::BodyPhase(encoder);
            }
            CtxInner::BodyPhase(_) => panic!("Wrong phase: BodyPhase"),
        }
    }

    /// Stream the response body chunks into this ctx. The return value will be the compressed
    /// data.
    ///
    /// Return None if compression is not enabled.
    pub fn response_body_filter(&mut self, data: Option<&Bytes>, end: bool) -> Option<Bytes> {
        match &mut self.0 {
            CtxInner::HeaderPhase { .. } => panic!("Wrong phase: HeaderPhase"),
            CtxInner::BodyPhase(compressor) => {
                let result = compressor
                    .as_mut()
                    .map(|c| {
                        // Feed even empty slice to compressor because it might yield data
                        // when `end` is true
                        let data = if let Some(b) = data { b.as_ref() } else { &[] };
                        c.encode(data, end)
                    })
                    .transpose();
                result.unwrap_or_else(|e| {
                    warn!("Failed to compress, compression disabled, {}", e);
                    // no point to transcode further data because bad data is already seen
                    self.0 = CtxInner::BodyPhase(None);
                    None
                })
            }
        }
    }

    // TODO: retire this function, replace it with the two functions above
    /// Feed the response into this ctx.
    /// This filter will mutate the response accordingly if encoding is needed.
    pub fn response_filter(&mut self, t: &mut HttpTask) {
        if !self.is_enabled() {
            return;
        }
        match t {
            HttpTask::Header(resp, end) => self.response_header_filter(resp, *end),
            HttpTask::Body(data, end) => {
                let compressed = self.response_body_filter(data.as_ref(), *end);
                if compressed.is_some() {
                    *t = HttpTask::Body(compressed, *end);
                }
            }
            HttpTask::Done => {
                // try to finish/flush compression
                let compressed = self.response_body_filter(None, true);
                if compressed.is_some() {
                    // compressor has more data to flush
                    *t = HttpTask::Body(compressed, true);
                }
            }
            _ => { /* Trailer, Failed: do nothing? */ }
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, EnumCountMacro)]
pub enum Algorithm {
    Any, // the "*"
    Gzip,
    Brotli,
    Zstd,
    Dcb,
    Dcz,
    // TODO: Identity,
    // TODO: Deflate
    Other, // anything unknown
}

impl Algorithm {
    pub fn as_str(&self) -> &'static str {
        match self {
            Algorithm::Gzip => "gzip",
            Algorithm::Brotli => "br",
            Algorithm::Zstd => "zstd",
            Algorithm::Dcb => "dcb",
            Algorithm::Dcz => "dcz",
            Algorithm::Any => "*",
            Algorithm::Other => "other",
        }
    }

    pub fn compressor(&self, level: u32) -> Option<Box<dyn Encode + Send + Sync>> {
        if level == 0 {
            None
        } else {
            match self {
                Self::Gzip => Some(Box::new(gzip::Compressor::new(level))),
                Self::Brotli => Some(Box::new(brotli::Compressor::new(level))),
                Self::Zstd => Some(Box::new(zstd::Compressor::new(level))),
                _ => None, // not implemented
            }
        }
    }

    pub fn maybe_compressor_with_dictionary(
        &self,
        level: u32,
        dictionary: &DictionaryData,
    ) -> Option<Box<dyn Encode + Send + Sync>> {
        if level == 0 {
            None
        } else {
            match self {
                Self::Dcz => {
                    match zstd::DictionaryCompressor::new(level, &dictionary.bytes, dictionary.hash)
                    {
                        Ok(c) => Some(Box::new(c)),
                        Err(e) => {
                            warn!("Failed to create DCZ compressor: {e}");
                            None
                        }
                    }
                }
                _ => None,
            }
        }
    }

    // The single source of truth for which algorithms can be decompressed: both
    // `decompressor` and `can_decompress` are derived from it, so the set cannot drift
    // between the two. The match is exhaustive on purpose, so that a newly added algorithm
    // has to state whether a decompressor exists for it.
    fn decompressor_impl(&self) -> Option<fn() -> Box<dyn Encode + Send + Sync>> {
        match self {
            Self::Gzip => Some(|| Box::new(gzip::Decompressor::new())),
            Self::Brotli => Some(|| Box::new(brotli::Decompressor::new())),
            // not implemented
            Self::Any | Self::Zstd | Self::Dcb | Self::Dcz | Self::Other => None,
        }
    }

    pub fn decompressor(&self, enabled: bool) -> Option<Box<dyn Encode + Send + Sync>> {
        if !enabled {
            None
        } else {
            self.decompressor_impl()
                .map(|new_decompressor| new_decompressor())
        }
    }

    /// Whether a decompressor is implemented for this algorithm.
    ///
    /// This is a property of the algorithm alone: it says nothing about whether decompression is
    /// *enabled* for it, which is configured separately with
    /// [`ResponseCompressionCtx::adjust_algorithm_decompression`]. [`Algorithm::decompressor`]
    /// hands out a decompressor only when both hold.
    ///
    /// Note that [`Algorithm::Other`] can never be decompressed: it stands for any content coding
    /// that isn't recognized, which includes multi-coding values such as `gzip, br`.
    ///
    /// This lets a caller tell whether a `Content-Encoding` is one that can be undone without
    /// paying to construct a decompressor, e.g. to predict what
    /// [`ResponseCompressionCtx::response_header_filter`] is about to do; see
    /// [`ResponseCompressionCtx::will_decompress`].
    pub fn can_decompress(&self) -> bool {
        self.decompressor_impl().is_some()
    }

    pub fn index(&self) -> usize {
        *self as usize
    }
}

impl From<&str> for Algorithm {
    fn from(s: &str) -> Self {
        use unicase::UniCase;

        let coding = UniCase::new(s);
        if coding == UniCase::ascii("gzip") {
            Algorithm::Gzip
        } else if coding == UniCase::ascii("br") {
            Algorithm::Brotli
        } else if coding == UniCase::ascii("zstd") {
            Algorithm::Zstd
        } else if coding == UniCase::ascii("dcb") {
            Algorithm::Dcb
        } else if coding == UniCase::ascii("dcz") {
            Algorithm::Dcz
        } else if s.is_empty() {
            Algorithm::Any
        } else {
            Algorithm::Other
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Action {
    Noop, // do nothing, e.g. when the input is already gzip
    Compress(Algorithm),
    Decompress(Algorithm),
}

// parse Accept-Encoding header and put it to the list
fn parse_accept_encoding(accept_encoding: Option<&http::HeaderValue>, list: &mut Vec<Algorithm>) {
    // https://www.rfc-editor.org/rfc/rfc9110#name-accept-encoding
    if let Some(ac) = accept_encoding {
        // fast path
        if ac.as_bytes() == b"gzip" {
            list.push(Algorithm::Gzip);
            return;
        }
        // properly parse AC header
        match sfv::Parser::parse_list(ac.as_bytes()) {
            Ok(parsed) => {
                for item in parsed {
                    if let sfv::ListEntry::Item(i) = item {
                        if let Some(s) = i.bare_item.as_token() {
                            // TODO: support q value
                            let algorithm = Algorithm::from(s);
                            // ignore algorithms that we don't understand ignore
                            if algorithm != Algorithm::Other {
                                list.push(Algorithm::from(s));
                            }
                        }
                    }
                }
            }
            Err(e) => {
                warn!("Failed to parse accept-encoding {ac:?}, {e}")
            }
        }
    } else {
        // "If no Accept-Encoding header, any content coding is acceptable"
        // keep the list empty
    }
}

#[test]
fn test_accept_encoding_req_header() {
    let mut header = RequestHeader::build("GET", b"/", None).unwrap();
    let mut ac_list = Vec::new();
    parse_accept_encoding(
        header.headers.get(http::header::ACCEPT_ENCODING),
        &mut ac_list,
    );
    assert!(ac_list.is_empty());

    let mut ac_list = Vec::new();
    header.insert_header("accept-encoding", "gzip").unwrap();
    parse_accept_encoding(
        header.headers.get(http::header::ACCEPT_ENCODING),
        &mut ac_list,
    );
    assert_eq!(ac_list[0], Algorithm::Gzip);

    let mut ac_list = Vec::new();
    header
        .insert_header("accept-encoding", "what, br, gzip")
        .unwrap();
    parse_accept_encoding(
        header.headers.get(http::header::ACCEPT_ENCODING),
        &mut ac_list,
    );
    assert_eq!(ac_list[0], Algorithm::Brotli);
    assert_eq!(ac_list[1], Algorithm::Gzip);
}

// test whether the response depends on Accept-Encoding header
fn depends_on_accept_encoding(
    resp: &ResponseHeader,
    compress_enabled: bool,
    decompress_enabled: &[bool],
) -> bool {
    use http::header::CONTENT_ENCODING;

    (decompress_enabled.iter().any(|enabled| *enabled)
        && resp.headers.get(CONTENT_ENCODING).is_some())
        || (compress_enabled && compressible(resp))
}

#[test]
fn test_decide_on_accept_encoding() {
    let mut resp = ResponseHeader::build(200, None).unwrap();
    resp.insert_header("content-length", "50").unwrap();
    resp.insert_header("content-type", "text/html").unwrap();
    resp.insert_header("content-encoding", "gzip").unwrap();

    // enabled
    assert!(depends_on_accept_encoding(&resp, false, &[true]));

    // decompress disabled => disabled
    assert!(!depends_on_accept_encoding(&resp, false, &[false]));

    // no content-encoding => disabled
    resp.remove_header("content-encoding");
    assert!(!depends_on_accept_encoding(&resp, false, &[true]));

    // compress enabled and compressible response => enabled
    assert!(depends_on_accept_encoding(&resp, true, &[false]));

    // compress disabled and compressible response => disabled
    assert!(!depends_on_accept_encoding(&resp, false, &[false]));

    // compress enabled and not compressible response => disabled
    resp.insert_header("content-type", "text/html+zip").unwrap();
    assert!(!depends_on_accept_encoding(&resp, true, &[false]));
}

// filter response header to see if (de)compression is needed
fn decide_action(resp: &ResponseHeader, accept_encoding: &[Algorithm]) -> Action {
    use http::header::CONTENT_ENCODING;

    let content_encoding = if let Some(ce) = resp.headers.get(CONTENT_ENCODING) {
        // https://www.rfc-editor.org/rfc/rfc9110#name-content-encoding
        if let Ok(ce_str) = std::str::from_utf8(ce.as_bytes()) {
            Some(Algorithm::from(ce_str))
        } else {
            // not utf-8, treat it as unknown encoding to leave it untouched
            Some(Algorithm::Other)
        }
    } else {
        // no Accept-encoding
        None
    };

    if let Some(ce) = content_encoding {
        if accept_encoding.contains(&ce) {
            // downstream can accept this encoding, nothing to do
            Action::Noop
        } else {
            // always decompress because uncompressed is always acceptable
            // https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
            // "If the representation has no content coding, then it is acceptable by default
            // unless specifically excluded..." TODO: check the exclude case
            // TODO: we could also transcode it to a preferred encoding, e.g. br->gzip
            Action::Decompress(ce)
        }
    } else if accept_encoding.is_empty() // both CE and AE are empty
        || !compressible(resp) // the type is not compressible
        || accept_encoding[0] == Algorithm::Any
    {
        Action::Noop
    } else {
        // try to compress with the first AC
        // TODO: support to configure preferred encoding
        Action::Compress(accept_encoding[0])
    }
}

#[test]
fn test_decide_action() {
    use Action::*;
    use Algorithm::*;

    let header = ResponseHeader::build(200, None).unwrap();
    // no compression asked, no compression needed
    assert_eq!(decide_action(&header, &[]), Noop);

    // already gzip, no compression needed
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-type", "text/html").unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    assert_eq!(decide_action(&header, &[Gzip]), Noop);

    // already gzip, no compression needed, upper case
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "GzIp").unwrap();
    header.insert_header("content-type", "text/html").unwrap();
    assert_eq!(decide_action(&header, &[Gzip]), Noop);

    // no encoding, compression needed, accepted content-type, large enough
    // Will compress
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "20").unwrap();
    header.insert_header("content-type", "text/html").unwrap();
    assert_eq!(decide_action(&header, &[Gzip]), Compress(Gzip));

    // too small
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "19").unwrap();
    header.insert_header("content-type", "text/html").unwrap();
    assert_eq!(decide_action(&header, &[Gzip]), Noop);

    // already compressed MIME
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "20").unwrap();
    header
        .insert_header("content-type", "text/html+zip")
        .unwrap();
    assert_eq!(decide_action(&header, &[Gzip]), Noop);

    // unsupported MIME
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "20").unwrap();
    header.insert_header("content-type", "image/jpg").unwrap();
    assert_eq!(decide_action(&header, &[Gzip]), Noop);

    // compressed, need decompress
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    assert_eq!(decide_action(&header, &[]), Decompress(Gzip));

    // accept-encoding different, need decompress
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    assert_eq!(decide_action(&header, &[Brotli]), Decompress(Gzip));

    // less preferred but no need to decompress
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    assert_eq!(decide_action(&header, &[Brotli, Gzip]), Noop);

    // dcb passthrough: client accepts dcb, response has dcb
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "dcb").unwrap();
    assert_eq!(decide_action(&header, &[Dcb, Brotli]), Noop);

    // dcz passthrough: client accepts dcz, response has dcz
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "dcz").unwrap();
    assert_eq!(decide_action(&header, &[Dcz, Zstd]), Noop);

    // Client wants dcz but response has brotli, decompress brotli
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "br").unwrap();
    assert_eq!(decide_action(&header, &[Dcz]), Decompress(Brotli));

    // Client wants dcz but response has zstd, decompress zstd
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "zstd").unwrap();
    assert_eq!(decide_action(&header, &[Dcz]), Decompress(Zstd));

    // Client wants dcb but response has gzip, decompress gzip
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    assert_eq!(decide_action(&header, &[Dcb]), Decompress(Gzip));

    // Client wants dcb but response has brotli, decompress brotli
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-encoding", "br").unwrap();
    assert_eq!(decide_action(&header, &[Dcb]), Decompress(Brotli));
}

#[test]
fn test_can_decompress() {
    use Algorithm::*;

    // every variant spelled out, sized by Algorithm::COUNT so that adding an algorithm fails
    // to compile here until it is considered
    const ALL: [Algorithm; Algorithm::COUNT] = [Any, Gzip, Brotli, Zstd, Dcb, Dcz, Other];

    for algorithm in ALL {
        // only gzip and brotli have a decompressor implementation
        assert_eq!(
            algorithm.can_decompress(),
            matches!(algorithm, Gzip | Brotli),
            "unexpected can_decompress() for {}",
            algorithm.as_str()
        );
        // can_decompress() must agree with what decompressor() actually hands out
        assert_eq!(
            algorithm.can_decompress(),
            algorithm.decompressor(true).is_some(),
            "can_decompress() disagrees with decompressor() for {}",
            algorithm.as_str()
        );
        // and nothing is decompressed when the flag is off
        assert!(algorithm.decompressor(false).is_none());
    }
}

// build a ctx that has already seen a request with the given accept-encoding
#[cfg(test)]
fn ctx_for_test(
    compression_level: u32,
    decompress_enable: bool,
    accept_encoding: Option<&str>,
) -> ResponseCompressionCtx {
    let mut ctx = ResponseCompressionCtx::new(compression_level, decompress_enable, false);
    let mut req = RequestHeader::build("GET", b"/", None).unwrap();
    if let Some(ae) = accept_encoding {
        req.insert_header("accept-encoding", ae).unwrap();
    }
    ctx.request_filter(&req);
    ctx
}

// build a compressible response with the given status and content-encoding
#[cfg(test)]
fn resp_for_test(status: u16, content_encoding: Option<&str>) -> ResponseHeader {
    let mut resp = ResponseHeader::build(status, None).unwrap();
    resp.insert_header("content-type", "text/html").unwrap();
    resp.insert_header("content-length", "1000").unwrap();
    if let Some(ce) = content_encoding {
        resp.insert_header("content-encoding", ce).unwrap();
    }
    resp
}

#[test]
fn test_will_decompress() {
    // gzip response the client cannot take: the body will be decompressed
    let ctx = ctx_for_test(0, true, Some("br"));
    assert!(ctx.will_decompress(&resp_for_test(200, Some("gzip"))));

    // the client takes gzip, so the body is passed through as is
    let ctx = ctx_for_test(0, true, Some("gzip"));
    assert!(!ctx.will_decompress(&resp_for_test(200, Some("gzip"))));

    // multi-coding content-encoding parses to Algorithm::Other, which has no decompressor,
    // so the body is left alone even though decompression is on for every algorithm
    let ctx = ctx_for_test(0, true, Some("br"));
    assert!(!ctx.will_decompress(&resp_for_test(200, Some("gzip, br"))));

    // zstd has no decompressor either
    let ctx = ctx_for_test(0, true, Some("br"));
    assert!(!ctx.will_decompress(&resp_for_test(200, Some("zstd"))));

    // (de)compression entirely disabled
    let ctx = ctx_for_test(0, false, Some("br"));
    assert!(!ctx.will_decompress(&resp_for_test(200, Some("gzip"))));

    // compression on but decompression off
    let ctx = ctx_for_test(6, false, Some("br"));
    assert!(!ctx.will_decompress(&resp_for_test(200, Some("gzip"))));

    // the per algorithm decompression flag is respected: gzip turned off
    let mut ctx = ctx_for_test(0, true, Some("br"));
    ctx.adjust_algorithm_decompression(Algorithm::Gzip, false);
    assert!(!ctx.will_decompress(&resp_for_test(200, Some("gzip"))));
    // ...while brotli is still on
    let mut ctx = ctx_for_test(0, true, Some("gzip"));
    ctx.adjust_algorithm_decompression(Algorithm::Gzip, false);
    assert!(ctx.will_decompress(&resp_for_test(200, Some("br"))));

    // informational responses are not final, no decision yet
    let ctx = ctx_for_test(0, true, Some("br"));
    assert!(!ctx.will_decompress(&resp_for_test(100, Some("gzip"))));
    assert!(!ctx.will_decompress(&resp_for_test(101, Some("gzip"))));

    // uncompressed response, nothing to decompress even when compression kicks in
    let ctx = ctx_for_test(6, true, Some("gzip"));
    assert!(!ctx.will_decompress(&resp_for_test(200, None)));

    // once the response header has been filtered the decision is already made
    let mut ctx = ctx_for_test(0, true, Some("br"));
    let mut resp = resp_for_test(200, Some("gzip"));
    assert!(ctx.will_decompress(&resp));
    ctx.response_header_filter(&mut resp, false);
    assert!(!ctx.will_decompress(&resp));
    // also safe to ask when the body phase installed no encoder at all
    let mut ctx = ctx_for_test(0, true, Some("gzip"));
    let mut resp = resp_for_test(200, Some("gzip"));
    ctx.response_header_filter(&mut resp, false);
    assert!(!ctx.will_decompress(&resp));
}

#[test]
fn test_will_decompress_agrees_with_response_header_filter() {
    // will_decompress() must predict exactly what response_header_filter() does. Decompression
    // is the only outcome that both drops content-encoding and starts streaming the body, so
    // that pair of headers is the observable signal.
    for (level, decompress, accept_encoding, content_encoding) in [
        (0, true, Some("br"), Some("gzip")),
        (0, true, Some("br"), Some("GzIp")),
        (0, true, Some("gzip"), Some("gzip")),
        (0, true, Some("gzip"), Some("br")),
        (0, true, Some("br"), Some("gzip, br")),
        (0, true, Some("br"), Some("zstd")),
        (0, true, Some("br"), Some("dcz")),
        (0, true, Some("br"), Some("nonsense")),
        (0, true, None, Some("gzip")),
        (0, true, Some("gzip"), None),
        (0, false, Some("br"), Some("gzip")),
        (6, false, Some("br"), Some("gzip")),
        (6, true, Some("br"), Some("gzip")),
        (6, true, Some("gzip"), None),
        (6, true, None, None),
        (0, false, None, None),
    ] {
        let mut ctx = ctx_for_test(level, decompress, accept_encoding);
        let mut resp = resp_for_test(200, content_encoding);
        let predicted = ctx.will_decompress(&resp);

        ctx.response_header_filter(&mut resp, false);
        let decompressed = resp.headers.get(http::header::CONTENT_ENCODING).is_none()
            && resp
                .headers
                .get(http::header::TRANSFER_ENCODING)
                .is_some_and(|te| te.as_bytes() == b"chunked");

        assert_eq!(
            predicted, decompressed,
            "will_decompress() mismatch for level {level}, decompress {decompress}, \
             accept-encoding {accept_encoding:?}, content-encoding {content_encoding:?}"
        );
    }
}

use once_cell::sync::Lazy;
use regex::Regex;

// Allow text, application, font, a few image/ MIME types and binary/octet-stream
// TODO: fine tune this list
static MIME_CHECK: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^(?:text/|application/|font/|image/(?:x-icon|svg\+xml|nd\.microsoft\.icon)|binary/octet-stream)")
        .unwrap()
});

// check if the response mime type is compressible
fn compressible(resp: &ResponseHeader) -> bool {
    // arbitrary size limit, things to consider
    // 1. too short body may have little redundancy to compress
    // 2. gzip header and footer overhead
    // 3. latency is the same as long as data fits in a TCP congestion window regardless of size
    const MIN_COMPRESS_LEN: usize = 20;

    // check if response is too small to compress
    if let Some(cl) = resp.headers.get(http::header::CONTENT_LENGTH) {
        if let Some(cl_num) = std::str::from_utf8(cl.as_bytes())
            .ok()
            .and_then(|v| v.parse::<usize>().ok())
        {
            if cl_num < MIN_COMPRESS_LEN {
                return false;
            }
        }
    }
    // no Content-Length or large enough, check content-type next
    if let Some(ct) = resp.headers.get(http::header::CONTENT_TYPE) {
        if let Ok(ct_str) = std::str::from_utf8(ct.as_bytes()) {
            if ct_str.contains("zip") {
                // heuristic: don't compress mime type that has zip in it
                false
            } else {
                // check if mime type in allow list
                MIME_CHECK.find(ct_str).is_some()
            }
        } else {
            false // invalid CT header, don't compress
        }
    } else {
        false // don't compress empty content-type
    }
}

/// Header name for the Available-Dictionary request header ([RFC 9842]).
/// TODO: Replace with http::header when available.
///
/// [RFC 9842]: https://datatracker.ietf.org/doc/html/rfc9842
static AVAILABLE_DICTIONARY: http::HeaderName =
    http::HeaderName::from_static("available-dictionary");

// add Vary header with the specified value or extend an existing Vary header value
fn add_vary_header(resp: &mut ResponseHeader, value: &http::header::HeaderName) {
    use http::header::{HeaderValue, VARY};

    let already_present = resp.headers.get_all(VARY).iter().any(|existing| {
        existing
            .as_bytes()
            .split(|b| *b == b',')
            .map(|v| v.trim_ascii())
            .any(|v| v == b"*" || v.eq_ignore_ascii_case(value.as_ref()))
    });

    if !already_present {
        resp.append_header(&VARY, HeaderValue::from_name(value.clone()))
            .unwrap();
    }
}

#[test]
fn test_add_vary_header() {
    let mut header = ResponseHeader::build(200, None).unwrap();
    add_vary_header(&mut header, &http::header::ACCEPT_ENCODING);
    assert_eq!(
        header
            .headers
            .get_all("Vary")
            .into_iter()
            .collect::<Vec<_>>(),
        vec!["accept-encoding"]
    );

    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("Vary", "Accept-Language").unwrap();
    add_vary_header(&mut header, &http::header::ACCEPT_ENCODING);
    assert_eq!(
        header
            .headers
            .get_all("Vary")
            .into_iter()
            .collect::<Vec<_>>(),
        vec!["Accept-Language", "accept-encoding"]
    );

    let mut header = ResponseHeader::build(200, None).unwrap();
    header
        .insert_header("Vary", "Accept-Language, Accept-Encoding")
        .unwrap();
    add_vary_header(&mut header, &http::header::ACCEPT_ENCODING);
    assert_eq!(
        header
            .headers
            .get_all("Vary")
            .into_iter()
            .collect::<Vec<_>>(),
        vec!["Accept-Language, Accept-Encoding"]
    );

    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("Vary", "*").unwrap();
    add_vary_header(&mut header, &http::header::ACCEPT_ENCODING);
    assert_eq!(
        header
            .headers
            .get_all("Vary")
            .into_iter()
            .collect::<Vec<_>>(),
        vec!["*"]
    );
}

fn adjust_response_header(resp: &mut ResponseHeader, action: &Action, preserve_etag: bool) {
    use http::header::{
        HeaderValue, ACCEPT_RANGES, CONTENT_ENCODING, CONTENT_LENGTH, ETAG, TRANSFER_ENCODING,
    };

    fn set_stream_headers(resp: &mut ResponseHeader) {
        // because the transcoding is streamed, content length is not known ahead
        resp.remove_header(&CONTENT_LENGTH);
        // remove Accept-Ranges header because range requests will no longer work
        resp.remove_header(&ACCEPT_RANGES);

        // we stream body now TODO: chunked is for h1 only
        resp.insert_header(&TRANSFER_ENCODING, HeaderValue::from_static("chunked"))
            .unwrap();
    }

    fn weaken_or_clear_etag(resp: &mut ResponseHeader) {
        // RFC9110: https://datatracker.ietf.org/doc/html/rfc9110#section-8.8.1
        // "a validator is weak if it is shared by two or more representations
        // of a given resource at the same time, unless those representations
        // have identical representation data"
        // Follow nginx gzip filter's example when changing content encoding:
        // - if the ETag is not a valid strong ETag, clear it (i.e. does not start with `"`)
        // - else, weaken it
        if let Some(etag) = resp.headers.get(&ETAG) {
            let etag_bytes = etag.as_bytes();
            if etag_bytes.starts_with(b"W/") {
                // this is already a weak ETag, noop
            } else if etag_bytes.starts_with(b"\"") {
                // strong ETag, weaken since we are changing the byte representation
                let weakened_etag = HeaderValue::from_bytes(&[b"W/", etag_bytes].concat())
                    .expect("valid header value prefixed with \"W/\" should remain valid");
                resp.insert_header(&ETAG, weakened_etag)
                    .expect("can insert weakened etag when etag was already valid");
            } else {
                // invalid strong ETag, just clear it
                // https://datatracker.ietf.org/doc/html/rfc9110#section-8.8.3
                // says the opaque-tag section needs to be a quoted string
                resp.remove_header(&ETAG);
            }
        }
    }

    match action {
        Action::Noop => { /* do nothing */ }
        Action::Decompress(_) => {
            resp.remove_header(&CONTENT_ENCODING);
            set_stream_headers(resp);
            if !preserve_etag {
                weaken_or_clear_etag(resp);
            }
        }
        Action::Compress(a) => {
            resp.insert_header(&CONTENT_ENCODING, HeaderValue::from_static(a.as_str()))
                .unwrap();
            set_stream_headers(resp);
            if !preserve_etag {
                weaken_or_clear_etag(resp);
            }
        }
    }
}

#[test]
fn test_adjust_response_header() {
    use Action::*;
    use Algorithm::*;

    // noop
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "20").unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    header.insert_header("accept-ranges", "bytes").unwrap();
    header.insert_header("etag", "\"abc123\"").unwrap();
    adjust_response_header(&mut header, &Noop, false);
    assert_eq!(
        header.headers.get("content-encoding").unwrap().as_bytes(),
        b"gzip"
    );
    assert_eq!(
        header.headers.get("content-length").unwrap().as_bytes(),
        b"20"
    );
    assert_eq!(
        header.headers.get("etag").unwrap().as_bytes(),
        b"\"abc123\""
    );
    assert!(header.headers.get("transfer-encoding").is_none());

    // decompress gzip
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "20").unwrap();
    header.insert_header("content-encoding", "gzip").unwrap();
    header.insert_header("accept-ranges", "bytes").unwrap();
    header.insert_header("etag", "\"abc123\"").unwrap();
    adjust_response_header(&mut header, &Decompress(Gzip), false);
    assert!(header.headers.get("content-encoding").is_none());
    assert!(header.headers.get("content-length").is_none());
    assert_eq!(
        header.headers.get("transfer-encoding").unwrap().as_bytes(),
        b"chunked"
    );
    assert!(header.headers.get("accept-ranges").is_none());
    assert_eq!(
        header.headers.get("etag").unwrap().as_bytes(),
        b"W/\"abc123\""
    );
    // when preserve_etag on, strong etag is kept
    header.insert_header("etag", "\"abc123\"").unwrap();
    adjust_response_header(&mut header, &Decompress(Gzip), true);
    assert_eq!(
        header.headers.get("etag").unwrap().as_bytes(),
        b"\"abc123\""
    );

    // compress
    let mut header = ResponseHeader::build(200, None).unwrap();
    header.insert_header("content-length", "20").unwrap();
    header.insert_header("accept-ranges", "bytes").unwrap();
    // try invalid etag, should be cleared
    header.insert_header("etag", "abc123").unwrap();
    adjust_response_header(&mut header, &Compress(Gzip), false);
    assert_eq!(
        header.headers.get("content-encoding").unwrap().as_bytes(),
        b"gzip"
    );
    assert!(header.headers.get("content-length").is_none());
    assert!(header.headers.get("accept-ranges").is_none());
    assert_eq!(
        header.headers.get("transfer-encoding").unwrap().as_bytes(),
        b"chunked"
    );
    assert!(header.headers.get("etag").is_none());
    // when preserve_etag on, etag is kept
    header.insert_header("etag", "abc123").unwrap();
    adjust_response_header(&mut header, &Compress(Gzip), true);
    assert_eq!(header.headers.get("etag").unwrap().as_bytes(), b"abc123");
}

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

    const TEST_DICTIONARY: &[u8] = b"The quick brown fox jumps over the lazy dog. \
        Common HTTP headers: Content-Type, Accept-Encoding, Cache-Control. \
        JSON patterns: {\"key\": \"value\"}, [\"array\", \"items\"].";

    fn test_dictionary_hash() -> [u8; 32] {
        let mut hash = [0u8; 32];
        for (i, byte) in TEST_DICTIONARY.iter().take(32).enumerate() {
            hash[i] = *byte;
        }
        hash
    }

    #[test]
    fn set_and_clear_dictionary() {
        let mut ctx = ResponseCompressionCtx::new(3, false, false);
        assert!(!ctx.has_dictionary());

        ctx.set_dictionary(Bytes::from_static(TEST_DICTIONARY), test_dictionary_hash());
        assert!(ctx.has_dictionary());

        ctx.clear_dictionary();
        assert!(!ctx.has_dictionary());
    }

    #[test]
    fn dcz_compression_with_dictionary() {
        let mut ctx = ResponseCompressionCtx::new(3, false, false);
        let hash = test_dictionary_hash();
        ctx.set_dictionary(Bytes::from_static(TEST_DICTIONARY), hash);

        let mut req = RequestHeader::build("GET", b"/test.js", None).unwrap();
        req.insert_header("accept-encoding", "dcz, br, gzip")
            .unwrap();
        ctx.request_filter(&req);

        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.insert_header("content-type", "application/javascript")
            .unwrap();
        resp.insert_header("content-length", "1000").unwrap();
        ctx.response_header_filter(&mut resp, false);

        assert_eq!(
            resp.headers.get("content-encoding").unwrap().as_bytes(),
            b"dcz"
        );
        // RFC 9842: DCZ responses must vary on Available-Dictionary.
        assert!(resp.headers.get_all("vary").iter().any(|v| v
            .as_bytes()
            .split(|b| *b == b',')
            .any(|t| t.trim_ascii().eq_ignore_ascii_case(b"available-dictionary"))));

        let input = Bytes::from_static(b"The quick brown fox jumps over the lazy dog again.");
        let compressed = ctx.response_body_filter(Some(&input), true).unwrap();

        assert!(compressed.len() >= 40);
        assert_eq!(&compressed[..8], &zstd::DCZ_MAGIC);
        assert_eq!(&compressed[8..40], &hash);
    }

    #[test]
    fn dcz_without_dictionary_no_compression() {
        let mut ctx = ResponseCompressionCtx::new(3, false, false);

        let mut req = RequestHeader::build("GET", b"/test.js", None).unwrap();
        req.insert_header("accept-encoding", "dcz").unwrap();
        ctx.request_filter(&req);

        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.insert_header("content-type", "application/javascript")
            .unwrap();
        resp.insert_header("content-length", "1000").unwrap();
        ctx.response_header_filter(&mut resp, false);

        // no dictionary set, no compression applied
        assert!(resp.headers.get("content-encoding").is_none());
        // No compression → no Vary: available-dictionary.
        assert!(!resp.headers.get_all("vary").iter().any(|v| v
            .as_bytes()
            .split(|b| *b == b',')
            .any(|t| t.trim_ascii().eq_ignore_ascii_case(b"available-dictionary"))));
    }

    #[test]
    fn dcz_no_fallback_without_dictionary() {
        let mut ctx = ResponseCompressionCtx::new(3, false, false);

        let mut req = RequestHeader::build("GET", b"/test.js", None).unwrap();
        req.insert_header("accept-encoding", "dcz, br, gzip")
            .unwrap();
        ctx.request_filter(&req);

        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.insert_header("content-type", "application/javascript")
            .unwrap();
        resp.insert_header("content-length", "1000").unwrap();
        ctx.response_header_filter(&mut resp, false);

        // dcz first but no dictionary, no automatic fallback
        assert!(resp.headers.get("content-encoding").is_none());
        // No compression → no Vary: available-dictionary.
        assert!(!resp.headers.get_all("vary").iter().any(|v| v
            .as_bytes()
            .split(|b| *b == b',')
            .any(|t| t.trim_ascii().eq_ignore_ascii_case(b"available-dictionary"))));
    }

    #[test]
    fn maybe_compressor_with_dictionary_dcz_only() {
        let dict_data = DictionaryData {
            bytes: Bytes::from_static(TEST_DICTIONARY),
            hash: test_dictionary_hash(),
        };

        // only Dcz returns a compressor
        assert!(Algorithm::Dcz
            .maybe_compressor_with_dictionary(3, &dict_data)
            .is_some());
        assert!(Algorithm::Gzip
            .maybe_compressor_with_dictionary(3, &dict_data)
            .is_none());
        assert!(Algorithm::Brotli
            .maybe_compressor_with_dictionary(3, &dict_data)
            .is_none());
        assert!(Algorithm::Zstd
            .maybe_compressor_with_dictionary(3, &dict_data)
            .is_none());
        // level 0 disables
        assert!(Algorithm::Dcz
            .maybe_compressor_with_dictionary(0, &dict_data)
            .is_none());
    }

    #[test]
    fn dcz_full_flow() {
        let mut ctx = ResponseCompressionCtx::new(3, false, false);
        let hash = test_dictionary_hash();
        ctx.set_dictionary(Bytes::from_static(TEST_DICTIONARY), hash);

        let mut req = RequestHeader::build("GET", b"/app.js", None).unwrap();
        req.insert_header("accept-encoding", "dcz").unwrap();
        ctx.request_filter(&req);

        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.insert_header("content-type", "application/javascript")
            .unwrap();
        resp.insert_header("content-length", "500").unwrap();
        ctx.response_header_filter(&mut resp, false);

        assert_eq!(
            resp.headers.get("content-encoding").unwrap().as_bytes(),
            b"dcz"
        );
        assert!(resp.headers.get("content-length").is_none());
        assert_eq!(
            resp.headers.get("transfer-encoding").unwrap().as_bytes(),
            b"chunked"
        );
        // RFC 9842: DCZ responses must vary on Available-Dictionary.
        assert!(resp.headers.get_all("vary").iter().any(|v| v
            .as_bytes()
            .split(|b| *b == b',')
            .any(|t| t.trim_ascii().eq_ignore_ascii_case(b"available-dictionary"))));

        let chunk1 = Bytes::from_static(b"First chunk. ");
        let output1 = ctx.response_body_filter(Some(&chunk1), false);
        assert!(output1.is_some());

        let chunk2 = Bytes::from_static(b"Second chunk.");
        let output2 = ctx.response_body_filter(Some(&chunk2), true);
        assert!(output2.is_some());

        let (name, total_in, total_out, _) = ctx.get_info().unwrap();
        assert_eq!(name, "dcz");
        assert_eq!(total_in, chunk1.len() + chunk2.len());
        assert!(total_out > 0);
    }

    #[test]
    fn regular_compression_no_available_dictionary_vary() {
        // Gzip compression should produce Vary: Accept-Encoding but NOT
        // Vary: available-dictionary.
        let mut ctx = ResponseCompressionCtx::new(3, false, false);

        let mut req = RequestHeader::build("GET", b"/page.html", None).unwrap();
        req.insert_header("accept-encoding", "gzip").unwrap();
        ctx.request_filter(&req);

        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.insert_header("content-type", "text/html").unwrap();
        resp.insert_header("content-length", "1000").unwrap();
        ctx.response_header_filter(&mut resp, false);

        assert_eq!(
            resp.headers.get("content-encoding").unwrap().as_bytes(),
            b"gzip"
        );
        assert!(resp.headers.get_all("vary").iter().any(|v| v
            .as_bytes()
            .split(|b| *b == b',')
            .any(|t| t.trim_ascii().eq_ignore_ascii_case(b"accept-encoding"))));
        assert!(!resp.headers.get_all("vary").iter().any(|v| v
            .as_bytes()
            .split(|b| *b == b',')
            .any(|t| t.trim_ascii().eq_ignore_ascii_case(b"available-dictionary"))));
    }

    #[test]
    fn is_header_phase_after_header_and_body_transition() {
        let mut ctx = ResponseCompressionCtx::new(3, false, false);
        assert!(ctx.is_header_phase());

        let mut req = RequestHeader::build("GET", b"/", None).unwrap();
        req.insert_header("accept-encoding", "gzip").unwrap();
        ctx.request_filter(&req);
        assert!(ctx.is_header_phase());

        let mut cont = ResponseHeader::build(100, None).unwrap();
        ctx.response_header_filter(&mut cont, false);
        assert!(ctx.is_header_phase());

        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.insert_header("content-type", "text/plain").unwrap();
        resp.insert_header("content-length", "0").unwrap();
        ctx.response_header_filter(&mut resp, true);
        assert!(!ctx.is_header_phase());
    }
}