koprs 0.5.4

A reusable, ergonomic library that streamlines Kubernetes operator development, allowing developers to build controllers with significantly less code.
Documentation
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
// src/tests/status.rs

#[cfg(test)]
mod status_tests {
    use http::{Request, Response, StatusCode};
    use k8s_openapi::api::core::v1::{ConfigMap, Node};
    use kube::Client;
    use kube::client::Body;
    use serde::Serialize;
    use serde_json::json;
    use tower_test::mock;

    use crate::scope::{Cluster, Namespaced};
    use crate::status::{patch_status, patch_status_cluster, patch_status_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 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()
    }

    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()
    }

    // -----------------------------------------------------------------------
    // Fixture builders
    // -----------------------------------------------------------------------

    fn configmap_json(name: &str, namespace: &str) -> serde_json::Value {
        json!({
            "apiVersion": "v1",
            "kind": "ConfigMap",
            "metadata": { "name": name, "namespace": namespace, "resourceVersion": "1" }
        })
    }

    fn node_json(name: &str) -> serde_json::Value {
        json!({
            "apiVersion": "v1",
            "kind": "Node",
            "metadata": { "name": name, "resourceVersion": "1" }
        })
    }

    // -----------------------------------------------------------------------
    // Status types used in tests
    // -----------------------------------------------------------------------

    /// Minimal status struct — anything Serialize-able is valid.
    #[derive(Serialize)]
    struct SimpleStatus {
        ready: bool,
    }

    /// A richer status with multiple fields to verify they all appear in the
    /// patch body.
    #[derive(Serialize)]
    struct RichStatus {
        ready: bool,
        message: String,
        observed_generation: i64,
    }

    // -----------------------------------------------------------------------
    // patch_status — URI must point at the /status subresource
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_namespaced_uri_contains_status_subresource() {
        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::PATCH);
            let uri = req.uri().to_string();
            // kube appends /status to the resource path for patch_status calls
            assert!(
                uri.contains("/namespaces/my-ns/configmaps/my-cm/status"),
                "expected /status subresource in uri, got: {uri}"
            );
            send.send_response(json_response(configmap_json("my-cm", "my-ns")));
        });

        patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("my-ns"),
            "my-cm",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_cluster_uri_contains_status_subresource_without_namespace() {
        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::PATCH);
            let uri = req.uri().to_string();
            assert!(
                uri.contains("/api/v1/nodes/my-node/status"),
                "expected /status subresource in uri, got: {uri}"
            );
            assert!(
                !uri.contains("namespaces"),
                "cluster-scoped resource must not have a namespace segment, got: {uri}"
            );
            send.send_response(json_response(node_json("my-node")));
        });

        patch_status::<Node, _, _>(
            client,
            Cluster,
            "my-node",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // patch_status — SSA query params
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_sends_ssa_field_manager_and_force_params() {
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            // PatchParams::apply(fm).force() produces ?fieldManager=…&force=true
            assert!(
                uri.contains("fieldManager=my-op"),
                "expected fieldManager param in uri, got: {uri}"
            );
            assert!(
                uri.contains("force=true"),
                "expected force=true param in uri, got: {uri}"
            );
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // patch_status — patch body structure
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_body_contains_api_version_and_kind() {
        // apply_status_patch builds the body from K::api_version and K::kind.
        // These must be present for SSA to work — without them the API server
        // cannot identify the resource type and will reject the request.
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let body = read_body_json(req).await;
            assert_eq!(
                body["apiVersion"], "v1",
                "patch body must include apiVersion"
            );
            assert_eq!(body["kind"], "ConfigMap", "patch body must include kind");
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_body_contains_status_field() {
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let body = read_body_json(req).await;
            assert_eq!(
                body["status"]["ready"], true,
                "patch body must nest status under the 'status' key"
            );
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_body_contains_all_status_fields() {
        // Verifies that the entire status struct is serialised, not just the
        // first field or a partial view.
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let body = read_body_json(req).await;
            assert_eq!(body["status"]["ready"], true);
            assert_eq!(body["status"]["message"], "all good");
            assert_eq!(body["status"]["observed_generation"], 42);
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            RichStatus {
                ready: true,
                message: "all good".to_string(),
                observed_generation: 42,
            },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_body_does_not_contain_spec_or_metadata_fields() {
        // The patch must only carry apiVersion, kind, and status.
        // Leaking spec or metadata into a status SSA patch can cause
        // unintended field ownership conflicts.
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let body = read_body_json(req).await;
            assert!(
                body.get("spec").is_none(),
                "patch body must not contain spec"
            );
            assert!(
                body.get("metadata").is_none(),
                "patch body must not contain metadata"
            );
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            SimpleStatus { ready: false },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // patch_status — return value
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_returns_deserialised_resource_from_server_response() {
        // The function returns whatever the server sends back, not the patch
        // we sent. This verifies that the response path is wired correctly.
        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(configmap_json("cm1", "ns1")));
        });

        let result = patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        assert_eq!(result.metadata.name.as_deref(), Some("cm1"));
        assert_eq!(result.metadata.namespace.as_deref(), Some("ns1"));

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // patch_status_namespaced — convenience wrapper
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_namespaced_wrapper_routes_to_correct_uri() {
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("/namespaces/ns1/configmaps/cm1/status"),
                "uri={uri}"
            );
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status_namespaced::<ConfigMap, _>(
            client,
            "ns1",
            "cm1",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_namespaced_wrapper_forwards_field_manager() {
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            assert!(
                req.uri().to_string().contains("fieldManager=specific-op"),
                "uri={}",
                req.uri()
            );
            send.send_response(json_response(configmap_json("cm1", "ns1")));
        });

        patch_status_namespaced::<ConfigMap, _>(
            client,
            "ns1",
            "cm1",
            SimpleStatus { ready: true },
            "specific-op",
        )
        .await
        .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // patch_status_cluster — convenience wrapper
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_cluster_wrapper_routes_to_correct_uri() {
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(uri.contains("/api/v1/nodes/n1/status"), "uri={uri}");
            assert!(!uri.contains("namespaces"), "uri={uri}");
            send.send_response(json_response(node_json("n1")));
        });

        patch_status_cluster::<Node, _>(client, "n1", SimpleStatus { ready: true }, "my-op")
            .await
            .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_cluster_wrapper_forwards_field_manager() {
        let (client, mut handle) = mock_client();

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            assert!(
                req.uri().to_string().contains("fieldManager=cluster-op"),
                "uri={}",
                req.uri()
            );
            send.send_response(json_response(node_json("n1")));
        });

        patch_status_cluster::<Node, _>(client, "n1", SimpleStatus { ready: true }, "cluster-op")
            .await
            .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // Error propagation
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn patch_status_propagates_server_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 = patch_status::<ConfigMap, _, _>(
            client,
            Namespaced("ns1"),
            "cm1",
            SimpleStatus { ready: true },
            "my-op",
        )
        .await;

        assert!(result.is_err(), "expected Err on 500, got Ok");
        server.await.unwrap();
    }

    #[tokio::test]
    async fn patch_status_cluster_propagates_server_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 =
            patch_status_cluster::<Node, _>(client, "n1", SimpleStatus { ready: true }, "my-op")
                .await;

        assert!(result.is_err(), "expected Err on 500, got Ok");
        server.await.unwrap();
    }
}