notedthat-api-http 0.5.0

HTTP API surface for NotedThat
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
//! HTTP API error types and JSON envelope.

use axum::Json;
use axum::http::header::{CONTENT_RANGE, RETRY_AFTER};
use axum::http::{HeaderName, StatusCode};
use axum::response::{IntoResponse, Response};
use notedthat_core::{Error as CoreError, StorageError};
use serde::Serialize;

/// HTTP-layer error — maps domain and storage errors to HTTP status codes.
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
    /// The request lacked valid Bearer credentials.
    #[error("unauthorized")]
    Unauthorized,
    /// The credential is valid, but the knowledge base's access policy does not
    /// grant this operation on this key.
    ///
    /// Distinct from [`Self::Unauthorized`] on purpose: `401` tells a caller
    /// that credentials might help, and `403` tells them that theirs are fine
    /// and the answer is still no. D43 reserved this code for exactly this.
    #[error("forbidden")]
    Forbidden,
    /// Indexer queue was full while enqueueing an upsert (PUT/COPY).
    #[error("indexer upsert backpressure")]
    IndexerBackpressureUpsert,
    /// Indexer queue was full while enqueueing a tombstone (DELETE).
    #[error("indexer tombstone backpressure")]
    IndexerBackpressureTombstone,
    /// A domain error from `notedthat-core`.
    #[error(transparent)]
    Core(#[from] CoreError),
    /// A storage-layer error not otherwise promoted to a top-level variant.
    ///
    /// Note: `StorageError::NotModified`, `StorageError::PreconditionFailed`, and
    /// `StorageError::RangeNotSatisfiable` are promoted via the manual `From<StorageError>`
    /// impl to top-level `ApiError` variants so that `IntoResponse` can emit the
    /// RFC-required headers (e.g. `Content-Range: bytes */N` for 416).
    #[error(transparent)]
    Storage(StorageError),
    /// A conditional PUT/DELETE failed because a precondition was not met.
    ///
    /// Maps to HTTP 412 Precondition Failed.
    #[error("precondition failed")]
    PreconditionFailed,
    /// The requested byte range could not be satisfied.
    ///
    /// `complete_length` is the total object size in bytes.  The `IntoResponse`
    /// impl emits `Content-Range: bytes */complete_length` per RFC 7233 §4.4.
    #[error("range not satisfiable")]
    RangeNotSatisfiable {
        /// Total object size in bytes.
        complete_length: u64,
    },
    /// The backend returned 304 Not Modified for a conditional GET/HEAD.
    ///
    /// Maps to HTTP 304 with no body, as required by RFC 7232 §4.1.
    #[error("not modified")]
    NotModified,
    /// The `Range:` header value could not be parsed per RFC 7233.
    ///
    /// Maps to HTTP 400 Bad Request.
    #[error("malformed range: {0}")]
    MalformedRange(String),
    /// A `Range: lines=…` header specified a range that exceeds the object's line count.
    ///
    /// Maps to HTTP 416 with `Content-Range: lines */<line_total>` and
    /// `X-Content-Range-Bytes: */<byte_total>` per the line-range extension.
    #[error("line range not satisfiable")]
    LineRangeNotSatisfiable {
        /// Total line count in the object.
        line_total: u64,
        /// Total byte count in the object.
        byte_total: u64,
    },
    /// A single-replace operation found no occurrence of `old_string`.
    #[error("no match found for old_string")]
    ReplaceNoMatch,
    /// A single-replace operation found multiple occurrences of `old_string`.
    #[error("multiple matches found ({count}); use replace_all to replace them all")]
    ReplaceAmbiguous {
        /// Number of occurrences found.
        count: u64,
    },
}

/// Promote specific `StorageError` variants to top-level `ApiError` variants so
/// that `IntoResponse` can emit the RFC-mandated response headers.
impl From<StorageError> for ApiError {
    fn from(e: StorageError) -> Self {
        match e {
            StorageError::NotModified => Self::NotModified,
            StorageError::PreconditionFailed => Self::PreconditionFailed,
            StorageError::RangeNotSatisfiable { complete_length } => {
                Self::RangeNotSatisfiable { complete_length }
            }
            other => Self::Storage(other),
        }
    }
}

impl From<notedthat_write::WriteError> for ApiError {
    fn from(e: notedthat_write::WriteError) -> Self {
        match e {
            notedthat_write::WriteError::Storage(e) => Self::Storage(e),
            notedthat_write::WriteError::TooLarge { size, limit }
            | notedthat_write::WriteError::PatchTooLarge { size, limit } => {
                Self::Core(CoreError::PayloadTooLarge { size, limit })
            }
            notedthat_write::WriteError::Path(e) => Self::Core(e),
            notedthat_write::WriteError::IndexerBackpressureUpsert => {
                Self::IndexerBackpressureUpsert
            }
            notedthat_write::WriteError::IndexerBackpressureTombstone => {
                Self::IndexerBackpressureTombstone
            }
            notedthat_write::WriteError::PatchLineOutOfRange {
                total_lines,
                total_bytes,
                ..
            } => Self::LineRangeNotSatisfiable {
                line_total: total_lines,
                byte_total: total_bytes,
            },
            notedthat_write::WriteError::PatchInvalidRange { message } => {
                Self::Core(CoreError::InvalidInput { message })
            }
            notedthat_write::WriteError::ReplaceNoMatch => Self::ReplaceNoMatch,
            notedthat_write::WriteError::ReplaceAmbiguous { count } => {
                Self::ReplaceAmbiguous { count }
            }
        }
    }
}

/// JSON error response body shape: `{ "error": "code", "message": "...", "request_id": "..." }`.
#[derive(Serialize)]
struct ErrorBody<'a> {
    error: &'a str,
    message: String,
    request_id: String,
}

#[derive(Serialize)]
struct ReplaceAmbiguousBody<'a> {
    error: &'a str,
    message: String,
    request_id: String,
    match_count: u64,
}

/// An [`ApiError`] paired with a `request_id` string so the JSON body and the
/// `x-request-id` response header both contain the same value.
pub struct ApiErrorResponse {
    /// The underlying error.
    pub error: ApiError,
    /// The request ID (from the `x-request-id` header via `tower-http`).
    pub request_id: String,
}

impl ApiErrorResponse {
    /// Build an unauthorized response with the provided request ID.
    #[must_use]
    pub fn unauthorized(request_id: String) -> Self {
        Self {
            error: ApiError::Unauthorized,
            request_id,
        }
    }
}

impl ApiError {
    fn status_and_code(&self) -> (StatusCode, &'static str) {
        match self {
            Self::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
            Self::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),
            Self::IndexerBackpressureUpsert | Self::IndexerBackpressureTombstone => {
                (StatusCode::SERVICE_UNAVAILABLE, "backend_unavailable")
            }
            Self::Core(CoreError::InvalidInput { .. }) => {
                (StatusCode::BAD_REQUEST, "invalid_request")
            }
            Self::Core(CoreError::NotFound { .. }) => (StatusCode::NOT_FOUND, "not_found"),
            Self::Core(CoreError::PayloadTooLarge { .. }) => {
                (StatusCode::PAYLOAD_TOO_LARGE, "payload_too_large")
            }
            Self::Core(CoreError::MalformedRange(_)) | Self::MalformedRange(_) => {
                (StatusCode::BAD_REQUEST, "malformed_range")
            }
            Self::LineRangeNotSatisfiable { .. }
            | Self::Core(CoreError::RangeNotSatisfiable { .. })
            | Self::RangeNotSatisfiable { .. } => {
                (StatusCode::RANGE_NOT_SATISFIABLE, "range_not_satisfiable")
            }
            Self::Core(CoreError::NotModified) | Self::NotModified => {
                (StatusCode::NOT_MODIFIED, "not_modified")
            }
            Self::Core(CoreError::PreconditionFailed) | Self::PreconditionFailed => {
                (StatusCode::PRECONDITION_FAILED, "precondition_failed")
            }
            Self::ReplaceNoMatch => (StatusCode::UNPROCESSABLE_ENTITY, "no_match"),
            Self::ReplaceAmbiguous { .. } => (StatusCode::UNPROCESSABLE_ENTITY, "ambiguous_match"),
            Self::Core(CoreError::BucketNameTooLong { .. } | CoreError::Config { .. }) => {
                (StatusCode::INTERNAL_SERVER_ERROR, "internal_error")
            }
            Self::Core(CoreError::Storage(e)) | Self::Storage(e) => Self::storage_status(e),
        }
    }

    fn storage_status(e: &StorageError) -> (StatusCode, &'static str) {
        match e {
            StorageError::NotFound { .. } | StorageError::BucketNotFound { .. } => {
                (StatusCode::NOT_FOUND, "not_found")
            }
            StorageError::BackendUnavailable { .. } => {
                (StatusCode::SERVICE_UNAVAILABLE, "backend_unavailable")
            }
            StorageError::NotModified => (StatusCode::NOT_MODIFIED, "not_modified"),
            StorageError::PreconditionFailed => {
                (StatusCode::PRECONDITION_FAILED, "precondition_failed")
            }
            StorageError::RangeNotSatisfiable { .. } => {
                (StatusCode::RANGE_NOT_SATISFIABLE, "range_not_satisfiable")
            }
            StorageError::Other { .. } => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
        }
    }

    /// Extract the `complete_length` for a 416 response, regardless of which
    /// wrapper the `RangeNotSatisfiable` error arrived in.
    fn range_not_satisfiable_length(&self) -> Option<u64> {
        match self {
            Self::RangeNotSatisfiable { complete_length }
            | Self::Storage(StorageError::RangeNotSatisfiable { complete_length })
            | Self::Core(CoreError::RangeNotSatisfiable { complete_length }) => {
                Some(*complete_length)
            }
            _ => None,
        }
    }

    /// Return `true` for all variants that map to HTTP 304 (empty body required).
    fn is_not_modified(&self) -> bool {
        matches!(
            self,
            Self::NotModified
                | Self::Storage(StorageError::NotModified)
                | Self::Core(CoreError::NotModified)
        )
    }
}

impl IntoResponse for ApiErrorResponse {
    fn into_response(self) -> Response {
        // Line-mode 416: emit Content-Range: lines */<total> + X-Content-Range-Bytes: */<total_bytes>.
        if let ApiError::LineRangeNotSatisfiable {
            line_total,
            byte_total,
        } = &self.error
        {
            return (
                StatusCode::RANGE_NOT_SATISFIABLE,
                [
                    (CONTENT_RANGE, format!("lines */{line_total}")),
                    (
                        HeaderName::from_static("x-content-range-bytes"),
                        format!("*/{byte_total}"),
                    ),
                ],
            )
                .into_response();
        }

        // 416 Range Not Satisfiable: RFC 7233 §4.4 requires
        // `Content-Range: bytes */N` and an empty body.
        if let Some(complete_length) = self.error.range_not_satisfiable_length() {
            let content_range = format!("bytes */{complete_length}");
            return (
                StatusCode::RANGE_NOT_SATISFIABLE,
                [(CONTENT_RANGE, content_range)],
            )
                .into_response();
        }

        // 304 Not Modified: RFC 7232 §4.1 forbids a message body.
        if self.error.is_not_modified() {
            return StatusCode::NOT_MODIFIED.into_response();
        }

        match &self.error {
            ApiError::Unauthorized => {
                let body = ErrorBody {
                    error: "unauthorized",
                    message: "provide a valid Bearer token in the Authorization header".to_string(),
                    request_id: self.request_id,
                };
                return (StatusCode::UNAUTHORIZED, Json(body)).into_response();
            }
            ApiError::IndexerBackpressureUpsert => {
                let body = ErrorBody {
                    error: "backend_unavailable",
                    message: "object stored; indexer queue full — retry to re-enqueue".to_string(),
                    request_id: self.request_id,
                };
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    [(RETRY_AFTER, "5")],
                    Json(body),
                )
                    .into_response();
            }
            ApiError::IndexerBackpressureTombstone => {
                let body = ErrorBody {
                    error: "backend_unavailable",
                    message: "deleted from storage; retry to clear from search index".to_string(),
                    request_id: self.request_id,
                };
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    [(RETRY_AFTER, "5")],
                    Json(body),
                )
                    .into_response();
            }
            ApiError::ReplaceAmbiguous { count } => {
                let body = ReplaceAmbiguousBody {
                    error: "ambiguous_match",
                    message: self.error.to_string(),
                    request_id: self.request_id,
                    match_count: *count,
                };
                return (StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response();
            }
            _ => {}
        }

        // All other variants return a JSON error body.
        let (status, code) = self.error.status_and_code();
        let message = self.error.to_string();
        let body = ErrorBody {
            error: code,
            message,
            request_id: self.request_id,
        };
        (status, Json(body)).into_response()
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        ApiErrorResponse {
            error: self,
            request_id: "unknown".to_string(),
        }
        .into_response()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::{Body, to_bytes};
    use axum::http::Request;
    use bytes::Bytes;
    use notedthat_core::{ConditionalHeaders, KbSlug, ObjectPath, Storage};
    use notedthat_indexer::IndexEvent;
    use notedthat_write::WriteError;
    use std::collections::BTreeMap;
    use std::sync::Arc;
    use tower::util::ServiceExt;

    const KB: &str = "notes";
    const TOKEN: &str = "test-token-abc";

    fn router() -> axum::Router {
        router_with_max_patchable_size(16 * 1024 * 1024)
    }

    fn router_with_max_patchable_size(max_patchable_size: u64) -> axum::Router {
        let kb = KbSlug::try_new(KB).unwrap();
        let mut kbs = BTreeMap::new();
        kbs.insert(KB.to_string(), kb);
        let (indexer_tx, mut rx) = tokio::sync::mpsc::channel(16);
        tokio::spawn(async move { while rx.recv().await.is_some() {} });

        crate::router::build_router(crate::state::AppState {
            storage: Arc::new(crate::testing::InMemoryStorage::default()),
            access_policies: Arc::new(notedthat_core::signed_in_policies(&kbs)),
            declared_kbs: Arc::new(kbs),
            bearer_token: Arc::new(TOKEN.to_string()),
            max_body_size: 16 * 1024 * 1024,
            max_patchable_size,
            indexer_tx,
            searcher: Arc::new(crate::testing::NoopSearcher),
        })
    }

    fn router_with_storage_and_indexer(
        storage: Arc<dyn Storage>,
        kb: KbSlug,
        max_patchable_size: u64,
        indexer_tx: tokio::sync::mpsc::Sender<IndexEvent>,
    ) -> axum::Router {
        let mut kbs = BTreeMap::new();
        kbs.insert(KB.to_string(), kb);
        crate::router::build_router(crate::state::AppState {
            storage,
            access_policies: Arc::new(notedthat_core::signed_in_policies(&kbs)),
            declared_kbs: Arc::new(kbs),
            bearer_token: Arc::new(TOKEN.to_string()),
            max_body_size: 16 * 1024 * 1024,
            max_patchable_size,
            indexer_tx,
            searcher: Arc::new(crate::testing::NoopSearcher),
        })
    }

    async fn put_object(router: axum::Router, path: &str, body: &'static [u8]) -> String {
        let response = router
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/v1/knowledgebases/{KB}/{path}"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "text/markdown")
                    .body(Body::from(Bytes::from_static(body)))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::CREATED);
        response
            .headers()
            .get(axum::http::header::ETAG)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string()
    }

    async fn get_object(router: axum::Router, path: &str) -> Bytes {
        let response = router
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(format!("/api/v1/knowledgebases/{KB}/{path}"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        to_bytes(response.into_body(), usize::MAX).await.unwrap()
    }

    async fn post_replace(
        router: axum::Router,
        path: &str,
        if_match: &str,
        body: &'static [u8],
    ) -> Response {
        router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/{path}"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .header(axum::http::header::IF_MATCH, if_match)
                    .body(Body::from(Bytes::from_static(body)))
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    async fn object_with_etag(
        storage: &crate::testing::InMemoryStorage,
        kb: &KbSlug,
        path: &str,
        body: &'static [u8],
    ) -> String {
        storage
            .put_object(
                kb,
                &ObjectPath::try_from_str(path).unwrap(),
                Bytes::from_static(body),
                Some("text/markdown"),
                ConditionalHeaders::default(),
            )
            .await
            .unwrap()
            .etag
            .unwrap()
    }

    async fn assert_invalid_request_response(response: Response) {
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "invalid_request");
    }

    #[tokio::test]
    async fn test_unauthorized_status_and_body() {
        let resp = ApiErrorResponse::unauthorized("req-123".to_string()).into_response();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "unauthorized");
        assert_eq!(json["request_id"], "req-123");
    }

    #[tokio::test]
    async fn test_not_found_status() {
        let err = ApiError::Core(CoreError::NotFound {
            resource: "foo".into(),
        });
        let resp = ApiErrorResponse {
            error: err,
            request_id: "rid".into(),
        }
        .into_response();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_payload_too_large_status() {
        let err = ApiError::Core(CoreError::PayloadTooLarge {
            size: 20_000_000,
            limit: 16_777_216,
        });
        let resp = ApiErrorResponse {
            error: err,
            request_id: "rid".into(),
        }
        .into_response();
        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
    }

    #[tokio::test]
    async fn test_request_id_in_body() {
        let err = ApiError::Core(CoreError::InvalidInput {
            message: "bad".into(),
        });
        let resp = ApiErrorResponse {
            error: err,
            request_id: "my-req-id".into(),
        }
        .into_response();
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["request_id"], "my-req-id");
    }

    #[tokio::test]
    async fn test_indexer_backpressure_upsert_503_body_and_retry_after() {
        let resp = ApiErrorResponse {
            error: ApiError::IndexerBackpressureUpsert,
            request_id: "rid".to_string(),
        }
        .into_response();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(resp.headers().get("retry-after").unwrap(), "5");
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "backend_unavailable");
        assert_eq!(
            json["message"],
            "object stored; indexer queue full — retry to re-enqueue"
        );
        assert_eq!(json["request_id"], "rid");
    }

    #[tokio::test]
    async fn test_indexer_backpressure_tombstone_503_body_and_retry_after() {
        let resp = ApiErrorResponse {
            error: ApiError::IndexerBackpressureTombstone,
            request_id: "rid".to_string(),
        }
        .into_response();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(resp.headers().get("retry-after").unwrap(), "5");
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "backend_unavailable");
        assert_eq!(
            json["message"],
            "deleted from storage; retry to clear from search index"
        );
        assert_eq!(json["request_id"], "rid");
    }

    #[test]
    fn test_from_write_error_indexer_backpressure() {
        assert!(matches!(
            ApiError::from(WriteError::IndexerBackpressureUpsert),
            ApiError::IndexerBackpressureUpsert
        ));
        assert!(matches!(
            ApiError::from(WriteError::IndexerBackpressureTombstone),
            ApiError::IndexerBackpressureTombstone
        ));
    }

    #[test]
    fn test_from_write_error_patch_too_large() {
        let api_err = ApiError::from(WriteError::PatchTooLarge {
            size: 200 * 1024 * 1024,
            limit: 100 * 1024 * 1024,
        });

        let (status, code) = api_err.status_and_code();
        assert_eq!(status.as_u16(), 413);
        assert_eq!(code, "payload_too_large");
    }

    #[test]
    fn test_from_write_error_patch_line_out_of_range() {
        let api_err = ApiError::from(WriteError::PatchLineOutOfRange {
            first: 999,
            last: 1000,
            total_lines: 20,
            total_bytes: 100,
        });

        let (status, code) = api_err.status_and_code();
        assert_eq!(status.as_u16(), 416);
        assert_eq!(code, "range_not_satisfiable");
    }

    #[test]
    fn test_from_write_error_patch_invalid_range() {
        let api_err = ApiError::from(WriteError::PatchInvalidRange {
            message: "test".into(),
        });

        let (status, code) = api_err.status_and_code();
        assert_eq!(status.as_u16(), 400);
        assert_eq!(code, "invalid_request");
    }

    #[test]
    fn test_from_write_error_replace_no_match() {
        let api_err = ApiError::from(WriteError::ReplaceNoMatch);

        let (status, code) = api_err.status_and_code();
        assert_eq!(status.as_u16(), 422);
        assert_eq!(code, "no_match");
    }

    #[test]
    fn test_from_write_error_replace_ambiguous() {
        let api_err = ApiError::from(WriteError::ReplaceAmbiguous { count: 3 });

        let (status, code) = api_err.status_and_code();
        assert_eq!(status.as_u16(), 422);
        assert_eq!(code, "ambiguous_match");
    }

    #[tokio::test]
    async fn test_ambiguous_match_body_includes_match_count() {
        let resp = ApiErrorResponse {
            error: ApiError::ReplaceAmbiguous { count: 3 },
            request_id: "req-1".into(),
        }
        .into_response();

        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "ambiguous_match");
        assert_eq!(json["match_count"], 3);
        assert_eq!(json["request_id"], "req-1");
    }

    #[tokio::test]
    async fn test_no_match_body_omits_match_count() {
        let resp = ApiErrorResponse {
            error: ApiError::ReplaceNoMatch,
            request_id: "req-1".into(),
        }
        .into_response();

        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "no_match");
        assert!(json.get("match_count").is_none());
    }

    #[tokio::test]
    async fn replace_missing_if_match_returns_400_invalid_request() {
        let response = router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/hello.md"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .body(Body::from(Bytes::from_static(
                        br#"{"old_string":"x","new_string":"y"}"#,
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_invalid_request_response(response).await;
    }

    #[tokio::test]
    async fn replace_if_match_star_returns_400() {
        let response = router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/hello.md"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .header(axum::http::header::IF_MATCH, "*")
                    .body(Body::from(Bytes::from_static(
                        br#"{"old_string":"x","new_string":"y"}"#,
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_invalid_request_response(response).await;
    }

    #[tokio::test]
    async fn replace_multi_value_if_match_returns_400() {
        let response = router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/hello.md"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .header(axum::http::header::IF_MATCH, "\"a\",\"b\"")
                    .body(Body::from(Bytes::from_static(
                        br#"{"old_string":"x","new_string":"y"}"#,
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_invalid_request_response(response).await;
    }

    #[tokio::test]
    async fn replace_malformed_json_body_returns_400() {
        let response = router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/hello.md"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .header(axum::http::header::IF_MATCH, "\"valid-etag\"")
                    .body(Body::from(Bytes::from_static(b"{invalid json")))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_invalid_request_response(response).await;
    }

    #[tokio::test]
    async fn replace_missing_old_string_field_returns_400() {
        let response = router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/hello.md"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .header(axum::http::header::IF_MATCH, "\"valid-etag\"")
                    .body(Body::from(Bytes::from_static(br#"{"new_string":"y"}"#)))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_invalid_request_response(response).await;
    }

    #[tokio::test]
    async fn replace_empty_old_string_returns_400() {
        let response = router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/api/v1/knowledgebases/{KB}/replace/hello.md"))
                    .header("authorization", format!("Bearer {TOKEN}"))
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .header(axum::http::header::IF_MATCH, "\"valid-etag\"")
                    .body(Body::from(Bytes::from_static(
                        br#"{"old_string":"","new_string":"y"}"#,
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_invalid_request_response(response).await;
    }

    #[tokio::test]
    async fn replace_single_match_happy_returns_200_with_etag_and_match_count() {
        let router = router();
        let etag = put_object(router.clone(), "hello.md", b"hello world").await;

        let response = post_replace(
            router.clone(),
            "hello.md",
            &etag,
            br#"{"old_string":"world","new_string":"planet"}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
        assert!(response.headers().get(axum::http::header::ETAG).is_some());
        assert_eq!(
            response.headers().get("content-location").unwrap(),
            "/api/v1/knowledgebases/notes/hello.md"
        );
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(json["etag"].as_str().is_some());
        assert_eq!(json["match_count"], 1);
        assert_eq!(json["total_bytes"], 12);
        assert_eq!(&get_object(router, "hello.md").await[..], b"hello planet");
    }

    #[tokio::test]
    async fn replace_no_match_returns_422_no_match() {
        let router = router();
        let etag = put_object(router.clone(), "hello.md", b"hello world").await;

        let response = post_replace(
            router.clone(),
            "hello.md",
            &etag,
            br#"{"old_string":"nonexistent","new_string":"x"}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "no_match");
        assert_eq!(&get_object(router, "hello.md").await[..], b"hello world");
    }

    #[tokio::test]
    async fn replace_ambiguous_returns_422_with_match_count() {
        let router = router();
        let etag = put_object(router.clone(), "hello.md", b"a b a").await;

        let response = post_replace(
            router.clone(),
            "hello.md",
            &etag,
            br#"{"old_string":"a","new_string":"Z"}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "ambiguous_match");
        assert_eq!(json["match_count"], 2);
        assert_eq!(&get_object(router, "hello.md").await[..], b"a b a");
    }

    #[tokio::test]
    async fn replace_all_true_multiple_matches_returns_200_with_count_2() {
        let router = router();
        let etag = put_object(router.clone(), "hello.md", b"a b a").await;

        let response = post_replace(
            router.clone(),
            "hello.md",
            &etag,
            br#"{"old_string":"a","new_string":"Z","replace_all":true}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["match_count"], 2);
        assert_eq!(json["total_bytes"], 5);
        assert_eq!(&get_object(router, "hello.md").await[..], b"Z b Z");
    }

    #[tokio::test]
    async fn replace_stale_etag_returns_412() {
        let router = router();
        put_object(router.clone(), "hello.md", b"hello world").await;

        let response = post_replace(
            router,
            "hello.md",
            "\"stale\"",
            br#"{"old_string":"world","new_string":"planet"}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED);
    }

    #[tokio::test]
    async fn replace_post_splice_size_over_cap_returns_413() {
        let router = router_with_max_patchable_size(20);
        let etag = put_object(router.clone(), "hello.md", b"1234567890").await;

        let response = post_replace(
            router,
            "hello.md",
            &etag,
            br#"{"old_string":"0","new_string":"abcdefghijklmnopqrstuvwxyz"}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "payload_too_large");
    }

    #[tokio::test]
    async fn replace_indexer_backpressure_returns_503_with_retry_after() {
        let kb = KbSlug::try_new(KB).unwrap();
        let storage = crate::testing::InMemoryStorage::default();
        let etag = object_with_etag(&storage, &kb, "hello.md", b"hello world").await;
        let (indexer_tx, _rx) = tokio::sync::mpsc::channel(1);
        indexer_tx
            .try_send(IndexEvent::Upsert {
                kb: kb.clone(),
                object_key: ObjectPath::try_from_str("queued.md").unwrap(),
                etag: "queued".to_string(),
                mtime: 0,
            })
            .unwrap();
        let router =
            router_with_storage_and_indexer(Arc::new(storage), kb, 16 * 1024 * 1024, indexer_tx);

        let response = post_replace(
            router,
            "hello.md",
            &etag,
            br#"{"old_string":"world","new_string":"planet"}"#,
        )
        .await;

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(response.headers().get("retry-after").unwrap(), "5");
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "backend_unavailable");
    }

    #[tokio::test]
    async fn test_precondition_failed_body_shape_unchanged() {
        let resp = ApiErrorResponse {
            error: ApiError::PreconditionFailed,
            request_id: "req-1".into(),
        }
        .into_response();

        assert_eq!(resp.status(), StatusCode::PRECONDITION_FAILED);
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let object = json.as_object().unwrap();
        assert_eq!(object.len(), 3);
        assert!(object.contains_key("error"));
        assert!(object.contains_key("message"));
        assert!(object.contains_key("request_id"));
    }

    // ─── New variant tests ────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_precondition_failed_412() {
        let resp = ApiError::PreconditionFailed.into_response();
        assert_eq!(resp.status(), StatusCode::PRECONDITION_FAILED);
    }

    #[tokio::test]
    async fn test_not_modified_304_empty_body() {
        let resp = ApiError::NotModified.into_response();
        assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        assert!(body.is_empty(), "304 must have an empty body");
    }

    #[tokio::test]
    async fn test_malformed_range_400() {
        let resp = ApiError::MalformedRange("bytes=abc".to_string()).into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// RFC 7233 §4.4: a 416 response MUST include `Content-Range: bytes */N`.
    #[tokio::test]
    async fn test_range_not_satisfiable_416_content_range_header() {
        let resp = ApiError::RangeNotSatisfiable {
            complete_length: 100,
        }
        .into_response();
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
        let cr = resp
            .headers()
            .get("content-range")
            .expect("content-range header must be present on 416");
        assert_eq!(cr.to_str().unwrap(), "bytes */100");
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        assert!(body.is_empty(), "416 body must be empty per RFC 7233 §4.4");
    }

    /// Same 416 check via the `ApiError::Storage(...)` wrapper (e.g. from router.rs
    /// call sites that use explicit wrapping instead of `Into::into`).
    #[tokio::test]
    async fn test_storage_range_not_satisfiable_416_content_range_header() {
        let resp = ApiError::Storage(StorageError::RangeNotSatisfiable {
            complete_length: 42,
        })
        .into_response();
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
        let cr = resp
            .headers()
            .get("content-range")
            .expect("content-range header must be present on 416");
        assert_eq!(cr.to_str().unwrap(), "bytes */42");
    }

    /// 304 from a wrapped `StorageError::NotModified` (explicit wrapping in router.rs).
    #[tokio::test]
    async fn test_storage_not_modified_304_empty_body() {
        let resp = ApiError::Storage(StorageError::NotModified).into_response();
        assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);
        let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        assert!(body.is_empty(), "304 must have an empty body");
    }

    /// `From<StorageError>` promotes `NotModified` to `ApiError::NotModified`.
    #[test]
    fn test_from_storage_error_not_modified() {
        let api_err = ApiError::from(StorageError::NotModified);
        assert!(matches!(api_err, ApiError::NotModified));
    }

    /// `From<StorageError>` promotes `PreconditionFailed` to `ApiError::PreconditionFailed`.
    #[test]
    fn test_from_storage_error_precondition_failed() {
        let api_err = ApiError::from(StorageError::PreconditionFailed);
        assert!(matches!(api_err, ApiError::PreconditionFailed));
    }

    /// `From<StorageError>` promotes `RangeNotSatisfiable` with the correct length.
    #[test]
    fn test_from_storage_error_range_not_satisfiable() {
        let api_err = ApiError::from(StorageError::RangeNotSatisfiable {
            complete_length: 999,
        });
        assert!(
            matches!(
                api_err,
                ApiError::RangeNotSatisfiable {
                    complete_length: 999
                }
            ),
            "expected RangeNotSatisfiable with complete_length=999, got {api_err:?}"
        );
    }

    /// Other `StorageError` variants must still be wrapped in `ApiError::Storage`.
    #[test]
    fn test_from_storage_error_other_wrapped() {
        let api_err = ApiError::from(StorageError::NotFound {
            key: "foo".to_string(),
        });
        assert!(matches!(api_err, ApiError::Storage(_)));
    }

    mod line_range_error {
        use super::*;
        use axum::body::Body;
        use axum::http::Request;
        use bytes::Bytes;
        use notedthat_core::KbSlug;
        use std::collections::BTreeMap;
        use std::sync::Arc;
        use tower::util::ServiceExt;

        const KB: &str = "notes";
        const TOKEN: &str = "test-token-abc";

        fn twenty_line_markdown() -> String {
            let mut body = String::new();
            for line in 1..=20 {
                std::fmt::Write::write_fmt(&mut body, format_args!("line {line:02}\n")).unwrap();
            }
            body
        }

        fn router() -> axum::Router {
            let kb = KbSlug::try_new(KB).unwrap();
            let mut kbs = BTreeMap::new();
            kbs.insert(KB.to_string(), kb);
            let (indexer_tx, mut rx) = tokio::sync::mpsc::channel(16);
            tokio::spawn(async move { while rx.recv().await.is_some() {} });

            crate::router::build_router(crate::state::AppState {
                storage: Arc::new(crate::testing::InMemoryStorage::default()),
                access_policies: Arc::new(notedthat_core::signed_in_policies(&kbs)),
                declared_kbs: Arc::new(kbs),
                bearer_token: Arc::new(TOKEN.to_string()),
                max_body_size: 16 * 1024 * 1024,
                max_patchable_size: 16 * 1024 * 1024,
                indexer_tx,
                searcher: Arc::new(crate::testing::NoopSearcher),
            })
        }

        async fn put_ranges_md(router: axum::Router) {
            let response = router
                .oneshot(
                    Request::builder()
                        .method("PUT")
                        .uri(format!("/api/v1/knowledgebases/{KB}/ranges.md"))
                        .header("authorization", format!("Bearer {TOKEN}"))
                        .header(axum::http::header::CONTENT_TYPE, "text/markdown")
                        .body(Body::from(Bytes::from(twenty_line_markdown())))
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::CREATED);
        }

        #[tokio::test]
        async fn malformed_line_range_returns_json_400() {
            let response = ApiError::MalformedRange("lines=abc".into()).into_response();

            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
            let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(json["error"], "malformed_range");
        }

        #[tokio::test]
        async fn line_range_not_satisfiable_returns_dual_headers_and_empty_body() {
            let response = ApiError::LineRangeNotSatisfiable {
                line_total: 20,
                byte_total: 100,
            }
            .into_response();

            assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
            assert_eq!(
                response.headers().get("content-range").unwrap(),
                "lines */20"
            );
            assert_eq!(
                response.headers().get("x-content-range-bytes").unwrap(),
                "*/100"
            );
            let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
            assert!(body.is_empty());
        }

        #[tokio::test]
        async fn out_of_range_line_get_returns_dual_headers_and_empty_body() {
            let router = router();
            put_ranges_md(router.clone()).await;

            let response = router
                .oneshot(
                    Request::builder()
                        .method("GET")
                        .uri(format!("/api/v1/knowledgebases/{KB}/ranges.md"))
                        .header("authorization", format!("Bearer {TOKEN}"))
                        .header(axum::http::header::RANGE, "lines=100-200")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
            assert_eq!(
                response.headers().get("content-range").unwrap(),
                "lines */20"
            );
            assert_eq!(
                response.headers().get("x-content-range-bytes").unwrap(),
                "*/160"
            );
            let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
            assert!(body.is_empty());
        }

        #[tokio::test]
        async fn byte_range_not_satisfiable_omits_line_byte_header() {
            let response = ApiError::RangeNotSatisfiable {
                complete_length: 100,
            }
            .into_response();

            assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
            assert_eq!(
                response.headers().get("content-range").unwrap(),
                "bytes */100"
            );
            assert!(response.headers().get("x-content-range-bytes").is_none());
        }

        #[test]
        fn patch_line_out_of_range_maps_to_line_range_not_satisfiable() {
            let error = ApiError::from(WriteError::PatchLineOutOfRange {
                first: 100,
                last: 200,
                total_lines: 20,
                total_bytes: 100,
            });

            assert!(matches!(
                error,
                ApiError::LineRangeNotSatisfiable {
                    line_total: 20,
                    byte_total: 100
                }
            ));
        }
    }
}