1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
use crate::{
acl::{AclManager, AuthorizationResult, Operation, Principal, ResourceType},
consumer::{ConsumerGroupConfig, ConsumerGroupCoordinator, ConsumerGroupMessage},
metrics::MetricsRegistry,
performance::{object_pool::MessagePools, ultra_performance::UltraPerformanceBroker},
protocol::{
high_performance_codec::HighPerformanceKafkaCodec, AlterConfigsRequest,
AlterConfigsResponse, BrokerMetadata, CreateTopicsRequest, CreateTopicsResponse,
DeleteTopicsRequest, DeleteTopicsResponse, DescribeConfigsRequest, DescribeConfigsResponse,
FetchRequest, FetchResponse, ListOffsetsRequest, ListOffsetsResponse, Message,
MetadataRequest, MetadataResponse, MultiFetchRequest, MultiFetchResponse, Offset,
PartitionFetchResponse, PartitionId, PartitionMetadata, ProduceRequest, ProduceResponse,
Request, Response, SaslAuthenticateRequest, SaslAuthenticateResponse, SaslHandshakeRequest,
SaslHandshakeResponse, TopicFetchResponse, TopicMetadata,
},
replication::{BrokerId, ReplicationConfig, ReplicationCoordinator},
storage::HybridStorage,
topic_manager::{PartitionAssigner, PartitionStrategy, TopicManager},
Result,
};
use std::sync::Arc;
use tokio::sync::broadcast::error::RecvError;
use tracing::{debug, error, info};
/// Enhanced topic description structure for detailed metadata
#[derive(Debug, Clone)]
pub struct TopicDescription {
pub name: String,
pub partitions: Vec<PartitionDescription>,
pub is_internal: bool,
pub error_code: i16,
}
#[derive(Debug, Clone)]
pub struct PartitionDescription {
pub id: u32,
pub leader: i32,
pub leader_epoch: i32,
pub replicas: Vec<i32>,
pub isr: Vec<i32>,
pub offline_replicas: Vec<i32>,
pub high_watermark: i64,
pub low_watermark: i64,
}
pub struct MessageHandler {
broker_id: BrokerId,
broker_port: u16,
storage: Arc<HybridStorage>,
topic_manager: Arc<TopicManager>,
partition_assigner: Arc<PartitionAssigner>,
replication_coordinator: Option<Arc<ReplicationCoordinator>>,
consumer_group_coordinator: Option<Arc<ConsumerGroupCoordinator>>,
metrics: Arc<MetricsRegistry>,
acl_manager: Option<Arc<parking_lot::RwLock<AclManager>>>,
ultra_performance_broker: Arc<UltraPerformanceBroker>,
#[allow(dead_code)]
high_performance_codec: HighPerformanceKafkaCodec,
#[allow(dead_code)]
message_pools: MessagePools,
}
impl MessageHandler {
pub fn new() -> Result<Self> {
Self::new_with_broker_id(0, 9092, false)
}
pub async fn new_with_recovery() -> Result<Self> {
Self::new_with_broker_id_and_recovery(0, 9092, false).await
}
pub fn new_with_broker_id(
broker_id: BrokerId,
broker_port: u16,
enable_replication: bool,
) -> Result<Self> {
Self::new_with_features(broker_id, broker_port, enable_replication, false)
}
pub async fn new_with_broker_id_and_recovery(
broker_id: BrokerId,
broker_port: u16,
enable_replication: bool,
) -> Result<Self> {
Self::new_with_features_and_recovery(broker_id, broker_port, enable_replication, false)
.await
}
pub fn new_with_features(
broker_id: BrokerId,
broker_port: u16,
enable_replication: bool,
enable_consumer_groups: bool,
) -> Result<Self> {
let storage = Arc::new(HybridStorage::new("./data")?);
let topic_manager = Arc::new(TopicManager::new());
let partition_assigner = Arc::new(PartitionAssigner::new(Arc::clone(&topic_manager)));
let replication_coordinator = if enable_replication {
Some(Arc::new(ReplicationCoordinator::new(
broker_id,
ReplicationConfig::default(),
)))
} else {
None
};
let consumer_group_coordinator = if enable_consumer_groups {
Some(Arc::new(ConsumerGroupCoordinator::new(
ConsumerGroupConfig::default(),
Arc::clone(&topic_manager),
Some(Arc::clone(&storage)),
None, // No metadata persistence directory configured by default
)))
} else {
None
};
let metrics = Arc::new(MetricsRegistry::new());
// Start metrics background tasks
let metrics_clone = Arc::clone(&metrics);
tokio::spawn(async move {
metrics_clone.start_background_tasks().await;
});
let ultra_performance_broker = Arc::new(UltraPerformanceBroker::new());
let handler = Self {
broker_id,
broker_port,
storage,
topic_manager,
partition_assigner,
replication_coordinator,
consumer_group_coordinator,
metrics,
acl_manager: None, // ACL disabled by default
ultra_performance_broker,
high_performance_codec: HighPerformanceKafkaCodec::new(),
message_pools: MessagePools::new(),
};
// Update topic metrics
handler.update_topic_metrics();
Ok(handler)
}
pub async fn new_with_features_and_recovery(
broker_id: BrokerId,
broker_port: u16,
enable_replication: bool,
enable_consumer_groups: bool,
) -> Result<Self> {
let storage = Arc::new(HybridStorage::new("./data")?);
storage.load_from_disk().await?;
let topic_manager = Arc::new(TopicManager::new());
// Register topics from storage recovery into topic manager
Self::register_recovered_topics(Arc::clone(&storage), Arc::clone(&topic_manager))?;
let partition_assigner = Arc::new(PartitionAssigner::new(Arc::clone(&topic_manager)));
let replication_coordinator = if enable_replication {
Some(Arc::new(ReplicationCoordinator::new(
broker_id,
ReplicationConfig::default(),
)))
} else {
None
};
let consumer_group_coordinator = if enable_consumer_groups {
let coordinator = Arc::new(ConsumerGroupCoordinator::new(
ConsumerGroupConfig::default(),
Arc::clone(&topic_manager),
Some(Arc::clone(&storage)),
None, // No metadata persistence directory configured by default
));
// Start the coordinator
coordinator.clone().start().await?;
Some(coordinator)
} else {
None
};
let metrics = Arc::new(MetricsRegistry::new());
// Start metrics background tasks
let metrics_clone = Arc::clone(&metrics);
tokio::spawn(async move {
metrics_clone.start_background_tasks().await;
});
let ultra_performance_broker = Arc::new(UltraPerformanceBroker::new());
let handler = Self {
broker_id,
broker_port,
storage,
topic_manager,
partition_assigner,
replication_coordinator,
consumer_group_coordinator,
metrics,
acl_manager: None, // ACL disabled by default
ultra_performance_broker,
high_performance_codec: HighPerformanceKafkaCodec::new(),
message_pools: MessagePools::new(),
};
// Update topic metrics after recovery
handler.update_topic_metrics();
Ok(handler)
}
pub async fn handle_request(&self, request: Request) -> Result<Response> {
// Record request received
self.metrics.broker.request_received();
match request {
Request::Produce(req) => {
debug!(
"Handling produce request for topic: {}, partition: {}",
req.topic, req.partition
);
self.handle_produce(req).await
}
Request::Fetch(req) => {
debug!(
"Handling fetch request for topic: {}, partition: {}, offset: {}",
req.topic, req.partition, req.offset
);
self.handle_fetch(req).await
}
Request::MultiFetch(req) => {
debug!(
"Handling multi-fetch request for {} topics with {} total partitions",
req.topics.len(),
req.topics.iter().map(|t| t.partitions.len()).sum::<usize>()
);
self.handle_multi_fetch(req).await
}
Request::ListOffsets(req) => {
debug!(
"Handling list offsets request for topic: {}, partition: {}, timestamp: {}",
req.topic, req.partition, req.timestamp
);
self.handle_list_offsets(req).await
}
Request::Metadata(req) => {
debug!("Handling metadata request for topics: {:?}", req.topics);
self.handle_metadata(req).await
}
Request::CreateTopics(req) => {
debug!(
"Handling create topics request for {} topics",
req.topics.len()
);
self.handle_create_topics(req).await
}
Request::DeleteTopics(req) => {
debug!(
"Handling delete topics request for {} topics",
req.topic_names.len()
);
self.handle_delete_topics(req).await
}
Request::DescribeConfigs(req) => {
debug!(
"Handling describe configs request for {} resources",
req.resources.len()
);
self.handle_describe_configs(req).await
}
Request::AlterConfigs(req) => {
debug!(
"Handling alter configs request for {} resources",
req.resources.len()
);
self.handle_alter_configs(req).await
}
Request::SaslHandshake(req) => {
debug!(
"Handling SASL handshake request for mechanism: {}",
req.mechanism
);
self.handle_sasl_handshake(req).await
}
Request::SaslAuthenticate(req) => {
debug!(
"Handling SASL authenticate request with {} bytes",
req.auth_bytes.len()
);
self.handle_sasl_authenticate(req).await
}
}
}
async fn handle_produce(&self, request: ProduceRequest) -> Result<Response> {
// 🚀 JAVA CLIENT COMPATIBILITY: Start performance timing for Java client optimization
let start_time = std::time::Instant::now();
// If partition is u32::MAX, use dynamic assignment
let partition = if request.partition == u32::MAX {
// Auto-assign partition based on message key
let key = request
.messages
.first()
.and_then(|msg| msg.key.as_ref())
.map(|bytes| bytes.as_ref());
let strategy = if key.is_some() {
PartitionStrategy::KeyHash
} else {
PartitionStrategy::RoundRobin
};
let assigned_partition =
self.partition_assigner
.assign_partition(&request.topic, key, strategy)?;
// Update topic metrics when a topic is potentially created
self.update_topic_metrics();
assigned_partition
} else {
// Use specified partition, ensure topic exists with proper partition count
self.topic_manager.ensure_topic_exists(&request.topic)?;
self.update_topic_metrics();
if !self
.topic_manager
.partition_exists(&request.topic, request.partition)
{
let topic_clone = request.topic.clone();
return Ok(Response::Produce(ProduceResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
base_offset: 0,
error_code: 3, // Unknown topic or partition
error_message: Some(format!(
"Partition {} does not exist for topic {}",
request.partition, topic_clone
)),
}));
}
request.partition
};
// Calculate metrics before moving messages
let message_count = request.messages.len() as u64;
// Calculate total bytes for metrics (performance optimized)
let total_bytes: u64 = request
.messages
.iter()
.map(|msg| {
let key_size = msg.key.as_ref().map(|k| k.len()).unwrap_or(0);
let value_size = msg.value.len();
let headers_size = msg
.headers
.iter()
.map(|(k, v)| k.len() + v.len())
.sum::<usize>();
// Include timestamp (8 bytes)
key_size + value_size + headers_size + 8
})
.sum::<usize>() as u64;
// Create shared message reference to avoid cloning
let messages_arc = Arc::new(request.messages);
// 🚀 JAVA CLIENT COMPATIBILITY: Use ultra-performance broker with fast acknowledgment
let base_offset = match self.ultra_performance_broker.append_messages_ultra_shared(
&request.topic,
partition,
Arc::clone(&messages_arc),
) {
Ok(offset) => {
let processing_duration = start_time.elapsed();
if processing_duration > std::time::Duration::from_millis(100) {
info!("⚠️ JAVA CLIENT WARNING: Slow message processing detected: {:?} (target: <100ms)", processing_duration);
}
info!("🚀 ULTRA-PERFORMANCE: Successfully used ultra-performance broker, offset: {}, duration: {:?}", offset, processing_duration);
offset
}
Err(e) => {
let processing_duration = start_time.elapsed();
info!("⚠️ ULTRA-PERFORMANCE: Ultra-performance broker failed ({}) after {:?}, falling back to traditional storage", e, processing_duration);
// Fallback to basic storage if ultra-performance fails
// Convert Arc back to Vec for compatibility
let messages = Arc::try_unwrap(messages_arc).unwrap_or_else(|arc| (*arc).clone());
self.storage
.append_messages(&request.topic, partition, messages)?
}
};
// Record metrics with actual message data
info!(
"📊 METRICS DEBUG: Recording {} messages, {} bytes",
message_count, total_bytes
);
self.metrics
.throughput
.record_produced(message_count, total_bytes);
self.metrics.storage.record_message_stored(total_bytes);
// If replication is enabled and this broker is the leader, replicate to followers
if let Some(ref coordinator) = self.replication_coordinator {
if coordinator.is_leader(&request.topic, partition).await {
// In a full implementation, we'd wait for replication acknowledgments
// based on the required acknowledgments (acks) setting
debug!(
"Replicating messages for {}:{} as leader (base_offset: {})",
request.topic, partition, base_offset
);
}
}
// 🚀 JAVA CLIENT COMPATIBILITY: Measure total processing time and log performance
let total_duration = start_time.elapsed();
if total_duration > std::time::Duration::from_millis(500) {
info!("🚨 JAVA CLIENT CRITICAL: Total processing time exceeded 500ms: {:?} (Java client timeout risk!)", total_duration);
} else if total_duration > std::time::Duration::from_millis(100) {
info!(
"⚠️ JAVA CLIENT WARNING: Processing time: {:?} (target: <100ms for Java clients)",
total_duration
);
} else {
info!(
"✅ JAVA CLIENT OPTIMIZED: Fast processing achieved: {:?}",
total_duration
);
}
info!(
"Produced messages to topic: {}, partition: {}, base_offset: {}, acks: {}, processing_time: {:?}",
request.topic, partition, base_offset, request.acks, total_duration
);
// Handle acks=0 (fire-and-forget) - no response should be sent
if request.acks == 0 {
info!("🔥 FIRE-AND-FORGET: acks=0, not sending response to client");
return Ok(Response::NoResponse);
}
// 🚀 JAVA CLIENT COMPATIBILITY: Force immediate buffer flush for Java clients
// This ensures data is persisted immediately and reduces timeout risk
self.force_immediate_flush(&request.topic, partition).await;
// 🚀 JAVA CLIENT COMPATIBILITY: Prioritized response construction for fast acknowledgment
let response = ProduceResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition,
base_offset,
error_code: 0,
error_message: None,
};
info!("📤 JAVA CLIENT ACK: Sending immediate acknowledgment for correlation_id: {}, total_time: {:?}", request.correlation_id, total_duration);
Ok(Response::Produce(response))
}
/// Force immediate buffer flush for Java clients to reduce timeout risk
async fn force_immediate_flush(&self, topic: &str, partition: u32) {
// 🚀 JAVA CLIENT BUFFER OPTIMIZATION: Force all buffered data to disk immediately
let flush_start = std::time::Instant::now();
// Force ultra-performance broker to flush its buffers
if let Err(e) = self
.ultra_performance_broker
.force_flush_partition(topic, partition)
.await
{
info!(
"⚠️ FLUSH WARNING: Ultra-performance broker flush failed: {}",
e
);
}
// Force traditional storage to flush as well (fallback)
if let Err(e) = self.storage.flush_partition(topic, partition) {
info!("⚠️ FLUSH WARNING: Traditional storage flush failed: {}", e);
}
let flush_duration = flush_start.elapsed();
if flush_duration > std::time::Duration::from_millis(10) {
info!(
"⚠️ FLUSH SLOW: Buffer flush took {:?} (target: <10ms)",
flush_duration
);
} else {
info!(
"✅ FLUSH FAST: Buffer flush completed in {:?}",
flush_duration
);
}
}
async fn handle_fetch(&self, request: FetchRequest) -> Result<Response> {
// Enhanced fetch with timeout and improved error handling
let start_time = std::time::Instant::now();
let timeout_duration = std::time::Duration::from_millis(request.timeout_ms as u64);
debug!(
"Handling fetch request for {}:{} from offset {}, max_bytes={}, timeout_ms={}",
request.topic, request.partition, request.offset, request.max_bytes, request.timeout_ms
);
// Validate topic and partition existence
let validation_result = self
.validate_topic_partition(&request.topic, request.partition)
.await;
if let Some(error_response) = validation_result {
return Ok(Response::Fetch(FetchResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
messages: vec![],
error_code: error_response.0,
error_message: Some(error_response.1),
}));
}
// Check if we have messages immediately available
let mut messages = self
.fetch_messages_with_limit(
&request.topic,
request.partition,
request.offset,
request.max_bytes,
)
.await?;
// If no messages and timeout > 0, wait for new messages
if messages.is_empty() && request.timeout_ms > 0 {
messages = self
.wait_for_messages(
&request.topic,
request.partition,
request.offset,
request.max_bytes,
timeout_duration,
start_time,
)
.await?;
}
let bytes_returned: usize = messages
.iter()
.map(|(_, msg)| msg.value.len() + msg.key.as_ref().map(|k| k.len()).unwrap_or(0))
.sum();
// Record metrics
let message_count = messages.len() as u64;
self.metrics
.throughput
.record_consumed(message_count, bytes_returned as u64);
debug!(
"Fetch completed: {} messages, {} bytes for {}:{} from offset {}",
messages.len(),
bytes_returned,
request.topic,
request.partition,
request.offset
);
let response = FetchResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
messages,
error_code: 0,
error_message: None,
};
Ok(Response::Fetch(response))
}
async fn handle_metadata(&self, request: MetadataRequest) -> Result<Response> {
debug!(
"Metadata request: topics={:?}, allow_auto_topic_creation={}",
request.topics, request.allow_auto_topic_creation
);
let requested_topics = if request.topics.is_empty() {
self.topic_manager.list_topics()
} else {
request.topics
};
let mut topic_metadata = Vec::new();
for topic in requested_topics {
if let Some(topic_info) = self.topic_manager.get_topic(&topic) {
let partition_metadata: Vec<PartitionMetadata> = topic_info
.partitions
.into_iter()
.map(|partition_info| PartitionMetadata {
id: partition_info.id,
leader: partition_info.leader.map(|id| id as i32),
replicas: partition_info
.replicas
.into_iter()
.map(|id| id as i32)
.collect(),
isr: partition_info
.in_sync_replicas
.into_iter()
.map(|id| id as i32)
.collect(),
leader_epoch: 0, // Default epoch for Java client compatibility
})
.collect();
topic_metadata.push(TopicMetadata {
name: topic,
error_code: 0, // NO_ERROR
partitions: partition_metadata,
});
} else if request.allow_auto_topic_creation {
// Auto-create topic if allowed and return its metadata
match self.topic_manager.ensure_topic_exists(&topic) {
Ok(topic_info) => {
let partition_metadata: Vec<PartitionMetadata> = topic_info
.partitions
.into_iter()
.map(|partition_info| PartitionMetadata {
id: partition_info.id,
leader: partition_info.leader.map(|id| id as i32),
replicas: partition_info
.replicas
.into_iter()
.map(|id| id as i32)
.collect(),
isr: partition_info
.in_sync_replicas
.into_iter()
.map(|id| id as i32)
.collect(),
leader_epoch: 0, // Default epoch for Java client compatibility
})
.collect();
topic_metadata.push(TopicMetadata {
name: topic,
error_code: 0, // NO_ERROR
partitions: partition_metadata,
});
// Update topic metrics when a topic is auto-created
self.update_topic_metrics();
}
Err(_) => {
// Failed to auto-create, return error
topic_metadata.push(TopicMetadata {
name: topic,
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
partitions: Vec::new(),
});
}
}
} else {
// Return unknown topic error for non-existent topics
topic_metadata.push(TopicMetadata {
name: topic,
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
partitions: Vec::new(),
});
}
}
let response = MetadataResponse {
correlation_id: request.correlation_id,
brokers: vec![BrokerMetadata {
node_id: 0,
host: "localhost".to_string(),
port: self.broker_port as i32,
}],
topics: topic_metadata,
api_version: request.api_version, // Forward the requested API version
};
Ok(Response::Metadata(response))
}
async fn handle_list_offsets(&self, request: ListOffsetsRequest) -> Result<Response> {
// Ensure topic exists
if self.topic_manager.get_topic(&request.topic).is_none() {
return Ok(Response::ListOffsets(ListOffsetsResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
timestamp: request.timestamp,
offset: -1,
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
error_message: Some("Unknown topic".to_string()),
}));
}
// Check if partition exists
if !self
.topic_manager
.partition_exists(&request.topic, request.partition)
{
return Ok(Response::ListOffsets(ListOffsetsResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
timestamp: request.timestamp,
offset: -1,
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
error_message: Some("Unknown partition".to_string()),
}));
}
// Get offset based on timestamp
let offset = match request.timestamp {
-2 => {
// Earliest offset
match self
.storage
.get_earliest_offset(&request.topic, request.partition)
{
Some(earliest_offset) => earliest_offset as i64,
None => 0, // If no messages, earliest is 0
}
}
-1 => {
// Latest offset - get from storage
match self
.storage
.get_latest_offset(&request.topic, request.partition)
{
Some(latest_offset) => latest_offset as i64,
None => 0, // If no messages, latest is 0
}
}
timestamp if timestamp >= 0 => {
// Find offset by timestamp
match self.storage.get_offset_by_timestamp(
&request.topic,
request.partition,
timestamp as u64,
) {
Some(found_offset) => found_offset as i64,
None => {
// If no message found with that timestamp, return latest offset
match self
.storage
.get_latest_offset(&request.topic, request.partition)
{
Some(latest_offset) => latest_offset as i64,
None => 0,
}
}
}
}
_invalid_timestamp => {
// Invalid timestamp, return error
return Ok(Response::ListOffsets(ListOffsetsResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
timestamp: request.timestamp,
offset: -1,
error_code: 43, // INVALID_TIMESTAMP
error_message: Some("Invalid timestamp value".to_string()),
}));
}
};
debug!(
"ListOffsets for {}:{} timestamp={} -> offset={}",
request.topic, request.partition, request.timestamp, offset
);
Ok(Response::ListOffsets(ListOffsetsResponse {
correlation_id: request.correlation_id,
topic: request.topic,
partition: request.partition,
timestamp: request.timestamp,
offset,
error_code: 0, // NO_ERROR
error_message: None,
}))
}
/// Enable replication for a partition as leader
pub async fn become_leader(
&self,
topic: &str,
partition: PartitionId,
replicas: Vec<BrokerId>,
) -> Result<()> {
if let Some(ref coordinator) = self.replication_coordinator {
coordinator
.become_leader(topic, partition, replicas)
.await?;
info!(
"Broker {} became leader for {}:{}",
self.broker_id, topic, partition
);
}
Ok(())
}
/// Enable replication for a partition as follower
pub async fn become_follower(
&self,
topic: &str,
partition: PartitionId,
leader_id: BrokerId,
) -> Result<()> {
if let Some(ref coordinator) = self.replication_coordinator {
coordinator
.become_follower(topic, partition, leader_id)
.await?;
info!(
"Broker {} became follower for {}:{} with leader {}",
self.broker_id, topic, partition, leader_id
);
}
Ok(())
}
/// Check if this broker is the leader for a partition
pub async fn is_leader(&self, topic: &str, partition: PartitionId) -> bool {
if let Some(ref coordinator) = self.replication_coordinator {
coordinator.is_leader(topic, partition).await
} else {
true // If replication is disabled, treat as leader
}
}
/// Get the leader for a partition
pub async fn get_leader(&self, topic: &str, partition: PartitionId) -> Option<BrokerId> {
if let Some(ref coordinator) = self.replication_coordinator {
coordinator.get_leader(topic, partition).await
} else {
Some(self.broker_id) // If replication is disabled, this broker is the leader
}
}
/// Handle consumer group message
pub async fn handle_consumer_group_message(
&self,
message: ConsumerGroupMessage,
) -> Result<ConsumerGroupMessage> {
if let Some(ref coordinator) = self.consumer_group_coordinator {
let response = match &message {
ConsumerGroupMessage::JoinGroup { .. } => {
coordinator.handle_join_group(message).await
}
ConsumerGroupMessage::SyncGroup { .. } => {
coordinator.handle_sync_group(message).await
}
ConsumerGroupMessage::Heartbeat { .. } => {
coordinator.handle_heartbeat(message).await
}
ConsumerGroupMessage::LeaveGroup { .. } => {
coordinator.handle_leave_group(message).await
}
ConsumerGroupMessage::ListGroups => coordinator.handle_list_groups().await,
ConsumerGroupMessage::DescribeGroups { .. } => {
coordinator.handle_describe_groups(message).await
}
_ => {
// Return error for unsupported message types
ConsumerGroupMessage::HeartbeatResponse {
error_code: crate::consumer::error_codes::INVALID_GROUP_ID,
}
}
};
Ok(response)
} else {
// Consumer groups are not enabled
Ok(ConsumerGroupMessage::HeartbeatResponse {
error_code: crate::consumer::error_codes::CONSUMER_COORDINATOR_NOT_AVAILABLE,
})
}
}
/// Get consumer group coordinator (if enabled)
pub fn get_consumer_group_coordinator(&self) -> Option<Arc<ConsumerGroupCoordinator>> {
self.consumer_group_coordinator.clone()
}
/// Check if consumer groups are enabled
pub fn consumer_groups_enabled(&self) -> bool {
self.consumer_group_coordinator.is_some()
}
/// Get metrics registry
pub fn get_metrics(&self) -> Arc<MetricsRegistry> {
Arc::clone(&self.metrics)
}
/// Get broker port
pub fn get_broker_port(&self) -> u16 {
self.broker_port
}
/// Update topic and partition metrics
pub fn update_topic_metrics(&self) {
let topic_names = self.topic_manager.list_topics();
let topic_count = topic_names.len();
let mut partition_count = 0usize;
for topic_name in topic_names {
if let Some(topic_metadata) = self.topic_manager.get_topic(&topic_name) {
partition_count += topic_metadata.num_partitions as usize;
}
}
self.metrics.broker.update_topic_count(topic_count);
self.metrics.broker.update_partition_count(partition_count);
}
/// Ensure a topic exists, creating it with default config if it doesn't
pub fn ensure_topic_exists(
&self,
topic_name: &str,
) -> Result<crate::topic_manager::TopicMetadata> {
self.topic_manager.ensure_topic_exists(topic_name)
}
/// Get topic metadata for Kafka metadata response
pub fn get_topic_metadata_for_kafka(
&self,
requested_topics: Option<Vec<String>>,
) -> Vec<(String, u32)> {
if let Some(topics) = requested_topics {
// Return metadata for specific requested topics
topics
.into_iter()
.filter_map(|topic| {
if let Some(topic_info) = self.topic_manager.get_topic(&topic) {
Some((topic, topic_info.num_partitions))
} else {
// Return the topic with error (0 partitions indicates error)
Some((topic, 0))
}
})
.collect()
} else {
// Return all topics
self.topic_manager
.list_topics()
.into_iter()
.filter_map(|topic| {
if let Some(topic_info) = self.topic_manager.get_topic(&topic) {
Some((topic, topic_info.num_partitions))
} else {
None
}
})
.collect()
}
}
/// Get enhanced topic descriptions for DescribeTopics functionality
pub fn get_enhanced_topic_descriptions(
&self,
requested_topics: Option<Vec<String>>,
) -> Vec<TopicDescription> {
let topics_to_describe = if let Some(topics) = requested_topics {
// Kafka protocol: empty topics array means "return all topics"
if topics.is_empty() {
info!("Empty topics array - should return all topics");
let all_topics = self.topic_manager.list_topics();
info!(
"Available topics from topic_manager.list_topics(): {:?}",
all_topics
);
all_topics
} else {
info!("Specific topics requested: {:?}", topics);
topics
}
} else {
info!("No topics specified - returning all topics");
let all_topics = self.topic_manager.list_topics();
info!(
"Available topics from topic_manager.list_topics(): {:?}",
all_topics
);
all_topics
};
topics_to_describe
.into_iter()
.map(|topic_name| {
if let Some(topic_info) = self.topic_manager.get_topic(&topic_name) {
// Topic exists - get detailed partition information
let mut partitions = Vec::new();
for partition_id in 0..topic_info.num_partitions {
// Get storage info for high/low watermarks
let high_watermark = self
.storage
.get_latest_offset(&topic_name, partition_id)
.map(|offset| offset + 1) // High watermark is next offset to be written
.unwrap_or(0);
let low_watermark = self
.storage
.get_earliest_offset(&topic_name, partition_id)
.unwrap_or(0);
partitions.push(PartitionDescription {
id: partition_id,
leader: 0, // This broker is always the leader for now
leader_epoch: 0,
replicas: vec![0], // Only this broker
isr: vec![0], // In-sync replicas - only this broker
offline_replicas: vec![], // No offline replicas
high_watermark: high_watermark as i64,
low_watermark: low_watermark as i64,
});
}
TopicDescription {
name: topic_name,
partitions,
is_internal: false,
error_code: 0,
}
} else {
// Topic doesn't exist
TopicDescription {
name: topic_name,
partitions: vec![],
is_internal: false,
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
}
}
})
.collect()
}
/// Validate topic and partition existence
async fn validate_topic_partition(
&self,
topic: &str,
partition: PartitionId,
) -> Option<(i16, String)> {
if let Some(topic_metadata) = self.topic_manager.get_topic(topic) {
if partition >= topic_metadata.num_partitions {
Some((
3,
format!(
"Partition {} does not exist for topic {} (has {} partitions)",
partition, topic, topic_metadata.num_partitions
),
))
} else {
None // Valid topic and partition
}
} else {
Some((3, format!("Topic {} does not exist", topic)))
}
}
/// Fetch messages with proper byte and message limits
async fn fetch_messages_with_limit(
&self,
topic: &str,
partition: PartitionId,
offset: Offset,
max_bytes: u32,
) -> Result<Vec<(Offset, Message)>> {
// Try ultra-performance fetch first
let all_messages = match self
.ultra_performance_broker
.fetch_messages_ultra(topic, partition, offset, max_bytes)
.await
{
Ok(messages) if !messages.is_empty() => messages,
_ => {
// Fallback to basic storage
self.storage
.fetch_messages(topic, partition, offset, max_bytes)?
}
};
// Apply stricter byte limiting
let mut result = Vec::new();
let mut bytes_accumulated = 0u32;
for (msg_offset, message) in all_messages {
let msg_size = message.value.len() as u32
+ message.key.as_ref().map(|k| k.len() as u32).unwrap_or(0);
// Always include at least one message, even if it exceeds max_bytes
if result.is_empty() || bytes_accumulated + msg_size <= max_bytes {
bytes_accumulated += msg_size;
result.push((msg_offset, message));
} else {
break;
}
}
Ok(result)
}
/// Wait for new messages with timeout
async fn wait_for_messages(
&self,
topic: &str,
partition: PartitionId,
offset: Offset,
max_bytes: u32,
timeout_duration: std::time::Duration,
start_time: std::time::Instant,
) -> Result<Vec<(Offset, Message)>> {
// Create a notification subscription
let mut notification_rx = self.storage.subscribe_to_messages();
loop {
let elapsed = start_time.elapsed();
if elapsed >= timeout_duration {
debug!(
"Fetch timeout after {:?} for {}:{}",
elapsed, topic, partition
);
break;
}
// Calculate remaining timeout
let remaining_timeout = timeout_duration.saturating_sub(elapsed);
// Wait for notification or timeout
match tokio::time::timeout(remaining_timeout, notification_rx.recv()).await {
Ok(Ok(notification)) => {
// Check if the notification is for our topic/partition and has messages at or after our offset
if notification.topic == topic && notification.partition == partition {
let (start_offset, end_offset) = notification.offset_range;
// Check if there are new messages at or after the offset we're waiting for
if end_offset > offset {
debug!(
"Received notification for {}:{} - new messages from {} to {} (waiting for {}+)",
topic, partition, start_offset, end_offset, offset
);
// Check for new messages
let messages = self
.fetch_messages_with_limit(topic, partition, offset, max_bytes)
.await?;
if !messages.is_empty() {
debug!(
"Found {} messages after notification wait {:?}",
messages.len(),
elapsed
);
return Ok(messages);
}
}
}
}
Ok(Err(RecvError::Lagged(_))) => {
// Channel lagged, try to fetch immediately
debug!("Notification channel lagged, checking for messages immediately");
let messages = self
.fetch_messages_with_limit(topic, partition, offset, max_bytes)
.await?;
if !messages.is_empty() {
return Ok(messages);
}
}
Ok(Err(RecvError::Closed)) => {
// Channel closed, fall back to polling
debug!("Notification channel closed, falling back to immediate check");
break;
}
Err(_) => {
// Timeout - check once more before giving up
debug!(
"No notifications received within timeout for {}:{}",
topic, partition
);
break;
}
}
}
// Final check for messages before returning empty result
let messages = self
.fetch_messages_with_limit(topic, partition, offset, max_bytes)
.await?;
if !messages.is_empty() {
debug!("Found {} messages on final check", messages.len());
}
Ok(messages)
}
/// Handle multi-topic fetch request
async fn handle_multi_fetch(&self, request: MultiFetchRequest) -> Result<Response> {
let start_time = std::time::Instant::now();
let timeout_duration = std::time::Duration::from_millis(request.max_wait_ms as u64);
debug!(
"Handling multi-fetch request for {} topics, max_wait_ms={}, min_bytes={}, max_bytes={}",
request.topics.len(), request.max_wait_ms, request.min_bytes, request.max_bytes
);
let mut topic_responses = Vec::new();
let mut total_bytes = 0u32;
let mut has_messages = false;
// Process each topic
for topic_request in request.topics {
let mut partition_responses = Vec::new();
// Process each partition in the topic
for partition_request in topic_request.partitions {
// Validate topic and partition
let validation_result = self
.validate_topic_partition(&topic_request.topic, partition_request.partition)
.await;
if let Some(error_response) = validation_result {
partition_responses.push(PartitionFetchResponse {
partition: partition_request.partition,
messages: vec![],
error_code: error_response.0,
error_message: Some(error_response.1),
});
continue;
}
// Fetch messages for this partition
let messages = self
.fetch_messages_with_limit(
&topic_request.topic,
partition_request.partition,
partition_request.offset,
partition_request.max_bytes,
)
.await?;
if !messages.is_empty() {
has_messages = true;
// Calculate bytes for this partition
let partition_bytes: u32 = messages
.iter()
.map(|(_, msg)| {
msg.value.len() as u32
+ msg.key.as_ref().map(|k| k.len() as u32).unwrap_or(0)
})
.sum();
total_bytes += partition_bytes;
}
partition_responses.push(PartitionFetchResponse {
partition: partition_request.partition,
messages,
error_code: 0,
error_message: None,
});
// Check if we've hit the max_bytes limit across all partitions
if total_bytes >= request.max_bytes {
debug!(
"Multi-fetch reached max_bytes limit: {} >= {}",
total_bytes, request.max_bytes
);
break;
}
}
topic_responses.push(TopicFetchResponse {
topic: topic_request.topic,
partitions: partition_responses,
});
// Check byte limit across topics too
if total_bytes >= request.max_bytes {
break;
}
}
// If no messages and min_bytes not satisfied, wait for timeout
if !has_messages && total_bytes < request.min_bytes && request.max_wait_ms > 0 {
debug!(
"Multi-fetch waiting for more data: {} bytes < {} min_bytes",
total_bytes, request.min_bytes
);
// In a real implementation, we'd wait for new messages or timeout
// For now, just add a small delay
tokio::time::sleep(std::cmp::min(
timeout_duration,
std::time::Duration::from_millis(50),
))
.await;
}
let elapsed = start_time.elapsed();
debug!(
"Multi-fetch completed: {} topics, {} total bytes in {:?}",
topic_responses.len(),
total_bytes,
elapsed
);
Ok(Response::MultiFetch(MultiFetchResponse {
correlation_id: request.correlation_id,
topics: topic_responses,
error_code: 0,
error_message: None,
}))
}
/// Handle create topics admin request
async fn handle_create_topics(&self, request: CreateTopicsRequest) -> Result<Response> {
use crate::protocol::{CreatableTopicConfigs, CreatableTopicResult};
let mut topic_results = Vec::new();
for topic in request.topics {
// Validate topic configuration
if topic.name.is_empty() {
topic_results.push(CreatableTopicResult {
name: topic.name.clone(),
topic_id: None,
error_code: 60, // INVALID_TOPIC_EXCEPTION
error_message: Some("Topic name cannot be empty".to_string()),
num_partitions: -1,
replication_factor: -1,
configs: Vec::new(),
});
continue;
}
// Check if topic already exists
if self.topic_manager.get_topic(&topic.name).is_some() {
topic_results.push(CreatableTopicResult {
name: topic.name.clone(),
topic_id: None,
error_code: 36, // TOPIC_ALREADY_EXISTS
error_message: Some(format!("Topic '{}' already exists", topic.name)),
num_partitions: -1,
replication_factor: -1,
configs: Vec::new(),
});
continue;
}
// Validate only mode
if request.validate_only {
topic_results.push(CreatableTopicResult {
name: topic.name.clone(),
topic_id: None,
error_code: 0, // Success for validation
error_message: None,
num_partitions: topic.num_partitions,
replication_factor: topic.replication_factor,
configs: topic
.configs
.into_iter()
.map(|c| CreatableTopicConfigs {
name: c.name,
value: c.value,
read_only: false,
config_source: 1, // DYNAMIC_TOPIC_CONFIG
is_sensitive: false,
})
.collect(),
});
continue;
}
// Create topic
let config = crate::topic_manager::TopicConfig {
num_partitions: topic.num_partitions as u32,
replication_factor: topic.replication_factor as u32,
segment_size: 1024 * 1024 * 1024, // 1GB default
retention_ms: Some(7 * 24 * 60 * 60 * 1000), // 7 days default
};
match self.topic_manager.create_topic(&topic.name, config) {
Ok(_) => {
info!(
"Created topic '{}' with {} partitions",
topic.name, topic.num_partitions
);
topic_results.push(CreatableTopicResult {
name: topic.name.clone(),
topic_id: Some(format!("topic-{}", topic.name)),
error_code: 0,
error_message: None,
num_partitions: topic.num_partitions,
replication_factor: topic.replication_factor,
configs: topic
.configs
.into_iter()
.map(|c| CreatableTopicConfigs {
name: c.name,
value: c.value,
read_only: false,
config_source: 1,
is_sensitive: false,
})
.collect(),
});
}
Err(e) => {
error!("Failed to create topic '{}': {}", topic.name, e);
topic_results.push(CreatableTopicResult {
name: topic.name.clone(),
topic_id: None,
error_code: 1, // UNKNOWN_SERVER_ERROR
error_message: Some(format!("Failed to create topic: {}", e)),
num_partitions: -1,
replication_factor: -1,
configs: Vec::new(),
});
}
}
}
Ok(Response::CreateTopics(CreateTopicsResponse {
correlation_id: request.correlation_id,
throttle_time_ms: 0,
topics: topic_results,
}))
}
/// Handle delete topics admin request
async fn handle_delete_topics(&self, request: DeleteTopicsRequest) -> Result<Response> {
use crate::protocol::DeletableTopicResult;
let mut responses = Vec::new();
for topic_name in request.topic_names {
// Check if topic exists
if self.topic_manager.get_topic(&topic_name).is_none() {
responses.push(DeletableTopicResult {
name: topic_name.clone(),
topic_id: None,
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
error_message: Some(format!("Topic '{}' does not exist", topic_name)),
});
continue;
}
// Delete topic (for now, just remove from topic manager)
// In a full implementation, this would also clean up storage
match self.topic_manager.delete_topic(&topic_name) {
Ok(_) => {
info!("Deleted topic '{}'", topic_name);
responses.push(DeletableTopicResult {
name: topic_name.clone(),
topic_id: Some(format!("topic-{}", topic_name)),
error_code: 0,
error_message: None,
});
}
Err(e) => {
error!("Failed to delete topic '{}': {}", topic_name, e);
responses.push(DeletableTopicResult {
name: topic_name.clone(),
topic_id: None,
error_code: 1, // UNKNOWN_SERVER_ERROR
error_message: Some(format!("Failed to delete topic: {}", e)),
});
}
}
}
Ok(Response::DeleteTopics(DeleteTopicsResponse {
correlation_id: request.correlation_id,
throttle_time_ms: 0,
responses,
}))
}
/// Handle describe configs admin request
async fn handle_describe_configs(&self, request: DescribeConfigsRequest) -> Result<Response> {
use crate::protocol::{DescribeConfigsResourceResult, DescribeConfigsResult};
let mut results = Vec::new();
for resource in request.resources {
match resource.resource_type {
2 => {
// Topic resource
if let Some(_topic) = self.topic_manager.get_topic(&resource.resource_name) {
// Return basic topic configurations
let mut configs = Vec::new();
// Add common topic configs
configs.push(DescribeConfigsResourceResult {
name: "cleanup.policy".to_string(),
value: "delete".to_string(),
read_only: false,
is_default: true,
config_source: 1, // DYNAMIC_TOPIC_CONFIG
is_sensitive: false,
synonyms: Vec::new(),
config_type: 4, // STRING
documentation: if request.include_documentation {
Some("The cleanup policy for segments".to_string())
} else {
None
},
});
configs.push(DescribeConfigsResourceResult {
name: "retention.ms".to_string(),
value: "604800000".to_string(), // 7 days
read_only: false,
is_default: true,
config_source: 1,
is_sensitive: false,
synonyms: Vec::new(),
config_type: 3, // LONG
documentation: if request.include_documentation {
Some("The retention time for log segments".to_string())
} else {
None
},
});
results.push(DescribeConfigsResult {
error_code: 0,
error_message: None,
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
configs,
});
} else {
results.push(DescribeConfigsResult {
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
error_message: Some(format!(
"Topic '{}' does not exist",
resource.resource_name
)),
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
configs: Vec::new(),
});
}
}
4 => {
// Broker resource
// Return basic broker configurations
let mut configs = Vec::new();
configs.push(DescribeConfigsResourceResult {
name: "log.retention.hours".to_string(),
value: "168".to_string(), // 7 days
read_only: false,
is_default: true,
config_source: 2, // DYNAMIC_BROKER_CONFIG
is_sensitive: false,
synonyms: Vec::new(),
config_type: 2, // INT
documentation: if request.include_documentation {
Some("The number of hours to keep log files".to_string())
} else {
None
},
});
results.push(DescribeConfigsResult {
error_code: 0,
error_message: None,
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
configs,
});
}
_ => {
results.push(DescribeConfigsResult {
error_code: 40, // INVALID_REQUEST
error_message: Some(format!(
"Unknown resource type: {}",
resource.resource_type
)),
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
configs: Vec::new(),
});
}
}
}
Ok(Response::DescribeConfigs(DescribeConfigsResponse {
correlation_id: request.correlation_id,
throttle_time_ms: 0,
results,
}))
}
/// Handle alter configs admin request
async fn handle_alter_configs(&self, request: AlterConfigsRequest) -> Result<Response> {
use crate::protocol::AlterConfigsResourceResponse;
let mut responses = Vec::new();
for resource in request.resources {
match resource.resource_type {
2 => {
// Topic resource
if let Some(_topic) = self.topic_manager.get_topic(&resource.resource_name) {
if request.validate_only {
info!(
"Validating config changes for topic '{}'",
resource.resource_name
);
responses.push(AlterConfigsResourceResponse {
error_code: 0,
error_message: None,
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
});
} else {
// For now, just log the config changes
// In a full implementation, this would update topic configurations
for config in &resource.configs {
info!(
"Setting config '{}' = {:?} for topic '{}'",
config.name, config.value, resource.resource_name
);
}
responses.push(AlterConfigsResourceResponse {
error_code: 0,
error_message: None,
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
});
}
} else {
responses.push(AlterConfigsResourceResponse {
error_code: 3, // UNKNOWN_TOPIC_OR_PARTITION
error_message: Some(format!(
"Topic '{}' does not exist",
resource.resource_name
)),
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
});
}
}
4 => {
// Broker resource
if request.validate_only {
info!(
"Validating config changes for broker '{}'",
resource.resource_name
);
} else {
// For now, just log the config changes
for config in &resource.configs {
info!(
"Setting broker config '{}' = {:?}",
config.name, config.value
);
}
}
responses.push(AlterConfigsResourceResponse {
error_code: 0,
error_message: None,
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
});
}
_ => {
responses.push(AlterConfigsResourceResponse {
error_code: 40, // INVALID_REQUEST
error_message: Some(format!(
"Unknown resource type: {}",
resource.resource_type
)),
resource_type: resource.resource_type,
resource_name: resource.resource_name.clone(),
});
}
}
}
Ok(Response::AlterConfigs(AlterConfigsResponse {
correlation_id: request.correlation_id,
throttle_time_ms: 0,
responses,
}))
}
async fn handle_sasl_handshake(&self, request: SaslHandshakeRequest) -> Result<Response> {
info!(
"SASL handshake requested for mechanism: {}",
request.mechanism
);
// For now, support PLAIN mechanism
let supported_mechanisms = vec!["PLAIN".to_string(), "SCRAM-SHA-256".to_string()];
let error_code = if supported_mechanisms.contains(&request.mechanism) {
0 // No error
} else {
33 // UNSUPPORTED_SASL_MECHANISM
};
Ok(Response::SaslHandshake(SaslHandshakeResponse {
correlation_id: request.correlation_id,
error_code,
mechanisms: supported_mechanisms,
}))
}
async fn handle_sasl_authenticate(&self, request: SaslAuthenticateRequest) -> Result<Response> {
info!(
"SASL authenticate requested with {} bytes of auth data",
request.auth_bytes.len()
);
// For now, return a simple successful authentication response
// In a full implementation, this would:
// 1. Parse the auth_bytes based on the SASL mechanism
// 2. Validate credentials against a user database
// 3. Create a session token if authentication succeeds
Ok(Response::SaslAuthenticate(SaslAuthenticateResponse {
correlation_id: request.correlation_id,
error_code: 0, // Success
error_message: None,
auth_bytes: Vec::new(), // Empty response for successful auth
session_lifetime_ms: 3600000, // 1 hour session
}))
}
/// Register topics recovered from storage into the topic manager
fn register_recovered_topics(
storage: Arc<HybridStorage>,
topic_manager: Arc<TopicManager>,
) -> Result<()> {
let recovered_topics = storage.get_topics();
for topic_name in recovered_topics {
let partitions = storage.get_partitions(&topic_name);
let partition_count = partitions.len() as u32;
if partition_count > 0 {
use crate::topic_manager::TopicConfig;
let config = TopicConfig {
num_partitions: partition_count,
..Default::default()
};
topic_manager.create_topic(&topic_name, config)?;
info!(
"Registered recovered topic '{}' with {} partitions",
topic_name, partition_count
);
}
}
Ok(())
}
/// Initialize ACL manager with configuration
pub fn with_acl_manager(mut self, acl_manager: AclManager) -> Self {
self.acl_manager = Some(Arc::new(parking_lot::RwLock::new(acl_manager)));
self
}
/// Check if ACLs are enabled
pub fn acl_enabled(&self) -> bool {
self.acl_manager.is_some()
}
/// Authorize a request based on principal and operation
pub fn authorize_request(
&self,
principal: &Principal,
resource_type: &ResourceType,
resource_name: &str,
operation: &Operation,
host: Option<&str>,
) -> AuthorizationResult {
match &self.acl_manager {
Some(acl_manager) => {
let acl_guard = acl_manager.read();
acl_guard.authorize(principal, resource_type, resource_name, operation, host)
}
None => AuthorizationResult::Allowed, // No ACL = allow all
}
}
/// Add ACL entry (requires write access)
pub fn add_acl(&self, acl: crate::acl::AclEntry) -> Result<()> {
match &self.acl_manager {
Some(acl_manager) => {
let mut acl_guard = acl_manager.write();
acl_guard.add_acl(acl);
Ok(())
}
None => Err(crate::FluxmqError::Config("ACL not enabled".to_string())),
}
}
/// Get ACL manager for external operations (read-only)
pub fn get_acl_manager(&self) -> Option<Arc<parking_lot::RwLock<AclManager>>> {
self.acl_manager.clone()
}
}