forked from ch-robinson/dotnet-avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonSchemaReader.cs
1289 lines (1150 loc) · 47 KB
/
JsonSchemaReader.cs
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
using Chr.Avro.Abstract;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Chr.Avro.Representation
{
/// <summary>
/// Reads an Avro schema from JSON.
/// </summary>
public interface IJsonSchemaReader : ISchemaReader
{
/// <summary>
/// Reads a serialized Avro schema.
/// </summary>
/// <param name="schema">
/// A JSON-encoded schema.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
/// <returns>
/// Returns a deserialized schema object.
/// </returns>
Schema Read(string schema, ConcurrentDictionary<string, Schema> cache = null, string scope = null);
}
/// <summary>
/// Reads Avro schemas from specific JSON tokens. Used by <see cref="JsonSchemaReader" /> to
/// break apart read logic.
/// </summary>
public interface IJsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
bool IsMatch(JToken token);
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope);
}
/// <summary>
/// Reads an Avro schema from JSON using <see cref="Newtonsoft.Json" /> components.
/// </summary>
public interface INewtonsoftJsonSchemaReader : IJsonSchemaReader
{
/// <summary>
/// Reads a serialized Avro schema.
/// </summary>
/// <param name="token">
/// A JSON token representing a schema.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
/// <returns>
/// Returns a deserialized schema object.
/// </returns>
Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache = null, string scope = null);
}
/// <summary>
/// A customizable JSON schema reader backed by a list of cases.
/// </summary>
public class JsonSchemaReader : INewtonsoftJsonSchemaReader
{
/// <summary>
/// A list of cases that the read methods will attempt to apply. If the first case does not
/// match, the next case will be tested, and so on.
/// </summary>
protected readonly IReadOnlyCollection<IJsonSchemaReaderCase> Cases;
/// <summary>
/// Creates a new JSON schema reader.
/// </summary>
/// <param name="cases">
/// An optional collection of cases. If no case collection is provided, the default set
/// will be used.
/// </param>
public JsonSchemaReader(IReadOnlyCollection<IJsonSchemaReaderCase> cases = null)
{
Cases = cases ?? new List<IJsonSchemaReaderCase>()
{
// logical types:
new DateJsonSchemaReaderCase(),
new DecimalJsonSchemaReaderCase(),
new DurationJsonSchemaReaderCase(),
new MicrosecondTimeJsonSchemaReaderCase(),
new MicrosecondTimestampJsonSchemaReaderCase(),
new MillisecondTimeJsonSchemaReaderCase(),
new MillisecondTimestampJsonSchemaReaderCase(),
new UuidJsonSchemaReaderCase(),
// collections:
new ArrayJsonSchemaReaderCase(this),
new MapJsonSchemaReaderCase(this),
// unions:
new UnionJsonSchemaReaderCase(this),
// named:
new EnumJsonSchemaReaderCase(),
new FixedJsonSchemaReaderCase(),
new RecordJsonSchemaReaderCase(this),
// others:
new DefaultJsonSchemaReaderCase()
};
}
/// <summary>
/// Reads a serialized Avro schema.
/// </summary>
/// <param name="schema">
/// A JSON-encoded schema.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
/// <returns>
/// Returns a deserialized schema object.
/// </returns>
public Schema Read(string schema, ConcurrentDictionary<string, Schema> cache = null, string scope = null)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(schema)))
{
return Read(stream, cache, scope);
}
}
/// <summary>
/// Reads a serialized Avro schema.
/// </summary>
/// <param name="stream">
/// The stream to read the serialized schema from. (The stream will not be disposed.)
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
/// <returns>
/// Returns a deserialized schema object.
/// </returns>
public Schema Read(Stream stream, ConcurrentDictionary<string, Schema> cache = null, string scope = null)
{
using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
using (var json = new JsonTextReader(reader))
{
return Read(JToken.Load(json), cache, scope);
}
}
/// <summary>
/// Reads a serialized Avro schema.
/// </summary>
/// <param name="token">
/// A JSON token representing a schema.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
/// <returns>
/// Returns a deserialized schema object.
/// </returns>
public Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache = null, string scope = null)
{
if (cache == null)
{
cache = new ConcurrentDictionary<string, Schema>();
}
var match = Cases.FirstOrDefault(c => c.IsMatch(token));
if (match == null)
{
throw new UnknownSchemaException($"No schema respresentation case matched {token.ToString()}");
}
return match.Read(token, cache, scope);
}
}
/// <summary>
/// A base JSON schema reader case.
/// </summary>
public abstract class JsonSchemaReaderCase : IJsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public abstract bool IsMatch(JToken token);
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public abstract Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope);
/// <summary>
/// Qualifies a name if it’s in a scope.
/// </summary>
protected virtual string QualifyName(string name, string scope)
{
return name.Contains(".") == false && scope != null
? $"{scope}.{name}"
: name;
}
}
/// <summary>
/// A JSON schema reader case with shared functions to extract fields from named schemas.
/// </summary>
public abstract class NamedJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// Extracts fully-qualified aliases from a named schema.
/// </summary>
protected virtual ICollection<string> GetQualifiedAliases(JObject @object, string scope)
{
if (!(@object[JsonAttributeToken.Aliases] is JToken aliases))
{
return null;
}
if (!(aliases is JArray && aliases.All(t => t.Type == JTokenType.String)))
{
throw new InvalidDataException("An \"aliases\" key must have an array of strings as its value.");
}
return aliases.Select(alias => QualifyName((string)alias, scope)).ToList();
}
/// <summary>
/// Extracts the fully-qualified name from a named schema.
/// </summary>
protected virtual string GetQualifiedName(JObject @object, string scope)
{
if (!(@object[JsonAttributeToken.Name] is JValue name && name.Type == JTokenType.String))
{
throw new InvalidDataException("A named schema must contain a \"name\" key with a string as its value.");
}
if (!(@object[JsonAttributeToken.Namespace] is JToken @namespace))
{
return QualifyName((string)name, scope);
}
if (!(@namespace is JValue && @namespace.Type == JTokenType.String))
{
throw new InvalidDataException("A \"namespace\" key must have a string as its value.");
}
return $"{(string)@namespace}.{(string)name}";
}
}
/// <summary>
/// A JSON schema reader case that matches array schemas.
/// </summary>
public class ArrayJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// A schema reader to use to resolve item types.
/// </summary>
protected readonly INewtonsoftJsonSchemaReader Reader;
/// <summary>
/// Creates a new array case.
/// </summary>
/// <param name="reader">
/// A schema reader to use to resolve item types.
/// </param>
public ArrayJsonSchemaReaderCase(INewtonsoftJsonSchemaReader reader)
{
Reader = reader ?? throw new ArgumentNullException(nameof(reader), "Schema reader cannot be null.");
}
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object && (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Array;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!(token is JObject @object && (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Array))
{
throw new ArgumentException("The array case can only be applied to valid array schema representations.");
}
var child = Reader.Read(GetItems(@object), cache, scope);
var key = cache.Single(p => p.Value == child).Key;
return cache.GetOrAdd($"{JsonSchemaToken.Array}<{key}>", _ => new ArraySchema(child));
}
/// <summary>
/// Extracts the item type from an array schema.
/// </summary>
protected virtual JToken GetItems(JObject @object)
{
if (!(@object[JsonAttributeToken.Items] is JToken items))
{
throw new InvalidDataException("Array schemas must contain an \"items\" key.");
}
return items;
}
}
/// <summary>
/// A JSON schema reader case that matches int schemas with date logical types.
/// </summary>
public class DateJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object
&& (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Int
&& (string)@object[JsonAttributeToken.LogicalType] == JsonSchemaToken.Date;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!IsMatch(token))
{
throw new ArgumentException("The date case can only be applied to \"int\" schemas with a \"date\" logical type.");
}
return cache.GetOrAdd($"{JsonSchemaToken.Int}!{JsonSchemaToken.Date}", _ => new IntSchema()
{
LogicalType = new DateLogicalType()
});
}
}
/// <summary>
/// A JSON schema reader case that matches bytes or fixed schemas with decimal logical types.
/// </summary>
public class DecimalJsonSchemaReaderCase : FixedJsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object
&& ((string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Bytes || (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Fixed)
&& (string)@object[JsonAttributeToken.LogicalType] == JsonSchemaToken.Decimal;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!(token is JObject @object && IsMatch(@object)))
{
throw new ArgumentException("The decimal case can only be applied to \"bytes\" schemas with a \"decimal\" logical type.");
}
if ((string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Fixed)
{
var schema = new FixedSchema(GetQualifiedName(@object, scope), GetSize(@object))
{
Aliases = GetQualifiedAliases(@object, scope) ?? new string[0],
LogicalType = new DecimalLogicalType(GetPrecision(@object), GetScale(@object))
};
if (!cache.TryAdd(schema.FullName, schema))
{
throw new InvalidDataException($"Invalid fixed name; a definition for {schema.FullName} was already read.");
}
foreach (var alias in schema.Aliases)
{
if (!cache.TryAdd(alias, schema))
{
throw new InvalidDataException($"Invalid fixed alias; a definition for {alias} was already read.");
}
}
return schema;
}
else
{
return cache.GetOrAdd($"{JsonSchemaToken.Bytes}!{JsonSchemaToken.Decimal}", new BytesSchema()
{
LogicalType = new DecimalLogicalType(GetPrecision(@object), GetScale(@object))
});
}
}
/// <summary>
/// Extracts the precision from a decimal schema.
/// </summary>
protected virtual int GetPrecision(JToken @object)
{
if (!(@object[JsonAttributeToken.Precision] is JValue precision && precision.Type == JTokenType.Integer))
{
throw new InvalidDataException("Decimal schemas must contain a \"precision\" key with an integer as its value.");
}
return (int)precision;
}
/// <summary>
/// Extracts the scale from a decimal schema.
/// </summary>
protected virtual int GetScale(JToken @object)
{
if (!(@object[JsonAttributeToken.Scale] is JValue scale && scale.Type == JTokenType.Integer))
{
throw new InvalidDataException("Decimal schemas must contain a \"scale\" key with an integer as its value.");
}
return (int)scale;
}
}
/// <summary>
/// A JSON schema reader case that matches all unhandled names.
/// </summary>
public class DefaultJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
if (token is JObject @object)
{
token = @object[JsonAttributeToken.Type];
}
return token is JValue value && value.Type == JTokenType.String;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (token is JObject @object)
{
token = @object[JsonAttributeToken.Type];
}
if (!(token is JValue value && value.Type == JTokenType.String))
{
throw new ArgumentException("The primitive case can only be applied to valid primitive schema representations.");
}
var type = (string)value;
switch (type)
{
case JsonSchemaToken.Boolean:
return cache.GetOrAdd(type, _ => new BooleanSchema());
case JsonSchemaToken.Bytes:
return cache.GetOrAdd(type, _ => new BytesSchema());
case JsonSchemaToken.Double:
return cache.GetOrAdd(type, _ => new DoubleSchema());
case JsonSchemaToken.Float:
return cache.GetOrAdd(type, _ => new FloatSchema());
case JsonSchemaToken.Int:
return cache.GetOrAdd(type, _ => new IntSchema());
case JsonSchemaToken.Long:
return cache.GetOrAdd(type, _ => new LongSchema());
case JsonSchemaToken.Null:
return cache.GetOrAdd(type, _ => new NullSchema());
case JsonSchemaToken.String:
return cache.GetOrAdd(type, _ => new StringSchema());
case var name:
var qualified = QualifyName(name, scope);
if (cache.TryGetValue(qualified, out var match))
{
return match;
}
if (name != qualified && cache.TryGetValue(name, out match))
{
return match;
}
throw new UnknownSchemaException($"\"{name}\" is not a known schema.");
}
}
}
/// <summary>
/// A JSON schema reader case that matches fixed schemas with duration logical types.
/// </summary>
public class DurationJsonSchemaReaderCase : FixedJsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object
&& (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Fixed
&& (string)@object[JsonAttributeToken.LogicalType] == JsonSchemaToken.Duration;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!(token is JObject @object && IsMatch(@object)))
{
throw new ArgumentException("The duration case can only be applied to \"fixed\" schemas with a \"duration\" logical type.");
}
var schema = new FixedSchema(GetQualifiedName(@object, scope), GetSize(@object))
{
Aliases = GetQualifiedAliases(@object, scope) ?? new string[0],
LogicalType = new DurationLogicalType()
};
if (!cache.TryAdd(schema.FullName, schema))
{
throw new InvalidDataException($"Invalid duration name; a definition for {schema.FullName} was already read.");
}
foreach (var alias in schema.Aliases)
{
if (!cache.TryAdd(alias, schema))
{
throw new InvalidDataException($"Invalid duration alias; a definition for {alias} was already read.");
}
}
return schema;
}
}
/// <summary>
/// A JSON schema reader case that matches enum schemas.
/// </summary>
public class EnumJsonSchemaReaderCase : NamedJsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object && (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Enum;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!(token is JObject @object && (string)token[JsonAttributeToken.Type] == JsonSchemaToken.Enum))
{
throw new ArgumentException("The enum case can only be applied to valid enum schema representations.");
}
var schema = new EnumSchema(GetQualifiedName(@object, scope), GetSymbols(@object))
{
Aliases = GetQualifiedAliases(@object, scope) ?? new string[0],
Documentation = GetDoc(@object)
};
if (!cache.TryAdd(schema.FullName, schema))
{
throw new InvalidDataException($"Invalid enum name; a definition for {schema.FullName} was already read.");
}
foreach (var alias in schema.Aliases)
{
if (!cache.TryAdd(alias, schema))
{
throw new InvalidDataException($"Invalid enum alias; a definition for {alias} was already read.");
}
}
return schema;
}
/// <summary>
/// Extracts the documentation field from an enum schema.
/// </summary>
protected virtual string GetDoc(JToken @object)
{
if (!(@object[JsonAttributeToken.Doc] is JToken doc))
{
return null;
}
if (!(doc is JValue && doc.Type == JTokenType.String))
{
throw new InvalidDataException("A \"doc\" key must have a string as its value.");
}
return (string)doc;
}
/// <summary>
/// Extracts the symbols from an enum schema.
/// </summary>
protected virtual ICollection<string> GetSymbols(JToken @object)
{
if (!(@object[JsonAttributeToken.Symbols] is JArray symbols && symbols.All(s => s.Type == JTokenType.String)))
{
throw new InvalidDataException("Enum schemas must contain a \"symbols\" key with an array of strings as its value.");
}
return symbols.Select(s => (string)s).ToList();
}
}
/// <summary>
/// A JSON schema reader case that matches fixed schemas.
/// </summary>
public class FixedJsonSchemaReaderCase : NamedJsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object && (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Fixed;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!(token is JObject @object && (string)token[JsonAttributeToken.Type] == JsonSchemaToken.Fixed))
{
throw new ArgumentException("The fixed case can only be applied to valid fixed schema representations.");
}
var schema = new FixedSchema(GetQualifiedName(@object, scope), GetSize(@object))
{
Aliases = GetQualifiedAliases(@object, scope) ?? new string[0]
};
if (!cache.TryAdd(schema.FullName, schema))
{
throw new InvalidDataException($"Invalid fixed name; a definition for {schema.FullName} was already read.");
}
foreach (var alias in schema.Aliases)
{
if (!cache.TryAdd(alias, schema))
{
throw new InvalidDataException($"Invalid fixed alias; a definition for {alias} was already read.");
}
}
return schema;
}
/// <summary>
/// Extracts the size from a fixed schema.
/// </summary>
protected virtual int GetSize(JToken @object)
{
if (!(@object[JsonAttributeToken.Size] is JValue size && size.Type == JTokenType.Integer))
{
throw new InvalidDataException("Fixed schemas must contain a \"size\" key with an integer as its value.");
}
return (int)size;
}
}
/// <summary>
/// A JSON schema reader case that matches map schemas.
/// </summary>
public class MapJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// A schema reader to use to resolve value types.
/// </summary>
protected readonly INewtonsoftJsonSchemaReader Reader;
/// <summary>
/// Creates a new map case.
/// </summary>
/// <param name="reader">
/// A schema reader to use to resolve item types.
/// </param>
public MapJsonSchemaReaderCase(INewtonsoftJsonSchemaReader reader)
{
Reader = reader ?? throw new ArgumentNullException(nameof(reader), "Schema reader cannot be null.");
}
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object && (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Map;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!(token is JObject @object && (string)token[JsonAttributeToken.Type] == JsonSchemaToken.Map))
{
throw new ArgumentException("The map case can only be applied to valid map schema representations.");
}
var child = Reader.Read(GetValues(@object), cache, scope);
var key = cache.Single(p => p.Value == child).Key;
return cache.GetOrAdd($"{JsonSchemaToken.Map}<{key}>", _ => new MapSchema(child));
}
/// <summary>
/// Extracts the value type from a map schema.
/// </summary>
protected virtual JToken GetValues(JObject @object)
{
if (!(@object[JsonAttributeToken.Values] is JToken values))
{
throw new InvalidDataException("Map schemas must contain a \"values\" key.");
}
return values;
}
}
/// <summary>
/// A JSON schema reader case that matches long schemas with microsecond time logical types.
/// </summary>
public class MicrosecondTimeJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object
&& (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Long
&& (string)@object[JsonAttributeToken.LogicalType] == JsonSchemaToken.TimeMicroseconds;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!IsMatch(token))
{
throw new ArgumentException("The microsecond time case can only be applied to \"long\" schemas with a \"time-micros\" logical type.");
}
return cache.GetOrAdd($"{JsonSchemaToken.Long}!{JsonSchemaToken.TimeMicroseconds}", _ => new LongSchema()
{
LogicalType = new MicrosecondTimeLogicalType()
});
}
}
/// <summary>
/// A JSON schema reader case that matches long schemas with microsecond timestamp logical types.
/// </summary>
public class MicrosecondTimestampJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object
&& (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Long
&& (string)@object[JsonAttributeToken.LogicalType] == JsonSchemaToken.TimestampMicroseconds;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!IsMatch(token))
{
throw new ArgumentException("The microsecond timestamp case can only be applied to \"long\" schemas with a \"timestamp-micros\" logical type.");
}
return cache.GetOrAdd($"{JsonSchemaToken.Long}!{JsonSchemaToken.TimestampMicroseconds}", _ => new LongSchema()
{
LogicalType = new MicrosecondTimestampLogicalType()
});
}
}
/// <summary>
/// A JSON schema reader case that matches int schemas with millisecond time logical types.
/// </summary>
public class MillisecondTimeJsonSchemaReaderCase : JsonSchemaReaderCase
{
/// <summary>
/// Determines whether the case can be applied to a token.
/// </summary>
public override bool IsMatch(JToken token)
{
return token is JObject @object
&& (string)@object[JsonAttributeToken.Type] == JsonSchemaToken.Int
&& (string)@object[JsonAttributeToken.LogicalType] == JsonSchemaToken.TimeMilliseconds;
}
/// <summary>
/// Reads a schema from a JSON token.
/// </summary>
/// <param name="token">
/// The token to parse.
/// </param>
/// <param name="cache">
/// An optional schema cache. The cache is populated as the schema is read and can be used
/// to provide schemas for certain names or cache keys.
/// </param>
/// <param name="scope">
/// The surrounding namespace, if any.
/// </param>
public override Schema Read(JToken token, ConcurrentDictionary<string, Schema> cache, string scope)
{
if (!IsMatch(token))
{
throw new ArgumentException("The millisecond time case can only be applied to \"int\" schemas with a \"time-millis\" logical type.");
}
return cache.GetOrAdd($"{JsonSchemaToken.Int}!{JsonSchemaToken.TimeMilliseconds}", _ => new IntSchema()
{
LogicalType = new MillisecondTimeLogicalType()