-
Notifications
You must be signed in to change notification settings - Fork 562
/
generator.py
executable file
·2037 lines (1839 loc) · 63.3 KB
/
generator.py
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
#!/usr/bin/env python3
#
# Copyright 2020 Redpanda Data, Inc.
#
# Use of this software is governed by the Business Source License
# included in the file licenses/BSL.md
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0
#
# Code generator for kafka messages
# =================================
#
# Message schemas are taken from the 2.4 branch.
#
# Kafka reference on schema:
# https://github.com/apache/kafka/blob/2.4/clients/src/main/resources/common/message/README.md
#
# TODO:
# - It has become clear that for the vast majority of cases where are using the
# path_type_map to override types, it would be more efficient to specify the
# same mapping using the field_name_type_map + a whitelist of request types.
#
# - Handle ignorable fields. Currently we handle nullable fields properly. The
# ignorable flag on a field doesn't change the wire protocol, but gives
# instruction on how things should behave when there is missing data.
#
# - Build a more robust way to define messages and their contents as
# sensitive. The current approach relies on a list of root structs to
# generate stream operators that don't contain sensitive information. We
# should strongly consider leveraging the C++ type system to generate code
# that forces users to explicitly "unwrap" sensitive fields before use, to
# make it easier to audit where sensitive information is used.
import io
import json
import pathlib
import re
import sys
import textwrap
import jsonschema
import jinja2
import enum
# Type overrides
# ==============
#
# The following four mappings:
#
# - path_type_map
# - entity_type_map
# - field_name_type_map
# - basic_type_map
#
# control how the types in a kafka message schema translate to redpanda types.
# the mappings are in order of preference. that is, a match in path_type_map
# will override a match in the entity_type_map.
# nested dictionary path within a json document
path_type_map = {
"OffsetFetchRequestData": {
"Topics": {
"PartitionIndexes": ("model::partition_id", "int32"),
}
},
"OffsetFetchResponseData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"CommittedOffset": ("model::offset", "int64"),
"CommittedLeaderEpoch": ("kafka::leader_epoch", "int32"),
},
}
},
"OffsetCommitRequestData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"CommittedOffset": ("model::offset", "int64"),
"CommittedLeaderEpoch": ("kafka::leader_epoch", "int32"),
},
},
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
},
"AddPartitionsToTxnRequestData": {
"Topics": {
"Partitions": ("model::partition_id", "int32")
}
},
"AddPartitionsToTxnResponseData": {
"Results": {
"Results": {
"PartitionIndex": ("model::partition_id", "int32")
}
}
},
"OffsetDeleteRequestData": {
"GroupId": ("kafka::group_id", "string"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32")
}
}
},
"OffsetDeleteResponseData": {
"ErrorCode": ("kafka::error_code", "int16"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"ErrorCode": ("kafka::error_code", "int16"),
}
}
},
"TxnOffsetCommitRequestData": {
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"CommittedOffset": ("model::offset", "int64"),
"CommittedLeaderEpoch": ("kafka::leader_epoch", "int32"),
},
}
},
"JoinGroupRequestData": {
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
"ProtocolType": ("kafka::protocol_type", "string"),
"Protocols": {
"Name": ("kafka::protocol_name", "string"),
},
},
"JoinGroupResponseData": {
"GenerationId": ("kafka::generation_id", "int32"),
"ProtocolName": ("kafka::protocol_name", "string"),
"Leader": ("kafka::member_id", "string"),
"MemberId": ("kafka::member_id", "string"),
"Members": {
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
},
},
"SyncGroupRequestData": {
"GenerationId": ("kafka::generation_id", "int32"),
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
"Assignments": {
"MemberId": ("kafka::member_id", "string"),
},
},
"HeartbeatRequestData": {
"GenerationId": ("kafka::generation_id", "int32"),
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
},
"LeaveGroupRequestData": {
"MemberId": ("kafka::member_id", "string"),
"Members": {
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
},
},
"LeaveGroupResponseData": {
"Members": {
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
},
},
"DeleteTopicsRequestData": {
"TimeoutMs": ("std::chrono::milliseconds", "int32"),
},
"CreateTopicsRequestData": {
"timeoutMs": ("std::chrono::milliseconds", "int32"),
"Topics": {
"Assignments": {
"PartitionIndex": ("model::partition_id", "int32"),
},
},
},
"CreateTopicsResponseData": {
"Topics": {
"Configs": {
"ConfigSource": ("kafka::describe_configs_source", "int8"),
},
"TopicConfigErrorCode": ("kafka::error_code", "int16"),
},
},
"FindCoordinatorRequestData": {
"KeyType": ("kafka::coordinator_type", "int8"),
},
"ListOffsetRequestData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"Timestamp": ("model::timestamp", "int64"),
"CurrentLeaderEpoch": ("kafka::leader_epoch", "int32"),
},
},
},
"ListOffsetResponseData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"Timestamp": ("model::timestamp", "int64"),
"Offset": ("model::offset", "int64"),
"LeaderEpoch": ("kafka::leader_epoch", "int32"),
},
},
},
"DescribeGroupsResponseData": {
"Groups": {
"ProtocolType": ("kafka::protocol_type", "string"),
"Members": {
"MemberId": ("kafka::member_id", "string"),
"GroupInstanceId": ("kafka::group_instance_id", "string"),
},
},
},
"DescribeConfigsRequestData": {
"Resources": {
"ResourceType": ("kafka::config_resource_type", "int8"),
},
},
"DescribeConfigsResponseData": {
"Results": {
"ResourceType": ("kafka::config_resource_type", "int8"),
"Configs": {
"ConfigSource": ("kafka::describe_configs_source", "int8"),
"ConfigType": ("kafka::describe_configs_type", "int8"),
},
},
},
"ProduceRequestData": {
"TimeoutMs": ("std::chrono::milliseconds", "int32"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"Records": ("kafka::produce_request_record_data", "iobuf"),
},
},
},
"ProduceResponseData": {
"Responses": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"BaseOffset": ("model::offset", "int64"),
"LogAppendTimeMs": ("model::timestamp", "int64"),
"LogStartOffset": ("model::offset", "int64"),
},
},
},
"MetadataResponseData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"IsrNodes": ("model::node_id", "int32"),
"LeaderEpoch": ("kafka::leader_epoch", "int32"),
},
},
},
"FetchRequestData": {
"MaxWaitMs": ("std::chrono::milliseconds", "int32"),
"IsolationLevel": ("model::isolation_level", "int8"),
"ReplicaId": ("model::node_id", "int32"),
"RackId": ("model::rack_id", "string"),
"Topics": {
"FetchPartitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"FetchOffset": ("model::offset", "int64"),
"CurrentLeaderEpoch": ("kafka::leader_epoch", "int32"),
},
},
},
"FetchResponseData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"HighWatermark": ("model::offset", "int64"),
"LastStableOffset": ("model::offset", "int64"),
"LogStartOffset": ("model::offset", "int64"),
"Records": ("kafka::batch_reader", "fetch_record_set"),
"PreferredReadReplica": ("model::node_id", "int32"),
},
},
},
"InitProducerIdRequestData": {
"TransactionTimeoutMs": ("std::chrono::milliseconds", "int32")
},
"CreatePartitionsRequestData": {
"TimeoutMs": ("std::chrono::milliseconds", "int32")
},
"OffsetForLeaderEpochRequestData": {
"Topics": {
"Partitions": {
"Partition": ("model::partition_id", "int32"),
"CurrentLeaderEpoch": ("kafka::leader_epoch", "int32"),
"LeaderEpoch": ("kafka::leader_epoch", "int32"),
}
}
},
"OffsetForLeaderEpochResponseData": {
"Topics": {
"Partitions": {
"Partition": ("model::partition_id", "int32"),
"LeaderEpoch": ("kafka::leader_epoch", "int32"),
"EndOffset": ("model::offset", "int64"),
}
}
},
"DeleteRecordsRequestData": {
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"Offset": ("model::offset", "int64"),
}
},
"TimeoutMs": ("std::chrono::milliseconds", "int32")
},
"DeleteRecordsResponseData": {
"ThrottleTimeMs": ("std::chrono::milliseconds", "int32"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
"LowWatermark": ("model::offset", "int64"),
"ErrorCode": ("kafka::error_code", "int16")
}
}
},
"AlterPartitionReassignmentsRequestData": {
"TimeoutMs": ("std::chrono::milliseconds", "int32"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
},
}
},
"AlterPartitionReassignmentsResponseData": {
"ThrottleTimeMs": ("std::chrono::milliseconds", "int32"),
"Responses": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
},
}
},
"ListPartitionReassignmentsRequestData": {
"TimeoutMs": ("std::chrono::milliseconds", "int32"),
"Topics": {
"PartitionIndexes": ("model::partition_id", "int32"),
}
},
"ListPartitionReassignmentsResponseData": {
"ThrottleTimeMs": ("std::chrono::milliseconds", "int32"),
"Topics": {
"Partitions": {
"PartitionIndex": ("model::partition_id", "int32"),
},
}
},
"DescribeProducersRequestData": {
"Topics": {
"PartitionIndexes": ("model::partition_id", "int32"),
}
},
"DescribeTransactionsResponseData": {
"Topics": {
"Partitions": ("model::partition_id", "int32"),
}
},
"DescribeClientQuotasRequestData": {
"Components": {
"MatchType": ("kafka::describe_client_quotas_match_type", "int8"),
},
},
}
# a few kafka field types specify an entity type
entity_type_map = dict(
groupId=("kafka::group_id", "string"),
transactionalId=("kafka::transactional_id", "string"),
topicName=("model::topic", "string"),
uuid=("kafka::uuid", "uuid"),
brokerId=("model::node_id", "int32"),
producerId=("kafka::producer_id", "int64"),
)
# mapping specified as a combination of native type and field name
field_name_type_map = {
("int16", "ErrorCode"): ("kafka::error_code", None),
("int32", "ThrottleTimeMs"): ("std::chrono::milliseconds", 0),
("int32", "SessionTimeoutMs"): ("std::chrono::milliseconds", None),
("int32", "RebalanceTimeoutMs"): ("std::chrono::milliseconds", None),
}
# primitive types
basic_type_map = dict(
string=("ss::sstring", "read_string_with_control_check()",
"read_nullable_string_with_control_check()",
"read_flex_string_with_control_check()",
"read_nullable_flex_string_with_control_check()"),
bytes=("bytes", "read_bytes()", None, "read_flex_bytes()", None),
bool=("bool", "read_bool()"),
int8=("int8_t", "read_int8()"),
int16=("int16_t", "read_int16()"),
int32=("int32_t", "read_int32()"),
int64=("int64_t", "read_int64()"),
float64=("float64_t", "read_float64()"),
uuid=("uuid", "read_uuid()"),
iobuf=("iobuf", None, "read_fragmented_nullable_bytes()", None,
"read_fragmented_nullable_flex_bytes()"),
fetch_record_set=("batch_reader", None, "read_nullable_batch_reader()",
None, "read_nullable_flex_batch_reader()"),
)
# Declare some fields as sensitive. Utmost care should be taken to ensure the
# contents of these fields are never made available over unsecure channels
# (sent over an unencrypted connection, printed in logs, etc.).
sensitive_map = {
"SaslAuthenticateRequestData": {
"AuthBytes": True,
},
"SaslAuthenticateResponseData": {
"AuthBytes": True,
},
}
# apply a rename to a struct. this is useful when there is a type name conflict
# between two request types. since we generate types in a flat namespace this
# feature is important for resolving naming conflicts.
#
# the format here is the field name path terminating with the expected type name
# mapping to the new type name.
# yapf: disable
struct_renames = {
("IncrementalAlterConfigsRequestData", "Resources"):
("AlterConfigsResource", "IncrementalAlterConfigsResource"),
("IncrementalAlterConfigsRequestData", "Resources", "Configs"):
("AlterableConfig", "IncrementalAlterableConfig"),
("IncrementalAlterConfigsResponseData", "Responses"):
("AlterConfigsResourceResponse", "IncrementalAlterConfigsResourceResponse"),
("AlterClientQuotasRequestData", "Entries"):
("EntryData", "AlterClientQuotasRequestEntryData"),
("AlterClientQuotasResponseData", "Entries"):
("EntryData", "AlterClientQuotasResponseEntryData"),
("DescribeClientQuotasResponseData", "Entries"):
("EntryData", "DescribeClientQuotasResponseEntryData"),
("AlterClientQuotasRequestData", "Entries", "Entity"):
("EntityData", "AlterClientQuotasRequestEntityData"),
("AlterClientQuotasResponseData", "Entries", "Entity"):
("EntityData", "AlterClientQuotasResponseEntityData"),
("DescribeClientQuotasResponseData", "Entries", "Entity"):
("EntityData", "DescribeClientQuotasResponseEntityData"),
}
# extra header per type name
extra_headers = {
"std::optional": dict(
header = ("<optional>",),
source = "utils/to_string.h"
),
"std::vector": dict(
header = "<vector>",
),
"kafka::produce_request_record_data": dict(
header = "kafka/protocol/kafka_batch_adapter.h",
),
"kafka::batch_reader": dict(
header = "kafka/protocol/batch_reader.h",
),
"model::timestamp": dict(
header = "model/timestamp.h",
),
"std::chrono::milliseconds": dict(
source = "utils/to_string.h",
),
}
# yapf: enable
# These types, when they appear as the member type of an array, will override
# the container type from std::vector
override_member_container = {
'metadata_response_partition': 'large_fragment_vector',
'metadata_response_topic': 'small_fragment_vector',
'fetchable_partition_response': 'small_fragment_vector',
'offset_fetch_response_partition': 'small_fragment_vector',
'int32_t': 'std::vector',
'model::node_id': 'std::vector',
'model::partition_id': 'std::vector',
'reassignable_partition_response': 'std::vector',
'reassignable_partition': 'std::vector',
'describe_configs_synonym': 'std::vector',
'createable_topic_config': 'std::vector',
'creatable_topic_configs': 'std::vector',
'creatable_replica_assignment': 'std::vector',
'offset_commit_request_partition': 'std::vector',
'offset_commit_response_partition': 'std::vector',
'offset_commit_request_topic': 'std::vector',
'offset_fetch_request_topic': 'std::vector',
'partition_produce_response': 'std::vector',
'creatable_acl_result': 'std::vector',
'listed_group': 'std::vector',
'offset_delete_request_partition': 'std::vector',
'deletable_group_result': 'std::vector',
'delete_acls_matching_acl': 'std::vector',
'txn_offset_commit_request_partition': 'std::vector',
'txn_offset_commit_request_topic': 'std::vector',
'txn_offset_commit_response_partition': 'std::vector',
}
def make_context_field(path):
"""
For a given path return a special field to be added to a generated
structure. This structure will not be encoded/decoded on the wire and is
used to add some extra context.
"""
if path == ("FetchResponseData", "Topics", "Partitions"):
return ("bool", "has_to_be_included{true}")
# a listing of expected struct types
STRUCT_TYPES = [
"ApiVersionsRequestKey",
"ApiVersionsResponseKey",
"OffsetFetchRequestTopic",
"OffsetFetchResponseTopic",
"OffsetFetchResponsePartition",
"OffsetCommitRequestTopic",
"OffsetCommitRequestPartition",
"OffsetCommitResponseTopic",
"OffsetCommitResponsePartition",
"JoinGroupRequestProtocol",
"JoinGroupResponseMember",
"SyncGroupRequestAssignment",
"MemberIdentity",
"MemberResponse",
"DeletableTopicResult",
"DescribeConfigsResult",
"DescribeConfigsResource",
"DescribeConfigsResourceResult",
"DescribeConfigsSynonym",
"ListOffsetTopic",
"ListOffsetTopicResponse",
"ListOffsetPartitionResponse",
"ListOffsetPartition",
"AlterConfigsResource",
"AlterableConfig",
"AlterConfigsResourceResponse",
"ListedGroup",
"DescribedGroup",
"DescribedGroupMember",
"CreatableTopic",
"CreatableTopicResult",
"CreatableReplicaAssignment",
"CreateableTopicConfig",
"CreatableTopicConfigs",
"DeletableGroupResult",
"DescribeAclsResource",
"AclDescription",
"DescribeLogDirsTopic",
"DescribableLogDirTopic",
"DescribeLogDirsResult",
"DescribeLogDirsPartition",
"CreatableAcl",
"CreatableAclResult",
"DeleteAclsFilter",
"DeleteAclsFilterResult",
"DeleteAclsMatchingAcl",
"TopicProduceResponse",
"PartitionProduceResponse",
"BatchIndexAndErrorMessage",
"TopicProduceData",
"PartitionProduceData",
"MetadataResponseBroker",
"MetadataRequestTopic",
"MetadataResponseTopic",
"MetadataResponsePartition",
"AddPartitionsToTxnTopic",
"AddPartitionsToTxnTopicResult",
"AddPartitionsToTxnPartitionResult",
"TxnOffsetCommitRequestTopic",
"TxnOffsetCommitResponseTopic",
"TxnOffsetCommitResponsePartition",
"TxnOffsetCommitRequestPartition",
"FetchTopic",
"ForgottenTopic",
"FetchPartition",
"FetchableTopicResponse",
"FetchablePartitionResponse",
"AbortedTransaction",
"CreatePartitionsTopic",
"CreatePartitionsTopicResult",
"CreatePartitionsAssignment",
"OffsetDeleteRequestTopic",
"OffsetDeleteRequestPartition",
"OffsetDeleteResponseTopic",
"OffsetDeleteResponsePartition",
"OffsetForLeaderTopic",
"OffsetForLeaderPartition",
"OffsetForLeaderTopicResult",
"EpochEndOffset",
"SupportedFeatureKey",
"FinalizedFeatureKey",
"DeleteTopicState",
"ReassignableTopic",
"ReassignablePartition",
"ReassignableTopicResponse",
"ReassignablePartitionResponse",
"ListPartitionReassignmentsTopics",
"OngoingTopicReassignment",
"OngoingPartitionReassignment",
"TopicRequest",
"TopicResponse",
"PartitionResponse",
"ProducerState",
"DescribeTransactionState",
"TopicData",
"ListTransactionState",
"DeleteRecordsTopic",
"DeleteRecordsPartition",
"DeleteRecordsTopicResult",
"DeleteRecordsPartitionResult",
"EntryData",
"EntityData",
"OpData",
"ComponentData",
"ValueData",
]
DROP_STREAM_OPERATOR = [
"metadata_response_data",
"metadata_response_topic",
"metadata_response_partition",
"metadata_response_broker",
]
# a list of struct types which are ineligible to have default-generated
# `operator==()`, because one or more of its member variables are not
# comparable
WITHOUT_DEFAULT_EQUALITY_OPERATOR = {
'kafka::batch_reader', 'kafka::produce_request_record_data'
}
# The following is a list of tag types which contain fields where their
# respective types are not prefixed with []. The generator special cases these
# as ArrayTypes
TAGGED_WITH_FIELDS = []
SCALAR_TYPES = list(basic_type_map.keys())
ENTITY_TYPES = list(entity_type_map.keys())
def apply_struct_renames(path, type_name):
rename = struct_renames.get(path, None)
if rename is None:
return type_name
assert rename[0] == type_name
return rename[1]
class VersionRange:
"""
A version range is fundamentally a range [min, max] but there are several
different ways in the kafka schema format to specify the bounds.
"""
def __init__(self, spec):
self.min, self.max = self._parse(spec)
def _parse(self, spec):
match = re.match("^(?P<min>\d+)$", spec)
if match:
min = int(match.group("min"))
return min, min
match = re.match("^(?P<min>\d+)\+$", spec)
if match:
min = int(match.group("min"))
return min, None
match = re.match("^(?P<min>\d+)\-(?P<max>\d+)$", spec)
if match:
min = int(match.group("min"))
max = int(match.group("max"))
return min, max
guard_modes = enum.Enum('guard_modes', 'GUARD, NO_GUARD, NO_SOURCE')
@property
def guard_enum(self):
return VersionRange.guard_modes
def _guard(self):
"""
Generate the C++ bounds check.
"""
if self.min == self.max:
cond = f"version == api_version({self.min})"
else:
cond = []
if self.min > 0:
cond.append(f"version >= api_version({self.min})")
if self.max != None:
cond.append(f"version <= api_version({self.max})")
cond = " && ".join(cond)
return (self.guard_enum.NO_GUARD,
None) if cond == "" else (self.guard_enum.GUARD, cond)
def guard(self, flex, first_flex):
"""
Optimize generated code by either omitting a guard or source itself
"""
if first_flex < 0:
return self._guard()
elif not flex:
if self.min >= first_flex:
return self.guard_enum.NO_SOURCE, None
else:
if self.max == None:
if self.min <= first_flex:
return self.guard_enum.NO_GUARD, None
elif self.max < first_flex:
return self.guard_enum.NO_SOURCE, None
elif self.max == first_flex:
return self.guard_enum.NO_GUARD, None
return self._guard()
def __repr__(self):
max = "+inf)" if self.max is None else f"{self.max}]"
return f"[{self.min}, {max}"
def snake_case(name):
"""Convert camel to snake case"""
return name[0].lower() + "".join(
[f"_{c.lower()}" if c.isupper() else c for c in name[1:]])
class FieldType:
ARRAY_RE = re.compile("^\[\](?P<type>.+)$")
def __init__(self, name):
self._name = name
@staticmethod
def create(field, path):
"""
FieldType factory based on Kafka field type name:
int32 -> Int32Type
[]int32 -> ArrayType(Int32Type)
[]FooType -> ArrayType(StructType)
Verifies that structs are only stored in arrays and that there are no array
of array types like [][]FooType.
"""
type_name = field["type"]
match = FieldType.ARRAY_RE.match(type_name)
is_array = match is not None
if is_array:
type_name = match.group("type")
# we do not assume 2d arrays
assert FieldType.ARRAY_RE.match(type_name) is None
if type_name in SCALAR_TYPES:
t = ScalarType(type_name)
else:
# Its possible for tagged types to contain fields where the type is not
# prefixed with [], these types are listed in the TAGGED_WITH_FIELDS map
is_array = is_array or (type_name in TAGGED_WITH_FIELDS)
assert is_array
path = path + (field["name"], )
type_name = apply_struct_renames(path, type_name)
t = StructType(type_name, field["fields"], path)
if is_array:
return ArrayType(t)
return t
@property
def is_struct(self):
return False
@property
def name(self):
return self._name
class ScalarType(FieldType):
def __init__(self, name):
super().__init__(name)
@property
def potentially_flexible_type(self):
"""Evaluates to true if the scalar type would be parsed as flex
if the version is high enough"""
return self.name == "string" or self.name == "bytes" or self.name == "iobuf"
class StructType(FieldType):
def __init__(self, name, fields, path=()):
super().__init__(snake_case(name))
self.fields = []
self.tags = []
for f in fields:
new_field = Field.create(f, path)
if new_field.is_tag:
self.tags.append(new_field)
else:
self.fields.append(new_field)
self.tags.sort(key=lambda x: x._tag)
self.context_field = make_context_field(path)
@property
def is_struct(self):
return True
@property
def format(self):
"""Format string for output operator"""
return " ".join(map(lambda f: f"{f.name}={{}}", self.fields))
def structs(self):
"""
Return all struct types reachable from this struct.
"""
res = []
all_fields = self.fields + self.tags
for field in all_fields:
t = field.type()
if isinstance(t, ArrayType):
t = t.value_type() # unwrap value type
if isinstance(t, StructType):
res += t.structs()
res.append(t)
return res
def headers(self, which):
"""
calculate extra headers needed to support this struct
"""
whiches = set(("header", "source"))
assert which in whiches
def type_iterator(fields):
for field in fields:
yield from field.type_name_parts()
t = field.type()
if isinstance(t, ArrayType):
t = t.value_type() # unwrap value type
if isinstance(t, StructType):
yield from type_iterator(t.fields)
types = set(type_iterator(self.fields))
def maybe_strings(s):
if isinstance(s, str):
yield s
else:
assert isinstance(s, tuple)
yield from s
def type_headers(t):
h = extra_headers.get(t, None)
if h is None:
return
assert isinstance(h, dict)
assert set(h.keys()) <= whiches
h = h.get(which, ())
yield from maybe_strings(h)
return set(h for t in types for h in type_headers(t))
@property
def is_default_comparable(self):
return all(field.is_default_comparable for field in self.fields)
@property
def is_streamable(self):
return self._name not in DROP_STREAM_OPERATOR and all(
field.is_streamable for field in self.fields)
class ArrayType(FieldType):
def __init__(self, value_type):
# the name of the ArrayType is its value type
super().__init__(value_type._name)
self._value_type = value_type
def value_type(self):
return self._value_type
@property
def potentially_flexible_type(self):
assert isinstance(self._value_type, ScalarType)
return self._value_type.potentially_flexible_type
class Field:
def __init__(self, field, field_type, path):
self._field = field
self._type = field_type
self._path = path + (self._field["name"], )
self._versions = VersionRange(self._field["versions"])
self._nullable_versions = self._field.get("nullableVersions", None)
if self._nullable_versions is not None:
self._nullable_versions = VersionRange(self._nullable_versions)
self._default_value = self._field.get("default", "")
if self._default_value == "null":
self._default_value = ""
self._tag = self._field.get("tag", None)
self._tagged_versions = self._field.get("taggedVersions", None)
if self._tagged_versions is not None:
self._tagged_versions = VersionRange(self._tagged_versions)
assert len(self._path)
@staticmethod
def create(field, path):
field_type = FieldType.create(field, path)
return Field(field, field_type, path)
def type(self):
return self._type
def tag(self):
return self._tag
def nullable(self):
return self._nullable_versions is not None
def versions(self):
return self._versions
def tagged_versions(self):
return self._tagged_versions
def default_value(self):
return self._default_value
def about(self):
return self._field.get("about", "<no description>")
def _redpanda_path_type(self):
"""
Resolve a redpanda field path type override.
"""
d = path_type_map
for p in self._path:
d = d.get(p, None)
if d is None:
break
if isinstance(d, tuple):
return d
return None
def _redpanda_type(self):
"""
Resolve a redpanda type override.
Lookup occurs from most to least specific.
"""
# path overrides
path_type = self._redpanda_path_type()
if path_type:
return path_type[0], None
# entity type overrides
et = self._field.get("entityType", None)
if et in entity_type_map:
return entity_type_map[et][0], None
tn = self._type.name
fn = self._field["name"]
# type/name overrides
if (tn, fn) in field_name_type_map:
return field_name_type_map[(tn, fn)]
# fundamental type overrides
if tn in basic_type_map:
return basic_type_map[tn][0], None
return tn, None
def _redpanda_decoder(self):
"""
Resolve a redpanda type override.
Lookup occurs from most to least specific.
"""
# path overrides
path_type = self._redpanda_path_type()
if path_type:
return basic_type_map[path_type[1]], path_type[0]