koprs 0.9.5

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
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
// src/tests/watcher.rs
//
// Testing strategy
// ----------------
// kube_runtime::watcher drives a two-phase protocol under the hood:
//
//   1. LIST   GET /api/v1/.../configmaps?watch=false&...
//   2. WATCH  GET /api/v1/.../configmaps?watch=true&resourceVersion=...
//
// The mock handle must serve both responses before the background task
// produces any signals on the mpsc channel. The WATCH response body is a
// newline-delimited stream of JSON `WatchEvent` objects — each event on its
// own line. Sending an ADDED event through the watch is what causes the
// watcher task to call `tx.send(())`.
//
// Because the watcher task runs in the background, every test that expects a
// signal uses `tokio::time::timeout` so a broken watcher cannot hang the
// suite indefinitely.

#[cfg(test)]
mod watcher_tests {
    use std::time::Duration;

    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 tokio::sync::mpsc;
    use tokio::time::timeout;
    use tower_test::mock;

    use crate::scope::{Cluster, Namespaced};
    use crate::watcher::{WatchEvent, watch, watch_events, watch_objects};

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

    // -----------------------------------------------------------------------
    // Protocol helpers
    // -----------------------------------------------------------------------

    /// A minimal ConfigMap JSON object, usable in list items and watch events.
    fn configmap_json(name: &str, namespace: &str) -> serde_json::Value {
        json!({
            "apiVersion": "v1",
            "kind": "ConfigMap",
            "metadata": {
                "name": name,
                "namespace": namespace,
                "resourceVersion": "100"
            }
        })
    }

    /// A minimal Node JSON object.
    fn node_json(name: &str) -> serde_json::Value {
        json!({
            "apiVersion": "v1",
            "kind": "Node",
            "metadata": {
                "name": name,
                "resourceVersion": "100"
            }
        })
    }

    /// The initial LIST response kube_runtime expects before opening a watch.
    ///
    /// `items` populates the list. `resource_version` seeds the `?resourceVersion=`
    /// parameter on the subsequent WATCH request.
    fn list_response(kind: &str, items: Vec<serde_json::Value>) -> Response<Body> {
        let body = json!({
            "apiVersion": "v1",
            "kind": kind,
            "metadata": { "resourceVersion": "100" },
            "items": items
        });
        json_response(body)
    }

    /// A WATCH response body: a newline-delimited stream of `WatchEvent` JSON
    /// objects. kube_runtime reads this as a streaming response — each `\n`
    /// terminates one event.
    ///
    /// Sending an `ADDED` event for an object causes `applied_objects()` to
    /// yield it, which is what makes the watcher task call `tx.send(())`.
    fn watch_events_response(events: Vec<serde_json::Value>) -> Response<Body> {
        let ndjson = events
            .into_iter()
            .map(|e| serde_json::to_string(&e).unwrap())
            .collect::<Vec<_>>()
            .join("\n");
        Response::builder()
            .status(StatusCode::OK)
            .header("Content-Type", "application/json")
            .body(Body::from(ndjson.into_bytes()))
            .unwrap()
    }

    /// A single `ADDED` WatchEvent wrapping the given object.
    fn added_event(object: serde_json::Value) -> serde_json::Value {
        json!({ "type": "ADDED", "object": object })
    }

    /// A single `MODIFIED` WatchEvent wrapping the given object.
    fn modified_event(object: serde_json::Value) -> serde_json::Value {
        json!({ "type": "MODIFIED", "object": object })
    }

    /// Assert that `rx` receives at least one signal within 2 seconds.
    async fn expect_signal(rx: &mut mpsc::Receiver<()>) {
        timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out waiting for watcher signal")
            .expect("channel closed before signal was received");
    }

    // -----------------------------------------------------------------------
    // watch — LIST + WATCH protocol
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_issues_list_then_watch_requests_in_sequence() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            // 1. Initial LIST request.
            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/ns1/configmaps"),
                "expected namespaced configmap list uri, got: {uri}"
            );
            // watch=true must NOT be present on the list call
            assert!(
                !uri.contains("watch=true"),
                "list request must not have watch=true, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));

            // 2. Long-poll WATCH request.
            let (req, send) = handle.next_request().await.unwrap();
            assert_eq!(req.method(), http::Method::GET);
            let uri = req.uri().to_string();
            assert!(
                uri.contains("watch=true"),
                "second request must be a watch, got: {uri}"
            );
            // Send an empty watch stream so the task completes cleanly.
            send.send_response(watch_events_response(vec![]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // watch — signal is sent for ADDED events
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_sends_signal_when_resource_is_added() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            // LIST — empty, just to seed resourceVersion
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            // WATCH — one ADDED event
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![added_event(configmap_json(
                "cm1", "ns1",
            ))]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch — signal is sent for MODIFIED events
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_sends_signal_when_resource_is_modified() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![modified_event(configmap_json(
                "cm1", "ns1",
            ))]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch — existing resources in the LIST also trigger signals
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_sends_signal_for_resources_present_in_initial_list() {
        // kube_runtime's applied_objects() synthesises ADDED events for items
        // returned in the initial list, so they also trigger tx.send(()).
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            // LIST — already contains one ConfigMap
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response(
                "ConfigMapList",
                vec![configmap_json("existing", "ns1")],
            ));

            // WATCH — empty, nothing new
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch — multiple events produce one signal each
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_sends_one_signal_per_applied_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![
                added_event(configmap_json("cm1", "ns1")),
                added_event(configmap_json("cm2", "ns1")),
            ]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        // Two ADDED events → two signals
        expect_signal(&mut rx).await;
        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch — label selector is forwarded to the API server
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_with_label_selector_forwards_selector_on_list_request() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            // LIST — check label selector is present
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("labelSelector=app%3Dmy-op")
                    || uri.contains("labelSelector=app=my-op"),
                "expected labelSelector in list uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));

            // WATCH — label selector should also be present
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("labelSelector=app%3Dmy-op")
                    || uri.contains("labelSelector=app=my-op"),
                "expected labelSelector in watch uri, got: {uri}"
            );
            send.send_response(watch_events_response(vec![]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), Some("app=my-op"), tx)
            .await
            .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_without_label_selector_omits_label_selector_param() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                !uri.contains("labelSelector"),
                "expected no labelSelector in uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // watch — cluster-scoped resources use Api::all (no namespace segment)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_cluster_scoped_list_uri_has_no_namespace_segment() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        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"),
                "expected nodes list uri, got: {uri}"
            );
            assert!(
                !uri.contains("namespaces"),
                "cluster-scoped watch must not have namespace segment, got: {uri}"
            );
            send.send_response(list_response("NodeList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<Node, _>(client, Cluster, None, tx).await.unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_cluster_scoped_sends_signal_on_added_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("NodeList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![added_event(node_json("n1"))]));
        });

        watch::<Node, _>(client, Cluster, None, tx).await.unwrap();

        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch_namespaced — convenience wrapper
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_namespaced_scopes_list_to_correct_namespace() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("/namespaces/prod/configmaps"),
                "expected prod namespace in uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<ConfigMap, _>(client, Namespaced("prod"), None, tx)
            .await
            .unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_namespaced_sends_signal_on_applied_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![added_event(configmap_json(
                "cm1", "prod",
            ))]));
        });

        watch::<ConfigMap, _>(client, Namespaced("prod"), None, tx)
            .await
            .unwrap();

        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch_namespaced_by_label — convenience wrapper
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_namespaced_by_label_forwards_label_selector() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("labelSelector"),
                "expected labelSelector in uri, got: {uri}"
            );
            assert!(
                uri.contains("/namespaces/ns1/configmaps"),
                "expected ns1 in uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<ConfigMap, _>(client, Namespaced("ns1"), Some("app=my-op"), tx)
            .await
            .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // watch_cluster — convenience wrapper
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_cluster_uses_all_api_without_namespace_segment() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(!uri.contains("namespaces"), "uri={uri}");
            assert!(uri.contains("/api/v1/nodes"), "uri={uri}");
            send.send_response(list_response("NodeList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<Node, _>(client, Cluster, None, tx).await.unwrap();

        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_cluster_sends_signal_on_applied_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("NodeList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![added_event(node_json("n1"))]));
        });

        watch::<Node, _>(client, Cluster, None, tx).await.unwrap();

        expect_signal(&mut rx).await;
    }

    // -----------------------------------------------------------------------
    // watch_cluster_by_label — convenience wrapper
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_cluster_by_label_forwards_selector_without_namespace() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(!uri.contains("namespaces"), "uri={uri}");
            assert!(uri.contains("labelSelector"), "uri={uri}");
            send.send_response(list_response("NodeList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch::<Node, _>(client, Cluster, Some("app=my-op"), tx)
            .await
            .unwrap();

        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // watch_objects — sends the resource T on ADDED/MODIFIED
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_objects_sends_resource_on_applied_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![added_event(configmap_json(
                "cm-data", "ns1",
            ))]));
        });

        watch_objects::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        let received = timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out waiting for resource")
            .expect("channel closed");

        // The actual resource is delivered — not just a unit signal.
        assert_eq!(
            received.metadata.name.as_deref(),
            Some("cm-data"),
            "received resource name should match the watch event"
        );
    }

    #[tokio::test]
    async fn watch_objects_scopes_to_correct_namespace() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("/namespaces/staging/configmaps"),
                "expected staging namespace in list uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch_objects::<ConfigMap, _>(client, Namespaced("staging"), None, tx)
            .await
            .unwrap();
        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_objects_cluster_scope_uses_all_api() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                !uri.contains("namespaces"),
                "cluster scope must not have namespace segment, got: {uri}"
            );
            assert!(uri.contains("/api/v1/nodes"), "uri={uri}");
            send.send_response(list_response("NodeList", vec![]));
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch_objects::<Node, _>(client, Cluster, None, tx)
            .await
            .unwrap();
        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_objects_forwards_label_selector() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("labelSelector=app%3Dmy-op")
                    || uri.contains("labelSelector=app=my-op"),
                "expected labelSelector in uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch_objects::<ConfigMap, _>(client, Namespaced("ns1"), Some("app=my-op"), tx)
            .await
            .unwrap();
        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // watch_events — sends WatchEvent<T> for applied and deleted events
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watch_events_sends_applied_on_added_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![added_event(configmap_json(
                "cm-added", "ns1",
            ))]));
        });

        watch_events::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        let event = timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out")
            .expect("channel closed");

        assert!(
            matches!(event, WatchEvent::Applied(_)),
            "expected WatchEvent::Applied for an ADDED watch event"
        );
        if let WatchEvent::Applied(r) = event {
            assert_eq!(r.metadata.name.as_deref(), Some("cm-added"));
        }
    }

    #[tokio::test]
    async fn watch_events_sends_deleted_on_deleted_event() {
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            // A DELETED watch event creates Event::Delete in kube-runtime.
            let deleted_event =
                json!({ "type": "DELETED", "object": configmap_json("cm-gone", "ns1") });
            send.send_response(watch_events_response(vec![deleted_event]));
        });

        watch_events::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        let event = timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out")
            .expect("channel closed");

        assert!(
            matches!(event, WatchEvent::Deleted(_)),
            "expected WatchEvent::Deleted for a DELETED watch event"
        );
        if let WatchEvent::Deleted(r) = event {
            assert_eq!(r.metadata.name.as_deref(), Some("cm-gone"));
        }
    }

    #[tokio::test]
    async fn watch_events_sends_applied_for_items_in_initial_list() {
        // Objects returned during the initial LIST phase become InitApply events
        // in kube-runtime. watch_events must convert them to WatchEvent::Applied.
        let (client, mut handle) = mock_client();
        let (tx, mut rx) = mpsc::channel(16);

        tokio::spawn(async move {
            // LIST response carries one existing object.
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response(
                "ConfigMapList",
                vec![configmap_json("pre-existing", "ns1")],
            ));
            // WATCH — empty, nothing new.
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch_events::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        let event = timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out")
            .expect("channel closed");

        assert!(
            matches!(event, WatchEvent::Applied(_)),
            "InitApply events from the LIST phase must become WatchEvent::Applied"
        );
        if let WatchEvent::Applied(r) = event {
            assert_eq!(r.metadata.name.as_deref(), Some("pre-existing"));
        }
    }

    #[tokio::test]
    async fn watch_events_scopes_to_correct_namespace() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("/namespaces/prod/configmaps"),
                "expected prod namespace in uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch_events::<ConfigMap, _>(client, Namespaced("prod"), None, tx)
            .await
            .unwrap();
        server.await.unwrap();
    }

    #[tokio::test]
    async fn watch_events_forwards_label_selector() {
        let (client, mut handle) = mock_client();
        let (tx, _rx) = mpsc::channel(16);

        let server = tokio::spawn(async move {
            let (req, send) = handle.next_request().await.unwrap();
            let uri = req.uri().to_string();
            assert!(
                uri.contains("labelSelector=app%3Dmy-op")
                    || uri.contains("labelSelector=app=my-op"),
                "expected labelSelector in uri, got: {uri}"
            );
            send.send_response(list_response("ConfigMapList", vec![]));
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(watch_events_response(vec![]));
        });

        watch_events::<ConfigMap, _>(client, Namespaced("ns1"), Some("app=my-op"), tx)
            .await
            .unwrap();
        server.await.unwrap();
    }

    // -----------------------------------------------------------------------
    // JoinHandle — task shuts down when receiver is dropped
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn watcher_task_shuts_down_when_all_receivers_are_dropped() {
        let (client, mut handle) = mock_client();
        let (tx, rx) = mpsc::channel::<()>(16);

        tokio::spawn(async move {
            let (_req, send) = handle.next_request().await.unwrap();
            send.send_response(list_response("ConfigMapList", vec![]));

            let (_req, send) = handle.next_request().await.unwrap();
            // Send a signal — but the receiver is already dropped by the time
            // the watcher task tries to send, so tx.send().ok() should swallow
            // the error rather than panic.
            send.send_response(watch_events_response(vec![added_event(configmap_json(
                "cm1", "ns1",
            ))]));
        });

        let handle = watch::<ConfigMap, _>(client, Namespaced("ns1"), None, tx)
            .await
            .unwrap();

        // Drop the receiver — the watcher task's tx.send().ok() must not panic.
        drop(rx);

        // The task should finish without panicking.
        timeout(Duration::from_secs(2), handle)
            .await
            .expect("watcher task did not shut down within timeout")
            .expect("watcher task panicked");
    }
}