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
//! Batched group deletion: [`AdminClient::delete_consumer_groups`],
//! [`AdminClient::delete_share_groups`] and
//! [`AdminClient::delete_streams_groups`].
//!
//! Each call finds the coordinator of every group with one batched
//! `FindCoordinator` request and sends one `DeleteGroups` request to each
//! coordinator, as Apache Kafka's `DeleteGroupsHandler` does with its
//! `CoordinatorStrategy`. A request to a coordinator that
//! fails or loses its connection finds the coordinator again.
use std::collections::BTreeMap;
use krabka_protocol::owned::delete_groups_request::DeleteGroupsRequest;
use crate::{
AdminClient, KafkaError,
group_coordinators::{GroupOutcome, group_error_outcome},
group_descriptions::request_error_outcomes,
};
/// The per-group results of a delete call: one entry for each requested
/// group, `Ok(())` for a deleted group.
pub type GroupDeletions = BTreeMap<String, Result<(), KafkaError>>;
impl AdminClient {
/// Deletes empty consumer groups with `DeleteGroups`, as Apache Kafka's
/// `deleteConsumerGroups` does with its `DeleteConsumerGroupsHandler`.
///
/// The call finds the coordinator of every group with one batched
/// `FindCoordinator` request and sends one `DeleteGroups` request to each
/// coordinator with the groups that it coordinates.
/// `COORDINATOR_LOAD_IN_PROGRESS` (14) sends a group to the same
/// coordinator again, and `COORDINATOR_NOT_AVAILABLE` (15) and
/// `NOT_COORDINATOR` (16) find its coordinator again. A lost
/// connection finds the coordinator again. The call waits with Kafka's
/// backoff between rounds and stops at `default.api.timeout.ms` (60 s),
/// where each pending group gets `REQUEST_TIMED_OUT` (7).
///
/// # Errors
/// The call itself does not fail. Each group gets its own [`KafkaError`],
/// such as `NON_EMPTY_GROUP` (68), `GROUP_ID_NOT_FOUND` (69) or
/// `REQUEST_TIMED_OUT` (7) at the deadline.
pub async fn delete_consumer_groups(&self, groups: &[&str]) -> GroupDeletions {
self.delete_groups("deleteConsumerGroups", groups).await
}
/// Deletes empty share groups. Apache Kafka's `deleteShareGroups` uses a
/// `DeleteShareGroupsHandler` that builds the same `DeleteGroups` request
/// as `deleteConsumerGroups`.
///
/// # Errors
/// See [`AdminClient::delete_consumer_groups`].
pub async fn delete_share_groups(&self, groups: &[&str]) -> GroupDeletions {
self.delete_groups("deleteShareGroups", groups).await
}
/// Deletes empty streams groups. Apache Kafka's `deleteStreamsGroups`
/// delegates to `deleteConsumerGroups`.
///
/// # Errors
/// See [`AdminClient::delete_consumer_groups`].
pub async fn delete_streams_groups(&self, groups: &[&str]) -> GroupDeletions {
self.delete_consumer_groups(groups).await
}
/// The `DeleteGroups` call of Kafka's `DeleteGroupsHandler`.
async fn delete_groups(&self, api: &'static str, groups: &[&str]) -> GroupDeletions {
self.call_group_coordinators(api, groups, |coordinator, keys| async move {
let connection = self.connect_coordinator(&coordinator).await?;
let request = DeleteGroupsRequest {
groups_names: keys.clone(),
..Default::default()
};
Ok(match connection.send(request).await {
Ok(response) => response
.results
.into_iter()
.map(|result| {
let outcome = match result.error_code {
0 => GroupOutcome::Done(Ok(())),
code => group_error_outcome(code, None, &[]),
};
(result.group_id, outcome)
})
.collect(),
Err(error) => request_error_outcomes(&keys, &error.into()),
})
})
.await
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use assert2::assert;
use krabka_client_core::MockReply;
use krabka_protocol::owned::{
delete_groups_request,
delete_groups_response::{DeletableGroupResult, DeleteGroupsResponse},
find_coordinator_request,
};
use super::*;
use crate::{
group_coordinators::{
kafka_error,
test_support::{GroupCluster, Lookup, group_cluster},
},
partition_leaders::test_support::{ApiVersionRange, decode_request, encode_response},
};
fn names(names: &[&str]) -> Vec<String> {
names.iter().map(|name| (*name).to_owned()).collect()
}
async fn delete_groups_cluster(find_coordinator_max: i16) -> GroupCluster {
group_cluster()
.count(1)
.apis(vec![
ApiVersionRange::builder()
.api_key(delete_groups_request::API_KEY)
.max_version(2)
.build(),
ApiVersionRange::builder()
.api_key(find_coordinator_request::API_KEY)
.max_version(find_coordinator_max)
.build(),
])
.lookup(|_, _| Lookup::At(0))
.answer(mock_delete_groups)
.call()
.await
}
/// Kafka's `DeleteGroupsHandler` batches the groups of one coordinator,
/// retries 14 on the same coordinator, finds the coordinator again on 15
/// and 16, and fails every other code. A `FindCoordinator` error that
/// Kafka does not retry fails the group without a `DeleteGroups` request.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn delete_groups_batches_and_retries_as_kafka_does() {
#[derive(Clone, Copy, Debug)]
enum Call {
Consumer,
Share,
Streams,
}
for call in [Call::Consumer, Call::Share, Call::Streams] {
// "moved" is on broker 1 first, and then on broker 0.
let codes = Arc::new(Mutex::new(maplit::btreemap! {
"done" => vec![0],
"loading" => vec![14, 0],
"moved" => vec![16, 0],
"busy" => vec![68],
}));
let cluster = group_cluster()
.count(2)
.apis(vec![
ApiVersionRange::builder()
.api_key(delete_groups_request::API_KEY)
.max_version(2)
.build(),
])
.lookup(|group, lookups| match (group, lookups) {
("denied", _) => Lookup::Error(30),
("moved", 0) => Lookup::At(1),
_ => Lookup::At(0),
})
.answer(move |_, api_key, version, body, _| {
if api_key != delete_groups_request::API_KEY {
return MockReply::Silent;
}
let request: DeleteGroupsRequest = decode_request(body, version, version >= 2);
let mut codes = codes.lock().expect("codes lock");
let results = request
.groups_names
.iter()
.map(|group| {
let script = codes.get_mut(group.as_str()).expect("scripted group");
let error_code = if script.len() > 1 {
script.remove(0)
} else {
script[0]
};
DeletableGroupResult {
group_id: group.clone(),
error_code,
..Default::default()
}
})
.collect();
MockReply::Respond(encode_response(
&DeleteGroupsResponse {
results,
..Default::default()
},
version,
version >= 2,
))
})
.call()
.await;
let admin = cluster.admin(krabka_units::secs(5)).await;
let groups = ["done", "loading", "moved", "busy", "denied"];
let result = match call {
Call::Consumer => admin.delete_consumer_groups(&groups).await,
Call::Share => admin.delete_share_groups(&groups).await,
Call::Streams => admin.delete_streams_groups(&groups).await,
};
let seen = cluster.stop();
let requests = seen
.requests
.iter()
.map(|request| {
let body: DeleteGroupsRequest =
decode_request(&request.body, request.version, request.version >= 2);
(request.broker, request.version, body.groups_names)
})
.collect::<Vec<_>>();
let lookups = seen
.find_coordinator
.into_iter()
.map(|(_, keys)| keys)
.collect::<Vec<_>>();
assert!(
(result, lookups)
== (
maplit::btreemap! {
"busy".to_owned() => Err(kafka_error(68, None)),
"denied".to_owned() => Err(kafka_error(30, None)),
"done".to_owned() => Ok(()),
"loading".to_owned() => Ok(()),
"moved".to_owned() => Ok(()),
},
vec![
names(&["busy", "denied", "done", "loading", "moved"]),
names(&["moved"]),
],
),
"case {call:?}"
);
// The first round sends one request to each coordinator; the
// second retries "loading" and the moved "moved" together.
let mut first_round = requests[..2].to_vec();
first_round.sort();
assert!(
(first_round, requests[2..].to_vec())
== (
vec![
(0, 2, names(&["busy", "done", "loading"])),
(1, 2, names(&["moved"])),
],
vec![(0, 2, names(&["loading", "moved"]))],
),
"case {call:?}"
);
}
}
fn mock_delete_groups(
_broker: usize,
api_key: i16,
version: i16,
body: &[u8],
_addr: std::net::SocketAddr,
) -> MockReply {
if api_key != delete_groups_request::API_KEY {
return MockReply::Silent;
}
let request: DeleteGroupsRequest = decode_request(body, version, version >= 2);
MockReply::Respond(encode_response(
&DeleteGroupsResponse {
results: request
.groups_names
.into_iter()
.map(|group_id| DeletableGroupResult {
group_id,
..Default::default()
})
.collect(),
..Default::default()
},
version,
version >= 2,
))
}
/// A broker at `FindCoordinator` v4 or later gets one lookup for every
/// group, and a broker below v4 gets one lookup for each group, sent all at
/// once. Each row compares the version and keys of every lookup, sorted
/// because concurrent lookups arrive in any order.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn group_lookups_batch_from_find_coordinator_v4_and_fan_out_below() {
for (name, find_coordinator_max, expected) in [
("v6 broker batches", 6, vec![(4, names(&["a", "b", "c"]))]),
("v4 broker batches", 4, vec![(4, names(&["a", "b", "c"]))]),
(
"v3 broker looks up each group",
3,
vec![(3, names(&["a"])), (3, names(&["b"])), (3, names(&["c"]))],
),
] {
let cluster = delete_groups_cluster(find_coordinator_max).await;
let admin = cluster.admin(krabka_units::secs(5)).await;
let result = admin.delete_consumer_groups(&["a", "b", "c"]).await;
let mut lookups = cluster
.stop()
.find_coordinator
.into_iter()
.map(|(version, keys)| (version.min(4), keys))
.collect::<Vec<_>>();
lookups.sort();
assert!(
(result, lookups)
== (
maplit::btreemap! {
"a".to_owned() => Ok(()),
"b".to_owned() => Ok(()),
"c".to_owned() => Ok(()),
},
expected,
),
"case {name}"
);
}
}
/// A broker below `FindCoordinator` v4 cannot look up many keys at once,
/// so each group gets its own lookup, as Kafka's `CoordinatorStrategy`
/// does after `disableBatch`. The groups of one coordinator still share
/// one `DeleteGroups` request.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn delete_groups_looks_up_one_group_at_a_time_below_find_coordinator_v4() {
let cluster = delete_groups_cluster(3).await;
let admin = cluster.admin(krabka_units::secs(5)).await;
let result = admin.delete_consumer_groups(&["a", "b"]).await;
let seen = cluster.stop();
assert!(
(result, seen.find_coordinator, seen.requests.len())
== (
maplit::btreemap! {
"a".to_owned() => Ok(()),
"b".to_owned() => Ok(()),
},
vec![(3, names(&["a"])), (3, names(&["b"]))],
1,
)
);
}
}