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
//! `OffsetFetch` (`api_key=9`). Reads from `Group.committed_offsets`.
//!
//! For v0-v7 the request carries the legacy single-group fields:
//! `group_id` + `topics: Option<Vec<OffsetFetchRequestTopic>>`. v8+ (KIP-516)
//! moves to a per-group `groups[]` array and, at v10, keys topics by
//! `topic_id`; that path is handled in `handle_groups`. Internal offset
//! storage stays name-keyed, so topic ids are resolved to names at the wire
//! boundary and echoed back on the response.
use bytes::{Bytes, BytesMut};
use tokio::sync::oneshot;
use crabka_metadata::{AclOperation, ResourceType};
use crabka_protocol::owned::offset_fetch_request::OffsetFetchRequest;
use crabka_protocol::owned::offset_fetch_response::{
OffsetFetchResponse, OffsetFetchResponseGroup, OffsetFetchResponsePartition,
OffsetFetchResponsePartitions, OffsetFetchResponseTopic, OffsetFetchResponseTopics,
};
use crabka_protocol::primitives::uuid::Uuid as WireUuid;
use crabka_protocol::{Decode, Encode};
use crate::authorizer::{AuthorizationRequest, AuthorizationResult, authorize_topics};
use crate::broker::Broker;
use crate::codes;
use crate::coordinator::unified::actor::{GroupActorMessage, GroupKindTag};
use crate::error::BrokerError;
#[allow(clippy::too_many_lines)] // ACL preamble (group + per-topic) + fetch-all vs named-topic branches; splitting hurts readability
pub(crate) async fn handle(
broker: &Broker,
version: i16,
_correlation_id: i32,
req_bytes: &[u8],
ctx: &crate::handlers::RequestContext<'_>,
) -> Result<Bytes, BrokerError> {
let mut cur: &[u8] = req_bytes;
let req = OffsetFetchRequest::decode(&mut cur, version)?;
// ── KIP-516 (v8+): per-group `groups[]` request/response shape ──
// v8 moved from a single (group_id, topics) pair to an array of
// groups, and v10 keys topics by `topic_id`. Internal offset storage
// stays name-keyed, so resolve id→name at the boundary and echo the
// id back. The legacy v0–v7 single-group path is preserved below.
if version >= 8 {
return handle_groups(broker, version, &req, ctx).await;
}
// ── ACL preamble ────────────────────────────────────────────
// Step 1: `Describe` on `Group(group_id)`. On Deny → whole-response
// `error_code = GROUP_AUTHORIZATION_FAILED (30)`.
{
let image = broker.controller.current_image();
let acl_req = AuthorizationRequest {
principal: ctx.principal,
host: ctx.peer,
resource_type: ResourceType::Group,
resource_name: req.group_id.as_str(),
operation: AclOperation::Describe,
};
if broker.config.authorizer.authorize(&*image, &acl_req) == AuthorizationResult::Deny {
let resp = OffsetFetchResponse {
topics: Vec::new(),
error_code: codes::GROUP_AUTHORIZATION_FAILED,
throttle_time_ms: 0,
..Default::default()
};
let mut buf = BytesMut::with_capacity(resp.encoded_len(version));
resp.encode(&mut buf, version)?;
return Ok(buf.freeze());
}
}
// Fetch the group's committed offsets from its actor (a classic actor is
// created for an unknown id; offsets are protocol-agnostic, so an existing
// actor of either kind serves `FetchCommitted` the same way).
let committed = {
let h = broker
.group_coordinator
.find(&req.group_id)
.unwrap_or_else(|| {
broker
.group_coordinator
.get_or_create_group(&req.group_id, GroupKindTag::Classic)
});
let (tx, rx) = oneshot::channel();
if h.tx
.send(GroupActorMessage::FetchCommitted { reply: tx })
.await
.is_ok()
{
rx.await.unwrap_or_default()
} else {
std::collections::HashMap::new()
}
};
// A `None` `topics` field (v ≥ 2) is the "fetch all" sentinel:
// return every committed offset stored for this group.
let topics_out: Vec<OffsetFetchResponseTopic> = if req.topics.is_none() {
// Aggregate all committed offsets grouped by topic name.
let mut by_topic: std::collections::HashMap<String, Vec<OffsetFetchResponsePartition>> =
std::collections::HashMap::new();
for ((topic, pid), entry) in &committed {
by_topic
.entry(topic.clone())
.or_default()
.push(OffsetFetchResponsePartition {
partition_index: *pid,
committed_offset: entry.offset,
committed_leader_epoch: entry.leader_epoch,
metadata: Some(entry.metadata.clone()),
error_code: codes::NONE,
..Default::default()
});
}
// ── ACL preamble ─────────────────────────────────────
// Step 2 (fetch-all): `Read` on each discovered topic. On Deny →
// per-topic `error_code = TOPIC_AUTHORIZATION_FAILED (29)`.
let discovered_topics: Vec<String> = by_topic.keys().cloned().collect();
let topic_decisions = {
let image = broker.controller.current_image();
authorize_topics(
broker.config.authorizer.as_ref(),
&*image,
ctx.principal,
ctx.peer,
AclOperation::Read,
discovered_topics.iter().map(String::as_str),
)
};
by_topic
.into_iter()
.map(|(name, partitions)| {
let denied = topic_decisions
.get(name.as_str())
.copied()
.unwrap_or(AuthorizationResult::Deny)
== AuthorizationResult::Deny;
if denied {
// Return the topic with TOPIC_AUTHORIZATION_FAILED on each partition.
OffsetFetchResponseTopic {
name,
partitions: partitions
.into_iter()
.map(|p| OffsetFetchResponsePartition {
partition_index: p.partition_index,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::TOPIC_AUTHORIZATION_FAILED,
..Default::default()
})
.collect(),
..Default::default()
}
} else {
OffsetFetchResponseTopic {
name,
partitions,
..Default::default()
}
}
})
.collect()
} else {
let req_topics = req.topics.as_deref().unwrap_or(&[]);
// ── ACL preamble ─────────────────────────────────────
// Step 2 (named topics): `Read` on each requested topic. On Deny →
// per-topic `error_code = TOPIC_AUTHORIZATION_FAILED (29)`.
let topic_decisions = {
let image = broker.controller.current_image();
authorize_topics(
broker.config.authorizer.as_ref(),
&*image,
ctx.principal,
ctx.peer,
AclOperation::Read,
req_topics.iter().map(|t| t.name.as_str()),
)
};
req_topics
.iter()
.map(|t| {
let denied = topic_decisions
.get(t.name.as_str())
.copied()
.unwrap_or(AuthorizationResult::Deny)
== AuthorizationResult::Deny;
if denied {
// Return all partitions with TOPIC_AUTHORIZATION_FAILED.
let partitions = t
.partition_indexes
.iter()
.map(|&pid| OffsetFetchResponsePartition {
partition_index: pid,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::TOPIC_AUTHORIZATION_FAILED,
..Default::default()
})
.collect();
OffsetFetchResponseTopic {
name: t.name.clone(),
partitions,
..Default::default()
}
} else {
let partitions = t
.partition_indexes
.iter()
.map(|&pid| match committed.get(&(t.name.clone(), pid)) {
Some(entry) => OffsetFetchResponsePartition {
partition_index: pid,
committed_offset: entry.offset,
committed_leader_epoch: entry.leader_epoch,
metadata: Some(entry.metadata.clone()),
error_code: codes::NONE,
..Default::default()
},
None => OffsetFetchResponsePartition {
partition_index: pid,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::NONE,
..Default::default()
},
})
.collect();
OffsetFetchResponseTopic {
name: t.name.clone(),
partitions,
..Default::default()
}
}
})
.collect()
};
let resp = OffsetFetchResponse {
topics: topics_out,
error_code: codes::NONE,
throttle_time_ms: 0,
..Default::default()
};
let mut buf = BytesMut::with_capacity(resp.encoded_len(version));
resp.encode(&mut buf, version)?;
Ok(buf.freeze())
}
/// v8+ per-group fetch. Processes `req.groups` into `resp.groups`, leaving
/// `resp.topics` empty (it is only encoded for v < 8). Offset storage is
/// name-keyed, so at v10 we resolve each requested `topic_id` → name and
/// echo the id back; unknown ids return `UNKNOWN_TOPIC_ID` per partition.
#[allow(clippy::too_many_lines)] // per-group loop: ACL + id→name resolve + named/fetch-all branches
async fn handle_groups(
broker: &Broker,
version: i16,
req: &OffsetFetchRequest,
ctx: &crate::handlers::RequestContext<'_>,
) -> Result<Bytes, BrokerError> {
let mut groups_out: Vec<OffsetFetchResponseGroup> = Vec::with_capacity(req.groups.len());
for grp in &req.groups {
// ── ACL: `Describe` on `Group(group_id)` ────────────────
{
let image = broker.controller.current_image();
let acl_req = AuthorizationRequest {
principal: ctx.principal,
host: ctx.peer,
resource_type: ResourceType::Group,
resource_name: grp.group_id.as_str(),
operation: AclOperation::Describe,
};
if broker.config.authorizer.authorize(&*image, &acl_req) == AuthorizationResult::Deny {
groups_out.push(OffsetFetchResponseGroup {
group_id: grp.group_id.clone(),
topics: Vec::new(),
error_code: codes::GROUP_AUTHORIZATION_FAILED,
..Default::default()
});
continue;
}
}
// Fetch the group's committed offsets from its actor (a classic actor
// is created for an unknown id; offsets are protocol-agnostic, so an
// existing actor of either kind serves `FetchCommitted` the same way).
let committed = {
let h = broker
.group_coordinator
.find(&grp.group_id)
.unwrap_or_else(|| {
broker
.group_coordinator
.get_or_create_group(&grp.group_id, GroupKindTag::Classic)
});
let (tx, rx) = oneshot::channel();
if h.tx
.send(GroupActorMessage::FetchCommitted { reply: tx })
.await
.is_ok()
{
rx.await.unwrap_or_default()
} else {
std::collections::HashMap::new()
}
};
let image = broker.controller.current_image();
// Named/id'd topics: resolve id→name (v10) and read each requested
// partition from the name-keyed store. `None` topics → fetch-all.
let topics_out: Vec<OffsetFetchResponseTopics> =
if let Some(req_topics) = grp.topics.as_deref() {
// Resolve each requested topic to a name first (id→name at
// v10); an unknown id is flagged so it short-circuits to
// UNKNOWN_TOPIC_ID without an ACL lookup.
let resolved: Vec<(&_, Option<String>)> = req_topics
.iter()
.map(|t| {
let name = if t.topic_id == WireUuid::ZERO {
Some(t.name.clone())
} else {
image
.topic_name_by_id(&uuid::Uuid::from_bytes(t.topic_id.0))
.map(str::to_string)
};
(t, name)
})
.collect();
// ── ACL: `Read` on each resolved topic. On Deny → per-partition
// TOPIC_AUTHORIZATION_FAILED (mirrors the v0–v7 path). The
// names are collected into an owned Vec so the decisions map
// doesn't borrow `resolved` (which is consumed below).
let auth_names: Vec<String> =
resolved.iter().filter_map(|(_, n)| n.clone()).collect();
let decisions = authorize_topics(
broker.config.authorizer.as_ref(),
&*image,
ctx.principal,
ctx.peer,
AclOperation::Read,
auth_names.iter().map(String::as_str),
);
resolved
.into_iter()
.map(|(t, name)| {
let Some(name) = name else {
// Unknown id → UNKNOWN_TOPIC_ID per partition.
return OffsetFetchResponseTopics {
name: String::new(),
topic_id: t.topic_id,
partitions: t
.partition_indexes
.iter()
.map(|&pid| OffsetFetchResponsePartitions {
partition_index: pid,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::UNKNOWN_TOPIC_ID,
..Default::default()
})
.collect(),
..Default::default()
};
};
let denied = decisions
.get(name.as_str())
.copied()
.unwrap_or(AuthorizationResult::Deny)
== AuthorizationResult::Deny;
let partitions = t
.partition_indexes
.iter()
.map(|&pid| {
if denied {
return OffsetFetchResponsePartitions {
partition_index: pid,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::TOPIC_AUTHORIZATION_FAILED,
..Default::default()
};
}
match committed.get(&(name.clone(), pid)) {
Some(entry) => OffsetFetchResponsePartitions {
partition_index: pid,
committed_offset: entry.offset,
committed_leader_epoch: entry.leader_epoch,
metadata: Some(entry.metadata.clone()),
error_code: codes::NONE,
..Default::default()
},
None => OffsetFetchResponsePartitions {
partition_index: pid,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::NONE,
..Default::default()
},
}
})
.collect();
OffsetFetchResponseTopics {
name,
topic_id: t.topic_id,
partitions,
..Default::default()
}
})
.collect()
} else {
// fetch-all: every committed offset for the group, grouped by
// topic name. Echo each topic's id (required at v10, where the
// name is dropped from the wire) and authorize Read per topic.
let mut by_topic: std::collections::HashMap<
String,
Vec<OffsetFetchResponsePartitions>,
> = std::collections::HashMap::new();
for ((topic, pid), entry) in &committed {
by_topic.entry(topic.clone()).or_default().push(
OffsetFetchResponsePartitions {
partition_index: *pid,
committed_offset: entry.offset,
committed_leader_epoch: entry.leader_epoch,
metadata: Some(entry.metadata.clone()),
error_code: codes::NONE,
..Default::default()
},
);
}
let discovered: Vec<String> = by_topic.keys().cloned().collect();
let decisions = authorize_topics(
broker.config.authorizer.as_ref(),
&*image,
ctx.principal,
ctx.peer,
AclOperation::Read,
discovered.iter().map(String::as_str),
);
by_topic
.into_iter()
.map(|(name, partitions)| {
let topic_id = image
.topic(&name)
.map_or(WireUuid::ZERO, |t| WireUuid(t.topic_id.into_bytes()));
let denied = decisions
.get(name.as_str())
.copied()
.unwrap_or(AuthorizationResult::Deny)
== AuthorizationResult::Deny;
if denied {
OffsetFetchResponseTopics {
name,
topic_id,
partitions: partitions
.into_iter()
.map(|p| OffsetFetchResponsePartitions {
partition_index: p.partition_index,
committed_offset: -1,
committed_leader_epoch: -1,
metadata: None,
error_code: codes::TOPIC_AUTHORIZATION_FAILED,
..Default::default()
})
.collect(),
..Default::default()
}
} else {
OffsetFetchResponseTopics {
name,
topic_id,
partitions,
..Default::default()
}
}
})
.collect()
};
groups_out.push(OffsetFetchResponseGroup {
group_id: grp.group_id.clone(),
topics: topics_out,
error_code: codes::NONE,
..Default::default()
});
}
let resp = OffsetFetchResponse {
topics: Vec::new(),
error_code: codes::NONE,
throttle_time_ms: 0,
groups: groups_out,
..Default::default()
};
let mut buf = BytesMut::with_capacity(resp.encoded_len(version));
resp.encode(&mut buf, version)?;
Ok(buf.freeze())
}