truss-image 0.25.0

Image toolkit with a shared Rust core across the CLI, HTTP server, and WASM demo.
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
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
use crate::TransformError;
use crate::core::error_class::ErrorClass;
use serde_json::json;
use std::io::{self, Write};
use std::net::TcpStream;

pub(super) const NOT_FOUND_BODY: &str =
    "{\"type\":\"about:blank\",\"title\":\"Not Found\",\"status\":404,\"detail\":\"not found\"}\n";

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct HttpResponse {
    pub(super) status: &'static str,
    pub(super) content_type: Option<&'static str>,
    pub(super) headers: Vec<(String, String)>,
    pub(super) body: Vec<u8>,
}

impl HttpResponse {
    pub(super) fn json(status: &'static str, body: Vec<u8>) -> Self {
        Self {
            status,
            content_type: Some("application/json"),
            headers: Vec::new(),
            body,
        }
    }

    /// Records the request id on the response: as the `X-Request-Id` header and, for a
    /// problem body, as its `requestId` member too, so a body that is logged or forwarded on
    /// its own still matches the server's access log line. The member is RFC 9457's
    /// extension mechanism; `instance` is not used because a client-supplied id need not be
    /// a URI.
    pub(super) fn attach_request_id(&mut self, request_id: &str) {
        self.headers
            .push(("X-Request-Id".to_string(), request_id.to_string()));
        if self.content_type != Some("application/problem+json") {
            return;
        }
        if let Ok(serde_json::Value::Object(mut problem)) =
            serde_json::from_slice::<serde_json::Value>(&self.body)
        {
            problem.insert(
                "requestId".to_string(),
                serde_json::Value::String(request_id.to_string()),
            );
            let mut body = serde_json::to_vec(&problem).expect("serialize problem body");
            body.push(b'\n');
            self.body = body;
        }
    }

    pub(super) fn problem(status: &'static str, body: Vec<u8>) -> Self {
        Self {
            status,
            content_type: Some("application/problem+json"),
            headers: Vec::new(),
            body,
        }
    }

    pub(super) fn binary_with_headers(
        status: &'static str,
        content_type: &'static str,
        headers: Vec<(String, String)>,
        body: Vec<u8>,
    ) -> Self {
        Self {
            status,
            content_type: Some(content_type),
            headers,
            body,
        }
    }

    pub(super) fn text(status: &'static str, content_type: &'static str, body: Vec<u8>) -> Self {
        Self {
            status,
            content_type: Some(content_type),
            headers: Vec::new(),
            body,
        }
    }

    pub(super) fn empty(status: &'static str, headers: Vec<(String, String)>) -> Self {
        Self {
            status,
            content_type: None,
            headers,
            body: Vec::new(),
        }
    }
}

/// Minimum body size (in bytes) below which gzip compression is skipped.
/// Very small bodies may actually grow when compressed due to gzip framing overhead.
const MIN_COMPRESS_BYTES: usize = 128;

/// Content types eligible for gzip compression.  Image types are excluded
/// because they are already compressed (JPEG, PNG, WebP, AVIF, etc.).
///
/// **Security note (BREACH):** If a future endpoint returns compressed
/// responses that mix attacker-controlled input with secret tokens, it may
/// be vulnerable to BREACH-style compression side-channel attacks. The
/// current endpoints (health, metrics, image transforms) do not include
/// secrets in the response body, so the risk is low today.
fn is_compressible_content_type(ct: &str) -> bool {
    let media_type = ct.split(';').next().unwrap_or("").trim();
    matches!(
        media_type,
        "application/json"
            | "application/problem+json"
            | "text/plain"
            | "application/openmetrics-text"
    )
}

/// How one answer is framed on the wire.
#[derive(Debug, Clone, Copy)]
pub(super) struct ResponseWriteOptions {
    /// The connection closes after this answer.
    pub(super) close: bool,
    /// The request was a HEAD, so the answer describes content it does not send.
    pub(super) is_head: bool,
    /// The client accepts gzip.
    pub(super) accepts_gzip: bool,
    pub(super) compression_level: u32,
}

impl ResponseWriteOptions {
    /// The framing for an answer written without content negotiation, which is every answer
    /// the server decides before it has read a request it can route.
    pub(super) fn closing(is_head: bool) -> Self {
        Self {
            close: true,
            is_head,
            accepts_gzip: false,
            compression_level: 1,
        }
    }
}

pub(super) fn write_response(
    stream: &mut TcpStream,
    response: HttpResponse,
    options: ResponseWriteOptions,
) -> io::Result<()> {
    use std::fmt::Write as FmtWrite;

    let ResponseWriteOptions {
        close,
        is_head,
        accepts_gzip,
        compression_level,
    } = options;

    let should_compress = accepts_gzip
        && response.body.len() >= MIN_COMPRESS_BYTES
        && response
            .content_type
            .is_some_and(is_compressible_content_type);

    let (body, is_compressed) = if should_compress {
        match gzip_compress(&response.body, compression_level) {
            Ok(compressed) if compressed.len() < response.body.len() => (compressed, true),
            _ => (response.body, false),
        }
    } else {
        (response.body, false)
    };

    // The declared length is the length of the content a GET would have received, which is
    // also the one thing a HEAD request is asking for. It is read after the compression
    // decision so that a compressed answer and a HEAD for the same resource agree.
    let content_length = body.len();
    let body = if is_head { Vec::new() } else { body };

    let connection_value = if close { "close" } else { "keep-alive" };
    let mut header = format!(
        "HTTP/1.1 {}\r\nContent-Length: {content_length}\r\nConnection: {connection_value}\r\n",
        response.status,
    );

    if let Some(content_type) = response.content_type {
        let _ = write!(header, "Content-Type: {content_type}\r\n");
    }

    if is_compressed {
        header.push_str("Content-Encoding: gzip\r\n");
    }

    // Collect Vary directives from response headers and compression, then emit
    // a single combined Vary header to avoid duplicate Vary lines.
    let mut vary_parts: Vec<&str> = Vec::new();
    if accepts_gzip
        && response
            .content_type
            .is_some_and(is_compressible_content_type)
    {
        vary_parts.push("Accept-Encoding");
    }
    for (name, value) in &response.headers {
        if name.eq_ignore_ascii_case("Vary") {
            for part in value.split(',') {
                let trimmed = part.trim();
                if !trimmed.is_empty()
                    && !vary_parts.iter().any(|v| v.eq_ignore_ascii_case(trimmed))
                {
                    vary_parts.push(trimmed);
                }
            }
        }
    }
    if !vary_parts.is_empty() {
        let _ = write!(header, "Vary: {}\r\n", vary_parts.join(", "));
    }

    for (name, value) in response.headers {
        if !name.eq_ignore_ascii_case("Vary") {
            let _ = write!(header, "{name}: {value}\r\n");
        }
    }

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

    stream.write_all(header.as_bytes())?;
    stream.write_all(&body)?;
    stream.flush()
}

fn gzip_compress(data: &[u8], level: u32) -> io::Result<Vec<u8>> {
    use flate2::Compression;
    use flate2::write::GzEncoder;

    let mut encoder = GzEncoder::new(Vec::new(), Compression::new(level));
    encoder.write_all(data)?;
    encoder.finish()
}

/// The response header that carries a transform warning, one header per warning.
///
/// It is the same text the CLI prints after `warning:` and the Wasm package returns in
/// `warnings`. The HTTP `Warning` field is deprecated by RFC 9111, and RFC 6648 retired the
/// `X-` prefix for new fields, which is how the name came to be this one.
pub(super) const WARNING_HEADER: &str = "Truss-Warning";

/// A warning's text as a header value: one line of visible ASCII.
///
/// A header cannot carry a line break, and the cache entry keeps the text on its first
/// line with a tab between warnings, so a tab, a carriage return, and a newline become a
/// space, and anything outside visible ASCII becomes `?`. The warnings truss raises are
/// ASCII already; this is what keeps a future one from breaking the framing.
pub(super) fn warning_header_value(text: &str) -> String {
    text.chars()
        .map(|c| match c {
            '\t' | '\r' | '\n' => ' ',
            ' '..='~' => c,
            _ => '?',
        })
        .collect()
}

/// Appends one [`WARNING_HEADER`] per warning.
pub(super) fn push_warning_headers(headers: &mut Vec<(String, String)>, warnings: &[String]) {
    for warning in warnings {
        headers.push((WARNING_HEADER.to_string(), warning_header_value(warning)));
    }
}

/// Where the problem types are described. Each [`ErrorClass`] is an anchor on this page.
pub(super) const PROBLEM_TYPES_URL: &str =
    "https://github.com/nao1215/truss/blob/main/docs/problems.md";

/// How RFC 9457 names a failure: `type` is a URI identifying the class, `title` is its fixed
/// short name, and `detail` describes the one occurrence. The class itself is
/// [`ErrorClass`], which the CLI and the Wasm adapter read from the same table, so a client
/// sees one classification whichever adapter it talks to.
///
/// A class added to [`ErrorClass`] needs its row in `docs/problems.md`, which is what the
/// `type` URI resolves to, and its `title` below.
impl ErrorClass {
    /// The fixed `title` of the class. RFC 9457 asks that it not change from one occurrence
    /// to the next, so nothing about the request goes in here; that is what `detail` is for.
    pub(super) const fn title(self) -> &'static str {
        match self {
            Self::InvalidRequest => "Invalid request",
            Self::InvalidOptions => "Invalid transform options",
            Self::InvalidInput => "Invalid input",
            Self::DecodeFailed => "Input could not be decoded",
            Self::UnsupportedMediaType => "Unsupported Media Type",
            Self::UnsupportedInputMediaType => "Unsupported input media type",
            Self::UnsupportedOutputMediaType => "Unsupported output media type",
            Self::EncodeFailed => "Output could not be encoded",
            Self::CapabilityMissing => "Capability not available",
            Self::LimitExceeded => "Limit exceeded",
            Self::Unauthorized => "Unauthorized",
            Self::Forbidden => "Forbidden",
            Self::NotFound => "Not Found",
            Self::MethodNotAllowed => "Method Not Allowed",
            Self::NotAcceptable => "Not Acceptable",
            Self::RequestTimeout => "Request Timeout",
            Self::PayloadTooLarge => "Payload Too Large",
            Self::UnprocessableEntity => "Unprocessable Entity",
            Self::TooManyRequests => "Too Many Requests",
            Self::InternalError => "Internal Server Error",
            Self::NotImplemented => "Not Implemented",
            Self::BadGateway => "Bad Gateway",
            Self::ServiceUnavailable => "Service Unavailable",
            Self::LoopDetected => "Loop Detected",
        }
    }

    /// The status line and the status code this class answers with.
    ///
    /// Every class has exactly one status, which is what lets `docs/problems.md` carry a
    /// status column, so the status is read from the class rather than repeated at each of
    /// the places that build a response.
    pub(super) const fn status(self) -> (&'static str, u16) {
        match self {
            Self::InvalidRequest
            | Self::InvalidOptions
            | Self::InvalidInput
            | Self::DecodeFailed => ("400 Bad Request", 400),
            Self::Unauthorized => ("401 Unauthorized", 401),
            Self::Forbidden => ("403 Forbidden", 403),
            Self::NotFound => ("404 Not Found", 404),
            Self::MethodNotAllowed => ("405 Method Not Allowed", 405),
            Self::NotAcceptable => ("406 Not Acceptable", 406),
            Self::RequestTimeout => ("408 Request Timeout", 408),
            Self::PayloadTooLarge | Self::LimitExceeded => ("413 Payload Too Large", 413),
            Self::UnsupportedMediaType
            | Self::UnsupportedInputMediaType
            | Self::UnsupportedOutputMediaType => ("415 Unsupported Media Type", 415),
            Self::UnprocessableEntity => ("422 Unprocessable Entity", 422),
            Self::TooManyRequests => ("429 Too Many Requests", 429),
            Self::InternalError | Self::EncodeFailed => ("500 Internal Server Error", 500),
            Self::NotImplemented | Self::CapabilityMissing => ("501 Not Implemented", 501),
            Self::BadGateway => ("502 Bad Gateway", 502),
            Self::ServiceUnavailable => ("503 Service Unavailable", 503),
            Self::LoopDetected => ("508 Loop Detected", 508),
        }
    }

    /// The `type` URI: the problem types page, at this class's anchor.
    pub(super) fn uri(self) -> String {
        format!("{PROBLEM_TYPES_URL}#{}", self.slug())
    }
}

/// The sentence for a JSON body truss could not turn into `what`.
///
/// `serde_json` reports a document that is not JSON and a document that is JSON and does not
/// match the schema through one error type, and one wording covered both, so a body with a
/// single value out of range was described as invalid JSON and sent the caller looking for a
/// syntax error that was not there. `classify` is what tells them apart.
pub(super) fn json_parse_message(what: &str, error: &serde_json::Error) -> String {
    match error.classify() {
        serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
            format!("{what} must be valid JSON: {error}")
        }
        serde_json::error::Category::Data | serde_json::error::Category::Io => {
            format!("{what} does not match the expected shape: {error}")
        }
    }
}

pub(super) fn bad_request_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::InvalidRequest, message)
}

pub(super) fn auth_required_response(message: &str) -> HttpResponse {
    let mut response = problem_response(ErrorClass::Unauthorized, message);
    response
        .headers
        .push(("WWW-Authenticate".to_string(), "Bearer".to_string()));
    response
}

pub(super) fn signed_url_unauthorized_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::Unauthorized, message)
}

pub(super) fn not_found_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::NotFound, message)
}

pub(super) fn forbidden_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::Forbidden, message)
}

pub(super) fn unsupported_media_type_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::UnsupportedMediaType, message)
}

/// Refuses a requested output format the pipeline cannot produce.
///
/// This is the class the transform itself raises for the same refusal, so a format truss
/// reads but cannot write is named the same way whether the server catches it in the options
/// or the encoder catches it later.
pub(super) fn unsupported_output_media_type_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::UnsupportedOutputMediaType, message)
}

pub(super) fn not_acceptable_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::NotAcceptable, message)
}

pub(super) fn unprocessable_entity_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::UnprocessableEntity, message)
}

pub(super) fn payload_too_large_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::PayloadTooLarge, message)
}

pub(super) fn request_timeout_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::RequestTimeout, message)
}

pub(super) fn internal_error_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::InternalError, message)
}

pub(super) fn bad_gateway_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::BadGateway, message)
}

/// Builds a 503, naming the delay after which a retry has a chance of succeeding.
///
/// `retry_after_secs` is `Some` when the condition clears on its own, which RFC 9110 section
/// 15.6.4 asks a 503 to say: without it a client retries immediately, and an immediate retry
/// adds to the load the answer was sent to shed. It is `None` when the condition is a
/// configuration the process cannot resolve by waiting, since naming a delay there would
/// invite a caller to poll something that will not change until an operator changes it.
pub(super) fn service_unavailable_response(
    message: &str,
    retry_after_secs: Option<u64>,
) -> HttpResponse {
    let mut resp = problem_response(ErrorClass::ServiceUnavailable, message);
    if let Some(secs) = retry_after_secs {
        resp.headers
            .push(("Retry-After".to_string(), secs.to_string()));
    }
    resp
}

pub(super) fn too_many_requests_response(message: &str) -> HttpResponse {
    let mut resp = problem_response(ErrorClass::TooManyRequests, message);
    // RFC 6585 section 4: include Retry-After so well-behaved clients back off.
    resp.headers
        .push(("Retry-After".to_string(), "1".to_string()));
    resp
}

pub(super) fn too_many_redirects_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::LoopDetected, message)
}

pub(super) fn not_implemented_response(message: &str) -> HttpResponse {
    problem_response(ErrorClass::NotImplemented, message)
}

/// Builds an RFC 9457 Problem Details error response.
///
/// The class carries the status, so a caller names only the class and the detail. The body is
/// `application/problem+json` with `type`, `title`, `status`, and `detail`, and gains
/// `requestId` when the response is sent, in [`HttpResponse::attach_request_id`]. The one
/// problem body that keeps `about:blank` as its `type` is [`NOT_FOUND_BODY`], for a route
/// that does not exist, where the status really is all there is to say.
pub(super) fn problem_response(class: ErrorClass, detail: &str) -> HttpResponse {
    let (status_line, _) = class.status();
    HttpResponse::problem(status_line, problem_detail_body(class, detail))
}

/// Serializes an RFC 9457 Problem Details JSON body.
pub(super) fn problem_detail_body(class: ErrorClass, detail: &str) -> Vec<u8> {
    let (_, status) = class.status();
    let mut body = serde_json::to_vec(&json!({
        "type": class.uri(),
        "title": class.title(),
        "status": status,
        "detail": crate::core::single_line(detail),
    }))
    .expect("serialize problem detail body");
    body.push(b'\n');
    body
}

/// Maps a transform failure onto the problem body that presents it.
///
/// The class comes from [`TransformError::class`], the one table the CLI and
/// `@nao1215/truss-wasm` also read, so the three adapters name a failure the same way, and
/// the class carries the status. Only the wording of `detail` is the server's own.
pub(super) fn transform_error_response(error: TransformError) -> HttpResponse {
    let class = error.class();
    let detail = match error {
        TransformError::EncodeFailed(reason) => {
            format!("failed to encode transformed artifact: {reason}")
        }
        TransformError::InvalidOptions(reason)
        | TransformError::InvalidInput(reason)
        | TransformError::DecodeFailed(reason)
        | TransformError::UnsupportedInputMediaType(reason)
        | TransformError::CapabilityMissing(reason)
        | TransformError::LimitExceeded(reason) => reason,
        // The error's own Display names the rule that was hit, so it is not restated here.
        ref error @ TransformError::UnsupportedOutputMediaType(_) => error.to_string(),
    };
    problem_response(class, &detail)
}

pub(super) fn map_source_io_error(error: io::Error) -> HttpResponse {
    match error.kind() {
        io::ErrorKind::NotFound => not_found_response("source artifact was not found"),
        _ => internal_error_response(&format!("failed to access source artifact: {error}")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{MediaType, TransformError};
    use rstest::rstest;
    use serde_json::Value;

    /// Parse the body of an HttpResponse as JSON.
    fn parse_body(response: &HttpResponse) -> Value {
        serde_json::from_slice(&response.body).expect("body should be valid JSON")
    }

    // ---------------------------------------------------------------
    // problem_detail_body
    // ---------------------------------------------------------------

    #[test]
    fn test_problem_detail_body_contains_required_fields() {
        let body = problem_detail_body(ErrorClass::NotFound, "resource missing");
        let v: Value = serde_json::from_slice(&body).expect("valid JSON");

        assert_eq!(v["type"], format!("{PROBLEM_TYPES_URL}#not-found"));
        assert_eq!(v["title"], "Not Found");
        assert_eq!(v["status"], 404);
        assert_eq!(v["detail"], "resource missing");
    }

    #[test]
    fn test_problem_detail_body_ends_with_newline() {
        let body = problem_detail_body(ErrorClass::InternalError, "boom");
        assert_eq!(*body.last().unwrap(), b'\n');
    }

    /// A message from a decoder in a dependency can carry a newline, which the CLI cannot
    /// print on one line and a reader of the JSON has no use for.
    #[test]
    fn problem_detail_body_folds_a_detail_that_leaves_its_line() {
        let body = problem_detail_body(
            ErrorClass::DecodeFailed,
            "Format error decoding Jpeg: Not enough bytes\n",
        );
        let value: serde_json::Value = serde_json::from_slice(&body).expect("parse the body");

        assert_eq!(
            value["detail"],
            "Format error decoding Jpeg: Not enough bytes"
        );
    }

    #[test]
    fn test_problem_detail_body_special_characters_in_detail() {
        let body = problem_detail_body(
            ErrorClass::InvalidRequest,
            "invalid <script>alert(1)</script>",
        );
        let v: Value = serde_json::from_slice(&body).expect("valid JSON");
        assert_eq!(v["detail"], "invalid <script>alert(1)</script>");
    }

    // ---------------------------------------------------------------
    // bad_request_response
    // ---------------------------------------------------------------

    #[test]
    fn test_bad_request_response_status_and_content_type() {
        let resp = bad_request_response("missing parameter");
        assert_eq!(resp.status, "400 Bad Request");
        assert_eq!(resp.content_type, Some("application/problem+json"));

        let v = parse_body(&resp);
        assert_eq!(v["status"], 400);
        assert_eq!(v["title"], "Invalid request");
        assert_eq!(v["detail"], "missing parameter");
    }

    // ---------------------------------------------------------------
    // not_found_response
    // ---------------------------------------------------------------

    #[test]
    fn test_not_found_response_status_and_body() {
        let resp = not_found_response("image not found");
        assert_eq!(resp.status, "404 Not Found");
        assert_eq!(resp.content_type, Some("application/problem+json"));

        let v = parse_body(&resp);
        assert_eq!(v["status"], 404);
        assert_eq!(v["title"], "Not Found");
        assert_eq!(v["detail"], "image not found");
    }

    // ---------------------------------------------------------------
    // internal_error_response
    // ---------------------------------------------------------------

    #[test]
    fn test_internal_error_response_status_and_body() {
        let resp = internal_error_response("disk full");
        assert_eq!(resp.status, "500 Internal Server Error");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 500);
        assert_eq!(v["title"], "Internal Server Error");
        assert_eq!(v["detail"], "disk full");
    }

    // ---------------------------------------------------------------
    // forbidden_response
    // ---------------------------------------------------------------

    #[test]
    fn test_forbidden_response_status_and_body() {
        let resp = forbidden_response("access denied");
        assert_eq!(resp.status, "403 Forbidden");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 403);
        assert_eq!(v["title"], "Forbidden");
        assert_eq!(v["detail"], "access denied");
    }

    // ---------------------------------------------------------------
    // unsupported_media_type_response
    // ---------------------------------------------------------------

    #[test]
    fn test_unsupported_media_type_response() {
        let resp = unsupported_media_type_response("image/gif is not supported");
        assert_eq!(resp.status, "415 Unsupported Media Type");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 415);
        assert_eq!(v["title"], "Unsupported Media Type");
    }

    // ---------------------------------------------------------------
    // not_acceptable_response
    // ---------------------------------------------------------------

    #[test]
    fn test_not_acceptable_response() {
        let resp = not_acceptable_response("no acceptable format");
        assert_eq!(resp.status, "406 Not Acceptable");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 406);
        assert_eq!(v["title"], "Not Acceptable");
    }

    // ---------------------------------------------------------------
    // payload_too_large_response
    // ---------------------------------------------------------------

    #[test]
    fn test_payload_too_large_response() {
        let resp = payload_too_large_response("exceeds 10MB limit");
        assert_eq!(resp.status, "413 Payload Too Large");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 413);
        assert_eq!(v["title"], "Payload Too Large");
        assert_eq!(v["detail"], "exceeds 10MB limit");
    }

    // ---------------------------------------------------------------
    // bad_gateway_response
    // ---------------------------------------------------------------

    #[test]
    fn test_bad_gateway_response() {
        let resp = bad_gateway_response("upstream error");
        assert_eq!(resp.status, "502 Bad Gateway");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 502);
        assert_eq!(v["title"], "Bad Gateway");
    }

    // ---------------------------------------------------------------
    // service_unavailable_response
    // ---------------------------------------------------------------

    #[test]
    fn test_service_unavailable_response() {
        let resp = service_unavailable_response("overloaded", Some(1));
        assert_eq!(resp.status, "503 Service Unavailable");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 503);
        assert_eq!(v["title"], "Service Unavailable");
    }

    // ---------------------------------------------------------------
    // too_many_requests_response
    // ---------------------------------------------------------------

    #[test]
    fn test_too_many_requests_response_includes_retry_after() {
        let resp = too_many_requests_response("rate limit exceeded");
        assert_eq!(resp.status, "429 Too Many Requests");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 429);
        assert_eq!(v["title"], "Too Many Requests");

        let retry_after = resp.headers.iter().find(|(name, _)| name == "Retry-After");
        assert_eq!(retry_after.map(|(_, v)| v.as_str()), Some("1"));
    }

    /// A status a client is expected to retry has to say when, or the retry is immediate and
    /// adds to the load the response was sent to shed. RFC 9110 section 15.6.4 says so for
    /// 503 and RFC 6585 section 4 says so for 429; the table is what keeps the next builder
    /// of a retryable status from being added without one.
    #[rstest]
    #[case(too_many_requests_response("rate limit exceeded"), "429")]
    #[case(
        service_unavailable_response("too many concurrent transforms; retry later", Some(1)),
        "503"
    )]
    fn a_retryable_status_says_when_to_come_back(
        #[case] response: HttpResponse,
        #[case] status: &str,
    ) {
        assert!(
            response.status.starts_with(status),
            "{} is not {status}",
            response.status
        );
        let retry_after = response
            .headers
            .iter()
            .find(|(name, _)| name == "Retry-After")
            .map(|(_, value)| value.as_str());
        let seconds = retry_after
            .unwrap_or_else(|| panic!("{status} must carry Retry-After"))
            .parse::<u64>()
            .expect("Retry-After is a delay in seconds");
        assert!(seconds >= 1, "{status} must name a delay, got {seconds}");
    }

    /// A 503 whose cause is a configuration says nothing about when to come back, because
    /// waiting is not what resolves it.
    #[test]
    fn a_configuration_failure_names_no_delay() {
        let resp = service_unavailable_response("private API bearer token is not configured", None);
        assert_eq!(resp.status, "503 Service Unavailable");
        assert!(
            !resp.headers.iter().any(|(name, _)| name == "Retry-After"),
            "a misconfiguration does not clear by waiting"
        );
    }

    // ---------------------------------------------------------------
    // too_many_redirects_response
    // ---------------------------------------------------------------

    #[test]
    fn test_too_many_redirects_response() {
        let resp = too_many_redirects_response("redirect loop");
        assert_eq!(resp.status, "508 Loop Detected");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 508);
        assert_eq!(v["title"], "Loop Detected");
    }

    // ---------------------------------------------------------------
    // not_implemented_response
    // ---------------------------------------------------------------

    #[test]
    fn test_not_implemented_response() {
        let resp = not_implemented_response("feature unavailable");
        assert_eq!(resp.status, "501 Not Implemented");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 501);
        assert_eq!(v["title"], "Not Implemented");
        assert_eq!(v["detail"], "feature unavailable");
    }

    // ---------------------------------------------------------------
    // signed_url_unauthorized_response
    // ---------------------------------------------------------------

    #[test]
    fn test_signed_url_unauthorized_response_no_www_authenticate() {
        let resp = signed_url_unauthorized_response("bad signature");
        assert_eq!(resp.status, "401 Unauthorized");
        assert_eq!(resp.content_type, Some("application/problem+json"));
        // Unlike auth_required_response, this should NOT have WWW-Authenticate.
        assert!(resp.headers.is_empty());

        let v = parse_body(&resp);
        assert_eq!(v["status"], 401);
        assert_eq!(v["detail"], "bad signature");
    }

    // ---------------------------------------------------------------
    // auth_required_response - WWW-Authenticate header
    // ---------------------------------------------------------------

    #[test]
    fn test_auth_required_response_includes_www_authenticate_header() {
        let resp = auth_required_response("token required");
        assert_eq!(resp.status, "401 Unauthorized");
        assert_eq!(resp.content_type, Some("application/problem+json"));

        let www_auth = resp
            .headers
            .iter()
            .find(|(name, _)| *name == "WWW-Authenticate");
        assert!(www_auth.is_some(), "must include WWW-Authenticate header");
        assert_eq!(www_auth.unwrap().1, "Bearer");

        let v = parse_body(&resp);
        assert_eq!(v["status"], 401);
        assert_eq!(v["title"], "Unauthorized");
        assert_eq!(v["detail"], "token required");
    }

    // ---------------------------------------------------------------
    // transform_error_response
    // ---------------------------------------------------------------

    #[test]
    fn test_transform_error_response_invalid_input() {
        let resp = transform_error_response(TransformError::InvalidInput("bad input".into()));
        assert_eq!(resp.status, "400 Bad Request");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "bad input");
    }

    #[test]
    fn test_transform_error_response_invalid_options() {
        let resp = transform_error_response(TransformError::InvalidOptions("bad opts".into()));
        assert_eq!(resp.status, "400 Bad Request");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "bad opts");
    }

    #[test]
    fn test_transform_error_response_decode_failed() {
        let resp = transform_error_response(TransformError::DecodeFailed("corrupt".into()));
        assert_eq!(resp.status, "400 Bad Request");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "corrupt");
    }

    #[test]
    fn test_transform_error_response_unsupported_input_media_type() {
        let resp = transform_error_response(TransformError::UnsupportedInputMediaType(
            "image/gif".into(),
        ));
        assert_eq!(resp.status, "415 Unsupported Media Type");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "image/gif");
    }

    #[test]
    fn test_transform_error_response_unsupported_output_media_type() {
        // Only gif and svg reach this arm, and each is refused for its own reason, so the
        // detail names the rule instead of restating the format the caller already sent.
        let resp =
            transform_error_response(TransformError::UnsupportedOutputMediaType(MediaType::Gif));
        assert_eq!(resp.status, "415 Unsupported Media Type");
        let v = parse_body(&resp);
        assert_eq!(
            v["detail"],
            "gif is an input-only format; choose an output format such as png, jpeg, webp, or avif"
        );

        let resp =
            transform_error_response(TransformError::UnsupportedOutputMediaType(MediaType::Svg));
        assert_eq!(resp.status, "415 Unsupported Media Type");
        let v = parse_body(&resp);
        assert_eq!(
            v["detail"],
            "svg output requires an svg input; choose a raster output format such as png, jpeg, webp, or avif"
        );
    }

    #[test]
    fn test_transform_error_response_encode_failed() {
        let resp = transform_error_response(TransformError::EncodeFailed("out of memory".into()));
        assert_eq!(resp.status, "500 Internal Server Error");
        let v = parse_body(&resp);
        assert_eq!(
            v["detail"],
            "failed to encode transformed artifact: out of memory"
        );
    }

    #[test]
    fn test_transform_error_response_capability_missing() {
        let resp = transform_error_response(TransformError::CapabilityMissing(
            "AVIF not compiled".into(),
        ));
        assert_eq!(resp.status, "501 Not Implemented");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "AVIF not compiled");
    }

    #[test]
    fn test_transform_error_response_limit_exceeded() {
        let resp = transform_error_response(TransformError::LimitExceeded("too large".into()));
        assert_eq!(resp.status, "413 Payload Too Large");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "too large");
    }

    // ---------------------------------------------------------------
    // map_source_io_error
    // ---------------------------------------------------------------

    #[test]
    fn test_map_source_io_error_not_found() {
        let err = io::Error::new(io::ErrorKind::NotFound, "no such file");
        let resp = map_source_io_error(err);
        assert_eq!(resp.status, "404 Not Found");
        let v = parse_body(&resp);
        assert_eq!(v["detail"], "source artifact was not found");
    }

    #[test]
    fn test_map_source_io_error_permission_denied() {
        let err = io::Error::new(io::ErrorKind::PermissionDenied, "forbidden");
        let resp = map_source_io_error(err);
        assert_eq!(resp.status, "500 Internal Server Error");
        let v = parse_body(&resp);
        let detail = v["detail"].as_str().unwrap();
        assert!(
            detail.starts_with("failed to access source artifact:"),
            "detail should describe the IO error, got: {detail}"
        );
    }

    #[test]
    fn test_map_source_io_error_other() {
        let err = io::Error::new(io::ErrorKind::ConnectionRefused, "refused");
        let resp = map_source_io_error(err);
        assert_eq!(resp.status, "500 Internal Server Error");
    }

    // ---------------------------------------------------------------
    // NOT_FOUND_BODY constant
    // ---------------------------------------------------------------

    #[test]
    fn test_not_found_body_is_valid_rfc7807_json() {
        let v: Value = serde_json::from_str(NOT_FOUND_BODY).expect("NOT_FOUND_BODY is valid JSON");
        assert_eq!(v["type"], "about:blank");
        assert_eq!(v["title"], "Not Found");
        assert_eq!(v["status"], 404);
        assert_eq!(v["detail"], "not found");
    }

    // ---------------------------------------------------------------
    // HttpResponse constructors
    // ---------------------------------------------------------------

    #[test]
    fn test_http_response_json_constructor() {
        let resp = HttpResponse::json("200 OK", b"{}".to_vec());
        assert_eq!(resp.status, "200 OK");
        assert_eq!(resp.content_type, Some("application/json"));
        assert!(resp.headers.is_empty());
        assert_eq!(resp.body, b"{}");
    }

    #[test]
    fn test_http_response_problem_constructor() {
        let resp = HttpResponse::problem("400 Bad Request", b"err".to_vec());
        assert_eq!(resp.content_type, Some("application/problem+json"));
        assert!(resp.headers.is_empty());
    }

    #[test]
    fn test_http_response_empty_constructor() {
        let headers = vec![("X-Custom".to_string(), "val".to_string())];
        let resp = HttpResponse::empty("204 No Content", headers);
        assert_eq!(resp.status, "204 No Content");
        assert!(resp.content_type.is_none());
        assert!(resp.body.is_empty());
        assert_eq!(resp.headers.len(), 1);
    }

    #[test]
    fn test_http_response_text_constructor() {
        let resp = HttpResponse::text("200 OK", "text/plain", b"hello".to_vec());
        assert_eq!(resp.content_type, Some("text/plain"));
        assert_eq!(resp.body, b"hello");
    }

    #[test]
    fn test_http_response_binary_with_headers_constructor() {
        let headers = vec![("Cache-Control".to_string(), "no-cache".to_string())];
        let resp =
            HttpResponse::binary_with_headers("200 OK", "image/png", headers, vec![0x89, 0x50]);
        assert_eq!(resp.content_type, Some("image/png"));
        assert_eq!(resp.headers.len(), 1);
        assert_eq!(resp.body, vec![0x89, 0x50]);
    }

    // ---------------------------------------------------------------
    // RFC 9457: every helper names its class in `type` and `title`
    // ---------------------------------------------------------------

    #[test]
    fn every_problem_response_names_its_class() {
        let responses = vec![
            (
                bad_request_response("x"),
                "invalid-request",
                "Invalid request",
                400,
            ),
            (
                auth_required_response("x"),
                "unauthorized",
                "Unauthorized",
                401,
            ),
            (
                signed_url_unauthorized_response("x"),
                "unauthorized",
                "Unauthorized",
                401,
            ),
            (forbidden_response("x"), "forbidden", "Forbidden", 403),
            (not_found_response("x"), "not-found", "Not Found", 404),
            (
                not_acceptable_response("x"),
                "not-acceptable",
                "Not Acceptable",
                406,
            ),
            (
                request_timeout_response("x"),
                "request-timeout",
                "Request Timeout",
                408,
            ),
            (
                payload_too_large_response("x"),
                "payload-too-large",
                "Payload Too Large",
                413,
            ),
            (
                unsupported_media_type_response("x"),
                "unsupported-media-type",
                "Unsupported Media Type",
                415,
            ),
            (
                unprocessable_entity_response("x"),
                "unprocessable-entity",
                "Unprocessable Entity",
                422,
            ),
            (
                too_many_requests_response("x"),
                "too-many-requests",
                "Too Many Requests",
                429,
            ),
            (
                internal_error_response("x"),
                "internal-error",
                "Internal Server Error",
                500,
            ),
            (
                not_implemented_response("x"),
                "not-implemented",
                "Not Implemented",
                501,
            ),
            (bad_gateway_response("x"), "bad-gateway", "Bad Gateway", 502),
            (
                service_unavailable_response("x", Some(1)),
                "service-unavailable",
                "Service Unavailable",
                503,
            ),
            (
                too_many_redirects_response("x"),
                "loop-detected",
                "Loop Detected",
                508,
            ),
        ];

        for (resp, slug, title, status) in &responses {
            assert_eq!(
                resp.content_type,
                Some("application/problem+json"),
                "{slug}"
            );
            let v = parse_body(resp);
            assert_eq!(v["type"], format!("{PROBLEM_TYPES_URL}#{slug}"), "{slug}");
            assert_eq!(v["title"], *title, "{slug}");
            assert_eq!(v["status"], *status, "{slug}");
            assert_eq!(v["detail"], "x", "{slug}");
        }
    }

    /// Every class has a section in `docs/problems.md` and a row in the table there naming
    /// the status it answers with.
    ///
    /// The `type` URI a caller reads resolves to that section, so a class with no section
    /// publishes a link to nothing, and the table is where a caller looks up what to branch
    /// on. Both are read out of the document rather than repeated here.
    #[test]
    fn every_class_has_its_section_and_its_status_in_the_problem_types_page() {
        const PROBLEM_DOCS: &str = include_str!("../../../docs/problems.md");
        // A Windows checkout has CRLF line endings, so the anchors are matched against the
        // text with the carriage returns taken out.
        let problem_docs = PROBLEM_DOCS.replace('\r', "");

        for class in ErrorClass::ALL {
            let slug = class.slug();
            assert!(
                problem_docs.contains(&format!("### {slug}\n")),
                "docs/problems.md has no section for {slug}"
            );
            let (_, status) = class.status();
            let row = problem_docs
                .lines()
                .find(|line| line.starts_with(&format!("| [{slug}](#{slug})")))
                .unwrap_or_else(|| panic!("docs/problems.md has no table row for {slug}"));
            let columns: Vec<&str> = row.split('|').map(str::trim).collect();
            assert_eq!(
                columns.get(3).copied(),
                Some(status.to_string().as_str()),
                "the row for {slug} names a status the class does not answer with: {row}"
            );
        }
    }

    /// The transform classes are the ones the CLI prints and the Wasm package reports as
    /// `kind`, one per variant, so the three adapters classify a failure the same way.
    #[test]
    fn transform_errors_map_onto_their_own_problem_types() {
        let cases = vec![
            (
                TransformError::InvalidOptions("o".into()),
                "invalid-options",
                "400 Bad Request",
            ),
            (
                TransformError::InvalidInput("i".into()),
                "invalid-input",
                "400 Bad Request",
            ),
            (
                TransformError::DecodeFailed("d".into()),
                "decode-failed",
                "400 Bad Request",
            ),
            (
                TransformError::UnsupportedInputMediaType("u".into()),
                "unsupported-input-media-type",
                "415 Unsupported Media Type",
            ),
            (
                TransformError::UnsupportedOutputMediaType(MediaType::Gif),
                "unsupported-output-media-type",
                "415 Unsupported Media Type",
            ),
            (
                TransformError::EncodeFailed("e".into()),
                "encode-failed",
                "500 Internal Server Error",
            ),
            (
                TransformError::CapabilityMissing("c".into()),
                "capability-missing",
                "501 Not Implemented",
            ),
            (
                TransformError::LimitExceeded("l".into()),
                "limit-exceeded",
                "413 Payload Too Large",
            ),
        ];

        for (error, slug, status) in cases {
            // The `type` is the class the error itself carries, not a second table the
            // server keeps: the CLI and the Wasm adapter read the same one.
            assert_eq!(error.class().slug(), slug, "{slug}");
            let resp = transform_error_response(error);
            assert_eq!(resp.status, status, "{slug}");
            let v = parse_body(&resp);
            assert_eq!(v["type"], format!("{PROBLEM_TYPES_URL}#{slug}"), "{slug}");
            assert_ne!(v["title"], "", "{slug}");
        }
    }

    /// A route that does not exist is the one body where the status is all there is.
    #[test]
    fn only_the_unknown_route_keeps_about_blank() {
        let v: Value = serde_json::from_str(NOT_FOUND_BODY).expect("valid JSON");
        assert_eq!(v["type"], "about:blank");
    }

    #[test]
    fn warning_header_value_is_one_line_of_visible_ascii() {
        assert_eq!(warning_header_value("plain text"), "plain text");
        assert_eq!(warning_header_value("a\tb\r\nc"), "a b  c");
        assert_eq!(warning_header_value("caf\u{e9} \u{7f}"), "caf? ?");

        let mut headers = Vec::new();
        push_warning_headers(&mut headers, &["one".to_string(), "two".to_string()]);
        assert_eq!(
            headers,
            vec![
                (WARNING_HEADER.to_string(), "one".to_string()),
                (WARNING_HEADER.to_string(), "two".to_string()),
            ]
        );
    }

    #[test]
    fn attach_request_id_sets_the_header_and_the_problem_member() {
        let mut problem = bad_request_response("x");
        problem.attach_request_id("req-1");
        assert!(
            problem
                .headers
                .contains(&("X-Request-Id".to_string(), "req-1".to_string()))
        );
        let v = parse_body(&problem);
        assert_eq!(v["requestId"], "req-1");
        assert_eq!(v["type"], format!("{PROBLEM_TYPES_URL}#invalid-request"));
        assert!(problem.body.ends_with(b"\n"));

        let mut image = HttpResponse::json("200 OK", b"{}".to_vec());
        image.attach_request_id("req-2");
        assert!(
            image
                .headers
                .contains(&("X-Request-Id".to_string(), "req-2".to_string()))
        );
        assert_eq!(
            image.body,
            b"{}".to_vec(),
            "only a problem body gains the member"
        );
    }

    // ---------------------------------------------------------------
    // compression helpers
    // ---------------------------------------------------------------

    #[test]
    fn test_is_compressible_json() {
        assert!(is_compressible_content_type("application/json"));
        assert!(is_compressible_content_type("application/problem+json"));
    }

    #[test]
    fn test_is_not_compressible_image() {
        assert!(!is_compressible_content_type("image/png"));
        assert!(!is_compressible_content_type("image/jpeg"));
        assert!(!is_compressible_content_type("image/webp"));
    }

    #[test]
    fn test_is_compressible_text() {
        assert!(is_compressible_content_type("text/plain"));
        assert!(is_compressible_content_type(
            "application/openmetrics-text; version=1.0.0; charset=utf-8"
        ));
    }

    #[test]
    fn test_gzip_compress_roundtrip() {
        use flate2::read::GzDecoder;
        use std::io::Read;

        let original = b"hello world, this is test data that should compress well. \
                        repeating repeating repeating repeating repeating repeating.";
        let compressed = gzip_compress(original, 1).unwrap();
        assert!(compressed.len() < original.len());

        let mut decoder = GzDecoder::new(&compressed[..]);
        let mut decompressed = Vec::new();
        decoder.read_to_end(&mut decompressed).unwrap();
        assert_eq!(decompressed, original);
    }

    #[test]
    fn test_not_compressible_unknown_type() {
        assert!(!is_compressible_content_type("application/octet-stream"));
        assert!(!is_compressible_content_type("video/mp4"));
    }

    // ---------------------------------------------------------------
    // compression threshold boundary (m12)
    // ---------------------------------------------------------------

    #[test]
    fn test_gzip_compress_below_threshold_skipped() {
        // Body of exactly MIN_COMPRESS_BYTES - 1 should NOT be compressed.
        let body = vec![b'x'; MIN_COMPRESS_BYTES - 1];
        let response = HttpResponse::json("200 OK", body.clone());
        let mut _stream_buf: Vec<u8> = Vec::new();
        // We can't call write_response_compressed directly with a Cursor
        // because it expects a TcpStream, so we test the decision logic.
        let should_compress = response.body.len() >= MIN_COMPRESS_BYTES
            && response
                .content_type
                .is_some_and(is_compressible_content_type);
        assert!(
            !should_compress,
            "body below threshold should not be compressed"
        );
    }

    #[test]
    fn test_gzip_compress_at_threshold_eligible() {
        // Body of exactly MIN_COMPRESS_BYTES should be eligible for compression.
        let body = vec![b'x'; MIN_COMPRESS_BYTES];
        let response = HttpResponse::json("200 OK", body);
        let should_compress = response.body.len() >= MIN_COMPRESS_BYTES
            && response
                .content_type
                .is_some_and(is_compressible_content_type);
        assert!(
            should_compress,
            "body at threshold should be eligible for compression"
        );
    }

    #[test]
    fn test_gzip_compress_above_threshold_eligible() {
        let body = vec![b'x'; MIN_COMPRESS_BYTES + 1];
        let response = HttpResponse::json("200 OK", body);
        let should_compress = response.body.len() >= MIN_COMPRESS_BYTES
            && response
                .content_type
                .is_some_and(is_compressible_content_type);
        assert!(
            should_compress,
            "body above threshold should be eligible for compression"
        );
    }

    // ---------------------------------------------------------------
    // write_response_compressed integration (m11)
    // ---------------------------------------------------------------

    /// Helper to capture the raw HTTP response bytes by using a connected
    /// socket pair.
    #[cfg(unix)]
    fn capture_response(response: HttpResponse, accepts_gzip: bool) -> Vec<u8> {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let mut client = std::net::TcpStream::connect(addr).unwrap();
        let (mut server_stream, _) = listener.accept().unwrap();

        write_response(
            &mut server_stream,
            response,
            ResponseWriteOptions {
                close: true,
                is_head: false,
                accepts_gzip,
                compression_level: 1,
            },
        )
        .unwrap();
        drop(server_stream);

        let mut buf = Vec::new();
        std::io::Read::read_to_end(&mut client, &mut buf).unwrap();
        buf
    }

    /// As `capture_response`, but for a chosen request method.
    #[cfg(unix)]
    fn capture_response_for_method(
        response: HttpResponse,
        accepts_gzip: bool,
        is_head: bool,
    ) -> Vec<u8> {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let mut client = std::net::TcpStream::connect(addr).unwrap();
        let (mut server_stream, _) = listener.accept().unwrap();

        write_response(
            &mut server_stream,
            response,
            ResponseWriteOptions {
                close: true,
                is_head,
                accepts_gzip,
                compression_level: 1,
            },
        )
        .unwrap();
        drop(server_stream);

        let mut buf = Vec::new();
        std::io::Read::read_to_end(&mut client, &mut buf).unwrap();
        buf
    }

    /// A HEAD answer reports the length a GET would have produced. RFC 9110 section 9.3.2
    /// asks for the same header fields as the GET, and the length is the one question HEAD
    /// is asked. Reporting zero told a caller nothing about the image it was sizing up.
    #[cfg(unix)]
    #[test]
    fn a_head_answer_reports_the_length_a_get_would_have_sent() {
        fn length_of(raw: &[u8]) -> (String, usize) {
            let text = String::from_utf8_lossy(raw);
            let head = text
                .split("\r\n\r\n")
                .next()
                .expect("a header block")
                .to_string();
            let declared = head
                .lines()
                .find_map(|line| line.strip_prefix("Content-Length: "))
                .expect("a declared length")
                .trim()
                .to_string();
            let body_start = text.find("\r\n\r\n").expect("a terminator") + 4;
            (declared, raw.len() - body_start)
        }

        // Small enough to be sent as is, and large enough to be compressed, since the length
        // a GET would have sent differs between the two.
        for body in [
            b"{\"ok\":true}".to_vec(),
            format!("{{\"data\":\"{}\"}}", "x".repeat(256)).into_bytes(),
        ] {
            for accepts_gzip in [false, true] {
                let get = capture_response_for_method(
                    HttpResponse::json("200 OK", body.clone()),
                    accepts_gzip,
                    false,
                );
                let head = capture_response_for_method(
                    HttpResponse::json("200 OK", body.clone()),
                    accepts_gzip,
                    true,
                );

                let (get_declared, get_body) = length_of(&get);
                let (head_declared, head_body) = length_of(&head);

                assert_eq!(
                    head_declared, get_declared,
                    "HEAD must report the GET length (gzip={accepts_gzip})"
                );
                assert_eq!(head_body, 0, "a HEAD answer carries no content");
                assert!(get_body > 0, "the GET answer carries its content");
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_write_response_compressed_applies_gzip() {
        use flate2::read::GzDecoder;
        use std::io::Read;

        // Create a JSON body large enough to be compressed.
        let body = format!("{{\"data\":\"{}\"}}", "x".repeat(256));
        let response = HttpResponse::json("200 OK", body.as_bytes().to_vec());
        let raw = capture_response(response, true);
        let raw_str = String::from_utf8_lossy(&raw);

        assert!(
            raw_str.contains("Content-Encoding: gzip"),
            "should contain Content-Encoding: gzip"
        );
        assert!(
            raw_str.contains("Vary: Accept-Encoding"),
            "should contain Vary header"
        );

        // Extract the body after the \r\n\r\n separator and decompress.
        let body_start = raw_str.find("\r\n\r\n").unwrap() + 4;
        let compressed_body = &raw[body_start..];
        let mut decoder = GzDecoder::new(compressed_body);
        let mut decompressed = String::new();
        decoder.read_to_string(&mut decompressed).unwrap();
        assert_eq!(decompressed, body);
    }

    #[cfg(unix)]
    #[test]
    fn test_write_response_compressed_skips_when_not_accepted() {
        let body = format!("{{\"data\":\"{}\"}}", "x".repeat(256));
        let response = HttpResponse::json("200 OK", body.as_bytes().to_vec());
        let raw = capture_response(response, false);
        let raw_str = String::from_utf8_lossy(&raw);

        assert!(
            !raw_str.contains("Content-Encoding: gzip"),
            "should NOT contain Content-Encoding: gzip"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_write_response_compressed_skips_small_body() {
        // Body smaller than MIN_COMPRESS_BYTES should not be compressed.
        let body = b"{\"ok\":true}".to_vec();
        let response = HttpResponse::json("200 OK", body);
        let raw = capture_response(response, true);
        let raw_str = String::from_utf8_lossy(&raw);

        assert!(
            !raw_str.contains("Content-Encoding: gzip"),
            "small body should not be compressed"
        );
        // Vary header should still be present for compressible content types.
        assert!(
            raw_str.contains("Vary: Accept-Encoding"),
            "Vary should be present for compressible type"
        );
    }
}