shardline-server 1.0.0

HTTP server boundary, runtime, and operator workflows for Shardline.
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
use std::{io::Error as IoError, num::TryFromIntError};

use axum::{
    Error as AxumError, Json,
    http::{HeaderValue, StatusCode, header::WWW_AUTHENTICATE},
    response::{IntoResponse, Response},
};
use serde::Serialize;
use serde_json::Error as JsonError;
use shardline_cache::ReconstructionCacheError;
use shardline_index::{
    FileRecordInvariantError, LocalIndexStoreError, MemoryIndexStoreError, MemoryRecordStoreError,
    PostgresMetadataStoreError, QuarantineCandidateError, RetentionHoldError, WebhookDeliveryError,
};
use shardline_protocol::{HashParseError, HttpRangeParseError, TokenCodecError};
pub use shardline_server_core::{
    InvalidLifecycleMetadataError, InvalidReconstructionResponseError, InvalidSerializedShardError,
    ParseStoredFileRecordError,
};
use shardline_storage::{LocalObjectStoreError, ObjectPrefixError, S3ObjectStoreError};
use thiserror::Error;
use tokio::task::JoinError;

use crate::{
    config::ServerConfigError, provider::ProviderServiceError, xet_adapter::XorbParseError,
};
use shardline_gc::GcError;
use shardline_oci_adapter::OciAdapterError;
use shardline_provider_events::ProviderEventsError;
use shardline_xet_adapter::XetAdapterError;

/// Object-storage subsystem failure.
#[derive(Debug, Error)]
pub enum ObjectStoreError {
    /// Local storage IO failed.
    #[error("local storage operation failed")]
    Local(#[from] LocalObjectStoreError),
    /// S3-compatible object-storage adapter access failed.
    #[error("s3 object storage adapter operation failed")]
    S3(#[from] S3ObjectStoreError),
    /// Object inventory prefix validation failed.
    #[error("object storage prefix validation failed")]
    Prefix(#[from] ObjectPrefixError),
    /// S3-compatible object storage was selected without concrete configuration.
    #[error("s3 object storage configuration is missing")]
    MissingS3Config,
    /// Stored object metadata disagreed with the expected transfer length.
    #[error("stored object length did not match indexed metadata")]
    StoredLengthMismatch,
    /// Storage migration found a content-addressed source object under the wrong key.
    #[error(
        "storage migration source object hash mismatch for key {key}: expected {expected_hash}, observed {observed_hash}"
    )]
    MigrationSourceHashMismatch {
        /// Content-addressed object key being migrated.
        key: String,
        /// Hash implied by the object key.
        expected_hash: String,
        /// Hash computed from the source object bytes.
        observed_hash: String,
    },
}

/// Metadata index subsystem failure.
#[derive(Debug, Error)]
pub enum IndexError {
    /// Index adapter access failed.
    #[error("index adapter operation failed")]
    Local(#[from] LocalIndexStoreError),
    /// In-memory index adapter access failed.
    #[error("memory index adapter operation failed")]
    MemoryIndex(#[from] MemoryIndexStoreError),
    /// In-memory record adapter access failed.
    #[error("memory record adapter operation failed")]
    MemoryRecord(#[from] MemoryRecordStoreError),
    /// Postgres metadata adapter access failed.
    #[error("postgres metadata adapter operation failed")]
    PostgresMetadata(#[from] PostgresMetadataStoreError),
    /// Retention hold input was invalid.
    #[error("retention hold input was invalid")]
    RetentionHold(#[from] RetentionHoldError),
    /// Quarantine candidate input was invalid.
    #[error("quarantine candidate input was invalid")]
    QuarantineCandidate(#[from] QuarantineCandidateError),
    /// Webhook delivery metadata was invalid.
    #[error("webhook delivery metadata was invalid")]
    WebhookDelivery(#[from] WebhookDeliveryError),
    /// Stored file metadata could not produce a valid reconstruction plan.
    #[error("stored file metadata was invalid")]
    FileRecordInvariant(#[from] FileRecordInvariantError),
    /// Lifecycle metadata was internally inconsistent.
    #[error("lifecycle metadata was internally inconsistent")]
    InvalidLifecycleMetadata(#[from] InvalidLifecycleMetadataError),
    /// A reconstruction response violated an internal protocol-shape invariant.
    #[error("reconstruction response invariant failed: {0}")]
    InvalidReconstructionResponse(#[from] InvalidReconstructionResponseError),
    /// A required metadata table was missing.
    #[error("required metadata table is missing: {0}")]
    MissingRequiredMetadataTable(String),
    /// Repository rename encountered conflicting target-scope metadata.
    #[error("repository rename target already contains conflicting metadata")]
    ConflictingRenameTargetRecord,
}

/// Server runtime failure.
///
/// This is the unified error type for the Shardline server layer. It maps
/// domain-specific errors from storage, indexing, protocol, auth, and OCI
/// subsystems into a single enum with HTTP status code mapping.
///
/// # Design
///
/// Each variant maps to exactly one HTTP status code via [`ServerError::status_code`].
/// Subsystem errors (e.g., [`LocalIndexStoreError`], [`S3ObjectStoreError`]) are
/// converted via `From` implementations for ergonomic `?` usage.
///
/// When adding new error sources, prefer adding a new variant with a `#[from]`
/// attribute over manual `From` implementations unless the source error maps
/// to multiple variants.
#[derive(Debug, Error)]
pub enum ServerError {
    /// Local storage IO failed.
    #[error("local storage operation failed")]
    Io(#[from] IoError),
    /// JSON serialization or deserialization failed.
    #[error("json operation failed")]
    Json(#[from] JsonError),
    /// Request body streaming failed.
    #[error("request body stream failed")]
    RequestBodyRead(#[source] AxumError),
    /// Request body exceeded the configured maximum accepted byte count.
    #[error("request body exceeded the configured maximum accepted byte count")]
    RequestBodyTooLarge,
    /// Request query exceeded the bounded metadata parser budget.
    #[error("request query exceeded the bounded metadata parser budget")]
    RequestQueryTooLarge,
    /// Request body frame slicing exceeded checked bounds.
    #[error("request body frame exceeded checked bounds")]
    RequestBodyFrameOutOfBounds,
    /// Numeric conversion exceeded supported bounds.
    #[error("numeric conversion exceeded supported bounds")]
    NumericConversion(#[from] TryFromIntError),
    /// Hash parsing failed.
    #[error("invalid content hash")]
    HashParse(#[from] HashParseError),
    /// Object-storage subsystem failure.
    #[error("object storage operation failed")]
    ObjectStore(#[from] ObjectStoreError),
    /// Metadata index subsystem failure.
    #[error("index adapter operation failed")]
    Index(#[from] IndexError),
    /// Stored file metadata exceeded the bounded parser ceiling.
    #[error("stored file metadata exceeded the bounded parser ceiling")]
    StoredFileMetadataTooLarge {
        /// Observed file length in bytes.
        observed_bytes: u64,
        /// Maximum accepted file length in bytes.
        maximum_bytes: u64,
    },
    /// Stored file metadata changed after bounded validation.
    #[error("stored file metadata length did not match the validated length")]
    StoredFileMetadataLengthMismatch,
    /// A file identifier was unsafe.
    #[error(
        "file identifier must be relative and must not contain traversal or control characters"
    )]
    InvalidFileId,
    /// A content hash was malformed.
    #[error("content hash must be 64 hexadecimal characters")]
    InvalidContentHash,
    /// The xorb transfer path prefix was unsupported.
    #[error("xorb transfer prefix must be default")]
    InvalidXorbPrefix,
    /// The uploaded xorb bytes did not match the requested hash.
    #[error("xorb body hash did not match the requested path hash")]
    XorbHashMismatch,
    /// The uploaded xorb bytes were not a valid serialized xorb object.
    #[error("xorb body was not a valid serialized xorb object")]
    InvalidSerializedXorb,
    /// The uploaded shard bytes were not a valid serialized shard object.
    #[error("shard body was not a valid serialized shard object")]
    InvalidSerializedShard(#[from] InvalidSerializedShardError),
    /// A shard upload referenced a missing xorb.
    #[error("shard referenced a missing xorb")]
    MissingReferencedXorb,
    /// Shard metadata exceeded bounded parser safety limits.
    #[error("shard metadata exceeded bounded parser safety limits")]
    TooManyShardTerms,
    /// Batch reconstruction requested too many file identifiers.
    #[error("batch reconstruction requested too many file identifiers")]
    TooManyBatchReconstructionFileIds,
    /// Requested content was not found.
    #[error("content not found")]
    NotFound,
    /// Arithmetic overflowed a checked bound.
    #[error("arithmetic overflow")]
    Overflow,
    /// The reconstruction range header was malformed.
    #[error("range header must use bytes=<start>-<end> syntax")]
    InvalidRangeHeader,
    /// The reconstruction range start exceeded the end of the file.
    #[error("requested range is not satisfiable")]
    RangeNotSatisfiable,
    /// The request did not include an authorization header.
    #[error("authorization header is missing")]
    MissingAuthorization,
    /// The authorization header was malformed.
    #[error("authorization header must use bearer format")]
    InvalidAuthorizationHeader,
    /// The bearer token was invalid.
    #[error("bearer token was invalid")]
    InvalidToken(TokenCodecError),
    /// The bearer token did not grant the required scope.
    #[error("bearer token does not grant the required scope")]
    InsufficientScope,
    /// The provider issuance endpoint is not configured.
    #[error("provider token issuance endpoint is not configured")]
    ProviderTokensDisabled,
    /// The provider bootstrap key was missing.
    #[error("provider bootstrap key is missing")]
    MissingProviderApiKey,
    /// The provider bootstrap key was invalid.
    #[error("provider bootstrap key is invalid")]
    InvalidProviderApiKey,
    /// The provider subject was missing from a bootstrap request.
    #[error("provider subject is missing")]
    MissingProviderSubject,
    /// The provider token issuance request contained invalid bounded metadata.
    #[error("provider token request was invalid")]
    InvalidProviderTokenRequest,
    /// The provider webhook authentication header was missing.
    #[error("provider webhook authentication is missing")]
    MissingProviderWebhookAuthentication,
    /// The provider webhook authentication header was invalid.
    #[error("provider webhook authentication is invalid")]
    InvalidProviderWebhookAuthentication,
    /// The provider webhook payload was invalid.
    #[error("provider webhook payload was invalid")]
    InvalidProviderWebhookPayload,
    /// The requested provider is not configured.
    #[error("provider is not configured")]
    UnknownProvider,
    /// Provider authorization denied the request.
    #[error("provider denied requested repository access")]
    ProviderDenied,
    /// Provider token issuance failed due to configuration or adapter errors.
    #[error("provider token issuance failed")]
    Provider(#[from] ProviderServiceError),
    /// Reconstruction cache adapter access failed.
    #[error("reconstruction cache adapter operation failed")]
    ReconstructionCache(#[from] ReconstructionCacheError),
    /// Server configuration was invalid for the selected runtime surface.
    #[error("server configuration was invalid")]
    Config(#[from] ServerConfigError),
    /// The uploaded body did not match the expected SHA-256 identifier.
    #[error("uploaded body hash did not match the expected sha256")]
    ExpectedBodyHashMismatch,
    /// A digest string was malformed.
    #[error("digest must use sha256:<64 lowercase hex> format")]
    InvalidDigest,
    /// A repository name or namespace path was malformed.
    #[error("repository name was invalid")]
    InvalidRepositoryName,
    /// A manifest reference or tag was malformed.
    #[error("manifest reference was invalid")]
    InvalidManifestReference,
    /// The requested representation does not match any accepted media type.
    #[error("requested representation was not acceptable")]
    NotAcceptable,
    /// The request requires a protocol-specific authentication challenge.
    #[error("authorization challenge required")]
    UnauthorizedChallenge(String),
    /// An upload session identifier was malformed.
    #[error("upload session identifier was invalid")]
    InvalidUploadSession,
    /// Too many OCI upload sessions are currently active.
    #[error("too many active oci upload sessions")]
    TooManyUploadSessions,
    /// Too many OCI registry token exchanges are currently active.
    #[error("too many active oci registry token requests")]
    TooManyRegistryTokenRequests,
    /// Redis reconstruction cache was selected without a URL.
    #[error("redis reconstruction cache requires a redis url")]
    MissingReconstructionCacheRedisUrl,
    /// The transfer concurrency limiter was unexpectedly unavailable.
    #[error("transfer concurrency limiter is unavailable")]
    TransferLimiterClosed,
    /// A blocking worker task failed before it could finish storage work.
    #[error("blocking worker task failed")]
    BlockingTask(#[source] JoinError),
}

impl ServerError {
    const fn status_code(&self) -> StatusCode {
        match self {
            Self::InvalidFileId
            | Self::InvalidContentHash
            | Self::InvalidDigest
            | Self::InvalidRepositoryName
            | Self::InvalidManifestReference
            | Self::InvalidUploadSession
            | Self::InvalidXorbPrefix
            | Self::HashParse(_) => StatusCode::BAD_REQUEST,
            Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
            Self::UnauthorizedChallenge(_) => StatusCode::UNAUTHORIZED,
            Self::InvalidRangeHeader => StatusCode::BAD_REQUEST,
            Self::RangeNotSatisfiable => StatusCode::RANGE_NOT_SATISFIABLE,
            Self::XorbHashMismatch
            | Self::InvalidSerializedXorb
            | Self::InvalidSerializedShard(_)
            | Self::MissingReferencedXorb => StatusCode::BAD_REQUEST,
            Self::TooManyShardTerms
            | Self::TooManyBatchReconstructionFileIds
            | Self::RequestBodyTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
            Self::RequestQueryTooLarge => StatusCode::URI_TOO_LONG,
            Self::RequestBodyRead(_) | Self::RequestBodyFrameOutOfBounds => StatusCode::BAD_REQUEST,
            Self::ExpectedBodyHashMismatch => StatusCode::BAD_REQUEST,
            Self::NotFound | Self::UnknownProvider | Self::ProviderTokensDisabled => {
                StatusCode::NOT_FOUND
            }
            Self::MissingAuthorization
            | Self::InvalidAuthorizationHeader
            | Self::InvalidToken(_)
            | Self::MissingProviderApiKey
            | Self::MissingProviderSubject
            | Self::MissingProviderWebhookAuthentication => StatusCode::UNAUTHORIZED,
            Self::InsufficientScope
            | Self::InvalidProviderApiKey
            | Self::InvalidProviderWebhookAuthentication
            | Self::ProviderDenied => StatusCode::FORBIDDEN,
            Self::InvalidProviderTokenRequest | Self::InvalidProviderWebhookPayload => {
                StatusCode::BAD_REQUEST
            }
            Self::TooManyUploadSessions | Self::TooManyRegistryTokenRequests => {
                StatusCode::TOO_MANY_REQUESTS
            }
            Self::TransferLimiterClosed => StatusCode::SERVICE_UNAVAILABLE,
            Self::Io(_)
            | Self::Json(_)
            | Self::NumericConversion(_)
            | Self::ObjectStore(_)
            | Self::Index(_)
            | Self::StoredFileMetadataTooLarge { .. }
            | Self::StoredFileMetadataLengthMismatch
            | Self::Config(_)
            | Self::Overflow
            | Self::MissingReconstructionCacheRedisUrl
            | Self::ReconstructionCache(_)
            | Self::BlockingTask(_)
            | Self::Provider(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl IntoResponse for ServerError {
    fn into_response(self) -> Response {
        let status = self.status_code();
        let should_attach_default_challenge = matches!(
            self,
            Self::MissingAuthorization | Self::InvalidAuthorizationHeader | Self::InvalidToken(_)
        );
        let custom_challenge = if let Self::UnauthorizedChallenge(custom_header) = &self {
            Some(custom_header.as_str())
        } else {
            None
        };
        let body = ErrorBody {
            error: self.to_string(),
        };
        let mut response = (status, Json(body)).into_response();
        if let Some(custom_header) = custom_challenge {
            if let Ok(header_value) = HeaderValue::from_str(custom_header) {
                response
                    .headers_mut()
                    .insert(WWW_AUTHENTICATE, header_value);
            }
        } else if should_attach_default_challenge {
            response.headers_mut().insert(
                WWW_AUTHENTICATE,
                HeaderValue::from_static("Bearer realm=\"shardline\""),
            );
        }
        response
    }
}

impl From<HttpRangeParseError> for ServerError {
    fn from(value: HttpRangeParseError) -> Self {
        match value {
            HttpRangeParseError::Unsatisfiable => Self::RangeNotSatisfiable,
            HttpRangeParseError::MissingBytesUnit
            | HttpRangeParseError::InvalidSyntax
            | HttpRangeParseError::InvalidNumber => Self::InvalidRangeHeader,
        }
    }
}

impl From<XorbParseError> for ServerError {
    fn from(value: XorbParseError) -> Self {
        match value {
            XorbParseError::HashMismatch => Self::XorbHashMismatch,
            XorbParseError::InvalidFormat(_)
            | XorbParseError::NumericConversion(_)
            | XorbParseError::Io(_) => Self::InvalidSerializedXorb,
        }
    }
}

impl From<XetAdapterError> for ServerError {
    fn from(value: XetAdapterError) -> Self {
        match value {
            XetAdapterError::Io(e) => Self::Io(e),
            XetAdapterError::NumericConversion(e) => Self::NumericConversion(e),
            XetAdapterError::HashParse(e) => Self::HashParse(e),
            XetAdapterError::ObjectStore(e) => Self::from(e),
            XetAdapterError::LocalObjectStore(e) => Self::ObjectStore(ObjectStoreError::Local(e)),
            XetAdapterError::S3ObjectStore(e) => Self::ObjectStore(ObjectStoreError::S3(e)),
            XetAdapterError::IndexStore(e) => Self::Index(IndexError::Local(e)),
            XetAdapterError::MemoryIndexStore(e) => Self::Index(IndexError::MemoryIndex(e)),
            XetAdapterError::MemoryRecordStore(e) => Self::Index(IndexError::MemoryRecord(e)),
            XetAdapterError::PostgresMetadata(e) => Self::Index(IndexError::PostgresMetadata(e)),
            XetAdapterError::FileRecordInvariant(e) => {
                Self::Index(IndexError::FileRecordInvariant(e))
            }
            XetAdapterError::InvalidContentHash => Self::InvalidContentHash,
            XetAdapterError::InvalidXorbPrefix => Self::InvalidXorbPrefix,
            XetAdapterError::XorbHashMismatch => Self::XorbHashMismatch,
            XetAdapterError::InvalidSerializedXorb => Self::InvalidSerializedXorb,
            XetAdapterError::InvalidSerializedShard(e) => Self::InvalidSerializedShard(e),
            XetAdapterError::MissingReferencedXorb => Self::MissingReferencedXorb,
            XetAdapterError::TooManyShardTerms => Self::TooManyShardTerms,
            XetAdapterError::NotFound => Self::NotFound,
            XetAdapterError::Overflow => Self::Overflow,
            XetAdapterError::RangeNotSatisfiable => Self::RangeNotSatisfiable,
        }
    }
}

impl From<ProviderEventsError> for ServerError {
    fn from(value: ProviderEventsError) -> Self {
        match value {
            ProviderEventsError::Overflow => Self::Overflow,
            ProviderEventsError::InvalidContentHash => Self::InvalidContentHash,
            ProviderEventsError::InvalidProviderWebhookPayload => {
                Self::InvalidProviderWebhookPayload
            }
            ProviderEventsError::ConflictingRenameTargetRecord => {
                Self::Index(IndexError::ConflictingRenameTargetRecord)
            }
            ProviderEventsError::Json(e) => Self::Json(e),
            ProviderEventsError::NumericConversion(e) => Self::NumericConversion(e),
            ProviderEventsError::RetentionHold(e) => Self::Index(IndexError::RetentionHold(e)),
            ProviderEventsError::XetAdapter(e) => Self::from(e),
            ProviderEventsError::IndexStore(e) => Self::Index(IndexError::Local(e)),
            ProviderEventsError::MemoryIndexStore(e) => Self::Index(IndexError::MemoryIndex(e)),
            ProviderEventsError::MemoryRecordStore(e) => Self::Index(IndexError::MemoryRecord(e)),
            ProviderEventsError::PostgresMetadata(e) => {
                Self::Index(IndexError::PostgresMetadata(e))
            }
            ProviderEventsError::WebhookDelivery(e) => Self::Index(IndexError::WebhookDelivery(e)),
            ProviderEventsError::ObjectStore(e) => Self::from(e),
            ProviderEventsError::ParseStoredFileRecord(e) => Self::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                e.to_string(),
            )),
        }
    }
}

impl From<GcError> for ServerError {
    fn from(err: GcError) -> Self {
        match err {
            GcError::Io(e) => Self::Io(e),
            GcError::Json(e) => Self::Json(e),
            GcError::NumericConversion(e) => Self::NumericConversion(e),
            GcError::ObjectStore(e) => Self::from(e),
            GcError::LocalObjectStore(e) => Self::ObjectStore(ObjectStoreError::Local(e)),
            GcError::S3ObjectStore(e) => Self::ObjectStore(ObjectStoreError::S3(e)),
            GcError::ObjectPrefix(e) => Self::ObjectStore(ObjectStoreError::Prefix(e)),
            GcError::IndexStore(e) => Self::Index(IndexError::Local(e)),
            GcError::MemoryIndexStore(e) => Self::Index(IndexError::MemoryIndex(e)),
            GcError::MemoryRecordStore(e) => Self::Index(IndexError::MemoryRecord(e)),
            GcError::PostgresMetadata(e) => Self::Index(IndexError::PostgresMetadata(e)),
            GcError::RetentionHold(e) => Self::Index(IndexError::RetentionHold(e)),
            GcError::QuarantineCandidate(e) => Self::Index(IndexError::QuarantineCandidate(e)),
            GcError::WebhookDelivery(e) => Self::Index(IndexError::WebhookDelivery(e)),
            GcError::FileRecordInvariant(e) => Self::Index(IndexError::FileRecordInvariant(e)),
            GcError::InvalidLifecycleMetadata(e) => {
                Self::Index(IndexError::InvalidLifecycleMetadata(e))
            }
            GcError::InvalidContentHash => Self::InvalidContentHash,
            GcError::Overflow => Self::Overflow,
            GcError::XetAdapter(e) => Self::from(e),
        }
    }
}

impl From<OciAdapterError> for ServerError {
    fn from(value: OciAdapterError) -> Self {
        match value {
            OciAdapterError::Io(e) => Self::Io(e),
            OciAdapterError::Json(e) => Self::Json(e),
            OciAdapterError::NumericConversion(e) => Self::NumericConversion(e),
            OciAdapterError::ObjectStore(e) => Self::from(e),
            OciAdapterError::S3ObjectStore(e) => Self::ObjectStore(ObjectStoreError::S3(e)),
            OciAdapterError::LocalObjectStore(e) => Self::ObjectStore(ObjectStoreError::Local(e)),
            OciAdapterError::ObjectPrefix(e) => Self::ObjectStore(ObjectStoreError::Prefix(e)),
            OciAdapterError::NotFound => Self::NotFound,
            OciAdapterError::Overflow => Self::Overflow,
            OciAdapterError::InvalidContentHash => Self::InvalidContentHash,
            OciAdapterError::InvalidDigest => Self::InvalidDigest,
            OciAdapterError::InvalidRepositoryName => Self::InvalidRepositoryName,
            OciAdapterError::InvalidManifestReference => Self::InvalidManifestReference,
            OciAdapterError::InvalidUploadSession => Self::InvalidUploadSession,
            OciAdapterError::TooManyUploadSessions => Self::TooManyUploadSessions,
            OciAdapterError::ExpectedBodyHashMismatch => Self::ExpectedBodyHashMismatch,
            OciAdapterError::BlockingTask(e) => Self::BlockingTask(e),
        }
    }
}

impl From<shardline_protocol_adapters::ProtocolError> for ServerError {
    fn from(error: shardline_protocol_adapters::ProtocolError) -> Self {
        match error {
            shardline_protocol_adapters::ProtocolError::InvalidContentHash => {
                Self::InvalidContentHash
            }
        }
    }
}

impl From<LocalObjectStoreError> for ServerError {
    fn from(e: LocalObjectStoreError) -> Self {
        Self::ObjectStore(ObjectStoreError::Local(e))
    }
}

impl From<S3ObjectStoreError> for ServerError {
    fn from(e: S3ObjectStoreError) -> Self {
        Self::ObjectStore(ObjectStoreError::S3(e))
    }
}

impl From<ObjectPrefixError> for ServerError {
    fn from(e: ObjectPrefixError) -> Self {
        Self::ObjectStore(ObjectStoreError::Prefix(e))
    }
}

impl From<LocalIndexStoreError> for ServerError {
    fn from(e: LocalIndexStoreError) -> Self {
        Self::Index(IndexError::Local(e))
    }
}

impl From<MemoryIndexStoreError> for ServerError {
    fn from(e: MemoryIndexStoreError) -> Self {
        Self::Index(IndexError::MemoryIndex(e))
    }
}

impl From<MemoryRecordStoreError> for ServerError {
    fn from(e: MemoryRecordStoreError) -> Self {
        Self::Index(IndexError::MemoryRecord(e))
    }
}

impl From<PostgresMetadataStoreError> for ServerError {
    fn from(e: PostgresMetadataStoreError) -> Self {
        Self::Index(IndexError::PostgresMetadata(e))
    }
}

impl From<RetentionHoldError> for ServerError {
    fn from(e: RetentionHoldError) -> Self {
        Self::Index(IndexError::RetentionHold(e))
    }
}

impl From<QuarantineCandidateError> for ServerError {
    fn from(e: QuarantineCandidateError) -> Self {
        Self::Index(IndexError::QuarantineCandidate(e))
    }
}

impl From<WebhookDeliveryError> for ServerError {
    fn from(e: WebhookDeliveryError) -> Self {
        Self::Index(IndexError::WebhookDelivery(e))
    }
}

impl From<FileRecordInvariantError> for ServerError {
    fn from(e: FileRecordInvariantError) -> Self {
        Self::Index(IndexError::FileRecordInvariant(e))
    }
}

impl From<InvalidLifecycleMetadataError> for ServerError {
    fn from(e: InvalidLifecycleMetadataError) -> Self {
        Self::Index(IndexError::InvalidLifecycleMetadata(e))
    }
}

impl From<InvalidReconstructionResponseError> for ServerError {
    fn from(e: InvalidReconstructionResponseError) -> Self {
        Self::Index(IndexError::InvalidReconstructionResponse(e))
    }
}

impl From<ParseStoredFileRecordError> for ServerError {
    fn from(e: ParseStoredFileRecordError) -> Self {
        match e {
            ParseStoredFileRecordError::StoredFileMetadataTooLarge {
                observed_bytes,
                maximum_bytes,
            } => Self::StoredFileMetadataTooLarge {
                observed_bytes,
                maximum_bytes,
            },
            ParseStoredFileRecordError::Json(e) => Self::Json(e),
        }
    }
}

#[derive(Debug, Serialize)]
struct ErrorBody {
    error: String,
}

#[cfg(test)]
mod tests {
    use axum::http::StatusCode;

    use super::ServerError;

    fn status_for(error: &ServerError) -> StatusCode {
        error.status_code()
    }

    #[test]
    fn not_found_maps_to_404() {
        assert_eq!(status_for(&ServerError::NotFound), StatusCode::NOT_FOUND);
    }

    #[test]
    fn insufficient_scope_maps_to_403() {
        assert_eq!(
            status_for(&ServerError::InsufficientScope),
            StatusCode::FORBIDDEN
        );
    }

    #[test]
    fn too_many_upload_sessions_maps_to_429() {
        assert_eq!(
            status_for(&ServerError::TooManyUploadSessions),
            StatusCode::TOO_MANY_REQUESTS
        );
    }

    #[test]
    fn too_many_registry_token_requests_maps_to_429() {
        assert_eq!(
            status_for(&ServerError::TooManyRegistryTokenRequests),
            StatusCode::TOO_MANY_REQUESTS
        );
    }

    #[test]
    fn missing_authorization_maps_to_401() {
        assert_eq!(
            status_for(&ServerError::MissingAuthorization),
            StatusCode::UNAUTHORIZED
        );
    }

    #[test]
    fn request_body_too_large_maps_to_413() {
        assert_eq!(
            status_for(&ServerError::RequestBodyTooLarge),
            StatusCode::PAYLOAD_TOO_LARGE
        );
    }

    #[test]
    fn invalid_file_id_maps_to_400() {
        assert_eq!(
            status_for(&ServerError::InvalidFileId),
            StatusCode::BAD_REQUEST
        );
    }

    #[test]
    fn range_not_satisfiable_maps_to_416() {
        assert_eq!(
            status_for(&ServerError::RangeNotSatisfiable),
            StatusCode::RANGE_NOT_SATISFIABLE
        );
    }

    #[test]
    fn not_acceptable_maps_to_406() {
        assert_eq!(
            status_for(&ServerError::NotAcceptable),
            StatusCode::NOT_ACCEPTABLE
        );
    }

    #[test]
    fn io_error_maps_to_500() {
        let io_err = std::io::Error::other("test");
        assert_eq!(
            status_for(&ServerError::Io(io_err)),
            StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[test]
    fn transfer_limiter_closed_maps_to_503() {
        assert_eq!(
            status_for(&ServerError::TransferLimiterClosed),
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    #[test]
    fn provider_denied_maps_to_403() {
        assert_eq!(
            status_for(&ServerError::ProviderDenied),
            StatusCode::FORBIDDEN
        );
    }

    #[test]
    fn unknown_provider_maps_to_404() {
        assert_eq!(
            status_for(&ServerError::UnknownProvider),
            StatusCode::NOT_FOUND
        );
    }

    #[test]
    fn overflow_maps_to_500() {
        assert_eq!(
            status_for(&ServerError::Overflow),
            StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[test]
    fn invalid_content_hash_maps_to_400() {
        assert_eq!(
            status_for(&ServerError::InvalidContentHash),
            StatusCode::BAD_REQUEST
        );
    }

    #[test]
    fn expected_body_hash_mismatch_maps_to_400() {
        assert_eq!(
            status_for(&ServerError::ExpectedBodyHashMismatch),
            StatusCode::BAD_REQUEST
        );
    }
}