loonfs-api 0.3.1

Wire types and durable-format codecs for LoonFS.
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
//! Every identifier newtype in the workspace, generated by the
//! `string_id!` and `numeric_id!` macros so all ids share one validated
//! surface.

use crate::hex::{hex_encode_bytes, is_lower_hex_byte};
use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

const SERVER_GENERATED_ID_BODY_LEN: usize = 32;

// ---------------------------------------------------------------------------
// Validation errors
// ---------------------------------------------------------------------------

macro_rules! validation_error {
    ($name:ident, $message:literal) => {
        /// Describes why supplied text does not satisfy this identifier's validation contract.
        #[derive(Debug, Clone, PartialEq, Eq, Error)]
        #[error($message)]
        pub struct $name {
            value: String,
            reason: String,
        }

        impl $name {
            pub(crate) fn new(value: &str, reason: impl Into<String>) -> Self {
                Self {
                    value: value.to_owned(),
                    reason: reason.into(),
                }
            }

            /// Returns the rejected input, or an empty string when echoing it would be unsafe.
            pub fn value(&self) -> &str {
                &self.value
            }

            /// Returns the specific grammar rule the rejected input violated.
            pub fn reason(&self) -> &str {
                &self.reason
            }
        }
    };
}

validation_error!(
    NamespaceIdValidationError,
    "invalid namespace_id {value:?}: {reason}"
);
validation_error!(
    CommitIdValidationError,
    "invalid commit_id {value:?}: {reason}"
);
validation_error!(
    GeneratedIdValidationError,
    "invalid generated id {value:?}: {reason}"
);
validation_error!(
    SnapshotIdValidationError,
    "invalid snapshot_id {value:?}: {reason}"
);
validation_error!(
    NameKeyValidationError,
    "invalid name_key {value:?}: {reason}"
);
validation_error!(
    WriterIdValidationError,
    "invalid writer_id {value:?}: {reason}"
);
validation_error!(
    BindingGenerationValidationError,
    "invalid binding_generation {value:?}: {reason}"
);

// ---------------------------------------------------------------------------
// Id macros
// ---------------------------------------------------------------------------

/// Defines a validated string-id newtype.
///
/// Every string id gets the same surface: `parse` (the only fallible
/// constructor), `as_str`, `TryFrom<&str>`/`TryFrom<String>`/`FromStr`
/// (all delegating to `parse`), `AsRef<str>`, `Borrow<str>`, `Display`
/// (the plain inner string), and serde as a plain string with validation
/// on deserialize.
///
/// Two forms:
/// - `string_id!(Name, error = ErrType, validate = validator)` uses a custom
///   `fn(&str) -> Result<(), ErrType>` validator.
/// - `string_id!(Name, prefix = "xyz")` validates the project-standard
///   server-generated shape `xyz_<32 lowercase hex>` and adds a
///   `generate()` constructor.
///
/// Either form may end with `schema(...)` metadata. Its optional `pattern`
/// and `example` are added to the OpenAPI string schema when that feature is
/// enabled.
///
/// Type-specific constructors that the macro cannot express (for example
/// `CommitId::generate` or `NameKey::for_display_name`) live in a separate
/// `impl` block next to the invocation.
macro_rules! string_id {
    (
        $(#[$meta:meta])*
        $name:ident,
        error = $error:ty,
        validate = $validate:expr
        $(, schema($($schema:tt)+))?
        $(,)?
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
        #[cfg_attr(
            feature = "openapi",
            schema(value_type = String $(, $($schema)+)?)
        )]
        pub struct $name(String);

        impl $name {
            /// Parses and validates the id from its serialized form.
            pub fn parse(value: impl AsRef<str>) -> Result<Self, $error> {
                let value = value.as_ref();
                ($validate)(value)?;
                Ok(Self(value.to_owned()))
            }

            /// Returns the serialized id.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl TryFrom<&str> for $name {
            type Error = $error;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::parse(value)
            }
        }

        impl TryFrom<String> for $name {
            type Error = $error;

            fn try_from(value: String) -> Result<Self, Self::Error> {
                Self::parse(value)
            }
        }

        impl std::str::FromStr for $name {
            type Err = $error;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                Self::parse(value)
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }

        impl std::borrow::Borrow<str> for $name {
            fn borrow(&self) -> &str {
                self.as_str()
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(&self.0)
            }
        }

        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = <String as serde::Deserialize>::deserialize(deserializer)?;
                Self::parse(value).map_err(serde::de::Error::custom)
            }
        }
    };
    (
        $(#[$meta:meta])*
        $name:ident,
        prefix = $prefix:literal
        $(, schema($($schema:tt)+))?
        $(,)?
    ) => {
        string_id! {
            $(#[$meta])*
            $name,
            error = GeneratedIdValidationError,
            validate = |value: &str| validate_generated_id($prefix, value)
            $(, schema($($schema)+))?
        }

        impl $name {
            /// Generates a valid random id.
            pub fn generate() -> Self {
                Self(generated_id($prefix))
            }
        }
    };
}

/// Defines a numeric (`u64`) id newtype.
///
/// Every numeric id gets `Copy`, ordering and hashing derives, `From<u64>`,
/// `Display` as the plain inner number, and serde as a plain number. The
/// inner field stays public: numeric ids are constructed positionally
/// (`InodeId(7)`) and read via `.0`.
macro_rules! numeric_id {
    (
        $(#[$meta:meta])*
        $name:ident,
        public_ordinal,
        schema_description = $schema_description:literal
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
        pub struct $name(pub u64);

        impl $name {
            /// Validates a numeric value before using it as an ordinal.
            ///
            /// Deserialization calls this method automatically. Code that
            /// receives a raw integer through another interface must call it
            /// explicitly. Direct tuple construction and `From<u64>` are for
            /// values that have already been validated.
            pub fn parse(value: u64) -> Result<Self, $crate::PublicOrdinalRangeError> {
                if value > $crate::MAX_PUBLIC_INTEGER {
                    return Err($crate::PublicOrdinalRangeError);
                }
                Ok(Self(value))
            }

            /// Returns the next ordinal, or an error at the public maximum.
            pub fn successor(self) -> Result<Self, $crate::PublicOrdinalRangeError> {
                $crate::next_public_ordinal(self.0)
                    .map(Self)
                    .ok_or($crate::PublicOrdinalRangeError)
            }
        }

        #[cfg(feature = "openapi")]
        impl utoipa::PartialSchema for $name {
            fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
                utoipa::openapi::schema::Object::builder()
                    .schema_type(utoipa::openapi::schema::Type::Integer)
                    .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
                        utoipa::openapi::KnownFormat::Int64,
                    )))
                    .minimum(Some(0u64))
                    .maximum(Some($crate::MAX_PUBLIC_INTEGER))
                    .description(Some($schema_description))
                    .into()
            }
        }

        #[cfg(feature = "openapi")]
        impl utoipa::ToSchema for $name {}

        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = <u64 as serde::Deserialize>::deserialize(deserializer)?;
                Self::parse(value).map_err(serde::de::Error::custom)
            }
        }

        impl From<u64> for $name {
            fn from(value: u64) -> Self {
                Self(value)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }
    };
    (
        $(#[$meta:meta])*
        $name:ident
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
        pub struct $name(pub u64);

        impl From<u64> for $name {
            fn from(value: u64) -> Self {
                Self(value)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }
    };
}

pub(crate) use numeric_id;
pub(crate) use string_id;
pub(crate) use validation_error;

// ---------------------------------------------------------------------------
// Shared validators and generators
// ---------------------------------------------------------------------------

/// Generates a project-standard opaque durable identifier.
///
/// Generated server-side IDs use an underscore prefix plus a 32-character
/// lowercase hexadecimal body, such as `cs_<32hex>` or `chk_<32hex>`.
///
/// Ids in the id inventory generate through their newtype `generate()`
/// constructors; this helper stays public for free-form generated labels
/// (for example a server's per-request id) that have no validated id type.
pub fn generated_id(prefix: &'static str) -> String {
    format!("{prefix}_{}", hex_encode_bytes(&random_128()))
}

/// Draws 128 fresh random bits.
///
/// Generated ids hex-encode these bytes. Content ids use the same generator,
/// which keeps their shard prefixes uniformly distributed.
fn random_128() -> [u8; 16] {
    let mut bytes = [0_u8; 16];
    getrandom::fill(&mut bytes).expect("the system random generator must be available");
    bytes
}

fn validate_generated_id(
    prefix: &'static str,
    value: &str,
) -> Result<(), GeneratedIdValidationError> {
    let expected_prefix = format!("{prefix}_");
    let Some(body) = value.strip_prefix(&expected_prefix) else {
        return Err(GeneratedIdValidationError::new(
            value,
            format!("must start with `{expected_prefix}`"),
        ));
    };
    if body.len() != SERVER_GENERATED_ID_BODY_LEN {
        return Err(GeneratedIdValidationError::new(
            value,
            format!("body must be {SERVER_GENERATED_ID_BODY_LEN} lowercase hex characters"),
        ));
    }
    if !body.bytes().all(is_lower_hex_byte) {
        return Err(GeneratedIdValidationError::new(
            value,
            "body must contain only lowercase hex characters".to_owned(),
        ));
    }
    Ok(())
}

fn validate_namespace_id(value: &str) -> Result<(), NamespaceIdValidationError> {
    validate_id_grammar(value).map_err(|reason| NamespaceIdValidationError::new(value, reason))?;
    // System tooling (for example the object-store doctor probes) writes
    // under namespace slots that must never collide with user namespaces.
    if value.starts_with("loonfs-") {
        return Err(NamespaceIdValidationError::new(
            value,
            "the `loonfs-` prefix is reserved for LoonFS system namespaces",
        ));
    }
    Ok(())
}

fn validate_commit_id(value: &str) -> Result<(), CommitIdValidationError> {
    validate_id_grammar(value).map_err(|reason| CommitIdValidationError::new(value, reason))
}

/// Maximum name-key length in UTF-8 bytes. Keys are derived from display
/// names capped at [`crate::path::MAX_DISPLAY_NAME_BYTES`]; case folding
/// expands at most threefold in bytes, so 768 admits every key derivable
/// from a valid name while bounding row keys, filter keys, and cursors.
pub const MAX_NAME_KEY_BYTES: usize = 768;
/// Maximum validated namespace and commit id length in UTF-8 bytes.
pub const MAX_ID_BYTES: usize = 128;

fn validate_name_key(value: &str) -> Result<(), NameKeyValidationError> {
    if value.is_empty() {
        return Err(NameKeyValidationError::new(value, "must not be empty"));
    }
    if value.contains('/') {
        return Err(NameKeyValidationError::new(value, "must not contain `/`"));
    }
    if matches!(value, "." | "..") {
        return Err(NameKeyValidationError::new(
            value,
            "must not be `.` or `..`",
        ));
    }
    if value.chars().any(|character| character.is_control()) {
        return Err(NameKeyValidationError::new(
            value,
            "must not contain control characters",
        ));
    }
    if value.len() > MAX_NAME_KEY_BYTES {
        // An oversized or hostile name must not ride along in error payloads that serialize onto the wire.
        return Err(NameKeyValidationError::new(
            "",
            format!("exceeds the maximum name key length of {MAX_NAME_KEY_BYTES} bytes"),
        ));
    }
    Ok(())
}

fn validate_id_grammar(value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err("must not be empty".to_owned());
    }
    if value.len() > MAX_ID_BYTES {
        return Err(format!("must be {MAX_ID_BYTES} bytes or fewer"));
    }
    if value.trim() != value {
        return Err("must not have leading or trailing whitespace".to_owned());
    }
    if matches!(value, "." | "..") {
        return Err("must not be `.` or `..`".to_owned());
    }

    let mut chars = value.chars();
    let first = chars
        .next()
        .expect("empty id returned before char validation");
    if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
        return Err("must start with a lowercase ASCII letter or digit".to_owned());
    }
    if !chars.all(is_allowed_id_tail_char) {
        return Err(
            "must contain only lowercase ASCII letters, digits, `.`, `_`, or `-`".to_owned(),
        );
    }

    Ok(())
}

fn is_allowed_id_tail_char(ch: char) -> bool {
    ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '.' | '_' | '-')
}

// ---------------------------------------------------------------------------
// String ids
// ---------------------------------------------------------------------------

string_id! {
    /// Durable id for one namespace.
    ///
    /// A namespace is one filesystem history. This id is not a display name and
    /// should not be reused after destruction. Its serialized form is 1 to 128
    /// lowercase ASCII letters, digits, dots, underscores, or hyphens, starting
    /// with a letter or digit; the `loonfs-` prefix is reserved for system use.
    NamespaceId,
    error = NamespaceIdValidationError,
    validate = validate_namespace_id,
    schema(
        // The `loonfs-` reservation stays in the description: a lookahead
        // would state it, but portable pattern dialects (RE2, most SDK
        // generators) reject lookaheads, so the pattern is the grammar only.
        pattern = r"^[a-z0-9][a-z0-9._-]{0,127}$",
        example = "demo"
    )
}

string_id! {
    /// Stable writer label supplied by the embedding process.
    WriterId,
    error = WriterIdValidationError,
    validate = |value: &str| {
        if value.trim().is_empty() {
            return Err(WriterIdValidationError::new(value, "must not be blank"));
        }
        Ok(())
    }
}

string_id! {
    /// Opaque token identifying one parent and name binding generation.
    BindingGeneration,
    error = BindingGenerationValidationError,
    validate = |value: &str| {
        if value.is_empty() {
            return Err(BindingGenerationValidationError::new(value, "must not be empty"));
        }
        if !value.bytes().all(is_lower_hex_byte) {
            return Err(BindingGenerationValidationError::new(
                value,
                "must contain only lowercase hex characters",
            ));
        }
        Ok(())
    },
    schema(pattern = r"^[0-9a-f]+$")
}

string_id! {
    /// Durable id for an immutable content store.
    ///
    /// Content stores own file bytes. Namespaces point at content stores.
    ContentStoreId,
    prefix = "cs"
}

string_id! {
    /// Client-supplied idempotency key for one logical commit.
    ///
    /// Reuse the same `CommitId` when retrying the same request. The accepted
    /// grammar is 1 to 128 lowercase ASCII letters, digits, dots, underscores,
    /// or hyphens, starting with a letter or digit. [`CommitId::generate`] returns
    /// `c_<32 lowercase hex>`, but callers may supply any value in that grammar.
    CommitId,
    error = CommitIdValidationError,
    validate = validate_commit_id,
    schema(
        pattern = r"^[a-z0-9][a-z0-9._-]{0,127}$",
        example = "c_f3a9c2d4b6e8417a90c5d2f8e1b7a6c0"
    )
}

impl CommitId {
    /// Generates a valid random commit id.
    pub fn generate() -> Self {
        Self(generated_id("c"))
    }
}

string_id! {
    /// Durable checkpoint identifier.
    ///
    /// The manifest number determines which namespace manifest it pins.
    CheckpointId,
    error = GeneratedIdValidationError,
    validate = validate_checkpoint_id,
    schema(
        pattern = r"^pin_[0-9]{20}-[0-9a-f]{16}$",
        example = "pin_00000000000000000001-0000000000000002"
    )
}

string_id! {
    /// Id of a snapshot.
    ///
    /// A snapshot is backed by a checkpoint record and uses that record's
    /// id, `pin_{manifest_no:020}-{16 lowercase hex}`.
    SnapshotId,
    error = SnapshotIdValidationError,
    validate = |value: &str| validate_checkpoint_id(value)
        .map_err(|error| SnapshotIdValidationError::new(&error.value, error.reason)),
    schema(
        pattern = r"^pin_[0-9]{20}-[0-9a-f]{16}$",
        example = "pin_00000000000000000001-0000000000000002"
    )
}

impl From<SnapshotId> for CheckpointId {
    fn from(snapshot_id: SnapshotId) -> Self {
        Self(snapshot_id.0)
    }
}

impl From<CheckpointId> for SnapshotId {
    fn from(checkpoint_id: CheckpointId) -> Self {
        Self(checkpoint_id.0)
    }
}

impl CheckpointId {
    /// Generates a new pin for the given manifest number.
    pub fn generate(manifest_no: ManifestNo) -> Self {
        let entropy = generated_id("pin");
        Self::parse(format!("pin_{:020}-{}", manifest_no.0, &entropy[4..20]))
            .expect("the pinned manifest number should be valid")
    }

    /// Returns the manifest number encoded in this id.
    pub fn manifest_no(&self) -> ManifestNo {
        ManifestNo(
            self.0[4..24]
                .parse()
                .expect("a pin id should contain a manifest number"),
        )
    }
}

fn validate_checkpoint_id(value: &str) -> Result<(), GeneratedIdValidationError> {
    let valid = value
        .strip_prefix("pin_")
        .and_then(|body| body.split_once('-'))
        .is_some_and(|(number, entropy)| {
            number.len() == 20
                && number.bytes().all(|byte| byte.is_ascii_digit())
                && number
                    .parse::<u64>()
                    .ok()
                    .and_then(|number| ManifestNo::parse(number).ok())
                    .is_some_and(|number| number.0 > 0)
                && entropy.len() == 16
                && entropy.bytes().all(is_lower_hex_byte)
        });
    if !valid {
        return Err(GeneratedIdValidationError::new(value, "must be `pin_` followed by a twenty-digit positive manifest number, `-`, and sixteen lowercase hex characters".to_owned()));
    }
    Ok(())
}

string_id! {
    /// Durable id for one upload session.
    UploadId,
    prefix = "upl",
    schema(
        pattern = r"^upl_[0-9a-f]{32}$",
        example = "upl_4d8f2c91a7b34e0f9c6d1a2b3e5f708c"
    )
}

string_id! {
    /// Durable identity of one immutable content object.
    ///
    /// The body is 128 fully random bits, with no time component: content
    /// object keys shard on the id's leading characters, and a clock-derived
    /// prefix would put every upload in one window into one shard. The id
    /// names *which object*, never what it contains — integrity evidence
    /// rides [`crate::ContentRef`] beside it.
    ContentId,
    prefix = "con",
    schema(
        pattern = r"^con_[0-9a-f]{32}$",
        example = "con_9f2a6c0e4b7d4a90b13f0d8c5e6a2b41"
    )
}

impl ContentId {
    /// Returns the two-character components for both content-key shard levels.
    ///
    /// Every valid id has a 32-character lowercase hex body, so this never
    /// panics.
    pub fn shard_prefixes(&self) -> [&str; CONTENT_ID_SHARD_LEVELS] {
        let first_start = CONTENT_ID_PREFIX_LEN;
        let second_start = first_start + CONTENT_ID_SHARD_WIDTH;
        [
            &self.0[first_start..second_start],
            &self.0[second_start..second_start + CONTENT_ID_SHARD_WIDTH],
        ]
    }
}

/// Byte length of the `con_` marker that precedes a content id's hex body.
const CONTENT_ID_PREFIX_LEN: usize = "con_".len();
/// Number of directory levels used to shard content objects.
const CONTENT_ID_SHARD_LEVELS: usize = 2;
/// Number of content-id body characters in each shard directory name.
const CONTENT_ID_SHARD_WIDTH: usize = 2;

string_id! {
    /// Durable id for one metadata segment.
    MetadataSegmentId,
    prefix = "seg"
}

string_id! {
    /// Identifies one streaming metadata compaction job for log correlation only.
    MetadataCompactionId,
    prefix = "cmp"
}

string_id! {
    /// Durable id for one derived-index segment file.
    IndexSegmentId,
    prefix = "idx"
}

string_id! {
    /// Name-policy-derived directory entry key.
    ///
    /// Use this for exact name preconditions. Keep user-facing spelling in
    /// `DisplayName`.
    NameKey,
    error = NameKeyValidationError,
    validate = validate_name_key,
    schema(example = "report.txt")
}

impl NameKey {
    /// Computes the lookup key for a display name.
    pub fn for_display_name(display_name: &crate::DisplayName) -> Self {
        Self(crate::name_key_for_display_name(display_name.as_str()))
    }
}

// ---------------------------------------------------------------------------
// Numeric ids
// ---------------------------------------------------------------------------

/// Maximum value for an ordinal exposed through the API.
///
/// This is `2^53 - 1`, the largest integer JSON clients can represent
/// without losing precision.
pub const MAX_PUBLIC_INTEGER: u64 = 9_007_199_254_740_991;

/// Returned when an ordinal exceeds [`MAX_PUBLIC_INTEGER`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PublicOrdinalRangeError;

impl fmt::Display for PublicOrdinalRangeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "must be an integer from 0 through {MAX_PUBLIC_INTEGER}")
    }
}

impl std::error::Error for PublicOrdinalRangeError {}

/// Returns the next ordinal, or `None` if the value is already at the limit.
pub fn next_public_ordinal(current: u64) -> Option<u64> {
    current
        .checked_add(1)
        .filter(|next| *next <= MAX_PUBLIC_INTEGER)
}

numeric_id! {
    /// Numeric identity of a file or directory within a namespace.
    ///
    /// Inodes are stable across renames.
    InodeId
}

#[cfg(feature = "openapi")]
#[allow(
    deprecated,
    reason = "the published schema uses the requested singular example field"
)]
impl utoipa::PartialSchema for InodeId {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        utoipa::openapi::schema::Object::builder()
            .schema_type(utoipa::openapi::schema::Type::String)
            .pattern(Some(crate::public_inode_id::PATTERN))
            .example(Some(serde_json::json!(crate::public_inode_id::EXAMPLE)))
            .description(Some(crate::public_inode_id::DESCRIPTION))
            .into()
    }
}

#[cfg(feature = "openapi")]
impl utoipa::ToSchema for InodeId {}

/// Inode 1 is always the root directory of a namespace.
pub const ROOT_INODE_ID: InodeId = InodeId(1);

/// First inode id available after the root inode.
pub const FIRST_ALLOCATABLE_INODE_ID: InodeId = InodeId(ROOT_INODE_ID.0 + 1);

numeric_id! {
    /// Revision number for a file's content.
    RevisionNo,
    public_ordinal,
    schema_description = "Revision number for a file's content. It increases whenever the content is replaced or restored."
}

numeric_id! {
    /// Sequence number assigned to a namespace commit.
    ///
    /// This number determines the order in which commits become visible.
    ChangeSeq,
    public_ordinal,
    schema_description = "Sequence number assigned to a namespace commit. It determines the order in which commits become visible."
}

numeric_id! {
    /// Contiguous WAL object number within one namespace.
    WalNo,
    public_ordinal,
    schema_description = "Contiguous WAL object number within one namespace."
}

numeric_id! {
    /// Monotonic manifest counter for one namespace.
    ///
    /// The manifest number can increase when metadata changes, even if no
    /// namespace commit is written.
    ManifestNo,
    public_ordinal,
    schema_description = "Monotonic manifest counter for one namespace. It can increase when metadata changes, even if no namespace commit is written."
}

numeric_id! {
    /// Monotonic run counter allocated by the manifest that names the run.
    ///
    /// A run is the set of segments one producer wrote together. The
    /// namespace manifest and the grep manifest each keep their own counter,
    /// so a run number means nothing outside the manifest that allocated it.
    RunNo,
    public_ordinal,
    schema_description = "Monotonic run counter allocated by the manifest that names the run. A run is the set of segments one producer wrote together."
}

numeric_id! {
    /// Counter used to reject writes from an older writer.
    WriterEpoch,
    public_ordinal,
    schema_description = "Counter used to reject writes from an older writer."
}

// ---------------------------------------------------------------------------
// Filesystem item kind
// ---------------------------------------------------------------------------

/// Filesystem item kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum InodeKind {
    /// File with revision history.
    File,
    /// Directory with child bindings.
    ///
    /// The wire value is pinned to `"dir"`; only the Rust name spells the
    /// word out.
    #[serde(rename = "dir")]
    Directory,
}

impl InodeKind {
    /// Returns the serialized value.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::File => "file",
            Self::Directory => "dir",
        }
    }
}

impl fmt::Display for InodeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::{
        next_public_ordinal, BindingGeneration, ChangeSeq, CheckpointId, CommitId, ContentId,
        ContentStoreId, InodeId, ManifestNo, MetadataSegmentId, NameKey, NamespaceId, RevisionNo,
        RunNo, SnapshotId, UploadId, WalNo, WriterEpoch, WriterId, MAX_PUBLIC_INTEGER,
    };
    use crate::AttributeRevisionNo;
    use std::collections::BTreeSet;

    #[test]
    fn public_ordinal_advancement_accepts_the_maximum_and_rejects_the_next_value() {
        assert_eq!(
            next_public_ordinal(MAX_PUBLIC_INTEGER - 1),
            Some(MAX_PUBLIC_INTEGER)
        );
        assert_eq!(next_public_ordinal(MAX_PUBLIC_INTEGER), None);
    }

    #[test]
    fn public_ordinal_inputs_must_fit_the_json_safe_integer_range() {
        macro_rules! assert_range {
            ($type:ty) => {{
                let constructed = <$type>::parse(MAX_PUBLIC_INTEGER)
                    .expect("construct the maximum public ordinal");
                assert_eq!(constructed.0, MAX_PUBLIC_INTEGER);

                let construction_error = <$type>::parse(MAX_PUBLIC_INTEGER + 1)
                    .expect_err("reject a value above the public limit");
                assert_eq!(
                    construction_error.to_string(),
                    "must be an integer from 0 through 9007199254740991"
                );

                let maximum = serde_json::from_str::<$type>(&MAX_PUBLIC_INTEGER.to_string())
                    .expect("deserialize the maximum public ordinal");
                assert_eq!(maximum.0, MAX_PUBLIC_INTEGER);

                let error = serde_json::from_str::<$type>(&(MAX_PUBLIC_INTEGER + 1).to_string())
                    .expect_err("ordinal above the public range");
                assert!(
                    error
                        .to_string()
                        .contains("must be an integer from 0 through 9007199254740991"),
                    "unexpected range error: {error}"
                );
            }};
        }

        assert_range!(RevisionNo);
        assert_range!(ChangeSeq);
        assert_range!(AttributeRevisionNo);
        assert_range!(ManifestNo);
        assert_range!(WalNo);
        assert_range!(RunNo);
        assert_range!(WriterEpoch);

        assert_eq!(
            serde_json::from_str::<InodeId>(&(MAX_PUBLIC_INTEGER + 1).to_string())
                .expect("inode ids retain the full u64 range"),
            InodeId(MAX_PUBLIC_INTEGER + 1)
        );
    }

    #[test]
    fn namespace_id_parse_accepts_allowed_grammar() {
        let long_id = format!("a{}", "b".repeat(127));
        for value in ["demo", "demo-1", "demo_1", "demo.v1", &long_id] {
            let parsed = NamespaceId::parse(value).expect("valid namespace_id");
            assert_eq!(parsed.as_str(), value);
        }
    }

    #[test]
    fn namespace_id_parse_rejects_invalid_values() {
        let long_id = format!("a{}", "b".repeat(128));
        for value in [
            "", "/", "a/b", ".", "..", " demo", "demo ", "demo\n", "demo?", "demo#", "demo%",
            "Demo", &long_id,
        ] {
            assert!(
                NamespaceId::parse(value).is_err(),
                "expected invalid namespace_id {value:?}"
            );
        }
    }

    #[test]
    fn namespace_id_parse_rejects_reserved_system_prefix() {
        assert!(NamespaceId::parse("loonfs-doctor-abc").is_err());
        assert!(NamespaceId::parse("loonfs-").is_err());
        // The reservation is a prefix rule, not a substring rule.
        assert_eq!(
            NamespaceId::parse("my-loonfs-notes")
                .expect("non-prefixed use is allowed")
                .as_str(),
            "my-loonfs-notes"
        );
        // Commit ids share the base grammar but not the reservation.
        assert!(CommitId::parse("loonfs-retry-1").is_ok());
    }

    #[test]
    fn writer_id_rejects_blank_text() {
        for value in ["", " ", "\n", " \t "] {
            assert!(WriterId::parse(value).is_err(), "accepted {value:?}");
        }
    }

    #[test]
    fn binding_generation_requires_nonempty_lowercase_hex() {
        for value in ["", "abcg", "ABC", "01-23"] {
            assert!(
                BindingGeneration::parse(value).is_err(),
                "accepted {value:?}"
            );
        }
        for value in ["0", "0123456789abcdef"] {
            assert_eq!(
                BindingGeneration::parse(value)
                    .expect("valid binding generation")
                    .as_str(),
                value
            );
        }
    }

    #[test]
    fn identity_try_from_validates_values() {
        assert_eq!(
            NamespaceId::try_from("demo")
                .expect("valid namespace id")
                .as_str(),
            "demo"
        );
        assert_eq!(
            CommitId::try_from("commit-1")
                .expect("valid commit id")
                .as_str(),
            "commit-1"
        );
        assert_eq!(
            ContentStoreId::try_from("cs_00000000000000000000000000000001")
                .expect("valid content store id")
                .as_str(),
            "cs_00000000000000000000000000000001"
        );
        assert_eq!(
            CheckpointId::try_from("pin_00000000000000000001-0000000000000001")
                .expect("valid checkpoint id")
                .as_str(),
            "pin_00000000000000000001-0000000000000001"
        );
        assert_eq!(
            NameKey::try_from("report.txt".to_owned())
                .expect("valid name key")
                .as_str(),
            "report.txt"
        );

        assert!(NamespaceId::try_from("invalid/name").is_err());
        assert!(CommitId::try_from("invalid/name").is_err());
        assert!(ContentStoreId::try_from("cs_0000000000000000000000000000000g").is_err());
        assert!(CheckpointId::try_from("chk_0000000000000000000000000000000g").is_err());
        assert!(NameKey::try_from("a/b").is_err());
    }

    #[test]
    fn identity_deserialize_validates_values() {
        let namespace_id: NamespaceId =
            serde_json::from_str(r#""demo""#).expect("valid namespace id json");
        assert_eq!(namespace_id.as_str(), "demo");
        let commit_id: CommitId =
            serde_json::from_str(r#""commit-1""#).expect("valid commit id json");
        assert_eq!(commit_id.as_str(), "commit-1");
        let content_store_id: ContentStoreId =
            serde_json::from_str(r#""cs_00000000000000000000000000000001""#)
                .expect("valid content store id json");
        assert_eq!(
            content_store_id.as_str(),
            "cs_00000000000000000000000000000001"
        );
        let checkpoint_id: CheckpointId =
            serde_json::from_str(r#""pin_00000000000000000001-0000000000000001""#)
                .expect("valid checkpoint id json");
        assert_eq!(
            checkpoint_id.as_str(),
            "pin_00000000000000000001-0000000000000001"
        );

        let namespace_error = serde_json::from_str::<NamespaceId>(r#""invalid/name""#)
            .expect_err("invalid namespace id json");
        assert!(namespace_error.to_string().contains("namespace_id"));
        let commit_error = serde_json::from_str::<CommitId>(r#""invalid/name""#)
            .expect_err("invalid commit id json");
        assert!(commit_error.to_string().contains("commit_id"));
        let content_store_error =
            serde_json::from_str::<ContentStoreId>(r#""cs_0000000000000000000000000000000g""#)
                .expect_err("invalid content store id json");
        assert!(content_store_error.to_string().contains("generated id"));
        let checkpoint_error =
            serde_json::from_str::<CheckpointId>(r#""chk_0000000000000000000000000000000g""#)
                .expect_err("invalid checkpoint id json");
        assert!(checkpoint_error.to_string().contains("generated id"));
    }

    #[test]
    fn generated_content_store_id_parse_requires_prefix_and_lower_hex_body() {
        let parsed = ContentStoreId::parse("cs_00000000000000000000000000000001")
            .expect("valid content store id");

        assert_eq!(parsed.as_str(), "cs_00000000000000000000000000000001");
        let hyphenated_content_store_id = ["cs", "1"].join("-");
        for value in [
            hyphenated_content_store_id.as_str(),
            "upl_00000000000000000000000000000001",
            "content-stores/foo",
            "cs_",
            "cs_abcdef",
            "cs_0000000000000000000000000000000",
            "cs_000000000000000000000000000000001",
            "cs_ABCDEF00000000000000000000000000",
            "cs_0000000000000000000000000000000g",
            " cs_00000000000000000000000000000001",
            "cs_00000000000000000000000000000001 ",
        ] {
            assert!(
                ContentStoreId::parse(value).is_err(),
                "expected invalid content store id {value:?}"
            );
        }
    }

    #[test]
    fn generated_upload_wal_metadata_segment_and_checkpoint_ids_reject_hyphenated_ids() {
        assert!(UploadId::parse("upl_00000000000000000000000000000001").is_ok());
        assert!(MetadataSegmentId::parse("seg_00000000000000000000000000000001").is_ok());
        assert!(CheckpointId::parse("pin_00000000000000000001-0000000000000001").is_ok());
        assert!(UploadId::parse(["upl", "123"].join("-")).is_err());
        // The two positional families are told apart by their prefix, never
        // by context.
        assert!(MetadataSegmentId::parse(["seg", "123"].join("-")).is_err());
        assert!(CheckpointId::parse(["chk", "123"].join("-")).is_err());
    }

    #[test]
    fn generated_runtime_ids_use_lower_hex_bodies() {
        let upload_id = UploadId::generate();
        let metadata_segment_id = MetadataSegmentId::generate();
        let checkpoint_id = CheckpointId::generate(ManifestNo(1));

        assert_generated_id_shape(upload_id.as_str(), "upl");
        assert_generated_id_shape(metadata_segment_id.as_str(), "seg");
        assert_eq!(checkpoint_id.manifest_no(), ManifestNo(1));
        assert!(UploadId::parse(upload_id.as_str()).is_ok());
        assert!(MetadataSegmentId::parse(metadata_segment_id.as_str()).is_ok());
        assert!(CheckpointId::parse(checkpoint_id.as_str()).is_ok());
    }

    #[test]
    fn checkpoint_ids_order_and_validate_their_manifest_numbers() {
        let first = CheckpointId::parse("pin_00000000000000000009-ffffffffffffffff").expect("pin");
        let second = CheckpointId::parse("pin_00000000000000000010-0000000000000000").expect("pin");
        assert!(first < second);
        assert_eq!(second.manifest_no(), ManifestNo(10));
        let snapshot_id = SnapshotId::from(second.clone());
        let decoded: SnapshotId = serde_json::from_str(
            &serde_json::to_string(&snapshot_id).expect("serialize snapshot id"),
        )
        .expect("decode snapshot id");
        assert_eq!(CheckpointId::from(decoded), second);
        for invalid in [
            "pin_00000000000000000000-0000000000000000".to_owned(),
            format!("pin_{:020}-0000000000000000", MAX_PUBLIC_INTEGER + 1),
            "pin_00000000000000000001-000000000000000G".to_owned(),
            "pin_1-0000000000000000".to_owned(),
            "pin_00000000000000000001-00000000000000000".to_owned(),
        ] {
            assert!(CheckpointId::parse(&invalid).is_err());
            assert!(SnapshotId::parse(&invalid).is_err());
        }
    }

    #[test]
    fn generated_content_ids_are_unique_and_shard_uniformly() {
        let mut ids = BTreeSet::new();
        let mut first_level_shards = BTreeSet::new();
        let mut leaf_shards = BTreeSet::new();
        for _ in 0..512 {
            let id = ContentId::generate();
            assert_generated_id_shape(id.as_str(), "con");
            let [first, second] = id.shard_prefixes();
            assert_eq!(first, &id.as_str()["con_".len().."con_".len() + 2]);
            assert_eq!(second, &id.as_str()["con_".len() + 2.."con_".len() + 4]);
            first_level_shards.insert(first.to_owned());
            leaf_shards.insert(format!("{first}/{second}"));
            assert!(
                ids.insert(id.clone()),
                "generated duplicate content id {id}"
            );
        }
        // 512 draws over 256 first-level and 65,536 leaf shards: a generator
        // with a fixed or clock-derived prefix would collapse into a handful
        // of shards.
        assert!(
            first_level_shards.len() > 128,
            "content id first-level shards are not spread: {} distinct",
            first_level_shards.len()
        );
        assert!(
            leaf_shards.len() > 480,
            "content id leaf shards are not spread: {} distinct",
            leaf_shards.len()
        );
    }

    #[test]
    fn content_id_parse_requires_the_generated_id_shape() {
        assert!(ContentId::parse("con_0123456789abcdef0123456789abcdef").is_ok());
        assert!(ContentId::parse("upl_0123456789abcdef0123456789abcdef").is_err());
    }

    fn assert_generated_id_shape(value: &str, prefix: &str) {
        let expected_prefix = format!("{prefix}_");
        let body = value
            .strip_prefix(&expected_prefix)
            .expect("generated id prefix");
        assert_eq!(body.len(), 32);
        assert!(
            body.bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)),
            "generated id body must be lowercase hex: {value}"
        );
    }

    #[test]
    fn name_key_parse_rejects_invalid_values() {
        assert_eq!(
            NameKey::parse("").expect_err("empty").reason(),
            "must not be empty"
        );
        assert_eq!(
            NameKey::parse("a/b").expect_err("slash").reason(),
            "must not contain `/`"
        );
        assert_eq!(
            NameKey::parse(".").expect_err("dot").reason(),
            "must not be `.` or `..`"
        );
        assert_eq!(
            NameKey::parse("a\u{0}b").expect_err("control").reason(),
            "must not contain control characters"
        );
        NameKey::parse("k".repeat(super::MAX_NAME_KEY_BYTES)).expect("cap is inclusive");
        assert_eq!(
            NameKey::parse("k".repeat(super::MAX_NAME_KEY_BYTES + 1))
                .expect_err("over cap")
                .reason(),
            "exceeds the maximum name key length of 768 bytes"
        );
    }

    #[test]
    fn name_key_serializes_as_string_and_validates_deserialize() {
        let name_key = NameKey::parse("report.txt").expect("valid name key");

        assert_eq!(
            serde_json::to_string(&name_key).expect("serialize name key"),
            "\"report.txt\""
        );
        assert_eq!(
            serde_json::from_str::<NameKey>("\"report.txt\"").expect("deserialize name key"),
            name_key
        );
        assert!(serde_json::from_str::<NameKey>("\"a/b\"").is_err());
    }
}