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
// src/tests/gc.rs
#[cfg(test)]
mod gc_tests {
use http::{Request, Response, StatusCode};
use k8s_openapi::api::core::v1::{ConfigMap, Node};
use kube::Client;
use kube::client::Body;
use serde_json::json;
use tower_test::mock;
use crate::gc::{gc_cluster_resources, gc_namespaced_resources, gc_resources};
use crate::scope::Namespaced;
// -----------------------------------------------------------------------
// Harness
// -----------------------------------------------------------------------
type MockHandle = mock::Handle<Request<Body>, Response<Body>>;
fn mock_client() -> (Client, MockHandle) {
let (svc, handle) = mock::pair::<Request<Body>, Response<Body>>();
(Client::new(svc, "default"), handle)
}
fn json_response(body: serde_json::Value) -> Response<Body> {
let bytes = serde_json::to_vec(&body).unwrap();
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(Body::from(bytes))
.unwrap()
}
fn not_found_response() -> Response<Body> {
let body = json!({
"apiVersion": "v1",
"kind": "Status",
"status": "Failure",
"reason": "NotFound",
"code": 404
});
Response::builder()
.status(StatusCode::NOT_FOUND)
.header("Content-Type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap()
}
fn server_error_response() -> Response<Body> {
let body = json!({
"apiVersion": "v1",
"kind": "Status",
"status": "Failure",
"reason": "InternalError",
"code": 500
});
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header("Content-Type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap()
}
// -----------------------------------------------------------------------
// Fixture builders
// -----------------------------------------------------------------------
/// A ConfigMap without a deletionTimestamp — a normal live resource.
fn configmap_json(name: &str, namespace: &str) -> serde_json::Value {
json!({
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {
"name": name,
"namespace": namespace,
"resourceVersion": "1"
}
})
}
/// A ConfigMap whose deletionTimestamp is set — it is already terminating.
fn terminating_configmap_json(name: &str, namespace: &str) -> serde_json::Value {
json!({
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {
"name": name,
"namespace": namespace,
"resourceVersion": "1",
"deletionTimestamp": "2024-01-01T00:00:00Z",
"finalizers": ["some-op/cleanup"]
}
})
}
/// A Node (cluster-scoped) without a deletionTimestamp.
fn node_json(name: &str) -> serde_json::Value {
json!({
"apiVersion": "v1",
"kind": "Node",
"metadata": {
"name": name,
"resourceVersion": "1"
}
})
}
/// A ConfigMapList containing the given items.
fn configmap_list(items: Vec<serde_json::Value>) -> serde_json::Value {
json!({
"apiVersion": "v1",
"kind": "ConfigMapList",
"metadata": { "resourceVersion": "1" },
"items": items
})
}
/// A NodeList containing the given items.
fn node_list(items: Vec<serde_json::Value>) -> serde_json::Value {
json!({
"apiVersion": "v1",
"kind": "NodeList",
"metadata": { "resourceVersion": "1" },
"items": items
})
}
/// An empty ConfigMapList.
fn empty_configmap_list() -> serde_json::Value {
configmap_list(vec![])
}
// -----------------------------------------------------------------------
// Read the outgoing request body as JSON.
// -----------------------------------------------------------------------
async fn read_body_json(req: Request<Body>) -> serde_json::Value {
use http_body_util::BodyExt as _;
let bytes = req.into_body().collect().await.unwrap().to_bytes();
serde_json::from_slice(&bytes).unwrap()
}
// -----------------------------------------------------------------------
// gc_resources — nothing to do (empty list)
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_does_nothing_when_list_is_empty() {
let (client, mut handle) = mock_client();
// Only one request is expected: the initial list.
let server = tokio::spawn(async move {
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::GET);
send.send_response(json_response(empty_configmap_list()));
// No further requests should arrive — the handle is dropped here.
});
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| true)
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — all resources are desired (no deletions)
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_skips_resources_that_are_desired() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::GET);
send.send_response(json_response(configmap_list(vec![configmap_json(
"cm-keep", "ns1",
)])));
// No DELETE or PATCH should follow — only one request total.
});
// Predicate always returns true → everything is desired.
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| true)
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — orphaned resource is deleted
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_deletes_orphaned_resource_not_in_desired_set() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List call — returns one orphaned resource.
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::GET);
let uri = req.uri().to_string();
assert!(
uri.contains("labelSelector"),
"expected label selector in list call, uri={uri}"
);
send.send_response(json_response(configmap_list(vec![configmap_json(
"orphan", "ns1",
)])));
// 2. DELETE call for the orphaned resource.
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::DELETE);
assert!(
req.uri()
.to_string()
.contains("/namespaces/ns1/configmaps/orphan"),
"uri={}",
req.uri()
);
// Kubernetes returns the deleted object (or a Status) — we return the object.
send.send_response(json_response(configmap_json("orphan", "ns1")));
// 3. After deletion kube calls clear_finalizers (PATCH finalizers=null).
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::PATCH);
let body = read_body_json(req).await;
assert_eq!(
body["metadata"]["finalizers"],
serde_json::Value::Null,
"clear_finalizers must set finalizers to null"
);
send.send_response(json_response(configmap_json("orphan", "ns1")));
});
// Predicate never matches "orphan" → it should be deleted.
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |r| {
r.metadata.name.as_deref() != Some("orphan")
})
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — multiple resources, mixed desired / orphaned
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_only_deletes_orphaned_resources_from_mixed_list() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List returns two resources: one desired, one orphaned.
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_list(vec![
configmap_json("keep", "ns1"),
configmap_json("orphan", "ns1"),
])));
// 2. DELETE for "orphan" only (no call for "keep").
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::DELETE);
assert!(
req.uri().to_string().contains("orphan"),
"uri={}",
req.uri()
);
send.send_response(json_response(configmap_json("orphan", "ns1")));
// 3. clear_finalizers PATCH after delete.
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_json("orphan", "ns1")));
});
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |r| {
r.metadata.name.as_deref() == Some("keep")
})
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — terminating resource gets finalizers cleared, not deleted
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_clears_finalizers_on_terminating_resource_instead_of_deleting() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List returns a resource that is already terminating.
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_list(vec![
terminating_configmap_json("terminating", "ns1"),
])));
// 2. Should go straight to a PATCH (clear_finalizers), skipping DELETE.
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(
req.method(),
http::Method::PATCH,
"expected PATCH to clear finalizers, not DELETE"
);
let uri = req.uri().to_string();
assert!(uri.contains("terminating"), "uri={uri}");
let body = read_body_json(req).await;
assert_eq!(body["metadata"]["finalizers"], serde_json::Value::Null);
send.send_response(json_response(terminating_configmap_json(
"terminating",
"ns1",
)));
});
// Resource is not desired (would normally trigger deletion), but because
// it has a deletionTimestamp the GC loop should only clear finalizers.
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| false)
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — delete returns 404 (already gone), should not error
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_tolerates_404_on_delete_as_already_deleted() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_list(vec![configmap_json(
"gone", "ns1",
)])));
// 2. DELETE → 404 (someone else already deleted it).
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::DELETE);
send.send_response(not_found_response());
// No PATCH should follow — the 404 path skips clear_finalizers.
});
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| false)
.await
.unwrap(); // must not return Err
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — non-404 delete error is propagated
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_propagates_non_404_delete_errors() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_list(vec![configmap_json(
"cm1", "ns1",
)])));
// 2. DELETE → 500
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(server_error_response());
});
let result =
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| false).await;
assert!(result.is_err(), "expected Err on 500 delete, got Ok");
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_resources — list error is propagated
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_propagates_list_errors() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(server_error_response());
});
let result =
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| false).await;
assert!(result.is_err(), "expected Err on 500 list, got Ok");
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_cluster_resources — convenience wrapper
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_cluster_resources_lists_and_deletes_without_namespace_segment() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List — cluster-scoped, no /namespaces/ in URI.
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::GET);
let uri = req.uri().to_string();
assert!(
!uri.contains("namespaces"),
"unexpected namespace in list uri={uri}"
);
send.send_response(json_response(node_list(vec![node_json("orphan-node")])));
// 2. DELETE
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::DELETE);
let uri = req.uri().to_string();
assert!(uri.contains("/api/v1/nodes/orphan-node"), "uri={uri}");
assert!(!uri.contains("namespaces"), "uri={uri}");
send.send_response(json_response(node_json("orphan-node")));
// 3. clear_finalizers PATCH
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(node_json("orphan-node")));
});
gc_cluster_resources::<Node>(client, "app=op", |_| false)
.await
.unwrap();
server.await.unwrap();
}
#[tokio::test]
async fn gc_cluster_resources_skips_desired_nodes() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(node_list(vec![node_json("keep-node")])));
// No further requests — the single desired node is skipped.
});
gc_cluster_resources::<Node>(client, "app=op", |_| true)
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// gc_namespaced_resources — convenience wrapper
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_namespaced_resources_lists_and_deletes_within_namespace() {
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List (gc_resources uses Api::all internally, then per-resource
// Api::namespaced — so the list URI uses the all-namespaces path).
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::GET);
send.send_response(json_response(configmap_list(vec![configmap_json(
"orphan", "prod",
)])));
// 2. DELETE via namespaced API.
let (req, send) = handle.next_request().await.unwrap();
assert_eq!(req.method(), http::Method::DELETE);
assert!(
req.uri().to_string().contains("configmaps/orphan"),
"uri={}",
req.uri()
);
send.send_response(json_response(configmap_json("orphan", "prod")));
// 3. clear_finalizers PATCH.
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_json("orphan", "prod")));
});
gc_namespaced_resources::<ConfigMap>(client, "prod", "app=op", |_| false)
.await
.unwrap();
server.await.unwrap();
}
// -----------------------------------------------------------------------
// clear_finalizers errors are silently swallowed
// -----------------------------------------------------------------------
#[tokio::test]
async fn gc_continues_when_clear_finalizers_patch_fails() {
// After a successful delete, the clear_finalizers PATCH may fail (e.g.
// the resource is already fully gone). The GC loop must swallow that
// error and return Ok.
let (client, mut handle) = mock_client();
let server = tokio::spawn(async move {
// 1. List
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_list(vec![configmap_json(
"orphan", "ns1",
)])));
// 2. DELETE succeeds.
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(json_response(configmap_json("orphan", "ns1")));
// 3. PATCH (clear_finalizers) → 404, resource already gone.
let (_req, send) = handle.next_request().await.unwrap();
send.send_response(not_found_response());
});
// Must not return Err even though the finalizer clear failed.
gc_resources::<ConfigMap, _>(client, Namespaced("ns1"), "app=op", |_| false)
.await
.unwrap();
server.await.unwrap();
}
}