-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathKNetCompactedReplicator.cs
More file actions
1633 lines (1465 loc) · 79.7 KB
/
KNetCompactedReplicator.cs
File metadata and controls
1633 lines (1465 loc) · 79.7 KB
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 (c) 2021-2026 MASES s.r.l.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Refer to LICENSE for more information.
*/
using MASES.JCOBridge.C2JBridge;
using MASES.KNet.Admin;
using MASES.KNet.Common;
using MASES.KNet.Consumer;
using MASES.KNet.Extensions;
using MASES.KNet.Producer;
using MASES.KNet.Serialization;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace MASES.KNet.Replicator
{
#region AccessRightsType
/// <summary>
/// <see cref="KNetCompactedReplicator{K, V}"/> access rights to data
/// </summary>
[Flags]
public enum AccessRightsType
{
/// <summary>
/// Data are readable, i.e. aligned with the others <see cref="KNetCompactedReplicator{K, V}"/> and accessible from this <see cref="KNetCompactedReplicator{K, V}"/>
/// </summary>
Read = 1,
/// <summary>
/// Data are writable, i.e. updates can be produced, but this <see cref="KNetCompactedReplicator{K, V}"/> is not accessible and not aligned with the others <see cref="KNetCompactedReplicator{K, V}"/>
/// </summary>
Write = 2,
/// <summary>
/// Data are readable and writable, i.e. updates can be produced, and data are aligned with the others <see cref="KNetCompactedReplicator{K, V}"/> and accessible from this <see cref="KNetCompactedReplicator{K, V}"/>
/// </summary>
ReadWrite = Read | Write,
}
#endregion
#region UpdateModeTypes
/// <summary>
/// <see cref="KNetCompactedReplicator{K, V}"/> update modes
/// </summary>
[Flags()]
public enum UpdateModeTypes
{
/// <summary>
/// The <see cref="KNetCompactedReplicator{K, V}"/> is updated as soon as an update is delivered to Kafka by the current application
/// </summary>
OnDelivery = 1,
/// <summary>
/// The <see cref="KNetCompactedReplicator{K, V}"/> is updated only after an update is consumed from Kafka, even if the add or update is made locally by the current instance
/// </summary>
OnConsume = 2,
/// <summary>
/// The <see cref="KNetCompactedReplicator{K, V}"/> is updated only after an update is consumed from Kafka, even if the add or update is made locally by the current instance. Plus the update waits the consume of the data before unlock
/// </summary>
OnConsumeSync = 3,
/// <summary>
/// The value is stored in <see cref="KNetCompactedReplicator{K, V}"/> only upon a request, otherwise only the key is stored
/// </summary>
Delayed = 0x1000
}
#endregion
#region IKNetCompactedReplicator<K, V, TJVMK, TJVMV>
/// <summary>
/// Public interface for <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
/// <typeparam name="K">The type of keys in the dictionary</typeparam>
/// <typeparam name="V">The type of values in the dictionary. Must be a nullable type</typeparam>
/// <typeparam name="TJVMK">The JVM type of <typeparamref name="K"/></typeparam>
/// <typeparam name="TJVMV">The JVM type of <typeparamref name="V"/></typeparam>
public interface IKNetCompactedReplicator<K, V, TJVMK, TJVMV> : IDictionary<K, V>, IDisposable
where V : class
{
#region Events
/// <summary>
/// Called when a [<typeparamref name="K"/>, <typeparamref name="V"/>] is added by consuming data from the others <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnRemoteAdd;
/// <summary>
/// Called when a [<typeparamref name="K"/>, <typeparamref name="V"/>] is updated by consuming data from the others <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnRemoteUpdate;
/// <summary>
/// Called when a [<typeparamref name="K"/>, <typeparamref name="V"/>] is removed by consuming data from the others <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnRemoteRemove;
/// <summary>
/// Called when a [<typeparamref name="K"/>, <typeparamref name="V"/>] is added on this <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnLocalAdd;
/// <summary>
/// Called when a [<typeparamref name="K"/>, <typeparamref name="V"/>] is updated on this <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnLocalUpdate;
/// <summary>
/// Called when a [<typeparamref name="K"/>, <typeparamref name="V"/>] is removed from this <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnLocalRemove;
/// <summary>
/// It is called to request if the [<typeparamref name="K"/>, <typeparamref name="V"/>] can be stored in the <see cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}"/> instance.
/// </summary>
/// <remarks>The second parameter reports the current value that depends on values set to <see cref="UpdateMode"/> and if it contains the <see cref="UpdateModeTypes.Delayed"/></remarks>
Func<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, bool, KeyValuePair<K, V>, bool> OnDelayedStore { get; }
#endregion
#region Public Properties
/// <summary>
/// Get or set <see cref="AccessRightsType"/>
/// </summary>
AccessRightsType AccessRights { get; }
/// <summary>
/// Get or set <see cref="UpdateModeTypes"/>
/// </summary>
UpdateModeTypes UpdateMode { get; }
/// <summary>
/// Get or set bootstrap servers
/// </summary>
string BootstrapServers { get; }
/// <summary>
/// Get or set topic name
/// </summary>
string StateName { get; }
/// <summary>
/// Get or set the group id, if not set a value is generated
/// </summary>
string GroupId { get; }
/// <summary>
/// Get or set partitions to use when topic is created for the first time, otherwise reports the partiions of the topic
/// </summary>
int Partitions { get; }
/// <summary>
/// Get or set the number of <see cref="KNetConsumer{K, V, TJVMK, TJVMV}"/> instances to be used, null to allocate <see cref="KNetConsumer{K, V, TJVMK, TJVMV}"/> based on <see cref="Partitions"/>
/// </summary>
int? ConsumerInstances { get; }
/// <summary>
/// Get or set replication factor to use when topic is created for the first time, otherwise reports the replication factor of the topic
/// </summary>
short ReplicationFactor { get; }
/// <summary>
/// Get or set the poll timeout to be used for <see cref="IConsumer{K, V, TJVMK, TJVMV}.ConsumeAsync(long)"/>
/// </summary>
long ConsumePollTimeout { get; }
/// <summary>
/// Get or set <see cref="TopicConfigBuilder"/> to use when topic is created for the first time
/// </summary>
TopicConfigBuilder TopicConfig { get; }
/// <summary>
/// Get or set <see cref="ConsumerConfigBuilder"/> to use in <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
ConsumerConfigBuilder ConsumerConfig { get; }
/// <summary>
/// Get or set <see cref="ProducerConfigBuilder"/> to use in <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>
/// </summary>
ProducerConfigBuilder ProducerConfig { get; }
/// <summary>
/// The <see cref="Type"/> used to create an instance of <see cref="KeySerDes"/>"/>
/// </summary>
Type KeySerDesSelector { get; }
/// <summary>
/// Get or set an instance of <see cref="ISerDes{K, TJVMK}"/> to use in <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>, by default it creates a default one based on <typeparamref name="K"/>
/// </summary>
ISerDes<K, TJVMK> KeySerDes { get; }
/// <summary>
/// The <see cref="Type"/> used to create an instance of <see cref="ValueSerDes"/>"/>
/// </summary>
Type ValueSerDesSelector { get; }
/// <summary>
/// Get or set an instance of <see cref="ISerDes{V, TJVMV}"/> to use in <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>, by default it creates a default one based on <typeparamref name="V"/>
/// </summary>
ISerDes<V, TJVMV> ValueSerDes { get; }
#if NET7_0_OR_GREATER
/// <summary>
/// <see langword="true"/> if enumeration will use prefetch and the number of records is more than <see cref="PrefetchThreshold"/>, i.e. the preparation of <see cref="ConsumerRecord{K, V, TJVMK, TJVMV}"/> happens in an external thread
/// </summary>
/// <remarks>It is <see langword="true"/> by default if one of <typeparamref name="K"/> or <typeparamref name="V"/> are not <see cref="ValueType"/>, override the value using <see cref="ApplyPrefetch(bool, int)"/></remarks>
bool IsPrefecth { get; }
/// <summary>
/// The minimum threshold to activate pretech, i.e. the preparation of <see cref="ConsumerRecord{K, V, TJVMK, TJVMV}"/> happens in external thread if <see cref="Org.Apache.Kafka.Clients.Consumer.ConsumerRecords{TJVMK, TJVMV}"/> contains more than <see cref="PrefetchThreshold"/> elements
/// </summary>
/// <remarks>The default value is 10, however it shall be chosen by the developer and in the decision shall be verified if external thread activation costs more than inline execution</remarks>
int PrefetchThreshold { get; }
#endif
/// <summary>
/// <see langword="true"/> if the instance was started
/// </summary>
bool IsStarted { get; }
/// <summary>
/// <see langword="true"/> if the instance was started
/// </summary>
bool IsAssigned { get; }
/// <summary>
/// Reports a snapshot of current lags (the value) associated to each partition (the key).
/// </summary>
/// <remarks>It is only a snapshot when the property is read and cannot reflect real conditions</remarks>
IReadOnlyDictionary<int, long> CurrentPartitionLags { get; }
/// <summary>
/// Reports a snapshot of current sync state the value (<see langword="true"/> means it is in sync) associated to each consumer (the key).
/// </summary>
/// <remarks>It is only a snapshot when the property is read and cannot reflect real conditions</remarks>
IReadOnlyDictionary<int, bool> CurrentConsumersSyncState { get; }
#endregion
#region Public methods
#if NET7_0_OR_GREATER
/// <summary>
/// Set to <see langword="true"/> to enable enumeration with prefetch over <paramref name="prefetchThreshold"/> threshold, i.e. preparation of <see cref="ConsumerRecord{K, V, TJVMK, TJVMV}"/> in external thread
/// </summary>
/// <param name="enablePrefetch"><see langword="true"/> to enable prefetch. See <see cref="IsPrefecth"/></param>
/// <param name="prefetchThreshold">The minimum threshold to activate pretech, default is 10. See <see cref="PrefetchThreshold"/></param>
/// <remarks>Setting <paramref name="prefetchThreshold"/> to a value less, or equal, to 0 and <paramref name="enablePrefetch"/> to <see langword="true"/>, the prefetch is always actived</remarks>
void ApplyPrefetch(bool enablePrefetch = true, int prefetchThreshold = 10);
#endif
/// <summary>
/// Start this <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>: create the <see cref="StateName"/> topic if not available, allocates Producer and Consumer, sets serializer/deserializer
/// </summary>
/// <exception cref="InvalidOperationException">Some errors occurred</exception>
void Start();
/// <summary>
/// Start this <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/>: create the <see cref="StateName"/> topic if not available, allocates Producer and Consumers, sets serializer/deserializer
/// Then waits its synchronization with <see cref="StateName"/> topic which stores dictionary data
/// </summary>
/// <param name="timeout">The number of milliseconds to wait, or <see cref="Timeout.Infinite"/> to wait indefinitely</param>
/// <returns><see langword="true"/> if the current instance synchronize within the given <paramref name="timeout"/>; otherwise, <see langword="false"/></returns>
/// <exception cref="InvalidOperationException">Some errors occurred or the provided <see cref="AccessRights"/> do not include the <see cref="AccessRightsType.Read"/> flag</exception>
bool StartAndWait(int timeout = Timeout.Infinite);
/// <summary>
/// Waits for all paritions assignment of the <see cref="StateName"/> topic which stores dictionary data
/// </summary>
/// <param name="timeout">The number of milliseconds to wait, or <see cref="Timeout.Infinite"/> to wait indefinitely</param>
/// <returns><see langword="true"/> if the current instance receives a signal within the given <paramref name="timeout"/>; otherwise, <see langword="false"/></returns>
/// <exception cref="InvalidOperationException">The provided <see cref="AccessRights"/> do not include the <see cref="AccessRightsType.Read"/> flag</exception>
bool WaitForStateAssignment(int timeout = Timeout.Infinite);
/// <summary>
/// Waits that <see cref="KNetCompactedReplicator{K, V, TJVMK, TJVMV}"/> is synchronized to the <see cref="StateName"/> topic which stores dictionary data
/// </summary>
/// <param name="timeout">The number of milliseconds to wait, or <see cref="Timeout.Infinite"/> to wait indefinitely</param>
/// <returns><see langword="true"/> if the current instance synchronize within the given <paramref name="timeout"/>; otherwise, <see langword="false"/></returns>
/// <exception cref="InvalidOperationException">The provided <see cref="AccessRights"/> do not include the <see cref="AccessRightsType.Read"/> flag</exception>
bool SyncWait(int timeout = Timeout.Infinite);
/// <summary>
/// Waits until all outstanding produce requests and delivery report callbacks are completed
/// </summary>
void Flush();
/// <summary>
/// Reports the <see cref="KNetProducer{K, V, TJVMK, TJVMV}"/> metrics. <see cref="Org.Apache.Kafka.Clients.Producer.KafkaProducer.Metrics"/>
/// </summary>
/// <typeparam name="TMetric">Extends <see cref="Org.Apache.Kafka.Common.Metric"/></typeparam>
/// <returns>A <see cref="Java.Util.Map"/> of <see cref="Org.Apache.Kafka.Common.MetricName"/> and <typeparamref name="TMetric"/></returns>
Java.Util.Map<Org.Apache.Kafka.Common.MetricName, TMetric> ProducerMetrics<TMetric>() where TMetric : Org.Apache.Kafka.Common.Metric;
/// <summary>
/// Reports the <see cref="KNetConsumer{K, V, TJVMK, TJVMV}"/> metrics. <see cref="Org.Apache.Kafka.Clients.Consumer.KafkaConsumer.Metrics"/>
/// </summary>
/// <typeparam name="TMetric">Extends <see cref="Org.Apache.Kafka.Common.Metric"/></typeparam>
/// <returns>An <see cref="IReadOnlyDictionary{T, V}"/> where the key is the current allocated <see cref="KNetConsumer{K, V, TJVMK, TJVMV}"/> and value is a <see cref="Java.Util.Map"/> of <see cref="Org.Apache.Kafka.Common.MetricName"/> and <typeparamref name="TMetric"/></returns>
IReadOnlyDictionary<int, Java.Util.Map<Org.Apache.Kafka.Common.MetricName, TMetric>> ConsumerMetrics<TMetric>() where TMetric : Org.Apache.Kafka.Common.Metric;
#endregion
}
#endregion
#region KNetCompactedReplicator<K, V, TJVMK, TJVMV>
/// <summary>
/// Provides a reliable dictionary, persisted in a COMPACTED Kafka topic and shared among applications
/// </summary>
/// <typeparam name="K">The type of keys in the dictionary</typeparam>
/// <typeparam name="V">The type of values in the dictionary. Must be a nullable type</typeparam>
/// <typeparam name="TJVMK">The JVM type of <typeparamref name="K"/></typeparam>
/// <typeparam name="TJVMV">The JVM type of <typeparamref name="V"/></typeparam>
public class KNetCompactedReplicator<K, V, TJVMK, TJVMV> : IKNetCompactedReplicator<K, V, TJVMK, TJVMV>
where V : class
{
const long InitialLagState = -2;
const long NotPresentLagState = -1;
const long InvalidLagState = -3;
#region Local storage data
interface ILocalDataStorage
{
object Lock { get; }
Int32 Partition { get; set; }
bool HasOffset { get; set; }
Int64 Offset { get; set; }
bool HasValue { get; set; }
V Value { get; set; }
}
struct LocalDataStorage : ILocalDataStorage
{
object _lock = new object();
public LocalDataStorage()
{
Partition = -1;
HasOffset = HasValue = false;
Offset = -1;
Value = null;
}
public object Lock => _lock;
public int Partition { get; set; }
public bool HasOffset { get; set; }
public long Offset { get; set; }
public bool HasValue { get; set; }
public V Value { get; set; }
}
#endregion
#region Local Enumerator
class LocalDataStorageEnumerator : IEnumerator<KeyValuePair<K, V>>
{
private IEnumerator<KeyValuePair<K, ILocalDataStorage>> _enumerator;
private readonly ConcurrentDictionary<K, ILocalDataStorage> _dictionary;
private readonly IConsumer<K, V, TJVMK, TJVMV> _consumer = null;
private readonly string _topic;
public LocalDataStorageEnumerator(ConcurrentDictionary<K, ILocalDataStorage> dictionary, IConsumer<K, V, TJVMK, TJVMV> consumer, string topic)
{
_dictionary = dictionary;
_consumer = consumer;
_topic = topic;
_enumerator = _dictionary.GetEnumerator();
}
KeyValuePair<K, V>? _current = null;
public KeyValuePair<K, V> Current
{
get
{
lock (_enumerator)
{
if (_current == null)
{
var localCurrent = _enumerator.Current;
ILocalDataStorage data = localCurrent.Value;
lock (data.Lock)
{
if (!data.HasValue)
{
OnDemandRetrieve(_consumer, _topic, localCurrent.Key, data);
}
_current = new KeyValuePair<K, V>(localCurrent.Key, localCurrent.Value.Value);
}
}
return _current.Value;
}
}
}
object IEnumerator.Current => Current;
public void Dispose()
{
_enumerator.Dispose();
}
public bool MoveNext()
{
lock (_enumerator)
{
_current = null;
return _enumerator.MoveNext();
}
}
public void Reset()
{
_enumerator.Reset();
}
public System.Collections.Generic.ICollection<V> Values()
{
System.Collections.Generic.List<V> values = new System.Collections.Generic.List<V>();
while (this.MoveNext())
{
values.Add(this.Current.Value);
}
return values;
}
public bool TryGetValue(K key, out V value)
{
value = default;
if (_dictionary.TryGetValue(key, out var data))
{
if (!data.HasValue)
{
OnDemandRetrieve(_consumer, _topic, key, data);
}
value = data.Value;
return true;
}
return false;
}
public bool Contains(KeyValuePair<K, V> item)
{
if (this.TryGetValue(item.Key, out var data))
{
return data == item.Value;
}
return false;
}
public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
{
var values = new System.Collections.Generic.List<KeyValuePair<K, V>>();
while (this.MoveNext())
{
values.Add(new KeyValuePair<K, V>(this.Current.Key, this.Current.Value));
}
Array.Copy(values.ToArray(), 0, array, arrayIndex, values.Count);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
static void OnDemandRetrieve(IConsumer<K, V, TJVMK, TJVMV> consumer, string topic, K key, ILocalDataStorage data)
{
var topicPartition = new Org.Apache.Kafka.Common.TopicPartition(topic, data.Partition);
var disposable1 = JVMBridgeCoreDisposable.Create(topicPartition);
var topics = Java.Util.Collections.Singleton(topicPartition);
var disposable2 = JVMBridgeCoreDisposable.Create(topics);
try
{
consumer.Assign(topics);
consumer.Seek(topicPartition, data.Offset);
var results = consumer.Poll(TimeSpan.FromMinutes(1)) ?? throw new InvalidOperationException("Failed to get records from remote.");
foreach (var result in results)
{
if (!Equals(result.Key, key)) continue;
if (data.Offset != result.Offset) throw new IndexOutOfRangeException($"Requested offset is {data.Offset} while received offset is {result.Offset}");
data.HasValue = true;
data.Value = result.Value;
break;
}
}
finally
{
disposable1?.Dispose();
disposable2?.Dispose();
}
}
}
#endregion
#region KNetCompactedConsumerRebalanceListener
class KNetCompactedConsumerRebalanceListener : Org.Apache.Kafka.Clients.Consumer.ConsumerRebalanceListener
{
int _consumerIndex;
public KNetCompactedConsumerRebalanceListener(int consumerIndex)
: base()
{
_consumerIndex = consumerIndex;
}
public int ConsumerIndex => _consumerIndex;
public new System.Action<KNetCompactedConsumerRebalanceListener, Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition>> OnOnPartitionsAssigned { get; set; }
public override void OnPartitionsAssigned(Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition> arg0)
{
OnOnPartitionsAssigned?.Invoke(this, arg0);
}
public new System.Action<KNetCompactedConsumerRebalanceListener, Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition>> OnOnPartitionsRevoked { get; set; }
public override void OnPartitionsRevoked(Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition> arg0)
{
OnOnPartitionsRevoked?.Invoke(this, arg0);
}
public new System.Action<KNetCompactedConsumerRebalanceListener, Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition>> OnOnPartitionsLost { get; set; }
public override void OnPartitionsLost(Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition> arg0)
{
OnOnPartitionsLost?.Invoke(this, arg0);
}
}
#endregion
#region Private members
private bool _consumerPollRun = false;
private Thread[] _consumerPollThreads = null;
private ManualResetEvent[] _consumerPollThreadWaiter = null;
private ConcurrentDictionary<K, ILocalDataStorage> _dictionary = new ConcurrentDictionary<K, ILocalDataStorage>();
private KNetCompactedConsumerRebalanceListener[] _consumerListeners = null;
private IConsumer<K, V, TJVMK, TJVMV>[] _consumers = null;
private IConsumer<K, V, TJVMK, TJVMV> _onTheFlyConsumer = null;
private IProducer<K, V, TJVMK, TJVMV> _producer = null;
private string _bootstrapServers = null;
private string _stateName = string.Empty;
private string _groupId = Guid.NewGuid().ToString();
private int _partitions = 1;
private int? _consumerInstances = null;
private short _replicationFactor = 1;
private long _consumePollTimeout = 10;
private TopicConfigBuilder _topicConfig = null;
private ConsumerConfigBuilder _consumerConfig = null;
private ProducerConfigBuilder _producerConfig = null;
private Func<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, bool, KeyValuePair<K, V>, bool> _onDelayedStore = null;
private AccessRightsType _accessrights = AccessRightsType.ReadWrite;
private UpdateModeTypes _updateMode = UpdateModeTypes.OnDelivery;
private Tuple<K, ManualResetEvent> _OnConsumeSyncWaiter = null;
private Dictionary<int, System.Collections.Generic.IList<int>> _consumerAssociatedPartition = new();
private ManualResetEvent[] _assignmentWaiters;
private bool[] _assignmentWaitersStatus;
private long[] _lastPartitionLags = null;
private Type _KeySerDesSelector = null;
private ISerDes<K, TJVMK> _keySerDes = null;
private bool _disposeKeySerDes = false;
private Type _ValueSerDesSelector = null;
private ISerDes<V, TJVMV> _valueSerDes = null;
private bool _disposeValueSerDes = false;
private bool _started = false;
#endregion
#region Events
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnRemoteAdd"/>
public event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnRemoteAdd;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnRemoteUpdate"/>
public event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnRemoteUpdate;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnRemoteRemove"/>
public event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnRemoteRemove;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnLocalAdd"/>
public event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnLocalAdd;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnLocalUpdate"/>
public event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnLocalUpdate;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnLocalRemove"/>
public event Action<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, KeyValuePair<K, V>> OnLocalRemove;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.OnDelayedStore"/>
public Func<IKNetCompactedReplicator<K, V, TJVMK, TJVMV>, bool, KeyValuePair<K, V>, bool> OnDelayedStore
{
get { return _onDelayedStore; }
set { CheckStarted(); _onDelayedStore = value; }
}
#endregion
#region Public Properties
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.AccessRights"/>
public AccessRightsType AccessRights { get { return _accessrights; } set { CheckStarted(); _accessrights = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.UpdateMode"/>
public UpdateModeTypes UpdateMode { get { return _updateMode; } set { CheckStarted(); _updateMode = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.BootstrapServers"/>
public string BootstrapServers { get { return _bootstrapServers; } set { CheckStarted(); _bootstrapServers = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.StateName"/>
public string StateName { get { return _stateName; } set { CheckStarted(); _stateName = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.GroupId"/>
public string GroupId { get { return _groupId; } set { CheckStarted(); _groupId = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.Partitions"/>
public int Partitions { get { return _partitions; } set { CheckStarted(); _partitions = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ConsumerInstances"/>
public int? ConsumerInstances { get { return _consumerInstances ?? _partitions; } set { CheckStarted(); _consumerInstances = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ReplicationFactor"/>
public short ReplicationFactor { get { return _replicationFactor; } set { CheckStarted(); _replicationFactor = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ConsumePollTimeout"/>
public long ConsumePollTimeout { get { return _consumePollTimeout; } set { CheckStarted(); _consumePollTimeout = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.TopicConfig"/>
public TopicConfigBuilder TopicConfig { get { return _topicConfig; } set { CheckStarted(); _topicConfig = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ConsumerConfig"/>
public ConsumerConfigBuilder ConsumerConfig { get { return _consumerConfig; } set { CheckStarted(); _consumerConfig = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ProducerConfig"/>
public ProducerConfigBuilder ProducerConfig { get { return _producerConfig; } set { CheckStarted(); _producerConfig = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.KeySerDesSelector"/>
public Type KeySerDesSelector
{
get { return _KeySerDesSelector; }
set
{
CheckStarted();
if (value.GetConstructors().Single(ci => ci.GetParameters().Length == 0) == null)
{
throw new ArgumentException($"{value.Name} does not contains a default constructor and cannot be used because it is not a valid ISerDesSelector type");
}
if (value.IsGenericType)
{
var keyT = value.GetGenericArguments();
if (keyT.Length != 1) { throw new ArgumentException($"{value.Name} does not contains a single generic argument and cannot be used because it is not a valid ISerDesSelector type"); }
var t = value.GetGenericTypeDefinition();
if (t.GetInterface(typeof(ISerDesSelector<>).Name) == null)
{
throw new ArgumentException($"{value.Name} does not implement ISerDesSelector<> and cannot be used because it is not a valid ISerDesSelector type");
}
_KeySerDesSelector = value;
}
else throw new ArgumentException($"{value.Name} is not a generic type and cannot be used as a valid ISerDesSelector type");
}
}
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.KeySerDes"/>
public ISerDes<K, TJVMK> KeySerDes { get { return _keySerDes; } set { CheckStarted(); _keySerDes = value; } }
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ValueSerDesSelector"/>
public Type ValueSerDesSelector
{
get { return _ValueSerDesSelector; }
set
{
CheckStarted();
if (value.GetConstructors().Single(ci => ci.GetParameters().Length == 0) == null)
{
throw new ArgumentException($"{value.Name} does not contains a default constructor and cannot be used because it is not a valid ISerDesSelector type");
}
if (value.IsGenericType)
{
var keyT = value.GetGenericArguments();
if (keyT.Length != 1) { throw new ArgumentException($"{value.Name} does not contains a single generic argument and cannot be used because it is not a valid ISerDesSelector type"); }
var t = value.GetGenericTypeDefinition();
if (t.GetInterface(typeof(ISerDesSelector<>).Name) == null)
{
throw new ArgumentException($"{value.Name} does not implement ISerDesSelector<> and cannot be used because it is not a valid ISerDesSelector type");
}
_ValueSerDesSelector = value;
}
else throw new ArgumentException($"{value.Name} is not a generic type and cannot be used as a valid ISerDesSelector type");
}
}
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.ValueSerDes"/>
public ISerDes<V, TJVMV> ValueSerDes { get { return _valueSerDes; } set { CheckStarted(); _valueSerDes = value; } }
#if NET7_0_OR_GREATER
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.IsPrefecth"/>
public bool IsPrefecth { get; private set; } = !(typeof(K).IsValueType && typeof(V).IsValueType);
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.PrefetchThreshold"/>
public int PrefetchThreshold { get; private set; } = 10;
#endif
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.IsStarted"/>
public bool IsStarted => _started;
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.IsAssigned"/>
public bool IsAssigned => _assignmentWaiters.All((o) => o.WaitOne(0));
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.CurrentPartitionLags"/>
public IReadOnlyDictionary<int, long> CurrentPartitionLags
{
get
{
ValidateStarted();
var dict = new System.Collections.Generic.Dictionary<int, long>();
for (int i = 0; i < _lastPartitionLags.Length; i++)
{
dict.Add(i, Interlocked.Read(ref _lastPartitionLags[i]));
}
return dict;
}
}
/// <inheritdoc cref="IKNetCompactedReplicator{K, V, TJVMK, TJVMV}.CurrentConsumersSyncState"/>
public IReadOnlyDictionary<int, bool> CurrentConsumersSyncState
{
get
{
ValidateStarted();
var dict = new System.Collections.Generic.Dictionary<int, bool>();
for (int i = 0; i < ConsumersToAllocate(); i++)
{
dict.Add(i, CheckConsumerSyncState(i));
}
return dict;
}
}
#endregion
#region Private methods
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
void CheckStarted()
{
if (_started) throw new InvalidOperationException("Cannot be changed after Start");
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
int ConsumersToAllocate()
{
return ConsumerInstances ?? Partitions;
}
bool UpdateModeOnDelivery => (UpdateMode & UpdateModeTypes.OnDelivery) == UpdateModeTypes.OnDelivery;
bool UpdateModeOnConsume => (UpdateMode & UpdateModeTypes.OnConsume) == UpdateModeTypes.OnConsume;
bool UpdateModeOnConsumeSync => (UpdateMode & UpdateModeTypes.OnConsumeSync) == UpdateModeTypes.OnConsumeSync;
bool UpdateModeDelayed => UpdateMode.HasFlag(UpdateModeTypes.Delayed);
private void OnMessage(ConsumerRecord<K, V, TJVMK, TJVMV> record)
{
if (record.Value == null)
{
_dictionary.TryRemove(record.Key, out var data);
OnRemoteRemove?.Invoke(this, new KeyValuePair<K, V>(record.Key, data.Value));
}
else
{
bool containsKey = true;
ILocalDataStorage data;
if (!_dictionary.TryGetValue(record.Key, out data))
{
containsKey = false;
data = new LocalDataStorage();
_dictionary[record.Key] = data;
}
lock (data.Lock)
{
data.Partition = record.Partition;
data.HasOffset = true;
data.Offset = record.Offset;
bool storeValue = UpdateModeDelayed ? false : true;
if (OnDelayedStore != null)
{
storeValue = OnDelayedStore.Invoke(this, storeValue, new KeyValuePair<K, V>(record.Key, record.Value));
}
if (storeValue)
{
data.HasValue = true;
data.Value = record.Value;
}
}
if (containsKey)
{
OnRemoteUpdate?.Invoke(this, new KeyValuePair<K, V>(record.Key, record.Value));
}
else
{
OnRemoteAdd?.Invoke(this, new KeyValuePair<K, V>(record.Key, record.Value));
}
}
if (_OnConsumeSyncWaiter != null)
{
if (_OnConsumeSyncWaiter.Item1.Equals(record.Key))
{
_OnConsumeSyncWaiter.Item2.Set();
}
}
}
private void OnTopicPartitionsAssigned(KNetCompactedConsumerRebalanceListener listener, Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition> topicPartitions)
{
foreach (var topicPartition in topicPartitions)
{
var partition = topicPartition.Partition();
lock (_consumerAssociatedPartition)
{
_consumerAssociatedPartition[listener.ConsumerIndex].Add(partition);
}
if (!_assignmentWaiters[partition].SafeWaitHandle.IsClosed)
{
lock (_assignmentWaitersStatus) { _assignmentWaitersStatus[partition] = true; }
_assignmentWaiters[partition].Set();
}
}
}
private void OnTopicPartitionsRevoked(KNetCompactedConsumerRebalanceListener listener, Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition> topicPartitions)
{
foreach (var topicPartition in topicPartitions)
{
var partition = topicPartition.Partition();
lock (_consumerAssociatedPartition)
{
_consumerAssociatedPartition[listener.ConsumerIndex].Remove(partition);
}
if (!_assignmentWaiters[partition].SafeWaitHandle.IsClosed)
{
lock (_assignmentWaitersStatus) { _assignmentWaitersStatus[partition] = false; }
_assignmentWaiters[partition].Reset();
}
}
}
private void OnTopicPartitionsLost(KNetCompactedConsumerRebalanceListener listener, Java.Util.Collection<Org.Apache.Kafka.Common.TopicPartition> topicPartitions)
{
foreach (var topicPartition in topicPartitions)
{
var partition = topicPartition.Partition();
lock (_consumerAssociatedPartition)
{
_consumerAssociatedPartition[listener.ConsumerIndex].Remove(partition);
}
if (!_assignmentWaiters[partition].SafeWaitHandle.IsClosed)
{
lock (_assignmentWaitersStatus) { _assignmentWaitersStatus[partition] = false; }
_assignmentWaiters[partition].Reset();
}
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private void AddOrUpdate(K key, V value)
{
ValidateAccessRights(AccessRightsType.Write);
ValidateStarted();
if (key == null)
throw new ArgumentNullException(nameof(key));
if (UpdateModeOnDelivery)
{
Org.Apache.Kafka.Clients.Producer.RecordMetadata metadata = null;
JVMBridgeException exception = null;
DateTime pTimestamp = DateTime.MaxValue;
using (AutoResetEvent deliverySemaphore = new AutoResetEvent(false))
{
using (Org.Apache.Kafka.Clients.Producer.Callback cb = new Org.Apache.Kafka.Clients.Producer.Callback()
{
OnOnCompletion = (record, error) =>
{
try
{
if (deliverySemaphore.SafeWaitHandle.IsClosed)
return;
metadata = record;
exception = error;
deliverySemaphore.Set();
}
catch { }
}
})
{
_producer.Produce(new ProducerRecord<K, V, TJVMK, TJVMV>(_stateName, key, value), cb);
deliverySemaphore.WaitOne();
if (exception != null) throw exception;
}
}
if (value == null)
{
_dictionary.TryRemove(key, out var data);
OnLocalRemove?.Invoke(this, new KeyValuePair<K, V>(key, data.Value));
}
else
{
bool containsKey = true;
ILocalDataStorage data;
if (!_dictionary.TryGetValue(key, out data))
{
containsKey = false;
data = new LocalDataStorage();
_dictionary[key] = data;
}
lock (data.Lock)
{
data.Partition = metadata.Partition();
data.HasOffset = metadata.HasOffset();
data.Offset = metadata.Offset();
bool storeValue = UpdateModeDelayed ? false : true;
if (OnDelayedStore != null)
{
storeValue = OnDelayedStore.Invoke(this, storeValue, new KeyValuePair<K, V>(key, value));
}
if (storeValue)
{
data.HasValue = true;
data.Value = value;
}
}
if (containsKey)
{
OnLocalUpdate?.Invoke(this, new KeyValuePair<K, V>(key, value));
}
else
{
OnLocalAdd?.Invoke(this, new KeyValuePair<K, V>(key, value));
}
}
}
else if (UpdateModeOnConsume || UpdateModeOnConsumeSync)
{
_producer.Produce(StateName, key, value, (Org.Apache.Kafka.Clients.Producer.Callback)null);
if (UpdateModeOnConsumeSync)
{
_OnConsumeSyncWaiter = new Tuple<K, ManualResetEvent>(key, new ManualResetEvent(false));
_OnConsumeSyncWaiter.Item2.WaitOne();
_OnConsumeSyncWaiter.Item2.Dispose();
}
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private void ValidateAccessRights(AccessRightsType rights)
{
if (!_accessrights.HasFlag(rights))
throw new InvalidOperationException($"{rights} access flag not set");
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private void ValidateStarted()
{
if (!IsStarted)
throw new InvalidOperationException("The instance was not started");
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
void BuildConsumers()
{
_consumerConfig ??= ConsumerConfigBuilder.Create()
.WithEnableAutoCommit(true)
.WithAutoOffsetReset(ConsumerConfigBuilder.AutoOffsetResetTypes.EARLIEST)
.WithAllowAutoCreateTopics(false);
ConsumerConfig.BootstrapServers = BootstrapServers;
if (!ConsumerConfig.ExistProperty(Org.Apache.Kafka.Clients.CommonClientConfigs.GROUP_ID_CONFIG))
{
ConsumerConfig.GroupId = GroupId;
}
if (KeySerDesSelector != null)
{
ConsumerConfig.KeySerDesSelector = KeySerDesSelector;
}
else if (KeySerDes == null) throw new InvalidOperationException($"{typeof(K)} needs an external deserializer, set {nameof(KeySerDesSelector)} or {nameof(KeySerDes)}.");
if (ValueSerDesSelector != null)
{
ConsumerConfig.ValueSerDesSelector = ValueSerDesSelector;
}
else if (ValueSerDes == null) throw new InvalidOperationException($"{typeof(V)} needs an external deserializer, set {nameof(ValueSerDesSelector)} or {nameof(ValueSerDes)}.");
_assignmentWaiters = new ManualResetEvent[Partitions];
_assignmentWaitersStatus = new bool[Partitions];
_lastPartitionLags = new long[Partitions];
_consumers = new KNetConsumer<K, V, TJVMK, TJVMV>[ConsumersToAllocate()];
_consumerListeners = new KNetCompactedConsumerRebalanceListener[ConsumersToAllocate()];
for (int i = 0; i < Partitions; i++)
{
_lastPartitionLags[i] = InitialLagState;
_assignmentWaiters[i] = new ManualResetEvent(false);
_assignmentWaitersStatus[i] = false;
}
for (int i = 0; i < ConsumersToAllocate(); i++)
{
_consumerAssociatedPartition.Add(i, new System.Collections.Generic.List<int>());
_consumers[i] = (KeySerDesSelector != null || ValueSerDesSelector != null) ? new KNetConsumer<K, V, TJVMK, TJVMV>(ConsumerConfig)
: new KNetConsumer<K, V, TJVMK, TJVMV>(ConsumerConfig, KeySerDes, ValueSerDes);
#if NET7_0_OR_GREATER
_consumers[i].ApplyPrefetch(IsPrefecth, PrefetchThreshold);
#endif
_consumers[i].SetCallback(OnMessage);
_consumerListeners[i] = new KNetCompactedConsumerRebalanceListener(i)