-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathProtobufSchema.java
2727 lines (2550 loc) · 102 KB
/
ProtobufSchema.java
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
/*
* Copyright 2020 Confluent Inc.
*
* Licensed under the Confluent Community License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package io.confluent.kafka.schemaregistry.protobuf;
import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static io.confluent.kafka.schemaregistry.protobuf.ProtobufSchemaUtils.findMatchingElement;
import static io.confluent.kafka.schemaregistry.protobuf.ProtobufSchemaUtils.findMatchingNode;
import static io.confluent.kafka.schemaregistry.protobuf.ProtobufSchemaUtils.jsonToFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.EnumHashBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.protobuf.AnyProto;
import com.google.protobuf.ApiProto;
import com.google.protobuf.ByteString;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange;
import com.google.protobuf.DescriptorProtos.DescriptorProto.ReservedRange;
import com.google.protobuf.DescriptorProtos.EnumDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumDescriptorProto.EnumReservedRange;
import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldOptions.CType;
import com.google.protobuf.DescriptorProtos.FieldOptions.JSType;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileOptions.OptimizeMode;
import com.google.protobuf.DescriptorProtos.MethodDescriptorProto;
import com.google.protobuf.DescriptorProtos.MethodOptions.IdempotencyLevel;
import com.google.protobuf.DescriptorProtos.OneofDescriptorProto;
import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.GenericDescriptor;
import com.google.protobuf.DurationProto;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.EmptyProto;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.FieldMaskProto;
import com.google.protobuf.GeneratedMessageV3.ExtendableMessage;
import com.google.protobuf.Message;
import com.google.protobuf.SourceContextProto;
import com.google.protobuf.StructProto;
import com.google.protobuf.TimestampProto;
import com.google.protobuf.TypeProto;
import com.google.protobuf.WrappersProto;
import com.google.type.CalendarPeriodProto;
import com.google.type.ColorProto;
import com.google.type.DateProto;
import com.google.type.DateTimeProto;
import com.google.type.DayOfWeekProto;
import com.google.type.ExprProto;
import com.google.type.FractionProto;
import com.google.type.IntervalProto;
import com.google.type.LatLngProto;
import com.google.type.MoneyProto;
import com.google.type.MonthProto;
import com.google.type.PhoneNumberProto;
import com.google.type.PostalAddressProto;
import com.google.type.QuaternionProto;
import com.google.type.TimeOfDayProto;
import com.squareup.wire.Syntax;
import com.squareup.wire.schema.Field;
import com.squareup.wire.schema.Location;
import com.squareup.wire.schema.ProtoType;
import com.squareup.wire.schema.internal.parser.EnumConstantElement;
import com.squareup.wire.schema.internal.parser.EnumElement;
import com.squareup.wire.schema.internal.parser.ExtendElement;
import com.squareup.wire.schema.internal.parser.ExtensionsElement;
import com.squareup.wire.schema.internal.parser.FieldElement;
import com.squareup.wire.schema.internal.parser.MessageElement;
import com.squareup.wire.schema.internal.parser.OneOfElement;
import com.squareup.wire.schema.internal.parser.OptionElement;
import com.squareup.wire.schema.internal.parser.OptionElement.Kind;
import com.squareup.wire.schema.internal.parser.ProtoFileElement;
import com.squareup.wire.schema.internal.parser.ProtoParser;
import com.squareup.wire.schema.internal.parser.ReservedElement;
import com.squareup.wire.schema.internal.parser.RpcElement;
import com.squareup.wire.schema.internal.parser.ServiceElement;
import com.squareup.wire.schema.internal.parser.TypeElement;
import io.confluent.kafka.schemaregistry.ParsedSchema;
import io.confluent.kafka.schemaregistry.client.rest.entities.Metadata;
import io.confluent.kafka.schemaregistry.client.rest.entities.RuleKind;
import io.confluent.kafka.schemaregistry.client.rest.entities.RuleSet;
import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaEntity;
import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaReference;
import io.confluent.kafka.schemaregistry.protobuf.ProtobufSchemaUtils.FormatContext;
import io.confluent.kafka.schemaregistry.protobuf.diff.Context;
import io.confluent.kafka.schemaregistry.protobuf.diff.Difference;
import io.confluent.kafka.schemaregistry.protobuf.diff.SchemaDiff;
import io.confluent.kafka.schemaregistry.protobuf.dynamic.DynamicSchema;
import io.confluent.kafka.schemaregistry.protobuf.dynamic.EnumDefinition;
import io.confluent.kafka.schemaregistry.protobuf.dynamic.MessageDefinition;
import io.confluent.kafka.schemaregistry.protobuf.dynamic.ServiceDefinition;
import io.confluent.kafka.schemaregistry.rules.FieldTransform;
import io.confluent.kafka.schemaregistry.rules.RuleConditionException;
import io.confluent.kafka.schemaregistry.rules.RuleContext;
import io.confluent.kafka.schemaregistry.rules.RuleContext.FieldContext;
import io.confluent.kafka.schemaregistry.rules.RuleException;
import io.confluent.kafka.schemaregistry.utils.JacksonMapper;
import io.confluent.protobuf.MetaProto;
import io.confluent.protobuf.MetaProto.Meta;
import io.confluent.protobuf.type.DecimalProto;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import kotlin.Pair;
import kotlin.ranges.IntRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProtobufSchema implements ParsedSchema {
private static final Logger log = LoggerFactory.getLogger(ProtobufSchema.class);
public static final String TYPE = "PROTOBUF";
public static final String PROTO2 = "proto2";
public static final String PROTO3 = "proto3";
public static final String DOC_FIELD = "doc";
public static final String PARAMS_FIELD = "params";
public static final String TAGS_FIELD = "tags";
public static final String PRECISION_KEY = "precision";
public static final String SCALE_KEY = "scale";
public static final String DEFAULT_NAME = "default";
public static final String MAP_ENTRY_SUFFIX = "Entry"; // Suffix used by protoc
public static final String KEY_FIELD = "key";
public static final String VALUE_FIELD = "value";
public static final String CONFLUENT_PREFIX = "confluent.";
public static final String CONFLUENT_FILE_META = "confluent.file_meta";
public static final String CONFLUENT_MESSAGE_META = "confluent.message_meta";
public static final String CONFLUENT_FIELD_META = "confluent.field_meta";
public static final String CONFLUENT_ENUM_META = "confluent.enum_meta";
public static final String CONFLUENT_ENUM_VALUE_META = "confluent.enum_value_meta";
private static final String JAVA_PACKAGE = "java_package";
private static final String JAVA_OUTER_CLASSNAME = "java_outer_classname";
private static final String JAVA_MULTIPLE_FILES = "java_multiple_files";
private static final String JAVA_GENERATE_EQUALS_AND_HASH = "java_generate_equals_and_hash";
private static final String JAVA_STRING_CHECK_UTF8 = "java_string_check_utf8";
private static final String OPTIMIZE_FOR = "optimize_for";
private static final String GO_PACKAGE = "go_package";
private static final String CC_GENERIC_SERVICES = "cc_generic_services";
private static final String JAVA_GENERIC_SERVICES = "java_generic_services";
private static final String PY_GENERIC_SERVICES = "py_generic_services";
private static final String PHP_GENERIC_SERVICES = "php_generic_services";
private static final String DEPRECATED = "deprecated";
private static final String CC_ENABLE_ARENAS = "cc_enable_arenas";
private static final String OBJC_CLASS_PREFIX = "objc_class_prefix";
private static final String CSHARP_NAMESPACE = "csharp_namespace";
private static final String SWIFT_PREFIX = "swift_prefix";
private static final String PHP_CLASS_PREFIX = "php_class_prefix";
private static final String PHP_NAMESPACE = "php_namespace";
private static final String PHP_METADATA_NAMESPACE = "php_metadata_namespace";
private static final String RUBY_PACKAGE = "ruby_package";
private static final String NO_STANDARD_DESCRIPTOR_ACCESSOR = "no_standard_descriptor_accessor";
private static final String MAP_ENTRY = "map_entry";
private static final String CTYPE = "ctype";
private static final String PACKED = "packed";
private static final String JSTYPE = "jstype";
private static final String ALLOW_ALIAS = "allow_alias";
private static final String IDEMPOTENCY_LEVEL = "idempotency_level";
public static final Location DEFAULT_LOCATION = Location.get("");
public static final String CFLT_META_LOCATION = "confluent/meta.proto";
public static final String CFLT_DECIMAL_LOCATION = "confluent/type/decimal.proto";
public static final String CALENDAR_PERIOD_LOCATION = "google/type/calendar_period.proto";
public static final String COLOR_LOCATION = "google/type/color.proto";
public static final String DATE_LOCATION = "google/type/date.proto";
public static final String DATETIME_LOCATION = "google/type/datetime.proto";
public static final String DAY_OF_WEEK_LOCATION = "google/type/dayofweek.proto";
public static final String DECIMAL_LOCATION = "google/type/decimal.proto";
public static final String EXPR_LOCATION = "google/type/expr.proto";
public static final String FRACTION_LOCATION = "google/type/fraction.proto";
public static final String INTERVAL_LOCATION = "google/type/interval.proto";
public static final String LATLNG_LOCATION = "google/type/latlng.proto";
public static final String MONEY_LOCATION = "google/type/money.proto";
public static final String MONTH_LOCATION = "google/type/month.proto";
public static final String PHONE_NUMBER_LOCATION = "google/type/phone_number.proto";
public static final String POSTAL_ADDRESS_LOCATION = "google/type/postal_address.proto";
public static final String QUATERNION_LOCATION = "google/type/quaternion.proto";
public static final String TIME_OF_DAY_LOCATION = "google/type/timeofday.proto";
public static final String ANY_LOCATION = "google/protobuf/any.proto";
public static final String API_LOCATION = "google/protobuf/api.proto";
public static final String DESCRIPTOR_LOCATION = "google/protobuf/descriptor.proto";
public static final String DURATION_LOCATION = "google/protobuf/duration.proto";
public static final String EMPTY_LOCATION = "google/protobuf/empty.proto";
public static final String FIELD_MASK_LOCATION = "google/protobuf/field_mask.proto";
public static final String SOURCE_CONTEXT_LOCATION = "google/protobuf/source_context.proto";
public static final String STRUCT_LOCATION = "google/protobuf/struct.proto";
public static final String TIMESTAMP_LOCATION = "google/protobuf/timestamp.proto";
public static final String TYPE_LOCATION = "google/protobuf/type.proto";
public static final String WRAPPER_LOCATION = "google/protobuf/wrappers.proto";
private static final ProtoFileElement CFLT_META_SCHEMA =
toProtoFile(MetaProto.getDescriptor().toProto()) ;
private static final ProtoFileElement CFLT_DECIMAL_SCHEMA =
toProtoFile(DecimalProto.getDescriptor().toProto()) ;
private static final ProtoFileElement CALENDAR_PERIOD_SCHEMA =
toProtoFile(CalendarPeriodProto.getDescriptor().toProto()) ;
private static final ProtoFileElement COLOR_SCHEMA =
toProtoFile(ColorProto.getDescriptor().toProto()) ;
private static final ProtoFileElement DATE_SCHEMA =
toProtoFile(DateProto.getDescriptor().toProto()) ;
private static final ProtoFileElement DATETIME_SCHEMA =
toProtoFile(DateTimeProto.getDescriptor().toProto()) ;
private static final ProtoFileElement DAY_OF_WEEK_SCHEMA =
toProtoFile(DayOfWeekProto.getDescriptor().toProto()) ;
private static final ProtoFileElement DECIMAL_SCHEMA =
toProtoFile(com.google.type.DecimalProto.getDescriptor().toProto()) ;
private static final ProtoFileElement EXPR_SCHEMA =
toProtoFile(ExprProto.getDescriptor().toProto()) ;
private static final ProtoFileElement FRACTION_SCHEMA =
toProtoFile(FractionProto.getDescriptor().toProto()) ;
private static final ProtoFileElement INTERVAL_SCHEMA =
toProtoFile(IntervalProto.getDescriptor().toProto()) ;
private static final ProtoFileElement LATLNG_SCHEMA =
toProtoFile(LatLngProto.getDescriptor().toProto()) ;
private static final ProtoFileElement MONEY_SCHEMA =
toProtoFile(MoneyProto.getDescriptor().toProto()) ;
private static final ProtoFileElement MONTH_SCHEMA =
toProtoFile(MonthProto.getDescriptor().toProto()) ;
private static final ProtoFileElement PHONE_NUMBER_SCHEMA =
toProtoFile(PhoneNumberProto.getDescriptor().toProto()) ;
private static final ProtoFileElement POSTAL_ADDRESS_SCHEMA =
toProtoFile(PostalAddressProto.getDescriptor().toProto()) ;
private static final ProtoFileElement QUATERNION_SCHEMA =
toProtoFile(QuaternionProto.getDescriptor().toProto()) ;
private static final ProtoFileElement TIME_OF_DAY_SCHEMA =
toProtoFile(TimeOfDayProto.getDescriptor().toProto()) ;
private static final ProtoFileElement ANY_SCHEMA =
toProtoFile(AnyProto.getDescriptor().toProto()) ;
private static final ProtoFileElement API_SCHEMA =
toProtoFile(ApiProto.getDescriptor().toProto()) ;
private static final ProtoFileElement DESCRIPTOR_SCHEMA =
toProtoFile(DescriptorProtos.getDescriptor().toProto()) ;
private static final ProtoFileElement DURATION_SCHEMA =
toProtoFile(DurationProto.getDescriptor().toProto()) ;
private static final ProtoFileElement EMPTY_SCHEMA =
toProtoFile(EmptyProto.getDescriptor().toProto()) ;
private static final ProtoFileElement FIELD_MASK_SCHEMA =
toProtoFile(FieldMaskProto.getDescriptor().toProto()) ;
private static final ProtoFileElement SOURCE_CONTEXT_SCHEMA =
toProtoFile(SourceContextProto.getDescriptor().toProto()) ;
private static final ProtoFileElement STRUCT_SCHEMA =
toProtoFile(StructProto.getDescriptor().toProto()) ;
private static final ProtoFileElement TIMESTAMP_SCHEMA =
toProtoFile(TimestampProto.getDescriptor().toProto()) ;
private static final ProtoFileElement TYPE_SCHEMA =
toProtoFile(TypeProto.getDescriptor().toProto()) ;
private static final ProtoFileElement WRAPPER_SCHEMA =
toProtoFile(WrappersProto.getDescriptor().toProto()) ;
public static final ExtensionRegistry EXTENSION_REGISTRY;
private static final HashMap<String, ProtoFileElement> KNOWN_DEPENDENCIES;
static {
EXTENSION_REGISTRY = ExtensionRegistry.newInstance();
DecimalProto.registerAllExtensions(EXTENSION_REGISTRY);
MetaProto.registerAllExtensions(EXTENSION_REGISTRY);
KNOWN_DEPENDENCIES = new HashMap<>();
KNOWN_DEPENDENCIES.put(CFLT_META_LOCATION, CFLT_META_SCHEMA);
KNOWN_DEPENDENCIES.put(CFLT_DECIMAL_LOCATION, CFLT_DECIMAL_SCHEMA);
KNOWN_DEPENDENCIES.put(CALENDAR_PERIOD_LOCATION, CALENDAR_PERIOD_SCHEMA);
KNOWN_DEPENDENCIES.put(COLOR_LOCATION, COLOR_SCHEMA);
KNOWN_DEPENDENCIES.put(DATE_LOCATION, DATE_SCHEMA);
KNOWN_DEPENDENCIES.put(DATETIME_LOCATION, DATETIME_SCHEMA);
KNOWN_DEPENDENCIES.put(DAY_OF_WEEK_LOCATION, DAY_OF_WEEK_SCHEMA);
KNOWN_DEPENDENCIES.put(DECIMAL_LOCATION, DECIMAL_SCHEMA);
KNOWN_DEPENDENCIES.put(EXPR_LOCATION, EXPR_SCHEMA);
KNOWN_DEPENDENCIES.put(FRACTION_LOCATION, FRACTION_SCHEMA);
KNOWN_DEPENDENCIES.put(INTERVAL_LOCATION, INTERVAL_SCHEMA);
KNOWN_DEPENDENCIES.put(LATLNG_LOCATION, LATLNG_SCHEMA);
KNOWN_DEPENDENCIES.put(MONEY_LOCATION, MONEY_SCHEMA);
KNOWN_DEPENDENCIES.put(MONTH_LOCATION, MONTH_SCHEMA);
KNOWN_DEPENDENCIES.put(PHONE_NUMBER_LOCATION, PHONE_NUMBER_SCHEMA);
KNOWN_DEPENDENCIES.put(POSTAL_ADDRESS_LOCATION, POSTAL_ADDRESS_SCHEMA);
KNOWN_DEPENDENCIES.put(QUATERNION_LOCATION, QUATERNION_SCHEMA);
KNOWN_DEPENDENCIES.put(TIME_OF_DAY_LOCATION, TIME_OF_DAY_SCHEMA);
KNOWN_DEPENDENCIES.put(ANY_LOCATION, ANY_SCHEMA);
KNOWN_DEPENDENCIES.put(API_LOCATION, API_SCHEMA);
KNOWN_DEPENDENCIES.put(DESCRIPTOR_LOCATION, DESCRIPTOR_SCHEMA);
KNOWN_DEPENDENCIES.put(DURATION_LOCATION, DURATION_SCHEMA);
KNOWN_DEPENDENCIES.put(EMPTY_LOCATION, EMPTY_SCHEMA);
KNOWN_DEPENDENCIES.put(FIELD_MASK_LOCATION, FIELD_MASK_SCHEMA);
KNOWN_DEPENDENCIES.put(SOURCE_CONTEXT_LOCATION, SOURCE_CONTEXT_SCHEMA);
KNOWN_DEPENDENCIES.put(STRUCT_LOCATION, STRUCT_SCHEMA);
KNOWN_DEPENDENCIES.put(TIMESTAMP_LOCATION, TIMESTAMP_SCHEMA);
KNOWN_DEPENDENCIES.put(TYPE_LOCATION, TYPE_SCHEMA);
KNOWN_DEPENDENCIES.put(WRAPPER_LOCATION, WRAPPER_SCHEMA);
}
public static Set<String> knownTypes() {
return KNOWN_DEPENDENCIES.keySet();
}
private final ProtoFileElement schemaObj;
private final Integer version;
private final String name;
private final List<SchemaReference> references;
private final Map<String, ProtoFileElement> dependencies;
private final Metadata metadata;
private final RuleSet ruleSet;
private transient String canonicalString;
private transient DynamicSchema dynamicSchema;
private transient Descriptor descriptor;
private transient int hashCode = NO_HASHCODE;
private static final int NO_HASHCODE = Integer.MIN_VALUE;
private static final Base64.Encoder base64Encoder = Base64.getEncoder();
private static final Base64.Decoder base64Decoder = Base64.getDecoder();
private static final ObjectMapper jsonMapper = JacksonMapper.INSTANCE;
private static volatile Method extensionFields;
public ProtobufSchema(String schemaString) {
this(schemaString, Collections.emptyList(), Collections.emptyMap(), null, null);
}
public ProtobufSchema(
String schemaString,
List<SchemaReference> references,
Map<String, String> resolvedReferences,
Integer version,
String name
) {
this(schemaString, references, resolvedReferences, null, null, version, name);
}
public ProtobufSchema(
String schemaString,
List<SchemaReference> references,
Map<String, String> resolvedReferences,
Metadata metadata,
RuleSet ruleSet,
Integer version,
String name
) {
try {
this.schemaObj = schemaString != null ? toProtoFile(schemaString) : null;
this.version = version;
this.name = name;
this.references = Collections.unmodifiableList(references);
this.dependencies = Collections.unmodifiableMap(resolvedReferences.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> toProtoFile(e.getValue())
)));
this.metadata = metadata;
this.ruleSet = ruleSet;
} catch (IllegalStateException e) {
log.error("Could not parse Protobuf schema {} with references {}", schemaString,
references, e);
throw e;
}
}
public ProtobufSchema(
ProtoFileElement protoFileElement,
List<SchemaReference> references,
Map<String, ProtoFileElement> dependencies
) {
this.schemaObj = protoFileElement;
this.version = null;
this.name = null;
this.references = Collections.unmodifiableList(references);
this.dependencies = Collections.unmodifiableMap(dependencies);
this.metadata = null;
this.ruleSet = null;
}
public ProtobufSchema(Descriptor descriptor) {
this(descriptor, Collections.emptyList());
}
public ProtobufSchema(Descriptor descriptor, List<SchemaReference> references) {
Map<String, ProtoFileElement> dependencies = new HashMap<>();
this.schemaObj = toProtoFile(descriptor.getFile(), dependencies);
this.version = null;
this.name = descriptor.getFullName();
this.references = Collections.unmodifiableList(references);
this.dependencies = Collections.unmodifiableMap(dependencies);
this.metadata = null;
this.ruleSet = null;
this.descriptor = descriptor;
}
public ProtobufSchema(EnumDescriptor enumDescriptor) {
this(enumDescriptor, Collections.emptyList());
}
public ProtobufSchema(EnumDescriptor enumDescriptor, List<SchemaReference> references) {
Map<String, ProtoFileElement> dependencies = new HashMap<>();
this.schemaObj = toProtoFile(enumDescriptor.getFile(), dependencies);
this.version = null;
this.name = enumDescriptor.getFullName();
this.references = Collections.unmodifiableList(references);
this.dependencies = Collections.unmodifiableMap(dependencies);
this.metadata = null;
this.ruleSet = null;
this.descriptor = null;
}
public ProtobufSchema(FileDescriptor fileDescriptor) {
this(fileDescriptor, Collections.emptyList());
}
public ProtobufSchema(FileDescriptor fileDescriptor, List<SchemaReference> references) {
Map<String, ProtoFileElement> dependencies = new HashMap<>();
this.schemaObj = toProtoFile(fileDescriptor, dependencies);
this.version = null;
this.name = null;
this.references = Collections.unmodifiableList(references);
this.dependencies = Collections.unmodifiableMap(dependencies);
this.metadata = null;
this.ruleSet = null;
this.descriptor = null;
}
private ProtobufSchema(
ProtoFileElement schemaObj,
Integer version,
String name,
List<SchemaReference> references,
Map<String, ProtoFileElement> dependencies,
Metadata metadata,
RuleSet ruleSet,
String canonicalString,
DynamicSchema dynamicSchema,
Descriptor descriptor
) {
this.schemaObj = schemaObj;
this.version = version;
this.name = name;
this.references = references;
this.dependencies = dependencies;
this.metadata = metadata;
this.ruleSet = ruleSet;
this.canonicalString = canonicalString;
this.dynamicSchema = dynamicSchema;
this.descriptor = descriptor;
}
@Override
public ProtobufSchema copy() {
return new ProtobufSchema(
this.schemaObj,
this.version,
this.name,
this.references,
this.dependencies,
this.metadata,
this.ruleSet,
this.canonicalString,
this.dynamicSchema,
this.descriptor
);
}
@Override
public ProtobufSchema copy(Integer version) {
return new ProtobufSchema(
this.schemaObj,
version,
this.name,
this.references,
this.dependencies,
this.metadata,
this.ruleSet,
this.canonicalString,
this.dynamicSchema,
this.descriptor
);
}
public ProtobufSchema copy(String name) {
return new ProtobufSchema(
this.schemaObj,
this.version,
name,
this.references,
this.dependencies,
this.metadata,
this.ruleSet,
this.canonicalString,
this.dynamicSchema,
// reset descriptor if names not equal
Objects.equals(this.name, name) ? this.descriptor : null
);
}
public ProtobufSchema copy(List<SchemaReference> references) {
return copy(references, this.dependencies);
}
public ProtobufSchema copy(
List<SchemaReference> references, Map<String, ProtoFileElement> dependencies) {
return new ProtobufSchema(
this.schemaObj,
this.version,
this.name,
references,
dependencies,
this.metadata,
this.ruleSet,
this.canonicalString,
this.dynamicSchema,
this.descriptor
);
}
@Override
public ProtobufSchema copy(Metadata metadata, RuleSet ruleSet) {
return new ProtobufSchema(
this.schemaObj,
this.version,
this.name,
this.references,
this.dependencies,
metadata,
ruleSet,
this.canonicalString,
this.dynamicSchema,
this.descriptor
);
}
@Override
public ParsedSchema copy(Map<SchemaEntity, Set<String>> tagsToAdd,
Map<SchemaEntity, Set<String>> tagsToRemove) {
ProtobufSchema schemaCopy = this.copy();
JsonNode original = jsonMapper.valueToTree(schemaCopy.rawSchema());
modifySchemaTags(schemaCopy.rawSchema(), original, tagsToAdd, tagsToRemove);
try {
ProtoFileElement newFileElement = jsonToFile(original);
return new ProtobufSchema(newFileElement.toSchema(),
schemaCopy.references(),
schemaCopy.dependencies().entrySet().stream().collect(
Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().toSchema())),
schemaCopy.metadata(),
schemaCopy.ruleSet(),
schemaCopy.version(),
schemaCopy.name()
);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot deserialize json into ProtoFileElement", e);
}
}
public ProtobufSchema copyWithSchema(String schema) {
return new ProtobufSchema(
toProtoFile(schema),
this.version,
this.name,
references,
this.dependencies,
this.metadata,
this.ruleSet,
schema,
null,
null
);
}
private ProtoFileElement toProtoFile(String schema) {
try {
return ProtoParser.Companion.parse(DEFAULT_LOCATION, schema);
} catch (Exception e) {
try {
// Attempt to parse binary FileDescriptorProto
byte[] bytes = base64Decoder.decode(schema);
return toProtoFile(FileDescriptorProto.parseFrom(bytes, EXTENSION_REGISTRY));
} catch (Exception pe) {
throw new IllegalArgumentException("Could not parse Protobuf - " + e.getMessage(), e);
}
}
}
private static ProtoFileElement toProtoFile(
FileDescriptor file, Map<String, ProtoFileElement> dependencies
) {
for (FileDescriptor dependency : file.getDependencies()) {
String depName = dependency.getName();
dependencies.put(depName, toProtoFile(dependency, dependencies));
}
return toProtoFile(file.toProto());
}
private static ProtoFileElement toProtoFile(FileDescriptorProto file) {
String packageName = file.getPackage();
// Don't set empty package name
if (packageName.isEmpty()) {
packageName = null;
}
Syntax syntax = null;
switch (file.getSyntax()) {
case PROTO2:
syntax = Syntax.PROTO_2;
break;
case PROTO3:
syntax = Syntax.PROTO_3;
break;
default:
break;
}
ImmutableList.Builder<TypeElement> types = ImmutableList.builder();
for (DescriptorProto md : file.getMessageTypeList()) {
MessageElement message = toMessage(file, md);
types.add(message);
}
for (EnumDescriptorProto ed : file.getEnumTypeList()) {
EnumElement enumer = toEnum(ed);
types.add(enumer);
}
ImmutableList.Builder<ServiceElement> services = ImmutableList.builder();
for (ServiceDescriptorProto sd : file.getServiceList()) {
ServiceElement service = toService(sd);
services.add(service);
}
ImmutableList.Builder<String> imports = ImmutableList.builder();
ImmutableList.Builder<String> publicImports = ImmutableList.builder();
List<String> dependencyList = file.getDependencyList();
Set<Integer> publicDependencyList = new HashSet<>(file.getPublicDependencyList());
for (int i = 0; i < dependencyList.size(); i++) {
String depName = dependencyList.get(i);
if (publicDependencyList.contains(i)) {
publicImports.add(depName);
} else {
imports.add(depName);
}
}
ImmutableList.Builder<OptionElement> options = ImmutableList.builder();
if (file.getOptions().hasJavaPackage()) {
options.add(new OptionElement(
JAVA_PACKAGE, Kind.STRING, file.getOptions().getJavaPackage(), false));
}
if (file.getOptions().hasJavaOuterClassname()) {
options.add(new OptionElement(
JAVA_OUTER_CLASSNAME, Kind.STRING, file.getOptions().getJavaOuterClassname(), false));
}
if (file.getOptions().hasJavaMultipleFiles()) {
options.add(new OptionElement(
JAVA_MULTIPLE_FILES, Kind.BOOLEAN, file.getOptions().getJavaMultipleFiles(), false));
}
if (file.getOptions().hasJavaGenerateEqualsAndHash()) {
options.add(new OptionElement(
JAVA_GENERATE_EQUALS_AND_HASH, Kind.BOOLEAN,
file.getOptions().getJavaGenerateEqualsAndHash(), false));
}
if (file.getOptions().hasJavaStringCheckUtf8()) {
options.add(new OptionElement(
JAVA_STRING_CHECK_UTF8, Kind.BOOLEAN, file.getOptions().getJavaStringCheckUtf8(), false));
}
if (file.getOptions().hasOptimizeFor()) {
options.add(new OptionElement(
OPTIMIZE_FOR, Kind.ENUM, file.getOptions().getOptimizeFor(), false));
}
if (file.getOptions().hasGoPackage()) {
options.add(new OptionElement(
GO_PACKAGE, Kind.STRING, file.getOptions().getGoPackage(), false));
}
if (file.getOptions().hasCcGenericServices()) {
options.add(new OptionElement(
CC_GENERIC_SERVICES, Kind.BOOLEAN, file.getOptions().getCcGenericServices(), false));
}
if (file.getOptions().hasJavaGenericServices()) {
options.add(new OptionElement(
JAVA_GENERIC_SERVICES, Kind.BOOLEAN, file.getOptions().getJavaGenericServices(), false));
}
if (file.getOptions().hasPyGenericServices()) {
options.add(new OptionElement(
PY_GENERIC_SERVICES, Kind.BOOLEAN, file.getOptions().getPyGenericServices(), false));
}
if (file.getOptions().hasPhpGenericServices()) {
options.add(new OptionElement(
PHP_GENERIC_SERVICES, Kind.BOOLEAN, file.getOptions().getPhpGenericServices(), false));
}
if (file.getOptions().hasDeprecated()) {
options.add(new OptionElement(
DEPRECATED, Kind.BOOLEAN, file.getOptions().getDeprecated(), false));
}
if (file.getOptions().hasCcEnableArenas()) {
options.add(new OptionElement(
CC_ENABLE_ARENAS, Kind.BOOLEAN, file.getOptions().getCcEnableArenas(), false));
}
if (file.getOptions().hasObjcClassPrefix()) {
options.add(new OptionElement(
OBJC_CLASS_PREFIX, Kind.STRING, file.getOptions().getObjcClassPrefix(), false));
}
if (file.getOptions().hasCsharpNamespace()) {
options.add(new OptionElement(
CSHARP_NAMESPACE, Kind.STRING, file.getOptions().getCsharpNamespace(), false));
}
if (file.getOptions().hasSwiftPrefix()) {
options.add(new OptionElement(
SWIFT_PREFIX, Kind.STRING, file.getOptions().getSwiftPrefix(), false));
}
if (file.getOptions().hasPhpClassPrefix()) {
options.add(new OptionElement(
PHP_CLASS_PREFIX, Kind.STRING, file.getOptions().getPhpClassPrefix(), false));
}
if (file.getOptions().hasPhpNamespace()) {
options.add(new OptionElement(
PHP_NAMESPACE, Kind.STRING, file.getOptions().getPhpNamespace(), false));
}
if (file.getOptions().hasPhpMetadataNamespace()) {
options.add(new OptionElement(
PHP_METADATA_NAMESPACE, Kind.STRING, file.getOptions().getPhpMetadataNamespace(), false));
}
if (file.getOptions().hasRubyPackage()) {
options.add(new OptionElement(
RUBY_PACKAGE, Kind.STRING, file.getOptions().getRubyPackage(), false));
}
if (file.getOptions().hasExtension(MetaProto.fileMeta)) {
Meta meta = file.getOptions().getExtension(MetaProto.fileMeta);
OptionElement option = toOption(CONFLUENT_FILE_META, meta);
if (option != null) {
options.add(option);
}
}
options.addAll(toCustomOptions(file.getOptions()));
ImmutableList.Builder<ExtendElement> extendElements =
toExtendElements(file, file.getExtensionList());
return new ProtoFileElement(DEFAULT_LOCATION,
packageName,
syntax,
imports.build(),
publicImports.build(),
types.build(),
services.build(),
extendElements.build(),
options.build()
);
}
private static ImmutableList.Builder<ExtendElement> toExtendElements(
FileDescriptorProto file, List<FieldDescriptorProto> fields) {
Map<String, ImmutableList.Builder<FieldElement>> extendFieldElements = new LinkedHashMap<>();
for (FieldDescriptorProto fd : fields) {
// Note that the extendee is a fully qualified name
ImmutableList.Builder<FieldElement> extendFields = extendFieldElements.computeIfAbsent(
fd.getExtendee(), k -> ImmutableList.builder());
extendFields.add(toField(file, fd, false));
}
ImmutableList.Builder<ExtendElement> extendElements = ImmutableList.builder();
for (Map.Entry<String, ImmutableList.Builder<FieldElement>> extendFieldElement :
extendFieldElements.entrySet()) {
extendElements.add(new ExtendElement(DEFAULT_LOCATION,
extendFieldElement.getKey(), "", extendFieldElement.getValue().build()));
}
return extendElements;
}
private static List<OptionElement> toCustomOptions(ExtendableMessage<?> options) {
// Uncomment this in case the getExtensionFields method is deprecated
//return options.getAllFields().entrySet().stream()
return getExtensionFields(options).entrySet().stream()
.filter(e -> e.getKey().isExtension()
&& !e.getKey().getFullName().startsWith(CONFLUENT_PREFIX))
.flatMap(e -> toOptionElements(e.getKey().getFullName(), e.getValue()))
.collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
private static Map<Descriptors.FieldDescriptor, Object> getExtensionFields(
ExtendableMessage<?> options) {
// We use reflection to access getExtensionFields as an optimization over calling getAllFields
try {
if (extensionFields == null) {
synchronized (ProtobufSchema.class) {
if (extensionFields == null) {
extensionFields = ExtendableMessage.class.getDeclaredMethod("getExtensionFields");
}
}
extensionFields.setAccessible(true);
}
return (Map<Descriptors.FieldDescriptor, Object>) extensionFields.invoke(options);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private static Stream<OptionElement> toOptionElements(String name, Object value) {
if (value instanceof List) {
return ((List<?>) value).stream().map(v -> toOptionElement(name, v));
} else {
return Stream.of(toOptionElement(name, value));
}
}
private static OptionElement toOptionElement(String name, Object value) {
return new OptionElement(name, toKind(value), toOptionValue(value, false), true);
}
private static Kind toKind(Object value) {
if (value instanceof String) {
return Kind.STRING;
} else if (value instanceof Boolean) {
return Kind.BOOLEAN;
} else if (value instanceof Number) {
return Kind.NUMBER;
} else if (value instanceof Enum || value instanceof EnumValueDescriptor) {
return Kind.ENUM;
} else if (value instanceof List) {
return Kind.LIST;
} else if (value instanceof Message) {
return Kind.MAP;
} else {
throw new IllegalArgumentException("Unsupported option type " + value.getClass().getName());
}
}
private static Object toOptionValue(Object value, boolean isMapValue) {
if (value instanceof List) {
return ((List<?>) value).stream()
.map(o -> toOptionValue(o, false))
.collect(Collectors.toList());
} else if (value instanceof Message) {
return toOptionMap((Message) value);
} else {
if (isMapValue) {
if (value instanceof Boolean) {
return new OptionElement.OptionPrimitive(Kind.BOOLEAN, value);
} else if (value instanceof Enum) {
return new OptionElement.OptionPrimitive(Kind.ENUM, value);
} else if (value instanceof Number) {
return new OptionElement.OptionPrimitive(Kind.NUMBER, value);
}
}
return value;
}
}
private static Map<String, Object> toOptionMap(Message message) {
return message.getAllFields().entrySet().stream()
.map(e -> new Pair<>(toOptionMapKey(e.getKey()), toOptionValue(e.getValue(), true)))
.filter(p -> p.getSecond() != null)
.collect(Collectors.toMap(Pair::getFirst, Pair::getSecond,
(e1, e2) -> e1, LinkedHashMap::new));
}
private static String toOptionMapKey(FieldDescriptor field) {
return field.isExtension() ? "[" + field.getFullName() + "]" : field.getName();
}
private static MessageElement toMessage(FileDescriptorProto file, DescriptorProto descriptor) {
String name = descriptor.getName();
log.trace("*** msg name: {}", name);
ImmutableList.Builder<FieldElement> fields = ImmutableList.builder();
ImmutableList.Builder<TypeElement> nested = ImmutableList.builder();
ImmutableList.Builder<ReservedElement> reserved = ImmutableList.builder();
ImmutableList.Builder<ExtensionsElement> extensions = ImmutableList.builder();
LinkedHashMap<String, ImmutableList.Builder<FieldElement>> oneofsMap = new LinkedHashMap<>();
for (OneofDescriptorProto od : descriptor.getOneofDeclList()) {
oneofsMap.put(od.getName(), ImmutableList.builder());
}
List<Map.Entry<String, ImmutableList.Builder<FieldElement>>> oneofs =
new ArrayList<>(oneofsMap.entrySet());
for (FieldDescriptorProto fd : descriptor.getFieldList()) {
if (fd.hasOneofIndex() && !fd.getProto3Optional()) {
FieldElement field = toField(file, fd, true);
oneofs.get(fd.getOneofIndex()).getValue().add(field);
} else {
FieldElement field = toField(file, fd, false);
fields.add(field);
}
}
for (DescriptorProto nestedDesc : descriptor.getNestedTypeList()) {
MessageElement nestedMessage = toMessage(file, nestedDesc);
nested.add(nestedMessage);
}
for (EnumDescriptorProto nestedDesc : descriptor.getEnumTypeList()) {
EnumElement nestedEnum = toEnum(nestedDesc);
nested.add(nestedEnum);
}
for (ReservedRange range : descriptor.getReservedRangeList()) {
ReservedElement reservedElem = toReserved(range);
reserved.add(reservedElem);
}
for (String reservedName : descriptor.getReservedNameList()) {
ReservedElement reservedElem = new ReservedElement(
DEFAULT_LOCATION,
"",
Collections.singletonList(reservedName)
);
reserved.add(reservedElem);
}
for (ExtensionRange extensionRange : descriptor.getExtensionRangeList()) {
ExtensionsElement extension = toExtension(extensionRange);
extensions.add(extension);
}
ImmutableList.Builder<OptionElement> options = ImmutableList.builder();
if (descriptor.getOptions().hasNoStandardDescriptorAccessor()) {
OptionElement option = new OptionElement(
NO_STANDARD_DESCRIPTOR_ACCESSOR, Kind.BOOLEAN,
descriptor.getOptions().getNoStandardDescriptorAccessor(), false
);
options.add(option);
}
if (descriptor.getOptions().hasDeprecated()) {
OptionElement option = new OptionElement(
DEPRECATED, Kind.BOOLEAN,
descriptor.getOptions().getDeprecated(), false
);
options.add(option);
}
if (descriptor.getOptions().hasMapEntry()) {
OptionElement option = new OptionElement(
MAP_ENTRY, Kind.BOOLEAN,
descriptor.getOptions().getMapEntry(), false
);
options.add(option);
}
if (descriptor.getOptions().hasExtension(MetaProto.messageMeta)) {
Meta meta = descriptor.getOptions().getExtension(MetaProto.messageMeta);
OptionElement option = toOption(CONFLUENT_MESSAGE_META, meta);
if (option != null) {
options.add(option);
}
}
options.addAll(toCustomOptions(descriptor.getOptions()));
ImmutableList.Builder<ExtendElement> extendElements =
toExtendElements(file, descriptor.getExtensionList());
// NOTE: skip groups
return new MessageElement(DEFAULT_LOCATION,
name,
"",
nested.build(),
options.build(),
reserved.build(),
fields.build(),
oneofs.stream()
.map(e -> toOneof(e.getKey(), e.getValue()))