kynos 0.3.0

An idiomatic, performance-focused REST API framework with OpenAPI 3.1 and 3.2 support.
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
//! What a flattened field contributes to the object that carries it.
//!
//! A description is only worth anything if the type it came from can produce an
//! instance it accepts. That is the property here, and it is checked the only
//! way that does not restate the emitter: serialize the value, compile the
//! emitted schema with a real JSON Schema validator, and validate one against
//! the other.
//!
//! `#[serde(flatten)]` is where the two halves can disagree without anything
//! else noticing. The flattened field's members become the parent's own, so the
//! parent composes the field's schema rather than naming it — and a composed
//! schema that constrains *every* member of the instance then reaches the
//! members the parent declared itself.
//!
//! A flattened map is the shape that does it, because a map names no member at
//! all. `kynos::schema::flatten::Flatten` is what refuses one outright;
//! `#[schema(open)]` is the declaration that the object really is open, and the
//! case below is what holds the description it then emits to the JSON the type
//! actually writes.

// `test-util` carries the JSON Schema validator, which is what makes this a
// check against an oracle rather than an assertion about the emitter written
// from the emitter.
#![cfg(all(feature = "macros", feature = "test-util"))]

use std::collections::BTreeMap;

use kynos::{
    Schema,
    openapi::{
        Schema as OpenApiSchema, SchemaObject,
        model::schema::types::{SchemaType, TypeSet},
    },
    schema::{
        MapKey, Schema as SchemaTrait, constraints::Constraints, flatten::OpenMap,
        registry::Registry,
    },
};
use serde::Serialize;

/// The schema `T` emits, with everything it refers to reachable from the root.
///
/// A flattened *named* type resolves to a `$ref` into `#/components/schemas`,
/// so the components the registry collected travel beside the body or the
/// validator has nothing to follow the reference to.
fn emitted<T: SchemaTrait>() -> serde_json::Value {
    let mut registry = kynos::schema::registry::Registry::new();
    let body = T::schema(&mut registry);

    let mut root = serde_json::to_value(body).expect("a schema serializes");
    let components =
        serde_json::to_value(registry.into_components()).expect("the components serialize");
    root.as_object_mut()
        .expect("a derived schema is an object")
        .insert("components".to_owned(), components);
    root
}

/// Every way `value` fails the schema its own type emits.
fn refusals<T: SchemaTrait + Serialize>(value: &T) -> Vec<String> {
    let schema = emitted::<T>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    let instance = serde_json::to_value(value).expect("the value serializes");

    validator
        .iter_errors(&instance)
        .map(|error| error.to_string())
        .collect()
}

/// A type that names its members, which is what makes it flattenable.
#[derive(Schema, Serialize, serde::Deserialize)]
struct Audit {
    at: String,
}

/// The closed case: a flattened struct, composed through a `$ref`.
#[derive(Schema, Serialize)]
struct Audited {
    id: u64,
    #[serde(flatten)]
    audit: Audit,
}

/// The open case: a flattened map, which names no member and says so.
#[derive(Schema, Serialize)]
struct Thing {
    id: u64,
    #[serde(flatten)]
    #[schema(open)]
    extra: BTreeMap<String, String>,
}

fn audited() -> Audited {
    Audited {
        id: 1,
        audit: Audit {
            at: "2026-01-01T00:00:00Z".to_owned(),
        },
    }
}

fn thing() -> Thing {
    Thing {
        id: 1,
        extra: BTreeMap::from([("k".to_owned(), "v".to_owned())]),
    }
}

/// A flattened struct describes the object the type writes.
///
/// The asymmetry that makes the map case hard: a named type resolves to a
/// `$ref`, whose target carries `properties` of its own and constrains nothing
/// it does not name, so composing it with `allOf` is already correct.
#[test]
fn a_flattened_struct_leaves_the_parents_own_properties_alone() {
    let refusals = refusals(&audited());
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Audited>()
    );
}

/// A tagged struct, whose tag serde writes as one more member.
#[derive(Schema, Serialize)]
#[serde(tag = "type")]
struct StampedAudit {
    at: String,
}

/// An open object carrying the tagged struct flattened.
#[derive(Schema, Serialize)]
struct Carrier {
    id: u64,
    #[serde(flatten)]
    stamp: StampedAudit,
}

/// A flattened tagged struct's tag reaches the parent through its `$ref`.
///
/// serde writes the tag into the parent's object, so the parent's schema
/// admits it, and holds it to the struct's name: a document naming another
/// tag, or none, is not one serde writes. serde's read is not asked, since the
/// parent is open and reads either.
#[test]
fn a_flattened_tagged_struct_holds_its_tag_through_the_parent() {
    let carrier = Carrier {
        id: 1,
        stamp: StampedAudit {
            at: "2026-01-01T00:00:00Z".to_owned(),
        },
    };
    let refusals = refusals(&carrier);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Carrier>()
    );

    let schema = emitted::<Carrier>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    for document in [
        serde_json::json!({ "id": 1, "at": "t", "type": "Other" }),
        serde_json::json!({ "id": 1, "at": "t" }),
    ] {
        assert!(
            !validator.is_valid(&document),
            "a tag serde never writes was accepted: {document} against {schema}"
        );
    }
}

/// An open flattened map describes the object the type writes.
///
/// The declared `id` is a member the parent named, so the map's value schema
/// must not reach it. `unevaluatedProperties` is the keyword that says so: it
/// sees the `properties` annotation across the `allOf`, which
/// `additionalProperties` does not.
#[test]
fn an_open_flattened_map_leaves_the_parents_own_properties_alone() {
    let refusals = refusals(&thing());
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Thing>()
    );
}

/// The map's values are still described.
///
/// The opposite failure, and the reason the repair cannot be to drop the
/// flattened schema: a member the map contributed must still be held to the
/// map's value type.
#[test]
fn an_open_flattened_map_still_constrains_the_members_it_contributes() {
    let schema = emitted::<Thing>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");

    assert!(
        !validator.is_valid(&serde_json::json!({ "id": 1, "k": 2 })),
        "a member contributed by a `BTreeMap<String, String>` was accepted as a number: {schema}"
    );
}

/// The keyword the open case emits, named rather than only exercised.
///
/// `unevaluatedProperties` and not `additionalProperties`: the second is
/// defined against its own schema object's `properties`, so hoisting the map's
/// value schema there would be correct for a lone flattened map and wrong the
/// moment a second flattened field contributed properties through a `$ref`.
#[test]
fn an_open_flattened_map_hoists_its_values_to_unevaluated_properties() {
    let schema = emitted::<Thing>();

    assert_eq!(
        schema["unevaluatedProperties"],
        serde_json::json!({ "type": "string" }),
        "{schema}"
    );
    assert!(
        schema["allOf"][0]["additionalProperties"].is_null(),
        "the map's `additionalProperties` stayed inside the `allOf` branch: {schema}"
    );
    assert!(
        schema["additionalProperties"].is_null(),
        "the map's values reached the parent's `additionalProperties`: {schema}"
    );
}

/// An open map that leaves itself out of the object when it is empty.
#[derive(Schema, Serialize, serde::Deserialize)]
struct Sparse {
    id: u64,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    #[schema(open)]
    extra: BTreeMap<String, String>,
}

/// An open map that skips itself on write describes what serde writes and reads.
///
/// The `Schema` derive accepts `skip_serializing_if` on a flattened field only
/// when it is `#[schema(open)]`, on the ground that serde reads the absent map
/// as empty and no flattened field is listed in `required`. That ground is held
/// here against the wire: the object written without the map validates and
/// reads back to an empty map, a map with members still validates, and a
/// member of the wrong type is still refused.
#[test]
fn an_open_map_that_skips_itself_when_empty_agrees_with_its_schema() {
    let empty = Sparse {
        id: 1,
        extra: BTreeMap::new(),
    };
    let written = serde_json::to_value(&empty).expect("the value serializes");
    assert_eq!(
        written,
        serde_json::json!({ "id": 1 }),
        "an empty map reached the object serde wrote"
    );

    let omitted = refusals(&empty);
    assert!(
        omitted.is_empty(),
        "the object written without the map fails its own description: {omitted:?}\n\
         schema: {}",
        emitted::<Sparse>()
    );

    let read: Sparse = serde_json::from_value(written).expect("the object serde wrote reads back");
    assert!(
        read.extra.is_empty(),
        "an absent map read back with members: {:?}",
        read.extra
    );

    let populated = refusals(&Sparse {
        id: 1,
        extra: BTreeMap::from([("k".to_owned(), "v".to_owned())]),
    });
    assert!(
        populated.is_empty(),
        "a map with members fails its own description: {populated:?}\n\
         schema: {}",
        emitted::<Sparse>()
    );

    let schema = emitted::<Sparse>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        !validator.is_valid(&serde_json::json!({ "id": 1, "k": 2 })),
        "a member contributed by a `BTreeMap<String, String>` was accepted as a number: {schema}"
    );
}

/// Both compositions on one container, which is the case the keyword was
/// chosen for.
///
/// `Audit` contributes `at` through a `$ref`, and the map contributes whatever
/// is left. `additionalProperties` hoisted to the parent would see only the
/// parent's own `properties` and so refuse `at`; `unevaluatedProperties` also
/// sees the `properties` annotation the `$ref` produced. That difference is the
/// whole reason the second keyword was chosen, and until this case existed
/// nothing exercised it.
#[derive(Schema, Serialize)]
struct Both {
    id: u64,
    #[serde(flatten)]
    audit: Audit,
    #[serde(flatten)]
    #[schema(open)]
    extra: BTreeMap<String, String>,
}

fn both() -> Both {
    Both {
        id: 1,
        audit: Audit {
            at: "2026-01-01T00:00:00Z".to_owned(),
        },
        extra: BTreeMap::from([("k".to_owned(), "v".to_owned())]),
    }
}

/// A closed flattened struct and an open flattened map compose.
#[test]
fn an_open_map_beside_a_flattened_struct_accepts_what_each_contributes() {
    let refusals = refusals(&both());
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Both>()
    );
}

/// And composing them weakens neither.
///
/// The converse of the case above. A description that merely admitted every
/// member would pass that one, so this separates them from both sides: a member
/// the map contributed still answers to the map's value schema, and the
/// flattened struct's own property is still required.
#[test]
fn an_open_map_beside_a_flattened_struct_weakens_neither() {
    let schema = emitted::<Both>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");

    assert!(
        !validator.is_valid(&serde_json::json!({
            "id": 1, "at": "2026-01-01T00:00:00Z", "k": 2
        })),
        "a member contributed by a `BTreeMap<String, String>` was accepted as a number: {schema}"
    );
    assert!(
        !validator.is_valid(&serde_json::json!({ "id": 1, "k": "v" })),
        "the flattened struct's own required property was not required: {schema}"
    );
}

/// A map key carrying a constraint, which an open flatten has nowhere to put.
#[derive(Schema, Serialize, PartialEq, Eq, PartialOrd, Ord)]
struct Sku(String);

impl MapKey for Sku {
    fn key_constraints() -> Constraints {
        let mut constraints = Constraints::default();
        constraints.pattern = Some("^[A-Z]{3}-[0-9]{4}$".to_owned());
        constraints
    }
}

/// The same map as a property, where its key constraint has a schema of its own.
#[derive(Schema, Serialize)]
struct Ledger {
    counts: BTreeMap<Sku, u64>,
}

/// And flattened open, where it does not.
#[derive(Schema, Serialize)]
struct Stock {
    id: u64,
    #[serde(flatten)]
    #[schema(open)]
    counts: BTreeMap<Sku, u64>,
}

/// An open flatten drops a key constraint rather than moving it.
///
/// Inside the `allOf` branch `propertyNames` would name `id` as well, and `id`
/// matches no SKU pattern, so keeping it would refuse the JSON the type writes.
/// The description is left weaker than `Sku` instead. `Ledger` is the same map
/// as a property, which is what makes the absence here an observation: there
/// the constraint is emitted.
#[test]
fn an_open_flatten_drops_the_key_constraint_rather_than_reaching_the_parent() {
    assert!(
        emitted::<Ledger>().to_string().contains("propertyNames"),
        "a map keyed by `Sku` emitted no key constraint at all: {}",
        emitted::<Ledger>()
    );

    let stock = Stock {
        id: 1,
        counts: BTreeMap::from([(Sku("ABC-0001".to_owned()), 3)]),
    };
    let schema = emitted::<Stock>();
    assert!(
        !schema.to_string().contains("propertyNames"),
        "a key constraint survived an open flatten: {schema}"
    );
    let refusals = refusals(&stock);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {schema}"
    );
}

/// An open map inside an internally tagged variant.
///
/// The variant's object carries the tag beside its own properties, and the
/// hoisted `unevaluatedProperties` sits on that object, so both the tag and
/// `id` are evaluated before the map's value schema applies.
#[derive(Schema, Serialize)]
#[serde(tag = "kind")]
enum Tally {
    Counted {
        id: u64,
        #[serde(flatten)]
        #[schema(open)]
        extra: BTreeMap<String, u64>,
    },
}

#[test]
fn an_open_map_in_a_tagged_variant_leaves_the_tag_and_the_variants_properties_alone() {
    let tally = Tally::Counted {
        id: 1,
        extra: BTreeMap::from([("k".to_owned(), 2)]),
    };
    let refusals = refusals(&tally);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Tally>()
    );

    let schema = emitted::<Tally>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        !validator.is_valid(&serde_json::json!({ "kind": "Counted", "id": 1, "k": "v" })),
        "a member contributed by a `BTreeMap<String, u64>` was accepted as a string: {schema}"
    );
}

/// The same open map inside an adjacently tagged variant.
///
/// The variant's fields sit under the content key rather than beside the tag,
/// so the hoisted `unevaluatedProperties` belongs to the content object and has
/// `id` and `name` to leave alone. `name` is a string where the map's values are
/// numbers, so a value schema left inside the `allOf` would refuse it.
#[derive(Schema, Serialize)]
#[serde(tag = "kind", content = "data")]
enum Wrapped {
    Counted {
        id: u64,
        name: String,
        #[serde(flatten)]
        #[schema(open)]
        extra: BTreeMap<String, u64>,
    },
}

#[test]
fn an_open_map_in_an_adjacently_tagged_variant_leaves_the_variants_properties_alone() {
    let wrapped = Wrapped::Counted {
        id: 1,
        name: "n".to_owned(),
        extra: BTreeMap::from([("k".to_owned(), 2)]),
    };
    let refusals = refusals(&wrapped);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Wrapped>()
    );

    let schema = emitted::<Wrapped>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        !validator.is_valid(&serde_json::json!({
            "kind": "Counted", "data": { "id": 1, "name": "n", "k": "v" }
        })),
        "a member contributed by a `BTreeMap<String, u64>` was accepted as a string: {schema}"
    );
}

/// A map described by hand rather than by a standard map's own implementation.
///
/// `OpenMap` is unsealed so a type like this can claim what `HashMap` and
/// `BTreeMap` claim: no component name, and an object described by
/// `additionalProperties` alone. The hoist reads that schema object rather than
/// the type, so this holds it to the documented contract and not to the two maps.
#[derive(Serialize)]
struct Headers(BTreeMap<String, String>);

impl SchemaTrait for Headers {
    fn schema(_registry: &mut Registry) -> OpenApiSchema {
        OpenApiSchema::Object(Box::new(SchemaObject {
            ty: Some(TypeSet::One(SchemaType::Object)),
            additional_properties: Some(Box::new(OpenApiSchema::of_type(SchemaType::String))),
            ..SchemaObject::default()
        }))
    }
}

impl OpenMap for Headers {}

#[derive(Schema, Serialize)]
struct Request {
    id: u64,
    #[serde(flatten)]
    #[schema(open)]
    headers: Headers,
}

#[test]
fn a_hand_written_open_map_is_hoisted_like_a_standard_one() {
    assert!(<Headers as SchemaTrait>::name().is_none());

    let request = Request {
        id: 1,
        headers: Headers(BTreeMap::from([("k".to_owned(), "v".to_owned())])),
    };
    let refusals = refusals(&request);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Request>()
    );

    let schema = emitted::<Request>();
    assert_eq!(
        schema["unevaluatedProperties"],
        serde_json::json!({ "type": "string" }),
        "{schema}"
    );
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        !validator.is_valid(&serde_json::json!({ "id": 1, "k": 2 })),
        "a member contributed by `Headers` was accepted as a number: {schema}"
    );
}

/// A closed object beside a flattened struct, which serde reads under
/// `deny_unknown_fields`.
#[derive(Schema, Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Sealed {
    id: u64,
    #[serde(flatten)]
    audit: Audit,
}

/// A closed object admits what the flattened struct contributes through its
/// `$ref`, and nothing serde refuses.
///
/// `unevaluatedProperties: false` sees the flattened struct's `properties`
/// across the `allOf` and the `$ref` inside it, which is what keeps `at`; an
/// `additionalProperties: false` beside the parent's own `properties` would
/// refuse it. Each document is checked against serde as well as the validator,
/// so the two agree rather than the schema agreeing with itself.
#[test]
fn a_closed_object_admits_what_a_flattened_struct_contributes_and_nothing_else() {
    let sealed = Sealed {
        id: 1,
        audit: Audit {
            at: "2026-01-01T00:00:00Z".to_owned(),
        },
    };
    let refusals = refusals(&sealed);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Sealed>()
    );

    let schema = emitted::<Sealed>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    let unknown = serde_json::json!({ "id": 1, "at": "t", "z": 2 });
    assert!(
        serde_json::from_value::<Sealed>(unknown.clone()).is_err(),
        "serde must refuse a member no field names"
    );
    assert!(
        !validator.is_valid(&unknown),
        "a member serde refuses was accepted: {schema}"
    );
}

/// A flattened struct whose field serde also reads under an alias.
#[derive(Schema, Serialize, serde::Deserialize)]
struct Located {
    #[serde(alias = "place")]
    at: String,
}

/// A closed object beside it, so an alias the flattened struct does not name is
/// refused rather than admitted as an unknown member.
#[derive(Schema, Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SealedLocation {
    id: u64,
    #[serde(flatten)]
    location: Located,
}

/// serde reads a flattened struct's field under its alias too, so the struct's
/// description names the alias where the closed parent sees it through the
/// `$ref`, and refuses the field under both names as serde does.
#[test]
fn a_flattened_structs_alias_is_read_through_the_closed_parent() {
    let schema = emitted::<SealedLocation>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");

    for document in [
        serde_json::json!({ "id": 1, "at": "a" }),
        serde_json::json!({ "id": 1, "place": "a" }),
    ] {
        assert!(
            serde_json::from_value::<SealedLocation>(document.clone()).is_ok(),
            "serde must read {document}"
        );
        assert!(
            validator.is_valid(&document),
            "a document serde reads was refused: {document}\nschema: {schema}"
        );
    }
    for document in [
        serde_json::json!({ "id": 1 }),
        serde_json::json!({ "id": 1, "at": "a", "place": "b" }),
        serde_json::json!({ "id": 1, "place": "a", "z": 2 }),
    ] {
        assert!(
            serde_json::from_value::<SealedLocation>(document.clone()).is_err(),
            "serde must refuse {document}"
        );
        assert!(
            !validator.is_valid(&document),
            "a document serde refuses was accepted: {document}\nschema: {schema}"
        );
    }
}

/// A flattened struct whose optional field serde also reads under an alias.
#[derive(Schema, Serialize, serde::Deserialize)]
struct Labelled {
    #[serde(alias = "tag")]
    label: Option<String>,
}

/// A closed object beside it, which admits either name only by seeing it
/// through the `$ref`.
#[derive(Schema, Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SealedLabel {
    id: u64,
    #[serde(flatten)]
    labelled: Labelled,
}

/// An optional field's names are bounded by a `not` over their pair rather
/// than a `oneOf`, so where the required case refuses the field absent, this
/// one admits it. The closed parent admits the field under either name or
/// neither, and as the `null` serde writes for `None`, and refuses it under
/// both as serde does.
#[test]
fn a_flattened_structs_optional_alias_is_read_through_the_closed_parent() {
    let schema = emitted::<SealedLabel>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");

    let written = serde_json::to_value(SealedLabel {
        id: 1,
        labelled: Labelled { label: None },
    })
    .expect("the value serializes");
    assert_eq!(written, serde_json::json!({ "id": 1, "label": null }));

    for document in [
        written,
        serde_json::json!({ "id": 1 }),
        serde_json::json!({ "id": 1, "tag": "a" }),
    ] {
        assert!(
            serde_json::from_value::<SealedLabel>(document.clone()).is_ok(),
            "serde must read {document}"
        );
        assert!(
            validator.is_valid(&document),
            "a document serde reads was refused: {document}\nschema: {schema}"
        );
    }
    let both = serde_json::json!({ "id": 1, "label": "a", "tag": "b" });
    assert!(
        serde_json::from_value::<SealedLabel>(both.clone()).is_err(),
        "serde must refuse {both}"
    );
    assert!(
        !validator.is_valid(&both),
        "a document serde refuses was accepted: {both}\nschema: {schema}"
    );
}

/// An adjacently tagged enum, which serde reads through `deserialize_struct` and
/// so takes its tag and content keys out of a closed parent.
#[derive(Schema, Serialize, serde::Deserialize)]
#[serde(tag = "kind", content = "value")]
enum Mode {
    Fixed { level: u8 },
    Off,
}

/// A closed object beside it.
#[derive(Schema, Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SealedMode {
    id: u64,
    #[serde(flatten)]
    mode: Mode,
}

/// A closed object admits what a flattened adjacently tagged enum contributes,
/// and refuses what serde refuses, each document held to serde's own read.
#[test]
fn a_closed_object_reads_a_flattened_adjacently_tagged_enum_as_serde_does() {
    let schema = emitted::<SealedMode>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");

    for value in [
        SealedMode {
            id: 1,
            mode: Mode::Fixed { level: 2 },
        },
        SealedMode {
            id: 1,
            mode: Mode::Off,
        },
    ] {
        let document = serde_json::to_value(&value).expect("the value serializes");
        assert!(
            serde_json::from_value::<SealedMode>(document.clone()).is_ok(),
            "serde must read back what it wrote: {document}"
        );
        assert!(
            validator.is_valid(&document),
            "a document serde reads was refused: {document}\nschema: {schema}"
        );
    }
    for document in [
        serde_json::json!({ "id": 1, "kind": "Fixed", "value": { "level": 2 }, "z": 3 }),
        serde_json::json!({ "id": 1, "value": { "level": 2 } }),
    ] {
        assert!(
            serde_json::from_value::<SealedMode>(document.clone()).is_err(),
            "serde must refuse {document}"
        );
        assert!(
            !validator.is_valid(&document),
            "a document serde refuses was accepted: {document}\nschema: {schema}"
        );
    }
}

/// A problem document carrying a member of its own type, the shape RFC 9457's
/// extension members exist for.
#[derive(Schema, Serialize)]
struct Extended {
    #[serde(flatten)]
    problem: kynos::Problem,
    balance: u32,
}

/// A flattened `Problem` describes the object the type writes.
///
/// `Problem` names its five registered members and admits the rest with
/// `additionalProperties: true`, which reaches the parent's `balance` from inside
/// the `allOf` and permits it. So the composition accepts both an extension the
/// problem carries and the member the parent declared, while the registered
/// members stay typed.
#[test]
fn a_flattened_problem_accepts_its_extension_members() {
    let extended = Extended {
        problem: kynos::Problem::new(kynos::http::StatusCode::FORBIDDEN)
            .with_detail("d")
            .with_extension("accounts", serde_json::json!(["/a"])),
        balance: 30,
    };
    assert_eq!(
        serde_json::to_value(&extended).expect("the value serializes"),
        serde_json::json!({
            "accounts": ["/a"], "balance": 30, "detail": "d",
            "status": 403, "title": "Forbidden", "type": "about:blank"
        })
    );
    let refusals = refusals(&extended);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Extended>()
    );

    let schema = emitted::<Extended>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        !validator.is_valid(&serde_json::json!({
            "type": "about:blank", "status": "403", "balance": 30
        })),
        "a problem's `status` was accepted as a string: {schema}"
    );
}

/// A flattened `Problem` beside an open map, the one neighbour where the
/// problem's `additionalProperties: true` does any work.
#[derive(Schema, Serialize)]
struct Throttled {
    #[serde(flatten)]
    problem: kynos::Problem,
    #[serde(flatten)]
    #[schema(open)]
    limits: BTreeMap<String, u64>,
}

/// A flattened `Problem` beside an open map describes the object the type
/// writes, and leaves the map's values unchecked.
///
/// `Problem`'s `additionalProperties: true` marks every member evaluated, the
/// map's included, so the hoisted `unevaluatedProperties` has nothing left to
/// constrain. Without the keyword the problem's own extension member would fall
/// to the map's value schema and be refused. `docs/schema.md` records the
/// looseness, which this pins.
#[test]
fn a_flattened_problem_beside_an_open_map_leaves_the_maps_values_unchecked() {
    let throttled = Throttled {
        problem: kynos::Problem::new(kynos::http::StatusCode::TOO_MANY_REQUESTS)
            .with_extension("retry", serde_json::json!("later")),
        limits: BTreeMap::from([("remaining".to_owned(), 0)]),
    };
    let refusals = refusals(&throttled);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Throttled>()
    );

    let schema = emitted::<Throttled>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        validator.is_valid(&serde_json::json!({
            "type": "about:blank", "status": 429, "remaining": "many"
        })),
        "a string under a map key was refused, so the recorded looseness no longer holds: {schema}"
    );
}

/// Arbitrary JSON beside the members the object declares, which is the payload
/// `Unchecked` exists to carry.
#[derive(Schema, Serialize)]
struct Envelope {
    id: u64,
    #[serde(flatten)]
    #[schema(open)]
    rest: kynos::schema::unchecked::Unchecked<serde_json::Map<String, serde_json::Value>>,
}

fn envelope() -> Envelope {
    Envelope {
        id: 1,
        rest: kynos::schema::unchecked::Unchecked(
            serde_json::json!({ "k": "v", "n": [1, { "deep": null }] })
                .as_object()
                .expect("an object literal")
                .clone(),
        ),
    }
}

/// An open `Unchecked` field describes the object the type writes.
///
/// Its schema carries no `additionalProperties`, so the hoist moves nothing and
/// the parent is left open: every member the payload contributes is admitted,
/// whatever its value.
#[test]
fn an_open_unchecked_field_accepts_whatever_it_contributes() {
    let refusals = refusals(&envelope());
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Envelope>()
    );

    let schema = emitted::<Envelope>();
    assert!(
        schema["unevaluatedProperties"].is_null(),
        "an unconstrained payload closed the object it was flattened into: {schema}"
    );
}

/// And leaving the object open weakens nothing it declared.
#[test]
fn an_open_unchecked_field_still_constrains_the_parents_own_properties() {
    let schema = emitted::<Envelope>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");

    assert!(
        !validator.is_valid(&serde_json::json!({ "id": "1", "k": "v" })),
        "the parent's `id` was accepted as a string: {schema}"
    );
    assert!(
        !validator.is_valid(&serde_json::json!({ "k": "v" })),
        "the parent's own required property was not required: {schema}"
    );
}

/// A `Problem` as an internally tagged newtype variant's payload, which is
/// composed with the tag-only object as a flattened field would be.
#[derive(Schema, Serialize)]
#[serde(tag = "outcome")]
enum Outcome {
    Failed(kynos::Problem),
    Done { id: u64 },
}

/// The tag is one more member `Problem`'s `additionalProperties: true` marks
/// evaluated and permits, so the composition accepts what serde writes, while
/// the tag and the registered members stay typed.
#[test]
fn a_problem_as_a_tagged_newtype_payload_accepts_what_serde_writes() {
    let failed = Outcome::Failed(
        kynos::Problem::new(kynos::http::StatusCode::CONFLICT)
            .with_extension("retry", serde_json::json!(true)),
    );
    assert_eq!(
        serde_json::to_value(&failed).expect("the value serializes"),
        serde_json::json!({
            "outcome": "Failed", "retry": true,
            "status": 409, "title": "Conflict", "type": "about:blank"
        })
    );
    let refusals = refusals(&failed);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Outcome>()
    );

    let schema = emitted::<Outcome>();
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        !validator.is_valid(&serde_json::json!({
            "outcome": "Failed", "type": "about:blank", "status": "409"
        })),
        "a problem's `status` was accepted as a string: {schema}"
    );
    assert!(
        !validator.is_valid(&serde_json::json!({
            "outcome": "Lost", "type": "about:blank", "status": 409
        })),
        "a tag naming no variant was accepted: {schema}"
    );

    let done = Outcome::Done { id: 1 };
    let refusals = self::refusals(&done);
    assert!(
        refusals.is_empty(),
        "the sibling struct variant is refused beside the problem branch: {refusals:?}\n\
         schema: {schema}"
    );
}

/// An `Unchecked` over a typed map, flattened open.
#[derive(Schema, Serialize)]
struct Tallies {
    id: u64,
    #[serde(flatten)]
    #[schema(open)]
    counts: kynos::schema::unchecked::Unchecked<BTreeMap<String, u64>>,
}

/// An open `Unchecked` over a typed map describes the object the type writes,
/// and waives the map's value schema as `Unchecked` waives any.
///
/// `Unchecked::schema` never reads its payload, so the hoist finds no
/// `additionalProperties` and the object is left open: a value the map would
/// never write is admitted too, which is what wrapping it says.
#[test]
fn an_open_unchecked_typed_map_accepts_what_serde_writes_and_waives_its_values() {
    let tallies = Tallies {
        id: 1,
        counts: kynos::schema::unchecked::Unchecked(BTreeMap::from([
            ("apples".to_owned(), 3),
            ("pears".to_owned(), 0),
        ])),
    };
    assert_eq!(
        serde_json::to_value(&tallies).expect("the value serializes"),
        serde_json::json!({ "id": 1, "apples": 3, "pears": 0 })
    );
    let refusals = refusals(&tallies);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Tallies>()
    );

    let schema = emitted::<Tallies>();
    assert!(
        schema["unevaluatedProperties"].is_null(),
        "an unchecked payload hoisted its map's value schema: {schema}"
    );
    let validator =
        jsonschema::draft202012::new(&schema).expect("an emitted schema compiles as draft 2020-12");
    assert!(
        validator.is_valid(&serde_json::json!({ "id": 1, "apples": "many" })),
        "a value the waived map schema would refuse was refused: {schema}"
    );
}

/// A field serde writes and never reads beside an open `Unchecked` payload.
#[derive(Schema, Serialize)]
struct Stamped {
    id: u64,
    #[serde(skip_deserializing)]
    stamp: u64,
    #[serde(flatten)]
    #[schema(open)]
    rest: kynos::schema::unchecked::Unchecked<serde_json::Map<String, serde_json::Value>>,
}

/// The schema leaves the field out, since serde never reads it, and an open
/// `Unchecked` hoists no `unevaluatedProperties` to refuse it with, so the
/// object still accepts what serde writes of it.
#[test]
fn a_field_serde_never_reads_beside_an_open_unchecked_field_is_admitted() {
    let stamped = Stamped {
        id: 1,
        stamp: 7,
        rest: kynos::schema::unchecked::Unchecked(
            serde_json::json!({ "k": "v" })
                .as_object()
                .expect("an object literal")
                .clone(),
        ),
    };
    assert_eq!(
        serde_json::to_value(&stamped).expect("the value serializes"),
        serde_json::json!({ "id": 1, "stamp": 7, "k": "v" })
    );
    let refusals = refusals(&stamped);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Stamped>()
    );

    let schema = emitted::<Stamped>();
    assert!(
        schema["properties"].get("stamp").is_none(),
        "a field serde never reads was described: {schema}"
    );
}

/// A field serde writes and never reads beside an open map whose values are
/// `Unchecked`.
#[derive(Schema, Serialize)]
struct Tagged {
    id: u64,
    #[serde(skip_deserializing)]
    stamp: u64,
    #[serde(flatten)]
    #[schema(open)]
    labels:
        std::collections::HashMap<String, kynos::schema::unchecked::Unchecked<serde_json::Value>>,
}

/// The map's value schema is hoisted, and it is the permissive one, so the
/// object's `unevaluatedProperties` refuses nothing: neither a value the map
/// contributes nor the field the schema leaves out.
#[test]
fn a_field_serde_never_reads_beside_an_open_map_of_unchecked_values_is_admitted() {
    let tagged = Tagged {
        id: 1,
        stamp: 7,
        labels: std::collections::HashMap::from([(
            "k".to_owned(),
            kynos::schema::unchecked::Unchecked(serde_json::json!({ "deep": [1, null] })),
        )]),
    };
    assert_eq!(
        serde_json::to_value(&tagged).expect("the value serializes"),
        serde_json::json!({ "id": 1, "stamp": 7, "k": { "deep": [1, null] } })
    );
    let refusals = refusals(&tagged);
    assert!(
        refusals.is_empty(),
        "the type cannot produce an instance its own description accepts: {refusals:?}\n\
         schema: {}",
        emitted::<Tagged>()
    );

    let schema = emitted::<Tagged>();
    assert!(
        schema["properties"].get("stamp").is_none(),
        "a field serde never reads was described: {schema}"
    );
    assert!(
        schema["unevaluatedProperties"]["x-kynos-unchecked"] == true,
        "the hoisted value schema is not the permissive one: {schema}"
    );
}